prompt
large_stringlengths 70
991k
| completion
large_stringlengths 0
1.02k
|
---|---|
<|file_name|>apps.rs<|end_file_name|><|fim▁begin|>use crate::scope::Scope;
#[derive(Debug, Clone, PartialEq)]
pub struct App {
pub client_name: String,
pub redirect_uris: String,
pub scopes: Scope,
pub website: Option<String>,
}
#[derive(Default, Builder, Debug, Clone, PartialEq, Serialize)]
#[builder(setter(into))]
pub struct AppId {
id: String,<|fim▁hole|> client_id: String,
client_secret: String,
}<|fim▁end|>
| |
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
<|fim▁hole|> author='Neil Newman, Jonathan Marini',
author_email='[email protected], [email protected]',
packages=['emergence'],
install_requires=['requests'],
)<|fim▁end|>
|
setup(
name='pyapi-emergence',
url='',
|
<|file_name|>tweeter.rs<|end_file_name|><|fim▁begin|>extern crate irc;
use std::default::Default;
use std::sync::Arc;
use std::thread::{sleep_ms, spawn};
use irc::client::prelude::*;
fn main() {
let config = Config {
nickname: Some(format!("pickles")),
server: Some(format!("irc.fyrechat.net")),
channels: Some(vec![format!("#vana")]),
.. Default::default()<|fim▁hole|> server.identify().unwrap();
let server2 = server.clone();
// Let's set up a loop that just prints the messages.
spawn(move || {
server2.iter().map(|m| print!("{}", m.unwrap().into_string())).count();
});
loop {
server.send_privmsg("#vana", "TWEET TWEET").unwrap();
sleep_ms(10 * 1000);
}
}<|fim▁end|>
|
};
let server = Arc::new(IrcServer::from_config(config).unwrap());
|
<|file_name|>sync.rs<|end_file_name|><|fim▁begin|>use core::ops::{Deref, DerefMut};
use kernel::sched::{task_locked, task_unlocked};
use arch::int::{disable_interrupts, enable_interrupts};
use spin::{Mutex as M, MutexGuard as MG};
pub struct Mutex<T> {
l: M<T>,
}
pub struct MutexGuard<'a, T: ?Sized + 'a> {
g: Option<MG<'a, T>>,
irq: bool,
task_locked: bool
}<|fim▁hole|>
pub const fn new(user_data: T) -> Mutex<T> {
Mutex {
l: M::new(user_data),
}
}
pub fn lock(&self) -> MutexGuard<T> {
task_locked();
MutexGuard {
g: Some(self.l.lock()),
irq: false,
task_locked: true
}
}
pub fn lock_irq(&self) -> MutexGuard<T> {
disable_interrupts();
task_locked();
MutexGuard {
g: Some(self.l.lock()),
irq: true,
task_locked: true
}
}
}
impl<'a, T: ?Sized> Deref for MutexGuard<'a, T> {
type Target = T;
fn deref<'b>(&'b self) -> &'b T {
self.g.as_ref().unwrap()
}
}
impl<'a, T: ?Sized> DerefMut for MutexGuard<'a, T> {
fn deref_mut<'b>(&'b mut self) -> &'b mut T {
self.g.as_mut().unwrap()
}
}
impl<'a, T: ?Sized> Drop for MutexGuard<'a, T> {
fn drop(&mut self) {
drop(self.g.take());
if self.task_locked {
task_unlocked();
}
if self.irq {
enable_interrupts();
}
}
}<|fim▁end|>
|
impl<T> Mutex<T> {
|
<|file_name|>contours.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
'''
This program illustrates the use of findContours and drawContours.
The original image is put up along with the image of drawn contours.
Usage:
contours.py
A trackbar is put up which controls the contour level from -3 to 3
'''
# Python 2/3 compatibility
from __future__ import print_function<|fim▁hole|>if PY3:
xrange = range
import numpy as np
import cv2
def make_image():
img = np.zeros((500, 500), np.uint8)
black, white = 0, 255
for i in xrange(6):
dx = int((i%2)*250 - 30)
dy = int((i/2.)*150)
if i == 0:
for j in xrange(11):
angle = (j+5)*np.pi/21
c, s = np.cos(angle), np.sin(angle)
x1, y1 = np.int32([dx+100+j*10-80*c, dy+100-90*s])
x2, y2 = np.int32([dx+100+j*10-30*c, dy+100-30*s])
cv2.line(img, (x1, y1), (x2, y2), white)
cv2.ellipse( img, (dx+150, dy+100), (100,70), 0, 0, 360, white, -1 )
cv2.ellipse( img, (dx+115, dy+70), (30,20), 0, 0, 360, black, -1 )
cv2.ellipse( img, (dx+185, dy+70), (30,20), 0, 0, 360, black, -1 )
cv2.ellipse( img, (dx+115, dy+70), (15,15), 0, 0, 360, white, -1 )
cv2.ellipse( img, (dx+185, dy+70), (15,15), 0, 0, 360, white, -1 )
cv2.ellipse( img, (dx+115, dy+70), (5,5), 0, 0, 360, black, -1 )
cv2.ellipse( img, (dx+185, dy+70), (5,5), 0, 0, 360, black, -1 )
cv2.ellipse( img, (dx+150, dy+100), (10,5), 0, 0, 360, black, -1 )
cv2.ellipse( img, (dx+150, dy+150), (40,10), 0, 0, 360, black, -1 )
cv2.ellipse( img, (dx+27, dy+100), (20,35), 0, 0, 360, white, -1 )
cv2.ellipse( img, (dx+273, dy+100), (20,35), 0, 0, 360, white, -1 )
return img
if __name__ == '__main__':
print(__doc__)
img = make_image()
h, w = img.shape[:2]
_, contours0, hierarchy = cv2.findContours( img.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
contours = [cv2.approxPolyDP(cnt, 3, True) for cnt in contours0]
def update(levels):
vis = np.zeros((h, w, 3), np.uint8)
levels = levels - 3
cv2.drawContours( vis, contours, (-1, 2)[levels <= 0], (128,255,255),
3, cv2.LINE_AA, hierarchy, abs(levels) )
cv2.imshow('contours', vis)
update(3)
cv2.createTrackbar( "levels+3", "contours", 3, 7, update )
cv2.imshow('image', img)
cv2.waitKey()
cv2.destroyAllWindows()<|fim▁end|>
|
import sys
PY3 = sys.version_info[0] == 3
|
<|file_name|>borrowck-move-out-of-struct-with-dtor.rs<|end_file_name|><|fim▁begin|><|fim▁hole|>struct S {f:~str}
impl Drop for S {
fn drop(&mut self) { println(self.f); }
}
fn move_in_match() {
match S {f:~"foo"} {
S {f:_s} => {}
//~^ ERROR cannot move out of type `S`, which defines the `Drop` trait
}
}
fn move_in_let() {
let S {f:_s} = S {f:~"foo"};
//~^ ERROR cannot move out of type `S`, which defines the `Drop` trait
}
fn move_in_fn_arg(S {f:_s}: S) {
//~^ ERROR cannot move out of type `S`, which defines the `Drop` trait
}
fn main() {}<|fim▁end|>
| |
<|file_name|>checks.py<|end_file_name|><|fim▁begin|>import json
import time
import git
import discord
import os
import aiohttp
from cogs.utils.dataIO import dataIO
from urllib.parse import quote as uriquote
try:
from lxml import etree
except ImportError:
from bs4 import BeautifulSoup
from urllib.parse import parse_qs, quote_plus
#from cogs.utils import common
# @common.deprecation_warn()
def load_config():
with open('settings/config.json', 'r') as f:
return json.load(f)
<|fim▁hole|> return json.load(f)
# @common.deprecation_warn()
def load_moderation():
with open('settings/moderation.json', 'r') as f:
return json.load(f)
# @common.deprecation_warn()
def load_notify_config():
with open('settings/notify.json', 'r') as f:
return json.load(f)
# @common.deprecation_warn()
def load_log_config():
with open('settings/log.json', 'r') as f:
return json.load(f)
def has_passed(oldtime):
if time.time() - 20.0 < oldtime:
return False
return time.time()
def set_status(bot):
if bot.default_status == 'idle':
return discord.Status.idle
elif bot.default_status == 'dnd':
return discord.Status.dnd
else:
return discord.Status.invisible
def user_post(key_users, user):
if time.time() - float(key_users[user][0]) < float(key_users[user][1]):
return False, [time.time(), key_users[user][1]]
else:
log = dataIO.load_json("settings/log.json")
now = time.time()
log["keyusers"][user] = [now, key_users[user][1]]
dataIO.save_json("settings/log.json", log)
return True, [now, key_users[user][1]]
def gc_clear(gc_time):
if time.time() - 3600.0 < gc_time:
return False
return time.time()
def game_time_check(oldtime, interval):
if time.time() - float(interval) < oldtime:
return False
return time.time()
def avatar_time_check(oldtime, interval):
if time.time() - float(interval) < oldtime:
return False
return time.time()
def update_bot(message):
g = git.cmd.Git(working_dir=os.getcwd())
branch = g.execute(["git", "rev-parse", "--abbrev-ref", "HEAD"])
g.execute(["git", "fetch", "origin", branch])
update = g.execute(["git", "remote", "show", "origin"])
if ('up to date' in update or 'fast-forward' in update) and message:
return False
else:
if message is False:
version = 4
else:
version = g.execute(["git", "rev-list", "--right-only", "--count", "{0}...origin/{0}".format(branch)])
version = description = str(int(version))
if int(version) > 4:
version = "4"
commits = g.execute(["git", "rev-list", "--max-count={0}".format(version), "origin/{0}".format(branch)])
commits = commits.split('\n')
em = discord.Embed(color=0x24292E, title='Latest changes for the selfbot:', description='{0} release(s) behind.'.format(description))
for i in range(int(version)):
i = i - 1 # Change i to i -1 to let the formatters below work
title = g.execute(["git", "log", "--format=%ar", "-n", "1", commits[i]])
field = g.execute(["git", "log", "--pretty=oneline", "--abbrev-commit", "--shortstat", commits[i], "^{0}".format(commits[i + 1])])
field = field[8:].strip()
link = 'https://github.com/appu1232/Discord-Selfbot/commit/%s' % commits[i]
em.add_field(name=title, value='{0}\n[Code changes]({1})'.format(field, link), inline=False)
em.set_thumbnail(url='https://image.flaticon.com/icons/png/512/25/25231.png')
em.set_footer(text='Full project: https://github.com/appu1232/Discord-Selfbot')
return em
def cmd_prefix_len():
config = load_config()
return len(config['cmd_prefix'])
def embed_perms(message):
try:
check = message.author.permissions_in(message.channel).embed_links
except:
check = True
return check
def get_user(message, user):
try:
member = message.mentions[0]
except:
member = message.guild.get_member_named(user)
if not member:
try:
member = message.guild.get_member(int(user))
except ValueError:
pass
if not member:
return None
return member
def find_channel(channel_list, text):
if text.isdigit():
found_channel = discord.utils.get(channel_list, id=int(text))
elif text.startswith("<#") and text.endswith(">"):
found_channel = discord.utils.get(channel_list,
id=text.replace("<", "").replace(">", "").replace("#", ""))
else:
found_channel = discord.utils.get(channel_list, name=text)
return found_channel
async def get_google_entries(query):
url = 'https://www.google.com/search?q={}'.format(uriquote(query))
params = {
'safe': 'off',
'lr': 'lang_en',
'h1': 'en'
}
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64)'
}
entries = []
async with aiohttp.ClientSession() as session:
async with session.get(url, params=params, headers=headers) as resp:
if resp.status != 200:
config = load_optional_config()
async with session.get("https://www.googleapis.com/customsearch/v1?q=" + quote_plus(query) + "&start=" + '1' + "&key=" + config['google_api_key'] + "&cx=" + config['custom_search_engine']) as resp:
result = json.loads(await resp.text())
return None, result['items'][0]['link']
try:
root = etree.fromstring(await resp.text(), etree.HTMLParser())
search_nodes = root.findall(".//div[@class='g']")
for node in search_nodes:
url_node = node.find('.//h3/a')
if url_node is None:
continue
url = url_node.attrib['href']
if not url.startswith('/url?'):
continue
url = parse_qs(url[5:])['q'][0]
entries.append(url)
except NameError:
root = BeautifulSoup(await resp.text(), 'html.parser')
for result in root.find_all("div", class_='g'):
url_node = result.find('h3')
if url_node:
for link in url_node.find_all('a', href=True):
url = link['href']
if not url.startswith('/url?'):
continue
url = parse_qs(url[5:])['q'][0]
entries.append(url)
return entries, root
def attach_perms(message):
return message.author.permissions_in(message.channel).attach_files
def parse_prefix(bot, text):
prefix = bot.cmd_prefix
if type(prefix) is list:
prefix = prefix[0]
return text.replace("[c]", prefix).replace("[b]", bot.bot_prefix)<|fim▁end|>
|
# @common.deprecation_warn()
def load_optional_config():
with open('settings/optional_config.json', 'r') as f:
|
<|file_name|>base.py<|end_file_name|><|fim▁begin|>from __future__ import unicode_literals
import copy
import sys
from functools import update_wrapper
from django.utils.six.moves import zip
import django.db.models.manager # Imported to register signal handler.
from django.conf import settings
from django.core.exceptions import (ObjectDoesNotExist,
MultipleObjectsReturned, FieldError, ValidationError, NON_FIELD_ERRORS)
from django.core import validators
from django.db.models.fields import AutoField, FieldDoesNotExist
from django.db.models.fields.related import (ManyToOneRel,
OneToOneField, add_lazy_relation)
from django.db import (router, transaction, DatabaseError,
DEFAULT_DB_ALIAS)
from django.db.models.query import Q
from django.db.models.query_utils import DeferredAttribute, deferred_class_factory
from django.db.models.deletion import Collector
from django.db.models.options import Options
from django.db.models import signals
from django.db.models.loading import register_models, get_model
from django.utils.translation import ugettext_lazy as _
from django.utils.functional import curry
from django.utils.encoding import force_str, force_text
from django.utils import six
from django.utils.text import get_text_list, capfirst
def subclass_exception(name, parents, module, attached_to=None):
"""
Create exception subclass. Used by ModelBase below.
If 'attached_to' is supplied, the exception will be created in a way that
allows it to be pickled, assuming the returned exception class will be added
as an attribute to the 'attached_to' class.
"""
class_dict = {'__module__': module}
if attached_to is not None:
def __reduce__(self):
# Exceptions are special - they've got state that isn't
# in self.__dict__. We assume it is all in self.args.
return (unpickle_inner_exception, (attached_to, name), self.args)
def __setstate__(self, args):
self.args = args
class_dict['__reduce__'] = __reduce__
class_dict['__setstate__'] = __setstate__
return type(name, parents, class_dict)
class ModelBase(type):
"""
Metaclass for all models.
"""
def __new__(cls, name, bases, attrs):
super_new = super(ModelBase, cls).__new__
# six.with_metaclass() inserts an extra class called 'NewBase' in the
# inheritance tree: Model -> NewBase -> object. But the initialization
# should be executed only once for a given model class.
# attrs will never be empty for classes declared in the standard way
# (ie. with the `class` keyword). This is quite robust.
if name == 'NewBase' and attrs == {}:
return super_new(cls, name, bases, attrs)
# Also ensure initialization is only performed for subclasses of Model
# (excluding Model class itself).
parents = [b for b in bases if isinstance(b, ModelBase) and
not (b.__name__ == 'NewBase' and b.__mro__ == (b, object))]
if not parents:
return super_new(cls, name, bases, attrs)
# Create the class.
module = attrs.pop('__module__')
new_class = super_new(cls, name, bases, {'__module__': module})
attr_meta = attrs.pop('Meta', None)
abstract = getattr(attr_meta, 'abstract', False)
if not attr_meta:
meta = getattr(new_class, 'Meta', None)
else:
meta = attr_meta
base_meta = getattr(new_class, '_meta', None)
if getattr(meta, 'app_label', None) is None:
# Figure out the app_label by looking one level up.
# For 'django.contrib.sites.models', this would be 'sites'.
model_module = sys.modules[new_class.__module__]
kwargs = {"app_label": model_module.__name__.split('.')[-2]}
else:
kwargs = {}
new_class.add_to_class('_meta', Options(meta, **kwargs))
if not abstract:
new_class.add_to_class('DoesNotExist', subclass_exception(str('DoesNotExist'),
tuple(x.DoesNotExist
for x in parents if hasattr(x, '_meta') and not x._meta.abstract)
or (ObjectDoesNotExist,),
module, attached_to=new_class))
new_class.add_to_class('MultipleObjectsReturned', subclass_exception(str('MultipleObjectsReturned'),
tuple(x.MultipleObjectsReturned
for x in parents if hasattr(x, '_meta') and not x._meta.abstract)
or (MultipleObjectsReturned,),
module, attached_to=new_class))
if base_meta and not base_meta.abstract:
# Non-abstract child classes inherit some attributes from their
# non-abstract parent (unless an ABC comes before it in the
# method resolution order).
if not hasattr(meta, 'ordering'):
new_class._meta.ordering = base_meta.ordering
if not hasattr(meta, 'get_latest_by'):
new_class._meta.get_latest_by = base_meta.get_latest_by
is_proxy = new_class._meta.proxy
# If the model is a proxy, ensure that the base class
# hasn't been swapped out.
if is_proxy and base_meta and base_meta.swapped:
raise TypeError("%s cannot proxy the swapped model '%s'." % (name, base_meta.swapped))
if getattr(new_class, '_default_manager', None):
if not is_proxy:
# Multi-table inheritance doesn't inherit default manager from
# parents.
new_class._default_manager = None
new_class._base_manager = None
else:
# Proxy classes do inherit parent's default manager, if none is
# set explicitly.
new_class._default_manager = new_class._default_manager._copy_to_model(new_class)
new_class._base_manager = new_class._base_manager._copy_to_model(new_class)
# Bail out early if we have already created this class.
m = get_model(new_class._meta.app_label, name,
seed_cache=False, only_installed=False)
if m is not None:
return m
# Add all attributes to the class.
for obj_name, obj in attrs.items():
new_class.add_to_class(obj_name, obj)
# All the fields of any type declared on this model
new_fields = new_class._meta.local_fields + \
new_class._meta.local_many_to_many + \
new_class._meta.virtual_fields
field_names = set([f.name for f in new_fields])
# Basic setup for proxy models.
if is_proxy:
base = None
for parent in [cls for cls in parents if hasattr(cls, '_meta')]:
if parent._meta.abstract:
if parent._meta.fields:
raise TypeError("Abstract base class containing model fields not permitted for proxy model '%s'." % name)
else:
continue
if base is not None:
raise TypeError("Proxy model '%s' has more than one non-abstract model base class." % name)
else:
base = parent
if base is None:
raise TypeError("Proxy model '%s' has no non-abstract model base class." % name)
if (new_class._meta.local_fields or
new_class._meta.local_many_to_many):
raise FieldError("Proxy model '%s' contains model fields." % name)
new_class._meta.setup_proxy(base)
new_class._meta.concrete_model = base._meta.concrete_model
else:
new_class._meta.concrete_model = new_class
# Do the appropriate setup for any model parents.
o2o_map = dict([(f.rel.to, f) for f in new_class._meta.local_fields
if isinstance(f, OneToOneField)])
for base in parents:
original_base = base
if not hasattr(base, '_meta'):
# Things without _meta aren't functional models, so they're
# uninteresting parents.
continue
parent_fields = base._meta.local_fields + base._meta.local_many_to_many
# Check for clashes between locally declared fields and those
# on the base classes (we cannot handle shadowed fields at the
# moment).
for field in parent_fields:
if field.name in field_names:
raise FieldError('Local field %r in class %r clashes '
'with field of similar name from '
'base class %r' %
(field.name, name, base.__name__))
if not base._meta.abstract:
# Concrete classes...
base = base._meta.concrete_model
if base in o2o_map:
field = o2o_map[base]
elif not is_proxy:
attr_name = '%s_ptr' % base._meta.module_name
field = OneToOneField(base, name=attr_name,
auto_created=True, parent_link=True)
new_class.add_to_class(attr_name, field)
else:
field = None
new_class._meta.parents[base] = field
else:
# .. and abstract ones.
for field in parent_fields:
new_class.add_to_class(field.name, copy.deepcopy(field))
# Pass any non-abstract parent classes onto child.
new_class._meta.parents.update(base._meta.parents)
# Inherit managers from the abstract base classes.
new_class.copy_managers(base._meta.abstract_managers)
# Proxy models inherit the non-abstract managers from their base,
# unless they have redefined any of them.
if is_proxy:
new_class.copy_managers(original_base._meta.concrete_managers)
# Inherit virtual fields (like GenericForeignKey) from the parent
# class
for field in base._meta.virtual_fields:
if base._meta.abstract and field.name in field_names:
raise FieldError('Local field %r in class %r clashes '\
'with field of similar name from '\
'abstract base class %r' % \
(field.name, name, base.__name__))
new_class.add_to_class(field.name, copy.deepcopy(field))
if abstract:
# Abstract base models can't be instantiated and don't appear in
# the list of models for an app. We do the final setup for them a
# little differently from normal models.
attr_meta.abstract = False
new_class.Meta = attr_meta
return new_class
new_class._prepare()
register_models(new_class._meta.app_label, new_class)
# Because of the way imports happen (recursively), we may or may not be
# the first time this model tries to register with the framework. There
# should only be one class for each model, so we always return the
# registered version.
return get_model(new_class._meta.app_label, name,
seed_cache=False, only_installed=False)
def copy_managers(cls, base_managers):
# This is in-place sorting of an Options attribute, but that's fine.
base_managers.sort()
for _, mgr_name, manager in base_managers:
val = getattr(cls, mgr_name, None)
if not val or val is manager:
new_manager = manager._copy_to_model(cls)
cls.add_to_class(mgr_name, new_manager)
def add_to_class(cls, name, value):
if hasattr(value, 'contribute_to_class'):
value.contribute_to_class(cls, name)
else:
setattr(cls, name, value)
def _prepare(cls):
"""
Creates some methods once self._meta has been populated.
"""
opts = cls._meta
opts._prepare(cls)
if opts.order_with_respect_to:
cls.get_next_in_order = curry(cls._get_next_or_previous_in_order, is_next=True)
cls.get_previous_in_order = curry(cls._get_next_or_previous_in_order, is_next=False)
# defer creating accessors on the foreign class until we are
# certain it has been created
def make_foreign_order_accessors(field, model, cls):
setattr(
field.rel.to,
'get_%s_order' % cls.__name__.lower(),
curry(method_get_order, cls)
)
setattr(
field.rel.to,
'set_%s_order' % cls.__name__.lower(),
curry(method_set_order, cls)
)
add_lazy_relation(
cls,
opts.order_with_respect_to,
opts.order_with_respect_to.rel.to,
make_foreign_order_accessors
)
# Give the class a docstring -- its definition.
if cls.__doc__ is None:
cls.__doc__ = "%s(%s)" % (cls.__name__, ", ".join([f.attname for f in opts.fields]))
if hasattr(cls, 'get_absolute_url'):
cls.get_absolute_url = update_wrapper(curry(get_absolute_url, opts, cls.get_absolute_url),
cls.get_absolute_url)
signals.class_prepared.send(sender=cls)
class ModelState(object):
"""
A class for storing instance state
"""
def __init__(self, db=None):
self.db = db
# If true, uniqueness validation checks will consider this a new, as-yet-unsaved object.
# Necessary for correct validation of new instances of objects with explicit (non-auto) PKs.
# This impacts validation only; it has no effect on the actual save.
self.adding = True
class Model(six.with_metaclass(ModelBase)):
_deferred = False
def __init__(self, *args, **kwargs):
signals.pre_init.send(sender=self.__class__, args=args, kwargs=kwargs)
# Set up the storage for instance state
self._state = ModelState()
# There is a rather weird disparity here; if kwargs, it's set, then args
# overrides it. It should be one or the other; don't duplicate the work
# The reason for the kwargs check is that standard iterator passes in by
# args, and instantiation for iteration is 33% faster.
args_len = len(args)
if args_len > len(self._meta.fields):
# Daft, but matches old exception sans the err msg.
raise IndexError("Number of args exceeds number of fields")
fields_iter = iter(self._meta.fields)
if not kwargs:
# The ordering of the zip calls matter - zip throws StopIteration
# when an iter throws it. So if the first iter throws it, the second
# is *not* consumed. We rely on this, so don't change the order
# without changing the logic.
for val, field in zip(args, fields_iter):
setattr(self, field.attname, val)
else:
# Slower, kwargs-ready version.
for val, field in zip(args, fields_iter):
setattr(self, field.attname, val)
kwargs.pop(field.name, None)
# Maintain compatibility with existing calls.
if isinstance(field.rel, ManyToOneRel):
kwargs.pop(field.attname, None)
# Now we're left with the unprocessed fields that *must* come from
# keywords, or default.
for field in fields_iter:
is_related_object = False
# This slightly odd construct is so that we can access any
# data-descriptor object (DeferredAttribute) without triggering its
# __get__ method.
if (field.attname not in kwargs and
isinstance(self.__class__.__dict__.get(field.attname), DeferredAttribute)):
# This field will be populated on request.
continue
if kwargs:
if isinstance(field.rel, ManyToOneRel):
try:
# Assume object instance was passed in.
rel_obj = kwargs.pop(field.name)
is_related_object = True
except KeyError:
try:
# Object instance wasn't passed in -- must be an ID.
val = kwargs.pop(field.attname)
except KeyError:
val = field.get_default()
else:
# Object instance was passed in. Special case: You can
# pass in "None" for related objects if it's allowed.
if rel_obj is None and field.null:
val = None
else:
try:
val = kwargs.pop(field.attname)
except KeyError:
# This is done with an exception rather than the
# default argument on pop because we don't want
# get_default() to be evaluated, and then not used.
# Refs #12057.
val = field.get_default()
else:
val = field.get_default()
if is_related_object:
# If we are passed a related instance, set it using the
# field.name instead of field.attname (e.g. "user" instead of
# "user_id") so that the object gets properly cached (and type
# checked) by the RelatedObjectDescriptor.
setattr(self, field.name, rel_obj)
else:
setattr(self, field.attname, val)
if kwargs:
for prop in list(kwargs):
try:
if isinstance(getattr(self.__class__, prop), property):
setattr(self, prop, kwargs.pop(prop))
except AttributeError:
pass
if kwargs:
raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
super(Model, self).__init__()
signals.post_init.send(sender=self.__class__, instance=self)
def __repr__(self):
try:
u = six.text_type(self)
except (UnicodeEncodeError, UnicodeDecodeError):
u = '[Bad Unicode data]'
return force_str('<%s: %s>' % (self.__class__.__name__, u))
def __str__(self):
if not six.PY3 and hasattr(self, '__unicode__'):
if type(self).__unicode__ == Model.__str__:
klass_name = type(self).__name__
raise RuntimeError("%s.__unicode__ is aliased to __str__. Did"
" you apply @python_2_unicode_compatible"
" without defining __str__?" % klass_name)
return force_text(self).encode('utf-8')
return '%s object' % self.__class__.__name__
def __eq__(self, other):
return isinstance(other, self.__class__) and self._get_pk_val() == other._get_pk_val()
def __ne__(self, other):
return not self.__eq__(other)
def __hash__(self):
return hash(self._get_pk_val())
def __reduce__(self):
"""
Provides pickling support. Normally, this just dispatches to Python's
standard handling. However, for models with deferred field loading, we
need to do things manually, as they're dynamically created classes and
only module-level classes can be pickled by the default path.
"""
if not self._deferred:
return super(Model, self).__reduce__()
data = self.__dict__
defers = []
for field in self._meta.fields:
if isinstance(self.__class__.__dict__.get(field.attname),
DeferredAttribute):
defers.append(field.attname)
model = self._meta.proxy_for_model
return (model_unpickle, (model, defers), data)
def _get_pk_val(self, meta=None):
if not meta:
meta = self._meta
return getattr(self, meta.pk.attname)
def _set_pk_val(self, value):
return setattr(self, self._meta.pk.attname, value)
pk = property(_get_pk_val, _set_pk_val)
def serializable_value(self, field_name):
"""
Returns the value of the field name for this instance. If the field is
a foreign key, returns the id value, instead of the object. If there's
no Field object with this name on the model, the model attribute's
value is returned directly.
Used to serialize a field's value (in the serializer, or form output,
for example). Normally, you would just access the attribute directly
and not use this method.
"""
try:
field = self._meta.get_field_by_name(field_name)[0]
except FieldDoesNotExist:
return getattr(self, field_name)
return getattr(self, field.attname)
def save(self, force_insert=False, force_update=False, using=None,
update_fields=None):
"""
Saves the current instance. Override this in a subclass if you want to
control the saving process.
<|fim▁hole|> """
using = using or router.db_for_write(self.__class__, instance=self)
if force_insert and (force_update or update_fields):
raise ValueError("Cannot force both insert and updating in model saving.")
if update_fields is not None:
# If update_fields is empty, skip the save. We do also check for
# no-op saves later on for inheritance cases. This bailout is
# still needed for skipping signal sending.
if len(update_fields) == 0:
return
update_fields = frozenset(update_fields)
field_names = set()
for field in self._meta.fields:
if not field.primary_key:
field_names.add(field.name)
if field.name != field.attname:
field_names.add(field.attname)
non_model_fields = update_fields.difference(field_names)
if non_model_fields:
raise ValueError("The following fields do not exist in this "
"model or are m2m fields: %s"
% ', '.join(non_model_fields))
# If saving to the same database, and this model is deferred, then
# automatically do a "update_fields" save on the loaded fields.
elif not force_insert and self._deferred and using == self._state.db:
field_names = set()
for field in self._meta.fields:
if not field.primary_key and not hasattr(field, 'through'):
field_names.add(field.attname)
deferred_fields = [
f.attname for f in self._meta.fields
if f.attname not in self.__dict__
and isinstance(self.__class__.__dict__[f.attname],
DeferredAttribute)]
loaded_fields = field_names.difference(deferred_fields)
if loaded_fields:
update_fields = frozenset(loaded_fields)
self.save_base(using=using, force_insert=force_insert,
force_update=force_update, update_fields=update_fields)
save.alters_data = True
def save_base(self, raw=False, cls=None, origin=None, force_insert=False,
force_update=False, using=None, update_fields=None):
"""
Does the heavy-lifting involved in saving. Subclasses shouldn't need to
override this method. It's separate from save() in order to hide the
need for overrides of save() to pass around internal-only parameters
('raw', 'cls', and 'origin').
"""
using = using or router.db_for_write(self.__class__, instance=self)
assert not (force_insert and (force_update or update_fields))
assert update_fields is None or len(update_fields) > 0
if cls is None:
cls = self.__class__
meta = cls._meta
if not meta.proxy:
origin = cls
else:
meta = cls._meta
if origin and not meta.auto_created:
signals.pre_save.send(sender=origin, instance=self, raw=raw, using=using,
update_fields=update_fields)
# If we are in a raw save, save the object exactly as presented.
# That means that we don't try to be smart about saving attributes
# that might have come from the parent class - we just save the
# attributes we have been given to the class we have been given.
# We also go through this process to defer the save of proxy objects
# to their actual underlying model.
if not raw or meta.proxy:
if meta.proxy:
org = cls
else:
org = None
for parent, field in meta.parents.items():
# At this point, parent's primary key field may be unknown
# (for example, from administration form which doesn't fill
# this field). If so, fill it.
if field and getattr(self, parent._meta.pk.attname) is None and getattr(self, field.attname) is not None:
setattr(self, parent._meta.pk.attname, getattr(self, field.attname))
self.save_base(cls=parent, origin=org, using=using,
update_fields=update_fields)
if field:
setattr(self, field.attname, self._get_pk_val(parent._meta))
# Since we didn't have an instance of the parent handy, we
# set attname directly, bypassing the descriptor.
# Invalidate the related object cache, in case it's been
# accidentally populated. A fresh instance will be
# re-built from the database if necessary.
cache_name = field.get_cache_name()
if hasattr(self, cache_name):
delattr(self, cache_name)
if meta.proxy:
return
if not meta.proxy:
non_pks = [f for f in meta.local_fields if not f.primary_key]
if update_fields:
non_pks = [f for f in non_pks if f.name in update_fields or f.attname in update_fields]
# First, try an UPDATE. If that doesn't update anything, do an INSERT.
pk_val = self._get_pk_val(meta)
pk_set = pk_val is not None
record_exists = True
manager = cls._base_manager
if pk_set:
# Determine if we should do an update (pk already exists, forced update,
# no force_insert)
if ((force_update or update_fields) or (not force_insert and
manager.using(using).filter(pk=pk_val).exists())):
if force_update or non_pks:
values = [(f, None, (raw and getattr(self, f.attname) or f.pre_save(self, False))) for f in non_pks]
if values:
rows = manager.using(using).filter(pk=pk_val)._update(values)
if force_update and not rows:
raise DatabaseError("Forced update did not affect any rows.")
if update_fields and not rows:
raise DatabaseError("Save with update_fields did not affect any rows.")
else:
record_exists = False
if not pk_set or not record_exists:
if meta.order_with_respect_to:
# If this is a model with an order_with_respect_to
# autopopulate the _order field
field = meta.order_with_respect_to
order_value = manager.using(using).filter(**{field.name: getattr(self, field.attname)}).count()
self._order = order_value
fields = meta.local_fields
if not pk_set:
if force_update or update_fields:
raise ValueError("Cannot force an update in save() with no primary key.")
fields = [f for f in fields if not isinstance(f, AutoField)]
record_exists = False
update_pk = bool(meta.has_auto_field and not pk_set)
result = manager._insert([self], fields=fields, return_id=update_pk, using=using, raw=raw)
if update_pk:
setattr(self, meta.pk.attname, result)
transaction.commit_unless_managed(using=using)
# Store the database on which the object was saved
self._state.db = using
# Once saved, this is no longer a to-be-added instance.
self._state.adding = False
# Signal that the save is complete
if origin and not meta.auto_created:
signals.post_save.send(sender=origin, instance=self, created=(not record_exists),
update_fields=update_fields, raw=raw, using=using)
save_base.alters_data = True
def delete(self, using=None):
using = using or router.db_for_write(self.__class__, instance=self)
assert self._get_pk_val() is not None, "%s object can't be deleted because its %s attribute is set to None." % (self._meta.object_name, self._meta.pk.attname)
collector = Collector(using=using)
collector.collect([self])
collector.delete()
delete.alters_data = True
def _get_FIELD_display(self, field):
value = getattr(self, field.attname)
return force_text(dict(field.flatchoices).get(value, value), strings_only=True)
def _get_next_or_previous_by_FIELD(self, field, is_next, **kwargs):
if not self.pk:
raise ValueError("get_next/get_previous cannot be used on unsaved objects.")
op = is_next and 'gt' or 'lt'
order = not is_next and '-' or ''
param = force_text(getattr(self, field.attname))
q = Q(**{'%s__%s' % (field.name, op): param})
q = q | Q(**{field.name: param, 'pk__%s' % op: self.pk})
qs = self.__class__._default_manager.using(self._state.db).filter(**kwargs).filter(q).order_by('%s%s' % (order, field.name), '%spk' % order)
try:
return qs[0]
except IndexError:
raise self.DoesNotExist("%s matching query does not exist." % self.__class__._meta.object_name)
def _get_next_or_previous_in_order(self, is_next):
cachename = "__%s_order_cache" % is_next
if not hasattr(self, cachename):
op = is_next and 'gt' or 'lt'
order = not is_next and '-_order' or '_order'
order_field = self._meta.order_with_respect_to
obj = self._default_manager.filter(**{
order_field.name: getattr(self, order_field.attname)
}).filter(**{
'_order__%s' % op: self._default_manager.values('_order').filter(**{
self._meta.pk.name: self.pk
})
}).order_by(order)[:1].get()
setattr(self, cachename, obj)
return getattr(self, cachename)
def prepare_database_save(self, unused):
return self.pk
def clean(self):
"""
Hook for doing any extra model-wide validation after clean() has been
called on every field by self.clean_fields. Any ValidationError raised
by this method will not be associated with a particular field; it will
have a special-case association with the field defined by NON_FIELD_ERRORS.
"""
pass
def validate_unique(self, exclude=None):
"""
Checks unique constraints on the model and raises ``ValidationError``
if any failed.
"""
unique_checks, date_checks = self._get_unique_checks(exclude=exclude)
errors = self._perform_unique_checks(unique_checks)
date_errors = self._perform_date_checks(date_checks)
for k, v in date_errors.items():
errors.setdefault(k, []).extend(v)
if errors:
raise ValidationError(errors)
def _get_unique_checks(self, exclude=None):
"""
Gather a list of checks to perform. Since validate_unique could be
called from a ModelForm, some fields may have been excluded; we can't
perform a unique check on a model that is missing fields involved
in that check.
Fields that did not validate should also be excluded, but they need
to be passed in via the exclude argument.
"""
if exclude is None:
exclude = []
unique_checks = []
unique_togethers = [(self.__class__, self._meta.unique_together)]
for parent_class in self._meta.parents.keys():
if parent_class._meta.unique_together:
unique_togethers.append((parent_class, parent_class._meta.unique_together))
for model_class, unique_together in unique_togethers:
for check in unique_together:
for name in check:
# If this is an excluded field, don't add this check.
if name in exclude:
break
else:
unique_checks.append((model_class, tuple(check)))
# These are checks for the unique_for_<date/year/month>.
date_checks = []
# Gather a list of checks for fields declared as unique and add them to
# the list of checks.
fields_with_class = [(self.__class__, self._meta.local_fields)]
for parent_class in self._meta.parents.keys():
fields_with_class.append((parent_class, parent_class._meta.local_fields))
for model_class, fields in fields_with_class:
for f in fields:
name = f.name
if name in exclude:
continue
if f.unique:
unique_checks.append((model_class, (name,)))
if f.unique_for_date and f.unique_for_date not in exclude:
date_checks.append((model_class, 'date', name, f.unique_for_date))
if f.unique_for_year and f.unique_for_year not in exclude:
date_checks.append((model_class, 'year', name, f.unique_for_year))
if f.unique_for_month and f.unique_for_month not in exclude:
date_checks.append((model_class, 'month', name, f.unique_for_month))
return unique_checks, date_checks
def _perform_unique_checks(self, unique_checks):
errors = {}
for model_class, unique_check in unique_checks:
# Try to look up an existing object with the same values as this
# object's values for all the unique field.
lookup_kwargs = {}
for field_name in unique_check:
f = self._meta.get_field(field_name)
lookup_value = getattr(self, f.attname)
if lookup_value is None:
# no value, skip the lookup
continue
if f.primary_key and not self._state.adding:
# no need to check for unique primary key when editing
continue
lookup_kwargs[str(field_name)] = lookup_value
# some fields were skipped, no reason to do the check
if len(unique_check) != len(lookup_kwargs):
continue
qs = model_class._default_manager.filter(**lookup_kwargs)
# Exclude the current object from the query if we are editing an
# instance (as opposed to creating a new one)
# Note that we need to use the pk as defined by model_class, not
# self.pk. These can be different fields because model inheritance
# allows single model to have effectively multiple primary keys.
# Refs #17615.
model_class_pk = self._get_pk_val(model_class._meta)
if not self._state.adding and model_class_pk is not None:
qs = qs.exclude(pk=model_class_pk)
if qs.exists():
if len(unique_check) == 1:
key = unique_check[0]
else:
key = NON_FIELD_ERRORS
errors.setdefault(key, []).append(self.unique_error_message(model_class, unique_check))
return errors
def _perform_date_checks(self, date_checks):
errors = {}
for model_class, lookup_type, field, unique_for in date_checks:
lookup_kwargs = {}
# there's a ticket to add a date lookup, we can remove this special
# case if that makes it's way in
date = getattr(self, unique_for)
if date is None:
continue
if lookup_type == 'date':
lookup_kwargs['%s__day' % unique_for] = date.day
lookup_kwargs['%s__month' % unique_for] = date.month
lookup_kwargs['%s__year' % unique_for] = date.year
else:
lookup_kwargs['%s__%s' % (unique_for, lookup_type)] = getattr(date, lookup_type)
lookup_kwargs[field] = getattr(self, field)
qs = model_class._default_manager.filter(**lookup_kwargs)
# Exclude the current object from the query if we are editing an
# instance (as opposed to creating a new one)
if not self._state.adding and self.pk is not None:
qs = qs.exclude(pk=self.pk)
if qs.exists():
errors.setdefault(field, []).append(
self.date_error_message(lookup_type, field, unique_for)
)
return errors
def date_error_message(self, lookup_type, field, unique_for):
opts = self._meta
return _("%(field_name)s must be unique for %(date_field)s %(lookup)s.") % {
'field_name': six.text_type(capfirst(opts.get_field(field).verbose_name)),
'date_field': six.text_type(capfirst(opts.get_field(unique_for).verbose_name)),
'lookup': lookup_type,
}
def unique_error_message(self, model_class, unique_check):
opts = model_class._meta
model_name = capfirst(opts.verbose_name)
# A unique field
if len(unique_check) == 1:
field_name = unique_check[0]
field = opts.get_field(field_name)
field_label = capfirst(field.verbose_name)
# Insert the error into the error dict, very sneaky
return field.error_messages['unique'] % {
'model_name': six.text_type(model_name),
'field_label': six.text_type(field_label)
}
# unique_together
else:
field_labels = [capfirst(opts.get_field(f).verbose_name) for f in unique_check]
field_labels = get_text_list(field_labels, _('and'))
return _("%(model_name)s with this %(field_label)s already exists.") % {
'model_name': six.text_type(model_name),
'field_label': six.text_type(field_labels)
}
def full_clean(self, exclude=None):
"""
Calls clean_fields, clean, and validate_unique, on the model,
and raises a ``ValidationError`` for any errors that occured.
"""
errors = {}
if exclude is None:
exclude = []
try:
self.clean_fields(exclude=exclude)
except ValidationError as e:
errors = e.update_error_dict(errors)
# Form.clean() is run even if other validation fails, so do the
# same with Model.clean() for consistency.
try:
self.clean()
except ValidationError as e:
errors = e.update_error_dict(errors)
# Run unique checks, but only for fields that passed validation.
for name in errors.keys():
if name != NON_FIELD_ERRORS and name not in exclude:
exclude.append(name)
try:
self.validate_unique(exclude=exclude)
except ValidationError as e:
errors = e.update_error_dict(errors)
if errors:
raise ValidationError(errors)
def clean_fields(self, exclude=None):
"""
Cleans all fields and raises a ValidationError containing message_dict
of all validation errors if any occur.
"""
if exclude is None:
exclude = []
errors = {}
for f in self._meta.fields:
if f.name in exclude:
continue
# Skip validation for empty fields with blank=True. The developer
# is responsible for making sure they have a valid value.
raw_value = getattr(self, f.attname)
if f.blank and raw_value in validators.EMPTY_VALUES:
continue
try:
setattr(self, f.attname, f.clean(raw_value, self))
except ValidationError as e:
errors[f.name] = e.messages
if errors:
raise ValidationError(errors)
############################################
# HELPER FUNCTIONS (CURRIED MODEL METHODS) #
############################################
# ORDERING METHODS #########################
def method_set_order(ordered_obj, self, id_list, using=None):
if using is None:
using = DEFAULT_DB_ALIAS
rel_val = getattr(self, ordered_obj._meta.order_with_respect_to.rel.field_name)
order_name = ordered_obj._meta.order_with_respect_to.name
# FIXME: It would be nice if there was an "update many" version of update
# for situations like this.
for i, j in enumerate(id_list):
ordered_obj.objects.filter(**{'pk': j, order_name: rel_val}).update(_order=i)
transaction.commit_unless_managed(using=using)
def method_get_order(ordered_obj, self):
rel_val = getattr(self, ordered_obj._meta.order_with_respect_to.rel.field_name)
order_name = ordered_obj._meta.order_with_respect_to.name
pk_name = ordered_obj._meta.pk.name
return [r[pk_name] for r in
ordered_obj.objects.filter(**{order_name: rel_val}).values(pk_name)]
##############################################
# HELPER FUNCTIONS (CURRIED MODEL FUNCTIONS) #
##############################################
def get_absolute_url(opts, func, self, *args, **kwargs):
return settings.ABSOLUTE_URL_OVERRIDES.get('%s.%s' % (opts.app_label, opts.module_name), func)(self, *args, **kwargs)
########
# MISC #
########
class Empty(object):
pass
def model_unpickle(model, attrs):
"""
Used to unpickle Model subclasses with deferred fields.
"""
cls = deferred_class_factory(model, attrs)
return cls.__new__(cls)
model_unpickle.__safe_for_unpickle__ = True
def unpickle_inner_exception(klass, exception_name):
# Get the exception class from the class it is attached to:
exception = getattr(klass, exception_name)
return exception.__new__(exception)<|fim▁end|>
|
The 'force_insert' and 'force_update' parameters can be used to insist
that the "save" must be an SQL insert or update (or equivalent for
non-SQL backends), respectively. Normally, they should not be set.
|
<|file_name|>package.py<|end_file_name|><|fim▁begin|>##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, [email protected], All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/spack/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#<|fim▁hole|># it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class Numdiff(AutotoolsPackage):
"""Numdiff is a little program that can be used to compare putatively
similar files line by line and field by field, ignoring small numeric
differences or/and different numeric formats."""
homepage = 'https://www.nongnu.org/numdiff'
url = 'http://nongnu.askapache.com/numdiff/numdiff-5.8.1.tar.gz'
maintainers = ['davydden']
version('5.9.0', '794461a7285d8b9b1f2c4a8149889ea6')
version('5.8.1', 'a295eb391f6cb1578209fc6b4f9d994e')
variant('nls', default=False,
description="Enable Natural Language Support")
variant('gmp', default=False,
description="Use GNU Multiple Precision Arithmetic Library")
depends_on('gettext', when='+nls')
depends_on('gmp', when='+gmp')
def configure_args(self):
spec = self.spec
args = []
if '+nls' in spec:
args.append('--enable-nls')
else:
args.append('--disable-nls')
if '+gmp' in spec:
# compile with -O0 as per upstream known issue with optimization
# and GMP; https://launchpad.net/ubuntu/+source/numdiff/+changelog
# http://www.nongnu.org/numdiff/#issues
# keep this variant off by default as one still encounter
# GNU MP: Cannot allocate memory (size=2305843009206983184)
args.extend([
'--enable-gmp',
'CFLAGS=-O0'
])
else:
args.append('--disable-gmp')
return args<|fim▁end|>
|
# This program is free software; you can redistribute it and/or modify
|
<|file_name|>service.py<|end_file_name|><|fim▁begin|>#
# 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.
"""Service object."""
from oslo_versionedobjects import base
from oslo_versionedobjects import fields
from knob.db.sqlalchemy import api as db_api
from knob.objects import base as knob_base
class Service(
knob_base.KnobObject,
base.VersionedObjectDictCompat,
base.ComparableVersionedObject,
):
fields = {
'id': fields.IntegerField(),
'host': fields.StringField(),
'binary': fields.StringField(),
'topic': fields.StringField(),
'created_at': fields.DateTimeField(read_only=True),
'updated_at': fields.DateTimeField(nullable=True),
'deleted_at': fields.DateTimeField(nullable=True)
}
@staticmethod
def _from_db_object(context, service, db_service):
for field in service.fields:
service[field] = db_service[field]
service._context = context
service.obj_reset_changes()
return service
@classmethod
def _from_db_objects(cls, context, list_obj):
return [cls._from_db_object(context, cls(context), obj)
for obj in list_obj]
@classmethod
def get_by_id(cls, context, service_id):
service_db = db_api.service_get(context, service_id)
service = cls._from_db_object(context, cls(), service_db)
return service
@classmethod
def create(cls, context, values):
return cls._from_db_object(
context,
cls(),
db_api.service_create(context, values))
@classmethod
def update_by_id(cls, context, service_id, values):
return cls._from_db_object(
context,
cls(),
db_api.service_update(context, service_id, values))
@classmethod
def delete(cls, context, service_id, soft_delete=True):
db_api.service_delete(context, service_id, soft_delete)
@classmethod
def get_all(cls, context):
return cls._from_db_objects(context,
db_api.service_get_all(context))
@classmethod<|fim▁hole|> db_api.service_get_all_by_args(context,
host,
binary,
topic))<|fim▁end|>
|
def get_all_by_args(cls, context, host, binary, topic):
return cls._from_db_objects(
context,
|
<|file_name|>ScriptLoader.cpp<|end_file_name|><|fim▁begin|>/*
* Copyright (C) 2005-2012 MaNGOS <http://www.getmangos.com/>
* Copyright (C) 2008-2012 Trinity <http://www.trinitycore.org/>
* Copyright (C) 2010-2012 Project SkyFire <http://www.projectskyfire.org/>
* Copyright (C) 2011-2012 Darkpeninsula Project <http://www.darkpeninsula.eu/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "gamePCH.h"
#include "ScriptPCH.h"
#include "ScriptLoader.h"
//examples
void AddSC_example_creature();
void AddSC_example_escort();
void AddSC_example_gossip_codebox();
void AddSC_example_misc();
//player scripts
void AddSC_player_mage_scripts();
void AddSC_example_commandscript();
// spells
void AddSC_deathknight_spell_scripts();
void AddSC_druid_spell_scripts();
void AddSC_generic_spell_scripts();
void AddSC_hunter_spell_scripts();
void AddSC_mage_spell_scripts();
void AddSC_paladin_spell_scripts();
void AddSC_priest_spell_scripts();
void AddSC_rogue_spell_scripts();
void AddSC_shaman_spell_scripts();
void AddSC_warlock_spell_scripts();
void AddSC_warrior_spell_scripts();
void AddSC_quest_spell_scripts();
void AddSC_item_spell_scripts();
void AddSC_example_spell_scripts();
void AddSC_SmartSCripts();
//Commands
void AddSC_account_commandscript();
void AddSC_achievement_commandscript();
void AddSC_gm_commandscript();
void AddSC_go_commandscript();
void AddSC_learn_commandscript();
void AddSC_misc_commandscript();
void AddSC_modify_commandscript();
void AddSC_npc_commandscript();
void AddSC_debug_commandscript();
void AddSC_reload_commandscript();
void AddSC_titles_commandscript();
void AddSC_wp_commandscript();
void AddSC_gobject_commandscript();
void AddSC_honor_commandscript();
void AddSC_quest_commandscript();
void AddSC_reload_commandscript();
void AddSC_remove_commandscript();
#ifdef SCRIPTS
//world
void AddSC_areatrigger_scripts();
void AddSC_boss_emeriss();
void AddSC_boss_taerar();
void AddSC_boss_ysondre();
void AddSC_generic_creature();
void AddSC_go_scripts();
void AddSC_guards();
void AddSC_item_scripts();
void AddSC_npc_professions();
void AddSC_npc_innkeeper();
void AddSC_npc_spell_click_spells();
void AddSC_npcs_special();
void AddSC_npc_taxi();
void AddSC_achievement_scripts();
//eastern kingdoms
void AddSC_alterac_valley(); //Alterac Valley
void AddSC_boss_balinda();
void AddSC_boss_drekthar();
void AddSC_boss_galvangar();
void AddSC_boss_vanndar();
void AddSC_blackrock_depths(); //Blackrock Depths
void AddSC_boss_ambassador_flamelash();
void AddSC_boss_anubshiah();
void AddSC_boss_draganthaurissan();
void AddSC_boss_general_angerforge();
void AddSC_boss_gorosh_the_dervish();
void AddSC_boss_grizzle();
void AddSC_boss_high_interrogator_gerstahn();
void AddSC_boss_magmus();
void AddSC_boss_moira_bronzebeard();
void AddSC_boss_tomb_of_seven();
void AddSC_instance_blackrock_depths();
void AddSC_boss_drakkisath(); //Blackrock Spire
void AddSC_boss_halycon();
void AddSC_boss_highlordomokk();
void AddSC_boss_mothersmolderweb();
void AddSC_boss_overlordwyrmthalak();
void AddSC_boss_shadowvosh();
void AddSC_boss_thebeast();
void AddSC_boss_warmastervoone();
void AddSC_boss_quatermasterzigris();
void AddSC_boss_pyroguard_emberseer();
void AddSC_boss_gyth();
void AddSC_boss_rend_blackhand();
void AddSC_boss_razorgore(); //Blackwing lair
void AddSC_boss_vael();
void AddSC_boss_broodlord();
void AddSC_boss_firemaw();
void AddSC_boss_ebonroc();
void AddSC_boss_flamegor();
void AddSC_boss_chromaggus();
void AddSC_boss_nefarian();
void AddSC_boss_victor_nefarius();
void AddSC_deadmines(); //Deadmines
void AddSC_instance_deadmines();
void AddSC_boss_mr_smite();
void AddSC_boss_glubtok();
void AddSC_gnomeregan(); //Gnomeregan
void AddSC_instance_gnomeregan();
void AddSC_gilneas(); // gilneas
void AddSC_boss_attumen(); //Karazhan
void AddSC_boss_curator();
void AddSC_boss_maiden_of_virtue();
void AddSC_boss_shade_of_aran();
void AddSC_boss_malchezaar();
void AddSC_boss_terestian_illhoof();
void AddSC_boss_moroes();
void AddSC_bosses_opera();
void AddSC_boss_netherspite();
void AddSC_instance_karazhan();
void AddSC_karazhan();
void AddSC_boss_nightbane();
void AddSC_boss_felblood_kaelthas(); // Magister's Terrace
void AddSC_boss_selin_fireheart();
void AddSC_boss_vexallus();
void AddSC_boss_priestess_delrissa();
void AddSC_instance_magisters_terrace();
void AddSC_magisters_terrace();
void AddSC_boss_lucifron(); //Molten core
void AddSC_boss_magmadar();
void AddSC_boss_gehennas();
void AddSC_boss_garr();
void AddSC_boss_baron_geddon();
void AddSC_boss_shazzrah();
void AddSC_boss_golemagg();
void AddSC_boss_sulfuron();
void AddSC_boss_majordomo();
void AddSC_boss_ragnaros();
void AddSC_instance_molten_core();
void AddSC_molten_core();
void AddSC_the_scarlet_enclave(); //Scarlet Enclave
void AddSC_the_scarlet_enclave_c1();
void AddSC_the_scarlet_enclave_c2();
void AddSC_the_scarlet_enclave_c5();
void AddSC_boss_arcanist_doan(); //Scarlet Monastery
void AddSC_boss_azshir_the_sleepless();
void AddSC_boss_bloodmage_thalnos();
void AddSC_boss_headless_horseman();
void AddSC_boss_herod();
void AddSC_boss_high_inquisitor_fairbanks();
void AddSC_boss_houndmaster_loksey();
void AddSC_boss_interrogator_vishas();
void AddSC_boss_scorn();
void AddSC_instance_scarlet_monastery();
void AddSC_boss_mograine_and_whitemane();
void AddSC_boss_darkmaster_gandling(); //Scholomance
void AddSC_boss_death_knight_darkreaver();
void AddSC_boss_theolenkrastinov();
void AddSC_boss_illuciabarov();
void AddSC_boss_instructormalicia();
void AddSC_boss_jandicebarov();
void AddSC_boss_kormok();
void AddSC_boss_lordalexeibarov();
void AddSC_boss_lorekeeperpolkelt();
void AddSC_boss_rasfrost();
void AddSC_boss_theravenian();
void AddSC_boss_vectus();
void AddSC_instance_scholomance();
void AddSC_shadowfang_keep(); //Shadowfang keep
void AddSC_instance_shadowfang_keep();
void AddSC_boss_magistrate_barthilas(); //Stratholme
void AddSC_boss_maleki_the_pallid();
void AddSC_boss_nerubenkan();
void AddSC_boss_cannon_master_willey();
void AddSC_boss_baroness_anastari();
void AddSC_boss_ramstein_the_gorger();
void AddSC_boss_timmy_the_cruel();
void AddSC_boss_postmaster_malown();
void AddSC_boss_baron_rivendare();
void AddSC_boss_dathrohan_balnazzar();
void AddSC_boss_order_of_silver_hand();
void AddSC_instance_stratholme();
void AddSC_stratholme();
void AddSC_sunken_temple(); // Sunken Temple
void AddSC_instance_sunken_temple();
void AddSC_instance_sunwell_plateau(); //Sunwell Plateau
void AddSC_boss_kalecgos();
void AddSC_boss_brutallus();
void AddSC_boss_felmyst();
void AddSC_boss_eredar_twins();
void AddSC_boss_muru();
void AddSC_boss_kiljaeden();
void AddSC_sunwell_plateau();
void AddSC_boss_archaedas(); //Uldaman
void AddSC_boss_ironaya();
void AddSC_uldaman();
void AddSC_instance_uldaman();
void AddSC_boss_akilzon(); //Zul'Aman
void AddSC_boss_halazzi();
void AddSC_boss_hex_lord_malacrass();
void AddSC_boss_janalai();
void AddSC_boss_nalorakk();
void AddSC_boss_zuljin();
void AddSC_instance_zulaman();
void AddSC_zulaman();
void AddSC_boss_jeklik(); //Zul'Gurub
void AddSC_boss_venoxis();
void AddSC_boss_marli();
void AddSC_boss_mandokir();
void AddSC_boss_gahzranka();
void AddSC_boss_thekal();
void AddSC_boss_arlokk();
void AddSC_boss_jindo();
void AddSC_boss_hakkar();
void AddSC_boss_grilek();
void AddSC_boss_hazzarah();
void AddSC_boss_renataki();
void AddSC_boss_wushoolay();
void AddSC_instance_zulgurub();
//void AddSC_alterac_mountains();
void AddSC_arathi_highlands();
void AddSC_blasted_lands();
void AddSC_boss_kruul();
void AddSC_burning_steppes();
void AddSC_dun_morogh();
void AddSC_duskwood();
void AddSC_eastern_plaguelands();
void AddSC_elwynn_forest();
void AddSC_eversong_woods();
void AddSC_ghostlands();
void AddSC_hinterlands();
void AddSC_ironforge();
void AddSC_isle_of_queldanas();
void AddSC_loch_modan();
void AddSC_redridge_mountains();
void AddSC_searing_gorge();
void AddSC_silvermoon_city();
void AddSC_silverpine_forest();
void AddSC_stormwind_city();
void AddSC_stranglethorn_vale();
void AddSC_swamp_of_sorrows();
void AddSC_tirisfal_glades();
void AddSC_undercity();
void AddSC_western_plaguelands();
void AddSC_westfall();
void AddSC_wetlands();
//kalimdor
void AddSC_blackfathom_deeps(); //Blackfathom Depths
void AddSC_boss_gelihast();
void AddSC_boss_kelris();
void AddSC_boss_aku_mai();
void AddSC_instance_blackfathom_deeps();
void AddSC_hyjal(); //CoT Battle for Mt. Hyjal
void AddSC_boss_archimonde();
void AddSC_instance_mount_hyjal();
void AddSC_hyjal_trash();
void AddSC_boss_rage_winterchill();
void AddSC_boss_anetheron();
void AddSC_boss_kazrogal();
void AddSC_boss_azgalor();
void AddSC_boss_captain_skarloc(); //CoT Old Hillsbrad
void AddSC_boss_epoch_hunter();
void AddSC_boss_lieutenant_drake();
void AddSC_instance_old_hillsbrad();
void AddSC_old_hillsbrad();
void AddSC_boss_aeonus(); //CoT The Dark Portal
void AddSC_boss_chrono_lord_deja();
void AddSC_boss_temporus();
void AddSC_dark_portal();
void AddSC_instance_dark_portal();
void AddSC_boss_epoch(); //CoT Culling Of Stratholme
void AddSC_boss_infinite_corruptor();
void AddSC_boss_salramm();
void AddSC_boss_mal_ganis();
void AddSC_boss_meathook();
void AddSC_culling_of_stratholme();
void AddSC_instance_culling_of_stratholme();
void AddSC_boss_celebras_the_cursed(); //Maraudon
void AddSC_boss_landslide();
void AddSC_boss_noxxion();
void AddSC_boss_ptheradras();
void AddSC_boss_onyxia(); //Onyxia's Lair
void AddSC_instance_onyxias_lair();
void AddSC_boss_amnennar_the_coldbringer(); //Razorfen Downs
void AddSC_razorfen_downs();
void AddSC_instance_razorfen_downs();
void AddSC_razorfen_kraul(); //Razorfen Kraul
void AddSC_boss_kurinnaxx(); //Ruins of ahn'qiraj
void AddSC_boss_rajaxx();
void AddSC_boss_moam();
void AddSC_boss_buru();
void AddSC_boss_ayamiss();
void AddSC_boss_ossirian();
void AddSC_instance_ruins_of_ahnqiraj();
void AddSC_boss_cthun(); //Temple of ahn'qiraj
void AddSC_boss_fankriss();
void AddSC_boss_huhuran();
void AddSC_bug_trio();
void AddSC_boss_sartura();
void AddSC_boss_skeram();
void AddSC_boss_twinemperors();
void AddSC_mob_anubisath_sentinel();
void AddSC_instance_temple_of_ahnqiraj();
void AddSC_wailing_caverns(); //Wailing caverns
void AddSC_instance_wailing_caverns();
void AddSC_zulfarrak(); //Zul'Farrak generic
void AddSC_instance_zulfarrak(); //Zul'Farrak instance script
void AddSC_npc_pusillin(); //Dire Maul Pusillin
void AddSC_ashenvale();
void AddSC_azshara();
void AddSC_azuremyst_isle();
void AddSC_bloodmyst_isle();
void AddSC_boss_azuregos();
void AddSC_darkshore();
void AddSC_desolace();
void AddSC_durotar();
void AddSC_dustwallow_marsh();
void AddSC_felwood();
void AddSC_feralas();
void AddSC_moonglade();
void AddSC_mulgore();
void AddSC_orgrimmar();
void AddSC_silithus();
void AddSC_stonetalon_mountains();
void AddSC_tanaris();
void AddSC_teldrassil();
void AddSC_the_barrens();
void AddSC_thousand_needles();
void AddSC_thunder_bluff();
void AddSC_ungoro_crater();
void AddSC_winterspring();
//Northrend
void AddSC_boss_slad_ran();
void AddSC_boss_moorabi();
void AddSC_boss_drakkari_colossus();
void AddSC_boss_gal_darah();
void AddSC_boss_eck();
void AddSC_instance_gundrak();
void AddSC_boss_krik_thir(); //Azjol-Nerub
void AddSC_boss_hadronox();
void AddSC_boss_anub_arak();
void AddSC_instance_azjol_nerub();
void AddSC_instance_ahnkahet(); //Azjol-Nerub Ahn'kahet
void AddSC_boss_amanitar();
void AddSC_boss_taldaram();
void AddSC_boss_jedoga_shadowseeker();
void AddSC_boss_elder_nadox();
void AddSC_boss_volazj();
void AddSC_boss_argent_challenge(); //Trial of the Champion
void AddSC_boss_black_knight();
void AddSC_boss_grand_champions();
void AddSC_instance_trial_of_the_champion();
void AddSC_trial_of_the_champion();
void AddSC_boss_anubarak_trial(); //Trial of the Crusader
void AddSC_boss_faction_champions();
void AddSC_boss_jaraxxus();
void AddSC_boss_northrend_beasts();
void AddSC_boss_twin_valkyr();
void AddSC_trial_of_the_crusader();
void AddSC_instance_trial_of_the_crusader();
void AddSC_boss_anubrekhan(); //Naxxramas
void AddSC_boss_maexxna();
void AddSC_boss_patchwerk();
void AddSC_boss_grobbulus();
void AddSC_boss_razuvious();
void AddSC_boss_kelthuzad();
void AddSC_boss_loatheb();
void AddSC_boss_noth();
void AddSC_boss_gluth();
void AddSC_boss_sapphiron();
void AddSC_boss_four_horsemen();
void AddSC_boss_faerlina();
void AddSC_boss_heigan();
void AddSC_boss_gothik();
void AddSC_boss_thaddius();
void AddSC_instance_naxxramas();
void AddSC_boss_magus_telestra(); //The Nexus Nexus
void AddSC_boss_anomalus();
void AddSC_boss_ormorok();
void AddSC_boss_keristrasza();
void AddSC_instance_nexus();
void AddSC_boss_drakos(); //The Nexus The Oculus
void AddSC_boss_urom();
void AddSC_boss_varos();
void AddSC_instance_oculus();
void AddSC_oculus();
void AddSC_boss_sartharion(); //Obsidian Sanctum
void AddSC_instance_obsidian_sanctum();
void AddSC_boss_bjarngrim(); //Ulduar Halls of Lightning
void AddSC_boss_loken();
void AddSC_boss_ionar();
void AddSC_boss_volkhan();
void AddSC_instance_halls_of_lightning();
void AddSC_boss_maiden_of_grief(); //Ulduar Halls of Stone
void AddSC_boss_krystallus();
void AddSC_boss_sjonnir();
void AddSC_instance_halls_of_stone();
void AddSC_halls_of_stone();
void AddSC_boss_auriaya(); //Ulduar Ulduar
void AddSC_boss_flame_leviathan();
void AddSC_boss_ignis();
void AddSC_boss_razorscale();
void AddSC_boss_xt002();
void AddSC_boss_kologarn();
void AddSC_boss_assembly_of_iron();
void AddSC_ulduar_teleporter();
void AddSC_instance_ulduar();
void AddSC_boss_keleseth(); //Utgarde Keep
void AddSC_boss_skarvald_dalronn();
void AddSC_boss_ingvar_the_plunderer();
void AddSC_instance_utgarde_keep();
void AddSC_boss_svala(); //Utgarde pinnacle
void AddSC_boss_palehoof();
void AddSC_boss_skadi();
void AddSC_boss_ymiron();
void AddSC_instance_utgarde_pinnacle();
void AddSC_utgarde_keep();
void AddSC_boss_archavon(); //Vault of Archavon
void AddSC_boss_emalon();
void AddSC_boss_koralon();
void AddSC_boss_toravon();
void AddSC_instance_archavon();
void AddSC_boss_trollgore(); //Drak'Tharon Keep
void AddSC_boss_novos();
void AddSC_boss_dred();
void AddSC_boss_tharon_ja();
void AddSC_instance_drak_tharon();
void AddSC_boss_cyanigosa(); //Violet Hold
void AddSC_boss_erekem();
void AddSC_boss_ichoron();
void AddSC_boss_lavanthor();
void AddSC_boss_moragg();
void AddSC_boss_xevozz();
void AddSC_boss_zuramat();
void AddSC_instance_violet_hold();
void AddSC_violet_hold();
void AddSC_instance_forge_of_souls(); //Forge of Souls
void AddSC_forge_of_souls();
void AddSC_boss_bronjahm();
void AddSC_boss_devourer_of_souls();
void AddSC_instance_pit_of_saron(); //Pit of Saron
void AddSC_pit_of_saron();
void AddSC_boss_garfrost();
void AddSC_boss_ick();
void AddSC_boss_tyrannus();
void AddSC_instance_halls_of_reflection(); // Halls of Reflection
void AddSC_halls_of_reflection();
void AddSC_boss_falric();
void AddSC_boss_marwyn();
void AddSC_boss_lord_marrowgar(); // Icecrown Citadel
void AddSC_boss_lady_deathwhisper();
void AddSC_boss_deathbringer_saurfang();
void AddSC_boss_festergut();
void AddSC_boss_rotface();
void AddSC_boss_professor_putricide();
void AddSC_boss_blood_prince_council();
void AddSC_boss_blood_queen_lana_thel();
void AddSC_boss_sindragosa();
void AddSC_icecrown_citadel_teleport();
void AddSC_instance_icecrown_citadel();
void AddSC_icecrown_citadel();
void AddSC_dalaran();
void AddSC_borean_tundra();
void AddSC_dragonblight();
void AddSC_grizzly_hills();
void AddSC_howling_fjord();
void AddSC_icecrown();
void AddSC_sholazar_basin();
void AddSC_storm_peaks();
void AddSC_zuldrak();
void AddSC_crystalsong_forest();
void AddSC_isle_of_conquest();
//outland
void AddSC_boss_exarch_maladaar(); //Auchindoun Auchenai Crypts
void AddSC_boss_shirrak_the_dead_watcher();
void AddSC_boss_nexusprince_shaffar(); //Auchindoun Mana Tombs
void AddSC_boss_pandemonius();
void AddSC_boss_darkweaver_syth(); //Auchindoun Sekketh Halls
void AddSC_boss_talon_king_ikiss();
void AddSC_instance_sethekk_halls();
void AddSC_instance_shadow_labyrinth(); //Auchindoun Shadow Labyrinth
void AddSC_boss_ambassador_hellmaw();
void AddSC_boss_blackheart_the_inciter();
void AddSC_boss_grandmaster_vorpil();
void AddSC_boss_murmur();
void AddSC_black_temple(); //Black Temple
void AddSC_boss_illidan();
void AddSC_boss_shade_of_akama();
void AddSC_boss_supremus();
void AddSC_boss_gurtogg_bloodboil();
void AddSC_boss_mother_shahraz();
void AddSC_boss_reliquary_of_souls();
void AddSC_boss_teron_gorefiend();
void AddSC_boss_najentus();
void AddSC_boss_illidari_council();
void AddSC_instance_black_temple();
void AddSC_boss_fathomlord_karathress(); //CR Serpent Shrine Cavern
void AddSC_boss_hydross_the_unstable();
void AddSC_boss_lady_vashj();
void AddSC_boss_leotheras_the_blind();
void AddSC_boss_morogrim_tidewalker();
void AddSC_instance_serpentshrine_cavern();
void AddSC_boss_the_lurker_below();
void AddSC_boss_hydromancer_thespia(); //CR Steam Vault
void AddSC_boss_mekgineer_steamrigger();
void AddSC_boss_warlord_kalithresh();
void AddSC_instance_steam_vault();
void AddSC_boss_hungarfen(); //CR Underbog
void AddSC_boss_the_black_stalker();
void AddSC_boss_gruul(); //Gruul's Lair
void AddSC_boss_high_king_maulgar();
void AddSC_instance_gruuls_lair();
void AddSC_boss_broggok(); //HC Blood Furnace
void AddSC_boss_kelidan_the_breaker();
void AddSC_boss_the_maker();
void AddSC_instance_blood_furnace();
void AddSC_boss_magtheridon(); //HC Magtheridon's Lair
void AddSC_instance_magtheridons_lair();
void AddSC_boss_grand_warlock_nethekurse(); //HC Shattered Halls
void AddSC_boss_warbringer_omrogg();
void AddSC_boss_warchief_kargath_bladefist();
void AddSC_instance_shattered_halls();
void AddSC_boss_watchkeeper_gargolmar(); //HC Ramparts
void AddSC_boss_omor_the_unscarred();
void AddSC_boss_vazruden_the_herald();
void AddSC_instance_ramparts();
void AddSC_arcatraz(); //TK Arcatraz
void AddSC_boss_harbinger_skyriss();
void AddSC_instance_arcatraz();
void AddSC_boss_high_botanist_freywinn(); //TK Botanica
void AddSC_boss_laj();
void AddSC_boss_warp_splinter();
void AddSC_boss_alar(); //TK The Eye
void AddSC_boss_kaelthas();
void AddSC_boss_void_reaver();
void AddSC_boss_high_astromancer_solarian();
void AddSC_instance_the_eye();
void AddSC_the_eye();
void AddSC_boss_gatewatcher_iron_hand(); //TK The Mechanar
void AddSC_boss_nethermancer_sepethrea();
void AddSC_boss_pathaleon_the_calculator();
void AddSC_instance_mechanar();
void AddSC_blades_edge_mountains();
void AddSC_boss_doomlordkazzak();
void AddSC_boss_doomwalker();
void AddSC_hellfire_peninsula();
void AddSC_nagrand();
void AddSC_netherstorm();
void AddSC_shadowmoon_valley();
void AddSC_shattrath_city();
void AddSC_terokkar_forest();
void AddSC_zangarmarsh();
// Cataclysm Scripts
void AddSC_the_stonecore(); //TheStonecore
void AddSC_instance_the_stonecore();
void AddSC_instance_halls_of_origination(); //Halls of Origination
void AddSC_boss_temple_guardian_anhuur();
void AddSC_boss_earthrager_ptah();
void AddSC_boss_anraphet();
void AddSC_instance_baradin_hold(); //Baradin Hold
void AddSC_boss_argaloth();
void AddSC_lost_city_of_the_tolvir(); //The Lost City of the Tol'vir
void AddSC_instance_lost_city_of_the_tolvir();
void AddSC_boss_lockmaw();
void AddSC_boss_high_prophet_barim();
void AddSC_instance_the_vortex_pinnacle(); //The Vortex Pinnacle
void AddSC_instance_grim_batol(); //Grim Batol
void AddSC_instance_throne_of_the_tides(); //Throne of the Tides
void AddSC_instance_blackrock_caverns(); //Blackrock Caverns
// Darkpeninsula
void AddSC_premium();
// The Maelstrom
// Kezan
void AddSC_kezan();
// battlegrounds
// outdoor pvp
void AddSC_outdoorpvp_ep();
void AddSC_outdoorpvp_hp();
void AddSC_outdoorpvp_na();
void AddSC_outdoorpvp_si();<|fim▁hole|>void AddSC_outdoorpvp_tf();
void AddSC_outdoorpvp_zm();
void AddSC_outdoorpvp_gh();
// player
void AddSC_chat_log();
#endif
void AddScripts()
{
AddExampleScripts();
AddPlayerScripts();
AddSpellScripts();
AddSC_SmartSCripts();
AddCommandScripts();
#ifdef SCRIPTS
AddWorldScripts();
AddEasternKingdomsScripts();
AddKalimdorScripts();
AddOutlandScripts();
AddNorthrendScripts();
AddBattlegroundScripts();
AddOutdoorPvPScripts();
AddCustomScripts();
#endif
}
void AddExampleScripts()
{
AddSC_example_creature();
AddSC_example_escort();
AddSC_example_gossip_codebox();
AddSC_example_misc();
AddSC_example_commandscript();
}
void AddPlayerScripts()
{
AddSC_player_mage_scripts();
}
void AddSpellScripts()
{
AddSC_deathknight_spell_scripts();
AddSC_druid_spell_scripts();
AddSC_generic_spell_scripts();
AddSC_hunter_spell_scripts();
AddSC_mage_spell_scripts();
AddSC_paladin_spell_scripts();
AddSC_priest_spell_scripts();
AddSC_rogue_spell_scripts();
AddSC_shaman_spell_scripts();
AddSC_warlock_spell_scripts();
AddSC_warrior_spell_scripts();
AddSC_quest_spell_scripts();
AddSC_item_spell_scripts();
AddSC_example_spell_scripts();
}
void AddCommandScripts()
{
AddSC_account_commandscript();
AddSC_achievement_commandscript();
AddSC_gm_commandscript();
AddSC_go_commandscript();
AddSC_learn_commandscript();
AddSC_misc_commandscript();
AddSC_modify_commandscript();
AddSC_npc_commandscript();
AddSC_debug_commandscript();
AddSC_reload_commandscript();
AddSC_reload_commandscript();
AddSC_titles_commandscript();
AddSC_wp_commandscript();
AddSC_gobject_commandscript();
AddSC_honor_commandscript();
AddSC_quest_commandscript();
AddSC_reload_commandscript();
AddSC_remove_commandscript();
}
void AddWorldScripts()
{
#ifdef SCRIPTS
AddSC_areatrigger_scripts();
AddSC_boss_emeriss();
AddSC_boss_taerar();
AddSC_boss_ysondre();
AddSC_generic_creature();
AddSC_go_scripts();
AddSC_guards();
AddSC_item_scripts();
AddSC_npc_professions();
AddSC_npc_innkeeper();
AddSC_npc_spell_click_spells();
AddSC_npcs_special();
AddSC_npc_taxi();
AddSC_achievement_scripts();
AddSC_chat_log();
#endif
}
void AddEasternKingdomsScripts()
{
#ifdef SCRIPTS
AddSC_alterac_valley(); //Alterac Valley
AddSC_boss_balinda();
AddSC_boss_drekthar();
AddSC_boss_galvangar();
AddSC_boss_vanndar();
AddSC_blackrock_depths(); //Blackrock Depths
AddSC_boss_ambassador_flamelash();
AddSC_boss_anubshiah();
AddSC_boss_draganthaurissan();
AddSC_boss_general_angerforge();
AddSC_boss_gorosh_the_dervish();
AddSC_boss_grizzle();
AddSC_boss_high_interrogator_gerstahn();
AddSC_boss_magmus();
AddSC_boss_moira_bronzebeard();
AddSC_boss_tomb_of_seven();
AddSC_instance_blackrock_depths();
AddSC_boss_drakkisath(); //Blackrock Spire
AddSC_boss_halycon();
AddSC_boss_highlordomokk();
AddSC_boss_mothersmolderweb();
AddSC_boss_overlordwyrmthalak();
AddSC_boss_shadowvosh();
AddSC_boss_thebeast();
AddSC_boss_warmastervoone();
AddSC_boss_quatermasterzigris();
AddSC_boss_pyroguard_emberseer();
AddSC_boss_gyth();
AddSC_boss_rend_blackhand();
AddSC_boss_razorgore(); //Blackwing lair
AddSC_boss_vael();
AddSC_boss_broodlord();
AddSC_boss_firemaw();
AddSC_boss_ebonroc();
AddSC_boss_flamegor();
AddSC_boss_chromaggus();
AddSC_boss_nefarian();
AddSC_boss_victor_nefarius();
AddSC_deadmines(); //Deadmines
AddSC_instance_deadmines();
AddSC_boss_mr_smite();
AddSC_boss_glubtok();
AddSC_gnomeregan(); //Gnomeregan
AddSC_instance_gnomeregan();
AddSC_gilneas(); // gilneas
AddSC_boss_attumen(); //Karazhan
AddSC_boss_curator();
AddSC_boss_maiden_of_virtue();
AddSC_boss_shade_of_aran();
AddSC_boss_malchezaar();
AddSC_boss_terestian_illhoof();
AddSC_boss_moroes();
AddSC_bosses_opera();
AddSC_boss_netherspite();
AddSC_instance_karazhan();
AddSC_karazhan();
AddSC_boss_nightbane();
AddSC_boss_felblood_kaelthas(); // Magister's Terrace
AddSC_boss_selin_fireheart();
AddSC_boss_vexallus();
AddSC_boss_priestess_delrissa();
AddSC_instance_magisters_terrace();
AddSC_magisters_terrace();
AddSC_boss_lucifron(); //Molten core
AddSC_boss_magmadar();
AddSC_boss_gehennas();
AddSC_boss_garr();
AddSC_boss_baron_geddon();
AddSC_boss_shazzrah();
AddSC_boss_golemagg();
AddSC_boss_sulfuron();
AddSC_boss_majordomo();
AddSC_boss_ragnaros();
AddSC_instance_molten_core();
AddSC_molten_core();
AddSC_the_scarlet_enclave(); //Scarlet Enclave
AddSC_the_scarlet_enclave_c1();
AddSC_the_scarlet_enclave_c2();
AddSC_the_scarlet_enclave_c5();
AddSC_boss_arcanist_doan(); //Scarlet Monastery
AddSC_boss_azshir_the_sleepless();
AddSC_boss_bloodmage_thalnos();
AddSC_boss_headless_horseman();
AddSC_boss_herod();
AddSC_boss_high_inquisitor_fairbanks();
AddSC_boss_houndmaster_loksey();
AddSC_boss_interrogator_vishas();
AddSC_boss_scorn();
AddSC_instance_scarlet_monastery();
AddSC_boss_mograine_and_whitemane();
AddSC_boss_darkmaster_gandling(); //Scholomance
AddSC_boss_death_knight_darkreaver();
AddSC_boss_theolenkrastinov();
AddSC_boss_illuciabarov();
AddSC_boss_instructormalicia();
AddSC_boss_jandicebarov();
AddSC_boss_kormok();
AddSC_boss_lordalexeibarov();
AddSC_boss_lorekeeperpolkelt();
AddSC_boss_rasfrost();
AddSC_boss_theravenian();
AddSC_boss_vectus();
AddSC_instance_scholomance();
AddSC_shadowfang_keep(); //Shadowfang keep
AddSC_instance_shadowfang_keep();
AddSC_boss_magistrate_barthilas(); //Stratholme
AddSC_boss_maleki_the_pallid();
AddSC_boss_nerubenkan();
AddSC_boss_cannon_master_willey();
AddSC_boss_baroness_anastari();
AddSC_boss_ramstein_the_gorger();
AddSC_boss_timmy_the_cruel();
AddSC_boss_postmaster_malown();
AddSC_boss_baron_rivendare();
AddSC_boss_dathrohan_balnazzar();
AddSC_boss_order_of_silver_hand();
AddSC_instance_stratholme();
AddSC_stratholme();
AddSC_sunken_temple(); // Sunken Temple
AddSC_instance_sunken_temple();
AddSC_instance_sunwell_plateau(); //Sunwell Plateau
AddSC_boss_kalecgos();
AddSC_boss_brutallus();
AddSC_boss_felmyst();
AddSC_boss_eredar_twins();
AddSC_boss_muru();
AddSC_boss_kiljaeden();
AddSC_sunwell_plateau();
AddSC_boss_archaedas(); //Uldaman
AddSC_boss_ironaya();
AddSC_uldaman();
AddSC_instance_uldaman();
AddSC_boss_akilzon(); //Zul'Aman
AddSC_boss_halazzi();
AddSC_boss_hex_lord_malacrass();
AddSC_boss_janalai();
AddSC_boss_nalorakk();
AddSC_boss_zuljin();
AddSC_instance_zulaman();
AddSC_zulaman();
AddSC_boss_jeklik(); //Zul'Gurub
AddSC_boss_venoxis();
AddSC_boss_marli();
AddSC_boss_mandokir();
AddSC_boss_gahzranka();
AddSC_boss_thekal();
AddSC_boss_arlokk();
AddSC_boss_jindo();
AddSC_boss_hakkar();
AddSC_boss_grilek();
AddSC_boss_hazzarah();
AddSC_boss_renataki();
AddSC_boss_wushoolay();
AddSC_instance_zulgurub();
//AddSC_alterac_mountains();
AddSC_arathi_highlands();
AddSC_blasted_lands();
AddSC_boss_kruul();
AddSC_burning_steppes();
AddSC_dun_morogh();
AddSC_duskwood();
AddSC_eastern_plaguelands();
AddSC_elwynn_forest();
AddSC_eversong_woods();
AddSC_ghostlands();
AddSC_hinterlands();
AddSC_ironforge();
AddSC_isle_of_queldanas();
AddSC_loch_modan();
AddSC_redridge_mountains();
AddSC_searing_gorge();
AddSC_silvermoon_city();
AddSC_silverpine_forest();
AddSC_stormwind_city();
AddSC_stranglethorn_vale();
AddSC_swamp_of_sorrows();
AddSC_tirisfal_glades();
AddSC_undercity();
AddSC_western_plaguelands();
AddSC_westfall();
AddSC_wetlands();
#endif
}
void AddKalimdorScripts()
{
#ifdef SCRIPTS
AddSC_blackfathom_deeps(); //Blackfathom Depths
AddSC_boss_gelihast();
AddSC_boss_kelris();
AddSC_boss_aku_mai();
AddSC_instance_blackfathom_deeps();
AddSC_hyjal(); //CoT Battle for Mt. Hyjal
AddSC_boss_archimonde();
AddSC_instance_mount_hyjal();
AddSC_hyjal_trash();
AddSC_boss_rage_winterchill();
AddSC_boss_anetheron();
AddSC_boss_kazrogal();
AddSC_boss_azgalor();
AddSC_boss_captain_skarloc(); //CoT Old Hillsbrad
AddSC_boss_epoch_hunter();
AddSC_boss_lieutenant_drake();
AddSC_instance_old_hillsbrad();
AddSC_old_hillsbrad();
AddSC_boss_aeonus(); //CoT The Dark Portal
AddSC_boss_chrono_lord_deja();
AddSC_boss_temporus();
AddSC_dark_portal();
AddSC_instance_dark_portal();
AddSC_boss_epoch(); //CoT Culling Of Stratholme
AddSC_boss_infinite_corruptor();
AddSC_boss_salramm();
AddSC_boss_mal_ganis();
AddSC_boss_meathook();
AddSC_culling_of_stratholme();
AddSC_instance_culling_of_stratholme();
AddSC_boss_celebras_the_cursed(); //Maraudon
AddSC_boss_landslide();
AddSC_boss_noxxion();
AddSC_boss_ptheradras();
AddSC_boss_onyxia(); //Onyxia's Lair
AddSC_instance_onyxias_lair();
AddSC_boss_amnennar_the_coldbringer(); //Razorfen Downs
AddSC_razorfen_downs();
AddSC_instance_razorfen_downs();
AddSC_razorfen_kraul(); //Razorfen Kraul
AddSC_boss_kurinnaxx(); //Ruins of ahn'qiraj
AddSC_boss_rajaxx();
AddSC_boss_moam();
AddSC_boss_buru();
AddSC_boss_ayamiss();
AddSC_boss_ossirian();
AddSC_instance_ruins_of_ahnqiraj();
AddSC_boss_cthun(); //Temple of ahn'qiraj
AddSC_boss_fankriss();
AddSC_boss_huhuran();
AddSC_bug_trio();
AddSC_boss_sartura();
AddSC_boss_skeram();
AddSC_boss_twinemperors();
AddSC_mob_anubisath_sentinel();
AddSC_instance_temple_of_ahnqiraj();
AddSC_wailing_caverns(); //Wailing caverns
AddSC_instance_wailing_caverns();
AddSC_zulfarrak(); //Zul'Farrak generic
AddSC_instance_zulfarrak(); //Zul'Farrak instance script
AddSC_npc_pusillin(); //Dire maul npc Pusillin
AddSC_ashenvale();
AddSC_azshara();
AddSC_azuremyst_isle();
AddSC_bloodmyst_isle();
AddSC_boss_azuregos();
AddSC_darkshore();
AddSC_desolace();
AddSC_durotar();
AddSC_dustwallow_marsh();
AddSC_felwood();
AddSC_feralas();
AddSC_moonglade();
AddSC_mulgore();
AddSC_orgrimmar();
AddSC_silithus();
AddSC_stonetalon_mountains();
AddSC_tanaris();
AddSC_teldrassil();
AddSC_the_barrens();
AddSC_thousand_needles();
AddSC_thunder_bluff();
AddSC_ungoro_crater();
AddSC_winterspring();
#endif
}
void AddOutlandScripts()
{
#ifdef SCRIPTS
AddSC_boss_exarch_maladaar(); //Auchindoun Auchenai Crypts
AddSC_boss_shirrak_the_dead_watcher();
AddSC_boss_nexusprince_shaffar(); //Auchindoun Mana Tombs
AddSC_boss_pandemonius();
AddSC_boss_darkweaver_syth(); //Auchindoun Sekketh Halls
AddSC_boss_talon_king_ikiss();
AddSC_instance_sethekk_halls();
AddSC_instance_shadow_labyrinth(); //Auchindoun Shadow Labyrinth
AddSC_boss_ambassador_hellmaw();
AddSC_boss_blackheart_the_inciter();
AddSC_boss_grandmaster_vorpil();
AddSC_boss_murmur();
AddSC_black_temple(); //Black Temple
AddSC_boss_illidan();
AddSC_boss_shade_of_akama();
AddSC_boss_supremus();
AddSC_boss_gurtogg_bloodboil();
AddSC_boss_mother_shahraz();
AddSC_boss_reliquary_of_souls();
AddSC_boss_teron_gorefiend();
AddSC_boss_najentus();
AddSC_boss_illidari_council();
AddSC_instance_black_temple();
AddSC_boss_fathomlord_karathress(); //CR Serpent Shrine Cavern
AddSC_boss_hydross_the_unstable();
AddSC_boss_lady_vashj();
AddSC_boss_leotheras_the_blind();
AddSC_boss_morogrim_tidewalker();
AddSC_instance_serpentshrine_cavern();
AddSC_boss_the_lurker_below();
AddSC_boss_hydromancer_thespia(); //CR Steam Vault
AddSC_boss_mekgineer_steamrigger();
AddSC_boss_warlord_kalithresh();
AddSC_instance_steam_vault();
AddSC_boss_hungarfen(); //CR Underbog
AddSC_boss_the_black_stalker();
AddSC_boss_gruul(); //Gruul's Lair
AddSC_boss_high_king_maulgar();
AddSC_instance_gruuls_lair();
AddSC_boss_broggok(); //HC Blood Furnace
AddSC_boss_kelidan_the_breaker();
AddSC_boss_the_maker();
AddSC_instance_blood_furnace();
AddSC_boss_magtheridon(); //HC Magtheridon's Lair
AddSC_instance_magtheridons_lair();
AddSC_boss_grand_warlock_nethekurse(); //HC Shattered Halls
AddSC_boss_warbringer_omrogg();
AddSC_boss_warchief_kargath_bladefist();
AddSC_instance_shattered_halls();
AddSC_boss_watchkeeper_gargolmar(); //HC Ramparts
AddSC_boss_omor_the_unscarred();
AddSC_boss_vazruden_the_herald();
AddSC_instance_ramparts();
AddSC_arcatraz(); //TK Arcatraz
AddSC_boss_harbinger_skyriss();
AddSC_instance_arcatraz();
AddSC_boss_high_botanist_freywinn(); //TK Botanica
AddSC_boss_laj();
AddSC_boss_warp_splinter();
AddSC_boss_alar(); //TK The Eye
AddSC_boss_kaelthas();
AddSC_boss_void_reaver();
AddSC_boss_high_astromancer_solarian();
AddSC_instance_the_eye();
AddSC_the_eye();
AddSC_boss_gatewatcher_iron_hand(); //TK The Mechanar
AddSC_boss_nethermancer_sepethrea();
AddSC_boss_pathaleon_the_calculator();
AddSC_instance_mechanar();
AddSC_blades_edge_mountains();
AddSC_boss_doomlordkazzak();
AddSC_boss_doomwalker();
AddSC_hellfire_peninsula();
AddSC_nagrand();
AddSC_netherstorm();
AddSC_shadowmoon_valley();
AddSC_shattrath_city();
AddSC_terokkar_forest();
AddSC_zangarmarsh();
#endif
}
void AddNorthrendScripts()
{
#ifdef SCRIPTS
AddSC_boss_slad_ran(); //Gundrak
AddSC_boss_moorabi();
AddSC_boss_drakkari_colossus();
AddSC_boss_gal_darah();
AddSC_boss_eck();
AddSC_instance_gundrak();
AddSC_boss_amanitar();
AddSC_boss_taldaram(); //Azjol-Nerub Ahn'kahet
AddSC_boss_elder_nadox();
AddSC_boss_jedoga_shadowseeker();
AddSC_boss_volazj();
AddSC_instance_ahnkahet();
AddSC_boss_argent_challenge(); //Trial of the Champion
AddSC_boss_black_knight();
AddSC_boss_grand_champions();
AddSC_instance_trial_of_the_champion();
AddSC_trial_of_the_champion();
AddSC_boss_anubarak_trial(); //Trial of the Crusader
AddSC_boss_faction_champions();
AddSC_boss_jaraxxus();
AddSC_trial_of_the_crusader();
AddSC_boss_twin_valkyr();
AddSC_boss_northrend_beasts();
AddSC_instance_trial_of_the_crusader();
AddSC_boss_krik_thir(); //Azjol-Nerub Azjol-Nerub
AddSC_boss_hadronox();
AddSC_boss_anub_arak();
AddSC_instance_azjol_nerub();
AddSC_boss_anubrekhan(); //Naxxramas
AddSC_boss_maexxna();
AddSC_boss_patchwerk();
AddSC_boss_grobbulus();
AddSC_boss_razuvious();
AddSC_boss_kelthuzad();
AddSC_boss_loatheb();
AddSC_boss_noth();
AddSC_boss_gluth();
AddSC_boss_sapphiron();
AddSC_boss_four_horsemen();
AddSC_boss_faerlina();
AddSC_boss_heigan();
AddSC_boss_gothik();
AddSC_boss_thaddius();
AddSC_instance_naxxramas();
AddSC_boss_magus_telestra(); //The Nexus Nexus
AddSC_boss_anomalus();
AddSC_boss_ormorok();
AddSC_boss_keristrasza();
AddSC_instance_nexus();
AddSC_boss_drakos(); //The Nexus The Oculus
AddSC_boss_urom();
AddSC_boss_varos();
AddSC_instance_oculus();
AddSC_oculus();
AddSC_boss_sartharion(); //Obsidian Sanctum
AddSC_instance_obsidian_sanctum();
AddSC_boss_bjarngrim(); //Ulduar Halls of Lightning
AddSC_boss_loken();
AddSC_boss_ionar();
AddSC_boss_volkhan();
AddSC_instance_halls_of_lightning();
AddSC_boss_maiden_of_grief(); //Ulduar Halls of Stone
AddSC_boss_krystallus();
AddSC_boss_sjonnir();
AddSC_instance_halls_of_stone();
AddSC_halls_of_stone();
AddSC_boss_auriaya(); //Ulduar Ulduar
AddSC_boss_flame_leviathan();
AddSC_boss_ignis();
AddSC_boss_razorscale();
AddSC_boss_xt002();
AddSC_boss_assembly_of_iron();
AddSC_boss_kologarn();
AddSC_ulduar_teleporter();
AddSC_instance_ulduar();
AddSC_boss_keleseth(); //Utgarde Keep
AddSC_boss_skarvald_dalronn();
AddSC_boss_ingvar_the_plunderer();
AddSC_instance_utgarde_keep();
AddSC_boss_svala(); //Utgarde pinnacle
AddSC_boss_palehoof();
AddSC_boss_skadi();
AddSC_boss_ymiron();
AddSC_instance_utgarde_pinnacle();
AddSC_utgarde_keep();
AddSC_boss_archavon(); //Vault of Archavon
AddSC_boss_emalon();
AddSC_boss_koralon();
AddSC_boss_toravon();
AddSC_instance_archavon();
AddSC_boss_trollgore(); //Drak'Tharon Keep
AddSC_boss_novos();
AddSC_boss_dred();
AddSC_boss_tharon_ja();
AddSC_instance_drak_tharon();
AddSC_boss_cyanigosa(); //Violet Hold
AddSC_boss_erekem();
AddSC_boss_ichoron();
AddSC_boss_lavanthor();
AddSC_boss_moragg();
AddSC_boss_xevozz();
AddSC_boss_zuramat();
AddSC_instance_violet_hold();
AddSC_violet_hold();
AddSC_instance_forge_of_souls(); //Forge of Souls
AddSC_forge_of_souls();
AddSC_boss_bronjahm();
AddSC_boss_devourer_of_souls();
AddSC_instance_pit_of_saron(); //Pit of Saron
AddSC_pit_of_saron();
AddSC_boss_garfrost();
AddSC_boss_ick();
AddSC_boss_tyrannus();
AddSC_instance_halls_of_reflection(); // Halls of Reflection
AddSC_halls_of_reflection();
AddSC_boss_falric();
AddSC_boss_marwyn();
AddSC_boss_lord_marrowgar(); // Icecrown Citadel
AddSC_boss_lady_deathwhisper();
AddSC_boss_deathbringer_saurfang();
AddSC_boss_festergut();
AddSC_boss_rotface();
AddSC_boss_professor_putricide();
AddSC_boss_blood_prince_council();
AddSC_boss_blood_queen_lana_thel();
AddSC_boss_sindragosa();
AddSC_icecrown_citadel_teleport();
AddSC_instance_icecrown_citadel();
AddSC_icecrown_citadel();
AddSC_dalaran();
AddSC_borean_tundra();
AddSC_dragonblight();
AddSC_grizzly_hills();
AddSC_howling_fjord();
AddSC_icecrown();
AddSC_sholazar_basin();
AddSC_storm_peaks();
AddSC_zuldrak();
AddSC_crystalsong_forest();
AddSC_isle_of_conquest();
// Cataclysm Scripts
AddSC_the_stonecore(); //The Stonecore
AddSC_instance_the_stonecore();
AddSC_instance_halls_of_origination(); //Halls of Origination
AddSC_boss_temple_guardian_anhuur();
AddSC_boss_earthrager_ptah();
AddSC_boss_anraphet();
AddSC_instance_baradin_hold(); //Baradin Hold
AddSC_boss_argaloth();
AddSC_lost_city_of_the_tolvir(); //Lost City of the Tol'vir
AddSC_instance_lost_city_of_the_tolvir();
AddSC_boss_lockmaw();
AddSC_boss_high_prophet_barim();
AddSC_instance_the_vortex_pinnacle(); //The Vortex Pinnacle
AddSC_instance_grim_batol(); //Grim Batol
AddSC_instance_throne_of_the_tides(); //Throne of the Tides
AddSC_instance_blackrock_caverns(); //Blackrock Caverns
// Darkpeninsula
AddSC_premium();
// The Maelstrom
// Kezan
AddSC_kezan();
#endif
}
void AddOutdoorPvPScripts()
{
#ifdef SCRIPTS
AddSC_outdoorpvp_ep();
AddSC_outdoorpvp_hp();
AddSC_outdoorpvp_na();
AddSC_outdoorpvp_si();
AddSC_outdoorpvp_tf();
AddSC_outdoorpvp_zm();
AddSC_outdoorpvp_gh();
#endif
}
void AddBattlegroundScripts()
{
#ifdef SCRIPTS
#endif
}
#ifdef SCRIPTS
/* This is where custom scripts' loading functions should be declared. */
#endif
void AddCustomScripts()
{
#ifdef SCRIPTS
/* This is where custom scripts should be added. */
#endif
}<|fim▁end|>
| |
<|file_name|>open.go<|end_file_name|><|fim▁begin|>// Copyright 2012, 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package state
import (
"fmt"
"strings"
"github.com/juju/errors"
"github.com/juju/names"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/txn"
"github.com/juju/juju/constraints"
"github.com/juju/juju/environs/config"
"github.com/juju/juju/mongo"
"github.com/juju/juju/state/watcher"
)
// Open connects to the server described by the given
// info, waits for it to be initialized, and returns a new State
// representing the environment connected to.
//
// A policy may be provided, which will be used to validate and
// modify behaviour of certain operations in state. A nil policy
// may be provided.
//
// Open returns unauthorizedError if access is unauthorized.
func Open(tag names.EnvironTag, info *mongo.MongoInfo, opts mongo.DialOpts, policy Policy) (*State, error) {
st, err := open(tag, info, opts, policy)
if err != nil {
return nil, errors.Trace(err)
}
if _, err := st.Environment(); err != nil {
if err := st.Close(); err != nil {
logger.Errorf("error closing state for unreadable environment %s: %v", tag.Id(), err)
}
return nil, errors.Annotatef(err, "cannot read environment %s", tag.Id())
}
// State should only be Opened on behalf of a state server environ; all
// other *States should be created via ForEnviron.
if err := st.start(tag); err != nil {
return nil, errors.Trace(err)
}
return st, nil
}
func open(tag names.EnvironTag, info *mongo.MongoInfo, opts mongo.DialOpts, policy Policy) (*State, error) {
logger.Infof("opening state, mongo addresses: %q; entity %v", info.Addrs, info.Tag)
logger.Debugf("dialing mongo")
session, err := mongo.DialWithInfo(info.Info, opts)
if err != nil {
return nil, maybeUnauthorized(err, "cannot connect to mongodb")
}
logger.Debugf("connection established")
err = mongodbLogin(session, info)
if err != nil {
session.Close()
return nil, errors.Trace(err)
}
logger.Debugf("mongodb login successful")
// In rare circumstances, we may be upgrading from pre-1.23, and not have the
// environment UUID available. In that case we need to infer what it might be;
// we depend on the assumption that this is the only circumstance in which
// the the UUID might not be known.
if tag.Id() == "" {
logger.Warningf("creating state without environment tag; inferring bootstrap environment")
ssInfo, err := readRawStateServerInfo(session)
if err != nil {
session.Close()
return nil, errors.Trace(err)
}
tag = ssInfo.EnvironmentTag
}
st, err := newState(tag, session, info, policy)
if err != nil {
session.Close()
return nil, errors.Trace(err)
}
return st, nil
}
// mongodbLogin logs in to the mongodb admin database.
func mongodbLogin(session *mgo.Session, mongoInfo *mongo.MongoInfo) error {
admin := session.DB("admin")
if mongoInfo.Tag != nil {
if err := admin.Login(mongoInfo.Tag.String(), mongoInfo.Password); err != nil {
return maybeUnauthorized(err, fmt.Sprintf("cannot log in to admin database as %q", mongoInfo.Tag))
}
} else if mongoInfo.Password != "" {
if err := admin.Login(mongo.AdminUser, mongoInfo.Password); err != nil {
return maybeUnauthorized(err, "cannot log in to admin database")
}
}
return nil
}
// Initialize sets up an initial empty state and returns it.
// This needs to be performed only once for the initial state server environment.
// It returns unauthorizedError if access is unauthorized.
func Initialize(owner names.UserTag, info *mongo.MongoInfo, cfg *config.Config, opts mongo.DialOpts, policy Policy) (_ *State, err error) {
uuid, ok := cfg.UUID()
if !ok {
return nil, errors.Errorf("environment uuid was not supplied")
}
envTag := names.NewEnvironTag(uuid)
st, err := open(envTag, info, opts, policy)
if err != nil {
return nil, errors.Trace(err)
}
defer func() {
if err != nil {
if closeErr := st.Close(); closeErr != nil {
logger.Errorf("error closing state while aborting Initialize: %v", closeErr)
}
}
}()
// A valid environment is used as a signal that the
// state has already been initalized. If this is the case
// do nothing.
if _, err := st.Environment(); err == nil {
return nil, errors.New("already initialized")
} else if !errors.IsNotFound(err) {
return nil, errors.Trace(err)
}
// When creating the state server environment, the new environment
// UUID is also used as the state server UUID.
logger.Infof("initializing state server environment %s", uuid)
ops, err := st.envSetupOps(cfg, uuid, uuid, owner)
if err != nil {
return nil, errors.Trace(err)
}
ops = append(ops,
createInitialUserOp(st, owner, info.Password),
txn.Op{
C: stateServersC,
Id: environGlobalKey,
Assert: txn.DocMissing,
Insert: &stateServersDoc{
EnvUUID: st.EnvironUUID(),
},
},
txn.Op{
C: stateServersC,
Id: apiHostPortsKey,
Assert: txn.DocMissing,
Insert: &apiHostPortsDoc{},
},
txn.Op{
C: stateServersC,
Id: stateServingInfoKey,
Assert: txn.DocMissing,
Insert: &StateServingInfo{},
},
txn.Op{
C: stateServersC,
Id: hostedEnvCountKey,
Assert: txn.DocMissing,
Insert: &hostedEnvCountDoc{},
},
)
if err := st.runTransaction(ops); err != nil {
return nil, errors.Trace(err)
}
if err := st.start(envTag); err != nil {
return nil, errors.Trace(err)
}
return st, nil
}
func (st *State) envSetupOps(cfg *config.Config, envUUID, serverUUID string, owner names.UserTag) ([]txn.Op, error) {
if err := checkEnvironConfig(cfg); err != nil {
return nil, errors.Trace(err)
}
// When creating the state server environment, the new environment
// UUID is also used as the state server UUID.
if serverUUID == "" {
serverUUID = envUUID
}
envUserOp := createEnvUserOp(envUUID, owner, owner, owner.Name())
ops := []txn.Op{
createConstraintsOp(st, environGlobalKey, constraints.Value{}),
createSettingsOp(environGlobalKey, cfg.AllAttrs()),
incHostedEnvironCountOp(),
createEnvironmentOp(st, owner, cfg.Name(), envUUID, serverUUID),
createUniqueOwnerEnvNameOp(owner, cfg.Name()),
envUserOp,
}
return ops, nil
}
func maybeUnauthorized(err error, msg string) error {
if err == nil {
return nil
}
if isUnauthorized(err) {
return errors.Unauthorizedf("%s: unauthorized mongo access: %v", msg, err)
}
return errors.Annotatef(err, msg)
}
func isUnauthorized(err error) bool {
if err == nil {
return false
}
// Some unauthorized access errors have no error code,
// just a simple error string; and some do have error codes
// but are not of consistent types (LastError/QueryError).
for _, prefix := range []string{"auth fail", "not authorized"} {
if strings.HasPrefix(err.Error(), prefix) {
return true
}
}
if err, ok := err.(*mgo.QueryError); ok {
return err.Code == 10057 ||
err.Message == "need to login" ||
err.Message == "unauthorized"
}
return false
}
// newState creates an incomplete *State, with a configured watcher but no
// pwatcher, leadershipManager, or serverTag. You must start() the returned
// *State before it will function correctly.
func newState(environTag names.EnvironTag, session *mgo.Session, mongoInfo *mongo.MongoInfo, policy Policy) (_ *State, resultErr error) {
// Set up database.
rawDB := session.DB(jujuDB)
database, err := allCollections().Load(rawDB, environTag.Id())
if err != nil {
return nil, errors.Trace(err)
}
if err := InitDbLogs(session); err != nil {
return nil, errors.Trace(err)
}
// Create State.
return &State{
environTag: environTag,
mongoInfo: mongoInfo,
session: session,
database: database,
policy: policy,
watcher: watcher.New(rawDB.C(txnLogC)),
}, nil
}
// MongoConnectionInfo returns information for connecting to mongo
func (st *State) MongoConnectionInfo() *mongo.MongoInfo {
return st.mongoInfo
}
// CACert returns the certificate used to validate the state connection.
func (st *State) CACert() string {
return st.mongoInfo.CACert
}
func (st *State) Close() (err error) {
defer errors.DeferredAnnotatef(&err, "closing state failed")
// TODO(fwereade): we have no defence against these components failing
// and leaving other parts of state going. They should be managed by a
// dependency.Engine (or perhaps worker.Runner).
var errs []error
handle := func(name string, err error) {
if err != nil {
errs = append(errs, errors.Annotatef(err, "error stopping %s", name))
}
}
handle("transaction watcher", st.watcher.Stop())
if st.pwatcher != nil {
handle("presence watcher", st.pwatcher.Stop())
}
if st.leadershipManager != nil {
st.leadershipManager.Kill()
handle("leadership manager", st.leadershipManager.Wait())
}
st.mu.Lock()
if st.allManager != nil {
handle("allwatcher manager", st.allManager.Stop())
}
if st.allEnvManager != nil {
handle("allenvwatcher manager", st.allEnvManager.Stop())
}
if st.allEnvWatcherBacking != nil {<|fim▁hole|>
if len(errs) > 0 {
for _, err := range errs[1:] {
logger.Errorf("while closing state: %v", err)
}
return errs[0]
}
logger.Debugf("closed state without error")
return nil
}<|fim▁end|>
|
handle("allenvwatcher backing", st.allEnvWatcherBacking.Release())
}
st.session.Close()
st.mu.Unlock()
|
<|file_name|>offline-pin-sharp.js<|end_file_name|><|fim▁begin|>import { h } from 'omi';
import createSvgIcon from './utils/createSvgIcon';<|fim▁hole|>export default createSvgIcon(h("path", {
d: "M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10 10-4.5 10-10S17.5 2 12 2zm5 16H7v-2h10v2zm-6.7-4L7 10.7l1.4-1.4 1.9 1.9 5.3-5.3L17 7.3 10.3 14z"
}), 'OfflinePinSharp');<|fim▁end|>
| |
<|file_name|>component-helpers.ts<|end_file_name|><|fim▁begin|>export interface DragDelta {
x: number
y: number<|fim▁hole|>
let targets: HTMLElement[] = []
export function getDragDeltas (
onDragDelta: (d: DragDelta) => void,
onMouseDown?: (e?: MouseEvent) => void
) {
let oldX = 0
let oldY = 0
let target: HTMLElement
function onmousedown (e: MouseEvent) {
target = e.currentTarget as HTMLElement
targets.push(target)
oldX = e.clientX
oldY = e.clientY
document.addEventListener('mousemove', onMouseMove)
document.addEventListener('mouseup', onMouseUp)
onMouseDown && onMouseDown(e)
}
function onMouseUp () {
document.removeEventListener('mousemove', onMouseMove)
document.removeEventListener('mouseup', onMouseUp)
targets = targets.filter(t => t !== target)
}
function onMouseMove (e: MouseEvent) {
for (const t of targets) {
if (t !== target && target.contains(t)) return
}
onDragDelta({
x: oldX - e.clientX,
y: oldY - e.clientY
})
oldX = e.clientX
oldY = e.clientY
}
return { onmousedown }
}<|fim▁end|>
|
}
|
<|file_name|>0015_auto_20161111_0313.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-11-11 03:13
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
<|fim▁hole|>
operations = [
migrations.AlterField(
model_name='flag',
name='resolved_by',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='resolved_flags', to=settings.AUTH_USER_MODEL),
),
]<|fim▁end|>
|
dependencies = [
('administration', '0014_auto_20161111_0255'),
]
|
<|file_name|>optimize_grid.py<|end_file_name|><|fim▁begin|># Explore some possibilities for optimizing the grid.
from __future__ import print_function
from . import (paver,trigrid,orthomaker)
from ..spatial import field
import sys
import numpy as np # from numpy import *
from scipy.linalg import norm
# from pylab import *
import matplotlib.pyplot as plt
class OptimizeGui(object):
def __init__(self,og):
self.og = og
self.p = og.p
def run(self):
self.usage()
self.fig = plt.figure()
self.p.plot(boundary=True)
plt.axis('equal')
self.cid = self.fig.canvas.mpl_connect('key_press_event', self.onpress)
self.cid_mouse = self.fig.canvas.mpl_connect('button_release_event',self.on_buttonrelease)
def usage(self):
print("t: flip edge")
print("y: relax neighborhood")
print("u: regrid at point")
print("i: relax node")
print("p: show bad cells")
def flip_edge_at_point(self,pnt):
"""assumes an og instance is visible """
e = self.p.closest_edge(pnt)
self.p.flip_edge(e)
self.p.plot()
def optimize_at_point(self,pnt):
c = self.p.closest_cell(pnt)
nbr = self.og.cell_neighborhood(c,2)
self.og.relax_neighborhood(nbr)
self.p.plot()
last_node_relaxed = None
def relax_node_at_point(self,pnt):
v = self.p.closest_point(pnt)
if v == self.last_node_relaxed:
print("Allowing beta")
self.p.safe_relax_one(v,use_beta=1)
else:
print("No beta")
self.p.safe_relax_one(v)
self.p.plot()
self.last_node_relaxed = v
def regrid_at_point(self,pnt):
c = self.p.closest_cell(pnt)
self.og.repave_neighborhood(c,scale_factor=0.8)
self.p.plot()
def show_bad_cells(self):
bad = np.nonzero( self.og.cell_scores() <0.1 )[0]
vc = self.p.vcenters()
ax = plt.axis()
plt.gca().texts = []
[plt.annotate(str(i),vc[i]) for i in bad]
plt.axis(ax)
def onpress(self,event):
if event.inaxes is not None:
print(event.xdata,event.ydata,event.key)
pnt = np.array( [event.xdata,event.ydata] )
if event.key == 't':
self.flip_edge_at_point(pnt)
print("Returned from calcs")
elif event.key == 'y':
self.optimize_at_point(pnt)
print("Returned from calcs")
elif event.key == 'u':
self.regrid_at_point(pnt)
elif event.key == 'i':
self.relax_node_at_point(pnt)
elif event.key == 'p':
self.show_bad_cells()
return True
last_axis = None
def on_buttonrelease(self,event):
if event.inaxes is not None:
if plt.axis() != self.last_axis:
print("Viewport has changed")
self.last_axis = plt.axis()
self.p.default_clip = self.last_axis
# simple resolution-dependent plotting:
if self.last_axis[1] - self.last_axis[0] > 3000:
self.p.plot(boundary=True)
else:
self.p.plot(boundary=False)
else:
print("button release but axis is the same")
class GridOptimizer(object):
def __init__(self,p):
self.p = p
self.original_density = p.density
# These are the values that, as needed, are used to construct a reduced scale
# apollonius field. since right now ApolloniusField doesn't support insertion
# and updates, we keep it as an array and recreate the field on demand.
valid = np.isfinite(p.points[:,0])
xy_min = p.points[valid].min(axis=0)
xy_max = p.points[valid].max(axis=0)
self.scale_reductions = np.array( [ [xy_min[0],xy_min[1],1e6],
[xy_min[0],xy_max[1],1e6],
[xy_max[0],xy_max[1],1e6],
[xy_max[0],xy_min[1],1e6]] )
apollo_rate = 1.1
def update_apollonius_field(self):
""" create an apollonius graph using the points/scales in self.scale_reductions,
and install it in self.p.
"""
if len(self.scale_reductions) == 0:
self.apollo = None
return
self.apollo = field.ApolloniusField(self.scale_reductions[:,:2],
self.scale_reductions[:,2],
r=self.apollo_rate)
self.p.density = field.BinopField( self.original_density,
minimum,
self.apollo )
# Explore a cost function based on voronoi-edge distance
def cell_scores(self,cell_ids=None,use_original_density=True):
""" Return scores for each cell, based on the minimum distance from the
voronoi center to an edge, normalized by local scale
invalid cells (i.e. have been deleted) get inf score
use_original_density: defaults to evaluating local scale using the
original density field. If set to false, use the current density
field of the paver (which may be a reduced Apollonius Graph field)
"""
p=self.p
if cell_ids is None:
cell_ids = np.arange(p.Ncells())
valid = (p.cells[cell_ids,0]>=0)
vc = p.vcenters()[cell_ids]
local_scale = np.zeros( len(cell_ids), np.float64)
if use_original_density:
local_scale[valid] = self.original_density( vc[valid,:] )
else:
local_scale[valid] = p.density( vc[valid,:] )
local_scale[~valid] = 1.0 # dummy
#
cell_scores = np.inf*np.ones( len(cell_ids) )
# 3 edge centers for every cell
ec1 = 0.5*(p.points[p.cells[cell_ids,0]] + p.points[p.cells[cell_ids,1]])
ec2 = 0.5*(p.points[p.cells[cell_ids,1]] + p.points[p.cells[cell_ids,2]])
ec3 = 0.5*(p.points[p.cells[cell_ids,2]] + p.points[p.cells[cell_ids,0]])
d1 = ((vc - ec1)**2).sum(axis=1)
d2 = ((vc - ec2)**2).sum(axis=1)
d3 = ((vc - ec3)**2).sum(axis=1)
# could be smarter and ignore boundary edges.. later.
# this also has the downside that as we refine the scales, the scores
# get worse. Maybe it would be better to compare the minimum ec value to
# the mean or maximum, say (max(ec) - min(ec)) / med(ec)
scores = np.sqrt(np.minimum(d1,d2,d3)) / local_scale
scores[~valid] = np.inf
return scores
def relax_neighborhood(self,nodes):
""" starting from the given set of nodes, relax in the area until the neighborhood score
stops going down.
"""
cells = set()
for n in nodes:
cells = cells.union( self.p.pnt2cells(n) )
cells = np.array(list(cells))
<|fim▁hole|>
while 1:
cp = self.p.checkpoint()
for n in nodes:
self.p.safe_relax_one(n)
new_worst = self.cell_scores(cells).min()
sys.stdout.write('.') ; sys.stdout.flush()
if new_worst < worst:
#print "That made it even worse."
self.p.revert(cp)
new_worst = worst
break
if new_worst < 1.01*worst:
#print "Not getting any better. ===> %g"%new_worst
break
worst = new_worst
print("Relax: %g => %g"%(starting_worst,new_worst))
self.p.commit()
def cell_neighborhood_apollo(self,c):
""" return the nodes near the given cell
the apollo version means the termination condition is based on the
expected radius of influence of a reduced scale at c
"""
vcs = self.p.vcenters()
c_vc = self.p.vcenters()[c]
orig_scale = self.original_density(c_vc)
apollo_scale = self.apollo(c_vc)
r = (orig_scale - apollo_scale) / (self.apollo.r - 1)
print("Will clear out a radius of %f"%r)
c_set = set()
def dfs(cc):
if cc in c_set:
return
if np.linalg.norm(vcs[cc] - c_vc) > r:
return
c_set.add(cc)
for child in self.p.cell_neighbors(cc):
dfs(child)
dfs(c)
cell_list = np.array(list(c_set))
return np.unique( self.p.cells[cell_list,:] )
def cell_neighborhood(self,c,nbr_count=2):
""" return the nodes near the given cell
if use_apollo is true, the termination condition is based on where
the apollonius scale is larger than the original scale
"""
c_set = set()
def dfs(cc,i):
if cc in c_set:
return
c_set.add(cc)
if i > 0:
for child in self.p.cell_neighbors(cc):
dfs(child,i-1)
dfs(c,nbr_count)
cell_list = np.array(list(c_set))
return np.unique( self.p.cells[cell_list,:] )
def relax_neighborhoods(self,score_threshold=0.1,count_threshold=5000,
neighborhood_size=2):
""" find the worst scores and try just relaxing in the general vicinity
"""
all_scores = self.cell_scores()
ranking = np.argsort(all_scores)
count = 0
while 1:
c = ranking[count]
score = all_scores[c]
if score > score_threshold:
break
nbr = self.cell_neighborhood(c,neighborhood_size)
self.relax_neighborhood(nbr)
count += 1
if count >= count_threshold:
break
# if set, then scale reductions will be handled through an Apollonius Graph
# otherwise, the density field is temporarily scaled down everywhere.
use_apollo = False
def repave_neighborhoods(self,score_threshold=0.1,count_threshold=5000,
neighborhood_size=3,
scale_factor=None):
""" find the worst scores and try just repaving the general vicinity
see repave_neighborhood for use of scale_factor.
if use_apollo is true, neighborhood size is ignored and instead the
neighborhood is defined by the telescoping ratio
"""
all_scores = self.cell_scores()
ranking = np.argsort(all_scores)
## neighborhoods may overlap - and cells might get deleted. Keep a
# record of cells that get deleted, and skip them later on.
# this could get replaced by a priority queue, and we would just update
# metrics as we go.
expired_cells = {}
def expire_cell(dc):
expired_cells[dc] = 1
cb_id = self.p.listen('delete_cell',expire_cell)
if self.use_apollo and scale_factor is not None and scale_factor < 1.0:
# Add reduction points for all cells currently over the limit
to_reduce = np.nonzero(all_scores<score_threshold)[0]
centers = self.p.vcenters()[to_reduce]
orig_scales = self.original_density( centers )
new_scales = scale_factor * orig_scales
xyz = np.concatenate( [centers,new_scales[:,newaxis]], axis=1)
self.scale_reductions = np.concatenate( [self.scale_reductions,xyz])
print( "Installing new Apollonius Field...")
self.update_apollonius_field()
print( "... Done")
count = 0
while 1:
c = ranking[count]
print("Considering cell %d"%c)
count += 1
# cell may have been deleted during other repaving
if self.p.cells[c,0] < 0:
print("It's been deleted")
continue
if expired_cells.has_key(c):
print("It had been deleted, and some other cell has taken its place")
continue
# cell may have been updated during other repaving
# note that it's possible that this cell was made a bit better,
# but still needs to be repaved. For now, don't worry about that
# because we probably want to relax the neighborhood before a second
# round of repaving.
if self.cell_scores(array([c]))[0] > all_scores[c]:
continue
score = all_scores[c]
if score > score_threshold:
break
# also, this cell may have gotten updated by another repaving -
# in which case we probably want
print( "Repaving a neighborhood")
self.repave_neighborhood(c,neighborhood_size=neighborhood_size,scale_factor=scale_factor)
print( "Done")
if count >= count_threshold:
break
self.p.unlisten(cb_id)
# a more heavy-handed approach -
# remove the neighborhood and repave
def repave_neighborhood(self,c,neighborhood_size=3,scale_factor=None,nbr_nodes=None):
"""
c: The cell around which to repave
n_s: how big the neighborhood is around the cell
scale_factor: if specified, a factor to be applied to the density field
during the repaving.
nbr_nodes: if specified, exactly these nodes will be removed (with their edges and
the cells belonging to those edges). otherwise, a neighborhood will be built up around
c.
"""
print("Top of repave_neighborhood - c = %d"%c)
starting_score = self.cell_scores(array([c]))
p = self.p
if nbr_nodes is None:
if scale_factor is not None and self.use_apollo and scale_factor < 1.0:
print( "dynamically defining neighborhood based on radius of Apollonius Graph influence")
nbr_nodes = self.cell_neighborhood_apollo(c)
else:
nbr_nodes = self.cell_neighborhood(c,neighborhood_size)
# delete all non boundary edges going to these nodes
edges_to_kill = np.unique( np.concatenate( [p.pnt2edges(n) for n in nbr_nodes] ) )
# but don't remove boundary edges:
# check both that it has cells on both sides, but also that it's not an
# internal guide edge
to_remove = (p.edges[edges_to_kill,4] >= 0) & (p.edge_data[edges_to_kill,1] < 0)
edges_to_kill = edges_to_kill[ to_remove]
for e in edges_to_kill:
# print "Deleting edge e=%d"%e
p.delete_edge(e,handle_unpaved=1)
# the nodes that are not on the boundary get deleted:
for n in nbr_nodes:
# node_on_boundary includes internal_guides, so this should be okay.
if p.node_on_boundary(n):
# SLIDE nodes are reset to HINT so that we're free to resample
# the boundary
if p.node_data[n,paver.STAT] == paver.SLIDE:
# print "Setting node n=%d to HINT"%n
p.node_data[n,paver.STAT] = paver.HINT
else:
# print "Deleting node n=%d"%n
p.delete_node(n)
old_ncells = p.Ncells()
saved_density = None
if scale_factor is not None:
if not ( self.use_apollo and scale_factor<1.0):
saved_density = p.density
p.density = p.density * scale_factor
print("Repaving...")
p.pave_all(n_steps=inf) # n_steps will keep it from renumbering afterwards
if saved_density is not None:
p.density = saved_density
new_cells = np.arange(old_ncells,p.Ncells())
new_scores = self.cell_scores(new_cells)
print("Repave: %g => %g"%(starting_score,new_scores.min()))
def full(self):
self.p.verbose = 0
self.relax_neighborhoods()
self.repave_neighborhoods(neighborhood_size=2)
self.relax_neighborhoods()
self.repave_neighborhoods(neighborhood_size=2,scale_factor=0.9)
self.repave_neighborhoods(neighborhood_size=2,scale_factor=0.8)
self.repave_neighborhoods(neighborhood_size=3,scale_factor=0.8)
self.repave_neighborhoods(neighborhood_size=3,scale_factor=0.75)
self.relax_neighborhoods()
for i in range(10):
scores = self.cell_scores()
print("iteration %d, %d bad cells"%(i, (scores<0.1).sum() ))
self.p.write_complete('iter%02d.pav'%i)
self.repave_neighborhoods(neighborhood_size=2,scale_factor=0.7)
self.p.write_complete('iter%02d-repaved.pav'%i)
self.relax_neighborhoods(neighborhood_size=5)
self.stats()
def stats(self):
scores = self.cell_scores()
print("Total cells with score below 0.1: %d"%( (scores<0.1).sum() ))
def gui(self):
""" A very simple gui for hand-optimizing.
"""
g = OptimizeGui(self)
g.run()
return g
if __name__ == '__main__':
p = paver.Paving.load_complete('/home/rusty/classes/research/suntans/grids/fullbay-0610/final.pav')
p.clean_unpaved()
opter = GridOptimizer(p)
opter.stats()
opter.full()
opter.stats()
# down to 25.
## Note on using the Apollonius graph for modifying the scale field:
# The idea is that rather than temporarily scaling down the density
# field to repave a subset of the grid, insert new AG points that will
# blend the reduced scale back into the background scale.
# This field would be persistent throughout the optimization.<|fim▁end|>
|
starting_worst = self.cell_scores(cells).min()
worst = starting_worst
|
<|file_name|>characters.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
# Character ranges of letters
letters = 'a-zA-Z\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u0103\u0106\u0107\
\u010c-\u010f\u0112-\u0115\u011a-\u012d\u0131\u0141\u0142\u0147\u0148\
\u0150-\u0153\u0158-\u0161\u0164\u0165\u016e-\u0171\u017d\u017e\
\u0391-\u03a1\u03a3-\u03a9\u03b1-\u03c9\u03d1\u03d2\u03d5\u03d6\
\u03da-\u03e1\u03f0\u03f1\u03f5\u210a-\u210c\u2110-\u2113\u211b\u211c\
\u2128\u212c\u212d\u212f-\u2131\u2133-\u2138\uf6b2-\uf6b5\uf6b7\uf6b9\
\uf6ba-\uf6bc\uf6be\uf6bf\uf6c1-\uf700\uf730\uf731\uf770\uf772\uf773\
\uf776\uf779\uf77a\uf77d-\uf780\uf782-\uf78b\uf78d-\uf78f\uf790\
\uf793-\uf79a\uf79c-\uf7a2\uf7a4-\uf7bd\uf800-\uf833\ufb01\ufb02'
# Character ranges of letterlikes
letterlikes = '\u0024\u00A1\u00A2\u00A3\u00A5\u00A7\u00A9\u00AB\u00AE\
\u00B0\u00B5\u00B6\u00B8\u00BB\u00BF\u02C7\u02D8\u2013\u2014\u2020\u2021\
\u2022\u2026\u2032\u2033\u2035\u2036\u2060\u20AC\u210F\u2122\u2127\u212B\
\u21B5\u2205\u221E\u221F\u2220\u2221\u2222\u22EE\u22EF\u22F0\u22F1\u2300\
\u2318\u231A\u23B4\u23B5\u2500\u2502\u25A0\u25A1\u25AA\u25AE\u25AF\u25B2\
\u25B3\u25BC\u25BD\u25C0\u25C6\u25C7\u25CB\u25CF\u25E6\u25FB\u25FC\u2605\
\u2639\u263A\u2660\u2661\u2662\u2663\u266D\u266E\u266F\u2736\uF3A0\uF3B8\
\uF3B9\uF527\uF528\uF720\uF721\uF722\uF723\uF725\uF749\uF74A\uF74D\uF74E\
\uF74F\uF750\uF751\uF752\uF753\uF754\uF755\uF756\uF757\uF760\uF763\uF766\
\uF768\uF769\uF76A\uF76B\uF76C\uF7D4\uF800\uF801\uF802\uF803\uF804\uF805\
\uF806\uF807\uF808\uF809\uF80A\uF80B\uF80C\uF80D\uF80E\uF80F\uF810\uF811\
\uF812\uF813\uF814\uF815\uF816\uF817\uF818\uF819\uF81A\uF81B\uF81C\uF81D\
\uF81E\uF81F\uF820\uF821\uF822\uF823\uF824\uF825\uF826\uF827\uF828\uF829\
\uF82A\uF82B\uF82C\uF82D\uF82E\uF82F\uF830\uF831\uF832\uF833\uFE35\uFE36\
\uFE37\uFE38'
# All supported longname characters
named_characters = {
'AAcute': '\u00E1',
'ABar': '\u0101',
'ACup': '\u0103',
'ADoubleDot': '\u00E4',
'AE': '\u00E6',
'AGrave': '\u00E0',
'AHat': '\u00E2',
'Aleph': '\u2135',
'AliasDelimiter': '\uF764',
'AliasIndicator': '\uF768',
'AlignmentMarker': '\uF760',
'Alpha': '\u03B1',
'AltKey': '\uF7D1',
'And': '\u2227',
'Angle': '\u2220',
'Angstrom': '\u212B',
'ARing': '\u00E5',
'AscendingEllipsis': '\u22F0',
'ATilde': '\u00E3',
'AutoLeftMatch': '\uF3A8',
'AutoOperand': '\uF3AE',
'AutoPlaceholder': '\uF3A4',
'AutoRightMatch': '\uF3A9',
'AutoSpace': '\uF3AD',
'Backslash': '\u2216',
'BeamedEighthNote': '\u266B',
'BeamedSixteenthNote': '\u266C',
'Because': '\u2235',
'Bet': '\u2136',
'Beta': '\u03B2',
'BlackBishop': '\u265D',
'BlackKing': '\u265A',
'BlackKnight': '\u265E',
'BlackPawn': '\u265F',
'BlackQueen': '\u265B',
'BlackRook': '\u265C',
'Breve': '\u02D8',
'Bullet': '\u2022',
'CAcute': '\u0107',
'CapitalAAcute': '\u00C1',
'CapitalABar': '\u0100',
'CapitalACup': '\u0102',
'CapitalADoubleDot': '\u00C4',
'CapitalAE': '\u00C6',
'CapitalAGrave': '\u00C0',
'CapitalAHat': '\u00C2',
'CapitalAlpha': '\u0391',
'CapitalARing': '\u00C5',
'CapitalATilde': '\u00C3',
'CapitalBeta': '\u0392',
'CapitalCAcute': '\u0106',
'CapitalCCedilla': '\u00C7',
'CapitalCHacek': '\u010C',
'CapitalChi': '\u03A7',
'CapitalDelta': '\u0394',
'CapitalDHacek': '\u010E',
'CapitalDifferentialD': '\uF74B',
'CapitalDigamma': '\u03DC',
'CapitalEAcute': '\u00C9',
'CapitalEBar': '\u0112',
'CapitalECup': '\u0114',
'CapitalEDoubleDot': '\u00CB',
'CapitalEGrave': '\u00C8',
'CapitalEHacek': '\u011A',
'CapitalEHat': '\u00CA',
'CapitalEpsilon': '\u0395',
'CapitalEta': '\u0397',
'CapitalEth': '\u00D0',
'CapitalGamma': '\u0393',
'CapitalIAcute': '\u00CD',
'CapitalICup': '\u012C',
'CapitalIDoubleDot': '\u00CF',
'CapitalIGrave': '\u00CC',
'CapitalIHat': '\u00CE',
'CapitalIota': '\u0399',
'CapitalKappa': '\u039A',
'CapitalKoppa': '\u03DE',
'CapitalLambda': '\u039B',
'CapitalLSlash': '\u0141',
'CapitalMu': '\u039C',
'CapitalNHacek': '\u0147',
'CapitalNTilde': '\u00D1',
'CapitalNu': '\u039D',
'CapitalOAcute': '\u00D3',
'CapitalODoubleAcute': '\u0150',
'CapitalODoubleDot': '\u00D6',
'CapitalOE': '\u0152',
'CapitalOGrave': '\u00D2',
'CapitalOHat': '\u00D4',
'CapitalOmega': '\u03A9',
'CapitalOmicron': '\u039F',
'CapitalOSlash': '\u00D8',
'CapitalOTilde': '\u00D5',
'CapitalPhi': '\u03A6',
'CapitalPi': '\u03A0',
'CapitalPsi': '\u03A8',
'CapitalRHacek': '\u0158',
'CapitalRho': '\u03A1',
'CapitalSampi': '\u03E0',
'CapitalSHacek': '\u0160',
'CapitalSigma': '\u03A3',
'CapitalStigma': '\u03DA',
'CapitalTau': '\u03A4',
'CapitalTHacek': '\u0164',
'CapitalTheta': '\u0398',
'CapitalThorn': '\u00DE',
'CapitalUAcute': '\u00DA',
'CapitalUDoubleAcute': '\u0170',
'CapitalUDoubleDot': '\u00DC',
'CapitalUGrave': '\u00D9',
'CapitalUHat': '\u00DB',
'CapitalUpsilon': '\u03A5',
'CapitalURing': '\u016E',
'CapitalXi': '\u039E',
'CapitalYAcute': '\u00DD',
'CapitalZeta': '\u0396',
'CapitalZHacek': '\u017D',
'Cap': '\u2322',
'CCedilla': '\u00E7',
'Cedilla': '\u00B8',
'CenterDot': '\u00B7',
'CenterEllipsis': '\u22EF',
'Cent': '\u00A2',
'CHacek': '\u010D',
'Checkmark': '\u2713',
'Chi': '\u03C7',
'CircleDot': '\u2299',
'CircleMinus': '\u2296',
'CirclePlus': '\u2295',
'CircleTimes': '\u2297',
'ClockwiseContourIntegral': '\u2232',
'CloseCurlyDoubleQuote': '\u201D',
'CloseCurlyQuote': '\u2019',
'CloverLeaf': '\u2318',
'ClubSuit': '\u2663',
'Colon': '\u2236',
'CommandKey': '\uF76A',
'Congruent': '\u2261',
'Conjugate': '\uF3C8',
'ConjugateTranspose': '\uF3C9',
'ConstantC': '\uF7DA',
'Continuation': '\uF3B1',
'ContourIntegral': '\u222E',
'ControlKey': '\uF763',
'Coproduct': '\u2210',
'Copyright': '\u00A9',
'CounterClockwiseContourIntegral': '\u2233',
'Cross': '\uF4A0',
'CupCap': '\u224D',
'Cup': '\u2323',
'CurlyCapitalUpsilon': '\u03D2',
'CurlyEpsilon': '\u03B5',
'CurlyKappa': '\u03F0',
'CurlyPhi': '\u03C6',
'CurlyPi': '\u03D6',
'CurlyRho': '\u03F1',
'CurlyTheta': '\u03D1',
'Currency': '\u00A4',
'Dagger': '\u2020',
'Dalet': '\u2138',
'Dash': '\u2013',
'Degree': '\u00B0',
'DeleteKey': '\uF7D0',
'Del': '\u2207',
'Delta': '\u03B4',
'DescendingEllipsis': '\u22F1',
'DHacek': '\u010F',
'Diameter': '\u2300',
'Diamond': '\u22C4',
'DiamondSuit': '\u2662',
'DifferenceDelta': '\u2206',
'DifferentialD': '\uF74C',
'Digamma': '\u03DD',
'DiscreteRatio': '\uF4A4',
'DiscreteShift': '\uF4A3',
'DiscretionaryHyphen': '\u00AD',
'DiscretionaryLineSeparator': '\uF76E',
'DiscretionaryParagraphSeparator': '\uF76F',
'Divide': '\u00F7',
'DotEqual': '\u2250',
'DotlessI': '\u0131',
'DotlessJ': '\uF700',
'DottedSquare': '\uF751',
'DoubleContourIntegral': '\u222F',
'DoubleDagger': '\u2021',
'DoubledGamma': '\uF74A',
'DoubleDownArrow': '\u21D3',
'DoubledPi': '\uF749',
'DoubleLeftArrow': '\u21D0',
'DoubleLeftRightArrow': '\u21D4',
'DoubleLeftTee': '\u2AE4',
'DoubleLongLeftArrow': '\u27F8',
'DoubleLongLeftRightArrow': '\u27FA',
'DoubleLongRightArrow': '\u27F9',
'DoublePrime': '\u2033',
'DoubleRightArrow': '\u21D2',
'DoubleRightTee': '\u22A8',
'DoubleStruckA': '\uF6E6',
'DoubleStruckB': '\uF6E7',
'DoubleStruckC': '\uF6E8',
'DoubleStruckCapitalA': '\uF7A4',
'DoubleStruckCapitalB': '\uF7A5',
'DoubleStruckCapitalC': '\uF7A6',
'DoubleStruckCapitalD': '\uF7A7',
'DoubleStruckCapitalE': '\uF7A8',
'DoubleStruckCapitalF': '\uF7A9',
'DoubleStruckCapitalG': '\uF7AA',
'DoubleStruckCapitalH': '\uF7AB',
'DoubleStruckCapitalI': '\uF7AC',
'DoubleStruckCapitalJ': '\uF7AD',
'DoubleStruckCapitalK': '\uF7AE',
'DoubleStruckCapitalL': '\uF7AF',
'DoubleStruckCapitalM': '\uF7B0',
'DoubleStruckCapitalN': '\uF7B1',
'DoubleStruckCapitalO': '\uF7B2',
'DoubleStruckCapitalP': '\uF7B3',
'DoubleStruckCapitalQ': '\uF7B4',
'DoubleStruckCapitalR': '\uF7B5',
'DoubleStruckCapitalS': '\uF7B6',
'DoubleStruckCapitalT': '\uF7B7',
'DoubleStruckCapitalU': '\uF7B8',
'DoubleStruckCapitalV': '\uF7B9',
'DoubleStruckCapitalW': '\uF7BA',
'DoubleStruckCapitalX': '\uF7BB',
'DoubleStruckCapitalY': '\uF7BC',
'DoubleStruckCapitalZ': '\uF7BD',
'DoubleStruckD': '\uF6E9',
'DoubleStruckE': '\uF6EA',
'DoubleStruckEight': '\uF7E3',
'DoubleStruckF': '\uF6EB',
'DoubleStruckFive': '\uF7E0',
'DoubleStruckFour': '\uF7DF',
'DoubleStruckG': '\uF6EC',
'DoubleStruckH': '\uF6ED',
'DoubleStruckI': '\uF6EE',
'DoubleStruckJ': '\uF6EF',
'DoubleStruckK': '\uF6F0',
'DoubleStruckL': '\uF6F1',
'DoubleStruckM': '\uF6F2',
'DoubleStruckN': '\uF6F3',
'DoubleStruckNine': '\uF7E4',
'DoubleStruckO': '\uF6F4',
'DoubleStruckOne': '\uF7DC',
'DoubleStruckP': '\uF6F5',
'DoubleStruckQ': '\uF6F6',
'DoubleStruckR': '\uF6F7',
'DoubleStruckS': '\uF6F8',
'DoubleStruckSeven': '\uF7E2',
'DoubleStruckSix': '\uF7E1',
'DoubleStruckT': '\uF6F9',
'DoubleStruckThree': '\uF7DE',
'DoubleStruckTwo': '\uF7DD',
'DoubleStruckU': '\uF6FA',
'DoubleStruckV': '\uF6FB',
'DoubleStruckW': '\uF6FC',
'DoubleStruckX': '\uF6FD',
'DoubleStruckY': '\uF6FE',
'DoubleStruckZ': '\uF6FF',
'DoubleStruckZero': '\uF7DB',
'DoubleUpArrow': '\u21D1',
'DoubleUpDownArrow': '\u21D5',
'DoubleVerticalBar': '\u2225',
'DownArrowBar': '\u2913',
'DownArrow': '\u2193',
'DownArrowUpArrow': '\u21F5',
'DownBreve': '\uF755',
'DownExclamation': '\u00A1',
'DownLeftRightVector': '\u2950',
'DownLeftTeeVector': '\u295E',
'DownLeftVector': '\u21BD',
'DownLeftVectorBar': '\u2956',
'DownPointer': '\u25BE',
'DownQuestion': '\u00BF',
'DownRightTeeVector': '\u295F',
'DownRightVector': '\u21C1',
'DownRightVectorBar': '\u2957',
'DownTeeArrow': '\u21A7',
'DownTee': '\u22A4',
'EAcute': '\u00E9',
'Earth': '\u2641',
'EBar': '\u0113',
'ECup': '\u0115',
'EDoubleDot': '\u00EB',
'EGrave': '\u00E8',
'EHacek': '\u011B',
'EHat': '\u00EA',
'EighthNote': '\u266A',
'Element': '\u2208',
'Ellipsis': '\u2026',
'EmptyCircle': '\u25CB',
'EmptyDiamond': '\u25C7',
'EmptyDownTriangle': '\u25BD',
'EmptyRectangle': '\u25AF',
'EmptySet': '\u2205',
'EmptySmallCircle': '\u25E6',
'EmptySmallSquare': '\u25FB',
'EmptySquare': '\u25A1',
'EmptyUpTriangle': '\u25B3',
'EmptyVerySmallSquare': '\u25AB',
'EnterKey': '\uF7D4',
'EntityEnd': '\uF3B9',
'EntityStart': '\uF3B8',
'Epsilon': '\u03F5',
'Equal': '\uF431',
'EqualTilde': '\u2242',
'Equilibrium': '\u21CC',
'Equivalent': '\u29E6',
'ErrorIndicator': '\uF767',
'EscapeKey': '\uF769',
'Eta': '\u03B7',
'Eth': '\u00F0',
'Euro': '\u20AC',
'Exists': '\u2203',
'ExponentialE': '\uF74D',
'FiLigature': '\uFB01',
'FilledCircle': '\u25CF',
'FilledDiamond': '\u25C6',
'FilledDownTriangle': '\u25BC',
'FilledLeftTriangle': '\u25C0',
'FilledRectangle': '\u25AE',
'FilledRightTriangle': '\u25B6',
'FilledSmallCircle': '\uF750',
'FilledSmallSquare': '\u25FC',
'FilledSquare': '\u25A0',
'FilledUpTriangle': '\u25B2',
'FilledVerySmallSquare': '\u25AA',
'FinalSigma': '\u03C2',
'FirstPage': '\uF7FA',
'FivePointedStar': '\u2605',
'Flat': '\u266D',
'FlLigature': '\uFB02',
'Florin': '\u0192',
'ForAll': '\u2200',
'FormalA': '\uF800',
'FormalB': '\uF801',
'FormalC': '\uF802',
'FormalCapitalA': '\uF81A',
'FormalCapitalB': '\uF81B',
'FormalCapitalC': '\uF81C',
'FormalCapitalD': '\uF81D',
'FormalCapitalE': '\uF81E',
'FormalCapitalF': '\uF81F',
'FormalCapitalG': '\uF820',
'FormalCapitalH': '\uF821',
'FormalCapitalI': '\uF822',
'FormalCapitalJ': '\uF823',
'FormalCapitalK': '\uF824',
'FormalCapitalL': '\uF825',
'FormalCapitalM': '\uF826',
'FormalCapitalN': '\uF827',
'FormalCapitalO': '\uF828',
'FormalCapitalP': '\uF829',
'FormalCapitalQ': '\uF82A',
'FormalCapitalR': '\uF82B',
'FormalCapitalS': '\uF82C',
'FormalCapitalT': '\uF82D',
'FormalCapitalU': '\uF82E',
'FormalCapitalV': '\uF82F',
'FormalCapitalW': '\uF830',
'FormalCapitalX': '\uF831',
'FormalCapitalY': '\uF832',
'FormalCapitalZ': '\uF833',
'FormalD': '\uF803',
'FormalE': '\uF804',
'FormalF': '\uF805',
'FormalG': '\uF806',
'FormalH': '\uF807',
'FormalI': '\uF808',
'FormalJ': '\uF809',
'FormalK': '\uF80A',
'FormalL': '\uF80B',
'FormalM': '\uF80C',
'FormalN': '\uF80D',
'FormalO': '\uF80E',
'FormalP': '\uF80F',
'FormalQ': '\uF810',
'FormalR': '\uF811',
'FormalS': '\uF812',
'FormalT': '\uF813',
'FormalU': '\uF814',
'FormalV': '\uF815',
'FormalW': '\uF816',
'FormalX': '\uF817',
'FormalY': '\uF818',
'FormalZ': '\uF819',
'FreakedSmiley': '\uF721',
'Function': '\uF4A1',
'Gamma': '\u03B3',
'Gimel': '\u2137',
'GothicA': '\uF6CC',
'GothicB': '\uF6CD',
'GothicC': '\uF6CE',
'GothicCapitalA': '\uF78A',
'GothicCapitalB': '\uF78B',
'GothicCapitalC': '\u212D',
'GothicCapitalD': '\uF78D',
'GothicCapitalE': '\uF78E',
'GothicCapitalF': '\uF78F',
'GothicCapitalG': '\uF790',
'GothicCapitalH': '\u210C',
'GothicCapitalI': '\u2111',
'GothicCapitalJ': '\uF793',
'GothicCapitalK': '\uF794',
'GothicCapitalL': '\uF795',
'GothicCapitalM': '\uF796',
'GothicCapitalN': '\uF797',
'GothicCapitalO': '\uF798',
'GothicCapitalP': '\uF799',
'GothicCapitalQ': '\uF79A',
'GothicCapitalR': '\u211C',
'GothicCapitalS': '\uF79C',
'GothicCapitalT': '\uF79D',
'GothicCapitalU': '\uF79E',
'GothicCapitalV': '\uF79F',
'GothicCapitalW': '\uF7A0',
'GothicCapitalX': '\uF7A1',
'GothicCapitalY': '\uF7A2',
'GothicCapitalZ': '\u2128',
'GothicD': '\uF6CF',
'GothicE': '\uF6D0',
'GothicEight': '\uF7ED',
'GothicF': '\uF6D1',
'GothicFive': '\uF7EA',
'GothicFour': '\uF7E9',
'GothicG': '\uF6D2',
'GothicH': '\uF6D3',
'GothicI': '\uF6D4',
'GothicJ': '\uF6D5',
'GothicK': '\uF6D6',
'GothicL': '\uF6D7',
'GothicM': '\uF6D8',
'GothicN': '\uF6D9',
'GothicNine': '\uF7EF',
'GothicO': '\uF6DA',
'GothicOne': '\uF7E6',
'GothicP': '\uF6DB',
'GothicQ': '\uF6DC',
'GothicR': '\uF6DD',
'GothicS': '\uF6DE',
'GothicSeven': '\uF7EC',
'GothicSix': '\uF7EB',
'GothicT': '\uF6DF',
'GothicThree': '\uF7E8',
'GothicTwo': '\uF7E7',
'GothicU': '\uF6E0',
'GothicV': '\uF6E1',
'GothicW': '\uF6E2',
'GothicX': '\uF6E3',
'GothicY': '\uF6E4',
'GothicZ': '\uF6E5',
'GothicZero': '\uF7E5',
'GrayCircle': '\uF753',
'GraySquare': '\uF752',
'GreaterEqualLess': '\u22DB',
'GreaterEqual': '\u2265',
'GreaterFullEqual': '\u2267',
'GreaterGreater': '\u226B',
'GreaterLess': '\u2277',
'GreaterSlantEqual': '\u2A7E',
'GreaterTilde': '\u2273',
'Hacek': '\u02C7',
'HappySmiley': '\u263A',
'HBar': '\u210F',
'HeartSuit': '\u2661',
'HermitianConjugate': '\uF3CE',
'HorizontalLine': '\u2500',
'HumpDownHump': '\u224E',
'HumpEqual': '\u224F',
'Hyphen': '\u2010',
'IAcute': '\u00ED',
'ICup': '\u012D',
'IDoubleDot': '\u00EF',
'IGrave': '\u00EC',
'IHat': '\u00EE',
'ImaginaryI': '\uF74E',
'ImaginaryJ': '\uF74F',
'ImplicitPlus': '\uF39E',
'Implies': '\uF523',
'Infinity': '\u221E',
'Integral': '\u222B',
'Intersection': '\u22C2',
'InvisibleApplication': '\uF76D',
'InvisibleComma': '\uF765',
'InvisiblePostfixScriptBase': '\uF3B4',
'InvisiblePrefixScriptBase': '\uF3B3',
'InvisibleSpace': '\uF360',
'InvisibleTimes': '\u2062',
'Iota': '\u03B9',
'Jupiter': '\u2643',
'Kappa': '\u03BA',
'KernelIcon': '\uF756',
'Koppa': '\u03DF',
'Lambda': '\u03BB',
'LastPage': '\uF7FB',
'LeftAngleBracket': '\u2329',
'LeftArrowBar': '\u21E4',
'LeftArrow': '\u2190',
'LeftArrowRightArrow': '\u21C6',
'LeftBracketingBar': '\uF603',
'LeftCeiling': '\u2308',
'LeftDoubleBracket': '\u301A',
'LeftDoubleBracketingBar': '\uF605',
'LeftDownTeeVector': '\u2961',
'LeftDownVectorBar': '\u2959',
'LeftDownVector': '\u21C3',
'LeftFloor': '\u230A',
'LeftGuillemet': '\u00AB',
'LeftModified': '\uF76B',
'LeftPointer': '\u25C2',
'LeftRightArrow': '\u2194',
'LeftRightVector': '\u294E',
'LeftSkeleton': '\uF761',
'LeftTee': '\u22A3',
'LeftTeeArrow': '\u21A4',
'LeftTeeVector': '\u295A',
'LeftTriangle': '\u22B2',
'LeftTriangleBar': '\u29CF',
'LeftTriangleEqual': '\u22B4',
'LeftUpDownVector': '\u2951',
'LeftUpTeeVector': '\u2960',
'LeftUpVector': '\u21BF',
'LeftUpVectorBar': '\u2958',
'LeftVector': '\u21BC',
'LeftVectorBar': '\u2952',
'LessEqual': '\u2264',
'LessEqualGreater': '\u22DA',
'LessFullEqual': '\u2266',
'LessGreater': '\u2276',
'LessLess': '\u226A',
'LessSlantEqual': '\u2A7D',
'LessTilde': '\u2272',
'LetterSpace': '\uF754',
'LightBulb': '\uF723',
'LongDash': '\u2014',
'LongEqual': '\uF7D9',
'LongLeftArrow': '\u27F5',
'LongLeftRightArrow': '\u27F7',
'LongRightArrow': '\u27F6',
'LowerLeftArrow': '\u2199',
'LowerRightArrow': '\u2198',
'LSlash': '\u0142',
'Mars': '\u2642',
'MathematicaIcon': '\uF757',
'MeasuredAngle': '\u2221',
'MediumSpace': '\u205F',
'Mercury': '\u263F',
'Mho': '\u2127',
'Micro': '\u00B5',
'Minus': '\u2212',
'MinusPlus': '\u2213',
'Mu': '\u03BC',
'Nand': '\u22BC',
'Natural': '\u266E',
'NegativeMediumSpace': '\uF383',
'NegativeThickSpace': '\uF384',
'NegativeThinSpace': '\uF382',
'NegativeVeryThinSpace': '\uF380',
'Neptune': '\u2646',
'NestedGreaterGreater': '\u2AA2',
'NestedLessLess': '\u2AA1',
'NeutralSmiley': '\uF722',
'NHacek': '\u0148',
'NoBreak': '\u2060',
'NonBreakingSpace': '\u00A0',
'Nor': '\u22BD',
'NotCongruent': '\u2262',
'NotCupCap': '\u226D',
'NotDoubleVerticalBar': '\u2226',
'NotElement': '\u2209',
'NotEqual': '\u2260',
'NotEqualTilde': '\uF400',
'NotExists': '\u2204',
'NotGreater': '\u226F',
'NotGreaterEqual': '\u2271',
'NotGreaterFullEqual': '\u2269',
'NotGreaterGreater': '\uF427',
'NotGreaterLess': '\u2279',
'NotGreaterSlantEqual': '\uF429',
'NotGreaterTilde': '\u2275',
'NotHumpDownHump': '\uF402',
'NotHumpEqual': '\uF401',
'NotLeftTriangle': '\u22EA',
'NotLeftTriangleBar': '\uF412',
'NotLeftTriangleEqual': '\u22EC',
'NotLessEqual': '\u2270',
'NotLessFullEqual': '\u2268',
'NotLessGreater': '\u2278',
'NotLess': '\u226E',
'NotLessLess': '\uF422',
'NotLessSlantEqual': '\uF424',
'NotLessTilde': '\u2274',
'Not': '\u00AC',
'NotNestedGreaterGreater': '\uF428',
'NotNestedLessLess': '\uF423',
'NotPrecedes': '\u2280',
'NotPrecedesEqual': '\uF42B',
'NotPrecedesSlantEqual': '\u22E0',
'NotPrecedesTilde': '\u22E8',
'NotReverseElement': '\u220C',
'NotRightTriangle': '\u22EB',
'NotRightTriangleBar': '\uF413',
'NotRightTriangleEqual': '\u22ED',
'NotSquareSubset': '\uF42E',
'NotSquareSubsetEqual': '\u22E2',
'NotSquareSuperset': '\uF42F',
'NotSquareSupersetEqual': '\u22E3',
'NotSubset': '\u2284',
'NotSubsetEqual': '\u2288',
'NotSucceeds': '\u2281',
'NotSucceedsEqual': '\uF42D',
'NotSucceedsSlantEqual': '\u22E1',
'NotSucceedsTilde': '\u22E9',
'NotSuperset': '\u2285',
'NotSupersetEqual': '\u2289',
'NotTilde': '\u2241',
'NotTildeEqual': '\u2244',
'NotTildeFullEqual': '\u2247',
'NotTildeTilde': '\u2249',
'NotVerticalBar': '\u2224',
'NTilde': '\u00F1',
'Nu': '\u03BD',
'Null': '\uF3A0',
'NumberSign': '\uF724',
'OAcute': '\u00F3',
'ODoubleAcute': '\u0151',
'ODoubleDot': '\u00F6',
'OE': '\u0153',
'OGrave': '\u00F2',
'OHat': '\u00F4',
'Omega': '\u03C9',
'Omicron': '\u03BF',
'OpenCurlyDoubleQuote': '\u201C',
'OpenCurlyQuote': '\u2018',
'OptionKey': '\uF7D2',
'Or': '\u2228',
'OSlash': '\u00F8',
'OTilde': '\u00F5',
'OverBrace': '\uFE37',
'OverBracket': '\u23B4',
'OverParenthesis': '\uFE35',
'Paragraph': '\u00B6',
'PartialD': '\u2202',
'Phi': '\u03D5',
'Pi': '\u03C0',
'Piecewise': '\uF361',
'Placeholder': '\uF528',
'PlusMinus': '\u00B1',
'Pluto': '\u2647',
'Precedes': '\u227A',
'PrecedesEqual': '\u2AAF',
'PrecedesSlantEqual': '\u227C',
'PrecedesTilde': '\u227E',
'Prime': '\u2032',
'Product': '\u220F',
'Proportion': '\u2237',
'Proportional': '\u221D',
'Psi': '\u03C8',
'QuarterNote': '\u2669',
'RawAmpersand': '\u0026',
'RawAt': '\u0040',
'RawBackquote': '\u0060',
'RawBackslash': '\u005C',
'RawColon': '\u003A',
'RawComma': '\u002C',
'RawDash': '\u002D',
'RawDollar': '\u0024',
'RawDot': '\u002E',
'RawDoubleQuote': '\u0022',
'RawEqual': '\u003D',
'RawEscape': '\u001B',
'RawExclamation': '\u0021',
'RawGreater': '\u003E',
'RawLeftBrace': '\u007B',
'RawLeftBracket': '\u005B',
'RawLeftParenthesis': '\u0028',
'RawLess': '\u003C',
'RawNumberSign': '\u0023',
'RawPercent': '\u0025',
'RawPlus': '\u002B',
'RawQuestion': '\u003F',
'RawQuote': '\u0027',
'RawRightBrace': '\u007D',
'RawRightBracket': '\u005D',
'RawRightParenthesis': '\u0029',
'RawSemicolon': '\u003B',
'RawSlash': '\u002F',
'RawSpace': '\u0020',
'RawStar': '\u002A',
'RawTab': '\u0009',
'RawTilde': '\u007E',
'RawUnderscore': '\u005F',
'RawVerticalBar': '\u007C',
'RawWedge': '\u005E',
'RegisteredTrademark': '\u00AE',
'ReturnIndicator': '\u21B5',
'ReturnKey': '\uF766',
'ReverseDoublePrime': '\u2036',
'ReverseElement': '\u220B',
'ReverseEquilibrium': '\u21CB',
'ReversePrime': '\u2035',
'ReverseUpEquilibrium': '\u296F',
'RHacek': '\u0159',
'Rho': '\u03C1',
'RightAngle': '\u221F',
'RightAngleBracket': '\u232A',
'RightArrow': '\u2192',
'RightArrowBar': '\u21E5',
'RightArrowLeftArrow': '\u21C4',
'RightBracketingBar': '\uF604',
'RightCeiling': '\u2309',
'RightDoubleBracket': '\u301B',
'RightDoubleBracketingBar': '\uF606',
'RightDownTeeVector': '\u295D',
'RightDownVector': '\u21C2',
'RightDownVectorBar': '\u2955',
'RightFloor': '\u230B',
'RightGuillemet': '\u00BB',
'RightModified': '\uF76C',
'RightPointer': '\u25B8',
'RightSkeleton': '\uF762',
'RightTee': '\u22A2',
'RightTeeArrow': '\u21A6',
'RightTeeVector': '\u295B',
'RightTriangle': '\u22B3',
'RightTriangleBar': '\u29D0',
'RightTriangleEqual': '\u22B5',
'RightUpDownVector': '\u294F',
'RightUpTeeVector': '\u295C',
'RightUpVector': '\u21BE',
'RightUpVectorBar': '\u2954',
'RightVector': '\u21C0',
'RightVectorBar': '\u2953',
'RoundImplies': '\u2970',
'RoundSpaceIndicator': '\uF3B2',
'Rule': '\uF522',
'RuleDelayed': '\uF51F',
'SadSmiley': '\u2639',
'Sampi': '\u03E0',
'Saturn': '\u2644',
'ScriptA': '\uF6B2',
'ScriptB': '\uF6B3',
'ScriptC': '\uF6B4',
'ScriptCapitalA': '\uF770',
'ScriptCapitalB': '\u212C',
'ScriptCapitalC': '\uF772',
'ScriptCapitalD': '\uF773',
'ScriptCapitalE': '\u2130',
'ScriptCapitalF': '\u2131',
'ScriptCapitalG': '\uF776',
'ScriptCapitalH': '\u210B',
'ScriptCapitalI': '\u2110',
'ScriptCapitalJ': '\uF779',
'ScriptCapitalK': '\uF77A',
'ScriptCapitalL': '\u2112',
'ScriptCapitalM': '\u2133',
'ScriptCapitalN': '\uF77D',
'ScriptCapitalO': '\uF77E',
'ScriptCapitalP': '\u2118',
'ScriptCapitalQ': '\uF780',
'ScriptCapitalR': '\u211B',
'ScriptCapitalS': '\uF782',
'ScriptCapitalT': '\uF783',
'ScriptCapitalU': '\uF784',
'ScriptCapitalV': '\uF785',
'ScriptCapitalW': '\uF786',
'ScriptCapitalX': '\uF787',
'ScriptCapitalY': '\uF788',
'ScriptCapitalZ': '\uF789',
'ScriptD': '\uF6B5',
'ScriptDotlessI': '\uF730',
'ScriptDotlessJ': '\uF731',
'ScriptE': '\u212F',
'ScriptEight': '\uF7F8',
'ScriptF': '\uF6B7',
'ScriptFive': '\uF7F5',
'ScriptFour': '\uF7F4',
'ScriptG': '\u210A',
'ScriptH': '\uF6B9',
'ScriptI': '\uF6BA',
'ScriptJ': '\uF6BB',
'ScriptK': '\uF6BC',
'ScriptL': '\u2113',
'ScriptM': '\uF6BE',
'ScriptN': '\uF6BF',
'ScriptNine': '\uF7F9',
'ScriptO': '\u2134',
'ScriptOne': '\uF7F1',
'ScriptP': '\uF6C1',
'ScriptQ': '\uF6C2',
'ScriptR': '\uF6C3',
'ScriptS': '\uF6C4',
'ScriptSeven': '\uF7F7',
'ScriptSix': '\uF7F6',
'ScriptT': '\uF6C5',
'ScriptThree': '\uF7F3',
'ScriptTwo': '\uF7F2',
'ScriptU': '\uF6C6',
'ScriptV': '\uF6C7',
'ScriptW': '\uF6C8',
'ScriptX': '\uF6C9',
'ScriptY': '\uF6CA',
'ScriptZ': '\uF6CB',
'ScriptZero': '\uF7F0',
'Section': '\u00A7',
'SelectionPlaceholder': '\uF527',
'SHacek': '\u0161',
'Sharp': '\u266F',
'ShortLeftArrow': '\uF526',
'ShortRightArrow': '\uF525',
'Sigma': '\u03C3',
'SixPointedStar': '\u2736',
'SkeletonIndicator': '\u2043',
'SmallCircle': '\u2218',
'SpaceIndicator': '\u2423',
'SpaceKey': '\uF7BF',
'SpadeSuit': '\u2660',
'SpanFromAbove': '\uF3BB',
'SpanFromBoth': '\uF3BC',
'SpanFromLeft': '\uF3BA',
'SphericalAngle': '\u2222',
'Sqrt': '\u221A',
'Square': '\uF520',
'SquareIntersection': '\u2293',
'SquareSubset': '\u228F',
'SquareSubsetEqual': '\u2291',
'SquareSuperset': '\u2290',
'SquareSupersetEqual': '\u2292',
'SquareUnion': '\u2294',
'Star': '\u22C6',
'Sterling': '\u00A3',
'Stigma': '\u03DB',
'Subset': '\u2282',
'SubsetEqual': '\u2286',
'Succeeds': '\u227B',
'SucceedsEqual': '\u2AB0',
'SucceedsSlantEqual': '\u227D',
'SucceedsTilde': '\u227F',
'SuchThat': '\u220D',
'Sum': '\u2211',
'Superset': '\u2283',
'SupersetEqual': '\u2287',
'SystemEnterKey': '\uF75F',
'SZ': '\u00DF',
'TabKey': '\uF7BE',
'Tau': '\u03C4',
'THacek': '\u0165',
'Therefore': '\u2234',
'Theta': '\u03B8',
'ThickSpace': '\u2005',
'ThinSpace': '\u2009',
'Thorn': '\u00FE',
'Tilde': '\u223C',
'TildeEqual': '\u2243',
'TildeFullEqual': '\u2245',
'TildeTilde': '\u2248',
'Times': '\u00D7',
'Trademark': '\u2122',
'Transpose': '\uF3C7',
'UAcute': '\u00FA',
'UDoubleAcute': '\u0171',
'UDoubleDot': '\u00FC',
'UGrave': '\u00F9',
'UHat': '\u00FB',
'UnderBrace': '\uFE38',
'UnderBracket': '\u23B5',
'UnderParenthesis': '\uFE36',
'Union': '\u22C3',
'UnionPlus': '\u228E',
'UpArrow': '\u2191',
'UpArrowBar': '\u2912',
'UpArrowDownArrow': '\u21C5',
'UpDownArrow': '\u2195',
'UpEquilibrium': '\u296E',
'UpperLeftArrow': '\u2196',
'UpperRightArrow': '\u2197',
'UpPointer': '\u25B4',
'Upsilon': '\u03C5',
'UpTee': '\u22A5',
'UpTeeArrow': '\u21A5',
'Uranus': '\u2645',
'URing': '\u016F',
'Vee': '\u22C1',
'Venus': '\u2640',
'VerticalBar': '\u2223',
'VerticalEllipsis': '\u22EE',
'VerticalLine': '\u2502',
'VerticalSeparator': '\uF432',
'VerticalTilde': '\u2240',
'VeryThinSpace': '\u200A',
'WarningSign': '\uF725',
'WatchIcon': '\u231A',
'Wedge': '\u22C0',
'WeierstrassP': '\u2118',
'WhiteBishop': '\u2657',
'WhiteKing': '\u2654',
'WhiteKnight': '\u2658',
'WhitePawn': '\u2659',
'WhiteQueen': '\u2655',
'WhiteRook': '\u2656',
'Wolf': '\uF720',
'Xi': '\u03BE',
'Xnor': '\uF4A2',
'Xor': '\u22BB',
'YAcute': '\u00FD',
'YDoubleDot': '\u00FF',
'Yen': '\u00A5',
'Zeta': '\u03B6',
'ZHacek': '\u017E',
}
aliased_characters = {
"a'": '\u00E1',
'a-': '\u0101',
'au': '\u0103',
'a"': '\u00E4',
'ae': '\u00E6',
'a`': '\u00E0',
'a^': '\u00E2',
'al': '\u2135',
'esc': '\uF768',
'am': '\uF760',
'a': '\u03B1',
'alpha': '\u03B1',
'alt': '\uF7D1',
'&&': '\u2227',
'and': '\u2227',
'Ang': '\u212B',
'ao': '\u00E5',
'a~': '\u00E3',
'\\': '\u2216',
'be': '\u2136',
'b': '\u03B2',
'beta': '\u03B2',
'bv': '\u02D8',
'bu': '\u2022',
"c'": '\u0107',
"A'": '\u00C1',
'A-': '\u0100',
'Au': '\u0102',
'A"': '\u00C4',
'AE': '\u00C6',
'A`': '\u00C0',
'A^': '\u00C2',
'A': '\u0391',
'Alpha': '\u0391',
'Ao': '\u00C5',
'A~': '\u00C3',
'B': '\u0392',
'Beta': '\u0392',
"C'": '\u0106',
'C,': '\u00C7',
'Cv': '\u010C',
'Ch': '\u03A7',
'Chi': '\u03A7',
'C': '\u03A7',
'D': '\u0394',
'Delta': '\u0394',
'Dv': '\u010E',
'DD': '\uF74B',
'Di': '\u03DC',
'Digamma': '\u03DC',
"E'": '\u00C9',
'E-': '\u0112',
'Eu': '\u0114',
'E"': '\u00CB',
'E`': '\u00C8',
'Ev': '\u011A',
'E^': '\u00CA',
'E': '\u0395',
'Epsilon': '\u0395',
'Et': '\u0397',
'Eta': '\u0397',
'H': '\u0397',
'D-': '\u00D0',
'G': '\u0393',
'Gamma': '\u0393',
"I'": '\u00CD',
'Iu': '\u012C',
'I"': '\u00CF',
'I`': '\u00CC',
'I^': '\u00CE',
'I': '\u0399',
'Iota': '\u0399',
'K': '\u039A',
'Kappa': '\u039A',
'Ko': '\u03DE',
'Koppa': '\u03DE',
'L': '\u039B',
'Lambda': '\u039B',
'L/': '\u0141',
'M': '\u039C',
'Mu': '\u039C',
'Nv': '\u0147',
'N~': '\u00D1',
'N': '\u039D',
'Nu': '\u039D',
"O'": '\u00D3',
"O''": '\u0150',
'O"': '\u00D6',
'OE': '\u0152',
'O`': '\u00D2',
'O^': '\u00D4',
'O': '\u03A9',
'Omega': '\u03A9',
'W': '\u03A9',
'Om': '\u039F',
'Omicron': '\u039F',
'O/': '\u00D8',
'O~': '\u00D5',
'Ph': '\u03A6',
'Phi': '\u03A6',
'F': '\u03A6',
'P': '\u03A0',
'Pi': '\u03A0',
'Ps': '\u03A8',
'Psi': '\u03A8',
'Y': '\u03A8',
'Rv': '\u0158',
'R': '\u03A1',
'Rho': '\u03A1',
'Sa': '\u03E0',
'Sampi': '\u03E0',
'Sv': '\u0160',
'S': '\u03A3',
'Sigma': '\u03A3',
'T': '\u03A4',
'Tau': '\u03A4',
'Tv': '\u0164',
'Th': '\u0398',
'Theta': '\u0398',
'Q': '\u0398',
'Thn': '\u00DE',
"U'": '\u00DA',
"U''": '\u0170',
'U"': '\u00DC',
'U`': '\u00D9',
'U^': '\u00DB',
'U': '\u03A5',
'Upsilon': '\u03A5',
'Uo': '\u016E',
'X': '\u039E',
'Xi': '\u039E',
"Y'": '\u00DD',
'Z': '\u0396',
'Zeta': '\u0396',
'Zv': '\u017D',
'c,': '\u00E7',
'cd': '\u00B8',
'.': '\u00B7',
'cent': '\u00A2',
'cv': '\u010D',
'ch': '\u03C7',
'chi': '\u03C7',
'c': '\u03C7',
'c.': '\u2299',
'c-': '\u2296',
'c+': '\u2295',
'c*': '\u2297',
'ccint': '\u2232',
'cl': '\u2318',
':': '\u2236',
'cmd': '\uF76A',
'===': '\u2261',
'co': '\uF3C8',
'conj': '\uF3C8',
'ct': '\uF3C9',
'cont': '\uF3B1',
'cint': '\u222E',
'ctrl': '\uF763',
'coprod': '\u2210',
'cccint': '\u2233',
'cross': '\uF4A0',
'cU': '\u03D2',
'cUpsilon': '\u03D2',
'ce': '\u03B5',
'cepsilon': '\u03B5',
'ck': '\u03F0',
'ckappa': '\u03F0',
'j': '\u03C6',
'cph': '\u03C6',
'cphi': '\u03C6',
'cp': '\u03D6',
'cpi': '\u03D6',
'cr': '\u03F1',
'crho': '\u03F1',
'cq': '\u03D1',
'cth': '\u03D1',
'ctheta': '\u03D1',
'dg': '\u2020',
'da': '\u2138',
'-': '\u2013',
'deg': '\u00B0',
' del': '\uF7D0',
'del': '\u2207',
'd': '\u03B4',
'delta': '\u03B4',
'dv': '\u010F',
'dia': '\u22C4',
'diffd': '\u2206',
'dd': '\uF74C',
'di': '\u03DD',
'digamma': '\u03DD',
'dratio': '\uF4A4',
'shift': '\uF4A3',
'dhy': '\u00AD',
'dlsep': '\uF76E',
'dpsep': '\uF76F',
'div': '\u00F7',
'.=': '\u2250',
'ddg': '\u2021',
'gg': '\uF74A',
'pp': '\uF749',
' <=': '\u21D0',
'<=>': '\u21D4',
'<==': '\u27F8',
'<==>': '\u27FA',
'==>': '\u27F9',
"''": '\u2033',
' =>': '\u21D2',
'dsa': '\uF6E6',
'dsb': '\uF6E7',
'dsc': '\uF6E8',
'dsA': '\uF7A4',
'dsB': '\uF7A5',
'dsC': '\uF7A6',
'dsD': '\uF7A7',
'dsE': '\uF7A8',
'dsF': '\uF7A9',
'dsG': '\uF7AA',
'dsH': '\uF7AB',
'dsI': '\uF7AC',
'dsJ': '\uF7AD',
'dsK': '\uF7AE',
'dsL': '\uF7AF',
'dsM': '\uF7B0',
'dsN': '\uF7B1',
'dsO': '\uF7B2',
'dsP': '\uF7B3',
'dsQ': '\uF7B4',
'dsR': '\uF7B5',
'dsS': '\uF7B6',
'dsT': '\uF7B7',
'dsU': '\uF7B8',
'dsV': '\uF7B9',
'dsW': '\uF7BA',
'dsX': '\uF7BB',
'dsY': '\uF7BC',
'dsZ': '\uF7BD',
'dsd': '\uF6E9',
'dse': '\uF6EA',
'ds8': '\uF7E3',
'dsf': '\uF6EB',
'ds5': '\uF7E0',
'ds4': '\uF7DF',
'dsg': '\uF6EC',
'dsh': '\uF6ED',
'dsi': '\uF6EE',
'dsj': '\uF6EF',
'dsk': '\uF6F0',
'dsl': '\uF6F1',
'dsm': '\uF6F2',
'dsn': '\uF6F3',
'ds9': '\uF7E4',
'dso': '\uF6F4',
'ds1': '\uF7DC',
'dsp': '\uF6F5',
'dsq': '\uF6F6',
'dsr': '\uF6F7',
'dss': '\uF6F8',
'ds7': '\uF7E2',
'ds6': '\uF7E1',
'dst': '\uF6F9',
'ds3': '\uF7DE',
'ds2': '\uF7DD',
'dsu': '\uF6FA',
'dsv': '\uF6FB',
'dsw': '\uF6FC',
'dsx': '\uF6FD',
'dsy': '\uF6FE',
'dsz': '\uF6FF',
'ds0': '\uF7DB',
' ||': '\u2225',
'dbv': '\uF755',
'd!': '\u00A1',
'd?': '\u00BF',
'dT': '\u22A4',
"e'": '\u00E9',
'e-': '\u0113',
'eu': '\u0115',
'e"': '\u00EB',
'e`': '\u00E8',
'ev': '\u011B',
'e^': '\u00EA',
'el': '\u2208',
'elem': '\u2208',
'...': '\u2026',
'eci': '\u25CB',
'es': '\u2205',
'esci': '\u25E6',
'essq': '\u25FB',
'esq': '\u25A1',
'ent': '\uF7D4',
'e': '\u03F5',
'epsilon': '\u03F5',
'==': '\uF431',
'=~': '\u2242',
'equi': '\u21CC',
'equiv': '\u29E6',
' esc': '\uF769',
'et': '\u03B7',
'eta': '\u03B7',
'h': '\u03B7',
'd-': '\u00F0',
'ex': '\u2203',
'ee': '\uF74D',
'fci': '\u25CF',
'fsci': '\uF750',
'fssq': '\u25FC',
'fsq': '\u25A0',
'fvssq': '\u25AA',
'fs': '\u03C2',
'*5': '\u2605',
'fa': '\u2200',
'$a': '\uF800',
'$b': '\uF801',
'$c': '\uF802',
'$A': '\uF81A',
'$B': '\uF81B',
'$C': '\uF81C',
'$D': '\uF81D',
'$E': '\uF81E',
'$F': '\uF81F',
'$G': '\uF820',
'$H': '\uF821',
'$I': '\uF822',
'$J': '\uF823',
'$K': '\uF824',
'$L': '\uF825',
'$M': '\uF826',
'$N': '\uF827',
'$O': '\uF828',
'$P': '\uF829',
'$Q': '\uF82A',
'$R': '\uF82B',
'$S': '\uF82C',
'$T': '\uF82D',
'$U': '\uF82E',
'$V': '\uF82F',
'$W': '\uF830',
'$X': '\uF831',
'$Y': '\uF832',
'$Z': '\uF833',
'$d': '\uF803',
'$e': '\uF804',
'$f': '\uF805',
'$g': '\uF806',
'$h': '\uF807',
'$i': '\uF808',
'$j': '\uF809',
'$k': '\uF80A',
'$l': '\uF80B',
'$m': '\uF80C',
'$n': '\uF80D',
'$o': '\uF80E',
'$p': '\uF80F',
'$q': '\uF810',
'$r': '\uF811',
'$s': '\uF812',
'$t': '\uF813',
'$u': '\uF814',
'$v': '\uF815',
'$w': '\uF816',
'$x': '\uF817',
'$y': '\uF818',
'$z': '\uF819',
':-@': '\uF721',
'fn': '\uF4A1',
'g': '\u03B3',
'gamma': '\u03B3',
'gi': '\u2137',
'goa': '\uF6CC',
'gob': '\uF6CD',
'goc': '\uF6CE',
'goA': '\uF78A',
'goB': '\uF78B',
'goC': '\u212D',
'goD': '\uF78D',
'goE': '\uF78E',
'goF': '\uF78F',
'goG': '\uF790',
'goH': '\u210C',
'goI': '\u2111',
'goJ': '\uF793',
'goK': '\uF794',
'goL': '\uF795',
'goM': '\uF796',
'goN': '\uF797',<|fim▁hole|> 'goS': '\uF79C',
'goT': '\uF79D',
'goU': '\uF79E',
'goV': '\uF79F',
'goW': '\uF7A0',
'goX': '\uF7A1',
'goY': '\uF7A2',
'goZ': '\u2128',
'god': '\uF6CF',
'goe': '\uF6D0',
'go8': '\uF7ED',
'gof': '\uF6D1',
'go5': '\uF7EA',
'go4': '\uF7E9',
'gog': '\uF6D2',
'goh': '\uF6D3',
'goi': '\uF6D4',
'goj': '\uF6D5',
'gok': '\uF6D6',
'gol': '\uF6D7',
'gom': '\uF6D8',
'gon': '\uF6D9',
'go9': '\uF7EF',
'goo': '\uF6DA',
'go1': '\uF7E6',
'gop': '\uF6DB',
'goq': '\uF6DC',
'gor': '\uF6DD',
'gos': '\uF6DE',
'go7': '\uF7EC',
'go6': '\uF7EB',
'got': '\uF6DF',
'go3': '\uF7E8',
'go2': '\uF7E7',
'gou': '\uF6E0',
'gov': '\uF6E1',
'gow': '\uF6E2',
'gox': '\uF6E3',
'goy': '\uF6E4',
'goz': '\uF6E5',
'go0': '\uF7E5',
'gci': '\uF753',
'gsq': '\uF752',
'>=': '\u2265',
'>/': '\u2A7E',
'>~': '\u2273',
'hck': '\u02C7',
':)': '\u263A',
':-)': '\u263A',
'hb': '\u210F',
'hc': '\uF3CE',
'hline': '\u2500',
'h=': '\u224F',
"i'": '\u00ED',
'iu': '\u012D',
'i"': '\u00EF',
'i`': '\u00EC',
'i^': '\u00EE',
'ii': '\uF74E',
'jj': '\uF74F',
'+': '\uF39E',
'=>': '\uF523',
'inf': '\u221E',
'int': '\u222B',
'inter': '\u22C2',
'@': '\uF76D',
',': '\uF765',
'is': '\uF360',
'i': '\u03B9',
'iota': '\u03B9',
'k': '\u03BA',
'kappa': '\u03BA',
'ko': '\u03DF',
'koppa': '\u03DF',
'l': '\u03BB',
'lambda': '\u03BB',
'<': '\u2329',
'<-': '\u2190',
'l|': '\uF603',
'lc': '\u2308',
'[[': '\u301A',
'l||': '\uF605',
'lf': '\u230A',
'g<<': '\u00AB',
'[': '\uF76B',
'<->': '\u2194',
'lT': '\u22A3',
'<=': '\u2264',
'</': '\u2A7D',
'<~': '\u2272',
'_': '\uF754',
'ls': '\uF754',
'--': '\u2014',
'<--': '\u27F5',
'<-->': '\u27F7',
'-->': '\u27F6',
'l/': '\u0142',
'math': '\uF757',
' ': '\u205F',
'mho': '\u2127',
'mi': '\u00B5',
'-+': '\u2213',
'm': '\u03BC',
'mu': '\u03BC',
'nand': '\u22BC',
'- ': '\uF383',
'- ': '\uF384',
'- ': '\uF382',
'- ': '\uF380',
':-|': '\uF722',
'nv': '\u0148',
'nb': '\u2060',
'nbs': '\u00A0',
'nor': '\u22BD',
'!===': '\u2262',
'!||': '\u2226',
'!el': '\u2209',
'!elem': '\u2209',
'!=': '\u2260',
'!=~': '\uF400',
'!ex': '\u2204',
'!>': '\u226F',
'!>=': '\u2271',
'!>/': '\uF429',
'!>~': '\u2275',
'!h=': '\uF401',
'!<=': '\u2270',
'!<': '\u226E',
'!</': '\uF424',
'!<~': '\u2274',
'!': '\u00AC',
'not': '\u00AC',
'!mem': '\u220C',
'!sub': '\u2284',
'!sub=': '\u2288',
'!sup': '\u2285',
'!sup=': '\u2289',
'!~': '\u2241',
'!~=': '\u2244',
'!~==': '\u2247',
'!~~': '\u2249',
'!|': '\u2224',
'n~': '\u00F1',
'n': '\u03BD',
'nu': '\u03BD',
'null': '\uF3A0',
"o'": '\u00F3',
"o''": '\u0151',
'o"': '\u00F6',
'oe': '\u0153',
'o`': '\u00F2',
'o^': '\u00F4',
'o': '\u03C9',
'omega': '\u03C9',
'w': '\u03C9',
'om': '\u03BF',
'omicron': '\u03BF',
'opt': '\uF7D2',
'||': '\u2228',
'or': '\u2228',
'o/': '\u00F8',
'o~': '\u00F5',
'o{': '\uFE37',
'o[': '\u23B4',
'o(': '\uFE35',
'pd': '\u2202',
'ph': '\u03D5',
'phi': '\u03D5',
'f': '\u03D5',
'p': '\u03C0',
'pi': '\u03C0',
'pw': '\uF361',
'pl': '\uF528',
'+-': '\u00B1',
"'": '\u2032',
'prod': '\u220F',
'prop': '\u221D',
'ps': '\u03C8',
'psi': '\u03C8',
'y': '\u03C8',
'rtm': '\u00AE',
'ret': '\u21B5',
' ret': '\uF766',
'``': '\u2036',
'mem': '\u220B',
'`': '\u2035',
'rv': '\u0159',
'r': '\u03C1',
'rho': '\u03C1',
'>': '\u232A',
' ->': '\u2192',
'r|': '\uF604',
'rc': '\u2309',
']]': '\u301B',
'r||': '\uF606',
'rf': '\u230B',
'g>>': '\u00BB',
']': '\uF76C',
'rT': '\u22A2',
'vec': '\u21C0',
'->': '\uF522',
':>': '\uF51F',
':-(': '\u2639',
'sa': '\u03E0',
'sampi': '\u03E0',
'sca': '\uF6B2',
'scb': '\uF6B3',
'scc': '\uF6B4',
'scA': '\uF770',
'scB': '\u212C',
'scC': '\uF772',
'scD': '\uF773',
'scE': '\u2130',
'scF': '\u2131',
'scG': '\uF776',
'scH': '\u210B',
'scI': '\u2110',
'scJ': '\uF779',
'scK': '\uF77A',
'scL': '\u2112',
'scM': '\u2133',
'scN': '\uF77D',
'scO': '\uF77E',
'scP': '\u2118',
'scQ': '\uF780',
'scR': '\u211B',
'scS': '\uF782',
'scT': '\uF783',
'scU': '\uF784',
'scV': '\uF785',
'scW': '\uF786',
'scX': '\uF787',
'scY': '\uF788',
'scZ': '\uF789',
'scd': '\uF6B5',
'sce': '\u212F',
'sc8': '\uF7F8',
'scf': '\uF6B7',
'sc5': '\uF7F5',
'sc4': '\uF7F4',
'scg': '\u210A',
'sch': '\uF6B9',
'sci': '\uF6BA',
'scj': '\uF6BB',
'sck': '\uF6BC',
'scl': '\u2113',
'scm': '\uF6BE',
'scn': '\uF6BF',
'sc9': '\uF7F9',
'sco': '\u2134',
'sc1': '\uF7F1',
'scp': '\uF6C1',
'scq': '\uF6C2',
'scr': '\uF6C3',
'scs': '\uF6C4',
'sc7': '\uF7F7',
'sc6': '\uF7F6',
'sct': '\uF6C5',
'sc3': '\uF7F3',
'sc2': '\uF7F2',
'scu': '\uF6C6',
'scv': '\uF6C7',
'scw': '\uF6C8',
'scx': '\uF6C9',
'scy': '\uF6CA',
'scz': '\uF6CB',
'sc0': '\uF7F0',
'spl': '\uF527',
'sv': '\u0161',
's': '\u03C3',
'sigma': '\u03C3',
'*6': '\u2736',
'sc': '\u2218',
'space': '\u2423',
'spc': '\uF7BF',
'sqrt': '\u221A',
'sq': '\uF520',
'star': '\u22C6',
'sti': '\u03DB',
'stigma': '\u03DB',
'sub': '\u2282',
'sub=': '\u2286',
'st': '\u220D',
'sum': '\u2211',
'sup': '\u2283',
'sup=': '\u2287',
'sz': '\u00DF',
'ss': '\u00DF',
'tab': '\uF7BE',
't': '\u03C4',
'tau': '\u03C4',
'tv': '\u0165',
'tf': '\u2234',
'th': '\u03B8',
'theta': '\u03B8',
'q': '\u03B8',
' ': '\u2005',
' ': '\u2009',
'thn': '\u00FE',
'~': '\u223C',
'~=': '\u2243',
'~==': '\u2245',
'~~': '\u2248',
'*': '\u00D7',
'tm': '\u2122',
'tr': '\uF3C7',
"u'": '\u00FA',
"u''": '\u0171',
'u"': '\u00FC',
'u`': '\u00F9',
'u^': '\u00FB',
'u{': '\uFE38',
'u[': '\u23B5',
'u(': '\uFE36',
'un': '\u22C3',
'u': '\u03C5',
'upsilon': '\u03C5',
'uT': '\u22A5',
'uo': '\u016F',
'v': '\u22C1',
' |': '\u2223',
'vline': '\u2502',
'|': '\uF432',
' ': '\u200A',
'^': '\u22C0',
'wp': '\u2118',
'wf': '\uF720',
'wolf': '\uF720',
'x': '\u03BE',
'xi': '\u03BE',
'xnor': '\uF4A2',
'xor': '\u22BB',
"y'": '\u00FD',
'z': '\u03B6',
'zeta': '\u03B6',
'zv': '\u017E',
}<|fim▁end|>
|
'goO': '\uF798',
'goP': '\uF799',
'goQ': '\uF79A',
'goR': '\u211C',
|
<|file_name|>AtomicTool.cpp<|end_file_name|><|fim▁begin|>//
// Copyright (c) 2014-2015, THUNDERBEAST GAMES LLC All rights reserved
// LICENSE: Atomic Game Engine Editor and Tools EULA
// Please see LICENSE_ATOMIC_EDITOR_AND_TOOLS.md in repository root for
// license information: https://github.com/AtomicGameEngine/AtomicGameEngine
//
#include <Atomic/Core/ProcessUtils.h>
#include <Atomic/IO/Log.h>
#include <Atomic/IO/FileSystem.h>
#include <Atomic/Engine/Engine.h>
#include <Atomic/Resource/ResourceCache.h>
#include <ToolCore/ToolSystem.h>
#include <ToolCore/ToolEnvironment.h>
#include <ToolCore/Build/BuildSystem.h>
#include <ToolCore/License/LicenseEvents.h>
#include <ToolCore/License/LicenseSystem.h>
#include <ToolCore/Command/Command.h>
#include <ToolCore/Command/CommandParser.h>
#include "AtomicTool.h"<|fim▁hole|>
using namespace ToolCore;
namespace AtomicTool
{
AtomicTool::AtomicTool(Context* context) :
Application(context),
deactivate_(false)
{
}
AtomicTool::~AtomicTool()
{
}
void AtomicTool::Setup()
{
const Vector<String>& arguments = GetArguments();
for (unsigned i = 0; i < arguments.Size(); ++i)
{
if (arguments[i].Length() > 1)
{
String argument = arguments[i].ToLower();
String value = i + 1 < arguments.Size() ? arguments[i + 1] : String::EMPTY;
if (argument == "--cli-data-path")
{
if (!value.Length())
ErrorExit("Unable to parse --cli-data-path");
cliDataPath_ = AddTrailingSlash(value);
}
else if (argument == "--activate")
{
if (!value.Length())
ErrorExit("Unable to parse --activation product key");
activationKey_ = value;
}
else if (argument == "--deactivate")
{
deactivate_ = true;
}
}
}
engineParameters_["Headless"] = true;
engineParameters_["LogLevel"] = LOG_INFO;
// no default resources (will be initialized later)
engineParameters_["ResourcePaths"] = "";
}
void AtomicTool::HandleCommandFinished(StringHash eventType, VariantMap& eventData)
{
GetSubsystem<Engine>()->Exit();
}
void AtomicTool::HandleCommandError(StringHash eventType, VariantMap& eventData)
{
String error = "Command Error";
const String& message = eventData[CommandError::P_MESSAGE].ToString();
if (message.Length())
error = message;
ErrorExit(error);
}
void AtomicTool::HandleLicenseEulaRequired(StringHash eventType, VariantMap& eventData)
{
ErrorExit("\nActivation Required: Please run: atomic-cli activate\n");
}
void AtomicTool::HandleLicenseActivationRequired(StringHash eventType, VariantMap& eventData)
{
ErrorExit("\nActivation Required: Please run: atomic-cli activate\n");
}
void AtomicTool::HandleLicenseSuccess(StringHash eventType, VariantMap& eventData)
{
if (command_.Null())
{
GetSubsystem<Engine>()->Exit();
return;
}
command_->Run();
}
void AtomicTool::HandleLicenseError(StringHash eventType, VariantMap& eventData)
{
ErrorExit("\nActivation Required: Please run: atomic-cli activate\n");
}
void AtomicTool::HandleLicenseActivationError(StringHash eventType, VariantMap& eventData)
{
String message = eventData[LicenseActivationError::P_MESSAGE].ToString();
ErrorExit(message);
}
void AtomicTool::HandleLicenseActivationSuccess(StringHash eventType, VariantMap& eventData)
{
LOGRAW("\nActivation successful, thank you!\n\n");
GetSubsystem<Engine>()->Exit();
}
void AtomicTool::DoActivation()
{
LicenseSystem* licenseSystem = GetSubsystem<LicenseSystem>();
if (!licenseSystem->ValidateKey(activationKey_))
{
ErrorExit(ToString("\nProduct key \"%s\" is invalid, keys are in the form ATOMIC-XXXX-XXXX-XXXX-XXXX\n", activationKey_.CString()));
return;
}
licenseSystem->LicenseAgreementConfirmed();
SubscribeToEvent(E_LICENSE_ACTIVATIONERROR, HANDLER(AtomicTool, HandleLicenseActivationError));
SubscribeToEvent(E_LICENSE_ACTIVATIONSUCCESS, HANDLER(AtomicTool, HandleLicenseActivationSuccess));
licenseSystem->RequestServerActivation(activationKey_);
}
void AtomicTool::HandleLicenseDeactivationError(StringHash eventType, VariantMap& eventData)
{
String message = eventData[LicenseDeactivationError::P_MESSAGE].ToString();
ErrorExit(message);
}
void AtomicTool::HandleLicenseDeactivationSuccess(StringHash eventType, VariantMap& eventData)
{
LOGRAW("\nDeactivation successful\n\n");
GetSubsystem<Engine>()->Exit();
}
void AtomicTool::DoDeactivation()
{
LicenseSystem* licenseSystem = GetSubsystem<LicenseSystem>();
if (!licenseSystem->LoadLicense())
{
ErrorExit("\nNot activated");
return;
}
if (!licenseSystem->Deactivate())
{
ErrorExit("\nNot activated\n");
return;
}
SubscribeToEvent(E_LICENSE_DEACTIVATIONERROR, HANDLER(AtomicTool, HandleLicenseDeactivationError));
SubscribeToEvent(E_LICENSE_DEACTIVATIONSUCCESS, HANDLER(AtomicTool, HandleLicenseDeactivationSuccess));
}
void AtomicTool::Start()
{
// Subscribe to events
SubscribeToEvent(E_COMMANDERROR, HANDLER(AtomicTool, HandleCommandError));
SubscribeToEvent(E_COMMANDFINISHED, HANDLER(AtomicTool, HandleCommandFinished));
SubscribeToEvent(E_LICENSE_EULAREQUIRED, HANDLER(AtomicTool, HandleLicenseEulaRequired));
SubscribeToEvent(E_LICENSE_ACTIVATIONREQUIRED, HANDLER(AtomicTool, HandleLicenseActivationRequired));
SubscribeToEvent(E_LICENSE_ERROR, HANDLER(AtomicTool, HandleLicenseError));
SubscribeToEvent(E_LICENSE_SUCCESS, HANDLER(AtomicTool, HandleLicenseSuccess));
const Vector<String>& arguments = GetArguments();
ToolSystem* tsystem = new ToolSystem(context_);
context_->RegisterSubsystem(tsystem);
ToolEnvironment* env = new ToolEnvironment(context_);
context_->RegisterSubsystem(env);
//#ifdef ATOMIC_DEV_BUILD
if (!env->InitFromJSON())
{
ErrorExit(ToString("Unable to initialize tool environment from %s", env->GetDevConfigFilename().CString()));
return;
}
if (!cliDataPath_.Length())
{
cliDataPath_ = env->GetRootSourceDir() + "/Resources/";
}
//#endif
ResourceCache* cache = GetSubsystem<ResourceCache>();
cache->AddResourceDir(env->GetCoreDataDir());
cache->AddResourceDir(env->GetPlayerDataDir());
tsystem->SetCLI();
tsystem->SetDataPath(cliDataPath_);
if (activationKey_.Length())
{
DoActivation();
return;
} else if (deactivate_)
{
DoDeactivation();
return;
}
BuildSystem* buildSystem = GetSubsystem<BuildSystem>();
SharedPtr<CommandParser> parser(new CommandParser(context_));
SharedPtr<Command> cmd(parser->Parse(arguments));
if (!cmd)
{
String error = "No command found";
if (parser->GetErrorMessage().Length())
error = parser->GetErrorMessage();
ErrorExit(error);
return;
}
if (cmd->RequiresProjectLoad())
{
FileSystem* fileSystem = GetSubsystem<FileSystem>();
String projectDirectory = fileSystem->GetCurrentDir();
Vector<String> projectFiles;
fileSystem->ScanDir(projectFiles, projectDirectory, "*.atomic", SCAN_FILES, false);
if (!projectFiles.Size())
{
ErrorExit(ToString("No .atomic project file in %s", projectDirectory.CString()));
return;
}
else if (projectFiles.Size() > 1)
{
ErrorExit(ToString("Multiple .atomic project files found in %s", projectDirectory.CString()));
return;
}
String projectFile = projectDirectory + "/" + projectFiles[0];
if (!tsystem->LoadProject(projectFile))
{
//ErrorExit(ToString("Failed to load project: %s", projectFile.CString()));
//return;
}
// Set the build path
String buildFolder = projectDirectory + "/" + "Build";
buildSystem->SetBuildPath(buildFolder);
if (!fileSystem->DirExists(buildFolder))
{
fileSystem->CreateDir(buildFolder);
if (!fileSystem->DirExists(buildFolder))
{
ErrorExit(ToString("Failed to create build folder: %s", buildFolder.CString()));
return;
}
}
}
command_ = cmd;
// BEGIN LICENSE MANAGEMENT
if (cmd->RequiresLicenseValidation())
{
GetSubsystem<LicenseSystem>()->Initialize();
}
else
{
if (command_.Null())
{
GetSubsystem<Engine>()->Exit();
return;
}
command_->Run();
}
// END LICENSE MANAGEMENT
}
void AtomicTool::Stop()
{
}
void AtomicTool::ErrorExit(const String& message)
{
engine_->Exit(); // Close the rendering window
exitCode_ = EXIT_FAILURE;
// Only for WIN32, otherwise the error messages would be double posted on Mac OS X and Linux platforms
if (!message.Length())
{
#ifdef WIN32
Atomic::ErrorExit(startupErrors_.Length() ? startupErrors_ :
"Application has been terminated due to unexpected error.", exitCode_);
#endif
}
else
Atomic::ErrorExit(message, exitCode_);
}
}<|fim▁end|>
|
DEFINE_APPLICATION_MAIN(AtomicTool::AtomicTool);
|
<|file_name|>index.js<|end_file_name|><|fim▁begin|>function example(name, deps) {
console.log('This is where fpscounter plugin code would execute in the node process.');<|fim▁hole|>module.exports = example;<|fim▁end|>
|
}
|
<|file_name|>ElasticJobSnapshotServiceConfigurationTest.java<|end_file_name|><|fim▁begin|>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.shardingsphere.elasticjob.lite.spring.boot.reg.snapshot;
import static org.junit.Assert.assertNotNull;
import org.apache.shardingsphere.elasticjob.lite.internal.snapshot.SnapshotService;<|fim▁hole|>import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
@SpringBootTest
@SpringBootApplication
@ActiveProfiles("snapshot")
public class ElasticJobSnapshotServiceConfigurationTest extends AbstractJUnit4SpringContextTests {
@BeforeClass
public static void init() {
EmbedTestingServer.start();
}
@Test
public void assertSnapshotServiceConfiguration() {
assertNotNull(applicationContext);
assertNotNull(applicationContext.getBean(SnapshotService.class));
}
}<|fim▁end|>
|
import org.apache.shardingsphere.elasticjob.lite.spring.boot.job.fixture.EmbedTestingServer;
|
<|file_name|>atmega16hvb.js<|end_file_name|><|fim▁begin|>module.exports = {
"name": "ATmega16HVB",
"timeout": 200,
"stabDelay": 100,
"cmdexeDelay": 25,
"syncLoops": 32,
"byteDelay": 0,
"pollIndex": 3,
"pollValue": 83,
"preDelay": 1,
"postDelay": 1,
"pgmEnable": [172, 83, 0, 0],
"erase": {
"cmd": [172, 128, 0, 0],
"delay": 45,
"pollMethod": 1
},
"flash": {
"write": [64, 76, 0],
"read": [32, 0, 0],
"mode": 65,
"blockSize": 128,
"delay": 10,
"poll2": 0,
"poll1": 0,
"size": 16384,
"pageSize": 128,
"pages": 128,
"addressOffset": null
},
"eeprom": {
"write": [193, 194, 0],
"read": [160, 0, 0],
"mode": 65,
"blockSize": 4,
"delay": 10,<|fim▁hole|> "pageSize": 4,
"pages": 128,
"addressOffset": 0
},
"sig": [30, 148, 13],
"signature": {
"size": 3,
"startAddress": 0,
"read": [48, 0, 0, 0]
},
"fuses": {
"startAddress": 0,
"write": {
"low": [172, 160, 0, 0],
"high": [172, 168, 0, 0]
},
"read": {
"low": [80, 0, 0, 0],
"high": [88, 8, 0, 0]
}
}
}<|fim▁end|>
|
"poll2": 0,
"poll1": 0,
"size": 512,
|
<|file_name|>AbstractChannel.js<|end_file_name|><|fim▁begin|>var KevoreeEntity = require('./KevoreeEntity');
/**
* AbstractChannel entity
*
* @type {AbstractChannel} extends KevoreeEntity
*/
module.exports = KevoreeEntity.extend({
toString: 'AbstractChannel',
construct: function () {
this.remoteNodes = {};
this.inputs = {};
},
internalSend: function (portPath, msg) {
var remoteNodeNames = this.remoteNodes[portPath];
for (var remoteNodeName in remoteNodeNames) {
this.onSend(remoteNodeName, msg);
}
},
/**
*
* @param remoteNodeName
* @param msg
*/
onSend: function (remoteNodeName, msg) {
},
remoteCallback: function (msg) {
for (var name in this.inputs) {
this.inputs[name].getCallback().call(this, msg);
}
},
addInternalRemoteNodes: function (portPath, remoteNodes) {
this.remoteNodes[portPath] = remoteNodes;
},<|fim▁hole|>});<|fim▁end|>
|
addInternalInputPort: function (port) {
this.inputs[port.getName()] = port;
}
|
<|file_name|>0046_element_tags.py<|end_file_name|><|fim▁begin|># Generated by Django 3.1.7 on 2021-02-28 19:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('siteapp', '0041_project_tags'),
('controls', '0045_auto_20210228_1431'),
]
operations = [
migrations.AddField(<|fim▁hole|> field=models.ManyToManyField(related_name='element', to='siteapp.Tag'),
),
]<|fim▁end|>
|
model_name='element',
name='tags',
|
<|file_name|>Building.java<|end_file_name|><|fim▁begin|>/*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* 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<|fim▁hole|> */
package org.jbpm.kie.test.objects;
public interface Building {
public Integer getDoors();
}<|fim▁end|>
|
* limitations under the License.
|
<|file_name|>confversion.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Copyright (c) 2010-2010 by drubin <drubin at smartcube.co.za>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Allows you to visually see if there are updates to your weechat system
#Versions
# 0.1 drubin - First release.
# - Basic functionality to save version history of your config files (only git, bzr)
# 0.2 ShockkPony - Fixed massive weechat startup time caused by initial config loading
SCRIPT_NAME = "confversion"
SCRIPT_AUTHOR = "drubin <drubin at smartcube.co.za>"
SCRIPT_VERSION = "0.2"
SCRIPT_LICENSE = "GPL3"
SCRIPT_DESC = "Stores version controlled history of your configuration files"
import_ok = True
import subprocess
try:
import weechat
except ImportError:
print "This script must be run under WeeChat."
print "Get WeeChat now at: http://www.weechat.org/"
import_ok = False
# script options
settings = {
#Currently supports git and bzr and possibly other that support simple "init" "add *.conf" "commit -m "message" "
"versioning_method" : "git",
"commit_each_change" : "true",
"commit_message" : "Commiting changes",
#Allows you to not auto commit stuff that relates to these configs
#, (comma) seperated list of config options
#The toggle_nicklist script can make this property annoying.
"auto_commit_ignore" : "weechat.bar.nicklist.hidden",
}
def shell_in_home(cmd):
try:
output = file("/dev/null","w")
subprocess.Popen(ver_method()+" "+cmd, cwd = weechat_home(),
stdout= output, stderr=output, shell=True)
except Exception as e:
print e
def weechat_home():
return weechat.info_get ("weechat_dir", "")
def ver_method():
return weechat.config_get_plugin("versioning_method")
def init_repo():
#Set up version control (doesn't matter if previously setup for bzr, git)
shell_in_home("init")
#Save first import OR on start up if needed.
commit_cb()
confversion_commit_finish_hook = 0<|fim▁hole|>
def commit_cb(data=None, remaning=None):
global confversion_commit_finish_hook
# only hook timer if not already hooked
if confversion_commit_finish_hook == 0:
confversion_commit_finish_hook = weechat.hook_timer(500, 0, 1, "commit_cb_finish", "")
return weechat.WEECHAT_RC_OK
def commit_cb_finish(data=None, remaining=None):
global confversion_commit_finish_hook
# save before doing commit
weechat.command("","/save")
# add all config changes to git
shell_in_home("add ./*.conf")
# do the commit
shell_in_home("commit -m \"%s\"" % weechat.config_get_plugin("commit_message"))
# set hook back to 0
confversion_commit_finish_hook = 0
return weechat.WEECHAT_RC_OK
def conf_update_cb(data, option, value):
#Commit data if not part of ignore list.
if weechat.config_get_plugin("commit_each_change") == "true" and not option in weechat.config_get_plugin("auto_commit_ignore").split(","):
#Call use pause else /save will be called before the config is actually saved to disc
#This is kinda hack but better input would be appricated.
weechat.hook_timer(500, 0, 1, "commit_cb", "")
return weechat.WEECHAT_RC_OK
def confversion_cmd(data, buffer, args):
commit_cb()
return weechat.WEECHAT_RC_OK
if weechat.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION, SCRIPT_LICENSE,
SCRIPT_DESC, "", ""):
for option, default_value in settings.iteritems():
if weechat.config_get_plugin(option) == "":
weechat.config_set_plugin(option, default_value)
weechat.hook_command("confversion", "Saves configurations to version control", "",
"",
"", "confversion_cmd", "")
init_repo()
hook = weechat.hook_config("*", "conf_update_cb", "")<|fim▁end|>
| |
<|file_name|>tabs.py<|end_file_name|><|fim▁begin|># Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
# Copyright 2012 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import tabs
from neutronclient.common import exceptions as neutron_exc
from openstack_dashboard.api import keystone
from openstack_dashboard.api import network
from openstack_dashboard.api import nova
from openstack_dashboard.dashboards.project.access_and_security.\
api_access.tables import EndpointsTable
from openstack_dashboard.dashboards.project.access_and_security.\<|fim▁hole|> security_groups.tables import SecurityGroupsTable
class SecurityGroupsTab(tabs.TableTab):
table_classes = (SecurityGroupsTable,)
name = _("Security Groups")
slug = "security_groups_tab"
template_name = "horizon/common/_detail_table.html"
permissions = ('openstack.services.compute',)
def get_security_groups_data(self):
try:
security_groups = network.security_group_list(self.request)
except neutron_exc.ConnectionFailed:
security_groups = []
exceptions.handle(self.request)
except Exception:
security_groups = []
exceptions.handle(self.request,
_('Unable to retrieve security groups.'))
return sorted(security_groups, key=lambda group: group.name)
class KeypairsTab(tabs.TableTab):
table_classes = (KeypairsTable,)
name = _("Key Pairs")
slug = "keypairs_tab"
template_name = "horizon/common/_detail_table.html"
permissions = ('openstack.services.compute',)
def get_keypairs_data(self):
try:
keypairs = nova.keypair_list(self.request)
except Exception:
keypairs = []
exceptions.handle(self.request,
_('Unable to retrieve key pair list.'))
return keypairs
class FloatingIPsTab(tabs.TableTab):
table_classes = (FloatingIPsTable,)
name = _("Floating IPs")
slug = "floating_ips_tab"
template_name = "horizon/common/_detail_table.html"
permissions = ('openstack.services.compute',)
def get_floating_ips_data(self):
try:
floating_ips = network.tenant_floating_ip_list(self.request)
except neutron_exc.ConnectionFailed:
floating_ips = []
exceptions.handle(self.request)
except Exception:
floating_ips = []
exceptions.handle(self.request,
_('Unable to retrieve floating IP addresses.'))
try:
floating_ip_pools = network.floating_ip_pools_list(self.request)
except neutron_exc.ConnectionFailed:
floating_ip_pools = []
exceptions.handle(self.request)
except Exception:
floating_ip_pools = []
exceptions.handle(self.request,
_('Unable to retrieve floating IP pools.'))
pool_dict = dict([(obj.id, obj.name) for obj in floating_ip_pools])
instances = []
try:
instances, has_more = nova.server_list(self.request)
except Exception:
exceptions.handle(self.request,
_('Unable to retrieve instance list.'))
instances_dict = dict([(obj.id, obj.name) for obj in instances])
for ip in floating_ips:
ip.instance_name = instances_dict.get(ip.instance_id)
ip.pool_name = pool_dict.get(ip.pool, ip.pool)
return floating_ips
def allowed(self, request):
return network.floating_ip_supported(request)
class APIAccessTab(tabs.TableTab):
table_classes = (EndpointsTable,)
name = _("API Access")
slug = "api_access_tab"
template_name = "horizon/common/_detail_table.html"
def get_endpoints_data(self):
services = []
for i, service in enumerate(self.request.user.service_catalog):
service['id'] = i
services.append(
keystone.Service(service, self.request.user.services_region))
return services
class AccessAndSecurityTabs(tabs.TabGroup):
slug = "access_security_tabs"
tabs = (SecurityGroupsTab, KeypairsTab, FloatingIPsTab, APIAccessTab)
sticky = True<|fim▁end|>
|
floating_ips.tables import FloatingIPsTable
from openstack_dashboard.dashboards.project.access_and_security.\
keypairs.tables import KeypairsTable
from openstack_dashboard.dashboards.project.access_and_security.\
|
<|file_name|>comment.rs<|end_file_name|><|fim▁begin|>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Formatting and tools for comments.
use std::{self, iter};
use syntax::codemap::Span;
use config::Config;
use rewrite::RewriteContext;
use shape::{Indent, Shape};
use string::{rewrite_string, StringFormat};
use utils::{first_line_width, last_line_width};
fn is_custom_comment(comment: &str) -> bool {
if !comment.starts_with("//") {
false
} else if let Some(c) = comment.chars().nth(2) {
!c.is_alphanumeric() && !c.is_whitespace()
} else {
false
}
}
#[derive(Copy, Clone, PartialEq, Eq)]
pub enum CommentStyle<'a> {
DoubleSlash,
TripleSlash,
Doc,
SingleBullet,
DoubleBullet,
Exclamation,
Custom(&'a str),
}
fn custom_opener(s: &str) -> &str {
s.lines().next().map_or("", |first_line| {
first_line
.find(' ')
.map_or(first_line, |space_index| &first_line[0..space_index + 1])
})
}
impl<'a> CommentStyle<'a> {
pub fn opener(&self) -> &'a str {
match *self {
CommentStyle::DoubleSlash => "// ",
CommentStyle::TripleSlash => "/// ",
CommentStyle::Doc => "//! ",
CommentStyle::SingleBullet => "/* ",
CommentStyle::DoubleBullet => "/** ",
CommentStyle::Exclamation => "/*! ",
CommentStyle::Custom(opener) => opener,
}
}
pub fn closer(&self) -> &'a str {
match *self {
CommentStyle::DoubleSlash |
CommentStyle::TripleSlash |
CommentStyle::Custom(..) |
CommentStyle::Doc => "",
CommentStyle::DoubleBullet => " **/",
CommentStyle::SingleBullet | CommentStyle::Exclamation => " */",
}
}
pub fn line_start(&self) -> &'a str {
match *self {
CommentStyle::DoubleSlash => "// ",
CommentStyle::TripleSlash => "/// ",
CommentStyle::Doc => "//! ",
CommentStyle::SingleBullet | CommentStyle::Exclamation => " * ",
CommentStyle::DoubleBullet => " ** ",
CommentStyle::Custom(opener) => opener,
}
}
pub fn to_str_tuplet(&self) -> (&'a str, &'a str, &'a str) {
(self.opener(), self.closer(), self.line_start())
}
pub fn line_with_same_comment_style(&self, line: &str, normalize_comments: bool) -> bool {
match *self {
CommentStyle::DoubleSlash | CommentStyle::TripleSlash | CommentStyle::Doc => {
line.trim_left().starts_with(self.line_start().trim_left())
|| comment_style(line, normalize_comments) == *self
}
CommentStyle::DoubleBullet | CommentStyle::SingleBullet | CommentStyle::Exclamation => {
line.trim_left().starts_with(self.closer().trim_left())
|| line.trim_left().starts_with(self.line_start().trim_left())
|| comment_style(line, normalize_comments) == *self
}
CommentStyle::Custom(opener) => line.trim_left().starts_with(opener.trim_right()),
}
}
}
fn comment_style(orig: &str, normalize_comments: bool) -> CommentStyle {
if !normalize_comments {
if orig.starts_with("/**") && !orig.starts_with("/**/") {
CommentStyle::DoubleBullet
} else if orig.starts_with("/*!") {
CommentStyle::Exclamation
} else if orig.starts_with("/*") {
CommentStyle::SingleBullet
} else if orig.starts_with("///") && orig.chars().nth(3).map_or(true, |c| c != '/') {
CommentStyle::TripleSlash
} else if orig.starts_with("//!") {
CommentStyle::Doc
} else if is_custom_comment(orig) {
CommentStyle::Custom(custom_opener(orig))
} else {
CommentStyle::DoubleSlash
}
} else if (orig.starts_with("///") && orig.chars().nth(3).map_or(true, |c| c != '/'))
|| (orig.starts_with("/**") && !orig.starts_with("/**/"))
{
CommentStyle::TripleSlash
} else if orig.starts_with("//!") || orig.starts_with("/*!") {
CommentStyle::Doc
} else if is_custom_comment(orig) {
CommentStyle::Custom(custom_opener(orig))
} else {
CommentStyle::DoubleSlash
}
}
pub fn combine_strs_with_missing_comments(
context: &RewriteContext,
prev_str: &str,
next_str: &str,
span: Span,
shape: Shape,
allow_extend: bool,
) -> Option<String> {
let mut allow_one_line = !prev_str.contains('\n') && !next_str.contains('\n');
let first_sep = if prev_str.is_empty() || next_str.is_empty() {
""
} else {
" "
};
let mut one_line_width =
last_line_width(prev_str) + first_line_width(next_str) + first_sep.len();
let indent_str = shape.indent.to_string(context.config);
let missing_comment = rewrite_missing_comment(span, shape, context)?;
if missing_comment.is_empty() {
if allow_extend && prev_str.len() + first_sep.len() + next_str.len() <= shape.width {
return Some(format!("{}{}{}", prev_str, first_sep, next_str));
} else {
let sep = if prev_str.is_empty() {
String::new()
} else {
String::from("\n") + &indent_str
};
return Some(format!("{}{}{}", prev_str, sep, next_str));
}
}
// We have a missing comment between the first expression and the second expression.
// Peek the the original source code and find out whether there is a newline between the first
// expression and the second expression or the missing comment. We will preserve the orginal
// layout whenever possible.
let original_snippet = context.snippet(span);
let prefer_same_line = if let Some(pos) = original_snippet.chars().position(|c| c == '/') {
!original_snippet[..pos].contains('\n')
} else {
!original_snippet.contains('\n')
};
one_line_width -= first_sep.len();
let first_sep = if prev_str.is_empty() || missing_comment.is_empty() {
String::new()
} else {
let one_line_width = last_line_width(prev_str) + first_line_width(&missing_comment) + 1;
if prefer_same_line && one_line_width <= shape.width {
String::from(" ")
} else {
format!("\n{}", indent_str)
}
};
let second_sep = if missing_comment.is_empty() || next_str.is_empty() {
String::new()
} else if missing_comment.starts_with("//") {
format!("\n{}", indent_str)
} else {
one_line_width += missing_comment.len() + first_sep.len() + 1;
allow_one_line &= !missing_comment.starts_with("//") && !missing_comment.contains('\n');
if prefer_same_line && allow_one_line && one_line_width <= shape.width {
String::from(" ")
} else {
format!("\n{}", indent_str)
}
};
Some(format!(
"{}{}{}{}{}",
prev_str,
first_sep,
missing_comment,
second_sep,
next_str,
))
}
pub fn rewrite_comment(
orig: &str,
block_style: bool,
shape: Shape,
config: &Config,
) -> Option<String> {
// If there are lines without a starting sigil, we won't format them correctly
// so in that case we won't even re-align (if !config.normalize_comments()) and
// we should stop now.
let num_bare_lines = orig.lines()
.map(|line| line.trim())
.filter(|l| {
!(l.starts_with('*') || l.starts_with("//") || l.starts_with("/*"))
})
.count();
if num_bare_lines > 0 && !config.normalize_comments() {
return Some(orig.to_owned());
}
if !config.normalize_comments() && !config.wrap_comments() {
return light_rewrite_comment(orig, shape.indent, config);
}
identify_comment(orig, block_style, shape, config)
}
fn identify_comment(
orig: &str,
block_style: bool,
shape: Shape,
config: &Config,
) -> Option<String> {
let style = comment_style(orig, false);
let first_group = orig.lines()
.take_while(|l| style.line_with_same_comment_style(l, false))
.collect::<Vec<_>>()
.join("\n");
let rest = orig.lines()
.skip(first_group.lines().count())
.collect::<Vec<_>>()
.join("\n");
let first_group_str = rewrite_comment_inner(&first_group, block_style, style, shape, config)?;
if rest.is_empty() {
Some(first_group_str)
} else {
identify_comment(&rest, block_style, shape, config).map(|rest_str| {
format!(
"{}\n{}{}",
first_group_str,
shape.indent.to_string(config),
rest_str
)
})
}
}
fn rewrite_comment_inner(
orig: &str,
block_style: bool,
style: CommentStyle,
shape: Shape,
config: &Config,
) -> Option<String> {
let (opener, closer, line_start) = if block_style {
CommentStyle::SingleBullet.to_str_tuplet()
} else {
comment_style(orig, config.normalize_comments()).to_str_tuplet()
};
let max_chars = shape
.width
.checked_sub(closer.len() + opener.len())
.unwrap_or(1);
let indent_str = shape.indent.to_string(config);
let fmt = StringFormat {
opener: "",
closer: "",
line_start: line_start,
line_end: "",
shape: Shape::legacy(max_chars, shape.indent + (opener.len() - line_start.len())),
trim_end: true,
config: config,
};
let line_breaks = orig.trim_right().chars().filter(|&c| c == '\n').count();
let lines = orig.lines()
.enumerate()
.map(|(i, mut line)| {
line = line.trim();
// Drop old closer.
if i == line_breaks && line.ends_with("*/") && !line.starts_with("//") {
line = line[..(line.len() - 2)].trim_right();
}
line
})
.map(|s| left_trim_comment_line(s, &style))
.map(|line| if orig.starts_with("/*") && line_breaks == 0 {
line.trim_left()
} else {
line
});
let mut result = opener.to_owned();
for line in lines {
if result == opener {
if line.is_empty() {
continue;
}
} else {
result.push('\n');
result.push_str(&indent_str);
result.push_str(line_start);
}
if config.wrap_comments() && line.len() > max_chars {
let rewrite = rewrite_string(line, &fmt).unwrap_or_else(|| line.to_owned());
result.push_str(&rewrite);
} else {
if line.is_empty() && result.ends_with(' ') {
// Remove space if this is an empty comment or a doc comment.
result.pop();
}
result.push_str(line);
}
}
result.push_str(closer);
if result == opener && result.ends_with(' ') {
// Trailing space.
result.pop();
}
Some(result)
}
/// Given the span, rewrite the missing comment inside it if available.
/// Note that the given span must only include comments (or leading/trailing whitespaces).
pub fn rewrite_missing_comment(
span: Span,
shape: Shape,
context: &RewriteContext,
) -> Option<String> {
let missing_snippet = context.snippet(span);
let trimmed_snippet = missing_snippet.trim();
if !trimmed_snippet.is_empty() {
rewrite_comment(trimmed_snippet, false, shape, context.config)
} else {
Some(String::new())
}
}
/// Recover the missing comments in the specified span, if available.
/// The layout of the comments will be preserved as long as it does not break the code
/// and its total width does not exceed the max width.
pub fn recover_missing_comment_in_span(
span: Span,
shape: Shape,
context: &RewriteContext,
used_width: usize,
) -> Option<String> {
let missing_comment = rewrite_missing_comment(span, shape, context)?;
if missing_comment.is_empty() {
Some(String::new())
} else {
let missing_snippet = context.snippet(span);
let pos = missing_snippet.chars().position(|c| c == '/').unwrap_or(0);
// 1 = ` `
let total_width = missing_comment.len() + used_width + 1;
let force_new_line_before_comment =
missing_snippet[..pos].contains('\n') || total_width > context.config.max_width();
let sep = if force_new_line_before_comment {
format!("\n{}", shape.indent.to_string(context.config))
} else {
String::from(" ")
};
Some(format!("{}{}", sep, missing_comment))
}
}
/// Trims whitespace and aligns to indent, but otherwise does not change comments.
fn light_rewrite_comment(orig: &str, offset: Indent, config: &Config) -> Option<String> {
let lines: Vec<&str> = orig.lines()
.map(|l| {
// This is basically just l.trim(), but in the case that a line starts
// with `*` we want to leave one space before it, so it aligns with the
// `*` in `/*`.
let first_non_whitespace = l.find(|c| !char::is_whitespace(c));
if let Some(fnw) = first_non_whitespace {
if l.as_bytes()[fnw] == b'*' && fnw > 0 {
&l[fnw - 1..]
} else {
&l[fnw..]
}
} else {
""
}.trim_right()
})
.collect();
Some(lines.join(&format!("\n{}", offset.to_string(config))))
}
/// Trims comment characters and possibly a single space from the left of a string.
/// Does not trim all whitespace.
fn left_trim_comment_line<'a>(line: &'a str, style: &CommentStyle) -> &'a str {
if line.starts_with("//! ") || line.starts_with("/// ") || line.starts_with("/*! ")
|| line.starts_with("/** ")
{
&line[4..]
} else if let CommentStyle::Custom(opener) = *style {
if line.starts_with(opener) {
&line[opener.len()..]
} else {
&line[opener.trim_right().len()..]
}
} else if line.starts_with("/* ") || line.starts_with("// ") || line.starts_with("//!")
|| line.starts_with("///") || line.starts_with("** ")
|| line.starts_with("/*!")
|| (line.starts_with("/**") && !line.starts_with("/**/"))
{
&line[3..]
} else if line.starts_with("/*") || line.starts_with("* ") || line.starts_with("//")
|| line.starts_with("**")
{
&line[2..]
} else if line.starts_with('*') {
&line[1..]
} else {
line
}
}
pub trait FindUncommented {
fn find_uncommented(&self, pat: &str) -> Option<usize>;
}
impl FindUncommented for str {
fn find_uncommented(&self, pat: &str) -> Option<usize> {
let mut needle_iter = pat.chars();
for (kind, (i, b)) in CharClasses::new(self.char_indices()) {
match needle_iter.next() {
None => {
return Some(i - pat.len());
}
Some(c) => match kind {
FullCodeCharKind::Normal | FullCodeCharKind::InString if b == c => {}
_ => {
needle_iter = pat.chars();
}
},
}
}
// Handle case where the pattern is a suffix of the search string
match needle_iter.next() {
Some(_) => None,
None => Some(self.len() - pat.len()),
}
}
}
// Returns the first byte position after the first comment. The given string
// is expected to be prefixed by a comment, including delimiters.
// Good: "/* /* inner */ outer */ code();"
// Bad: "code(); // hello\n world!"
pub fn find_comment_end(s: &str) -> Option<usize> {
let mut iter = CharClasses::new(s.char_indices());
for (kind, (i, _c)) in &mut iter {
if kind == FullCodeCharKind::Normal || kind == FullCodeCharKind::InString {
return Some(i);
}
}
// Handle case where the comment ends at the end of s.
if iter.status == CharClassesStatus::Normal {
Some(s.len())
} else {
None
}
}
/// Returns true if text contains any comment.
pub fn contains_comment(text: &str) -> bool {
CharClasses::new(text.chars()).any(|(kind, _)| kind.is_comment())
}
/// Remove trailing spaces from the specified snippet. We do not remove spaces
/// inside strings or comments.
pub fn remove_trailing_white_spaces(text: &str) -> String {
let mut buffer = String::with_capacity(text.len());
let mut space_buffer = String::with_capacity(128);
for (char_kind, c) in CharClasses::new(text.chars()) {
match c {
'\n' => {
if char_kind == FullCodeCharKind::InString {
buffer.push_str(&space_buffer);
}
space_buffer.clear();
buffer.push('\n');
}
_ if c.is_whitespace() => {
space_buffer.push(c);
}
_ => {
if !space_buffer.is_empty() {
buffer.push_str(&space_buffer);
space_buffer.clear();
}
buffer.push(c);
}
}
}
buffer
}
<|fim▁hole|>{
base: iter::Peekable<T>,
status: CharClassesStatus,
}
trait RichChar {
fn get_char(&self) -> char;
}
impl RichChar for char {
fn get_char(&self) -> char {
*self
}
}
impl RichChar for (usize, char) {
fn get_char(&self) -> char {
self.1
}
}
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
enum CharClassesStatus {
Normal,
LitString,
LitStringEscape,
LitChar,
LitCharEscape,
// The u32 is the nesting deepness of the comment
BlockComment(u32),
// Status when the '/' has been consumed, but not yet the '*', deepness is
// the new deepness (after the comment opening).
BlockCommentOpening(u32),
// Status when the '*' has been consumed, but not yet the '/', deepness is
// the new deepness (after the comment closing).
BlockCommentClosing(u32),
LineComment,
}
/// Distinguish between functional part of code and comments
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum CodeCharKind {
Normal,
Comment,
}
/// Distinguish between functional part of code and comments,
/// describing opening and closing of comments for ease when chunking
/// code from tagged characters
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
enum FullCodeCharKind {
Normal,
/// The first character of a comment, there is only one for a comment (always '/')
StartComment,
/// Any character inside a comment including the second character of comment
/// marks ("//", "/*")
InComment,
/// Last character of a comment, '\n' for a line comment, '/' for a block comment.
EndComment,
/// Inside a string.
InString,
}
impl FullCodeCharKind {
fn is_comment(&self) -> bool {
match *self {
FullCodeCharKind::StartComment |
FullCodeCharKind::InComment |
FullCodeCharKind::EndComment => true,
_ => false,
}
}
fn to_codecharkind(&self) -> CodeCharKind {
if self.is_comment() {
CodeCharKind::Comment
} else {
CodeCharKind::Normal
}
}
}
impl<T> CharClasses<T>
where
T: Iterator,
T::Item: RichChar,
{
fn new(base: T) -> CharClasses<T> {
CharClasses {
base: base.peekable(),
status: CharClassesStatus::Normal,
}
}
}
impl<T> Iterator for CharClasses<T>
where
T: Iterator,
T::Item: RichChar,
{
type Item = (FullCodeCharKind, T::Item);
fn next(&mut self) -> Option<(FullCodeCharKind, T::Item)> {
let item = self.base.next()?;
let chr = item.get_char();
let mut char_kind = FullCodeCharKind::Normal;
self.status = match self.status {
CharClassesStatus::LitString => match chr {
'"' => CharClassesStatus::Normal,
'\\' => {
char_kind = FullCodeCharKind::InString;
CharClassesStatus::LitStringEscape
}
_ => {
char_kind = FullCodeCharKind::InString;
CharClassesStatus::LitString
}
},
CharClassesStatus::LitStringEscape => {
char_kind = FullCodeCharKind::InString;
CharClassesStatus::LitString
}
CharClassesStatus::LitChar => match chr {
'\\' => CharClassesStatus::LitCharEscape,
'\'' => CharClassesStatus::Normal,
_ => CharClassesStatus::LitChar,
},
CharClassesStatus::LitCharEscape => CharClassesStatus::LitChar,
CharClassesStatus::Normal => match chr {
'"' => {
char_kind = FullCodeCharKind::InString;
CharClassesStatus::LitString
}
'\'' => CharClassesStatus::LitChar,
'/' => match self.base.peek() {
Some(next) if next.get_char() == '*' => {
self.status = CharClassesStatus::BlockCommentOpening(1);
return Some((FullCodeCharKind::StartComment, item));
}
Some(next) if next.get_char() == '/' => {
self.status = CharClassesStatus::LineComment;
return Some((FullCodeCharKind::StartComment, item));
}
_ => CharClassesStatus::Normal,
},
_ => CharClassesStatus::Normal,
},
CharClassesStatus::BlockComment(deepness) => {
assert_ne!(deepness, 0);
self.status = match self.base.peek() {
Some(next) if next.get_char() == '/' && chr == '*' => {
CharClassesStatus::BlockCommentClosing(deepness - 1)
}
Some(next) if next.get_char() == '*' && chr == '/' => {
CharClassesStatus::BlockCommentOpening(deepness + 1)
}
_ => CharClassesStatus::BlockComment(deepness),
};
return Some((FullCodeCharKind::InComment, item));
}
CharClassesStatus::BlockCommentOpening(deepness) => {
assert_eq!(chr, '*');
self.status = CharClassesStatus::BlockComment(deepness);
return Some((FullCodeCharKind::InComment, item));
}
CharClassesStatus::BlockCommentClosing(deepness) => {
assert_eq!(chr, '/');
if deepness == 0 {
self.status = CharClassesStatus::Normal;
return Some((FullCodeCharKind::EndComment, item));
} else {
self.status = CharClassesStatus::BlockComment(deepness);
return Some((FullCodeCharKind::InComment, item));
}
}
CharClassesStatus::LineComment => match chr {
'\n' => {
self.status = CharClassesStatus::Normal;
return Some((FullCodeCharKind::EndComment, item));
}
_ => {
self.status = CharClassesStatus::LineComment;
return Some((FullCodeCharKind::InComment, item));
}
},
};
Some((char_kind, item))
}
}
/// Iterator over functional and commented parts of a string. Any part of a string is either
/// functional code, either *one* block comment, either *one* line comment. Whitespace between
/// comments is functional code. Line comments contain their ending newlines.
struct UngroupedCommentCodeSlices<'a> {
slice: &'a str,
iter: iter::Peekable<CharClasses<std::str::CharIndices<'a>>>,
}
impl<'a> UngroupedCommentCodeSlices<'a> {
fn new(code: &'a str) -> UngroupedCommentCodeSlices<'a> {
UngroupedCommentCodeSlices {
slice: code,
iter: CharClasses::new(code.char_indices()).peekable(),
}
}
}
impl<'a> Iterator for UngroupedCommentCodeSlices<'a> {
type Item = (CodeCharKind, usize, &'a str);
fn next(&mut self) -> Option<Self::Item> {
let (kind, (start_idx, _)) = self.iter.next()?;
match kind {
FullCodeCharKind::Normal | FullCodeCharKind::InString => {
// Consume all the Normal code
while let Some(&(char_kind, _)) = self.iter.peek() {
if char_kind.is_comment() {
break;
}
let _ = self.iter.next();
}
}
FullCodeCharKind::StartComment => {
// Consume the whole comment
while let Some((FullCodeCharKind::InComment, (_, _))) = self.iter.next() {}
}
_ => panic!(),
}
let slice = match self.iter.peek() {
Some(&(_, (end_idx, _))) => &self.slice[start_idx..end_idx],
None => &self.slice[start_idx..],
};
Some((
if kind.is_comment() {
CodeCharKind::Comment
} else {
CodeCharKind::Normal
},
start_idx,
slice,
))
}
}
/// Iterator over an alternating sequence of functional and commented parts of
/// a string. The first item is always a, possibly zero length, subslice of
/// functional text. Line style comments contain their ending newlines.
pub struct CommentCodeSlices<'a> {
slice: &'a str,
last_slice_kind: CodeCharKind,
last_slice_end: usize,
}
impl<'a> CommentCodeSlices<'a> {
pub fn new(slice: &'a str) -> CommentCodeSlices<'a> {
CommentCodeSlices {
slice: slice,
last_slice_kind: CodeCharKind::Comment,
last_slice_end: 0,
}
}
}
impl<'a> Iterator for CommentCodeSlices<'a> {
type Item = (CodeCharKind, usize, &'a str);
fn next(&mut self) -> Option<Self::Item> {
if self.last_slice_end == self.slice.len() {
return None;
}
let mut sub_slice_end = self.last_slice_end;
let mut first_whitespace = None;
let subslice = &self.slice[self.last_slice_end..];
let mut iter = CharClasses::new(subslice.char_indices());
for (kind, (i, c)) in &mut iter {
let is_comment_connector = self.last_slice_kind == CodeCharKind::Normal
&& &subslice[..2] == "//"
&& [' ', '\t'].contains(&c);
if is_comment_connector && first_whitespace.is_none() {
first_whitespace = Some(i);
}
if kind.to_codecharkind() == self.last_slice_kind && !is_comment_connector {
let last_index = match first_whitespace {
Some(j) => j,
None => i,
};
sub_slice_end = self.last_slice_end + last_index;
break;
}
if !is_comment_connector {
first_whitespace = None;
}
}
if let (None, true) = (iter.next(), sub_slice_end == self.last_slice_end) {
// This was the last subslice.
sub_slice_end = match first_whitespace {
Some(i) => self.last_slice_end + i,
None => self.slice.len(),
};
}
let kind = match self.last_slice_kind {
CodeCharKind::Comment => CodeCharKind::Normal,
CodeCharKind::Normal => CodeCharKind::Comment,
};
let res = (
kind,
self.last_slice_end,
&self.slice[self.last_slice_end..sub_slice_end],
);
self.last_slice_end = sub_slice_end;
self.last_slice_kind = kind;
Some(res)
}
}
/// Checks is `new` didn't miss any comment from `span`, if it removed any, return previous text
/// (if it fits in the width/offset, else return None), else return `new`
pub fn recover_comment_removed(
new: String,
span: Span,
context: &RewriteContext,
) -> Option<String> {
let snippet = context.snippet(span);
if snippet != new && changed_comment_content(&snippet, &new) {
// We missed some comments. Keep the original text.
Some(snippet)
} else {
Some(new)
}
}
/// Return true if the two strings of code have the same payload of comments.
/// The payload of comments is everything in the string except:
/// - actual code (not comments)
/// - comment start/end marks
/// - whitespace
/// - '*' at the beginning of lines in block comments
fn changed_comment_content(orig: &str, new: &str) -> bool {
// Cannot write this as a fn since we cannot return types containing closures
let code_comment_content = |code| {
let slices = UngroupedCommentCodeSlices::new(code);
slices
.filter(|&(ref kind, _, _)| *kind == CodeCharKind::Comment)
.flat_map(|(_, _, s)| CommentReducer::new(s))
};
let res = code_comment_content(orig).ne(code_comment_content(new));
debug!(
"comment::changed_comment_content: {}\norig: '{}'\nnew: '{}'\nraw_old: {}\nraw_new: {}",
res,
orig,
new,
code_comment_content(orig).collect::<String>(),
code_comment_content(new).collect::<String>()
);
res
}
/// Iterator over the 'payload' characters of a comment.
/// It skips whitespace, comment start/end marks, and '*' at the beginning of lines.
/// The comment must be one comment, ie not more than one start mark (no multiple line comments,
/// for example).
struct CommentReducer<'a> {
is_block: bool,
at_start_line: bool,
iter: std::str::Chars<'a>,
}
impl<'a> CommentReducer<'a> {
fn new(comment: &'a str) -> CommentReducer<'a> {
let is_block = comment.starts_with("/*");
let comment = remove_comment_header(comment);
CommentReducer {
is_block: is_block,
at_start_line: false, // There are no supplementary '*' on the first line
iter: comment.chars(),
}
}
}
impl<'a> Iterator for CommentReducer<'a> {
type Item = char;
fn next(&mut self) -> Option<Self::Item> {
loop {
let mut c = self.iter.next()?;
if self.is_block && self.at_start_line {
while c.is_whitespace() {
c = self.iter.next()?;
}
// Ignore leading '*'
if c == '*' {
c = self.iter.next()?;
}
} else if c == '\n' {
self.at_start_line = true;
}
if !c.is_whitespace() {
return Some(c);
}
}
}
}
fn remove_comment_header(comment: &str) -> &str {
if comment.starts_with("///") || comment.starts_with("//!") {
&comment[3..]
} else if comment.starts_with("//") {
&comment[2..]
} else if (comment.starts_with("/**") && !comment.starts_with("/**/"))
|| comment.starts_with("/*!")
{
&comment[3..comment.len() - 2]
} else {
assert!(
comment.starts_with("/*"),
format!("string '{}' is not a comment", comment)
);
&comment[2..comment.len() - 2]
}
}
#[cfg(test)]
mod test {
use super::{contains_comment, rewrite_comment, CharClasses, CodeCharKind, CommentCodeSlices,
FindUncommented, FullCodeCharKind};
use shape::{Indent, Shape};
#[test]
fn char_classes() {
let mut iter = CharClasses::new("//\n\n".chars());
assert_eq!((FullCodeCharKind::StartComment, '/'), iter.next().unwrap());
assert_eq!((FullCodeCharKind::InComment, '/'), iter.next().unwrap());
assert_eq!((FullCodeCharKind::EndComment, '\n'), iter.next().unwrap());
assert_eq!((FullCodeCharKind::Normal, '\n'), iter.next().unwrap());
assert_eq!(None, iter.next());
}
#[test]
fn comment_code_slices() {
let input = "code(); /* test */ 1 + 1";
let mut iter = CommentCodeSlices::new(input);
assert_eq!((CodeCharKind::Normal, 0, "code(); "), iter.next().unwrap());
assert_eq!(
(CodeCharKind::Comment, 8, "/* test */"),
iter.next().unwrap()
);
assert_eq!((CodeCharKind::Normal, 18, " 1 + 1"), iter.next().unwrap());
assert_eq!(None, iter.next());
}
#[test]
fn comment_code_slices_two() {
let input = "// comment\n test();";
let mut iter = CommentCodeSlices::new(input);
assert_eq!((CodeCharKind::Normal, 0, ""), iter.next().unwrap());
assert_eq!(
(CodeCharKind::Comment, 0, "// comment\n"),
iter.next().unwrap()
);
assert_eq!(
(CodeCharKind::Normal, 11, " test();"),
iter.next().unwrap()
);
assert_eq!(None, iter.next());
}
#[test]
fn comment_code_slices_three() {
let input = "1 // comment\n // comment2\n\n";
let mut iter = CommentCodeSlices::new(input);
assert_eq!((CodeCharKind::Normal, 0, "1 "), iter.next().unwrap());
assert_eq!(
(CodeCharKind::Comment, 2, "// comment\n // comment2\n"),
iter.next().unwrap()
);
assert_eq!((CodeCharKind::Normal, 29, "\n"), iter.next().unwrap());
assert_eq!(None, iter.next());
}
#[test]
#[cfg_attr(rustfmt, rustfmt_skip)]
fn format_comments() {
let mut config: ::config::Config = Default::default();
config.set().wrap_comments(true);
config.set().normalize_comments(true);
let comment = rewrite_comment(" //test",
true,
Shape::legacy(100, Indent::new(0, 100)),
&config).unwrap();
assert_eq!("/* test */", comment);
let comment = rewrite_comment("// comment on a",
false,
Shape::legacy(10, Indent::empty()),
&config).unwrap();
assert_eq!("// comment\n// on a", comment);
let comment = rewrite_comment("// A multi line comment\n // between args.",
false,
Shape::legacy(60, Indent::new(0, 12)),
&config).unwrap();
assert_eq!("// A multi line comment\n // between args.", comment);
let input = "// comment";
let expected =
"/* comment */";
let comment = rewrite_comment(input,
true,
Shape::legacy(9, Indent::new(0, 69)),
&config).unwrap();
assert_eq!(expected, comment);
let comment = rewrite_comment("/* trimmed */",
true,
Shape::legacy(100, Indent::new(0, 100)),
&config).unwrap();
assert_eq!("/* trimmed */", comment);
}
// This is probably intended to be a non-test fn, but it is not used. I'm
// keeping it around unless it helps us test stuff.
fn uncommented(text: &str) -> String {
CharClasses::new(text.chars())
.filter_map(|(s, c)| match s {
FullCodeCharKind::Normal | FullCodeCharKind::InString => Some(c),
_ => None,
})
.collect()
}
#[test]
fn test_uncommented() {
assert_eq!(&uncommented("abc/*...*/"), "abc");
assert_eq!(
&uncommented("// .... /* \n../* /* *** / */ */a/* // */c\n"),
"..ac\n"
);
assert_eq!(&uncommented("abc \" /* */\" qsdf"), "abc \" /* */\" qsdf");
}
#[test]
fn test_contains_comment() {
assert_eq!(contains_comment("abc"), false);
assert_eq!(contains_comment("abc // qsdf"), true);
assert_eq!(contains_comment("abc /* kqsdf"), true);
assert_eq!(contains_comment("abc \" /* */\" qsdf"), false);
}
#[test]
fn test_find_uncommented() {
fn check(haystack: &str, needle: &str, expected: Option<usize>) {
assert_eq!(expected, haystack.find_uncommented(needle));
}
check("/*/ */test", "test", Some(6));
check("//test\ntest", "test", Some(7));
check("/* comment only */", "whatever", None);
check(
"/* comment */ some text /* more commentary */ result",
"result",
Some(46),
);
check("sup // sup", "p", Some(2));
check("sup", "x", None);
check(r#"π? /**/ π is nice!"#, r#"π is nice"#, Some(9));
check("/*sup yo? \n sup*/ sup", "p", Some(20));
check("hel/*lohello*/lo", "hello", None);
check("acb", "ab", None);
check(",/*A*/ ", ",", Some(0));
check("abc", "abc", Some(0));
check("/* abc */", "abc", None);
check("/**/abc/* */", "abc", Some(4));
check("\"/* abc */\"", "abc", Some(4));
check("\"/* abc", "abc", Some(4));
}
}<|fim▁end|>
|
struct CharClasses<T>
where
T: Iterator,
T::Item: RichChar,
|
<|file_name|>BasicInstructionPropertyDumper.cpp<|end_file_name|><|fim▁begin|>//===--- BasicInstructionPropertyDumper.cpp -------------------------------===//
//
// This source file is part of the Swift.org open source project
//<|fim▁hole|>//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/SIL/SILFunction.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/SILModule.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/raw_ostream.h"
using namespace swift;
namespace {
class BasicInstructionPropertyDumper : public SILModuleTransform {
void run() override {
for (auto &Fn : *getModule()) {
unsigned Count = 0;
llvm::outs() << "@" << Fn.getName() << "\n";
for (auto &BB : Fn) {
for (auto &I : BB) {
llvm::outs() << "Inst #: " << Count++ << "\n " << I;
llvm::outs() << " Mem Behavior: " << I.getMemoryBehavior() << "\n";
llvm::outs() << " Release Behavior: " << I.getReleasingBehavior()
<< "\n";
}
}
}
}
llvm::StringRef getName() override {
return "BasicInstructionPropertyDumper";
}
};
} // end anonymous namespace
SILTransform *swift::createBasicInstructionPropertyDumper() {
return new BasicInstructionPropertyDumper();
}<|fim▁end|>
|
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
|
<|file_name|>ClientSecretDto.java<|end_file_name|><|fim▁begin|>/*
* Copyright (C) 2018 the original author or authors.
*
* This file is part of jBB Application Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*/
package org.jbb.security.rest.oauth.client;
import io.swagger.annotations.ApiModel;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@Builder
@ApiModel("OAuthClientSecret")
@NoArgsConstructor(access = AccessLevel.PUBLIC)
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class ClientSecretDto {
<|fim▁hole|>
}<|fim▁end|>
|
private String clientSecret;
|
<|file_name|>position.py<|end_file_name|><|fim▁begin|>from django import forms
from faculty.event_types.base import BaseEntryForm
from faculty.event_types.base import CareerEventHandlerBase
from faculty.event_types.choices import Choices
from faculty.event_types.base import TeachingAdjust
from faculty.event_types.fields import TeachingCreditField
from faculty.event_types.mixins import TeachingCareerEvent
from faculty.event_types.search import ChoiceSearchRule
from faculty.event_types.search import ComparableSearchRule
class AdminPositionEventHandler(CareerEventHandlerBase, TeachingCareerEvent):
"""
Given admin position
"""
EVENT_TYPE = 'ADMINPOS'
NAME = 'Admin Position'
TO_HTML_TEMPLATE = """
{% extends "faculty/event_base.html" %}{% load event_display %}{% block dl %}
<dt>Position</dt><dd>{{ handler|get_display:'position' }}</dd>
<dt>Teaching Credit</dt><dd>{{ handler|get_display:'teaching_credit' }}</dd>
{% endblock %}
"""
class EntryForm(BaseEntryForm):
POSITIONS = Choices(
('UGRAD_DIRECTOR', 'Undergrad Program Director'),
('GRAD_DIRECTOR', 'Graduate Program Director'),
('DDP_DIRECTOR', 'Dual-Degree Program Director'),
('ASSOC_DIRECTOR', 'Associate Director/Chair'),
('DIRECTOR', 'School Director/Chair'),
('ASSOC_DEAN', 'Associate Dean'),
('DEAN', 'Dean'),
('OTHER', 'Other Admin Position'),
)
position = forms.ChoiceField(required=True, choices=POSITIONS)
teaching_credit = TeachingCreditField(required=False, initial=None)
SEARCH_RULES = {
'position': ChoiceSearchRule,<|fim▁hole|> 'teaching_credit': ComparableSearchRule,
}
SEARCH_RESULT_FIELDS = [
'position',
'teaching_credit',
]
def get_position_display(self):
return self.EntryForm.POSITIONS.get(self.get_config('position'), 'N/A')
def get_teaching_credit_display(self):
return self.get_config('teaching_credit', default='N/A')
@classmethod
def default_title(cls):
return 'Admin Position'
def short_summary(self):
position = self.get_position_display()
return 'Admin Position: {0}'.format(position)
def teaching_adjust_per_semester(self):
credit = self.get_config('teaching_credit', 0)
return TeachingAdjust(credit, 0)<|fim▁end|>
| |
<|file_name|>shader_param.rs<|end_file_name|><|fim▁begin|>// Copyright 2015 The Gfx-rs Developers.
//
// 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.
use syntax::{abi, ast, codemap, ext};
use syntax::ext::base::ItemDecorator;
use syntax::ext::build::AstBuilder;
use syntax::owned_slice::OwnedSlice;
use syntax::parse::token;
use syntax::ptr::P;
#[derive(Copy, Clone, PartialEq, Debug)]
enum Param {
Uniform,
Block,
Texture,
Special,
}
#[derive(Copy, Clone, Debug)]
enum ParamError {
DeprecatedTexture,
}
/// Classify variable types (`i32`, `TextureParam`, etc) into the `Param`
fn classify(node: &ast::Ty_) -> Result<Param, ParamError> {
match *node {
ast::TyPath(_,ref path) => match path.segments.last() {
Some(segment) => match segment.identifier.name.as_str() {
"RawBuffer" => Ok(Param::Block),
"TextureParam" => Ok(Param::Texture),
"Texture" => Err(ParamError::DeprecatedTexture),
"PhantomData" => Ok(Param::Special),
_ => Ok(Param::Uniform),
},
None => Ok(Param::Uniform),
},
_ => Ok(Param::Uniform),
}
}
/// Generates the the method body for `gfx::shade::ShaderParam::create_link`
fn method_create(cx: &mut ext::base::ExtCtxt,
span: codemap::Span,
definition: &ast::StructDef,
input: ast::Ident,
link_ident: ast::Ident,
path_root: ast::Ident)
-> P<ast::Block> {
let init_expr = cx.expr_struct_ident(
span, link_ident,
definition.fields.iter().scan((), |_, field| {
field.node.ident().map(|name|
cx.field_imm(field.span, name, cx.expr_none(field.span))
)
}).collect()
);
let class_info: Vec<(Param, P<ast::Expr>)> = definition.fields.iter().scan((), |_, field|
match (field.node.ident(), classify(&field.node.ty.node)) {
(None, _) => {
cx.span_err(field.span, "Named fields are required for `ShaderParam`");
None
},
(Some(fname), Ok(c)) => {
let name = match super::find_name(cx, field.span, &field.node.attrs) {
Some(name) => name,
None => token::get_ident(fname),
};
Some((c, cx.expr_str(field.span, name)))
},
(Some(fname), Err(e)) => {
cx.span_err(field.span, &format!(
"Unrecognized parameter ({:?}) type {:?}",
fname.as_str(), e
));
None
},
}
).collect();
let gen_arms = |ptype: Param, var: ast::Ident| -> Vec<ast::Arm> {
class_info.iter().zip(definition.fields.iter())
.filter(|&(&(ref class, _), _)| *class == ptype)
.scan((), |_, (&(_, ref name_expr), field)|
field.node.ident().map(|name| quote_arm!(cx,
$name_expr => {out.$name = Some(i as $path_root::gfx::shade::$var)}
))
).collect()
};
let par_ident = cx.ident_of("ParameterId");
let uniform_arms = gen_arms(Param::Uniform, par_ident);
let block_arms = gen_arms(Param::Block, par_ident);
let texture_arms = gen_arms(Param::Texture, par_ident);
let expr = quote_expr!(cx, {
let mut out = $init_expr;
for (i, u) in $input.uniforms.iter().enumerate() {
let _ = i; // suppress warning about unused i
match &u.name[..] {
$uniform_arms
_ => return Err($path_root::gfx::shade::
ParameterError::MissingUniform(u.name.clone())),
}
}
for (i, b) in $input.blocks.iter().enumerate() {
let _ = i; // suppress warning about unused i
match &b.name[..] {
$block_arms
_ => return Err($path_root::gfx::shade::
ParameterError::MissingBlock(b.name.clone())),
}
}
for (i, t) in $input.textures.iter().enumerate() {
let _ = i; // suppress warning about unused i
match &t.name[..] {
$texture_arms
_ => return Err($path_root::gfx::shade::
ParameterError::MissingTexture(t.name.clone())),
}
}
Ok(out)
});
cx.block_expr(expr)
}
/// Generates the the method body for `gfx::shade::ShaderParam::fill_params`
fn method_fill(cx: &mut ext::base::ExtCtxt,
span: codemap::Span,
definition: &ast::StructDef,
_path_root: ast::Ident)
-> P<ast::Block> {
let max_num = cx.expr_usize(span, definition.fields.len());
let mut calls = vec![
quote_stmt!(cx, out.uniforms.reserve($max_num);),
quote_stmt!(cx, out.blocks.reserve($max_num);),
quote_stmt!(cx, out.textures.reserve($max_num);),
];
calls.extend(definition.fields.iter().scan((), |_, field| {
let name = match field.node.ident() {
Some(n) => n,
None => {
cx.span_err(span, "Named fields are required for `ShaderParam`");
return None
}
};
classify(&field.node.ty.node).ok().map(|param| match param {
Param::Uniform => quote_stmt!(cx,
link.$name.map_or((), |id| {
out.uniforms[id as usize] = Some(self.$name.into());
})
),
Param::Block => quote_stmt!(cx,
link.$name.map_or((), |id| {
out.blocks[id as usize] = Some(self.$name.clone());
})
),
Param::Texture => quote_stmt!(cx,
link.$name.map_or((), |id| {
out.textures[id as usize] = Some(self.$name.clone());
})
),
Param::Special => quote_stmt!(cx, ()),
})
}));
let calls = calls.map_in_place(Option::unwrap);
cx.block_all(span, calls, None)
}
/// A helper function that translates variable type (`i32`, `Texture`, etc)
/// into ParameterId
fn node_to_var_type(cx: &mut ext::base::ExtCtxt,
span: codemap::Span, node: &ast::Ty_,
path_root: ast::Ident) -> P<ast::Ty> {
let id = cx.ident_of(match classify(node) {
Ok(Param::Uniform) | Ok(Param::Block) | Ok(Param::Texture) => "ParameterId",
Ok(Param::Special) => return quote_ty!(cx, Option<()>),
Err(ParamError::DeprecatedTexture) => {
cx.span_err(span, "Use gfx::shade::TextureParam for texture vars instead of gfx::handle::Texture");
""
},
});
quote_ty!(cx, Option<$path_root::gfx::shade::$id>)
}
fn impl_type(cx: &mut ext::base::ExtCtxt, span: codemap::Span,
name: &str, type_ident: ast::Ident) -> ast::ImplItem {
ast::ImplItem {
id: ast::DUMMY_NODE_ID,
ident: cx.ident_of(name),
vis: ast::Visibility::Inherited,
attrs: Vec::new(),
node: ast::TypeImplItem(cx.ty_ident(span, type_ident)),
span: span
}
}
fn impl_method(cx: &mut ext::base::ExtCtxt, span: codemap::Span, name: &str,
with_self: bool, declaration: P<ast::FnDecl>, body: P<ast::Block>)
-> ast::ImplItem {
ast::ImplItem {
id: ast::DUMMY_NODE_ID,
ident: cx.ident_of(name),
vis: ast::Visibility::Inherited,
attrs: Vec::new(),
node: ast::MethodImplItem(
ast::MethodSig {
unsafety: ast::Unsafety::Normal,
abi: abi::Abi::Rust,
decl: declaration,
generics: ast::Generics {
lifetimes: Vec::new(),
ty_params: OwnedSlice::empty(),
where_clause: ast::WhereClause {
id: ast::DUMMY_NODE_ID,
predicates: Vec::new()
}
},
explicit_self: codemap::Spanned {
node: if with_self {
ast::SelfRegion(None, ast::MutImmutable, cx.ident_of("self"))
} else {
ast::SelfStatic
},
span: span
}
},
body
),
span: span
}
}
#[derive(Copy, Clone)]
pub struct ShaderParam;
impl ItemDecorator for ShaderParam {
/// Decorator for `shader_param` attribute
fn expand(&self, context: &mut ext::base::ExtCtxt, span: codemap::Span,
meta_item: &ast::MetaItem, item: &ast::Item,
push: &mut FnMut(P<ast::Item>)) {
// Insert the `gfx` reexport module
let extern_hack = context.ident_of(super::EXTERN_CRATE_HACK);
let path_root = super::extern_crate_hack(context, span, |i| (*push)(i));
// constructing the Link struct
let (base_def, generics, link_def) = match item.node {
ast::ItemStruct(ref definition, ref generics) => {
(definition, generics.clone(), ast::StructDef {
fields: definition.fields.iter()
.map(|f| codemap::Spanned {
node: ast::StructField_ {
kind: f.node.kind,
id: f.node.id,
ty: node_to_var_type(context, f.span, &f.node.ty.node, path_root),
attrs: Vec::new(),
},
span: f.span,
}).collect(),
ctor_id: None,
})
},
_ => {
context.span_err(span, "Only free-standing named structs allowed to derive ShaderParam");
return;
}
};
// derive and push
let link_name = format!("_{}Link", item.ident.as_str());
let link_ident = context.ident_of(&link_name);
let link_item = context.item_struct(span, link_ident, link_def)
.map(|mut litem| {
litem.attrs.push(context.attribute(span,
context.meta_list(span, token::InternedString::new("derive"), vec![
context.meta_word(span, token::InternedString::new("Copy")),
context.meta_word(span, token::InternedString::new("Clone")),
context.meta_word(span, token::InternedString::new("Debug")),
])
));
litem.vis = item.vis;
litem
});
(*push)(link_item);
// process meta parameters (expecting none)
match meta_item.node {
ast::MetaWord(_) => (), //expected
_ => {
context.span_err(meta_item.span, "#[shader_param] needs no param");
}
}
// find the generic `Resources` bound
let resource_ident = match generics.ty_params.iter().find(|typ|
typ.bounds.iter().find(|b| match **b {
ast::TraitTyParamBound(ref poly_trait, _) =>
poly_trait.trait_ref.path.segments.last().unwrap().identifier.as_str() == "Resources",
ast::RegionTyParamBound(_) => false,
}).is_some()<|fim▁hole|> ){
Some(typ) => typ.ident,
None => {
context.span_err(meta_item.span, "#[shader_param] unable to find generic `gfx::Resources` bound");
context.ident_of("R")
}
};
// construct `create_link()`
let lifetimes = generics.lifetimes.iter().map(|ld| ld.lifetime).collect();
let generic_parameters = generics.ty_params.iter().map(|ty|
context.ty_ident(span, ty.ident)
).collect();
let struct_ty = context.ty_path(context.path_all(
span, false,
vec![item.ident],
lifetimes,
generic_parameters,
Vec::new(),
));
let create_param = context.ident_of("params");
let body_create = method_create(context, span, base_def, create_param, link_ident, path_root);
let decl_create = context.fn_decl(
vec![
ast::Arg {
ty: quote_ty!(context, Option<&$struct_ty>),
pat: context.pat_wild(span),
id: ast::DUMMY_NODE_ID,
},
ast::Arg {
ty: quote_ty!(context, &$extern_hack::gfx::ProgramInfo),
pat: context.pat_ident(span, create_param),
id: ast::DUMMY_NODE_ID,
},
],
context.ty_path(context.path_all(
span, false, vec![context.ident_of("Result")],
Vec::new(), vec![
context.ty_ident(span, link_ident),
quote_ty!(context, $extern_hack::gfx::shade::ParameterError),
], Vec::new()
)),
);
// construct `fill_params()`
let body_fill = method_fill(context, span, base_def, path_root);
let decl_fill = context.fn_decl(
vec![
ast::Arg::new_self(span, ast::MutImmutable, context.ident_of("self")),
ast::Arg {
ty: quote_ty!(context, &$link_ident),
pat: context.pat_ident(span, context.ident_of("link")),
id: ast::DUMMY_NODE_ID,
},
ast::Arg {
ty: quote_ty!(context, &mut $extern_hack::gfx::ParamStorage<$resource_ident>),
pat: context.pat_ident(span, context.ident_of("out")),
id: ast::DUMMY_NODE_ID,
},
],
quote_ty!(context, ())
);
// construct implementations for types and methods
let impls = vec![
P(impl_type(context, span, "Resources", resource_ident)),
P(impl_type(context, span, "Link", link_ident)),
P(impl_method(context, span, "create_link", false, decl_create, body_create)),
P(impl_method(context, span, "fill_params", true, decl_fill, body_fill))
];
// final implementation item
let item = context.item(span, item.ident, Vec::new(), ast::Item_::ItemImpl(
ast::Unsafety::Normal,
ast::ImplPolarity::Positive,
generics,
Some(context.trait_ref(context.path(span, vec![
extern_hack,
context.ident_of("gfx"),
context.ident_of("shade"),
context.ident_of("ShaderParam"),
]))),
struct_ty,
impls
));
(*push)(super::fixup_extern_crate_paths(item, path_root));
}
}<|fim▁end|>
| |
<|file_name|>duck_test.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python
class Duck:
"""
this class implies a new way to express polymorphism using duck typing.
This class has 2 functions: quack() and fly() consisting no parameter.
"""
def quack(self):
print("Quack, quack!");
def fly(self):
print("Flap, Flap!");
class Person:
def quack(self):
print("I'm Quackin'!");
def fly(self):
print("I'm Flyin'!");
def in_the_forest(mallard):
""" This function is used for express polymorphism behavior except inheritance """
mallard.quack()
mallard.fly()
duck = Duck()
person = Person()<|fim▁hole|>in_the_forest(Duck())
in_the_forest(Person())<|fim▁end|>
|
# passing object to in_the_forest() function
|
<|file_name|>import_vosa.py<|end_file_name|><|fim▁begin|>import csv
from datetime import datetime
from django.conf import settings
from django.core.management import BaseCommand
from bustimes.utils import download_if_changed
from ...models import Licence, Registration, Variation
def parse_date(date_string):
if date_string:
return datetime.strptime(date_string, '%d/%m/%y').date()
def download_if_modified(path):
url = f"https://content.mgmt.dvsacloud.uk/olcs.prod.dvsa.aws/data-gov-uk-export/{path}"
return download_if_changed(settings.DATA_DIR / path, url)
class Command(BaseCommand):
@staticmethod
def add_arguments(parser):
parser.add_argument('regions', nargs='?', type=str, default="FBCMKGDH")
def get_rows(self, path):
with open(settings.DATA_DIR / path) as open_file:
yield from csv.DictReader(open_file)
def handle(self, regions, **kwargs):
for region in regions:
modified_1, last_modified_1 = download_if_modified(f"Bus_RegisteredOnly_{region}.csv")
modified_2, last_modified_2 = download_if_modified(f"Bus_Variation_{region}.csv")
if modified_1 or modified_2:
print(region, last_modified_1, last_modified_2)
self.handle_region(region)
def handle_region(self, region):
lics = Licence.objects.filter(traffic_area=region)
lics = lics.in_bulk(field_name="licence_number")
lics_to_update = set()
lics_to_create = []
regs = Registration.objects.filter(licence__traffic_area=region)
regs = regs.in_bulk(field_name="registration_number")
regs_to_update = set()
regs_to_create = []
variations = Variation.objects.filter(registration__licence__traffic_area=region)
variations = variations.select_related('registration').all()
variations_dict = {}
for variation in variations:
reg_no = variation.registration.registration_number
if reg_no in variations_dict:
variations_dict[reg_no][variation.variation_number] = variation
else:
variations_dict[reg_no] = {
variation.variation_number: variation
}
# vars_to_update = set()
vars_to_create = []
# previous_line = None
# cardinals = set()
for line in self.get_rows(f"Bus_Variation_{region}.csv"):
reg_no = line["Reg_No"]
var_no = int(line["Variation Number"])
lic_no = line["Lic_No"]
if lic_no in lics:
licence = lics[lic_no]
if licence.id and licence not in lics_to_update:
licence.trading_name = ''
lics_to_update.add(licence)
else:
licence = Licence(licence_number=lic_no)
lics_to_create.append(licence)
lics[lic_no] = licence
licence.name = line['Op_Name']
# a licence can have multiple trading names
if line['trading_name'] not in licence.trading_name:
if licence.trading_name:
licence.trading_name = f"{licence.trading_name}\n{line['trading_name']}"
else:
licence.trading_name = line['trading_name']
if licence.address != line['Address']:
if licence.address:
print(licence.address, line['Address'])
licence.address = line['Address']
if licence.traffic_area:
assert licence.traffic_area == line['Current Traffic Area']
else:
licence.traffic_area = line['Current Traffic Area']
licence.discs = line['Discs in Possession'] or 0
licence.authorised_discs = line['AUTHDISCS'] or 0
licence.description = line['Description']
licence.granted_date = parse_date(line['Granted_Date'])
licence.expiry_date = parse_date(line['Exp_Date'])
if len(reg_no) > 20:
# PK0000098/PK0000098/364
parts = reg_no.split('/')
assert parts[0] == parts[1]
reg_no = f'{parts[1]}/{parts[2]}'
if reg_no in regs:
registration = regs[reg_no]
if registration.id and registration not in regs_to_update:
regs_to_update.add(registration)
else:
registration = Registration(
registration_number=reg_no,
registered=False
)
regs_to_create.append(registration)
regs[reg_no] = registration
registration.licence = licence
status = line['Registration Status']
registration.registration_status = status
if var_no == 0 and status == 'New':
registration.registered = True
elif status == 'Registered':
registration.registered = True
elif status == 'Cancelled' or status == 'Admin Cancelled' or status == 'Cancellation':
registration.registered = False
registration.start_point = line['start_point']
registration.finish_point = line['finish_point']
registration.via = line['via']
registration.subsidies_description = line['Subsidies_Description']
registration.subsidies_details = line['Subsidies_Details']
registration.traffic_area_office_covered_by_area = line['TAO Covered BY Area']
# a registration can have multiple numbers
if registration.service_number:
if line['Service Number'] not in registration.service_number:
registration.service_number = f"{registration.service_number}\n{line['Service Number']}"
else:
registration.service_number = line['Service Number']
# a registration can have multiple types
if registration.service_type_description:
if line['Service_Type_Description'] not in registration.service_type_description:
registration.service_type_description += f"\n{line['Service_Type_Description']}"
else:
registration.service_type_description = line['Service_Type_Description']
if registration.authority_description:
if line['Auth_Description'] not in registration.authority_description:
registration.authority_description += f"\n{line['Auth_Description']}"
if len(registration.authority_description) > 255:
# some National Express coach services cover many authorities
# print(reg_no)
registration.authority_description = registration.authority_description[:255]
else:
registration.authority_description = line['Auth_Description']
# if previous_line:
# if previous_line["Reg_No"] == reg_no:
# if int(previous_line["Variation Number"]) == var_no:
# for key in line:
# prev = previous_line[key]
# value = line[key]
# if prev != value:
# if key not in (
# 'Auth_Description', 'TAO Covered BY Area',
# 'trading_name', 'Pub_Text', 'Registration Status', 'end_date', 'received_date'
# 'effective_date', 'short_notice', 'Service_Type_Description'
# ):
# print(reg_no)
# print(f"'{key}': '{prev}', '{value}'")
# cardinals.add(key)
# # print(line)
variation = Variation(registration=registration, variation_number=var_no)
if reg_no in variations_dict:
if var_no in variations_dict[reg_no]:
continue # ?
else:
variations_dict[reg_no][var_no] = variation
else:
variations_dict[reg_no] = {var_no: variation}
variation.effective_date = parse_date(line['effective_date'])
variation.date_received = parse_date(line['received_date'])
variation.end_date = parse_date(line['end_date'])
variation.service_type_other_details = line['Service_Type_Other_Details']
variation.registration_status = line['Registration Status']
variation.publication_text = line['Pub_Text']
variation.short_notice = line['Short Notice']
assert not variation.id
if not variation.id:
vars_to_create.append(variation)
# previous_line = line
<|fim▁hole|>
# use this file to work out if a registration has not been cancelled/expired
for line in self.get_rows(f"Bus_RegisteredOnly_{region}.csv"):
reg_no = line["Reg_No"]
reg = regs[reg_no]
if reg.registration_status != line["Registration Status"]:
reg.registration_status = line["Registration Status"]
reg.registered = True
# if previous_line and previous_line["Reg_No"] == reg_no:
# for key in line:
# prev = previous_line[key]
# value = line[key]
# if prev != value:
# cardinals.add(key)
# if key == 'TAO Covered BY Area':
# print(prev, value)
# previous_line = line
# print(cardinals)
Licence.objects.bulk_update(
lics_to_update,
["name", "trading_name", "traffic_area", "discs", "authorised_discs",
"description", "granted_date", "expiry_date", "address"]
)
Licence.objects.bulk_create(lics_to_create)
for registration in regs_to_create:
registration.licence = registration.licence
Registration.objects.bulk_update(
regs_to_update,
["start_point", "finish_point", "via",
"subsidies_description", "subsidies_details",
"traffic_area_office_covered_by_area",
"service_number", "service_type_description",
"registration_status", "authority_description",
"registered"],
batch_size=1000
)
Registration.objects.bulk_create(regs_to_create)
Variation.objects.bulk_create(vars_to_create)
# Variation.objects.bulk_update(
# vars_to_update,
# ['date_received', 'end_date', 'service_type_other_details', 'registration_status', 'publication_text',
# 'short_notice']
# )<|fim▁end|>
|
# previous_line = None
# cardinals = set()
|
<|file_name|>watchLoginStatus.tsx<|end_file_name|><|fim▁begin|>import type { TRPGMiddleware } from '@redux/types/__all__';
import constants from '../constants/index';
import type { UserInfo } from '@redux/types/user';
const { LOGIN_SUCCESS, LOGIN_TOKEN_SUCCESS, LOGIN_FAILED } = constants;
/**
* 监听登录状态的变更
* 将其登录结果发送到回调
*/
interface LoginStatusCallback {
onLoginSuccess?: (info: UserInfo) => void;<|fim▁hole|> onLoginFailed?: () => void;
}
export const watchLoginStatus = (cb: LoginStatusCallback): TRPGMiddleware => ({
dispatch,
getState,
}) => (next) => (action) => {
if (action.type === LOGIN_SUCCESS || action.type === LOGIN_TOKEN_SUCCESS) {
cb.onLoginSuccess?.(action.payload);
}
if (action.type === LOGIN_FAILED) {
cb.onLoginFailed?.();
}
next(action);
};<|fim▁end|>
| |
<|file_name|>TeamRepository.ts<|end_file_name|><|fim▁begin|>import Team = require('./Team');<|fim▁hole|> private teams:Team[] = []
teamExists(teamID:string, successCallBack:Function, failCallBack:Function) {
var team:Team = this.getTeam(teamID);
(team != null) ? successCallBack(team) : failCallBack('User not found');
}
public addTeam(team:Team) {
this.teams.push(team);
}
public getTeam(aUUID:string):Team {
for (var i in this.teams) {
var currentTeam = this.teams[i];
if (currentTeam.hasUUID(aUUID)) {
return currentTeam;
}
}
return null;
}
getTeamsByMember(aUserID:string):Team[] {
var teams:Team[] = [];
for (var currentTeamIndex in this.teams) {
var team = this.teams[currentTeamIndex];
if (team.hasMember(aUserID)) {
teams.push(team);
}
}
return teams;
}
hasMember(aUserID:string):boolean {
for (var currentTeamIndex in this.teams) {
var team = this.teams[currentTeamIndex];
if (team.hasMember(aUserID)) {
return true;
}
}
return false;
}
public getDataInJSON():any {
var result:any[] = [];
for (var currentTeamIndex in this.teams) {
var currentTeam = this.teams[currentTeamIndex];
result.push(currentTeam.getDataInJSON());
}
return result;
}
public displayShortState() {
console.log("\n\n+++\t Etat du repository des Teams\t+++");
for (var currentTeamIndex in this.teams) {
var currentTeam = this.teams[currentTeamIndex];
console.log("#", currentTeam.getUUID(), "\t\nLeader:", currentTeam.getLeader().getName(), "\t| \tName : '", currentTeam.getName(), "'\n", "\tMembers:\n", currentTeam.getStringDescriptionOfMembers());
}
}
}
export = TeamRepository;<|fim▁end|>
|
class TeamRepository {
|
<|file_name|>test-extensions.test.ts<|end_file_name|><|fim▁begin|>/* eslint-disable no-console */
import assert from "assert";
import * as fs from "fs";
import * as os from "os";
import * as asyncio from "@azure-tools/async-io";
import * as tasks from "@azure-tools/tasks";
import { ExtensionManager, InvalidPackageIdentityException, UnresolvedPackageException } from "../src";
const tmpFolder = fs.mkdtempSync(`${fs.mkdtempSync(`${os.tmpdir()}/test`)}/install-pkg`);
// Those test do install pacakge and could take a little bit of time. Increasing timeout to 50s.
const TEST_TIMEOUT = 50_000;
describe("TestExtensions", () => {
let extensionManager: ExtensionManager;
beforeEach(async () => {
extensionManager = await ExtensionManager.Create(tmpFolder);
});
afterEach(async () => {
try {
await extensionManager.dispose();
try {
await tasks.Delay(500);
await asyncio.rmdir(tmpFolder);
} catch (E) {
console.error("rmdir is giving grief... [probably intermittent]");
}
} catch (e) {
console.error("ABORTING\n");
console.error(e);
throw "AFTER TEST ABORTED";
}
});
it(
"reset",
async () => {
await extensionManager.reset();
{
console.log("Installing Once");
// install it once
const dni = await extensionManager.findPackage("echo-cli", "*");
const installing = extensionManager.installPackage(dni, false, 60000, (i) => {});
const extension = await installing;
assert.notEqual(await extension.configuration, "the configuration file isnt where it should be?");
}
{
console.log("Attempt Overwrite");
// install/overwrite
const dni = await extensionManager.findPackage("echo-cli", "*");
const installing = extensionManager.installPackage(dni, true, 60000, (i) => {});
// install at the same time?
const dni2 = await extensionManager.findPackage("echo-cli", "*");
const installing2 = extensionManager.installPackage(dni2, true, 60000, (i) => {});
// wait for it.
const extension = await installing;
assert.notEqual(await extension.configuration, "");
const extension2 = await installing2;
assert.notEqual(await extension.configuration, "");
let done = false;
for (const each of await extensionManager.getInstalledExtensions()) {
done = true;
// make sure we have one extension installed and that it is echo-cli (for testing)
assert.equal(each.name, "echo-cli");
}
assert.equal(done, true, "Package is not installed");
//await tasks.Delay(5000);
}
},
TEST_TIMEOUT,
);
/*
@test async 'FindPackage- in github'() {
// github repo style
const npmpkg = await extensionManager.findPackage('npm', 'npm/npm');
assert.equal(npmpkg.name, 'npm');
}
*/
it(
"FindPackage- in npm",
async () => {
const p = await extensionManager.findPackage("autorest");
assert.equal(p.name, "autorest");
},
TEST_TIMEOUT,
);
it(
"FindPackage- unknown package",
async () => {
let threw = false;
try {
const p = await extensionManager.findPackage("koooopasdpasdppasdpa");
} catch (e) {
if (e instanceof UnresolvedPackageException) {
threw = true;
}
}
assert.equal(threw, true, "Expected unknown package to throw UnresolvedPackageException");
},
TEST_TIMEOUT,
);
it(
"BadPackageID- garbage name",
async () => {
let threw = false;
try {
await extensionManager.findPackage("LLLLl", "$DDFOIDFJIODFJ");
} catch (e) {
if (e instanceof InvalidPackageIdentityException) {
threw = true;
}
}
assert.equal(threw, true, "Expected bad package id to throw InvalidPackageIdentityException");
},
TEST_TIMEOUT,
);
it("View Versions", async () => {
// gets a package
const pkg = await extensionManager.findPackage("echo-cli");
// finds out if there are more versions
assert.equal((await pkg.allVersions).length > 5, true);
});
it(
"Install Extension",
async () => {
const dni = await extensionManager.findPackage("echo-cli", "1.0.8");
const installing = extensionManager.installPackage(dni, false, 5 * 60 * 1000, (installing) => {});
const extension = await installing;
assert.notEqual(await extension.configuration, "");
let done = false;
for (const each of await extensionManager.getInstalledExtensions()) {
done = true;
// make sure we have one extension installed and that it is echo-cli (for testing)
assert.equal(each.name, "echo-cli");
}
assert.equal(done, true, "Package is not installed");
},
TEST_TIMEOUT,
);
it(
"Install Extension via star",
async () => {
const dni = await extensionManager.findPackage("echo-cli", "*");
const installing = extensionManager.installPackage(dni, false, 5 * 60 * 1000, (installing) => {});
const extension = await installing;
assert.notEqual(await extension.configuration, "");
let done = false;
for (const each of await extensionManager.getInstalledExtensions()) {
done = true;
// make sure we have one extension installed and that it is echo-cli (for testing)
assert.equal(each.name, "echo-cli");
}
assert.equal(done, true, "Package is not installed");
},
TEST_TIMEOUT,
);
it(<|fim▁hole|> "Force install",
async () => {
const dni = await extensionManager.findPackage("echo-cli", "*");
const installing = extensionManager.installPackage(dni, false, 5 * 60 * 1000, (installing) => {});
const extension = await installing;
assert.notEqual(await extension.configuration, "");
// erase the readme.md file in the installed folder (check if force works to reinstall)
await asyncio.rmFile(await extension.configurationPath);
// reinstall with force!
const installing2 = extensionManager.installPackage(dni, true, 5 * 60 * 1000, (installing) => {});
const extension2 = await installing2;
// is the file back?
assert.notEqual(await extension2.configuration, "");
},
TEST_TIMEOUT,
);
it(
"Test Start",
async () => {
try {
const dni = await extensionManager.findPackage("none", "fearthecowboy/echo-cli");
const installing = extensionManager.installPackage(dni, false, 5 * 60 * 1000, (installing) => {});
const extension = await installing;
assert.notEqual(await extension.configuration, "");
const proc = await extension.start();
await tasks.When(proc, "exit");
} catch (E) {
// oh well...
console.error(E);
assert(false, "FAILED DURING START TEST.");
}
},
TEST_TIMEOUT,
);
});<|fim▁end|>
| |
<|file_name|>datatype-date-format_fr.js<|end_file_name|><|fim▁begin|>/*<|fim▁hole|>Copyright 2012 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add("lang/datatype-date-format_fr",function(a){a.Intl.add("datatype-date-format","fr",{"a":["dim.","lun.","mar.","mer.","jeu.","ven.","sam."],"A":["dimanche","lundi","mardi","mercredi","jeudi","vendredi","samedi"],"b":["janv.","févr.","mars","avr.","mai","juin","juil.","août","sept.","oct.","nov.","déc."],"B":["janvier","février","mars","avril","mai","juin","juillet","août","septembre","octobre","novembre","décembre"],"c":"%a %d %b %Y %H:%M:%S %Z","p":["AM","PM"],"P":["am","pm"],"x":"%d/%m/%y","X":"%H:%M:%S"});},"3.5.0");<|fim▁end|>
|
YUI 3.5.0 (build 5089)
|
<|file_name|>provision.test.tsx<|end_file_name|><|fim▁begin|>/* eslint-env jest */
/*
import * as RPCTypes from '../../constants/types/rpc-gen'
import * as Constants from '../../constants/provision'
import * as Tabs from '../../constants/tabs'
import * as ProvisionGen from '../provision-gen'
import * as RouteTreeGen from '../route-tree-gen'
import HiddenString from '../../util/hidden-string'
import provisionSaga, {_testing} from '../provision'
import {RPCError} from '../../util/errors'
import {createStore, applyMiddleware} from 'redux'
import rootReducer from '../../reducers'
import createSagaMiddleware from 'redux-saga'
jest.mock('../../engine')
jest.mock('../../engine/require')
const noError = new HiddenString('')
// Sets up redux and the provision manager. Starts by making an incoming call into the manager
const makeInit = ({method, payload, initialStore}: {method: string; payload: any; initialStore?: Object}) => {
const {dispatch, getState, sagaMiddleware} = startReduxSaga(initialStore)
const manager = _testing.makeProvisioningManager(false)
const callMap = manager.getCustomResponseIncomingCallMap()
const mockIncomingCall = callMap[method]
if (!mockIncomingCall) {
throw new Error('No call')
}
const response = {error: jest.fn(), result: jest.fn()}
const effect: any = mockIncomingCall(payload as any, response as any)
if (effect) {
// Throws in the generator only, so we have to stash it
let thrown: Error | null = null
sagaMiddleware.run(function*(): IterableIterator<any> {
try {
yield effect
} catch (e) {
thrown = e
}
})
if (thrown) {
throw thrown
}
}
return {
_testing: manager._testing(),
dispatch,
getState,
manager,
response,
}
}
const startReduxSaga = (initialStore?: Object) => {
const sagaMiddleware = createSagaMiddleware({
onError: e => {
throw e
},
})
const store = createStore(rootReducer as any, initialStore, applyMiddleware(sagaMiddleware))
const getState: () => any = store.getState
const dispatch = store.dispatch
sagaMiddleware.run(provisionSaga)
dispatch(RouteTreeGen.createSwitchLoggedIn({loggedIn: true}))
dispatch(RouteTreeGen.createNavigateAppend({path: [Tabs.loginTab]}))
return {
dispatch,
getState,
sagaMiddleware,
}
}
describe('provisioningManagerProvisioning', () => {
const manager = _testing.makeProvisioningManager(false)
const callMap = manager.getCustomResponseIncomingCallMap()
it('cancels are correct', () => {
const keys = ['keybase.1.gpgUi.selectKey', 'keybase.1.loginUi.getEmailOrUsername']
keys.forEach(k => {
const response = {error: jest.fn(), result: jest.fn()}
callMap[k](undefined as any, response)
expect(response.result).not.toHaveBeenCalled()
expect(response.error).toHaveBeenCalledWith({
code: RPCTypes.StatusCode.scinputcanceled,
desc: 'Input canceled',
})
})
})
})
describe('text code happy path', () => {
const incoming = new HiddenString('incomingSecret')
const outgoing = new HiddenString('outgoingSecret')
let init: ReturnType<typeof makeInit>
beforeEach(() => {
init = makeInit({
method: 'keybase.1.provisionUi.DisplayAndPromptSecret',
payload: {phrase: incoming.stringValue()},
})
})
it('init', () => {
const {_testing, response, getState} = init
expect(_testing.stashedResponse['keybase.1.provisionUi.DisplayAndPromptSecret']).toEqual(response)
expect(getState().provision.codePageIncomingTextCode).toEqual(incoming)
expect(getState().provision.error).toEqual(noError)
})
// it('navs to the code page', () => {
// const {getRoutePath} = init
// expect(getRoutePath()).toEqual(I.List([Tabs.loginTab, 'codePage']))
// })
it('submit text code empty throws', () => {
const {dispatch, response} = init
dispatch(ProvisionGen.createSubmitTextCode({phrase: new HiddenString('')}))
expect(response.result).toHaveBeenCalledWith({phrase: 'invalid', secret: null})
expect(response.error).not.toHaveBeenCalled()
})
it('submit text code with spaces works', () => {
const {dispatch, response, getState} = init
dispatch(
ProvisionGen.createSubmitTextCode({
phrase: new HiddenString(' this is a text code\n\nthat works'),
})
)
const good = 'this is a text code that works'
expect(getState().provision.codePageOutgoingTextCode.stringValue()).toEqual(good)
expect(response.result).toHaveBeenCalledWith({phrase: good, secret: null})
expect(response.error).not.toHaveBeenCalled()
})
it('submit text code', () => {
const {response, dispatch, getState} = init
dispatch(ProvisionGen.createSubmitTextCode({phrase: outgoing}))
expect(response.result).toHaveBeenCalledWith({phrase: outgoing.stringValue(), secret: null})
expect(response.error).not.toHaveBeenCalled()<|fim▁hole|> expect(getState().provision.codePageOutgoingTextCode).toEqual(outgoing)
expect(getState().provision.error).toEqual(noError)
expect(getState().config.globalError).toEqual(undefined)
// only submit once
dispatch(ProvisionGen.createSubmitTextCode({phrase: outgoing}))
expect(getState().config.globalError).not.toEqual(undefined)
})
})
describe('text code error path', () => {
const phrase = new HiddenString('incomingSecret')
const error = new HiddenString('anerror')
let init: ReturnType<typeof makeInit>
beforeEach(() => {
init = makeInit({
method: 'keybase.1.provisionUi.DisplayAndPromptSecret',
payload: {phrase: phrase.stringValue(), previousErr: error.stringValue()},
})
})
it('init', () => {
const {_testing, response, getState} = init
expect(_testing.stashedResponse['keybase.1.provisionUi.DisplayAndPromptSecret']).toEqual(response)
expect(getState().provision.codePageIncomingTextCode).toEqual(phrase)
expect(getState().provision.error).toEqual(error)
})
// it("doesn't nav away", () => {
// const {getRoutePath} = init
// expect(getRoutePath()).toEqual(I.List([Tabs.loginTab]))
// })
it('submit clears error and submits', () => {
const {response, getState, dispatch} = init
const reply = new HiddenString('reply')
dispatch(ProvisionGen.createSubmitTextCode({phrase: reply}))
expect(getState().provision.error).toEqual(noError)
expect(response.result).toHaveBeenCalledWith({phrase: reply.stringValue(), secret: null})
expect(response.error).not.toHaveBeenCalled()
expect(getState().config.globalError).toEqual(undefined)
// only submit once
dispatch(ProvisionGen.createSubmitTextCode({phrase: reply}))
expect(getState().config.globalError).not.toEqual(undefined)
})
})
describe('device name empty', () => {
const existingDevices: Array<string> = []
const init = makeInit({
method: 'keybase.1.provisionUi.PromptNewDeviceName',
payload: {errorMessage: '', existingDevices: null},
})
const {getState}: {getState: () => any} = init
expect(getState().provision.existingDevices).toEqual(existingDevices)
expect(getState().provision.error).toEqual(noError)
})
describe('device name happy path', () => {
const existingDevices = ['dev1', 'dev2', 'dev3']
let init: ReturnType<typeof makeInit>
beforeEach(() => {
init = makeInit({
method: 'keybase.1.provisionUi.PromptNewDeviceName',
payload: {errorMessage: '', existingDevices: existingDevices},
})
})
it('init', () => {
const {getState} = init
expect(getState().provision.existingDevices).toEqual(existingDevices)
expect(getState().provision.error).toEqual(noError)
})
// it('navs to device name page', () => {
// const {getRoutePath} = init
// expect(getRoutePath()).toEqual(I.List([Tabs.loginTab, 'setPublicName']))
// })
it('submit', () => {
const {response, getState, dispatch} = init
const name = 'new name'
dispatch(ProvisionGen.createSubmitDeviceName({name}))
expect(response.result).toHaveBeenCalledWith(name)
expect(response.error).not.toHaveBeenCalled()
expect(getState().config.globalError).toEqual(undefined)
dispatch(ProvisionGen.createSubmitDeviceName({name}))
expect(getState().config.globalError).not.toEqual(undefined)
})
})
describe('device name error path', () => {
const existingDevices: Array<string> = []
const error = new HiddenString('invalid name')
let init: ReturnType<typeof makeInit>
beforeEach(() => {
init = makeInit({
method: 'keybase.1.provisionUi.PromptNewDeviceName',
payload: {errorMessage: error.stringValue(), existingDevices: existingDevices},
})
})
it('init', () => {
const {getState} = init
expect(getState().provision.existingDevices).toEqual(existingDevices)
expect(getState().provision.error).toEqual(error)
})
// it("doesn't nav away", () => {
// const {getRoutePath} = init
// expect(getRoutePath()).toEqual(I.List([Tabs.loginTab]))
// })
it('update name and submit clears error and submits', () => {
const {response, getState, dispatch} = init
const name = 'new name'
dispatch(ProvisionGen.createSubmitDeviceName({name}))
expect(getState().provision.error).toEqual(noError)
expect(response.result).toHaveBeenCalledWith(name)
expect(response.error).not.toHaveBeenCalled()
expect(getState().config.globalError).toEqual(undefined)
// only submit once
dispatch(ProvisionGen.createSubmitDeviceName({name}))
expect(getState().config.globalError).not.toEqual(undefined)
})
})
describe('other device happy path', () => {
const mobile = {deviceID: '0', name: 'mobile', type: 'mobile'} as any
const desktop = {deviceID: '1', name: 'desktop', type: 'desktop'} as any
const backup = {deviceID: '2', name: 'backup', type: 'backup'} as any
const rpcDevices = [mobile, desktop, backup]
const devices = rpcDevices.map(Constants.rpcDeviceToDevice)
let init: ReturnType<typeof makeInit>
beforeEach(() => {
init = makeInit({
method: 'keybase.1.provisionUi.chooseDevice',
payload: {devices: rpcDevices},
})
})
it('init', () => {
const {getState} = init
expect(getState().provision.devices).toEqual(devices)
expect(getState().provision.error).toEqual(noError)
})
// it('navs to device page', () => {
// const {getRoutePath} = init
// expect(getRoutePath()).toEqual(I.List([Tabs.loginTab, 'selectOtherDevice']))
// })
it('submit mobile', () => {
const {response, getState, dispatch} = init
dispatch(ProvisionGen.createSubmitDeviceSelect({name: mobile.name}))
expect(getState().provision.codePageOtherDevice.id).toEqual(mobile.deviceID)
expect(getState().provision.codePageOtherDevice.type).toEqual('mobile')
expect(getState().provision.error).toEqual(noError)
expect(getState().config.globalError).toEqual(undefined)
expect(response.result).toHaveBeenCalledWith(mobile.deviceID)
expect(response.error).not.toHaveBeenCalled()
// only submit once
dispatch(ProvisionGen.createSubmitDeviceSelect({name: mobile.name}))
expect(getState().config.globalError).not.toEqual(undefined)
})
it('submit desktop', () => {
const {response, getState, dispatch} = init
dispatch(ProvisionGen.createSubmitDeviceSelect({name: desktop.name}))
expect(getState().provision.codePageOtherDevice.id).toEqual(desktop.deviceID)
expect(getState().provision.codePageOtherDevice.type).toEqual('desktop')
expect(getState().provision.error).toEqual(noError)
expect(getState().config.globalError).toEqual(undefined)
expect(response.result).toHaveBeenCalledWith(desktop.deviceID)
expect(response.error).not.toHaveBeenCalled()
// only submit once
dispatch(ProvisionGen.createSubmitDeviceSelect({name: desktop.name}))
expect(getState().config.globalError).not.toEqual(undefined)
})
it('submit paperkey/backup', () => {
const {response, getState, dispatch} = init
dispatch(ProvisionGen.createSubmitDeviceSelect({name: backup.name}))
expect(getState().provision.codePageOtherDevice.id).toEqual(backup.deviceID)
expect(getState().provision.codePageOtherDevice.type).toEqual('backup')
expect(getState().provision.error).toEqual(noError)
expect(getState().config.globalError).toEqual(undefined)
expect(response.result).toHaveBeenCalledWith(backup.deviceID)
expect(response.error).not.toHaveBeenCalled()
// only submit once
dispatch(ProvisionGen.createSubmitDeviceSelect({name: backup.name}))
expect(getState().config.globalError).not.toEqual(undefined)
})
it('doesnt allow unknown', () => {
const {dispatch} = init
expect(() => dispatch(ProvisionGen.createSubmitDeviceSelect({name: 'not there'}))).toThrow()
})
})
describe('other device error path', () => {
let init: ReturnType<typeof makeInit>
beforeEach(() => {
// daemon should never do this
init = makeInit({
method: 'keybase.1.provisionUi.chooseDevice',
payload: {devices: null},
})
})
it('init', () => {
const {getState} = init
expect(getState().provision.devices).toEqual([])
expect(getState().provision.error).toEqual(noError)
})
})
describe('other device no devices', () => {
let init: ReturnType<typeof makeInit>
const rpcDevices = null
beforeEach(() => {
init = makeInit({
method: 'keybase.1.provisionUi.chooseDevice',
payload: {devices: rpcDevices},
})
})
it('init', () => {
const {getState} = init
expect(getState().provision.devices).toEqual([])
expect(getState().provision.error).toEqual(noError)
})
})
describe('choose gpg happy path', () => {
let init: ReturnType<typeof makeInit>
beforeEach(() => {
init = makeInit({
method: 'keybase.1.provisionUi.chooseGPGMethod',
payload: {},
})
})
it('init', () => {
const {getState} = init
expect(getState().provision.error.stringValue()).toEqual('')
})
// it('navs to the gpg page', () => {
// const {getRoutePath} = init
// expect(getRoutePath()).toEqual(I.List([Tabs.loginTab, 'gpgSign']))
// })
it('no submit on error', () => {
const {response, dispatch} = init
// shouldn't really be possible, but inject an error
dispatch(ProvisionGen.createShowPaperkeyPage({error: new HiddenString('something')}))
dispatch(ProvisionGen.createSubmitGPGMethod({exportKey: true}))
expect(response.result).not.toHaveBeenCalled()
expect(response.error).not.toHaveBeenCalled()
})
it('submit export key', () => {
const {response, getState, dispatch} = init
dispatch(ProvisionGen.createSubmitGPGMethod({exportKey: true}))
expect(response.result).toHaveBeenCalledWith(RPCTypes.GPGMethod.gpgImport)
expect(response.error).not.toHaveBeenCalled()
expect(getState().config.globalError).toEqual(undefined)
// only submit once
dispatch(ProvisionGen.createSubmitGPGMethod({exportKey: true}))
expect(getState().config.globalError).not.toEqual(undefined)
})
it('submit sign key', () => {
const {response, getState, dispatch} = init
dispatch(ProvisionGen.createSubmitGPGMethod({exportKey: false}))
expect(response.result).toHaveBeenCalledWith(RPCTypes.GPGMethod.gpgSign)
expect(response.error).not.toHaveBeenCalled()
expect(getState().config.globalError).toEqual(undefined)
// only submit once
dispatch(ProvisionGen.createSubmitGPGMethod({exportKey: false}))
expect(getState().config.globalError).not.toEqual(undefined)
})
})
describe('password happy path', () => {
let init: ReturnType<typeof makeInit>
beforeEach(() => {
init = makeInit({
method: 'keybase.1.secretUi.getPassphrase',
payload: {
pinentry: {
retryLabel: null,
type: RPCTypes.PassphraseType.passPhrase,
},
},
})
})
it('init', () => {
const {getState} = init
expect(getState().provision.error).toEqual(noError)
})
// it('navs to password page', () => {
// const {getRoutePath} = init
// expect(getRoutePath()).toEqual(I.List([Tabs.loginTab, 'password']))
// })
it('submit', () => {
const {response, getState, dispatch} = init
const password = new HiddenString('a password')
dispatch(ProvisionGen.createSubmitPassword({password}))
expect(response.result).toHaveBeenCalledWith({passphrase: password.stringValue(), storeSecret: false})
expect(response.error).not.toHaveBeenCalled()
expect(getState().config.globalError).toEqual(undefined)
// only submit once
dispatch(ProvisionGen.createSubmitPassword({password}))
expect(getState().config.globalError).not.toEqual(undefined)
})
})
describe('passphrase error path', () => {
const error = new HiddenString('invalid passphrase')
let init: ReturnType<typeof makeInit>
beforeEach(() => {
init = makeInit({
method: 'keybase.1.secretUi.getPassphrase',
payload: {
pinentry: {
retryLabel: error.stringValue(),
type: RPCTypes.PassphraseType.passPhrase,
},
},
})
})
it('init', () => {
const {getState} = init
expect(getState().provision.error).toEqual(error)
})
// it("doesn't nav away", () => {
// const {getRoutePath} = init
// expect(getRoutePath()).toEqual(I.List([Tabs.loginTab]))
// })
it('submit clears error and submits', () => {
const {response, getState, dispatch} = init
const password = new HiddenString('a password')
dispatch(ProvisionGen.createSubmitPassword({password}))
expect(getState().provision.error).toEqual(noError)
expect(response.result).toHaveBeenCalledWith({passphrase: password.stringValue(), storeSecret: false})
expect(response.error).not.toHaveBeenCalled()
expect(getState().config.globalError).toEqual(undefined)
// only submit once
dispatch(ProvisionGen.createSubmitPassword({password}))
expect(getState().config.globalError).not.toEqual(undefined)
})
})
describe('paperkey happy path', () => {
let init: ReturnType<typeof makeInit>
beforeEach(() => {
init = makeInit({
method: 'keybase.1.secretUi.getPassphrase',
payload: {
pinentry: {
retryLabel: null,
type: RPCTypes.PassphraseType.paperKey,
},
},
})
})
it('init', () => {
const {getState} = init
expect(getState().provision.error).toEqual(noError)
})
// it('navs to paperkey page', () => {
// const {getRoutePath} = init
// expect(getRoutePath()).toEqual(I.List([Tabs.loginTab, 'paperkey']))
// })
it('submit', () => {
const {response, getState, dispatch} = init
const paperkey = new HiddenString('one two three four five six seven eight')
dispatch(ProvisionGen.createSubmitPaperkey({paperkey}))
expect(response.result).toHaveBeenCalledWith({passphrase: paperkey.stringValue(), storeSecret: false})
expect(response.error).not.toHaveBeenCalled()
expect(getState().config.globalError).toEqual(undefined)
// only submit once
dispatch(ProvisionGen.createSubmitPaperkey({paperkey}))
expect(getState().config.globalError).not.toEqual(undefined)
})
})
describe('paperkey error path', () => {
const error = new HiddenString('invalid paperkey')
let init: ReturnType<typeof makeInit>
beforeEach(() => {
init = makeInit({
method: 'keybase.1.secretUi.getPassphrase',
payload: {
pinentry: {
retryLabel: error.stringValue(),
type: RPCTypes.PassphraseType.paperKey,
},
},
})
})
it('init', () => {
const {getState} = init
expect(getState().provision.error).toEqual(error)
})
// it("doesn't nav away", () => {
// const {getRoutePath} = init
// expect(getRoutePath()).toEqual(I.List([Tabs.loginTab]))
// })
it('submit clears error and submits', () => {
const {response, getState, dispatch} = init
const paperkey = new HiddenString('eight seven six five four three two one')
dispatch(ProvisionGen.createSubmitPaperkey({paperkey}))
expect(getState().provision.error).toEqual(noError)
expect(response.result).toHaveBeenCalledWith({passphrase: paperkey.stringValue(), storeSecret: false})
expect(response.error).not.toHaveBeenCalled()
expect(getState().config.globalError).toEqual(undefined)
// only submit once
dispatch(ProvisionGen.createSubmitPaperkey({paperkey}))
expect(getState().config.globalError).not.toEqual(undefined)
})
})
describe('canceling provision', () => {
it('ignores other paths', () => {
// you can't be on other paths in the login tab space
})
// it('cancels', () => {
// const {dispatch, response, manager} = makeInit({
// method: 'keybase.1.provisionUi.DisplayAndPromptSecret',
// payload: {phrase: 'aaa'},
// })
// dispatch(RouteTreeGen.createNavigateUp())
// expect(response.result).not.toHaveBeenCalled()
// expect(response.error).toHaveBeenCalledWith({
// code: RPCTypes.StatusCode.scinputcanceled,
// desc: 'Input canceled',
// })
// expect(manager._stashedResponse).toEqual(null)
// expect(manager._stashedResponseKey).toEqual(null)
// })
// it('clears errors', () => {
// const {dispatch, getState} = makeInit({
// method: 'keybase.1.provisionUi.DisplayAndPromptSecret',
// payload: {phrase: 'aaa'},
// })
// const error = new HiddenString('generic error')
// dispatch(ProvisionGen.createProvisionError({error}))
// dispatch(RouteTreeGen.createNavigateUp())
// expect(getState().provision.error).toEqual(noError)
// expect(getState().provision.finalError).toEqual(null)
// })
})
describe('start the whole process', () => {
const {getState, dispatch} = startReduxSaga()
const error = new HiddenString('generic error')
dispatch(ProvisionGen.createProvisionError({error}))
dispatch(ProvisionGen.createStartProvision())
expect(getState().provision).toEqual(Constants.makeState())
// expect(getRoutePath()).toEqual(I.List([Tabs.loginTab, 'username']))
})
describe('Submit user email', () => {
const {getState, dispatch} = startReduxSaga()
const action = ProvisionGen.createSubmitUsername({username: '[email protected]'})
dispatch(action)
expect(getState().provision.username).toEqual(action.payload.username)
expect(getState().provision.error).toEqual(noError)
expect(getState().provision.finalError).toEqual(undefined)
})
describe('generic errors show', () => {
it('shows error', () => {
const {getState, dispatch} = startReduxSaga()
const error = new HiddenString('generic error')
dispatch(ProvisionGen.createProvisionError({error}))
expect(getState().provision.error).toEqual(error)
})
})
describe('final errors show', () => {
it('shows the final error page', () => {
const {getState, dispatch} = startReduxSaga()
const error = new RPCError('something bad happened', 1, [])
dispatch(ProvisionGen.createShowFinalErrorPage({finalError: error, fromDeviceAdd: false}))
expect(getState().provision.finalError).toBeTruthy()
// expect(getRoutePath()).toEqual(I.List([Tabs.loginTab, 'error']))
})
it('ignore cancel', () => {
const {getState, dispatch} = startReduxSaga()
const error = new RPCError('Input canceled', RPCTypes.StatusCode.scinputcanceled)
dispatch(ProvisionGen.createShowFinalErrorPage({finalError: error, fromDeviceAdd: false}))
expect(getState().provision.finalError).toEqual(undefined)
// expect(getRoutePath()).toEqual(I.List([Tabs.loginTab]))
})
it('shows the final error page (devices add)', () => {
const {getState, dispatch} = startReduxSaga()
dispatch(RouteTreeGen.createSwitchLoggedIn({loggedIn: true}))
dispatch(RouteTreeGen.createNavigateAppend({path: [Tabs.devicesTab]}))
// expect(getRoutePath()).toEqual(I.List([Tabs.devicesTab]))
const error = new RPCError('something bad happened', 1, [])
dispatch(ProvisionGen.createShowFinalErrorPage({finalError: error, fromDeviceAdd: true}))
expect(getState().provision.finalError).toBeTruthy()
// expect(getRoutePath()).toEqual(I.List([Tabs.devicesTab, 'error']))
})
it('ignore cancel (devices add)', () => {
const {getState, dispatch} = startReduxSaga()
dispatch(RouteTreeGen.createSwitchLoggedIn({loggedIn: true}))
dispatch(RouteTreeGen.createNavigateAppend({path: [Tabs.devicesTab]}))
const error = new RPCError('Input canceled', RPCTypes.StatusCode.scinputcanceled)
dispatch(ProvisionGen.createShowFinalErrorPage({finalError: error, fromDeviceAdd: true}))
expect(getState().provision.finalError).toEqual(undefined)
// expect(getRoutePath()).toEqual(I.List([Tabs.devicesTab]))
})
})
describe('reset works', () => {
const {getState, dispatch} = startReduxSaga()
dispatch({payload: {}, type: 'common:resetStore'})
expect(getState().provision).toEqual(Constants.makeState())
})
*/
export default {}<|fim▁end|>
| |
<|file_name|>messageAction.js<|end_file_name|><|fim▁begin|>import { Template } from 'meteor/templating';
Template.messageAction.helpers({
isButton() {
return this.type === 'button';
},
areButtonsHorizontal() {
return Template.parentData(1).button_alignment === 'horizontal';
},
jsActionButtonClassname(processingType) {
return `js-actionButton-${ processingType || 'sendMessage' }`;<|fim▁hole|> },
});<|fim▁end|>
| |
<|file_name|>index.js<|end_file_name|><|fim▁begin|><|fim▁hole|>import { AppHeader, AppFooter } from "../App";
import config from "../../../config";
import { fromJS } from "immutable";
import Spinner from "react-spinner";
import { PlaylistNavBar } from "../../components/PlaylistNavBar";
export class LoadingMoment extends Component {
constructor(props) {
super(props);
this.state = { story: null, momentId: 0, storyMomentList: [] };
}
async componentDidMount() {
let path = this.props.location.pathname;
let storyId = path.split("/")[3];
let momentId = path.split("/")[5];
let storyMomentList = [];
const response = await fetch(`${config.apiEntry}/api/stories/${storyId}`);
let storyObj = await response.json();
let momentList = fromJS(storyObj.momentList);
momentList.forEach((m) => storyMomentList.push(m));
this.setState({
story: storyObj,
momentId: momentId,
storyMomentList: storyMomentList,
});
this.props.history.push(`/stories/story/${storyId}/moment/${momentId}`);
}
render() {
return (
<div className="app-container">
<AppHeader />
<PlaylistNavBar
currentStory={this.state.story}
currentMomentId={this.state.momentId}
moments={this.state.storyMomentList}
history={this.props.history}
/>
<div className="text-center lead">
<p>Loading moment...</p>
<Spinner />
</div>
<AppFooter />
</div>
);
}
}<|fim▁end|>
|
import React, { Component } from "react";
|
<|file_name|>google-cloud-spanner.d.ts<|end_file_name|><|fim▁begin|>/*
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.
*/
// Based on reading the cocde in:
// https://github.com/GoogleCloudPlatform/google-cloud-node/blob/master/packages/spanner/src/index.js
declare module '@google-cloud/spanner' {
import * as stream from 'stream';
namespace spanner {
export interface Query {
sql: string;
}
export interface SpannerDate {
// A fake field to make this type unique: fake nominal typing using npm namespace.
__type__: '@google-cloud/spanner:SpannerDate';
}
export interface SpannerFloat {
// A fake field to make this type unique: fake nominal typing using npm namespace.
__type__: '@google-cloud/spanner:SpannerFloat';
}
export interface SpannerInt {
// A fake field to make this type unique: fake nominal typing using npm namespace.
__type__: '@google-cloud/spanner:SpannerInt';
}
export interface SpannerTimestamp {
// A fake field to make this type unique: fake nominal typing using npm namespace.
__type__: '@google-cloud/spanner:SpannerTimestamp';
}
export interface SpannerBytes {
// A fake field to make this type unique: fake nominal typing using npm namespace.
__type__: '@google-cloud/spanner:SpannerBytes';
}
export type InputField = string | null | SpannerDate | SpannerFloat
| SpannerInt | SpannerTimestamp | SpannerBytes;
export interface InputRow {
[columnKey:string] : InputField;
}
export interface Table {
insert(rows:InputRow[]): Promise<void>;
deleteRows(rowKeys:string[] | string[][]) : Promise<void>;
update(rows:InputRow[]) : Promise<void>;
}
// The value representation chosen here by the spanner nodejs client
// library is pretty surprising: INT64s are converted into
// Objects with a value field that is the string representation of the number.
// Strings on the other hand are just strings.
export type ResultValue = { value: string }
// TODO(yiqingh): decompose ResultField into subtypes.
export type ResultField = string | ResultValue | null | Date | Uint8Array | string[];
// Rows and Columns (Fields) in that row.
export type ResultRow = Array<{ name:string; value: ResultField }>
export type QueryResult = ResultRow[];
type StreamingQuery = stream.Readable;
// export interface StreamingQuery {
// on(kind:'error', f: (e:Error) => void) : void;
// on(kind:'data', f: (row:ResultRow) => void) : void;
// on(kind:'end', f: () => void) : void;
// }
export interface Database {
table(tableName:string): Table;
run(query:Query):Promise<QueryResult[]>;
// runStream(query:Query): StreamingQuery;
runStream(query:Query): stream.Readable;
close(cb ?: () => void) : void;
}
export interface DatabaseOptions {
keepAlive: number; // number of minutes between pings to the DB.
}
export interface Instance {
database(databaseName:string, opts ?: DatabaseOptions) : Database;
}
export interface Spanner {
instance(instanceId:string): Instance;
}
// TODO(ldixon): define spanner date.
export interface ListInstancesQuery {
autoPaginate: boolean; // Default true
filter: string; // Filter method to select instances
maxApiCalls: number;
pageSize: number;
pageToken: string;
}
export interface ListInstancesResponse {
err: Error;
instances: Instance[];
apiResponse: Object;
}
export interface Operation {}
export interface SpannerInit {
(params: { projectId: string }): Spanner;
date(x: string | Date | null) : SpannerDate;
timestamp(x: string | Date | null) : SpannerTimestamp;
float(x: number | string | null) : SpannerFloat;
int(x: number | string | null) : SpannerInt;
bytes(x: number | string | null) : SpannerBytes;
//
createInstance(name: string, config : Object) : Promise<void>;
// https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.InstanceAdmin.ListInstances
getInstances(query: ListInstancesQuery) : Promise<void>;
operation(name:string): Operation;
}
}<|fim▁hole|> var spanner: spanner.SpannerInit;
export = spanner;
}<|fim▁end|>
| |
<|file_name|>email_mirror.py<|end_file_name|><|fim▁begin|>"""Cron job implementation of Zulip's incoming email gateway's helper
for forwarding emails into Zulip.
https://zulip.readthedocs.io/en/latest/production/email-gateway.html
The email gateway supports two major modes of operation: An email
server (using postfix) where the email address configured in
EMAIL_GATEWAY_PATTERN delivers emails directly to Zulip, and this, a
cron job that connects to an IMAP inbox (which receives the emails)
periodically.<|fim▁hole|>connect to your IMAP server and batch-process all messages.
We extract and validate the target stream from information in the
recipient address and retrieve, forward, and archive the message.
"""
import email
import email.policy
import logging
from email.message import EmailMessage
from imaplib import IMAP4_SSL
from typing import Any, Generator
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from zerver.lib.email_mirror import logger, process_message
## Setup ##
log_format = "%(asctime)s: %(message)s"
logging.basicConfig(format=log_format)
formatter = logging.Formatter(log_format)
file_handler = logging.FileHandler(settings.EMAIL_MIRROR_LOG_PATH)
file_handler.setFormatter(formatter)
logger.setLevel(logging.DEBUG)
logger.addHandler(file_handler)
def get_imap_messages() -> Generator[EmailMessage, None, None]:
mbox = IMAP4_SSL(settings.EMAIL_GATEWAY_IMAP_SERVER, settings.EMAIL_GATEWAY_IMAP_PORT)
mbox.login(settings.EMAIL_GATEWAY_LOGIN, settings.EMAIL_GATEWAY_PASSWORD)
try:
mbox.select(settings.EMAIL_GATEWAY_IMAP_FOLDER)
try:
status, num_ids_data = mbox.search(None, 'ALL')
for message_id in num_ids_data[0].split():
status, msg_data = mbox.fetch(message_id, '(RFC822)')
assert isinstance(msg_data[0], tuple)
msg_as_bytes = msg_data[0][1]
message = email.message_from_bytes(msg_as_bytes, policy=email.policy.default)
# https://github.com/python/typeshed/issues/2417
assert isinstance(message, EmailMessage)
yield message
mbox.store(message_id, '+FLAGS', '\\Deleted')
mbox.expunge()
finally:
mbox.close()
finally:
mbox.logout()
class Command(BaseCommand):
help = __doc__
def handle(self, *args: Any, **options: str) -> None:
# We're probably running from cron, try to batch-process mail
if (not settings.EMAIL_GATEWAY_BOT or not settings.EMAIL_GATEWAY_LOGIN or
not settings.EMAIL_GATEWAY_PASSWORD or not settings.EMAIL_GATEWAY_IMAP_SERVER or
not settings.EMAIL_GATEWAY_IMAP_PORT or not settings.EMAIL_GATEWAY_IMAP_FOLDER):
raise CommandError("Please configure the email mirror gateway in /etc/zulip/, "
"or specify $ORIGINAL_RECIPIENT if piping a single mail.")
for message in get_imap_messages():
process_message(message)<|fim▁end|>
|
Run this in a cronjob every N minutes if you have configured Zulip to
poll an external IMAP mailbox for messages. The script will then
|
<|file_name|>test_xlog_cleanup.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
"""
Copyright (c) 2004-Present Pivotal Software, Inc.
This program and the accompanying materials are made available under
the terms of the 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 gppylib.commands.base import Command
from gppylib.db import dbconn
from tinctest import logger
from mpp.lib.PSQL import PSQL
from mpp.models import MPPTestCase
from mpp.gpdb.tests.storage.walrepl import lib as walrepl
import mpp.gpdb.tests.storage.walrepl.run
import os
import shutil
import subprocess
class basebackup_cases(mpp.gpdb.tests.storage.walrepl.run.StandbyRunMixin, MPPTestCase):
def tearDown(self):
super(basebackup_cases, self).tearDown()
self.reset_fault('base_backup_post_create_checkpoint')
def run_gpfaultinjector(self, fault_type, fault_name):
cmd_str = 'gpfaultinjector -s 1 -y {0} -f {1}'.format(
fault_type, fault_name)
cmd = Command(cmd_str, cmd_str)
cmd.run()
return cmd.get_results()
def resume(self, fault_name):
return self.run_gpfaultinjector('resume', fault_name)
def suspend_at(self, fault_name):
return self.run_gpfaultinjector('suspend', fault_name)
def reset_fault(self, fault_name):
return self.run_gpfaultinjector('reset', fault_name)
def fault_status(self, fault_name):
return self.run_gpfaultinjector('status', fault_name)
def wait_triggered(self, fault_name):
search = "fault injection state:'triggered'"
for i in walrepl.polling(10, 3):
result = self.fault_status(fault_name)
stdout = result.stdout
if stdout.find(search) > 0:
return True
return False
def test_xlogcleanup(self):
"""
Test for verifying if xlog seg created while basebackup
dumps out data does not get cleaned
"""
shutil.rmtree('base', True)
PSQL.run_sql_command('DROP table if exists foo')
# Inject fault at post checkpoint create (basebackup)
logger.info ('Injecting base_backup_post_create_checkpoint fault ...')
result = self.suspend_at(
'base_backup_post_create_checkpoint')
logger.info(result.stdout)
self.assertEqual(result.rc, 0, result.stdout)
# Now execute basebackup. It will be blocked due to the
# injected fault.
logger.info ('Perform basebackup with xlog & recovery.conf...')
pg_basebackup = subprocess.Popen(['pg_basebackup', '-x', '-R', '-D', 'base']
, stdout = subprocess.PIPE
, stderr = subprocess.PIPE)
# Give basebackup a moment to reach the fault &
# trigger it
logger.info('Check if suspend fault is hit ...')
triggered = self.wait_triggered(
'base_backup_post_create_checkpoint')
self.assertTrue(triggered, 'Fault was not triggered')
# Perform operations that causes xlog seg generation
logger.info ('Performing xlog seg generation ...')
count = 0
while (count < 10):
PSQL.run_sql_command('select pg_switch_xlog(); select pg_switch_xlog(); checkpoint;')
count = count + 1
# Resume basebackup
result = self.resume('base_backup_post_create_checkpoint')
logger.info(result.stdout)
self.assertEqual(result.rc, 0, result.stdout)
# Wait until basebackup end
logger.info('Waiting for basebackup to end ...')
sql = "SELECT count(*) FROM pg_stat_replication"
with dbconn.connect(dbconn.DbURL(), utility=True) as conn:
while (True):
curs = dbconn.execSQL(conn, sql)<|fim▁hole|>
# Verify if basebackup completed successfully
# See if recovery.conf exists (Yes - Pass)
self.assertTrue(os.path.exists(os.path.join('base','recovery.conf')))
logger.info ('Found recovery.conf in the backup directory.')
logger.info ('Pass')<|fim▁end|>
|
results = curs.fetchall()
if (int(results[0][0]) == 0):
break;
|
<|file_name|>multihmatrix.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# coding: utf-8
import os,sys
import ctypes
import numpy as np
from .hmatrix import _C_HMatrix, HMatrix
class _C_MultiHMatrix(ctypes.Structure):
"""Holder for the raw data from the C++ code."""
pass
class AbstractMultiHMatrix:
"""Common code for the two actual MultiHMatrix classes below."""
ndim = 2 # To mimic a numpy 2D array
def __init__(self, c_data: _C_MultiHMatrix, **params):
# Users should use one of the two constructors below.
self.c_data = c_data
self.shape = (self.lib.multi_nbrows(c_data), self.lib.multi_nbcols(c_data))
self.size = self.lib.nbhmats(c_data)
self.lib.getHMatrix.restype=ctypes.POINTER(_C_HMatrix)
self.lib.getHMatrix.argtypes=[ctypes.POINTER(_C_MultiHMatrix), ctypes.c_int]
self.hmatrices = []
for l in range(0,self.size):
c_data_hmatrix = self.lib.getHMatrix(self.c_data,l)
self.hmatrices.append(HMatrix(c_data_hmatrix,**params))
self.params = params.copy()
@classmethod
def from_coefs(cls, getcoefs, nm, points_target, points_source=None, **params):
"""Construct an instance of the class from a evaluation function.
<|fim▁hole|> points_target: np.ndarray of shape (N, 3)
The coordinates of the target points. If points_source=None, also the coordinates of the target points
points_source: np.ndarray of shape (N, 3)
If not None; the coordinates of the source points.
epsilon: float, keyword-only, optional
Tolerance of the Adaptive Cross Approximation
eta: float, keyword-only, optional
Criterion to choose the blocks to compress
minclustersize: int, keyword-only, optional
Minimum shape of a block
maxblocksize: int, keyword-only, optional
Maximum number of coefficients in a block
Returns
-------
MultiHMatrix or ComplexMultiHMatrix
"""
# Set params.
cls._set_building_params(**params)
# Boilerplate code for Python/C++ interface.
_getcoefs_func_type = ctypes.CFUNCTYPE(None, ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_double))
if points_source is None:
cls.lib.MultiHMatrixCreateSym.restype = ctypes.POINTER(_C_MultiHMatrix)
cls.lib.MultiHMatrixCreateSym.argtypes = [
np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'),
ctypes.c_int,
_getcoefs_func_type,
ctypes.c_int
]
# Call the C++ backend.
c_data = cls.lib.MultiHMatrixCreateSym(points_target, points_target.shape[0], _getcoefs_func_type(getcoefs),nm)
else:
cls.lib.MultiHMatrixCreate.restype = ctypes.POINTER(_C_MultiHMatrix)
cls.lib.MultiHMatrixCreate.argtypes = [
np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'),
ctypes.c_int,
np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'),
ctypes.c_int,
_getcoefs_func_type,
ctypes.c_int
]
# Call the C++ backend.
c_data = cls.lib.MultiHMatrixCreate(points_target,points_target.shape[0],points_source, points_source.shape[0], _getcoefs_func_type(getcoefs),nm)
return cls(c_data, **params)
@classmethod
def from_submatrices(cls, getsubmatrix, nm, points_target, points_source=None, **params):
"""Construct an instance of the class from a evaluation function.
Parameters
----------
points: np.ndarray of shape (N, 3)
The coordinates of the points.
getsubmatrix: Callable
A function evaluating the matrix in a given range.
epsilon: float, keyword-only, optional
Tolerance of the Adaptive Cross Approximation
eta: float, keyword-only, optional
Criterion to choose the blocks to compress
minclustersize: int, keyword-only, optional
Minimum shape of a block
maxblocksize: int, keyword-only, optional
Maximum number of coefficients in a block
Returns
-------
HMatrix or ComplexHMatrix
"""
# Set params.
cls._set_building_params(**params)
# Boilerplate code for Python/C++ interface.
_getsumatrix_func_type = ctypes.CFUNCTYPE(
None, ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int),
ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_double)
)
if points_source is None:
cls.lib.MultiHMatrixCreatewithsubmatSym.restype = ctypes.POINTER(_C_MultiHMatrix)
cls.lib.MultiHMatrixCreatewithsubmatSym.argtypes = [
np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'),
ctypes.c_int,
_getsumatrix_func_type,
ctypes.c_int
]
# Call the C++ backend.
c_data = cls.lib.MultiHMatrixCreatewithsubmatSym(points_target, points_target.shape[0], _getsumatrix_func_type(getsubmatrix),nm)
else:
cls.lib.MultiHMatrixCreatewithsubmat.restype = ctypes.POINTER(_C_MultiHMatrix)
cls.lib.MultiHMatrixCreatewithsubmat.argtypes = [
np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'),
ctypes.c_int,
np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'),
ctypes.c_int,
_getsumatrix_func_type,
ctypes.c_int
]
# Call the C++ backend.
c_data = cls.lib.MultiHMatrixCreatewithsubmat(points_target,points_target.shape[0],points_source, points_source.shape[0], _getsumatrix_func_type(getsubmatrix),nm)
return cls(c_data, **params)
@classmethod
def _set_building_params(cls, *, eta=None, minclustersize=None, epsilon=None, maxblocksize=None):
"""Put the parameters in the C++ backend."""
if epsilon is not None:
cls.lib.setepsilon.restype = None
cls.lib.setepsilon.argtypes = [ ctypes.c_double ]
cls.lib.setepsilon(epsilon)
if eta is not None:
cls.lib.seteta.restype = None
cls.lib.seteta.argtypes = [ ctypes.c_double ]
cls.lib.seteta(eta)
if minclustersize is not None:
cls.lib.setminclustersize.restype = None
cls.lib.setminclustersize.argtypes = [ ctypes.c_int ]
cls.lib.setminclustersize(minclustersize)
if maxblocksize is not None:
cls.lib.setmaxblocksize.restype = None
cls.lib.setmaxblocksize.argtypes = [ ctypes.c_int ]
cls.lib.setmaxblocksize(maxblocksize)
def __str__(self):
return f"{self.__class__.__name__}(shape={self.shape})"
def __getitem__(self, key):
# self.lib.getHMatrix.restype=ctypes.POINTER(_C_HMatrix)
# self.lib.getHMatrix.argtypes=[ctypes.POINTER(_C_MultiHMatrix), ctypes.c_int]
# c_data_hmatrix = self.lib.getHMatrix(self.c_data,key)
# return HMatrix(c_data_hmatrix,**self.params)
return self.hmatrices[key]
def matvec(self, l , vector):
"""Matrix-vector product (interface for scipy iterative solvers)."""
assert self.shape[1] == vector.shape[0], "Matrix-vector product of matrices of wrong shapes."
# Boilerplate for Python/C++ interface
self.lib.MultiHMatrixVecProd.argtypes = [
ctypes.POINTER(_C_MultiHMatrix),
ctypes.c_int,
np.ctypeslib.ndpointer(self.dtype, flags='C_CONTIGUOUS'),
np.ctypeslib.ndpointer(self.dtype, flags='C_CONTIGUOUS')
]
# Initialize vector
result = np.zeros((self.shape[0],), dtype=self.dtype)
# Call C++ backend
self.lib.MultiHMatrixVecProd(self.c_data,l , vector, result)
return result
class MultiHMatrix(AbstractMultiHMatrix):
"""A real-valued hierarchical matrix based on htool C++ library.
Create with HMatrix.from_coefs or HMatrix.from_submatrices.
Attributes
----------
c_data:
Pointer to the raw data used by the C++ library.
shape: Tuple[int, int]
Shape of the matrix.
nb_dense_blocks: int
Number of dense blocks in the hierarchical matrix.
nb_low_rank_blocks: int
Number of sparse blocks in the hierarchical matrix.
nb_blocks: int
Total number of blocks in the decomposition.
params: dict
The parameters that have been used to build the matrix.
"""
libfile = os.path.join(os.path.dirname(__file__), '../libhtool_shared')
if 'linux' in sys.platform:
lib = ctypes.cdll.LoadLibrary(libfile+'.so')
elif sys.platform == 'darwin':
lib = ctypes.cdll.LoadLibrary(libfile+'.dylib')
elif sys.platform == 'win32':
lib = ctypes.cdll.LoadLibrary(libfile+'.dll')
dtype = ctypes.c_double
class ComplexMultiHMatrix(AbstractMultiHMatrix):
"""A complex-valued hierarchical matrix based on htool C++ library.
Create with ComplexHMatrix.from_coefs or ComplexHMatrix.from_submatrices.
Attributes
----------
c_data:
Pointer to the raw data used by the C++ library.
shape: Tuple[int, int]
Shape of the matrix.
nb_dense_blocks: int
Number of dense blocks in the hierarchical matrix.
nb_low_rank_blocks: int
Number of sparse blocks in the hierarchical matrix.
nb_blocks: int
Total number of blocks in the decomposition.
params: dict
The parameters that have been used to build the matrix.
"""
libfile = os.path.join(os.path.dirname(__file__), '../libhtool_shared_complex')
if 'linux' in sys.platform:
lib = ctypes.cdll.LoadLibrary(libfile+'.so')
elif sys.platform == 'darwin':
lib = ctypes.cdll.LoadLibrary(libfile+'.dylib')
elif sys.platform == 'win32':
lib = ctypes.cdll.LoadLibrary(libfile+'.dll')
dtype = np.complex128<|fim▁end|>
|
Parameters
----------
getcoefs: Callable
A function evaluating an array of matrices at given coordinates.
|
<|file_name|>ali_alert_get_db_metric.cc<|end_file_name|><|fim▁begin|>#include <stdio.h>
#include "ali_api_core.h"
#include "ali_string_utils.h"
#include "ali_alert.h"
#include "json/value.h"
#include "json/reader.h"
using namespace aliyun;
namespace {
void Json2Type(const Json::Value& value, std::string* item);
<|fim▁hole|>class Json2Array {
public:
Json2Array(const Json::Value& value, std::vector<T>* vec) {
if(!value.isArray()) {
return;
}
for(int i = 0; i < value.size(); i++) {
T val;
Json2Type(value[i], &val);
vec->push_back(val);
}
}
};
void Json2Type(const Json::Value& value, std::string* item) {
*item = value.asString();
}
void Json2Type(const Json::Value& value, AlertGetDBMetricResponseType* item) {
if(value.isMember("code")) {
item->code = value["code"].asString();
}
if(value.isMember("message")) {
item->message = value["message"].asString();
}
if(value.isMember("success")) {
item->success = value["success"].asString();
}
if(value.isMember("traceId")) {
item->trace_id = value["traceId"].asString();
}
if(value.isMember("result")) {
item->result = value["result"].asString();
}
}
}
int Alert::GetDBMetric(const AlertGetDBMetricRequestType& req,
AlertGetDBMetricResponseType* response,
AlertErrorInfo* error_info) {
std::string str_response;
int status_code;
int ret = 0;
bool parse_success = false;
Json::Value val;
Json::Reader reader;
std::string secheme = this->use_tls_ ? "https" : "http";
std::string url = secheme + "://" + host_ + get_format_string("/projects/%s/dbMetrics/%s", req.project_name.c_str(), req.metric_name.c_str());
AliRoaRequest* req_rpc = new AliRoaRequest(version_,
appid_,
secret_,
url);
if((!this->use_tls_) && this->proxy_host_ && this->proxy_host_[0]) {
req_rpc->SetHttpProxy( this->proxy_host_);
}
req_rpc->setRequestMethod("GET");
if(req_rpc->CommitRequest() != 0) {
if(error_info) {
error_info->code = "connect to host failed";
}
ret = -1;
goto out;
}
status_code = req_rpc->WaitResponseHeaderComplete();
req_rpc->ReadResponseBody(str_response);
if(status_code > 0 && !str_response.empty()){
parse_success = reader.parse(str_response, val);
}
if(!parse_success) {
if(error_info) {
error_info->code = "parse response failed";
}
ret = -1;
goto out;
}
if(status_code!= 200 && error_info) {
error_info->request_id = val.isMember("RequestId") ? val["RequestId"].asString(): "";
error_info->code = val.isMember("Code") ? val["Code"].asString(): "";
error_info->host_id = val.isMember("HostId") ? val["HostId"].asString(): "";
error_info->message = val.isMember("Message") ? val["Message"].asString(): "";
}
if(status_code== 200 && response) {
Json2Type(val, response);
}
ret = status_code;
out:
delete req_rpc;
return ret;
}<|fim▁end|>
|
void Json2Type(const Json::Value& value, AlertGetDBMetricResponseType* item);
template<typename T>
|
<|file_name|>parse-line-number-range.js<|end_file_name|><|fim▁begin|>const rangeParser = require(`parse-numeric-range`)
module.exports = language => {
if (!language) {
return ``
}
if (language.split(`{`).length > 1) {
let [splitLanguage, ...options] = language.split(`{`)
let highlightLines = [],
numberLines = false,
numberLinesStartAt
// Options can be given in any order and are optional
options.forEach(option => {
option = option.slice(0, -1)
// Test if the option is for line hightlighting
if (rangeParser.parse(option).length > 0) {
highlightLines = rangeParser.parse(option).filter(n => n > 0)
}
option = option.split(`:`)
// Test if the option is for line numbering
// Option must look like `numberLines: true` or `numberLines: <integer>`
// Otherwise we disable line numbering
if (
option.length === 2 &&
option[0] === `numberLines` &&
(option[1].trim() === `true` ||
Number.isInteger(parseInt(option[1].trim(), 10)))
) {
numberLines = true
numberLinesStartAt =
option[1].trim() === `true` ? 1 : parseInt(option[1].trim(), 10)
}<|fim▁hole|> })
return {
splitLanguage,
highlightLines,
numberLines,
numberLinesStartAt,
}
}
return { splitLanguage: language }
}<|fim▁end|>
| |
<|file_name|>analyze_gsimg-newauth.py<|end_file_name|><|fim▁begin|># 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://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.
'''
analyze_gsimg.py - analyze G Suite image processing workflow
Download image from Google Drive, archive to Google Cloud Storage, send
to Google Cloud Vision for processing, add results row to Google Sheet.
'''
from __future__ import print_function
import argparse
import base64
import io<|fim▁hole|>
from googleapiclient import discovery, http
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2 import credentials
k_ize = lambda b: '%6.2fK' % (b/1000.) # bytes to kBs
FILE = 'YOUR_IMG_ON_DRIVE'
BUCKET = 'YOUR_BUCKET_NAME'
PARENT = '' # YOUR IMG FILE PREFIX
SHEET = 'YOUR_SHEET_ID'
TOP = 5 # TOP # of VISION LABELS TO SAVE
DEBUG = False
# process credentials for OAuth2 tokens
creds = None
TOKENS = 'tokens.json' # OAuth2 token storage
SCOPES = (
'https://www.googleapis.com/auth/drive.readonly',
'https://www.googleapis.com/auth/devstorage.full_control',
'https://www.googleapis.com/auth/cloud-vision',
'https://www.googleapis.com/auth/spreadsheets',
)
if os.path.exists(TOKENS):
creds = credentials.Credentials.from_authorized_user_file(TOKENS)
if not (creds and creds.valid):
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'client_secret.json', SCOPES)
creds = flow.run_local_server()
with open(TOKENS, 'w') as token:
token.write(creds.to_json())
# create API service endpoints
DRIVE = discovery.build('drive', 'v3', credentials=creds)
GCS = discovery.build('storage', 'v1', credentials=creds)
VISION = discovery.build('vision', 'v1', credentials=creds)
SHEETS = discovery.build('sheets', 'v4', credentials=creds)
def drive_get_img(fname):
'download file from Drive and return file info & binary if found'
# search for file on Google Drive
rsp = DRIVE.files().list(q="name='%s'" % fname,
fields='files(id,name,mimeType,modifiedTime)'
).execute().get('files', [])
# download binary & return file info if found, else return None
if rsp:
target = rsp[0] # use first matching file
fileId = target['id']
fname = target['name']
mtype = target['mimeType']
binary = DRIVE.files().get_media(fileId=fileId).execute()
return fname, mtype, target['modifiedTime'], binary
def gcs_blob_upload(fname, bucket, media, mimetype):
'upload an object to a Google Cloud Storage bucket'
# build blob metadata and upload via GCS API
body = {'name': fname, 'uploadType': 'multipart', 'contentType': mimetype}
return GCS.objects().insert(bucket=bucket, body=body,
media_body=http.MediaIoBaseUpload(io.BytesIO(media), mimetype),
fields='bucket,name').execute()
def vision_label_img(img, top):
'send image to Vision API for label annotation'
# build image metadata and call Vision API to process
body = {'requests': [{
'image': {'content': img},
'features': [{'type': 'LABEL_DETECTION', 'maxResults': top}],
}]}
rsp = VISION.images().annotate(body=body).execute().get('responses', [{}])[0]
# return top labels for image as CSV for Sheet (row)
if 'labelAnnotations' in rsp:
return ', '.join('(%.2f%%) %s' % (
label['score']*100., label['description']) \
for label in rsp['labelAnnotations'])
def sheet_append_row(sheet, row):
'append row to a Google Sheet, return #cells added'
# call Sheets API to write row to Sheet (via its ID)
rsp = SHEETS.spreadsheets().values().append(
spreadsheetId=sheet, range='Sheet1',
valueInputOption='USER_ENTERED', body={'values': [row]}
).execute()
if rsp:
return rsp.get('updates').get('updatedCells')
def main(fname, bucket, sheet_id, folder, top, debug):
'"main()" drives process from image download through report generation'
# download img file & info from Drive
rsp = drive_get_img(fname)
if not rsp:
return
fname, mtype, ftime, data = rsp
if debug:
print('Downloaded %r (%s, %s, size: %d)' % (fname, mtype, ftime, len(data)))
# upload file to GCS
gcsname = '%s/%s'% (folder, fname)
rsp = gcs_blob_upload(gcsname, bucket, data, mtype)
if not rsp:
return
if debug:
print('Uploaded %r to GCS bucket %r' % (rsp['name'], rsp['bucket']))
# process w/Vision
rsp = vision_label_img(base64.b64encode(data).decode('utf-8'), top)
if not rsp:
return
if debug:
print('Top %d labels from Vision API: %s' % (top, rsp))
# push results to Sheet, get cells-saved count
fsize = k_ize(len(data))
row = [folder,
'=HYPERLINK("storage.cloud.google.com/%s/%s", "%s")' % (
bucket, gcsname, fname), mtype, ftime, fsize, rsp
]
rsp = sheet_append_row(sheet_id, row)
if not rsp:
return
if debug:
print('Added %d cells to Google Sheet' % rsp)
return True
if __name__ == '__main__':
# args: [-hv] [-i imgfile] [-b bucket] [-f folder] [-s Sheet ID] [-t top labels]
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--imgfile", action="store_true",
default=FILE, help="image file filename")
parser.add_argument("-b", "--bucket_id", action="store_true",
default=BUCKET, help="Google Cloud Storage bucket name")
parser.add_argument("-f", "--folder", action="store_true",
default=PARENT, help="Google Cloud Storage image folder")
parser.add_argument("-s", "--sheet_id", action="store_true",
default=SHEET, help="Google Sheet Drive file ID (44-char str)")
parser.add_argument("-t", "--viz_top", action="store_true",
default=TOP, help="return top N (default %d) Vision API labels" % TOP)
parser.add_argument("-v", "--verbose", action="store_true",
default=DEBUG, help="verbose display output")
args = parser.parse_args()
print('Processing file %r... please wait' % args.imgfile)
rsp = main(args.imgfile, args.bucket_id,
args.sheet_id, args.folder, args.viz_top, args.verbose)
if rsp:
sheet_url = 'https://docs.google.com/spreadsheets/d/%s/edit' % args.sheet_id
print('DONE: opening web browser to it, or see %s' % sheet_url)
webbrowser.open(sheet_url, new=1, autoraise=True)
else:
print('ERROR: could not process %r' % args.imgfile)<|fim▁end|>
|
import os
import webbrowser
|
<|file_name|>P1011_test.py<|end_file_name|><|fim▁begin|>import P1011
import unittest
class test_phylab(unittest.TestCase):
def testSteelWire_1(self):
m = [10.000,12.000,14.000,16.000,18.000,20.000,22.000,24.000,26.00]
C_plus = [3.50, 3.81, 4.10, 4.40, 4.69, 4.98, 5.28, 5.59, 5.89]
C_sub = [3.52, 3.80, 4.08, 4.38, 4.70, 4.99, 5.30, 5.59, 5.89]
D = [0.789, 0.788, 0.788, 0.787, 0.788]
L = 38.9
H = 77.0
b = 8.50
res = P1011.SteelWire(m, C_plus, C_sub, D, L, H, b)
self.assertEqual(res,'(1.90\\pm0.04){\\times}10^{11}',"test SteelWire fail")
def testInertia_1(self):
m = [711.77, 711.82, 1242.30, 131.76, 241.56,238.38]
d = [99.95, 99.95, 93.85, 114.60, 610.00]
T = [[4.06, 4.06, 4.07, 4.06, 4.06], [6.57, 6.57, 6.57, 6.56, 6.57],
[8.16, 8.16, 8.17, 8.17, 8.17], [7.35, 7.35, 7.33, 7.35, 7.37],
[11.40, 11.40, 11.41, 11.41, 11.41]]<|fim▁hole|> [32.96,32.96,32.96,32.97,32.96]]
res = P1011.Inertia(m, d, T, l, T2)
x = 1
if(abs(res[0] - 0.9999989) > pow(10,-7)):
x = 0
if(abs(res[1] - 610.9)/610.9 > 0.001):
x = 0
self.assertEqual(x,1,"test Inertia fail")
if __name__ =='__main__':
unittest.main()<|fim▁end|>
|
l = [34.92, 6.02, 33.05]
T2 = [[13.07,13.07,13.07,13.07,13.06],[16.86,16.86,16.88,16.87,16.88],
[21.79,21.82,21.83,21.84,21.84],[27.28,27.28,27.29,27.27,27.27],
|
<|file_name|>promise-utils.ts<|end_file_name|><|fim▁begin|>module formFor {
/**
* Supplies $q service with additional methods.
*
* <p>Intended for use only by formFor directive; this class is not exposed to the $injector.
*/
export class PromiseUtils implements ng.IQService {
private $q_:ng.IQService;
/**
* Constructor.
*
* @param $q Injector-supplied $q service
*/
constructor($q:ng.IQService) {
this.$q_ = $q;
}
/**
* @inheritDoc
*/
all(promises:ng.IPromise<any>[]):ng.IPromise<any[]> {
return this.$q_.all(promises);
}
/**
* @inheritDoc
*/
defer<T>():ng.IDeferred<T> {
return this.$q_.defer();
}
/**
* Similar to $q.reject, this is a convenience method to create and resolve a Promise.
*
* @param data Value to resolve the promise with
* @returns A resolved promise
*/
resolve(data?:any):ng.IPromise<any> {
var deferred:ng.IDeferred<any> = this.$q_.defer();
deferred.resolve(data);
return deferred.promise;
}
/**
* @inheritDoc
*/
reject(reason?:any):ng.IPromise<void> {
return this.$q_.reject(reason);
}
/**
* Similar to $q.all but waits for all promises to resolve/reject before resolving/rejecting.
*
* @param promises Array of Promises
* @returns A promise to be resolved or rejected once all of the observed promises complete
*/
waitForAll(promises:ng.IPromise<any>[]):ng.IPromise<any> {
var deferred:ng.IDeferred<any> = this.$q_.defer();
var results:Object = {};
var counter:number = 0;
var errored:boolean = false;
function updateResult(key:string, data:any):void {
if (!results.hasOwnProperty(key)) {
results[key] = data;
counter--;
}
checkForDone();
}
function checkForDone():void {
if (counter === 0) {
if (errored) {
deferred.reject(results);
} else {
deferred.resolve(results);
}
}
}
angular.forEach(promises, (promise:ng.IPromise<any>, key:string) => {
counter++;
promise.then(
(data:any) => {
updateResult(key, data);
},
(data:any) => {
errored = true;
updateResult(key, data);
});
});
checkForDone(); // Handle empty Array
return deferred.promise;
}
/**<|fim▁hole|> }
}
}<|fim▁end|>
|
* @inheritDoc
*/
when<T>(value:T):ng.IPromise<T> {
return this.$q_.when(value);
|
<|file_name|>SewerRule.java<|end_file_name|><|fim▁begin|>package net.anthavio.sewer.test;
import net.anthavio.sewer.ServerInstance;
import net.anthavio.sewer.ServerInstanceManager;
import net.anthavio.sewer.ServerMetadata;
import net.anthavio.sewer.ServerMetadata.CacheScope;
import net.anthavio.sewer.ServerType;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
/**
*
* public class MyCoolTests {
*
* @Rule
* private SewerRule sewer = new SewerRule(ServerType.JETTY, "src/test/jetty8", 0);
*
* @Test
* public void test() {
* int port = sewer.getServer().getLocalPorts()[0];
* }
*
* }
*
* Can interact with method annotations - http://www.codeaffine.com/2012/09/24/junit-rules/
*
* @author martin.vanek
*
*/
public class SewerRule implements TestRule {
private final ServerInstanceManager manager = ServerInstanceManager.INSTANCE;
private final ServerMetadata metadata;
private ServerInstance server;
public SewerRule(ServerType type, String home) {
this(type, home, -1, null, CacheScope.JVM);
}
public SewerRule(ServerType type, String home, int port) {
this(type, home, port, null, CacheScope.JVM);
}
public SewerRule(ServerType type, String home, int port, CacheScope cache) {
this(type, home, port, null, cache);
}
public SewerRule(ServerType type, String home, int port, String[] configs, CacheScope cache) {
this.metadata = new ServerMetadata(type, home, port, configs, cache);
}
public ServerInstance getServer() {
return server;
}
@Override
public Statement apply(Statement base, Description description) {
return new SewerStatement(base);
}
public class SewerStatement extends Statement {
private final Statement base;
public SewerStatement(Statement base) {
this.base = base;
}
@Override
public void evaluate() throws Throwable {
server = manager.borrowServer(metadata);
try {
base.evaluate();
} finally {
manager.returnServer(metadata);
}<|fim▁hole|>
}
}<|fim▁end|>
|
}
|
<|file_name|>test_views.py<|end_file_name|><|fim▁begin|>from django.core.urlresolvers import resolve
from django.template.loader import render_to_string
from django.test import TestCase
from django.http import HttpRequest
from django.utils.html import escape
from unittest import skip
from lists.views import home_page
from lists.models import Item, List
from lists.forms import (
ItemForm, ExistingListItemForm,
EMPTY_ITEM_ERROR, DUPLICATE_ITEM_ERROR
)<|fim▁hole|>
def test_home_page_renders_home_template(self):
response = self.client.get('/')
self.assertTemplateUsed(response, 'home.html')
def test_home_page_uses_item_form(self):
response = self.client.get('/')
self.assertIsInstance(response.context['form'], ItemForm)
class ListViewTest(TestCase):
def post_invalid_input(self):
list_ = List.objects.create()
return self.client.post(
'/lists/%d/' % (list_.id),
data={'text': ''}
)
def test_for_invalid_input_nothing_saved_to_db(self):
self.post_invalid_input()
self.assertEqual(Item.objects.count(), 0)
def test_for_invalid_input_renders_list_template(self):
response = self.post_invalid_input()
self.assertEqual(response.status_code, 200)
def test_for_invalid_input_passes_form_to_template(self):
response = self.post_invalid_input()
self.assertIsInstance(response.context['form'], ExistingListItemForm)
def test_for_invalid_input_shows_error_on_page(self):
response = self.post_invalid_input()
self.assertContains(response, escape(EMPTY_ITEM_ERROR))
def test_duplicate_item_validation_errors_end_up_on_lists_page(self):
list1 = List.objects.create()
item1 = Item.objects.create(list=list1, text='textey')
response = self.client.post(
'/lists/%d/' % (list1.id),
data={'text':'textey'}
)
expected_error = escape(DUPLICATE_ITEM_ERROR)
self.assertContains(response, expected_error)
self.assertTemplateUsed(response, 'list.html')
self.assertEqual(Item.objects.all().count(), 1)
def test_uses_list_template(self):
list_ = List.objects.create()
response = self.client.get('/lists/%d/' % (list_.id,))
self.assertTemplateUsed(response, 'list.html')
def test_display_only_items_for_that_list(self):
correct_list = List.objects.create()
Item.objects.create(text='i1', list=correct_list)
Item.objects.create(text='i2', list=correct_list)
other_list = List.objects.create()
Item.objects.create(text='i1o', list=other_list)
Item.objects.create(text='i2o', list=other_list)
response = self.client.get('/lists/%d/' % (correct_list.id,))
self.assertContains(response, 'i1')
self.assertContains(response, 'i2')
self.assertNotContains(response, 'i1o')
self.assertNotContains(response, 'i2o')
def test_passes_correct_list_to_template(self):
other_list = List.objects.create()
correct_list = List.objects.create()
response = self.client.get('/lists/%d/' % (correct_list.id,))
self.assertEqual(response.context['list'], correct_list)
def test_can_save_a_POST_request_to_an_existing_list(self):
other_list = List.objects.create()
correct_list = List.objects.create()
self.client.post(
'/lists/%d/' % (correct_list.id,),
data={'text': 'A new item for an existing list'}
)
self.assertEqual(Item.objects.count(), 1)
new_item = Item.objects.first()
self.assertEqual(new_item.text, 'A new item for an existing list')
self.assertEqual(new_item.list, correct_list)
def test_POST_redirects_to_list_view(self):
other_list = List.objects.create()
correct_list = List.objects.create()
response = self.client.post (
'/lists/%d/' % (correct_list.id,),
data={'text': 'A new item for an existing list'}
)
self.assertRedirects(response, '/lists/%d/' % (correct_list.id,))
def test_displays_item_form(self):
list_ = List.objects.create()
response = self.client.get('/lists/%d/' % (list_.id))
self.assertIsInstance(response.context['form'], ExistingListItemForm)
self.assertContains(response, 'name="text"')
class NewListTest(TestCase):
def test_saving_a_POST_request(self):
self.client.post(
'/lists/new',
data={'text': 'A new list item'},
)
self.assertEqual(Item.objects.count(), 1)
new_item = Item.objects.first()
self.assertEqual(new_item.text, 'A new list item')
def test_redirects_after_POST(self):
response = self.client.post(
'/lists/new',
data={'text':'A new list item'}
)
new_list = List.objects.first()
self.assertRedirects(response, '/lists/%d/' % (new_list.id,))
def test_for_invalid_input_renders_home_template(self):
response = self.client.post('/lists/new', data={'text': ''})
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'home.html')
def test_validation_errors_are_shown_on_home_page(self):
response = self.client.post('/lists/new', data={'text': ''})
self.assertContains(response, escape(EMPTY_ITEM_ERROR))
def test_for_invalid_input_passes_form_to_template(self):
response = self.client.post('/lists/new', data={'text': ''})
self.assertIsInstance(response.context['form'], ItemForm)
def test_invalid_list_items_arent_saved(self):
self.client.post('/lists/new', data={"text": ''})
self.assertEqual(List.objects.count(), 0)
self.assertEqual(Item.objects.count(), 0)<|fim▁end|>
|
class HomePageTest(TestCase):
|
<|file_name|>repl.js<|end_file_name|><|fim▁begin|>/*
* repl.js
* Copyright (C) 2015 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the BSD license.
*/
"use strict"; /*jshint node:true */
var fs = require('fs');
var path = require('path');
var vm = require('vm');
var util = require('util');
var utils = require('./utils');
var completelib = require('./completer');
var colored = utils.safe_colored;
var RapydScript = (typeof create_rapydscript_compiler === 'function') ? create_rapydscript_compiler() : require('./compiler').create_compiler();
var has_prop = Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty);
function create_ctx(baselib, show_js, console) {
var ctx = vm.createContext({'console':console, 'show_js': !!show_js, 'RapydScript':RapydScript, 'require':require});
vm.runInContext(baselib, ctx, {'filename':'baselib-plain-pretty.js'});
vm.runInContext('var __name__ = "__repl__";', ctx);
return ctx;
}
var homedir = process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'];
var cachedir = expanduser(process.env.XDG_CACHE_HOME || '~/.cache');
function expanduser(x) {
if (!x) return x;
if (x === '~') return homedir;
if (x.slice(0, 2) != '~/') return x;
return path.join(homedir, x.slice(2));
}
function repl_defaults(options) {
options = options || {};
if (!options.input) options.input = process.stdin;
if (!options.output) options.output = process.stdout;
if (options.show_js === undefined) options.show_js = true;
if (!options.ps1) options.ps1 = '>>> ';
if (!options.ps2) options.ps2 = '... ';
if (!options.console) options.console = console;
if (!options.readline) options.readline = require('readline');
if (options.terminal === undefined) options.terminal = options.output.isTTY;
if (options.histfile === undefined) options.histfile = path.join(cachedir, 'rapydscript-repl.history');
options.colored = (options.terminal) ? colored : (function (string) { return string; });
options.historySize = options.history_size || 1000;
return options;
}
function read_history(options) {
if (options.histfile) {
try {
return fs.readFileSync(options.histfile, 'utf-8').split('\n');
} catch (e) { return []; }
}
}
function write_history(options, history) {
if (options.histfile) {
history = history.join('\n');
try {
return fs.writeFileSync(options.histfile, history, 'utf-8');
} catch (e) {}
}
}
module.exports = function(options) {
options = repl_defaults(options);
options.completer = completer;
var rl = options.readline.createInterface(options);
var ps1 = options.colored(options.ps1, 'green');
var ps2 = options.colored(options.ps2, 'yellow');
var ctx = create_ctx(print_ast(RapydScript.parse('(def ():\n yield 1\n)'), true), options.show_js, options.console);
var buffer = [];
var more = false;
var LINE_CONTINUATION_CHARS = ':\\';
var toplevel;
var import_dirs = utils.get_import_dirs();
var find_completions = completelib(RapydScript, options);
options.console.log(options.colored('Welcome to the RapydScript REPL! Press Ctrl+C then Ctrl+D to quit.', 'green', true));
if (options.show_js)
options.console.log(options.colored('Use show_js=False to stop the REPL from showing the compiled JavaScript.', 'green', true));
else
options.console.log(options.colored('Use show_js=True to have the REPL show the compiled JavaScript before executing it.', 'green', true));
options.console.log();
function print_ast(ast, keep_baselib) {
var output_options = {omit_baselib:!keep_baselib, write_name:false, private_scope:false, beautify:true, keep_docstrings:true};
if (keep_baselib) output_options.baselib_plain = fs.readFileSync(path.join(options.lib_path, 'baselib-plain-pretty.js'), 'utf-8');
var output = new RapydScript.OutputStream(output_options);
ast.print(output);
return output.get();
}
function resetbuffer() { buffer = []; }
function completer(line) {
return find_completions(line, ctx);
}
function prompt() {
var lw = '';
if (more && buffer.length) {
var prev_line = buffer[buffer.length - 1];
if (prev_line.trimRight().substr(prev_line.length - 1) == ':') lw = ' ';
prev_line = prev_line.match(/^\s+/);
if (prev_line) lw += prev_line;
}
rl.setPrompt((more) ? ps2 : ps1);
if (rl.sync_prompt) rl.prompt(lw);
else {
rl.prompt();
if (lw) rl.write(lw);
}
}
function runjs(js) {
var result;
if (vm.runInContext('show_js', ctx)) {
options.console.log(options.colored('---------- Compiled JavaScript ---------', 'green', true));
options.console.log(js);
options.console.log(options.colored('---------- Running JavaScript ---------', 'green', true));
}
try {
// Despite what the docs say node does not actually output any errors by itself
// so, in case this bug is fixed later, we turn it off explicitly.
result = vm.runInContext(js, ctx, {'filename':'<repl>', 'displayErrors':false});
} catch(e) {
if (e.stack) options.console.error(e.stack);
else options.console.error(e.toString());
}
if (result !== undefined) {
options.console.log(util.inspect(result, {'colors':options.terminal}));
}
}
function compile_source(source) {
var classes = (toplevel) ? toplevel.classes : undefined;
var scoped_flags = (toplevel) ? toplevel.scoped_flags: undefined;<|fim▁hole|> 'libdir': options.imp_path,
'import_dirs': import_dirs,
'classes': classes,
'scoped_flags': scoped_flags,
});
} catch(e) {
if (e.is_eof && e.line == buffer.length && e.col > 0) return true;
if (e.message && e.line !== undefined) options.console.log(e.line + ':' + e.col + ':' + e.message);
else options.console.log(e.stack || e.toString());
return false;
}
var output = print_ast(toplevel);
if (classes) {
var exports = {};
toplevel.exports.forEach(function (name) { exports[name] = true; });
Object.getOwnPropertyNames(classes).forEach(function (name) {
if (!has_prop(exports, name) && !has_prop(toplevel.classes, name))
toplevel.classes[name] = classes[name];
});
}
scoped_flags = toplevel.scoped_flags;
runjs(output);
return false;
}
function push(line) {
buffer.push(line);
var ll = line.trimRight();
if (ll && LINE_CONTINUATION_CHARS.indexOf(ll.substr(ll.length - 1)) > -1)
return true;
var source = buffer.join('\n');
if (!source.trim()) { resetbuffer(); return false; }
var incomplete = compile_source(source);
if (!incomplete) resetbuffer();
return incomplete;
}
rl.on('line', function(line) {
if (more) {
// We are in a block
var line_is_empty = !line.trimLeft();
if (line_is_empty && buffer.length && !buffer[buffer.length - 1].trimLeft()) {
// We have two empty lines, evaluate the block
more = push(line.trimLeft());
} else buffer.push(line);
} else more = push(line); // Not in a block, evaluate line
prompt();
})
.on('close', function() {
options.console.log('Bye!');
if (rl.history) write_history(options, rl.history);
process.exit(0);
})
.on('SIGINT', function() {
rl.clearLine();
options.console.log('Keyboard Interrupt');
resetbuffer();
more = false;
prompt();
})
.on('SIGCONT', function() {
prompt();
});
rl.history = read_history(options);
prompt();
};<|fim▁end|>
|
try {
toplevel = RapydScript.parse(source, {
'filename':'<repl>',
'basedir': process.cwd(),
|
<|file_name|>_9001_developer.py<|end_file_name|><|fim▁begin|># Copyright 2015 Cisco Systems, 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.
from django.conf import settings
DASHBOARD = 'developer'
ADD_ANGULAR_MODULES = [
'horizon.dashboard.developer'
]
ADD_INSTALLED_APPS = [
'openstack_dashboard.contrib.developer'
]
ADD_SCSS_FILES = [
'dashboard/developer/developer.scss',
]
AUTO_DISCOVER_STATIC_FILES = True
DISABLED = True
if getattr(settings, 'DEBUG', False):<|fim▁hole|><|fim▁end|>
|
DISABLED = False
|
<|file_name|>compute_rigid_transform.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# encoding: utf-8
"""
Author: Isabel Restrepo
August 12, 2012
Compute rigid transformation between two point clounds using feature correspondances
"""
import os
import sys
import glob
import time
from optparse import OptionParser
from xml.etree.ElementTree import ElementTree
from vpcl_adaptor import *
from boxm2_utils import *
parser = OptionParser()
parser.add_option("--srcRoot", action="store", type="string", dest="src_scene_root", help="root folder, this is where the .ply input and output files should reside")
parser.add_option("--tgtRoot", action="store", type="string", dest="tgt_scene_root", help="root folder, this is where the .ply input and output files should reside")
parser.add_option("--basenameIn", action="store", type="string", dest="basename_in", help="basename of .ply file")
parser.add_option("-r", "--radius", action="store", type="int", dest="radius", help="radius (multiple of resolution)");
parser.add_option("-p", "--percent", action="store", type="int", dest="percentile", help="data percentile");
parser.add_option("-d", "--descriptor", action="store", type="string", dest="descriptor_type", help="name of the descriptor i.e FPFH");
parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=False, help="verbose - if false std is redirected to a logfile");
(opts, args) = parser.parse_args()
print opts
print args
#path to where all scenes are
src_scene_root=opts.src_scene_root;
tgt_scene_root=opts.tgt_scene_root;
radius = opts.radius; #gets multiplied by the resolution of the scene
percentile = opts.percentile;
descriptor_type = opts.descriptor_type;
verbose=opts.verbose;
<|fim▁hole|>src_fname = src_scene_root + "/" + opts.basename_in + "_" + str(percentile) + ".ply"
src_features_dir = src_scene_root + "/" + descriptor_type + "_" + str(radius);
src_features_fname = src_features_dir + "/descriptors_" + str(percentile) + ".pcd";
tgt_fname = tgt_scene_root + "/" + opts.basename_in + "_" + str(percentile) + ".ply"
tgt_features_dir = tgt_scene_root + "/" + descriptor_type + "_" + str(radius);
tgt_features_fname = tgt_features_dir + "/descriptors_" + str(percentile) + ".pcd";
tform_cloud_fname = tgt_features_dir + "/tform_cloud_" + str(percentile) + ".pcd";
tform_fname = tgt_features_dir + "/transformation_" + str(percentile) + ".txt";
if verbose :
print src_fname, src_features_fname
print tgt_fname, tgt_features_fname, tform_cloud_fname, tform_fname
compute_rigid_transformation(src_fname, tgt_fname, src_features_fname, tgt_features_fname, tform_cloud_fname, tform_fname, descriptor_type);
if not verbose:
vpcl_batch.reset_stdout();
print "Done"
sys.exit(0)<|fim▁end|>
|
if not verbose:
vpcl_batch.set_stdout("./logs/log_" + descriptor_type + 'percetile' + str(percentile) +'.log')
|
<|file_name|>tmedia_session_jsep.js<|end_file_name|><|fim▁begin|>/*
* Copyright (C) 2012-2018 Doubango Telecom <http://www.doubango.org>
* License: BSD
* This file is part of Open Source sipML5 solution <http://www.sipml5.org>
*/
// http://tools.ietf.org/html/draft-uberti-rtcweb-jsep-02
// JSEP00: webkitPeerConnection00 (http://www.w3.org/TR/2012/WD-webrtc-20120209/)
// JSEP01: webkitRTCPeerConnection (http://www.w3.org/TR/webrtc/), https://webrtc-demos.appspot.com/html/pc1.html
// Mozilla: http://mozilla.github.com/webrtc-landing/pc_test.html
// Contraints: https://webrtc-demos.appspot.com/html/constraints-and-stats.html
// Android: https://groups.google.com/group/discuss-webrtc/browse_thread/thread/b8538c85df801b40
// Canary 'muted': https://groups.google.com/group/discuss-webrtc/browse_thread/thread/8200f2049c4de29f
// Canary state events: https://groups.google.com/group/discuss-webrtc/browse_thread/thread/bd30afc3e2f43f6d
// DTMF: https://groups.google.com/group/discuss-webrtc/browse_thread/thread/1354781f202adbf9
// IceRestart: https://groups.google.com/group/discuss-webrtc/browse_thread/thread/c189584d380eaa97
// Video Resolution: https://code.google.com/p/chromium/issues/detail?id=143631#c9
// Webrtc-Everywhere: https://github.com/sarandogou/webrtc-everywhere
// Adapter.js: https://github.com/sarandogou/webrtc
tmedia_session_jsep.prototype = Object.create(tmedia_session.prototype);
tmedia_session_jsep01.prototype = Object.create(tmedia_session_jsep.prototype);
tmedia_session_jsep.prototype.o_pc = null;
tmedia_session_jsep.prototype.b_cache_stream = false;
tmedia_session_jsep.prototype.o_local_stream = null;
tmedia_session_jsep.prototype.o_sdp_jsep_lo = null;
tmedia_session_jsep.prototype.o_sdp_lo = null;
tmedia_session_jsep.prototype.b_sdp_lo_pending = false;
tmedia_session_jsep.prototype.o_sdp_json_ro = null;
tmedia_session_jsep.prototype.o_sdp_ro = null;
tmedia_session_jsep.prototype.b_sdp_ro_pending = false;
tmedia_session_jsep.prototype.b_sdp_ro_offer = false;
tmedia_session_jsep.prototype.s_answererSessionId = null;
tmedia_session_jsep.prototype.s_offererSessionId = null;
tmedia_session_jsep.prototype.ao_ice_servers = null;
tmedia_session_jsep.prototype.o_bandwidth = { audio: undefined, video: undefined };
tmedia_session_jsep.prototype.o_video_size = { minWidth: undefined, minHeight: undefined, maxWidth: undefined, maxHeight: undefined };
tmedia_session_jsep.prototype.d_screencast_windowid = 0; // BFCP. #0 means entire desktop
tmedia_session_jsep.prototype.b_ro_changed = false;
tmedia_session_jsep.prototype.b_lo_held = false;
tmedia_session_jsep.prototype.b_ro_held = false;
//
// JSEP
//
tmedia_session_jsep.prototype.CreateInstance = function (o_mgr) {
return new tmedia_session_jsep01(o_mgr);
}
function tmedia_session_jsep(o_mgr) {
tmedia_session.call(this, o_mgr.e_type, o_mgr);
}
tmedia_session_jsep.prototype.__set = function (o_param) {
if (!o_param) {
return -1;
}
switch (o_param.s_key) {
case 'ice-servers':
{
this.ao_ice_servers = o_param.o_value;
return 0;
}
case 'cache-stream':
{
this.b_cache_stream = !!o_param.o_value;
return 0;
}
case 'bandwidth':
{
this.o_bandwidth = o_param.o_value;
return 0;
}
case 'video-size':
{
this.o_video_size = o_param.o_value;
return 0;
}
case 'screencast-windowid':
{
this.d_screencast_windowid = parseFloat(o_param.o_value.toString());
if (this.o_pc && this.o_pc.setScreencastSrcWindowId) {
this.o_pc.setScreencastSrcWindowId(this.d_screencast_windowid);
}
return 0;
}
case 'mute-audio':
case 'mute-video':
{
if (this.o_pc && typeof o_param.o_value == "boolean") {
if (this.o_pc.mute) {
this.o_pc.mute((o_param.s_key === 'mute-audio') ? "audio" : "video", o_param.o_value);
}
else if (this.o_local_stream) {
var tracks = (o_param.s_key === 'mute-audio') ? this.o_local_stream.getAudioTracks() : this.o_local_stream.getVideoTracks();
if (tracks) {
for (var i = 0; i < tracks.length; ++i) {
tracks[i].enabled = !o_param.o_value;
}
}
}
}
}
}
return -2;
}
tmedia_session_jsep.prototype.__prepare = function () {
return 0;
}
tmedia_session_jsep.prototype.__set_media_type = function (e_type) {
if (e_type != this.e_type) {
this.e_type = e_type;
this.o_sdp_lo = null;
}
return 0;
}
tmedia_session_jsep.prototype.__processContent = function (s_req_name, s_content_type, s_content_ptr, i_content_size) {
if (this.o_pc && this.o_pc.processContent) {
this.o_pc.processContent(s_req_name, s_content_type, s_content_ptr, i_content_size);
return 0;
}
return -1;
}
tmedia_session_jsep.prototype.__send_dtmf = function (s_digit) {
if (this.o_pc && this.o_pc.sendDTMF) {
this.o_pc.sendDTMF(s_digit);
return 0;
}
return -1;
}
tmedia_session_jsep.prototype.__start = function () {
if (this.o_local_stream && this.o_local_stream.start) {
// cached stream would be stopped in close()
this.o_local_stream.start();
}
return 0;
}
tmedia_session_jsep.prototype.__pause = function () {
if (this.o_local_stream && this.o_local_stream.pause) {
this.o_local_stream.pause();
}
return 0;
}
tmedia_session_jsep.prototype.__stop = function () {
this.close();
this.o_sdp_lo = null;
tsk_utils_log_info("PeerConnection::stop()");
return 0;
}
tmedia_session_jsep.prototype.decorate_lo = function () {
if (this.o_sdp_lo) {
/* Session name for debugging - Requires by webrtc2sip to set RTCWeb type */
var o_hdr_S;
if ((o_hdr_S = this.o_sdp_lo.get_header(tsdp_header_type_e.S))) {
o_hdr_S.s_value = "Doubango Telecom - " + tsk_utils_get_navigator_friendly_name();
}
/* HACK: https://bugzilla.mozilla.org/show_bug.cgi?id=1072384 */
var o_hdr_O;
if ((o_hdr_O = this.o_sdp_lo.get_header(tsdp_header_type_e.O))) {
if (o_hdr_O.s_addr === "0.0.0.0") {
o_hdr_O.s_addr = "127.0.0.1";
}
}<|fim▁hole|> }
/* hold / resume, profile, bandwidth... */
var i_index = 0;
var o_hdr_M;
var b_fingerprint = !!this.o_sdp_lo.get_header_a("fingerprint"); // session-level fingerprint
while ((o_hdr_M = this.o_sdp_lo.get_header_at(tsdp_header_type_e.M, i_index++))) {
// hold/resume
o_hdr_M.set_holdresume_att(this.b_lo_held, this.b_ro_held);
// HACK: Nightly 20.0a1 uses RTP/SAVPF for DTLS-SRTP which is not correct. More info at https://bugzilla.mozilla.org/show_bug.cgi?id=827932.
if (o_hdr_M.find_a("crypto")) {
o_hdr_M.s_proto = "RTP/SAVPF";
}
else if (b_fingerprint || o_hdr_M.find_a("fingerprint")) {
o_hdr_M.s_proto = "UDP/TLS/RTP/SAVPF";
}
// HACK: https://bugzilla.mozilla.org/show_bug.cgi?id=1072384
if (o_hdr_M.o_hdr_C && o_hdr_M.o_hdr_C.s_addr === "0.0.0.0") {
o_hdr_M.o_hdr_C.s_addr = "127.0.0.1";
}
// bandwidth
if (this.o_bandwidth) {
if (this.o_bandwidth.audio && o_hdr_M.s_media.toLowerCase() == "audio") {
o_hdr_M.add_header(new tsdp_header_B("AS:" + this.o_bandwidth.audio));
}
else if (this.o_bandwidth.video && o_hdr_M.s_media.toLowerCase() == "video") {
o_hdr_M.add_header(new tsdp_header_B("AS:" + this.o_bandwidth.video));
}
}
}
}
return 0;
}
tmedia_session_jsep.prototype.decorate_ro = function (b_remove_bundle) {
if (this.o_sdp_ro) {
var o_hdr_M, o_hdr_A;
var i_index = 0, i;
// FIXME: Chrome fails to parse SDP with global SDP "a=" attributes
// Chrome 21.0.1154.0+ generate "a=group:BUNDLE audio video" but cannot parse it
// In fact, new the attribute is left the ice callback is called twice and the 2nd one trigger new INVITE then 200OK. The SYN_ERR is caused by the SDP in the 200 OK.
// Is it because of "a=rtcp:1 IN IP4 0.0.0.0"?
if (b_remove_bundle) {
this.o_sdp_ro.remove_header(tsdp_header_type_e.A);
}
// ==== START: RFC5939 utility functions ==== //
var rfc5939_get_acap_part = function (o_hdr_a, i_part/* i_part = 1: field, 2: value*/) {
var ao_match = o_hdr_a.s_value.match(/^\d\s+(\w+):([\D|\d]+)/i);
if (ao_match && ao_match.length == 3) {
return ao_match[i_part];
}
}
var rfc5939_acap_ensure = function (o_hdr_a) {
if (o_hdr_a && o_hdr_a.s_field == "acap") {
o_hdr_a.s_field = rfc5939_get_acap_part(o_hdr_a, 1);
o_hdr_a.s_value = rfc5939_get_acap_part(o_hdr_a, 2);
}
}
var rfc5939_get_headerA_at = function (o_msg, s_media, s_field, i_index) {
var i_pos = 0;
var get_headerA_at = function (o_sdp, s_field, i_index) {
if (o_sdp) {
var ao_headersA = (o_sdp.ao_headers || o_sdp.ao_hdr_A);
for (var i = 0; i < ao_headersA.length; ++i) {
if (ao_headersA[i].e_type == tsdp_header_type_e.A && ao_headersA[i].s_value) {
var b_found = (ao_headersA[i].s_field === s_field);
if (!b_found && ao_headersA[i].s_field == "acap") {
b_found = (rfc5939_get_acap_part(ao_headersA[i], 1) == s_field);
}
if (b_found && i_pos++ >= i_index) {
return ao_headersA[i];
}
}
}
}
}
var o_hdr_a = get_headerA_at(o_msg, s_field, i_index); // find at session level
if (!o_hdr_a) {
return get_headerA_at(o_msg.get_header_m_by_name(s_media), s_field, i_index); // find at media level
}
return o_hdr_a;
}
// ==== END: RFC5939 utility functions ==== //
// change profile if not secure
//!\ firefox nighly: DTLS-SRTP only, chrome: SDES-SRTP
var b_fingerprint = !!this.o_sdp_ro.get_header_a("fingerprint"); // session-level fingerprint
while ((o_hdr_M = this.o_sdp_ro.get_header_at(tsdp_header_type_e.M, i_index++))) {
// check for "crypto:"/"fingerprint:" lines (event if it's not valid to provide "crypto" lines in non-secure SDP many clients do it, so, just check)
if (o_hdr_M.s_proto.indexOf("SAVP") < 0) {
if (o_hdr_M.find_a("crypto")) {
o_hdr_M.s_proto = "RTP/SAVPF";
break;
}
else if (b_fingerprint || o_hdr_M.find_a("fingerprint")) {
o_hdr_M.s_proto = "UDP/TLS/RTP/SAVPF";
break;
}
}
// rfc5939: "acap:fingerprint,setup,connection"
if (o_hdr_M.s_proto.indexOf("SAVP") < 0) {
if ((o_hdr_A = rfc5939_get_headerA_at(this.o_sdp_ro, o_hdr_M.s_media, "fingerprint", 0))) {
rfc5939_acap_ensure(o_hdr_A);
if ((o_hdr_A = rfc5939_get_headerA_at(this.o_sdp_ro, o_hdr_M.s_media, "setup", 0))) {
rfc5939_acap_ensure(o_hdr_A);
}
if ((o_hdr_A = rfc5939_get_headerA_at(this.o_sdp_ro, o_hdr_M.s_media, "connection", 0))) {
rfc5939_acap_ensure(o_hdr_A);
}
o_hdr_M.s_proto = "UDP/TLS/RTP/SAVP";
}
}
// rfc5939: "acap:crypto". Only if DTLS is OFF
if (o_hdr_M.s_proto.indexOf("SAVP") < 0) {
i = 0;
while ((o_hdr_A = rfc5939_get_headerA_at(this.o_sdp_ro, o_hdr_M.s_media, "crypto", i++))) {
rfc5939_acap_ensure(o_hdr_A);
o_hdr_M.s_proto = "RTP/SAVPF";
// do not break => find next "acap:crypto" lines and ensure them
}
}
// HACK: Nightly 20.0a1 uses RTP/SAVPF for DTLS-SRTP which is not correct. More info at https://bugzilla.mozilla.org/show_bug.cgi?id=827932
// Same for chrome: https://code.google.com/p/sipml5/issues/detail?id=92
if (o_hdr_M.s_proto.indexOf("UDP/TLS/RTP/SAVP") != -1) {
o_hdr_M.s_proto = "RTP/SAVPF";
}
}
}
return 0;
}
tmedia_session_jsep.prototype.subscribe_stream_events = function () {
if (this.o_pc) {
var This = (tmedia_session_jsep01.mozThis || this);
this.o_pc.onaddstream = function (evt) {
tsk_utils_log_info("__on_add_stream");
This.o_remote_stream = evt.stream;
if (This.o_mgr) {
This.o_mgr.set_stream_remote(evt.stream);
}
}
this.o_pc.onremovestream = function (evt) {
tsk_utils_log_info("__on_remove_stream");
This.o_remote_stream = null;
if (This.o_mgr) {
This.o_mgr.set_stream_remote(null);
}
}
}
}
tmedia_session_jsep.prototype.close = function () {
if (this.o_mgr) { // 'onremovestream' not always called
this.o_mgr.set_stream_remote(null);
this.o_mgr.set_stream_local(null);
}
if (this.o_pc) {
if (this.o_local_stream) {
// TODO: On Firefox 26: Error: "removeStream not implemented yet"
try { this.o_pc.removeStream(this.o_local_stream); } catch (e) { tsk_utils_log_error(e); }
if (!this.b_cache_stream || (this.e_type == tmedia_type_e.SCREEN_SHARE)) { // only stop if caching is disabled or screenshare
try {
var tracks = this.o_local_stream.getTracks();
for (var track in tracks) {
tracks[track].stop();
}
} catch (e) { tsk_utils_log_error(e); }
try { this.o_local_stream.stop(); } catch (e) { } // Deprecated in Chrome 45: https://github.com/DoubangoTelecom/sipml5/issues/231
}
this.o_local_stream = null;
}
this.o_pc.close();
this.o_pc = null;
this.b_sdp_lo_pending = false;
this.b_sdp_ro_pending = false;
}
}
tmedia_session_jsep.prototype.__acked = function () {
return 0;
}
tmedia_session_jsep.prototype.__hold = function () {
if (this.b_lo_held) {
// tsk_utils_log_warn('already on hold');
return;
}
this.b_lo_held = true;
this.o_sdp_ro = null;
this.o_sdp_lo = null;
if (this.o_pc && this.o_local_stream) {
this.o_pc.removeStream(this.o_local_stream);
}
return 0;
}
tmedia_session_jsep.prototype.__resume = function () {
if (!this.b_lo_held) {
// tsk_utils_log_warn('not on hold');
return;
}
this.b_lo_held = false;
this.o_sdp_lo = null;
this.o_sdp_ro = null;
if (this.o_pc && this.o_local_stream) {
this.o_pc.addStream(this.o_local_stream);
}
return 0;
}
//
// JSEP01
//
function tmedia_session_jsep01(o_mgr) {
tmedia_session_jsep.call(this, o_mgr);
this.o_media_constraints =
{
'mandatory':
{
'OfferToReceiveAudio': !!(this.e_type.i_id & tmedia_type_e.AUDIO.i_id),
'OfferToReceiveVideo': !!(this.e_type.i_id & tmedia_type_e.VIDEO.i_id)
}
};
if (tsk_utils_get_navigator_friendly_name() == 'firefox') {
tmedia_session_jsep01.mozThis = this; // FIXME: no longer needed? At least not needed on FF 34.05
this.o_media_constraints.mandatory.MozDontOfferDataChannel = true;
}
}
tmedia_session_jsep01.mozThis = undefined;
tmedia_session_jsep01.onGetUserMediaSuccess = function (o_stream, _This) {
tsk_utils_log_info("onGetUserMediaSuccess");
var This = (tmedia_session_jsep01.mozThis || _This);
if (This && This.o_pc && This.o_mgr) {
if (!This.b_sdp_lo_pending) {
tsk_utils_log_warn("onGetUserMediaSuccess but no local sdp request is pending");
return;
}
if (o_stream) {
// save stream other next calls
if (o_stream.getAudioTracks().length > 0 && o_stream.getVideoTracks().length == 0) {
__o_jsep_stream_audio = o_stream;
}
else if (o_stream.getAudioTracks().length > 0 && o_stream.getVideoTracks().length > 0) {
__o_jsep_stream_audiovideo = o_stream;
}
if (!This.o_local_stream) {
This.o_mgr.callback(tmedia_session_events_e.STREAM_LOCAL_ACCEPTED, this.e_type);
}
// HACK: Firefox only allows to call gum one time
if (tmedia_session_jsep01.mozThis) {
__o_jsep_stream_audiovideo = __o_jsep_stream_audio = o_stream;
}
This.o_local_stream = o_stream;
This.o_pc.addStream(o_stream);
}
else {
// Probably call held
}
This.o_mgr.set_stream_local(o_stream);
var b_answer = ((This.b_sdp_ro_pending || This.b_sdp_ro_offer) && (This.o_sdp_ro != null));
if (b_answer) {
tsk_utils_log_info("createAnswer");
This.o_pc.createAnswer(
tmedia_session_jsep01.mozThis ? tmedia_session_jsep01.onCreateSdpSuccess : function (o_offer) { tmedia_session_jsep01.onCreateSdpSuccess(o_offer, This); },
tmedia_session_jsep01.mozThis ? tmedia_session_jsep01.onCreateSdpError : function (s_error) { tmedia_session_jsep01.onCreateSdpError(s_error, This); },
This.o_media_constraints,
false // createProvisionalAnswer
);
}
else {
tsk_utils_log_info("createOffer");
This.o_pc.createOffer(
tmedia_session_jsep01.mozThis ? tmedia_session_jsep01.onCreateSdpSuccess : function (o_offer) { tmedia_session_jsep01.onCreateSdpSuccess(o_offer, This); },
tmedia_session_jsep01.mozThis ? tmedia_session_jsep01.onCreateSdpError : function (s_error) { tmedia_session_jsep01.onCreateSdpError(s_error, This); },
This.o_media_constraints
);
}
}
}
tmedia_session_jsep01.onGetUserMediaError = function (s_error, _This) {
tsk_utils_log_info("onGetUserMediaError");
var This = (tmedia_session_jsep01.mozThis || _This);
if (This && This.o_mgr) {
tsk_utils_log_error(s_error);
This.o_mgr.callback(tmedia_session_events_e.STREAM_LOCAL_REFUSED, This.e_type);
}
}
tmedia_session_jsep01.onCreateSdpSuccess = function (o_sdp, _This) {
tsk_utils_log_info("onCreateSdpSuccess");
var This = (tmedia_session_jsep01.mozThis || _This);
if (This && This.o_pc) {
This.o_pc.setLocalDescription(o_sdp,
tmedia_session_jsep01.mozThis ? tmedia_session_jsep01.onSetLocalDescriptionSuccess : function () { tmedia_session_jsep01.onSetLocalDescriptionSuccess(This); },
tmedia_session_jsep01.mozThis ? tmedia_session_jsep01.onSetLocalDescriptionError : function (s_error) { tmedia_session_jsep01.onSetLocalDescriptionError(s_error, This); }
);
}
}
tmedia_session_jsep01.onCreateSdpError = function (s_error, _This) {
tsk_utils_log_info("onCreateSdpError");
var This = (tmedia_session_jsep01.mozThis || _This);
if (This && This.o_mgr) {
tsk_utils_log_error(s_error);
This.o_mgr.callback(tmedia_session_events_e.GET_LO_FAILED, This.e_type);
}
}
tmedia_session_jsep01.onSetLocalDescriptionSuccess = function (_This) {
tsk_utils_log_info("onSetLocalDescriptionSuccess");
var This = (tmedia_session_jsep01.mozThis || _This);
if (This && This.o_pc) {
if ((This.o_pc.iceGatheringState || This.o_pc.iceState) === "complete") {
tmedia_session_jsep01.onIceGatheringCompleted(This);
}
This.b_sdp_ro_offer = false; // reset until next incoming RO
}
}
tmedia_session_jsep01.onSetLocalDescriptionError = function (s_error, _This) {
tsk_utils_log_info("onSetLocalDescriptionError");
var This = (tmedia_session_jsep01.mozThis || _This);
if (This && This.o_mgr) {
tsk_utils_log_error(s_error.toString());
This.o_mgr.callback(tmedia_session_events_e.GET_LO_FAILED, This.e_type);
}
}
tmedia_session_jsep01.onSetRemoteDescriptionSuccess = function (_This) {
tsk_utils_log_info("onSetRemoteDescriptionSuccess");
var This = (tmedia_session_jsep01.mozThis || _This);
if (This) {
if (!This.b_sdp_ro_pending && This.b_sdp_ro_offer) {
This.o_sdp_lo = null; // to force new SDP when get_lo() is called
}
}
}
tmedia_session_jsep01.onSetRemoteDescriptionError = function (s_error, _This) {
tsk_utils_log_info("onSetRemoteDescriptionError");
var This = (tmedia_session_jsep01.mozThis || _This);
if (This) {
This.o_mgr.callback(tmedia_session_events_e.SET_RO_FAILED, This.e_type);
tsk_utils_log_error(s_error);
}
}
tmedia_session_jsep01.onIceGatheringCompleted = function (_This) {
tsk_utils_log_info("onIceGatheringCompleted");
var This = (tmedia_session_jsep01.mozThis || _This);
if (This && This.o_pc) {
if (!This.b_sdp_lo_pending) {
tsk_utils_log_warn("onIceGatheringCompleted but no local sdp request is pending");
return;
}
This.b_sdp_lo_pending = false;
// HACK: Firefox Nightly 20.0a1(2013-01-08): PeerConnection.localDescription has a wrong value (remote sdp). More info at https://bugzilla.mozilla.org/show_bug.cgi?id=828235
var localDescription = (This.localDescription || This.o_pc.localDescription);
if (localDescription) {
This.o_sdp_jsep_lo = localDescription;
This.o_sdp_lo = tsdp_message.prototype.Parse(This.o_sdp_jsep_lo.sdp);
This.decorate_lo();
if (This.o_mgr) {
This.o_mgr.callback(tmedia_session_events_e.GET_LO_SUCCESS, This.e_type);
}
}
else {
This.o_mgr.callback(tmedia_session_events_e.GET_LO_FAILED, This.e_type);
tsk_utils_log_error("localDescription is null");
}
}
}
tmedia_session_jsep01.onIceCandidate = function (o_event, _This) {
var This = (tmedia_session_jsep01.mozThis || _This);
if (!This || !This.o_pc) {
tsk_utils_log_error("This/PeerConnection is null: unexpected");
return;
}
var iceState = (This.o_pc.iceGatheringState || This.o_pc.iceState);
tsk_utils_log_info("onIceCandidate = " + iceState);
if (iceState === "complete" || (o_event && !o_event.candidate)) {
tsk_utils_log_info("ICE GATHERING COMPLETED!");
tmedia_session_jsep01.onIceGatheringCompleted(This);
}
else if (This.o_pc.iceState === "failed") {
tsk_utils_log_error("Ice state is 'failed'");
This.o_mgr.callback(tmedia_session_events_e.GET_LO_FAILED, This.e_type);
}
}
tmedia_session_jsep01.onNegotiationNeeded = function (o_event, _This) {
tsk_utils_log_info("onNegotiationNeeded");
var This = (tmedia_session_jsep01.mozThis || _This);
if (!This || !This.o_pc) {
// do not raise error: could happen after pc.close()
return;
}
if ((This.o_pc.iceGatheringState || This.o_pc.iceState) !== "new") {
tmedia_session_jsep01.onGetUserMediaSuccess(This.b_lo_held ? null : This.o_local_stream, This);
}
}
tmedia_session_jsep01.onSignalingstateChange = function (o_event, _This) {
var This = (tmedia_session_jsep01.mozThis || _This);
if (!This || !This.o_pc) {
// do not raise error: could happen after pc.close()
return;
}
tsk_utils_log_info("onSignalingstateChange:" + This.o_pc.signalingState);
if (This.o_local_stream && This.o_pc.signalingState === "have-remote-offer") {
tmedia_session_jsep01.onGetUserMediaSuccess(This.o_local_stream, This);
}
}
tmedia_session_jsep01.prototype.__get_lo = function () {
var This = this;
if (!this.o_pc && !this.b_lo_held) {
var o_video_constraints = {
mandatory: {},
optional: []
};
if ((this.e_type.i_id & tmedia_type_e.SCREEN_SHARE.i_id) == tmedia_type_e.SCREEN_SHARE.i_id) {
o_video_constraints.mandatory.chromeMediaSource = 'screen';
}
if (this.e_type.i_id & tmedia_type_e.VIDEO.i_id) {
if (this.o_video_size) {
if (this.o_video_size.minWidth) o_video_constraints.mandatory.minWidth = this.o_video_size.minWidth;
if (this.o_video_size.minHeight) o_video_constraints.mandatory.minHeight = this.o_video_size.minHeight;
if (this.o_video_size.maxWidth) o_video_constraints.mandatory.maxWidth = this.o_video_size.maxWidth;
if (this.o_video_size.maxHeight) o_video_constraints.mandatory.maxHeight = this.o_video_size.maxHeight;
}
try { tsk_utils_log_info("Video Contraints:" + JSON.stringify(o_video_constraints)); } catch (e) { }
}
var o_iceServers = this.ao_ice_servers;
if (!o_iceServers) { // defines default ICE servers only if none exist (because WebRTC requires ICE)
// HACK Nightly 21.0a1 (2013-02-18):
// - In RTCConfiguration passed to RTCPeerConnection constructor: FQDN not yet implemented (only IP-#s). Omitting "stun:stun.l.google.com:19302"
// - CHANGE-REQUEST not supported when using "numb.viagenie.ca"
// - (stun/ERR) Missing XOR-MAPPED-ADDRESS when using "stun.l.google.com"
// numb.viagenie.ca: 66.228.45.110:
// stun.l.google.com: 173.194.78.127
// stun.counterpath.net: 216.93.246.18
// "23.21.150.121" is the default STUN server used in Nightly
o_iceServers = tmedia_session_jsep01.mozThis
? [{ url: 'stun:23.21.150.121:3478' }, { url: 'stun:216.93.246.18:3478' }, { url: 'stun:66.228.45.110:3478' }, { url: 'stun:173.194.78.127:19302' }]
: [{ url: 'stun:stun.l.google.com:19302' }, { url: 'stun:stun.counterpath.net:3478' }, { url: 'stun:numb.viagenie.ca:3478' }];
}
try { tsk_utils_log_info("ICE servers:" + JSON.stringify(o_iceServers)); } catch (e) { }
this.o_pc = new window.RTCPeerConnection(
(o_iceServers && !o_iceServers.length) ? null : { iceServers: o_iceServers, rtcpMuxPolicy: "negotiate" }, // empty array is used to disable STUN/TURN.
this.o_media_constraints
);
this.o_pc.onicecandidate = tmedia_session_jsep01.mozThis ? tmedia_session_jsep01.onIceCandidate : function (o_event) { tmedia_session_jsep01.onIceCandidate(o_event, This); };
this.o_pc.onnegotiationneeded = tmedia_session_jsep01.mozThis ? tmedia_session_jsep01.onNegotiationNeeded : function (o_event) { tmedia_session_jsep01.onNegotiationNeeded(o_event, This); };
this.o_pc.onsignalingstatechange = tmedia_session_jsep01.mozThis ? tmedia_session_jsep01.onSignalingstateChange : function (o_event) { tmedia_session_jsep01.onSignalingstateChange(o_event, This); };
this.subscribe_stream_events();
}
if (!this.o_sdp_lo && !this.b_sdp_lo_pending) {
this.b_sdp_lo_pending = true;
// set penfing ro if there is one
if (this.b_sdp_ro_pending && this.o_sdp_ro) {
this.__set_ro(this.o_sdp_ro, true);
}
// get media stream
if (this.e_type == tmedia_type_e.AUDIO && (this.b_cache_stream && __o_jsep_stream_audio)) {
tmedia_session_jsep01.onGetUserMediaSuccess(__o_jsep_stream_audio, This);
}
else if (this.e_type == tmedia_type_e.AUDIO_VIDEO && (this.b_cache_stream && __o_jsep_stream_audiovideo)) {
tmedia_session_jsep01.onGetUserMediaSuccess(__o_jsep_stream_audiovideo, This);
}
else {
if (!this.b_lo_held && !this.o_local_stream) {
this.o_mgr.callback(tmedia_session_events_e.STREAM_LOCAL_REQUESTED, this.e_type);
navigator.getUserMedia(
{
audio: (this.e_type == tmedia_type_e.SCREEN_SHARE) ? false : !!(this.e_type.i_id & tmedia_type_e.AUDIO.i_id), // IMPORTANT: Chrome '28.0.1500.95 m' doesn't support using audio with screenshare
video: !!(this.e_type.i_id & tmedia_type_e.VIDEO.i_id) ? o_video_constraints : false, // "SCREEN_SHARE" contains "VIDEO" flag -> (VIDEO & SCREEN_SHARE) = VIDEO
data: false
},
tmedia_session_jsep01.mozThis ? tmedia_session_jsep01.onGetUserMediaSuccess : function (o_stream) { tmedia_session_jsep01.onGetUserMediaSuccess(o_stream, This); },
tmedia_session_jsep01.mozThis ? tmedia_session_jsep01.onGetUserMediaError : function (s_error) { tmedia_session_jsep01.onGetUserMediaError(s_error, This); }
);
}
}
}
return this.o_sdp_lo;
}
tmedia_session_jsep01.prototype.__set_ro = function (o_sdp, b_is_offer) {
if (!o_sdp) {
tsk_utils_log_error("Invalid argument");
return -1;
}
/* update remote offer */
this.o_sdp_ro = o_sdp;
this.b_sdp_ro_offer = b_is_offer;
/* reset local sdp */
if (b_is_offer) {
this.o_sdp_lo = null;
}
if (this.o_pc) {
try {
var This = this;
this.decorate_ro(false);
tsk_utils_log_info("setRemoteDescription(" + (b_is_offer ? "offer)" : "answer)") + "\n" + this.o_sdp_ro);
this.o_pc.setRemoteDescription(
new window.RTCSessionDescription({ type: b_is_offer ? "offer" : "answer", sdp: This.o_sdp_ro.toString() }),
tmedia_session_jsep01.mozThis ? tmedia_session_jsep01.onSetRemoteDescriptionSuccess : function () { tmedia_session_jsep01.onSetRemoteDescriptionSuccess(This); },
tmedia_session_jsep01.mozThis ? tmedia_session_jsep01.onSetRemoteDescriptionError : function (s_error) { tmedia_session_jsep01.onSetRemoteDescriptionError(s_error, This); }
);
}
catch (e) {
tsk_utils_log_error(e);
this.o_mgr.callback(tmedia_session_events_e.SET_RO_FAILED, this.e_type);
return -2;
}
finally {
this.b_sdp_ro_pending = false;
}
}
else {
this.b_sdp_ro_pending = true;
}
return 0;
}<|fim▁end|>
|
/* Remove 'video' media if not enabled (bug in chrome: doesn't honor 'has_video' parameter) */
if (!(this.e_type.i_id & tmedia_type_e.VIDEO.i_id)) {
this.o_sdp_lo.remove_media("video");
|
<|file_name|>sv.js<|end_file_name|><|fim▁begin|>OC.L10N.register(
"files",
{
"Storage is temporarily not available" : "Lagring är tillfälligt inte tillgänglig",
"Storage invalid" : "Lagring ogiltig",
"Unknown error" : "Okänt fel",
"File could not be found" : "Fil kunde inte hittas",
"Move or copy" : "Flytta eller kopiera",
"Download" : "Hämta",
"Delete" : "Ta bort",
"Home" : "Hem",
"Close" : "Stäng",
"Favorites" : "Favoriter",
"Could not create folder \"{dir}\"" : "Kunde inte skapa mapp \"{dir}\"",
"This will stop your current uploads." : "Detta kommer att stoppa nuvarande uppladdningar.",
"Upload cancelled." : "Uppladdning avbruten.",
"Processing files …" : "Bearbetar filer ...",
"…" : "...",
"Unable to upload {filename} as it is a directory or has 0 bytes" : "Kan inte ladda upp {filename} eftersom den antingen är en mapp eller har 0 bytes.",
"Not enough free space, you are uploading {size1} but only {size2} is left" : "Inte tillräckligt med ledigt utrymme, du laddar upp {size1} men endast {size2} finns kvar.",
"Target folder \"{dir}\" does not exist any more" : "Målmapp \"{dir}\" existerar inte mer",
"Not enough free space" : "Inte tillräckligt med ledigt utrymme",
"An unknown error has occurred" : "Ett okänt fel uppstod",
"Uploading …" : "Laddar upp ..",
"{loadedSize} of {totalSize} ({bitrate})" : "{loadedSize} av {totalSize} ({bitrate})",
"Uploading that item is not supported" : "Uppladdning av det här objektet stöds inte",
"Target folder does not exist any more" : "Målmapp existerar inte längre",
"Operation is blocked by access control" : "Operationen blockeras av åtkomstkontroll",
"Error when assembling chunks, status code {status}" : "Fel vid ihopsättning av bitarna: statuskod: {status}",
"Actions" : "Åtgärder",
"Rename" : "Byt namn",
"Copy" : "Kopiera",
"Choose target folder" : "Välj målmapp",
"Open" : "Öppna",
"Delete file" : "Ta bort fil",
"Delete folder" : "Ta bort mapp",
"Disconnect storage" : "Koppla bort lagring",
"Leave this share" : "Lämna denna delning",
"Could not load info for file \"{file}\"" : "Kunde inte läsa in information för filen \"{file}\"",
"Files" : "Filer",
"Details" : "Detaljer",
"Select" : "Välj",
"Pending" : "Väntar",
"Unable to determine date" : "Misslyckades avgöra datum",
"This operation is forbidden" : "Denna operation är förbjuden",
"This directory is unavailable, please check the logs or contact the administrator" : "Denna katalog är inte tillgänglig, vänligen kontrollera loggarna eller kontakta administratören",
"Could not move \"{file}\", target exists" : "Kunde inte flytta \"{file}\", filen existerar redan",
"Could not move \"{file}\"" : "Kunde inte flytta \"{file}\"",
"copy" : "kopia",
"Could not copy \"{file}\", target exists" : "Kunde inte kopiera \"{file}\", filen existerar redan",
"Could not copy \"{file}\"" : "Kunde inte kopiera \"{file}\"",
"Copied {origin} inside {destination}" : "Kopierade {origin} till {destination}",
"Copied {origin} and {nbfiles} other files inside {destination}" : "Kopierade {origin} och {nbfiles} andra filer i {destination}",
"{newName} already exists" : "{newName} existerar redan",
"Could not rename \"{fileName}\", it does not exist any more" : "Kunde inte döpa om \"{fileName}\", filen existerar inte mer",
"The name \"{targetName}\" is already used in the folder \"{dir}\". Please choose a different name." : "Namnet \"{targetName}\" används redan i mappen \"{dir}\". Vänligen välj ett annat namn.",
"Could not rename \"{fileName}\"" : "Kan inte döpa om \"{fileName}\"",
"Could not create file \"{file}\"" : "Kunde inte skapa fil \"{fileName}\"",
"Could not create file \"{file}\" because it already exists" : "Kunde inte skapa fil \"{file}\" därför att den redan existerar",
"Could not create folder \"{dir}\" because it already exists" : "Kunde inte skapa \"{dir}\" därför att den redan existerar",
"Could not fetch file details \"{file}\"" : "Kunde inte hämta filinformation \"{file}\"",
"Error deleting file \"{fileName}\"." : "Fel när \"{fileName}\" skulle raderas.",
"No search results in other folders for {tag}{filter}{endtag}" : "Inga sökresultat i andra mappar för {tag}{filter}{endtag}",
"Enter more than two characters to search in other folders" : "Ange mer än två tecken för att söka i andra mappar",
"Name" : "Namn",
"Size" : "Storlek",
"Modified" : "Ändrad",
"_%n folder_::_%n folders_" : ["%n mapp","%n mappar"],
"_%n file_::_%n files_" : ["%n fil","%n filer"],
"{dirs} and {files}" : "{dirs} och {files}",
"_including %n hidden_::_including %n hidden_" : ["inkluderar %n gömd","inkluderar %n gömda"],
"You don’t have permission to upload or create files here" : "Du har inte tillåtelse att ladda upp eller skapa filer här",
"_Uploading %n file_::_Uploading %n files_" : ["Laddar upp %n fil","Laddar upp %n filer"],
"New" : "Ny",
"Select file range" : "Välj filintervall",
"{used} of {quota} used" : "{used} av {quota} använt",
"{used} used" : "{used} använt",
"\"{name}\" is an invalid file name." : "\"{name}\" är ett ogiltigt filnamn.",
"File name cannot be empty." : "Filnamn kan inte vara tomt.",
"\"/\" is not allowed inside a file name." : "\"/\" är inte tillåtet i ett filnamn.",
"\"{name}\" is not an allowed filetype" : "\"{name}\" är inte en tillåten filtyp",
"Storage of {owner} is full, files can not be updated or synced anymore!" : "Lagring av {owner} är full, filer kan inte uppdateras eller synkroniseras längre!",
"Your storage is full, files can not be updated or synced anymore!" : "Ditt lagringsutrymme är fullt, filer kan inte längre uppdateras eller synkroniseras!",
"Storage of {owner} is almost full ({usedSpacePercent}%)." : "Lagring av {owner} är nästan full ({usedSpacePercent}%).",
"Your storage is almost full ({usedSpacePercent}%)." : "Ditt lagringsutrymme är nästan fullt ({usedSpacePercent}%).",
"_matches '{filter}'_::_match '{filter}'_" : ["matchar '{filter}'","matcha '{filter}'"],
"View in folder" : "Utforska i mapp",
"Copied!" : "Kopierad!",
"Copy direct link (only works for users who have access to this file/folder)" : "Kopiera direktlänk (fungerar endast för användare som har åtkomst till denna fil eller mapp)",
"Path" : "Sökväg",
"_%n byte_::_%n bytes_" : ["%n bytes","%n bytes"],
"Favorited" : "Favoriserad",
"Favorite" : "Favorit",
"You can only favorite a single file or folder at a time" : "Du kan bara favoritmarkera en fil eller mapp åt gången",
"New folder" : "Ny mapp",
"Upload file" : "Ladda upp fil",
"Recent" : "Senaste",
"Not favorited" : "Inte favoriserade",
"Remove from favorites" : "Ta bort från favoriter",
"Add to favorites" : "Lägg till i favoriter",
"An error occurred while trying to update the tags" : "Ett fel uppstod när uppdatera taggarna",
"Added to favorites" : "Lades till i favoriter",
"Removed from favorites" : "Togs bort från favoriter",
"You added {file} to your favorites" : "Du la till {file} till dina favoriter",
"You removed {file} from your favorites" : "Du tog bort {file} från dina favoriter",
"File changes" : "Filändringar",
"Created by {user}" : "Skapad av {user}",
"Changed by {user}" : "Ändrad av {user}",
"Deleted by {user}" : "Raderad av {user}",<|fim▁hole|> "Restored by {user}" : "Återställd av {user}",
"Renamed by {user}" : "Filnamn ändrat av {user}",
"Moved by {user}" : "Flyttad av {user}",
"\"remote user\"" : "\"extern användare\"",
"You created {file}" : "Du skapade {file}",
"You created an encrypted file in {file}" : "Du skapade en krypterad fil i {file}",
"{user} created {file}" : "{user} skapade {file}",
"{user} created an encrypted file in {file}" : "{user} skapade en krypterad fil i {file}",
"{file} was created in a public folder" : "{file} skapades i en offentlig mapp",
"You changed {file}" : "Du ändrade {file}",
"You changed an encrypted file in {file}" : "Du ändrade en krypterad fil i {file}",
"{user} changed {file}" : "{user} ändrade {file}",
"{user} changed an encrypted file in {file}" : "{user} ändrade en krypterad fil i {file}",
"You deleted {file}" : "Du tog bort {file}",
"You deleted an encrypted file in {file}" : "Du tog bort en krypterad fil i {file}",
"{user} deleted {file}" : "{user} tog bort {file}",
"{user} deleted an encrypted file in {file}" : "{user} tog bort en krypterad fil i {file}",
"You restored {file}" : "Du återställde {file}",
"{user} restored {file}" : "{user} återställde {file}",
"You renamed {oldfile} to {newfile}" : "Du ändrade filnamn {oldfile} till {newfile}",
"{user} renamed {oldfile} to {newfile}" : "{user} ändrade filnamn {oldfile} till {newfile}",
"You moved {oldfile} to {newfile}" : "Du flyttade {oldfile} till {newfile}",
"{user} moved {oldfile} to {newfile}" : "{user} flyttade {oldfile} till {newfile}",
"A file has been added to or removed from your <strong>favorites</strong>" : "En fil har lagts till eller tagits bort från dina <strong>favoriter</strong>",
"A file or folder has been <strong>changed</strong>" : "En ny fil eller mapp har blivit <strong>ändrad</strong>",
"A favorite file or folder has been <strong>changed</strong>" : "En favorit-fil eller mapp har blivit <strong>ändrad</strong>",
"All files" : "Alla filer",
"Unlimited" : "Obegränsad",
"Upload (max. %s)" : "Ladda upp (högst %s)",
"Accept" : "Acceptera",
"Reject" : "Avvisa",
"Incoming ownership transfer from {user}" : "Inkommande ägaröverföring från {user}",
"Do you want to accept {path}?\n\nNote: The transfer process after accepting may take up to 1 hour." : "Vill du acceptera {path}?\n\nNotera: Överföringen kan efter att du accepterat ta upp till 1 timme.",
"Ownership transfer failed" : "Ägarskapsöverföring misslyckades",
"Your ownership transfer of {path} to {user} failed." : "Din ägaröverföring av {path} till {user} misslyckades.",
"The ownership transfer of {path} from {user} failed." : "Din ägaröverföring av {path} från {user} misslyckades.",
"Ownership transfer done" : "Ägarskapsöverföring klar",
"Your ownership transfer of {path} to {user} has completed." : "Din ägaröverföring av {path} till {user} är klar.",
"The ownership transfer of {path} from {user} has completed." : "Ägaröverföringen av {path} från {user} är klar.",
"in %s" : "om %s",
"File Management" : "Filhantering",
"Transfer ownership of a file or folder" : "Överför ägarskap till en fil eller mapp",
"Choose file or folder to transfer" : "Välj fil eller mapp att överföra",
"Change" : "Ändra",
"New owner" : "Ny ägare",
"Search users" : "Sök användare",
"Choose a file or folder to transfer" : "Välj en fil eller mapp att överföra",
"Transfer" : "Överför",
"Transfer {path} to {userid}" : "Överför {path} till {userid}",
"Invalid path selected" : "Ogiltig sökväg vald",
"Ownership transfer request sent" : "Förfrågan om ägaröverföring skickad",
"Cannot transfer ownership of a file or folder you don't own" : "Det går inte att överföra ägarskap till en fil eller mapp som du inte äger",
"Tags" : "Taggar",
"Unable to change the favourite state of the file" : "Kan inte ändra filens favoritstatus",
"Error while loading the file data" : "Fel vid inläsning av fildata",
"%s used" : "%s använt",
"%s%% of %s used" : "%s%% av %s använt",
"%1$s of %2$s used" : "%1$s av %2$s använt",
"Settings" : "Inställningar",
"Show hidden files" : "Visa dolda filer",
"WebDAV" : "WebDAV",
"Use this address to access your Files via WebDAV" : "Använd denna adress för att komma åt dina filer med WebDAV",
"Toggle grid view" : "Växla rutnätsvy",
"No files in here" : "Inga filer kunde hittas",
"Upload some content or sync with your devices!" : "Ladda upp innehåll eller synkronisera med dina enheter!",
"No entries found in this folder" : "Inget innehåll hittades i denna mapp",
"Select all" : "Välj allt",
"Upload too large" : "För stor uppladdning",
"The files you are trying to upload exceed the maximum size for file uploads on this server." : "Filerna du försöker ladda upp överstiger den maximala storleken för filöverföringar på servern.",
"No favorites yet" : "Inga favoriter ännu",
"Files and folders you mark as favorite will show up here" : "Filer och mappar markerade som favoriter kommer att visas här",
"Deleted files" : "Borttagna filer",
"Shares" : "Delningar",
"Shared with others" : "Delad med andra",
"Shared with you" : "Delad med dig",
"Shared by link" : "Delad via länk",
"Deleted shares" : "Borttagna delningar",
"Pending shares" : "Väntande delningar",
"Text file" : "Textfil",
"New text file.txt" : "Ny textfil.txt",
"Unshare" : "Sluta dela",
"This group folder is full, files can not be updated or synced anymore!" : "Denna gruppmapp är full, filer kan inte uppdateras eller synkroniseras längre!",
"This external storage is full, files can not be updated or synced anymore!" : "Denna externa lagring är full, filer kan inte uppdateras eller synkroniseras längre!",
"Storage of {owner} is almost full ({usedSpacePercent}%)" : "Lagring av {owner} är nästan full ({usedSpacePercent}%)",
"This group folder is almost full ({usedSpacePercent}%)" : "Denna gruppmapp är nästan full ({usedSpacePercent}%)",
"This external storage is almost full ({usedSpacePercent}%)" : "Denna externa lagring är nästan full ({usedSpacePercent}%)",
"Your storage is almost full ({usedSpacePercent}%)" : "Ditt lagringsutrymme är nästan fullt ({usedSpacePercent}%)",
"A file or folder has been <strong>changed</strong> or <strong>renamed</strong>" : "En fil har blivit <strong>ändrad</strong> eller <strong>bytt namn</strong>",
"A new file or folder has been <strong>created</strong>" : "En ny fil eller mapp har blivit <strong>skapad</strong>",
"A file or folder has been <strong>deleted</strong>" : "En fil eller mapp har <strong>tagits bort</strong>",
"Limit notifications about creation and changes to your <strong>favorite files</strong> <em>(Stream only)</em>" : "Begränsa aviseringar om skapande och ändringar till dina <strong>favoritfiler</strong> <em>(Endast i flödet)</em>",
"A file or folder has been <strong>restored</strong>" : "En fil eller mapp har <strong>återställts</strong>",
"Cannot transfter ownership of a file or folder you don't own" : "Det går inte att överföra ägarskap till en fil eller mapp som du inte äger",
"Use this address to <a href=\"%s\" target=\"_blank\" rel=\"noreferrer noopener\">access your Files via WebDAV</a>" : "Använd denna adress för att <a href=\"%s\" target=\"_blank\" rel=\"noreferrer noopener\">komma åt dina filer med WebDAV</a>"
},
"nplurals=2; plural=(n != 1);");<|fim▁end|>
| |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright (c) 2013 LE GOFF Vincent
# 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<|fim▁hole|># THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
# OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""Package containing the different outputs.
Each output type is defined inside a module.
"""<|fim▁end|>
|
# without specific prior written permission.
#
|
<|file_name|>pairtree_revlookup.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
FS Pairtree storage - Reverse lookup
====================================
Conventions used:
From http://www.cdlib.org/inside/diglib/pairtree/pairtreespec.html version 0.1
This is an implementation of a reverse lookup index, using the pairtree path spec to
record the link between local id and the id's that it corresponds to.
eg to denote issn:1234-1234 as being linked to a global id of "uuid:1e4f..."
--> create a file at ROOT_DIR/pairtree_rl/is/sn/+1/23/4-/12/34/uuid+1e4f...
Note that the id it links to is recorded as a filename encoded as per the pairtree spec.
Usage
=====
>>> from pairtree import PairtreeReverseLookup
>>> rl = PairtreeReverseLookup(storage_dir="ROOT")
>>> rl["issn:1234-1234"].append("uuid:1e4f...")
>>> rl["issn:1234-1234"]
["uuid:1e4f"]
>>> rl["issn:1234-1234"] = ["id:1", "uuid:32fad..."]
>>>
Notes
=====
This was created to avoid certain race conditions I had with a pickled dictionary for this index.
A sqllite or similar lookup would also be effective, but this one relies solely on pairtree.
"""
import os
from pairtree.pairtree_path import id_encode, id_decode, id_to_dirpath
PAIRTREE_RL = "pairtree_rl"
class PairtreeReverseLookup_list(object):
def __init__(self, rl_dir, id):
self._rl_dir = rl_dir
self._id = id
self._dirpath = id_to_dirpath(self._id, self._rl_dir)
def _get_ids(self):
if os.path.isdir(self._dirpath):
ids = []
for f in os.listdir(self._dirpath):
ids.append(id_decode(f))
return ids
else:
return []
def _add_id(self, new_id):
if not os.path.exists(self._dirpath):
os.makedirs(self._dirpath)
enc_id = id_encode(new_id)
if not os.path.isfile(enc_id):
with open(os.path.join(self._dirpath, enc_id), "w") as f:
f.write(new_id)
def _exists(self, id):
if os.path.exists(self._dirpath):
return id_encode(id) in os.listdir(self._dirpath)
else:
return False
def append(self, *args):
[self._add_id(x) for x in args if not self._exists(x)]
def __len__(self):
return len(os.listdir(self._dirpath))
def __repr__(self):
return "ID:'%s' -> ['%s']" % (self._id, "','".join(self._get_ids()))
def __str__(self):
return self.__repr__()
def __iter__(self):
for f in self._get_ids():
yield id_decode(f)
class PairtreeReverseLookup(object):
def __init__(self, storage_dir="data"):
self._storage_dir = storage_dir
self._rl_dir = os.path.join(storage_dir, PAIRTREE_RL)
self._init_store()
def _init_store(self):
if not os.path.isdir(self._storage_dir):
os.makedirs(self._storage_dir)
def __getitem__(self, id):<|fim▁hole|> return PairtreeReverseLookup_list(self._rl_dir, id)
def __setitem__(self, id, value):
id_c = PairtreeReverseLookup_list(self._rl_dir, id)
if isinstance(list, value):
id_c.append(*value)
else:
id_c.append(value)
def __delitem__(self, id):
dirpath = id_to_dirpath(id, self._rl_dir)
if os.path.isdir(dirpath):
for f in os.listdir(dirpath):
os.remove(os.path.join(dirpath, f))
os.removedirs(dirpath) # will throw OSError if the dir cannot be removed.
self._init_store() # just in case<|fim▁end|>
| |
<|file_name|>Logs.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python
# encoding: utf-8
# WARNING! Do not edit! https://waf.io/book/index.html#_obtaining_the_waf_file
import os,re,traceback,sys
from waflib import Utils,ansiterm
if not os.environ.get('NOSYNC',False):
if sys.stdout.isatty()and id(sys.stdout)==id(sys.__stdout__):
sys.stdout=ansiterm.AnsiTerm(sys.stdout)
if sys.stderr.isatty()and id(sys.stderr)==id(sys.__stderr__):
sys.stderr=ansiterm.AnsiTerm(sys.stderr)
import logging
LOG_FORMAT=os.environ.get('WAF_LOG_FORMAT','%(asctime)s %(c1)s%(zone)s%(c2)s %(message)s')
HOUR_FORMAT=os.environ.get('WAF_HOUR_FORMAT','%H:%M:%S')
zones=[]
verbose=0
colors_lst={'USE':True,'BOLD':'\x1b[01;1m','RED':'\x1b[01;31m','GREEN':'\x1b[32m','YELLOW':'\x1b[33m','PINK':'\x1b[35m','BLUE':'\x1b[01;34m','CYAN':'\x1b[36m','GREY':'\x1b[37m','NORMAL':'\x1b[0m','cursor_on':'\x1b[?25h','cursor_off':'\x1b[?25l',}
indicator='\r\x1b[K%s%s%s'
try:
unicode
except NameError:
unicode=None
def enable_colors(use):
if use==1:
if not(sys.stderr.isatty()or sys.stdout.isatty()):
use=0
if Utils.is_win32 and os.name!='java':
term=os.environ.get('TERM','')
else:
term=os.environ.get('TERM','dumb')
if term in('dumb','emacs'):
use=0
if use>=1:
os.environ['TERM']='vt100'<|fim▁hole|> def get_term_cols():
return 80
get_term_cols.__doc__="""
Returns the console width in characters.
:return: the number of characters per line
:rtype: int
"""
def get_color(cl):
if colors_lst['USE']:
return colors_lst.get(cl,'')
return''
class color_dict(object):
def __getattr__(self,a):
return get_color(a)
def __call__(self,a):
return get_color(a)
colors=color_dict()
re_log=re.compile(r'(\w+): (.*)',re.M)
class log_filter(logging.Filter):
def __init__(self,name=''):
logging.Filter.__init__(self,name)
def filter(self,rec):
global verbose
rec.zone=rec.module
if rec.levelno>=logging.INFO:
return True
m=re_log.match(rec.msg)
if m:
rec.zone=m.group(1)
rec.msg=m.group(2)
if zones:
return getattr(rec,'zone','')in zones or'*'in zones
elif not verbose>2:
return False
return True
class log_handler(logging.StreamHandler):
def emit(self,record):
try:
try:
self.stream=record.stream
except AttributeError:
if record.levelno>=logging.WARNING:
record.stream=self.stream=sys.stderr
else:
record.stream=self.stream=sys.stdout
self.emit_override(record)
self.flush()
except(KeyboardInterrupt,SystemExit):
raise
except:
self.handleError(record)
def emit_override(self,record,**kw):
self.terminator=getattr(record,'terminator','\n')
stream=self.stream
if unicode:
msg=self.formatter.format(record)
fs='%s'+self.terminator
try:
if(isinstance(msg,unicode)and getattr(stream,'encoding',None)):
fs=fs.decode(stream.encoding)
try:
stream.write(fs%msg)
except UnicodeEncodeError:
stream.write((fs%msg).encode(stream.encoding))
else:
stream.write(fs%msg)
except UnicodeError:
stream.write((fs%msg).encode('utf-8'))
else:
logging.StreamHandler.emit(self,record)
class formatter(logging.Formatter):
def __init__(self):
logging.Formatter.__init__(self,LOG_FORMAT,HOUR_FORMAT)
def format(self,rec):
try:
msg=rec.msg.decode('utf-8')
except Exception:
msg=rec.msg
use=colors_lst['USE']
if(use==1 and rec.stream.isatty())or use==2:
c1=getattr(rec,'c1',None)
if c1 is None:
c1=''
if rec.levelno>=logging.ERROR:
c1=colors.RED
elif rec.levelno>=logging.WARNING:
c1=colors.YELLOW
elif rec.levelno>=logging.INFO:
c1=colors.GREEN
c2=getattr(rec,'c2',colors.NORMAL)
msg='%s%s%s'%(c1,msg,c2)
else:
msg=re.sub(r'\r(?!\n)|\x1B\[(K|.*?(m|h|l))','',msg)
if rec.levelno>=logging.INFO:
if rec.args:
return msg%rec.args
return msg
rec.msg=msg
rec.c1=colors.PINK
rec.c2=colors.NORMAL
return logging.Formatter.format(self,rec)
log=None
def debug(*k,**kw):
global verbose
if verbose:
k=list(k)
k[0]=k[0].replace('\n',' ')
global log
log.debug(*k,**kw)
def error(*k,**kw):
global log,verbose
log.error(*k,**kw)
if verbose>2:
st=traceback.extract_stack()
if st:
st=st[:-1]
buf=[]
for filename,lineno,name,line in st:
buf.append(' File %r, line %d, in %s'%(filename,lineno,name))
if line:
buf.append(' %s'%line.strip())
if buf:log.error('\n'.join(buf))
def warn(*k,**kw):
global log
log.warn(*k,**kw)
def info(*k,**kw):
global log
log.info(*k,**kw)
def init_log():
global log
log=logging.getLogger('waflib')
log.handlers=[]
log.filters=[]
hdlr=log_handler()
hdlr.setFormatter(formatter())
log.addHandler(hdlr)
log.addFilter(log_filter())
log.setLevel(logging.DEBUG)
def make_logger(path,name):
logger=logging.getLogger(name)
hdlr=logging.FileHandler(path,'w')
formatter=logging.Formatter('%(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.DEBUG)
return logger
def make_mem_logger(name,to_log,size=8192):
from logging.handlers import MemoryHandler
logger=logging.getLogger(name)
hdlr=MemoryHandler(size,target=to_log)
formatter=logging.Formatter('%(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.memhandler=hdlr
logger.setLevel(logging.DEBUG)
return logger
def free_logger(logger):
try:
for x in logger.handlers:
x.close()
logger.removeHandler(x)
except Exception:
pass
def pprint(col,msg,label='',sep='\n'):
global info
info('%s%s%s %s',colors(col),msg,colors.NORMAL,label,extra={'terminator':sep})<|fim▁end|>
|
colors_lst['USE']=use
try:
get_term_cols=ansiterm.get_term_cols
except AttributeError:
|
<|file_name|>home.js<|end_file_name|><|fim▁begin|>'use strict';
angular.module('myApp.home', ['ngRoute'])
// Declared route
.config(['$routeProvider', function($routeProvider) {<|fim▁hole|>}])
// Home controller
.controller('HomeCtrl', [function() {
}]);<|fim▁end|>
|
$routeProvider.when('/home', {
templateUrl: 'views/home/home.html',
controller: 'HomeCtrl'
});
|
<|file_name|>test_figure.py<|end_file_name|><|fim▁begin|>from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
from six.moves import xrange
from nose.tools import assert_equal, assert_true
from matplotlib.testing.decorators import image_comparison, cleanup
from matplotlib.axes import Axes
import matplotlib.pyplot as plt
import numpy as np
@cleanup
def test_figure_label():
# pyplot figure creation, selection and closing with figure label and
# number
plt.close('all')
plt.figure('today')
plt.figure(3)
plt.figure('tomorrow')
plt.figure()
plt.figure(0)
plt.figure(1)
plt.figure(3)
assert_equal(plt.get_fignums(), [0, 1, 3, 4, 5])
assert_equal(plt.get_figlabels(), ['', 'today', '', 'tomorrow', ''])
plt.close(10)
plt.close()
plt.close(5)
plt.close('tomorrow')
assert_equal(plt.get_fignums(), [0, 1])
assert_equal(plt.get_figlabels(), ['', 'today'])
@cleanup
def test_fignum_exists():
# pyplot figure creation, selection and closing with fignum_exists
plt.figure('one')
plt.figure(2)
plt.figure('three')
plt.figure()
assert_equal(plt.fignum_exists('one'), True)
assert_equal(plt.fignum_exists(2), True)
assert_equal(plt.fignum_exists('three'), True)
assert_equal(plt.fignum_exists(4), True)
plt.close('one')
plt.close(4)
assert_equal(plt.fignum_exists('one'), False)
assert_equal(plt.fignum_exists(4), False)
@image_comparison(baseline_images=['figure_today'])
def test_figure():
# named figure support
fig = plt.figure('today')
ax = fig.add_subplot(111)
ax.set_title(fig.get_label())
ax.plot(list(xrange(5)))
# plot red line in a different figure.
plt.figure('tomorrow')
plt.plot([0, 1], [1, 0], 'r')
# Return to the original; make sure the red line is not there.
plt.figure('today')
plt.close('tomorrow')
@cleanup
def test_gca():
fig = plt.figure()
ax1 = fig.add_axes([0, 0, 1, 1])
assert_true(fig.gca(projection='rectilinear') is ax1)
assert_true(fig.gca() is ax1)
ax2 = fig.add_subplot(121, projection='polar')
assert_true(fig.gca() is ax2)
assert_true(fig.gca(polar=True)is ax2)
ax3 = fig.add_subplot(122)
assert_true(fig.gca() is ax3)
# the final request for a polar axes will end up creating one
# with a spec of 111.
assert_true(fig.gca(polar=True) is not ax3)
assert_true(fig.gca(polar=True) is not ax2)
assert_equal(fig.gca().get_geometry(), (1, 1, 1))
fig.sca(ax1)
assert_true(fig.gca(projection='rectilinear') is ax1)
assert_true(fig.gca() is ax1)
@image_comparison(baseline_images=['figure_suptitle'])
def test_suptitle():
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
fig.suptitle('hello', color='r')
fig.suptitle('title', color='g', rotation='30')
@cleanup
def test_suptitle_fontproperties():
from matplotlib.font_manager import FontProperties
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
fps = FontProperties(size='large', weight='bold')
txt = fig.suptitle('fontprops title', fontproperties=fps)
assert_equal(txt.get_fontsize(), fps.get_size_in_points())
assert_equal(txt.get_weight(), fps.get_weight())
@image_comparison(baseline_images=['alpha_background'],
# only test png and svg. The PDF output appears correct,
# but Ghostscript does not preserve the background color.
extensions=['png', 'svg'],
savefig_kwarg={'facecolor': (0, 1, 0.4),
'edgecolor': 'none'})
def test_alpha():
# We want an image which has a background color and an
# alpha of 0.4.
fig = plt.figure(figsize=[2, 1])
fig.set_facecolor((0, 1, 0.4))
fig.patch.set_alpha(0.4)
import matplotlib.patches as mpatches
fig.patches.append(mpatches.CirclePolygon([20, 20],
radius=15,
alpha=0.6,
facecolor='red'))
@cleanup
def test_too_many_figures():
import warnings
with warnings.catch_warnings(record=True) as w:
for i in range(22):
fig = plt.figure()
assert len(w) == 1
def test_iterability_axes_argument():
# This is a regression test for matplotlib/matplotlib#3196. If one of the
# arguments returned by _as_mpl_axes defines __getitem__ but is not
# iterable, this would raise an execption. This is because we check
# whether the arguments are iterable, and if so we try and convert them
# to a tuple. However, the ``iterable`` function returns True if
# __getitem__ is present, but some classes can define __getitem__ without
# being iterable. The tuple conversion is now done in a try...except in
# case it fails.
class MyAxes(Axes):
def __init__(self, *args, **kwargs):
kwargs.pop('myclass', None)
return Axes.__init__(self, *args, **kwargs)
class MyClass(object):
def __getitem__(self, item):
if item != 'a':
raise ValueError("item should be a")
def _as_mpl_axes(self):
return MyAxes, {'myclass': self}
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection=MyClass())
plt.close(fig)
@cleanup
def test_set_fig_size():
fig = plt.figure()
# check figwidth
fig.set_figwidth(5)
assert_equal(fig.get_figwidth(), 5)
# check figheight
fig.set_figheight(1)
assert_equal(fig.get_figheight(), 1)
# check using set_size_inches
fig.set_size_inches(2, 4)
assert_equal(fig.get_figwidth(), 2)
assert_equal(fig.get_figheight(), 4)
# check using tuple to first argument
fig.set_size_inches((1, 3))
assert_equal(fig.get_figwidth(), 1)
assert_equal(fig.get_figheight(), 3)
@cleanup
def test_axes_remove():
fig, axes = plt.subplots(2, 2)
axes[-1, -1].remove()
for ax in axes.ravel()[:-1]:
assert ax in fig.axes<|fim▁hole|> assert_equal(len(fig.axes), 3)
def test_figaspect():
w, h = plt.figaspect(np.float64(2) / np.float64(1))
assert h / w == 2
w, h = plt.figaspect(2)
assert h / w == 2
w, h = plt.figaspect(np.zeros((1, 2)))
assert h / w == 0.5
w, h = plt.figaspect(np.zeros((2, 2)))
assert h / w == 1
if __name__ == "__main__":
import nose
nose.runmodule(argv=['-s', '--with-doctest'], exit=False)<|fim▁end|>
|
assert axes[-1, -1] not in fig.axes
|
<|file_name|>wiki.js<|end_file_name|><|fim▁begin|>// Runs the wiki on port 80<|fim▁hole|>
var server = require('./server');
server.run(80);<|fim▁end|>
| |
<|file_name|>test_extensions.py<|end_file_name|><|fim▁begin|># Copyright 2012 OpenStack Foundation
# 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<|fim▁hole|>#
# 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 oslo_log import log as logging
from tempest.api.compute import base
from tempest import config
from tempest import test
CONF = config.CONF
LOG = logging.getLogger(__name__)
class ExtensionsTestJSON(base.BaseV2ComputeTest):
@test.idempotent_id('3bb27738-b759-4e0d-a5fa-37d7a6df07d1')
def test_list_extensions(self):
# List of all extensions
if len(CONF.compute_feature_enabled.api_extensions) == 0:
raise self.skipException('There are not any extensions configured')
extensions = self.extensions_client.list_extensions()['extensions']
ext = CONF.compute_feature_enabled.api_extensions[0]
if ext == 'all':
self.assertIn('Hosts', map(lambda x: x['name'], extensions))
elif ext:
self.assertIn(ext, map(lambda x: x['alias'], extensions))
else:
raise self.skipException('There are not any extensions configured')
# Log extensions list
extension_list = map(lambda x: x['alias'], extensions)
LOG.debug("Nova extensions: %s" % ','.join(extension_list))
@test.idempotent_id('05762f39-bdfa-4cdb-9b46-b78f8e78e2fd')
@test.requires_ext(extension='os-consoles', service='compute')
def test_get_extension(self):
# get the specified extensions
extension = self.extensions_client.show_extension('os-consoles')
self.assertEqual('os-consoles', extension['extension']['alias'])<|fim▁end|>
| |
<|file_name|>dialogues.py<|end_file_name|><|fim▁begin|>"""
EDENetworks, a genetic network analyzer
Copyright (C) 2011 Aalto University
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""
"""
Collection of dialogue windows
"""
import pynet,os,netio,netext,visuals,eden,transforms
import random
import heapq
import string
import percolator
import shutil
from math import ceil
from Tkinter import *
import tkMessageBox
#from pylab import *
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg,NavigationToolbar2TkAgg
# NEW DIALOGUE WINDOWS / JS / MAY-JUNE 09
class MySimpleDialog(Toplevel):
'''Master class for a dialog popup window.
Functions body() and apply() to be overridden
with whatever the dialog should be doing.'''
def __init__(self,parent,title=None):
Toplevel.__init__(self,parent)
self.transient(parent)
self.title(title)
self.parent=parent
self.result=None
body=Frame(self)
self.initial_focus=self.body(self,body)
body.pack(padx=5,pady=5)
self.buttonbox()
self.grab_set()
if not self.initial_focus:
self.initial_focus(self)
self.protocol("WM_DELETE_WINDOW",self.cancel)
self.geometry("+%d+%d" % (parent.winfo_rootx()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)
def body(self,masterclass,masterwindow):
pass
def buttonbox(self):
"""OK and Cancel buttons"""
box=Frame(self)
w=Button(box,text="OK",width=10,command=self.ok,default=ACTIVE)
w.pack(side=LEFT,padx=5,pady=5)
w=Button(box,text="Cancel",width=10,command=self.cancel)<|fim▁hole|>
self.bind("<Return>",self.ok)
self.bind("<Escape",self.cancel)
box.pack()
def ok(self,event=None):
if not self.validate():
self.initial_focus.focus_set()
return
self.withdraw()
self.update_idletasks()
self.applyme()
self.cancel()
def cancel(self,event=None):
self.parent.focus_set()
self.destroy()
def validate(self):
return 1
def applyme(self):
pass
def displayBusyCursor(self):
self.parent.configure(cursor='watch')
self.parent.update()
self.parent.after_idle(self.removeBusyCursor)
def removeBusyCursor(self):
self.parent.configure(cursor='arrow')
class WLogbinDialog(MySimpleDialog):
"""Asks for the number of bins for log binning
and allows linear bins for 1...10"""
def __init__(self,parent,title=None):
Toplevel.__init__(self,parent)
self.configure(bg='Gray80')
self.transient(parent)
if title:
self.title=title
self.parent=parent
self.result=None
self.linfirst=IntVar()
self.numbins=StringVar()
body=Frame(self,bg='Gray80')
self.initial_focus=self.body(self,body)
body.pack(padx=5,pady=5)
self.buttonbox()
self.grab_set()
if not self.initial_focus:
self.initial_focus(self)
self.protocol("WM_DELETE_WINDOW",self.cancel)
self.geometry("+%d+%d" % (parent.winfo_rootx()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)
def body(self,masterclass,masterwindow):
self.b1=Checkbutton(masterwindow,text='Use linear bins for 1..10',variable=masterclass.linfirst,state=ACTIVE,bg='Gray80')
self.b1.grid(row=0,column=0,columnspan=2)
Label(masterwindow,text='Number of bins:',bg='Gray80').grid(row=1,column=0)
self.c1=Entry(masterwindow,textvariable=masterclass.numbins,bg='Gray95')
masterclass.numbins.set('30')
self.c1.grid(row=1,column=1)
return self.c1
def applyme(self):
self.result=[self.linfirst.get(),float(self.numbins.get())]
class LoadMatrixDialog(MySimpleDialog):
"""Asks for the number of bins for log binning
and allows linear bins for 1...10"""
def __init__(self,parent,title='Please provide information:'):
Toplevel.__init__(self,parent)
# self.configure(bg='Gray80')
# self.transient(parent)
self.title(title)
self.parent=parent
self.result=None
self.clones=StringVar()
self.measuretype=StringVar()
body=Frame(self)
self.initial_focus=self.body(self,body)
body.pack(padx=5,pady=5)
self.buttonbox()
self.grab_set()
if not self.initial_focus:
self.initial_focus(self)
self.protocol("WM_DELETE_WINDOW",self.cancel)
self.geometry("+%d+%d" % (parent.winfo_rootx()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)
def body(self,masterclass,masterwindow):
self.c1=Label(masterwindow,text='What distance measure has been used?',bg='DarkOliveGreen2',anchor=W)
self.c1.grid(row=0,column=0)
r1=Radiobutton(masterwindow,text='Non-shared alleles',value='nsa',variable=masterclass.measuretype)
r2=Radiobutton(masterwindow,text='Linear Manhattan',value='lm',variable=masterclass.measuretype)
r3=Radiobutton(masterwindow,text='Allele parsimony',value='ap',variable=masterclass.measuretype)
r4=Radiobutton(masterwindow,text='Hybrid',value="hybrid",variable=masterclass.measuretype)
r5=Radiobutton(masterwindow,text='Other',value="other",variable=masterclass.measuretype)
r1.grid(row=1,column=0,sticky=W)
r2.grid(row=2,column=0,sticky=W)
r3.grid(row=3,column=0,sticky=W)
r4.grid(row=4,column=0,sticky=W)
r5.grid(row=5,column=0,sticky=W)
self.c2=Label(masterwindow,text='How have clones been handled?',bg='DarkOliveGreen2',anchor=W)
self.c2.grid(row=6,column=0)
r6=Radiobutton(masterwindow,text='Removed',value='collapsed',variable=masterclass.clones)
r7=Radiobutton(masterwindow,text='Kept',value='included',variable=masterclass.clones)
r8=Radiobutton(masterwindow,text='Unknown',value='unknown',variable=masterclass.clones)
r6.grid(row=7,column=0,sticky=W)
r7.grid(row=8,column=0,sticky=W)
r8.grid(row=9,column=0,sticky=W)
masterclass.measuretype.set('other')
masterclass.clones.set('unknown')
return self.c1
def applyme(self):
self.result=[self.measuretype.get(),self.clones.get()]
class MetaHelpWindow(MySimpleDialog):
def __init__(self,parent,title=None,datatype='msat'):
Toplevel.__init__(self,parent)
self.configure(bg='Gray80')
self.transient(parent)
self.datatype=datatype
if title:
self.title=title
self.parent=parent
self.result=None
self.linfirst=IntVar()
self.numbins=StringVar()
body=Frame(self,bg='Gray80')
self.initial_focus=self.body(self,body)
body.pack(padx=5,pady=5)
self.buttonbox()
self.grab_set()
if not self.initial_focus:
self.initial_focus(self)
self.protocol("WM_DELETE_WINDOW",self.cancel)
self.geometry("+%d+%d" % (parent.winfo_rootx()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)
def body(self,masterclass,masterwindow):
self.text=Text(self,bg='Gray90')
self.text.pack(expand=YES,fill=BOTH)
str1="Auxiliary data files are used for reading node properties, such as labels, classes, and sampling sites. "
str2="File format is ASCII, such that each row lists properties for a node. \n"
str3="The first row must contain HEADERS, i.e. labels for the properties. \n\n"
str4="Example for the first row: \n node_label node_site node_latitude node_longitude node_geoclass \n"
if self.datatype=='net':
str4=str4+"\nWhen the input data is a network (.edg,.gml), THE FIRST HEADER COLUMN MUST BE node_label, "
str4=str4+"and there must be a row for each node in the original network, using original node labels."
str4=str4+"If you have saved the node properties in EDEN Analyzer, this has been taken care of already."
if self.datatype=='msat':
str4=str4+"\nThere must be one row for each row in the original microsatellite data file. "
if self.datatype=="dmat":
str4=str4+"\nThere must be one row for each row in the original distance matrix file. "
self.text.insert(INSERT,str1+str2+str3+str4)
class AskNumberOfBins(MySimpleDialog):
"""Asks for number of bins for binning"""
def __init__(self,parent,title=None):
Toplevel.__init__(self,parent)
#self.configure(bg='Gray80')
# self.transient(parent)
if title:
self.title=title
self.parent=parent
self.result=None
# self.linfirst=IntVar()
self.numbins=StringVar()
body=Frame(self)
self.initial_focus=self.body(self,body)
body.pack(padx=5,pady=5)
self.buttonbox()
self.grab_set()
if not self.initial_focus:
self.initial_focus(self)
self.protocol("WM_DELETE_WINDOW",self.cancel)
self.geometry("+%d+%d" % (parent.winfo_rootx()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)
def body(self,masterclass,masterwindow):
# self.b1=Checkbutton(masterwindow,text='Use linear bins for 1..10',variable=masterclass.linfirst,state=ACTIVE,bg='Gray80')
# self.b1.grid(row=0,column=0,columnspan=2)
Label(masterwindow,text='Number of bins:').grid(row=1,column=0)
self.c1=Entry(masterwindow,textvariable=masterclass.numbins,bg='Gray95')
masterclass.numbins.set('30')
self.c1.grid(row=1,column=1)
return self.c1
def applyme(self):
self.result=float(self.numbins.get())
def validate(self):
userstr=self.numbins.get()
try:
nbins=int(userstr)
except Exception:
tkMessageBox.showerror(
"Error:",
"Number of bins must be an integer.")
return 0
if nbins<2:
tkMessageBox.showerror(
"Error:",
"Number of bins must be larger than one.")
return 0
return 1
class ProjectLaunchDialog(MySimpleDialog):
"""First window shown when launching a new analysis wizard.
Inquires if the user wants to load microsatellite data,
a distance matrix, or a network file."""
def __init__(self,parent,title=None):
Toplevel.__init__(self,parent)
#self.configure(bg='Gray80')
# self.transient(parent)
self.title("New analysis project")
self.parent=parent
self.result=None
self.datatype=StringVar()
# self.linfirst=IntVar()
body=Frame(self)
self.initial_focus=self.body(self,body)
body.pack(padx=5,pady=5)
self.buttonbox()
self.grab_set()
if not self.initial_focus:
self.initial_focus(self)
self.protocol("WM_DELETE_WINDOW",self.cancel)
self.geometry("+%d+%d" % (parent.winfo_rootx()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)
def body(self,masterclass,masterwindow):
# self.b1=Checkbutton(masterwindow,text='Use linear bins for 1..10',variable=masterclass.linfirst,state=ACTIVE,bg='Gray80')
# self.b1.grid(row=0,column=0,columnspan=2)
self.wholeframe=Frame(masterwindow,relief='sunken',borderwidth=2)
self.clabel=Label(self.wholeframe,text="Select input data type:",justify=LEFT,anchor=W,bg='gray90',relief='groove',borderwidth=1)
self.clabel.pack(side=TOP,expand=YES,fill=X,ipadx=5,ipady=5)
self.bottompart=Frame(self.wholeframe)
r1=Radiobutton(self.bottompart,text='Genotype matrix, haploid, individual centred',value='ms_haploid',variable=masterclass.datatype)
r125=Radiobutton(self.bottompart,text='Genotype matrix, diploid, individual centred',value='ms_diploid',variable=masterclass.datatype)
r15=Radiobutton(self.bottompart,text='Genotype matrix, haploid, sampling site based',value='mpop_haploid',variable=masterclass.datatype)
r175=Radiobutton(self.bottompart,text='Genotype matrix, diploid, sampling site based',value='mpop_diploid',variable=masterclass.datatype)
r1875=Radiobutton(self.bottompart,text='Presence/absence matrix',value='presabs',variable=masterclass.datatype)
r19=Radiobutton(self.bottompart,text='Presence/abundancy matrix',value='presabu',variable=masterclass.datatype)
r2=Radiobutton(self.bottompart,text='Distance matrix',value='dmat',variable=masterclass.datatype)
r3=Radiobutton(self.bottompart,text='Network data',value='net',variable=masterclass.datatype)
r1.grid(row=1,column=0,sticky=W)
r125.grid(row=3,column=0,sticky=W)
r15.grid(row=2,column=0,sticky=W)
r175.grid(row=4,column=0,sticky=W)
r1875.grid(row=5,column=0,sticky=W)
r19.grid(row=6,column=0,sticky=W)
r2.grid(row=7,column=0,sticky=W)
r3.grid(row=8,column=0,sticky=W)
self.bottompart.pack(side=TOP,expand=YES,fill=BOTH,ipadx=7,ipady=7)
masterclass.datatype.set('ms_haploid')
self.wholeframe.pack(side=TOP,expand=YES,fill=BOTH)
return self.wholeframe
def applyme(self):
self.result=(self.datatype.get())
class ChooseMatrixNodeNames(MySimpleDialog):
"""First window shown when launching a new analysis wizard.
Inquires if the user wants to load microsatellite data,
a distance matrix, or a network file."""
def __init__(self,parent,title=None,titlemsg="How to set node labels?"):
Toplevel.__init__(self,parent)
#self.configure(bg='Gray80')
# self.transient(parent)
self.title(title)
self.titlemsg=titlemsg
self.parent=parent
self.result=None
self.measuretype=StringVar()
# self.linfirst=IntVar()
body=Frame(self)
self.initial_focus=self.body(self,body)
body.pack(padx=5,pady=5)
self.buttonbox()
self.grab_set()
if not self.initial_focus:
self.initial_focus(self)
self.protocol("WM_DELETE_WINDOW",self.cancel)
self.geometry("+%d+%d" % (parent.winfo_rootx()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)
def body(self,masterclass,masterwindow,titlemsg="How to set node labels?"):
self.wholeframe=Frame(masterwindow,relief='sunken',borderwidth=2)
self.clabel=Label(self.wholeframe,text=self.titlemsg,justify=LEFT,anchor=W,bg='gray90',relief='groove',borderwidth=1)
self.clabel.pack(side=TOP,expand=YES,fill=X,ipadx=5,ipady=5)
self.bottompart=Frame(self.wholeframe)
r1=Radiobutton(self.bottompart,text='From file',value='file',variable=masterclass.measuretype)
r2=Radiobutton(self.bottompart,text='1..N',value='numbers',variable=masterclass.measuretype)
r1.grid(row=1,column=0,sticky=W)
r2.grid(row=2,column=0,sticky=W)
self.bottompart.pack(side=TOP,expand=YES,fill=BOTH,ipadx=7,ipady=7)
masterclass.measuretype.set('nsa')
self.wholeframe.pack(side=TOP,expand=YES,fill=BOTH)
return self.wholeframe
def applyme(self):
self.result=(self.measuretype.get())
class ChooseDistanceMeasure(MySimpleDialog):
"""First window shown when launching a new analysis wizard.
Inquires if the user wants to load microsatellite data,
a distance matrix, or a network file."""
def __init__(self,parent,title=None,titlemsg="Choose genetic distance measure"):
Toplevel.__init__(self,parent)
#self.configure(bg='Gray80')
# self.transient(parent)
self.title(title)
self.titlemsg=titlemsg
self.parent=parent
self.result=None
self.measuretype=StringVar()
# self.linfirst=IntVar()
body=Frame(self)
self.initial_focus=self.body(self,body)
body.pack(padx=5,pady=5)
self.buttonbox()
self.grab_set()
if not self.initial_focus:
self.initial_focus(self)
self.protocol("WM_DELETE_WINDOW",self.cancel)
self.geometry("+%d+%d" % (parent.winfo_rootx()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)
def body(self,masterclass,masterwindow,titlemsg="Choose genetic distance measure"):
# self.b1=Checkbutton(masterwindow,text='Use linear bins for 1..10',variable=masterclass.linfirst,state=ACTIVE,bg='Gray80')
# self.b1.grid(row=0,column=0,columnspan=2)
self.wholeframe=Frame(masterwindow,relief='sunken',borderwidth=2)
self.clabel=Label(self.wholeframe,text=self.titlemsg,justify=LEFT,anchor=W,bg='gray90',relief='groove',borderwidth=1)
self.clabel.pack(side=TOP,expand=YES,fill=X,ipadx=5,ipady=5)
self.bottompart=Frame(self.wholeframe)
#r1=Radiobutton(self.bottompart,text='Non-shared alleles',value='nsa',variable=masterclass.measuretype)
r1=Radiobutton(self.bottompart,text='Allele Sharing',value='ap',variable=masterclass.measuretype)
r2=Radiobutton(self.bottompart,text='Linear Manhattan',value='lm',variable=masterclass.measuretype)
#r3=Radiobutton(self.bottompart,text='Allele parsimony',value='ap',variable=masterclass.measuretype)
#r4=Radiobutton(self.bottompart,text='Hybrid',value="hybrid",variable=masterclass.measuretype)
r1.grid(row=1,column=0,sticky=W)
r2.grid(row=2,column=0,sticky=W)
#r3.grid(row=3,column=0,sticky=W)
#r4.grid(row=4,column=0,sticky=W)
self.bottompart.pack(side=TOP,expand=YES,fill=BOTH,ipadx=7,ipady=7)
masterclass.measuretype.set('nsa')
self.wholeframe.pack(side=TOP,expand=YES,fill=BOTH)
return self.wholeframe
def applyme(self):
self.result=(self.measuretype.get())
class ImportMetadataYesNo(MySimpleDialog):
"""First window shown when launching a new analysis wizard.
Inquires if the user wants to load microsatellite data,
a distance matrix, or a network file."""
def __init__(self,parent,title=None,titlemsg="Do you want to import auxiliary node data?",datatype='msat'):
Toplevel.__init__(self,parent)
#self.configure(bg='Gray80')
# self.transient(parent)
self.title(title)
self.datatype=datatype
self.titlemsg=titlemsg
self.parent=parent
self.result=None
self.metatype=IntVar()
# self.linfirst=IntVar()
body=Frame(self)
self.initial_focus=self.body(self,body)
body.pack(padx=5,pady=5)
self.buttonbox(self.datatype)
self.grab_set()
if not self.initial_focus:
self.initial_focus(self)
self.protocol("WM_DELETE_WINDOW",self.cancel)
self.geometry("+%d+%d" % (parent.winfo_rootx()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)
def buttonbox(self,datatype='msat'):
"""OK, Cancel and Help buttons"""
box=Frame(self)
w=Button(box,text="OK",width=10,command=self.ok,default=ACTIVE)
w.pack(side=LEFT,padx=5,pady=5)
w=Button(box,text="Cancel",width=10,command=self.cancel)
w.pack(side=LEFT,padx=5,pady=5)
w=Button(box,text="Help",width=10,command=lambda s=self,t=datatype: s.displayhelp(t))
w.pack(side=LEFT,padx=5,pady=5)
self.bind("<Return>",self.ok)
self.bind("<Escape",self.cancel)
box.pack()
def body(self,masterclass,masterwindow,titlemsg="Do you want to import auxiliary node data?"):
# self.b1=Checkbutton(masterwindow,text='Use linear bins for 1..10',variable=masterclass.linfirst,state=ACTIVE,bg='Gray80')
# self.b1.grid(row=0,column=0,columnspan=2)
self.wholeframe=Frame(masterwindow,relief='sunken',borderwidth=2)
self.clabel=Label(self.wholeframe,text=self.titlemsg,justify=LEFT,anchor=W,bg='gray90',relief='groove',borderwidth=1)
self.clabel.pack(side=TOP,expand=YES,fill=X,ipadx=5,ipady=5)
self.bottompart=Frame(self.wholeframe)
r1=Radiobutton(self.bottompart,text='Yes',value=1,variable=masterclass.metatype)
r2=Radiobutton(self.bottompart,text='No',value=0,variable=masterclass.metatype)
r1.grid(row=1,column=0,sticky=W)
r2.grid(row=2,column=0,sticky=W)
masterclass.metatype.set(1)
self.bottompart.pack(side=TOP,expand=YES,fill=BOTH,ipadx=7,ipady=7)
self.wholeframe.pack(side=TOP,expand=YES,fill=BOTH)
return self.wholeframe
def applyme(self):
self.result=(self.metatype.get())
def displayhelp(self,datatype):
MetaHelpWindow(self,datatype)
class MatrixDialog(MySimpleDialog):
"""Used when loading a matrix. Asks if the matrix contains weights or distances"""
def __init__(self,parent,title=None):
Toplevel.__init__(self,parent)
#self.configure(bg='Gray80')
# self.transient(parent)
if title:
self.title=title
self.parent=parent
self.result=None
self.mattype=IntVar()
# self.linfirst=IntVar()
body=Frame(self)
self.initial_focus=self.body(self,body)
body.pack(padx=5,pady=5)
self.buttonbox()
self.grab_set()
if not self.initial_focus:
self.initial_focus(self)
self.protocol("WM_DELETE_WINDOW",self.cancel)
self.geometry("+%d+%d" % (parent.winfo_rootx()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)
def body(self,masterclass,masterwindow):
# self.b1=Checkbutton(masterwindow,text='Use linear bins for 1..10',variable=masterclass.linfirst,state=ACTIVE,bg='Gray80')
# self.b1.grid(row=0,column=0,columnspan=2)
self.c1=Label(masterwindow,text='Matrix type:')
self.c1.grid(row=0,column=0)
r1=Radiobutton(masterwindow,text='Weight matrix',value=1,variable=masterclass.mattype)
r2=Radiobutton(masterwindow,text='Distance matrix',value=0,variable=masterclass.mattype)
r1.grid(row=0,column=1,sticky=W)
r2.grid(row=1,column=1,sticky=W)
masterclass.mattype.set(0)
return self.c1
def applyme(self):
self.result=(self.mattype.get())
class MsatDialog(MySimpleDialog):
"""Used when loading a matrix. Asks if the matrix contains weights or distances"""
def __init__(self,parent,title=None,titlemsg="Handling clones"):
Toplevel.__init__(self,parent)
#self.configure(bg='Gray80')
# self.transient(parent)
self.title(title)
self.titlemsg=titlemsg
self.parent=parent
self.result=None
self.mattype=IntVar()
# self.linfirst=IntVar()
body=Frame(self)
self.initial_focus=self.body(self,body)
body.pack(padx=5,pady=5)
self.buttonbox()
self.grab_set()
if not self.initial_focus:
self.initial_focus(self)
self.protocol("WM_DELETE_WINDOW",self.cancel)
self.geometry("+%d+%d" % (parent.winfo_rootx()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)
def body(self,masterclass,masterwindow,titlemsg="Handling clones"):
# self.b1=Checkbutton(masterwindow,text='Use linear bins for 1..10',variable=masterclass.linfirst,state=ACTIVE,bg='Gray80')
# self.b1.grid(row=0,column=0,columnspan=2)
self.wholeframe=Frame(masterwindow,relief='sunken',borderwidth=2)
self.clabel=Label(self.wholeframe,text=self.titlemsg,justify=LEFT,anchor=W,bg='gray90',relief='groove',borderwidth=1)
self.clabel.pack(side=TOP,expand=YES,fill=X,ipadx=5,ipady=5)
self.bottompart=Frame(self.wholeframe)
r1=Radiobutton(self.bottompart,text='Collapse clones',value=1,variable=masterclass.mattype)
r2=Radiobutton(self.bottompart,text='Leave clones',value=0,variable=masterclass.mattype)
r1.grid(row=1,column=0,sticky=W)
r2.grid(row=2,column=0,sticky=W)
self.bottompart.pack(side=TOP,expand=YES,fill=BOTH,ipadx=7,ipady=7)
self.wholeframe.pack(side=TOP,expand=YES,fill=BOTH)
masterclass.mattype.set(1)
return self.wholeframe
def applyme(self):
self.result=(self.mattype.get())
class VisualizationDialog(MySimpleDialog):
"""Asks options for network visualization"""
def __init__(self,parent,title=None):
Toplevel.__init__(self,parent)
#self.configure(bg='Gray80')
# self.transient(parent)
if title:
self.title=title
self.parent=parent
self.result=None
self.winsize=IntVar()
self.vtxsize=StringVar()
self.vtxcolor=StringVar()
self.bgcolor=StringVar()
self.showlabels=StringVar()
# self.linfirst=IntVar()
body=Frame(self)
self.initial_focus=self.body(self,body)
body.pack(padx=5,pady=5)
self.buttonbox()
self.grab_set()
if not self.initial_focus:
self.initial_focus(self)
self.protocol("WM_DELETE_WINDOW",self.cancel)
self.geometry("+%d+%d" % (parent.winfo_rootx()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)
def body(self,masterclass,masterwindow):
# self.b1=Checkbutton(masterwindow,text='Use linear bins for 1..10',variable=masterclass.linfirst,state=ACTIVE,bg='Gray80')
# self.b1.grid(row=0,column=0,columnspan=2)
self.c1=Label(masterwindow,text='Vertex color:')
self.c1.grid(row=0,column=0)
rowcount=-1
for text, value in [('Black','000000'),('White','999999'),('Red','990000'),('Green','009900'),('Blue','000099'),('By strength','-1')]:
rowcount+=1
Radiobutton(masterwindow,text=text,value=value,variable=masterclass.vtxcolor).grid(row=rowcount,column=1,sticky=W)
masterclass.vtxcolor.set('-1')
Label(masterwindow,text='Vertex size:').grid(row=rowcount+1,column=0)
for text, value in [('Small','0.4'),('Medium','0.7'),('Large','0.99'),('By strength','-1.0')]:
rowcount=rowcount+1
Radiobutton(masterwindow,text=text,value=value,variable=masterclass.vtxsize).grid(row=rowcount,column=1,sticky=W)
masterclass.vtxsize.set('-1.0')
Label(masterwindow,text='Show with:').grid(row=rowcount+1,column=0)
for text, value in [('White background','white'),('Black background','black')]:
rowcount=rowcount+1
Radiobutton(masterwindow,text=text,value=value,variable=masterclass.bgcolor).grid(row=rowcount,column=1,sticky=W)
masterclass.bgcolor.set('black')
Label(masterwindow,text="Vertex labels:").grid(row=rowcount+1,column=0)
for text, value in [('None','none'),('All','all'),('Top 10','top10')]:
rowcount=rowcount+1
Radiobutton(masterwindow,text=text,value=value,variable=masterclass.showlabels).grid(row=rowcount,column=1,sticky=W)
masterclass.showlabels.set('all')
return self.c1
def applyme(self):
self.result=(self.vtxcolor.get(),self.vtxsize.get(),self.bgcolor.get(),self.showlabels.get())
class AskThreshold(MySimpleDialog):
"""Asks threshold for thresholding"""
def __init__(self,parent,title=None):
Toplevel.__init__(self,parent)
#self.configure(bg='Gray80')
# self.transient(parent)
if title:
self.title=title
self.parent=parent
self.result=None
# self.linfirst=IntVar()
self.threshold=StringVar()
body=Frame(self)
self.initial_focus=self.body(self,body)
body.pack(padx=5,pady=5)
self.buttonbox()
self.grab_set()
if not self.initial_focus:
self.initial_focus(self)
self.protocol("WM_DELETE_WINDOW",self.cancel)
self.geometry("+%d+%d" % (parent.winfo_rootx()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)
def body(self,masterclass,masterwindow):
# self.b1=Checkbutton(masterwindow,text='Use linear bins for 1..10',variable=masterclass.linfirst,state=ACTIVE,bg='Gray80')
# self.b1.grid(row=0,column=0,columnspan=2)
Label(masterwindow,text='Threshold:').grid(row=1,column=0)
self.c1=Entry(masterwindow,textvariable=masterclass.threshold,bg='Gray95')
masterclass.threshold.set('0')
self.c1.grid(row=1,column=1)
return self.c1
def applyme(self):
self.result=float(self.threshold.get())
class PercolationDialog(MySimpleDialog):
"""First window shown when launching a new analysis wizard.
Inquires if the user wants to load microsatellite data,
a distance matrix, or a network file."""
def __init__(self,parent,title=None,titlemsg="Set threshold distance",pdata=[],suscmax_thresh=0.0):
Toplevel.__init__(self,parent)
#self.configure(bg='Gray80')
# self.transient(parent)
self.title(title)
self.titlemsg=titlemsg
self.parent=parent
self.result=None
self.data=pdata
self.default_thresh=suscmax_thresh
self.threshold=StringVar()
# self.linfirst=IntVar()
body=Frame(self)
self.initial_focus=self.body(self,body)
body.pack(padx=5,pady=5)
self.buttonbox()
self.grab_set()
if not self.initial_focus:
self.initial_focus(self)
self.protocol("WM_DELETE_WINDOW",self.cancel)
self.geometry("+%d+%d" % (parent.winfo_rootx()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)
def body(self,masterclass,masterwindow,titlemsg="Choose genetic distance measure"):
# self.b1=Checkbutton(masterwindow,text='Use linear bins for 1..10',variable=masterclass.linfirst,state=ACTIVE,bg='Gray80')
# self.b1.grid(row=0,column=0,columnspan=2)
self.wholeframe=Frame(masterwindow,relief='groove',borderwidth=2,bg="Gray95")
# self.clabel=Label(self.wholeframe,text=self.titlemsg,bg='DarkOliveGreen2',relief='groove',borderwidth=1)
# self.clabel.pack(side=TOP,expand=YES,fill=X,ipadx=5,ipady=5)
self.midpart=Frame(self.wholeframe)
myplot=visuals.ReturnPlotObject(self.data,plotcommand="plot",addstr=",color=\"#9e0b0f\"",titlestring="Largest component size:Susceptibility",xstring="Threshold distance",ystring="GCC size:Susceptibility",fontsize=9)
myplot.canvas=FigureCanvasTkAgg(myplot.thisFigure,master=self.midpart)
myplot.canvas.show()
myplot.canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=YES, padx=10,pady=10)
self.midpart.pack(side=TOP,expand=YES,fill=BOTH)
self.bottompart=Frame(self.wholeframe)
Label(self.bottompart,text='Estimated percolation threshold = %2.2f' % self.default_thresh).grid(row=1,column=0,columnspan=2)
Label(self.bottompart,text='Threshold: ').grid(row=2,column=0)
self.c1=Entry(self.bottompart,textvariable=masterclass.threshold,bg='Gray95')
masterclass.threshold.set(str(self.default_thresh))
self.c1.grid(row=2,column=1)
self.bottompart.pack(side=TOP,expand=YES,fill=BOTH,ipadx=7,ipady=7)
self.wholeframe.pack(side=TOP,expand=YES,fill=BOTH)
return self.wholeframe
def applyme(self):
self.result=(self.threshold.get())
class VisualizationOptions(MySimpleDialog):
"""First window shown when launching a new analysis wizard.
Inquires if the user wants to load microsatellite data,
a distance matrix, or a network file."""
def __init__(self,parent,network,title=None,titlemsg="Choose visualization options"):
Toplevel.__init__(self,parent)
#self.configure(bg='Gray80')
# self.transient(parent)
self.title(title)
self.titlemsg=titlemsg
self.parent=parent
self.result=None
self.vcolor=StringVar()
self.vsize=StringVar()
self.bgcolor=IntVar()
# self.linfirst=IntVar()
body=Frame(self)
self.initial_focus=self.body(self,body)
body.pack(padx=5,pady=5)
self.buttonbox(self.datatype)
self.grab_set()
if not self.initial_focus:
self.initial_focus(self)
self.protocol("WM_DELETE_WINDOW",self.cancel)
self.geometry("+%d+%d" % (parent.winfo_rootx()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)
def buttonbox(self,datatype='msat'):
"""OK, Cancel and Help buttons"""
box=Frame(self)
w=Button(box,text="OK",width=10,command=self.ok,default=ACTIVE)
w.pack(side=LEFT,padx=5,pady=5)
w=Button(box,text="Cancel",width=10,command=self.cancel)
w.pack(side=LEFT,padx=5,pady=5)
self.bind("<Return>",self.ok)
self.bind("<Escape",self.cancel)
box.pack()
def body(self,masterclass,masterwindow,titlemsg="Select visualization options"):
# self.b1=Checkbutton(masterwindow,text='Use linear bins for 1..10',variable=masterclass.linfirst,state=ACTIVE,bg='Gray80')
# self.b1.grid(row=0,column=0,columnspan=2)
self.wholeframe=Frame(masterwindow,relief='sunken',borderwidth=2)
self.clabel=Label(self.wholeframe,text=self.titlemsg,justify=LEFT,anchor=W,bg='gray90',relief='groove',borderwidth=1)
self.clabel.pack(side=TOP,expand=YES,fill=X,ipadx=5,ipady=5)
self.bottompart=Frame(self.wholeframe)
scrollbar = Scrollbar(self.bottompart, orient=VERTICAL)
listbox = Listbox(self.bottompart, yscrollcommand=scrollbar.set)
scrollbar.config(command=listbox.yview)
scrollbar.pack(side=RIGHT, fill=Y)
listbox.pack(side=LEFT, fill=BOTH, expand=1)
listbox.insert(END,'none')
listbox.insert(END,'by degree')
plist=netext.getNumericProperties(network)
for prop in plist:
listbox.insert(END,prop)
self.bottompart.pack(side=TOP,expand=YES,fill=BOTH,ipadx=7,ipady=7)
self.wholeframe.pack(side=TOP,expand=YES,fill=BOTH)
return self.wholeframe
def applyme(self):
#self.result=(self.metatype.get())
pass
def displayhelp(self,datatype):
MetaHelpWindow(self,datatype)
class SliderDialog(MySimpleDialog):
"""Dialog for inputting a value using a slider (e.g. for font sizes etc)"""
def __init__(self,parent,title=None,titlemsg="Select label font size",minval=0,maxval=100,currval=7):
Toplevel.__init__(self,parent)
#self.configure(bg='Gray80')
# self.transient(parent)
self.title(title)
self.titlemsg=titlemsg
self.parent=parent
self.result=None
self.slidertype=IntVar()
self.minval=minval
self.maxval=maxval
self.currval=currval
# self.linfirst=IntVar()
body=Frame(self)
self.initial_focus=self.body(self,body)
body.pack(padx=5,pady=5)
self.buttonbox()
self.grab_set()
if not self.initial_focus:
self.initial_focus(self)
self.protocol("WM_DELETE_WINDOW",self.cancel)
self.geometry("+%d+%d" % (parent.winfo_rootx()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)
def body(self,masterclass,masterwindow,titlemsg="Select label font size"):
# self.b1=Checkbutton(masterwindow,text='Use linear bins for 1..10',variable=masterclass.linfirst,state=ACTIVE,bg='Gray80')
# self.b1.grid(row=0,column=0,columnspan=2)
self.wholeframe=Frame(masterwindow,relief='sunken',borderwidth=2)
self.clabel=Label(self.wholeframe,text=self.titlemsg,justify=LEFT,anchor=W,bg='gray90',relief='groove',borderwidth=1)
self.clabel.pack(side=TOP,expand=YES,fill=X,ipadx=5,ipady=5)
self.bottompart=Frame(self.wholeframe)
self.scale=Scale(self.bottompart, from_=self.minval, to=self.maxval, orient=HORIZONTAL)
self.scale.set(self.currval)
self.scale.pack()
self.bottompart.pack(side=TOP,expand=YES,fill=BOTH,ipadx=7,ipady=7)
self.wholeframe.pack(side=TOP,expand=YES,fill=BOTH)
return self.wholeframe
def applyme(self):
self.result=(self.scale.get())
class DoubleSliderDialog(MySimpleDialog):
"""Dialog for inputting a value using a slider (e.g. for font sizes etc)"""
def __init__(self,parent,title=None,titlemsg="Select label font size",resolution=1,minval_1=0,maxval_1=100,currval_1=7,minval_2=0,maxval_2=0,currval_2=7,slidertext_1='min',slidertext_2='max'):
Toplevel.__init__(self,parent)
#self.configure(bg='Gray80')
# self.transient(parent)
self.title(title)
self.titlemsg=titlemsg
self.parent=parent
self.result=None
self.slidertype_1=IntVar()
self.minval_1=minval_1
self.maxval_1=maxval_1
self.currval_1=currval_1
self.slidertext_1=slidertext_1
self.resolution=resolution
self.slidertype_2=IntVar()
self.minval_2=minval_2
self.maxval_2=maxval_2
self.currval_2=currval_2
self.slidertext_2=slidertext_2
# self.linfirst=IntVar()
body=Frame(self)
self.initial_focus=self.body(self,body)
body.pack(padx=5,pady=5)
self.buttonbox()
self.grab_set()
if not self.initial_focus:
self.initial_focus(self)
self.protocol("WM_DELETE_WINDOW",self.cancel)
self.geometry("+%d+%d" % (parent.winfo_rootx()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)
def body(self,masterclass,masterwindow,titlemsg="Select label font size"):
# self.b1=Checkbutton(masterwindow,text='Use linear bins for 1..10',variable=masterclass.linfirst,state=ACTIVE,bg='Gray80')
# self.b1.grid(row=0,column=0,columnspan=2)
self.wholeframe=Frame(masterwindow,relief='sunken',borderwidth=2)
self.clabel=Label(self.wholeframe,text=self.titlemsg,justify=LEFT,anchor=W,bg='gray90',relief='groove',borderwidth=1)
self.clabel.pack(side=TOP,expand=YES,fill=X,ipadx=5,ipady=5)
self.bottompart=Frame(self.wholeframe)
Label(self.bottompart,text=self.slidertext_1,justify=LEFT,anchor=W,bg='gray90',relief='groove',borderwidth=1).grid(row=0,column=0)
self.scale_1=Scale(self.bottompart, from_=self.minval_1, to=self.maxval_1, orient=HORIZONTAL,resolution=self.resolution)
self.scale_1.set(self.currval_1)
self.scale_1.grid(row=0,column=1)
Label(self.bottompart,text=self.slidertext_2,justify=LEFT,anchor=W,bg='gray90',relief='groove',borderwidth=1).grid(row=1,column=0)
self.scale_2=Scale(self.bottompart, from_=self.minval_2, to=self.maxval_2, orient=HORIZONTAL,resolution=self.resolution)
self.scale_2.set(self.currval_2)
self.scale_2.grid(row=1,column=1)
self.bottompart.pack(side=TOP,expand=YES,fill=BOTH,ipadx=7,ipady=7)
self.wholeframe.pack(side=TOP,expand=YES,fill=BOTH)
return self.wholeframe
def applyme(self):
self.result=[self.scale_1.get(),self.scale_2.get()]
class ColorMapDialog(MySimpleDialog):
"""Lists color maps and asks to choose one"""
def __init__(self,parent,title='Select color map:',current_map='orange'):
Toplevel.__init__(self,parent)
# self.configure(bg='Gray80')
# self.transient(parent)
self.title(title)
self.parent=parent
self.result=None
self.current_map=current_map
self.colormap=StringVar()
body=Frame(self)
self.initial_focus=self.body(self,body)
body.pack(padx=5,pady=5)
self.buttonbox()
self.grab_set()
if not self.initial_focus:
self.initial_focus(self)
self.protocol("WM_DELETE_WINDOW",self.cancel)
self.geometry("+%d+%d" % (parent.winfo_rootx()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)
def body(self,masterclass,masterwindow):
self.c1=Label(masterwindow,text='Please choose color map',anchor=W)
self.c1.grid(row=0,column=0)
colormaps=["orange","hsv","jet","spectral","winter","Accent","Paired","binary","gray"]
rowcounter=1
curr_frame=[]
curr_plot=[]
for cmap in colormaps:
Radiobutton(masterwindow,text=cmap,value=cmap,variable=masterclass.colormap).grid(row=rowcounter,column=0,sticky=W)
curr_frame.append(Frame(masterwindow))
curr_plot.append(visuals.ReturnColorMapPlot(cmap))
curr_plot[-1].canvas=FigureCanvasTkAgg(curr_plot[-1],curr_frame[-1])
curr_plot[-1].canvas.show()
curr_plot[-1].canvas.get_tk_widget().grid(row=rowcounter,column=1)
curr_frame[-1].grid(row=rowcounter,column=1,sticky=W)
rowcounter=rowcounter+1
if self.current_map in colormaps:
masterclass.colormap.set(self.current_map)
else:
masterclass.colormap.set('orange')
return self.c1
def applyme(self):
self.result=self.colormap.get()
class WaitWindow(MySimpleDialog):
"""Used when loading a matrix. Asks if the matrix contains weights or distances"""
def __init__(self,parent,title=None,titlemsg="Please wait...",hasProgressbar=False):
Toplevel.__init__(self,parent)
#self.configure(bg='Gray80')
#self.transient(parent)
self.title(title)
self.titlemsg=titlemsg
self.parent=parent
self.hasProgressbar=hasProgressbar
self.result=None
body=Frame(self)
self.initial_focus=self.body(self,body)
body.pack(padx=5,pady=5)
#self.buttonbox()
#self.grab_set()
if not self.initial_focus:
self.initial_focus(self)
self.protocol("WM_DELETE_WINDOW",self.cancel)
self.geometry("+%d+%d" % (parent.winfo_rootx()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
def go(self,lambda_operation):
self.result=lambda_operation()
self.ok()
#self.wait_window(self)
def body(self,masterclass,masterwindow,titlemsg="Please wait..."):
self.wholeframe=Frame(masterwindow,relief='sunken',borderwidth=2)
self.clabel=Label(self.wholeframe,text=self.titlemsg,
justify=LEFT,
anchor=W,
bg='darkolivegreen2',
relief='groove',borderwidth=1,padx=3,pady=3,width=40)
self.clabel.pack(side=TOP,expand=YES,fill=X,ipadx=5,ipady=5)
self.bottompart=Frame(self.wholeframe)
self.l1=Label(self.bottompart,text=self.titlemsg,justify=LEFT,
anchor=W,bg='white',relief='flat',padx=3,pady=3)
self.l1.grid(row=1,column=0,sticky=W)
self.l1['fg']='black'
if self.hasProgressbar:
self.progressbar=Meter(self.bottompart,value=0.0)
self.progressbar.grid(row=4,column=0,sticky=W)
self.updatePointer=self.progressbar.set
self.bottompart.pack(side=TOP,expand=YES,fill=BOTH,ipadx=7,ipady=7)
self.wholeframe.pack(side=TOP,expand=YES,fill=BOTH)
return self.wholeframe
def applyme(self):
return self.result
class MsLoadWaiter(MySimpleDialog):
"""Used when loading a matrix. Asks if the matrix contains weights or distances"""
def __init__(self,parent,inputfile,removeclones,measuretype,title="Processing microsatellite data",titlemsg="Please wait",nodeNames=None,datatype=None):
Toplevel.__init__(self,parent)
self.title(title)
self.titlemsg=titlemsg
self.parent=parent
self.datatype=datatype
self.result=None
body=Frame(self)
self.initial_focus=self.body(self,body)
body.pack(padx=5,pady=5)
#self.buttonbox()
self.grab_set()
self.points=['.','..','...']
self.pointcounter=0
self.displayBusyCursor()
if not self.initial_focus:
self.initial_focus(self)
self.protocol("WM_DELETE_WINDOW",self.cancel)
self.geometry("+%d+%d" % (parent.winfo_rootx()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.l1['fg']='#b0b0b0'
self.l1.update()
if removeclones:
self.l2['text']='Removing clones...'
self.l2['fg']='black'
self.l2.update()
if datatype=="ms_diploid":
msdata_initial=eden.MicrosatelliteData(inputfile)
else:
msdata_initial=eden.MicrosatelliteDataHaploid(inputfile)
if removeclones:
[msdata,keeptheserows]=msdata_initial.getUniqueSubset(returnOldIndices=True)
clones='collapsed'
if nodeNames!=None:
newNodeNames=[]
keeptheserows=sorted(keeptheserows)
for row in keeptheserows:
newNodeNames.append(nodeNames[row])
nodeNames=newNodeNames
else:
nodeNames=sorted(keeptheserows)
# trick to accommodate for (possible) node properties - we will use only "keeptheserows" containing indices to non-clonal samples
else:
msdata=msdata_initial
clones='included'
keeptheserows=None
self.clones=clones
self.keeptheserows=keeptheserows
self.l3['text']='Calculating distance matrix...'
self.l3['fg']='black'
self.l3.update()
self.l2['fg']='#b0b0b0'
self.l2.update()
m=msdata.getDistanceMatrix(measuretype,nodeNames=nodeNames,progressUpdater=self.progressbar.set)
if removeclones:
Nclones=msdata_initial.getNumberOfNodes()-len(keeptheserows)
else:
Nclones=None
self.Nclones=Nclones
self.m=m
self.msdata=msdata
self.ok()
def animate(self):
self.pointcounter=self.pointcounter+1
if self.pointcounter==3:
self.pointcounter=0
self.clabel['text']=self.titlemsg+self.points[self.pointcounter]
self.clabel.update()
self.after(500,self.animate)
def body(self,masterclass,masterwindow,titlemsg="Please wait!"):
# self.b1=Checkbutton(masterwindow,text='Use linear bins for 1..10',variable=masterclass.linfirst,state=ACTIVE,bg='Gray80')
# self.b1.grid(row=0,column=0,columnspan=2)
self.wholeframe=Frame(masterwindow,relief='sunken',borderwidth=2)
self.clabel=Label(self.wholeframe,text=self.titlemsg,
justify=LEFT,
anchor=W,
bg='darkolivegreen2',
relief='groove',borderwidth=1,padx=3,pady=3,width=40)
self.clabel.pack(side=TOP,expand=YES,fill=X,ipadx=5,ipady=5)
self.bottompart=Frame(self.wholeframe)
self.l1=Label(self.bottompart,text='Reading file...',justify=LEFT,
anchor=W,bg='white',relief='flat',padx=3,pady=3)
self.l1.grid(row=1,column=0,sticky=W)
self.l1['fg']='black'
self.l2=Label(self.bottompart,text='-',justify=LEFT,
anchor=W,bg='white',relief='flat',padx=3,pady=3)
self.l2.grid(row=2,column=0,sticky=W)
self.l3=Label(self.bottompart,text='-',justify=LEFT,
anchor=W,bg='white',relief='flat',padx=3,pady=3)
self.l3.grid(row=3,column=0,sticky=W)
self.progressbar=Meter(self.bottompart,value=0.0)
self.progressbar.grid(row=4,column=0,sticky=W)
self.bottompart.pack(side=TOP,expand=YES,fill=BOTH,ipadx=7,ipady=7)
self.wholeframe.pack(side=TOP,expand=YES,fill=BOTH)
return self.wholeframe
def applyme(self):
self.result=[self.Nclones,self.clones,self.keeptheserows,self.m,self.msdata]
class LoadWaiter(MySimpleDialog):
"""Display progress bar while doing something."""
def __init__(self,parent,function,args=[],kwargs=None,callback_function_parameter="progressUpdater",bodymsg="Processing...",titlemsg="Please wait"):
Toplevel.__init__(self,parent)
title=titlemsg
if kwargs==None:
kwargs={}
self.title(title)
self.titlemsg=titlemsg
self.parent=parent
self.result=None
body=Frame(self)
self.initial_focus=self.body(self,body,titlemsg=titlemsg,bodymsg=bodymsg)
body.pack(padx=5,pady=5)
#self.buttonbox()
self.grab_set()
self.points=['.','..','...']
self.pointcounter=0
self.displayBusyCursor()
if not self.initial_focus:
self.initial_focus(self)
self.protocol("WM_DELETE_WINDOW",self.cancel)
self.geometry("+%d+%d" % (parent.winfo_rootx()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.l1['fg']='#b0b0b0'
self.l1.update()
kwargs[callback_function_parameter]=self.progressbar.set
self.output=function(*args,**kwargs)
self.ok()
def animate(self):
self.pointcounter=self.pointcounter+1
if self.pointcounter==3:
self.pointcounter=0
self.clabel['text']=self.titlemsg+self.points[self.pointcounter]
self.clabel.update()
self.after(500,self.animate)
def body(self,masterclass,masterwindow,titlemsg="",bodymsg=""):
self.wholeframe=Frame(masterwindow,relief='sunken',borderwidth=2)
self.clabel=Label(self.wholeframe,text=self.titlemsg,
justify=LEFT,
anchor=W,
bg='darkolivegreen2',
relief='groove',borderwidth=1,padx=3,pady=3,width=40)
self.clabel.pack(side=TOP,expand=YES,fill=X,ipadx=5,ipady=5)
self.bottompart=Frame(self.wholeframe)
self.l1=Label(self.bottompart,text=bodymsg,justify=LEFT,
anchor=W,bg='white',relief='flat',padx=3,pady=3)
self.l1.grid(row=1,column=0,sticky=W)
self.l1['fg']='black'
"""
self.l2=Label(self.bottompart,text='-',justify=LEFT,
anchor=W,bg='white',relief='flat',padx=3,pady=3)
self.l2.grid(row=2,column=0,sticky=W)
self.l3=Label(self.bottompart,text='-',justify=LEFT,
anchor=W,bg='white',relief='flat',padx=3,pady=3)
self.l3.grid(row=3,column=0,sticky=W)
"""
self.progressbar=Meter(self.bottompart,value=0.0)
self.progressbar.grid(row=4,column=0,sticky=W)
self.bottompart.pack(side=TOP,expand=YES,fill=BOTH,ipadx=7,ipady=7)
self.wholeframe.pack(side=TOP,expand=YES,fill=BOTH)
return self.wholeframe
def applyme(self):
self.result=self.output
class GenericLoadWaiter(MySimpleDialog):
"""Generic class for wait windows displaying one item"""
def __init__(self,parent,filename,removeclones,measuretype,title=None,titlemsg="Please wait",specmsg="Processing"):
Toplevel.__init__(self,parent)
#self.configure(bg='Gray80')
# self.transient(parent)
self.title(title)
self.titlemsg=titlemsg
self.specmsg=specmsg
self.parent=parent
self.result=None
body=Frame(self)
self.initial_focus=self.body(self,body)
body.pack(padx=5,pady=5)
#self.buttonbox()
self.grab_set()
self.points=['.','..','...']
self.pointcounter=0
self.displayBusyCursor()
if not self.initial_focus:
self.initial_focus(self)
self.protocol("WM_DELETE_WINDOW",self.cancel)
self.geometry("+%d+%d" % (parent.winfo_rootx()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
# INSERT YOUR FUNCTIONALITY HERE
self.ok()
def body(self,masterclass,masterwindow,titlemsg="Please wait!"):
self.wholeframe=Frame(masterwindow,relief='sunken',borderwidth=2)
self.clabel=Label(self.wholeframe,text=self.titlemsg,justify=LEFT,anchor=W,bg='darkolivegreen2',relief='groove',borderwidth=1,padx=3,pady=3,width=40)
self.clabel.pack(side=TOP,expand=YES,fill=X,ipadx=5,ipady=5)
self.bottompart=Frame(self.wholeframe)
self.l1=Label(self.bottompart,text=self.specmsg,justify=LEFT,anchor=W,bg='white',relief='flat',padx=3,pady=3)
self.l1.grid(row=1,column=0,sticky=W)
self.l1['fg']='black'
self.bottompart.pack(side=TOP,expand=YES,fill=BOTH,ipadx=7,ipady=7)
self.wholeframe.pack(side=TOP,expand=YES,fill=BOTH)
return self.wholeframe
class MetaLoadWaiter(GenericLoadWaiter):
"""Generic class for wait windows displaying one item"""
def __init__(self,parent,m,keeptheserows,title=None,titlemsg="Please wait",specmsg="Processing"):
Toplevel.__init__(self,parent)
#self.configure(bg='Gray80')
# self.transient(parent)
self.title(title)
self.titlemsg=titlemsg
self.specmsg=specmsg
self.parent=parent
self.result=None
body=Frame(self)
self.initial_focus=self.body(self,body)
body.pack(padx=5,pady=5)
# self.buttonbox()
self.grab_set()
self.points=['.','..','...']
self.pointcounter=0
self.displayBusyCursor()
if not self.initial_focus:
self.initial_focus(self)
self.protocol("WM_DELETE_WINDOW",self.cancel)
self.geometry("+%d+%d" % (parent.winfo_rootx()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.distancematrix=transforms.filterNet(m,keeptheserows)
self.ok()
def applyme(self):
self.result=self.distancematrix
class HimmeliWaiter(GenericLoadWaiter):
"""Generic class for wait windows displaying one item"""
def __init__(self,parent,net,time,usemst,coordinates=None,title=None,titlemsg="Please wait",specmsg="Processing..."):
Toplevel.__init__(self,parent)
#self.configure(bg='Gray80')
self.transient(parent)
self.title(title)
self.titlemsg=titlemsg
self.specmsg=specmsg
self.parent=parent
self.result=None
body=Frame(self)
self.initial_focus=self.body(self,body)
body.pack(padx=5,pady=5)
# self.buttonbox()
self.grab_set()
self.points=['.','..','...']
self.pointcounter=0
self.displayBusyCursor()
if not self.initial_focus:
self.initial_focus(self)
self.protocol("WM_DELETE_WINDOW",self.cancel)
self.geometry("+%d+%d" % (parent.winfo_rootx()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
if usemst:
h=visuals.Himmeli(net,time=time,coordinates=coordinates,useMST=usemst)
else:
h=visuals.Himmeli(net,time=time,useMST=usemst)
self.coords=h.getCoordinates()
del h
self.ok()
def applyme(self):
self.result=self.coords
class Meter(Frame):
'''A simple progress bar widget.
Made by Michael'''
def __init__(self, master, fillcolor='orchid1', text='',
value=0.0, **kw):
Frame.__init__(self, master, bg='white', width=350,
height=20)
self.configure(**kw)
self._c = Canvas(self, bg=self['bg'],
width=self['width'], height=self['height'],\
highlightthickness=0, relief='flat',
bd=0)
self._c.pack(fill='x', expand=1)
self._r = self._c.create_rectangle(0, 0, 0,
int(self['height']), fill=fillcolor, width=0)
self._t = self._c.create_text(int(self['width'])/2,
int(self['height'])/2, text='')
self.set(value, text)
def set(self, value=0.0, text=None):
#make the value failsafe:
if value < 0.0:
value = 0.0
elif value > 1.0:
value = 1.0
if text == None:
#if no text is specified get the default percentage string:
text = str(int(round(100 * value))) + ' %'
self._c.coords(self._r, 0, 0, int(self['width']) * value,
int(self['height']))
self._c.itemconfigure(self._t, text=text)
self.update()
class BootstrapPopulationsDialog(MySimpleDialog):
"""Asks for the number of bins for log binning
and allows linear bins for 1...10"""
def __init__(self,parent,title='Please provide information:',initRuns=100):
Toplevel.__init__(self,parent)
self.title(title)
self.parent=parent
self.result=None
self.initRuns=initRuns
self.nRuns=StringVar()
body=Frame(self)
self.initial_focus=self.body(self,body)
body.pack(padx=5,pady=5)
self.buttonbox()
self.grab_set()
if not self.initial_focus:
self.initial_focus(self)
self.protocol("WM_DELETE_WINDOW",self.cancel)
self.geometry("+%d+%d" % (parent.winfo_rootx()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)
def body(self,masterclass,masterwindow):
self.c1=Label(masterwindow,text='Number of repetitions?',
anchor=W)
self.c1.grid(row=0,column=0)
self.e1=Entry(masterwindow,textvariable=self.nRuns,bg='Gray95')
self.nRuns.set(str(self.initRuns))
self.e1.grid(row=1,column=0)
self.c2=Label(masterwindow,text='Percentage of nodes in each location?',
anchor=W)
self.c2.grid(row=2,column=0)
self.scale_1=Scale(masterwindow, from_=0.0, to=1.0,
orient=HORIZONTAL,resolution=0.01)
self.scale_1.set(0.5)
self.scale_1.grid(row=3,column=0)
return self.c1
def applyme(self):
self.result=[self.scale_1.get(),self.e1.get()]
class SliderDialog2(MySimpleDialog):
"""Asks for the number of bins for log binning
and allows linear bins for 1...10"""
def __init__(self,parent,sMin,sMax,sRes,sStart,title='Please provide information:',bodyText="How much?"):
Toplevel.__init__(self,parent)
self.title(title)
self.sMin=sMin
self.sMax=sMax
self.sRes=sRes
self.sStart=sStart
self.bodyText=bodyText
self.parent=parent
self.result=None
self.clones=StringVar()
self.measuretype=StringVar()
body=Frame(self)
self.initial_focus=self.body(self,body)
body.pack(padx=5,pady=5)
self.buttonbox()
self.grab_set()
if not self.initial_focus:
self.initial_focus(self)
self.protocol("WM_DELETE_WINDOW",self.cancel)
self.geometry("+%d+%d" % (parent.winfo_rootx()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)
def body(self,masterclass,masterwindow):
self.c=Label(masterwindow,text='Percentage of nodes in each location?',
anchor=W)
self.c.grid(row=0,column=0)
self.scale=Scale(masterwindow, from_=self.sMin, to=self.sMax,
orient=HORIZONTAL,resolution=self.sRes)
self.scale.set(self.sStart)
self.scale.grid(row=1,column=0)
return self.c
def applyme(self):
self.result=self.scale.get()
class AskNumberDialog(MySimpleDialog):
"""Asks for a number
"""
def __init__(self,parent,title='Please provide information:',bodyText="Number: ",initNumber=100):
Toplevel.__init__(self,parent)
self.title(title)
self.bodyText=bodyText
self.parent=parent
self.result=None
self.initNumber=initNumber
self.theNumber=StringVar()
#self.measuretype=StringVar()
body=Frame(self)
self.initial_focus=self.body(self,body)
body.pack(padx=5,pady=5)
self.buttonbox()
self.grab_set()
if not self.initial_focus:
self.initial_focus(self)
self.protocol("WM_DELETE_WINDOW",self.cancel)
self.geometry("+%d+%d" % (parent.winfo_rootx()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)
def body(self,masterclass,masterwindow):
self.c1=Label(masterwindow,text=self.bodyText,
anchor=W)
self.c1.grid(row=0,column=0)
self.e1=Entry(masterwindow,textvariable=self.theNumber,bg='Gray95')
self.theNumber.set(str(self.initNumber))
self.e1.grid(row=1,column=0)
return self.c1
def applyme(self):
self.result=self.e1.get()
class EDENRadioDialog(MySimpleDialog):
"""A dialog with a radio selector."""
def __init__(self,parent,title=None,titlemsg="Choose one:",options=["Default"]):
Toplevel.__init__(self,parent)
self.title(title)
self.titlemsg=titlemsg
self.parent=parent
self.options=options
self.result=StringVar()
body=Frame(self)
self.initial_focus=self.body(self,body)
body.pack(padx=5,pady=5)
self.buttonbox()
self.grab_set()
if not self.initial_focus:
self.initial_focus(self)
self.protocol("WM_DELETE_WINDOW",self.cancel)
self.geometry("+%d+%d" % (parent.winfo_rootx()+50,parent.winfo_rooty()+50))
self.initial_focus.focus_set()
self.wait_window(self)
def body(self,masterclass,masterwindow,titlemsg="Choose genetic distance measure"):
self.wholeframe=Frame(masterwindow,relief='sunken',borderwidth=2)
self.clabel=Label(self.wholeframe,text=self.titlemsg,justify=LEFT,anchor=W,bg='gray90',relief='groove',borderwidth=1)
self.clabel.pack(side=TOP,expand=YES,fill=X,ipadx=5,ipady=5)
self.bottompart=Frame(self.wholeframe)
buttons=[]
for i,value in enumerate(masterclass.options):
r=Radiobutton(self.bottompart,text=value,value=value,variable=masterclass.result)
r.grid(row=i+1,column=0,sticky=W)
masterclass.result.set(masterclass.options[0])
self.bottompart.pack(side=TOP,expand=YES,fill=BOTH,ipadx=7,ipady=7)
self.wholeframe.pack(side=TOP,expand=YES,fill=BOTH)
return self.wholeframe
def applyme(self):
self.result=(self.result.get())<|fim▁end|>
|
w.pack(side=LEFT,padx=5,pady=5)
|
<|file_name|>ProfileService_WinRT.cpp<|end_file_name|><|fim▁begin|>// Copyright (c) Microsoft Corporation
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include "pch.h"
#include "ProfileService_winrt.h"
#include "Utils_WinRT.h"
using namespace pplx;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Platform;
using namespace Platform::Collections;
using namespace Microsoft::Xbox::Services::System;
using namespace xbox::services::social;
using namespace xbox::services;
NAMESPACE_MICROSOFT_XBOX_SERVICES_SOCIAL_BEGIN<|fim▁hole|>ProfileService::ProfileService(
_In_ profile_service cppObj
):
m_cppObj(std::move(cppObj))
{
}
IAsyncOperation<XboxUserProfile^>^
ProfileService::GetUserProfileAsync(
_In_ String^ xboxUserId
)
{
auto task = m_cppObj.get_user_profile(
STRING_T_FROM_PLATFORM_STRING(xboxUserId)
)
.then([](xbox::services::xbox_live_result<xbox_user_profile> cppUserProfile)
{
THROW_HR_IF_ERR(cppUserProfile.err());
return ref new XboxUserProfile(cppUserProfile.payload());
});
return ASYNC_FROM_TASK(task);
}
IAsyncOperation<IVectorView<XboxUserProfile^>^>^
ProfileService::GetUserProfilesAsync(
_In_ IVectorView<String^>^ xboxUserIds
)
{
std::vector<string_t> vecXboxUserIds = UtilsWinRT::CovertVectorViewToStdVectorString(xboxUserIds);
auto task = m_cppObj.get_user_profiles(vecXboxUserIds)
.then([](xbox::services::xbox_live_result<std::vector<xbox_user_profile>> cppUserProfiles)
{
THROW_HR_IF_ERR(cppUserProfiles.err());
Vector<XboxUserProfile^>^ responseVector = ref new Vector<XboxUserProfile^>();
const auto& result = cppUserProfiles.payload();
for (auto& cppUserProfile : result)
{
auto userProfile = ref new XboxUserProfile(cppUserProfile);
responseVector->Append(userProfile);
}
return responseVector->GetView();
});
return ASYNC_FROM_TASK(task);
}
IAsyncOperation<IVectorView<XboxUserProfile^>^>^
ProfileService::GetUserProfilesForSocialGroupAsync(
_In_ Platform::String^ socialGroup
)
{
auto task = m_cppObj.get_user_profiles_for_social_group(STRING_T_FROM_PLATFORM_STRING(socialGroup))
.then([](xbox_live_result<std::vector<xbox_user_profile>> cppUserProfileList)
{
THROW_IF_ERR(cppUserProfileList);
Vector<XboxUserProfile^>^ responseVector = ref new Vector<XboxUserProfile^>();
for (auto& cppUserProfile : cppUserProfileList.payload())
{
XboxUserProfile^ userProfile = ref new XboxUserProfile(cppUserProfile);
responseVector->Append(userProfile);
}
return responseVector->GetView();
});
return ASYNC_FROM_TASK(task);
}
NAMESPACE_MICROSOFT_XBOX_SERVICES_SOCIAL_END<|fim▁end|>
| |
<|file_name|>main.py<|end_file_name|><|fim▁begin|># This file is part of Parti.
# Copyright (C) 2008 Nathaniel Smith <[email protected]>
# Parti is released under the terms of the GNU GPL v2, or, at your option, any
# later version. See the file COPYING for details.
import gobject
import sys
import os
import socket
import time
from optparse import OptionParser
import logging
from subprocess import Popen, PIPE
import xpra
from xpra.bencode import bencode
from xpra.dotxpra import DotXpra
from xpra.platform import (XPRA_LOCAL_SERVERS_SUPPORTED,
DEFAULT_SSH_CMD,
GOT_PASSWORD_PROMPT_SUGGESTION)
from xpra.protocol import TwoFileConnection, SocketConnection
def nox():
if "DISPLAY" in os.environ:
del os.environ["DISPLAY"]
# This is an error on Fedora/RH, so make it an error everywhere so it will
# be noticed:
import warnings
warnings.filterwarnings("error", "could not open display")
def main(script_file, cmdline):
#################################################################
## NOTE NOTE NOTE
##
## If you modify anything here, then remember to update the man page
## (xpra.1) as well!
##
## NOTE NOTE NOTE
#################################################################
if XPRA_LOCAL_SERVERS_SUPPORTED:
start_str = "\t%prog start DISPLAY\n"
list_str = "\t%prog list\n"
upgrade_str = "\t%prog upgrade DISPLAY"
note_str = ""
else:
start_str = ""
list_str = ""
upgrade_str = ""
note_str = "(This xpra install does not support starting local servers.)"
parser = OptionParser(version="xpra v%s" % xpra.__version__,
usage="".join(["\n",
start_str,
"\t%prog attach [DISPLAY]\n",
"\t%prog stop [DISPLAY]\n",
list_str,
upgrade_str,
note_str]))
if XPRA_LOCAL_SERVERS_SUPPORTED:
parser.add_option("--start-child", action="append",
dest="children", metavar="CMD",
help="program to spawn in new server (may be repeated)")
parser.add_option("--exit-with-children", action="store_true",
dest="exit_with_children", default=False,
help="Terminate server when --start-child command(s) exit")
parser.add_option("--no-daemon", action="store_false",
dest="daemon", default=True,
help="Don't daemonize when running as a server")
parser.add_option("--xvfb", action="store",
dest="xvfb", default="Xvfb", metavar="CMD",
help="How to run the headless X server (default: '%default')")
parser.add_option("--bind-tcp", action="store",
dest="bind_tcp", default=None,
metavar="[HOST]:PORT",
help="Listen for connections over TCP (insecure)")
parser.add_option("-z", "--compress", action="store",
dest="compression_level", type="int", default=3,
metavar="LEVEL",
help="How hard to work on compressing data."
+ " 0 to disable compression,"
+ " 9 for maximal (slowest) compression. Default: %default.")
parser.add_option("--ssh", action="store",
dest="ssh", default=DEFAULT_SSH_CMD, metavar="CMD",
help="How to run ssh (default: '%default')")
parser.add_option("--remote-xpra", action="store",
dest="remote_xpra", default=".xpra/run-xpra",
metavar="CMD",
help="How to run xpra on the remote host (default: '%default')")
parser.add_option("-d", "--debug", action="store",
dest="debug", default=None, metavar="FILTER1,FILTER2,...",
help="List of categories to enable debugging for (or \"all\")")
(options, args) = parser.parse_args(cmdline[1:])
if not args:
parser.error("need a mode")
logging.root.setLevel(logging.INFO)
if options.debug is not None:
categories = options.debug.split(",")
for cat in categories:
if cat.startswith("-"):
logging.getLogger(cat[1:]).setLevel(logging.INFO)
if cat == "all":
logger = logging.root
else:
logger = logging.getLogger(cat)
logger.setLevel(logging.DEBUG)
logging.root.addHandler(logging.StreamHandler(sys.stderr))
mode = args.pop(0)
if mode in ("start", "upgrade") and XPRA_LOCAL_SERVERS_SUPPORTED:
nox()
from xpra.scripts.server import run_server
run_server(parser, options, mode, script_file, args)
elif mode == "attach":
try:
run_client(parser, options, args)
except KeyboardInterrupt:
sys.stdout.write("Exiting on keyboard interrupt\n")
elif mode == "stop":
nox()
run_stop(parser, options, args)
elif mode == "list" and XPRA_LOCAL_SERVERS_SUPPORTED:
run_list(parser, options, args)
elif mode == "_proxy" and XPRA_LOCAL_SERVERS_SUPPORTED:
nox()
run_proxy(parser, options, args)
else:
parser.error("invalid mode '%s'" % mode)
def parse_display_name(parser, opts, display_name):
if display_name.startswith("ssh:"):
desc = {
"type": "ssh",
"local": False
}
sshspec = display_name[len("ssh:"):]
if ":" in sshspec:
(desc["host"], desc["display"]) = sshspec.split(":", 1)
desc["display"] = ":" + desc["display"]
desc["display_as_args"] = [desc["display"]]
else:
desc["host"] = sshspec
desc["display"] = None
desc["display_as_args"] = []
desc["ssh"] = opts.ssh.split()
desc["full_ssh"] = desc["ssh"] + ["-T", desc["host"]]
desc["remote_xpra"] = opts.remote_xpra.split()
desc["full_remote_xpra"] = desc["full_ssh"] + desc["remote_xpra"]
return desc
elif display_name.startswith(":"):
desc = {
"type": "unix-domain",<|fim▁hole|> "display": display_name,
}
return desc
elif display_name.startswith("tcp:"):
desc = {
"type": "tcp",
"local": False,
}
host_spec = display_name[4:]
(desc["host"], port_str) = host_spec.split(":", 1)
desc["port"] = int(port_str)
if desc["host"] == "":
desc["host"] = "127.0.0.1"
return desc
else:
parser.error("unknown format for display name")
def pick_display(parser, opts, extra_args):
if len(extra_args) == 0:
if not XPRA_LOCAL_SERVERS_SUPPORTED:
parser.error("need to specify a display")
# Pick a default server
sockdir = DotXpra()
servers = sockdir.sockets()
live_servers = [display
for (state, display) in servers
if state is DotXpra.LIVE]
if len(live_servers) == 0:
parser.error("cannot find a live server to connect to")
elif len(live_servers) == 1:
return parse_display_name(parser, opts, live_servers[0])
else:
parser.error("there are multiple servers running, please specify")
elif len(extra_args) == 1:
return parse_display_name(parser, opts, extra_args[0])
else:
parser.error("too many arguments")
def _socket_connect(sock, target):
try:
sock.connect(target)
except socket.error, e:
sys.exit("Connection failed: %s" % (e,))
return SocketConnection(sock)
def connect_or_fail(display_desc):
if display_desc["type"] == "ssh":
cmd = (display_desc["full_remote_xpra"]
+ ["_proxy"] + display_desc["display_as_args"])
try:
child = Popen(cmd, stdin=PIPE, stdout=PIPE)
except OSError, e:
sys.exit("Error running ssh program '%s': %s" % (cmd[0], e))
return TwoFileConnection(child.stdin, child.stdout)
elif XPRA_LOCAL_SERVERS_SUPPORTED and display_desc["type"] == "unix-domain":
sockdir = DotXpra()
sock = socket.socket(socket.AF_UNIX)
return _socket_connect(sock,
sockdir.socket_path(display_desc["display"]))
elif display_desc["type"] == "tcp":
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
return _socket_connect(sock,
(display_desc["host"], display_desc["port"]))
else:
assert False, "unsupported display type in connect"
def handshake_complete_msg(*args):
sys.stdout.write("Attached (press Control-C to detach)\n")
def got_gibberish_msg(obj, data):
if "assword" in data:
sys.stdout.write("Your ssh program appears to be asking for a password.\n"
+ GOT_PASSWORD_PROMPT_SUGGESTION)
sys.stdout.flush()
if "login" in data:
sys.stdout.write("Your ssh program appears to be asking for a username.\n"
"Perhaps try using something like 'ssh:USER@host:display'?\n")
sys.stdout.flush()
def run_client(parser, opts, extra_args):
from xpra.client import XpraClient
conn = connect_or_fail(pick_display(parser, opts, extra_args))
if opts.compression_level < 0 or opts.compression_level > 9:
parser.error("Compression level must be between 0 and 9 inclusive.")
app = XpraClient(conn, opts.compression_level)
app.connect("handshake-complete", handshake_complete_msg)
app.connect("received-gibberish", got_gibberish_msg)
app.run()
def run_proxy(parser, opts, extra_args):
from xpra.proxy import XpraProxy
assert "gtk" not in sys.modules
server_conn = connect_or_fail(pick_display(parser, opts, extra_args))
app = XpraProxy(TwoFileConnection(sys.stdout, sys.stdin), server_conn)
app.run()
def run_stop(parser, opts, extra_args):
assert "gtk" not in sys.modules
magic_string = bencode(["hello", []]) + bencode(["shutdown-server"])
display_desc = pick_display(parser, opts, extra_args)
conn = connect_or_fail(display_desc)
while magic_string:
magic_string = magic_string[conn.write(magic_string):]
while conn.read(4096):
pass
if display_desc["local"]:
sockdir = DotXpra()
for i in xrange(6):
final_state = sockdir.server_state(display_desc["display"])
if final_state is DotXpra.LIVE:
time.sleep(0.5)
else:
break
if final_state is DotXpra.DEAD:
print "xpra at %s has exited." % display_desc["display"]
sys.exit(0)
elif final_state is DotXpra.UNKNOWN:
print ("How odd... I'm not sure what's going on with xpra at %s"
% display_desc["display"])
sys.exit(1)
elif final_state is DotXpra.LIVE:
print "Failed to shutdown xpra at %s" % display_desc["display"]
sys.exit(1)
else:
assert False
else:
print "Sent shutdown command"
def run_list(parser, opts, extra_args):
assert "gtk" not in sys.modules
if extra_args:
parser.error("too many arguments for mode")
sockdir = DotXpra()
results = sockdir.sockets()
if not results:
sys.stdout.write("No xpra sessions found\n")
else:
sys.stdout.write("Found the following xpra sessions:\n")
for state, display in results:
sys.stdout.write("\t%s session at %s" % (state, display))
if state is DotXpra.DEAD:
try:
os.unlink(sockdir.socket_path(display))
except OSError:
pass
else:
sys.stdout.write(" (cleaned up)")
sys.stdout.write("\n")<|fim▁end|>
|
"local": True,
|
<|file_name|>const_FRAC_1_PI.rs<|end_file_name|><|fim▁begin|>#![feature(core)]<|fim▁hole|>extern crate core;
#[cfg(test)]
mod tests {
use core::f32::consts::FRAC_1_PI;
// 1.0/pi
// pub const FRAC_1_PI: f32 = 0.318309886183790671537767526745028724_f32;
#[test]
fn frac_1_pi_test1() {
let mut value: f32 = 0.0_f32;
unsafe {
*(&mut value as *mut f32 as *mut u32) =
0b0_01111101_01000101111100110000011;
}
assert_eq!(FRAC_1_PI, value);
}
}<|fim▁end|>
| |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>__version__ = '0.4'
__author__ = 'Martin Natano <[email protected]>'
_repository = None
_branch = 'git-orm'
_remote = 'origin'
class GitError(Exception): pass
def set_repository(value):
from pygit2 import discover_repository, Repository
global _repository
if value is None:
_repository = None
return
try:
path = discover_repository(value)
except KeyError:
raise GitError('no repository found in "{}"'.format(value))
_repository = Repository(path)
def get_repository():
return _repository
def set_branch(value):
global _branch
_branch = value
def get_branch():<|fim▁hole|>
def set_remote(value):
global _remote
_remote = value
def get_remote():
return _remote<|fim▁end|>
|
return _branch
|
<|file_name|>Setup.py<|end_file_name|><|fim▁begin|>"""In the case that the Setup.py file fails to execute, please manually install the following packages,
or execute the requirements.sh script."""
# Installing Requirements: #
# pip install git+https://github.com/pwaller/pyfiglet #
# pip install colorama #
# pip install termcolor #
# pip install blessings #
from distutils.core import setup
setup(name='DPS East Hackathon Rule booklet.',
version='1.0',
description='DPS East Hackathon Rule booklet.',
author='thel3l',
author_email='[email protected]',
url='https://www.github.com/thel3l/hackathon-dpse',
packages=['distutils', 'distutils.command', 'pyfiglet', 'colorama', 'termcolor', 'blessings'],<|fim▁hole|><|fim▁end|>
|
)
|
<|file_name|>elixirSenseSignatureHelpProvider.ts<|end_file_name|><|fim▁begin|>import { join, sep } from 'path';
import * as vscode from 'vscode';
import { ElixirSenseClient } from './elixirSenseClient';
import { checkElixirSenseClientInitialized, checkTokenCancellation } from './elixirSenseValidations';
function validateResultIsNotNone(result: any) {
if (result === 'none') {
throw new Error();
}
return result;
}
export class ElixirSenseSignatureHelpProvider implements vscode.SignatureHelpProvider {
constructor(private elixirSenseClient: ElixirSenseClient) {}
provideSignatureHelp(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken): Thenable<vscode.SignatureHelp> {
return new Promise((resolve, reject) => {
let elixirSenseClientError;
const resultPromise = Promise.resolve(this.elixirSenseClient)
.then(elixirSenseClient => checkElixirSenseClientInitialized(elixirSenseClient))
.catch(err => {
elixirSenseClientError = err;
});
if (elixirSenseClientError) {
console.error('rejecting', elixirSenseClientError);
reject();
return;
}
const documentPath = (document.uri || { fsPath: '' }).fsPath || '';
if (!documentPath.startsWith(join(this.elixirSenseClient.projectPath, sep))) {
reject();
return;
}
const payload = {
buffer: document.getText(),
line: position.line + 1,
column: position.character + 1
};
return resultPromise
.then((elixirSenseClient: ElixirSenseClient) => elixirSenseClient.send('signature', payload))
.then(result => checkTokenCancellation(token, result))
.then(result => validateResultIsNotNone(result))
.then(result => {
let paramPosition = result.active_param;
const pipeBefore = result.pipe_before;
let signatures = result.signatures.filter(sig => sig.params.length > paramPosition);
if (signatures.length === 0 && result.signatures.length > 0) {
signatures = result.signatures.slice(result.signatures.length - 1, result.signatures.length);
if (signatures[0].params[signatures[0].params.length - 1].includes('\\ []')) {
paramPosition = signatures[0].params.length - 1;
}
}
const vsSigs = this.processSignatures(signatures);
const signatureHelper = new vscode.SignatureHelp();
signatureHelper.activeParameter = paramPosition;
signatureHelper.activeSignature = 0;
signatureHelper.signatures = vsSigs;<|fim▁hole|> .catch(err => {
console.error('rejecting', err);
reject();
});
});
}
processSignatures(signatures): vscode.SignatureInformation[] {
return Array.from(signatures).map(s => this.genSignatureInfo(s));
}
genSignatureInfo(signature): vscode.SignatureInformation {
const si = new vscode.SignatureInformation(signature.name + '(' + signature.params.join(', ') + ')', signature.documentation + '\n' + signature.spec);
si.parameters = Array.from(signature.params).map(p => this.genParameterInfo(p));
return si;
}
genParameterInfo(param): vscode.ParameterInformation {
return new vscode.ParameterInformation(param);
}
}<|fim▁end|>
|
resolve(signatureHelper);
})
|
<|file_name|>core.js<|end_file_name|><|fim▁begin|>/**
* Fac.js
* (c) 2017 Owen Luke
* https://github.com/tasjs/fac
* Released under the MIT License.
*/
var copy = require('./copy');
var chain = require('./chain');
var super_ = require('./super');
var core = {
new: function(options){
typeof options === 'string' && (options = {name: options});
var obj = chain.create(this, options);
obj.protoName = this.name;
obj.model = this;
obj.super = super_;
chain.init(obj.parent, options, obj);
return obj;
},
extends: function(proto, p1){
var obj = chain.create(this, {});
var options = proto;
if (typeof p1 !== 'undefined') {
var args = Array.prototype.slice.call(arguments);
for (var i = 0, len = args.length - 1; i < len; i ++) {
options = args[i];
copy.do(obj, options);
}
options = args[i];
}
copy.do(obj, options);
obj.protoName = options.name;
obj.super = super_;
typeof options.default === 'function' && options.default.call(obj, options);
return obj;
},
ext: function(options){
copy.do(this, options);
return this;
},
spawn: function(options) {
typeof options === 'string' && (options = {name: options});
var obj = Object.create(this);
copy.do(obj, options);
chain.init(this, options, obj);
return obj;
},
isChildOf: function(obj){
return chain.isChildOf(obj, this);
},
isParentOf: function(obj){
return chain.isParentOf(obj, this);
},<|fim▁hole|> },
isDescendantOf: function(obj){
return chain.isDescendantOf(obj, this);
},
isModelOf: function(obj){
return this === obj.model;
},
isCopyOf: function(obj){
return this.model === obj;
}
};
module.exports = core;<|fim▁end|>
|
isAncestorOf: function(obj){
return chain.isAncestorOf(obj, this);
|
<|file_name|>excel_importer.py<|end_file_name|><|fim▁begin|>from corehq.util.spreadsheets.excel import WorkbookJSONReader
from soil import DownloadBase
class UnknownFileRefException(Exception):
pass
class ExcelImporter(object):
"""
Base class for `SingleExcelImporter` and `MultiExcelImporter`.
This is not meant to be used directly.
"""
def __init__(self, task, file_ref_id):
self.task = task
self.progress = 0
if self.task:
DownloadBase.set_progress(self.task, 0, 100)
download_ref = DownloadBase.get(file_ref_id)
if download_ref is None:
raise UnknownFileRefException("Could not find file wih ref %s. It may have expired" % file_ref_id)
self.workbook = WorkbookJSONReader(download_ref.get_filename())
def mark_complete(self):
if self.task:
DownloadBase.set_progress(self.task, 100, 100)
def add_progress(self, count=1):
self.progress += count
if self.task:
DownloadBase.set_progress(self.task, self.progress, self.total_rows)
class SingleExcelImporter(ExcelImporter):
"""
Manage importing from an excel file with only one
worksheet.
"""
def __init__(self, task, file_ref_id):
super(SingleExcelImporter, self).__init__(task, file_ref_id)
self.worksheet = self.workbook.worksheets[0]
self.total_rows = self.worksheet.worksheet.get_highest_row()
class MultiExcelImporter(ExcelImporter):<|fim▁hole|> relevant worksheets.
"""
def __init__(self, task, file_ref_id):
super(MultiExcelImporter, self).__init__(task, file_ref_id)
self.worksheets = self.workbook.worksheets
self.total_rows = sum(ws.worksheet.get_highest_row() for ws in self.worksheets)<|fim▁end|>
|
"""
Manage importing from an excel file with multiple
|
<|file_name|>while-with-break.rs<|end_file_name|><|fim▁begin|>// -*- rust -*-
pub fn main() {<|fim▁hole|> while i < 100 {
info!(i);
i = i + 1;
if i == 95 {
let _v: ~[int] =
~[1, 2, 3, 4, 5]; // we check that it is freed by break
info!("breaking");
break;
}
}
assert_eq!(i, 95);
}<|fim▁end|>
|
let mut i: int = 90;
|
<|file_name|>models.py<|end_file_name|><|fim▁begin|># Define a custom User class to work with django-social-auth
from django.db import models
from django.contrib.auth.models import User
class Task(models.Model):
name = models.CharField(max_length=200)
owner = models.ForeignKey(User)
finished = models.BooleanField(default=False)
shared = models.BooleanField(default=False)
class Viewer(models.Model):
name = models.ForeignKey(User)
tasks = models.ForeignKey(Task)
class Friends(models.Model):<|fim▁hole|> friend = models.ForeignKey(User, related_name="friend_set")
class CustomUserManager(models.Manager):
def create_user(self, username, email):
return self.model._default_manager.create(username=username)
class CustomUser(models.Model):
username = models.CharField(max_length=128)
last_login = models.DateTimeField(blank=True, null=True)
objects = CustomUserManager()
def is_authenticated(self):
return True<|fim▁end|>
|
created = models.DateTimeField(auto_now_add=True, editable=False)
creator = models.ForeignKey(User, related_name="friendship_creator_set")
|
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>VERSION = (1, 2, 21)
def get_version():<|fim▁hole|> return '%d.%d.%d'%VERSION
__author__ = 'Marinho Brandao'
#__date__ = '$Date: 2008-07-26 14:04:51 -0300 (Ter, 26 Fev 2008) $'[7:-2]
__license__ = 'GNU Lesser General Public License (LGPL)'
__url__ = 'http://django-plus.googlecode.com'
__version__ = get_version()
def get_dynamic_template(slug, context=None):
from models import DynamicTemplate
return DynamicTemplate.objects.get(slug=slug).render(context or {})<|fim▁end|>
| |
<|file_name|>CompareDump.cpp<|end_file_name|><|fim▁begin|>/*
---------------------------------------------------------------------------
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team
All rights reserved.
Redistribution and use of this software 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 assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
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.
---------------------------------------------------------------------------
*/
/** @file CompareDump.cpp
* @brief Implementation of the 'assimp cmpdmp', which compares
* two model dumps for equality. It plays an important role
* in the regression test suite.
*/
#include "Main.h"
const char* AICMD_MSG_CMPDUMP_HELP =
"assimp cmpdump <actual> <expected>\n"
"\tCompare two short dumps produced with \'assimp dump <..> -s\' for equality.\n"
;
#include "../../code/assbin_chunks.h"
////////////////////////////////////////////////////////////////////////////////////////////////////
#include "generic_inserter.hpp"
#include <map>
#include <deque>
#include <stack>
#include <sstream>
#include <iostream>
#include "../../include/assimp/ai_assert.h"
// get << for aiString
template <typename char_t, typename traits_t>
void mysprint(std::basic_ostream<char_t, traits_t>& os, const aiString& vec) {
os << "[length: \'" << std::dec << vec.length << "\' content: \'" << vec.data << "\']";
}
template <typename char_t, typename traits_t>
std::basic_ostream<char_t, traits_t>& operator<< (std::basic_ostream<char_t, traits_t>& os, const aiString& vec) {
return generic_inserter(mysprint<char_t,traits_t>, os, vec);
}
class sliced_chunk_iterator;
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @class compare_fails_exception
///
/// @brief Sentinel exception to return quickly from deeply nested control paths
////////////////////////////////////////////////////////////////////////////////////////////////////
class compare_fails_exception : public virtual std::exception {
public:
enum {MAX_ERR_LEN = 4096};
/* public c'tors */
compare_fails_exception(const char* msg) {
strncpy(mywhat,msg,MAX_ERR_LEN-1);
strcat(mywhat,"\n");
}
/* public member functions */
const char* what() const throw() {
return mywhat;
}
private:
char mywhat[MAX_ERR_LEN+1];
};
#define MY_FLT_EPSILON 1e-1f
#define MY_DBL_EPSILON 1e-1
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @class comparer_context
///
/// @brief Record our way through the files to be compared and dump useful information if we fail.
////////////////////////////////////////////////////////////////////////////////////////////////////
class comparer_context {
friend class sliced_chunk_iterator;
public:
/* construct given two file handles to compare */
comparer_context(FILE* actual,FILE* expect)
: actual(actual)
, expect(expect)
, cnt_chunks(0)
{
ai_assert(actual);
ai_assert(expect);
fseek(actual,0,SEEK_END);
lengths.push(std::make_pair(static_cast<uint32_t>(ftell(actual)),0));
fseek(actual,0,SEEK_SET);
history.push_back(HistoryEntry("---",PerChunkCounter()));
}
public:
/* set new scope */
void push_elem(const char* msg) {
const std::string s = msg;
PerChunkCounter::const_iterator it = history.back().second.find(s);
if(it != history.back().second.end()) {
++history.back().second[s];
}
else history.back().second[s] = 0;
history.push_back(HistoryEntry(s,PerChunkCounter()));
debug_trace.push_back("PUSH " + s);
}
/* leave current scope */
void pop_elem() {
ai_assert(history.size());
debug_trace.push_back("POP "+ history.back().first);
history.pop_back();
}
/* push current chunk length and start offset on top of stack */
void push_length(uint32_t nl, uint32_t start) {
lengths.push(std::make_pair(nl,start));
++cnt_chunks;
}
/* pop the chunk length stack */
void pop_length() {
ai_assert(lengths.size());
lengths.pop();
}
/* access the current chunk length */
uint32_t get_latest_chunk_length() {
ai_assert(lengths.size());
return lengths.top().first;
}
/* access the current chunk start offset */
uint32_t get_latest_chunk_start() {
ai_assert(lengths.size());
return lengths.top().second;
}
/* total number of chunk headers passed so far*/
uint32_t get_num_chunks() {
return cnt_chunks;
}
/* get ACTUAL file desc. != NULL */
FILE* get_actual() const {
return actual;
}
/* get EXPECT file desc. != NULL */
FILE* get_expect() const {
return expect;
}
/* compare next T from both streams, name occurs in error messages */
template<typename T> T cmp(const std::string& name) {
T a,e;
read(a,e);
if(a != e) {
std::stringstream ss;
failure((ss<< "Expected " << e << ", but actual is " << a,
ss.str()),name);
}
// std::cout << name << " " << std::hex << a << std::endl;
return a;
}
/* compare next num T's from both streams, name occurs in error messages */
template<typename T> void cmp(size_t num,const std::string& name) {
for(size_t n = 0; n < num; ++n) {
std::stringstream ss;
cmp<T>((ss<<name<<"["<<n<<"]",ss.str()));
// std::cout << name << " " << std::hex << a << std::endl;
}
}
/* Bounds of an aiVector3D array (separate function
* because partial specializations of member functions are illegal--)*/
template<typename T> void cmp_bounds(const std::string& name) {
cmp<T> (name+".<minimum-value>");
cmp<T> (name+".<maximum-value>");
}
private:
/* Report failure */
AI_WONT_RETURN void failure(const std::string& err, const std::string& name) AI_WONT_RETURN_SUFFIX {
std::stringstream ss;
throw compare_fails_exception((ss
<< "Files are different at "
<< history.back().first
<< "."
<< name
<< ".\nError is: "
<< err
<< ".\nCurrent position in scene hierarchy is "
<< print_hierarchy(),ss.str().c_str()
));
}
/** print our 'stack' */
std::string print_hierarchy() {
std::stringstream ss;
ss << "\n";
const char* last = history.back().first.c_str();
std::string pad;
for(ChunkHistory::reverse_iterator rev = history.rbegin(),
end = history.rend(); rev != end; ++rev, pad += " ")
{
ss << pad << (*rev).first << "(Index: " << (*rev).second[last] << ")" << "\n";
last = (*rev).first.c_str();
}
ss << std::endl << "Debug trace: "<< "\n";
for (std::vector<std::string>::const_iterator it = debug_trace.begin(); it != debug_trace.end(); ++it) {
ss << *it << "\n";
}
ss << std::flush;
return ss.str();
}
/* read from both streams at the same time */
template <typename T> void read(T& filla,T& fille) {
if(1 != fread(&filla,sizeof(T),1,actual)) {
EOFActual();
}
if(1 != fread(&fille,sizeof(T),1,expect)) {
EOFExpect();
}
}
private:
void EOFActual() {
std::stringstream ss;
throw compare_fails_exception((ss
<< "Unexpected EOF reading ACTUAL.\nCurrent position in scene hierarchy is "
<< print_hierarchy(),ss.str().c_str()
));
}
void EOFExpect() {
std::stringstream ss;
throw compare_fails_exception((ss
<< "Unexpected EOF reading EXPECT.\nCurrent position in scene hierarchy is "
<< print_hierarchy(),ss.str().c_str()
));
}
FILE *const actual, *const expect;
typedef std::map<std::string,unsigned int> PerChunkCounter;
typedef std::pair<std::string,PerChunkCounter> HistoryEntry;
typedef std::deque<HistoryEntry> ChunkHistory;
ChunkHistory history;
std::vector<std::string> debug_trace;
typedef std::stack<std::pair<uint32_t,uint32_t> > LengthStack;
LengthStack lengths;
uint32_t cnt_chunks;
};
////////////////////////////////////////////////////////////////////////////////////////////////////
/* specialization for aiString (it needs separate handling because its on-disk representation
* differs from its binary representation in memory and can't be treated as an array of n T's.*/
template <> void comparer_context :: read<aiString>(aiString& filla,aiString& fille) {
uint32_t lena,lene;
read(lena,lene);
if(lena && 1 != fread(&filla.data,lena,1,actual)) {
EOFActual();
}
if(lene && 1 != fread(&fille.data,lene,1,expect)) {
EOFExpect();
}
fille.data[fille.length=static_cast<unsigned int>(lene)] = '\0';
filla.data[filla.length=static_cast<unsigned int>(lena)] = '\0';
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/* Specialization for float, uses epsilon for comparisons*/
template<> float comparer_context :: cmp<float>(const std::string& name)
{
float a,e,t;
read(a,e);
if((t=fabs(a-e)) > MY_FLT_EPSILON) {
std::stringstream ss;
failure((ss<< "Expected " << e << ", but actual is "
<< a << " (delta is " << t << ")", ss.str()),name);
}
return a;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/* Specialization for double, uses epsilon for comparisons*/
template<> double comparer_context :: cmp<double>(const std::string& name)
{
double a,e,t;
read(a,e);
if((t=fabs(a-e)) > MY_DBL_EPSILON) {
std::stringstream ss;
failure((ss<< "Expected " << e << ", but actual is "
<< a << " (delta is " << t << ")", ss.str()),name);
}
return a;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/* Specialization for aiVector3D */
template<> aiVector3D comparer_context :: cmp<aiVector3D >(const std::string& name)
{
const float x = cmp<float>(name+".x");
const float y = cmp<float>(name+".y");
const float z = cmp<float>(name+".z");
return aiVector3D(x,y,z);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/* Specialization for aiColor4D */
template<> aiColor4D comparer_context :: cmp<aiColor4D >(const std::string& name)
{
const float r = cmp<float>(name+".r");
const float g = cmp<float>(name+".g");
const float b = cmp<float>(name+".b");
const float a = cmp<float>(name+".a");
return aiColor4D(r,g,b,a);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/* Specialization for aiQuaternion */
template<> aiQuaternion comparer_context :: cmp<aiQuaternion >(const std::string& name)
{
const float w = cmp<float>(name+".w");
const float x = cmp<float>(name+".x");
const float y = cmp<float>(name+".y");
const float z = cmp<float>(name+".z");
return aiQuaternion(w,x,y,z);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/* Specialization for aiQuatKey */
template<> aiQuatKey comparer_context :: cmp<aiQuatKey >(const std::string& name)
{
const double mTime = cmp<double>(name+".mTime");
const aiQuaternion mValue = cmp<aiQuaternion>(name+".mValue");
return aiQuatKey(mTime,mValue);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/* Specialization for aiVectorKey */
template<> aiVectorKey comparer_context :: cmp<aiVectorKey >(const std::string& name)
{
const double mTime = cmp<double>(name+".mTime");
const aiVector3D mValue = cmp<aiVector3D>(name+".mValue");
return aiVectorKey(mTime,mValue);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/* Specialization for aiMatrix4x4 */
template<> aiMatrix4x4 comparer_context :: cmp<aiMatrix4x4 >(const std::string& name)
{
aiMatrix4x4 res;
for(unsigned int i = 0; i < 4; ++i) {
for(unsigned int j = 0; j < 4; ++j) {
std::stringstream ss;
res[i][j] = cmp<float>(name+(ss<<".m"<<i<<j,ss.str()));
}
}
return res;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/* Specialization for aiVertexWeight */
template<> aiVertexWeight comparer_context :: cmp<aiVertexWeight >(const std::string& name)
{
const unsigned int mVertexId = cmp<unsigned int>(name+".mVertexId");
const float mWeight = cmp<float>(name+".mWeight");
return aiVertexWeight(mVertexId,mWeight);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @class sliced_chunk_iterator
///
/// @brief Helper to iterate easily through corresponding chunks of two dumps simultaneously.
///
/// Not a *real* iterator, doesn't fully conform to the isocpp iterator spec
////////////////////////////////////////////////////////////////////////////////////////////////////
class sliced_chunk_iterator {
friend class sliced_chunk_reader;
sliced_chunk_iterator(comparer_context& ctx, long end)
: ctx(ctx)
, endit(false)
, next(std::numeric_limits<long>::max())
, end(end)
{
load_next();
}
public:
~sliced_chunk_iterator() {
fseek(ctx.get_actual(),end,SEEK_SET);
fseek(ctx.get_expect(),end,SEEK_SET);
}
public:
/* get current chunk head */
typedef std::pair<uint32_t,uint32_t> Chunk;
const Chunk& operator*() {
return current;
}
/* get to next chunk head */
const sliced_chunk_iterator& operator++() {
cleanup();
load_next();
return *this;
}
/* */
bool is_end() const {
return endit;
}
private:
/* get to the end of *this* chunk */
void cleanup() {
if(next != std::numeric_limits<long>::max()) {
fseek(ctx.get_actual(),next,SEEK_SET);
fseek(ctx.get_expect(),next,SEEK_SET);
ctx.pop_length();
}
}
/* advance to the next chunk */
void load_next() {
Chunk actual;
size_t res=0;
const long cur = ftell(ctx.get_expect());
if(end-cur<8) {
current = std::make_pair(0u,0u);
endit = true;
return;
}
res|=fread(¤t.first,4,1,ctx.get_expect());
res|=fread(¤t.second,4,1,ctx.get_expect()) <<1u;
res|=fread(&actual.first,4,1,ctx.get_actual()) <<2u;
res|=fread(&actual.second,4,1,ctx.get_actual()) <<3u;
if(res!=0xf) {
ctx.failure("IO Error reading chunk head, dumps are malformed","<ChunkHead>");
}
if (current.first != actual.first) {
std::stringstream ss;
ctx.failure((ss
<<"Chunk headers do not match. EXPECT: "
<< std::hex << current.first
<<" ACTUAL: "
<< /*std::hex */actual.first,
ss.str()),
"<ChunkHead>");
}
if (current.first != actual.first) {
std::stringstream ss;
ctx.failure((ss
<<"Chunk lengths do not match. EXPECT: "
<<current.second
<<" ACTUAL: "
<< actual.second,
ss.str()),
"<ChunkHead>");
}
next = cur+current.second+8;
ctx.push_length(current.second,cur+8);
}
comparer_context& ctx;
Chunk current;
bool endit;
long next,end;
};
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @class sliced_chunk_reader
///
/// @brief Helper to iterate easily through corresponding chunks of two dumps simultaneously.
////////////////////////////////////////////////////////////////////////////////////////////////////
class sliced_chunk_reader {
public:
//
sliced_chunk_reader(comparer_context& ctx)
: ctx(ctx)
{}
//
~sliced_chunk_reader() {
}
public:
sliced_chunk_iterator begin() const {
return sliced_chunk_iterator(ctx,ctx.get_latest_chunk_length()+
ctx.get_latest_chunk_start());
}
private:
comparer_context& ctx;
};
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @class scoped_chunk
///
/// @brief Utility to simplify usage of comparer_context.push_elem/pop_elem
////////////////////////////////////////////////////////////////////////////////////////////////////
class scoped_chunk {
public:
//
scoped_chunk(comparer_context& ctx,const char* msg)
: ctx(ctx)<|fim▁hole|>
//
~scoped_chunk()
{
ctx.pop_elem();
}
private:
comparer_context& ctx;
};
////////////////////////////////////////////////////////////////////////////////////////////////////
void CompareOnTheFlyMaterialProperty(comparer_context& comp) {
scoped_chunk chunk(comp,"aiMaterialProperty");
comp.cmp<aiString>("mKey");
comp.cmp<uint32_t>("mSemantic");
comp.cmp<uint32_t>("mIndex");
const uint32_t length = comp.cmp<uint32_t>("mDataLength");
const aiPropertyTypeInfo type = static_cast<aiPropertyTypeInfo>(
comp.cmp<uint32_t>("mType"));
switch (type)
{
case aiPTI_Float:
comp.cmp<float>(length/4,"mData");
break;
case aiPTI_String:
comp.cmp<aiString>("mData");
break;
case aiPTI_Integer:
comp.cmp<uint32_t>(length/4,"mData");
break;
case aiPTI_Buffer:
comp.cmp<uint8_t>(length,"mData");
break;
default:
break;
};
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void CompareOnTheFlyMaterial(comparer_context& comp) {
scoped_chunk chunk(comp,"aiMaterial");
comp.cmp<uint32_t>("aiMaterial::mNumProperties");
sliced_chunk_reader reader(comp);
for(sliced_chunk_iterator it = reader.begin(); !it.is_end(); ++it) {
if ((*it).first == ASSBIN_CHUNK_AIMATERIALPROPERTY) {
CompareOnTheFlyMaterialProperty(comp);
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void CompareOnTheFlyBone(comparer_context& comp) {
scoped_chunk chunk(comp,"aiBone");
comp.cmp<aiString>("mName");
comp.cmp<uint32_t>("mNumWeights");
comp.cmp<aiMatrix4x4>("mOffsetMatrix");
comp.cmp_bounds<aiVertexWeight>("mWeights");
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void CompareOnTheFlyNodeAnim(comparer_context& comp) {
scoped_chunk chunk(comp,"aiNodeAnim");
comp.cmp<aiString>("mNodeName");
comp.cmp<uint32_t>("mNumPositionKeys");
comp.cmp<uint32_t>("mNumRotationKeys");
comp.cmp<uint32_t>("mNumScalingKeys");
comp.cmp<uint32_t>("mPreState");
comp.cmp<uint32_t>("mPostState");
comp.cmp_bounds<aiVectorKey>("mPositionKeys");
comp.cmp_bounds<aiQuatKey>("mRotationKeys");
comp.cmp_bounds<aiVectorKey>("mScalingKeys");
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void CompareOnTheFlyMesh(comparer_context& comp) {
scoped_chunk chunk(comp,"aiMesh");
comp.cmp<uint32_t>("mPrimitiveTypes");
comp.cmp<uint32_t>("mNumVertices");
const uint32_t nf = comp.cmp<uint32_t>("mNumFaces");
comp.cmp<uint32_t>("mNumBones");
comp.cmp<uint32_t>("mMaterialIndex");
const uint32_t present = comp.cmp<uint32_t>("<vertex-components-present>");
if(present & ASSBIN_MESH_HAS_POSITIONS) {
comp.cmp_bounds<aiVector3D>("mVertices");
}
if(present & ASSBIN_MESH_HAS_NORMALS) {
comp.cmp_bounds<aiVector3D>("mNormals");
}
if(present & ASSBIN_MESH_HAS_TANGENTS_AND_BITANGENTS) {
comp.cmp_bounds<aiVector3D>("mTangents");
comp.cmp_bounds<aiVector3D>("mBitangents");
}
for(unsigned int i = 0; present & ASSBIN_MESH_HAS_COLOR(i); ++i) {
std::stringstream ss;
comp.cmp_bounds<aiColor4D>((ss<<"mColors["<<i<<"]",ss.str()));
}
for(unsigned int i = 0; present & ASSBIN_MESH_HAS_TEXCOORD(i); ++i) {
std::stringstream ss;
comp.cmp<uint32_t>((ss<<"mNumUVComponents["<<i<<"]",ss.str()));
comp.cmp_bounds<aiVector3D>((ss.clear(),ss<<"mTextureCoords["<<i<<"]",ss.str()));
}
for(unsigned int i = 0; i< ((nf+511)/512); ++i) {
std::stringstream ss;
comp.cmp<uint32_t>((ss<<"mFaces["<<i*512<<"-"<<std::min(static_cast<
uint32_t>((i+1)*512),nf)<<"]",ss.str()));
}
sliced_chunk_reader reader(comp);
for(sliced_chunk_iterator it = reader.begin(); !it.is_end(); ++it) {
if ((*it).first == ASSBIN_CHUNK_AIBONE) {
CompareOnTheFlyBone(comp);
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void CompareOnTheFlyCamera(comparer_context& comp) {
scoped_chunk chunk(comp,"aiCamera");
comp.cmp<aiString>("mName");
comp.cmp<aiVector3D>("mPosition");
comp.cmp<aiVector3D>("mLookAt");
comp.cmp<aiVector3D>("mUp");
comp.cmp<float>("mHorizontalFOV");
comp.cmp<float>("mClipPlaneNear");
comp.cmp<float>("mClipPlaneFar");
comp.cmp<float>("mAspect");
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void CompareOnTheFlyLight(comparer_context& comp) {
scoped_chunk chunk(comp,"aiLight");
comp.cmp<aiString>("mName");
const aiLightSourceType type = static_cast<aiLightSourceType>(
comp.cmp<uint32_t>("mType"));
if(type!=aiLightSource_DIRECTIONAL) {
comp.cmp<float>("mAttenuationConstant");
comp.cmp<float>("mAttenuationLinear");
comp.cmp<float>("mAttenuationQuadratic");
}
comp.cmp<aiVector3D>("mColorDiffuse");
comp.cmp<aiVector3D>("mColorSpecular");
comp.cmp<aiVector3D>("mColorAmbient");
if(type==aiLightSource_SPOT) {
comp.cmp<float>("mAngleInnerCone");
comp.cmp<float>("mAngleOuterCone");
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void CompareOnTheFlyAnimation(comparer_context& comp) {
scoped_chunk chunk(comp,"aiAnimation");
comp.cmp<aiString>("mName");
comp.cmp<double>("mDuration");
comp.cmp<double>("mTicksPerSecond");
comp.cmp<uint32_t>("mNumChannels");
sliced_chunk_reader reader(comp);
for(sliced_chunk_iterator it = reader.begin(); !it.is_end(); ++it) {
if ((*it).first == ASSBIN_CHUNK_AINODEANIM) {
CompareOnTheFlyNodeAnim(comp);
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void CompareOnTheFlyTexture(comparer_context& comp) {
scoped_chunk chunk(comp,"aiTexture");
const uint32_t w = comp.cmp<uint32_t>("mWidth");
const uint32_t h = comp.cmp<uint32_t>("mHeight");
(void)w; (void)h;
comp.cmp<char>("achFormatHint[0]");
comp.cmp<char>("achFormatHint[1]");
comp.cmp<char>("achFormatHint[2]");
comp.cmp<char>("achFormatHint[3]");
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void CompareOnTheFlyNode(comparer_context& comp) {
scoped_chunk chunk(comp,"aiNode");
comp.cmp<aiString>("mName");
comp.cmp<aiMatrix4x4>("mTransformation");
comp.cmp<uint32_t>("mNumChildren");
comp.cmp<uint32_t>(comp.cmp<uint32_t>("mNumMeshes"),"mMeshes");
sliced_chunk_reader reader(comp);
for(sliced_chunk_iterator it = reader.begin(); !it.is_end(); ++it) {
if ((*it).first == ASSBIN_CHUNK_AINODE) {
CompareOnTheFlyNode(comp);
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void CompareOnTheFlyScene(comparer_context& comp) {
scoped_chunk chunk(comp,"aiScene");
comp.cmp<uint32_t>("mFlags");
comp.cmp<uint32_t>("mNumMeshes");
comp.cmp<uint32_t>("mNumMaterials");
comp.cmp<uint32_t>("mNumAnimations");
comp.cmp<uint32_t>("mNumTextures");
comp.cmp<uint32_t>("mNumLights");
comp.cmp<uint32_t>("mNumCameras");
sliced_chunk_reader reader(comp);
for(sliced_chunk_iterator it = reader.begin(); !it.is_end(); ++it) {
if ((*it).first == ASSBIN_CHUNK_AIMATERIAL) {
CompareOnTheFlyMaterial(comp);
}
else if ((*it).first == ASSBIN_CHUNK_AITEXTURE) {
CompareOnTheFlyTexture(comp);
}
else if ((*it).first == ASSBIN_CHUNK_AIMESH) {
CompareOnTheFlyMesh(comp);
}
else if ((*it).first == ASSBIN_CHUNK_AIANIMATION) {
CompareOnTheFlyAnimation(comp);
}
else if ((*it).first == ASSBIN_CHUNK_AICAMERA) {
CompareOnTheFlyCamera(comp);
}
else if ((*it).first == ASSBIN_CHUNK_AILIGHT) {
CompareOnTheFlyLight(comp);
}
else if ((*it).first == ASSBIN_CHUNK_AINODE) {
CompareOnTheFlyNode(comp);
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void CompareOnTheFly(comparer_context& comp)
{
sliced_chunk_reader reader(comp);
for(sliced_chunk_iterator it = reader.begin(); !it.is_end(); ++it) {
if ((*it).first == ASSBIN_CHUNK_AISCENE) {
CompareOnTheFlyScene(comp);
break;
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void CheckHeader(comparer_context& comp)
{
fseek(comp.get_actual(),ASSBIN_HEADER_LENGTH,SEEK_CUR);
fseek(comp.get_expect(),ASSBIN_HEADER_LENGTH,SEEK_CUR);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
int Assimp_CompareDump (const char* const* params, unsigned int num)
{
// --help
if ((num == 1 && !strcmp( params[0], "-h")) || !strcmp( params[0], "--help") || !strcmp( params[0], "-?") ) {
printf("%s",AICMD_MSG_CMPDUMP_HELP);
return 0;
}
// assimp cmpdump actual expected
if (num < 2) {
std::cout << "assimp cmpdump: Invalid number of arguments. "
"See \'assimp cmpdump --help\'\r\n" << std::endl;
return 1;
}
if(!strcmp(params[0],params[1])) {
std::cout << "assimp cmpdump: same file, same content." << std::endl;
return 0;
}
class file_ptr
{
public:
file_ptr(FILE *p)
: m_file(p)
{}
~file_ptr()
{
if (m_file)
{
fclose(m_file);
m_file = NULL;
}
}
operator FILE *() { return m_file; }
private:
FILE *m_file;
};
file_ptr actual(fopen(params[0],"rb"));
if (!actual) {
std::cout << "assimp cmpdump: Failure reading ACTUAL data from " <<
params[0] << std::endl;
return -5;
}
file_ptr expected(fopen(params[1],"rb"));
if (!expected) {
std::cout << "assimp cmpdump: Failure reading EXPECT data from " <<
params[1] << std::endl;
return -6;
}
comparer_context comp(actual,expected);
try {
CheckHeader(comp);
CompareOnTheFly(comp);
}
catch(const compare_fails_exception& ex) {
printf("%s",ex.what());
return -1;
}
catch(...) {
// we don't bother checking too rigourously here, so
// we might end up here ...
std::cout << "Unknown failure, are the input files well-defined?";
return -3;
}
std::cout << "Success (totally " << std::dec << comp.get_num_chunks() <<
" chunks)" << std::endl;
return 0;
}<|fim▁end|>
|
{
ctx.push_elem(msg);
}
|
<|file_name|>services.go<|end_file_name|><|fim▁begin|>package services
import (
"fmt"
"net"
"net/url"
"github.com/tolivb/scf/pkg/config"
)
// Services interface
type Services interface {
Start() error
}
// Syslog service responsible for receiving log messages
type Syslog struct {
cfg *config.Config
conn *net.UDPConn
status *Status<|fim▁hole|> addr string
net string
}
// Start implements Services interface
func (s *Syslog) Start() error {
if s.conn != nil {
return fmt.Errorf("Syslog service already started on %s", s.addr)
}
udpAddr, err := net.ResolveUDPAddr(s.net, s.addr)
if err != nil {
return fmt.Errorf("Syslog unable to resolve listen addr %s: %s", s.addr, err)
}
s.cfg.Log.Debug("Syslog listen addr resolved to %", udpAddr)
conn, err := net.ListenUDP(s.net, udpAddr)
if err != nil {
return err
}
s.conn = conn
s.cfg.Log.Info("Syslog rcv service started on %s://%s", s.net, s.addr)
go func(s *Syslog) {
defer s.conn.Close()
defer s.cfg.Wg.Done()
rcvBuff := make([]byte, 2048)
s.cfg.Log.Debug("Syslog buffer[2048] created %s")
for {
n, _, err := s.conn.ReadFromUDP(rcvBuff)
if err != nil {
s.cfg.Log.Error("Syslog read from %s failed with: %s", s.addr, err)
} else {
s.cfg.Log.Info("%d - %s ", n, rcvBuff[0:n])
s.status.NewEvent("syslog", EINCIN, nil)
}
}
}(s)
return nil
}
// NewLogReceiver used to create a new listen service that receives log messages(syslog)
func NewLogReceiver(cfg *config.Config, status *Status) (Services, error) {
if cfg.ListenAddr == "" {
return nil, fmt.Errorf("%s", "Listen address is empty")
}
addr, err := url.Parse(cfg.ListenAddr)
if err != nil {
return nil, err
}
if addr.Scheme != "udp" {
return nil, fmt.Errorf("Unsupported schema `%s`", addr.Scheme)
}
return &Syslog{
cfg: cfg,
net: addr.Scheme,
addr: addr.Host,
status: status,
}, nil
}<|fim▁end|>
| |
<|file_name|>point_to_point_communication.py<|end_file_name|><|fim▁begin|>import chainer
from chainer import cuda
import chainer.utils
class Send(chainer.Function):
"""Send elements to target process."""
def __init__(self, comm, peer_rank, peer_tag):
chainer.utils.experimental('chainermn.functions.Send')
self.comm = comm
self.peer_rank = peer_rank
self.peer_tag = peer_tag
@property
def label(self):
return "{} (peer_rank: {})".format(
self.__class__.__name__,
self.peer_rank)
def forward(self, inputs):
xp = cuda.get_array_module(*inputs)
# The last input is dummy variable, to retain gradient computation
# of this function.
xs = inputs[:-1]
if len(xs) == 1:
xs = xs[0]
self.comm.send(xs, self.peer_rank, self.peer_tag)
# Return an empty variable, which serves as "delegate_variable."
return xp.array([], dtype=xp.float32),
def backward(self, inputs, grad_outputs):
xp = cuda.get_array_module(*inputs)
dummy_grad = xp.array([], dtype=xp.float32)
grad = self.comm.recv(self.peer_rank, self.peer_tag)
if isinstance(grad, tuple):
return tuple([xp.array(gy) for gy in grad] + [dummy_grad])
else:
return xp.array(grad), dummy_grad
class Recv(chainer.Function):
"""Receive elements from target process."""
def __init__(self, comm, peer_rank, peer_tag):
chainer.utils.experimental('chainermn.functions.Recv')
self.comm = comm
self.peer_rank = peer_rank
self.peer_tag = peer_tag
def __call__(self, *inputs):
xp = cuda.get_array_module(*inputs)
if inputs == ():
# Expected to be invoked without any args in usual case.
if chainer.__version__.startswith('1.'):
# For backward compatibility.
dummy_var = chainer.Variable(
xp.array([], dtype=xp.float32),
volatile='auto')
else:
# This variable is necessary to backprop correctly
# in Chainer v2. This trick relies on the fact
# chainer.Variable.requires_grad is True by default
# in Chainer v2.0.0.
dummy_var = chainer.Variable(xp.array([], dtype=xp.float32))
dummy_var.name = 'dummy_var'
return super(Recv, self).__call__(dummy_var)
else:
# Used for retaining computational graph.
return super(Recv, self).__call__(*inputs)
@property
def label(self):
return "{} (peer_rank: {})".format(
self.__class__.__name__,
self.peer_rank)
def forward(self, inputs):
data = self.comm.recv(self.peer_rank, self.peer_tag)
if not isinstance(data, tuple):
data = tuple([data])
return data
def backward(self, inputs, grad_outputs):
xp = cuda.get_array_module(*inputs)
self.comm.send(grad_outputs, self.peer_rank, self.peer_tag)
# dummy_var is needed to maintain Chainer's constraint.
if inputs == ():
dummy_var = tuple([xp.array([], dtype=xp.float32)])
else:
dummy_var = tuple([xp.zeros(x.shape, dtype=xp.float32)
for x in inputs])
return dummy_var
def send(x, communicator, rank, tag=0):
"""Send elements to target process.
This function returns a dummy variable only holding the computational
graph. If ``backward()`` is invoked by this dummy variable, it will
try to receive gradients from the target process and send them back
to the parent nodes.
Args:
x (Variable): Variable holding a matrix which you would like to send.
communicator (chainer.communicators.CommunicatorBase):
ChainerMN communicator.
rank (int): Target process specifier.
tag (int): Optional message ID (MPI feature).
Returns:
~chainer.Variable:
A dummy variable with no actual data, only holding the
computational graph. Please refer
``chainermn.functions.pseudo_connect`` for detail.
<|fim▁hole|> raise ValueError(
'rank must be different from communicator rank, '
'otherwise deadlock occurs')
xp = cuda.get_array_module(*x)
# Dummy variable to retain gradient computation of send,
# otherwise the corresponding recv will cause deadlock in backward
# in the case where all inputs for this function does not require_grad.
dummy_var = chainer.Variable(xp.array([], dtype=xp.float32))
if isinstance(x, list) or isinstance(x, tuple):
inputs = x + type(x)([dummy_var])
delegate_variable = Send(
communicator, peer_rank=rank, peer_tag=tag)(*inputs)
else:
delegate_variable = Send(
communicator, peer_rank=rank, peer_tag=tag)(x, dummy_var)
delegate_variable.name = 'delegate_variable'
return delegate_variable
def recv(communicator, rank, delegate_variable=None, tag=0, force_tuple=False):
"""Receive elements from target process.
This function returns data received from target process. If ``backward()``
is invoked, it will try to send gradients to the target process.
The received array will be on the current CUDA device if the corresponding
``send()`` is invoked with arrays on GPU.
Please be aware that the current CUDA device is intended one.
(``https://docs-cupy.chainer.org/en/stable/tutorial/basic.html#current-device``)
.. note::
If you define non-connected computational graph on one process,
you have to use ``delegate_variable`` to specify the output of
previous computational graph component.
Otherwise ``backward()`` does not work well.
Please refer ``chainermn.functions.pseudo_connect`` for detail.
Args:
communicator (chainer.communicators.CommunicatorBase):
ChainerMN communicator.
rank (int): Target process specifier.
delegate_variable (chainer.Variable):
Pointer to the other non-connected component.
tag (int): Optional message ID (MPI feature).
force_tuple (bool): If ``False`` (the default) a Variable will be
returned when the number of outputs is one. Otherwise, this
method returns a tuple even when the number of outputs is one.
Returns:
~chainer.Variable:
Data received from target process. If ``backward()`` is invoked
by this variable, it will send gradients to the target process.
"""
chainer.utils.experimental('chainermn.functions.recv')
if rank == communicator.rank:
raise ValueError(
'rank must be different from communicator rank, '
'otherwise deadlock occurs')
if delegate_variable is None:
res = Recv(
communicator,
peer_rank=rank,
peer_tag=tag)()
else:
delegate_variable.name = 'delegate_variable'
res = Recv(
communicator,
peer_rank=rank,
peer_tag=tag)(delegate_variable)
if force_tuple and not isinstance(res, tuple):
return tuple([res])
else:
return res<|fim▁end|>
|
"""
chainer.utils.experimental('chainermn.functions.send')
if rank == communicator.rank:
|
<|file_name|>Stump.java<|end_file_name|><|fim▁begin|>package uk.co.edgeorgedev.lumber;
/**
* Root of Logging interface
* @author edgeorge<|fim▁hole|> */
public interface Stump {
/** Log a verbose message */
void v(Class<?> clazz, String message);
void v(Class<?> clazz, Throwable th);
//v,d,i,w,e,wtf
}<|fim▁end|>
|
* @version 1.0
* @since 2014-06-23
|
<|file_name|>Util.js<|end_file_name|><|fim▁begin|>'use strict';
define([],<|fim▁hole|>
var Util = class {
static charToLineCh(string, char) {
var stringUpToChar = string.substr(0, char);
var lines = stringUpToChar.split("\n");
return {
line: lines.length - 1,
ch: lines[lines.length - 1].length
};
}
};
return Util;
});<|fim▁end|>
|
function($) {
|
<|file_name|>show_posts.rs<|end_file_name|><|fim▁begin|>extern crate diesel_demo;
extern crate diesel;
use self::diesel_demo::*;
use self::diesel_demo::models::*;
use self::diesel::prelude::*;
fn main()
{<|fim▁hole|> .limit(5)
.load::<Post>(&connection)
.expect("Error loading posts");
println!("Displaying {} posts", results.len());
for post in results
{
println!("{}", post.title);
println!("--------\n");
println!("{}", post.body);
}
}<|fim▁end|>
|
use diesel_demo::schema::posts::dsl::*;
let connection = establish_connection();
let results = posts.filter(published.eq(true))
|
<|file_name|>_uirevision.py<|end_file_name|><|fim▁begin|>import _plotly_utils.basevalidators
class UirevisionValidator(_plotly_utils.basevalidators.AnyValidator):
def __init__(self, plotly_name="uirevision", parent_name="bar", **kwargs):
super(UirevisionValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,<|fim▁hole|> **kwargs
)<|fim▁end|>
|
edit_type=kwargs.pop("edit_type", "none"),
|
<|file_name|>notificator.js<|end_file_name|><|fim▁begin|>$(function () {
'use strict';
const notificationType = {
success: 'Success',
error: 'Error',
info: 'Info'
},
notificationTypeClass = {
success: 'toast-success',
info: 'toast-info',
error: 'toast-error'
};
function initSignalR() {
let connection = $.connection,
hub = connection.notificationHub;
hub.client.toast = (message, dellay, type) => {
console.log('CALLEEEEEEEEEEEED')
<|fim▁hole|> } else if (type === notificationType.info) {
Materialize.toast(message, dellay, notificationTypeClass.info)
} else {
Materialize.toast(message, dellay, notificationTypeClass.error)
}
};
connection.hub.start().done(() => hub.server.init());
}
initSignalR();
}());<|fim▁end|>
|
if (type === notificationType.success) {
Materialize.toast(message, dellay, notificationTypeClass.success)
|
<|file_name|>pubsub.py<|end_file_name|><|fim▁begin|># Copyright 2015 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.
import time
import unittest2
from gcloud import _helpers
from gcloud import pubsub
from gcloud.pubsub.subscription import Subscription
from gcloud.pubsub.topic import Topic
_helpers._PROJECT_ENV_VAR_NAME = 'GCLOUD_TESTS_PROJECT_ID'
pubsub.set_defaults()
class TestPubsub(unittest2.TestCase):
def setUp(self):
self.to_delete = []
def tearDown(self):
for doomed in self.to_delete:
doomed.delete()
def test_create_topic(self):
TOPIC_NAME = 'a-new-topic'
topic = Topic(TOPIC_NAME)
self.assertFalse(topic.exists())
topic.create()
self.to_delete.append(topic)
self.assertTrue(topic.exists())
self.assertEqual(topic.name, TOPIC_NAME)
def test_list_topics(self):
topics_to_create = [
'new%d' % (1000 * time.time(),),
'newer%d' % (1000 * time.time(),),
'newest%d' % (1000 * time.time(),),
]<|fim▁hole|> self.to_delete.append(topic)
# Retrieve the topics.
all_topics, _ = pubsub.list_topics()
project = pubsub.get_default_project()
created = [topic for topic in all_topics
if topic.name in topics_to_create and
topic.project == project]
self.assertEqual(len(created), len(topics_to_create))
def test_create_subscription(self):
TOPIC_NAME = 'subscribe-me'
topic = Topic(TOPIC_NAME)
self.assertFalse(topic.exists())
topic.create()
self.to_delete.append(topic)
SUBSCRIPTION_NAME = 'subscribing-now'
subscription = Subscription(SUBSCRIPTION_NAME, topic)
self.assertFalse(subscription.exists())
subscription.create()
self.to_delete.append(subscription)
self.assertTrue(subscription.exists())
self.assertEqual(subscription.name, SUBSCRIPTION_NAME)
self.assertTrue(subscription.topic is topic)
def test_list_subscriptions(self):
TOPIC_NAME = 'subscribe-me'
topic = Topic(TOPIC_NAME)
self.assertFalse(topic.exists())
topic.create()
self.to_delete.append(topic)
subscriptions_to_create = [
'new%d' % (1000 * time.time(),),
'newer%d' % (1000 * time.time(),),
'newest%d' % (1000 * time.time(),),
]
for subscription_name in subscriptions_to_create:
subscription = Subscription(subscription_name, topic)
subscription.create()
self.to_delete.append(subscription)
# Retrieve the subscriptions.
all_subscriptions, _ = pubsub.list_subscriptions()
created = [subscription for subscription in all_subscriptions
if subscription.name in subscriptions_to_create and
subscription.topic.name == TOPIC_NAME]
self.assertEqual(len(created), len(subscriptions_to_create))
def test_message_pull_mode_e2e(self):
TOPIC_NAME = 'subscribe-me'
topic = Topic(TOPIC_NAME, timestamp_messages=True)
self.assertFalse(topic.exists())
topic.create()
self.to_delete.append(topic)
SUBSCRIPTION_NAME = 'subscribing-now'
subscription = Subscription(SUBSCRIPTION_NAME, topic)
self.assertFalse(subscription.exists())
subscription.create()
self.to_delete.append(subscription)
MESSAGE_1 = b'MESSAGE ONE'
MESSAGE_2 = b'MESSAGE ONE'
EXTRA_1 = 'EXTRA 1'
EXTRA_2 = 'EXTRA 2'
topic.publish(MESSAGE_1, extra=EXTRA_1)
topic.publish(MESSAGE_2, extra=EXTRA_2)
received = subscription.pull(max_messages=2)
ack_ids = [recv[0] for recv in received]
subscription.acknowledge(ack_ids)
messages = [recv[1] for recv in received]
def _by_timestamp(message):
return message.timestamp
message1, message2 = sorted(messages, key=_by_timestamp)
self.assertEqual(message1.data, MESSAGE_1)
self.assertEqual(message1.attributes['extra'], EXTRA_1)
self.assertEqual(message2.data, MESSAGE_2)
self.assertEqual(message2.attributes['extra'], EXTRA_2)<|fim▁end|>
|
for topic_name in topics_to_create:
topic = Topic(topic_name)
topic.create()
|
<|file_name|>skipUntil.ts<|end_file_name|><|fim▁begin|><|fim▁hole|>Observable.prototype.skipUntil = skipUntil;
declare module '../../Observable' {
interface Observable<T> {
skipUntil: SkipUntilSignature<T>;
}
}<|fim▁end|>
|
import {Observable} from '../../Observable';
import {skipUntil, SkipUntilSignature} from '../../operator/skipUntil';
|
<|file_name|>_ticklen.py<|end_file_name|><|fim▁begin|>import _plotly_utils.basevalidators
class TicklenValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(
self, plotly_name="ticklen", parent_name="treemap.marker.colorbar", **kwargs
):
super(TicklenValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,<|fim▁hole|> edit_type=kwargs.pop("edit_type", "colorbars"),
min=kwargs.pop("min", 0),
role=kwargs.pop("role", "style"),
**kwargs
)<|fim▁end|>
| |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# Copyright Kitware 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
#<|fim▁hole|># 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.
###############################################################################
import collections
from .google import Google
from .github import GitHub
from .linkedin import LinkedIn
def addProvider(provider):
idMap[provider.getProviderName()] = provider
idMap = collections.OrderedDict()
addProvider(Google)
addProvider(GitHub)
addProvider(LinkedIn)<|fim▁end|>
|
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
|
<|file_name|>border-left-radius.js<|end_file_name|><|fim▁begin|>/**
* Border Left Radius
*/
module.exports = function (decl, args) {
var radius = args[1] || '3px';
decl.replaceWith({
prop: 'border-bottom-left-radius',
value: radius,
source: decl.source
}, {
prop: 'border-top-left-radius',
value: radius,<|fim▁hole|>};<|fim▁end|>
|
source: decl.source
});
|
<|file_name|>worker.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */<|fim▁hole|>use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull;
use dom::bindings::codegen::InheritTypes::{EventCast, EventTargetCast};
use dom::bindings::error::{Fallible, ErrorResult};
use dom::bindings::error::Error::Syntax;
use dom::bindings::global::{GlobalRef, GlobalField};
use dom::bindings::refcounted::Trusted;
use dom::bindings::structuredclone::StructuredCloneData;
use dom::bindings::trace::JSTraceable;
use dom::bindings::utils::{Reflectable, reflect_dom_object};
use dom::bindings::js::Root;
use dom::window::WindowHelpers;
use dom::dedicatedworkerglobalscope::DedicatedWorkerGlobalScope;
use dom::errorevent::ErrorEvent;
use dom::event::{Event, EventBubbles, EventCancelable, EventHelpers};
use dom::eventtarget::{EventTarget, EventTargetHelpers, EventTargetTypeId};
use dom::messageevent::MessageEvent;
use dom::workerglobalscope::WorkerGlobalScopeInit;
use script_task::{ScriptChan, ScriptMsg, Runnable};
use devtools_traits::{DevtoolsPageInfo, ScriptToDevtoolsControlMsg};
use util::str::DOMString;
use ipc_channel::ipc;
use js::jsapi::{JSContext, HandleValue, RootedValue};
use js::jsapi::{JSAutoRequest, JSAutoCompartment};
use js::jsval::UndefinedValue;
use url::UrlParser;
use std::borrow::ToOwned;
use std::sync::mpsc::{channel, Sender};
pub type TrustedWorkerAddress = Trusted<Worker>;
// https://html.spec.whatwg.org/multipage/#worker
#[dom_struct]
pub struct Worker {
eventtarget: EventTarget,
global: GlobalField,
/// Sender to the Receiver associated with the DedicatedWorkerGlobalScope
/// this Worker created.
sender: Sender<(TrustedWorkerAddress, ScriptMsg)>,
}
impl Worker {
fn new_inherited(global: GlobalRef, sender: Sender<(TrustedWorkerAddress, ScriptMsg)>) -> Worker {
Worker {
eventtarget: EventTarget::new_inherited(EventTargetTypeId::Worker),
global: GlobalField::from_rooted(&global),
sender: sender,
}
}
pub fn new(global: GlobalRef, sender: Sender<(TrustedWorkerAddress, ScriptMsg)>) -> Root<Worker> {
reflect_dom_object(box Worker::new_inherited(global, sender),
global,
WorkerBinding::Wrap)
}
// https://www.whatwg.org/html/#dom-worker
pub fn Constructor(global: GlobalRef, script_url: DOMString) -> Fallible<Root<Worker>> {
// Step 2-4.
let worker_url = match UrlParser::new().base_url(&global.get_url()).parse(&script_url) {
Ok(url) => url,
Err(_) => return Err(Syntax),
};
let resource_task = global.resource_task();
let constellation_chan = global.constellation_chan();
let (sender, receiver) = channel();
let worker = Worker::new(global, sender.clone());
let worker_ref = Trusted::new(global.get_cx(), worker.r(), global.script_chan());
let worker_id = global.get_next_worker_id();
let (devtools_sender, devtools_receiver) = ipc::channel().unwrap();
let optional_sender = match global.devtools_chan() {
Some(ref chan) => {
let pipeline_id = global.pipeline();
let title = format!("Worker for {}", worker_url);
let page_info = DevtoolsPageInfo {
title: title,
url: worker_url.clone(),
};
chan.send(ScriptToDevtoolsControlMsg::NewGlobal((pipeline_id, Some(worker_id)),
devtools_sender.clone(),
page_info)).unwrap();
Some(devtools_sender)
},
None => None,
};
let init = WorkerGlobalScopeInit {
resource_task: resource_task,
mem_profiler_chan: global.mem_profiler_chan(),
devtools_chan: global.devtools_chan(),
devtools_sender: optional_sender,
constellation_chan: constellation_chan,
worker_id: worker_id,
};
DedicatedWorkerGlobalScope::run_worker_scope(
init, worker_url, global.pipeline(), devtools_receiver, worker_ref,
global.script_chan(), sender, receiver);
Ok(worker)
}
pub fn handle_message(address: TrustedWorkerAddress,
data: StructuredCloneData) {
let worker = address.root();
let global = worker.r().global.root();
let target = EventTargetCast::from_ref(worker.r());
let _ar = JSAutoRequest::new(global.r().get_cx());
let _ac = JSAutoCompartment::new(global.r().get_cx(), target.reflector().get_jsobject().get());
let mut message = RootedValue::new(global.r().get_cx(), UndefinedValue());
data.read(global.r(), message.handle_mut());
MessageEvent::dispatch_jsval(target, global.r(), message.handle());
}
pub fn dispatch_simple_error(address: TrustedWorkerAddress) {
let worker = address.root();
let global = worker.r().global.root();
let target = EventTargetCast::from_ref(worker.r());
let event = Event::new(global.r(),
"error".to_owned(),
EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable);
event.r().fire(target);
}
pub fn handle_error_message(address: TrustedWorkerAddress, message: DOMString,
filename: DOMString, lineno: u32, colno: u32) {
let worker = address.root();
let global = worker.r().global.root();
let error = RootedValue::new(global.r().get_cx(), UndefinedValue());
let target = EventTargetCast::from_ref(worker.r());
let errorevent = ErrorEvent::new(global.r(), "error".to_owned(),
EventBubbles::Bubbles, EventCancelable::Cancelable,
message, filename, lineno, colno, error.handle());
let event = EventCast::from_ref(errorevent.r());
event.fire(target);
}
}
impl<'a> WorkerMethods for &'a Worker {
// https://html.spec.whatwg.org/multipage/#dom-dedicatedworkerglobalscope-postmessage
fn PostMessage(self, cx: *mut JSContext, message: HandleValue) -> ErrorResult {
let data = try!(StructuredCloneData::write(cx, message));
let address = Trusted::new(cx, self, self.global.root().r().script_chan().clone());
self.sender.send((address, ScriptMsg::DOMMessage(data))).unwrap();
Ok(())
}
event_handler!(message, GetOnmessage, SetOnmessage);
}
pub struct WorkerMessageHandler {
addr: TrustedWorkerAddress,
data: StructuredCloneData,
}
impl WorkerMessageHandler {
pub fn new(addr: TrustedWorkerAddress, data: StructuredCloneData) -> WorkerMessageHandler {
WorkerMessageHandler {
addr: addr,
data: data,
}
}
}
impl Runnable for WorkerMessageHandler {
fn handler(self: Box<WorkerMessageHandler>) {
let this = *self;
Worker::handle_message(this.addr, this.data);
}
}
pub struct WorkerEventHandler {
addr: TrustedWorkerAddress,
}
impl WorkerEventHandler {
pub fn new(addr: TrustedWorkerAddress) -> WorkerEventHandler {
WorkerEventHandler {
addr: addr
}
}
}
impl Runnable for WorkerEventHandler {
fn handler(self: Box<WorkerEventHandler>) {
let this = *self;
Worker::dispatch_simple_error(this.addr);
}
}
pub struct WorkerErrorHandler {
addr: TrustedWorkerAddress,
msg: DOMString,
file_name: DOMString,
line_num: u32,
col_num: u32,
}
impl WorkerErrorHandler {
pub fn new(addr: TrustedWorkerAddress, msg: DOMString, file_name: DOMString, line_num: u32, col_num: u32)
-> WorkerErrorHandler {
WorkerErrorHandler {
addr: addr,
msg: msg,
file_name: file_name,
line_num: line_num,
col_num: col_num,
}
}
}
impl Runnable for WorkerErrorHandler {
fn handler(self: Box<WorkerErrorHandler>) {
let this = *self;
Worker::handle_error_message(this.addr, this.msg, this.file_name, this.line_num, this.col_num);
}
}<|fim▁end|>
|
use dom::bindings::codegen::Bindings::WorkerBinding;
use dom::bindings::codegen::Bindings::WorkerBinding::WorkerMethods;
|
<|file_name|>factory.py<|end_file_name|><|fim▁begin|>value_None = object()
class FactoryException(Exception):
pass
class Factory:
class Item:
def __init__(self, factory, i):
self.factory = factory
self.i = i
@property
def value(self):
return self.factory.value(self.i)
@value.setter
def value(self, value):
self.i = self.factory.i(value)
def copy(self):
return self.factory.item(self.i)
def __eq__(self, other):
try:<|fim▁hole|> return self.factory is other.factory and self.i == other.i
except AttributeError:
return self.value == other
def __ne__(self, other):
return not self == other
def __hash__(self):
return hash(self.factory) ^ hash(self.i)
def __int__(self):
return self.i
def __str__(self):
return self.factory.istr(self)
def __repr__(self):
return f'Item({self.factory.istr(self)})'
@staticmethod
def istr(item):
return str(item.value)
def i(self, value):
raise NotImplementedError
def item(self, i=None, value=value_None):
if not self.check_ivalue(i, value):
raise FactoryException('factory.item(): index and values do not match')
if i is None:
i = 0 if value is value_None else self.i(value)
return self.Item(self, i) # this might be annoying for union...
def check_ivalue(self, i, value):
return i is None or value is value_None or self.value(i) == value
def isitem(self, item):
try:
return item.factory is self and 0 <= item.i < self.nitems
except AttributeError:
return False
@property
def items(self):
return map(self.item, range(self.nitems))
def __iter__(self):
return self.items
def __len__(self):
return self.nitems<|fim▁end|>
| |
<|file_name|>confirm-dialog.component.spec.ts<|end_file_name|><|fim▁begin|>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { AppModule } from '../../../../app.module';
import { MAT_DIALOG_DATA, MatDialog, MatDialogRef } from '@angular/material';
import { ConfirmDialogComponent } from './confirm-dialog.component';
describe('ConfirmDialogComponent', () => {<|fim▁hole|>
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
AppModule,
],
providers: [
{ provide: MAT_DIALOG_DATA, useValue: {} },
{ provide: MatDialogRef }
]
})
.compileComponents();
}));
beforeEach(() => {
dialog = TestBed.get(MatDialog);
fixture = TestBed.createComponent(ConfirmDialogComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});<|fim▁end|>
|
let component: ConfirmDialogComponent;
let dialog: MatDialog;
let fixture: ComponentFixture<ConfirmDialogComponent>;
|
<|file_name|>Path.cpp<|end_file_name|><|fim▁begin|>/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "2D.h"
#include "PathAnalysis.h"
#include "PathHelpers.h"
namespace mozilla {
namespace gfx {
static float CubicRoot(float aValue) {
if (aValue < 0.0) {
return -CubicRoot(-aValue);
}
else {
return powf(aValue, 1.0f / 3.0f);
}
}
struct BezierControlPoints
{
BezierControlPoints() {}
BezierControlPoints(const Point &aCP1, const Point &aCP2,
const Point &aCP3, const Point &aCP4)
: mCP1(aCP1), mCP2(aCP2), mCP3(aCP3), mCP4(aCP4)
{
}
Point mCP1, mCP2, mCP3, mCP4;
};
void
FlattenBezier(const BezierControlPoints &aPoints,
PathSink *aSink, Float aTolerance);
Path::Path()
{
}
Path::~Path()
{
}
Float
Path::ComputeLength()
{
EnsureFlattenedPath();
return mFlattenedPath->ComputeLength();
}
Point
Path::ComputePointAtLength(Float aLength, Point* aTangent)
{
EnsureFlattenedPath();
return mFlattenedPath->ComputePointAtLength(aLength, aTangent);
}
void
Path::EnsureFlattenedPath()
{
if (!mFlattenedPath) {
mFlattenedPath = new FlattenedPath();
StreamToSink(mFlattenedPath);
}
}
// This is the maximum deviation we allow (with an additional ~20% margin of
// error) of the approximation from the actual Bezier curve.
const Float kFlatteningTolerance = 0.0001f;
void
FlattenedPath::MoveTo(const Point &aPoint)
{
MOZ_ASSERT(!mCalculatedLength);
FlatPathOp op;
op.mType = FlatPathOp::OP_MOVETO;
op.mPoint = aPoint;
mPathOps.push_back(op);
mLastMove = aPoint;
}
void
FlattenedPath::LineTo(const Point &aPoint)
{
MOZ_ASSERT(!mCalculatedLength);
FlatPathOp op;
op.mType = FlatPathOp::OP_LINETO;
op.mPoint = aPoint;
mPathOps.push_back(op);
}
void
FlattenedPath::BezierTo(const Point &aCP1,
const Point &aCP2,
const Point &aCP3)
{
MOZ_ASSERT(!mCalculatedLength);
FlattenBezier(BezierControlPoints(CurrentPoint(), aCP1, aCP2, aCP3), this, kFlatteningTolerance);
}
void
FlattenedPath::QuadraticBezierTo(const Point &aCP1,
const Point &aCP2)
{
MOZ_ASSERT(!mCalculatedLength);
// We need to elevate the degree of this quadratic B�zier to cubic, so we're
// going to add an intermediate control point, and recompute control point 1.
// The first and last control points remain the same.
// This formula can be found on http://fontforge.sourceforge.net/bezier.html
Point CP0 = CurrentPoint();
Point CP1 = (CP0 + aCP1 * 2.0) / 3.0;
Point CP2 = (aCP2 + aCP1 * 2.0) / 3.0;
Point CP3 = aCP2;
BezierTo(CP1, CP2, CP3);
}
void
FlattenedPath::Close()
{
MOZ_ASSERT(!mCalculatedLength);
LineTo(mLastMove);
}
void
FlattenedPath::Arc(const Point &aOrigin, float aRadiusX, float aRadiusY,
float aRotationAngle, float aStartAngle,
float aEndAngle, bool aAntiClockwise)
{
ArcToBezier(this, aOrigin, Size(aRadiusX, aRadiusY), aStartAngle, aEndAngle, aAntiClockwise);
}
Float
FlattenedPath::ComputeLength()
{
if (!mCalculatedLength) {
Point currentPoint;
for (uint32_t i = 0; i < mPathOps.size(); i++) {
if (mPathOps[i].mType == FlatPathOp::OP_MOVETO) {
currentPoint = mPathOps[i].mPoint;
} else {
mCachedLength += Distance(currentPoint, mPathOps[i].mPoint);
currentPoint = mPathOps[i].mPoint;
}
}
mCalculatedLength = true;
}
return mCachedLength;
}
Point
FlattenedPath::ComputePointAtLength(Float aLength, Point *aTangent)
{
// We track the last point that -wasn't- in the same place as the current
// point so if we pass the edge of the path with a bunch of zero length
// paths we still get the correct tangent vector.
Point lastPointSinceMove;
Point currentPoint;
for (uint32_t i = 0; i < mPathOps.size(); i++) {
if (mPathOps[i].mType == FlatPathOp::OP_MOVETO) {
if (Distance(currentPoint, mPathOps[i].mPoint)) {
lastPointSinceMove = currentPoint;
}
currentPoint = mPathOps[i].mPoint;
} else {
Float segmentLength = Distance(currentPoint, mPathOps[i].mPoint);
if (segmentLength) {
lastPointSinceMove = currentPoint;
if (segmentLength > aLength) {
Point currentVector = mPathOps[i].mPoint - currentPoint;
Point tangent = currentVector / segmentLength;
if (aTangent) {
*aTangent = tangent;
}
return currentPoint + tangent * aLength;
}
}
aLength -= segmentLength;
currentPoint = mPathOps[i].mPoint;
}
}
Point currentVector = currentPoint - lastPointSinceMove;
if (aTangent) {
if (hypotf(currentVector.x, currentVector.y)) {
*aTangent = currentVector / hypotf(currentVector.x, currentVector.y);
} else {
*aTangent = Point();
}
}
return currentPoint;
}
// This function explicitly permits aControlPoints to refer to the same object
// as either of the other arguments.
static void
SplitBezier(const BezierControlPoints &aControlPoints,
BezierControlPoints *aFirstSegmentControlPoints,
BezierControlPoints *aSecondSegmentControlPoints,
Float t)
{
MOZ_ASSERT(aSecondSegmentControlPoints);
*aSecondSegmentControlPoints = aControlPoints;
Point cp1a = aControlPoints.mCP1 + (aControlPoints.mCP2 - aControlPoints.mCP1) * t;
Point cp2a = aControlPoints.mCP2 + (aControlPoints.mCP3 - aControlPoints.mCP2) * t;
Point cp1aa = cp1a + (cp2a - cp1a) * t;
Point cp3a = aControlPoints.mCP3 + (aControlPoints.mCP4 - aControlPoints.mCP3) * t;
Point cp2aa = cp2a + (cp3a - cp2a) * t;
Point cp1aaa = cp1aa + (cp2aa - cp1aa) * t;
aSecondSegmentControlPoints->mCP4 = aControlPoints.mCP4;
if(aFirstSegmentControlPoints) {
aFirstSegmentControlPoints->mCP1 = aControlPoints.mCP1;
aFirstSegmentControlPoints->mCP2 = cp1a;
aFirstSegmentControlPoints->mCP3 = cp1aa;
aFirstSegmentControlPoints->mCP4 = cp1aaa;
}
aSecondSegmentControlPoints->mCP1 = cp1aaa;
aSecondSegmentControlPoints->mCP2 = cp2aa;
aSecondSegmentControlPoints->mCP3 = cp3a;
}
static void
FlattenBezierCurveSegment(const BezierControlPoints &aControlPoints,
PathSink *aSink,
Float aTolerance)
{
/* The algorithm implemented here is based on:
* http://cis.usouthal.edu/~hain/general/Publications/Bezier/Bezier%20Offset%20Curves.pdf
*
* The basic premise is that for a small t the third order term in the
* equation of a cubic bezier curve is insignificantly small. This can
* then be approximated by a quadratic equation for which the maximum
* difference from a linear approximation can be much more easily determined.
*/
BezierControlPoints currentCP = aControlPoints;
Float t = 0;
while (t < 1.0f) {
Point cp21 = currentCP.mCP2 - currentCP.mCP3;
Point cp31 = currentCP.mCP3 - currentCP.mCP1;
Float s3 = (cp31.x * cp21.y - cp31.y * cp21.x) / hypotf(cp21.x, cp21.y);
t = 2 * Float(sqrt(aTolerance / (3. * abs(s3))));
if (t >= 1.0f) {
aSink->LineTo(aControlPoints.mCP4);
break;
}
Point prevCP2, prevCP3, nextCP1, nextCP2, nextCP3;
SplitBezier(currentCP, nullptr, ¤tCP, t);
aSink->LineTo(currentCP.mCP1);
}
}
static inline void
FindInflectionApproximationRange(BezierControlPoints aControlPoints,
Float *aMin, Float *aMax, Float aT,
Float aTolerance)
{
SplitBezier(aControlPoints, nullptr, &aControlPoints, aT);
Point cp21 = aControlPoints.mCP2 - aControlPoints.mCP1;
Point cp41 = aControlPoints.mCP4 - aControlPoints.mCP1;
if (cp21.x == 0.f && cp21.y == 0.f) {
// In this case s3 becomes lim[n->0] (cp41.x * n) / n - (cp41.y * n) / n = cp41.x - cp41.y.
// Use the absolute value so that Min and Max will correspond with the
// minimum and maximum of the range.
*aMin = aT - CubicRoot(abs(aTolerance / (cp41.x - cp41.y)));
*aMax = aT + CubicRoot(abs(aTolerance / (cp41.x - cp41.y)));
return;
}
Float s3 = (cp41.x * cp21.y - cp41.y * cp21.x) / hypotf(cp21.x, cp21.y);
if (s3 == 0) {
// This means within the precision we have it can be approximated
// infinitely by a linear segment. Deal with this by specifying the
// approximation range as extending beyond the entire curve.
*aMin = -1.0f;
*aMax = 2.0f;
return;
}
Float tf = CubicRoot(abs(aTolerance / s3));
*aMin = aT - tf * (1 - aT);
*aMax = aT + tf * (1 - aT);
}
/* Find the inflection points of a bezier curve. Will return false if the
* curve is degenerate in such a way that it is best approximated by a straight
* line.
*
* The below algorithm was written by Jeff Muizelaar <[email protected]>, explanation follows:
*
* The lower inflection point is returned in aT1, the higher one in aT2. In the
* case of a single inflection point this will be in aT1.
*
* The method is inspired by the algorithm in "analysis of in?ection points for planar cubic bezier curve"
*
* Here are some differences between this algorithm and versions discussed elsewhere in the literature:
*
* zhang et. al compute a0, d0 and e0 incrementally using the follow formula:<|fim▁hole|> * Point a0 = CP2 - CP1
* Point a1 = CP3 - CP2
* Point a2 = CP4 - CP1
*
* Point d0 = a1 - a0
* Point d1 = a2 - a1
* Point e0 = d1 - d0
*
* this avoids any multiplications and may or may not be faster than the approach take below.
*
* "fast, precise flattening of cubic bezier path and ofset curves" by hain et. al
* Point a = CP1 + 3 * CP2 - 3 * CP3 + CP4
* Point b = 3 * CP1 - 6 * CP2 + 3 * CP3
* Point c = -3 * CP1 + 3 * CP2
* Point d = CP1
* the a, b, c, d can be expressed in terms of a0, d0 and e0 defined above as:
* c = 3 * a0
* b = 3 * d0
* a = e0
*
*
* a = 3a = a.y * b.x - a.x * b.y
* b = 3b = a.y * c.x - a.x * c.y
* c = 9c = b.y * c.x - b.x * c.y
*
* The additional multiples of 3 cancel each other out as show below:
*
* x = (-b + sqrt(b * b - 4 * a * c)) / (2 * a)
* x = (-3 * b + sqrt(3 * b * 3 * b - 4 * a * 3 * 9 * c / 3)) / (2 * 3 * a)
* x = 3 * (-b + sqrt(b * b - 4 * a * c)) / (2 * 3 * a)
* x = (-b + sqrt(b * b - 4 * a * c)) / (2 * a)
*
* I haven't looked into whether the formulation of the quadratic formula in
* hain has any numerical advantages over the one used below.
*/
static inline void
FindInflectionPoints(const BezierControlPoints &aControlPoints,
Float *aT1, Float *aT2, uint32_t *aCount)
{
// Find inflection points.
// See www.faculty.idc.ac.il/arik/quality/appendixa.html for an explanation
// of this approach.
Point A = aControlPoints.mCP2 - aControlPoints.mCP1;
Point B = aControlPoints.mCP3 - (aControlPoints.mCP2 * 2) + aControlPoints.mCP1;
Point C = aControlPoints.mCP4 - (aControlPoints.mCP3 * 3) + (aControlPoints.mCP2 * 3) - aControlPoints.mCP1;
Float a = Float(B.x) * C.y - Float(B.y) * C.x;
Float b = Float(A.x) * C.y - Float(A.y) * C.x;
Float c = Float(A.x) * B.y - Float(A.y) * B.x;
if (a == 0) {
// Not a quadratic equation.
if (b == 0) {
// Instead of a linear acceleration change we have a constant
// acceleration change. This means the equation has no solution
// and there are no inflection points, unless the constant is 0.
// In that case the curve is a straight line, essentially that means
// the easiest way to deal with is is by saying there's an inflection
// point at t == 0. The inflection point approximation range found will
// automatically extend into infinity.
if (c == 0) {
*aCount = 1;
*aT1 = 0;
return;
}
*aCount = 0;
return;
}
*aT1 = -c / b;
*aCount = 1;
return;
} else {
Float discriminant = b * b - 4 * a * c;
if (discriminant < 0) {
// No inflection points.
*aCount = 0;
} else if (discriminant == 0) {
*aCount = 1;
*aT1 = -b / (2 * a);
} else {
/* Use the following formula for computing the roots:
*
* q = -1/2 * (b + sign(b) * sqrt(b^2 - 4ac))
* t1 = q / a
* t2 = c / q
*/
Float q = sqrtf(discriminant);
if (b < 0) {
q = b - q;
} else {
q = b + q;
}
q *= Float(-1./2);
*aT1 = q / a;
*aT2 = c / q;
if (*aT1 > *aT2) {
std::swap(*aT1, *aT2);
}
*aCount = 2;
}
}
return;
}
void
FlattenBezier(const BezierControlPoints &aControlPoints,
PathSink *aSink, Float aTolerance)
{
Float t1;
Float t2;
uint32_t count;
FindInflectionPoints(aControlPoints, &t1, &t2, &count);
// Check that at least one of the inflection points is inside [0..1]
if (count == 0 || ((t1 < 0 || t1 > 1.0) && ((t2 < 0 || t2 > 1.0) || count == 1)) ) {
FlattenBezierCurveSegment(aControlPoints, aSink, aTolerance);
return;
}
Float t1min = t1, t1max = t1, t2min = t2, t2max = t2;
BezierControlPoints remainingCP = aControlPoints;
// For both inflection points, calulate the range where they can be linearly
// approximated if they are positioned within [0,1]
if (count > 0 && t1 >= 0 && t1 < 1.0) {
FindInflectionApproximationRange(aControlPoints, &t1min, &t1max, t1, aTolerance);
}
if (count > 1 && t2 >= 0 && t2 < 1.0) {
FindInflectionApproximationRange(aControlPoints, &t2min, &t2max, t2, aTolerance);
}
BezierControlPoints nextCPs = aControlPoints;
BezierControlPoints prevCPs;
// Process ranges. [t1min, t1max] and [t2min, t2max] are approximated by line
// segments.
if (t1min > 0) {
// Flatten the Bezier up until the first inflection point's approximation
// point.
SplitBezier(aControlPoints, &prevCPs,
&remainingCP, t1min);
FlattenBezierCurveSegment(prevCPs, aSink, aTolerance);
}
if (t1max >= 0 && t1max < 1.0 && (count == 1 || t2min > t1max)) {
// The second inflection point's approximation range begins after the end
// of the first, approximate the first inflection point by a line and
// subsequently flatten up until the end or the next inflection point.
SplitBezier(aControlPoints, nullptr, &nextCPs, t1max);
aSink->LineTo(nextCPs.mCP1);
if (count == 1 || (count > 1 && t2min >= 1.0)) {
// No more inflection points to deal with, flatten the rest of the curve.
FlattenBezierCurveSegment(nextCPs, aSink, aTolerance);
}
} else if (count > 1 && t2min > 1.0) {
// We've already concluded t2min <= t1max, so if this is true the
// approximation range for the first inflection point runs past the
// end of the curve, draw a line to the end and we're done.
aSink->LineTo(aControlPoints.mCP4);
return;
}
if (count > 1 && t2min < 1.0 && t2max > 0) {
if (t2min > 0 && t2min < t1max) {
// In this case the t2 approximation range starts inside the t1
// approximation range.
SplitBezier(aControlPoints, nullptr, &nextCPs, t1max);
aSink->LineTo(nextCPs.mCP1);
} else if (t2min > 0 && t1max > 0) {
SplitBezier(aControlPoints, nullptr, &nextCPs, t1max);
// Find a control points describing the portion of the curve between t1max and t2min.
Float t2mina = (t2min - t1max) / (1 - t1max);
SplitBezier(nextCPs, &prevCPs, &nextCPs, t2mina);
FlattenBezierCurveSegment(prevCPs, aSink, aTolerance);
} else if (t2min > 0) {
// We have nothing interesting before t2min, find that bit and flatten it.
SplitBezier(aControlPoints, &prevCPs, &nextCPs, t2min);
FlattenBezierCurveSegment(prevCPs, aSink, aTolerance);
}
if (t2max < 1.0) {
// Flatten the portion of the curve after t2max
SplitBezier(aControlPoints, nullptr, &nextCPs, t2max);
// Draw a line to the start, this is the approximation between t2min and
// t2max.
aSink->LineTo(nextCPs.mCP1);
FlattenBezierCurveSegment(nextCPs, aSink, aTolerance);
} else {
// Our approximation range extends beyond the end of the curve.
aSink->LineTo(aControlPoints.mCP4);
return;
}
}
}
}
}<|fim▁end|>
|
*
|
<|file_name|>bazel_windows_cpp_test.py<|end_file_name|><|fim▁begin|># Copyright 2017 The Bazel Authors. 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.
import glob
import os
import unittest
from src.test.py.bazel import test_base
class BazelWindowsCppTest(test_base.TestBase):
def createProjectFiles(self):
self.CreateWorkspaceWithDefaultRepos('WORKSPACE')
self.ScratchFile('BUILD', [
'package(',
' default_visibility = ["//visibility:public"],',
' features=["windows_export_all_symbols"]',
')',
'',
'cc_library(',
' name = "A",',
' srcs = ["a.cc"],',
' hdrs = ["a.h"],',
' copts = ["/DCOMPILING_A_DLL"],',
' features = ["no_windows_export_all_symbols"],',
')',
'',
'cc_library(',
' name = "B",',
' srcs = ["b.cc"],',
' hdrs = ["b.h"],',
' deps = [":A"],',
' copts = ["/DNO_DLLEXPORT"],',
')',
'',
'cc_binary(',
' name = "C",',
' srcs = ["c.cc"],',
' deps = [":A", ":B" ],',
' linkstatic = 0,',
')',
])
self.ScratchFile('a.cc', [
'#include <stdio.h>',
'#include "a.h"',
'int a = 0;',
'void hello_A() {',
' a++;',
' printf("Hello A, %d\\n", a);',
'}',
])
self.ScratchFile('b.cc', [
'#include <stdio.h>',
'#include "a.h"',
'#include "b.h"',
'void hello_B() {',
' hello_A();',
' printf("Hello B\\n");',
'}',
])
header_temp = [
'#ifndef %{name}_H',
'#define %{name}_H',
'',
'#if NO_DLLEXPORT',
' #define DLLEXPORT',
'#elif COMPILING_%{name}_DLL',
' #define DLLEXPORT __declspec(dllexport)',
'#else',
' #define DLLEXPORT __declspec(dllimport)',
'#endif',
'',
'DLLEXPORT void hello_%{name}();',
'',
'#endif',
]
self.ScratchFile('a.h',
[line.replace('%{name}', 'A') for line in header_temp])
self.ScratchFile('b.h',
[line.replace('%{name}', 'B') for line in header_temp])
c_cc_content = [
'#include <stdio.h>',
'#include "a.h"',
'#include "b.h"',
'',
'void hello_C() {',
' hello_A();',
' hello_B();',
' printf("Hello C\\n");',
'}',
'',
'int main() {',
' hello_C();',
' return 0;',
'}',
]
self.ScratchFile('c.cc', c_cc_content)
self.ScratchFile('lib/BUILD', [
'cc_library(',
' name = "A",',
' srcs = ["dummy.cc"],',
' features = ["windows_export_all_symbols"],',
' visibility = ["//visibility:public"],',
')',
])
self.ScratchFile('lib/dummy.cc', ['void dummy() {}'])
self.ScratchFile('main/main.cc', c_cc_content)
def getBazelInfo(self, info_key):
exit_code, stdout, stderr = self.RunBazel(['info', info_key])
self.AssertExitCode(exit_code, 0, stderr)
return stdout[0]
def testBuildDynamicLibraryWithUserExportedSymbol(self):
self.createProjectFiles()
bazel_bin = self.getBazelInfo('bazel-bin')
# //:A export symbols by itself using __declspec(dllexport), so it doesn't
# need Bazel to export symbols using DEF file.
exit_code, _, stderr = self.RunBazel(
['build', '//:A', '--output_groups=dynamic_library'])
self.AssertExitCode(exit_code, 0, stderr)
# TODO(pcloudy): change suffixes to .lib and .dll after making DLL
# extensions correct on Windows.
import_library = os.path.join(bazel_bin, 'A.if.lib')
shared_library = os.path.join(bazel_bin, 'A.dll')
empty_def_file = os.path.join(bazel_bin, 'A.gen.empty.def')
self.assertTrue(os.path.exists(import_library))
self.assertTrue(os.path.exists(shared_library))
# An empty DEF file should be generated for //:A
self.assertTrue(os.path.exists(empty_def_file))
def testBuildDynamicLibraryWithExportSymbolFeature(self):
self.createProjectFiles()
bazel_bin = self.getBazelInfo('bazel-bin')
# //:B doesn't export symbols by itself, so it need Bazel to export symbols
# using DEF file.
exit_code, _, stderr = self.RunBazel(
['build', '//:B', '--output_groups=dynamic_library'])
self.AssertExitCode(exit_code, 0, stderr)
# TODO(pcloudy): change suffixes to .lib and .dll after making DLL
# extensions correct on Windows.
import_library = os.path.join(bazel_bin, 'B.if.lib')
shared_library = os.path.join(bazel_bin, 'B.dll')
def_file = os.path.join(bazel_bin, 'B.gen.def')
self.assertTrue(os.path.exists(import_library))
self.assertTrue(os.path.exists(shared_library))
# DEF file should be generated for //:B
self.assertTrue(os.path.exists(def_file))
# Test build //:B if windows_export_all_symbols feature is disabled by
# no_windows_export_all_symbols.
exit_code, _, stderr = self.RunBazel([
'build', '//:B', '--output_groups=dynamic_library',
'--features=no_windows_export_all_symbols'
])
self.AssertExitCode(exit_code, 0, stderr)
import_library = os.path.join(bazel_bin, 'B.if.lib')
shared_library = os.path.join(bazel_bin, 'B.dll')
empty_def_file = os.path.join(bazel_bin, 'B.gen.empty.def')
self.assertTrue(os.path.exists(import_library))
self.assertTrue(os.path.exists(shared_library))
# An empty DEF file should be generated for //:B
self.assertTrue(os.path.exists(empty_def_file))
self.AssertFileContentNotContains(empty_def_file, 'hello_B')
def testBuildCcBinaryWithDependenciesDynamicallyLinked(self):
self.createProjectFiles()
bazel_bin = self.getBazelInfo('bazel-bin')
# Since linkstatic=0 is specified for //:C, it's dependencies should be
# dynamically linked.
exit_code, _, stderr = self.RunBazel(['build', '//:C'])
self.AssertExitCode(exit_code, 0, stderr)
# TODO(pcloudy): change suffixes to .lib and .dll after making DLL
# extensions correct on
# Windows.
# a_import_library
self.assertTrue(os.path.exists(os.path.join(bazel_bin, 'A.if.lib')))
# a_shared_library
self.assertTrue(os.path.exists(os.path.join(bazel_bin, 'A.dll')))
# a_def_file
self.assertTrue(os.path.exists(os.path.join(bazel_bin, 'A.gen.empty.def')))
# b_import_library
self.assertTrue(os.path.exists(os.path.join(bazel_bin, 'B.if.lib')))
# b_shared_library
self.assertTrue(os.path.exists(os.path.join(bazel_bin, 'B.dll')))
# b_def_file
self.assertTrue(os.path.exists(os.path.join(bazel_bin, 'B.gen.def')))
# c_exe
self.assertTrue(os.path.exists(os.path.join(bazel_bin, 'C.exe')))
def testBuildCcBinaryFromDifferentPackage(self):
self.createProjectFiles()
self.ScratchFile('main/BUILD', [
'cc_binary(',
' name = "main",',
' srcs = ["main.cc"],',
' deps = ["//:B"],',
' linkstatic = 0,'
')',
])
bazel_bin = self.getBazelInfo('bazel-bin')
exit_code, _, stderr = self.RunBazel(['build', '//main:main'])
self.AssertExitCode(exit_code, 0, stderr)
# Test if A.dll and B.dll are copied to the directory of main.exe
main_bin = os.path.join(bazel_bin, 'main/main.exe')
self.assertTrue(os.path.exists(main_bin))
self.assertTrue(os.path.exists(os.path.join(bazel_bin, 'main/A.dll')))
self.assertTrue(os.path.exists(os.path.join(bazel_bin, 'main/B.dll')))
# Run the binary to see if it runs successfully
exit_code, stdout, stderr = self.RunProgram([main_bin])
self.AssertExitCode(exit_code, 0, stderr)
self.assertEqual(['Hello A, 1', 'Hello A, 2', 'Hello B', 'Hello C'], stdout)
def testBuildCcBinaryDependsOnConflictDLLs(self):
self.createProjectFiles()
self.ScratchFile(
'main/BUILD',
[
'cc_binary(',
' name = "main",',
' srcs = ["main.cc"],',
' deps = ["//:B", "//lib:A"],', # Transitively depends on //:A
' linkstatic = 0,'
')',
])
bazel_bin = self.getBazelInfo('bazel-bin')
# //main:main depends on both //lib:A and //:A
exit_code, _, stderr = self.RunBazel(
['build', '//main:main', '--incompatible_avoid_conflict_dlls'])
self.AssertExitCode(exit_code, 0, stderr)
# Run the binary to see if it runs successfully
main_bin = os.path.join(bazel_bin, 'main/main.exe')
exit_code, stdout, stderr = self.RunProgram([main_bin])
self.AssertExitCode(exit_code, 0, stderr)
self.assertEqual(['Hello A, 1', 'Hello A, 2', 'Hello B', 'Hello C'], stdout)
# There are 2 A_{hash}.dll since //main:main depends on both //lib:A and
# //:A
self.assertEqual(
len(glob.glob(os.path.join(bazel_bin, 'main', 'A_*.dll'))), 2)
# There is only 1 B_{hash}.dll
self.assertEqual(
len(glob.glob(os.path.join(bazel_bin, 'main', 'B_*.dll'))), 1)
def testBuildDifferentCcBinariesDependOnConflictDLLs(self):
self.createProjectFiles()
self.ScratchFile(
'main/BUILD',
[
'cc_binary(',
' name = "main",',
' srcs = ["main.cc"],',
' deps = ["//:B"],', # Transitively depends on //:A
' linkstatic = 0,'
')',
'',
'cc_binary(',
' name = "other_main",',
' srcs = ["other_main.cc"],',
' deps = ["//lib:A"],',
' linkstatic = 0,'
')',
])
bazel_bin = self.getBazelInfo('bazel-bin')
self.ScratchFile('main/other_main.cc', ['int main() {return 0;}'])
# Building //main:main should succeed
exit_code, _, stderr = self.RunBazel(
['build', '//main:main', '--incompatible_avoid_conflict_dlls'])
self.AssertExitCode(exit_code, 0, stderr)
main_bin = os.path.join(bazel_bin, 'main/main.exe')
# Run the main_bin binary to see if it runs successfully
exit_code, stdout, stderr = self.RunProgram([main_bin])
self.AssertExitCode(exit_code, 0, stderr)
self.assertEqual(['Hello A, 1', 'Hello A, 2', 'Hello B', 'Hello C'], stdout)
# There is only 1 A_{hash}.dll since //main:main depends transitively on
# //:A
self.assertEqual(
len(glob.glob(os.path.join(bazel_bin, 'main', 'A_*.dll'))), 1)
# There is only 1 B_{hash}.dll
self.assertEqual(
len(glob.glob(os.path.join(bazel_bin, 'main', 'B_*.dll'))), 1)
# Building //main:other_main should succeed
exit_code, _, stderr = self.RunBazel([
'build', '//main:main', '//main:other_main',
'--incompatible_avoid_conflict_dlls'
])
self.AssertExitCode(exit_code, 0, stderr)
other_main_bin = os.path.join(bazel_bin, 'main/other_main.exe')
# Run the other_main_bin binary to see if it runs successfully
exit_code, stdout, stderr = self.RunProgram([other_main_bin])
self.AssertExitCode(exit_code, 0, stderr)
# There are 2 A_{hash}.dll since //main:main depends on //:A
# and //main:other_main depends on //lib:A
self.assertEqual(
len(glob.glob(os.path.join(bazel_bin, 'main', 'A_*.dll'))), 2)
def testDLLIsCopiedFromExternalRepo(self):
self.ScratchFile('ext_repo/WORKSPACE')
self.ScratchFile('ext_repo/BUILD', [
'cc_library(',
' name = "A",',
' srcs = ["a.cc"],',
' features = ["windows_export_all_symbols"],',
' visibility = ["//visibility:public"],',
')',
])
self.ScratchFile('ext_repo/a.cc', [
'#include <stdio.h>',
'void hello_A() {',
' printf("Hello A\\n");',
'}',
])
self.ScratchFile('WORKSPACE', [
'local_repository(',
' name = "ext_repo",',
' path = "ext_repo",',
')',
])
self.ScratchFile('BUILD', [
'cc_binary(',
' name = "main",',
' srcs = ["main.cc"],',
' deps = ["@ext_repo//:A"],',
' linkstatic = 0,',
')',
])
self.ScratchFile('main.cc', [
'extern void hello_A();',
'',
'int main() {',
' hello_A();',
' return 0;',
'}',
])
bazel_bin = self.getBazelInfo('bazel-bin')
exit_code, _, stderr = self.RunBazel(['build', '//:main'])
self.AssertExitCode(exit_code, 0, stderr)
# Test if A.dll is copied to the directory of main.exe
main_bin = os.path.join(bazel_bin, 'main.exe')
self.assertTrue(os.path.exists(main_bin))
self.assertTrue(os.path.exists(os.path.join(bazel_bin, 'A.dll')))
# Run the binary to see if it runs successfully
exit_code, stdout, stderr = self.RunProgram([main_bin])
self.AssertExitCode(exit_code, 0, stderr)
self.assertEqual(['Hello A'], stdout)
def testDynamicLinkingMSVCRT(self):
self.createProjectFiles()
bazel_output = self.getBazelInfo('output_path')
# By default, it should link to msvcrt dynamically.
exit_code, _, stderr = self.RunBazel(
['build', '//:A', '--output_groups=dynamic_library', '-s'])
paramfile = os.path.join(
bazel_output, 'x64_windows-fastbuild/bin/A.dll-2.params')
self.AssertExitCode(exit_code, 0, stderr)
self.assertIn('/MD', ''.join(stderr))
self.AssertFileContentContains(paramfile, '/DEFAULTLIB:msvcrt.lib')
self.assertNotIn('/MT', ''.join(stderr))
self.AssertFileContentNotContains(paramfile, '/DEFAULTLIB:libcmt.lib')
# Test build in debug mode.
exit_code, _, stderr = self.RunBazel(
['build', '-c', 'dbg', '//:A', '--output_groups=dynamic_library', '-s'])
paramfile = os.path.join(bazel_output, 'x64_windows-dbg/bin/A.dll-2.params')
self.AssertExitCode(exit_code, 0, stderr)
self.assertIn('/MDd', ''.join(stderr))
self.AssertFileContentContains(paramfile, '/DEFAULTLIB:msvcrtd.lib')
self.assertNotIn('/MTd', ''.join(stderr))
self.AssertFileContentNotContains(paramfile, '/DEFAULTLIB:libcmtd.lib')
def testStaticLinkingMSVCRT(self):
self.createProjectFiles()
bazel_output = self.getBazelInfo('output_path')
# With static_link_msvcrt feature, it should link to msvcrt statically.
exit_code, _, stderr = self.RunBazel([
'build', '//:A', '--output_groups=dynamic_library',
'--features=static_link_msvcrt', '-s'
])
paramfile = os.path.join(
bazel_output, 'x64_windows-fastbuild/bin/A.dll-2.params')
self.AssertExitCode(exit_code, 0, stderr)
self.assertNotIn('/MD', ''.join(stderr))
self.AssertFileContentNotContains(paramfile, '/DEFAULTLIB:msvcrt.lib')
self.assertIn('/MT', ''.join(stderr))
self.AssertFileContentContains(paramfile, '/DEFAULTLIB:libcmt.lib')
# Test build in debug mode.
exit_code, _, stderr = self.RunBazel([
'build', '-c', 'dbg', '//:A', '--output_groups=dynamic_library',
'--features=static_link_msvcrt', '-s'
])
paramfile = os.path.join(bazel_output, 'x64_windows-dbg/bin/A.dll-2.params')
self.AssertExitCode(exit_code, 0, stderr)
self.assertNotIn('/MDd', ''.join(stderr))
self.AssertFileContentNotContains(paramfile, '/DEFAULTLIB:msvcrtd.lib')
self.assertIn('/MTd', ''.join(stderr))
self.AssertFileContentContains(paramfile, '/DEFAULTLIB:libcmtd.lib')
def testBuildSharedLibraryFromCcBinaryWithStaticLink(self):
self.createProjectFiles()
self.ScratchFile(
'main/BUILD',
[
'cc_binary(',
' name = "main.dll",',
' srcs = ["main.cc"],',
' deps = ["//:B"],', # Transitively depends on //:A
' linkstatic = 1,'
' linkshared = 1,'
' features=["windows_export_all_symbols"]',
')',
])
bazel_bin = self.getBazelInfo('bazel-bin')
exit_code, _, stderr = self.RunBazel([
'build', '//main:main.dll',
'--output_groups=default,runtime_dynamic_libraries,interface_library'
])
self.AssertExitCode(exit_code, 0, stderr)
main_library = os.path.join(bazel_bin, 'main/main.dll')
main_interface = os.path.join(bazel_bin, 'main/main.dll.if.lib')
def_file = os.path.join(bazel_bin, 'main/main.dll.gen.def')
self.assertTrue(os.path.exists(main_library))
self.assertTrue(os.path.exists(main_interface))
self.assertTrue(os.path.exists(def_file))
# A.dll and B.dll should not be copied.
self.assertFalse(os.path.exists(os.path.join(bazel_bin, 'main/A.dll')))
self.assertFalse(os.path.exists(os.path.join(bazel_bin, 'main/B.dll')))
self.AssertFileContentContains(def_file, 'hello_A')
self.AssertFileContentContains(def_file, 'hello_B')
self.AssertFileContentContains(def_file, 'hello_C')
def testBuildSharedLibraryFromCcBinaryWithDynamicLink(self):
self.createProjectFiles()
self.ScratchFile(
'main/BUILD',
[
'cc_binary(',
' name = "main.dll",',
' srcs = ["main.cc"],',
' deps = ["//:B"],', # Transitively depends on //:A
' linkstatic = 0,'
' linkshared = 1,'
' features=["windows_export_all_symbols"]',
')',
'',
'genrule(',
' name = "renamed_main",',
' srcs = [":main.dll"],',
' outs = ["main_renamed.dll"],',
' cmd = "cp $< $@",',
')',
])
bazel_bin = self.getBazelInfo('bazel-bin')
exit_code, _, stderr = self.RunBazel([
'build', '//main:main.dll',
'--output_groups=default,runtime_dynamic_libraries,interface_library'
])
self.AssertExitCode(exit_code, 0, stderr)
main_library = os.path.join(bazel_bin, 'main/main.dll')
main_interface = os.path.join(bazel_bin, 'main/main.dll.if.lib')
def_file = os.path.join(bazel_bin, 'main/main.dll.gen.def')
self.assertTrue(os.path.exists(main_library))
self.assertTrue(os.path.exists(main_interface))
self.assertTrue(os.path.exists(def_file))
# A.dll and B.dll should be built and copied because they belong to
# runtime_dynamic_libraries output group.
self.assertTrue(os.path.exists(os.path.join(bazel_bin, 'main/A.dll')))
self.assertTrue(os.path.exists(os.path.join(bazel_bin, 'main/B.dll')))
# hello_A and hello_B should not be exported.
self.AssertFileContentNotContains(def_file, 'hello_A')
self.AssertFileContentNotContains(def_file, 'hello_B')
self.AssertFileContentContains(def_file, 'hello_C')
# The copy should succeed since //main:main.dll is only supposed to refer to
# main.dll, A.dll and B.dll should be in a separate output group.
exit_code, _, stderr = self.RunBazel(['build', '//main:renamed_main'])
self.AssertExitCode(exit_code, 0, stderr)
def testGetDefFileOfSharedLibraryFromCcBinary(self):
self.createProjectFiles()
self.ScratchFile(
'main/BUILD',
[
'cc_binary(',
' name = "main.dll",',
' srcs = ["main.cc"],',
' deps = ["//:B"],', # Transitively depends on //:A
' linkstatic = 1,'
' linkshared = 1,'
')',
])
bazel_bin = self.getBazelInfo('bazel-bin')
exit_code, _, stderr = self.RunBazel(
['build', '//main:main.dll', '--output_groups=def_file'])
self.AssertExitCode(exit_code, 0, stderr)
# Although windows_export_all_symbols is not specified for this target,
# we should still be able to get the DEF file by def_file output group.
def_file = os.path.join(bazel_bin, 'main/main.dll.gen.def')
self.assertTrue(os.path.exists(def_file))
self.AssertFileContentContains(def_file, 'hello_A')
self.AssertFileContentContains(def_file, 'hello_B')
self.AssertFileContentContains(def_file, 'hello_C')
def testBuildSharedLibraryWithoutAnySymbolExported(self):
self.createProjectFiles()
self.ScratchFile('BUILD', [
'cc_binary(',
' name = "A.dll",',
' srcs = ["a.cc", "a.h"],',
' copts = ["/DNO_DLLEXPORT"],',
' linkshared = 1,'
')',
])
bazel_bin = self.getBazelInfo('bazel-bin')
exit_code, _, stderr = self.RunBazel(['build', '//:A.dll'])
self.AssertExitCode(exit_code, 0, stderr)
# Although windows_export_all_symbols is not specified for this target,
# we should still be able to build a DLL without any symbol exported.
empty_def_file = os.path.join(bazel_bin, 'A.dll.gen.empty.def')
self.assertTrue(os.path.exists(empty_def_file))
self.AssertFileContentNotContains(empty_def_file, 'hello_A')
def testUsingDefFileGeneratedFromCcLibrary(self):
self.CreateWorkspaceWithDefaultRepos('WORKSPACE')
self.ScratchFile('lib_A.cc', ['void hello_A() {}'])
self.ScratchFile('lib_B.cc', ['void hello_B() {}'])
self.ScratchFile('BUILD', [
'cc_library(',
' name = "lib_A",',
' srcs = ["lib_A.cc"],',
')',
'',
'cc_library(',
' name = "lib_B",',
' srcs = ["lib_B.cc"],',
' deps = [":lib_A"]',
')',
'',
'filegroup(',
' name = "lib_B_symbols",',
' srcs = [":lib_B"],',
' output_group = "def_file",',
')',
'',
'cc_binary(',
' name = "lib.dll",',
' deps = [":lib_B"],',
' win_def_file = ":lib_B_symbols",',
' linkshared = 1,',
')',
])
# Test specifying DEF file in cc_binary
bazel_bin = self.getBazelInfo('bazel-bin')
exit_code, _, stderr = self.RunBazel(['build', '//:lib.dll', '-s'])
self.AssertExitCode(exit_code, 0, stderr)
def_file = bazel_bin + '/lib_B.gen.def'
self.assertTrue(os.path.exists(def_file))
# hello_A should not be exported
self.AssertFileContentNotContains(def_file, 'hello_A')
# hello_B should be exported
self.AssertFileContentContains(def_file, 'hello_B')
def testWinDefFileAttribute(self):
self.CreateWorkspaceWithDefaultRepos('WORKSPACE')
self.ScratchFile('lib.cc', ['void hello() {}'])
self.ScratchFile('my_lib.def', [
'EXPORTS',
' ?hello@@YAXXZ',
])
self.ScratchFile('BUILD', [
'cc_library(',
' name = "lib",',
' srcs = ["lib.cc"],',
' win_def_file = "my_lib.def",',
')',
'',
'cc_binary(',
' name = "lib_dy.dll",',
' srcs = ["lib.cc"],',
' win_def_file = "my_lib.def",',
' linkshared = 1,',
')',
])
# Test exporting symbols using custom DEF file in cc_library.<|fim▁hole|> ])
self.AssertExitCode(exit_code, 0, stderr)
bazel_bin = self.getBazelInfo('bazel-bin')
lib_if = os.path.join(bazel_bin, 'lib.if.lib')
lib_def = os.path.join(bazel_bin, 'lib.gen.def')
self.assertTrue(os.path.exists(lib_if))
self.assertFalse(os.path.exists(lib_def))
# Test specifying DEF file in cc_binary
exit_code, _, stderr = self.RunBazel(['build', '//:lib_dy.dll', '-s'])
self.AssertExitCode(exit_code, 0, stderr)
filepath = bazel_bin + '/lib_dy.dll-2.params'
with open(filepath, 'r', encoding='latin-1') as param_file:
self.assertIn('/DEF:my_lib.def', param_file.read())
def testCcImportRule(self):
self.CreateWorkspaceWithDefaultRepos('WORKSPACE')
self.ScratchFile('BUILD', [
'cc_import(',
' name = "a_import",',
' static_library = "A.lib",',
' shared_library = "A.dll",',
' interface_library = "A.if.lib",',
' hdrs = ["a.h"],',
' alwayslink = 1,',
')',
])
exit_code, _, stderr = self.RunBazel([
'build', '//:a_import',
])
self.AssertExitCode(exit_code, 0, stderr)
def testCopyDLLAsSource(self):
self.CreateWorkspaceWithDefaultRepos('WORKSPACE')
self.ScratchFile('BUILD', [
'cc_import(',
' name = "a_import",',
' shared_library = "A.dll",',
')',
'',
'cc_binary(',
' name = "bin",',
' srcs = ["bin.cc"],',
' deps = ["//:a_import"],',
')',
])
self.ScratchFile('A.dll')
self.ScratchFile('bin.cc', [
'int main() {',
' return 0;',
'}',
])
exit_code, _, stderr = self.RunBazel([
'build',
'//:bin',
])
self.AssertExitCode(exit_code, 0, stderr)
bazel_bin = self.getBazelInfo('bazel-bin')
a_dll = os.path.join(bazel_bin, 'A.dll')
# Even though A.dll is in the same package as bin.exe, but it still should
# be copied to the output directory of bin.exe.
self.assertTrue(os.path.exists(a_dll))
def testCppErrorShouldBeVisible(self):
self.CreateWorkspaceWithDefaultRepos('WORKSPACE')
self.ScratchFile('BUILD', [
'cc_binary(',
' name = "bad",',
' srcs = ["bad.cc"],',
')',
])
self.ScratchFile('bad.cc', [
'int main(int argc, char** argv) {',
' this_is_an_error();',
'}',
])
exit_code, stdout, stderr = self.RunBazel(['build', '//:bad'])
self.AssertExitCode(exit_code, 1, stderr)
self.assertIn('this_is_an_error', ''.join(stdout))
def testBuildWithClangClByCompilerFlag(self):
self.CreateWorkspaceWithDefaultRepos('WORKSPACE')
self.ScratchFile('BUILD', [
'cc_binary(',
' name = "main",',
' srcs = ["main.cc"],',
')',
])
self.ScratchFile('main.cc', [
'int main() {',
' return 0;',
'}',
])
exit_code, _, stderr = self.RunBazel([
'build', '-s', '--compiler=clang-cl',
'--incompatible_enable_cc_toolchain_resolution=false', '//:main'
])
self.AssertExitCode(exit_code, 0, stderr)
self.assertIn('clang-cl.exe', ''.join(stderr))
def testBuildWithClangClByToolchainResolution(self):
self.CreateWorkspaceWithDefaultRepos('WORKSPACE', [
'register_execution_platforms(',
' ":windows_clang"',
')',
'',
'register_toolchains(',
' "@local_config_cc//:cc-toolchain-x64_windows-clang-cl",',
')',
])
self.ScratchFile('BUILD', [
'platform(',
' name = "windows_clang",',
' constraint_values = [',
' "@platforms//cpu:x86_64",',
' "@platforms//os:windows",',
' "@bazel_tools//tools/cpp:clang-cl",',
' ]',
')',
'',
'cc_binary(',
' name = "main",',
' srcs = ["main.cc"],',
')',
])
self.ScratchFile('main.cc', [
'int main() {',
' return 0;',
'}',
])
exit_code, _, stderr = self.RunBazel([
'build', '-s', '--incompatible_enable_cc_toolchain_resolution=true',
'//:main'
])
self.AssertExitCode(exit_code, 0, stderr)
self.assertIn('clang-cl.exe', ''.join(stderr))
def createSimpleCppWorkspace(self, name):
work_dir = self.ScratchDir(name)
self.ScratchFile(name + '/WORKSPACE', ['workspace(name = "%s")' % name])
self.ScratchFile(
name + '/BUILD',
['cc_library(name = "lib", srcs = ["lib.cc"], hdrs = ["lib.h"])'])
self.ScratchFile(name + '/lib.h', ['void hello();'])
self.ScratchFile(name + '/lib.cc', ['#include "lib.h"', 'void hello() {}'])
return work_dir
# Regression test for https://github.com/bazelbuild/bazel/issues/9172
def testCacheBetweenWorkspaceWithDifferentNames(self):
cache_dir = self.ScratchDir('cache')
dir_a = self.createSimpleCppWorkspace('A')
dir_b = self.createSimpleCppWorkspace('B')
exit_code, _, stderr = self.RunBazel(
['build', '--disk_cache=' + cache_dir, ':lib'], cwd=dir_a)
self.AssertExitCode(exit_code, 0, stderr)
exit_code, _, stderr = self.RunBazel(
['build', '--disk_cache=' + cache_dir, ':lib'], cwd=dir_b)
self.AssertExitCode(exit_code, 0, stderr)
# Regression test for https://github.com/bazelbuild/bazel/issues/9321
def testCcCompileWithTreeArtifactAsSource(self):
self.CreateWorkspaceWithDefaultRepos('WORKSPACE')
self.ScratchFile('BUILD', [
'load(":genccs.bzl", "genccs")',
'',
'genccs(',
' name = "gen_tree",',
')',
'',
'cc_library(',
' name = "main",',
' srcs = [ "gen_tree" ]',
')',
'',
'cc_binary(',
' name = "genccs",',
' srcs = [ "genccs.cpp" ],',
')',
])
self.ScratchFile('genccs.bzl', [
'def _impl(ctx):',
' tree = ctx.actions.declare_directory(ctx.attr.name + ".cc")',
' ctx.actions.run(',
' inputs = [],',
' outputs = [ tree ],',
' arguments = [ tree.path ],',
' progress_message = "Generating cc files into \'%s\'" % tree.path,',
' executable = ctx.executable._tool,',
' )',
'',
' return [ DefaultInfo(files = depset([ tree ])) ]',
'',
'genccs = rule(',
' implementation = _impl,',
' attrs = {',
' "_tool": attr.label(',
' executable = True,',
' cfg = "host",',
' allow_files = True,',
' default = Label("//:genccs"),',
' )',
' }',
')',
])
self.ScratchFile('genccs.cpp', [
'#include <fstream>',
'#include <Windows.h>',
'using namespace std;',
'',
'int main (int argc, char *argv[]) {',
' CreateDirectory(argv[1], NULL);',
' ofstream myfile;',
' myfile.open(string(argv[1]) + string("/foo.cpp"));',
' myfile << "int main() { return 42; }";',
' return 0;',
'}',
])
exit_code, _, stderr = self.RunBazel(['build', '//:main'])
self.AssertExitCode(exit_code, 0, stderr)
def testBuild32BitCppBinaryWithMsvcCL(self):
self.CreateWorkspaceWithDefaultRepos('WORKSPACE')
self.ScratchFile('BUILD', [
'cc_binary(',
' name = "main",',
' srcs = ["main.cc"],',
')',
])
self.ScratchFile('main.cc', [
'int main() {',
' return 0;',
'}',
])
exit_code, _, stderr = self.RunBazel(
['build', '-s', '--cpu=x64_x86_windows', '//:main'])
self.AssertExitCode(exit_code, 0, stderr)
self.assertIn('x86/cl.exe', ''.join(stderr))
def testBuildArmCppBinaryWithMsvcCL(self):
self.CreateWorkspaceWithDefaultRepos('WORKSPACE')
self.ScratchFile('BUILD', [
'cc_binary(',
' name = "main",',
' srcs = ["main.cc"],',
')',
])
self.ScratchFile('main.cc', [
'int main() {',
' return 0;',
'}',
])
exit_code, _, stderr = self.RunBazel(
['build', '-s', '--cpu=x64_arm_windows', '//:main'])
self.AssertExitCode(exit_code, 0, stderr)
self.assertIn('arm/cl.exe', ''.join(stderr))
def testBuildArm64CppBinaryWithMsvcCL(self):
self.CreateWorkspaceWithDefaultRepos('WORKSPACE')
self.ScratchFile('BUILD', [
'cc_binary(',
' name = "main",',
' srcs = ["main.cc"],',
')',
])
self.ScratchFile('main.cc', [
'int main() {',
' return 0;',
'}',
])
exit_code, _, stderr = self.RunBazel(
['build', '-s', '--cpu=x64_arm64_windows', '//:main'])
self.AssertExitCode(exit_code, 0, stderr)
self.assertIn('arm64/cl.exe', ''.join(stderr))
if __name__ == '__main__':
unittest.main()<|fim▁end|>
|
# Auto-generating DEF file should be disabled when custom DEF file specified
exit_code, _, stderr = self.RunBazel([
'build', '//:lib', '-s', '--output_groups=dynamic_library',
'--features=windows_export_all_symbols'
|
<|file_name|>pieceTreeTextBuffer.ts<|end_file_name|><|fim▁begin|>/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as strings from 'vs/base/common/strings';
import { Position } from 'vs/editor/common/core/position';
import { Range } from 'vs/editor/common/core/range';
import { ApplyEditsResult, EndOfLinePreference, FindMatch, IInternalModelContentChange, ISingleEditOperationIdentifier, ITextBuffer, ITextSnapshot, ValidAnnotatedEditOperation, IValidEditOperation } from 'vs/editor/common/model';
import { PieceTreeBase, StringBuffer } from 'vs/editor/common/model/pieceTreeTextBuffer/pieceTreeBase';
import { SearchData } from 'vs/editor/common/model/textModelSearch';
import { countEOL, StringEOL } from 'vs/editor/common/model/tokensStore';
import { TextChange } from 'vs/editor/common/model/textChange';
export interface IValidatedEditOperation {
sortIndex: number;
identifier: ISingleEditOperationIdentifier | null;
range: Range;
rangeOffset: number;
rangeLength: number;
text: string;
eolCount: number;
firstLineLength: number;
lastLineLength: number;
forceMoveMarkers: boolean;
isAutoWhitespaceEdit: boolean;
}
export interface IReverseSingleEditOperation extends IValidEditOperation {
sortIndex: number;
}
export class PieceTreeTextBuffer implements ITextBuffer {
private readonly _pieceTree: PieceTreeBase;
private readonly _BOM: string;
private _mightContainRTL: boolean;
private _mightContainNonBasicASCII: boolean;
constructor(chunks: StringBuffer[], BOM: string, eol: '\r\n' | '\n', containsRTL: boolean, isBasicASCII: boolean, eolNormalized: boolean) {
this._BOM = BOM;
this._mightContainNonBasicASCII = !isBasicASCII;
this._mightContainRTL = containsRTL;
this._pieceTree = new PieceTreeBase(chunks, eol, eolNormalized);
}
// #region TextBuffer
public equals(other: ITextBuffer): boolean {
if (!(other instanceof PieceTreeTextBuffer)) {
return false;
}
if (this._BOM !== other._BOM) {
return false;
}
if (this.getEOL() !== other.getEOL()) {
return false;
}
return this._pieceTree.equal(other._pieceTree);
}
public mightContainRTL(): boolean {
return this._mightContainRTL;
}
public mightContainNonBasicASCII(): boolean {
return this._mightContainNonBasicASCII;
}
public getBOM(): string {
return this._BOM;
}
public getEOL(): '\r\n' | '\n' {
return this._pieceTree.getEOL();
}<|fim▁hole|> return this._pieceTree.createSnapshot(preserveBOM ? this._BOM : '');
}
public getOffsetAt(lineNumber: number, column: number): number {
return this._pieceTree.getOffsetAt(lineNumber, column);
}
public getPositionAt(offset: number): Position {
return this._pieceTree.getPositionAt(offset);
}
public getRangeAt(start: number, length: number): Range {
let end = start + length;
const startPosition = this.getPositionAt(start);
const endPosition = this.getPositionAt(end);
return new Range(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column);
}
public getValueInRange(range: Range, eol: EndOfLinePreference = EndOfLinePreference.TextDefined): string {
if (range.isEmpty()) {
return '';
}
const lineEnding = this._getEndOfLine(eol);
return this._pieceTree.getValueInRange(range, lineEnding);
}
public getValueLengthInRange(range: Range, eol: EndOfLinePreference = EndOfLinePreference.TextDefined): number {
if (range.isEmpty()) {
return 0;
}
if (range.startLineNumber === range.endLineNumber) {
return (range.endColumn - range.startColumn);
}
let startOffset = this.getOffsetAt(range.startLineNumber, range.startColumn);
let endOffset = this.getOffsetAt(range.endLineNumber, range.endColumn);
return endOffset - startOffset;
}
public getCharacterCountInRange(range: Range, eol: EndOfLinePreference = EndOfLinePreference.TextDefined): number {
if (this._mightContainNonBasicASCII) {
// we must count by iterating
let result = 0;
const fromLineNumber = range.startLineNumber;
const toLineNumber = range.endLineNumber;
for (let lineNumber = fromLineNumber; lineNumber <= toLineNumber; lineNumber++) {
const lineContent = this.getLineContent(lineNumber);
const fromOffset = (lineNumber === fromLineNumber ? range.startColumn - 1 : 0);
const toOffset = (lineNumber === toLineNumber ? range.endColumn - 1 : lineContent.length);
for (let offset = fromOffset; offset < toOffset; offset++) {
if (strings.isHighSurrogate(lineContent.charCodeAt(offset))) {
result = result + 1;
offset = offset + 1;
} else {
result = result + 1;
}
}
}
result += this._getEndOfLine(eol).length * (toLineNumber - fromLineNumber);
return result;
}
return this.getValueLengthInRange(range, eol);
}
public getLength(): number {
return this._pieceTree.getLength();
}
public getLineCount(): number {
return this._pieceTree.getLineCount();
}
public getLinesContent(): string[] {
return this._pieceTree.getLinesContent();
}
public getLineContent(lineNumber: number): string {
return this._pieceTree.getLineContent(lineNumber);
}
public getLineCharCode(lineNumber: number, index: number): number {
return this._pieceTree.getLineCharCode(lineNumber, index);
}
public getLineLength(lineNumber: number): number {
return this._pieceTree.getLineLength(lineNumber);
}
public getLineMinColumn(lineNumber: number): number {
return 1;
}
public getLineMaxColumn(lineNumber: number): number {
return this.getLineLength(lineNumber) + 1;
}
public getLineFirstNonWhitespaceColumn(lineNumber: number): number {
const result = strings.firstNonWhitespaceIndex(this.getLineContent(lineNumber));
if (result === -1) {
return 0;
}
return result + 1;
}
public getLineLastNonWhitespaceColumn(lineNumber: number): number {
const result = strings.lastNonWhitespaceIndex(this.getLineContent(lineNumber));
if (result === -1) {
return 0;
}
return result + 2;
}
private _getEndOfLine(eol: EndOfLinePreference): string {
switch (eol) {
case EndOfLinePreference.LF:
return '\n';
case EndOfLinePreference.CRLF:
return '\r\n';
case EndOfLinePreference.TextDefined:
return this.getEOL();
}
throw new Error('Unknown EOL preference');
}
public setEOL(newEOL: '\r\n' | '\n'): void {
this._pieceTree.setEOL(newEOL);
}
public applyEdits(rawOperations: ValidAnnotatedEditOperation[], recordTrimAutoWhitespace: boolean, computeUndoEdits: boolean): ApplyEditsResult {
let mightContainRTL = this._mightContainRTL;
let mightContainNonBasicASCII = this._mightContainNonBasicASCII;
let canReduceOperations = true;
let operations: IValidatedEditOperation[] = [];
for (let i = 0; i < rawOperations.length; i++) {
let op = rawOperations[i];
if (canReduceOperations && op._isTracked) {
canReduceOperations = false;
}
let validatedRange = op.range;
if (!mightContainRTL && op.text) {
// check if the new inserted text contains RTL
mightContainRTL = strings.containsRTL(op.text);
}
if (!mightContainNonBasicASCII && op.text) {
mightContainNonBasicASCII = !strings.isBasicASCII(op.text);
}
let validText = '';
let eolCount = 0;
let firstLineLength = 0;
let lastLineLength = 0;
if (op.text) {
let strEOL: StringEOL;
[eolCount, firstLineLength, lastLineLength, strEOL] = countEOL(op.text);
const bufferEOL = this.getEOL();
const expectedStrEOL = (bufferEOL === '\r\n' ? StringEOL.CRLF : StringEOL.LF);
if (strEOL === StringEOL.Unknown || strEOL === expectedStrEOL) {
validText = op.text;
} else {
validText = op.text.replace(/\r\n|\r|\n/g, bufferEOL);
}
}
operations[i] = {
sortIndex: i,
identifier: op.identifier || null,
range: validatedRange,
rangeOffset: this.getOffsetAt(validatedRange.startLineNumber, validatedRange.startColumn),
rangeLength: this.getValueLengthInRange(validatedRange),
text: validText,
eolCount: eolCount,
firstLineLength: firstLineLength,
lastLineLength: lastLineLength,
forceMoveMarkers: Boolean(op.forceMoveMarkers),
isAutoWhitespaceEdit: op.isAutoWhitespaceEdit || false
};
}
// Sort operations ascending
operations.sort(PieceTreeTextBuffer._sortOpsAscending);
let hasTouchingRanges = false;
for (let i = 0, count = operations.length - 1; i < count; i++) {
let rangeEnd = operations[i].range.getEndPosition();
let nextRangeStart = operations[i + 1].range.getStartPosition();
if (nextRangeStart.isBeforeOrEqual(rangeEnd)) {
if (nextRangeStart.isBefore(rangeEnd)) {
// overlapping ranges
throw new Error('Overlapping ranges are not allowed!');
}
hasTouchingRanges = true;
}
}
if (canReduceOperations) {
operations = this._reduceOperations(operations);
}
// Delta encode operations
let reverseRanges = (computeUndoEdits || recordTrimAutoWhitespace ? PieceTreeTextBuffer._getInverseEditRanges(operations) : []);
let newTrimAutoWhitespaceCandidates: { lineNumber: number, oldContent: string }[] = [];
if (recordTrimAutoWhitespace) {
for (let i = 0; i < operations.length; i++) {
let op = operations[i];
let reverseRange = reverseRanges[i];
if (op.isAutoWhitespaceEdit && op.range.isEmpty()) {
// Record already the future line numbers that might be auto whitespace removal candidates on next edit
for (let lineNumber = reverseRange.startLineNumber; lineNumber <= reverseRange.endLineNumber; lineNumber++) {
let currentLineContent = '';
if (lineNumber === reverseRange.startLineNumber) {
currentLineContent = this.getLineContent(op.range.startLineNumber);
if (strings.firstNonWhitespaceIndex(currentLineContent) !== -1) {
continue;
}
}
newTrimAutoWhitespaceCandidates.push({ lineNumber: lineNumber, oldContent: currentLineContent });
}
}
}
}
let reverseOperations: IReverseSingleEditOperation[] | null = null;
if (computeUndoEdits) {
let reverseRangeDeltaOffset = 0;
reverseOperations = [];
for (let i = 0; i < operations.length; i++) {
const op = operations[i];
const reverseRange = reverseRanges[i];
const bufferText = this.getValueInRange(op.range);
const reverseRangeOffset = op.rangeOffset + reverseRangeDeltaOffset;
reverseRangeDeltaOffset += (op.text.length - bufferText.length);
reverseOperations[i] = {
sortIndex: op.sortIndex,
identifier: op.identifier,
range: reverseRange,
text: bufferText,
textChange: new TextChange(op.rangeOffset, bufferText, reverseRangeOffset, op.text)
};
}
// Can only sort reverse operations when the order is not significant
if (!hasTouchingRanges) {
reverseOperations.sort((a, b) => a.sortIndex - b.sortIndex);
}
}
this._mightContainRTL = mightContainRTL;
this._mightContainNonBasicASCII = mightContainNonBasicASCII;
const contentChanges = this._doApplyEdits(operations);
let trimAutoWhitespaceLineNumbers: number[] | null = null;
if (recordTrimAutoWhitespace && newTrimAutoWhitespaceCandidates.length > 0) {
// sort line numbers auto whitespace removal candidates for next edit descending
newTrimAutoWhitespaceCandidates.sort((a, b) => b.lineNumber - a.lineNumber);
trimAutoWhitespaceLineNumbers = [];
for (let i = 0, len = newTrimAutoWhitespaceCandidates.length; i < len; i++) {
let lineNumber = newTrimAutoWhitespaceCandidates[i].lineNumber;
if (i > 0 && newTrimAutoWhitespaceCandidates[i - 1].lineNumber === lineNumber) {
// Do not have the same line number twice
continue;
}
let prevContent = newTrimAutoWhitespaceCandidates[i].oldContent;
let lineContent = this.getLineContent(lineNumber);
if (lineContent.length === 0 || lineContent === prevContent || strings.firstNonWhitespaceIndex(lineContent) !== -1) {
continue;
}
trimAutoWhitespaceLineNumbers.push(lineNumber);
}
}
return new ApplyEditsResult(
reverseOperations,
contentChanges,
trimAutoWhitespaceLineNumbers
);
}
/**
* Transform operations such that they represent the same logic edit,
* but that they also do not cause OOM crashes.
*/
private _reduceOperations(operations: IValidatedEditOperation[]): IValidatedEditOperation[] {
if (operations.length < 1000) {
// We know from empirical testing that a thousand edits work fine regardless of their shape.
return operations;
}
// At one point, due to how events are emitted and how each operation is handled,
// some operations can trigger a high amount of temporary string allocations,
// that will immediately get edited again.
// e.g. a formatter inserting ridiculous ammounts of \n on a model with a single line
// Therefore, the strategy is to collapse all the operations into a huge single edit operation
return [this._toSingleEditOperation(operations)];
}
_toSingleEditOperation(operations: IValidatedEditOperation[]): IValidatedEditOperation {
let forceMoveMarkers = false;
const firstEditRange = operations[0].range;
const lastEditRange = operations[operations.length - 1].range;
const entireEditRange = new Range(firstEditRange.startLineNumber, firstEditRange.startColumn, lastEditRange.endLineNumber, lastEditRange.endColumn);
let lastEndLineNumber = firstEditRange.startLineNumber;
let lastEndColumn = firstEditRange.startColumn;
const result: string[] = [];
for (let i = 0, len = operations.length; i < len; i++) {
const operation = operations[i];
const range = operation.range;
forceMoveMarkers = forceMoveMarkers || operation.forceMoveMarkers;
// (1) -- Push old text
result.push(this.getValueInRange(new Range(lastEndLineNumber, lastEndColumn, range.startLineNumber, range.startColumn)));
// (2) -- Push new text
if (operation.text.length > 0) {
result.push(operation.text);
}
lastEndLineNumber = range.endLineNumber;
lastEndColumn = range.endColumn;
}
const text = result.join('');
const [eolCount, firstLineLength, lastLineLength] = countEOL(text);
return {
sortIndex: 0,
identifier: operations[0].identifier,
range: entireEditRange,
rangeOffset: this.getOffsetAt(entireEditRange.startLineNumber, entireEditRange.startColumn),
rangeLength: this.getValueLengthInRange(entireEditRange, EndOfLinePreference.TextDefined),
text: text,
eolCount: eolCount,
firstLineLength: firstLineLength,
lastLineLength: lastLineLength,
forceMoveMarkers: forceMoveMarkers,
isAutoWhitespaceEdit: false
};
}
private _doApplyEdits(operations: IValidatedEditOperation[]): IInternalModelContentChange[] {
operations.sort(PieceTreeTextBuffer._sortOpsDescending);
let contentChanges: IInternalModelContentChange[] = [];
// operations are from bottom to top
for (let i = 0; i < operations.length; i++) {
let op = operations[i];
const startLineNumber = op.range.startLineNumber;
const startColumn = op.range.startColumn;
const endLineNumber = op.range.endLineNumber;
const endColumn = op.range.endColumn;
if (startLineNumber === endLineNumber && startColumn === endColumn && op.text.length === 0) {
// no-op
continue;
}
if (op.text) {
// replacement
this._pieceTree.delete(op.rangeOffset, op.rangeLength);
this._pieceTree.insert(op.rangeOffset, op.text, true);
} else {
// deletion
this._pieceTree.delete(op.rangeOffset, op.rangeLength);
}
const contentChangeRange = new Range(startLineNumber, startColumn, endLineNumber, endColumn);
contentChanges.push({
range: contentChangeRange,
rangeLength: op.rangeLength,
text: op.text,
rangeOffset: op.rangeOffset,
forceMoveMarkers: op.forceMoveMarkers
});
}
return contentChanges;
}
findMatchesLineByLine(searchRange: Range, searchData: SearchData, captureMatches: boolean, limitResultCount: number): FindMatch[] {
return this._pieceTree.findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount);
}
// #endregion
// #region helper
// testing purpose.
public getPieceTree(): PieceTreeBase {
return this._pieceTree;
}
/**
* Assumes `operations` are validated and sorted ascending
*/
public static _getInverseEditRanges(operations: IValidatedEditOperation[]): Range[] {
let result: Range[] = [];
let prevOpEndLineNumber: number = 0;
let prevOpEndColumn: number = 0;
let prevOp: IValidatedEditOperation | null = null;
for (let i = 0, len = operations.length; i < len; i++) {
let op = operations[i];
let startLineNumber: number;
let startColumn: number;
if (prevOp) {
if (prevOp.range.endLineNumber === op.range.startLineNumber) {
startLineNumber = prevOpEndLineNumber;
startColumn = prevOpEndColumn + (op.range.startColumn - prevOp.range.endColumn);
} else {
startLineNumber = prevOpEndLineNumber + (op.range.startLineNumber - prevOp.range.endLineNumber);
startColumn = op.range.startColumn;
}
} else {
startLineNumber = op.range.startLineNumber;
startColumn = op.range.startColumn;
}
let resultRange: Range;
if (op.text.length > 0) {
// the operation inserts something
const lineCount = op.eolCount + 1;
if (lineCount === 1) {
// single line insert
resultRange = new Range(startLineNumber, startColumn, startLineNumber, startColumn + op.firstLineLength);
} else {
// multi line insert
resultRange = new Range(startLineNumber, startColumn, startLineNumber + lineCount - 1, op.lastLineLength + 1);
}
} else {
// There is nothing to insert
resultRange = new Range(startLineNumber, startColumn, startLineNumber, startColumn);
}
prevOpEndLineNumber = resultRange.endLineNumber;
prevOpEndColumn = resultRange.endColumn;
result.push(resultRange);
prevOp = op;
}
return result;
}
private static _sortOpsAscending(a: IValidatedEditOperation, b: IValidatedEditOperation): number {
let r = Range.compareRangesUsingEnds(a.range, b.range);
if (r === 0) {
return a.sortIndex - b.sortIndex;
}
return r;
}
private static _sortOpsDescending(a: IValidatedEditOperation, b: IValidatedEditOperation): number {
let r = Range.compareRangesUsingEnds(a.range, b.range);
if (r === 0) {
return b.sortIndex - a.sortIndex;
}
return -r;
}
// #endregion
}<|fim▁end|>
|
public createSnapshot(preserveBOM: boolean): ITextSnapshot {
|
<|file_name|>server.cpp<|end_file_name|><|fim▁begin|>/*
Copyright (c) 2012-2014 The SSDB Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
*/
#include "server.h"
#include "../util/strings.h"
#include "../util/file.h"
#include "../util/config.h"
#include "../util/log.h"
#include "../util/ip_filter.h"
#include "link.h"
#include <vector>
static DEF_PROC(ping);
static DEF_PROC(info);
static DEF_PROC(auth);
#define TICK_INTERVAL 100 // ms
#define STATUS_REPORT_TICKS (300 * 1000/TICK_INTERVAL) // second
volatile bool quit = false;
volatile uint32_t g_ticks = 0;
void signal_handler(int sig){
switch(sig){
case SIGTERM:
case SIGINT:{
quit = true;
break;
}
case SIGALRM:{
g_ticks ++;
break;
}
}
}
NetworkServer::NetworkServer(){
tick_interval = TICK_INTERVAL;
status_report_ticks = STATUS_REPORT_TICKS;
conf = NULL;
serv_link = NULL;
link_count = 0;
fdes = new Fdevents();
ip_filter = new IpFilter();
// add built-in procs, can be overridden
proc_map.set_proc("ping", "r", proc_ping);
proc_map.set_proc("info", "r", proc_info);
proc_map.set_proc("auth", "r", proc_auth);
signal(SIGPIPE, SIG_IGN);
signal(SIGINT, signal_handler);
signal(SIGTERM, signal_handler);
#ifndef __CYGWIN__
signal(SIGALRM, signal_handler);
{
struct itimerval tv;
tv.it_interval.tv_sec = (TICK_INTERVAL / 1000);
tv.it_interval.tv_usec = (TICK_INTERVAL % 1000) * 1000;
tv.it_value.tv_sec = 1;
tv.it_value.tv_usec = 0;
setitimer(ITIMER_REAL, &tv, NULL);
}
#endif
}
NetworkServer::~NetworkServer(){
delete conf;
delete serv_link;
delete fdes;
delete ip_filter;
writer->stop();
delete writer;
reader->stop();
delete reader;
}
void NetworkServer::init(const char *conf_file){
if(!is_file(conf_file)){
fprintf(stderr, "'%s' is not a file or not exists!\n", conf_file);
exit(1);
}
conf = Config::load(conf_file);
if(!conf){
fprintf(stderr, "error loading conf file: '%s'\n", conf_file);
exit(1);
}
{
std::string conf_dir = real_dirname(conf_file);
if(chdir(conf_dir.c_str()) == -1){
fprintf(stderr, "error chdir: %s\n", conf_dir.c_str());
exit(1);
}
}
this->init(*conf);
}
void NetworkServer::init(const Config &conf){
// init ip_filter
{
Config *cc = (Config *)conf.get("server");
if(cc != NULL){
std::vector<Config *> *children = &cc->children;
std::vector<Config *>::iterator it;
for(it = children->begin(); it != children->end(); it++){
if((*it)->key == "allow"){
const char *ip = (*it)->str();
log_info(" allow %s", ip);
ip_filter->add_allow(ip);
}
if((*it)->key == "deny"){
const char *ip = (*it)->str();
log_info(" deny %s", ip);
ip_filter->add_deny(ip);
}
}
}
}
{ // server
const char *ip = conf.get_str("server.ip");
int port = conf.get_num("server.port");
if(ip == NULL || ip[0] == '\0'){
ip = "127.0.0.1";
}
serv_link = Link::listen(ip, port);
if(serv_link == NULL){
log_fatal("error opening server socket! %s", strerror(errno));
fprintf(stderr, "error opening server socket! %s\n", strerror(errno));
exit(1);
}
log_info("server listen on %s:%d", ip, port);
std::string password;
password = conf.get_str("server.auth");
if(password.size() && (password.size() < 32 || password == "very-strong-password")){
log_fatal("weak password is not allowed!");
fprintf(stderr, "WARNING! Weak password is not allowed!\n");
exit(1);
}
if(password.empty()){
log_info("auth: off");
}else{
log_info("auth: on");
}
this->need_auth = false;
if(!password.empty()){
this->need_auth = true;
this->password = password;
}
}
}
void NetworkServer::serve(){
writer = new ProcWorkerPool("writer");
writer->start(WRITER_THREADS);
reader = new ProcWorkerPool("reader");
reader->start(READER_THREADS);
ready_list_t ready_list;
ready_list_t ready_list_2;
ready_list_t::iterator it;
const Fdevents::events_t *events;
fdes->set(serv_link->fd(), FDEVENT_IN, 0, serv_link);
fdes->set(this->reader->fd(), FDEVENT_IN, 0, this->reader);
fdes->set(this->writer->fd(), FDEVENT_IN, 0, this->writer);
uint32_t last_ticks = g_ticks;
while(!quit){
// status report
if((uint32_t)(g_ticks - last_ticks) >= STATUS_REPORT_TICKS){
last_ticks = g_ticks;
log_info("server running, links: %d", this->link_count);
}
ready_list.swap(ready_list_2);
ready_list_2.clear();
if(!ready_list.empty()){
// ready_list not empty, so we should return immediately
events = fdes->wait(0);
}else{
events = fdes->wait(50);
}
if(events == NULL){
log_fatal("events.wait error: %s", strerror(errno));
break;
}
for(int i=0; i<(int)events->size(); i++){
const Fdevent *fde = events->at(i);
if(fde->data.ptr == serv_link){
Link *link = accept_link();
if(link){
this->link_count ++;
log_debug("new link from %s:%d, fd: %d, links: %d",
link->remote_ip, link->remote_port, link->fd(), this->link_count);
fdes->set(link->fd(), FDEVENT_IN, 1, link);
}
}else if(fde->data.ptr == this->reader || fde->data.ptr == this->writer){
ProcWorkerPool *worker = (ProcWorkerPool *)fde->data.ptr;
ProcJob job;
if(worker->pop(&job) == 0){
log_fatal("reading result from workers error!");
exit(0);
}
if(proc_result(&job, &ready_list) == PROC_ERROR){
//
}
}else{
proc_client_event(fde, &ready_list);
}
}
for(it = ready_list.begin(); it != ready_list.end(); it ++){
Link *link = *it;
if(link->error()){
this->link_count --;
fdes->del(link->fd());
delete link;
continue;
}
const Request *req = link->recv();
if(req == NULL){
log_warn("fd: %d, link parse error, delete link", link->fd());
this->link_count --;
fdes->del(link->fd());
delete link;
continue;
}
if(req->empty()){
fdes->set(link->fd(), FDEVENT_IN, 1, link);
continue;
}
link->active_time = millitime();
ProcJob job;
job.link = link;
this->proc(&job);
if(job.result == PROC_THREAD){
fdes->del(link->fd());
continue;
}
if(job.result == PROC_BACKEND){
fdes->del(link->fd());
this->link_count --;
continue;
}
if(proc_result(&job, &ready_list_2) == PROC_ERROR){
//
}
} // end foreach ready link
}
}
Link* NetworkServer::accept_link(){
Link *link = serv_link->accept();
if(link == NULL){
log_error("accept failed! %s", strerror(errno));
return NULL;
}
if(!ip_filter->check_pass(link->remote_ip)){
log_debug("ip_filter deny link from %s:%d", link->remote_ip, link->remote_port);
delete link;<|fim▁hole|> link->nodelay();
link->noblock();
link->create_time = millitime();
link->active_time = link->create_time;
return link;
}
int NetworkServer::proc_result(ProcJob *job, ready_list_t *ready_list){
Link *link = job->link;
int len;
if(job->cmd){
job->cmd->calls += 1;
job->cmd->time_wait += job->time_wait;
job->cmd->time_proc += job->time_proc;
}
if(job->result == PROC_ERROR){
log_info("fd: %d, proc error, delete link", link->fd());
goto proc_err;
}
len = link->write();
//log_debug("write: %d", len);
if(len < 0){
log_debug("fd: %d, write: %d, delete link", link->fd(), len);
goto proc_err;
}
if(!link->output->empty()){
fdes->set(link->fd(), FDEVENT_OUT, 1, link);
}
if(link->input->empty()){
fdes->set(link->fd(), FDEVENT_IN, 1, link);
}else{
fdes->clr(link->fd(), FDEVENT_IN);
ready_list->push_back(link);
}
return PROC_OK;
proc_err:
this->link_count --;
fdes->del(link->fd());
delete link;
return PROC_ERROR;
}
/*
event:
read => ready_list OR close
write => NONE
proc =>
done: write & (read OR ready_list)
async: stop (read & write)
1. When writing to a link, it may happen to be in the ready_list,
so we cannot close that link in write process, we could only
just mark it as closed.
2. When reading from a link, it is never in the ready_list, so it
is safe to close it in read process, also safe to put it into
ready_list.
3. Ignore FDEVENT_ERR
A link is in either one of these places:
1. ready list
2. async worker queue
So it safe to delete link when processing ready list and async worker result.
*/
int NetworkServer::proc_client_event(const Fdevent *fde, ready_list_t *ready_list){
Link *link = (Link *)fde->data.ptr;
if(fde->events & FDEVENT_IN){
ready_list->push_back(link);
if(link->error()){
return 0;
}
int len = link->read();
//log_debug("fd: %d read: %d", link->fd(), len);
if(len <= 0){
log_debug("fd: %d, read: %d, delete link", link->fd(), len);
link->mark_error();
return 0;
}
}
if(fde->events & FDEVENT_OUT){
if(link->error()){
return 0;
}
int len = link->write();
if(len <= 0){
log_debug("fd: %d, write: %d, delete link", link->fd(), len);
link->mark_error();
return 0;
}
if(link->output->empty()){
fdes->clr(link->fd(), FDEVENT_OUT);
}
}
return 0;
}
void NetworkServer::proc(ProcJob *job){
job->serv = this;
job->result = PROC_OK;
job->stime = millitime();
const Request *req = job->link->last_recv();
Response resp;
do{
// AUTH
if(this->need_auth && job->link->auth == false && req->at(0) != "auth"){
resp.push_back("noauth");
resp.push_back("authentication required");
break;
}
Command *cmd = proc_map.get_proc(req->at(0));
if(!cmd){
resp.push_back("client_error");
resp.push_back("Unknown Command: " + req->at(0).String());
break;
}
job->cmd = cmd;
if(cmd->flags & Command::FLAG_THREAD){
if(cmd->flags & Command::FLAG_WRITE){
job->result = PROC_THREAD;
writer->push(*job);
}else{
job->result = PROC_THREAD;
reader->push(*job);
}
return;
}
proc_t p = cmd->proc;
job->time_wait = 1000 * (millitime() - job->stime);
job->result = (*p)(this, job->link, *req, &resp);
job->time_proc = 1000 * (millitime() - job->stime) - job->time_wait;
}while(0);
if(job->link->send(resp.resp) == -1){
job->result = PROC_ERROR;
}else{
if(log_level() >= Logger::LEVEL_DEBUG){
log_debug("w:%.3f,p:%.3f, req: %s, resp: %s",
job->time_wait, job->time_proc,
serialize_req(*req).c_str(),
serialize_req(resp.resp).c_str());
}
}
}
/* built-in procs */
static int proc_ping(NetworkServer *net, Link *link, const Request &req, Response *resp){
resp->push_back("ok");
return 0;
}
static int proc_info(NetworkServer *net, Link *link, const Request &req, Response *resp){
resp->push_back("ok");
resp->push_back("ideawu's network server framework");
resp->push_back("version");
resp->push_back("1.0");
resp->push_back("links");
resp->add(net->link_count);
{
int64_t calls = 0;
proc_map_t::iterator it;
for(it=net->proc_map.begin(); it!=net->proc_map.end(); it++){
Command *cmd = it->second;
calls += cmd->calls;
}
resp->push_back("total_calls");
resp->add(calls);
}
return 0;
}
static int proc_auth(NetworkServer *net, Link *link, const Request &req, Response *resp){
if(req.size() != 2){
resp->push_back("client_error");
}else{
if(!net->need_auth || req[1] == net->password){
link->auth = true;
resp->push_back("ok");
resp->push_back("1");
}else{
resp->push_back("error");
resp->push_back("invalid password");
}
}
return 0;
}<|fim▁end|>
|
return NULL;
}
|
<|file_name|>pRunoff.py<|end_file_name|><|fim▁begin|>from numpy import zeros
from gwlfe.Memoization import memoize
from gwlfe.MultiUse_Fxns.Runoff.RurQRunoff import RurQRunoff
from gwlfe.MultiUse_Fxns.Runoff.RurQRunoff import RurQRunoff_f
from gwlfe.Output.Loading.PConc import PConc
from gwlfe.Output.Loading.PConc import PConc_f<|fim▁hole|>def pRunoff(NYrs, DaysMonth, InitSnow_0, Temp, Prec, AntMoist_0, NRur, NUrb, CN, Grow_0, Area, PhosConc, ManuredAreas,
FirstManureMonth, LastManureMonth, ManPhos, FirstManureMonth2,
LastManureMonth2):
result = zeros((NYrs, 12, 10))
rur_q_runoff = RurQRunoff(NYrs, DaysMonth, InitSnow_0, Temp, Prec, AntMoist_0, NRur, NUrb, CN, Grow_0)
p_conc = PConc(NRur, NUrb, PhosConc, ManPhos, ManuredAreas, FirstManureMonth, LastManureMonth, FirstManureMonth2,
LastManureMonth2)
for Y in range(NYrs):
for i in range(12):
for l in range(NRur):
# += changed to =
result[Y][i][l] = 0.1 * p_conc[i][l] * rur_q_runoff[Y][l][i] * Area[l]
return result
@memoize
def pRunoff_f(NYrs, DaysMonth, InitSnow_0, Temp, Prec, AntMoist_0, NRur, NUrb, CN, Grow_0, Area, PhosConc, ManuredAreas,
FirstManureMonth, LastManureMonth, ManPhos, FirstManureMonth2, LastManureMonth2):
p_conc = PConc_f(NRur, NUrb, PhosConc, ManPhos, ManuredAreas, FirstManureMonth, LastManureMonth, FirstManureMonth2,
LastManureMonth2)[:, :NRur]
rur_q_runoff = RurQRunoff_f(NYrs, DaysMonth, InitSnow_0, Temp, Prec, AntMoist_0, NRur, NUrb, CN, Grow_0)
return 0.1 * p_conc * rur_q_runoff * Area[:NRur]<|fim▁end|>
|
@memoize
|
<|file_name|>gmock-internal-utils.cc<|end_file_name|><|fim▁begin|>// Copyright 2007, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: [email protected] (Zhanyong Wan)
// Google Mock - a framework for writing C++ mock classes.
//
// This file defines some utilities useful for implementing Google
// Mock. They are subject to change without notice, so please DO NOT
// USE THEM IN USER CODE.
#include "gmock/internal/gmock-internal-utils.h"
#include <ctype.h>
#include <ostream> // NOLINT
#include <string>
#include "gmock/gmock.h"
#include "gmock/internal/gmock-port.h"
#include "gtest/gtest.h"
namespace testing {
namespace internal {
// Joins a vector of strings as if they are fields of a tuple; returns
// the joined string.
GTEST_API_ std::string JoinAsTuple(const Strings& fields) {
switch (fields.size()) {
case 0:
return "";
case 1:
return fields[0];
default:
std::string result = "(" + fields[0];
for (size_t i = 1; i < fields.size(); i++) {
result += ", ";
result += fields[i];
}
result += ")";
return result;
}
}
// Converts an identifier name to a space-separated list of lower-case
// words. Each maximum substring of the form [A-Za-z][a-z]*|\d+ is
// treated as one word. For example, both "FooBar123" and
// "foo_bar_123" are converted to "foo bar 123".
GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name) {
std::string result;
char prev_char = '\0';
for (const char* p = id_name; *p != '\0'; prev_char = *(p++)) {
// We don't care about the current locale as the input is
// guaranteed to be a valid C++ identifier name.
const bool starts_new_word = IsUpper(*p) ||
(!IsAlpha(prev_char) && IsLower(*p)) ||
(!IsDigit(prev_char) && IsDigit(*p));
if (IsAlNum(*p)) {
if (starts_new_word && result != "")
result += ' ';
result += ToLower(*p);
}
}
return result;
}
// This class reports Google Mock failures as Google Test failures. A
// user can define another class in a similar fashion if they intend to
// use Google Mock with a testing framework other than Google Test.
class GoogleTestFailureReporter : public FailureReporterInterface {
public:
virtual void ReportFailure(FailureType type, const char* file, int line,
const std::string& message) {
AssertHelper(type == kFatal ?
TestPartResult::kFatalFailure :
TestPartResult::kNonFatalFailure,
file,
line,
message.c_str()) = Message();
if (type == kFatal) {
posix::Abort();
}
}
};
<|fim▁hole|> // guarantees that the following use of failure_reporter is
// thread-safe. We may need to add additional synchronization to
// protect failure_reporter if we port Google Mock to other
// compilers.
static FailureReporterInterface* const failure_reporter =
new GoogleTestFailureReporter();
return failure_reporter;
}
// Protects global resources (stdout in particular) used by Log().
static GTEST_DEFINE_STATIC_MUTEX_(g_log_mutex);
// Returns true iff a log with the given severity is visible according
// to the --gmock_verbose flag.
GTEST_API_ bool LogIsVisible(LogSeverity severity) {
if (GMOCK_FLAG(verbose) == kInfoVerbosity) {
// Always show the log if --gmock_verbose=info.
return true;
} else if (GMOCK_FLAG(verbose) == kErrorVerbosity) {
// Always hide it if --gmock_verbose=error.
return false;
} else {
// If --gmock_verbose is neither "info" nor "error", we treat it
// as "warning" (its default value).
return severity == kWarning;
}
}
// Prints the given message to stdout iff 'severity' >= the level
// specified by the --gmock_verbose flag. If stack_frames_to_skip >=
// 0, also prints the stack trace excluding the top
// stack_frames_to_skip frames. In opt mode, any positive
// stack_frames_to_skip is treated as 0, since we don't know which
// function calls will be inlined by the compiler and need to be
// conservative.
GTEST_API_ void Log(LogSeverity severity, const std::string& message,
int stack_frames_to_skip) {
if (!LogIsVisible(severity))
return;
// Ensures that logs from different threads don't interleave.
MutexLock l(&g_log_mutex);
// "using ::std::cout;" doesn't work with Symbian's STLport, where cout is a
// macro.
if (severity == kWarning) {
// Prints a GMOCK WARNING marker to make the warnings easily searchable.
std::cout << "\nGMOCK WARNING:";
}
// Pre-pends a new-line to message if it doesn't start with one.
if (message.empty() || message[0] != '\n') {
std::cout << "\n";
}
std::cout << message;
if (stack_frames_to_skip >= 0) {
#ifdef NDEBUG
// In opt mode, we have to be conservative and skip no stack frame.
const int actual_to_skip = 0;
#else
// In dbg mode, we can do what the caller tell us to do (plus one
// for skipping this function's stack frame).
const int actual_to_skip = stack_frames_to_skip + 1;
#endif // NDEBUG
// Appends a new-line to message if it doesn't end with one.
if (!message.empty() && *message.rbegin() != '\n') {
std::cout << "\n";
}
std::cout << "Stack trace:\n"
<< ::testing::internal::GetCurrentOsStackTraceExceptTop(
::testing::UnitTest::GetInstance(), actual_to_skip);
}
std::cout << ::std::flush;
}
GTEST_API_ WithoutMatchers GetWithoutMatchers() { return WithoutMatchers(); }
GTEST_API_ void IllegalDoDefault(const char* file, int line) {
internal::Assert(
false, file, line,
"You are using DoDefault() inside a composite action like "
"DoAll() or WithArgs(). This is not supported for technical "
"reasons. Please instead spell out the default action, or "
"assign the default action to an Action variable and use "
"the variable in various places.");
}
} // namespace internal
} // namespace testing<|fim▁end|>
|
// Returns the global failure reporter. Will create a
// GoogleTestFailureReporter and return it the first time called.
GTEST_API_ FailureReporterInterface* GetFailureReporter() {
// Points to the global failure reporter used by Google Mock. gcc
|
<|file_name|>TodoItem.tsx<|end_file_name|><|fim▁begin|>import * as React from "react"
import { Component } from "react"
interface TodoProps {
onClick: () => void,
completed: boolean,
text: string
}
export class TodoItem extends Component<TodoProps, void> {
public render() {
return (
<li
onClick={() => this.props.onClick()}
style={{
cursor: "pointer",
textDecoration: this.props.completed ? "line-through" : "none"<|fim▁hole|> </li>
)
}
}<|fim▁end|>
|
}}
>
{this.props.text}
|
<|file_name|>internal_unstable.rs<|end_file_name|><|fim▁begin|>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(staged_api, allow_internal_unstable)]
#![staged_api]
#![stable(feature = "stable", since = "1.0.0")]
#[unstable(feature = "function")]
pub fn unstable() {}
#[stable(feature = "stable", since = "1.0.0")]
pub struct Foo {
#[unstable(feature = "struct_field")]
pub x: u8
}
#[allow_internal_unstable]
#[macro_export]
macro_rules! call_unstable_allow {<|fim▁hole|>
#[allow_internal_unstable]
#[macro_export]
macro_rules! construct_unstable_allow {
($e: expr) => {
$crate::Foo { x: $e }
}
}
#[allow_internal_unstable]
#[macro_export]
macro_rules! pass_through_allow {
($e: expr) => { $e }
}
#[macro_export]
macro_rules! call_unstable_noallow {
() => { $crate::unstable() }
}
#[macro_export]
macro_rules! construct_unstable_noallow {
($e: expr) => {
$crate::Foo { x: $e }
}
}
#[macro_export]
macro_rules! pass_through_noallow {
($e: expr) => { $e }
}<|fim▁end|>
|
() => { $crate::unstable() }
}
|
<|file_name|>ff_select_support_class_tests.py<|end_file_name|><|fim▁begin|># Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from selenium import webdriver
from selenium.test.selenium.webdriver.common import select_class_tests
from selenium.test.selenium.webdriver.common.webserver import SimpleWebServer
def setup_module(module):
webserver = SimpleWebServer()
webserver.start()
FirefoxSelectElementHandlingTests.webserver = webserver
FirefoxSelectElementHandlingTests.driver = webdriver.Firefox()
class FirefoxSelectElementHandlingTests(select_class_tests.WebDriverSelectSupportTests):
pass
<|fim▁hole|> FirefoxSelectElementHandlingTests.webserver.stop()<|fim▁end|>
|
def teardown_module(module):
FirefoxSelectElementHandlingTests.driver.quit()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.