prompt
large_stringlengths 70
991k
| completion
large_stringlengths 0
1.02k
|
---|---|
<|file_name|>remapping.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
import rospy
from geometry_msgs.msg import Twist
def callback_function(data):
#FILL IN HERE
global publisher_name, msg
msg.linear.x = -data.linear.x
msg.angular.z = -data.angular.z
publisher_name.publish(msg)
def subscriber_name():
# Initialize node
rospy.init_node('subscriber_name', anonymous=True)
#FILL IN HERE
global publisher_name,msg
msg = Twist()
publisher_name = rospy.Publisher('remapped_topic_name',Twist,queue_size = 16)<|fim▁hole|> rospy.Rate(30)
rospy.spin()
if __name__ == '__main__':
try:
subscriber_name()
except rospy.ROSInterruptException:
pass<|fim▁end|> | rospy.Subscriber('turtle1/cmd_vel', Twist, callback_function) |
<|file_name|>searchView.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2011 Deepin, Inc.
# 2011 Wang Yong
#
# Author: Wang Yong <[email protected]>
# Maintainer: Wang Yong <[email protected]>
#
# 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
# 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<|fim▁hole|># You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from appItem import *
from constant import *
from draw import *
from lang import __, getDefaultLanguage
import appView
import gtk
import pango
import utils
class SearchItem(DownloadItem):
'''Application item.'''
MAX_CHARS = 50
VERSION_MAX_CHARS = 30
APP_LEFT_PADDING_X = 5
STAR_PADDING_X = 2
NORMAL_PADDING_X = 2
VOTE_PADDING_X = 3
VOTE_PADDING_Y = 1
LIKE_PADDING_X = 10
RATE_PADDING_X = 3
SIZE_LABEL_WIDTH = 60
def __init__(self, appInfo, switchStatus, downloadQueue,
entryDetailCallback, sendVoteCallback, index, getSelectIndex, setSelectIndex,
launchApplicationCallback):
'''Init for application item.'''
DownloadItem.__init__(self, appInfo, switchStatus, downloadQueue)
self.appInfo = appInfo
self.entryDetailCallback = entryDetailCallback
self.sendVoteCallback = sendVoteCallback
self.index = index
self.setSelectIndex = setSelectIndex
self.launchApplicationCallback = launchApplicationCallback
# Init.
self.itemBox = gtk.HBox()
self.itemEventBox = gtk.EventBox()
self.itemEventBox.connect("button-press-event", self.clickItem)
drawListItem(self.itemEventBox, index, getSelectIndex)
self.itemFrame = gtk.Alignment()
self.itemFrame.set(0.0, 0.5, 1.0, 1.0)
self.appBasicView = AppBasicView(self.appInfo, 200 + APP_BASIC_WIDTH_ADJUST, self.itemBox, self.entryDetailView)
# Widget that status will change.
self.installingProgressbar = None
self.installingFeedbackLabel = None
self.upgradingProgressbar = None
self.upgradingFeedbackLabel = None
# Connect components.
self.itemBox.pack_start(self.appBasicView.align, True, True, self.APP_LEFT_PADDING_X)
self.appAdditionBox = gtk.HBox()
self.appAdditionAlign = gtk.Alignment()
self.appAdditionAlign.set(1.0, 0.5, 0.0, 0.0)
self.appAdditionAlign.add(self.appAdditionBox)
self.itemBox.pack_start(self.appAdditionAlign, False, False)
self.initAdditionStatus()
self.itemEventBox.add(self.itemBox)
self.itemFrame.add(self.itemEventBox)
self.itemFrame.show_all()
def entryDetailView(self):
'''Entry detail view.'''
self.entryDetailCallback(PAGE_REPO, self.appInfo)
def clickItem(self, widget, event):
'''Click item.'''
if utils.isDoubleClick(event):
self.entryDetailView()
else:
self.setSelectIndex(self.index)
def initAdditionStatus(self):
'''Add addition status.'''
status = self.appInfo.status
if status in [APP_STATE_NORMAL, APP_STATE_UPGRADE, APP_STATE_INSTALLED]:
self.initNormalStatus()
elif status == APP_STATE_DOWNLOADING:
self.initDownloadingStatus(self.appAdditionBox)
elif status == APP_STATE_DOWNLOAD_PAUSE:
self.initDownloadPauseStatus(self.appAdditionBox)
elif status == APP_STATE_INSTALLING:
self.initInstallingStatus()
elif status == APP_STATE_UPGRADING:
self.initUpgradingStatus()
self.itemFrame.show_all()
def initNormalStatus(self):
'''Init normal status.'''
pkg = self.appInfo.pkg
# Clean right box first.
utils.containerRemoveAll(self.appAdditionBox)
# Add application vote information.
self.appVoteView = VoteView(
self.appInfo, PAGE_REPO,
self.sendVoteCallback)
self.appAdditionBox.pack_start(self.appVoteView.eventbox, False, False)
# Add application size.
size = utils.getPkgSize(pkg)
appSizeLabel = DynamicSimpleLabel(
self.appAdditionBox,
utils.formatFileSize(size),
appTheme.getDynamicColor("appSize"),
LABEL_FONT_SIZE,
)
appSize = appSizeLabel.getLabel()
appSize.set_size_request(self.SIZE_LABEL_WIDTH, -1)
appSize.set_alignment(1.0, 0.5)
self.appAdditionBox.pack_start(appSize, False, False, self.LIKE_PADDING_X)
# Add action button.
(actionButtonBox, actionButtonAlign) = createActionButton()
self.appAdditionBox.pack_start(actionButtonAlign, False, False)
if self.appInfo.status == APP_STATE_NORMAL:
(appButton, appButtonAlign) = newActionButton(
"install", 0.5, 0.5,
"cell", False, __("Action Install"), BUTTON_FONT_SIZE_SMALL, "buttonFont"
)
appButton.connect("button-release-event", lambda widget, event: self.switchToDownloading())
actionButtonBox.pack_start(appButtonAlign)
elif self.appInfo.status == APP_STATE_UPGRADE:
(appButton, appButtonAlign) = newActionButton(
"update", 0.5, 0.5,
"cell", False, __("Action Update"), BUTTON_FONT_SIZE_SMALL, "buttonFont"
)
appButton.connect("button-release-event", lambda widget, event: self.switchToDownloading())
actionButtonBox.pack_start(appButtonAlign)
else:
execPath = self.appInfo.execPath
if execPath:
(appButton, appButtonAlign) = newActionButton(
"update", 0.5, 0.5,
"cell", False, __("Action Startup"), BUTTON_FONT_SIZE_SMALL, "buttonFont"
)
appButton.connect("button-release-event", lambda widget, event: self.launchApplicationCallback(execPath))
actionButtonBox.pack_start(appButtonAlign)
else:
appInstalledDynamicLabel = DynamicSimpleLabel(
actionButtonBox,
__("Action Installed"),
appTheme.getDynamicColor("installed"),
LABEL_FONT_SIZE,
)
appInstalledLabel = appInstalledDynamicLabel.getLabel()
buttonImage = appTheme.getDynamicPixbuf("cell/update_hover.png").getPixbuf()
appInstalledLabel.set_size_request(buttonImage.get_width(), buttonImage.get_height())
actionButtonBox.pack_start(appInstalledLabel)
def updateVoteView(self, starLevel, commentNum):
'''Update vote view.'''
if self.appInfo.status in [APP_STATE_NORMAL, APP_STATE_UPGRADE, APP_STATE_INSTALLED] and self.appVoteView != None:
self.appVoteView.updateVote(starLevel, commentNum)
self.appBasicView.updateCommentNum(commentNum)
class SearchView(appView.AppView):
'''Search view.'''
def __init__(self, appNum, getListFunc, switchStatus, downloadQueue,
entryDetailCallback, sendVoteCallback, fetchVoteCallback,
launchApplicationCallback):
'''Init for search view.'''
appView.AppView.__init__(self, appNum, PAGE_REPO, True)
# Init.
self.getListFunc = getListFunc
self.switchStatus = switchStatus
self.downloadQueue = downloadQueue
self.entryDetailCallback = entryDetailCallback
self.sendVoteCallback = sendVoteCallback
self.fetchVoteCallback = fetchVoteCallback
self.launchApplicationCallback = launchApplicationCallback
self.itemDict = {}
self.show()
def updateSearch(self, appNum):
'''Update view.'''
self.appNum = appNum
self.calculateMaxPageIndex()
self.pageIndex = 1
self.show()
def createAppList(self, appList):
'''Create application list.'''
# Init.
itemPaddingY = 5
box = gtk.VBox()
for (index, appInfo) in enumerate(appList):
appItem = SearchItem(appInfo, self.switchStatus, self.downloadQueue,
self.entryDetailCallback,
self.sendVoteCallback,
index, self.getSelectItemIndex, self.setSelectItemIndex,
self.launchApplicationCallback)
box.pack_start(appItem.itemFrame, False, False)
self.itemDict[utils.getPkgName(appItem.appInfo.pkg)] = appItem
return box<|fim▁end|> | # GNU General Public License for more details.
# |
<|file_name|>BlockJukeBox.java<|end_file_name|><|fim▁begin|>package net.minecraft.src;
public class BlockJukeBox extends BlockContainer
{
protected BlockJukeBox(int par1)
{
super(par1, Material.wood);
this.setCreativeTab(CreativeTabs.tabDecorations);
}
/**
* Called upon block activation (right click on the block.)
*/
public boolean onBlockActivated(World par1World, int par2, int par3, int par4, EntityPlayer par5EntityPlayer, int par6, float par7, float par8, float par9)
{
if (par1World.getBlockMetadata(par2, par3, par4) == 0)
{<|fim▁hole|> {
this.ejectRecord(par1World, par2, par3, par4);
return true;
}
}
/**
* Insert the specified music disc in the jukebox at the given coordinates
*/
public void insertRecord(World par1World, int par2, int par3, int par4, ItemStack par5ItemStack)
{
if (!par1World.isRemote)
{
TileEntityRecordPlayer var6 = (TileEntityRecordPlayer)par1World.getBlockTileEntity(par2, par3, par4);
if (var6 != null)
{
var6.func_96098_a(par5ItemStack.copy());
par1World.setBlockMetadata(par2, par3, par4, 1, 2);
}
}
}
/**
* Ejects the current record inside of the jukebox.
*/
public void ejectRecord(World par1World, int par2, int par3, int par4)
{
if (!par1World.isRemote)
{
TileEntityRecordPlayer var5 = (TileEntityRecordPlayer)par1World.getBlockTileEntity(par2, par3, par4);
if (var5 != null)
{
ItemStack var6 = var5.func_96097_a();
if (var6 != null)
{
par1World.playAuxSFX(1005, par2, par3, par4, 0);
par1World.playRecord((String)null, par2, par3, par4);
var5.func_96098_a((ItemStack)null);
par1World.setBlockMetadata(par2, par3, par4, 0, 2);
float var7 = 0.7F;
double var8 = (double)(par1World.rand.nextFloat() * var7) + (double)(1.0F - var7) * 0.5D;
double var10 = (double)(par1World.rand.nextFloat() * var7) + (double)(1.0F - var7) * 0.2D + 0.6D;
double var12 = (double)(par1World.rand.nextFloat() * var7) + (double)(1.0F - var7) * 0.5D;
ItemStack var14 = var6.copy();
EntityItem var15 = new EntityItem(par1World, (double)par2 + var8, (double)par3 + var10, (double)par4 + var12, var14);
var15.delayBeforeCanPickup = 10;
par1World.spawnEntityInWorld(var15);
}
}
}
}
/**
* ejects contained items into the world, and notifies neighbours of an update, as appropriate
*/
public void breakBlock(World par1World, int par2, int par3, int par4, int par5, int par6)
{
this.ejectRecord(par1World, par2, par3, par4);
super.breakBlock(par1World, par2, par3, par4, par5, par6);
}
/**
* Drops the block items with a specified chance of dropping the specified items
*/
public void dropBlockAsItemWithChance(World par1World, int par2, int par3, int par4, int par5, float par6, int par7)
{
if (!par1World.isRemote)
{
super.dropBlockAsItemWithChance(par1World, par2, par3, par4, par5, par6, 0);
}
}
/**
* Returns a new instance of a block's tile entity class. Called on placing the block.
*/
public TileEntity createNewTileEntity(World par1World)
{
return new TileEntityRecordPlayer();
}
/**
* If this returns true, then comparators facing away from this block will use the value from
* getComparatorInputOverride instead of the actual redstone signal strength.
*/
public boolean hasComparatorInputOverride()
{
return true;
}
/**
* If hasComparatorInputOverride returns true, the return value from this is used instead of the redstone signal
* strength when this block inputs to a comparator.
*/
public int getComparatorInputOverride(World par1World, int par2, int par3, int par4, int par5)
{
ItemStack var6 = ((TileEntityRecordPlayer)par1World.getBlockTileEntity(par2, par3, par4)).func_96097_a();
return var6 == null ? 0 : var6.itemID + 1 - Item.record13.itemID;
}
}<|fim▁end|> | return false;
}
else |
<|file_name|>Datasource.java<|end_file_name|><|fim▁begin|>package Cheiron.Datasource;
import java.util.Map;
public abstract class Datasource {
<|fim▁hole|> public abstract Map<String, Map<String, String>> getData() throws Exception;
public Object get(String field) throws Exception {
return this.getClass().getDeclaredField(field).get(this);
}
public void set(String field, Object value) throws Exception {
this.getClass().getDeclaredField(field).set(this, value);
}
}<|fim▁end|> | |
<|file_name|>test_cfgparser.py<|end_file_name|><|fim▁begin|>import ConfigParser
import StringIO
from test_support import TestFailed, verify
def basic(src):
print "Testing basic accessors..."
cf = ConfigParser.ConfigParser()
sio = StringIO.StringIO(src)
cf.readfp(sio)
L = cf.sections()
L.sort()
verify(L == [r'Commented Bar',
r'Foo Bar',
r'Internationalized Stuff',
r'Section\with$weird%characters[' '\t',
r'Spacey Bar',
],
"unexpected list of section names")
# The use of spaces in the section names serves as a regression test for
# SourceForge bug #115357.
# http://sourceforge.net/bugs/?func=detailbug&group_id=5470&bug_id=115357
verify(cf.get('Foo Bar', 'foo', raw=1) == 'bar')
verify(cf.get('Spacey Bar', 'foo', raw=1) == 'bar')
verify(cf.get('Commented Bar', 'foo', raw=1) == 'bar')
verify('__name__' not in cf.options("Foo Bar"),
'__name__ "option" should not be exposed by the API!')
# Make sure the right things happen for remove_option();
# added to include check for SourceForge bug #123324:
verify(cf.remove_option('Foo Bar', 'foo'),
"remove_option() failed to report existance of option")
verify(not cf.has_option('Foo Bar', 'foo'),
"remove_option() failed to remove option")
verify(not cf.remove_option('Foo Bar', 'foo'),
"remove_option() failed to report non-existance of option"
" that was removed")
try:
cf.remove_option('No Such Section', 'foo')
except ConfigParser.NoSectionError:
pass
else:
raise TestFailed(
"remove_option() failed to report non-existance of option"
" that never existed")
def case_sensitivity():
print "Testing case sensitivity..."
cf = ConfigParser.ConfigParser()
cf.add_section("A")
cf.add_section("a")
L = cf.sections()
L.sort()
verify(L == ["A", "a"])
cf.set("a", "B", "value")
verify(cf.options("a") == ["b"])
verify(cf.get("a", "b", raw=1) == "value",
"could not locate option, expecting case-insensitive option names")
verify(cf.has_option("a", "b"))
cf.set("A", "A-B", "A-B value")
for opt in ("a-b", "A-b", "a-B", "A-B"):
verify(cf.has_option("A", opt),
"has_option() returned false for option which should exist")
verify(cf.options("A") == ["a-b"])
verify(cf.options("a") == ["b"])
cf.remove_option("a", "B")
verify(cf.options("a") == [])
# SF bug #432369:
cf = ConfigParser.ConfigParser()
sio = StringIO.StringIO("[MySection]\nOption: first line\n\tsecond line\n")
cf.readfp(sio)
verify(cf.options("MySection") == ["option"])
verify(cf.get("MySection", "Option") == "first line\nsecond line")
def boolean(src):
print "Testing interpretation of boolean Values..."
cf = ConfigParser.ConfigParser()
sio = StringIO.StringIO(src)
cf.readfp(sio)
for x in range(1, 5):
verify(cf.getboolean('BOOLTEST', 't%d' % (x)) == 1)
for x in range(1, 5):
verify(cf.getboolean('BOOLTEST', 'f%d' % (x)) == 0)
for x in range(1, 5):
try:
cf.getboolean('BOOLTEST', 'e%d' % (x))
except ValueError:
pass
else:
raise TestFailed(
"getboolean() failed to report a non boolean value")
def interpolation(src):
print "Testing value interpolation..."
cf = ConfigParser.ConfigParser({"getname": "%(__name__)s"})
sio = StringIO.StringIO(src)
cf.readfp(sio)
verify(cf.get("Foo", "getname") == "Foo")
verify(cf.get("Foo", "bar") == "something with interpolation (1 step)")
verify(cf.get("Foo", "bar9")
== "something with lots of interpolation (9 steps)")
verify(cf.get("Foo", "bar10")
== "something with lots of interpolation (10 steps)")
expect_get_error(cf, ConfigParser.InterpolationDepthError, "Foo", "bar11")
def parse_errors():
print "Testing parse errors..."
expect_parse_error(ConfigParser.ParsingError,
"""[Foo]\n extra-spaces: splat\n""")
expect_parse_error(ConfigParser.ParsingError,
"""[Foo]\n extra-spaces= splat\n""")
expect_parse_error(ConfigParser.ParsingError,
"""[Foo]\noption-without-value\n""")
expect_parse_error(ConfigParser.ParsingError,
"""[Foo]\n:value-without-option-name\n""")
expect_parse_error(ConfigParser.ParsingError,
"""[Foo]\n=value-without-option-name\n""")
expect_parse_error(ConfigParser.MissingSectionHeaderError,
"""No Section!\n""")
def query_errors():
print "Testing query interface..."
cf = ConfigParser.ConfigParser()
verify(cf.sections() == [],
"new ConfigParser should have no defined sections")
verify(not cf.has_section("Foo"),
"new ConfigParser should have no acknowledged sections")
try:
cf.options("Foo")
except ConfigParser.NoSectionError, e:
pass
else:
raise TestFailed(
"Failed to catch expected NoSectionError from options()")
try:
cf.set("foo", "bar", "value")
except ConfigParser.NoSectionError, e:
pass
else:
raise TestFailed("Failed to catch expected NoSectionError from set()")
expect_get_error(cf, ConfigParser.NoSectionError, "foo", "bar")
cf.add_section("foo")
expect_get_error(cf, ConfigParser.NoOptionError, "foo", "bar")
def weird_errors():
print "Testing miscellaneous error conditions..."
cf = ConfigParser.ConfigParser()
cf.add_section("Foo")
try:
cf.add_section("Foo")
except ConfigParser.DuplicateSectionError, e:
pass
else:
raise TestFailed("Failed to catch expected DuplicateSectionError")
def expect_get_error(cf, exctype, section, option, raw=0):
try:
cf.get(section, option, raw=raw)
except exctype, e:
pass<|fim▁hole|>def expect_parse_error(exctype, src):
cf = ConfigParser.ConfigParser()
sio = StringIO.StringIO(src)
try:
cf.readfp(sio)
except exctype, e:
pass
else:
raise TestFailed("Failed to catch expected " + exctype.__name__)
basic(r"""
[Foo Bar]
foo=bar
[Spacey Bar]
foo = bar
[Commented Bar]
foo: bar ; comment
[Section\with$weird%characters[""" '\t' r"""]
[Internationalized Stuff]
foo[bg]: Bulgarian
foo=Default
foo[en]=English
foo[de]=Deutsch
""")
case_sensitivity()
boolean(r"""
[BOOLTEST]
T1=1
T2=TRUE
T3=True
T4=oN
T5=yes
F1=0
F2=FALSE
F3=False
F4=oFF
F5=nO
E1=2
E2=foo
E3=-1
E4=0.1
E5=FALSE AND MORE
""")
interpolation(r"""
[Foo]
bar=something %(with1)s interpolation (1 step)
bar9=something %(with9)s lots of interpolation (9 steps)
bar10=something %(with10)s lots of interpolation (10 steps)
bar11=something %(with11)s lots of interpolation (11 steps)
with11=%(with10)s
with10=%(with9)s
with9=%(with8)s
with8=%(with7)s
with7=%(with6)s
with6=%(with5)s
with5=%(with4)s
with4=%(with3)s
with3=%(with2)s
with2=%(with1)s
with1=with
[Mutual Recursion]
foo=%(bar)s
bar=%(foo)s
""")
parse_errors()
query_errors()
weird_errors()<|fim▁end|> | else:
raise TestFailed("Failed to catch expected " + exctype.__name__)
|
<|file_name|>WizardPanelNotFoundException.java<|end_file_name|><|fim▁begin|>package fr.inserm.ihm;
public class WizardPanelNotFoundException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = -1947507532224487459L;
public WizardPanelNotFoundException() {
super();
}<|fim▁hole|>
}<|fim▁end|> | |
<|file_name|>scenes.rs<|end_file_name|><|fim▁begin|>// +--------------------------------------------------------------------------+
// | Copyright 2016 Matthew D. Steele <[email protected]> |
// | |
// | This file is part of System Syzygy. |
// | |
// | System Syzygy 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. |
// | |
// | System Syzygy 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 details. |
// | |
// | You should have received a copy of the GNU General Public License along |
// | with System Syzygy. If not, see <http://www.gnu.org/licenses/>. |
// +--------------------------------------------------------------------------+
use crate::elements::{Ast, Scene, TalkPos, TalkStyle};
use crate::gui::{Rect, Resources, Sound};
// ========================================================================= //
const UGRENT: i32 = 2;
const YTTRIS: i32 = 1;
// ========================================================================= //
#[cfg_attr(rustfmt, rustfmt_skip)]
pub fn compile_intro_scene(resources: &mut Resources) -> Scene {
let ast = vec![
Ast::Seq(vec![
Ast::SetBg("plane_and_simple"),
Ast::Place(YTTRIS, "chars/yttris", 0, (444, 288)),
Ast::Wait(0.75),
Ast::Place(UGRENT, "chars/ugrent", 0, (-16, 304)),<|fim▁hole|> Ast::Sound(Sound::talk_hi()),
Ast::Talk(YTTRIS, TalkStyle::Normal, TalkPos::NW,
"Hey there, Ugrent!\n\
How's it going?"),
]),
Ast::Seq(vec![
Ast::Sound(Sound::talk_lo()),
Ast::Talk(UGRENT, TalkStyle::Normal, TalkPos::NE,
"Yttris. You know anything about\n\
the character mismatches in the\n\
security checkpoint back there?"),
]),
Ast::Seq(vec![
Ast::Sound(Sound::talk_hi()),
Ast::Talk(YTTRIS, TalkStyle::Normal, TalkPos::NW,
"Huh? No. What are\n\
you talking about?"),
]),
Ast::Seq(vec![
Ast::Sound(Sound::talk_lo()),
Ast::Talk(UGRENT, TalkStyle::Normal, TalkPos::NE,
"Never mind. What are\n\
you working on here?"),
]),
Ast::Seq(vec![
Ast::Sound(Sound::talk_hi()),
Ast::Talk(YTTRIS, TalkStyle::Normal, TalkPos::NW,
"Oh, this thing? This is the ship's\n\
forward planar switchboard."),
]),
Ast::Seq(vec![
Ast::Sound(Sound::talk_hi()),
Ast::Talk(YTTRIS, TalkStyle::Normal, TalkPos::NW,
"That explosion shook all the\n\
connectors loose, so now I have\n\
to redo them all. Booorrring!"),
]),
Ast::Seq(vec![
Ast::Slide(YTTRIS, (436, 288), true, true, 0.25),
Ast::Sound(Sound::talk_hi()),
Ast::Talk(YTTRIS, TalkStyle::Normal, TalkPos::NW,
"Oooh, maybe I should wire\n\
them all up $ibackwards$r this\n\
time! $iThat$r would be fun!"),
]),
Ast::Seq(vec![
Ast::Slide(UGRENT, (250, 304), true, true, 0.25),
Ast::Sound(Sound::talk_hi()),
Ast::Talk(UGRENT, TalkStyle::Normal, TalkPos::NE,
"What!? No! Yttris, right\n\
now we need to get the ship\n\
back to normal. This is no\n\
time for improvising!"),
]),
Ast::Seq(vec![
Ast::Sound(Sound::talk_hi()),
Ast::Talk(YTTRIS, TalkStyle::Normal, TalkPos::NW,
"Aw, you're no fun."),
]),
Ast::Seq(vec![
Ast::Sound(Sound::talk_lo()),
Ast::Talk(UGRENT, TalkStyle::Normal, TalkPos::NE,
"Look, the last thing we need\n\
here is another explosion because\n\
we didn't do things by the book."),
]),
Ast::Seq(vec![
Ast::Slide(UGRENT, (200, 304), true, true, 0.75),
Ast::Sound(Sound::talk_hi()),
Ast::Talk(UGRENT, TalkStyle::Normal, TalkPos::NE,
"Let's just take this\n\
thing in stages and do\n\
them one at a time."),
]),
];
Ast::compile_scene(resources, ast)
}
// ========================================================================= //
#[cfg_attr(rustfmt, rustfmt_skip)]
pub fn compile_ugrent_midscene(resources: &mut Resources) -> (i32, Scene) {
let ast = vec![
Ast::Seq(vec![
Ast::Sound(Sound::talk_hi()),
Ast::Talk(UGRENT, TalkStyle::Normal, TalkPos::NE,
"Each node has to connect\n\
to each other node, so\n\
there can only be so\n\
many stages, right?"),
]),
];
(UGRENT, Ast::compile_scene(resources, ast))
}
#[cfg_attr(rustfmt, rustfmt_skip)]
pub fn compile_yttris_midscene(resources: &mut Resources) -> (i32, Scene) {
let ast = vec![
Ast::Seq(vec![
Ast::Sound(Sound::talk_hi()),
Ast::Talk(YTTRIS, TalkStyle::Normal, TalkPos::NW,
"C'mon, this is an undirected\n\
graph we're talking about.\n\
Wiring it backwards doesn't\n\
even make a difference!"),
]),
Ast::Seq(vec![
Ast::Sound(Sound::talk_lo()),
Ast::Talk(UGRENT, TalkStyle::Normal, TalkPos::NE,
"Look, let's just put\n\
it back the same\n\
way it was before."),
]),
];
(YTTRIS, Ast::compile_scene(resources, ast))
}
// ========================================================================= //
#[cfg_attr(rustfmt, rustfmt_skip)]
pub fn compile_outro_scene(resources: &mut Resources, visible: Rect) -> Scene {
let ast = vec![
Ast::Seq(vec![
Ast::Sound(Sound::solve_puzzle_chime()),
Ast::Wait(1.0),
Ast::Sound(Sound::talk_hi()),
Ast::Talk(YTTRIS, TalkStyle::Normal, TalkPos::NW,
"There! All fixed."),
]),
Ast::Seq(vec![
Ast::Slide(UGRENT, (388, 304), true, true, 1.25),
Ast::Sound(Sound::talk_hi()),
Ast::Talk(UGRENT, TalkStyle::Normal, TalkPos::NW,
"Good. Keep working on\n\
repairs. I need to continue\n\
my security sweep."),
]),
Ast::Par(vec![
Ast::Seq(vec![
Ast::Sound(Sound::small_jump()),
Ast::Jump(UGRENT, (436, 288), 0.5),
Ast::Sound(Sound::small_jump()),
Ast::Jump(UGRENT, (484, 272), 0.5),
Ast::Slide(UGRENT, (592, 272), false, false, 0.5),
Ast::SetPos(UGRENT, (visible.right() + 16, 272)),
]),
Ast::Seq(vec![
Ast::Wait(0.75),
Ast::Sound(Sound::talk_hi()),
Ast::Talk(YTTRIS, TalkStyle::Normal, TalkPos::NW,
"Will do!"),
]),
]),
Ast::Seq(vec![
Ast::Wait(0.5),
Ast::Sound(Sound::small_jump()),
Ast::Jump(YTTRIS, (388, 304), 0.5),
Ast::Slide(YTTRIS, (284, 304), true, true, 0.75),
Ast::Sound(Sound::talk_hi()),
Ast::Talk(YTTRIS, TalkStyle::Normal, TalkPos::NE,
"He's gone! Now's\n\
my chance to flip\n\
it all backwards!"),
]),
Ast::Par(vec![
Ast::Seq(vec![
Ast::Sound(Sound::talk_hi()),
Ast::Talk(UGRENT, TalkStyle::Normal, TalkPos::W,
"I heard that!"),
]),
Ast::Seq(vec![
Ast::Wait(0.5),
Ast::Sound(Sound::talk_hi()),
Ast::Talk(YTTRIS, TalkStyle::Normal, TalkPos::NE,
"Haha! I'm just\n\
$ikidding$r, Ugrent!"),
]),
]),
Ast::Seq(vec![
Ast::Sound(Sound::talk_thought()),
Ast::Talk(YTTRIS, TalkStyle::Thought, TalkPos::NE,
"No sense of\n\
humor at all..."),
]),
Ast::Seq(vec![
Ast::Remove(UGRENT),
Ast::Slide(YTTRIS, (-16, 304), true, false, 1.0),
Ast::Remove(YTTRIS),
Ast::Wait(1.0),
Ast::Queue(1, 7),
Ast::Wait(0.1),
Ast::Queue(0, 0),
Ast::Queue(1, 6),
Ast::Wait(0.1),
Ast::Queue(0, 1),
Ast::Queue(1, 5),
Ast::Wait(0.1),
Ast::Queue(0, 2),
Ast::Queue(1, 4),
Ast::Wait(0.1),
Ast::Queue(0, 3),
Ast::Queue(1, 3),
Ast::Wait(0.1),
Ast::Queue(0, 4),
Ast::Queue(1, 2),
Ast::Wait(0.1),
Ast::Queue(0, 5),
Ast::Queue(1, 1),
Ast::Wait(0.1),
Ast::Queue(1, 0),
Ast::Wait(1.0),
]),
];
Ast::compile_scene(resources, ast)
}
// ========================================================================= //<|fim▁end|> | Ast::Slide(UGRENT, (220, 304), false, true, 1.25), |
<|file_name|>aldryn_config.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from aldryn_client import forms
<|fim▁hole|> plugin_name = forms.CharField('Plugin name', initial='Facebook Comments')
plugin_template = forms.CharField('Plugin Template', initial='djangocms_fbcomments/default.html')
app_id = forms.CharField('Facebook App ID', required=False)
def to_settings(self, data, settings):
settings['DJANGOCMS_FBCOMMENTS_PLUGIN_MODULE'] = data['plugin_module']
settings['DJANGOCMS_FBCOMMENTS_PLUGIN_NAME'] = data['plugin_name']
settings['DJANGOCMS_FBCOMMENTS_PLUGIN_TEMPLATE'] = data['plugin_template']
settings['DJANGOCMS_FBCOMMENTS_APP_ID'] = data['app_id']
return settings<|fim▁end|> | class Form(forms.BaseForm):
plugin_module = forms.CharField('Plugin module name', initial='Generic') |
<|file_name|>bitcoin_mn.ts<|end_file_name|><|fim▁begin|><TS language="mn" version="2.1">
<context>
<name>AddressBookPage</name>
<message>
<source>Create a new address</source>
<translation>Шинэ хаяг нээх</translation>
</message>
<message>
<source>&New</source>
<translation>&Шинэ</translation>
</message>
<message>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Одоогоор сонгогдсон байгаа хаягуудыг сануулах</translation>
</message>
<message>
<source>&Copy</source>
<translation>&Хуулах</translation>
</message>
<message>
<source>C&lose</source>
<translation>&Хаах</translation>
</message>
<message>
<source>Delete the currently selected address from the list</source>
<translation>Одоо сонгогдсон байгаа хаягуудыг жагсаалтаас устгах</translation>
</message>
<message>
<source>Enter address or label to search</source>
<translation>Хайлт хийхийн тулд хаяг эсвэл шошгыг оруул</translation>
</message>
<message>
<source>Export the data in the current tab to a file</source>
<translation>Сонгогдсон таб дээрхи дата-г экспортлох</translation>
</message>
<message>
<source>&Export</source>
<translation>&Экспортдлох</translation>
</message>
<message>
<source>&Delete</source>
<translation>&Устгах</translation>
</message>
<message>
<source>Choose the address to send coins to</source>
<translation>Зооснуудыг илгээх хаягийг сонгоно уу</translation>
</message>
<message>
<source>Choose the address to receive coins with</source>
<translation>Зооснуудыг хүлээн авах хаягийг сонгоно уу</translation>
</message>
<message>
<source>C&hoose</source>
<translation>С&онго</translation>
</message>
<message>
<source>Sending addresses</source>
<translation>Илгээх хаягууд</translation>
</message>
<message>
<source>Receiving addresses</source>
<translation>Хүлээн авах хаяг</translation>
</message>
<message>
<source>These are your Qtum addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation>Эдгээр Биткойн хаягууд нь илгээх хаягууд. Хүлээн авах хаяг болон тоо хэмжээг илгээхээсээ өмнө сайн нягталж үзэж байна уу</translation>
</message>
<message>
<source>&Copy Address</source>
<translation>Хаягийг &Хуулбарлах</translation>
</message>
<message>
<source>Copy &Label</source>
<translation>&Шошгыг хуулбарлах</translation>
</message>
<message>
<source>&Edit</source>
<translation>&Ѳѳрчлѳх</translation>
</message>
<message>
<source>Export Address List</source>
<translation>Экспорт хийх хаягуудын жагсаалт</translation>
</message>
<message>
<source>Comma separated file (*.csv)</source>
<translation>Таслалаар тусгаарлагдсан хүснэгтэн файл (.csv)</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<source>Label</source>
<translation>Шошго</translation>
</message>
<message>
<source>Address</source>
<translation>Хаяг</translation>
</message>
<message>
<source>(no label)</source>
<translation>(шошгогүй)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<source>Enter passphrase</source>
<translation>Нууц үгийг оруул</translation>
</message>
<message>
<source>New passphrase</source>
<translation>Шинэ нууц үг</translation>
</message>
<message>
<source>Repeat new passphrase</source>
<translation>Шинэ нууц үгийг давтана уу</translation>
</message>
<message>
<source>Encrypt wallet</source>
<translation>Түрүйвчийг цоожлох</translation>
</message>
<message>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Энэ үйлдэлийг гүйцэтгэхийн тулд та нууц үгээрээ түрүйвчийн цоожийг тайлах хэрэгтэй</translation>
</message>
<message>
<source>Unlock wallet</source>
<translation>Түрүйвчийн цоожийг тайлах</translation>
</message>
<message>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Энэ үйлдэлийг гүйцэтгэхийн тулд та эхлээд түрүйвчийн нууц үгийг оруулж цоожийг тайлах шаардлагтай.</translation>
</message>
<message>
<source>Decrypt wallet</source>
<translation>Түрүйвчийн цоожийг устгах</translation>
</message>
<message>
<source>Change passphrase</source>
<translation>Нууц үгийг солих</translation>
</message>
<message>
<source>Confirm wallet encryption</source>
<translation>Түрүйвчийн цоожийг баталгаажуулах</translation>
</message>
<message>
<source>Wallet encrypted</source>
<translation>Түрүйвч цоожлогдлоо</translation>
</message>
<message>
<source>Wallet encryption failed</source>
<translation>Түрүйвчийн цоожлол амжилттай болсонгүй</translation>
</message>
<message>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Түрүйвчийн цоожлол дотоод алдаанаас үүдэн амжилттай болсонгүй. Түрүйвч цоожлогдоогүй байна.</translation>
</message>
<message>
<source>The supplied passphrases do not match.</source>
<translation>Таны оруулсан нууц үг таарсангүй</translation>
</message>
<message>
<source>Wallet unlock failed</source>
<translation>Түрүйвчийн цоож тайлагдсангүй</translation>
</message>
<message>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Таны оруулсан түрүйвчийн цоожийг тайлах нууц үг буруу байна</translation>
</message>
<message>
<source>Wallet decryption failed</source>
<translation>Түрүйвчийн цоож амжилттай устгагдсангүй</translation>
</message>
<message>
<source>Wallet passphrase was successfully changed.</source>
<translation>Түрүйвчийн нууц үг амжилттай ѳѳр</translation>
</message>
</context>
<context>
<name>BanTableModel</name>
</context>
<context>
<name>QtumGUI</name>
<message>
<source>Sign &message...</source>
<translation>&Зурвас хавсаргах...</translation>
</message>
<message>
<source>Synchronizing with network...</source>
<translation>Сүлжээтэй тааруулж байна...</translation>
</message>
<message>
<source>&Transactions</source>
<translation>Гүйлгээнүүд</translation>
</message>
<message>
<source>Browse transaction history</source>
<translation>Гүйлгээнүүдийн түүхийг харах</translation>
</message>
<message>
<source>E&xit</source>
<translation>Гарах</translation>
</message>
<message>
<source>Quit application</source>
<translation>Програмаас Гарах</translation>
</message>
<message>
<source>About &Qt</source>
<translation>&Клиентийн тухай</translation>
</message>
<message>
<source>Show information about Qt</source>
<translation>Клиентийн тухай мэдээллийг харуул</translation>
</message>
<message>
<source>&Options...</source>
<translation>&Сонголтууд...</translation>
</message>
<message>
<source>&Encrypt Wallet...</source>
<translation>&Түрүйвчийг цоожлох...</translation>
</message>
<message>
<source>&Backup Wallet...</source>
<translation>&Түрүйвчийг Жоорлох...</translation>
</message>
<message>
<source>&Change Passphrase...</source>
<translation>&Нууц Үгийг Солих...</translation>
</message>
<message>
<source>Change the passphrase used for wallet encryption</source>
<translation>Түрүйвчийг цоожлох нууц үгийг солих</translation>
</message>
<message>
<source>&Show / Hide</source>
<translation>&Харуул / Нуу</translation>
</message>
<message>
<source>&File</source>
<translation>&Файл</translation>
</message>
<message>
<source>&Settings</source>
<translation>&Тохиргоо</translation>
</message>
<message>
<source>&Help</source>
<translation>&Тусламж</translation>
</message>
<message>
<source>Error</source>
<translation>Алдаа</translation>
</message>
<message>
<source>Information</source>
<translation>Мэдээллэл</translation>
</message>
<message>
<source>Up to date</source>
<translation>Шинэчлэгдсэн</translation>
</message>
<message>
<source>Sent transaction</source>
<translation>Гадагшаа гүйлгээ</translation>
</message>
<message>
<source>Incoming transaction</source>
<translation>Дотогшоо гүйлгээ</translation>
</message>
<message>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Түрүйвч <b>цоожтой</b> ба одоогоор цоож <b>онгорхой</b> байна</translation>
</message>
<message>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Түрүйвч <b>цоожтой</b> ба одоогоор цоож <b>хаалттай</b> байна</translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<source>Amount:</source>
<translation>Хэмжээ:</translation>
</message>
<message>
<source>Fee:</source>
<translation>Тѳлбѳр:</translation>
</message>
<message>
<source>Amount</source>
<translation>Хэмжээ</translation>
</message>
<message>
<source>Date</source>
<translation>Огноо</translation>
</message>
<message>
<source>Confirmed</source>
<translation>Баталгаажлаа</translation>
</message>
<message>
<source>Copy address</source>
<translation>Хаягийг санах</translation>
</message>
<message>
<source>Copy label</source>
<translation>Шошгыг санах</translation>
</message>
<message>
<source>Copy amount</source>
<translation>Хэмжээг санах</translation>
</message>
<message>
<source>Copy change</source>
<translation>Ѳѳрчлѳлтийг санах</translation>
</message>
<message>
<source>(no label)</source>
<translation>(шошгогүй)</translation>
</message>
<message>
<source>(change)</source>
<translation>(ѳѳрчлѳх)</translation>
</message>
</context>
<context>
<name>CreateWalletActivity</name>
</context>
<context>
<name>CreateWalletDialog</name>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<source>Edit Address</source>
<translation>Хаягийг ѳѳрчлѳх</translation>
</message>
<message>
<source>&Label</source>
<translation>&Шошго</translation>
</message>
<message>
<source>&Address</source>
<translation>&Хаяг</translation>
</message>
<message>
<source>New sending address</source>
<translation>Шинэ явуулах хаяг</translation>
</message>
<message>
<source>Edit receiving address</source>
<translation>Хүлээн авах хаягийг ѳѳрчлѳх</translation>
</message>
<message>
<source>Edit sending address</source>
<translation>Явуулах хаягийг ѳѳрчлѳх</translation>
</message>
<message>
<source>Could not unlock wallet.</source>
<translation>Түрүйвчийн цоожийг тайлж чадсангүй</translation>
</message>
<message>
<source>New key generation failed.</source>
<translation>Шинэ түлхүүр амжилттай гарсангүй</translation>
</message>
</context>
<context>
<name>FreespaceChecker</name>
</context>
<context>
<name>HelpMessageDialog</name>
<message>
<source>version</source>
<translation>хувилбар</translation>
</message>
</context>
<context>
<name>Intro</name>
<message>
<source>Qtum</source>
<translation>Биткойн</translation>
</message>
<message>
<source>Error</source>
<translation>Алдаа</translation>
</message>
</context>
<context>
<name>ModalOverlay</name>
<message>
<source>Last block time</source>
<translation>Сүүлийн блокийн хугацаа</translation>
</message>
</context>
<context>
<name>OpenURIDialog</name>
</context>
<context>
<name>OpenWalletActivity</name>
</context>
<context>
<name>OptionsDialog</name>
<message>
<source>Options</source>
<translation>Сонголтууд</translation>
</message>
<message>
<source>IP address of the proxy (e.g. IPv4: 127.0.0.1 / IPv6: ::1)</source>
<translation>проксигийн IP хаяг (жишээ нь: IPv4: 127.0.0.1 / IPv6: ::1)</translation>
</message>
<message>
<source>&Network</source>
<translation>Сүлжээ</translation>
</message>
<message>
<source>W&allet</source>
<translation>Түрүйвч</translation>
</message>
<message>
<source>Client restart required to activate changes.</source>
<translation>Ѳѳрчлѳлтүүдийг идэвхижүүлхийн тулд клиентийг ахин эхлүүлэх шаардлагтай</translation><|fim▁hole|> <translation>Алдаа</translation>
</message>
<message>
<source>This change would require a client restart.</source>
<translation>Энэ ѳѳрчлѳлтийг оруулахын тулд кли1нт програмыг ахин эхлүүлэх шаардлагтай</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<source>Available:</source>
<translation>Хэрэглэж болох хэмжээ:</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
</context>
<context>
<name>PeerTableModel</name>
</context>
<context>
<name>QObject</name>
<message>
<source>Amount</source>
<translation>Хэмжээ</translation>
</message>
<message>
<source>N/A</source>
<translation>Алга Байна</translation>
</message>
<message>
<source>unknown</source>
<translation>үл мэдэгдэх</translation>
</message>
</context>
<context>
<name>QRImageWidget</name>
<message>
<source>PNG Image (*.png)</source>
<translation>PNG форматын зураг (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<source>N/A</source>
<translation>Алга Байна</translation>
</message>
<message>
<source>Client version</source>
<translation>Клиентийн хувилбар</translation>
</message>
<message>
<source>&Information</source>
<translation>&Мэдээллэл</translation>
</message>
<message>
<source>General</source>
<translation>Ерѳнхий</translation>
</message>
<message>
<source>Network</source>
<translation>Сүлжээ</translation>
</message>
<message>
<source>Name</source>
<translation>Нэр</translation>
</message>
<message>
<source>Number of connections</source>
<translation>Холболтын тоо</translation>
</message>
<message>
<source>Block chain</source>
<translation>Блокийн цуваа</translation>
</message>
<message>
<source>Current number of blocks</source>
<translation>Одоогийн блокийн тоо</translation>
</message>
<message>
<source>Last block time</source>
<translation>Сүүлийн блокийн хугацаа</translation>
</message>
<message>
<source>&Open</source>
<translation>&Нээх</translation>
</message>
<message>
<source>&Console</source>
<translation>&Консол</translation>
</message>
<message>
<source>Clear console</source>
<translation>Консолыг цэвэрлэх</translation>
</message>
</context>
<context>
<name>ReceiveCoinsDialog</name>
<message>
<source>&Amount:</source>
<translation>Хэмжээ:</translation>
</message>
<message>
<source>&Label:</source>
<translation>&Шошго:</translation>
</message>
<message>
<source>&Message:</source>
<translation>Зурвас:</translation>
</message>
<message>
<source>Show</source>
<translation>Харуул</translation>
</message>
<message>
<source>Remove the selected entries from the list</source>
<translation>Сонгогдсон ѳгѳгдлүүдийг устгах</translation>
</message>
<message>
<source>Remove</source>
<translation>Устгах</translation>
</message>
<message>
<source>Copy label</source>
<translation>Шошгыг санах</translation>
</message>
<message>
<source>Copy message</source>
<translation>Зурвасыг санах</translation>
</message>
<message>
<source>Copy amount</source>
<translation>Хэмжээг санах</translation>
</message>
</context>
<context>
<name>ReceiveRequestDialog</name>
<message>
<source>Copy &Address</source>
<translation>Хаягийг &Хуулбарлах</translation>
</message>
<message>
<source>Address</source>
<translation>Хаяг</translation>
</message>
<message>
<source>Amount</source>
<translation>Хэмжээ</translation>
</message>
<message>
<source>Label</source>
<translation>Шошго</translation>
</message>
<message>
<source>Message</source>
<translation>Зурвас</translation>
</message>
<message>
<source>Wallet</source>
<translation>Түрүйвч</translation>
</message>
</context>
<context>
<name>RecentRequestsTableModel</name>
<message>
<source>Date</source>
<translation>Огноо</translation>
</message>
<message>
<source>Label</source>
<translation>Шошго</translation>
</message>
<message>
<source>Message</source>
<translation>Зурвас</translation>
</message>
<message>
<source>(no label)</source>
<translation>(шошгогүй)</translation>
</message>
<message>
<source>(no message)</source>
<translation>(зурвас алга)</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<source>Send Coins</source>
<translation>Зоос явуулах</translation>
</message>
<message>
<source>automatically selected</source>
<translation>автоматаар сонгогдсон</translation>
</message>
<message>
<source>Insufficient funds!</source>
<translation>Таны дансны үлдэгдэл хүрэлцэхгүй байна!</translation>
</message>
<message>
<source>Amount:</source>
<translation>Хэмжээ:</translation>
</message>
<message>
<source>Fee:</source>
<translation>Тѳлбѳр:</translation>
</message>
<message>
<source>Send to multiple recipients at once</source>
<translation>Нэгэн зэрэг олон хүлээн авагчруу явуулах</translation>
</message>
<message>
<source>Add &Recipient</source>
<translation>&Хүлээн авагчийг Нэмэх</translation>
</message>
<message>
<source>Clear &All</source>
<translation>&Бүгдийг Цэвэрлэ</translation>
</message>
<message>
<source>Balance:</source>
<translation>Баланс:</translation>
</message>
<message>
<source>Confirm the send action</source>
<translation>Явуулах үйлдлийг баталгаажуулна уу</translation>
</message>
<message>
<source>S&end</source>
<translation>Яв&уул</translation>
</message>
<message>
<source>Copy amount</source>
<translation>Хэмжээг санах</translation>
</message>
<message>
<source>Copy change</source>
<translation>Ѳѳрчлѳлтийг санах</translation>
</message>
<message>
<source>or</source>
<translation>эсвэл</translation>
</message>
<message>
<source>Confirm send coins</source>
<translation>Зоос явуулахыг баталгаажуулна уу</translation>
</message>
<message>
<source>The amount to pay must be larger than 0.</source>
<translation>Тѳлѳх хэмжээ 0.-оос их байх ёстой</translation>
</message>
<message>
<source>The amount exceeds your balance.</source>
<translation>Энэ хэмжээ таны балансаас хэтэрсэн байна.</translation>
</message>
<message>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>Гүйлгээний тѳлбѳр %1-ийг тооцхоор нийт дүн нь таны балансаас хэтрээд байна.</translation>
</message>
<message>
<source>Warning: Invalid Qtum address</source>
<translation>Анхаар:Буруу Биткойны хаяг байна</translation>
</message>
<message>
<source>(no label)</source>
<translation>(шошгогүй)</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<source>A&mount:</source>
<translation>Дүн:</translation>
</message>
<message>
<source>Pay &To:</source>
<translation>Тѳлѳх &хаяг:</translation>
</message>
<message>
<source>&Label:</source>
<translation>&Шошго:</translation>
</message>
<message>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<source>Paste address from clipboard</source>
<translation>Копидсон хаягийг буулгах</translation>
</message>
<message>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<source>Message:</source>
<translation>Зурвас:</translation>
</message>
<message>
<source>Pay To:</source>
<translation>Тѳлѳх хаяг:</translation>
</message>
</context>
<context>
<name>ShutdownWindow</name>
<message>
<source>Do not shut down the computer until this window disappears.</source>
<translation>Энэ цонхыг хаагдтал компьютерээ бүү унтраагаарай</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<source>Paste address from clipboard</source>
<translation>Копидсон хаягийг буулгах</translation>
</message>
<message>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<source>Clear &All</source>
<translation>&Бүгдийг Цэвэрлэ</translation>
</message>
</context>
<context>
<name>TrafficGraphWidget</name>
</context>
<context>
<name>TransactionDesc</name>
<message>
<source>Open until %1</source>
<translation>%1 хүртэл нээлттэй</translation>
</message>
<message>
<source>%1/unconfirmed</source>
<translation>%1/баталгаажаагүй</translation>
</message>
<message>
<source>%1 confirmations</source>
<translation>%1 баталгаажилтууд</translation>
</message>
<message>
<source>Date</source>
<translation>Огноо</translation>
</message>
<message>
<source>unknown</source>
<translation>үл мэдэгдэх</translation>
</message>
<message>
<source>Message</source>
<translation>Зурвас</translation>
</message>
<message>
<source>Transaction ID</source>
<translation>Тодорхойлолт</translation>
</message>
<message>
<source>Amount</source>
<translation>Хэмжээ</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<source>This pane shows a detailed description of the transaction</source>
<translation>Гүйлгээний дэлгэрэнгүйг энэ бичил цонх харуулж байна</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<source>Date</source>
<translation>Огноо</translation>
</message>
<message>
<source>Type</source>
<translation>Тѳрѳл</translation>
</message>
<message>
<source>Label</source>
<translation>Шошго</translation>
</message>
<message>
<source>Open until %1</source>
<translation>%1 хүртэл нээлттэй</translation>
</message>
<message>
<source>Unconfirmed</source>
<translation>Баталгаажаагүй</translation>
</message>
<message>
<source>Confirmed (%1 confirmations)</source>
<translation>Баталгаажлаа (%1 баталгаажилт)</translation>
</message>
<message>
<source>Conflicted</source>
<translation>Зѳрчилдлѳѳ</translation>
</message>
<message>
<source>Generated but not accepted</source>
<translation>Үүсгэгдсэн гэхдээ хүлээн авагдаагүй</translation>
</message>
<message>
<source>Received with</source>
<translation>Хүлээн авсан хаяг</translation>
</message>
<message>
<source>Received from</source>
<translation>Хүлээн авагдсан хаяг</translation>
</message>
<message>
<source>Sent to</source>
<translation>Явуулсан хаяг</translation>
</message>
<message>
<source>Payment to yourself</source>
<translation>Ѳѳрлүүгээ хийсэн тѳлбѳр</translation>
</message>
<message>
<source>Mined</source>
<translation>Олборлогдсон</translation>
</message>
<message>
<source>(n/a)</source>
<translation>(алга байна)</translation>
</message>
<message>
<source>(no label)</source>
<translation>(шошгогүй)</translation>
</message>
<message>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Гүйлгээний байдал. Энд хулганыг авчирч баталгаажуулалтын тоог харна уу.</translation>
</message>
<message>
<source>Date and time that the transaction was received.</source>
<translation>Гүйлгээг хүлээн авсан огноо ба цаг.</translation>
</message>
<message>
<source>Type of transaction.</source>
<translation>Гүйлгээний тѳрѳл</translation>
</message>
<message>
<source>Amount removed from or added to balance.</source>
<translation>Балансаас авагдсан болон нэмэгдсэн хэмжээ.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<source>All</source>
<translation>Бүгд</translation>
</message>
<message>
<source>Today</source>
<translation>Ѳнѳѳдѳр</translation>
</message>
<message>
<source>This week</source>
<translation>Энэ долоо хоног</translation>
</message>
<message>
<source>This month</source>
<translation>Энэ сар</translation>
</message>
<message>
<source>Last month</source>
<translation>Ѳнгѳрсѳн сар</translation>
</message>
<message>
<source>This year</source>
<translation>Энэ жил</translation>
</message>
<message>
<source>Received with</source>
<translation>Хүлээн авсан хаяг</translation>
</message>
<message>
<source>Sent to</source>
<translation>Явуулсан хаяг</translation>
</message>
<message>
<source>To yourself</source>
<translation>Ѳѳрлүүгээ</translation>
</message>
<message>
<source>Mined</source>
<translation>Олборлогдсон</translation>
</message>
<message>
<source>Other</source>
<translation>Бусад</translation>
</message>
<message>
<source>Min amount</source>
<translation>Хамгийн бага хэмжээ</translation>
</message>
<message>
<source>Copy address</source>
<translation>Хаягийг санах</translation>
</message>
<message>
<source>Copy label</source>
<translation>Шошгыг санах</translation>
</message>
<message>
<source>Copy amount</source>
<translation>Хэмжээг санах</translation>
</message>
<message>
<source>Edit label</source>
<translation>Шошгыг ѳѳрчлѳх</translation>
</message>
<message>
<source>Show transaction details</source>
<translation>Гүйлгээний дэлгэрэнгүйг харуул</translation>
</message>
<message>
<source>Comma separated file (*.csv)</source>
<translation>Таслалаар тусгаарлагдсан хүснэгтэн файл (.csv)</translation>
</message>
<message>
<source>Confirmed</source>
<translation>Баталгаажлаа</translation>
</message>
<message>
<source>Date</source>
<translation>Огноо</translation>
</message>
<message>
<source>Type</source>
<translation>Тѳрѳл</translation>
</message>
<message>
<source>Label</source>
<translation>Шошго</translation>
</message>
<message>
<source>Address</source>
<translation>Хаяг</translation>
</message>
<message>
<source>ID</source>
<translation>Тодорхойлолт</translation>
</message>
<message>
<source>The transaction history was successfully saved to %1.</source>
<translation>Гүйлгээнүй түүхийг %1-д амжилттай хадгаллаа.</translation>
</message>
<message>
<source>to</source>
<translation>-рүү/руу</translation>
</message>
</context>
<context>
<name>UnitDisplayStatusBarControl</name>
</context>
<context>
<name>WalletController</name>
</context>
<context>
<name>WalletFrame</name>
<message>
<source>No wallet has been loaded.</source>
<translation>Ямар ч түрүйвч ачааллагдсангүй.</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<source>Send Coins</source>
<translation>Зоос явуулах</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<source>&Export</source>
<translation>&Экспортдлох</translation>
</message>
<message>
<source>Export the data in the current tab to a file</source>
<translation>Сонгогдсон таб дээрхи дата-г экспортлох</translation>
</message>
</context>
<context>
<name>qtum-core</name>
<message>
<source>Insufficient funds</source>
<translation>Таны дансны үлдэгдэл хүрэлцэхгүй байна</translation>
</message>
<message>
<source>Loading block index...</source>
<translation>Блокийн индексүүдийг ачааллаж байна...</translation>
</message>
<message>
<source>Loading wallet...</source>
<translation>Түрүйвчийг ачааллаж байна...</translation>
</message>
<message>
<source>Rescanning...</source>
<translation>Ахин уншиж байна...</translation>
</message>
<message>
<source>Done loading</source>
<translation>Ачааллаж дууслаа</translation>
</message>
</context>
</TS><|fim▁end|> | </message>
<message>
<source>Error</source> |
<|file_name|>__init__.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.
"""Request body validating middleware for OpenStack Identity resources."""
from keystone.common.validation import validators
def lazy_validate(request_body_schema, resource_to_validate):
"""A non-decorator way to validate a request, to be used inline.
:param request_body_schema: a schema to validate the resource reference
:param resource_to_validate: dictionary to validate
:raises keystone.exception.ValidationError: if `resource_to_validate` is
None. (see wrapper method below).
:raises TypeError: at decoration time when the expected resource to
validate isn't found in the decorated method's
signature
"""
schema_validator = validators.SchemaValidator(request_body_schema)
schema_validator.validate(resource_to_validate)<|fim▁hole|> """Clone a property schema into one that is nullable.
:param dict property_schema: schema to clone into a nullable schema
:returns: a new dict schema
"""
# TODO(dstanek): deal with the case where type is already a list; we don't
# do that yet so I'm not wasting time on it
new_schema = property_schema.copy()
new_schema['type'] = [property_schema['type'], 'null']
# NOTE(kmalloc): If enum is specified (such as our boolean case) ensure we
# add null to the enum as well so that null can be passed/validated as
# expected. Without adding to the enum, null will not validate as enum is
# explicitly listing valid values. According to the JSON Schema
# specification, the values must be unique in the enum array.
if 'enum' in new_schema and None not in new_schema['enum']:
# In the enum the 'null' is NoneType
new_schema['enum'].append(None)
return new_schema<|fim▁end|> |
def nullable(property_schema): |
<|file_name|>jquery-ui.js<|end_file_name|><|fim▁begin|>/*! jQuery UI - v1.10.3 - 2013-05-03
* http://jqueryui.com
* Includes: jquery.ui.core.js, jquery.ui.widget.js, jquery.ui.mouse.js, jquery.ui.draggable.js, jquery.ui.droppable.js, jquery.ui.resizable.js, jquery.ui.selectable.js, jquery.ui.sortable.js, jquery.ui.effect.js, jquery.ui.accordion.js, jquery.ui.autocomplete.js, jquery.ui.button.js, jquery.ui.datepicker.js, jquery.ui.dialog.js, jquery.ui.effect-blind.js, jquery.ui.effect-bounce.js, jquery.ui.effect-clip.js, jquery.ui.effect-drop.js, jquery.ui.effect-explode.js, jquery.ui.effect-fade.js, jquery.ui.effect-fold.js, jquery.ui.effect-highlight.js, jquery.ui.effect-pulsate.js, jquery.ui.effect-scale.js, jquery.ui.effect-shake.js, jquery.ui.effect-slide.js, jquery.ui.effect-transfer.js, jquery.ui.menu.js, jquery.ui.position.js, jquery.ui.progressbar.js, jquery.ui.slider.js, jquery.ui.spinner.js, jquery.ui.tabs.js, jquery.ui.tooltip.js
* Copyright 2013 jQuery Foundation and other contributors; Licensed MIT */
(function( $, undefined ) {
var uuid = 0,
runiqueId = /^ui-id-\d+$/;
// $.ui might exist from components with no dependencies, e.g., $.ui.position
$.ui = $.ui || {};
$.extend( $.ui, {
version: "1.10.3",
keyCode: {
BACKSPACE: 8,
COMMA: 188,
DELETE: 46,
DOWN: 40,
END: 35,
ENTER: 13,
ESCAPE: 27,
HOME: 36,
LEFT: 37,
NUMPAD_ADD: 107,
NUMPAD_DECIMAL: 110,
NUMPAD_DIVIDE: 111,
NUMPAD_ENTER: 108,
NUMPAD_MULTIPLY: 106,
NUMPAD_SUBTRACT: 109,
PAGE_DOWN: 34,
PAGE_UP: 33,
PERIOD: 190,
RIGHT: 39,
SPACE: 32,
TAB: 9,
UP: 38
}
});
// plugins
$.fn.extend({
focus: (function( orig ) {
return function( delay, fn ) {
return typeof delay === "number" ?
this.each(function() {
var elem = this;
setTimeout(function() {
$( elem ).focus();
if ( fn ) {
fn.call( elem );
}
}, delay );
}) :
orig.apply( this, arguments );
};
})( $.fn.focus ),
scrollParent: function() {
var scrollParent;
if (($.ui.ie && (/(static|relative)/).test(this.css("position"))) || (/absolute/).test(this.css("position"))) {
scrollParent = this.parents().filter(function() {
return (/(relative|absolute|fixed)/).test($.css(this,"position")) && (/(auto|scroll)/).test($.css(this,"overflow")+$.css(this,"overflow-y")+$.css(this,"overflow-x"));
}).eq(0);
} else {
scrollParent = this.parents().filter(function() {
return (/(auto|scroll)/).test($.css(this,"overflow")+$.css(this,"overflow-y")+$.css(this,"overflow-x"));
}).eq(0);
}
return (/fixed/).test(this.css("position")) || !scrollParent.length ? $(document) : scrollParent;
},
zIndex: function( zIndex ) {
if ( zIndex !== undefined ) {
return this.css( "zIndex", zIndex );
}
if ( this.length ) {
var elem = $( this[ 0 ] ), position, value;
while ( elem.length && elem[ 0 ] !== document ) {
// Ignore z-index if position is set to a value where z-index is ignored by the browser
// This makes behavior of this function consistent across browsers
// WebKit always returns auto if the element is positioned
position = elem.css( "position" );
if ( position === "absolute" || position === "relative" || position === "fixed" ) {
// IE returns 0 when zIndex is not specified
// other browsers return a string
// we ignore the case of nested elements with an explicit value of 0
// <div style="z-index: -10;"><div style="z-index: 0;"></div></div>
value = parseInt( elem.css( "zIndex" ), 10 );
if ( !isNaN( value ) && value !== 0 ) {
return value;
}
}
elem = elem.parent();
}
}
return 0;
},
uniqueId: function() {
return this.each(function() {
if ( !this.id ) {
this.id = "ui-id-" + (++uuid);
}
});
},
removeUniqueId: function() {
return this.each(function() {
if ( runiqueId.test( this.id ) ) {
$( this ).removeAttr( "id" );
}
});
}
});
// selectors
function focusable( element, isTabIndexNotNaN ) {
var map, mapName, img,
nodeName = element.nodeName.toLowerCase();
if ( "area" === nodeName ) {
map = element.parentNode;
mapName = map.name;
if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) {
return false;
}
img = $( "img[usemap=#" + mapName + "]" )[0];
return !!img && visible( img );
}
return ( /input|select|textarea|button|object/.test( nodeName ) ?
!element.disabled :
"a" === nodeName ?
element.href || isTabIndexNotNaN :
isTabIndexNotNaN) &&
// the element and all of its ancestors must be visible
visible( element );
}
function visible( element ) {
return $.expr.filters.visible( element ) &&
!$( element ).parents().addBack().filter(function() {
return $.css( this, "visibility" ) === "hidden";
}).length;
}
$.extend( $.expr[ ":" ], {
data: $.expr.createPseudo ?
$.expr.createPseudo(function( dataName ) {
return function( elem ) {
return !!$.data( elem, dataName );
};
}) :
// support: jQuery <1.8
function( elem, i, match ) {
return !!$.data( elem, match[ 3 ] );
},
focusable: function( element ) {
return focusable( element, !isNaN( $.attr( element, "tabindex" ) ) );
},
tabbable: function( element ) {
var tabIndex = $.attr( element, "tabindex" ),
isTabIndexNaN = isNaN( tabIndex );
return ( isTabIndexNaN || tabIndex >= 0 ) && focusable( element, !isTabIndexNaN );
}
});
// support: jQuery <1.8
if ( !$( "<a>" ).outerWidth( 1 ).jquery ) {
$.each( [ "Width", "Height" ], function( i, name ) {
var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ],
type = name.toLowerCase(),
orig = {
innerWidth: $.fn.innerWidth,
innerHeight: $.fn.innerHeight,
outerWidth: $.fn.outerWidth,
outerHeight: $.fn.outerHeight
};
function reduce( elem, size, border, margin ) {
$.each( side, function() {
size -= parseFloat( $.css( elem, "padding" + this ) ) || 0;
if ( border ) {
size -= parseFloat( $.css( elem, "border" + this + "Width" ) ) || 0;
}
if ( margin ) {
size -= parseFloat( $.css( elem, "margin" + this ) ) || 0;
}
});
return size;
}
$.fn[ "inner" + name ] = function( size ) {
if ( size === undefined ) {
return orig[ "inner" + name ].call( this );
}
return this.each(function() {
$( this ).css( type, reduce( this, size ) + "px" );
});
};
$.fn[ "outer" + name] = function( size, margin ) {
if ( typeof size !== "number" ) {
return orig[ "outer" + name ].call( this, size );
}
return this.each(function() {
$( this).css( type, reduce( this, size, true, margin ) + "px" );
});
};
});
}
// support: jQuery <1.8
if ( !$.fn.addBack ) {
$.fn.addBack = function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter( selector )
);
};
}
// support: jQuery 1.6.1, 1.6.2 (http://bugs.jquery.com/ticket/9413)
if ( $( "<a>" ).data( "a-b", "a" ).removeData( "a-b" ).data( "a-b" ) ) {
$.fn.removeData = (function( removeData ) {
return function( key ) {
if ( arguments.length ) {
return removeData.call( this, $.camelCase( key ) );
} else {
return removeData.call( this );
}
};
})( $.fn.removeData );
}
// deprecated
$.ui.ie = !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() );
$.support.selectstart = "onselectstart" in document.createElement( "div" );
$.fn.extend({
disableSelection: function() {
return this.bind( ( $.support.selectstart ? "selectstart" : "mousedown" ) +
".ui-disableSelection", function( event ) {
event.preventDefault();
});
},
enableSelection: function() {
return this.unbind( ".ui-disableSelection" );
}
});
$.extend( $.ui, {
// $.ui.plugin is deprecated. Use $.widget() extensions instead.
plugin: {
add: function( module, option, set ) {
var i,
proto = $.ui[ module ].prototype;
for ( i in set ) {
proto.plugins[ i ] = proto.plugins[ i ] || [];
proto.plugins[ i ].push( [ option, set[ i ] ] );
}
},
call: function( instance, name, args ) {
var i,
set = instance.plugins[ name ];
if ( !set || !instance.element[ 0 ].parentNode || instance.element[ 0 ].parentNode.nodeType === 11 ) {
return;
}
for ( i = 0; i < set.length; i++ ) {
if ( instance.options[ set[ i ][ 0 ] ] ) {
set[ i ][ 1 ].apply( instance.element, args );
}
}
}
},
// only used by resizable
hasScroll: function( el, a ) {
//If overflow is hidden, the element might have extra content, but the user wants to hide it
if ( $( el ).css( "overflow" ) === "hidden") {
return false;
}
var scroll = ( a && a === "left" ) ? "scrollLeft" : "scrollTop",
has = false;
if ( el[ scroll ] > 0 ) {
return true;
}
// TODO: determine which cases actually cause this to happen
// if the element doesn't have the scroll set, see if it's possible to
// set the scroll
el[ scroll ] = 1;
has = ( el[ scroll ] > 0 );
el[ scroll ] = 0;
return has;
}
});
})( jQuery );
(function( $, undefined ) {
var uuid = 0,
slice = Array.prototype.slice,
_cleanData = $.cleanData;
$.cleanData = function( elems ) {
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
try {
$( elem ).triggerHandler( "remove" );
// http://bugs.jquery.com/ticket/8235
} catch( e ) {}
}
_cleanData( elems );
};
$.widget = function( name, base, prototype ) {
var fullName, existingConstructor, constructor, basePrototype,
// proxiedPrototype allows the provided prototype to remain unmodified
// so that it can be used as a mixin for multiple widgets (#8876)
proxiedPrototype = {},
namespace = name.split( "." )[ 0 ];
name = name.split( "." )[ 1 ];
fullName = namespace + "-" + name;
if ( !prototype ) {
prototype = base;
base = $.Widget;
}
// create selector for plugin
$.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) {
return !!$.data( elem, fullName );
};
$[ namespace ] = $[ namespace ] || {};
existingConstructor = $[ namespace ][ name ];
constructor = $[ namespace ][ name ] = function( options, element ) {
// allow instantiation without "new" keyword
if ( !this._createWidget ) {
return new constructor( options, element );
}
// allow instantiation without initializing for simple inheritance
// must use "new" keyword (the code above always passes args)
if ( arguments.length ) {
this._createWidget( options, element );
}
};
// extend with the existing constructor to carry over any static properties
$.extend( constructor, existingConstructor, {
version: prototype.version,
// copy the object used to create the prototype in case we need to
// redefine the widget later
_proto: $.extend( {}, prototype ),
// track widgets that inherit from this widget in case this widget is
// redefined after a widget inherits from it
_childConstructors: []
});
basePrototype = new base();
// we need to make the options hash a property directly on the new instance
// otherwise we'll modify the options hash on the prototype that we're
// inheriting from
basePrototype.options = $.widget.extend( {}, basePrototype.options );
$.each( prototype, function( prop, value ) {
if ( !$.isFunction( value ) ) {
proxiedPrototype[ prop ] = value;
return;
}
proxiedPrototype[ prop ] = (function() {
var _super = function() {
return base.prototype[ prop ].apply( this, arguments );
},
_superApply = function( args ) {
return base.prototype[ prop ].apply( this, args );
};
return function() {
var __super = this._super,
__superApply = this._superApply,
returnValue;
this._super = _super;
this._superApply = _superApply;
returnValue = value.apply( this, arguments );
this._super = __super;
this._superApply = __superApply;
return returnValue;
};
})();
});
constructor.prototype = $.widget.extend( basePrototype, {
// TODO: remove support for widgetEventPrefix
// always use the name + a colon as the prefix, e.g., draggable:start
// don't prefix for widgets that aren't DOM-based
widgetEventPrefix: existingConstructor ? basePrototype.widgetEventPrefix : name
}, proxiedPrototype, {
constructor: constructor,
namespace: namespace,
widgetName: name,
widgetFullName: fullName
});
// If this widget is being redefined then we need to find all widgets that
// are inheriting from it and redefine all of them so that they inherit from
// the new version of this widget. We're essentially trying to replace one
// level in the prototype chain.
if ( existingConstructor ) {
$.each( existingConstructor._childConstructors, function( i, child ) {
var childPrototype = child.prototype;
// redefine the child widget using the same prototype that was
// originally used, but inherit from the new version of the base
$.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto );
});
// remove the list of existing child constructors from the old constructor
// so the old child constructors can be garbage collected
delete existingConstructor._childConstructors;
} else {
base._childConstructors.push( constructor );
}
$.widget.bridge( name, constructor );
};
$.widget.extend = function( target ) {
var input = slice.call( arguments, 1 ),
inputIndex = 0,
inputLength = input.length,
key,
value;
for ( ; inputIndex < inputLength; inputIndex++ ) {
for ( key in input[ inputIndex ] ) {
value = input[ inputIndex ][ key ];
if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) {
// Clone objects
if ( $.isPlainObject( value ) ) {
target[ key ] = $.isPlainObject( target[ key ] ) ?
$.widget.extend( {}, target[ key ], value ) :
// Don't extend strings, arrays, etc. with objects
$.widget.extend( {}, value );
// Copy everything else by reference
} else {
target[ key ] = value;
}
}
}
}
return target;
};
$.widget.bridge = function( name, object ) {
var fullName = object.prototype.widgetFullName || name;
$.fn[ name ] = function( options ) {
var isMethodCall = typeof options === "string",
args = slice.call( arguments, 1 ),
returnValue = this;
// allow multiple hashes to be passed on init
options = !isMethodCall && args.length ?
$.widget.extend.apply( null, [ options ].concat(args) ) :
options;
if ( isMethodCall ) {
this.each(function() {
var methodValue,
instance = $.data( this, fullName );
if ( !instance ) {
return $.error( "cannot call methods on " + name + " prior to initialization; " +
"attempted to call method '" + options + "'" );
}
if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) {
return $.error( "no such method '" + options + "' for " + name + " widget instance" );
}
methodValue = instance[ options ].apply( instance, args );
if ( methodValue !== instance && methodValue !== undefined ) {
returnValue = methodValue && methodValue.jquery ?
returnValue.pushStack( methodValue.get() ) :
methodValue;
return false;
}
});
} else {
this.each(function() {
var instance = $.data( this, fullName );
if ( instance ) {
instance.option( options || {} )._init();
} else {
$.data( this, fullName, new object( options, this ) );
}
});
}
return returnValue;
};
};
$.Widget = function( /* options, element */ ) {};
$.Widget._childConstructors = [];
$.Widget.prototype = {
widgetName: "widget",
widgetEventPrefix: "",
defaultElement: "<div>",
options: {
disabled: false,
// callbacks
create: null
},
_createWidget: function( options, element ) {
element = $( element || this.defaultElement || this )[ 0 ];
this.element = $( element );
this.uuid = uuid++;
this.eventNamespace = "." + this.widgetName + this.uuid;
this.options = $.widget.extend( {},
this.options,
this._getCreateOptions(),
options );
this.bindings = $();
this.hoverable = $();
this.focusable = $();
if ( element !== this ) {
$.data( element, this.widgetFullName, this );
this._on( true, this.element, {
remove: function( event ) {
if ( event.target === element ) {
this.destroy();
}
}
});
this.document = $( element.style ?
// element within the document
element.ownerDocument :
// element is window or document
element.document || element );
this.window = $( this.document[0].defaultView || this.document[0].parentWindow );
}
this._create();
this._trigger( "create", null, this._getCreateEventData() );
this._init();
},
_getCreateOptions: $.noop,
_getCreateEventData: $.noop,
_create: $.noop,
_init: $.noop,
destroy: function() {
this._destroy();
// we can probably remove the unbind calls in 2.0
// all event bindings should go through this._on()
this.element
.unbind( this.eventNamespace )
// 1.9 BC for #7810
// TODO remove dual storage
.removeData( this.widgetName )
.removeData( this.widgetFullName )
// support: jquery <1.6.3
// http://bugs.jquery.com/ticket/9413
.removeData( $.camelCase( this.widgetFullName ) );
this.widget()
.unbind( this.eventNamespace )
.removeAttr( "aria-disabled" )
.removeClass(
this.widgetFullName + "-disabled " +
"ui-state-disabled" );
// clean up events and states
this.bindings.unbind( this.eventNamespace );
this.hoverable.removeClass( "ui-state-hover" );
this.focusable.removeClass( "ui-state-focus" );
},
_destroy: $.noop,
widget: function() {
return this.element;
},
option: function( key, value ) {
var options = key,
parts,
curOption,
i;
if ( arguments.length === 0 ) {
// don't return a reference to the internal hash
return $.widget.extend( {}, this.options );
}
if ( typeof key === "string" ) {
// handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } }
options = {};
parts = key.split( "." );
key = parts.shift();
if ( parts.length ) {
curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] );
for ( i = 0; i < parts.length - 1; i++ ) {
curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {};
curOption = curOption[ parts[ i ] ];
}
key = parts.pop();
if ( value === undefined ) {
return curOption[ key ] === undefined ? null : curOption[ key ];
}
curOption[ key ] = value;
} else {
if ( value === undefined ) {
return this.options[ key ] === undefined ? null : this.options[ key ];
}
options[ key ] = value;
}
}
this._setOptions( options );
return this;
},
_setOptions: function( options ) {
var key;
for ( key in options ) {
this._setOption( key, options[ key ] );
}
return this;
},
_setOption: function( key, value ) {
this.options[ key ] = value;
if ( key === "disabled" ) {
this.widget()
.toggleClass( this.widgetFullName + "-disabled ui-state-disabled", !!value )
.attr( "aria-disabled", value );
this.hoverable.removeClass( "ui-state-hover" );
this.focusable.removeClass( "ui-state-focus" );
}
return this;
},
enable: function() {
return this._setOption( "disabled", false );
},
disable: function() {
return this._setOption( "disabled", true );
},
_on: function( suppressDisabledCheck, element, handlers ) {
var delegateElement,
instance = this;
// no suppressDisabledCheck flag, shuffle arguments
if ( typeof suppressDisabledCheck !== "boolean" ) {
handlers = element;
element = suppressDisabledCheck;
suppressDisabledCheck = false;
}
// no element argument, shuffle and use this.element
if ( !handlers ) {
handlers = element;
element = this.element;
delegateElement = this.widget();
} else {
// accept selectors, DOM elements
element = delegateElement = $( element );
this.bindings = this.bindings.add( element );
}
$.each( handlers, function( event, handler ) {
function handlerProxy() {
// allow widgets to customize the disabled handling
// - disabled as an array instead of boolean
// - disabled class as method for disabling individual parts
if ( !suppressDisabledCheck &&
( instance.options.disabled === true ||
$( this ).hasClass( "ui-state-disabled" ) ) ) {
return;
}
return ( typeof handler === "string" ? instance[ handler ] : handler )
.apply( instance, arguments );
}
// copy the guid so direct unbinding works
if ( typeof handler !== "string" ) {
handlerProxy.guid = handler.guid =
handler.guid || handlerProxy.guid || $.guid++;
}
var match = event.match( /^(\w+)\s*(.*)$/ ),
eventName = match[1] + instance.eventNamespace,
selector = match[2];
if ( selector ) {
delegateElement.delegate( selector, eventName, handlerProxy );
} else {
element.bind( eventName, handlerProxy );
}
});
},
_off: function( element, eventName ) {
eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) + this.eventNamespace;
element.unbind( eventName ).undelegate( eventName );
},
_delay: function( handler, delay ) {
function handlerProxy() {
return ( typeof handler === "string" ? instance[ handler ] : handler )
.apply( instance, arguments );
}
var instance = this;
return setTimeout( handlerProxy, delay || 0 );
},
_hoverable: function( element ) {
this.hoverable = this.hoverable.add( element );
this._on( element, {
mouseenter: function( event ) {
$( event.currentTarget ).addClass( "ui-state-hover" );
},
mouseleave: function( event ) {
$( event.currentTarget ).removeClass( "ui-state-hover" );
}
});
},
_focusable: function( element ) {
this.focusable = this.focusable.add( element );
this._on( element, {
focusin: function( event ) {
$( event.currentTarget ).addClass( "ui-state-focus" );
},
focusout: function( event ) {
$( event.currentTarget ).removeClass( "ui-state-focus" );
}
});
},
_trigger: function( type, event, data ) {
var prop, orig,
callback = this.options[ type ];
data = data || {};
event = $.Event( event );
event.type = ( type === this.widgetEventPrefix ?
type :
this.widgetEventPrefix + type ).toLowerCase();
// the original event may come from any element
// so we need to reset the target on the new event
event.target = this.element[ 0 ];
// copy original event properties over to the new event
orig = event.originalEvent;
if ( orig ) {
for ( prop in orig ) {
if ( !( prop in event ) ) {
event[ prop ] = orig[ prop ];
}
}
}
this.element.trigger( event, data );
return !( $.isFunction( callback ) &&
callback.apply( this.element[0], [ event ].concat( data ) ) === false ||
event.isDefaultPrevented() );
}
};
$.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) {
$.Widget.prototype[ "_" + method ] = function( element, options, callback ) {
if ( typeof options === "string" ) {
options = { effect: options };
}
var hasOptions,
effectName = !options ?
method :
options === true || typeof options === "number" ?
defaultEffect :
options.effect || defaultEffect;
options = options || {};
if ( typeof options === "number" ) {
options = { duration: options };
}
hasOptions = !$.isEmptyObject( options );
options.complete = callback;
if ( options.delay ) {
element.delay( options.delay );
}
if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) {
element[ method ]( options );
} else if ( effectName !== method && element[ effectName ] ) {
element[ effectName ]( options.duration, options.easing, callback );
} else {
element.queue(function( next ) {
$( this )[ method ]();
if ( callback ) {
callback.call( element[ 0 ] );
}
next();
});
}
};
});
})( jQuery );
(function( $, undefined ) {
var mouseHandled = false;
$( document ).mouseup( function() {
mouseHandled = false;
});
$.widget("ui.mouse", {
version: "1.10.3",
options: {
cancel: "input,textarea,button,select,option",
distance: 1,
delay: 0
},
_mouseInit: function() {
var that = this;
this.element
.bind("mousedown."+this.widgetName, function(event) {
return that._mouseDown(event);
})
.bind("click."+this.widgetName, function(event) {
if (true === $.data(event.target, that.widgetName + ".preventClickEvent")) {
$.removeData(event.target, that.widgetName + ".preventClickEvent");
event.stopImmediatePropagation();
return false;
}
});
this.started = false;
},
// TODO: make sure destroying one instance of mouse doesn't mess with
// other instances of mouse
_mouseDestroy: function() {
this.element.unbind("."+this.widgetName);
if ( this._mouseMoveDelegate ) {
$(document)
.unbind("mousemove."+this.widgetName, this._mouseMoveDelegate)
.unbind("mouseup."+this.widgetName, this._mouseUpDelegate);
}
},
_mouseDown: function(event) {
// don't let more than one widget handle mouseStart
if( mouseHandled ) { return; }
// we may have missed mouseup (out of window)
(this._mouseStarted && this._mouseUp(event));
this._mouseDownEvent = event;
var that = this,
btnIsLeft = (event.which === 1),
// event.target.nodeName works around a bug in IE 8 with
// disabled inputs (#7620)
elIsCancel = (typeof this.options.cancel === "string" && event.target.nodeName ? $(event.target).closest(this.options.cancel).length : false);
if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) {
return true;
}
this.mouseDelayMet = !this.options.delay;
if (!this.mouseDelayMet) {
this._mouseDelayTimer = setTimeout(function() {
that.mouseDelayMet = true;
}, this.options.delay);
}
if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
this._mouseStarted = (this._mouseStart(event) !== false);
if (!this._mouseStarted) {
event.preventDefault();
return true;
}
}
// Click event may never have fired (Gecko & Opera)
if (true === $.data(event.target, this.widgetName + ".preventClickEvent")) {
$.removeData(event.target, this.widgetName + ".preventClickEvent");
}
// these delegates are required to keep context
this._mouseMoveDelegate = function(event) {
return that._mouseMove(event);
};
this._mouseUpDelegate = function(event) {
return that._mouseUp(event);
};
$(document)
.bind("mousemove."+this.widgetName, this._mouseMoveDelegate)
.bind("mouseup."+this.widgetName, this._mouseUpDelegate);
event.preventDefault();
mouseHandled = true;
return true;
},
_mouseMove: function(event) {
// IE mouseup check - mouseup happened when mouse was out of window
if ($.ui.ie && ( !document.documentMode || document.documentMode < 9 ) && !event.button) {
return this._mouseUp(event);
}
if (this._mouseStarted) {
this._mouseDrag(event);
return event.preventDefault();
}
if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
this._mouseStarted =
(this._mouseStart(this._mouseDownEvent, event) !== false);
(this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event));
}
return !this._mouseStarted;
},
_mouseUp: function(event) {
$(document)
.unbind("mousemove."+this.widgetName, this._mouseMoveDelegate)
.unbind("mouseup."+this.widgetName, this._mouseUpDelegate);
if (this._mouseStarted) {
this._mouseStarted = false;
if (event.target === this._mouseDownEvent.target) {
$.data(event.target, this.widgetName + ".preventClickEvent", true);
}
this._mouseStop(event);
}
return false;
},
_mouseDistanceMet: function(event) {
return (Math.max(
Math.abs(this._mouseDownEvent.pageX - event.pageX),
Math.abs(this._mouseDownEvent.pageY - event.pageY)
) >= this.options.distance
);
},
_mouseDelayMet: function(/* event */) {
return this.mouseDelayMet;
},
// These are placeholder methods, to be overriden by extending plugin
_mouseStart: function(/* event */) {},
_mouseDrag: function(/* event */) {},
_mouseStop: function(/* event */) {},
_mouseCapture: function(/* event */) { return true; }
});
})(jQuery);
(function( $, undefined ) {
$.widget("ui.draggable", $.ui.mouse, {
version: "1.10.3",
widgetEventPrefix: "drag",
options: {
addClasses: true,
appendTo: "parent",
axis: false,
connectToSortable: false,
containment: false,
cursor: "auto",
cursorAt: false,
grid: false,
handle: false,
helper: "original",
iframeFix: false,
opacity: false,
refreshPositions: false,
revert: false,
revertDuration: 500,
scope: "default",
scroll: true,
scrollSensitivity: 20,
scrollSpeed: 20,
snap: false,
snapMode: "both",
snapTolerance: 20,
stack: false,
zIndex: false,
// callbacks
drag: null,
start: null,
stop: null
},
_create: function() {
if (this.options.helper === "original" && !(/^(?:r|a|f)/).test(this.element.css("position"))) {
this.element[0].style.position = "relative";
}
if (this.options.addClasses){
this.element.addClass("ui-draggable");
}
if (this.options.disabled){
this.element.addClass("ui-draggable-disabled");
}
this._mouseInit();
},
_destroy: function() {
this.element.removeClass( "ui-draggable ui-draggable-dragging ui-draggable-disabled" );
this._mouseDestroy();
},
_mouseCapture: function(event) {
var o = this.options;
// among others, prevent a drag on a resizable-handle
if (this.helper || o.disabled || $(event.target).closest(".ui-resizable-handle").length > 0) {
return false;
}
//Quit if we're not on a valid handle
this.handle = this._getHandle(event);
if (!this.handle) {
return false;
}
$(o.iframeFix === true ? "iframe" : o.iframeFix).each(function() {
$("<div class='ui-draggable-iframeFix' style='background: #fff;'></div>")
.css({
width: this.offsetWidth+"px", height: this.offsetHeight+"px",
position: "absolute", opacity: "0.001", zIndex: 1000
})
.css($(this).offset())
.appendTo("body");
});
return true;
},
_mouseStart: function(event) {
var o = this.options;
//Create and append the visible helper
this.helper = this._createHelper(event);
this.helper.addClass("ui-draggable-dragging");
//Cache the helper size
this._cacheHelperProportions();
//If ddmanager is used for droppables, set the global draggable
if($.ui.ddmanager) {
$.ui.ddmanager.current = this;
}
/*
* - Position generation -
* This block generates everything position related - it's the core of draggables.
*/
//Cache the margins of the original element
this._cacheMargins();
//Store the helper's css position
this.cssPosition = this.helper.css( "position" );
this.scrollParent = this.helper.scrollParent();
this.offsetParent = this.helper.offsetParent();
this.offsetParentCssPosition = this.offsetParent.css( "position" );
//The element's absolute position on the page minus margins
this.offset = this.positionAbs = this.element.offset();
this.offset = {
top: this.offset.top - this.margins.top,
left: this.offset.left - this.margins.left
};
//Reset scroll cache
this.offset.scroll = false;
$.extend(this.offset, {
click: { //Where the click happened, relative to the element
left: event.pageX - this.offset.left,
top: event.pageY - this.offset.top
},
parent: this._getParentOffset(),
relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper
});
//Generate the original position
this.originalPosition = this.position = this._generatePosition(event);
this.originalPageX = event.pageX;
this.originalPageY = event.pageY;
//Adjust the mouse offset relative to the helper if "cursorAt" is supplied
(o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt));
//Set a containment if given in the options
this._setContainment();
//Trigger event + callbacks
if(this._trigger("start", event) === false) {
this._clear();
return false;
}
//Recache the helper size
this._cacheHelperProportions();
//Prepare the droppable offsets
if ($.ui.ddmanager && !o.dropBehaviour) {
$.ui.ddmanager.prepareOffsets(this, event);
}
this._mouseDrag(event, true); //Execute the drag once - this causes the helper not to be visible before getting its correct position
//If the ddmanager is used for droppables, inform the manager that dragging has started (see #5003)
if ( $.ui.ddmanager ) {
$.ui.ddmanager.dragStart(this, event);
}
return true;
},
_mouseDrag: function(event, noPropagation) {
// reset any necessary cached properties (see #5009)
if ( this.offsetParentCssPosition === "fixed" ) {
this.offset.parent = this._getParentOffset();
}
//Compute the helpers position
this.position = this._generatePosition(event);
this.positionAbs = this._convertPositionTo("absolute");
//Call plugins and callbacks and use the resulting position if something is returned
if (!noPropagation) {
var ui = this._uiHash();
if(this._trigger("drag", event, ui) === false) {
this._mouseUp({});
return false;
}
this.position = ui.position;
}
if(!this.options.axis || this.options.axis !== "y") {
this.helper[0].style.left = this.position.left+"px";
}
if(!this.options.axis || this.options.axis !== "x") {
this.helper[0].style.top = this.position.top+"px";
}
if($.ui.ddmanager) {
$.ui.ddmanager.drag(this, event);
}
return false;
},
_mouseStop: function(event) {
//If we are using droppables, inform the manager about the drop
var that = this,
dropped = false;
if ($.ui.ddmanager && !this.options.dropBehaviour) {
dropped = $.ui.ddmanager.drop(this, event);
}
//if a drop comes from outside (a sortable)
if(this.dropped) {
dropped = this.dropped;
this.dropped = false;
}
//if the original element is no longer in the DOM don't bother to continue (see #8269)
if ( this.options.helper === "original" && !$.contains( this.element[ 0 ].ownerDocument, this.element[ 0 ] ) ) {
return false;
}
if((this.options.revert === "invalid" && !dropped) || (this.options.revert === "valid" && dropped) || this.options.revert === true || ($.isFunction(this.options.revert) && this.options.revert.call(this.element, dropped))) {
$(this.helper).animate(this.originalPosition, parseInt(this.options.revertDuration, 10), function() {
if(that._trigger("stop", event) !== false) {
that._clear();
}
});
} else {
if(this._trigger("stop", event) !== false) {
this._clear();
}
}
return false;
},
_mouseUp: function(event) {
//Remove frame helpers
$("div.ui-draggable-iframeFix").each(function() {
this.parentNode.removeChild(this);
});
//If the ddmanager is used for droppables, inform the manager that dragging has stopped (see #5003)
if( $.ui.ddmanager ) {
$.ui.ddmanager.dragStop(this, event);
}
return $.ui.mouse.prototype._mouseUp.call(this, event);
},
cancel: function() {
if(this.helper.is(".ui-draggable-dragging")) {
this._mouseUp({});
} else {
this._clear();
}
return this;
},
_getHandle: function(event) {
return this.options.handle ?
!!$( event.target ).closest( this.element.find( this.options.handle ) ).length :
true;
},
_createHelper: function(event) {
var o = this.options,
helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event])) : (o.helper === "clone" ? this.element.clone().removeAttr("id") : this.element);
if(!helper.parents("body").length) {
helper.appendTo((o.appendTo === "parent" ? this.element[0].parentNode : o.appendTo));
}
if(helper[0] !== this.element[0] && !(/(fixed|absolute)/).test(helper.css("position"))) {
helper.css("position", "absolute");
}
return helper;
},
_adjustOffsetFromHelper: function(obj) {
if (typeof obj === "string") {
obj = obj.split(" ");
}
if ($.isArray(obj)) {
obj = {left: +obj[0], top: +obj[1] || 0};
}
if ("left" in obj) {
this.offset.click.left = obj.left + this.margins.left;
}
if ("right" in obj) {
this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
}
if ("top" in obj) {
this.offset.click.top = obj.top + this.margins.top;
}
if ("bottom" in obj) {
this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
}
},
_getParentOffset: function() {
//Get the offsetParent and cache its position
var po = this.offsetParent.offset();
// This is a special case where we need to modify a offset calculated on start, since the following happened:
// 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent
// 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that
// the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag
if(this.cssPosition === "absolute" && this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) {
po.left += this.scrollParent.scrollLeft();
po.top += this.scrollParent.scrollTop();
}
//This needs to be actually done for all browsers, since pageX/pageY includes this information
//Ugly IE fix
if((this.offsetParent[0] === document.body) ||
(this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() === "html" && $.ui.ie)) {
po = { top: 0, left: 0 };
}
return {
top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0),
left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0)
};
},
_getRelativeOffset: function() {
if(this.cssPosition === "relative") {
var p = this.element.position();
return {
top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(),
left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft()
};
} else {
return { top: 0, left: 0 };
}
},
_cacheMargins: function() {
this.margins = {
left: (parseInt(this.element.css("marginLeft"),10) || 0),
top: (parseInt(this.element.css("marginTop"),10) || 0),
right: (parseInt(this.element.css("marginRight"),10) || 0),
bottom: (parseInt(this.element.css("marginBottom"),10) || 0)
};
},
_cacheHelperProportions: function() {
this.helperProportions = {
width: this.helper.outerWidth(),
height: this.helper.outerHeight()
};
},
_setContainment: function() {
var over, c, ce,
o = this.options;
if ( !o.containment ) {
this.containment = null;
return;
}
if ( o.containment === "window" ) {
this.containment = [
$( window ).scrollLeft() - this.offset.relative.left - this.offset.parent.left,
$( window ).scrollTop() - this.offset.relative.top - this.offset.parent.top,
$( window ).scrollLeft() + $( window ).width() - this.helperProportions.width - this.margins.left,
$( window ).scrollTop() + ( $( window ).height() || document.body.parentNode.scrollHeight ) - this.helperProportions.height - this.margins.top
];
return;
}
if ( o.containment === "document") {
this.containment = [
0,
0,
$( document ).width() - this.helperProportions.width - this.margins.left,
( $( document ).height() || document.body.parentNode.scrollHeight ) - this.helperProportions.height - this.margins.top
];
return;
}
if ( o.containment.constructor === Array ) {
this.containment = o.containment;
return;
}
if ( o.containment === "parent" ) {
o.containment = this.helper[ 0 ].parentNode;
}
c = $( o.containment );
ce = c[ 0 ];
if( !ce ) {
return;
}
over = c.css( "overflow" ) !== "hidden";
this.containment = [
( parseInt( c.css( "borderLeftWidth" ), 10 ) || 0 ) + ( parseInt( c.css( "paddingLeft" ), 10 ) || 0 ),
( parseInt( c.css( "borderTopWidth" ), 10 ) || 0 ) + ( parseInt( c.css( "paddingTop" ), 10 ) || 0 ) ,
( over ? Math.max( ce.scrollWidth, ce.offsetWidth ) : ce.offsetWidth ) - ( parseInt( c.css( "borderRightWidth" ), 10 ) || 0 ) - ( parseInt( c.css( "paddingRight" ), 10 ) || 0 ) - this.helperProportions.width - this.margins.left - this.margins.right,
( over ? Math.max( ce.scrollHeight, ce.offsetHeight ) : ce.offsetHeight ) - ( parseInt( c.css( "borderBottomWidth" ), 10 ) || 0 ) - ( parseInt( c.css( "paddingBottom" ), 10 ) || 0 ) - this.helperProportions.height - this.margins.top - this.margins.bottom
];
this.relative_container = c;
},
_convertPositionTo: function(d, pos) {
if(!pos) {
pos = this.position;
}
var mod = d === "absolute" ? 1 : -1,
scroll = this.cssPosition === "absolute" && !( this.scrollParent[ 0 ] !== document && $.contains( this.scrollParent[ 0 ], this.offsetParent[ 0 ] ) ) ? this.offsetParent : this.scrollParent;
//Cache the scroll
if (!this.offset.scroll) {
this.offset.scroll = {top : scroll.scrollTop(), left : scroll.scrollLeft()};
}
return {
top: (
pos.top + // The absolute mouse position
this.offset.relative.top * mod + // Only for relative positioned nodes: Relative offset from element to offset parent
this.offset.parent.top * mod - // The offsetParent's offset without borders (offset + border)
( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : this.offset.scroll.top ) * mod )
),
left: (
pos.left + // The absolute mouse position
this.offset.relative.left * mod + // Only for relative positioned nodes: Relative offset from element to offset parent
this.offset.parent.left * mod - // The offsetParent's offset without borders (offset + border)
( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : this.offset.scroll.left ) * mod )
)
};
},
_generatePosition: function(event) {
var containment, co, top, left,
o = this.options,
scroll = this.cssPosition === "absolute" && !( this.scrollParent[ 0 ] !== document && $.contains( this.scrollParent[ 0 ], this.offsetParent[ 0 ] ) ) ? this.offsetParent : this.scrollParent,
pageX = event.pageX,
pageY = event.pageY;
//Cache the scroll
if (!this.offset.scroll) {
this.offset.scroll = {top : scroll.scrollTop(), left : scroll.scrollLeft()};
}
/*
* - Position constraining -
* Constrain the position to a mix of grid, containment.
*/
// If we are not dragging yet, we won't check for options
if ( this.originalPosition ) {
if ( this.containment ) {
if ( this.relative_container ){
co = this.relative_container.offset();
containment = [
this.containment[ 0 ] + co.left,
this.containment[ 1 ] + co.top,
this.containment[ 2 ] + co.left,
this.containment[ 3 ] + co.top
];
}
else {
containment = this.containment;
}
if(event.pageX - this.offset.click.left < containment[0]) {
pageX = containment[0] + this.offset.click.left;
}
if(event.pageY - this.offset.click.top < containment[1]) {
pageY = containment[1] + this.offset.click.top;
}
if(event.pageX - this.offset.click.left > containment[2]) {
pageX = containment[2] + this.offset.click.left;
}
if(event.pageY - this.offset.click.top > containment[3]) {
pageY = containment[3] + this.offset.click.top;
}
}
if(o.grid) {
//Check for grid elements set to 0 to prevent divide by 0 error causing invalid argument errors in IE (see ticket #6950)
top = o.grid[1] ? this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1] : this.originalPageY;
pageY = containment ? ((top - this.offset.click.top >= containment[1] || top - this.offset.click.top > containment[3]) ? top : ((top - this.offset.click.top >= containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top;
left = o.grid[0] ? this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0] : this.originalPageX;
pageX = containment ? ((left - this.offset.click.left >= containment[0] || left - this.offset.click.left > containment[2]) ? left : ((left - this.offset.click.left >= containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left;
}
}
return {
top: (
pageY - // The absolute mouse position
this.offset.click.top - // Click offset (relative to the element)
this.offset.relative.top - // Only for relative positioned nodes: Relative offset from element to offset parent
this.offset.parent.top + // The offsetParent's offset without borders (offset + border)
( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : this.offset.scroll.top )
),
left: (
pageX - // The absolute mouse position
this.offset.click.left - // Click offset (relative to the element)
this.offset.relative.left - // Only for relative positioned nodes: Relative offset from element to offset parent
this.offset.parent.left + // The offsetParent's offset without borders (offset + border)
( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : this.offset.scroll.left )
)
};
},
_clear: function() {
this.helper.removeClass("ui-draggable-dragging");
if(this.helper[0] !== this.element[0] && !this.cancelHelperRemoval) {
this.helper.remove();
}
this.helper = null;
this.cancelHelperRemoval = false;
},
// From now on bulk stuff - mainly helpers
_trigger: function(type, event, ui) {
ui = ui || this._uiHash();
$.ui.plugin.call(this, type, [event, ui]);
//The absolute position has to be recalculated after plugins
if(type === "drag") {
this.positionAbs = this._convertPositionTo("absolute");
}
return $.Widget.prototype._trigger.call(this, type, event, ui);
},
plugins: {},
_uiHash: function() {
return {
helper: this.helper,
position: this.position,
originalPosition: this.originalPosition,
offset: this.positionAbs
};
}
});
$.ui.plugin.add("draggable", "connectToSortable", {
start: function(event, ui) {
var inst = $(this).data("ui-draggable"), o = inst.options,
uiSortable = $.extend({}, ui, { item: inst.element });
inst.sortables = [];
$(o.connectToSortable).each(function() {
var sortable = $.data(this, "ui-sortable");
if (sortable && !sortable.options.disabled) {
inst.sortables.push({
instance: sortable,
shouldRevert: sortable.options.revert
});
sortable.refreshPositions(); // Call the sortable's refreshPositions at drag start to refresh the containerCache since the sortable container cache is used in drag and needs to be up to date (this will ensure it's initialised as well as being kept in step with any changes that might have happened on the page).
sortable._trigger("activate", event, uiSortable);
}
});
},
stop: function(event, ui) {
//If we are still over the sortable, we fake the stop event of the sortable, but also remove helper
var inst = $(this).data("ui-draggable"),
uiSortable = $.extend({}, ui, { item: inst.element });
$.each(inst.sortables, function() {
if(this.instance.isOver) {
this.instance.isOver = 0;
inst.cancelHelperRemoval = true; //Don't remove the helper in the draggable instance
this.instance.cancelHelperRemoval = false; //Remove it in the sortable instance (so sortable plugins like revert still work)
//The sortable revert is supported, and we have to set a temporary dropped variable on the draggable to support revert: "valid/invalid"
if(this.shouldRevert) {
this.instance.options.revert = this.shouldRevert;
}
//Trigger the stop of the sortable
this.instance._mouseStop(event);
this.instance.options.helper = this.instance.options._helper;
//If the helper has been the original item, restore properties in the sortable
if(inst.options.helper === "original") {
this.instance.currentItem.css({ top: "auto", left: "auto" });
}
} else {
this.instance.cancelHelperRemoval = false; //Remove the helper in the sortable instance
this.instance._trigger("deactivate", event, uiSortable);
}
});
},
drag: function(event, ui) {
var inst = $(this).data("ui-draggable"), that = this;
$.each(inst.sortables, function() {
var innermostIntersecting = false,
thisSortable = this;
//Copy over some variables to allow calling the sortable's native _intersectsWith
this.instance.positionAbs = inst.positionAbs;
this.instance.helperProportions = inst.helperProportions;
this.instance.offset.click = inst.offset.click;
if(this.instance._intersectsWith(this.instance.containerCache)) {
innermostIntersecting = true;
$.each(inst.sortables, function () {
this.instance.positionAbs = inst.positionAbs;
this.instance.helperProportions = inst.helperProportions;
this.instance.offset.click = inst.offset.click;
if (this !== thisSortable &&
this.instance._intersectsWith(this.instance.containerCache) &&
$.contains(thisSortable.instance.element[0], this.instance.element[0])
) {
innermostIntersecting = false;
}
return innermostIntersecting;
});
}
if(innermostIntersecting) {
//If it intersects, we use a little isOver variable and set it once, so our move-in stuff gets fired only once
if(!this.instance.isOver) {
this.instance.isOver = 1;
//Now we fake the start of dragging for the sortable instance,
//by cloning the list group item, appending it to the sortable and using it as inst.currentItem
//We can then fire the start event of the sortable with our passed browser event, and our own helper (so it doesn't create a new one)
this.instance.currentItem = $(that).clone().removeAttr("id").appendTo(this.instance.element).data("ui-sortable-item", true);
this.instance.options._helper = this.instance.options.helper; //Store helper option to later restore it
this.instance.options.helper = function() { return ui.helper[0]; };
event.target = this.instance.currentItem[0];
this.instance._mouseCapture(event, true);
this.instance._mouseStart(event, true, true);
//Because the browser event is way off the new appended portlet, we modify a couple of variables to reflect the changes
this.instance.offset.click.top = inst.offset.click.top;
this.instance.offset.click.left = inst.offset.click.left;
this.instance.offset.parent.left -= inst.offset.parent.left - this.instance.offset.parent.left;
this.instance.offset.parent.top -= inst.offset.parent.top - this.instance.offset.parent.top;
inst._trigger("toSortable", event);
inst.dropped = this.instance.element; //draggable revert needs that
//hack so receive/update callbacks work (mostly)
inst.currentItem = inst.element;
this.instance.fromOutside = inst;
}
//Provided we did all the previous steps, we can fire the drag event of the sortable on every draggable drag, when it intersects with the sortable
if(this.instance.currentItem) {
this.instance._mouseDrag(event);
}
} else {
//If it doesn't intersect with the sortable, and it intersected before,
//we fake the drag stop of the sortable, but make sure it doesn't remove the helper by using cancelHelperRemoval
if(this.instance.isOver) {
this.instance.isOver = 0;
this.instance.cancelHelperRemoval = true;
//Prevent reverting on this forced stop
this.instance.options.revert = false;
// The out event needs to be triggered independently
this.instance._trigger("out", event, this.instance._uiHash(this.instance));
this.instance._mouseStop(event, true);
this.instance.options.helper = this.instance.options._helper;
//Now we remove our currentItem, the list group clone again, and the placeholder, and animate the helper back to it's original size
this.instance.currentItem.remove();
if(this.instance.placeholder) {
this.instance.placeholder.remove();
}
inst._trigger("fromSortable", event);
inst.dropped = false; //draggable revert needs that
}
}
});
}
});
$.ui.plugin.add("draggable", "cursor", {
start: function() {
var t = $("body"), o = $(this).data("ui-draggable").options;
if (t.css("cursor")) {
o._cursor = t.css("cursor");
}
t.css("cursor", o.cursor);
},
stop: function() {
var o = $(this).data("ui-draggable").options;
if (o._cursor) {
$("body").css("cursor", o._cursor);
}
}
});
$.ui.plugin.add("draggable", "opacity", {
start: function(event, ui) {
var t = $(ui.helper), o = $(this).data("ui-draggable").options;
if(t.css("opacity")) {
o._opacity = t.css("opacity");
}
t.css("opacity", o.opacity);
},
stop: function(event, ui) {
var o = $(this).data("ui-draggable").options;
if(o._opacity) {
$(ui.helper).css("opacity", o._opacity);
}
}
});
$.ui.plugin.add("draggable", "scroll", {
start: function() {
var i = $(this).data("ui-draggable");
if(i.scrollParent[0] !== document && i.scrollParent[0].tagName !== "HTML") {
i.overflowOffset = i.scrollParent.offset();
}
},
drag: function( event ) {
var i = $(this).data("ui-draggable"), o = i.options, scrolled = false;
if(i.scrollParent[0] !== document && i.scrollParent[0].tagName !== "HTML") {
if(!o.axis || o.axis !== "x") {
if((i.overflowOffset.top + i.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity) {
i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop + o.scrollSpeed;
} else if(event.pageY - i.overflowOffset.top < o.scrollSensitivity) {
i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop - o.scrollSpeed;
}
}
if(!o.axis || o.axis !== "y") {
if((i.overflowOffset.left + i.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity) {
i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft + o.scrollSpeed;
} else if(event.pageX - i.overflowOffset.left < o.scrollSensitivity) {
i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft - o.scrollSpeed;
}
}
} else {
if(!o.axis || o.axis !== "x") {
if(event.pageY - $(document).scrollTop() < o.scrollSensitivity) {
scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
} else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity) {
scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed);
}
}
if(!o.axis || o.axis !== "y") {
if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity) {
scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed);
} else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity) {
scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed);
}
}
}
if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) {
$.ui.ddmanager.prepareOffsets(i, event);
}
}
});
$.ui.plugin.add("draggable", "snap", {
start: function() {
var i = $(this).data("ui-draggable"),
o = i.options;
i.snapElements = [];
$(o.snap.constructor !== String ? ( o.snap.items || ":data(ui-draggable)" ) : o.snap).each(function() {
var $t = $(this),
$o = $t.offset();
if(this !== i.element[0]) {
i.snapElements.push({
item: this,
width: $t.outerWidth(), height: $t.outerHeight(),
top: $o.top, left: $o.left
});
}
});
},
drag: function(event, ui) {
var ts, bs, ls, rs, l, r, t, b, i, first,
inst = $(this).data("ui-draggable"),
o = inst.options,
d = o.snapTolerance,
x1 = ui.offset.left, x2 = x1 + inst.helperProportions.width,
y1 = ui.offset.top, y2 = y1 + inst.helperProportions.height;
for (i = inst.snapElements.length - 1; i >= 0; i--){
l = inst.snapElements[i].left;
r = l + inst.snapElements[i].width;
t = inst.snapElements[i].top;
b = t + inst.snapElements[i].height;
if ( x2 < l - d || x1 > r + d || y2 < t - d || y1 > b + d || !$.contains( inst.snapElements[ i ].item.ownerDocument, inst.snapElements[ i ].item ) ) {
if(inst.snapElements[i].snapping) {
(inst.options.snap.release && inst.options.snap.release.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item })));
}
inst.snapElements[i].snapping = false;
continue;
}
if(o.snapMode !== "inner") {
ts = Math.abs(t - y2) <= d;
bs = Math.abs(b - y1) <= d;
ls = Math.abs(l - x2) <= d;
rs = Math.abs(r - x1) <= d;
if(ts) {
ui.position.top = inst._convertPositionTo("relative", { top: t - inst.helperProportions.height, left: 0 }).top - inst.margins.top;
}
if(bs) {
ui.position.top = inst._convertPositionTo("relative", { top: b, left: 0 }).top - inst.margins.top;
}
if(ls) {
ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l - inst.helperProportions.width }).left - inst.margins.left;
}
if(rs) {
ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r }).left - inst.margins.left;
}
}
first = (ts || bs || ls || rs);
if(o.snapMode !== "outer") {
ts = Math.abs(t - y1) <= d;
bs = Math.abs(b - y2) <= d;
ls = Math.abs(l - x1) <= d;
rs = Math.abs(r - x2) <= d;
if(ts) {
ui.position.top = inst._convertPositionTo("relative", { top: t, left: 0 }).top - inst.margins.top;
}
if(bs) {
ui.position.top = inst._convertPositionTo("relative", { top: b - inst.helperProportions.height, left: 0 }).top - inst.margins.top;
}
if(ls) {
ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l }).left - inst.margins.left;
}
if(rs) {
ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r - inst.helperProportions.width }).left - inst.margins.left;
}
}
if(!inst.snapElements[i].snapping && (ts || bs || ls || rs || first)) {
(inst.options.snap.snap && inst.options.snap.snap.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item })));
}
inst.snapElements[i].snapping = (ts || bs || ls || rs || first);
}
}
});
$.ui.plugin.add("draggable", "stack", {
start: function() {
var min,
o = this.data("ui-draggable").options,
group = $.makeArray($(o.stack)).sort(function(a,b) {
return (parseInt($(a).css("zIndex"),10) || 0) - (parseInt($(b).css("zIndex"),10) || 0);
});
if (!group.length) { return; }
min = parseInt($(group[0]).css("zIndex"), 10) || 0;
$(group).each(function(i) {
$(this).css("zIndex", min + i);
});
this.css("zIndex", (min + group.length));
}
});
$.ui.plugin.add("draggable", "zIndex", {
start: function(event, ui) {
var t = $(ui.helper), o = $(this).data("ui-draggable").options;
if(t.css("zIndex")) {
o._zIndex = t.css("zIndex");
}
t.css("zIndex", o.zIndex);
},
stop: function(event, ui) {
var o = $(this).data("ui-draggable").options;
if(o._zIndex) {
$(ui.helper).css("zIndex", o._zIndex);
}
}
});
})(jQuery);
(function( $, undefined ) {
function isOverAxis( x, reference, size ) {
return ( x > reference ) && ( x < ( reference + size ) );
}
$.widget("ui.droppable", {
version: "1.10.3",
widgetEventPrefix: "drop",
options: {
accept: "*",
activeClass: false,
autoHide: false,
addClasses: true,
greedy: false,
hoverClass: false,
scope: "default",
tolerance: "intersect",
// callbacks
activate: null,
deactivate: null,
drop: null,
out: null,
over: null
},
_create: function() {
var o = this.options,
accept = o.accept;
this.isover = false;
this.isout = true;
this.accept = $.isFunction(accept) ? accept : function(d) {
return d.is(accept);
};
//Store the droppable's proportions
this.proportions = { width: this.element[0].offsetWidth, height: this.element[0].offsetHeight };
// Add the reference and positions to the manager
$.ui.ddmanager.droppables[o.scope] = $.ui.ddmanager.droppables[o.scope] || [];
$.ui.ddmanager.droppables[o.scope].push(this);
(o.addClasses && this.element.addClass("ui-droppable"));
},
_destroy: function() {
var i = 0,
drop = $.ui.ddmanager.droppables[this.options.scope];
for ( ; i < drop.length; i++ ) {
if ( drop[i] === this ) {
drop.splice(i, 1);
}
}
this.element.removeClass("ui-droppable ui-droppable-disabled");
},
_setOption: function(key, value) {
if(key === "accept") {
this.accept = $.isFunction(value) ? value : function(d) {
return d.is(value);
};
}
$.Widget.prototype._setOption.apply(this, arguments);
},
_activate: function(event) {
var draggable = $.ui.ddmanager.current;
if(this.options.activeClass) {
this.element.addClass(this.options.activeClass);
}
if(draggable){
this._trigger("activate", event, this.ui(draggable));
}
},
_deactivate: function(event) {
var draggable = $.ui.ddmanager.current;
if(this.options.activeClass) {
this.element.removeClass(this.options.activeClass);
}
if(draggable){
this._trigger("deactivate", event, this.ui(draggable));
}
},
_over: function(event) {
var draggable = $.ui.ddmanager.current;
// Bail if draggable and droppable are same element
if (!draggable || (draggable.currentItem || draggable.element)[0] === this.element[0]) {
return;
}
if (this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) {
if(this.options.hoverClass) {
this.element.addClass(this.options.hoverClass);
}
this._trigger("over", event, this.ui(draggable));
}
},
_out: function(event) {
var draggable = $.ui.ddmanager.current;
// Bail if draggable and droppable are same element
if (!draggable || (draggable.currentItem || draggable.element)[0] === this.element[0]) {
return;
}
if (this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) {
if(this.options.hoverClass) {
this.element.removeClass(this.options.hoverClass);
}
this._trigger("out", event, this.ui(draggable));
}
},
_drop: function(event,custom) {
var draggable = custom || $.ui.ddmanager.current,
childrenIntersection = false;
// Bail if draggable and droppable are same element
if (!draggable || (draggable.currentItem || draggable.element)[0] === this.element[0]) {
return false;
}
this.element.find(":data(ui-droppable)").not(".ui-draggable-dragging").each(function() {
var inst = $.data(this, "ui-droppable");
if(
inst.options.greedy &&
!inst.options.disabled &&
inst.options.scope === draggable.options.scope &&
inst.accept.call(inst.element[0], (draggable.currentItem || draggable.element)) &&
$.ui.intersect(draggable, $.extend(inst, { offset: inst.element.offset() }), inst.options.tolerance)
) { childrenIntersection = true; return false; }
});
if(childrenIntersection) {
return false;
}
if(this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) {
if(this.options.activeClass) {
this.element.removeClass(this.options.activeClass);
}
if(this.options.hoverClass) {
this.element.removeClass(this.options.hoverClass);
}
this._trigger("drop", event, this.ui(draggable));
return this.element;
}
return false;
},
ui: function(c) {
return {
draggable: (c.currentItem || c.element),
helper: c.helper,
position: c.position,
offset: c.positionAbs
};
}
});
$.ui.intersect = function(draggable, droppable, toleranceMode) {
if (!droppable.offset) {
return false;
}
var draggableLeft, draggableTop,
x1 = (draggable.positionAbs || draggable.position.absolute).left, x2 = x1 + draggable.helperProportions.width,
y1 = (draggable.positionAbs || draggable.position.absolute).top, y2 = y1 + draggable.helperProportions.height,
l = droppable.offset.left, r = l + droppable.proportions.width,
t = droppable.offset.top, b = t + droppable.proportions.height;
switch (toleranceMode) {
case "fit":
return (l <= x1 && x2 <= r && t <= y1 && y2 <= b);
case "intersect":
return (l < x1 + (draggable.helperProportions.width / 2) && // Right Half
x2 - (draggable.helperProportions.width / 2) < r && // Left Half
t < y1 + (draggable.helperProportions.height / 2) && // Bottom Half
y2 - (draggable.helperProportions.height / 2) < b ); // Top Half
case "pointer":
draggableLeft = ((draggable.positionAbs || draggable.position.absolute).left + (draggable.clickOffset || draggable.offset.click).left);
draggableTop = ((draggable.positionAbs || draggable.position.absolute).top + (draggable.clickOffset || draggable.offset.click).top);
return isOverAxis( draggableTop, t, droppable.proportions.height ) && isOverAxis( draggableLeft, l, droppable.proportions.width );
case "touch":
return (
(y1 >= t && y1 <= b) || // Top edge touching
(y2 >= t && y2 <= b) || // Bottom edge touching
(y1 < t && y2 > b) // Surrounded vertically
) && (
(x1 >= l && x1 <= r) || // Left edge touching
(x2 >= l && x2 <= r) || // Right edge touching
(x1 < l && x2 > r) // Surrounded horizontally
);
default:
return false;
}
};
/*
This manager tracks offsets of draggables and droppables
*/
$.ui.ddmanager = {
current: null,
droppables: { "default": [] },
prepareOffsets: function(t, event) {
var i, j,
m = $.ui.ddmanager.droppables[t.options.scope] || [],
type = event ? event.type : null, // workaround for #2317
list = (t.currentItem || t.element).find(":data(ui-droppable)").addBack();
droppablesLoop: for (i = 0; i < m.length; i++) {
//No disabled and non-accepted
if(m[i].options.disabled || (t && !m[i].accept.call(m[i].element[0],(t.currentItem || t.element)))) {
continue;
}
// Filter out elements in the current dragged item
for (j=0; j < list.length; j++) {
if(list[j] === m[i].element[0]) {
m[i].proportions.height = 0;
continue droppablesLoop;
}
}
m[i].visible = m[i].element.css("display") !== "none";
if(!m[i].visible) {
continue;
}
//Activate the droppable if used directly from draggables
if(type === "mousedown") {
m[i]._activate.call(m[i], event);
}
m[i].offset = m[i].element.offset();
m[i].proportions = { width: m[i].element[0].offsetWidth, height: m[i].element[0].offsetHeight };
}
},
drop: function(draggable, event) {
var dropped = false;
// Create a copy of the droppables in case the list changes during the drop (#9116)
$.each(($.ui.ddmanager.droppables[draggable.options.scope] || []).slice(), function() {
if(!this.options) {
return;
}
if (!this.options.disabled && this.visible && $.ui.intersect(draggable, this, this.options.tolerance)) {
dropped = this._drop.call(this, event) || dropped;
}
if (!this.options.disabled && this.visible && this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) {
this.isout = true;
this.isover = false;
this._deactivate.call(this, event);
}
});
return dropped;
},
dragStart: function( draggable, event ) {
//Listen for scrolling so that if the dragging causes scrolling the position of the droppables can be recalculated (see #5003)
draggable.element.parentsUntil( "body" ).bind( "scroll.droppable", function() {
if( !draggable.options.refreshPositions ) {
$.ui.ddmanager.prepareOffsets( draggable, event );
}
});
},
drag: function(draggable, event) {
//If you have a highly dynamic page, you might try this option. It renders positions every time you move the mouse.
if(draggable.options.refreshPositions) {
$.ui.ddmanager.prepareOffsets(draggable, event);
}
//Run through all droppables and check their positions based on specific tolerance options
$.each($.ui.ddmanager.droppables[draggable.options.scope] || [], function() {
if(this.options.disabled || this.greedyChild || !this.visible) {
return;
}
var parentInstance, scope, parent,
intersects = $.ui.intersect(draggable, this, this.options.tolerance),
c = !intersects && this.isover ? "isout" : (intersects && !this.isover ? "isover" : null);
if(!c) {
return;
}
if (this.options.greedy) {
// find droppable parents with same scope
scope = this.options.scope;
parent = this.element.parents(":data(ui-droppable)").filter(function () {
return $.data(this, "ui-droppable").options.scope === scope;
});
if (parent.length) {
parentInstance = $.data(parent[0], "ui-droppable");
parentInstance.greedyChild = (c === "isover");
}
}
// we just moved into a greedy child
if (parentInstance && c === "isover") {
parentInstance.isover = false;
parentInstance.isout = true;
parentInstance._out.call(parentInstance, event);
}
this[c] = true;
this[c === "isout" ? "isover" : "isout"] = false;
this[c === "isover" ? "_over" : "_out"].call(this, event);
// we just moved out of a greedy child
if (parentInstance && c === "isout") {
parentInstance.isout = false;
parentInstance.isover = true;
parentInstance._over.call(parentInstance, event);
}
});
},
dragStop: function( draggable, event ) {
draggable.element.parentsUntil( "body" ).unbind( "scroll.droppable" );
//Call prepareOffsets one final time since IE does not fire return scroll events when overflow was caused by drag (see #5003)
if( !draggable.options.refreshPositions ) {
$.ui.ddmanager.prepareOffsets( draggable, event );
}
}
};
})(jQuery);
(function( $, undefined ) {
function num(v) {
return parseInt(v, 10) || 0;
}
function isNumber(value) {
return !isNaN(parseInt(value, 10));
}
$.widget("ui.resizable", $.ui.mouse, {
version: "1.10.3",
widgetEventPrefix: "resize",
options: {
alsoResize: false,
animate: false,
animateDuration: "slow",
animateEasing: "swing",
aspectRatio: false,
autoHide: false,
containment: false,
ghost: false,
grid: false,
handles: "e,s,se",
helper: false,
maxHeight: null,
maxWidth: null,
minHeight: 10,
minWidth: 10,
// See #7960
zIndex: 90,
// callbacks
resize: null,
start: null,
stop: null
},
_create: function() {
var n, i, handle, axis, hname,
that = this,
o = this.options;
this.element.addClass("ui-resizable");
$.extend(this, {
_aspectRatio: !!(o.aspectRatio),
aspectRatio: o.aspectRatio,
originalElement: this.element,
_proportionallyResizeElements: [],
_helper: o.helper || o.ghost || o.animate ? o.helper || "ui-resizable-helper" : null
});
//Wrap the element if it cannot hold child nodes
if(this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)) {
//Create a wrapper element and set the wrapper to the new current internal element
this.element.wrap(
$("<div class='ui-wrapper' style='overflow: hidden;'></div>").css({
position: this.element.css("position"),
width: this.element.outerWidth(),
height: this.element.outerHeight(),
top: this.element.css("top"),
left: this.element.css("left")
})
);
//Overwrite the original this.element
this.element = this.element.parent().data(
"ui-resizable", this.element.data("ui-resizable")
);
this.elementIsWrapper = true;
//Move margins to the wrapper
this.element.css({ marginLeft: this.originalElement.css("marginLeft"), marginTop: this.originalElement.css("marginTop"), marginRight: this.originalElement.css("marginRight"), marginBottom: this.originalElement.css("marginBottom") });
this.originalElement.css({ marginLeft: 0, marginTop: 0, marginRight: 0, marginBottom: 0});
//Prevent Safari textarea resize
this.originalResizeStyle = this.originalElement.css("resize");
this.originalElement.css("resize", "none");
//Push the actual element to our proportionallyResize internal array
this._proportionallyResizeElements.push(this.originalElement.css({ position: "static", zoom: 1, display: "block" }));
// avoid IE jump (hard set the margin)
this.originalElement.css({ margin: this.originalElement.css("margin") });
// fix handlers offset
this._proportionallyResize();
}
this.handles = o.handles || (!$(".ui-resizable-handle", this.element).length ? "e,s,se" : { n: ".ui-resizable-n", e: ".ui-resizable-e", s: ".ui-resizable-s", w: ".ui-resizable-w", se: ".ui-resizable-se", sw: ".ui-resizable-sw", ne: ".ui-resizable-ne", nw: ".ui-resizable-nw" });
if(this.handles.constructor === String) {
if ( this.handles === "all") {
this.handles = "n,e,s,w,se,sw,ne,nw";
}
n = this.handles.split(",");
this.handles = {};
for(i = 0; i < n.length; i++) {
handle = $.trim(n[i]);
hname = "ui-resizable-"+handle;
axis = $("<div class='ui-resizable-handle " + hname + "'></div>");
// Apply zIndex to all handles - see #7960
axis.css({ zIndex: o.zIndex });
//TODO : What's going on here?
if ("se" === handle) {
axis.addClass("ui-icon ui-icon-gripsmall-diagonal-se");
}
//Insert into internal handles object and append to element
this.handles[handle] = ".ui-resizable-"+handle;
this.element.append(axis);
}
}
this._renderAxis = function(target) {
var i, axis, padPos, padWrapper;
target = target || this.element;
for(i in this.handles) {
if(this.handles[i].constructor === String) {
this.handles[i] = $(this.handles[i], this.element).show();
}
//Apply pad to wrapper element, needed to fix axis position (textarea, inputs, scrolls)
if (this.elementIsWrapper && this.originalElement[0].nodeName.match(/textarea|input|select|button/i)) {
axis = $(this.handles[i], this.element);
//Checking the correct pad and border
padWrapper = /sw|ne|nw|se|n|s/.test(i) ? axis.outerHeight() : axis.outerWidth();
//The padding type i have to apply...
padPos = [ "padding",
/ne|nw|n/.test(i) ? "Top" :
/se|sw|s/.test(i) ? "Bottom" :
/^e$/.test(i) ? "Right" : "Left" ].join("");
target.css(padPos, padWrapper);
this._proportionallyResize();
}
//TODO: What's that good for? There's not anything to be executed left
if(!$(this.handles[i]).length) {
continue;
}
}
};
//TODO: make renderAxis a prototype function
this._renderAxis(this.element);
this._handles = $(".ui-resizable-handle", this.element)
.disableSelection();
//Matching axis name
this._handles.mouseover(function() {
if (!that.resizing) {
if (this.className) {
axis = this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i);
}
//Axis, default = se
that.axis = axis && axis[1] ? axis[1] : "se";
}
});
//If we want to auto hide the elements
if (o.autoHide) {
this._handles.hide();
$(this.element)
.addClass("ui-resizable-autohide")
.mouseenter(function() {
if (o.disabled) {
return;
}
$(this).removeClass("ui-resizable-autohide");
that._handles.show();
})
.mouseleave(function(){
if (o.disabled) {
return;
}
if (!that.resizing) {
$(this).addClass("ui-resizable-autohide");
that._handles.hide();
}
});
}
//Initialize the mouse interaction
this._mouseInit();
},
_destroy: function() {
this._mouseDestroy();
var wrapper,
_destroy = function(exp) {
$(exp).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing")
.removeData("resizable").removeData("ui-resizable").unbind(".resizable").find(".ui-resizable-handle").remove();
};
//TODO: Unwrap at same DOM position
if (this.elementIsWrapper) {
_destroy(this.element);
wrapper = this.element;
this.originalElement.css({
position: wrapper.css("position"),
width: wrapper.outerWidth(),
height: wrapper.outerHeight(),
top: wrapper.css("top"),
left: wrapper.css("left")
}).insertAfter( wrapper );
wrapper.remove();
}
this.originalElement.css("resize", this.originalResizeStyle);
_destroy(this.originalElement);
return this;
},
_mouseCapture: function(event) {
var i, handle,
capture = false;
for (i in this.handles) {
handle = $(this.handles[i])[0];
if (handle === event.target || $.contains(handle, event.target)) {
capture = true;
}
}
return !this.options.disabled && capture;
},
_mouseStart: function(event) {
var curleft, curtop, cursor,
o = this.options,
iniPos = this.element.position(),
el = this.element;
this.resizing = true;
// bugfix for http://dev.jquery.com/ticket/1749
if ( (/absolute/).test( el.css("position") ) ) {
el.css({ position: "absolute", top: el.css("top"), left: el.css("left") });
} else if (el.is(".ui-draggable")) {
el.css({ position: "absolute", top: iniPos.top, left: iniPos.left });
}
this._renderProxy();
curleft = num(this.helper.css("left"));
curtop = num(this.helper.css("top"));
if (o.containment) {
curleft += $(o.containment).scrollLeft() || 0;
curtop += $(o.containment).scrollTop() || 0;
}
//Store needed variables
this.offset = this.helper.offset();
this.position = { left: curleft, top: curtop };
this.size = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() };
this.originalSize = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() };
this.originalPosition = { left: curleft, top: curtop };
this.sizeDiff = { width: el.outerWidth() - el.width(), height: el.outerHeight() - el.height() };
this.originalMousePosition = { left: event.pageX, top: event.pageY };
//Aspect Ratio
this.aspectRatio = (typeof o.aspectRatio === "number") ? o.aspectRatio : ((this.originalSize.width / this.originalSize.height) || 1);
cursor = $(".ui-resizable-" + this.axis).css("cursor");
$("body").css("cursor", cursor === "auto" ? this.axis + "-resize" : cursor);
el.addClass("ui-resizable-resizing");
this._propagate("start", event);
return true;
},
_mouseDrag: function(event) {
//Increase performance, avoid regex
var data,
el = this.helper, props = {},
smp = this.originalMousePosition,
a = this.axis,
prevTop = this.position.top,
prevLeft = this.position.left,
prevWidth = this.size.width,
prevHeight = this.size.height,
dx = (event.pageX-smp.left)||0,
dy = (event.pageY-smp.top)||0,
trigger = this._change[a];
if (!trigger) {
return false;
}
// Calculate the attrs that will be change
data = trigger.apply(this, [event, dx, dy]);
// Put this in the mouseDrag handler since the user can start pressing shift while resizing
this._updateVirtualBoundaries(event.shiftKey);
if (this._aspectRatio || event.shiftKey) {
data = this._updateRatio(data, event);
}
data = this._respectSize(data, event);
this._updateCache(data);
// plugins callbacks need to be called first
this._propagate("resize", event);
if (this.position.top !== prevTop) {
props.top = this.position.top + "px";
}
if (this.position.left !== prevLeft) {
props.left = this.position.left + "px";
}
if (this.size.width !== prevWidth) {
props.width = this.size.width + "px";
}
if (this.size.height !== prevHeight) {
props.height = this.size.height + "px";
}
el.css(props);
if (!this._helper && this._proportionallyResizeElements.length) {
this._proportionallyResize();
}
// Call the user callback if the element was resized
if ( ! $.isEmptyObject(props) ) {
this._trigger("resize", event, this.ui());
}
return false;
},
_mouseStop: function(event) {
this.resizing = false;
var pr, ista, soffseth, soffsetw, s, left, top,
o = this.options, that = this;
if(this._helper) {
pr = this._proportionallyResizeElements;
ista = pr.length && (/textarea/i).test(pr[0].nodeName);
soffseth = ista && $.ui.hasScroll(pr[0], "left") /* TODO - jump height */ ? 0 : that.sizeDiff.height;
soffsetw = ista ? 0 : that.sizeDiff.width;
s = { width: (that.helper.width() - soffsetw), height: (that.helper.height() - soffseth) };
left = (parseInt(that.element.css("left"), 10) + (that.position.left - that.originalPosition.left)) || null;
top = (parseInt(that.element.css("top"), 10) + (that.position.top - that.originalPosition.top)) || null;
if (!o.animate) {
this.element.css($.extend(s, { top: top, left: left }));
}
that.helper.height(that.size.height);
that.helper.width(that.size.width);
if (this._helper && !o.animate) {
this._proportionallyResize();
}
}
$("body").css("cursor", "auto");
this.element.removeClass("ui-resizable-resizing");
this._propagate("stop", event);
if (this._helper) {
this.helper.remove();
}
return false;
},
_updateVirtualBoundaries: function(forceAspectRatio) {
var pMinWidth, pMaxWidth, pMinHeight, pMaxHeight, b,
o = this.options;
b = {
minWidth: isNumber(o.minWidth) ? o.minWidth : 0,
maxWidth: isNumber(o.maxWidth) ? o.maxWidth : Infinity,
minHeight: isNumber(o.minHeight) ? o.minHeight : 0,
maxHeight: isNumber(o.maxHeight) ? o.maxHeight : Infinity
};
if(this._aspectRatio || forceAspectRatio) {
// We want to create an enclosing box whose aspect ration is the requested one
// First, compute the "projected" size for each dimension based on the aspect ratio and other dimension
pMinWidth = b.minHeight * this.aspectRatio;
pMinHeight = b.minWidth / this.aspectRatio;
pMaxWidth = b.maxHeight * this.aspectRatio;
pMaxHeight = b.maxWidth / this.aspectRatio;
if(pMinWidth > b.minWidth) {
b.minWidth = pMinWidth;
}
if(pMinHeight > b.minHeight) {
b.minHeight = pMinHeight;
}
if(pMaxWidth < b.maxWidth) {
b.maxWidth = pMaxWidth;
}
if(pMaxHeight < b.maxHeight) {
b.maxHeight = pMaxHeight;
}
}
this._vBoundaries = b;
},
_updateCache: function(data) {
this.offset = this.helper.offset();
if (isNumber(data.left)) {
this.position.left = data.left;
}
if (isNumber(data.top)) {
this.position.top = data.top;
}
if (isNumber(data.height)) {
this.size.height = data.height;
}
if (isNumber(data.width)) {
this.size.width = data.width;
}
},
_updateRatio: function( data ) {
var cpos = this.position,
csize = this.size,
a = this.axis;
if (isNumber(data.height)) {
data.width = (data.height * this.aspectRatio);
} else if (isNumber(data.width)) {
data.height = (data.width / this.aspectRatio);
}
if (a === "sw") {
data.left = cpos.left + (csize.width - data.width);
data.top = null;
}
if (a === "nw") {
data.top = cpos.top + (csize.height - data.height);
data.left = cpos.left + (csize.width - data.width);
}
return data;
},
_respectSize: function( data ) {
var o = this._vBoundaries,
a = this.axis,
ismaxw = isNumber(data.width) && o.maxWidth && (o.maxWidth < data.width), ismaxh = isNumber(data.height) && o.maxHeight && (o.maxHeight < data.height),
isminw = isNumber(data.width) && o.minWidth && (o.minWidth > data.width), isminh = isNumber(data.height) && o.minHeight && (o.minHeight > data.height),
dw = this.originalPosition.left + this.originalSize.width,
dh = this.position.top + this.size.height,
cw = /sw|nw|w/.test(a), ch = /nw|ne|n/.test(a);
if (isminw) {
data.width = o.minWidth;
}
if (isminh) {
data.height = o.minHeight;
}
if (ismaxw) {
data.width = o.maxWidth;
}
if (ismaxh) {
data.height = o.maxHeight;
}
if (isminw && cw) {
data.left = dw - o.minWidth;
}
if (ismaxw && cw) {
data.left = dw - o.maxWidth;
}
if (isminh && ch) {
data.top = dh - o.minHeight;
}
if (ismaxh && ch) {
data.top = dh - o.maxHeight;
}
// fixing jump error on top/left - bug #2330
if (!data.width && !data.height && !data.left && data.top) {
data.top = null;
} else if (!data.width && !data.height && !data.top && data.left) {
data.left = null;
}
return data;
},
_proportionallyResize: function() {
if (!this._proportionallyResizeElements.length) {
return;
}
var i, j, borders, paddings, prel,
element = this.helper || this.element;
for ( i=0; i < this._proportionallyResizeElements.length; i++) {
prel = this._proportionallyResizeElements[i];
if (!this.borderDif) {
this.borderDif = [];
borders = [prel.css("borderTopWidth"), prel.css("borderRightWidth"), prel.css("borderBottomWidth"), prel.css("borderLeftWidth")];
paddings = [prel.css("paddingTop"), prel.css("paddingRight"), prel.css("paddingBottom"), prel.css("paddingLeft")];
for ( j = 0; j < borders.length; j++ ) {
this.borderDif[ j ] = ( parseInt( borders[ j ], 10 ) || 0 ) + ( parseInt( paddings[ j ], 10 ) || 0 );
}
}
prel.css({
height: (element.height() - this.borderDif[0] - this.borderDif[2]) || 0,
width: (element.width() - this.borderDif[1] - this.borderDif[3]) || 0
});
}
},
_renderProxy: function() {
var el = this.element, o = this.options;
this.elementOffset = el.offset();
if(this._helper) {
this.helper = this.helper || $("<div style='overflow:hidden;'></div>");
this.helper.addClass(this._helper).css({
width: this.element.outerWidth() - 1,
height: this.element.outerHeight() - 1,
position: "absolute",
left: this.elementOffset.left +"px",
top: this.elementOffset.top +"px",
zIndex: ++o.zIndex //TODO: Don't modify option
});
this.helper
.appendTo("body")
.disableSelection();
} else {
this.helper = this.element;
}
},
_change: {
e: function(event, dx) {
return { width: this.originalSize.width + dx };
},
w: function(event, dx) {
var cs = this.originalSize, sp = this.originalPosition;
return { left: sp.left + dx, width: cs.width - dx };
},
n: function(event, dx, dy) {
var cs = this.originalSize, sp = this.originalPosition;
return { top: sp.top + dy, height: cs.height - dy };
},
s: function(event, dx, dy) {
return { height: this.originalSize.height + dy };
},
se: function(event, dx, dy) {
return $.extend(this._change.s.apply(this, arguments), this._change.e.apply(this, [event, dx, dy]));
},
sw: function(event, dx, dy) {
return $.extend(this._change.s.apply(this, arguments), this._change.w.apply(this, [event, dx, dy]));
},
ne: function(event, dx, dy) {
return $.extend(this._change.n.apply(this, arguments), this._change.e.apply(this, [event, dx, dy]));
},
nw: function(event, dx, dy) {
return $.extend(this._change.n.apply(this, arguments), this._change.w.apply(this, [event, dx, dy]));
}
},
_propagate: function(n, event) {
$.ui.plugin.call(this, n, [event, this.ui()]);
(n !== "resize" && this._trigger(n, event, this.ui()));
},
plugins: {},
ui: function() {
return {
originalElement: this.originalElement,
element: this.element,
helper: this.helper,
position: this.position,
size: this.size,
originalSize: this.originalSize,
originalPosition: this.originalPosition
};
}
});
/*
* Resizable Extensions
*/
$.ui.plugin.add("resizable", "animate", {
stop: function( event ) {
var that = $(this).data("ui-resizable"),
o = that.options,
pr = that._proportionallyResizeElements,
ista = pr.length && (/textarea/i).test(pr[0].nodeName),
soffseth = ista && $.ui.hasScroll(pr[0], "left") /* TODO - jump height */ ? 0 : that.sizeDiff.height,
soffsetw = ista ? 0 : that.sizeDiff.width,
style = { width: (that.size.width - soffsetw), height: (that.size.height - soffseth) },
left = (parseInt(that.element.css("left"), 10) + (that.position.left - that.originalPosition.left)) || null,
top = (parseInt(that.element.css("top"), 10) + (that.position.top - that.originalPosition.top)) || null;
that.element.animate(
$.extend(style, top && left ? { top: top, left: left } : {}), {
duration: o.animateDuration,
easing: o.animateEasing,
step: function() {
var data = {
width: parseInt(that.element.css("width"), 10),
height: parseInt(that.element.css("height"), 10),
top: parseInt(that.element.css("top"), 10),
left: parseInt(that.element.css("left"), 10)
};
if (pr && pr.length) {
$(pr[0]).css({ width: data.width, height: data.height });
}
// propagating resize, and updating values for each animation step
that._updateCache(data);
that._propagate("resize", event);
}
}
);
}
});
$.ui.plugin.add("resizable", "containment", {
start: function() {
var element, p, co, ch, cw, width, height,
that = $(this).data("ui-resizable"),
o = that.options,
el = that.element,
oc = o.containment,
ce = (oc instanceof $) ? oc.get(0) : (/parent/.test(oc)) ? el.parent().get(0) : oc;
if (!ce) {
return;
}
that.containerElement = $(ce);
if (/document/.test(oc) || oc === document) {
that.containerOffset = { left: 0, top: 0 };
that.containerPosition = { left: 0, top: 0 };
that.parentData = {
element: $(document), left: 0, top: 0,
width: $(document).width(), height: $(document).height() || document.body.parentNode.scrollHeight
};
}
// i'm a node, so compute top, left, right, bottom
else {
element = $(ce);
p = [];
$([ "Top", "Right", "Left", "Bottom" ]).each(function(i, name) { p[i] = num(element.css("padding" + name)); });
that.containerOffset = element.offset();
that.containerPosition = element.position();
that.containerSize = { height: (element.innerHeight() - p[3]), width: (element.innerWidth() - p[1]) };
co = that.containerOffset;
ch = that.containerSize.height;
cw = that.containerSize.width;
width = ($.ui.hasScroll(ce, "left") ? ce.scrollWidth : cw );
height = ($.ui.hasScroll(ce) ? ce.scrollHeight : ch);
that.parentData = {
element: ce, left: co.left, top: co.top, width: width, height: height
};
}
},
resize: function( event ) {
var woset, hoset, isParent, isOffsetRelative,
that = $(this).data("ui-resizable"),
o = that.options,
co = that.containerOffset, cp = that.position,
pRatio = that._aspectRatio || event.shiftKey,
cop = { top:0, left:0 }, ce = that.containerElement;
if (ce[0] !== document && (/static/).test(ce.css("position"))) {
cop = co;
}
if (cp.left < (that._helper ? co.left : 0)) {
that.size.width = that.size.width + (that._helper ? (that.position.left - co.left) : (that.position.left - cop.left));
if (pRatio) {
that.size.height = that.size.width / that.aspectRatio;
}
that.position.left = o.helper ? co.left : 0;
}
if (cp.top < (that._helper ? co.top : 0)) {
that.size.height = that.size.height + (that._helper ? (that.position.top - co.top) : that.position.top);
if (pRatio) {
that.size.width = that.size.height * that.aspectRatio;
}
that.position.top = that._helper ? co.top : 0;
}
that.offset.left = that.parentData.left+that.position.left;
that.offset.top = that.parentData.top+that.position.top;
woset = Math.abs( (that._helper ? that.offset.left - cop.left : (that.offset.left - cop.left)) + that.sizeDiff.width );
hoset = Math.abs( (that._helper ? that.offset.top - cop.top : (that.offset.top - co.top)) + that.sizeDiff.height );
isParent = that.containerElement.get(0) === that.element.parent().get(0);
isOffsetRelative = /relative|absolute/.test(that.containerElement.css("position"));
if(isParent && isOffsetRelative) {
woset -= that.parentData.left;
}
if (woset + that.size.width >= that.parentData.width) {
that.size.width = that.parentData.width - woset;
if (pRatio) {
that.size.height = that.size.width / that.aspectRatio;
}
}
if (hoset + that.size.height >= that.parentData.height) {
that.size.height = that.parentData.height - hoset;
if (pRatio) {
that.size.width = that.size.height * that.aspectRatio;
}
}
},
stop: function(){
var that = $(this).data("ui-resizable"),
o = that.options,
co = that.containerOffset,
cop = that.containerPosition,
ce = that.containerElement,
helper = $(that.helper),
ho = helper.offset(),
w = helper.outerWidth() - that.sizeDiff.width,
h = helper.outerHeight() - that.sizeDiff.height;
if (that._helper && !o.animate && (/relative/).test(ce.css("position"))) {
$(this).css({ left: ho.left - cop.left - co.left, width: w, height: h });
}
if (that._helper && !o.animate && (/static/).test(ce.css("position"))) {
$(this).css({ left: ho.left - cop.left - co.left, width: w, height: h });
}
}
});
$.ui.plugin.add("resizable", "alsoResize", {
start: function () {
var that = $(this).data("ui-resizable"),
o = that.options,
_store = function (exp) {
$(exp).each(function() {
var el = $(this);
el.data("ui-resizable-alsoresize", {
width: parseInt(el.width(), 10), height: parseInt(el.height(), 10),
left: parseInt(el.css("left"), 10), top: parseInt(el.css("top"), 10)
});
});
};
if (typeof(o.alsoResize) === "object" && !o.alsoResize.parentNode) {
if (o.alsoResize.length) { o.alsoResize = o.alsoResize[0]; _store(o.alsoResize); }
else { $.each(o.alsoResize, function (exp) { _store(exp); }); }
}else{
_store(o.alsoResize);
}
},
resize: function (event, ui) {
var that = $(this).data("ui-resizable"),
o = that.options,
os = that.originalSize,
op = that.originalPosition,
delta = {
height: (that.size.height - os.height) || 0, width: (that.size.width - os.width) || 0,
top: (that.position.top - op.top) || 0, left: (that.position.left - op.left) || 0
},
_alsoResize = function (exp, c) {
$(exp).each(function() {
var el = $(this), start = $(this).data("ui-resizable-alsoresize"), style = {},
css = c && c.length ? c : el.parents(ui.originalElement[0]).length ? ["width", "height"] : ["width", "height", "top", "left"];
$.each(css, function (i, prop) {
var sum = (start[prop]||0) + (delta[prop]||0);
if (sum && sum >= 0) {
style[prop] = sum || null;
}
});
el.css(style);
});
};
if (typeof(o.alsoResize) === "object" && !o.alsoResize.nodeType) {
$.each(o.alsoResize, function (exp, c) { _alsoResize(exp, c); });
}else{
_alsoResize(o.alsoResize);
}
},
stop: function () {
$(this).removeData("resizable-alsoresize");
}
});
$.ui.plugin.add("resizable", "ghost", {
start: function() {
var that = $(this).data("ui-resizable"), o = that.options, cs = that.size;
that.ghost = that.originalElement.clone();
that.ghost
.css({ opacity: 0.25, display: "block", position: "relative", height: cs.height, width: cs.width, margin: 0, left: 0, top: 0 })
.addClass("ui-resizable-ghost")
.addClass(typeof o.ghost === "string" ? o.ghost : "");
that.ghost.appendTo(that.helper);
},
resize: function(){
var that = $(this).data("ui-resizable");
if (that.ghost) {
that.ghost.css({ position: "relative", height: that.size.height, width: that.size.width });
}
},
stop: function() {
var that = $(this).data("ui-resizable");
if (that.ghost && that.helper) {
that.helper.get(0).removeChild(that.ghost.get(0));
}
}
});
$.ui.plugin.add("resizable", "grid", {
resize: function() {
var that = $(this).data("ui-resizable"),
o = that.options,
cs = that.size,
os = that.originalSize,
op = that.originalPosition,
a = that.axis,
grid = typeof o.grid === "number" ? [o.grid, o.grid] : o.grid,
gridX = (grid[0]||1),
gridY = (grid[1]||1),
ox = Math.round((cs.width - os.width) / gridX) * gridX,
oy = Math.round((cs.height - os.height) / gridY) * gridY,
newWidth = os.width + ox,
newHeight = os.height + oy,
isMaxWidth = o.maxWidth && (o.maxWidth < newWidth),
isMaxHeight = o.maxHeight && (o.maxHeight < newHeight),
isMinWidth = o.minWidth && (o.minWidth > newWidth),
isMinHeight = o.minHeight && (o.minHeight > newHeight);
o.grid = grid;
if (isMinWidth) {
newWidth = newWidth + gridX;
}
if (isMinHeight) {
newHeight = newHeight + gridY;
}
if (isMaxWidth) {
newWidth = newWidth - gridX;
}
if (isMaxHeight) {
newHeight = newHeight - gridY;
}
if (/^(se|s|e)$/.test(a)) {
that.size.width = newWidth;
that.size.height = newHeight;
} else if (/^(ne)$/.test(a)) {
that.size.width = newWidth;
that.size.height = newHeight;
that.position.top = op.top - oy;
} else if (/^(sw)$/.test(a)) {
that.size.width = newWidth;
that.size.height = newHeight;
that.position.left = op.left - ox;
} else {
that.size.width = newWidth;
that.size.height = newHeight;
that.position.top = op.top - oy;
that.position.left = op.left - ox;
}
}
});
})(jQuery);
(function( $, undefined ) {
$.widget("ui.selectable", $.ui.mouse, {
version: "1.10.3",
options: {
appendTo: "body",
autoRefresh: true,
distance: 0,
filter: "*",
tolerance: "touch",
// callbacks
selected: null,
selecting: null,
start: null,
stop: null,
unselected: null,
unselecting: null
},
_create: function() {
var selectees,
that = this;
this.element.addClass("ui-selectable");
this.dragged = false;
// cache selectee children based on filter
this.refresh = function() {
selectees = $(that.options.filter, that.element[0]);
selectees.addClass("ui-selectee");
selectees.each(function() {
var $this = $(this),
pos = $this.offset();
$.data(this, "selectable-item", {
element: this,
$element: $this,
left: pos.left,
top: pos.top,
right: pos.left + $this.outerWidth(),
bottom: pos.top + $this.outerHeight(),
startselected: false,
selected: $this.hasClass("ui-selected"),
selecting: $this.hasClass("ui-selecting"),
unselecting: $this.hasClass("ui-unselecting")
});
});
};
this.refresh();
this.selectees = selectees.addClass("ui-selectee");
this._mouseInit();
this.helper = $("<div class='ui-selectable-helper'></div>");
},
_destroy: function() {
this.selectees
.removeClass("ui-selectee")
.removeData("selectable-item");
this.element
.removeClass("ui-selectable ui-selectable-disabled");
this._mouseDestroy();
},
_mouseStart: function(event) {
var that = this,
options = this.options;
this.opos = [event.pageX, event.pageY];
if (this.options.disabled) {
return;
}
this.selectees = $(options.filter, this.element[0]);
this._trigger("start", event);
$(options.appendTo).append(this.helper);
// position helper (lasso)
this.helper.css({
"left": event.pageX,
"top": event.pageY,
"width": 0,
"height": 0
});
if (options.autoRefresh) {
this.refresh();
}
this.selectees.filter(".ui-selected").each(function() {
var selectee = $.data(this, "selectable-item");
selectee.startselected = true;
if (!event.metaKey && !event.ctrlKey) {
selectee.$element.removeClass("ui-selected");
selectee.selected = false;
selectee.$element.addClass("ui-unselecting");
selectee.unselecting = true;
// selectable UNSELECTING callback
that._trigger("unselecting", event, {
unselecting: selectee.element
});
}
});
$(event.target).parents().addBack().each(function() {
var doSelect,
selectee = $.data(this, "selectable-item");
if (selectee) {
doSelect = (!event.metaKey && !event.ctrlKey) || !selectee.$element.hasClass("ui-selected");
selectee.$element
.removeClass(doSelect ? "ui-unselecting" : "ui-selected")
.addClass(doSelect ? "ui-selecting" : "ui-unselecting");
selectee.unselecting = !doSelect;
selectee.selecting = doSelect;
selectee.selected = doSelect;
// selectable (UN)SELECTING callback
if (doSelect) {
that._trigger("selecting", event, {
selecting: selectee.element
});
} else {
that._trigger("unselecting", event, {
unselecting: selectee.element
});
}
return false;
}
});
},
_mouseDrag: function(event) {
this.dragged = true;
if (this.options.disabled) {
return;
}
var tmp,
that = this,
options = this.options,
x1 = this.opos[0],
y1 = this.opos[1],
x2 = event.pageX,
y2 = event.pageY;
if (x1 > x2) { tmp = x2; x2 = x1; x1 = tmp; }
if (y1 > y2) { tmp = y2; y2 = y1; y1 = tmp; }
this.helper.css({left: x1, top: y1, width: x2-x1, height: y2-y1});
this.selectees.each(function() {
var selectee = $.data(this, "selectable-item"),
hit = false;
//prevent helper from being selected if appendTo: selectable
if (!selectee || selectee.element === that.element[0]) {
return;
}
if (options.tolerance === "touch") {
hit = ( !(selectee.left > x2 || selectee.right < x1 || selectee.top > y2 || selectee.bottom < y1) );
} else if (options.tolerance === "fit") {
hit = (selectee.left > x1 && selectee.right < x2 && selectee.top > y1 && selectee.bottom < y2);
}
if (hit) {
// SELECT
if (selectee.selected) {
selectee.$element.removeClass("ui-selected");
selectee.selected = false;
}
if (selectee.unselecting) {
selectee.$element.removeClass("ui-unselecting");
selectee.unselecting = false;
}
if (!selectee.selecting) {
selectee.$element.addClass("ui-selecting");
selectee.selecting = true;
// selectable SELECTING callback
that._trigger("selecting", event, {
selecting: selectee.element
});
}
} else {
// UNSELECT
if (selectee.selecting) {
if ((event.metaKey || event.ctrlKey) && selectee.startselected) {
selectee.$element.removeClass("ui-selecting");
selectee.selecting = false;
selectee.$element.addClass("ui-selected");
selectee.selected = true;
} else {
selectee.$element.removeClass("ui-selecting");
selectee.selecting = false;
if (selectee.startselected) {
selectee.$element.addClass("ui-unselecting");
selectee.unselecting = true;
}
// selectable UNSELECTING callback
that._trigger("unselecting", event, {
unselecting: selectee.element
});
}
}
if (selectee.selected) {
if (!event.metaKey && !event.ctrlKey && !selectee.startselected) {
selectee.$element.removeClass("ui-selected");
selectee.selected = false;
selectee.$element.addClass("ui-unselecting");
selectee.unselecting = true;
// selectable UNSELECTING callback
that._trigger("unselecting", event, {
unselecting: selectee.element
});
}
}
}
});
return false;
},
_mouseStop: function(event) {
var that = this;
this.dragged = false;
$(".ui-unselecting", this.element[0]).each(function() {
var selectee = $.data(this, "selectable-item");
selectee.$element.removeClass("ui-unselecting");
selectee.unselecting = false;
selectee.startselected = false;
that._trigger("unselected", event, {
unselected: selectee.element
});
});
$(".ui-selecting", this.element[0]).each(function() {
var selectee = $.data(this, "selectable-item");
selectee.$element.removeClass("ui-selecting").addClass("ui-selected");
selectee.selecting = false;
selectee.selected = true;
selectee.startselected = true;
that._trigger("selected", event, {
selected: selectee.element
});
});
this._trigger("stop", event);
this.helper.remove();
return false;
}
});
})(jQuery);
(function( $, undefined ) {
/*jshint loopfunc: true */
function isOverAxis( x, reference, size ) {
return ( x > reference ) && ( x < ( reference + size ) );
}
function isFloating(item) {
return (/left|right/).test(item.css("float")) || (/inline|table-cell/).test(item.css("display"));
}
$.widget("ui.sortable", $.ui.mouse, {
version: "1.10.3",
widgetEventPrefix: "sort",
ready: false,
options: {
appendTo: "parent",
axis: false,
connectWith: false,
containment: false,
cursor: "auto",
cursorAt: false,
dropOnEmpty: true,
forcePlaceholderSize: false,
forceHelperSize: false,
grid: false,
handle: false,
helper: "original",
items: "> *",
opacity: false,
placeholder: false,
revert: false,
scroll: true,
scrollSensitivity: 20,
scrollSpeed: 20,
scope: "default",
tolerance: "intersect",
zIndex: 1000,
// callbacks
activate: null,
beforeStop: null,
change: null,
deactivate: null,
out: null,
over: null,
receive: null,
remove: null,
sort: null,
start: null,
stop: null,
update: null
},
_create: function() {
var o = this.options;
this.containerCache = {};
this.element.addClass("ui-sortable");
//Get the items
this.refresh();
//Let's determine if the items are being displayed horizontally
this.floating = this.items.length ? o.axis === "x" || isFloating(this.items[0].item) : false;
//Let's determine the parent's offset
this.offset = this.element.offset();
//Initialize mouse events for interaction
this._mouseInit();
//We're ready to go
this.ready = true;
},
_destroy: function() {
this.element
.removeClass("ui-sortable ui-sortable-disabled");
this._mouseDestroy();
for ( var i = this.items.length - 1; i >= 0; i-- ) {
this.items[i].item.removeData(this.widgetName + "-item");
}
return this;
},
_setOption: function(key, value){
if ( key === "disabled" ) {
this.options[ key ] = value;
this.widget().toggleClass( "ui-sortable-disabled", !!value );
} else {
// Don't call widget base _setOption for disable as it adds ui-state-disabled class
$.Widget.prototype._setOption.apply(this, arguments);
}
},
_mouseCapture: function(event, overrideHandle) {
var currentItem = null,
validHandle = false,
that = this;
if (this.reverting) {
return false;
}
if(this.options.disabled || this.options.type === "static") {
return false;
}
//We have to refresh the items data once first
this._refreshItems(event);
//Find out if the clicked node (or one of its parents) is a actual item in this.items
$(event.target).parents().each(function() {
if($.data(this, that.widgetName + "-item") === that) {
currentItem = $(this);
return false;
}
});
if($.data(event.target, that.widgetName + "-item") === that) {
currentItem = $(event.target);
}
if(!currentItem) {
return false;
}
if(this.options.handle && !overrideHandle) {
$(this.options.handle, currentItem).find("*").addBack().each(function() {
if(this === event.target) {
validHandle = true;
}
});
if(!validHandle) {
return false;
}
}
this.currentItem = currentItem;
this._removeCurrentsFromItems();
return true;
},
_mouseStart: function(event, overrideHandle, noActivation) {
var i, body,
o = this.options;
this.currentContainer = this;
//We only need to call refreshPositions, because the refreshItems call has been moved to mouseCapture
this.refreshPositions();
//Create and append the visible helper
this.helper = this._createHelper(event);
//Cache the helper size
this._cacheHelperProportions();
/*
* - Position generation -
* This block generates everything position related - it's the core of draggables.
*/
//Cache the margins of the original element
this._cacheMargins();
//Get the next scrolling parent
this.scrollParent = this.helper.scrollParent();
//The element's absolute position on the page minus margins
this.offset = this.currentItem.offset();
this.offset = {
top: this.offset.top - this.margins.top,
left: this.offset.left - this.margins.left
};
$.extend(this.offset, {
click: { //Where the click happened, relative to the element
left: event.pageX - this.offset.left,
top: event.pageY - this.offset.top
},
parent: this._getParentOffset(),
relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper
});
// Only after we got the offset, we can change the helper's position to absolute
// TODO: Still need to figure out a way to make relative sorting possible
this.helper.css("position", "absolute");
this.cssPosition = this.helper.css("position");
//Generate the original position
this.originalPosition = this._generatePosition(event);
this.originalPageX = event.pageX;
this.originalPageY = event.pageY;
//Adjust the mouse offset relative to the helper if "cursorAt" is supplied
(o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt));
//Cache the former DOM position
this.domPosition = { prev: this.currentItem.prev()[0], parent: this.currentItem.parent()[0] };
//If the helper is not the original, hide the original so it's not playing any role during the drag, won't cause anything bad this way
if(this.helper[0] !== this.currentItem[0]) {
this.currentItem.hide();
}
//Create the placeholder
this._createPlaceholder();
//Set a containment if given in the options
if(o.containment) {
this._setContainment();
}
if( o.cursor && o.cursor !== "auto" ) { // cursor option
body = this.document.find( "body" );
// support: IE
this.storedCursor = body.css( "cursor" );
body.css( "cursor", o.cursor );
this.storedStylesheet = $( "<style>*{ cursor: "+o.cursor+" !important; }</style>" ).appendTo( body );
}
if(o.opacity) { // opacity option
if (this.helper.css("opacity")) {
this._storedOpacity = this.helper.css("opacity");
}
this.helper.css("opacity", o.opacity);
}
if(o.zIndex) { // zIndex option
if (this.helper.css("zIndex")) {
this._storedZIndex = this.helper.css("zIndex");
}
this.helper.css("zIndex", o.zIndex);
}
//Prepare scrolling
if(this.scrollParent[0] !== document && this.scrollParent[0].tagName !== "HTML") {
this.overflowOffset = this.scrollParent.offset();
}
//Call callbacks
this._trigger("start", event, this._uiHash());
//Recache the helper size
if(!this._preserveHelperProportions) {
this._cacheHelperProportions();
}
//Post "activate" events to possible containers
if( !noActivation ) {
for ( i = this.containers.length - 1; i >= 0; i-- ) {
this.containers[ i ]._trigger( "activate", event, this._uiHash( this ) );
}
}
//Prepare possible droppables
if($.ui.ddmanager) {
$.ui.ddmanager.current = this;
}
if ($.ui.ddmanager && !o.dropBehaviour) {
$.ui.ddmanager.prepareOffsets(this, event);
}
this.dragging = true;
this.helper.addClass("ui-sortable-helper");
this._mouseDrag(event); //Execute the drag once - this causes the helper not to be visible before getting its correct position
return true;
},
_mouseDrag: function(event) {
var i, item, itemElement, intersection,
o = this.options,
scrolled = false;
//Compute the helpers position
this.position = this._generatePosition(event);
this.positionAbs = this._convertPositionTo("absolute");
if (!this.lastPositionAbs) {
this.lastPositionAbs = this.positionAbs;
}
//Do scrolling
if(this.options.scroll) {
if(this.scrollParent[0] !== document && this.scrollParent[0].tagName !== "HTML") {
if((this.overflowOffset.top + this.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity) {
this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop + o.scrollSpeed;
} else if(event.pageY - this.overflowOffset.top < o.scrollSensitivity) {
this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop - o.scrollSpeed;
}
if((this.overflowOffset.left + this.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity) {
this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft + o.scrollSpeed;
} else if(event.pageX - this.overflowOffset.left < o.scrollSensitivity) {
this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft - o.scrollSpeed;
}
} else {
if(event.pageY - $(document).scrollTop() < o.scrollSensitivity) {
scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
} else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity) {
scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed);
}
if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity) {
scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed);
} else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity) {
scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed);
}
}
if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) {
$.ui.ddmanager.prepareOffsets(this, event);
}
}
//Regenerate the absolute position used for position checks
this.positionAbs = this._convertPositionTo("absolute");
//Set the helper position
if(!this.options.axis || this.options.axis !== "y") {
this.helper[0].style.left = this.position.left+"px";
}
if(!this.options.axis || this.options.axis !== "x") {
this.helper[0].style.top = this.position.top+"px";
}
//Rearrange
for (i = this.items.length - 1; i >= 0; i--) {
//Cache variables and intersection, continue if no intersection
item = this.items[i];
itemElement = item.item[0];
intersection = this._intersectsWithPointer(item);
if (!intersection) {
continue;
}
// Only put the placeholder inside the current Container, skip all
// items form other containers. This works because when moving
// an item from one container to another the
// currentContainer is switched before the placeholder is moved.
//
// Without this moving items in "sub-sortables" can cause the placeholder to jitter
// beetween the outer and inner container.
if (item.instance !== this.currentContainer) {
continue;
}
// cannot intersect with itself
// no useless actions that have been done before
// no action if the item moved is the parent of the item checked
if (itemElement !== this.currentItem[0] &&
this.placeholder[intersection === 1 ? "next" : "prev"]()[0] !== itemElement &&
!$.contains(this.placeholder[0], itemElement) &&
(this.options.type === "semi-dynamic" ? !$.contains(this.element[0], itemElement) : true)
) {
this.direction = intersection === 1 ? "down" : "up";
if (this.options.tolerance === "pointer" || this._intersectsWithSides(item)) {
this._rearrange(event, item);
} else {
break;
}
this._trigger("change", event, this._uiHash());
break;
}
}
//Post events to containers
this._contactContainers(event);
//Interconnect with droppables
if($.ui.ddmanager) {
$.ui.ddmanager.drag(this, event);
}
//Call callbacks
this._trigger("sort", event, this._uiHash());
this.lastPositionAbs = this.positionAbs;
return false;
},
_mouseStop: function(event, noPropagation) {
if(!event) {
return;
}
//If we are using droppables, inform the manager about the drop
if ($.ui.ddmanager && !this.options.dropBehaviour) {
$.ui.ddmanager.drop(this, event);
}
if(this.options.revert) {
var that = this,
cur = this.placeholder.offset(),
axis = this.options.axis,
animation = {};
if ( !axis || axis === "x" ) {
animation.left = cur.left - this.offset.parent.left - this.margins.left + (this.offsetParent[0] === document.body ? 0 : this.offsetParent[0].scrollLeft);
}
if ( !axis || axis === "y" ) {
animation.top = cur.top - this.offset.parent.top - this.margins.top + (this.offsetParent[0] === document.body ? 0 : this.offsetParent[0].scrollTop);
}
this.reverting = true;
$(this.helper).animate( animation, parseInt(this.options.revert, 10) || 500, function() {
that._clear(event);
});
} else {
this._clear(event, noPropagation);
}
return false;
},
cancel: function() {
if(this.dragging) {
this._mouseUp({ target: null });
if(this.options.helper === "original") {
this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper");
} else {
this.currentItem.show();
}
//Post deactivating events to containers
for (var i = this.containers.length - 1; i >= 0; i--){
this.containers[i]._trigger("deactivate", null, this._uiHash(this));
if(this.containers[i].containerCache.over) {
this.containers[i]._trigger("out", null, this._uiHash(this));
this.containers[i].containerCache.over = 0;
}
}
}
if (this.placeholder) {
//$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node!
if(this.placeholder[0].parentNode) {
this.placeholder[0].parentNode.removeChild(this.placeholder[0]);
}
if(this.options.helper !== "original" && this.helper && this.helper[0].parentNode) {
this.helper.remove();
}
$.extend(this, {
helper: null,
dragging: false,
reverting: false,
_noFinalSort: null
});
if(this.domPosition.prev) {
$(this.domPosition.prev).after(this.currentItem);
} else {
$(this.domPosition.parent).prepend(this.currentItem);
}
}
return this;
},
serialize: function(o) {
var items = this._getItemsAsjQuery(o && o.connected),
str = [];
o = o || {};
$(items).each(function() {
var res = ($(o.item || this).attr(o.attribute || "id") || "").match(o.expression || (/(.+)[\-=_](.+)/));
if (res) {
str.push((o.key || res[1]+"[]")+"="+(o.key && o.expression ? res[1] : res[2]));
}
});
if(!str.length && o.key) {
str.push(o.key + "=");
}
return str.join("&");
},
toArray: function(o) {
var items = this._getItemsAsjQuery(o && o.connected),
ret = [];
o = o || {};
items.each(function() { ret.push($(o.item || this).attr(o.attribute || "id") || ""); });
return ret;
},
/* Be careful with the following core functions */
_intersectsWith: function(item) {
var x1 = this.positionAbs.left,
x2 = x1 + this.helperProportions.width,
y1 = this.positionAbs.top,
y2 = y1 + this.helperProportions.height,
l = item.left,
r = l + item.width,
t = item.top,
b = t + item.height,
dyClick = this.offset.click.top,
dxClick = this.offset.click.left,
isOverElementHeight = ( this.options.axis === "x" ) || ( ( y1 + dyClick ) > t && ( y1 + dyClick ) < b ),
isOverElementWidth = ( this.options.axis === "y" ) || ( ( x1 + dxClick ) > l && ( x1 + dxClick ) < r ),
isOverElement = isOverElementHeight && isOverElementWidth;
if ( this.options.tolerance === "pointer" ||
this.options.forcePointerForContainers ||
(this.options.tolerance !== "pointer" && this.helperProportions[this.floating ? "width" : "height"] > item[this.floating ? "width" : "height"])
) {
return isOverElement;
} else {
return (l < x1 + (this.helperProportions.width / 2) && // Right Half
x2 - (this.helperProportions.width / 2) < r && // Left Half
t < y1 + (this.helperProportions.height / 2) && // Bottom Half
y2 - (this.helperProportions.height / 2) < b ); // Top Half
}
},
_intersectsWithPointer: function(item) {
var isOverElementHeight = (this.options.axis === "x") || isOverAxis(this.positionAbs.top + this.offset.click.top, item.top, item.height),
isOverElementWidth = (this.options.axis === "y") || isOverAxis(this.positionAbs.left + this.offset.click.left, item.left, item.width),
isOverElement = isOverElementHeight && isOverElementWidth,
verticalDirection = this._getDragVerticalDirection(),
horizontalDirection = this._getDragHorizontalDirection();
if (!isOverElement) {
return false;
}
return this.floating ?
( ((horizontalDirection && horizontalDirection === "right") || verticalDirection === "down") ? 2 : 1 )
: ( verticalDirection && (verticalDirection === "down" ? 2 : 1) );
},
_intersectsWithSides: function(item) {
var isOverBottomHalf = isOverAxis(this.positionAbs.top + this.offset.click.top, item.top + (item.height/2), item.height),
isOverRightHalf = isOverAxis(this.positionAbs.left + this.offset.click.left, item.left + (item.width/2), item.width),
verticalDirection = this._getDragVerticalDirection(),
horizontalDirection = this._getDragHorizontalDirection();
if (this.floating && horizontalDirection) {
return ((horizontalDirection === "right" && isOverRightHalf) || (horizontalDirection === "left" && !isOverRightHalf));
} else {
return verticalDirection && ((verticalDirection === "down" && isOverBottomHalf) || (verticalDirection === "up" && !isOverBottomHalf));
}
},
_getDragVerticalDirection: function() {
var delta = this.positionAbs.top - this.lastPositionAbs.top;
return delta !== 0 && (delta > 0 ? "down" : "up");
},
_getDragHorizontalDirection: function() {
var delta = this.positionAbs.left - this.lastPositionAbs.left;
return delta !== 0 && (delta > 0 ? "right" : "left");
},
refresh: function(event) {
this._refreshItems(event);
this.refreshPositions();
return this;
},
_connectWith: function() {
var options = this.options;
return options.connectWith.constructor === String ? [options.connectWith] : options.connectWith;
},
_getItemsAsjQuery: function(connected) {
var i, j, cur, inst,
items = [],
queries = [],
connectWith = this._connectWith();
if(connectWith && connected) {
for (i = connectWith.length - 1; i >= 0; i--){
cur = $(connectWith[i]);
for ( j = cur.length - 1; j >= 0; j--){
inst = $.data(cur[j], this.widgetFullName);
if(inst && inst !== this && !inst.options.disabled) {
queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element) : $(inst.options.items, inst.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"), inst]);
}
}
}
}
queries.push([$.isFunction(this.options.items) ? this.options.items.call(this.element, null, { options: this.options, item: this.currentItem }) : $(this.options.items, this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"), this]);
for (i = queries.length - 1; i >= 0; i--){
queries[i][0].each(function() {
items.push(this);
});
}
return $(items);
},
_removeCurrentsFromItems: function() {
var list = this.currentItem.find(":data(" + this.widgetName + "-item)");
this.items = $.grep(this.items, function (item) {
for (var j=0; j < list.length; j++) {
if(list[j] === item.item[0]) {
return false;
}
}
return true;
});
},
_refreshItems: function(event) {
this.items = [];
this.containers = [this];
var i, j, cur, inst, targetData, _queries, item, queriesLength,
items = this.items,
queries = [[$.isFunction(this.options.items) ? this.options.items.call(this.element[0], event, { item: this.currentItem }) : $(this.options.items, this.element), this]],
connectWith = this._connectWith();
if(connectWith && this.ready) { //Shouldn't be run the first time through due to massive slow-down
for (i = connectWith.length - 1; i >= 0; i--){
cur = $(connectWith[i]);
for (j = cur.length - 1; j >= 0; j--){
inst = $.data(cur[j], this.widgetFullName);
if(inst && inst !== this && !inst.options.disabled) {
queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element[0], event, { item: this.currentItem }) : $(inst.options.items, inst.element), inst]);
this.containers.push(inst);
}
}
}
}
for (i = queries.length - 1; i >= 0; i--) {
targetData = queries[i][1];
_queries = queries[i][0];
for (j=0, queriesLength = _queries.length; j < queriesLength; j++) {
item = $(_queries[j]);
item.data(this.widgetName + "-item", targetData); // Data for target checking (mouse manager)
items.push({
item: item,
instance: targetData,
width: 0, height: 0,
left: 0, top: 0
});
}
}
},
refreshPositions: function(fast) {
//This has to be redone because due to the item being moved out/into the offsetParent, the offsetParent's position will change
if(this.offsetParent && this.helper) {
this.offset.parent = this._getParentOffset();
}
var i, item, t, p;
for (i = this.items.length - 1; i >= 0; i--){
item = this.items[i];
//We ignore calculating positions of all connected containers when we're not over them
if(item.instance !== this.currentContainer && this.currentContainer && item.item[0] !== this.currentItem[0]) {
continue;
}
t = this.options.toleranceElement ? $(this.options.toleranceElement, item.item) : item.item;
if (!fast) {
item.width = t.outerWidth();
item.height = t.outerHeight();
}
p = t.offset();
item.left = p.left;
item.top = p.top;
}
if(this.options.custom && this.options.custom.refreshContainers) {
this.options.custom.refreshContainers.call(this);
} else {
for (i = this.containers.length - 1; i >= 0; i--){
p = this.containers[i].element.offset();
this.containers[i].containerCache.left = p.left;
this.containers[i].containerCache.top = p.top;
this.containers[i].containerCache.width = this.containers[i].element.outerWidth();
this.containers[i].containerCache.height = this.containers[i].element.outerHeight();
}
}
return this;
},
_createPlaceholder: function(that) {
that = that || this;
var className,
o = that.options;
if(!o.placeholder || o.placeholder.constructor === String) {
className = o.placeholder;
o.placeholder = {
element: function() {
var nodeName = that.currentItem[0].nodeName.toLowerCase(),
element = $( "<" + nodeName + ">", that.document[0] )
.addClass(className || that.currentItem[0].className+" ui-sortable-placeholder")
.removeClass("ui-sortable-helper");
if ( nodeName === "tr" ) {
that.currentItem.children().each(function() {
$( "<td> </td>", that.document[0] )
.attr( "colspan", $( this ).attr( "colspan" ) || 1 )
.appendTo( element );
});
} else if ( nodeName === "img" ) {
element.attr( "src", that.currentItem.attr( "src" ) );
}
if ( !className ) {
element.css( "visibility", "hidden" );
}
return element;
},
update: function(container, p) {
// 1. If a className is set as 'placeholder option, we don't force sizes - the class is responsible for that
// 2. The option 'forcePlaceholderSize can be enabled to force it even if a class name is specified
if(className && !o.forcePlaceholderSize) {
return;
}
//If the element doesn't have a actual height by itself (without styles coming from a stylesheet), it receives the inline height from the dragged item
if(!p.height()) { p.height(that.currentItem.innerHeight() - parseInt(that.currentItem.css("paddingTop")||0, 10) - parseInt(that.currentItem.css("paddingBottom")||0, 10)); }
if(!p.width()) { p.width(that.currentItem.innerWidth() - parseInt(that.currentItem.css("paddingLeft")||0, 10) - parseInt(that.currentItem.css("paddingRight")||0, 10)); }
}
};
}
//Create the placeholder
that.placeholder = $(o.placeholder.element.call(that.element, that.currentItem));
//Append it after the actual current item
that.currentItem.after(that.placeholder);
//Update the size of the placeholder (TODO: Logic to fuzzy, see line 316/317)
o.placeholder.update(that, that.placeholder);
},
_contactContainers: function(event) {
var i, j, dist, itemWithLeastDistance, posProperty, sizeProperty, base, cur, nearBottom, floating,
innermostContainer = null,
innermostIndex = null;
// get innermost container that intersects with item
for (i = this.containers.length - 1; i >= 0; i--) {
// never consider a container that's located within the item itself
if($.contains(this.currentItem[0], this.containers[i].element[0])) {
continue;
}
if(this._intersectsWith(this.containers[i].containerCache)) {
// if we've already found a container and it's more "inner" than this, then continue
if(innermostContainer && $.contains(this.containers[i].element[0], innermostContainer.element[0])) {
continue;
}
innermostContainer = this.containers[i];
innermostIndex = i;
} else {
// container doesn't intersect. trigger "out" event if necessary
if(this.containers[i].containerCache.over) {
this.containers[i]._trigger("out", event, this._uiHash(this));
this.containers[i].containerCache.over = 0;
}
}
}
// if no intersecting containers found, return
if(!innermostContainer) {
return;
}
// move the item into the container if it's not there already
if(this.containers.length === 1) {
if (!this.containers[innermostIndex].containerCache.over) {
this.containers[innermostIndex]._trigger("over", event, this._uiHash(this));
this.containers[innermostIndex].containerCache.over = 1;
}
} else {
//When entering a new container, we will find the item with the least distance and append our item near it
dist = 10000;
itemWithLeastDistance = null;
floating = innermostContainer.floating || isFloating(this.currentItem);
posProperty = floating ? "left" : "top";
sizeProperty = floating ? "width" : "height";
base = this.positionAbs[posProperty] + this.offset.click[posProperty];
for (j = this.items.length - 1; j >= 0; j--) {
if(!$.contains(this.containers[innermostIndex].element[0], this.items[j].item[0])) {
continue;
}
if(this.items[j].item[0] === this.currentItem[0]) {
continue;
}
if (floating && !isOverAxis(this.positionAbs.top + this.offset.click.top, this.items[j].top, this.items[j].height)) {
continue;
}
cur = this.items[j].item.offset()[posProperty];
nearBottom = false;
if(Math.abs(cur - base) > Math.abs(cur + this.items[j][sizeProperty] - base)){
nearBottom = true;
cur += this.items[j][sizeProperty];
}
if(Math.abs(cur - base) < dist) {
dist = Math.abs(cur - base); itemWithLeastDistance = this.items[j];
this.direction = nearBottom ? "up": "down";
}
}
//Check if dropOnEmpty is enabled
if(!itemWithLeastDistance && !this.options.dropOnEmpty) {
return;
}
if(this.currentContainer === this.containers[innermostIndex]) {
return;
}
itemWithLeastDistance ? this._rearrange(event, itemWithLeastDistance, null, true) : this._rearrange(event, null, this.containers[innermostIndex].element, true);
this._trigger("change", event, this._uiHash());
this.containers[innermostIndex]._trigger("change", event, this._uiHash(this));
this.currentContainer = this.containers[innermostIndex];
//Update the placeholder
this.options.placeholder.update(this.currentContainer, this.placeholder);
this.containers[innermostIndex]._trigger("over", event, this._uiHash(this));
this.containers[innermostIndex].containerCache.over = 1;
}
},
_createHelper: function(event) {
var o = this.options,
helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event, this.currentItem])) : (o.helper === "clone" ? this.currentItem.clone() : this.currentItem);
//Add the helper to the DOM if that didn't happen already
if(!helper.parents("body").length) {
$(o.appendTo !== "parent" ? o.appendTo : this.currentItem[0].parentNode)[0].appendChild(helper[0]);
}
if(helper[0] === this.currentItem[0]) {
this._storedCSS = { width: this.currentItem[0].style.width, height: this.currentItem[0].style.height, position: this.currentItem.css("position"), top: this.currentItem.css("top"), left: this.currentItem.css("left") };
}
if(!helper[0].style.width || o.forceHelperSize) {
helper.width(this.currentItem.width());
}
if(!helper[0].style.height || o.forceHelperSize) {
helper.height(this.currentItem.height());
}
return helper;
},
_adjustOffsetFromHelper: function(obj) {
if (typeof obj === "string") {
obj = obj.split(" ");
}
if ($.isArray(obj)) {
obj = {left: +obj[0], top: +obj[1] || 0};
}
if ("left" in obj) {
this.offset.click.left = obj.left + this.margins.left;
}
if ("right" in obj) {
this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
}
if ("top" in obj) {
this.offset.click.top = obj.top + this.margins.top;
}
if ("bottom" in obj) {
this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
}
},
_getParentOffset: function() {
//Get the offsetParent and cache its position
this.offsetParent = this.helper.offsetParent();
var po = this.offsetParent.offset();
// This is a special case where we need to modify a offset calculated on start, since the following happened:
// 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent
// 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that
// the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag
if(this.cssPosition === "absolute" && this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) {
po.left += this.scrollParent.scrollLeft();
po.top += this.scrollParent.scrollTop();
}
// This needs to be actually done for all browsers, since pageX/pageY includes this information
// with an ugly IE fix
if( this.offsetParent[0] === document.body || (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() === "html" && $.ui.ie)) {
po = { top: 0, left: 0 };
}
return {
top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0),
left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0)
};
},
_getRelativeOffset: function() {
if(this.cssPosition === "relative") {
var p = this.currentItem.position();
return {
top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(),
left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft()
};
} else {
return { top: 0, left: 0 };
}
},
_cacheMargins: function() {
this.margins = {
left: (parseInt(this.currentItem.css("marginLeft"),10) || 0),
top: (parseInt(this.currentItem.css("marginTop"),10) || 0)
};
},
_cacheHelperProportions: function() {
this.helperProportions = {
width: this.helper.outerWidth(),
height: this.helper.outerHeight()
};
},
_setContainment: function() {
var ce, co, over,
o = this.options;
if(o.containment === "parent") {
o.containment = this.helper[0].parentNode;
}
if(o.containment === "document" || o.containment === "window") {
this.containment = [
0 - this.offset.relative.left - this.offset.parent.left,
0 - this.offset.relative.top - this.offset.parent.top,
$(o.containment === "document" ? document : window).width() - this.helperProportions.width - this.margins.left,
($(o.containment === "document" ? document : window).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top
];
}
if(!(/^(document|window|parent)$/).test(o.containment)) {
ce = $(o.containment)[0];
co = $(o.containment).offset();
over = ($(ce).css("overflow") !== "hidden");
this.containment = [
co.left + (parseInt($(ce).css("borderLeftWidth"),10) || 0) + (parseInt($(ce).css("paddingLeft"),10) || 0) - this.margins.left,
co.top + (parseInt($(ce).css("borderTopWidth"),10) || 0) + (parseInt($(ce).css("paddingTop"),10) || 0) - this.margins.top,
co.left+(over ? Math.max(ce.scrollWidth,ce.offsetWidth) : ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"),10) || 0) - (parseInt($(ce).css("paddingRight"),10) || 0) - this.helperProportions.width - this.margins.left,
co.top+(over ? Math.max(ce.scrollHeight,ce.offsetHeight) : ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"),10) || 0) - (parseInt($(ce).css("paddingBottom"),10) || 0) - this.helperProportions.height - this.margins.top
];
}
},
_convertPositionTo: function(d, pos) {
if(!pos) {
pos = this.position;
}
var mod = d === "absolute" ? 1 : -1,
scroll = this.cssPosition === "absolute" && !(this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent,
scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);
return {
top: (
pos.top + // The absolute mouse position
this.offset.relative.top * mod + // Only for relative positioned nodes: Relative offset from element to offset parent
this.offset.parent.top * mod - // The offsetParent's offset without borders (offset + border)
( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod)
),
left: (
pos.left + // The absolute mouse position
this.offset.relative.left * mod + // Only for relative positioned nodes: Relative offset from element to offset parent
this.offset.parent.left * mod - // The offsetParent's offset without borders (offset + border)
( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ) * mod)
)
};
},
_generatePosition: function(event) {
var top, left,
o = this.options,
pageX = event.pageX,
pageY = event.pageY,
scroll = this.cssPosition === "absolute" && !(this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);
// This is another very weird special case that only happens for relative elements:
// 1. If the css position is relative
// 2. and the scroll parent is the document or similar to the offset parent
// we have to refresh the relative offset during the scroll so there are no jumps
if(this.cssPosition === "relative" && !(this.scrollParent[0] !== document && this.scrollParent[0] !== this.offsetParent[0])) {
this.offset.relative = this._getRelativeOffset();
}
/*
* - Position constraining -
* Constrain the position to a mix of grid, containment.
*/
if(this.originalPosition) { //If we are not dragging yet, we won't check for options
if(this.containment) {
if(event.pageX - this.offset.click.left < this.containment[0]) {
pageX = this.containment[0] + this.offset.click.left;
}
if(event.pageY - this.offset.click.top < this.containment[1]) {
pageY = this.containment[1] + this.offset.click.top;
}
if(event.pageX - this.offset.click.left > this.containment[2]) {
pageX = this.containment[2] + this.offset.click.left;
}
if(event.pageY - this.offset.click.top > this.containment[3]) {
pageY = this.containment[3] + this.offset.click.top;
}
}
if(o.grid) {
top = this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1];
pageY = this.containment ? ( (top - this.offset.click.top >= this.containment[1] && top - this.offset.click.top <= this.containment[3]) ? top : ((top - this.offset.click.top >= this.containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top;
left = this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0];
pageX = this.containment ? ( (left - this.offset.click.left >= this.containment[0] && left - this.offset.click.left <= this.containment[2]) ? left : ((left - this.offset.click.left >= this.containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left;
}
}
return {
top: (
pageY - // The absolute mouse position
this.offset.click.top - // Click offset (relative to the element)
this.offset.relative.top - // Only for relative positioned nodes: Relative offset from element to offset parent
this.offset.parent.top + // The offsetParent's offset without borders (offset + border)
( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ))
),
left: (
pageX - // The absolute mouse position
this.offset.click.left - // Click offset (relative to the element)
this.offset.relative.left - // Only for relative positioned nodes: Relative offset from element to offset parent
this.offset.parent.left + // The offsetParent's offset without borders (offset + border)
( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ))
)
};
},
_rearrange: function(event, i, a, hardRefresh) {
a ? a[0].appendChild(this.placeholder[0]) : i.item[0].parentNode.insertBefore(this.placeholder[0], (this.direction === "down" ? i.item[0] : i.item[0].nextSibling));
//Various things done here to improve the performance:
// 1. we create a setTimeout, that calls refreshPositions
// 2. on the instance, we have a counter variable, that get's higher after every append
// 3. on the local scope, we copy the counter variable, and check in the timeout, if it's still the same
// 4. this lets only the last addition to the timeout stack through
this.counter = this.counter ? ++this.counter : 1;
var counter = this.counter;
this._delay(function() {
if(counter === this.counter) {
this.refreshPositions(!hardRefresh); //Precompute after each DOM insertion, NOT on mousemove
}
});
},
_clear: function(event, noPropagation) {
this.reverting = false;
// We delay all events that have to be triggered to after the point where the placeholder has been removed and
// everything else normalized again
var i,
delayedTriggers = [];
// We first have to update the dom position of the actual currentItem
// Note: don't do it if the current item is already removed (by a user), or it gets reappended (see #4088)
if(!this._noFinalSort && this.currentItem.parent().length) {
this.placeholder.before(this.currentItem);
}
this._noFinalSort = null;
if(this.helper[0] === this.currentItem[0]) {
for(i in this._storedCSS) {
if(this._storedCSS[i] === "auto" || this._storedCSS[i] === "static") {
this._storedCSS[i] = "";
}
}
this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper");
} else {
this.currentItem.show();
}
if(this.fromOutside && !noPropagation) {
delayedTriggers.push(function(event) { this._trigger("receive", event, this._uiHash(this.fromOutside)); });
}
if((this.fromOutside || this.domPosition.prev !== this.currentItem.prev().not(".ui-sortable-helper")[0] || this.domPosition.parent !== this.currentItem.parent()[0]) && !noPropagation) {
delayedTriggers.push(function(event) { this._trigger("update", event, this._uiHash()); }); //Trigger update callback if the DOM position has changed
}
// Check if the items Container has Changed and trigger appropriate
// events.
if (this !== this.currentContainer) {
if(!noPropagation) {
delayedTriggers.push(function(event) { this._trigger("remove", event, this._uiHash()); });
delayedTriggers.push((function(c) { return function(event) { c._trigger("receive", event, this._uiHash(this)); }; }).call(this, this.currentContainer));
delayedTriggers.push((function(c) { return function(event) { c._trigger("update", event, this._uiHash(this)); }; }).call(this, this.currentContainer));
}
}
//Post events to containers
for (i = this.containers.length - 1; i >= 0; i--){
if(!noPropagation) {
delayedTriggers.push((function(c) { return function(event) { c._trigger("deactivate", event, this._uiHash(this)); }; }).call(this, this.containers[i]));
}
if(this.containers[i].containerCache.over) {
delayedTriggers.push((function(c) { return function(event) { c._trigger("out", event, this._uiHash(this)); }; }).call(this, this.containers[i]));
this.containers[i].containerCache.over = 0;
}
}
//Do what was originally in plugins
if ( this.storedCursor ) {
this.document.find( "body" ).css( "cursor", this.storedCursor );
this.storedStylesheet.remove();
}
if(this._storedOpacity) {
this.helper.css("opacity", this._storedOpacity);
}
if(this._storedZIndex) {
this.helper.css("zIndex", this._storedZIndex === "auto" ? "" : this._storedZIndex);
}
this.dragging = false;
if(this.cancelHelperRemoval) {
if(!noPropagation) {
this._trigger("beforeStop", event, this._uiHash());
for (i=0; i < delayedTriggers.length; i++) {
delayedTriggers[i].call(this, event);
} //Trigger all delayed events
this._trigger("stop", event, this._uiHash());
}
this.fromOutside = false;
return false;
}
if(!noPropagation) {
this._trigger("beforeStop", event, this._uiHash());
}
//$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node!
this.placeholder[0].parentNode.removeChild(this.placeholder[0]);
if(this.helper[0] !== this.currentItem[0]) {
this.helper.remove();
}
this.helper = null;
if(!noPropagation) {
for (i=0; i < delayedTriggers.length; i++) {
delayedTriggers[i].call(this, event);
} //Trigger all delayed events
this._trigger("stop", event, this._uiHash());
}
this.fromOutside = false;
return true;
},
_trigger: function() {
if ($.Widget.prototype._trigger.apply(this, arguments) === false) {
this.cancel();
}
},
_uiHash: function(_inst) {
var inst = _inst || this;
return {
helper: inst.helper,
placeholder: inst.placeholder || $([]),
position: inst.position,
originalPosition: inst.originalPosition,
offset: inst.positionAbs,
item: inst.currentItem,
sender: _inst ? _inst.element : null
};
}
});
})(jQuery);
(function($, undefined) {
var dataSpace = "ui-effects-";
$.effects = {
effect: {}
};
/*!
* jQuery Color Animations v2.1.2
* https://github.com/jquery/jquery-color
*
* Copyright 2013 jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* Date: Wed Jan 16 08:47:09 2013 -0600
*/
(function( jQuery, undefined ) {
var stepHooks = "backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor",
// plusequals test for += 100 -= 100
rplusequals = /^([\-+])=\s*(\d+\.?\d*)/,
// a set of RE's that can match strings and generate color tuples.
stringParsers = [{
re: /rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
parse: function( execResult ) {
return [
execResult[ 1 ],
execResult[ 2 ],
execResult[ 3 ],
execResult[ 4 ]
];
}
}, {
re: /rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
parse: function( execResult ) {
return [
execResult[ 1 ] * 2.55,
execResult[ 2 ] * 2.55,
execResult[ 3 ] * 2.55,
execResult[ 4 ]
];
}
}, {
// this regex ignores A-F because it's compared against an already lowercased string
re: /#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/,
parse: function( execResult ) {
return [
parseInt( execResult[ 1 ], 16 ),
parseInt( execResult[ 2 ], 16 ),
parseInt( execResult[ 3 ], 16 )
];
}
}, {
// this regex ignores A-F because it's compared against an already lowercased string
re: /#([a-f0-9])([a-f0-9])([a-f0-9])/,
parse: function( execResult ) {
return [
parseInt( execResult[ 1 ] + execResult[ 1 ], 16 ),
parseInt( execResult[ 2 ] + execResult[ 2 ], 16 ),
parseInt( execResult[ 3 ] + execResult[ 3 ], 16 )
];
}
}, {
re: /hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
space: "hsla",
parse: function( execResult ) {
return [
execResult[ 1 ],
execResult[ 2 ] / 100,
execResult[ 3 ] / 100,
execResult[ 4 ]
];
}
}],
// jQuery.Color( )
color = jQuery.Color = function( color, green, blue, alpha ) {
return new jQuery.Color.fn.parse( color, green, blue, alpha );
},
spaces = {
rgba: {
props: {
red: {
idx: 0,
type: "byte"
},
green: {
idx: 1,
type: "byte"
},
blue: {
idx: 2,
type: "byte"
}
}
},
hsla: {
props: {
hue: {
idx: 0,
type: "degrees"
},
saturation: {
idx: 1,
type: "percent"
},
lightness: {
idx: 2,
type: "percent"
}
}
}
},
propTypes = {
"byte": {
floor: true,
max: 255
},
"percent": {
max: 1
},
"degrees": {
mod: 360,
floor: true
}
},
support = color.support = {},
// element for support tests
supportElem = jQuery( "<p>" )[ 0 ],
// colors = jQuery.Color.names
colors,
// local aliases of functions called often
each = jQuery.each;
// determine rgba support immediately
supportElem.style.cssText = "background-color:rgba(1,1,1,.5)";
support.rgba = supportElem.style.backgroundColor.indexOf( "rgba" ) > -1;
// define cache name and alpha properties
// for rgba and hsla spaces
each( spaces, function( spaceName, space ) {
space.cache = "_" + spaceName;
space.props.alpha = {
idx: 3,
type: "percent",
def: 1
};
});
function clamp( value, prop, allowEmpty ) {
var type = propTypes[ prop.type ] || {};
if ( value == null ) {
return (allowEmpty || !prop.def) ? null : prop.def;
}
// ~~ is an short way of doing floor for positive numbers
value = type.floor ? ~~value : parseFloat( value );
// IE will pass in empty strings as value for alpha,
// which will hit this case
if ( isNaN( value ) ) {
return prop.def;
}
if ( type.mod ) {
// we add mod before modding to make sure that negatives values
// get converted properly: -10 -> 350
return (value + type.mod) % type.mod;
}
// for now all property types without mod have min and max
return 0 > value ? 0 : type.max < value ? type.max : value;
}
function stringParse( string ) {
var inst = color(),
rgba = inst._rgba = [];
string = string.toLowerCase();
each( stringParsers, function( i, parser ) {
var parsed,
match = parser.re.exec( string ),
values = match && parser.parse( match ),
spaceName = parser.space || "rgba";
if ( values ) {
parsed = inst[ spaceName ]( values );
// if this was an rgba parse the assignment might happen twice
// oh well....
inst[ spaces[ spaceName ].cache ] = parsed[ spaces[ spaceName ].cache ];
rgba = inst._rgba = parsed._rgba;
// exit each( stringParsers ) here because we matched
return false;
}
});
// Found a stringParser that handled it
if ( rgba.length ) {
// if this came from a parsed string, force "transparent" when alpha is 0
// chrome, (and maybe others) return "transparent" as rgba(0,0,0,0)
if ( rgba.join() === "0,0,0,0" ) {
jQuery.extend( rgba, colors.transparent );
}
return inst;
}
// named colors
return colors[ string ];
}
color.fn = jQuery.extend( color.prototype, {
parse: function( red, green, blue, alpha ) {
if ( red === undefined ) {
this._rgba = [ null, null, null, null ];
return this;
}
if ( red.jquery || red.nodeType ) {
red = jQuery( red ).css( green );
green = undefined;
}
var inst = this,
type = jQuery.type( red ),
rgba = this._rgba = [];
// more than 1 argument specified - assume ( red, green, blue, alpha )
if ( green !== undefined ) {
red = [ red, green, blue, alpha ];
type = "array";
}
if ( type === "string" ) {
return this.parse( stringParse( red ) || colors._default );
}
if ( type === "array" ) {
each( spaces.rgba.props, function( key, prop ) {
rgba[ prop.idx ] = clamp( red[ prop.idx ], prop );
});
return this;
}
if ( type === "object" ) {
if ( red instanceof color ) {
each( spaces, function( spaceName, space ) {
if ( red[ space.cache ] ) {
inst[ space.cache ] = red[ space.cache ].slice();
}
});
} else {
each( spaces, function( spaceName, space ) {
var cache = space.cache;
each( space.props, function( key, prop ) {
// if the cache doesn't exist, and we know how to convert
if ( !inst[ cache ] && space.to ) {
// if the value was null, we don't need to copy it
// if the key was alpha, we don't need to copy it either
if ( key === "alpha" || red[ key ] == null ) {
return;
}
inst[ cache ] = space.to( inst._rgba );
}
// this is the only case where we allow nulls for ALL properties.
// call clamp with alwaysAllowEmpty
inst[ cache ][ prop.idx ] = clamp( red[ key ], prop, true );
});
// everything defined but alpha?
if ( inst[ cache ] && jQuery.inArray( null, inst[ cache ].slice( 0, 3 ) ) < 0 ) {
// use the default of 1
inst[ cache ][ 3 ] = 1;
if ( space.from ) {
inst._rgba = space.from( inst[ cache ] );
}
}
});
}
return this;
}
},
is: function( compare ) {
var is = color( compare ),
same = true,
inst = this;
each( spaces, function( _, space ) {
var localCache,
isCache = is[ space.cache ];
if (isCache) {
localCache = inst[ space.cache ] || space.to && space.to( inst._rgba ) || [];
each( space.props, function( _, prop ) {
if ( isCache[ prop.idx ] != null ) {
same = ( isCache[ prop.idx ] === localCache[ prop.idx ] );
return same;
}
});
}
return same;
});
return same;
},
_space: function() {
var used = [],
inst = this;
each( spaces, function( spaceName, space ) {
if ( inst[ space.cache ] ) {
used.push( spaceName );
}
});
return used.pop();
},
transition: function( other, distance ) {
var end = color( other ),
spaceName = end._space(),
space = spaces[ spaceName ],
startColor = this.alpha() === 0 ? color( "transparent" ) : this,
start = startColor[ space.cache ] || space.to( startColor._rgba ),
result = start.slice();
end = end[ space.cache ];
each( space.props, function( key, prop ) {
var index = prop.idx,
startValue = start[ index ],
endValue = end[ index ],
type = propTypes[ prop.type ] || {};
// if null, don't override start value
if ( endValue === null ) {
return;
}
// if null - use end
if ( startValue === null ) {
result[ index ] = endValue;
} else {
if ( type.mod ) {
if ( endValue - startValue > type.mod / 2 ) {
startValue += type.mod;
} else if ( startValue - endValue > type.mod / 2 ) {
startValue -= type.mod;
}
}
result[ index ] = clamp( ( endValue - startValue ) * distance + startValue, prop );
}
});
return this[ spaceName ]( result );
},
blend: function( opaque ) {
// if we are already opaque - return ourself
if ( this._rgba[ 3 ] === 1 ) {
return this;
}
var rgb = this._rgba.slice(),
a = rgb.pop(),
blend = color( opaque )._rgba;
return color( jQuery.map( rgb, function( v, i ) {
return ( 1 - a ) * blend[ i ] + a * v;
}));
},
toRgbaString: function() {
var prefix = "rgba(",
rgba = jQuery.map( this._rgba, function( v, i ) {
return v == null ? ( i > 2 ? 1 : 0 ) : v;
});
if ( rgba[ 3 ] === 1 ) {
rgba.pop();
prefix = "rgb(";
}
return prefix + rgba.join() + ")";
},
toHslaString: function() {
var prefix = "hsla(",
hsla = jQuery.map( this.hsla(), function( v, i ) {
if ( v == null ) {
v = i > 2 ? 1 : 0;
}
// catch 1 and 2
if ( i && i < 3 ) {
v = Math.round( v * 100 ) + "%";
}
return v;
});
if ( hsla[ 3 ] === 1 ) {
hsla.pop();
prefix = "hsl(";
}
return prefix + hsla.join() + ")";
},
toHexString: function( includeAlpha ) {
var rgba = this._rgba.slice(),
alpha = rgba.pop();
if ( includeAlpha ) {
rgba.push( ~~( alpha * 255 ) );
}
return "#" + jQuery.map( rgba, function( v ) {
// default to 0 when nulls exist
v = ( v || 0 ).toString( 16 );
return v.length === 1 ? "0" + v : v;
}).join("");
},
toString: function() {
return this._rgba[ 3 ] === 0 ? "transparent" : this.toRgbaString();
}
});
color.fn.parse.prototype = color.fn;
// hsla conversions adapted from:
// https://code.google.com/p/maashaack/source/browse/packages/graphics/trunk/src/graphics/colors/HUE2RGB.as?r=5021
function hue2rgb( p, q, h ) {
h = ( h + 1 ) % 1;
if ( h * 6 < 1 ) {
return p + (q - p) * h * 6;
}
if ( h * 2 < 1) {
return q;
}
if ( h * 3 < 2 ) {
return p + (q - p) * ((2/3) - h) * 6;
}
return p;
}
spaces.hsla.to = function ( rgba ) {
if ( rgba[ 0 ] == null || rgba[ 1 ] == null || rgba[ 2 ] == null ) {
return [ null, null, null, rgba[ 3 ] ];
}
var r = rgba[ 0 ] / 255,
g = rgba[ 1 ] / 255,
b = rgba[ 2 ] / 255,
a = rgba[ 3 ],
max = Math.max( r, g, b ),
min = Math.min( r, g, b ),
diff = max - min,
add = max + min,
l = add * 0.5,
h, s;
if ( min === max ) {
h = 0;
} else if ( r === max ) {
h = ( 60 * ( g - b ) / diff ) + 360;
} else if ( g === max ) {
h = ( 60 * ( b - r ) / diff ) + 120;
} else {
h = ( 60 * ( r - g ) / diff ) + 240;
}
// chroma (diff) == 0 means greyscale which, by definition, saturation = 0%
// otherwise, saturation is based on the ratio of chroma (diff) to lightness (add)
if ( diff === 0 ) {
s = 0;
} else if ( l <= 0.5 ) {
s = diff / add;
} else {
s = diff / ( 2 - add );
}
return [ Math.round(h) % 360, s, l, a == null ? 1 : a ];
};
spaces.hsla.from = function ( hsla ) {
if ( hsla[ 0 ] == null || hsla[ 1 ] == null || hsla[ 2 ] == null ) {
return [ null, null, null, hsla[ 3 ] ];
}
var h = hsla[ 0 ] / 360,
s = hsla[ 1 ],
l = hsla[ 2 ],
a = hsla[ 3 ],
q = l <= 0.5 ? l * ( 1 + s ) : l + s - l * s,
p = 2 * l - q;
return [
Math.round( hue2rgb( p, q, h + ( 1 / 3 ) ) * 255 ),
Math.round( hue2rgb( p, q, h ) * 255 ),
Math.round( hue2rgb( p, q, h - ( 1 / 3 ) ) * 255 ),
a
];
};
each( spaces, function( spaceName, space ) {
var props = space.props,
cache = space.cache,
to = space.to,
from = space.from;
// makes rgba() and hsla()
color.fn[ spaceName ] = function( value ) {
// generate a cache for this space if it doesn't exist
if ( to && !this[ cache ] ) {
this[ cache ] = to( this._rgba );
}
if ( value === undefined ) {
return this[ cache ].slice();
}
var ret,
type = jQuery.type( value ),
arr = ( type === "array" || type === "object" ) ? value : arguments,
local = this[ cache ].slice();
each( props, function( key, prop ) {
var val = arr[ type === "object" ? key : prop.idx ];
if ( val == null ) {
val = local[ prop.idx ];
}
local[ prop.idx ] = clamp( val, prop );
});
if ( from ) {
ret = color( from( local ) );
ret[ cache ] = local;
return ret;
} else {
return color( local );
}
};
// makes red() green() blue() alpha() hue() saturation() lightness()
each( props, function( key, prop ) {
// alpha is included in more than one space
if ( color.fn[ key ] ) {
return;
}
color.fn[ key ] = function( value ) {
var vtype = jQuery.type( value ),
fn = ( key === "alpha" ? ( this._hsla ? "hsla" : "rgba" ) : spaceName ),
local = this[ fn ](),
cur = local[ prop.idx ],
match;
if ( vtype === "undefined" ) {
return cur;
}
if ( vtype === "function" ) {
value = value.call( this, cur );
vtype = jQuery.type( value );
}
if ( value == null && prop.empty ) {
return this;
}
if ( vtype === "string" ) {
match = rplusequals.exec( value );
if ( match ) {
value = cur + parseFloat( match[ 2 ] ) * ( match[ 1 ] === "+" ? 1 : -1 );
}
}
local[ prop.idx ] = value;
return this[ fn ]( local );
};
});
});
// add cssHook and .fx.step function for each named hook.
// accept a space separated string of properties
color.hook = function( hook ) {
var hooks = hook.split( " " );
each( hooks, function( i, hook ) {
jQuery.cssHooks[ hook ] = {
set: function( elem, value ) {
var parsed, curElem,
backgroundColor = "";
if ( value !== "transparent" && ( jQuery.type( value ) !== "string" || ( parsed = stringParse( value ) ) ) ) {
value = color( parsed || value );
if ( !support.rgba && value._rgba[ 3 ] !== 1 ) {
curElem = hook === "backgroundColor" ? elem.parentNode : elem;
while (
(backgroundColor === "" || backgroundColor === "transparent") &&
curElem && curElem.style
) {
try {
backgroundColor = jQuery.css( curElem, "backgroundColor" );
curElem = curElem.parentNode;
} catch ( e ) {
}
}
value = value.blend( backgroundColor && backgroundColor !== "transparent" ?
backgroundColor :
"_default" );
}
value = value.toRgbaString();
}
try {
elem.style[ hook ] = value;
} catch( e ) {
// wrapped to prevent IE from throwing errors on "invalid" values like 'auto' or 'inherit'
}
}
};
jQuery.fx.step[ hook ] = function( fx ) {
if ( !fx.colorInit ) {
fx.start = color( fx.elem, hook );
fx.end = color( fx.end );
fx.colorInit = true;
}
jQuery.cssHooks[ hook ].set( fx.elem, fx.start.transition( fx.end, fx.pos ) );
};
});
};
color.hook( stepHooks );
jQuery.cssHooks.borderColor = {
expand: function( value ) {
var expanded = {};
each( [ "Top", "Right", "Bottom", "Left" ], function( i, part ) {
expanded[ "border" + part + "Color" ] = value;
});
return expanded;
}
};
// Basic color names only.
// Usage of any of the other color names requires adding yourself or including
// jquery.color.svg-names.js.
colors = jQuery.Color.names = {
// 4.1. Basic color keywords
aqua: "#00ffff",
black: "#000000",
blue: "#0000ff",
fuchsia: "#ff00ff",
gray: "#808080",
green: "#008000",
lime: "#00ff00",
maroon: "#800000",
navy: "#000080",
olive: "#808000",
purple: "#800080",
red: "#ff0000",
silver: "#c0c0c0",
teal: "#008080",
white: "#ffffff",
yellow: "#ffff00",
// 4.2.3. "transparent" color keyword
transparent: [ null, null, null, 0 ],
_default: "#ffffff"
};
})( jQuery );
/******************************************************************************/
/****************************** CLASS ANIMATIONS ******************************/
/******************************************************************************/
(function() {
var classAnimationActions = [ "add", "remove", "toggle" ],
shorthandStyles = {
border: 1,
borderBottom: 1,
borderColor: 1,
borderLeft: 1,
borderRight: 1,
borderTop: 1,
borderWidth: 1,
margin: 1,
padding: 1
};
$.each([ "borderLeftStyle", "borderRightStyle", "borderBottomStyle", "borderTopStyle" ], function( _, prop ) {
$.fx.step[ prop ] = function( fx ) {
if ( fx.end !== "none" && !fx.setAttr || fx.pos === 1 && !fx.setAttr ) {
jQuery.style( fx.elem, prop, fx.end );
fx.setAttr = true;
}
};
});
function getElementStyles( elem ) {
var key, len,
style = elem.ownerDocument.defaultView ?
elem.ownerDocument.defaultView.getComputedStyle( elem, null ) :
elem.currentStyle,
styles = {};
if ( style && style.length && style[ 0 ] && style[ style[ 0 ] ] ) {
len = style.length;
while ( len-- ) {
key = style[ len ];
if ( typeof style[ key ] === "string" ) {
styles[ $.camelCase( key ) ] = style[ key ];
}
}
// support: Opera, IE <9
} else {
for ( key in style ) {
if ( typeof style[ key ] === "string" ) {
styles[ key ] = style[ key ];
}
}
}
return styles;
}
function styleDifference( oldStyle, newStyle ) {
var diff = {},
name, value;
for ( name in newStyle ) {
value = newStyle[ name ];
if ( oldStyle[ name ] !== value ) {
if ( !shorthandStyles[ name ] ) {
if ( $.fx.step[ name ] || !isNaN( parseFloat( value ) ) ) {
diff[ name ] = value;
}
}
}
}
return diff;
}
// support: jQuery <1.8
if ( !$.fn.addBack ) {
$.fn.addBack = function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter( selector )
);
};
}
$.effects.animateClass = function( value, duration, easing, callback ) {
var o = $.speed( duration, easing, callback );
return this.queue( function() {
var animated = $( this ),
baseClass = animated.attr( "class" ) || "",
applyClassChange,
allAnimations = o.children ? animated.find( "*" ).addBack() : animated;
// map the animated objects to store the original styles.
allAnimations = allAnimations.map(function() {
var el = $( this );
return {
el: el,
start: getElementStyles( this )
};
});
// apply class change
applyClassChange = function() {
$.each( classAnimationActions, function(i, action) {
if ( value[ action ] ) {
animated[ action + "Class" ]( value[ action ] );
}
});
};
applyClassChange();
// map all animated objects again - calculate new styles and diff
allAnimations = allAnimations.map(function() {
this.end = getElementStyles( this.el[ 0 ] );
this.diff = styleDifference( this.start, this.end );
return this;
});
// apply original class
animated.attr( "class", baseClass );
// map all animated objects again - this time collecting a promise
allAnimations = allAnimations.map(function() {
var styleInfo = this,
dfd = $.Deferred(),
opts = $.extend({}, o, {
queue: false,
complete: function() {
dfd.resolve( styleInfo );
}
});
this.el.animate( this.diff, opts );
return dfd.promise();
});
// once all animations have completed:
$.when.apply( $, allAnimations.get() ).done(function() {
// set the final class
applyClassChange();
// for each animated element,
// clear all css properties that were animated
$.each( arguments, function() {
var el = this.el;
$.each( this.diff, function(key) {
el.css( key, "" );
});
});
// this is guarnteed to be there if you use jQuery.speed()
// it also handles dequeuing the next anim...
o.complete.call( animated[ 0 ] );
});
});
};
$.fn.extend({
addClass: (function( orig ) {
return function( classNames, speed, easing, callback ) {
return speed ?
$.effects.animateClass.call( this,
{ add: classNames }, speed, easing, callback ) :
orig.apply( this, arguments );
};
})( $.fn.addClass ),
removeClass: (function( orig ) {
return function( classNames, speed, easing, callback ) {
return arguments.length > 1 ?
$.effects.animateClass.call( this,
{ remove: classNames }, speed, easing, callback ) :
orig.apply( this, arguments );
};
})( $.fn.removeClass ),
toggleClass: (function( orig ) {
return function( classNames, force, speed, easing, callback ) {
if ( typeof force === "boolean" || force === undefined ) {
if ( !speed ) {
// without speed parameter
return orig.apply( this, arguments );
} else {
return $.effects.animateClass.call( this,
(force ? { add: classNames } : { remove: classNames }),
speed, easing, callback );
}
} else {
// without force parameter
return $.effects.animateClass.call( this,
{ toggle: classNames }, force, speed, easing );
}
};
})( $.fn.toggleClass ),
switchClass: function( remove, add, speed, easing, callback) {
return $.effects.animateClass.call( this, {
add: add,
remove: remove
}, speed, easing, callback );
}
});
})();
/******************************************************************************/
/*********************************** EFFECTS **********************************/
/******************************************************************************/
(function() {
$.extend( $.effects, {
version: "1.10.3",
// Saves a set of properties in a data storage
save: function( element, set ) {
for( var i=0; i < set.length; i++ ) {
if ( set[ i ] !== null ) {
element.data( dataSpace + set[ i ], element[ 0 ].style[ set[ i ] ] );
}
}
},
// Restores a set of previously saved properties from a data storage
restore: function( element, set ) {
var val, i;
for( i=0; i < set.length; i++ ) {
if ( set[ i ] !== null ) {
val = element.data( dataSpace + set[ i ] );
// support: jQuery 1.6.2
// http://bugs.jquery.com/ticket/9917
// jQuery 1.6.2 incorrectly returns undefined for any falsy value.
// We can't differentiate between "" and 0 here, so we just assume
// empty string since it's likely to be a more common value...
if ( val === undefined ) {
val = "";
}
element.css( set[ i ], val );
}
}
},
setMode: function( el, mode ) {
if (mode === "toggle") {
mode = el.is( ":hidden" ) ? "show" : "hide";
}
return mode;
},
// Translates a [top,left] array into a baseline value
// this should be a little more flexible in the future to handle a string & hash
getBaseline: function( origin, original ) {
var y, x;
switch ( origin[ 0 ] ) {
case "top": y = 0; break;
case "middle": y = 0.5; break;
case "bottom": y = 1; break;
default: y = origin[ 0 ] / original.height;
}
switch ( origin[ 1 ] ) {
case "left": x = 0; break;
case "center": x = 0.5; break;
case "right": x = 1; break;
default: x = origin[ 1 ] / original.width;
}
return {
x: x,
y: y
};
},
// Wraps the element around a wrapper that copies position properties
createWrapper: function( element ) {
// if the element is already wrapped, return it
if ( element.parent().is( ".ui-effects-wrapper" )) {
return element.parent();
}
// wrap the element
var props = {
width: element.outerWidth(true),
height: element.outerHeight(true),
"float": element.css( "float" )
},
wrapper = $( "<div></div>" )
.addClass( "ui-effects-wrapper" )
.css({
fontSize: "100%",
background: "transparent",
border: "none",
margin: 0,
padding: 0
}),
// Store the size in case width/height are defined in % - Fixes #5245
size = {
width: element.width(),
height: element.height()
},
active = document.activeElement;
// support: Firefox
// Firefox incorrectly exposes anonymous content
// https://bugzilla.mozilla.org/show_bug.cgi?id=561664
try {
active.id;
} catch( e ) {
active = document.body;
}
element.wrap( wrapper );
// Fixes #7595 - Elements lose focus when wrapped.
if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) {
$( active ).focus();
}
wrapper = element.parent(); //Hotfix for jQuery 1.4 since some change in wrap() seems to actually lose the reference to the wrapped element
// transfer positioning properties to the wrapper
if ( element.css( "position" ) === "static" ) {
wrapper.css({ position: "relative" });
element.css({ position: "relative" });
} else {
$.extend( props, {
position: element.css( "position" ),
zIndex: element.css( "z-index" )
});
$.each([ "top", "left", "bottom", "right" ], function(i, pos) {
props[ pos ] = element.css( pos );
if ( isNaN( parseInt( props[ pos ], 10 ) ) ) {
props[ pos ] = "auto";
}
});
element.css({
position: "relative",
top: 0,
left: 0,
right: "auto",
bottom: "auto"
});
}
element.css(size);
return wrapper.css( props ).show();
},
removeWrapper: function( element ) {
var active = document.activeElement;
if ( element.parent().is( ".ui-effects-wrapper" ) ) {
element.parent().replaceWith( element );
// Fixes #7595 - Elements lose focus when wrapped.
if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) {
$( active ).focus();
}
}
return element;
},
setTransition: function( element, list, factor, value ) {
value = value || {};
$.each( list, function( i, x ) {
var unit = element.cssUnit( x );
if ( unit[ 0 ] > 0 ) {
value[ x ] = unit[ 0 ] * factor + unit[ 1 ];
}
});
return value;
}
});
// return an effect options object for the given parameters:
function _normalizeArguments( effect, options, speed, callback ) {
// allow passing all options as the first parameter
if ( $.isPlainObject( effect ) ) {
options = effect;
effect = effect.effect;
}
// convert to an object
effect = { effect: effect };
// catch (effect, null, ...)
if ( options == null ) {
options = {};
}
// catch (effect, callback)
if ( $.isFunction( options ) ) {
callback = options;
speed = null;
options = {};
}
// catch (effect, speed, ?)
if ( typeof options === "number" || $.fx.speeds[ options ] ) {
callback = speed;
speed = options;
options = {};
}
// catch (effect, options, callback)
if ( $.isFunction( speed ) ) {
callback = speed;
speed = null;
}
// add options to effect
if ( options ) {
$.extend( effect, options );
}
speed = speed || options.duration;
effect.duration = $.fx.off ? 0 :
typeof speed === "number" ? speed :
speed in $.fx.speeds ? $.fx.speeds[ speed ] :
$.fx.speeds._default;
effect.complete = callback || options.complete;
return effect;
}
function standardAnimationOption( option ) {
// Valid standard speeds (nothing, number, named speed)
if ( !option || typeof option === "number" || $.fx.speeds[ option ] ) {
return true;
}
// Invalid strings - treat as "normal" speed
if ( typeof option === "string" && !$.effects.effect[ option ] ) {
return true;
}
// Complete callback
if ( $.isFunction( option ) ) {
return true;
}
// Options hash (but not naming an effect)
if ( typeof option === "object" && !option.effect ) {
return true;
}
// Didn't match any standard API
return false;
}
$.fn.extend({
effect: function( /* effect, options, speed, callback */ ) {
var args = _normalizeArguments.apply( this, arguments ),
mode = args.mode,
queue = args.queue,
effectMethod = $.effects.effect[ args.effect ];
if ( $.fx.off || !effectMethod ) {
// delegate to the original method (e.g., .show()) if possible
if ( mode ) {
return this[ mode ]( args.duration, args.complete );
} else {
return this.each( function() {
if ( args.complete ) {
args.complete.call( this );
}
});
}
}
function run( next ) {
var elem = $( this ),
complete = args.complete,
mode = args.mode;
function done() {
if ( $.isFunction( complete ) ) {
complete.call( elem[0] );
}
if ( $.isFunction( next ) ) {
next();
}
}
// If the element already has the correct final state, delegate to
// the core methods so the internal tracking of "olddisplay" works.
if ( elem.is( ":hidden" ) ? mode === "hide" : mode === "show" ) {
elem[ mode ]();
done();
} else {
effectMethod.call( elem[0], args, done );
}
}
return queue === false ? this.each( run ) : this.queue( queue || "fx", run );
},
show: (function( orig ) {
return function( option ) {
if ( standardAnimationOption( option ) ) {
return orig.apply( this, arguments );
} else {
var args = _normalizeArguments.apply( this, arguments );
args.mode = "show";
return this.effect.call( this, args );
}
};
})( $.fn.show ),
hide: (function( orig ) {
return function( option ) {
if ( standardAnimationOption( option ) ) {
return orig.apply( this, arguments );
} else {
var args = _normalizeArguments.apply( this, arguments );
args.mode = "hide";
return this.effect.call( this, args );
}
};
})( $.fn.hide ),
toggle: (function( orig ) {
return function( option ) {
if ( standardAnimationOption( option ) || typeof option === "boolean" ) {
return orig.apply( this, arguments );
} else {
var args = _normalizeArguments.apply( this, arguments );
args.mode = "toggle";
return this.effect.call( this, args );
}
};
})( $.fn.toggle ),
// helper functions
cssUnit: function(key) {
var style = this.css( key ),
val = [];
$.each( [ "em", "px", "%", "pt" ], function( i, unit ) {
if ( style.indexOf( unit ) > 0 ) {
val = [ parseFloat( style ), unit ];
}
});
return val;
}
});
})();
/******************************************************************************/
/*********************************** EASING ***********************************/
/******************************************************************************/
(function() {
// based on easing equations from Robert Penner (http://www.robertpenner.com/easing)
var baseEasings = {};
$.each( [ "Quad", "Cubic", "Quart", "Quint", "Expo" ], function( i, name ) {
baseEasings[ name ] = function( p ) {
return Math.pow( p, i + 2 );
};
});
$.extend( baseEasings, {
Sine: function ( p ) {
return 1 - Math.cos( p * Math.PI / 2 );
},
Circ: function ( p ) {
return 1 - Math.sqrt( 1 - p * p );
},
Elastic: function( p ) {
return p === 0 || p === 1 ? p :
-Math.pow( 2, 8 * (p - 1) ) * Math.sin( ( (p - 1) * 80 - 7.5 ) * Math.PI / 15 );
},
Back: function( p ) {
return p * p * ( 3 * p - 2 );
},
Bounce: function ( p ) {
var pow2,
bounce = 4;
while ( p < ( ( pow2 = Math.pow( 2, --bounce ) ) - 1 ) / 11 ) {}
return 1 / Math.pow( 4, 3 - bounce ) - 7.5625 * Math.pow( ( pow2 * 3 - 2 ) / 22 - p, 2 );
}
});
$.each( baseEasings, function( name, easeIn ) {
$.easing[ "easeIn" + name ] = easeIn;
$.easing[ "easeOut" + name ] = function( p ) {
return 1 - easeIn( 1 - p );
};
$.easing[ "easeInOut" + name ] = function( p ) {
return p < 0.5 ?
easeIn( p * 2 ) / 2 :
1 - easeIn( p * -2 + 2 ) / 2;
};
});
})();
})(jQuery);
(function( $, undefined ) {
var uid = 0,
hideProps = {},
showProps = {};
hideProps.height = hideProps.paddingTop = hideProps.paddingBottom =
hideProps.borderTopWidth = hideProps.borderBottomWidth = "hide";
showProps.height = showProps.paddingTop = showProps.paddingBottom =
showProps.borderTopWidth = showProps.borderBottomWidth = "show";
$.widget( "ui.accordion", {
version: "1.10.3",
options: {
active: 0,
animate: {},
collapsible: false,
event: "click",
header: "> li > :first-child,> :not(li):even",
heightStyle: "auto",
icons: {
activeHeader: "ui-icon-triangle-1-s",
header: "ui-icon-triangle-1-e"
},
// callbacks
activate: null,
beforeActivate: null
},
_create: function() {
var options = this.options;
this.prevShow = this.prevHide = $();
this.element.addClass( "ui-accordion ui-widget ui-helper-reset" )
// ARIA
.attr( "role", "tablist" );
// don't allow collapsible: false and active: false / null
if ( !options.collapsible && (options.active === false || options.active == null) ) {
options.active = 0;
}
this._processPanels();
// handle negative values
if ( options.active < 0 ) {
options.active += this.headers.length;
}
this._refresh();
},
_getCreateEventData: function() {
return {
header: this.active,
panel: !this.active.length ? $() : this.active.next(),
content: !this.active.length ? $() : this.active.next()
};
},
_createIcons: function() {
var icons = this.options.icons;
if ( icons ) {
$( "<span>" )
.addClass( "ui-accordion-header-icon ui-icon " + icons.header )
.prependTo( this.headers );
this.active.children( ".ui-accordion-header-icon" )
.removeClass( icons.header )
.addClass( icons.activeHeader );
this.headers.addClass( "ui-accordion-icons" );
}
},
_destroyIcons: function() {
this.headers
.removeClass( "ui-accordion-icons" )
.children( ".ui-accordion-header-icon" )
.remove();
},
_destroy: function() {
var contents;
// clean up main element
this.element
.removeClass( "ui-accordion ui-widget ui-helper-reset" )
.removeAttr( "role" );
// clean up headers
this.headers
.removeClass( "ui-accordion-header ui-accordion-header-active ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-state-disabled ui-corner-top" )
.removeAttr( "role" )
.removeAttr( "aria-selected" )
.removeAttr( "aria-controls" )
.removeAttr( "tabIndex" )
.each(function() {
if ( /^ui-accordion/.test( this.id ) ) {
this.removeAttribute( "id" );
}
});
this._destroyIcons();
// clean up content panels
contents = this.headers.next()
.css( "display", "" )
.removeAttr( "role" )
.removeAttr( "aria-expanded" )
.removeAttr( "aria-hidden" )
.removeAttr( "aria-labelledby" )
.removeClass( "ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active ui-state-disabled" )
.each(function() {
if ( /^ui-accordion/.test( this.id ) ) {
this.removeAttribute( "id" );
}
});
if ( this.options.heightStyle !== "content" ) {
contents.css( "height", "" );
}
},
_setOption: function( key, value ) {
if ( key === "active" ) {
// _activate() will handle invalid values and update this.options
this._activate( value );
return;
}
if ( key === "event" ) {
if ( this.options.event ) {
this._off( this.headers, this.options.event );
}
this._setupEvents( value );
}
this._super( key, value );
// setting collapsible: false while collapsed; open first panel
if ( key === "collapsible" && !value && this.options.active === false ) {
this._activate( 0 );
}
if ( key === "icons" ) {
this._destroyIcons();
if ( value ) {
this._createIcons();
}
}
// #5332 - opacity doesn't cascade to positioned elements in IE
// so we need to add the disabled class to the headers and panels
if ( key === "disabled" ) {
this.headers.add( this.headers.next() )
.toggleClass( "ui-state-disabled", !!value );
}
},
_keydown: function( event ) {
/*jshint maxcomplexity:15*/
if ( event.altKey || event.ctrlKey ) {
return;
}
var keyCode = $.ui.keyCode,
length = this.headers.length,
currentIndex = this.headers.index( event.target ),
toFocus = false;
switch ( event.keyCode ) {
case keyCode.RIGHT:
case keyCode.DOWN:
toFocus = this.headers[ ( currentIndex + 1 ) % length ];
break;
case keyCode.LEFT:
case keyCode.UP:
toFocus = this.headers[ ( currentIndex - 1 + length ) % length ];
break;
case keyCode.SPACE:
case keyCode.ENTER:
this._eventHandler( event );
break;
case keyCode.HOME:
toFocus = this.headers[ 0 ];
break;
case keyCode.END:
toFocus = this.headers[ length - 1 ];
break;
}
if ( toFocus ) {
$( event.target ).attr( "tabIndex", -1 );
$( toFocus ).attr( "tabIndex", 0 );
toFocus.focus();
event.preventDefault();
}
},
_panelKeyDown : function( event ) {
if ( event.keyCode === $.ui.keyCode.UP && event.ctrlKey ) {
$( event.currentTarget ).prev().focus();
}
},
refresh: function() {
var options = this.options;
this._processPanels();
// was collapsed or no panel
if ( ( options.active === false && options.collapsible === true ) || !this.headers.length ) {
options.active = false;
this.active = $();
// active false only when collapsible is true
} else if ( options.active === false ) {
this._activate( 0 );
// was active, but active panel is gone
} else if ( this.active.length && !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) {
// all remaining panel are disabled
if ( this.headers.length === this.headers.find(".ui-state-disabled").length ) {
options.active = false;
this.active = $();
// activate previous panel
} else {
this._activate( Math.max( 0, options.active - 1 ) );
}
// was active, active panel still exists
} else {
// make sure active index is correct
options.active = this.headers.index( this.active );
}
this._destroyIcons();
this._refresh();
},
_processPanels: function() {
this.headers = this.element.find( this.options.header )
.addClass( "ui-accordion-header ui-helper-reset ui-state-default ui-corner-all" );
this.headers.next()
.addClass( "ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom" )
.filter(":not(.ui-accordion-content-active)")
.hide();
},
_refresh: function() {
var maxHeight,
options = this.options,
heightStyle = options.heightStyle,
parent = this.element.parent(),
accordionId = this.accordionId = "ui-accordion-" +
(this.element.attr( "id" ) || ++uid);
this.active = this._findActive( options.active )
.addClass( "ui-accordion-header-active ui-state-active ui-corner-top" )
.removeClass( "ui-corner-all" );
this.active.next()
.addClass( "ui-accordion-content-active" )
.show();
this.headers
.attr( "role", "tab" )
.each(function( i ) {
var header = $( this ),
headerId = header.attr( "id" ),
panel = header.next(),
panelId = panel.attr( "id" );
if ( !headerId ) {
headerId = accordionId + "-header-" + i;
header.attr( "id", headerId );
}
if ( !panelId ) {
panelId = accordionId + "-panel-" + i;
panel.attr( "id", panelId );
}
header.attr( "aria-controls", panelId );
panel.attr( "aria-labelledby", headerId );
})
.next()
.attr( "role", "tabpanel" );
this.headers
.not( this.active )
.attr({
"aria-selected": "false",
tabIndex: -1
})
.next()
.attr({
"aria-expanded": "false",
"aria-hidden": "true"
})
.hide();
// make sure at least one header is in the tab order
if ( !this.active.length ) {
this.headers.eq( 0 ).attr( "tabIndex", 0 );
} else {
this.active.attr({
"aria-selected": "true",
tabIndex: 0
})
.next()
.attr({
"aria-expanded": "true",
"aria-hidden": "false"
});
}
this._createIcons();
this._setupEvents( options.event );
if ( heightStyle === "fill" ) {
maxHeight = parent.height();
this.element.siblings( ":visible" ).each(function() {
var elem = $( this ),
position = elem.css( "position" );
if ( position === "absolute" || position === "fixed" ) {
return;
}
maxHeight -= elem.outerHeight( true );
});
this.headers.each(function() {
maxHeight -= $( this ).outerHeight( true );
});
this.headers.next()
.each(function() {
$( this ).height( Math.max( 0, maxHeight -
$( this ).innerHeight() + $( this ).height() ) );
})
.css( "overflow", "auto" );
} else if ( heightStyle === "auto" ) {
maxHeight = 0;
this.headers.next()
.each(function() {
maxHeight = Math.max( maxHeight, $( this ).css( "height", "" ).height() );
})
.height( maxHeight );
}
},
_activate: function( index ) {
var active = this._findActive( index )[ 0 ];
// trying to activate the already active panel
if ( active === this.active[ 0 ] ) {
return;
}
// trying to collapse, simulate a click on the currently active header
active = active || this.active[ 0 ];
this._eventHandler({
target: active,
currentTarget: active,
preventDefault: $.noop
});
},
_findActive: function( selector ) {
return typeof selector === "number" ? this.headers.eq( selector ) : $();
},
_setupEvents: function( event ) {
var events = {
keydown: "_keydown"
};
if ( event ) {
$.each( event.split(" "), function( index, eventName ) {
events[ eventName ] = "_eventHandler";
});
}
this._off( this.headers.add( this.headers.next() ) );
this._on( this.headers, events );
this._on( this.headers.next(), { keydown: "_panelKeyDown" });
this._hoverable( this.headers );
this._focusable( this.headers );
},
_eventHandler: function( event ) {
var options = this.options,
active = this.active,
clicked = $( event.currentTarget ),
clickedIsActive = clicked[ 0 ] === active[ 0 ],
collapsing = clickedIsActive && options.collapsible,
toShow = collapsing ? $() : clicked.next(),
toHide = active.next(),
eventData = {
oldHeader: active,
oldPanel: toHide,
newHeader: collapsing ? $() : clicked,
newPanel: toShow
};
event.preventDefault();
if (
// click on active header, but not collapsible
( clickedIsActive && !options.collapsible ) ||
// allow canceling activation
( this._trigger( "beforeActivate", event, eventData ) === false ) ) {
return;
}
options.active = collapsing ? false : this.headers.index( clicked );
// when the call to ._toggle() comes after the class changes
// it causes a very odd bug in IE 8 (see #6720)
this.active = clickedIsActive ? $() : clicked;
this._toggle( eventData );
// switch classes
// corner classes on the previously active header stay after the animation
active.removeClass( "ui-accordion-header-active ui-state-active" );
if ( options.icons ) {
active.children( ".ui-accordion-header-icon" )
.removeClass( options.icons.activeHeader )
.addClass( options.icons.header );
}
if ( !clickedIsActive ) {
clicked
.removeClass( "ui-corner-all" )
.addClass( "ui-accordion-header-active ui-state-active ui-corner-top" );
if ( options.icons ) {
clicked.children( ".ui-accordion-header-icon" )
.removeClass( options.icons.header )
.addClass( options.icons.activeHeader );
}
clicked
.next()
.addClass( "ui-accordion-content-active" );
}
},
_toggle: function( data ) {
var toShow = data.newPanel,
toHide = this.prevShow.length ? this.prevShow : data.oldPanel;
// handle activating a panel during the animation for another activation
this.prevShow.add( this.prevHide ).stop( true, true );
this.prevShow = toShow;
this.prevHide = toHide;
if ( this.options.animate ) {
this._animate( toShow, toHide, data );
} else {
toHide.hide();
toShow.show();
this._toggleComplete( data );
}
toHide.attr({
"aria-expanded": "false",
"aria-hidden": "true"
});
toHide.prev().attr( "aria-selected", "false" );
// if we're switching panels, remove the old header from the tab order
// if we're opening from collapsed state, remove the previous header from the tab order
// if we're collapsing, then keep the collapsing header in the tab order
if ( toShow.length && toHide.length ) {
toHide.prev().attr( "tabIndex", -1 );
} else if ( toShow.length ) {
this.headers.filter(function() {
return $( this ).attr( "tabIndex" ) === 0;
})
.attr( "tabIndex", -1 );
}
toShow
.attr({
"aria-expanded": "true",
"aria-hidden": "false"
})
.prev()
.attr({
"aria-selected": "true",
tabIndex: 0
});
},
_animate: function( toShow, toHide, data ) {
var total, easing, duration,
that = this,
adjust = 0,
down = toShow.length &&
( !toHide.length || ( toShow.index() < toHide.index() ) ),
animate = this.options.animate || {},
options = down && animate.down || animate,
complete = function() {
that._toggleComplete( data );
};
if ( typeof options === "number" ) {
duration = options;
}
if ( typeof options === "string" ) {
easing = options;
}
// fall back from options to animation in case of partial down settings
easing = easing || options.easing || animate.easing;
duration = duration || options.duration || animate.duration;
if ( !toHide.length ) {
return toShow.animate( showProps, duration, easing, complete );
}
if ( !toShow.length ) {
return toHide.animate( hideProps, duration, easing, complete );
}
total = toShow.show().outerHeight();
toHide.animate( hideProps, {
duration: duration,
easing: easing,
step: function( now, fx ) {
fx.now = Math.round( now );
}
});
toShow
.hide()
.animate( showProps, {
duration: duration,
easing: easing,
complete: complete,
step: function( now, fx ) {
fx.now = Math.round( now );
if ( fx.prop !== "height" ) {
adjust += fx.now;
} else if ( that.options.heightStyle !== "content" ) {
fx.now = Math.round( total - toHide.outerHeight() - adjust );
adjust = 0;
}
}
});
},
_toggleComplete: function( data ) {
var toHide = data.oldPanel;
toHide
.removeClass( "ui-accordion-content-active" )
.prev()
.removeClass( "ui-corner-top" )
.addClass( "ui-corner-all" );
// Work around for rendering bug in IE (#5421)
if ( toHide.length ) {
toHide.parent()[0].className = toHide.parent()[0].className;
}
this._trigger( "activate", null, data );
}
});
})( jQuery );
(function( $, undefined ) {
// used to prevent race conditions with remote data sources
var requestIndex = 0;
$.widget( "ui.autocomplete", {
version: "1.10.3",
defaultElement: "<input>",
options: {
appendTo: null,
autoFocus: false,
delay: 300,
minLength: 1,
position: {
my: "left top",
at: "left bottom",
collision: "none"
},
source: null,
// callbacks
change: null,
close: null,
focus: null,
open: null,
response: null,
search: null,
select: null
},
pending: 0,
_create: function() {
// Some browsers only repeat keydown events, not keypress events,
// so we use the suppressKeyPress flag to determine if we've already
// handled the keydown event. #7269
// Unfortunately the code for & in keypress is the same as the up arrow,
// so we use the suppressKeyPressRepeat flag to avoid handling keypress
// events when we know the keydown event was used to modify the
// search term. #7799
var suppressKeyPress, suppressKeyPressRepeat, suppressInput,
nodeName = this.element[0].nodeName.toLowerCase(),
isTextarea = nodeName === "textarea",
isInput = nodeName === "input";
this.isMultiLine =
// Textareas are always multi-line
isTextarea ? true :
// Inputs are always single-line, even if inside a contentEditable element
// IE also treats inputs as contentEditable
isInput ? false :
// All other element types are determined by whether or not they're contentEditable
this.element.prop( "isContentEditable" );
this.valueMethod = this.element[ isTextarea || isInput ? "val" : "text" ];
this.isNewMenu = true;
this.element
.addClass( "ui-autocomplete-input" )
.attr( "autocomplete", "off" );
this._on( this.element, {
keydown: function( event ) {
/*jshint maxcomplexity:15*/
if ( this.element.prop( "readOnly" ) ) {
suppressKeyPress = true;
suppressInput = true;
suppressKeyPressRepeat = true;
return;
}
suppressKeyPress = false;
suppressInput = false;
suppressKeyPressRepeat = false;
var keyCode = $.ui.keyCode;
switch( event.keyCode ) {
case keyCode.PAGE_UP:
suppressKeyPress = true;
this._move( "previousPage", event );
break;
case keyCode.PAGE_DOWN:
suppressKeyPress = true;
this._move( "nextPage", event );
break;
case keyCode.UP:
suppressKeyPress = true;
this._keyEvent( "previous", event );
break;
case keyCode.DOWN:
suppressKeyPress = true;
this._keyEvent( "next", event );
break;
case keyCode.ENTER:
case keyCode.NUMPAD_ENTER:
// when menu is open and has focus
if ( this.menu.active ) {
// #6055 - Opera still allows the keypress to occur
// which causes forms to submit
suppressKeyPress = true;
event.preventDefault();
this.menu.select( event );
}
break;
case keyCode.TAB:
if ( this.menu.active ) {
this.menu.select( event );
}
break;
case keyCode.ESCAPE:
if ( this.menu.element.is( ":visible" ) ) {
this._value( this.term );
this.close( event );
// Different browsers have different default behavior for escape
// Single press can mean undo or clear
// Double press in IE means clear the whole form
event.preventDefault();
}
break;
default:
suppressKeyPressRepeat = true;
// search timeout should be triggered before the input value is changed
this._searchTimeout( event );
break;
}
},
keypress: function( event ) {
if ( suppressKeyPress ) {
suppressKeyPress = false;
if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) {
event.preventDefault();
}
return;
}
if ( suppressKeyPressRepeat ) {
return;
}
// replicate some key handlers to allow them to repeat in Firefox and Opera
var keyCode = $.ui.keyCode;
switch( event.keyCode ) {
case keyCode.PAGE_UP:
this._move( "previousPage", event );
break;
case keyCode.PAGE_DOWN:
this._move( "nextPage", event );
break;
case keyCode.UP:
this._keyEvent( "previous", event );
break;
case keyCode.DOWN:
this._keyEvent( "next", event );
break;
}
},
input: function( event ) {
if ( suppressInput ) {
suppressInput = false;
event.preventDefault();
return;
}
this._searchTimeout( event );
},
focus: function() {
this.selectedItem = null;
this.previous = this._value();
},
blur: function( event ) {
if ( this.cancelBlur ) {
delete this.cancelBlur;
return;
}
clearTimeout( this.searching );
this.close( event );
this._change( event );
}
});
this._initSource();
this.menu = $( "<ul>" )
.addClass( "ui-autocomplete ui-front" )
.appendTo( this._appendTo() )
.menu({
// disable ARIA support, the live region takes care of that
role: null
})
.hide()
.data( "ui-menu" );
this._on( this.menu.element, {
mousedown: function( event ) {
// prevent moving focus out of the text field
event.preventDefault();
// IE doesn't prevent moving focus even with event.preventDefault()
// so we set a flag to know when we should ignore the blur event
this.cancelBlur = true;
this._delay(function() {
delete this.cancelBlur;
});
// clicking on the scrollbar causes focus to shift to the body
// but we can't detect a mouseup or a click immediately afterward
// so we have to track the next mousedown and close the menu if
// the user clicks somewhere outside of the autocomplete
var menuElement = this.menu.element[ 0 ];
if ( !$( event.target ).closest( ".ui-menu-item" ).length ) {
this._delay(function() {
var that = this;
this.document.one( "mousedown", function( event ) {
if ( event.target !== that.element[ 0 ] &&
event.target !== menuElement &&
!$.contains( menuElement, event.target ) ) {
that.close();
}
});
});
}
},
menufocus: function( event, ui ) {
// support: Firefox
// Prevent accidental activation of menu items in Firefox (#7024 #9118)
if ( this.isNewMenu ) {
this.isNewMenu = false;
if ( event.originalEvent && /^mouse/.test( event.originalEvent.type ) ) {
this.menu.blur();
this.document.one( "mousemove", function() {
$( event.target ).trigger( event.originalEvent );
});
return;
}
}
var item = ui.item.data( "ui-autocomplete-item" );
if ( false !== this._trigger( "focus", event, { item: item } ) ) {
// use value to match what will end up in the input, if it was a key event
if ( event.originalEvent && /^key/.test( event.originalEvent.type ) ) {
this._value( item.value );
}
} else {
// Normally the input is populated with the item's value as the
// menu is navigated, causing screen readers to notice a change and
// announce the item. Since the focus event was canceled, this doesn't
// happen, so we update the live region so that screen readers can
// still notice the change and announce it.
this.liveRegion.text( item.value );
}
},
menuselect: function( event, ui ) {
var item = ui.item.data( "ui-autocomplete-item" ),
previous = this.previous;
// only trigger when focus was lost (click on menu)
if ( this.element[0] !== this.document[0].activeElement ) {
this.element.focus();
this.previous = previous;
// #6109 - IE triggers two focus events and the second
// is asynchronous, so we need to reset the previous
// term synchronously and asynchronously :-(
this._delay(function() {
this.previous = previous;
this.selectedItem = item;
});
}
if ( false !== this._trigger( "select", event, { item: item } ) ) {
this._value( item.value );
}
// reset the term after the select event
// this allows custom select handling to work properly
this.term = this._value();
this.close( event );
this.selectedItem = item;
}
});
this.liveRegion = $( "<span>", {
role: "status",
"aria-live": "polite"
})
.addClass( "ui-helper-hidden-accessible" )
.insertBefore( this.element );
// turning off autocomplete prevents the browser from remembering the
// value when navigating through history, so we re-enable autocomplete
// if the page is unloaded before the widget is destroyed. #7790
this._on( this.window, {
beforeunload: function() {
this.element.removeAttr( "autocomplete" );
}
});
},
_destroy: function() {
clearTimeout( this.searching );
this.element
.removeClass( "ui-autocomplete-input" )
.removeAttr( "autocomplete" );
this.menu.element.remove();
this.liveRegion.remove();
},
_setOption: function( key, value ) {
this._super( key, value );
if ( key === "source" ) {
this._initSource();
}
if ( key === "appendTo" ) {
this.menu.element.appendTo( this._appendTo() );
}
if ( key === "disabled" && value && this.xhr ) {
this.xhr.abort();
}
},
_appendTo: function() {
var element = this.options.appendTo;
if ( element ) {
element = element.jquery || element.nodeType ?
$( element ) :
this.document.find( element ).eq( 0 );
}
if ( !element ) {
element = this.element.closest( ".ui-front" );
}
if ( !element.length ) {
element = this.document[0].body;
}
return element;
},
_initSource: function() {
var array, url,
that = this;
if ( $.isArray(this.options.source) ) {
array = this.options.source;
this.source = function( request, response ) {
response( $.ui.autocomplete.filter( array, request.term ) );
};
} else if ( typeof this.options.source === "string" ) {
url = this.options.source;
this.source = function( request, response ) {
if ( that.xhr ) {
that.xhr.abort();
}
that.xhr = $.ajax({
url: url,
data: request,
dataType: "json",
success: function( data ) {
response( data );
},
error: function() {
response( [] );
}
});
};
} else {
this.source = this.options.source;
}
},
_searchTimeout: function( event ) {
clearTimeout( this.searching );
this.searching = this._delay(function() {
// only search if the value has changed
if ( this.term !== this._value() ) {
this.selectedItem = null;
this.search( null, event );
}
}, this.options.delay );
},
search: function( value, event ) {
value = value != null ? value : this._value();
// always save the actual value, not the one passed as an argument
this.term = this._value();
if ( value.length < this.options.minLength ) {
return this.close( event );
}
if ( this._trigger( "search", event ) === false ) {
return;
}
return this._search( value );
},
_search: function( value ) {
this.pending++;
this.element.addClass( "ui-autocomplete-loading" );
this.cancelSearch = false;
this.source( { term: value }, this._response() );
},
_response: function() {
var that = this,
index = ++requestIndex;
return function( content ) {
if ( index === requestIndex ) {
that.__response( content );
}
that.pending--;
if ( !that.pending ) {
that.element.removeClass( "ui-autocomplete-loading" );
}
};
},
__response: function( content ) {
if ( content ) {
content = this._normalize( content );
}
this._trigger( "response", null, { content: content } );
if ( !this.options.disabled && content && content.length && !this.cancelSearch ) {
this._suggest( content );
this._trigger( "open" );
} else {
// use ._close() instead of .close() so we don't cancel future searches
this._close();
}
},
close: function( event ) {
this.cancelSearch = true;
this._close( event );
},
_close: function( event ) {
if ( this.menu.element.is( ":visible" ) ) {
this.menu.element.hide();
this.menu.blur();
this.isNewMenu = true;
this._trigger( "close", event );
}
},
_change: function( event ) {
if ( this.previous !== this._value() ) {
this._trigger( "change", event, { item: this.selectedItem } );
}
},
_normalize: function( items ) {
// assume all items have the right format when the first item is complete
if ( items.length && items[0].label && items[0].value ) {
return items;
}
return $.map( items, function( item ) {
if ( typeof item === "string" ) {
return {
label: item,
value: item
};
}
return $.extend({
label: item.label || item.value,
value: item.value || item.label
}, item );
});
},
_suggest: function( items ) {
var ul = this.menu.element.empty();
this._renderMenu( ul, items );
this.isNewMenu = true;
this.menu.refresh();
// size and position menu
ul.show();
this._resizeMenu();
ul.position( $.extend({
of: this.element
}, this.options.position ));
if ( this.options.autoFocus ) {
this.menu.next();
}
},
_resizeMenu: function() {
var ul = this.menu.element;
ul.outerWidth( Math.max(
// Firefox wraps long text (possibly a rounding bug)
// so we add 1px to avoid the wrapping (#7513)
ul.width( "" ).outerWidth() + 1,
this.element.outerWidth()
) );
},
_renderMenu: function( ul, items ) {
var that = this;
$.each( items, function( index, item ) {
that._renderItemData( ul, item );
});
},
_renderItemData: function( ul, item ) {
return this._renderItem( ul, item ).data( "ui-autocomplete-item", item );
},
_renderItem: function( ul, item ) {
return $( "<li>" )
.append( $( "<a>" ).text( item.label ) )
.appendTo( ul );
},
_move: function( direction, event ) {
if ( !this.menu.element.is( ":visible" ) ) {
this.search( null, event );
return;
}
if ( this.menu.isFirstItem() && /^previous/.test( direction ) ||
this.menu.isLastItem() && /^next/.test( direction ) ) {
this._value( this.term );
this.menu.blur();
return;
}
this.menu[ direction ]( event );
},
widget: function() {
return this.menu.element;
},
_value: function() {
return this.valueMethod.apply( this.element, arguments );
},
_keyEvent: function( keyEvent, event ) {
if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) {
this._move( keyEvent, event );
// prevents moving cursor to beginning/end of the text field in some browsers
event.preventDefault();
}
}
});
$.extend( $.ui.autocomplete, {
escapeRegex: function( value ) {
return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
},
filter: function(array, term) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
return $.grep( array, function(value) {
return matcher.test( value.label || value.value || value );
});
}
});
// live region extension, adding a `messages` option
// NOTE: This is an experimental API. We are still investigating
// a full solution for string manipulation and internationalization.
$.widget( "ui.autocomplete", $.ui.autocomplete, {
options: {
messages: {
noResults: "No search results.",
results: function( amount ) {
return amount + ( amount > 1 ? " results are" : " result is" ) +
" available, use up and down arrow keys to navigate.";
}
}
},
__response: function( content ) {
var message;
this._superApply( arguments );
if ( this.options.disabled || this.cancelSearch ) {
return;
}
if ( content && content.length ) {
message = this.options.messages.results( content.length );
} else {
message = this.options.messages.noResults;
}
this.liveRegion.text( message );
}
});
}( jQuery ));
(function( $, undefined ) {
var lastActive, startXPos, startYPos, clickDragged,
baseClasses = "ui-button ui-widget ui-state-default ui-corner-all",
stateClasses = "ui-state-hover ui-state-active ",
typeClasses = "ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary ui-button-text-only",
formResetHandler = function() {
var form = $( this );
setTimeout(function() {
form.find( ":ui-button" ).button( "refresh" );
}, 1 );
},
radioGroup = function( radio ) {
var name = radio.name,
form = radio.form,
radios = $( [] );
if ( name ) {
name = name.replace( /'/g, "\\'" );
if ( form ) {
radios = $( form ).find( "[name='" + name + "']" );
} else {
radios = $( "[name='" + name + "']", radio.ownerDocument )
.filter(function() {
return !this.form;
});
}
}
return radios;
};
$.widget( "ui.button", {
version: "1.10.3",
defaultElement: "<button>",
options: {
disabled: null,
text: true,
label: null,
icons: {
primary: null,
secondary: null
}
},
_create: function() {
this.element.closest( "form" )
.unbind( "reset" + this.eventNamespace )
.bind( "reset" + this.eventNamespace, formResetHandler );
if ( typeof this.options.disabled !== "boolean" ) {
this.options.disabled = !!this.element.prop( "disabled" );
} else {
this.element.prop( "disabled", this.options.disabled );
}
this._determineButtonType();
this.hasTitle = !!this.buttonElement.attr( "title" );
var that = this,
options = this.options,
toggleButton = this.type === "checkbox" || this.type === "radio",
activeClass = !toggleButton ? "ui-state-active" : "",
focusClass = "ui-state-focus";
if ( options.label === null ) {
options.label = (this.type === "input" ? this.buttonElement.val() : this.buttonElement.html());
}
this._hoverable( this.buttonElement );
this.buttonElement
.addClass( baseClasses )
.attr( "role", "button" )
.bind( "mouseenter" + this.eventNamespace, function() {
if ( options.disabled ) {
return;
}
if ( this === lastActive ) {
$( this ).addClass( "ui-state-active" );
}
})
.bind( "mouseleave" + this.eventNamespace, function() {
if ( options.disabled ) {
return;
}
$( this ).removeClass( activeClass );
})
.bind( "click" + this.eventNamespace, function( event ) {
if ( options.disabled ) {
event.preventDefault();
event.stopImmediatePropagation();
}
});
this.element
.bind( "focus" + this.eventNamespace, function() {
// no need to check disabled, focus won't be triggered anyway
that.buttonElement.addClass( focusClass );
})
.bind( "blur" + this.eventNamespace, function() {
that.buttonElement.removeClass( focusClass );
});
if ( toggleButton ) {
this.element.bind( "change" + this.eventNamespace, function() {
if ( clickDragged ) {
return;
}
that.refresh();
});
// if mouse moves between mousedown and mouseup (drag) set clickDragged flag
// prevents issue where button state changes but checkbox/radio checked state
// does not in Firefox (see ticket #6970)
this.buttonElement
.bind( "mousedown" + this.eventNamespace, function( event ) {
if ( options.disabled ) {
return;
}
clickDragged = false;
startXPos = event.pageX;
startYPos = event.pageY;
})
.bind( "mouseup" + this.eventNamespace, function( event ) {
if ( options.disabled ) {
return;
}
if ( startXPos !== event.pageX || startYPos !== event.pageY ) {
clickDragged = true;
}
});
}
if ( this.type === "checkbox" ) {
this.buttonElement.bind( "click" + this.eventNamespace, function() {
if ( options.disabled || clickDragged ) {
return false;
}
});
} else if ( this.type === "radio" ) {
this.buttonElement.bind( "click" + this.eventNamespace, function() {
if ( options.disabled || clickDragged ) {
return false;
}
$( this ).addClass( "ui-state-active" );
that.buttonElement.attr( "aria-pressed", "true" );
var radio = that.element[ 0 ];
radioGroup( radio )
.not( radio )
.map(function() {
return $( this ).button( "widget" )[ 0 ];
})
.removeClass( "ui-state-active" )
.attr( "aria-pressed", "false" );
});
} else {
this.buttonElement
.bind( "mousedown" + this.eventNamespace, function() {
if ( options.disabled ) {
return false;
}
$( this ).addClass( "ui-state-active" );
lastActive = this;
that.document.one( "mouseup", function() {
lastActive = null;
});
})
.bind( "mouseup" + this.eventNamespace, function() {
if ( options.disabled ) {
return false;
}
$( this ).removeClass( "ui-state-active" );
})
.bind( "keydown" + this.eventNamespace, function(event) {
if ( options.disabled ) {
return false;
}
if ( event.keyCode === $.ui.keyCode.SPACE || event.keyCode === $.ui.keyCode.ENTER ) {
$( this ).addClass( "ui-state-active" );
}
})
// see #8559, we bind to blur here in case the button element loses
// focus between keydown and keyup, it would be left in an "active" state
.bind( "keyup" + this.eventNamespace + " blur" + this.eventNamespace, function() {
$( this ).removeClass( "ui-state-active" );
});
if ( this.buttonElement.is("a") ) {
this.buttonElement.keyup(function(event) {
if ( event.keyCode === $.ui.keyCode.SPACE ) {
// TODO pass through original event correctly (just as 2nd argument doesn't work)
$( this ).click();
}
});
}
}
// TODO: pull out $.Widget's handling for the disabled option into
// $.Widget.prototype._setOptionDisabled so it's easy to proxy and can
// be overridden by individual plugins
this._setOption( "disabled", options.disabled );
this._resetButton();
},
_determineButtonType: function() {
var ancestor, labelSelector, checked;
if ( this.element.is("[type=checkbox]") ) {
this.type = "checkbox";
} else if ( this.element.is("[type=radio]") ) {
this.type = "radio";
} else if ( this.element.is("input") ) {
this.type = "input";
} else {
this.type = "button";
}
if ( this.type === "checkbox" || this.type === "radio" ) {
// we don't search against the document in case the element
// is disconnected from the DOM
ancestor = this.element.parents().last();
labelSelector = "label[for='" + this.element.attr("id") + "']";
this.buttonElement = ancestor.find( labelSelector );
if ( !this.buttonElement.length ) {
ancestor = ancestor.length ? ancestor.siblings() : this.element.siblings();
this.buttonElement = ancestor.filter( labelSelector );
if ( !this.buttonElement.length ) {
this.buttonElement = ancestor.find( labelSelector );
}
}
this.element.addClass( "ui-helper-hidden-accessible" );
checked = this.element.is( ":checked" );
if ( checked ) {
this.buttonElement.addClass( "ui-state-active" );
}
this.buttonElement.prop( "aria-pressed", checked );
} else {
this.buttonElement = this.element;
}
},
widget: function() {
return this.buttonElement;
},
_destroy: function() {
this.element
.removeClass( "ui-helper-hidden-accessible" );
this.buttonElement
.removeClass( baseClasses + " " + stateClasses + " " + typeClasses )
.removeAttr( "role" )
.removeAttr( "aria-pressed" )
.html( this.buttonElement.find(".ui-button-text").html() );
if ( !this.hasTitle ) {
this.buttonElement.removeAttr( "title" );
}
},
_setOption: function( key, value ) {
this._super( key, value );
if ( key === "disabled" ) {
if ( value ) {
this.element.prop( "disabled", true );
} else {
this.element.prop( "disabled", false );
}
return;
}
this._resetButton();
},
refresh: function() {
//See #8237 & #8828
var isDisabled = this.element.is( "input, button" ) ? this.element.is( ":disabled" ) : this.element.hasClass( "ui-button-disabled" );
if ( isDisabled !== this.options.disabled ) {
this._setOption( "disabled", isDisabled );
}
if ( this.type === "radio" ) {
radioGroup( this.element[0] ).each(function() {
if ( $( this ).is( ":checked" ) ) {
$( this ).button( "widget" )
.addClass( "ui-state-active" )
.attr( "aria-pressed", "true" );
} else {
$( this ).button( "widget" )
.removeClass( "ui-state-active" )
.attr( "aria-pressed", "false" );
}
});
} else if ( this.type === "checkbox" ) {
if ( this.element.is( ":checked" ) ) {
this.buttonElement
.addClass( "ui-state-active" )
.attr( "aria-pressed", "true" );
} else {
this.buttonElement
.removeClass( "ui-state-active" )
.attr( "aria-pressed", "false" );
}
}
},
_resetButton: function() {
if ( this.type === "input" ) {
if ( this.options.label ) {
this.element.val( this.options.label );
}
return;
}
var buttonElement = this.buttonElement.removeClass( typeClasses ),
buttonText = $( "<span></span>", this.document[0] )
.addClass( "ui-button-text" )
.html( this.options.label )
.appendTo( buttonElement.empty() )
.text(),
icons = this.options.icons,
multipleIcons = icons.primary && icons.secondary,
buttonClasses = [];
if ( icons.primary || icons.secondary ) {
if ( this.options.text ) {
buttonClasses.push( "ui-button-text-icon" + ( multipleIcons ? "s" : ( icons.primary ? "-primary" : "-secondary" ) ) );
}
if ( icons.primary ) {
buttonElement.prepend( "<span class='ui-button-icon-primary ui-icon " + icons.primary + "'></span>" );
}
if ( icons.secondary ) {
buttonElement.append( "<span class='ui-button-icon-secondary ui-icon " + icons.secondary + "'></span>" );
}
if ( !this.options.text ) {
buttonClasses.push( multipleIcons ? "ui-button-icons-only" : "ui-button-icon-only" );
if ( !this.hasTitle ) {
buttonElement.attr( "title", $.trim( buttonText ) );
}
}
} else {
buttonClasses.push( "ui-button-text-only" );
}
buttonElement.addClass( buttonClasses.join( " " ) );
}
});
$.widget( "ui.buttonset", {
version: "1.10.3",
options: {
items: "button, input[type=button], input[type=submit], input[type=reset], input[type=checkbox], input[type=radio], a, :data(ui-button)"
},
_create: function() {
this.element.addClass( "ui-buttonset" );
},
_init: function() {
this.refresh();
},
_setOption: function( key, value ) {
if ( key === "disabled" ) {
this.buttons.button( "option", key, value );
}
this._super( key, value );
},
refresh: function() {
var rtl = this.element.css( "direction" ) === "rtl";
this.buttons = this.element.find( this.options.items )
.filter( ":ui-button" )
.button( "refresh" )
.end()
.not( ":ui-button" )
.button()
.end()
.map(function() {
return $( this ).button( "widget" )[ 0 ];
})
.removeClass( "ui-corner-all ui-corner-left ui-corner-right" )
.filter( ":first" )
.addClass( rtl ? "ui-corner-right" : "ui-corner-left" )
.end()
.filter( ":last" )
.addClass( rtl ? "ui-corner-left" : "ui-corner-right" )
.end()
.end();
},
_destroy: function() {
this.element.removeClass( "ui-buttonset" );
this.buttons
.map(function() {
return $( this ).button( "widget" )[ 0 ];
})
.removeClass( "ui-corner-left ui-corner-right" )
.end()
.button( "destroy" );
}
});
}( jQuery ) );
(function( $, undefined ) {
$.extend($.ui, { datepicker: { version: "1.10.3" } });
var PROP_NAME = "datepicker",
instActive;
/* Date picker manager.
Use the singleton instance of this class, $.datepicker, to interact with the date picker.
Settings for (groups of) date pickers are maintained in an instance object,
allowing multiple different settings on the same page. */
function Datepicker() {
this._curInst = null; // The current instance in use
this._keyEvent = false; // If the last event was a key event
this._disabledInputs = []; // List of date picker inputs that have been disabled
this._datepickerShowing = false; // True if the popup picker is showing , false if not
this._inDialog = false; // True if showing within a "dialog", false if not
this._mainDivId = "ui-datepicker-div"; // The ID of the main datepicker division
this._inlineClass = "ui-datepicker-inline"; // The name of the inline marker class
this._appendClass = "ui-datepicker-append"; // The name of the append marker class
this._triggerClass = "ui-datepicker-trigger"; // The name of the trigger marker class
this._dialogClass = "ui-datepicker-dialog"; // The name of the dialog marker class
this._disableClass = "ui-datepicker-disabled"; // The name of the disabled covering marker class
this._unselectableClass = "ui-datepicker-unselectable"; // The name of the unselectable cell marker class
this._currentClass = "ui-datepicker-current-day"; // The name of the current day marker class
this._dayOverClass = "ui-datepicker-days-cell-over"; // The name of the day hover marker class
this.regional = []; // Available regional settings, indexed by language code
this.regional[""] = { // Default regional settings
closeText: "Done", // Display text for close link
prevText: "Prev", // Display text for previous month link
nextText: "Next", // Display text for next month link
currentText: "Today", // Display text for current month link
monthNames: ["January","February","March","April","May","June",
"July","August","September","October","November","December"], // Names of months for drop-down and formatting
monthNamesShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], // For formatting
dayNames: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], // For formatting
dayNamesShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], // For formatting
dayNamesMin: ["Su","Mo","Tu","We","Th","Fr","Sa"], // Column headings for days starting at Sunday
weekHeader: "Wk", // Column header for week of the year
dateFormat: "mm/dd/yy", // See format options on parseDate
firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
isRTL: false, // True if right-to-left language, false if left-to-right
showMonthAfterYear: false, // True if the year select precedes month, false for month then year
yearSuffix: "" // Additional text to append to the year in the month headers
};
this._defaults = { // Global defaults for all the date picker instances
showOn: "focus", // "focus" for popup on focus,
// "button" for trigger button, or "both" for either
showAnim: "fadeIn", // Name of jQuery animation for popup
showOptions: {}, // Options for enhanced animations
defaultDate: null, // Used when field is blank: actual date,
// +/-number for offset from today, null for today
appendText: "", // Display text following the input box, e.g. showing the format
buttonText: "...", // Text for trigger button
buttonImage: "", // URL for trigger button image
buttonImageOnly: false, // True if the image appears alone, false if it appears on a button
hideIfNoPrevNext: false, // True to hide next/previous month links
// if not applicable, false to just disable them
navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links
gotoCurrent: false, // True if today link goes back to current selection instead
changeMonth: false, // True if month can be selected directly, false if only prev/next
changeYear: false, // True if year can be selected directly, false if only prev/next
yearRange: "c-10:c+10", // Range of years to display in drop-down,
// either relative to today's year (-nn:+nn), relative to currently displayed year
// (c-nn:c+nn), absolute (nnnn:nnnn), or a combination of the above (nnnn:-n)
showOtherMonths: false, // True to show dates in other months, false to leave blank
selectOtherMonths: false, // True to allow selection of dates in other months, false for unselectable
showWeek: false, // True to show week of the year, false to not show it
calculateWeek: this.iso8601Week, // How to calculate the week of the year,
// takes a Date and returns the number of the week for it
shortYearCutoff: "+10", // Short year values < this are in the current century,
// > this are in the previous century,
// string value starting with "+" for current year + value
minDate: null, // The earliest selectable date, or null for no limit
maxDate: null, // The latest selectable date, or null for no limit
duration: "fast", // Duration of display/closure
beforeShowDay: null, // Function that takes a date and returns an array with
// [0] = true if selectable, false if not, [1] = custom CSS class name(s) or "",
// [2] = cell title (optional), e.g. $.datepicker.noWeekends
beforeShow: null, // Function that takes an input field and
// returns a set of custom settings for the date picker
onSelect: null, // Define a callback function when a date is selected
onChangeMonthYear: null, // Define a callback function when the month or year is changed
onClose: null, // Define a callback function when the datepicker is closed
numberOfMonths: 1, // Number of months to show at a time
showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0)
stepMonths: 1, // Number of months to step back/forward
stepBigMonths: 12, // Number of months to step back/forward for the big links
altField: "", // Selector for an alternate field to store selected dates into
altFormat: "", // The date format to use for the alternate field
constrainInput: true, // The input is constrained by the current date format
showButtonPanel: false, // True to show button panel, false to not show it
autoSize: false, // True to size the input for the date format, false to leave as is
disabled: false // The initial disabled state
};
$.extend(this._defaults, this.regional[""]);
this.dpDiv = bindHover($("<div id='" + this._mainDivId + "' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>"));
}
$.extend(Datepicker.prototype, {
/* Class name added to elements to indicate already configured with a date picker. */
markerClassName: "hasDatepicker",
//Keep track of the maximum number of rows displayed (see #7043)
maxRows: 4,
// TODO rename to "widget" when switching to widget factory
_widgetDatepicker: function() {
return this.dpDiv;
},
/* Override the default settings for all instances of the date picker.
* @param settings object - the new settings to use as defaults (anonymous object)
* @return the manager object
*/
setDefaults: function(settings) {
extendRemove(this._defaults, settings || {});
return this;
},
/* Attach the date picker to a jQuery selection.
* @param target element - the target input field or division or span
* @param settings object - the new settings to use for this date picker instance (anonymous)
*/
_attachDatepicker: function(target, settings) {
var nodeName, inline, inst;
nodeName = target.nodeName.toLowerCase();
inline = (nodeName === "div" || nodeName === "span");
if (!target.id) {
this.uuid += 1;
target.id = "dp" + this.uuid;
}
inst = this._newInst($(target), inline);
inst.settings = $.extend({}, settings || {});
if (nodeName === "input") {
this._connectDatepicker(target, inst);
} else if (inline) {
this._inlineDatepicker(target, inst);
}
},
/* Create a new instance object. */
_newInst: function(target, inline) {
var id = target[0].id.replace(/([^A-Za-z0-9_\-])/g, "\\\\$1"); // escape jQuery meta chars
return {id: id, input: target, // associated target
selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection
drawMonth: 0, drawYear: 0, // month being drawn
inline: inline, // is datepicker inline or not
dpDiv: (!inline ? this.dpDiv : // presentation div
bindHover($("<div class='" + this._inlineClass + " ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")))};
},
/* Attach the date picker to an input field. */
_connectDatepicker: function(target, inst) {
var input = $(target);
inst.append = $([]);
inst.trigger = $([]);
if (input.hasClass(this.markerClassName)) {
return;
}
this._attachments(input, inst);
input.addClass(this.markerClassName).keydown(this._doKeyDown).
keypress(this._doKeyPress).keyup(this._doKeyUp);
this._autoSize(inst);
$.data(target, PROP_NAME, inst);
//If disabled option is true, disable the datepicker once it has been attached to the input (see ticket #5665)
if( inst.settings.disabled ) {
this._disableDatepicker( target );
}
},
/* Make attachments based on settings. */
_attachments: function(input, inst) {
var showOn, buttonText, buttonImage,
appendText = this._get(inst, "appendText"),
isRTL = this._get(inst, "isRTL");
if (inst.append) {
inst.append.remove();
}
if (appendText) {
inst.append = $("<span class='" + this._appendClass + "'>" + appendText + "</span>");
input[isRTL ? "before" : "after"](inst.append);
}
input.unbind("focus", this._showDatepicker);
if (inst.trigger) {
inst.trigger.remove();
}
showOn = this._get(inst, "showOn");
if (showOn === "focus" || showOn === "both") { // pop-up date picker when in the marked field
input.focus(this._showDatepicker);
}
if (showOn === "button" || showOn === "both") { // pop-up date picker when button clicked
buttonText = this._get(inst, "buttonText");
buttonImage = this._get(inst, "buttonImage");
inst.trigger = $(this._get(inst, "buttonImageOnly") ?
$("<img/>").addClass(this._triggerClass).
attr({ src: buttonImage, alt: buttonText, title: buttonText }) :
$("<button type='button'></button>").addClass(this._triggerClass).
html(!buttonImage ? buttonText : $("<img/>").attr(
{ src:buttonImage, alt:buttonText, title:buttonText })));
input[isRTL ? "before" : "after"](inst.trigger);
inst.trigger.click(function() {
if ($.datepicker._datepickerShowing && $.datepicker._lastInput === input[0]) {
$.datepicker._hideDatepicker();
} else if ($.datepicker._datepickerShowing && $.datepicker._lastInput !== input[0]) {
$.datepicker._hideDatepicker();
$.datepicker._showDatepicker(input[0]);
} else {
$.datepicker._showDatepicker(input[0]);
}
return false;
});
}
},
/* Apply the maximum length for the date format. */
_autoSize: function(inst) {
if (this._get(inst, "autoSize") && !inst.inline) {
var findMax, max, maxI, i,
date = new Date(2009, 12 - 1, 20), // Ensure double digits
dateFormat = this._get(inst, "dateFormat");
if (dateFormat.match(/[DM]/)) {
findMax = function(names) {
max = 0;
maxI = 0;
for (i = 0; i < names.length; i++) {
if (names[i].length > max) {
max = names[i].length;
maxI = i;
}
}
return maxI;
};
date.setMonth(findMax(this._get(inst, (dateFormat.match(/MM/) ?
"monthNames" : "monthNamesShort"))));
date.setDate(findMax(this._get(inst, (dateFormat.match(/DD/) ?
"dayNames" : "dayNamesShort"))) + 20 - date.getDay());
}
inst.input.attr("size", this._formatDate(inst, date).length);
}
},
/* Attach an inline date picker to a div. */
_inlineDatepicker: function(target, inst) {
var divSpan = $(target);
if (divSpan.hasClass(this.markerClassName)) {
return;
}
divSpan.addClass(this.markerClassName).append(inst.dpDiv);
$.data(target, PROP_NAME, inst);
this._setDate(inst, this._getDefaultDate(inst), true);
this._updateDatepicker(inst);
this._updateAlternate(inst);
//If disabled option is true, disable the datepicker before showing it (see ticket #5665)
if( inst.settings.disabled ) {
this._disableDatepicker( target );
}
// Set display:block in place of inst.dpDiv.show() which won't work on disconnected elements
// http://bugs.jqueryui.com/ticket/7552 - A Datepicker created on a detached div has zero height
inst.dpDiv.css( "display", "block" );
},
/* Pop-up the date picker in a "dialog" box.
* @param input element - ignored
* @param date string or Date - the initial date to display
* @param onSelect function - the function to call when a date is selected
* @param settings object - update the dialog date picker instance's settings (anonymous object)
* @param pos int[2] - coordinates for the dialog's position within the screen or
* event - with x/y coordinates or
* leave empty for default (screen centre)
* @return the manager object
*/
_dialogDatepicker: function(input, date, onSelect, settings, pos) {
var id, browserWidth, browserHeight, scrollX, scrollY,
inst = this._dialogInst; // internal instance
if (!inst) {
this.uuid += 1;
id = "dp" + this.uuid;
this._dialogInput = $("<input type='text' id='" + id +
"' style='position: absolute; top: -100px; width: 0px;'/>");
this._dialogInput.keydown(this._doKeyDown);
$("body").append(this._dialogInput);
inst = this._dialogInst = this._newInst(this._dialogInput, false);
inst.settings = {};
$.data(this._dialogInput[0], PROP_NAME, inst);
}
extendRemove(inst.settings, settings || {});
date = (date && date.constructor === Date ? this._formatDate(inst, date) : date);
this._dialogInput.val(date);
this._pos = (pos ? (pos.length ? pos : [pos.pageX, pos.pageY]) : null);
if (!this._pos) {
browserWidth = document.documentElement.clientWidth;
browserHeight = document.documentElement.clientHeight;
scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
scrollY = document.documentElement.scrollTop || document.body.scrollTop;
this._pos = // should use actual width/height below
[(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY];
}
// move input on screen for focus, but hidden behind dialog
this._dialogInput.css("left", (this._pos[0] + 20) + "px").css("top", this._pos[1] + "px");
inst.settings.onSelect = onSelect;
this._inDialog = true;
this.dpDiv.addClass(this._dialogClass);
this._showDatepicker(this._dialogInput[0]);
if ($.blockUI) {
$.blockUI(this.dpDiv);
}
$.data(this._dialogInput[0], PROP_NAME, inst);
return this;
},
/* Detach a datepicker from its control.
* @param target element - the target input field or division or span
*/
_destroyDatepicker: function(target) {
var nodeName,
$target = $(target),
inst = $.data(target, PROP_NAME);
if (!$target.hasClass(this.markerClassName)) {
return;
}
nodeName = target.nodeName.toLowerCase();
$.removeData(target, PROP_NAME);
if (nodeName === "input") {
inst.append.remove();
inst.trigger.remove();
$target.removeClass(this.markerClassName).
unbind("focus", this._showDatepicker).
unbind("keydown", this._doKeyDown).
unbind("keypress", this._doKeyPress).
unbind("keyup", this._doKeyUp);
} else if (nodeName === "div" || nodeName === "span") {
$target.removeClass(this.markerClassName).empty();
}
},
/* Enable the date picker to a jQuery selection.
* @param target element - the target input field or division or span
*/
_enableDatepicker: function(target) {
var nodeName, inline,
$target = $(target),
inst = $.data(target, PROP_NAME);
if (!$target.hasClass(this.markerClassName)) {
return;
}
nodeName = target.nodeName.toLowerCase();
if (nodeName === "input") {
target.disabled = false;
inst.trigger.filter("button").
each(function() { this.disabled = false; }).end().
filter("img").css({opacity: "1.0", cursor: ""});
} else if (nodeName === "div" || nodeName === "span") {
inline = $target.children("." + this._inlineClass);
inline.children().removeClass("ui-state-disabled");
inline.find("select.ui-datepicker-month, select.ui-datepicker-year").
prop("disabled", false);
}
this._disabledInputs = $.map(this._disabledInputs,
function(value) { return (value === target ? null : value); }); // delete entry
},
/* Disable the date picker to a jQuery selection.
* @param target element - the target input field or division or span
*/
_disableDatepicker: function(target) {
var nodeName, inline,
$target = $(target),
inst = $.data(target, PROP_NAME);
if (!$target.hasClass(this.markerClassName)) {
return;
}
nodeName = target.nodeName.toLowerCase();
if (nodeName === "input") {
target.disabled = true;
inst.trigger.filter("button").
each(function() { this.disabled = true; }).end().
filter("img").css({opacity: "0.5", cursor: "default"});
} else if (nodeName === "div" || nodeName === "span") {
inline = $target.children("." + this._inlineClass);
inline.children().addClass("ui-state-disabled");
inline.find("select.ui-datepicker-month, select.ui-datepicker-year").
prop("disabled", true);
}
this._disabledInputs = $.map(this._disabledInputs,
function(value) { return (value === target ? null : value); }); // delete entry
this._disabledInputs[this._disabledInputs.length] = target;
},
/* Is the first field in a jQuery collection disabled as a datepicker?
* @param target element - the target input field or division or span
* @return boolean - true if disabled, false if enabled
*/
_isDisabledDatepicker: function(target) {
if (!target) {
return false;
}
for (var i = 0; i < this._disabledInputs.length; i++) {
if (this._disabledInputs[i] === target) {
return true;
}
}
return false;
},
/* Retrieve the instance data for the target control.
* @param target element - the target input field or division or span
* @return object - the associated instance data
* @throws error if a jQuery problem getting data
*/
_getInst: function(target) {
try {
return $.data(target, PROP_NAME);
}
catch (err) {
throw "Missing instance data for this datepicker";
}
},
/* Update or retrieve the settings for a date picker attached to an input field or division.
* @param target element - the target input field or division or span
* @param name object - the new settings to update or
* string - the name of the setting to change or retrieve,
* when retrieving also "all" for all instance settings or
* "defaults" for all global defaults
* @param value any - the new value for the setting
* (omit if above is an object or to retrieve a value)
*/
_optionDatepicker: function(target, name, value) {
var settings, date, minDate, maxDate,
inst = this._getInst(target);
if (arguments.length === 2 && typeof name === "string") {
return (name === "defaults" ? $.extend({}, $.datepicker._defaults) :
(inst ? (name === "all" ? $.extend({}, inst.settings) :
this._get(inst, name)) : null));
}
settings = name || {};
if (typeof name === "string") {
settings = {};
settings[name] = value;
}
if (inst) {
if (this._curInst === inst) {
this._hideDatepicker();
}
date = this._getDateDatepicker(target, true);
minDate = this._getMinMaxDate(inst, "min");
maxDate = this._getMinMaxDate(inst, "max");
extendRemove(inst.settings, settings);
// reformat the old minDate/maxDate values if dateFormat changes and a new minDate/maxDate isn't provided
if (minDate !== null && settings.dateFormat !== undefined && settings.minDate === undefined) {
inst.settings.minDate = this._formatDate(inst, minDate);
}
if (maxDate !== null && settings.dateFormat !== undefined && settings.maxDate === undefined) {
inst.settings.maxDate = this._formatDate(inst, maxDate);
}
if ( "disabled" in settings ) {
if ( settings.disabled ) {
this._disableDatepicker(target);
} else {
this._enableDatepicker(target);
}
}
this._attachments($(target), inst);
this._autoSize(inst);
this._setDate(inst, date);
this._updateAlternate(inst);
this._updateDatepicker(inst);
}
},
// change method deprecated
_changeDatepicker: function(target, name, value) {
this._optionDatepicker(target, name, value);
},
/* Redraw the date picker attached to an input field or division.
* @param target element - the target input field or division or span
*/
_refreshDatepicker: function(target) {
var inst = this._getInst(target);
if (inst) {
this._updateDatepicker(inst);
}
},
/* Set the dates for a jQuery selection.
* @param target element - the target input field or division or span
* @param date Date - the new date
*/
_setDateDatepicker: function(target, date) {
var inst = this._getInst(target);
if (inst) {
this._setDate(inst, date);
this._updateDatepicker(inst);
this._updateAlternate(inst);
}
},
/* Get the date(s) for the first entry in a jQuery selection.
* @param target element - the target input field or division or span
* @param noDefault boolean - true if no default date is to be used
* @return Date - the current date
*/
_getDateDatepicker: function(target, noDefault) {
var inst = this._getInst(target);
if (inst && !inst.inline) {
this._setDateFromField(inst, noDefault);
}
return (inst ? this._getDate(inst) : null);
},
/* Handle keystrokes. */
_doKeyDown: function(event) {
var onSelect, dateStr, sel,
inst = $.datepicker._getInst(event.target),
handled = true,
isRTL = inst.dpDiv.is(".ui-datepicker-rtl");
inst._keyEvent = true;
if ($.datepicker._datepickerShowing) {
switch (event.keyCode) {
case 9: $.datepicker._hideDatepicker();
handled = false;
break; // hide on tab out
case 13: sel = $("td." + $.datepicker._dayOverClass + ":not(." +
$.datepicker._currentClass + ")", inst.dpDiv);
if (sel[0]) {
$.datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[0]);
}
onSelect = $.datepicker._get(inst, "onSelect");
if (onSelect) {
dateStr = $.datepicker._formatDate(inst);
// trigger custom callback
onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]);
} else {
$.datepicker._hideDatepicker();
}
return false; // don't submit the form
case 27: $.datepicker._hideDatepicker();
break; // hide on escape
case 33: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
-$.datepicker._get(inst, "stepBigMonths") :
-$.datepicker._get(inst, "stepMonths")), "M");
break; // previous month/year on page up/+ ctrl
case 34: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
+$.datepicker._get(inst, "stepBigMonths") :
+$.datepicker._get(inst, "stepMonths")), "M");
break; // next month/year on page down/+ ctrl
case 35: if (event.ctrlKey || event.metaKey) {
$.datepicker._clearDate(event.target);
}
handled = event.ctrlKey || event.metaKey;
break; // clear on ctrl or command +end
case 36: if (event.ctrlKey || event.metaKey) {
$.datepicker._gotoToday(event.target);
}
handled = event.ctrlKey || event.metaKey;
break; // current on ctrl or command +home
case 37: if (event.ctrlKey || event.metaKey) {
$.datepicker._adjustDate(event.target, (isRTL ? +1 : -1), "D");
}
handled = event.ctrlKey || event.metaKey;
// -1 day on ctrl or command +left
if (event.originalEvent.altKey) {
$.datepicker._adjustDate(event.target, (event.ctrlKey ?
-$.datepicker._get(inst, "stepBigMonths") :
-$.datepicker._get(inst, "stepMonths")), "M");
}
// next month/year on alt +left on Mac
break;
case 38: if (event.ctrlKey || event.metaKey) {
$.datepicker._adjustDate(event.target, -7, "D");
}
handled = event.ctrlKey || event.metaKey;
break; // -1 week on ctrl or command +up
case 39: if (event.ctrlKey || event.metaKey) {
$.datepicker._adjustDate(event.target, (isRTL ? -1 : +1), "D");
}
handled = event.ctrlKey || event.metaKey;
// +1 day on ctrl or command +right
if (event.originalEvent.altKey) {
$.datepicker._adjustDate(event.target, (event.ctrlKey ?
+$.datepicker._get(inst, "stepBigMonths") :
+$.datepicker._get(inst, "stepMonths")), "M");
}
// next month/year on alt +right
break;
case 40: if (event.ctrlKey || event.metaKey) {
$.datepicker._adjustDate(event.target, +7, "D");
}
handled = event.ctrlKey || event.metaKey;
break; // +1 week on ctrl or command +down
default: handled = false;
}
} else if (event.keyCode === 36 && event.ctrlKey) { // display the date picker on ctrl+home
$.datepicker._showDatepicker(this);
} else {
handled = false;
}
if (handled) {
event.preventDefault();
event.stopPropagation();
}
},
/* Filter entered characters - based on date format. */
_doKeyPress: function(event) {
var chars, chr,
inst = $.datepicker._getInst(event.target);
if ($.datepicker._get(inst, "constrainInput")) {
chars = $.datepicker._possibleChars($.datepicker._get(inst, "dateFormat"));
chr = String.fromCharCode(event.charCode == null ? event.keyCode : event.charCode);
return event.ctrlKey || event.metaKey || (chr < " " || !chars || chars.indexOf(chr) > -1);
}
},
/* Synchronise manual entry and field/alternate field. */
_doKeyUp: function(event) {
var date,
inst = $.datepicker._getInst(event.target);
if (inst.input.val() !== inst.lastVal) {
try {
date = $.datepicker.parseDate($.datepicker._get(inst, "dateFormat"),
(inst.input ? inst.input.val() : null),
$.datepicker._getFormatConfig(inst));
if (date) { // only if valid
$.datepicker._setDateFromField(inst);
$.datepicker._updateAlternate(inst);
$.datepicker._updateDatepicker(inst);
}
}
catch (err) {
}
}
return true;
},
/* Pop-up the date picker for a given input field.
* If false returned from beforeShow event handler do not show.
* @param input element - the input field attached to the date picker or
* event - if triggered by focus
*/
_showDatepicker: function(input) {
input = input.target || input;
if (input.nodeName.toLowerCase() !== "input") { // find from button/image trigger
input = $("input", input.parentNode)[0];
}
if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput === input) { // already here
return;
}
var inst, beforeShow, beforeShowSettings, isFixed,
offset, showAnim, duration;
inst = $.datepicker._getInst(input);
if ($.datepicker._curInst && $.datepicker._curInst !== inst) {
$.datepicker._curInst.dpDiv.stop(true, true);
if ( inst && $.datepicker._datepickerShowing ) {
$.datepicker._hideDatepicker( $.datepicker._curInst.input[0] );
}
}
beforeShow = $.datepicker._get(inst, "beforeShow");
beforeShowSettings = beforeShow ? beforeShow.apply(input, [input, inst]) : {};
if(beforeShowSettings === false){
return;
}
extendRemove(inst.settings, beforeShowSettings);
inst.lastVal = null;
$.datepicker._lastInput = input;
$.datepicker._setDateFromField(inst);
if ($.datepicker._inDialog) { // hide cursor
input.value = "";
}
if (!$.datepicker._pos) { // position below input
$.datepicker._pos = $.datepicker._findPos(input);
$.datepicker._pos[1] += input.offsetHeight; // add the height
}
isFixed = false;
$(input).parents().each(function() {
isFixed |= $(this).css("position") === "fixed";
return !isFixed;
});
offset = {left: $.datepicker._pos[0], top: $.datepicker._pos[1]};
$.datepicker._pos = null;
//to avoid flashes on Firefox
inst.dpDiv.empty();
// determine sizing offscreen
inst.dpDiv.css({position: "absolute", display: "block", top: "-1000px"});
$.datepicker._updateDatepicker(inst);
// fix width for dynamic number of date pickers
// and adjust position before showing
offset = $.datepicker._checkOffset(inst, offset, isFixed);
inst.dpDiv.css({position: ($.datepicker._inDialog && $.blockUI ?
"static" : (isFixed ? "fixed" : "absolute")), display: "none",
left: offset.left + "px", top: offset.top + "px"});
if (!inst.inline) {
showAnim = $.datepicker._get(inst, "showAnim");
duration = $.datepicker._get(inst, "duration");
inst.dpDiv.zIndex($(input).zIndex()+1);
$.datepicker._datepickerShowing = true;
if ( $.effects && $.effects.effect[ showAnim ] ) {
inst.dpDiv.show(showAnim, $.datepicker._get(inst, "showOptions"), duration);
} else {
inst.dpDiv[showAnim || "show"](showAnim ? duration : null);
}
if ( $.datepicker._shouldFocusInput( inst ) ) {
inst.input.focus();
}
$.datepicker._curInst = inst;
}
},
/* Generate the date picker content. */
_updateDatepicker: function(inst) {
this.maxRows = 4; //Reset the max number of rows being displayed (see #7043)
instActive = inst; // for delegate hover events
inst.dpDiv.empty().append(this._generateHTML(inst));
this._attachHandlers(inst);
inst.dpDiv.find("." + this._dayOverClass + " a").mouseover();
var origyearshtml,
numMonths = this._getNumberOfMonths(inst),
cols = numMonths[1],
width = 17;
inst.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width("");
if (cols > 1) {
inst.dpDiv.addClass("ui-datepicker-multi-" + cols).css("width", (width * cols) + "em");
}
inst.dpDiv[(numMonths[0] !== 1 || numMonths[1] !== 1 ? "add" : "remove") +
"Class"]("ui-datepicker-multi");
inst.dpDiv[(this._get(inst, "isRTL") ? "add" : "remove") +
"Class"]("ui-datepicker-rtl");
if (inst === $.datepicker._curInst && $.datepicker._datepickerShowing && $.datepicker._shouldFocusInput( inst ) ) {
inst.input.focus();
}
// deffered render of the years select (to avoid flashes on Firefox)
if( inst.yearshtml ){
origyearshtml = inst.yearshtml;
setTimeout(function(){
//assure that inst.yearshtml didn't change.
if( origyearshtml === inst.yearshtml && inst.yearshtml ){
inst.dpDiv.find("select.ui-datepicker-year:first").replaceWith(inst.yearshtml);
}
origyearshtml = inst.yearshtml = null;
}, 0);
}
},
// #6694 - don't focus the input if it's already focused
// this breaks the change event in IE
// Support: IE and jQuery <1.9
_shouldFocusInput: function( inst ) {
return inst.input && inst.input.is( ":visible" ) && !inst.input.is( ":disabled" ) && !inst.input.is( ":focus" );
},
/* Check positioning to remain on screen. */
_checkOffset: function(inst, offset, isFixed) {
var dpWidth = inst.dpDiv.outerWidth(),
dpHeight = inst.dpDiv.outerHeight(),
inputWidth = inst.input ? inst.input.outerWidth() : 0,
inputHeight = inst.input ? inst.input.outerHeight() : 0,
viewWidth = document.documentElement.clientWidth + (isFixed ? 0 : $(document).scrollLeft()),
viewHeight = document.documentElement.clientHeight + (isFixed ? 0 : $(document).scrollTop());
offset.left -= (this._get(inst, "isRTL") ? (dpWidth - inputWidth) : 0);
offset.left -= (isFixed && offset.left === inst.input.offset().left) ? $(document).scrollLeft() : 0;
offset.top -= (isFixed && offset.top === (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0;
// now check if datepicker is showing outside window viewport - move to a better place if so.
offset.left -= Math.min(offset.left, (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ?
Math.abs(offset.left + dpWidth - viewWidth) : 0);
offset.top -= Math.min(offset.top, (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ?
Math.abs(dpHeight + inputHeight) : 0);
return offset;
},
/* Find an object's position on the screen. */
_findPos: function(obj) {
var position,
inst = this._getInst(obj),
isRTL = this._get(inst, "isRTL");
while (obj && (obj.type === "hidden" || obj.nodeType !== 1 || $.expr.filters.hidden(obj))) {
obj = obj[isRTL ? "previousSibling" : "nextSibling"];
}
position = $(obj).offset();
return [position.left, position.top];
},
/* Hide the date picker from view.
* @param input element - the input field attached to the date picker
*/
_hideDatepicker: function(input) {
var showAnim, duration, postProcess, onClose,
inst = this._curInst;
if (!inst || (input && inst !== $.data(input, PROP_NAME))) {
return;
}
if (this._datepickerShowing) {
showAnim = this._get(inst, "showAnim");
duration = this._get(inst, "duration");
postProcess = function() {
$.datepicker._tidyDialog(inst);
};
// DEPRECATED: after BC for 1.8.x $.effects[ showAnim ] is not needed
if ( $.effects && ( $.effects.effect[ showAnim ] || $.effects[ showAnim ] ) ) {
inst.dpDiv.hide(showAnim, $.datepicker._get(inst, "showOptions"), duration, postProcess);
} else {
inst.dpDiv[(showAnim === "slideDown" ? "slideUp" :
(showAnim === "fadeIn" ? "fadeOut" : "hide"))]((showAnim ? duration : null), postProcess);
}
if (!showAnim) {
postProcess();
}
this._datepickerShowing = false;
onClose = this._get(inst, "onClose");
if (onClose) {
onClose.apply((inst.input ? inst.input[0] : null), [(inst.input ? inst.input.val() : ""), inst]);
}
this._lastInput = null;
if (this._inDialog) {
this._dialogInput.css({ position: "absolute", left: "0", top: "-100px" });
if ($.blockUI) {
$.unblockUI();
$("body").append(this.dpDiv);
}
}
this._inDialog = false;
}
},
/* Tidy up after a dialog display. */
_tidyDialog: function(inst) {
inst.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar");
},
/* Close date picker if clicked elsewhere. */
_checkExternalClick: function(event) {
if (!$.datepicker._curInst) {
return;
}
var $target = $(event.target),
inst = $.datepicker._getInst($target[0]);
if ( ( ( $target[0].id !== $.datepicker._mainDivId &&
$target.parents("#" + $.datepicker._mainDivId).length === 0 &&
!$target.hasClass($.datepicker.markerClassName) &&
!$target.closest("." + $.datepicker._triggerClass).length &&
$.datepicker._datepickerShowing && !($.datepicker._inDialog && $.blockUI) ) ) ||
( $target.hasClass($.datepicker.markerClassName) && $.datepicker._curInst !== inst ) ) {
$.datepicker._hideDatepicker();
}
},
/* Adjust one of the date sub-fields. */
_adjustDate: function(id, offset, period) {
var target = $(id),
inst = this._getInst(target[0]);
if (this._isDisabledDatepicker(target[0])) {
return;
}
this._adjustInstDate(inst, offset +
(period === "M" ? this._get(inst, "showCurrentAtPos") : 0), // undo positioning
period);
this._updateDatepicker(inst);
},
/* Action for current link. */
_gotoToday: function(id) {
var date,
target = $(id),
inst = this._getInst(target[0]);
if (this._get(inst, "gotoCurrent") && inst.currentDay) {
inst.selectedDay = inst.currentDay;
inst.drawMonth = inst.selectedMonth = inst.currentMonth;
inst.drawYear = inst.selectedYear = inst.currentYear;
} else {
date = new Date();
inst.selectedDay = date.getDate();
inst.drawMonth = inst.selectedMonth = date.getMonth();
inst.drawYear = inst.selectedYear = date.getFullYear();
}
this._notifyChange(inst);
this._adjustDate(target);
},
/* Action for selecting a new month/year. */
_selectMonthYear: function(id, select, period) {
var target = $(id),
inst = this._getInst(target[0]);
inst["selected" + (period === "M" ? "Month" : "Year")] =
inst["draw" + (period === "M" ? "Month" : "Year")] =
parseInt(select.options[select.selectedIndex].value,10);
this._notifyChange(inst);
this._adjustDate(target);
},
/* Action for selecting a day. */
_selectDay: function(id, month, year, td) {
var inst,
target = $(id);
if ($(td).hasClass(this._unselectableClass) || this._isDisabledDatepicker(target[0])) {
return;
}
inst = this._getInst(target[0]);
inst.selectedDay = inst.currentDay = $("a", td).html();
inst.selectedMonth = inst.currentMonth = month;
inst.selectedYear = inst.currentYear = year;
this._selectDate(id, this._formatDate(inst,
inst.currentDay, inst.currentMonth, inst.currentYear));
},
/* Erase the input field and hide the date picker. */
_clearDate: function(id) {
var target = $(id);
this._selectDate(target, "");
},
/* Update the input field with the selected date. */
_selectDate: function(id, dateStr) {
var onSelect,
target = $(id),
inst = this._getInst(target[0]);
dateStr = (dateStr != null ? dateStr : this._formatDate(inst));
if (inst.input) {
inst.input.val(dateStr);
}
this._updateAlternate(inst);
onSelect = this._get(inst, "onSelect");
if (onSelect) {
onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); // trigger custom callback
} else if (inst.input) {
inst.input.trigger("change"); // fire the change event
}
if (inst.inline){
this._updateDatepicker(inst);
} else {
this._hideDatepicker();
this._lastInput = inst.input[0];
if (typeof(inst.input[0]) !== "object") {
inst.input.focus(); // restore focus
}
this._lastInput = null;
}
},
/* Update any alternate field to synchronise with the main field. */
_updateAlternate: function(inst) {
var altFormat, date, dateStr,
altField = this._get(inst, "altField");
if (altField) { // update alternate field too
altFormat = this._get(inst, "altFormat") || this._get(inst, "dateFormat");
date = this._getDate(inst);
dateStr = this.formatDate(altFormat, date, this._getFormatConfig(inst));
$(altField).each(function() { $(this).val(dateStr); });
}
},
/* Set as beforeShowDay function to prevent selection of weekends.
* @param date Date - the date to customise
* @return [boolean, string] - is this date selectable?, what is its CSS class?
*/
noWeekends: function(date) {
var day = date.getDay();
return [(day > 0 && day < 6), ""];
},
/* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition.
* @param date Date - the date to get the week for
* @return number - the number of the week within the year that contains this date
*/
iso8601Week: function(date) {
var time,
checkDate = new Date(date.getTime());
// Find Thursday of this week starting on Monday
checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7));
time = checkDate.getTime();
checkDate.setMonth(0); // Compare with Jan 1
checkDate.setDate(1);
return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1;
},
/* Parse a string value into a date object.
* See formatDate below for the possible formats.
*
* @param format string - the expected format of the date
* @param value string - the date in the above format
* @param settings Object - attributes include:
* shortYearCutoff number - the cutoff year for determining the century (optional)
* dayNamesShort string[7] - abbreviated names of the days from Sunday (optional)
* dayNames string[7] - names of the days from Sunday (optional)
* monthNamesShort string[12] - abbreviated names of the months (optional)
* monthNames string[12] - names of the months (optional)
* @return Date - the extracted date value or null if value is blank
*/
parseDate: function (format, value, settings) {
if (format == null || value == null) {
throw "Invalid arguments";
}
value = (typeof value === "object" ? value.toString() : value + "");
if (value === "") {
return null;
}
var iFormat, dim, extra,
iValue = 0,
shortYearCutoffTemp = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff,
shortYearCutoff = (typeof shortYearCutoffTemp !== "string" ? shortYearCutoffTemp :
new Date().getFullYear() % 100 + parseInt(shortYearCutoffTemp, 10)),
dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort,
dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames,
monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort,
monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames,
year = -1,
month = -1,
day = -1,
doy = -1,
literal = false,
date,
// Check whether a format character is doubled
lookAhead = function(match) {
var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match);
if (matches) {
iFormat++;
}
return matches;
},
// Extract a number from the string value
getNumber = function(match) {
var isDoubled = lookAhead(match),
size = (match === "@" ? 14 : (match === "!" ? 20 :
(match === "y" && isDoubled ? 4 : (match === "o" ? 3 : 2)))),
digits = new RegExp("^\\d{1," + size + "}"),
num = value.substring(iValue).match(digits);
if (!num) {
throw "Missing number at position " + iValue;
}
iValue += num[0].length;
return parseInt(num[0], 10);
},
// Extract a name from the string value and convert to an index
getName = function(match, shortNames, longNames) {
var index = -1,
names = $.map(lookAhead(match) ? longNames : shortNames, function (v, k) {
return [ [k, v] ];
}).sort(function (a, b) {
return -(a[1].length - b[1].length);
});
$.each(names, function (i, pair) {
var name = pair[1];
if (value.substr(iValue, name.length).toLowerCase() === name.toLowerCase()) {
index = pair[0];
iValue += name.length;
return false;
}
});
if (index !== -1) {
return index + 1;
} else {
throw "Unknown name at position " + iValue;
}
},
// Confirm that a literal character matches the string value
checkLiteral = function() {
if (value.charAt(iValue) !== format.charAt(iFormat)) {
throw "Unexpected literal at position " + iValue;
}
iValue++;
};
for (iFormat = 0; iFormat < format.length; iFormat++) {
if (literal) {
if (format.charAt(iFormat) === "'" && !lookAhead("'")) {
literal = false;
} else {
checkLiteral();
}
} else {
switch (format.charAt(iFormat)) {
case "d":
day = getNumber("d");
break;
case "D":
getName("D", dayNamesShort, dayNames);
break;
case "o":
doy = getNumber("o");
break;
case "m":
month = getNumber("m");
break;
case "M":
month = getName("M", monthNamesShort, monthNames);
break;
case "y":
year = getNumber("y");
break;
case "@":
date = new Date(getNumber("@"));
year = date.getFullYear();
month = date.getMonth() + 1;
day = date.getDate();
break;
case "!":
date = new Date((getNumber("!") - this._ticksTo1970) / 10000);
year = date.getFullYear();
month = date.getMonth() + 1;
day = date.getDate();
break;
case "'":
if (lookAhead("'")){
checkLiteral();
} else {
literal = true;
}
break;
default:
checkLiteral();
}
}
}
if (iValue < value.length){
extra = value.substr(iValue);
if (!/^\s+/.test(extra)) {
throw "Extra/unparsed characters found in date: " + extra;
}
}
if (year === -1) {
year = new Date().getFullYear();
} else if (year < 100) {
year += new Date().getFullYear() - new Date().getFullYear() % 100 +
(year <= shortYearCutoff ? 0 : -100);
}
if (doy > -1) {
month = 1;
day = doy;
do {
dim = this._getDaysInMonth(year, month - 1);
if (day <= dim) {
break;
}
month++;
day -= dim;
} while (true);
}
date = this._daylightSavingAdjust(new Date(year, month - 1, day));
if (date.getFullYear() !== year || date.getMonth() + 1 !== month || date.getDate() !== day) {
throw "Invalid date"; // E.g. 31/02/00
}
return date;
},
/* Standard date formats. */
ATOM: "yy-mm-dd", // RFC 3339 (ISO 8601)
COOKIE: "D, dd M yy",
ISO_8601: "yy-mm-dd",
RFC_822: "D, d M y",
RFC_850: "DD, dd-M-y",
RFC_1036: "D, d M y",
RFC_1123: "D, d M yy",
RFC_2822: "D, d M yy",
RSS: "D, d M y", // RFC 822
TICKS: "!",
TIMESTAMP: "@",
W3C: "yy-mm-dd", // ISO 8601
_ticksTo1970: (((1970 - 1) * 365 + Math.floor(1970 / 4) - Math.floor(1970 / 100) +
Math.floor(1970 / 400)) * 24 * 60 * 60 * 10000000),
/* Format a date object into a string value.
* The format can be combinations of the following:
* d - day of month (no leading zero)
* dd - day of month (two digit)
* o - day of year (no leading zeros)
* oo - day of year (three digit)
* D - day name short
* DD - day name long
* m - month of year (no leading zero)
* mm - month of year (two digit)
* M - month name short
* MM - month name long
* y - year (two digit)
* yy - year (four digit)
* @ - Unix timestamp (ms since 01/01/1970)
* ! - Windows ticks (100ns since 01/01/0001)
* "..." - literal text
* '' - single quote
*
* @param format string - the desired format of the date
* @param date Date - the date value to format
* @param settings Object - attributes include:
* dayNamesShort string[7] - abbreviated names of the days from Sunday (optional)
* dayNames string[7] - names of the days from Sunday (optional)
* monthNamesShort string[12] - abbreviated names of the months (optional)
* monthNames string[12] - names of the months (optional)
* @return string - the date in the above format
*/
formatDate: function (format, date, settings) {
if (!date) {
return "";
}
var iFormat,
dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort,
dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames,
monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort,
monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames,
// Check whether a format character is doubled
lookAhead = function(match) {
var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match);
if (matches) {
iFormat++;
}
return matches;
},
// Format a number, with leading zero if necessary
formatNumber = function(match, value, len) {
var num = "" + value;
if (lookAhead(match)) {
while (num.length < len) {
num = "0" + num;
}
}
return num;
},
// Format a name, short or long as requested
formatName = function(match, value, shortNames, longNames) {
return (lookAhead(match) ? longNames[value] : shortNames[value]);
},
output = "",
literal = false;
if (date) {
for (iFormat = 0; iFormat < format.length; iFormat++) {
if (literal) {
if (format.charAt(iFormat) === "'" && !lookAhead("'")) {
literal = false;
} else {
output += format.charAt(iFormat);
}
} else {
switch (format.charAt(iFormat)) {
case "d":
output += formatNumber("d", date.getDate(), 2);
break;
case "D":
output += formatName("D", date.getDay(), dayNamesShort, dayNames);
break;
case "o":
output += formatNumber("o",
Math.round((new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime() - new Date(date.getFullYear(), 0, 0).getTime()) / 86400000), 3);
break;
case "m":
output += formatNumber("m", date.getMonth() + 1, 2);
break;
case "M":
output += formatName("M", date.getMonth(), monthNamesShort, monthNames);
break;
case "y":
output += (lookAhead("y") ? date.getFullYear() :
(date.getYear() % 100 < 10 ? "0" : "") + date.getYear() % 100);
break;
case "@":
output += date.getTime();
break;
case "!":
output += date.getTime() * 10000 + this._ticksTo1970;
break;
case "'":
if (lookAhead("'")) {
output += "'";
} else {
literal = true;
}
break;
default:
output += format.charAt(iFormat);
}
}
}
}
return output;
},
/* Extract all possible characters from the date format. */
_possibleChars: function (format) {
var iFormat,
chars = "",
literal = false,
// Check whether a format character is doubled
lookAhead = function(match) {
var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match);
if (matches) {
iFormat++;
}
return matches;
};
for (iFormat = 0; iFormat < format.length; iFormat++) {
if (literal) {
if (format.charAt(iFormat) === "'" && !lookAhead("'")) {
literal = false;
} else {
chars += format.charAt(iFormat);
}
} else {
switch (format.charAt(iFormat)) {
case "d": case "m": case "y": case "@":
chars += "0123456789";
break;
case "D": case "M":
return null; // Accept anything
case "'":
if (lookAhead("'")) {
chars += "'";
} else {
literal = true;
}
break;
default:
chars += format.charAt(iFormat);
}
}
}
return chars;
},
/* Get a setting value, defaulting if necessary. */
_get: function(inst, name) {
return inst.settings[name] !== undefined ?
inst.settings[name] : this._defaults[name];
},
/* Parse existing date and initialise date picker. */
_setDateFromField: function(inst, noDefault) {
if (inst.input.val() === inst.lastVal) {
return;
}
var dateFormat = this._get(inst, "dateFormat"),
dates = inst.lastVal = inst.input ? inst.input.val() : null,
defaultDate = this._getDefaultDate(inst),
date = defaultDate,
settings = this._getFormatConfig(inst);
try {
date = this.parseDate(dateFormat, dates, settings) || defaultDate;
} catch (event) {
dates = (noDefault ? "" : dates);
}
inst.selectedDay = date.getDate();
inst.drawMonth = inst.selectedMonth = date.getMonth();
inst.drawYear = inst.selectedYear = date.getFullYear();
inst.currentDay = (dates ? date.getDate() : 0);
inst.currentMonth = (dates ? date.getMonth() : 0);
inst.currentYear = (dates ? date.getFullYear() : 0);
this._adjustInstDate(inst);
},
/* Retrieve the default date shown on opening. */
_getDefaultDate: function(inst) {
return this._restrictMinMax(inst,
this._determineDate(inst, this._get(inst, "defaultDate"), new Date()));
},
/* A date may be specified as an exact value or a relative one. */
_determineDate: function(inst, date, defaultDate) {
var offsetNumeric = function(offset) {
var date = new Date();
date.setDate(date.getDate() + offset);
return date;
},
offsetString = function(offset) {
try {
return $.datepicker.parseDate($.datepicker._get(inst, "dateFormat"),
offset, $.datepicker._getFormatConfig(inst));
}
catch (e) {
// Ignore
}
var date = (offset.toLowerCase().match(/^c/) ?
$.datepicker._getDate(inst) : null) || new Date(),
year = date.getFullYear(),
month = date.getMonth(),
day = date.getDate(),
pattern = /([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,
matches = pattern.exec(offset);
while (matches) {
switch (matches[2] || "d") {
case "d" : case "D" :
day += parseInt(matches[1],10); break;
case "w" : case "W" :
day += parseInt(matches[1],10) * 7; break;
case "m" : case "M" :
month += parseInt(matches[1],10);
day = Math.min(day, $.datepicker._getDaysInMonth(year, month));
break;
case "y": case "Y" :
year += parseInt(matches[1],10);
day = Math.min(day, $.datepicker._getDaysInMonth(year, month));
break;
}
matches = pattern.exec(offset);
}
return new Date(year, month, day);
},
newDate = (date == null || date === "" ? defaultDate : (typeof date === "string" ? offsetString(date) :
(typeof date === "number" ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : new Date(date.getTime()))));
newDate = (newDate && newDate.toString() === "Invalid Date" ? defaultDate : newDate);
if (newDate) {
newDate.setHours(0);
newDate.setMinutes(0);
newDate.setSeconds(0);
newDate.setMilliseconds(0);
}
return this._daylightSavingAdjust(newDate);
},
/* Handle switch to/from daylight saving.
* Hours may be non-zero on daylight saving cut-over:
* > 12 when midnight changeover, but then cannot generate
* midnight datetime, so jump to 1AM, otherwise reset.
* @param date (Date) the date to check
* @return (Date) the corrected date
*/
_daylightSavingAdjust: function(date) {
if (!date) {
return null;
}
date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0);
return date;
},
/* Set the date(s) directly. */
_setDate: function(inst, date, noChange) {
var clear = !date,
origMonth = inst.selectedMonth,
origYear = inst.selectedYear,
newDate = this._restrictMinMax(inst, this._determineDate(inst, date, new Date()));
inst.selectedDay = inst.currentDay = newDate.getDate();
inst.drawMonth = inst.selectedMonth = inst.currentMonth = newDate.getMonth();
inst.drawYear = inst.selectedYear = inst.currentYear = newDate.getFullYear();
if ((origMonth !== inst.selectedMonth || origYear !== inst.selectedYear) && !noChange) {
this._notifyChange(inst);
}
this._adjustInstDate(inst);
if (inst.input) {
inst.input.val(clear ? "" : this._formatDate(inst));
}
},
/* Retrieve the date(s) directly. */
_getDate: function(inst) {
var startDate = (!inst.currentYear || (inst.input && inst.input.val() === "") ? null :
this._daylightSavingAdjust(new Date(
inst.currentYear, inst.currentMonth, inst.currentDay)));
return startDate;
},
/* Attach the onxxx handlers. These are declared statically so
* they work with static code transformers like Caja.
*/
_attachHandlers: function(inst) {
var stepMonths = this._get(inst, "stepMonths"),
id = "#" + inst.id.replace( /\\\\/g, "\\" );
inst.dpDiv.find("[data-handler]").map(function () {
var handler = {
prev: function () {
$.datepicker._adjustDate(id, -stepMonths, "M");
},
next: function () {
$.datepicker._adjustDate(id, +stepMonths, "M");
},
hide: function () {
$.datepicker._hideDatepicker();
},
today: function () {
$.datepicker._gotoToday(id);
},
selectDay: function () {
$.datepicker._selectDay(id, +this.getAttribute("data-month"), +this.getAttribute("data-year"), this);
return false;
},
selectMonth: function () {
$.datepicker._selectMonthYear(id, this, "M");
return false;
},
selectYear: function () {
$.datepicker._selectMonthYear(id, this, "Y");
return false;
}
};
$(this).bind(this.getAttribute("data-event"), handler[this.getAttribute("data-handler")]);
});
},
/* Generate the HTML for the current state of the date picker. */
_generateHTML: function(inst) {
var maxDraw, prevText, prev, nextText, next, currentText, gotoDate,
controls, buttonPanel, firstDay, showWeek, dayNames, dayNamesMin,
monthNames, monthNamesShort, beforeShowDay, showOtherMonths,
selectOtherMonths, defaultDate, html, dow, row, group, col, selectedDate,
cornerClass, calender, thead, day, daysInMonth, leadDays, curRows, numRows,
printDate, dRow, tbody, daySettings, otherMonth, unselectable,
tempDate = new Date(),
today = this._daylightSavingAdjust(
new Date(tempDate.getFullYear(), tempDate.getMonth(), tempDate.getDate())), // clear time
isRTL = this._get(inst, "isRTL"),
showButtonPanel = this._get(inst, "showButtonPanel"),
hideIfNoPrevNext = this._get(inst, "hideIfNoPrevNext"),
navigationAsDateFormat = this._get(inst, "navigationAsDateFormat"),
numMonths = this._getNumberOfMonths(inst),
showCurrentAtPos = this._get(inst, "showCurrentAtPos"),
stepMonths = this._get(inst, "stepMonths"),
isMultiMonth = (numMonths[0] !== 1 || numMonths[1] !== 1),
currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) :
new Date(inst.currentYear, inst.currentMonth, inst.currentDay))),
minDate = this._getMinMaxDate(inst, "min"),
maxDate = this._getMinMaxDate(inst, "max"),
drawMonth = inst.drawMonth - showCurrentAtPos,
drawYear = inst.drawYear;
if (drawMonth < 0) {
drawMonth += 12;
drawYear--;
}
if (maxDate) {
maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(),
maxDate.getMonth() - (numMonths[0] * numMonths[1]) + 1, maxDate.getDate()));
maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw);
while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) {
drawMonth--;
if (drawMonth < 0) {
drawMonth = 11;
drawYear--;
}
}
}
inst.drawMonth = drawMonth;
inst.drawYear = drawYear;
prevText = this._get(inst, "prevText");
prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText,
this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)),
this._getFormatConfig(inst)));
prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ?
"<a class='ui-datepicker-prev ui-corner-all' data-handler='prev' data-event='click'" +
" title='" + prevText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w") + "'>" + prevText + "</span></a>" :
(hideIfNoPrevNext ? "" : "<a class='ui-datepicker-prev ui-corner-all ui-state-disabled' title='"+ prevText +"'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w") + "'>" + prevText + "</span></a>"));
nextText = this._get(inst, "nextText");
nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText,
this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)),
this._getFormatConfig(inst)));
next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ?
"<a class='ui-datepicker-next ui-corner-all' data-handler='next' data-event='click'" +
" title='" + nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e") + "'>" + nextText + "</span></a>" :
(hideIfNoPrevNext ? "" : "<a class='ui-datepicker-next ui-corner-all ui-state-disabled' title='"+ nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e") + "'>" + nextText + "</span></a>"));
currentText = this._get(inst, "currentText");
gotoDate = (this._get(inst, "gotoCurrent") && inst.currentDay ? currentDate : today);
currentText = (!navigationAsDateFormat ? currentText :
this.formatDate(currentText, gotoDate, this._getFormatConfig(inst)));
controls = (!inst.inline ? "<button type='button' class='ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all' data-handler='hide' data-event='click'>" +
this._get(inst, "closeText") + "</button>" : "");
buttonPanel = (showButtonPanel) ? "<div class='ui-datepicker-buttonpane ui-widget-content'>" + (isRTL ? controls : "") +
(this._isInRange(inst, gotoDate) ? "<button type='button' class='ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all' data-handler='today' data-event='click'" +
">" + currentText + "</button>" : "") + (isRTL ? "" : controls) + "</div>" : "";
firstDay = parseInt(this._get(inst, "firstDay"),10);
firstDay = (isNaN(firstDay) ? 0 : firstDay);
showWeek = this._get(inst, "showWeek");
dayNames = this._get(inst, "dayNames");
dayNamesMin = this._get(inst, "dayNamesMin");
monthNames = this._get(inst, "monthNames");
monthNamesShort = this._get(inst, "monthNamesShort");
beforeShowDay = this._get(inst, "beforeShowDay");
showOtherMonths = this._get(inst, "showOtherMonths");
selectOtherMonths = this._get(inst, "selectOtherMonths");
defaultDate = this._getDefaultDate(inst);
html = "";
dow;
for (row = 0; row < numMonths[0]; row++) {
group = "";
this.maxRows = 4;
for (col = 0; col < numMonths[1]; col++) {
selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay));
cornerClass = " ui-corner-all";
calender = "";
if (isMultiMonth) {
calender += "<div class='ui-datepicker-group";
if (numMonths[1] > 1) {
switch (col) {
case 0: calender += " ui-datepicker-group-first";
cornerClass = " ui-corner-" + (isRTL ? "right" : "left"); break;
case numMonths[1]-1: calender += " ui-datepicker-group-last";
cornerClass = " ui-corner-" + (isRTL ? "left" : "right"); break;
default: calender += " ui-datepicker-group-middle"; cornerClass = ""; break;
}
}
calender += "'>";
}
calender += "<div class='ui-datepicker-header ui-widget-header ui-helper-clearfix" + cornerClass + "'>" +
(/all|left/.test(cornerClass) && row === 0 ? (isRTL ? next : prev) : "") +
(/all|right/.test(cornerClass) && row === 0 ? (isRTL ? prev : next) : "") +
this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate,
row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers
"</div><table class='ui-datepicker-calendar'><thead>" +
"<tr>";
thead = (showWeek ? "<th class='ui-datepicker-week-col'>" + this._get(inst, "weekHeader") + "</th>" : "");
for (dow = 0; dow < 7; dow++) { // days of the week
day = (dow + firstDay) % 7;
thead += "<th" + ((dow + firstDay + 6) % 7 >= 5 ? " class='ui-datepicker-week-end'" : "") + ">" +
"<span title='" + dayNames[day] + "'>" + dayNamesMin[day] + "</span></th>";
}
calender += thead + "</tr></thead><tbody>";
daysInMonth = this._getDaysInMonth(drawYear, drawMonth);
if (drawYear === inst.selectedYear && drawMonth === inst.selectedMonth) {
inst.selectedDay = Math.min(inst.selectedDay, daysInMonth);
}
leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7;
curRows = Math.ceil((leadDays + daysInMonth) / 7); // calculate the number of rows to generate
numRows = (isMultiMonth ? this.maxRows > curRows ? this.maxRows : curRows : curRows); //If multiple months, use the higher number of rows (see #7043)
this.maxRows = numRows;
printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays));
for (dRow = 0; dRow < numRows; dRow++) { // create date picker rows
calender += "<tr>";
tbody = (!showWeek ? "" : "<td class='ui-datepicker-week-col'>" +
this._get(inst, "calculateWeek")(printDate) + "</td>");
for (dow = 0; dow < 7; dow++) { // create date picker days
daySettings = (beforeShowDay ?
beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, ""]);
otherMonth = (printDate.getMonth() !== drawMonth);
unselectable = (otherMonth && !selectOtherMonths) || !daySettings[0] ||
(minDate && printDate < minDate) || (maxDate && printDate > maxDate);
tbody += "<td class='" +
((dow + firstDay + 6) % 7 >= 5 ? " ui-datepicker-week-end" : "") + // highlight weekends
(otherMonth ? " ui-datepicker-other-month" : "") + // highlight days from other months
((printDate.getTime() === selectedDate.getTime() && drawMonth === inst.selectedMonth && inst._keyEvent) || // user pressed key
(defaultDate.getTime() === printDate.getTime() && defaultDate.getTime() === selectedDate.getTime()) ?
// or defaultDate is current printedDate and defaultDate is selectedDate
" " + this._dayOverClass : "") + // highlight selected day
(unselectable ? " " + this._unselectableClass + " ui-state-disabled": "") + // highlight unselectable days
(otherMonth && !showOtherMonths ? "" : " " + daySettings[1] + // highlight custom dates
(printDate.getTime() === currentDate.getTime() ? " " + this._currentClass : "") + // highlight selected day
(printDate.getTime() === today.getTime() ? " ui-datepicker-today" : "")) + "'" + // highlight today (if different)
((!otherMonth || showOtherMonths) && daySettings[2] ? " title='" + daySettings[2].replace(/'/g, "'") + "'" : "") + // cell title
(unselectable ? "" : " data-handler='selectDay' data-event='click' data-month='" + printDate.getMonth() + "' data-year='" + printDate.getFullYear() + "'") + ">" + // actions
(otherMonth && !showOtherMonths ? " " : // display for other months
(unselectable ? "<span class='ui-state-default'>" + printDate.getDate() + "</span>" : "<a class='ui-state-default" +
(printDate.getTime() === today.getTime() ? " ui-state-highlight" : "") +
(printDate.getTime() === currentDate.getTime() ? " ui-state-active" : "") + // highlight selected day
(otherMonth ? " ui-priority-secondary" : "") + // distinguish dates from other months
"' href='#'>" + printDate.getDate() + "</a>")) + "</td>"; // display selectable date
printDate.setDate(printDate.getDate() + 1);
printDate = this._daylightSavingAdjust(printDate);
}
calender += tbody + "</tr>";
}
drawMonth++;
if (drawMonth > 11) {
drawMonth = 0;
drawYear++;
}
calender += "</tbody></table>" + (isMultiMonth ? "</div>" +
((numMonths[0] > 0 && col === numMonths[1]-1) ? "<div class='ui-datepicker-row-break'></div>" : "") : "");
group += calender;
}
html += group;
}
html += buttonPanel;
inst._keyEvent = false;
return html;
},
/* Generate the month and year header. */
_generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate,
secondary, monthNames, monthNamesShort) {
var inMinYear, inMaxYear, month, years, thisYear, determineYear, year, endYear,
changeMonth = this._get(inst, "changeMonth"),
changeYear = this._get(inst, "changeYear"),
showMonthAfterYear = this._get(inst, "showMonthAfterYear"),
html = "<div class='ui-datepicker-title'>",
monthHtml = "";
// month selection
if (secondary || !changeMonth) {
monthHtml += "<span class='ui-datepicker-month'>" + monthNames[drawMonth] + "</span>";
} else {
inMinYear = (minDate && minDate.getFullYear() === drawYear);
inMaxYear = (maxDate && maxDate.getFullYear() === drawYear);
monthHtml += "<select class='ui-datepicker-month' data-handler='selectMonth' data-event='change'>";
for ( month = 0; month < 12; month++) {
if ((!inMinYear || month >= minDate.getMonth()) && (!inMaxYear || month <= maxDate.getMonth())) {
monthHtml += "<option value='" + month + "'" +
(month === drawMonth ? " selected='selected'" : "") +
">" + monthNamesShort[month] + "</option>";
}
}
monthHtml += "</select>";
}
if (!showMonthAfterYear) {
html += monthHtml + (secondary || !(changeMonth && changeYear) ? " " : "");
}
// year selection
if ( !inst.yearshtml ) {
inst.yearshtml = "";
if (secondary || !changeYear) {
html += "<span class='ui-datepicker-year'>" + drawYear + "</span>";
} else {
// determine range of years to display
years = this._get(inst, "yearRange").split(":");
thisYear = new Date().getFullYear();
determineYear = function(value) {
var year = (value.match(/c[+\-].*/) ? drawYear + parseInt(value.substring(1), 10) :
(value.match(/[+\-].*/) ? thisYear + parseInt(value, 10) :
parseInt(value, 10)));
return (isNaN(year) ? thisYear : year);
};
year = determineYear(years[0]);
endYear = Math.max(year, determineYear(years[1] || ""));
year = (minDate ? Math.max(year, minDate.getFullYear()) : year);
endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear);
inst.yearshtml += "<select class='ui-datepicker-year' data-handler='selectYear' data-event='change'>";
for (; year <= endYear; year++) {
inst.yearshtml += "<option value='" + year + "'" +
(year === drawYear ? " selected='selected'" : "") +
">" + year + "</option>";
}
inst.yearshtml += "</select>";
html += inst.yearshtml;
inst.yearshtml = null;
}
}
html += this._get(inst, "yearSuffix");
if (showMonthAfterYear) {
html += (secondary || !(changeMonth && changeYear) ? " " : "") + monthHtml;
}
html += "</div>"; // Close datepicker_header
return html;
},
/* Adjust one of the date sub-fields. */
_adjustInstDate: function(inst, offset, period) {
var year = inst.drawYear + (period === "Y" ? offset : 0),
month = inst.drawMonth + (period === "M" ? offset : 0),
day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) + (period === "D" ? offset : 0),
date = this._restrictMinMax(inst, this._daylightSavingAdjust(new Date(year, month, day)));
inst.selectedDay = date.getDate();
inst.drawMonth = inst.selectedMonth = date.getMonth();
inst.drawYear = inst.selectedYear = date.getFullYear();
if (period === "M" || period === "Y") {
this._notifyChange(inst);
}
},
/* Ensure a date is within any min/max bounds. */
_restrictMinMax: function(inst, date) {
var minDate = this._getMinMaxDate(inst, "min"),
maxDate = this._getMinMaxDate(inst, "max"),
newDate = (minDate && date < minDate ? minDate : date);
return (maxDate && newDate > maxDate ? maxDate : newDate);
},
/* Notify change of month/year. */
_notifyChange: function(inst) {
var onChange = this._get(inst, "onChangeMonthYear");
if (onChange) {
onChange.apply((inst.input ? inst.input[0] : null),
[inst.selectedYear, inst.selectedMonth + 1, inst]);
}
},
/* Determine the number of months to show. */
_getNumberOfMonths: function(inst) {
var numMonths = this._get(inst, "numberOfMonths");
return (numMonths == null ? [1, 1] : (typeof numMonths === "number" ? [1, numMonths] : numMonths));
},
/* Determine the current maximum date - ensure no time components are set. */
_getMinMaxDate: function(inst, minMax) {
return this._determineDate(inst, this._get(inst, minMax + "Date"), null);
},
/* Find the number of days in a given month. */
_getDaysInMonth: function(year, month) {
return 32 - this._daylightSavingAdjust(new Date(year, month, 32)).getDate();
},
/* Find the day of the week of the first of a month. */
_getFirstDayOfMonth: function(year, month) {
return new Date(year, month, 1).getDay();
},
/* Determines if we should allow a "next/prev" month display change. */
_canAdjustMonth: function(inst, offset, curYear, curMonth) {
var numMonths = this._getNumberOfMonths(inst),
date = this._daylightSavingAdjust(new Date(curYear,
curMonth + (offset < 0 ? offset : numMonths[0] * numMonths[1]), 1));
if (offset < 0) {
date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth()));
}
return this._isInRange(inst, date);
},
/* Is the given date in the accepted range? */
_isInRange: function(inst, date) {
var yearSplit, currentYear,
minDate = this._getMinMaxDate(inst, "min"),
maxDate = this._getMinMaxDate(inst, "max"),
minYear = null,
maxYear = null,
years = this._get(inst, "yearRange");
if (years){
yearSplit = years.split(":");
currentYear = new Date().getFullYear();
minYear = parseInt(yearSplit[0], 10);
maxYear = parseInt(yearSplit[1], 10);
if ( yearSplit[0].match(/[+\-].*/) ) {
minYear += currentYear;
}
if ( yearSplit[1].match(/[+\-].*/) ) {
maxYear += currentYear;
}
}
return ((!minDate || date.getTime() >= minDate.getTime()) &&
(!maxDate || date.getTime() <= maxDate.getTime()) &&
(!minYear || date.getFullYear() >= minYear) &&
(!maxYear || date.getFullYear() <= maxYear));
},
/* Provide the configuration settings for formatting/parsing. */
_getFormatConfig: function(inst) {
var shortYearCutoff = this._get(inst, "shortYearCutoff");
shortYearCutoff = (typeof shortYearCutoff !== "string" ? shortYearCutoff :
new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10));
return {shortYearCutoff: shortYearCutoff,
dayNamesShort: this._get(inst, "dayNamesShort"), dayNames: this._get(inst, "dayNames"),
monthNamesShort: this._get(inst, "monthNamesShort"), monthNames: this._get(inst, "monthNames")};
},
/* Format the given date for display. */
_formatDate: function(inst, day, month, year) {
if (!day) {
inst.currentDay = inst.selectedDay;
inst.currentMonth = inst.selectedMonth;
inst.currentYear = inst.selectedYear;
}
var date = (day ? (typeof day === "object" ? day :
this._daylightSavingAdjust(new Date(year, month, day))) :
this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay)));
return this.formatDate(this._get(inst, "dateFormat"), date, this._getFormatConfig(inst));
}
});
/*
* Bind hover events for datepicker elements.
* Done via delegate so the binding only occurs once in the lifetime of the parent div.
* Global instActive, set by _updateDatepicker allows the handlers to find their way back to the active picker.
*/
function bindHover(dpDiv) {
var selector = "button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";
return dpDiv.delegate(selector, "mouseout", function() {
$(this).removeClass("ui-state-hover");
if (this.className.indexOf("ui-datepicker-prev") !== -1) {
$(this).removeClass("ui-datepicker-prev-hover");
}
if (this.className.indexOf("ui-datepicker-next") !== -1) {
$(this).removeClass("ui-datepicker-next-hover");
}
})
.delegate(selector, "mouseover", function(){
if (!$.datepicker._isDisabledDatepicker( instActive.inline ? dpDiv.parent()[0] : instActive.input[0])) {
$(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover");
$(this).addClass("ui-state-hover");
if (this.className.indexOf("ui-datepicker-prev") !== -1) {
$(this).addClass("ui-datepicker-prev-hover");
}
if (this.className.indexOf("ui-datepicker-next") !== -1) {
$(this).addClass("ui-datepicker-next-hover");
}
}
});
}
/* jQuery extend now ignores nulls! */
function extendRemove(target, props) {
$.extend(target, props);
for (var name in props) {
if (props[name] == null) {
target[name] = props[name];
}
}
return target;
}
/* Invoke the datepicker functionality.
@param options string - a command, optionally followed by additional parameters or
Object - settings for attaching new datepicker functionality
@return jQuery object */
$.fn.datepicker = function(options){
/* Verify an empty collection wasn't passed - Fixes #6976 */
if ( !this.length ) {
return this;
}
/* Initialise the date picker. */
if (!$.datepicker.initialized) {
$(document).mousedown($.datepicker._checkExternalClick);
$.datepicker.initialized = true;
}
/* Append datepicker main container to body if not exist. */
if ($("#"+$.datepicker._mainDivId).length === 0) {
$("body").append($.datepicker.dpDiv);
}
var otherArgs = Array.prototype.slice.call(arguments, 1);
if (typeof options === "string" && (options === "isDisabled" || options === "getDate" || options === "widget")) {
return $.datepicker["_" + options + "Datepicker"].
apply($.datepicker, [this[0]].concat(otherArgs));
}
if (options === "option" && arguments.length === 2 && typeof arguments[1] === "string") {
return $.datepicker["_" + options + "Datepicker"].
apply($.datepicker, [this[0]].concat(otherArgs));
}
return this.each(function() {
typeof options === "string" ?
$.datepicker["_" + options + "Datepicker"].
apply($.datepicker, [this].concat(otherArgs)) :
$.datepicker._attachDatepicker(this, options);
});
};
$.datepicker = new Datepicker(); // singleton instance
$.datepicker.initialized = false;
$.datepicker.uuid = new Date().getTime();
$.datepicker.version = "1.10.3";
})(jQuery);
(function( $, undefined ) {
var sizeRelatedOptions = {
buttons: true,
height: true,
maxHeight: true,
maxWidth: true,
minHeight: true,
minWidth: true,
width: true
},
resizableRelatedOptions = {
maxHeight: true,
maxWidth: true,
minHeight: true,
minWidth: true
};
$.widget( "ui.dialog", {
version: "1.10.3",
options: {
appendTo: "body",
autoOpen: true,
buttons: [],
closeOnEscape: true,
closeText: "close",
dialogClass: "",
draggable: true,
hide: null,
height: "auto",
maxHeight: null,
maxWidth: null,
minHeight: 150,
minWidth: 150,
modal: false,
position: {
my: "center",
at: "center",
of: window,
collision: "fit",
// Ensure the titlebar is always visible
using: function( pos ) {
var topOffset = $( this ).css( pos ).offset().top;
if ( topOffset < 0 ) {
$( this ).css( "top", pos.top - topOffset );
}
}
},
resizable: true,
show: null,
title: null,
width: 300,
// callbacks
beforeClose: null,
close: null,
drag: null,
dragStart: null,
dragStop: null,
focus: null,
open: null,
resize: null,
resizeStart: null,
resizeStop: null
},
_create: function() {
this.originalCss = {
display: this.element[0].style.display,
width: this.element[0].style.width,
minHeight: this.element[0].style.minHeight,
maxHeight: this.element[0].style.maxHeight,
height: this.element[0].style.height
};
this.originalPosition = {
parent: this.element.parent(),
index: this.element.parent().children().index( this.element )
};
this.originalTitle = this.element.attr("title");
this.options.title = this.options.title || this.originalTitle;
this._createWrapper();
this.element
.show()
.removeAttr("title")
.addClass("ui-dialog-content ui-widget-content")
.appendTo( this.uiDialog );
this._createTitlebar();
this._createButtonPane();
if ( this.options.draggable && $.fn.draggable ) {
this._makeDraggable();
}
if ( this.options.resizable && $.fn.resizable ) {
this._makeResizable();
}
this._isOpen = false;
},
_init: function() {
if ( this.options.autoOpen ) {
this.open();
}
},
_appendTo: function() {
var element = this.options.appendTo;
if ( element && (element.jquery || element.nodeType) ) {
return $( element );
}
return this.document.find( element || "body" ).eq( 0 );
},
_destroy: function() {
var next,
originalPosition = this.originalPosition;
this._destroyOverlay();
this.element
.removeUniqueId()
.removeClass("ui-dialog-content ui-widget-content")
.css( this.originalCss )
// Without detaching first, the following becomes really slow
.detach();
this.uiDialog.stop( true, true ).remove();
if ( this.originalTitle ) {
this.element.attr( "title", this.originalTitle );
}
next = originalPosition.parent.children().eq( originalPosition.index );
// Don't try to place the dialog next to itself (#8613)
if ( next.length && next[0] !== this.element[0] ) {
next.before( this.element );
} else {
originalPosition.parent.append( this.element );
}
},
widget: function() {
return this.uiDialog;
},
disable: $.noop,
enable: $.noop,
close: function( event ) {
var that = this;
if ( !this._isOpen || this._trigger( "beforeClose", event ) === false ) {
return;
}
this._isOpen = false;
this._destroyOverlay();
if ( !this.opener.filter(":focusable").focus().length ) {
// Hiding a focused element doesn't trigger blur in WebKit
// so in case we have nothing to focus on, explicitly blur the active element
// https://bugs.webkit.org/show_bug.cgi?id=47182
$( this.document[0].activeElement ).blur();
}
this._hide( this.uiDialog, this.options.hide, function() {
that._trigger( "close", event );
});
},
isOpen: function() {
return this._isOpen;
},
moveToTop: function() {
this._moveToTop();
},
_moveToTop: function( event, silent ) {
var moved = !!this.uiDialog.nextAll(":visible").insertBefore( this.uiDialog ).length;
if ( moved && !silent ) {
this._trigger( "focus", event );
}
return moved;
},
open: function() {
var that = this;
if ( this._isOpen ) {
if ( this._moveToTop() ) {
this._focusTabbable();
}
return;
}
this._isOpen = true;
this.opener = $( this.document[0].activeElement );
this._size();
this._position();
this._createOverlay();
this._moveToTop( null, true );
this._show( this.uiDialog, this.options.show, function() {
that._focusTabbable();
that._trigger("focus");
});
this._trigger("open");
},
_focusTabbable: function() {
// Set focus to the first match:
// 1. First element inside the dialog matching [autofocus]
// 2. Tabbable element inside the content element
// 3. Tabbable element inside the buttonpane
// 4. The close button
// 5. The dialog itself
var hasFocus = this.element.find("[autofocus]");
if ( !hasFocus.length ) {
hasFocus = this.element.find(":tabbable");
}
if ( !hasFocus.length ) {
hasFocus = this.uiDialogButtonPane.find(":tabbable");
}
if ( !hasFocus.length ) {
hasFocus = this.uiDialogTitlebarClose.filter(":tabbable");
}
if ( !hasFocus.length ) {
hasFocus = this.uiDialog;
}
hasFocus.eq( 0 ).focus();
},
_keepFocus: function( event ) {
function checkFocus() {
var activeElement = this.document[0].activeElement,
isActive = this.uiDialog[0] === activeElement ||
$.contains( this.uiDialog[0], activeElement );
if ( !isActive ) {
this._focusTabbable();
}
}
event.preventDefault();
checkFocus.call( this );
// support: IE
// IE <= 8 doesn't prevent moving focus even with event.preventDefault()
// so we check again later
this._delay( checkFocus );
},
_createWrapper: function() {
this.uiDialog = $("<div>")
.addClass( "ui-dialog ui-widget ui-widget-content ui-corner-all ui-front " +
this.options.dialogClass )
.hide()
.attr({
// Setting tabIndex makes the div focusable
tabIndex: -1,
role: "dialog"
})
.appendTo( this._appendTo() );
this._on( this.uiDialog, {
keydown: function( event ) {
if ( this.options.closeOnEscape && !event.isDefaultPrevented() && event.keyCode &&
event.keyCode === $.ui.keyCode.ESCAPE ) {
event.preventDefault();
this.close( event );
return;
}
// prevent tabbing out of dialogs
if ( event.keyCode !== $.ui.keyCode.TAB ) {
return;
}
var tabbables = this.uiDialog.find(":tabbable"),
first = tabbables.filter(":first"),
last = tabbables.filter(":last");
if ( ( event.target === last[0] || event.target === this.uiDialog[0] ) && !event.shiftKey ) {
first.focus( 1 );
event.preventDefault();
} else if ( ( event.target === first[0] || event.target === this.uiDialog[0] ) && event.shiftKey ) {
last.focus( 1 );
event.preventDefault();
}
},
mousedown: function( event ) {
if ( this._moveToTop( event ) ) {
this._focusTabbable();
}
}
});
// We assume that any existing aria-describedby attribute means
// that the dialog content is marked up properly
// otherwise we brute force the content as the description
if ( !this.element.find("[aria-describedby]").length ) {
this.uiDialog.attr({
"aria-describedby": this.element.uniqueId().attr("id")
});
}
},
_createTitlebar: function() {
var uiDialogTitle;
this.uiDialogTitlebar = $("<div>")
.addClass("ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix")
.prependTo( this.uiDialog );
this._on( this.uiDialogTitlebar, {
mousedown: function( event ) {
// Don't prevent click on close button (#8838)
// Focusing a dialog that is partially scrolled out of view
// causes the browser to scroll it into view, preventing the click event
if ( !$( event.target ).closest(".ui-dialog-titlebar-close") ) {
// Dialog isn't getting focus when dragging (#8063)
this.uiDialog.focus();
}
}
});
this.uiDialogTitlebarClose = $("<button></button>")
.button({
label: this.options.closeText,
icons: {
primary: "ui-icon-closethick"
},
text: false
})
.addClass("ui-dialog-titlebar-close")
.appendTo( this.uiDialogTitlebar );
this._on( this.uiDialogTitlebarClose, {
click: function( event ) {
event.preventDefault();
this.close( event );
}
});
uiDialogTitle = $("<span>")
.uniqueId()
.addClass("ui-dialog-title")
.prependTo( this.uiDialogTitlebar );
this._title( uiDialogTitle );
this.uiDialog.attr({
"aria-labelledby": uiDialogTitle.attr("id")
});
},
_title: function( title ) {
if ( !this.options.title ) {
title.html(" ");
}
title.text( this.options.title );
},
_createButtonPane: function() {
this.uiDialogButtonPane = $("<div>")
.addClass("ui-dialog-buttonpane ui-widget-content ui-helper-clearfix");
this.uiButtonSet = $("<div>")
.addClass("ui-dialog-buttonset")
.appendTo( this.uiDialogButtonPane );
this._createButtons();
},
_createButtons: function() {
var that = this,
buttons = this.options.buttons;
// if we already have a button pane, remove it
this.uiDialogButtonPane.remove();
this.uiButtonSet.empty();
if ( $.isEmptyObject( buttons ) || ($.isArray( buttons ) && !buttons.length) ) {
this.uiDialog.removeClass("ui-dialog-buttons");
return;
}
$.each( buttons, function( name, props ) {
var click, buttonOptions;
props = $.isFunction( props ) ?
{ click: props, text: name } :
props;
// Default to a non-submitting button
props = $.extend( { type: "button" }, props );
// Change the context for the click callback to be the main element
click = props.click;
props.click = function() {
click.apply( that.element[0], arguments );
};
buttonOptions = {
icons: props.icons,
text: props.showText
};
delete props.icons;
delete props.showText;
$( "<button></button>", props )
.button( buttonOptions )
.appendTo( that.uiButtonSet );
});
this.uiDialog.addClass("ui-dialog-buttons");
this.uiDialogButtonPane.appendTo( this.uiDialog );
},
_makeDraggable: function() {
var that = this,
options = this.options;
function filteredUi( ui ) {
return {
position: ui.position,
offset: ui.offset
};
}
this.uiDialog.draggable({
cancel: ".ui-dialog-content, .ui-dialog-titlebar-close",
handle: ".ui-dialog-titlebar",
containment: "document",
start: function( event, ui ) {
$( this ).addClass("ui-dialog-dragging");
that._blockFrames();
that._trigger( "dragStart", event, filteredUi( ui ) );
},
drag: function( event, ui ) {
that._trigger( "drag", event, filteredUi( ui ) );
},
stop: function( event, ui ) {
options.position = [
ui.position.left - that.document.scrollLeft(),
ui.position.top - that.document.scrollTop()
];
$( this ).removeClass("ui-dialog-dragging");
that._unblockFrames();
that._trigger( "dragStop", event, filteredUi( ui ) );
}
});
},
_makeResizable: function() {
var that = this,
options = this.options,
handles = options.resizable,
// .ui-resizable has position: relative defined in the stylesheet
// but dialogs have to use absolute or fixed positioning
position = this.uiDialog.css("position"),
resizeHandles = typeof handles === "string" ?
handles :
"n,e,s,w,se,sw,ne,nw";
function filteredUi( ui ) {
return {
originalPosition: ui.originalPosition,
originalSize: ui.originalSize,
position: ui.position,
size: ui.size
};
}
this.uiDialog.resizable({
cancel: ".ui-dialog-content",
containment: "document",
alsoResize: this.element,
maxWidth: options.maxWidth,
maxHeight: options.maxHeight,
minWidth: options.minWidth,
minHeight: this._minHeight(),
handles: resizeHandles,
start: function( event, ui ) {
$( this ).addClass("ui-dialog-resizing");
that._blockFrames();
that._trigger( "resizeStart", event, filteredUi( ui ) );
},
resize: function( event, ui ) {
that._trigger( "resize", event, filteredUi( ui ) );
},
stop: function( event, ui ) {
options.height = $( this ).height();
options.width = $( this ).width();
$( this ).removeClass("ui-dialog-resizing");
that._unblockFrames();
that._trigger( "resizeStop", event, filteredUi( ui ) );
}
})
.css( "position", position );
},
_minHeight: function() {
var options = this.options;
return options.height === "auto" ?
options.minHeight :
Math.min( options.minHeight, options.height );
},
_position: function() {
// Need to show the dialog to get the actual offset in the position plugin
var isVisible = this.uiDialog.is(":visible");
if ( !isVisible ) {
this.uiDialog.show();
}
this.uiDialog.position( this.options.position );
if ( !isVisible ) {
this.uiDialog.hide();
}
},
_setOptions: function( options ) {
var that = this,
resize = false,
resizableOptions = {};
$.each( options, function( key, value ) {
that._setOption( key, value );
if ( key in sizeRelatedOptions ) {
resize = true;
}
if ( key in resizableRelatedOptions ) {
resizableOptions[ key ] = value;
}
});
if ( resize ) {
this._size();
this._position();
}
if ( this.uiDialog.is(":data(ui-resizable)") ) {
this.uiDialog.resizable( "option", resizableOptions );
}
},
_setOption: function( key, value ) {
/*jshint maxcomplexity:15*/
var isDraggable, isResizable,
uiDialog = this.uiDialog;
if ( key === "dialogClass" ) {
uiDialog
.removeClass( this.options.dialogClass )
.addClass( value );
}
if ( key === "disabled" ) {
return;
}
this._super( key, value );
if ( key === "appendTo" ) {
this.uiDialog.appendTo( this._appendTo() );
}
if ( key === "buttons" ) {
this._createButtons();
}
if ( key === "closeText" ) {
this.uiDialogTitlebarClose.button({
// Ensure that we always pass a string
label: "" + value
});
}
if ( key === "draggable" ) {
isDraggable = uiDialog.is(":data(ui-draggable)");
if ( isDraggable && !value ) {
uiDialog.draggable("destroy");
}
if ( !isDraggable && value ) {
this._makeDraggable();
}
}
if ( key === "position" ) {
this._position();
}
if ( key === "resizable" ) {
// currently resizable, becoming non-resizable
isResizable = uiDialog.is(":data(ui-resizable)");
if ( isResizable && !value ) {
uiDialog.resizable("destroy");
}
// currently resizable, changing handles
if ( isResizable && typeof value === "string" ) {
uiDialog.resizable( "option", "handles", value );
}
// currently non-resizable, becoming resizable
if ( !isResizable && value !== false ) {
this._makeResizable();
}
}
if ( key === "title" ) {
this._title( this.uiDialogTitlebar.find(".ui-dialog-title") );
}
},
_size: function() {
// If the user has resized the dialog, the .ui-dialog and .ui-dialog-content
// divs will both have width and height set, so we need to reset them
var nonContentHeight, minContentHeight, maxContentHeight,
options = this.options;
// Reset content sizing
this.element.show().css({
width: "auto",
minHeight: 0,
maxHeight: "none",
height: 0
});
if ( options.minWidth > options.width ) {
options.width = options.minWidth;
}
// reset wrapper sizing
// determine the height of all the non-content elements
nonContentHeight = this.uiDialog.css({
height: "auto",
width: options.width
})
.outerHeight();
minContentHeight = Math.max( 0, options.minHeight - nonContentHeight );
maxContentHeight = typeof options.maxHeight === "number" ?
Math.max( 0, options.maxHeight - nonContentHeight ) :
"none";
if ( options.height === "auto" ) {
this.element.css({
minHeight: minContentHeight,
maxHeight: maxContentHeight,
height: "auto"
});
} else {
this.element.height( Math.max( 0, options.height - nonContentHeight ) );
}
if (this.uiDialog.is(":data(ui-resizable)") ) {
this.uiDialog.resizable( "option", "minHeight", this._minHeight() );
}
},
_blockFrames: function() {
this.iframeBlocks = this.document.find( "iframe" ).map(function() {
var iframe = $( this );
return $( "<div>" )
.css({
position: "absolute",
width: iframe.outerWidth(),
height: iframe.outerHeight()
})
.appendTo( iframe.parent() )
.offset( iframe.offset() )[0];
});
},
_unblockFrames: function() {
if ( this.iframeBlocks ) {
this.iframeBlocks.remove();
delete this.iframeBlocks;
}
},
_allowInteraction: function( event ) {
if ( $( event.target ).closest(".ui-dialog").length ) {
return true;
}
// TODO: Remove hack when datepicker implements
// the .ui-front logic (#8989)
return !!$( event.target ).closest(".ui-datepicker").length;
},
_createOverlay: function() {
if ( !this.options.modal ) {
return;
}
var that = this,
widgetFullName = this.widgetFullName;
if ( !$.ui.dialog.overlayInstances ) {
// Prevent use of anchors and inputs.
// We use a delay in case the overlay is created from an
// event that we're going to be cancelling. (#2804)
this._delay(function() {
// Handle .dialog().dialog("close") (#4065)
if ( $.ui.dialog.overlayInstances ) {
this.document.bind( "focusin.dialog", function( event ) {
if ( !that._allowInteraction( event ) ) {
event.preventDefault();
$(".ui-dialog:visible:last .ui-dialog-content")
.data( widgetFullName )._focusTabbable();
}
});
}
});
}
this.overlay = $("<div>")
.addClass("ui-widget-overlay ui-front")
.appendTo( this._appendTo() );
this._on( this.overlay, {
mousedown: "_keepFocus"
});
$.ui.dialog.overlayInstances++;
},
_destroyOverlay: function() {
if ( !this.options.modal ) {
return;
}
if ( this.overlay ) {
$.ui.dialog.overlayInstances--;
if ( !$.ui.dialog.overlayInstances ) {
this.document.unbind( "focusin.dialog" );
}
this.overlay.remove();
this.overlay = null;
}
}
});
$.ui.dialog.overlayInstances = 0;
// DEPRECATED
if ( $.uiBackCompat !== false ) {
// position option with array notation
// just override with old implementation
$.widget( "ui.dialog", $.ui.dialog, {
_position: function() {
var position = this.options.position,
myAt = [],
offset = [ 0, 0 ],
isVisible;
if ( position ) {
if ( typeof position === "string" || (typeof position === "object" && "0" in position ) ) {
myAt = position.split ? position.split(" ") : [ position[0], position[1] ];
if ( myAt.length === 1 ) {
myAt[1] = myAt[0];
}
$.each( [ "left", "top" ], function( i, offsetPosition ) {
if ( +myAt[ i ] === myAt[ i ] ) {
offset[ i ] = myAt[ i ];
myAt[ i ] = offsetPosition;
}
});
position = {
my: myAt[0] + (offset[0] < 0 ? offset[0] : "+" + offset[0]) + " " +
myAt[1] + (offset[1] < 0 ? offset[1] : "+" + offset[1]),
at: myAt.join(" ")
};
}
position = $.extend( {}, $.ui.dialog.prototype.options.position, position );
} else {
position = $.ui.dialog.prototype.options.position;
}
// need to show the dialog to get the actual offset in the position plugin
isVisible = this.uiDialog.is(":visible");
if ( !isVisible ) {
this.uiDialog.show();
}
this.uiDialog.position( position );
if ( !isVisible ) {
this.uiDialog.hide();
}
}
});
}
}( jQuery ) );
(function( $, undefined ) {
var rvertical = /up|down|vertical/,
rpositivemotion = /up|left|vertical|horizontal/;
$.effects.effect.blind = function( o, done ) {
// Create element
var el = $( this ),
props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
mode = $.effects.setMode( el, o.mode || "hide" ),
direction = o.direction || "up",
vertical = rvertical.test( direction ),
ref = vertical ? "height" : "width",
ref2 = vertical ? "top" : "left",
motion = rpositivemotion.test( direction ),
animation = {},
show = mode === "show",
wrapper, distance, margin;
// if already wrapped, the wrapper's properties are my property. #6245
if ( el.parent().is( ".ui-effects-wrapper" ) ) {
$.effects.save( el.parent(), props );
} else {
$.effects.save( el, props );
}
el.show();
wrapper = $.effects.createWrapper( el ).css({
overflow: "hidden"
});
distance = wrapper[ ref ]();
margin = parseFloat( wrapper.css( ref2 ) ) || 0;
animation[ ref ] = show ? distance : 0;
if ( !motion ) {
el
.css( vertical ? "bottom" : "right", 0 )
.css( vertical ? "top" : "left", "auto" )
.css({ position: "absolute" });
animation[ ref2 ] = show ? margin : distance + margin;
}
// start at 0 if we are showing
if ( show ) {
wrapper.css( ref, 0 );
if ( ! motion ) {
wrapper.css( ref2, margin + distance );
}
}
// Animate
wrapper.animate( animation, {
duration: o.duration,
easing: o.easing,
queue: false,
complete: function() {
if ( mode === "hide" ) {
el.hide();
}
$.effects.restore( el, props );
$.effects.removeWrapper( el );
done();
}
});
};
})(jQuery);
(function( $, undefined ) {
$.effects.effect.bounce = function( o, done ) {
var el = $( this ),
props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
// defaults:
mode = $.effects.setMode( el, o.mode || "effect" ),
hide = mode === "hide",
show = mode === "show",
direction = o.direction || "up",
distance = o.distance,
times = o.times || 5,
// number of internal animations
anims = times * 2 + ( show || hide ? 1 : 0 ),
speed = o.duration / anims,
easing = o.easing,
// utility:
ref = ( direction === "up" || direction === "down" ) ? "top" : "left",
motion = ( direction === "up" || direction === "left" ),
i,
upAnim,
downAnim,
// we will need to re-assemble the queue to stack our animations in place
queue = el.queue(),
queuelen = queue.length;
// Avoid touching opacity to prevent clearType and PNG issues in IE
if ( show || hide ) {
props.push( "opacity" );
}
$.effects.save( el, props );
el.show();
$.effects.createWrapper( el ); // Create Wrapper
// default distance for the BIGGEST bounce is the outer Distance / 3
if ( !distance ) {
distance = el[ ref === "top" ? "outerHeight" : "outerWidth" ]() / 3;
}
if ( show ) {
downAnim = { opacity: 1 };
downAnim[ ref ] = 0;
// if we are showing, force opacity 0 and set the initial position
// then do the "first" animation
el.css( "opacity", 0 )
.css( ref, motion ? -distance * 2 : distance * 2 )
.animate( downAnim, speed, easing );
}
// start at the smallest distance if we are hiding
if ( hide ) {
distance = distance / Math.pow( 2, times - 1 );
}
downAnim = {};
downAnim[ ref ] = 0;
// Bounces up/down/left/right then back to 0 -- times * 2 animations happen here
for ( i = 0; i < times; i++ ) {
upAnim = {};
upAnim[ ref ] = ( motion ? "-=" : "+=" ) + distance;
el.animate( upAnim, speed, easing )
.animate( downAnim, speed, easing );
distance = hide ? distance * 2 : distance / 2;
}
// Last Bounce when Hiding
if ( hide ) {
upAnim = { opacity: 0 };
upAnim[ ref ] = ( motion ? "-=" : "+=" ) + distance;
el.animate( upAnim, speed, easing );
}
el.queue(function() {
if ( hide ) {
el.hide();
}
$.effects.restore( el, props );
$.effects.removeWrapper( el );
done();
});
// inject all the animations we just queued to be first in line (after "inprogress")
if ( queuelen > 1) {
queue.splice.apply( queue,
[ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) );
}
el.dequeue();
};
})(jQuery);
(function( $, undefined ) {
$.effects.effect.clip = function( o, done ) {
// Create element
var el = $( this ),
props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
mode = $.effects.setMode( el, o.mode || "hide" ),
show = mode === "show",
direction = o.direction || "vertical",
vert = direction === "vertical",
size = vert ? "height" : "width",
position = vert ? "top" : "left",
animation = {},
wrapper, animate, distance;
// Save & Show
$.effects.save( el, props );
el.show();
// Create Wrapper
wrapper = $.effects.createWrapper( el ).css({
overflow: "hidden"
});
animate = ( el[0].tagName === "IMG" ) ? wrapper : el;
distance = animate[ size ]();
// Shift
if ( show ) {
animate.css( size, 0 );
animate.css( position, distance / 2 );
}
// Create Animation Object:
animation[ size ] = show ? distance : 0;
animation[ position ] = show ? 0 : distance / 2;
// Animate
animate.animate( animation, {
queue: false,
duration: o.duration,
easing: o.easing,
complete: function() {
if ( !show ) {
el.hide();
}
$.effects.restore( el, props );
$.effects.removeWrapper( el );
done();
}
});
};
})(jQuery);
(function( $, undefined ) {
$.effects.effect.drop = function( o, done ) {
var el = $( this ),
props = [ "position", "top", "bottom", "left", "right", "opacity", "height", "width" ],
mode = $.effects.setMode( el, o.mode || "hide" ),
show = mode === "show",
direction = o.direction || "left",
ref = ( direction === "up" || direction === "down" ) ? "top" : "left",
motion = ( direction === "up" || direction === "left" ) ? "pos" : "neg",
animation = {
opacity: show ? 1 : 0
},
distance;
// Adjust
$.effects.save( el, props );
el.show();
$.effects.createWrapper( el );
distance = o.distance || el[ ref === "top" ? "outerHeight": "outerWidth" ]( true ) / 2;
if ( show ) {
el
.css( "opacity", 0 )
.css( ref, motion === "pos" ? -distance : distance );
}
// Animation
animation[ ref ] = ( show ?
( motion === "pos" ? "+=" : "-=" ) :
( motion === "pos" ? "-=" : "+=" ) ) +
distance;
// Animate
el.animate( animation, {
queue: false,
duration: o.duration,
easing: o.easing,
complete: function() {
if ( mode === "hide" ) {
el.hide();
}
$.effects.restore( el, props );
$.effects.removeWrapper( el );
done();
}
});
};
})(jQuery);
(function( $, undefined ) {
$.effects.effect.explode = function( o, done ) {
var rows = o.pieces ? Math.round( Math.sqrt( o.pieces ) ) : 3,
cells = rows,
el = $( this ),
mode = $.effects.setMode( el, o.mode || "hide" ),
show = mode === "show",
// show and then visibility:hidden the element before calculating offset
offset = el.show().css( "visibility", "hidden" ).offset(),
// width and height of a piece
width = Math.ceil( el.outerWidth() / cells ),
height = Math.ceil( el.outerHeight() / rows ),
pieces = [],
// loop
i, j, left, top, mx, my;
// children animate complete:
function childComplete() {
pieces.push( this );
if ( pieces.length === rows * cells ) {
animComplete();
}
}
// clone the element for each row and cell.
for( i = 0; i < rows ; i++ ) { // ===>
top = offset.top + i * height;
my = i - ( rows - 1 ) / 2 ;
for( j = 0; j < cells ; j++ ) { // |||
left = offset.left + j * width;
mx = j - ( cells - 1 ) / 2 ;
// Create a clone of the now hidden main element that will be absolute positioned
// within a wrapper div off the -left and -top equal to size of our pieces
el
.clone()
.appendTo( "body" )
.wrap( "<div></div>" )
.css({
position: "absolute",
visibility: "visible",
left: -j * width,
top: -i * height
})
// select the wrapper - make it overflow: hidden and absolute positioned based on
// where the original was located +left and +top equal to the size of pieces
.parent()
.addClass( "ui-effects-explode" )
.css({
position: "absolute",
overflow: "hidden",
width: width,
height: height,
left: left + ( show ? mx * width : 0 ),
top: top + ( show ? my * height : 0 ),
opacity: show ? 0 : 1
}).animate({
left: left + ( show ? 0 : mx * width ),
top: top + ( show ? 0 : my * height ),
opacity: show ? 1 : 0
}, o.duration || 500, o.easing, childComplete );
}
}
function animComplete() {
el.css({
visibility: "visible"
});
$( pieces ).remove();
if ( !show ) {
el.hide();
}
done();
}
};
})(jQuery);
(function( $, undefined ) {
$.effects.effect.fade = function( o, done ) {
var el = $( this ),
mode = $.effects.setMode( el, o.mode || "toggle" );
el.animate({
opacity: mode
}, {
queue: false,
duration: o.duration,
easing: o.easing,
complete: done
});
};
})( jQuery );
(function( $, undefined ) {
$.effects.effect.fold = function( o, done ) {
// Create element
var el = $( this ),
props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
mode = $.effects.setMode( el, o.mode || "hide" ),
show = mode === "show",
hide = mode === "hide",
size = o.size || 15,
percent = /([0-9]+)%/.exec( size ),
horizFirst = !!o.horizFirst,
widthFirst = show !== horizFirst,
ref = widthFirst ? [ "width", "height" ] : [ "height", "width" ],
duration = o.duration / 2,
wrapper, distance,
animation1 = {},
animation2 = {};
$.effects.save( el, props );
el.show();
// Create Wrapper
wrapper = $.effects.createWrapper( el ).css({
overflow: "hidden"
});
distance = widthFirst ?
[ wrapper.width(), wrapper.height() ] :
[ wrapper.height(), wrapper.width() ];
if ( percent ) {
size = parseInt( percent[ 1 ], 10 ) / 100 * distance[ hide ? 0 : 1 ];
}
if ( show ) {
wrapper.css( horizFirst ? {
height: 0,
width: size
} : {
height: size,
width: 0
});
}
// Animation
animation1[ ref[ 0 ] ] = show ? distance[ 0 ] : size;
animation2[ ref[ 1 ] ] = show ? distance[ 1 ] : 0;
// Animate
wrapper
.animate( animation1, duration, o.easing )
.animate( animation2, duration, o.easing, function() {
if ( hide ) {
el.hide();
}
$.effects.restore( el, props );
$.effects.removeWrapper( el );
done();
});
};
})(jQuery);
(function( $, undefined ) {
$.effects.effect.highlight = function( o, done ) {
var elem = $( this ),
props = [ "backgroundImage", "backgroundColor", "opacity" ],
mode = $.effects.setMode( elem, o.mode || "show" ),
animation = {
backgroundColor: elem.css( "backgroundColor" )
};
if (mode === "hide") {
animation.opacity = 0;
}
$.effects.save( elem, props );
elem
.show()
.css({
backgroundImage: "none",
backgroundColor: o.color || "#ffff99"
})
.animate( animation, {
queue: false,
duration: o.duration,
easing: o.easing,
complete: function() {
if ( mode === "hide" ) {
elem.hide();
}
$.effects.restore( elem, props );
done();
}
});
};
})(jQuery);
(function( $, undefined ) {
$.effects.effect.pulsate = function( o, done ) {
var elem = $( this ),
mode = $.effects.setMode( elem, o.mode || "show" ),
show = mode === "show",
hide = mode === "hide",
showhide = ( show || mode === "hide" ),
// showing or hiding leaves of the "last" animation
anims = ( ( o.times || 5 ) * 2 ) + ( showhide ? 1 : 0 ),
duration = o.duration / anims,
animateTo = 0,
queue = elem.queue(),
queuelen = queue.length,
i;
if ( show || !elem.is(":visible")) {
elem.css( "opacity", 0 ).show();
animateTo = 1;
}
// anims - 1 opacity "toggles"
for ( i = 1; i < anims; i++ ) {
elem.animate({
opacity: animateTo
}, duration, o.easing );
animateTo = 1 - animateTo;
}
elem.animate({
opacity: animateTo
}, duration, o.easing);
elem.queue(function() {
if ( hide ) {
elem.hide();
}
done();
});
// We just queued up "anims" animations, we need to put them next in the queue
if ( queuelen > 1 ) {
queue.splice.apply( queue,
[ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) );
}
elem.dequeue();
};
})(jQuery);
(function( $, undefined ) {
$.effects.effect.puff = function( o, done ) {
var elem = $( this ),
mode = $.effects.setMode( elem, o.mode || "hide" ),
hide = mode === "hide",
percent = parseInt( o.percent, 10 ) || 150,
factor = percent / 100,
original = {
height: elem.height(),
width: elem.width(),
outerHeight: elem.outerHeight(),
outerWidth: elem.outerWidth()
};
$.extend( o, {
effect: "scale",
queue: false,
fade: true,
mode: mode,
complete: done,
percent: hide ? percent : 100,
from: hide ?
original :
{
height: original.height * factor,
width: original.width * factor,
outerHeight: original.outerHeight * factor,
outerWidth: original.outerWidth * factor
}
});
elem.effect( o );
};
$.effects.effect.scale = function( o, done ) {
// Create element
var el = $( this ),
options = $.extend( true, {}, o ),
mode = $.effects.setMode( el, o.mode || "effect" ),
percent = parseInt( o.percent, 10 ) ||
( parseInt( o.percent, 10 ) === 0 ? 0 : ( mode === "hide" ? 0 : 100 ) ),
direction = o.direction || "both",
origin = o.origin,
original = {
height: el.height(),
width: el.width(),
outerHeight: el.outerHeight(),
outerWidth: el.outerWidth()
},
factor = {
y: direction !== "horizontal" ? (percent / 100) : 1,
x: direction !== "vertical" ? (percent / 100) : 1
};
// We are going to pass this effect to the size effect:
options.effect = "size";
options.queue = false;
options.complete = done;
// Set default origin and restore for show/hide
if ( mode !== "effect" ) {
options.origin = origin || ["middle","center"];
options.restore = true;
}
options.from = o.from || ( mode === "show" ? {
height: 0,
width: 0,
outerHeight: 0,
outerWidth: 0
} : original );
options.to = {
height: original.height * factor.y,
width: original.width * factor.x,
outerHeight: original.outerHeight * factor.y,
outerWidth: original.outerWidth * factor.x
};
// Fade option to support puff
if ( options.fade ) {
if ( mode === "show" ) {
options.from.opacity = 0;
options.to.opacity = 1;
}
if ( mode === "hide" ) {
options.from.opacity = 1;
options.to.opacity = 0;
}
}
// Animate
el.effect( options );
};
$.effects.effect.size = function( o, done ) {
// Create element
var original, baseline, factor,
el = $( this ),
props0 = [ "position", "top", "bottom", "left", "right", "width", "height", "overflow", "opacity" ],
// Always restore
props1 = [ "position", "top", "bottom", "left", "right", "overflow", "opacity" ],
// Copy for children
props2 = [ "width", "height", "overflow" ],
cProps = [ "fontSize" ],
vProps = [ "borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom" ],
hProps = [ "borderLeftWidth", "borderRightWidth", "paddingLeft", "paddingRight" ],
// Set options
mode = $.effects.setMode( el, o.mode || "effect" ),
restore = o.restore || mode !== "effect",
scale = o.scale || "both",
origin = o.origin || [ "middle", "center" ],
position = el.css( "position" ),
props = restore ? props0 : props1,
zero = {
height: 0,
width: 0,
outerHeight: 0,
outerWidth: 0
};
if ( mode === "show" ) {
el.show();
}
original = {
height: el.height(),
width: el.width(),
outerHeight: el.outerHeight(),
outerWidth: el.outerWidth()
};
if ( o.mode === "toggle" && mode === "show" ) {
el.from = o.to || zero;
el.to = o.from || original;
} else {
el.from = o.from || ( mode === "show" ? zero : original );
el.to = o.to || ( mode === "hide" ? zero : original );
}
// Set scaling factor
factor = {
from: {
y: el.from.height / original.height,
x: el.from.width / original.width
},
to: {
y: el.to.height / original.height,
x: el.to.width / original.width
}
};
// Scale the css box
if ( scale === "box" || scale === "both" ) {
// Vertical props scaling
if ( factor.from.y !== factor.to.y ) {
props = props.concat( vProps );
el.from = $.effects.setTransition( el, vProps, factor.from.y, el.from );
el.to = $.effects.setTransition( el, vProps, factor.to.y, el.to );
}
// Horizontal props scaling
if ( factor.from.x !== factor.to.x ) {
props = props.concat( hProps );
el.from = $.effects.setTransition( el, hProps, factor.from.x, el.from );
el.to = $.effects.setTransition( el, hProps, factor.to.x, el.to );
}
}
// Scale the content
if ( scale === "content" || scale === "both" ) {
// Vertical props scaling
if ( factor.from.y !== factor.to.y ) {
props = props.concat( cProps ).concat( props2 );
el.from = $.effects.setTransition( el, cProps, factor.from.y, el.from );
el.to = $.effects.setTransition( el, cProps, factor.to.y, el.to );
}
}
$.effects.save( el, props );
el.show();
$.effects.createWrapper( el );
el.css( "overflow", "hidden" ).css( el.from );
// Adjust
if (origin) { // Calculate baseline shifts
baseline = $.effects.getBaseline( origin, original );
el.from.top = ( original.outerHeight - el.outerHeight() ) * baseline.y;
el.from.left = ( original.outerWidth - el.outerWidth() ) * baseline.x;
el.to.top = ( original.outerHeight - el.to.outerHeight ) * baseline.y;
el.to.left = ( original.outerWidth - el.to.outerWidth ) * baseline.x;
}
el.css( el.from ); // set top & left
// Animate
if ( scale === "content" || scale === "both" ) { // Scale the children
// Add margins/font-size
vProps = vProps.concat([ "marginTop", "marginBottom" ]).concat(cProps);
hProps = hProps.concat([ "marginLeft", "marginRight" ]);
props2 = props0.concat(vProps).concat(hProps);
el.find( "*[width]" ).each( function(){
var child = $( this ),
c_original = {
height: child.height(),
width: child.width(),
outerHeight: child.outerHeight(),
outerWidth: child.outerWidth()
};
if (restore) {
$.effects.save(child, props2);
}
child.from = {
height: c_original.height * factor.from.y,
width: c_original.width * factor.from.x,
outerHeight: c_original.outerHeight * factor.from.y,
outerWidth: c_original.outerWidth * factor.from.x
};
child.to = {
height: c_original.height * factor.to.y,
width: c_original.width * factor.to.x,
outerHeight: c_original.height * factor.to.y,
outerWidth: c_original.width * factor.to.x
};
// Vertical props scaling
if ( factor.from.y !== factor.to.y ) {
child.from = $.effects.setTransition( child, vProps, factor.from.y, child.from );
child.to = $.effects.setTransition( child, vProps, factor.to.y, child.to );
}
// Horizontal props scaling
if ( factor.from.x !== factor.to.x ) {
child.from = $.effects.setTransition( child, hProps, factor.from.x, child.from );
child.to = $.effects.setTransition( child, hProps, factor.to.x, child.to );
}
// Animate children
child.css( child.from );
child.animate( child.to, o.duration, o.easing, function() {
// Restore children
if ( restore ) {
$.effects.restore( child, props2 );
}
});
});
}
// Animate
el.animate( el.to, {
queue: false,
duration: o.duration,
easing: o.easing,
complete: function() {
if ( el.to.opacity === 0 ) {
el.css( "opacity", el.from.opacity );
}
if( mode === "hide" ) {
el.hide();
}
$.effects.restore( el, props );
if ( !restore ) {
// we need to calculate our new positioning based on the scaling
if ( position === "static" ) {
el.css({
position: "relative",
top: el.to.top,
left: el.to.left
});
} else {
$.each([ "top", "left" ], function( idx, pos ) {
el.css( pos, function( _, str ) {
var val = parseInt( str, 10 ),
toRef = idx ? el.to.left : el.to.top;
// if original was "auto", recalculate the new value from wrapper
if ( str === "auto" ) {
return toRef + "px";
}
return val + toRef + "px";
});
});
}
}
$.effects.removeWrapper( el );
done();
}
});
};
})(jQuery);
(function( $, undefined ) {
$.effects.effect.shake = function( o, done ) {
var el = $( this ),
props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
mode = $.effects.setMode( el, o.mode || "effect" ),
direction = o.direction || "left",
distance = o.distance || 20,
times = o.times || 3,
anims = times * 2 + 1,
speed = Math.round(o.duration/anims),
ref = (direction === "up" || direction === "down") ? "top" : "left",
positiveMotion = (direction === "up" || direction === "left"),
animation = {},
animation1 = {},
animation2 = {},
i,
// we will need to re-assemble the queue to stack our animations in place
queue = el.queue(),
queuelen = queue.length;
$.effects.save( el, props );
el.show();
$.effects.createWrapper( el );
// Animation
animation[ ref ] = ( positiveMotion ? "-=" : "+=" ) + distance;
animation1[ ref ] = ( positiveMotion ? "+=" : "-=" ) + distance * 2;
animation2[ ref ] = ( positiveMotion ? "-=" : "+=" ) + distance * 2;
// Animate
el.animate( animation, speed, o.easing );
// Shakes
for ( i = 1; i < times; i++ ) {
el.animate( animation1, speed, o.easing ).animate( animation2, speed, o.easing );
}
el
.animate( animation1, speed, o.easing )
.animate( animation, speed / 2, o.easing )
.queue(function() {
if ( mode === "hide" ) {
el.hide();
}
$.effects.restore( el, props );
$.effects.removeWrapper( el );
done();
});
// inject all the animations we just queued to be first in line (after "inprogress")
if ( queuelen > 1) {
queue.splice.apply( queue,
[ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) );
}
el.dequeue();
};
})(jQuery);
(function( $, undefined ) {
$.effects.effect.slide = function( o, done ) {
// Create element
var el = $( this ),
props = [ "position", "top", "bottom", "left", "right", "width", "height" ],
mode = $.effects.setMode( el, o.mode || "show" ),
show = mode === "show",
direction = o.direction || "left",
ref = (direction === "up" || direction === "down") ? "top" : "left",
positiveMotion = (direction === "up" || direction === "left"),
distance,
animation = {};
// Adjust
$.effects.save( el, props );
el.show();
distance = o.distance || el[ ref === "top" ? "outerHeight" : "outerWidth" ]( true );
$.effects.createWrapper( el ).css({
overflow: "hidden"
});
if ( show ) {
el.css( ref, positiveMotion ? (isNaN(distance) ? "-" + distance : -distance) : distance );
}
// Animation
animation[ ref ] = ( show ?
( positiveMotion ? "+=" : "-=") :
( positiveMotion ? "-=" : "+=")) +
distance;
// Animate
el.animate( animation, {
queue: false,
duration: o.duration,
easing: o.easing,
complete: function() {
if ( mode === "hide" ) {
el.hide();
}
$.effects.restore( el, props );
$.effects.removeWrapper( el );
done();
}
});
};
})(jQuery);
(function( $, undefined ) {
$.effects.effect.transfer = function( o, done ) {
var elem = $( this ),
target = $( o.to ),
targetFixed = target.css( "position" ) === "fixed",
body = $("body"),
fixTop = targetFixed ? body.scrollTop() : 0,
fixLeft = targetFixed ? body.scrollLeft() : 0,
endPosition = target.offset(),
animation = {
top: endPosition.top - fixTop ,
left: endPosition.left - fixLeft ,
height: target.innerHeight(),
width: target.innerWidth()
},
startPosition = elem.offset(),
transfer = $( "<div class='ui-effects-transfer'></div>" )
.appendTo( document.body )
.addClass( o.className )
.css({
top: startPosition.top - fixTop ,
left: startPosition.left - fixLeft ,
height: elem.innerHeight(),
width: elem.innerWidth(),
position: targetFixed ? "fixed" : "absolute"
})
.animate( animation, o.duration, o.easing, function() {
transfer.remove();
done();
});
};
})(jQuery);
(function( $, undefined ) {
$.widget( "ui.menu", {
version: "1.10.3",
defaultElement: "<ul>",
delay: 300,
options: {
icons: {
submenu: "ui-icon-carat-1-e"
},
menus: "ul",
position: {
my: "left top",
at: "right top"
},
role: "menu",
// callbacks
blur: null,
focus: null,
select: null
},
_create: function() {
this.activeMenu = this.element;
// flag used to prevent firing of the click handler
// as the event bubbles up through nested menus
this.mouseHandled = false;
this.element
.uniqueId()
.addClass( "ui-menu ui-widget ui-widget-content ui-corner-all" )
.toggleClass( "ui-menu-icons", !!this.element.find( ".ui-icon" ).length )
.attr({
role: this.options.role,
tabIndex: 0
})
// need to catch all clicks on disabled menu
// not possible through _on
.bind( "click" + this.eventNamespace, $.proxy(function( event ) {
if ( this.options.disabled ) {
event.preventDefault();
}
}, this ));
if ( this.options.disabled ) {
this.element
.addClass( "ui-state-disabled" )
.attr( "aria-disabled", "true" );
}
this._on({
// Prevent focus from sticking to links inside menu after clicking
// them (focus should always stay on UL during navigation).
"mousedown .ui-menu-item > a": function( event ) {
event.preventDefault();
},
"click .ui-state-disabled > a": function( event ) {
event.preventDefault();
},
"click .ui-menu-item:has(a)": function( event ) {
var target = $( event.target ).closest( ".ui-menu-item" );
if ( !this.mouseHandled && target.not( ".ui-state-disabled" ).length ) {
this.mouseHandled = true;
this.select( event );
// Open submenu on click
if ( target.has( ".ui-menu" ).length ) {
this.expand( event );
} else if ( !this.element.is( ":focus" ) ) {
// Redirect focus to the menu
this.element.trigger( "focus", [ true ] );
// If the active item is on the top level, let it stay active.
// Otherwise, blur the active item since it is no longer visible.
if ( this.active && this.active.parents( ".ui-menu" ).length === 1 ) {
clearTimeout( this.timer );
}
}
}
},
"mouseenter .ui-menu-item": function( event ) {
var target = $( event.currentTarget );
// Remove ui-state-active class from siblings of the newly focused menu item
// to avoid a jump caused by adjacent elements both having a class with a border
target.siblings().children( ".ui-state-active" ).removeClass( "ui-state-active" );
this.focus( event, target );
},
mouseleave: "collapseAll",
"mouseleave .ui-menu": "collapseAll",
focus: function( event, keepActiveItem ) {
// If there's already an active item, keep it active
// If not, activate the first item
var item = this.active || this.element.children( ".ui-menu-item" ).eq( 0 );
if ( !keepActiveItem ) {
this.focus( event, item );
}
},
blur: function( event ) {
this._delay(function() {
if ( !$.contains( this.element[0], this.document[0].activeElement ) ) {
this.collapseAll( event );
}
});
},
keydown: "_keydown"
});
this.refresh();
// Clicks outside of a menu collapse any open menus
this._on( this.document, {
click: function( event ) {
if ( !$( event.target ).closest( ".ui-menu" ).length ) {
this.collapseAll( event );
}
// Reset the mouseHandled flag
this.mouseHandled = false;
}
});
},
_destroy: function() {
// Destroy (sub)menus
this.element
.removeAttr( "aria-activedescendant" )
.find( ".ui-menu" ).addBack()
.removeClass( "ui-menu ui-widget ui-widget-content ui-corner-all ui-menu-icons" )
.removeAttr( "role" )
.removeAttr( "tabIndex" )
.removeAttr( "aria-labelledby" )
.removeAttr( "aria-expanded" )
.removeAttr( "aria-hidden" )
.removeAttr( "aria-disabled" )
.removeUniqueId()
.show();
// Destroy menu items
this.element.find( ".ui-menu-item" )
.removeClass( "ui-menu-item" )
.removeAttr( "role" )
.removeAttr( "aria-disabled" )
.children( "a" )
.removeUniqueId()
.removeClass( "ui-corner-all ui-state-hover" )
.removeAttr( "tabIndex" )
.removeAttr( "role" )
.removeAttr( "aria-haspopup" )
.children().each( function() {
var elem = $( this );
if ( elem.data( "ui-menu-submenu-carat" ) ) {
elem.remove();
}
});
// Destroy menu dividers
this.element.find( ".ui-menu-divider" ).removeClass( "ui-menu-divider ui-widget-content" );
},
_keydown: function( event ) {
/*jshint maxcomplexity:20*/
var match, prev, character, skip, regex,
preventDefault = true;
function escape( value ) {
return value.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" );
}
switch ( event.keyCode ) {
case $.ui.keyCode.PAGE_UP:
this.previousPage( event );
break;
case $.ui.keyCode.PAGE_DOWN:
this.nextPage( event );
break;
case $.ui.keyCode.HOME:
this._move( "first", "first", event );
break;
case $.ui.keyCode.END:
this._move( "last", "last", event );
break;
case $.ui.keyCode.UP:
this.previous( event );
break;
case $.ui.keyCode.DOWN:
this.next( event );
break;
case $.ui.keyCode.LEFT:
this.collapse( event );
break;
case $.ui.keyCode.RIGHT:
if ( this.active && !this.active.is( ".ui-state-disabled" ) ) {
this.expand( event );
}
break;
case $.ui.keyCode.ENTER:
case $.ui.keyCode.SPACE:
this._activate( event );
break;
case $.ui.keyCode.ESCAPE:
this.collapse( event );
break;
default:
preventDefault = false;
prev = this.previousFilter || "";
character = String.fromCharCode( event.keyCode );
skip = false;
clearTimeout( this.filterTimer );
if ( character === prev ) {
skip = true;
} else {
character = prev + character;
}
regex = new RegExp( "^" + escape( character ), "i" );
match = this.activeMenu.children( ".ui-menu-item" ).filter(function() {
return regex.test( $( this ).children( "a" ).text() );
});
match = skip && match.index( this.active.next() ) !== -1 ?
this.active.nextAll( ".ui-menu-item" ) :
match;
// If no matches on the current filter, reset to the last character pressed
// to move down the menu to the first item that starts with that character
if ( !match.length ) {
character = String.fromCharCode( event.keyCode );
regex = new RegExp( "^" + escape( character ), "i" );
match = this.activeMenu.children( ".ui-menu-item" ).filter(function() {
return regex.test( $( this ).children( "a" ).text() );
});
}
if ( match.length ) {
this.focus( event, match );
if ( match.length > 1 ) {
this.previousFilter = character;
this.filterTimer = this._delay(function() {
delete this.previousFilter;
}, 1000 );
} else {
delete this.previousFilter;
}
} else {
delete this.previousFilter;
}
}
if ( preventDefault ) {
event.preventDefault();
}
},
_activate: function( event ) {
if ( !this.active.is( ".ui-state-disabled" ) ) {
if ( this.active.children( "a[aria-haspopup='true']" ).length ) {
this.expand( event );
} else {
this.select( event );
}
}
},
refresh: function() {
var menus,
icon = this.options.icons.submenu,
submenus = this.element.find( this.options.menus );
// Initialize nested menus
submenus.filter( ":not(.ui-menu)" )
.addClass( "ui-menu ui-widget ui-widget-content ui-corner-all" )
.hide()
.attr({
role: this.options.role,
"aria-hidden": "true",
"aria-expanded": "false"
})
.each(function() {
var menu = $( this ),
item = menu.prev( "a" ),
submenuCarat = $( "<span>" )
.addClass( "ui-menu-icon ui-icon " + icon )
.data( "ui-menu-submenu-carat", true );
item
.attr( "aria-haspopup", "true" )
.prepend( submenuCarat );
menu.attr( "aria-labelledby", item.attr( "id" ) );
});
menus = submenus.add( this.element );
// Don't refresh list items that are already adapted
menus.children( ":not(.ui-menu-item):has(a)" )
.addClass( "ui-menu-item" )
.attr( "role", "presentation" )
.children( "a" )
.uniqueId()
.addClass( "ui-corner-all" )
.attr({
tabIndex: -1,
role: this._itemRole()
});
// Initialize unlinked menu-items containing spaces and/or dashes only as dividers
menus.children( ":not(.ui-menu-item)" ).each(function() {
var item = $( this );
// hyphen, em dash, en dash
if ( !/[^\-\u2014\u2013\s]/.test( item.text() ) ) {
item.addClass( "ui-widget-content ui-menu-divider" );
}
});
// Add aria-disabled attribute to any disabled menu item
menus.children( ".ui-state-disabled" ).attr( "aria-disabled", "true" );
// If the active item has been removed, blur the menu
if ( this.active && !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) {
this.blur();
}
},
_itemRole: function() {
return {
menu: "menuitem",
listbox: "option"
}[ this.options.role ];
},
_setOption: function( key, value ) {
if ( key === "icons" ) {
this.element.find( ".ui-menu-icon" )
.removeClass( this.options.icons.submenu )
.addClass( value.submenu );
}
this._super( key, value );
},
focus: function( event, item ) {
var nested, focused;
this.blur( event, event && event.type === "focus" );
this._scrollIntoView( item );
this.active = item.first();
focused = this.active.children( "a" ).addClass( "ui-state-focus" );
// Only update aria-activedescendant if there's a role
// otherwise we assume focus is managed elsewhere
if ( this.options.role ) {
this.element.attr( "aria-activedescendant", focused.attr( "id" ) );
}
// Highlight active parent menu item, if any
this.active
.parent()
.closest( ".ui-menu-item" )
.children( "a:first" )
.addClass( "ui-state-active" );
if ( event && event.type === "keydown" ) {
this._close();
} else {
this.timer = this._delay(function() {
this._close();
}, this.delay );
}
nested = item.children( ".ui-menu" );
if ( nested.length && ( /^mouse/.test( event.type ) ) ) {
this._startOpening(nested);
}
this.activeMenu = item.parent();
this._trigger( "focus", event, { item: item } );
},
_scrollIntoView: function( item ) {
var borderTop, paddingTop, offset, scroll, elementHeight, itemHeight;
if ( this._hasScroll() ) {
borderTop = parseFloat( $.css( this.activeMenu[0], "borderTopWidth" ) ) || 0;
paddingTop = parseFloat( $.css( this.activeMenu[0], "paddingTop" ) ) || 0;
offset = item.offset().top - this.activeMenu.offset().top - borderTop - paddingTop;
scroll = this.activeMenu.scrollTop();
elementHeight = this.activeMenu.height();
itemHeight = item.height();
if ( offset < 0 ) {
this.activeMenu.scrollTop( scroll + offset );
} else if ( offset + itemHeight > elementHeight ) {
this.activeMenu.scrollTop( scroll + offset - elementHeight + itemHeight );
}
}
},
blur: function( event, fromFocus ) {
if ( !fromFocus ) {
clearTimeout( this.timer );
}
if ( !this.active ) {
return;
}
this.active.children( "a" ).removeClass( "ui-state-focus" );
this.active = null;
this._trigger( "blur", event, { item: this.active } );
},
_startOpening: function( submenu ) {
clearTimeout( this.timer );
// Don't open if already open fixes a Firefox bug that caused a .5 pixel
// shift in the submenu position when mousing over the carat icon
if ( submenu.attr( "aria-hidden" ) !== "true" ) {
return;
}
this.timer = this._delay(function() {
this._close();
this._open( submenu );
}, this.delay );
},
_open: function( submenu ) {
var position = $.extend({
of: this.active
}, this.options.position );
clearTimeout( this.timer );
this.element.find( ".ui-menu" ).not( submenu.parents( ".ui-menu" ) )
.hide()
.attr( "aria-hidden", "true" );
submenu
.show()
.removeAttr( "aria-hidden" )
.attr( "aria-expanded", "true" )
.position( position );
},
collapseAll: function( event, all ) {
clearTimeout( this.timer );
this.timer = this._delay(function() {
// If we were passed an event, look for the submenu that contains the event
var currentMenu = all ? this.element :
$( event && event.target ).closest( this.element.find( ".ui-menu" ) );
// If we found no valid submenu ancestor, use the main menu to close all sub menus anyway
if ( !currentMenu.length ) {
currentMenu = this.element;
}
this._close( currentMenu );
this.blur( event );
this.activeMenu = currentMenu;
}, this.delay );
},
// With no arguments, closes the currently active menu - if nothing is active
// it closes all menus. If passed an argument, it will search for menus BELOW
_close: function( startMenu ) {
if ( !startMenu ) {
startMenu = this.active ? this.active.parent() : this.element;
}
startMenu
.find( ".ui-menu" )
.hide()
.attr( "aria-hidden", "true" )
.attr( "aria-expanded", "false" )
.end()
.find( "a.ui-state-active" )
.removeClass( "ui-state-active" );
},
collapse: function( event ) {
var newItem = this.active &&
this.active.parent().closest( ".ui-menu-item", this.element );
if ( newItem && newItem.length ) {
this._close();
this.focus( event, newItem );
}
},
expand: function( event ) {
var newItem = this.active &&
this.active
.children( ".ui-menu " )
.children( ".ui-menu-item" )
.first();
if ( newItem && newItem.length ) {
this._open( newItem.parent() );
// Delay so Firefox will not hide activedescendant change in expanding submenu from AT
this._delay(function() {
this.focus( event, newItem );
});
}
},
next: function( event ) {
this._move( "next", "first", event );
},
previous: function( event ) {
this._move( "prev", "last", event );
},
isFirstItem: function() {
return this.active && !this.active.prevAll( ".ui-menu-item" ).length;
},
isLastItem: function() {
return this.active && !this.active.nextAll( ".ui-menu-item" ).length;
},
_move: function( direction, filter, event ) {
var next;
if ( this.active ) {
if ( direction === "first" || direction === "last" ) {
next = this.active
[ direction === "first" ? "prevAll" : "nextAll" ]( ".ui-menu-item" )
.eq( -1 );
} else {
next = this.active
[ direction + "All" ]( ".ui-menu-item" )
.eq( 0 );
}
}
if ( !next || !next.length || !this.active ) {
next = this.activeMenu.children( ".ui-menu-item" )[ filter ]();
}
this.focus( event, next );
},
nextPage: function( event ) {
var item, base, height;
if ( !this.active ) {
this.next( event );
return;
}
if ( this.isLastItem() ) {
return;
}
if ( this._hasScroll() ) {
base = this.active.offset().top;
height = this.element.height();
this.active.nextAll( ".ui-menu-item" ).each(function() {
item = $( this );
return item.offset().top - base - height < 0;
});
this.focus( event, item );
} else {
this.focus( event, this.activeMenu.children( ".ui-menu-item" )
[ !this.active ? "first" : "last" ]() );
}
},
previousPage: function( event ) {
var item, base, height;
if ( !this.active ) {
this.next( event );
return;
}
if ( this.isFirstItem() ) {
return;
}
if ( this._hasScroll() ) {
base = this.active.offset().top;
height = this.element.height();
this.active.prevAll( ".ui-menu-item" ).each(function() {
item = $( this );
return item.offset().top - base + height > 0;
});
this.focus( event, item );
} else {
this.focus( event, this.activeMenu.children( ".ui-menu-item" ).first() );
}
},
_hasScroll: function() {
return this.element.outerHeight() < this.element.prop( "scrollHeight" );
},
select: function( event ) {
// TODO: It should never be possible to not have an active item at this
// point, but the tests don't trigger mouseenter before click.
this.active = this.active || $( event.target ).closest( ".ui-menu-item" );
var ui = { item: this.active };
if ( !this.active.has( ".ui-menu" ).length ) {
this.collapseAll( event, true );
}
this._trigger( "select", event, ui );
}
});
}( jQuery ));
(function( $, undefined ) {
$.ui = $.ui || {};
var cachedScrollbarWidth,
max = Math.max,
abs = Math.abs,
round = Math.round,
rhorizontal = /left|center|right/,
rvertical = /top|center|bottom/,
roffset = /[\+\-]\d+(\.[\d]+)?%?/,
rposition = /^\w+/,
rpercent = /%$/,
_position = $.fn.position;
function getOffsets( offsets, width, height ) {
return [
parseFloat( offsets[ 0 ] ) * ( rpercent.test( offsets[ 0 ] ) ? width / 100 : 1 ),
parseFloat( offsets[ 1 ] ) * ( rpercent.test( offsets[ 1 ] ) ? height / 100 : 1 )
];
}
function parseCss( element, property ) {
return parseInt( $.css( element, property ), 10 ) || 0;
}
function getDimensions( elem ) {
var raw = elem[0];
if ( raw.nodeType === 9 ) {
return {
width: elem.width(),
height: elem.height(),
offset: { top: 0, left: 0 }
};
}
if ( $.isWindow( raw ) ) {
return {
width: elem.width(),
height: elem.height(),
offset: { top: elem.scrollTop(), left: elem.scrollLeft() }
};
}
if ( raw.preventDefault ) {
return {
width: 0,
height: 0,
offset: { top: raw.pageY, left: raw.pageX }
};
}
return {
width: elem.outerWidth(),
height: elem.outerHeight(),
offset: elem.offset()
};
}
$.position = {
scrollbarWidth: function() {
if ( cachedScrollbarWidth !== undefined ) {
return cachedScrollbarWidth;
}
var w1, w2,
div = $( "<div style='display:block;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>" ),
innerDiv = div.children()[0];
$( "body" ).append( div );
w1 = innerDiv.offsetWidth;
div.css( "overflow", "scroll" );
w2 = innerDiv.offsetWidth;
if ( w1 === w2 ) {
w2 = div[0].clientWidth;
}
div.remove();
return (cachedScrollbarWidth = w1 - w2);
},
getScrollInfo: function( within ) {
var overflowX = within.isWindow ? "" : within.element.css( "overflow-x" ),
overflowY = within.isWindow ? "" : within.element.css( "overflow-y" ),
hasOverflowX = overflowX === "scroll" ||
( overflowX === "auto" && within.width < within.element[0].scrollWidth ),
hasOverflowY = overflowY === "scroll" ||
( overflowY === "auto" && within.height < within.element[0].scrollHeight );
return {
width: hasOverflowY ? $.position.scrollbarWidth() : 0,
height: hasOverflowX ? $.position.scrollbarWidth() : 0
};
},
getWithinInfo: function( element ) {
var withinElement = $( element || window ),
isWindow = $.isWindow( withinElement[0] );
return {
element: withinElement,
isWindow: isWindow,
offset: withinElement.offset() || { left: 0, top: 0 },
scrollLeft: withinElement.scrollLeft(),
scrollTop: withinElement.scrollTop(),
width: isWindow ? withinElement.width() : withinElement.outerWidth(),
height: isWindow ? withinElement.height() : withinElement.outerHeight()
};
}
};
$.fn.position = function( options ) {
if ( !options || !options.of ) {
return _position.apply( this, arguments );
}
// make a copy, we don't want to modify arguments
options = $.extend( {}, options );
var atOffset, targetWidth, targetHeight, targetOffset, basePosition, dimensions,
target = $( options.of ),
within = $.position.getWithinInfo( options.within ),
scrollInfo = $.position.getScrollInfo( within ),
collision = ( options.collision || "flip" ).split( " " ),
offsets = {};
dimensions = getDimensions( target );
if ( target[0].preventDefault ) {
// force left top to allow flipping
options.at = "left top";
}
targetWidth = dimensions.width;
targetHeight = dimensions.height;
targetOffset = dimensions.offset;
// clone to reuse original targetOffset later
basePosition = $.extend( {}, targetOffset );
// force my and at to have valid horizontal and vertical positions
// if a value is missing or invalid, it will be converted to center
$.each( [ "my", "at" ], function() {
var pos = ( options[ this ] || "" ).split( " " ),
horizontalOffset,
verticalOffset;
if ( pos.length === 1) {
pos = rhorizontal.test( pos[ 0 ] ) ?
pos.concat( [ "center" ] ) :
rvertical.test( pos[ 0 ] ) ?
[ "center" ].concat( pos ) :
[ "center", "center" ];
}
pos[ 0 ] = rhorizontal.test( pos[ 0 ] ) ? pos[ 0 ] : "center";
pos[ 1 ] = rvertical.test( pos[ 1 ] ) ? pos[ 1 ] : "center";
// calculate offsets
horizontalOffset = roffset.exec( pos[ 0 ] );
verticalOffset = roffset.exec( pos[ 1 ] );
offsets[ this ] = [
horizontalOffset ? horizontalOffset[ 0 ] : 0,
verticalOffset ? verticalOffset[ 0 ] : 0
];
// reduce to just the positions without the offsets
options[ this ] = [
rposition.exec( pos[ 0 ] )[ 0 ],
rposition.exec( pos[ 1 ] )[ 0 ]
];
});
// normalize collision option
if ( collision.length === 1 ) {
collision[ 1 ] = collision[ 0 ];
}
if ( options.at[ 0 ] === "right" ) {
basePosition.left += targetWidth;
} else if ( options.at[ 0 ] === "center" ) {
basePosition.left += targetWidth / 2;
}
if ( options.at[ 1 ] === "bottom" ) {
basePosition.top += targetHeight;
} else if ( options.at[ 1 ] === "center" ) {
basePosition.top += targetHeight / 2;
}
atOffset = getOffsets( offsets.at, targetWidth, targetHeight );
basePosition.left += atOffset[ 0 ];
basePosition.top += atOffset[ 1 ];
return this.each(function() {
var collisionPosition, using,
elem = $( this ),
elemWidth = elem.outerWidth(),
elemHeight = elem.outerHeight(),
marginLeft = parseCss( this, "marginLeft" ),
marginTop = parseCss( this, "marginTop" ),
collisionWidth = elemWidth + marginLeft + parseCss( this, "marginRight" ) + scrollInfo.width,
collisionHeight = elemHeight + marginTop + parseCss( this, "marginBottom" ) + scrollInfo.height,
position = $.extend( {}, basePosition ),
myOffset = getOffsets( offsets.my, elem.outerWidth(), elem.outerHeight() );
if ( options.my[ 0 ] === "right" ) {
position.left -= elemWidth;
} else if ( options.my[ 0 ] === "center" ) {
position.left -= elemWidth / 2;
}
if ( options.my[ 1 ] === "bottom" ) {
position.top -= elemHeight;
} else if ( options.my[ 1 ] === "center" ) {
position.top -= elemHeight / 2;
}
position.left += myOffset[ 0 ];
position.top += myOffset[ 1 ];
// if the browser doesn't support fractions, then round for consistent results
if ( !$.support.offsetFractions ) {
position.left = round( position.left );
position.top = round( position.top );
}
collisionPosition = {
marginLeft: marginLeft,
marginTop: marginTop
};
$.each( [ "left", "top" ], function( i, dir ) {
if ( $.ui.position[ collision[ i ] ] ) {
$.ui.position[ collision[ i ] ][ dir ]( position, {
targetWidth: targetWidth,
targetHeight: targetHeight,
elemWidth: elemWidth,
elemHeight: elemHeight,
collisionPosition: collisionPosition,
collisionWidth: collisionWidth,
collisionHeight: collisionHeight,
offset: [ atOffset[ 0 ] + myOffset[ 0 ], atOffset [ 1 ] + myOffset[ 1 ] ],
my: options.my,
at: options.at,
within: within,
elem : elem
});
}
});
if ( options.using ) {
// adds feedback as second argument to using callback, if present
using = function( props ) {
var left = targetOffset.left - position.left,
right = left + targetWidth - elemWidth,
top = targetOffset.top - position.top,
bottom = top + targetHeight - elemHeight,
feedback = {
target: {
element: target,
left: targetOffset.left,
top: targetOffset.top,
width: targetWidth,
height: targetHeight
},
element: {
element: elem,
left: position.left,
top: position.top,
width: elemWidth,
height: elemHeight
},
horizontal: right < 0 ? "left" : left > 0 ? "right" : "center",
vertical: bottom < 0 ? "top" : top > 0 ? "bottom" : "middle"
};
if ( targetWidth < elemWidth && abs( left + right ) < targetWidth ) {
feedback.horizontal = "center";
}
if ( targetHeight < elemHeight && abs( top + bottom ) < targetHeight ) {
feedback.vertical = "middle";
}
if ( max( abs( left ), abs( right ) ) > max( abs( top ), abs( bottom ) ) ) {
feedback.important = "horizontal";
} else {
feedback.important = "vertical";
}
options.using.call( this, props, feedback );
};
}
elem.offset( $.extend( position, { using: using } ) );
});
};
$.ui.position = {
fit: {
left: function( position, data ) {
var within = data.within,
withinOffset = within.isWindow ? within.scrollLeft : within.offset.left,
outerWidth = within.width,
collisionPosLeft = position.left - data.collisionPosition.marginLeft,
overLeft = withinOffset - collisionPosLeft,
overRight = collisionPosLeft + data.collisionWidth - outerWidth - withinOffset,
newOverRight;
// element is wider than within
if ( data.collisionWidth > outerWidth ) {
// element is initially over the left side of within
if ( overLeft > 0 && overRight <= 0 ) {
newOverRight = position.left + overLeft + data.collisionWidth - outerWidth - withinOffset;
position.left += overLeft - newOverRight;
// element is initially over right side of within
} else if ( overRight > 0 && overLeft <= 0 ) {
position.left = withinOffset;
// element is initially over both left and right sides of within
} else {
if ( overLeft > overRight ) {
position.left = withinOffset + outerWidth - data.collisionWidth;
} else {
position.left = withinOffset;
}
}
// too far left -> align with left edge
} else if ( overLeft > 0 ) {
position.left += overLeft;
// too far right -> align with right edge
} else if ( overRight > 0 ) {
position.left -= overRight;
// adjust based on position and margin
} else {
position.left = max( position.left - collisionPosLeft, position.left );
}
},
top: function( position, data ) {
var within = data.within,
withinOffset = within.isWindow ? within.scrollTop : within.offset.top,
outerHeight = data.within.height,
collisionPosTop = position.top - data.collisionPosition.marginTop,
overTop = withinOffset - collisionPosTop,
overBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset,
newOverBottom;
// element is taller than within
if ( data.collisionHeight > outerHeight ) {
// element is initially over the top of within
if ( overTop > 0 && overBottom <= 0 ) {
newOverBottom = position.top + overTop + data.collisionHeight - outerHeight - withinOffset;
position.top += overTop - newOverBottom;
// element is initially over bottom of within
} else if ( overBottom > 0 && overTop <= 0 ) {
position.top = withinOffset;
// element is initially over both top and bottom of within
} else {
if ( overTop > overBottom ) {
position.top = withinOffset + outerHeight - data.collisionHeight;
} else {
position.top = withinOffset;
}
}
// too far up -> align with top
} else if ( overTop > 0 ) {
position.top += overTop;
// too far down -> align with bottom edge
} else if ( overBottom > 0 ) {
position.top -= overBottom;
// adjust based on position and margin
} else {
position.top = max( position.top - collisionPosTop, position.top );
}
}
},
flip: {
left: function( position, data ) {
var within = data.within,
withinOffset = within.offset.left + within.scrollLeft,
outerWidth = within.width,
offsetLeft = within.isWindow ? within.scrollLeft : within.offset.left,
collisionPosLeft = position.left - data.collisionPosition.marginLeft,
overLeft = collisionPosLeft - offsetLeft,
overRight = collisionPosLeft + data.collisionWidth - outerWidth - offsetLeft,
myOffset = data.my[ 0 ] === "left" ?
-data.elemWidth :
data.my[ 0 ] === "right" ?
data.elemWidth :
0,
atOffset = data.at[ 0 ] === "left" ?
data.targetWidth :
data.at[ 0 ] === "right" ?
-data.targetWidth :
0,
offset = -2 * data.offset[ 0 ],
newOverRight,
newOverLeft;
if ( overLeft < 0 ) {
newOverRight = position.left + myOffset + atOffset + offset + data.collisionWidth - outerWidth - withinOffset;
if ( newOverRight < 0 || newOverRight < abs( overLeft ) ) {
position.left += myOffset + atOffset + offset;
}
}
else if ( overRight > 0 ) {
newOverLeft = position.left - data.collisionPosition.marginLeft + myOffset + atOffset + offset - offsetLeft;
if ( newOverLeft > 0 || abs( newOverLeft ) < overRight ) {
position.left += myOffset + atOffset + offset;
}
}
},
top: function( position, data ) {
var within = data.within,
withinOffset = within.offset.top + within.scrollTop,
outerHeight = within.height,
offsetTop = within.isWindow ? within.scrollTop : within.offset.top,
collisionPosTop = position.top - data.collisionPosition.marginTop,
overTop = collisionPosTop - offsetTop,
overBottom = collisionPosTop + data.collisionHeight - outerHeight - offsetTop,
top = data.my[ 1 ] === "top",
myOffset = top ?
-data.elemHeight :
data.my[ 1 ] === "bottom" ?
data.elemHeight :
0,
atOffset = data.at[ 1 ] === "top" ?
data.targetHeight :
data.at[ 1 ] === "bottom" ?
-data.targetHeight :
0,
offset = -2 * data.offset[ 1 ],
newOverTop,
newOverBottom;
if ( overTop < 0 ) {
newOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight - outerHeight - withinOffset;
if ( ( position.top + myOffset + atOffset + offset) > overTop && ( newOverBottom < 0 || newOverBottom < abs( overTop ) ) ) {
position.top += myOffset + atOffset + offset;
}
}
else if ( overBottom > 0 ) {
newOverTop = position.top - data.collisionPosition.marginTop + myOffset + atOffset + offset - offsetTop;
if ( ( position.top + myOffset + atOffset + offset) > overBottom && ( newOverTop > 0 || abs( newOverTop ) < overBottom ) ) {
position.top += myOffset + atOffset + offset;
}
}
}
},
flipfit: {
left: function() {
$.ui.position.flip.left.apply( this, arguments );
$.ui.position.fit.left.apply( this, arguments );
},
top: function() {
$.ui.position.flip.top.apply( this, arguments );
$.ui.position.fit.top.apply( this, arguments );
}
}
};
// fraction support test
(function () {
var testElement, testElementParent, testElementStyle, offsetLeft, i,
body = document.getElementsByTagName( "body" )[ 0 ],
div = document.createElement( "div" );
//Create a "fake body" for testing based on method used in jQuery.support
testElement = document.createElement( body ? "div" : "body" );
testElementStyle = {
visibility: "hidden",
width: 0,
height: 0,
border: 0,
margin: 0,
background: "none"
};
if ( body ) {
$.extend( testElementStyle, {
position: "absolute",
left: "-1000px",
top: "-1000px"
});
}
for ( i in testElementStyle ) {
testElement.style[ i ] = testElementStyle[ i ];
}
testElement.appendChild( div );
testElementParent = body || document.documentElement;
testElementParent.insertBefore( testElement, testElementParent.firstChild );
div.style.cssText = "position: absolute; left: 10.7432222px;";
offsetLeft = $( div ).offset().left;
$.support.offsetFractions = offsetLeft > 10 && offsetLeft < 11;
testElement.innerHTML = "";
testElementParent.removeChild( testElement );
})();
}( jQuery ) );
(function( $, undefined ) {
$.widget( "ui.progressbar", {
version: "1.10.3",
options: {
max: 100,
value: 0,
change: null,
complete: null
},
min: 0,
_create: function() {
// Constrain initial value
this.oldValue = this.options.value = this._constrainedValue();
this.element
.addClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" )
.attr({
// Only set static values, aria-valuenow and aria-valuemax are
// set inside _refreshValue()
role: "progressbar",
"aria-valuemin": this.min
});
this.valueDiv = $( "<div class='ui-progressbar-value ui-widget-header ui-corner-left'></div>" )
.appendTo( this.element );
this._refreshValue();
},
_destroy: function() {
this.element
.removeClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" )
.removeAttr( "role" )
.removeAttr( "aria-valuemin" )
.removeAttr( "aria-valuemax" )
.removeAttr( "aria-valuenow" );
this.valueDiv.remove();
},
value: function( newValue ) {
if ( newValue === undefined ) {
return this.options.value;
}
this.options.value = this._constrainedValue( newValue );
this._refreshValue();
},
_constrainedValue: function( newValue ) {
if ( newValue === undefined ) {
newValue = this.options.value;
}
this.indeterminate = newValue === false;
// sanitize value
if ( typeof newValue !== "number" ) {
newValue = 0;
}
return this.indeterminate ? false :
Math.min( this.options.max, Math.max( this.min, newValue ) );
},
_setOptions: function( options ) {
// Ensure "value" option is set after other values (like max)
var value = options.value;
delete options.value;
this._super( options );
this.options.value = this._constrainedValue( value );
this._refreshValue();
},
_setOption: function( key, value ) {
if ( key === "max" ) {
// Don't allow a max less than min
value = Math.max( this.min, value );
}
this._super( key, value );
},
_percentage: function() {
return this.indeterminate ? 100 : 100 * ( this.options.value - this.min ) / ( this.options.max - this.min );
},
_refreshValue: function() {
var value = this.options.value,
percentage = this._percentage();
this.valueDiv
.toggle( this.indeterminate || value > this.min )
.toggleClass( "ui-corner-right", value === this.options.max )
.width( percentage.toFixed(0) + "%" );
this.element.toggleClass( "ui-progressbar-indeterminate", this.indeterminate );
if ( this.indeterminate ) {
this.element.removeAttr( "aria-valuenow" );
if ( !this.overlayDiv ) {
this.overlayDiv = $( "<div class='ui-progressbar-overlay'></div>" ).appendTo( this.valueDiv );
}
} else {
this.element.attr({
"aria-valuemax": this.options.max,
"aria-valuenow": value
});
if ( this.overlayDiv ) {
this.overlayDiv.remove();
this.overlayDiv = null;
}
}
if ( this.oldValue !== value ) {
this.oldValue = value;
this._trigger( "change" );
}
if ( value === this.options.max ) {
this._trigger( "complete" );
}
}
});
})( jQuery );
(function( $, undefined ) {
// number of pages in a slider
// (how many times can you page up/down to go through the whole range)
var numPages = 5;
$.widget( "ui.slider", $.ui.mouse, {
version: "1.10.3",
widgetEventPrefix: "slide",
options: {
animate: false,
distance: 0,
max: 100,
min: 0,
orientation: "horizontal",
range: false,
step: 1,
value: 0,
values: null,
// callbacks
change: null,
slide: null,
start: null,
stop: null
},
_create: function() {
this._keySliding = false;
this._mouseSliding = false;
this._animateOff = true;
this._handleIndex = null;
this._detectOrientation();
this._mouseInit();
this.element
.addClass( "ui-slider" +
" ui-slider-" + this.orientation +
" ui-widget" +
" ui-widget-content" +
" ui-corner-all");
this._refresh();
this._setOption( "disabled", this.options.disabled );
this._animateOff = false;
},
_refresh: function() {
this._createRange();
this._createHandles();
this._setupEvents();
this._refreshValue();
},
_createHandles: function() {
var i, handleCount,
options = this.options,
existingHandles = this.element.find( ".ui-slider-handle" ).addClass( "ui-state-default ui-corner-all" ),
handle = "<a class='ui-slider-handle ui-state-default ui-corner-all' href='#'></a>",
handles = [];
handleCount = ( options.values && options.values.length ) || 1;
if ( existingHandles.length > handleCount ) {
existingHandles.slice( handleCount ).remove();
existingHandles = existingHandles.slice( 0, handleCount );
}
for ( i = existingHandles.length; i < handleCount; i++ ) {
handles.push( handle );
}
this.handles = existingHandles.add( $( handles.join( "" ) ).appendTo( this.element ) );
this.handle = this.handles.eq( 0 );
this.handles.each(function( i ) {
$( this ).data( "ui-slider-handle-index", i );
});
},
_createRange: function() {
var options = this.options,
classes = "";
if ( options.range ) {
if ( options.range === true ) {
if ( !options.values ) {
options.values = [ this._valueMin(), this._valueMin() ];
} else if ( options.values.length && options.values.length !== 2 ) {
options.values = [ options.values[0], options.values[0] ];
} else if ( $.isArray( options.values ) ) {
options.values = options.values.slice(0);
}
}
if ( !this.range || !this.range.length ) {
this.range = $( "<div></div>" )
.appendTo( this.element );
classes = "ui-slider-range" +
// note: this isn't the most fittingly semantic framework class for this element,
// but worked best visually with a variety of themes
" ui-widget-header ui-corner-all";
} else {
this.range.removeClass( "ui-slider-range-min ui-slider-range-max" )
// Handle range switching from true to min/max
.css({
"left": "",
"bottom": ""
});
}
this.range.addClass( classes +
( ( options.range === "min" || options.range === "max" ) ? " ui-slider-range-" + options.range : "" ) );
} else {
this.range = $([]);
}
},
_setupEvents: function() {
var elements = this.handles.add( this.range ).filter( "a" );
this._off( elements );
this._on( elements, this._handleEvents );
this._hoverable( elements );
this._focusable( elements );
},
_destroy: function() {
this.handles.remove();
this.range.remove();
this.element
.removeClass( "ui-slider" +
" ui-slider-horizontal" +
" ui-slider-vertical" +
" ui-widget" +
" ui-widget-content" +
" ui-corner-all" );
this._mouseDestroy();
},
_mouseCapture: function( event ) {
var position, normValue, distance, closestHandle, index, allowed, offset, mouseOverHandle,
that = this,
o = this.options;
if ( o.disabled ) {
return false;
}
this.elementSize = {
width: this.element.outerWidth(),
height: this.element.outerHeight()
};
this.elementOffset = this.element.offset();
position = { x: event.pageX, y: event.pageY };
normValue = this._normValueFromMouse( position );
distance = this._valueMax() - this._valueMin() + 1;
this.handles.each(function( i ) {
var thisDistance = Math.abs( normValue - that.values(i) );
if (( distance > thisDistance ) ||
( distance === thisDistance &&
(i === that._lastChangedValue || that.values(i) === o.min ))) {
distance = thisDistance;
closestHandle = $( this );
index = i;
}
});
allowed = this._start( event, index );
if ( allowed === false ) {
return false;
}
this._mouseSliding = true;
this._handleIndex = index;
closestHandle
.addClass( "ui-state-active" )
.focus();
offset = closestHandle.offset();
mouseOverHandle = !$( event.target ).parents().addBack().is( ".ui-slider-handle" );
this._clickOffset = mouseOverHandle ? { left: 0, top: 0 } : {
left: event.pageX - offset.left - ( closestHandle.width() / 2 ),
top: event.pageY - offset.top -
( closestHandle.height() / 2 ) -
( parseInt( closestHandle.css("borderTopWidth"), 10 ) || 0 ) -
( parseInt( closestHandle.css("borderBottomWidth"), 10 ) || 0) +
( parseInt( closestHandle.css("marginTop"), 10 ) || 0)
};
if ( !this.handles.hasClass( "ui-state-hover" ) ) {
this._slide( event, index, normValue );
}
this._animateOff = true;
return true;
},
_mouseStart: function() {
return true;
},
_mouseDrag: function( event ) {
var position = { x: event.pageX, y: event.pageY },
normValue = this._normValueFromMouse( position );
this._slide( event, this._handleIndex, normValue );
return false;
},
_mouseStop: function( event ) {
this.handles.removeClass( "ui-state-active" );
this._mouseSliding = false;
this._stop( event, this._handleIndex );
this._change( event, this._handleIndex );
this._handleIndex = null;
this._clickOffset = null;
this._animateOff = false;
return false;
},
_detectOrientation: function() {
this.orientation = ( this.options.orientation === "vertical" ) ? "vertical" : "horizontal";
},
_normValueFromMouse: function( position ) {
var pixelTotal,
pixelMouse,
percentMouse,
valueTotal,
valueMouse;
if ( this.orientation === "horizontal" ) {
pixelTotal = this.elementSize.width;
pixelMouse = position.x - this.elementOffset.left - ( this._clickOffset ? this._clickOffset.left : 0 );
} else {
pixelTotal = this.elementSize.height;
pixelMouse = position.y - this.elementOffset.top - ( this._clickOffset ? this._clickOffset.top : 0 );
}
percentMouse = ( pixelMouse / pixelTotal );
if ( percentMouse > 1 ) {
percentMouse = 1;
}
if ( percentMouse < 0 ) {
percentMouse = 0;
}
if ( this.orientation === "vertical" ) {
percentMouse = 1 - percentMouse;
}
valueTotal = this._valueMax() - this._valueMin();
valueMouse = this._valueMin() + percentMouse * valueTotal;
return this._trimAlignValue( valueMouse );
},
_start: function( event, index ) {
var uiHash = {
handle: this.handles[ index ],
value: this.value()
};
if ( this.options.values && this.options.values.length ) {
uiHash.value = this.values( index );
uiHash.values = this.values();
}
return this._trigger( "start", event, uiHash );
},
_slide: function( event, index, newVal ) {
var otherVal,
newValues,
allowed;
if ( this.options.values && this.options.values.length ) {
otherVal = this.values( index ? 0 : 1 );
if ( ( this.options.values.length === 2 && this.options.range === true ) &&
( ( index === 0 && newVal > otherVal) || ( index === 1 && newVal < otherVal ) )
) {
newVal = otherVal;
}
if ( newVal !== this.values( index ) ) {
newValues = this.values();
newValues[ index ] = newVal;
// A slide can be canceled by returning false from the slide callback
allowed = this._trigger( "slide", event, {
handle: this.handles[ index ],
value: newVal,
values: newValues
} );
otherVal = this.values( index ? 0 : 1 );
if ( allowed !== false ) {
this.values( index, newVal, true );
}
}
} else {
if ( newVal !== this.value() ) {
// A slide can be canceled by returning false from the slide callback
allowed = this._trigger( "slide", event, {
handle: this.handles[ index ],
value: newVal
} );
if ( allowed !== false ) {
this.value( newVal );
}
}
}
},
_stop: function( event, index ) {
var uiHash = {
handle: this.handles[ index ],
value: this.value()
};
if ( this.options.values && this.options.values.length ) {
uiHash.value = this.values( index );
uiHash.values = this.values();
}
this._trigger( "stop", event, uiHash );
},
_change: function( event, index ) {
if ( !this._keySliding && !this._mouseSliding ) {
var uiHash = {
handle: this.handles[ index ],
value: this.value()
};
if ( this.options.values && this.options.values.length ) {
uiHash.value = this.values( index );
uiHash.values = this.values();
}
//store the last changed value index for reference when handles overlap
this._lastChangedValue = index;
this._trigger( "change", event, uiHash );
}
},
value: function( newValue ) {
if ( arguments.length ) {
this.options.value = this._trimAlignValue( newValue );
this._refreshValue();
this._change( null, 0 );
return;
}
return this._value();
},
values: function( index, newValue ) {
var vals,
newValues,
i;
if ( arguments.length > 1 ) {
this.options.values[ index ] = this._trimAlignValue( newValue );
this._refreshValue();
this._change( null, index );
return;
}
if ( arguments.length ) {
if ( $.isArray( arguments[ 0 ] ) ) {
vals = this.options.values;
newValues = arguments[ 0 ];
for ( i = 0; i < vals.length; i += 1 ) {
vals[ i ] = this._trimAlignValue( newValues[ i ] );
this._change( null, i );
}
this._refreshValue();
} else {
if ( this.options.values && this.options.values.length ) {
return this._values( index );
} else {
return this.value();
}
}
} else {
return this._values();
}
},
_setOption: function( key, value ) {
var i,
valsLength = 0;
if ( key === "range" && this.options.range === true ) {
if ( value === "min" ) {
this.options.value = this._values( 0 );
this.options.values = null;
} else if ( value === "max" ) {
this.options.value = this._values( this.options.values.length-1 );
this.options.values = null;
}
}
if ( $.isArray( this.options.values ) ) {
valsLength = this.options.values.length;
}
$.Widget.prototype._setOption.apply( this, arguments );
switch ( key ) {
case "orientation":
this._detectOrientation();
this.element
.removeClass( "ui-slider-horizontal ui-slider-vertical" )
.addClass( "ui-slider-" + this.orientation );
this._refreshValue();
break;
case "value":
this._animateOff = true;
this._refreshValue();
this._change( null, 0 );
this._animateOff = false;
break;
case "values":
this._animateOff = true;
this._refreshValue();
for ( i = 0; i < valsLength; i += 1 ) {
this._change( null, i );
}
this._animateOff = false;
break;
case "min":
case "max":
this._animateOff = true;
this._refreshValue();
this._animateOff = false;
break;
case "range":
this._animateOff = true;
this._refresh();
this._animateOff = false;
break;
}
},
//internal value getter
// _value() returns value trimmed by min and max, aligned by step
_value: function() {
var val = this.options.value;
val = this._trimAlignValue( val );
return val;
},
//internal values getter
// _values() returns array of values trimmed by min and max, aligned by step
// _values( index ) returns single value trimmed by min and max, aligned by step
_values: function( index ) {
var val,
vals,
i;
if ( arguments.length ) {
val = this.options.values[ index ];
val = this._trimAlignValue( val );
return val;
} else if ( this.options.values && this.options.values.length ) {
// .slice() creates a copy of the array
// this copy gets trimmed by min and max and then returned
vals = this.options.values.slice();
for ( i = 0; i < vals.length; i+= 1) {
vals[ i ] = this._trimAlignValue( vals[ i ] );
}
return vals;
} else {
return [];
}
},
// returns the step-aligned value that val is closest to, between (inclusive) min and max
_trimAlignValue: function( val ) {
if ( val <= this._valueMin() ) {
return this._valueMin();
}
if ( val >= this._valueMax() ) {
return this._valueMax();
}
var step = ( this.options.step > 0 ) ? this.options.step : 1,
valModStep = (val - this._valueMin()) % step,
alignValue = val - valModStep;
if ( Math.abs(valModStep) * 2 >= step ) {
alignValue += ( valModStep > 0 ) ? step : ( -step );
}
// Since JavaScript has problems with large floats, round
// the final value to 5 digits after the decimal point (see #4124)
return parseFloat( alignValue.toFixed(5) );
},
_valueMin: function() {
return this.options.min;
},
_valueMax: function() {
return this.options.max;
},
_refreshValue: function() {
var lastValPercent, valPercent, value, valueMin, valueMax,
oRange = this.options.range,
o = this.options,
that = this,
animate = ( !this._animateOff ) ? o.animate : false,
_set = {};
if ( this.options.values && this.options.values.length ) {
this.handles.each(function( i ) {
valPercent = ( that.values(i) - that._valueMin() ) / ( that._valueMax() - that._valueMin() ) * 100;
_set[ that.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%";
$( this ).stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate );
if ( that.options.range === true ) {
if ( that.orientation === "horizontal" ) {
if ( i === 0 ) {
that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { left: valPercent + "%" }, o.animate );
}
if ( i === 1 ) {
that.range[ animate ? "animate" : "css" ]( { width: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } );
}
} else {
if ( i === 0 ) {
that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { bottom: ( valPercent ) + "%" }, o.animate );
}
if ( i === 1 ) {
that.range[ animate ? "animate" : "css" ]( { height: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } );
}
}
}
lastValPercent = valPercent;
});
} else {
value = this.value();
valueMin = this._valueMin();
valueMax = this._valueMax();
valPercent = ( valueMax !== valueMin ) ?
( value - valueMin ) / ( valueMax - valueMin ) * 100 :
0;
_set[ this.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%";
this.handle.stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate );
if ( oRange === "min" && this.orientation === "horizontal" ) {
this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { width: valPercent + "%" }, o.animate );
}
if ( oRange === "max" && this.orientation === "horizontal" ) {
this.range[ animate ? "animate" : "css" ]( { width: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } );
}
if ( oRange === "min" && this.orientation === "vertical" ) {
this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { height: valPercent + "%" }, o.animate );
}
if ( oRange === "max" && this.orientation === "vertical" ) {
this.range[ animate ? "animate" : "css" ]( { height: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } );
}
}
},
_handleEvents: {
keydown: function( event ) {
/*jshint maxcomplexity:25*/
var allowed, curVal, newVal, step,
index = $( event.target ).data( "ui-slider-handle-index" );
switch ( event.keyCode ) {
case $.ui.keyCode.HOME:
case $.ui.keyCode.END:
case $.ui.keyCode.PAGE_UP:
case $.ui.keyCode.PAGE_DOWN:
case $.ui.keyCode.UP:
case $.ui.keyCode.RIGHT:
case $.ui.keyCode.DOWN:
case $.ui.keyCode.LEFT:
event.preventDefault();
if ( !this._keySliding ) {
this._keySliding = true;
$( event.target ).addClass( "ui-state-active" );
allowed = this._start( event, index );
if ( allowed === false ) {
return;
}
}
break;
}
step = this.options.step;
if ( this.options.values && this.options.values.length ) {
curVal = newVal = this.values( index );
} else {
curVal = newVal = this.value();
}
switch ( event.keyCode ) {
case $.ui.keyCode.HOME:
newVal = this._valueMin();
break;
case $.ui.keyCode.END:
newVal = this._valueMax();
break;
case $.ui.keyCode.PAGE_UP:
newVal = this._trimAlignValue( curVal + ( (this._valueMax() - this._valueMin()) / numPages ) );
break;
case $.ui.keyCode.PAGE_DOWN:
newVal = this._trimAlignValue( curVal - ( (this._valueMax() - this._valueMin()) / numPages ) );
break;
case $.ui.keyCode.UP:
case $.ui.keyCode.RIGHT:
if ( curVal === this._valueMax() ) {
return;
}
newVal = this._trimAlignValue( curVal + step );
break;
case $.ui.keyCode.DOWN:
case $.ui.keyCode.LEFT:
if ( curVal === this._valueMin() ) {
return;
}
newVal = this._trimAlignValue( curVal - step );
break;
}
this._slide( event, index, newVal );
},
click: function( event ) {
event.preventDefault();
},
keyup: function( event ) {
var index = $( event.target ).data( "ui-slider-handle-index" );
if ( this._keySliding ) {
this._keySliding = false;
this._stop( event, index );
this._change( event, index );
$( event.target ).removeClass( "ui-state-active" );
}
}
}
});
}(jQuery));
(function( $ ) {
function modifier( fn ) {
return function() {
var previous = this.element.val();
fn.apply( this, arguments );
this._refresh();
if ( previous !== this.element.val() ) {
this._trigger( "change" );
}
};
}
$.widget( "ui.spinner", {
version: "1.10.3",
defaultElement: "<input>",
widgetEventPrefix: "spin",
options: {
culture: null,
icons: {
down: "ui-icon-triangle-1-s",
up: "ui-icon-triangle-1-n"
},
incremental: true,
max: null,
min: null,
numberFormat: null,
page: 10,
step: 1,
change: null,
spin: null,
start: null,
stop: null
},
_create: function() {
// handle string values that need to be parsed
this._setOption( "max", this.options.max );
this._setOption( "min", this.options.min );
this._setOption( "step", this.options.step );
// format the value, but don't constrain
this._value( this.element.val(), true );
this._draw();
this._on( this._events );
this._refresh();
// turning off autocomplete prevents the browser from remembering the
// value when navigating through history, so we re-enable autocomplete
// if the page is unloaded before the widget is destroyed. #7790
this._on( this.window, {
beforeunload: function() {
this.element.removeAttr( "autocomplete" );
}
});
},
_getCreateOptions: function() {
var options = {},
element = this.element;
$.each( [ "min", "max", "step" ], function( i, option ) {
var value = element.attr( option );
if ( value !== undefined && value.length ) {
options[ option ] = value;
}
});
return options;
},
_events: {
keydown: function( event ) {
if ( this._start( event ) && this._keydown( event ) ) {
event.preventDefault();
}
},
keyup: "_stop",
focus: function() {
this.previous = this.element.val();
},
blur: function( event ) {
if ( this.cancelBlur ) {
delete this.cancelBlur;
return;
}
this._stop();
this._refresh();
if ( this.previous !== this.element.val() ) {
this._trigger( "change", event );
}
},
mousewheel: function( event, delta ) {
if ( !delta ) {
return;
}
if ( !this.spinning && !this._start( event ) ) {
return false;
}
this._spin( (delta > 0 ? 1 : -1) * this.options.step, event );
clearTimeout( this.mousewheelTimer );
this.mousewheelTimer = this._delay(function() {
if ( this.spinning ) {
this._stop( event );
}
}, 100 );
event.preventDefault();
},
"mousedown .ui-spinner-button": function( event ) {
var previous;
// We never want the buttons to have focus; whenever the user is
// interacting with the spinner, the focus should be on the input.
// If the input is focused then this.previous is properly set from
// when the input first received focus. If the input is not focused
// then we need to set this.previous based on the value before spinning.
previous = this.element[0] === this.document[0].activeElement ?
this.previous : this.element.val();
function checkFocus() {
var isActive = this.element[0] === this.document[0].activeElement;
if ( !isActive ) {
this.element.focus();
this.previous = previous;
// support: IE
// IE sets focus asynchronously, so we need to check if focus
// moved off of the input because the user clicked on the button.
this._delay(function() {
this.previous = previous;
});
}
}
// ensure focus is on (or stays on) the text field
event.preventDefault();
checkFocus.call( this );
// support: IE
// IE doesn't prevent moving focus even with event.preventDefault()
// so we set a flag to know when we should ignore the blur event
// and check (again) if focus moved off of the input.
this.cancelBlur = true;
this._delay(function() {
delete this.cancelBlur;
checkFocus.call( this );
});
if ( this._start( event ) === false ) {
return;
}
this._repeat( null, $( event.currentTarget ).hasClass( "ui-spinner-up" ) ? 1 : -1, event );
},
"mouseup .ui-spinner-button": "_stop",
"mouseenter .ui-spinner-button": function( event ) {
// button will add ui-state-active if mouse was down while mouseleave and kept down
if ( !$( event.currentTarget ).hasClass( "ui-state-active" ) ) {
return;
}
if ( this._start( event ) === false ) {
return false;
}
this._repeat( null, $( event.currentTarget ).hasClass( "ui-spinner-up" ) ? 1 : -1, event );
},
// TODO: do we really want to consider this a stop?
// shouldn't we just stop the repeater and wait until mouseup before
// we trigger the stop event?
"mouseleave .ui-spinner-button": "_stop"
},
_draw: function() {
var uiSpinner = this.uiSpinner = this.element
.addClass( "ui-spinner-input" )
.attr( "autocomplete", "off" )
.wrap( this._uiSpinnerHtml() )
.parent()
// add buttons
.append( this._buttonHtml() );
this.element.attr( "role", "spinbutton" );
// button bindings
this.buttons = uiSpinner.find( ".ui-spinner-button" )
.attr( "tabIndex", -1 )
.button()
.removeClass( "ui-corner-all" );
// IE 6 doesn't understand height: 50% for the buttons
// unless the wrapper has an explicit height
if ( this.buttons.height() > Math.ceil( uiSpinner.height() * 0.5 ) &&
uiSpinner.height() > 0 ) {
uiSpinner.height( uiSpinner.height() );
}
// disable spinner if element was already disabled
if ( this.options.disabled ) {
this.disable();
}
},
_keydown: function( event ) {
var options = this.options,
keyCode = $.ui.keyCode;
switch ( event.keyCode ) {
case keyCode.UP:
this._repeat( null, 1, event );
return true;
case keyCode.DOWN:
this._repeat( null, -1, event );
return true;
case keyCode.PAGE_UP:
this._repeat( null, options.page, event );
return true;
case keyCode.PAGE_DOWN:
this._repeat( null, -options.page, event );
return true;
}
return false;
},
_uiSpinnerHtml: function() {
return "<span class='ui-spinner ui-widget ui-widget-content ui-corner-all'></span>";
},
_buttonHtml: function() {
return "" +
"<a class='ui-spinner-button ui-spinner-up ui-corner-tr'>" +
"<span class='ui-icon " + this.options.icons.up + "'>▲</span>" +
"</a>" +
"<a class='ui-spinner-button ui-spinner-down ui-corner-br'>" +
"<span class='ui-icon " + this.options.icons.down + "'>▼</span>" +
"</a>";
},
_start: function( event ) {
if ( !this.spinning && this._trigger( "start", event ) === false ) {
return false;
}
if ( !this.counter ) {
this.counter = 1;
}
this.spinning = true;
return true;
},
_repeat: function( i, steps, event ) {
i = i || 500;
clearTimeout( this.timer );
this.timer = this._delay(function() {
this._repeat( 40, steps, event );
}, i );
this._spin( steps * this.options.step, event );
},
_spin: function( step, event ) {
var value = this.value() || 0;
if ( !this.counter ) {
this.counter = 1;
}
value = this._adjustValue( value + step * this._increment( this.counter ) );
if ( !this.spinning || this._trigger( "spin", event, { value: value } ) !== false) {
this._value( value );
this.counter++;
}
},
_increment: function( i ) {
var incremental = this.options.incremental;
if ( incremental ) {
return $.isFunction( incremental ) ?
incremental( i ) :
Math.floor( i*i*i/50000 - i*i/500 + 17*i/200 + 1 );
}
return 1;
},
_precision: function() {
var precision = this._precisionOf( this.options.step );
if ( this.options.min !== null ) {
precision = Math.max( precision, this._precisionOf( this.options.min ) );
}
return precision;
},
_precisionOf: function( num ) {
var str = num.toString(),
decimal = str.indexOf( "." );
return decimal === -1 ? 0 : str.length - decimal - 1;
},
_adjustValue: function( value ) {
var base, aboveMin,
options = this.options;
// make sure we're at a valid step
// - find out where we are relative to the base (min or 0)
base = options.min !== null ? options.min : 0;
aboveMin = value - base;
// - round to the nearest step
aboveMin = Math.round(aboveMin / options.step) * options.step;
// - rounding is based on 0, so adjust back to our base
value = base + aboveMin;
// fix precision from bad JS floating point math
value = parseFloat( value.toFixed( this._precision() ) );
// clamp the value
if ( options.max !== null && value > options.max) {
return options.max;
}
if ( options.min !== null && value < options.min ) {
return options.min;
}
return value;
},
_stop: function( event ) {
if ( !this.spinning ) {
return;
}
clearTimeout( this.timer );
clearTimeout( this.mousewheelTimer );
this.counter = 0;
this.spinning = false;
this._trigger( "stop", event );
},
_setOption: function( key, value ) {
if ( key === "culture" || key === "numberFormat" ) {
var prevValue = this._parse( this.element.val() );
this.options[ key ] = value;
this.element.val( this._format( prevValue ) );
return;
}
if ( key === "max" || key === "min" || key === "step" ) {
if ( typeof value === "string" ) {
value = this._parse( value );
}
}
if ( key === "icons" ) {
this.buttons.first().find( ".ui-icon" )
.removeClass( this.options.icons.up )
.addClass( value.up );
this.buttons.last().find( ".ui-icon" )
.removeClass( this.options.icons.down )
.addClass( value.down );
}
this._super( key, value );
if ( key === "disabled" ) {
if ( value ) {
this.element.prop( "disabled", true );
this.buttons.button( "disable" );
} else {
this.element.prop( "disabled", false );
this.buttons.button( "enable" );
}
}
},
_setOptions: modifier(function( options ) {
this._super( options );
this._value( this.element.val() );
}),
_parse: function( val ) {
if ( typeof val === "string" && val !== "" ) {
val = window.Globalize && this.options.numberFormat ?
Globalize.parseFloat( val, 10, this.options.culture ) : +val;
}
return val === "" || isNaN( val ) ? null : val;
},
_format: function( value ) {
if ( value === "" ) {
return "";
}
return window.Globalize && this.options.numberFormat ?
Globalize.format( value, this.options.numberFormat, this.options.culture ) :
value;
},
_refresh: function() {
this.element.attr({
"aria-valuemin": this.options.min,
"aria-valuemax": this.options.max,
// TODO: what should we do with values that can't be parsed?
"aria-valuenow": this._parse( this.element.val() )
});
},
// update the value without triggering change
_value: function( value, allowAny ) {
var parsed;
if ( value !== "" ) {
parsed = this._parse( value );
if ( parsed !== null ) {
if ( !allowAny ) {
parsed = this._adjustValue( parsed );
}
value = this._format( parsed );
}
}
this.element.val( value );
this._refresh();
},
_destroy: function() {
this.element
.removeClass( "ui-spinner-input" )
.prop( "disabled", false )
.removeAttr( "autocomplete" )
.removeAttr( "role" )
.removeAttr( "aria-valuemin" )
.removeAttr( "aria-valuemax" )
.removeAttr( "aria-valuenow" );
this.uiSpinner.replaceWith( this.element );
},
stepUp: modifier(function( steps ) {
this._stepUp( steps );
}),
_stepUp: function( steps ) {
if ( this._start() ) {
this._spin( (steps || 1) * this.options.step );
this._stop();
}
},
stepDown: modifier(function( steps ) {
this._stepDown( steps );
}),
_stepDown: function( steps ) {
if ( this._start() ) {
this._spin( (steps || 1) * -this.options.step );
this._stop();
}
},
pageUp: modifier(function( pages ) {
this._stepUp( (pages || 1) * this.options.page );
}),
pageDown: modifier(function( pages ) {
this._stepDown( (pages || 1) * this.options.page );
}),
value: function( newVal ) {
if ( !arguments.length ) {
return this._parse( this.element.val() );
}
modifier( this._value ).call( this, newVal );
},
widget: function() {
return this.uiSpinner;
}
});
}( jQuery ) );
(function( $, undefined ) {
var tabId = 0,
rhash = /#.*$/;
function getNextTabId() {
return ++tabId;
}
function isLocal( anchor ) {
return anchor.hash.length > 1 &&
decodeURIComponent( anchor.href.replace( rhash, "" ) ) ===
decodeURIComponent( location.href.replace( rhash, "" ) );
}
$.widget( "ui.tabs", {
version: "1.10.3",
delay: 300,
options: {
active: null,
collapsible: false,
event: "click",
heightStyle: "content",
hide: null,
show: null,
// callbacks
activate: null,
beforeActivate: null,
beforeLoad: null,
load: null
},
_create: function() {
var that = this,
options = this.options;
this.running = false;
this.element
.addClass( "ui-tabs ui-widget ui-widget-content ui-corner-all" )
.toggleClass( "ui-tabs-collapsible", options.collapsible )
// Prevent users from focusing disabled tabs via click
.delegate( ".ui-tabs-nav > li", "mousedown" + this.eventNamespace, function( event ) {
if ( $( this ).is( ".ui-state-disabled" ) ) {
event.preventDefault();
}
})
// support: IE <9
// Preventing the default action in mousedown doesn't prevent IE
// from focusing the element, so if the anchor gets focused, blur.
// We don't have to worry about focusing the previously focused
// element since clicking on a non-focusable element should focus
// the body anyway.
.delegate( ".ui-tabs-anchor", "focus" + this.eventNamespace, function() {
if ( $( this ).closest( "li" ).is( ".ui-state-disabled" ) ) {
this.blur();
}
});
this._processTabs();
options.active = this._initialActive();
// Take disabling tabs via class attribute from HTML
// into account and update option properly.
if ( $.isArray( options.disabled ) ) {
options.disabled = $.unique( options.disabled.concat(
$.map( this.tabs.filter( ".ui-state-disabled" ), function( li ) {
return that.tabs.index( li );
})
) ).sort();
}
// check for length avoids error when initializing empty list
if ( this.options.active !== false && this.anchors.length ) {
this.active = this._findActive( options.active );
} else {
this.active = $();
}
this._refresh();
if ( this.active.length ) {
this.load( options.active );
}
},
_initialActive: function() {
var active = this.options.active,
collapsible = this.options.collapsible,
locationHash = location.hash.substring( 1 );
if ( active === null ) {
// check the fragment identifier in the URL
if ( locationHash ) {
this.tabs.each(function( i, tab ) {
if ( $( tab ).attr( "aria-controls" ) === locationHash ) {
active = i;
return false;
}
});
}
// check for a tab marked active via a class
if ( active === null ) {
active = this.tabs.index( this.tabs.filter( ".ui-tabs-active" ) );
}
// no active tab, set to false
if ( active === null || active === -1 ) {
active = this.tabs.length ? 0 : false;
}
}
// handle numbers: negative, out of range
if ( active !== false ) {
active = this.tabs.index( this.tabs.eq( active ) );
if ( active === -1 ) {
active = collapsible ? false : 0;
}
}
// don't allow collapsible: false and active: false
if ( !collapsible && active === false && this.anchors.length ) {
active = 0;
}
return active;
},
_getCreateEventData: function() {
return {
tab: this.active,
panel: !this.active.length ? $() : this._getPanelForTab( this.active )
};
},
_tabKeydown: function( event ) {
/*jshint maxcomplexity:15*/
var focusedTab = $( this.document[0].activeElement ).closest( "li" ),
selectedIndex = this.tabs.index( focusedTab ),
goingForward = true;
if ( this._handlePageNav( event ) ) {
return;
}
switch ( event.keyCode ) {
case $.ui.keyCode.RIGHT:
case $.ui.keyCode.DOWN:
selectedIndex++;
break;
case $.ui.keyCode.UP:
case $.ui.keyCode.LEFT:
goingForward = false;
selectedIndex--;
break;
case $.ui.keyCode.END:
selectedIndex = this.anchors.length - 1;
break;
case $.ui.keyCode.HOME:
selectedIndex = 0;
break;
case $.ui.keyCode.SPACE:
// Activate only, no collapsing
event.preventDefault();
clearTimeout( this.activating );
this._activate( selectedIndex );
return;
case $.ui.keyCode.ENTER:
// Toggle (cancel delayed activation, allow collapsing)
event.preventDefault();
clearTimeout( this.activating );
// Determine if we should collapse or activate
this._activate( selectedIndex === this.options.active ? false : selectedIndex );
return;
default:
return;
}
// Focus the appropriate tab, based on which key was pressed
event.preventDefault();
clearTimeout( this.activating );
selectedIndex = this._focusNextTab( selectedIndex, goingForward );
// Navigating with control key will prevent automatic activation
if ( !event.ctrlKey ) {
// Update aria-selected immediately so that AT think the tab is already selected.
// Otherwise AT may confuse the user by stating that they need to activate the tab,
// but the tab will already be activated by the time the announcement finishes.
focusedTab.attr( "aria-selected", "false" );
this.tabs.eq( selectedIndex ).attr( "aria-selected", "true" );
this.activating = this._delay(function() {
this.option( "active", selectedIndex );
}, this.delay );
}
},
_panelKeydown: function( event ) {
if ( this._handlePageNav( event ) ) {
return;
}
// Ctrl+up moves focus to the current tab
if ( event.ctrlKey && event.keyCode === $.ui.keyCode.UP ) {
event.preventDefault();
this.active.focus();
}
},
// Alt+page up/down moves focus to the previous/next tab (and activates)
_handlePageNav: function( event ) {
if ( event.altKey && event.keyCode === $.ui.keyCode.PAGE_UP ) {
this._activate( this._focusNextTab( this.options.active - 1, false ) );
return true;
}
if ( event.altKey && event.keyCode === $.ui.keyCode.PAGE_DOWN ) {
this._activate( this._focusNextTab( this.options.active + 1, true ) );
return true;
}
},
_findNextTab: function( index, goingForward ) {
var lastTabIndex = this.tabs.length - 1;
function constrain() {
if ( index > lastTabIndex ) {
index = 0;
}
if ( index < 0 ) {
index = lastTabIndex;
}
return index;
}
while ( $.inArray( constrain(), this.options.disabled ) !== -1 ) {
index = goingForward ? index + 1 : index - 1;
}
return index;
},
_focusNextTab: function( index, goingForward ) {
index = this._findNextTab( index, goingForward );
this.tabs.eq( index ).focus();
return index;
},
_setOption: function( key, value ) {
if ( key === "active" ) {
// _activate() will handle invalid values and update this.options
this._activate( value );
return;
}
if ( key === "disabled" ) {
// don't use the widget factory's disabled handling
this._setupDisabled( value );
return;
}
this._super( key, value);
if ( key === "collapsible" ) {
this.element.toggleClass( "ui-tabs-collapsible", value );
// Setting collapsible: false while collapsed; open first panel
if ( !value && this.options.active === false ) {
this._activate( 0 );
}
}
if ( key === "event" ) {
this._setupEvents( value );
}
if ( key === "heightStyle" ) {
this._setupHeightStyle( value );
}
},
_tabId: function( tab ) {
return tab.attr( "aria-controls" ) || "ui-tabs-" + getNextTabId();
},
_sanitizeSelector: function( hash ) {
return hash ? hash.replace( /[!"$%&'()*+,.\/:;<=>?@\[\]\^`{|}~]/g, "\\$&" ) : "";
},
refresh: function() {
var options = this.options,
lis = this.tablist.children( ":has(a[href])" );
// get disabled tabs from class attribute from HTML
// this will get converted to a boolean if needed in _refresh()
options.disabled = $.map( lis.filter( ".ui-state-disabled" ), function( tab ) {
return lis.index( tab );
});
this._processTabs();
// was collapsed or no tabs
if ( options.active === false || !this.anchors.length ) {
options.active = false;
this.active = $();
// was active, but active tab is gone
} else if ( this.active.length && !$.contains( this.tablist[ 0 ], this.active[ 0 ] ) ) {
// all remaining tabs are disabled
if ( this.tabs.length === options.disabled.length ) {
options.active = false;
this.active = $();
// activate previous tab
} else {
this._activate( this._findNextTab( Math.max( 0, options.active - 1 ), false ) );
}
// was active, active tab still exists
} else {
// make sure active index is correct
options.active = this.tabs.index( this.active );
}
this._refresh();
},
_refresh: function() {
this._setupDisabled( this.options.disabled );
this._setupEvents( this.options.event );
this._setupHeightStyle( this.options.heightStyle );
this.tabs.not( this.active ).attr({
"aria-selected": "false",
tabIndex: -1
});
this.panels.not( this._getPanelForTab( this.active ) )
.hide()
.attr({
"aria-expanded": "false",
"aria-hidden": "true"
});
// Make sure one tab is in the tab order
if ( !this.active.length ) {
this.tabs.eq( 0 ).attr( "tabIndex", 0 );
} else {
this.active
.addClass( "ui-tabs-active ui-state-active" )
.attr({
"aria-selected": "true",
tabIndex: 0
});
this._getPanelForTab( this.active )
.show()
.attr({
"aria-expanded": "true",
"aria-hidden": "false"
});
}
},
_processTabs: function() {
var that = this;
this.tablist = this._getList()
.addClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" )
.attr( "role", "tablist" );
this.tabs = this.tablist.find( "> li:has(a[href])" )
.addClass( "ui-state-default ui-corner-top" )
.attr({
role: "tab",
tabIndex: -1
});
this.anchors = this.tabs.map(function() {
return $( "a", this )[ 0 ];
})
.addClass( "ui-tabs-anchor" )
.attr({
role: "presentation",
tabIndex: -1
});
this.panels = $();
this.anchors.each(function( i, anchor ) {
var selector, panel, panelId,
anchorId = $( anchor ).uniqueId().attr( "id" ),
tab = $( anchor ).closest( "li" ),
originalAriaControls = tab.attr( "aria-controls" );
// inline tab
if ( isLocal( anchor ) ) {
selector = anchor.hash;
panel = that.element.find( that._sanitizeSelector( selector ) );
// remote tab
} else {
panelId = that._tabId( tab );
selector = "#" + panelId;
panel = that.element.find( selector );
if ( !panel.length ) {
panel = that._createPanel( panelId );
panel.insertAfter( that.panels[ i - 1 ] || that.tablist );
}
panel.attr( "aria-live", "polite" );
}
if ( panel.length) {
that.panels = that.panels.add( panel );
}
if ( originalAriaControls ) {
tab.data( "ui-tabs-aria-controls", originalAriaControls );
}
tab.attr({
"aria-controls": selector.substring( 1 ),
"aria-labelledby": anchorId
});
panel.attr( "aria-labelledby", anchorId );
});
this.panels
.addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" )
.attr( "role", "tabpanel" );
},
// allow overriding how to find the list for rare usage scenarios (#7715)
_getList: function() {<|fim▁hole|>
_createPanel: function( id ) {
return $( "<div>" )
.attr( "id", id )
.addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" )
.data( "ui-tabs-destroy", true );
},
_setupDisabled: function( disabled ) {
if ( $.isArray( disabled ) ) {
if ( !disabled.length ) {
disabled = false;
} else if ( disabled.length === this.anchors.length ) {
disabled = true;
}
}
// disable tabs
for ( var i = 0, li; ( li = this.tabs[ i ] ); i++ ) {
if ( disabled === true || $.inArray( i, disabled ) !== -1 ) {
$( li )
.addClass( "ui-state-disabled" )
.attr( "aria-disabled", "true" );
} else {
$( li )
.removeClass( "ui-state-disabled" )
.removeAttr( "aria-disabled" );
}
}
this.options.disabled = disabled;
},
_setupEvents: function( event ) {
var events = {
click: function( event ) {
event.preventDefault();
}
};
if ( event ) {
$.each( event.split(" "), function( index, eventName ) {
events[ eventName ] = "_eventHandler";
});
}
this._off( this.anchors.add( this.tabs ).add( this.panels ) );
this._on( this.anchors, events );
this._on( this.tabs, { keydown: "_tabKeydown" } );
this._on( this.panels, { keydown: "_panelKeydown" } );
this._focusable( this.tabs );
this._hoverable( this.tabs );
},
_setupHeightStyle: function( heightStyle ) {
var maxHeight,
parent = this.element.parent();
if ( heightStyle === "fill" ) {
maxHeight = parent.height();
maxHeight -= this.element.outerHeight() - this.element.height();
this.element.siblings( ":visible" ).each(function() {
var elem = $( this ),
position = elem.css( "position" );
if ( position === "absolute" || position === "fixed" ) {
return;
}
maxHeight -= elem.outerHeight( true );
});
this.element.children().not( this.panels ).each(function() {
maxHeight -= $( this ).outerHeight( true );
});
this.panels.each(function() {
$( this ).height( Math.max( 0, maxHeight -
$( this ).innerHeight() + $( this ).height() ) );
})
.css( "overflow", "auto" );
} else if ( heightStyle === "auto" ) {
maxHeight = 0;
this.panels.each(function() {
maxHeight = Math.max( maxHeight, $( this ).height( "" ).height() );
}).height( maxHeight );
}
},
_eventHandler: function( event ) {
var options = this.options,
active = this.active,
anchor = $( event.currentTarget ),
tab = anchor.closest( "li" ),
clickedIsActive = tab[ 0 ] === active[ 0 ],
collapsing = clickedIsActive && options.collapsible,
toShow = collapsing ? $() : this._getPanelForTab( tab ),
toHide = !active.length ? $() : this._getPanelForTab( active ),
eventData = {
oldTab: active,
oldPanel: toHide,
newTab: collapsing ? $() : tab,
newPanel: toShow
};
event.preventDefault();
if ( tab.hasClass( "ui-state-disabled" ) ||
// tab is already loading
tab.hasClass( "ui-tabs-loading" ) ||
// can't switch durning an animation
this.running ||
// click on active header, but not collapsible
( clickedIsActive && !options.collapsible ) ||
// allow canceling activation
( this._trigger( "beforeActivate", event, eventData ) === false ) ) {
return;
}
options.active = collapsing ? false : this.tabs.index( tab );
this.active = clickedIsActive ? $() : tab;
if ( this.xhr ) {
this.xhr.abort();
}
if ( !toHide.length && !toShow.length ) {
$.error( "jQuery UI Tabs: Mismatching fragment identifier." );
}
if ( toShow.length ) {
this.load( this.tabs.index( tab ), event );
}
this._toggle( event, eventData );
},
// handles show/hide for selecting tabs
_toggle: function( event, eventData ) {
var that = this,
toShow = eventData.newPanel,
toHide = eventData.oldPanel;
this.running = true;
function complete() {
that.running = false;
that._trigger( "activate", event, eventData );
}
function show() {
eventData.newTab.closest( "li" ).addClass( "ui-tabs-active ui-state-active" );
if ( toShow.length && that.options.show ) {
that._show( toShow, that.options.show, complete );
} else {
toShow.show();
complete();
}
}
// start out by hiding, then showing, then completing
if ( toHide.length && this.options.hide ) {
this._hide( toHide, this.options.hide, function() {
eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" );
show();
});
} else {
eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" );
toHide.hide();
show();
}
toHide.attr({
"aria-expanded": "false",
"aria-hidden": "true"
});
eventData.oldTab.attr( "aria-selected", "false" );
// If we're switching tabs, remove the old tab from the tab order.
// If we're opening from collapsed state, remove the previous tab from the tab order.
// If we're collapsing, then keep the collapsing tab in the tab order.
if ( toShow.length && toHide.length ) {
eventData.oldTab.attr( "tabIndex", -1 );
} else if ( toShow.length ) {
this.tabs.filter(function() {
return $( this ).attr( "tabIndex" ) === 0;
})
.attr( "tabIndex", -1 );
}
toShow.attr({
"aria-expanded": "true",
"aria-hidden": "false"
});
eventData.newTab.attr({
"aria-selected": "true",
tabIndex: 0
});
},
_activate: function( index ) {
var anchor,
active = this._findActive( index );
// trying to activate the already active panel
if ( active[ 0 ] === this.active[ 0 ] ) {
return;
}
// trying to collapse, simulate a click on the current active header
if ( !active.length ) {
active = this.active;
}
anchor = active.find( ".ui-tabs-anchor" )[ 0 ];
this._eventHandler({
target: anchor,
currentTarget: anchor,
preventDefault: $.noop
});
},
_findActive: function( index ) {
return index === false ? $() : this.tabs.eq( index );
},
_getIndex: function( index ) {
// meta-function to give users option to provide a href string instead of a numerical index.
if ( typeof index === "string" ) {
index = this.anchors.index( this.anchors.filter( "[href$='" + index + "']" ) );
}
return index;
},
_destroy: function() {
if ( this.xhr ) {
this.xhr.abort();
}
this.element.removeClass( "ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible" );
this.tablist
.removeClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" )
.removeAttr( "role" );
this.anchors
.removeClass( "ui-tabs-anchor" )
.removeAttr( "role" )
.removeAttr( "tabIndex" )
.removeUniqueId();
this.tabs.add( this.panels ).each(function() {
if ( $.data( this, "ui-tabs-destroy" ) ) {
$( this ).remove();
} else {
$( this )
.removeClass( "ui-state-default ui-state-active ui-state-disabled " +
"ui-corner-top ui-corner-bottom ui-widget-content ui-tabs-active ui-tabs-panel" )
.removeAttr( "tabIndex" )
.removeAttr( "aria-live" )
.removeAttr( "aria-busy" )
.removeAttr( "aria-selected" )
.removeAttr( "aria-labelledby" )
.removeAttr( "aria-hidden" )
.removeAttr( "aria-expanded" )
.removeAttr( "role" );
}
});
this.tabs.each(function() {
var li = $( this ),
prev = li.data( "ui-tabs-aria-controls" );
if ( prev ) {
li
.attr( "aria-controls", prev )
.removeData( "ui-tabs-aria-controls" );
} else {
li.removeAttr( "aria-controls" );
}
});
this.panels.show();
if ( this.options.heightStyle !== "content" ) {
this.panels.css( "height", "" );
}
},
enable: function( index ) {
var disabled = this.options.disabled;
if ( disabled === false ) {
return;
}
if ( index === undefined ) {
disabled = false;
} else {
index = this._getIndex( index );
if ( $.isArray( disabled ) ) {
disabled = $.map( disabled, function( num ) {
return num !== index ? num : null;
});
} else {
disabled = $.map( this.tabs, function( li, num ) {
return num !== index ? num : null;
});
}
}
this._setupDisabled( disabled );
},
disable: function( index ) {
var disabled = this.options.disabled;
if ( disabled === true ) {
return;
}
if ( index === undefined ) {
disabled = true;
} else {
index = this._getIndex( index );
if ( $.inArray( index, disabled ) !== -1 ) {
return;
}
if ( $.isArray( disabled ) ) {
disabled = $.merge( [ index ], disabled ).sort();
} else {
disabled = [ index ];
}
}
this._setupDisabled( disabled );
},
load: function( index, event ) {
index = this._getIndex( index );
var that = this,
tab = this.tabs.eq( index ),
anchor = tab.find( ".ui-tabs-anchor" ),
panel = this._getPanelForTab( tab ),
eventData = {
tab: tab,
panel: panel
};
// not remote
if ( isLocal( anchor[ 0 ] ) ) {
return;
}
this.xhr = $.ajax( this._ajaxSettings( anchor, event, eventData ) );
// support: jQuery <1.8
// jQuery <1.8 returns false if the request is canceled in beforeSend,
// but as of 1.8, $.ajax() always returns a jqXHR object.
if ( this.xhr && this.xhr.statusText !== "canceled" ) {
tab.addClass( "ui-tabs-loading" );
panel.attr( "aria-busy", "true" );
this.xhr
.success(function( response ) {
// support: jQuery <1.8
// http://bugs.jquery.com/ticket/11778
setTimeout(function() {
panel.html( response );
that._trigger( "load", event, eventData );
}, 1 );
})
.complete(function( jqXHR, status ) {
// support: jQuery <1.8
// http://bugs.jquery.com/ticket/11778
setTimeout(function() {
if ( status === "abort" ) {
that.panels.stop( false, true );
}
tab.removeClass( "ui-tabs-loading" );
panel.removeAttr( "aria-busy" );
if ( jqXHR === that.xhr ) {
delete that.xhr;
}
}, 1 );
});
}
},
_ajaxSettings: function( anchor, event, eventData ) {
var that = this;
return {
url: anchor.attr( "href" ),
beforeSend: function( jqXHR, settings ) {
return that._trigger( "beforeLoad", event,
$.extend( { jqXHR : jqXHR, ajaxSettings: settings }, eventData ) );
}
};
},
_getPanelForTab: function( tab ) {
var id = $( tab ).attr( "aria-controls" );
return this.element.find( this._sanitizeSelector( "#" + id ) );
}
});
})( jQuery );
(function( $ ) {
var increments = 0;
function addDescribedBy( elem, id ) {
var describedby = (elem.attr( "aria-describedby" ) || "").split( /\s+/ );
describedby.push( id );
elem
.data( "ui-tooltip-id", id )
.attr( "aria-describedby", $.trim( describedby.join( " " ) ) );
}
function removeDescribedBy( elem ) {
var id = elem.data( "ui-tooltip-id" ),
describedby = (elem.attr( "aria-describedby" ) || "").split( /\s+/ ),
index = $.inArray( id, describedby );
if ( index !== -1 ) {
describedby.splice( index, 1 );
}
elem.removeData( "ui-tooltip-id" );
describedby = $.trim( describedby.join( " " ) );
if ( describedby ) {
elem.attr( "aria-describedby", describedby );
} else {
elem.removeAttr( "aria-describedby" );
}
}
$.widget( "ui.tooltip", {
version: "1.10.3",
options: {
content: function() {
// support: IE<9, Opera in jQuery <1.7
// .text() can't accept undefined, so coerce to a string
var title = $( this ).attr( "title" ) || "";
// Escape title, since we're going from an attribute to raw HTML
return $( "<a>" ).text( title ).html();
},
hide: true,
// Disabled elements have inconsistent behavior across browsers (#8661)
items: "[title]:not([disabled])",
position: {
my: "left top+15",
at: "left bottom",
collision: "flipfit flip"
},
show: true,
tooltipClass: null,
track: false,
// callbacks
close: null,
open: null
},
_create: function() {
this._on({
mouseover: "open",
focusin: "open"
});
// IDs of generated tooltips, needed for destroy
this.tooltips = {};
// IDs of parent tooltips where we removed the title attribute
this.parents = {};
if ( this.options.disabled ) {
this._disable();
}
},
_setOption: function( key, value ) {
var that = this;
if ( key === "disabled" ) {
this[ value ? "_disable" : "_enable" ]();
this.options[ key ] = value;
// disable element style changes
return;
}
this._super( key, value );
if ( key === "content" ) {
$.each( this.tooltips, function( id, element ) {
that._updateContent( element );
});
}
},
_disable: function() {
var that = this;
// close open tooltips
$.each( this.tooltips, function( id, element ) {
var event = $.Event( "blur" );
event.target = event.currentTarget = element[0];
that.close( event, true );
});
// remove title attributes to prevent native tooltips
this.element.find( this.options.items ).addBack().each(function() {
var element = $( this );
if ( element.is( "[title]" ) ) {
element
.data( "ui-tooltip-title", element.attr( "title" ) )
.attr( "title", "" );
}
});
},
_enable: function() {
// restore title attributes
this.element.find( this.options.items ).addBack().each(function() {
var element = $( this );
if ( element.data( "ui-tooltip-title" ) ) {
element.attr( "title", element.data( "ui-tooltip-title" ) );
}
});
},
open: function( event ) {
var that = this,
target = $( event ? event.target : this.element )
// we need closest here due to mouseover bubbling,
// but always pointing at the same event target
.closest( this.options.items );
// No element to show a tooltip for or the tooltip is already open
if ( !target.length || target.data( "ui-tooltip-id" ) ) {
return;
}
if ( target.attr( "title" ) ) {
target.data( "ui-tooltip-title", target.attr( "title" ) );
}
target.data( "ui-tooltip-open", true );
// kill parent tooltips, custom or native, for hover
if ( event && event.type === "mouseover" ) {
target.parents().each(function() {
var parent = $( this ),
blurEvent;
if ( parent.data( "ui-tooltip-open" ) ) {
blurEvent = $.Event( "blur" );
blurEvent.target = blurEvent.currentTarget = this;
that.close( blurEvent, true );
}
if ( parent.attr( "title" ) ) {
parent.uniqueId();
that.parents[ this.id ] = {
element: this,
title: parent.attr( "title" )
};
parent.attr( "title", "" );
}
});
}
this._updateContent( target, event );
},
_updateContent: function( target, event ) {
var content,
contentOption = this.options.content,
that = this,
eventType = event ? event.type : null;
if ( typeof contentOption === "string" ) {
return this._open( event, target, contentOption );
}
content = contentOption.call( target[0], function( response ) {
// ignore async response if tooltip was closed already
if ( !target.data( "ui-tooltip-open" ) ) {
return;
}
// IE may instantly serve a cached response for ajax requests
// delay this call to _open so the other call to _open runs first
that._delay(function() {
// jQuery creates a special event for focusin when it doesn't
// exist natively. To improve performance, the native event
// object is reused and the type is changed. Therefore, we can't
// rely on the type being correct after the event finished
// bubbling, so we set it back to the previous value. (#8740)
if ( event ) {
event.type = eventType;
}
this._open( event, target, response );
});
});
if ( content ) {
this._open( event, target, content );
}
},
_open: function( event, target, content ) {
var tooltip, events, delayedShow,
positionOption = $.extend( {}, this.options.position );
if ( !content ) {
return;
}
// Content can be updated multiple times. If the tooltip already
// exists, then just update the content and bail.
tooltip = this._find( target );
if ( tooltip.length ) {
tooltip.find( ".ui-tooltip-content" ).html( content );
return;
}
// if we have a title, clear it to prevent the native tooltip
// we have to check first to avoid defining a title if none exists
// (we don't want to cause an element to start matching [title])
//
// We use removeAttr only for key events, to allow IE to export the correct
// accessible attributes. For mouse events, set to empty string to avoid
// native tooltip showing up (happens only when removing inside mouseover).
if ( target.is( "[title]" ) ) {
if ( event && event.type === "mouseover" ) {
target.attr( "title", "" );
} else {
target.removeAttr( "title" );
}
}
tooltip = this._tooltip( target );
addDescribedBy( target, tooltip.attr( "id" ) );
tooltip.find( ".ui-tooltip-content" ).html( content );
function position( event ) {
positionOption.of = event;
if ( tooltip.is( ":hidden" ) ) {
return;
}
tooltip.position( positionOption );
}
if ( this.options.track && event && /^mouse/.test( event.type ) ) {
this._on( this.document, {
mousemove: position
});
// trigger once to override element-relative positioning
position( event );
} else {
tooltip.position( $.extend({
of: target
}, this.options.position ) );
}
tooltip.hide();
this._show( tooltip, this.options.show );
// Handle tracking tooltips that are shown with a delay (#8644). As soon
// as the tooltip is visible, position the tooltip using the most recent
// event.
if ( this.options.show && this.options.show.delay ) {
delayedShow = this.delayedShow = setInterval(function() {
if ( tooltip.is( ":visible" ) ) {
position( positionOption.of );
clearInterval( delayedShow );
}
}, $.fx.interval );
}
this._trigger( "open", event, { tooltip: tooltip } );
events = {
keyup: function( event ) {
if ( event.keyCode === $.ui.keyCode.ESCAPE ) {
var fakeEvent = $.Event(event);
fakeEvent.currentTarget = target[0];
this.close( fakeEvent, true );
}
},
remove: function() {
this._removeTooltip( tooltip );
}
};
if ( !event || event.type === "mouseover" ) {
events.mouseleave = "close";
}
if ( !event || event.type === "focusin" ) {
events.focusout = "close";
}
this._on( true, target, events );
},
close: function( event ) {
var that = this,
target = $( event ? event.currentTarget : this.element ),
tooltip = this._find( target );
// disabling closes the tooltip, so we need to track when we're closing
// to avoid an infinite loop in case the tooltip becomes disabled on close
if ( this.closing ) {
return;
}
// Clear the interval for delayed tracking tooltips
clearInterval( this.delayedShow );
// only set title if we had one before (see comment in _open())
if ( target.data( "ui-tooltip-title" ) ) {
target.attr( "title", target.data( "ui-tooltip-title" ) );
}
removeDescribedBy( target );
tooltip.stop( true );
this._hide( tooltip, this.options.hide, function() {
that._removeTooltip( $( this ) );
});
target.removeData( "ui-tooltip-open" );
this._off( target, "mouseleave focusout keyup" );
// Remove 'remove' binding only on delegated targets
if ( target[0] !== this.element[0] ) {
this._off( target, "remove" );
}
this._off( this.document, "mousemove" );
if ( event && event.type === "mouseleave" ) {
$.each( this.parents, function( id, parent ) {
$( parent.element ).attr( "title", parent.title );
delete that.parents[ id ];
});
}
this.closing = true;
this._trigger( "close", event, { tooltip: tooltip } );
this.closing = false;
},
_tooltip: function( element ) {
var id = "ui-tooltip-" + increments++,
tooltip = $( "<div>" )
.attr({
id: id,
role: "tooltip"
})
.addClass( "ui-tooltip ui-widget ui-corner-all ui-widget-content " +
( this.options.tooltipClass || "" ) );
$( "<div>" )
.addClass( "ui-tooltip-content" )
.appendTo( tooltip );
tooltip.appendTo( this.document[0].body );
this.tooltips[ id ] = element;
return tooltip;
},
_find: function( target ) {
var id = target.data( "ui-tooltip-id" );
return id ? $( "#" + id ) : $();
},
_removeTooltip: function( tooltip ) {
tooltip.remove();
delete this.tooltips[ tooltip.attr( "id" ) ];
},
_destroy: function() {
var that = this;
// close open tooltips
$.each( this.tooltips, function( id, element ) {
// Delegate to close method to handle common cleanup
var event = $.Event( "blur" );
event.target = event.currentTarget = element[0];
that.close( event, true );
// Remove immediately; destroying an open tooltip doesn't use the
// hide animation
$( "#" + id ).remove();
// Restore the title
if ( element.data( "ui-tooltip-title" ) ) {
element.attr( "title", element.data( "ui-tooltip-title" ) );
element.removeData( "ui-tooltip-title" );
}
});
}
});
}( jQuery ) );<|fim▁end|> | return this.element.find( "ol,ul" ).eq( 0 );
}, |
<|file_name|>test_run_info.py<|end_file_name|><|fim▁begin|>from unittest import TestCase
from micall.drivers.run_info import RunInfo
from micall.drivers.sample import Sample
from micall.drivers.sample_group import SampleGroup
class RunInfoTest(TestCase):
def test_get_all_samples(self):<|fim▁hole|> run_info = RunInfo(
sample_groups=[SampleGroup(Sample(fastq1='1a_R1_001.fastq'),
Sample(fastq1='1b_R1_001.fastq')),
SampleGroup(Sample(fastq1='2_R1_001.fastq'))])
fastq_paths = [sample.fastq1 for sample in run_info.get_all_samples()]
self.assertEqual(expected_fastq_paths, fastq_paths)<|fim▁end|> | expected_fastq_paths = ['1a_R1_001.fastq',
'1b_R1_001.fastq',
'2_R1_001.fastq']
|
<|file_name|>app.e2e-spec.ts<|end_file_name|><|fim▁begin|>import { AppPage } from './app.po';
import { browser, logging } from 'protractor';
describe('workspace-project App', () => {
let page: AppPage;
beforeEach(() => {
page = new AppPage();
});
it('should display welcome message', () => {
page.navigateTo();
expect(page.getTitleText()).toEqual('www app is running!');
});
afterEach(async () => {
// Assert that there are no errors emitted from the browser
const logs = await browser.manage().logs().get(logging.Type.BROWSER);
expect(logs).not.toContain(jasmine.objectContaining({
level: logging.Level.SEVERE,<|fim▁hole|> } as logging.Entry));
});
});<|fim▁end|> | |
<|file_name|>DependencyInjectionAspectSupport.java<|end_file_name|><|fim▁begin|>/*
* Copyright 2002-2004 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans.factory.support;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.propertyeditors.ClassEditor;
/**
* Convenient superclass for aspects/persistence API
* configuration classes that should be able to autowire
* objects into a factory.
* <p>
* There are two ways of doing this: by mapping managed classes to prototype bean definitions
* in the factory; and by identifying classes of which instances should be autowired into the factory
* using the autowiring capables of AutowireCapableBeanFactory. If your managed class implements
* Spring lifecycle interfaces such as BeanFactoryAware or ApplicationContextAware, you must use the
* former method. With the latter method, only properties will be set, based on automatic satisfaction
* of dependencies from other beans (singleton or non-singleton) defined in the factory.
*
* <p>Could also use attributes on persistent classes to identify those eligible for autowiring, or
* even the prototype bean name.
* @see org.springframework.beans.factory.config.AutowireCapableBeanFactory
*
* @since 1.2
* @author Rod Johnson
*/
public abstract class DependencyInjectionAspectSupport implements InitializingBean, BeanFactoryAware {
protected final Log log = LogFactory.getLog(getClass());
private BeanFactory beanFactory;
private AutowireCapableBeanFactory aabf;
/**
* Map of Class to prototype name
*/
private Map managedClassToPrototypeMap = new HashMap();
private int defaultAutowireMode = 0;
/**
* List of Class
*/
protected List autowireByTypeClasses = new LinkedList();
/**
* List of Class
*/
private List autowireByNameClasses = new LinkedList();<|fim▁hole|>
/**
* @return Returns the autowireAll.
*/
public int getDefaultAutowireMode() {
return defaultAutowireMode;
}
/**
* Convenient property enabling autowiring of all instances. We might want this in an
* AspectJ aspect subclass, for example, relying on the AspectJ aspect to target the
* advice.
* @param autowireAll The autowireAll to set.
*/
public void setDefaultAutowireMode(int mode) {
if (mode != 0 && mode != AutowireCapableBeanFactory.AUTOWIRE_BY_NAME && mode != AbstractAutowireCapableBeanFactory.AUTOWIRE_BY_TYPE) {
throw new IllegalArgumentException("defaultAutowireMode must be a constant on AutowireCapableBeanFactory: AUTOWIRE_BY_TYPE or AUTOWIRE_BY_NAME");
}
defaultAutowireMode = mode;
}
public void setBeanFactory(BeanFactory beanFactory) {
this.beanFactory = beanFactory;
if (beanFactory instanceof AutowireCapableBeanFactory) {
this.aabf = (AutowireCapableBeanFactory) beanFactory;
}
}
/**
* Expose the owning bean factory to subclasses.
* Call only after initialization is complete.
* @return the owning bean factory. Cannot be null in valid use of this class.
*/
protected BeanFactory getBeanFactory() {
return this.beanFactory;
}
/**
* Set the Classes or class names that will be autowired by type
* @param autowireByTypeClasses list of Class or String classname
*/
public void setAutowireByTypeClasses(List autowireByTypeClasses) {
this.autowireByTypeClasses = convertListFromStringsToClassesIfNecessary(autowireByTypeClasses);
}
/**
* Return classes autowired by type
* @return list of Class
*/
public List getAutowireByTypeClasses() {
return autowireByTypeClasses;
}
public void addAutowireByTypeClass(Class clazz) {
this.autowireByTypeClasses.add(clazz);
}
/**
* Set the Classes or class names that will be autowired by name
* @param autowireByNameClasses list of Class or String classname
*/
public void setAutowireByNameClasses(List autowireByNameClasses) {
this.autowireByNameClasses = convertListFromStringsToClassesIfNecessary(autowireByNameClasses);
}
/**
* Return classes autowired by name
* @return list of Class
*/
public List getAutowireByNameClasses() {
return autowireByNameClasses;
}
public void addAutowireByNameClass(Class clazz) {
this.autowireByNameClasses.add(clazz);
}
/**
* Property key is class FQN, value is prototype name to use to obtain a new instance
* @param persistentClassBeanNames
*/
public void setManagedClassNamesToPrototypeNames(Properties persistentClassBeanNames) {
for (Iterator i = persistentClassBeanNames.keySet().iterator(); i.hasNext();) {
String className = (String) i.next();
String beanName = persistentClassBeanNames.getProperty(className);
addManagedClassToPrototypeMapping(classNameStringToClass(className), beanName);
}
}
/**
* Utility method to convert a collection from a list of String class name to a list of Classes
* @param l list which may contain Class or String
* @return list of resolved Class instances
*/
private List convertListFromStringsToClassesIfNecessary(List l) {
List classes = new ArrayList(l.size());
for (Iterator itr = l.iterator(); itr.hasNext();) {
Object next = itr.next();
if (next instanceof String) {
next = classNameStringToClass((String) next);
}
classes.add(next);
}
return classes;
}
/**
* Resolve this FQN
* @param className name of the class to resolve
* @return the Class
*/
private Class classNameStringToClass(String className) {
ClassEditor ce = new ClassEditor();
ce.setAsText(className);
return (Class) ce.getValue();
}
/**
* Return a Map of managed classes to prototype names
* @return Map with key being FQN and value prototype bean name to use for that class
*/
public Map getManagedClassToPrototypeNames() {
return this.managedClassToPrototypeMap;
}
public void addManagedClassToPrototypeMapping(Class clazz, String beanName) {
this.managedClassToPrototypeMap.put(clazz, beanName);
}
/**
* Check that mandatory properties were set
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
*/
public final void afterPropertiesSet() {
if (beanFactory == null) {
throw new IllegalArgumentException("beanFactory is required");
}
validateConfiguration();
validateProperties();
}
/**
* Subclasses should implement this to validate their configuration
*/
protected abstract void validateProperties();
protected void validateConfiguration() {
if (managedClassToPrototypeMap.isEmpty() && autowireByTypeClasses.isEmpty() && autowireByNameClasses.isEmpty() && defaultAutowireMode == 0) {
throw new IllegalArgumentException("Must set persistent class information: no managed classes configured and no autowiring configuration or defaults");
}
if ((defaultAutowireMode != 0 || !autowireByTypeClasses.isEmpty() || !autowireByNameClasses.isEmpty()) && aabf == null) {
throw new IllegalArgumentException("Autowiring supported only when running in an AutowireCapableBeanFactory");
}
// Check that all persistent classes map to prototype definitions
for (Iterator itr = managedClassToPrototypeMap.keySet().iterator(); itr.hasNext(); ) {
String beanName = (String) managedClassToPrototypeMap.get(itr.next());
if (!beanFactory.containsBean(beanName)) {
throw new IllegalArgumentException("No bean with name '" + beanName + "' defined in factory");
}
if (beanFactory.isSingleton(beanName)) {
throw new IllegalArgumentException("Bean name '" + beanName + "' must be a prototype, with singleton=\"false\"");
}
}
log.info("Validated " + managedClassToPrototypeMap.size() + " persistent class to prototype mappings");
}
/**
* Subclasses can call this to autowire properties on an existing object
* @param o
* @param autowireMode
* @throws BeansException
*/
protected void autowireProperties(Object o) throws NoAutowiringConfigurationForClassException, BeansException {
if (autowireByTypeClasses.contains(o.getClass())) {
aabf.autowireBeanProperties(o, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);
}
else if (autowireByNameClasses.contains(o.getClass())) {
aabf.autowireBeanProperties(o, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);
}
else if (defaultAutowireMode == AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE) {
aabf.autowireBeanProperties(o, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);
}
else if (defaultAutowireMode == AutowireCapableBeanFactory.AUTOWIRE_BY_NAME) {
aabf.autowireBeanProperties(o, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);
}
else {
throw new NoAutowiringConfigurationForClassException(o.getClass());
}
log.info("Autowired properties of persistent object with class=" + o.getClass().getName());
}
/**
* Subclasses will call this to create an object of the requisite class
* @param clazz
* @return
* @throws NoAutowiringConfigurationForClassException
*/
protected Object createAndConfigure(Class clazz) throws NoAutowiringConfigurationForClassException {
Object o = null;
String name = (String) managedClassToPrototypeMap.get(clazz);
if (name != null) {
o = beanFactory.getBean(name);
}
else {
// Fall back to trying autowiring
o = BeanUtils.instantiateClass(clazz);
autowireProperties(o);
}
if (o == null) {
throw new NoAutowiringConfigurationForClassException(clazz);
}
else {
return o;
}
}
protected class NoAutowiringConfigurationForClassException extends Exception {
public NoAutowiringConfigurationForClassException(Class clazz) {
super(clazz + " cannot be autowired");
}
}
}<|fim▁end|> | |
<|file_name|>manage.py<|end_file_name|><|fim▁begin|>#! /usr/bin/python2
# vim: set fileencoding=utf-8
from dateutil.parser import parse
from subprocess import check_output
from shutil import copy
import datetime
import sys
import os.path
import isoweek
DATE_FORMAT = '%Y%m%d'
START = """\documentclass[a4paper,oneside,draft,
notitlepage,11pt,svgnames]{scrreprt}<|fim▁hole|>\\begin{document}
"""
END = """
\printbibliography{}
\end{document}"""
MD_ACTIVITY = """# Activity {.unnumbered}
~~~~
"""
def create(date):
filename = date.strftime(DATE_FORMAT)
month = date.strftime('%B')
day = date.strftime('%d')
with open('template.tex', 'r') as t:
content = t.read()
content = content.replace('MONTH', month)
content = content.replace('DAY', day)
content = content.replace('content', filename+'.tex')
with open('current.tex', 'w') as f:
f.write(content)
copy('content.md', filename+'.md')
print('gvim {}'.format(filename+'.md'))
def week(date):
week = isoweek.Week.withdate(date)
name = 'w{}.tex'.format(week.week)
together([week.day(d) for d in range(7)], name)
def together(dates, name):
include = '\chapter{{{}}}\n\input{{{}}}'
res = [include.format(d.strftime('%B %d'),
d.strftime(DATE_FORMAT)) for d in dates
if os.path.exists(d.strftime(DATE_FORMAT)+'.tex')]
with open(name, 'w') as f:
f.write(START+'\n'.join(res)+END)
print('mv {} w.tex'.format(name))
def log(date):
cmd = "git whatchanged --since='{}' --pretty=format:'%B'"
cmd += "|sed '/^$/d'|sed 's/^.*\.\.\. //'"
since = date.replace(hour=4)
log = check_output(cmd.format(str(since)),
shell=True).strip()+"\n\n~~~~"
log = MD_ACTIVITY + log
print(log)
return log.replace('\t', ' ')
def since(date):
today = datetime.datetime.now()
name = date.strftime(DATE_FORMAT) + '_' + today.strftime(DATE_FORMAT)
days = [(date + datetime.timedelta(days=i)).date()
for i in range(1, (today-date).days+1)]
together(days, name+'.tex')
def finish(date):
today = datetime.datetime.now()
name = today.strftime(DATE_FORMAT)
with open(name+'.md', 'a') as f:
f.write(log(today))
cmd = 'pandoc -f markdown -t latex {}.md'
cmd += " |grep -v addcontent|sed -e '/^\\\\sec/ s/\\\\label.*$//'"
print(cmd.format(name))
latex = check_output(cmd.format(name), shell=True)
with open(name+'.tex', 'w') as today_log:
today_log.write(latex)
print('latexmk -pdf -pvc current')
print('mv current.pdf {}.pdf'.format(name))
if __name__ == '__main__':
date = datetime.datetime.now()
command = 'create'
if len(sys.argv) > 1:
command = sys.argv[1].strip()
if len(sys.argv) > 2:
date = parse(sys.argv[2], dayfirst=True)
globals()[command](date)<|fim▁end|> | \\newcommand{\workingDate}{\\today}
\input{preambule} |
<|file_name|>local.rs<|end_file_name|><|fim▁begin|>extern crate log;
extern crate tempfile;
use boxfuture::{BoxFuture, Boxable};
use fs::{self, GlobMatching, PathGlobs, PathStatGetter, Snapshot, StrictGlobMatching};
use futures::{future, Future, Stream};
use std::collections::BTreeSet;
use std::os::unix::process::ExitStatusExt;
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::sync::Arc;
use tokio_codec::{Decoder, FramedRead};
use tokio_process::{Child, CommandExt};
use super::{ExecuteProcessRequest, FallibleExecuteProcessResult};
use bytes::{Bytes, BytesMut};
pub struct CommandRunner {
store: fs::Store,
fs_pool: Arc<fs::ResettablePool>,
work_dir: PathBuf,
cleanup_local_dirs: bool,
}
impl CommandRunner {
pub fn new(
store: fs::Store,
fs_pool: Arc<fs::ResettablePool>,
work_dir: PathBuf,
cleanup_local_dirs: bool,
) -> CommandRunner {
CommandRunner {
store,
fs_pool,
work_dir,
cleanup_local_dirs,
}
}
fn outputs_stream_for_child(
mut child: Child,
) -> impl Stream<Item = ChildOutput, Error = String> + Send {
// TODO: This assumes that the Child was launched with stdout/stderr `Stdio::piped`.
let stdout_stream = FramedRead::new(child.stdout().take().unwrap(), IdentityDecoder)
.map(|bytes| ChildOutput::Stdout(bytes.into()));
let stderr_stream = FramedRead::new(child.stderr().take().unwrap(), IdentityDecoder)
.map(|bytes| ChildOutput::Stderr(bytes.into()));
let exit_stream = child.into_stream().map(|exit_status| {
ChildOutput::Exit(
exit_status
.code()
.or_else(|| exit_status.signal().map(|signal| -signal)),
)
});
stdout_stream
.select(stderr_stream)
.chain(exit_stream)
.map_err(|e| format!("Failed to consume process outputs: {:?}", e))
}
fn construct_output_snapshot(
store: fs::Store,
posix_fs: Arc<fs::PosixFS>,
output_file_paths: BTreeSet<PathBuf>,
output_dir_paths: BTreeSet<PathBuf>,
) -> BoxFuture<Snapshot, String> {
let output_dirs_glob_strings: Result<Vec<String>, String> = output_dir_paths
.into_iter()
.map(|p| {
p.into_os_string()
.into_string()
.map_err(|e| format!("Error stringifying output_directories: {:?}", e))
.map(|s| format!("{}/**", s))
})
.collect();
let output_dirs_future = posix_fs
.expand(try_future!(PathGlobs::create(
&try_future!(output_dirs_glob_strings),
&[],
StrictGlobMatching::Ignore,
)))
.map_err(|e| format!("Error stating output dirs: {}", e));
let output_files_future = posix_fs
.path_stats(output_file_paths.into_iter().collect())
.map_err(|e| format!("Error stating output files: {}", e));
output_files_future
.join(output_dirs_future)
.and_then(|(output_files_stats, output_dirs_stats)| {
let paths: Vec<_> = output_files_stats
.into_iter()
.chain(output_dirs_stats.into_iter().map(Some))
.collect();
fs::Snapshot::from_path_stats(
store.clone(),
fs::OneOffStoreFileByDigest::new(store, posix_fs),
paths.into_iter().filter_map(|v| v).collect(),
)
})
.to_boxed()
}
}
impl super::CommandRunner for CommandRunner {
///
/// Runs a command on this machine in the passed working directory.
///
fn run(&self, req: ExecuteProcessRequest) -> BoxFuture<FallibleExecuteProcessResult, String> {
let workdir = try_future!(
tempfile::Builder::new()
.prefix("process-execution")
.tempdir_in(&self.work_dir)
.map_err(|err| {
format!(
"Error making tempdir for local process execution: {:?}",
err
)
})
);
let workdir_path = workdir.path().to_owned();
let workdir_path2 = workdir_path.clone();
let store = self.store.clone();
let fs_pool = self.fs_pool.clone();
let env = req.env;
let output_file_paths = req.output_files;
let output_dir_paths = req.output_directories;
let cleanup_local_dirs = self.cleanup_local_dirs;
let argv = req.argv;
let req_description = req.description;
self
.store
.materialize_directory(workdir_path.clone(), req.input_files)
.and_then(move |()| {
Command::new(&argv[0])
.args(&argv[1..])
.current_dir(&workdir_path)
.env_clear()
// It would be really nice not to have to manually set PATH but this is sadly the only way
// to stop automatic PATH searching.
.env("PATH", "")
.envs(env)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn_async()
.map_err(|e| format!("Error launching process: {:?}", e))
})
.and_then(|child| {
// Consume the stream of ChildOutputs incrementally.
let init = (
BytesMut::with_capacity(8192),
BytesMut::with_capacity(8192),
None,
);
Self::outputs_stream_for_child(child).fold(
init,
|(mut stdout, mut stderr, mut exit_code), child_output| {
match child_output {
ChildOutput::Stdout(bytes) => stdout.extend_from_slice(&bytes),
ChildOutput::Stderr(bytes) => stderr.extend_from_slice(&bytes),
ChildOutput::Exit(code) => exit_code = code,
};
Ok((stdout, stderr, exit_code)) as Result<_, String>
},
)
})
.and_then(move |(stdout, stderr, exit_code)| {
let output_snapshot = if output_file_paths.is_empty() && output_dir_paths.is_empty() {
future::ok(fs::Snapshot::empty()).to_boxed()
} else {
// Use no ignore patterns, because we are looking for explicitly listed paths.
future::done(fs::PosixFS::new(workdir_path2, fs_pool, &[]))
.map_err(|err| {
format!(
"Error making posix_fs to fetch local process execution output files: {}",
err
)
})
.map(Arc::new)
.and_then(|posix_fs| {
CommandRunner::construct_output_snapshot(
store,
posix_fs,
output_file_paths,
output_dir_paths,
)
})
.to_boxed()
};
output_snapshot
.map(move |snapshot| FallibleExecuteProcessResult {
stdout: stdout.freeze(),
stderr: stderr.freeze(),
exit_code: exit_code.unwrap_or(-1),
output_directory: snapshot.digest,
})
.to_boxed()
})
.then(move |result| {
// Force workdir not to get dropped until after we've ingested the outputs
if !cleanup_local_dirs {
// This consumes the `TempDir` without deleting directory on the filesystem, meaning
// that the temporary directory will no longer be automatically deleted when dropped.
let preserved_path = workdir.into_path();
info!(
"preserved local process execution dir `{:?}` for {:?}",
preserved_path, req_description
);
} // Else, workdir gets dropped here
result
})
.to_boxed()
}
fn reset_prefork(&self) {
self.store.reset_prefork();
self.fs_pool.reset();
}
}
///
/// A Decoder that emits bytes immediately for any non-empty buffer.
///
struct IdentityDecoder;
impl Decoder for IdentityDecoder {
type Item = Bytes;
type Error = ::std::io::Error;
fn decode(&mut self, buf: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
if buf.len() == 0 {
Ok(None)
} else {
Ok(Some(buf.take().freeze()))
}
}
}
///
/// An enum of the possible outputs from a child process.
///
#[derive(Debug)]
enum ChildOutput {
Stdout(Bytes),
Stderr(Bytes),
Exit(Option<i32>),
}
#[cfg(test)]
mod tests {
extern crate tempfile;
extern crate testutil;
use super::super::CommandRunner as CommandRunnerTrait;
use super::{ExecuteProcessRequest, FallibleExecuteProcessResult};
use fs;
use futures::Future;
use std;
use std::collections::{BTreeMap, BTreeSet};
use std::env;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use tempfile::TempDir;
use testutil::data::{TestData, TestDirectory};
use testutil::{as_bytes, owned_string_vec};
#[test]
#[cfg(unix)]
fn stdout() {
let result = run_command_locally(ExecuteProcessRequest {
argv: owned_string_vec(&["/bin/echo", "-n", "foo"]),
env: BTreeMap::new(),
input_files: fs::EMPTY_DIGEST,
output_files: BTreeSet::new(),
output_directories: BTreeSet::new(),
timeout: Duration::from_millis(1000),
description: "echo foo".to_string(),
});
assert_eq!(
result.unwrap(),
FallibleExecuteProcessResult {
stdout: as_bytes("foo"),
stderr: as_bytes(""),
exit_code: 0,
output_directory: fs::EMPTY_DIGEST,
}
)
}
#[test]
#[cfg(unix)]
fn stdout_and_stderr_and_exit_code() {
let result = run_command_locally(ExecuteProcessRequest {
argv: owned_string_vec(&["/bin/bash", "-c", "echo -n foo ; echo >&2 -n bar ; exit 1"]),
env: BTreeMap::new(),
input_files: fs::EMPTY_DIGEST,
output_files: BTreeSet::new(),
output_directories: BTreeSet::new(),
timeout: Duration::from_millis(1000),
description: "echo foo and fail".to_string(),
});
assert_eq!(
result.unwrap(),
FallibleExecuteProcessResult {
stdout: as_bytes("foo"),
stderr: as_bytes("bar"),
exit_code: 1,
output_directory: fs::EMPTY_DIGEST,
}
)
}
#[test]
#[cfg(unix)]
fn capture_exit_code_signal() {
// Launch a process that kills itself with a signal.
let result = run_command_locally(ExecuteProcessRequest {
argv: owned_string_vec(&["/bin/bash", "-c", "kill $$"]),
env: BTreeMap::new(),
input_files: fs::EMPTY_DIGEST,
output_files: BTreeSet::new(),
output_directories: BTreeSet::new(),
timeout: Duration::from_millis(1000),
description: "kill self".to_string(),
});
assert_eq!(
result.unwrap(),
FallibleExecuteProcessResult {
stdout: as_bytes(""),
stderr: as_bytes(""),
exit_code: -15,
output_directory: fs::EMPTY_DIGEST,
}
)
}
#[test]
#[cfg(unix)]
fn env() {
let mut env: BTreeMap<String, String> = BTreeMap::new();
env.insert("FOO".to_string(), "foo".to_string());
env.insert("BAR".to_string(), "not foo".to_string());
let result = run_command_locally(ExecuteProcessRequest {
argv: owned_string_vec(&["/usr/bin/env"]),
env: env.clone(),
input_files: fs::EMPTY_DIGEST,
output_files: BTreeSet::new(),
output_directories: BTreeSet::new(),
timeout: Duration::from_millis(1000),
description: "run env".to_string(),
});
let stdout = String::from_utf8(result.unwrap().stdout.to_vec()).unwrap();
let got_env: BTreeMap<String, String> = stdout
.split("\n")
.filter(|line| !line.is_empty())
.map(|line| line.splitn(2, "="))
.map(|mut parts| {
(
parts.next().unwrap().to_string(),
parts.next().unwrap_or("").to_string(),
)
})
.filter(|x| x.0 != "PATH")
.collect();
assert_eq!(env, got_env);
}
#[test]
#[cfg(unix)]
fn env_is_deterministic() {
fn make_request() -> ExecuteProcessRequest {
let mut env = BTreeMap::new();
env.insert("FOO".to_string(), "foo".to_string());
env.insert("BAR".to_string(), "not foo".to_string());
ExecuteProcessRequest {
argv: owned_string_vec(&["/usr/bin/env"]),
env: env,
input_files: fs::EMPTY_DIGEST,
output_files: BTreeSet::new(),
output_directories: BTreeSet::new(),
timeout: Duration::from_millis(1000),
description: "run env".to_string(),
}
}
let result1 = run_command_locally(make_request());
let result2 = run_command_locally(make_request());
assert_eq!(result1.unwrap(), result2.unwrap());
}
#[test]
fn binary_not_found() {
run_command_locally(ExecuteProcessRequest {
argv: owned_string_vec(&["echo", "-n", "foo"]),
env: BTreeMap::new(),
input_files: fs::EMPTY_DIGEST,
output_files: BTreeSet::new(),
output_directories: BTreeSet::new(),
timeout: Duration::from_millis(1000),
description: "echo foo".to_string(),
}).expect_err("Want Err");
}
#[test]
fn output_files_none() {
let result = run_command_locally(ExecuteProcessRequest {
argv: owned_string_vec(&[
which("bash").expect("No bash on PATH").to_str().unwrap(),
"-c",
"exit 0",
]),
env: BTreeMap::new(),
input_files: fs::EMPTY_DIGEST,
output_files: BTreeSet::new(),
output_directories: BTreeSet::new(),
timeout: Duration::from_millis(1000),
description: "bash".to_string(),
});
assert_eq!(
result.unwrap(),
FallibleExecuteProcessResult {
stdout: as_bytes(""),
stderr: as_bytes(""),
exit_code: 0,
output_directory: fs::EMPTY_DIGEST,
}
)
}
#[test]
fn output_files_one() {
let result = run_command_locally(ExecuteProcessRequest {
argv: vec![
find_bash(),
"-c".to_owned(),
format!("echo -n {} > {}", TestData::roland().string(), "roland"),
],
env: BTreeMap::new(),
input_files: fs::EMPTY_DIGEST,
output_files: vec![PathBuf::from("roland")].into_iter().collect(),
output_directories: BTreeSet::new(),
timeout: Duration::from_millis(1000),
description: "bash".to_string(),
});
assert_eq!(
result.unwrap(),
FallibleExecuteProcessResult {
stdout: as_bytes(""),
stderr: as_bytes(""),
exit_code: 0,
output_directory: TestDirectory::containing_roland().digest(),
}
)
}
#[test]
fn output_dirs() {
let result = run_command_locally(ExecuteProcessRequest {
argv: vec![
find_bash(),
"-c".to_owned(),
format!(
"/bin/mkdir cats && echo -n {} > {} ; echo -n {} > treats",
TestData::roland().string(),
"cats/roland",
TestData::catnip().string()
),
],
env: BTreeMap::new(),
input_files: fs::EMPTY_DIGEST,
output_files: vec![PathBuf::from("treats")].into_iter().collect(),
output_directories: vec![PathBuf::from("cats")].into_iter().collect(),
timeout: Duration::from_millis(1000),
description: "bash".to_string(),
});
assert_eq!(
result.unwrap(),<|fim▁hole|> exit_code: 0,
output_directory: TestDirectory::recursive().digest(),
}
)
}
#[test]
fn output_files_many() {
let result = run_command_locally(ExecuteProcessRequest {
argv: vec![
find_bash(),
"-c".to_owned(),
format!(
"/bin/mkdir cats ; echo -n {} > cats/roland ; echo -n {} > treats",
TestData::roland().string(),
TestData::catnip().string()
),
],
env: BTreeMap::new(),
input_files: fs::EMPTY_DIGEST,
output_files: vec![PathBuf::from("cats/roland"), PathBuf::from("treats")]
.into_iter()
.collect(),
output_directories: BTreeSet::new(),
timeout: Duration::from_millis(1000),
description: "treats-roland".to_string(),
});
assert_eq!(
result.unwrap(),
FallibleExecuteProcessResult {
stdout: as_bytes(""),
stderr: as_bytes(""),
exit_code: 0,
output_directory: TestDirectory::recursive().digest(),
}
)
}
#[test]
fn output_files_execution_failure() {
let result = run_command_locally(ExecuteProcessRequest {
argv: vec![
find_bash(),
"-c".to_owned(),
format!(
"echo -n {} > {} ; exit 1",
TestData::roland().string(),
"roland"
),
],
env: BTreeMap::new(),
input_files: fs::EMPTY_DIGEST,
output_files: vec![PathBuf::from("roland")].into_iter().collect(),
output_directories: BTreeSet::new(),
timeout: Duration::from_millis(1000),
description: "echo foo".to_string(),
});
assert_eq!(
result.unwrap(),
FallibleExecuteProcessResult {
stdout: as_bytes(""),
stderr: as_bytes(""),
exit_code: 1,
output_directory: TestDirectory::containing_roland().digest(),
}
)
}
#[test]
fn output_files_partial_output() {
let result = run_command_locally(ExecuteProcessRequest {
argv: vec![
find_bash(),
"-c".to_owned(),
format!("echo -n {} > {}", TestData::roland().string(), "roland"),
],
env: BTreeMap::new(),
input_files: fs::EMPTY_DIGEST,
output_files: vec![PathBuf::from("roland"), PathBuf::from("susannah")]
.into_iter()
.collect(),
output_directories: BTreeSet::new(),
timeout: Duration::from_millis(1000),
description: "echo-roland".to_string(),
});
assert_eq!(
result.unwrap(),
FallibleExecuteProcessResult {
stdout: as_bytes(""),
stderr: as_bytes(""),
exit_code: 0,
output_directory: TestDirectory::containing_roland().digest(),
}
)
}
#[test]
fn test_directory_preservation() {
let preserved_work_tmpdir = TempDir::new().unwrap();
let preserved_work_root = preserved_work_tmpdir.path().to_owned();
let result = run_command_locally_in_dir(
ExecuteProcessRequest {
argv: vec![
find_bash(),
"-c".to_owned(),
format!("echo -n {} > {}", TestData::roland().string(), "roland"),
],
env: BTreeMap::new(),
input_files: fs::EMPTY_DIGEST,
output_files: vec![PathBuf::from("roland")].into_iter().collect(),
output_directories: BTreeSet::new(),
timeout: Duration::from_millis(1000),
description: "bash".to_string(),
},
preserved_work_root.clone(),
false,
);
result.unwrap();
assert!(preserved_work_root.exists());
// Collect all of the top level sub-dirs under our test workdir.
let subdirs = testutil::file::list_dir(&preserved_work_root);
assert_eq!(subdirs.len(), 1);
// Then look for a file like e.g. `/tmp/abc1234/process-execution7zt4pH/roland`
let rolands_path = preserved_work_root.join(&subdirs[0]).join("roland");
assert!(rolands_path.exists());
}
#[test]
fn test_directory_preservation_error() {
let preserved_work_tmpdir = TempDir::new().unwrap();
let preserved_work_root = preserved_work_tmpdir.path().to_owned();
assert!(preserved_work_root.exists());
assert_eq!(testutil::file::list_dir(&preserved_work_root).len(), 0);
run_command_locally_in_dir(
ExecuteProcessRequest {
argv: vec!["doesnotexist".to_owned()],
env: BTreeMap::new(),
input_files: fs::EMPTY_DIGEST,
output_files: BTreeSet::new(),
output_directories: BTreeSet::new(),
timeout: Duration::from_millis(1000),
description: "failing execution".to_string(),
},
preserved_work_root.clone(),
false,
).expect_err("Want process to fail");
assert!(preserved_work_root.exists());
// Collect all of the top level sub-dirs under our test workdir.
assert_eq!(testutil::file::list_dir(&preserved_work_root).len(), 1);
}
fn run_command_locally(
req: ExecuteProcessRequest,
) -> Result<FallibleExecuteProcessResult, String> {
let work_dir = TempDir::new().unwrap();
run_command_locally_in_dir_with_cleanup(req, work_dir.path().to_owned())
}
fn run_command_locally_in_dir_with_cleanup(
req: ExecuteProcessRequest,
dir: PathBuf,
) -> Result<FallibleExecuteProcessResult, String> {
run_command_locally_in_dir(req, dir, true)
}
fn run_command_locally_in_dir(
req: ExecuteProcessRequest,
dir: PathBuf,
cleanup: bool,
) -> Result<FallibleExecuteProcessResult, String> {
let store_dir = TempDir::new().unwrap();
let pool = Arc::new(fs::ResettablePool::new("test-pool-".to_owned()));
let store = fs::Store::local_only(store_dir.path(), pool.clone()).unwrap();
let runner = super::CommandRunner {
store: store,
fs_pool: pool,
work_dir: dir,
cleanup_local_dirs: cleanup,
};
runner.run(req).wait()
}
fn find_bash() -> String {
which("bash")
.expect("No bash on PATH")
.to_str()
.expect("Path to bash not unicode")
.to_owned()
}
fn which(executable: &str) -> Option<PathBuf> {
if let Some(paths) = env::var_os("PATH") {
for path in env::split_paths(&paths) {
let executable_path = path.join(executable);
if is_executable(&executable_path) {
return Some(executable_path);
}
}
}
None
}
fn is_executable(path: &Path) -> bool {
std::fs::metadata(path)
.map(|meta| meta.permissions().mode() & 0o100 == 0o100)
.unwrap_or(false)
}
}<|fim▁end|> | FallibleExecuteProcessResult {
stdout: as_bytes(""),
stderr: as_bytes(""), |
<|file_name|>generate_null_dataset.py<|end_file_name|><|fim▁begin|># This file is part of jacqq.py
# Copyright (C) 2015 Saman Jirjies - sjirjies(at)asu(dot)edu.
#
# 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/>.
import os
import csv
import argparse
# This script generates a null data set where all outputs are 0 when passed through Jacquez's Q.
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Generate a lattice of pentagon case-control points",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('x_size', type=int, help="Number of clusters to form in the x direction.")
parser.add_argument('y_size', type=int, help="Number of clusters to form in the y direction.")
parser.add_argument('histories_data', help="Location to write individuals' residential history.")
parser.add_argument('details_data', help="Location to write individuals' status data set.")
parser.add_argument('focus_data', help="Location to write focus data set")
args = parser.parse_args()
lattice_size_y = args.x_size
lattice_size_x = args.y_size
case_locations = []
for xi in range(0, lattice_size_x):
for yi in range(0, lattice_size_y):
case_locations.append((2+(10*xi), 2+(10*yi)))
focus_locations = []
for xi in range(0, lattice_size_x - 1):
for yi in range(0, lattice_size_y - 1):
focus_locations.append((7+(10*xi), 7+(10*yi)))
# Generate details data
csv_file = open(args.details_data, 'w')
try:
writer = csv.writer(csv_file)
writer.writerow(('ID', 'is_case'))
for case_index, case_point in enumerate(case_locations):
writer.writerow(('case_'+str(case_index+1), 1))
for control_name in ('A', 'B', 'C', 'D', 'E'):
writer.writerow(('control_'+str(case_index+1)+control_name, 0))
finally:
csv_file.close()
# Generate time series data
csv_file = open(args.histories_data, 'w')
try:
writer = csv.writer(csv_file)
writer.writerow(('ID', 'start_date', 'end_date', 'x', 'y'))
start_date = '20150101'
end_date = '20150102'
for id_index, case_point in enumerate(case_locations):
writer.writerow(('case_'+str(id_index+1), start_date, end_date, case_point[0], case_point[1]))
writer.writerow(('control_'+str(id_index+1)+'A', start_date, end_date, case_point[0], case_point[1]-2))
writer.writerow(('control_'+str(id_index+1)+'B', start_date, end_date, case_point[0]+2, case_point[1]))
writer.writerow(('control_'+str(id_index+1)+'C', start_date, end_date, case_point[0]+1, case_point[1]+1))
writer.writerow(('control_'+str(id_index+1)+'D', start_date, end_date, case_point[0]-1, case_point[1]+1))
writer.writerow(('control_'+str(id_index+1)+'E', start_date, end_date, case_point[0]-2, case_point[1]))
finally:
csv_file.close()
print("Finished generating null dataset")
# Generate focus data
csv_file = open(args.focus_data, 'w')
try:
writer = csv.writer(csv_file)
writer.writerow(('ID', 'start_date', 'end_date', 'x', 'y'))
start_date = '20150101'
end_date = '20150102'
for index, location in enumerate(focus_locations):
writer.writerow(('focus_' + str(index+1), start_date, end_date, location[0], location[1]))
finally:<|fim▁hole|><|fim▁end|> | csv_file.close() |
<|file_name|>bls_bft_replica_plenum.py<|end_file_name|><|fim▁begin|>from typing import Optional
from common.serializers.serialization import state_roots_serializer
from crypto.bls.bls_bft import BlsBft
from crypto.bls.bls_bft_replica import BlsBftReplica
from crypto.bls.bls_multi_signature import MultiSignature, MultiSignatureValue
from crypto.bls.indy_crypto.bls_crypto_indy_crypto import IndyCryptoBlsUtils
from plenum.common.constants import BLS_PREFIX, AUDIT_LEDGER_ID, TXN_PAYLOAD, \
TXN_PAYLOAD_DATA, AUDIT_TXN_LEDGER_ROOT, AUDIT_TXN_STATE_ROOT, AUDIT_TXN_PP_SEQ_NO
from plenum.common.messages.node_messages import PrePrepare, Prepare, Commit
from plenum.common.metrics_collector import MetricsCollector, NullMetricsCollector, measure_time, MetricsName
from plenum.common.types import f
from plenum.common.util import compare_3PC_keys
from plenum.server.consensus.utils import replica_name_to_node_name
from plenum.server.database_manager import DatabaseManager
from stp_core.common.log import getlogger
logger = getlogger()
class BlsBftReplicaPlenum(BlsBftReplica):
def __init__(self,
node_id,
bls_bft: BlsBft,
is_master,
database_manager: DatabaseManager,
metrics: MetricsCollector = NullMetricsCollector()):
super().__init__(bls_bft, is_master)
self._all_bls_latest_multi_sigs = None
self.node_id = node_id
self._database_manager = database_manager
self._all_signatures = {}<|fim▁hole|> # enable BLS for all ledgers
return True
# ----VALIDATE----
@measure_time(MetricsName.BLS_VALIDATE_PREPREPARE_TIME)
def validate_pre_prepare(self, pre_prepare: PrePrepare, sender):
if f.BLS_MULTI_SIGS.nm in pre_prepare and pre_prepare.blsMultiSigs:
multi_sigs = pre_prepare.blsMultiSigs
for sig in multi_sigs:
multi_sig = MultiSignature.from_list(*sig)
if not self._validate_multi_sig(multi_sig):
return BlsBftReplica.PPR_BLS_MULTISIG_WRONG
def validate_prepare(self, prepare: Prepare, sender):
pass
@measure_time(MetricsName.BLS_VALIDATE_COMMIT_TIME)
def validate_commit(self, commit: Commit, sender, pre_prepare: PrePrepare):
if f.BLS_SIGS.nm not in commit:
return
audit_txn = self._get_correct_audit_transaction(pre_prepare)
if not audit_txn:
return
audit_payload = audit_txn[TXN_PAYLOAD][TXN_PAYLOAD_DATA]
for lid, sig in commit.blsSigs.items():
lid = int(lid)
if lid not in audit_payload[AUDIT_TXN_STATE_ROOT] or lid not in audit_payload[AUDIT_TXN_LEDGER_ROOT]:
return BlsBftReplicaPlenum.CM_BLS_SIG_WRONG
if not self._validate_signature(sender, sig,
BlsBftReplicaPlenum._create_fake_pre_prepare_for_multi_sig(
lid,
audit_payload[AUDIT_TXN_STATE_ROOT][lid],
audit_payload[AUDIT_TXN_LEDGER_ROOT][lid],
pre_prepare
)):
return BlsBftReplicaPlenum.CM_BLS_SIG_WRONG
# ----CREATE/UPDATE----
@measure_time(MetricsName.BLS_UPDATE_PREPREPARE_TIME)
def update_pre_prepare(self, pre_prepare_params, ledger_id):
if not self._can_process_ledger(ledger_id):
return pre_prepare_params
if self._all_bls_latest_multi_sigs is not None:
# update BLS_MULTI_SIGS only (not BLS_MULTI_SIG)
# Pass None for backward compatibility
pre_prepare_params.append(None)
pre_prepare_params.append([val.as_list() for val in self._all_bls_latest_multi_sigs])
self._all_bls_latest_multi_sigs = None
return pre_prepare_params
def update_prepare(self, prepare_params, ledger_id):
# Send BLS signature in COMMITs only
return prepare_params
@measure_time(MetricsName.BLS_UPDATE_COMMIT_TIME)
def update_commit(self, commit_params, pre_prepare: PrePrepare):
ledger_id = pre_prepare.ledgerId
state_root_hash = pre_prepare.stateRootHash
if not self._can_process_ledger(ledger_id):
return commit_params
if not self._bls_bft.can_sign_bls():
logger.debug("{}{} can not sign COMMIT {} for state {}: No BLS keys"
.format(BLS_PREFIX, self, commit_params, state_root_hash))
return commit_params
# update BLS_SIGS only (not BLS_SIG)
# Use ' ' as BLS_SIG for backward-compatibility as BLS_SIG in COMMIT is optional but not Nullable
commit_params.append(' ')
last_audit_txn = self._get_correct_audit_transaction(pre_prepare)
if last_audit_txn:
res = {}
payload_data = last_audit_txn[TXN_PAYLOAD][TXN_PAYLOAD_DATA]
for ledger_id in payload_data[AUDIT_TXN_STATE_ROOT].keys():
fake_pp = BlsBftReplicaPlenum._create_fake_pre_prepare_for_multi_sig(
ledger_id,
payload_data[AUDIT_TXN_STATE_ROOT].get(ledger_id),
payload_data[AUDIT_TXN_LEDGER_ROOT].get(ledger_id),
pre_prepare
)
bls_signature = self._sign_state(fake_pp)
logger.debug("{}{} signed COMMIT {} for state {} with sig {}"
.format(BLS_PREFIX, self, commit_params, state_root_hash, bls_signature))
res[str(ledger_id)] = bls_signature
commit_params.append(res)
return commit_params
# ----PROCESS----
def process_pre_prepare(self, pre_prepare: PrePrepare, sender):
# does not matter which ledger id is current PPR for
# mult-sig is for domain ledger anyway
self._save_multi_sig_shared(pre_prepare)
def process_prepare(self, prepare: Prepare, sender):
pass
def process_commit(self, commit: Commit, sender):
key_3PC = (commit.viewNo, commit.ppSeqNo)
if f.BLS_SIGS.nm in commit and commit.blsSigs is not None:
if key_3PC not in self._all_signatures:
self._all_signatures[key_3PC] = {}
for ledger_id in commit.blsSigs.keys():
if ledger_id not in self._all_signatures[key_3PC]:
self._all_signatures[key_3PC][ledger_id] = {}
self._all_signatures[key_3PC][ledger_id][self.get_node_name(sender)] = commit.blsSigs[ledger_id]
def process_order(self, key, quorums, pre_prepare):
if not self._can_process_ledger(pre_prepare.ledgerId):
return
if not self._can_calculate_multi_sig(key, quorums):
return
# calculate signature always to keep master and non-master in sync
# but save on master only
all_bls_multi_sigs = self._calculate_all_multi_sigs(key, pre_prepare)
if not self._is_master:
return
if all_bls_multi_sigs:
for bls_multi_sig in all_bls_multi_sigs:
self._save_multi_sig_local(bls_multi_sig)
self._all_bls_latest_multi_sigs = all_bls_multi_sigs
# ----GC----
def gc(self, key_3PC):
keys_to_remove = []
for key in self._all_signatures.keys():
if compare_3PC_keys(key, key_3PC) >= 0:
keys_to_remove.append(key)
for key in keys_to_remove:
self._all_signatures.pop(key, None)
# ----MULT_SIG----
def _create_multi_sig_value_for_pre_prepare(self, pre_prepare: PrePrepare, pool_state_root_hash):
multi_sig_value = MultiSignatureValue(ledger_id=pre_prepare.ledgerId,
state_root_hash=pre_prepare.stateRootHash,
pool_state_root_hash=pool_state_root_hash,
txn_root_hash=pre_prepare.txnRootHash,
timestamp=pre_prepare.ppTime)
return multi_sig_value
def _validate_signature(self, sender, bls_sig, pre_prepare: PrePrepare):
pool_root_hash = self._get_pool_root_hash(pre_prepare, serialize=False)
sender_node = self.get_node_name(sender)
pk = self._bls_bft.bls_key_register.get_key_by_name(sender_node, pool_root_hash)
if not pk:
return False
pool_root_hash_ser = self._get_pool_root_hash(pre_prepare)
message = self._create_multi_sig_value_for_pre_prepare(pre_prepare,
pool_root_hash_ser)
result = self._bls_bft.bls_crypto_verifier.verify_sig(bls_sig, message.as_single_value(), pk)
if not result:
logger.info("Incorrect bls signature {} in commit for "
"{} public key: '{}' and message: '{}' from "
"pre-prepare: {}".format(bls_sig, sender,
IndyCryptoBlsUtils.bls_to_str(pk),
message, pre_prepare))
return result
def _validate_multi_sig(self, multi_sig: MultiSignature):
public_keys = []
pool_root_hash = self.state_root_serializer.deserialize(
multi_sig.value.pool_state_root_hash)
for node_name in multi_sig.participants:
bls_key = self._bls_bft.bls_key_register.get_key_by_name(node_name,
pool_root_hash)
# TODO: It's optional for now
if bls_key:
public_keys.append(bls_key)
value = multi_sig.value.as_single_value()
return self._bls_bft.bls_crypto_verifier.verify_multi_sig(multi_sig.signature,
value,
public_keys)
def _sign_state(self, pre_prepare: PrePrepare):
pool_root_hash = self._get_pool_root_hash(pre_prepare)
message = self._create_multi_sig_value_for_pre_prepare(pre_prepare,
pool_root_hash).as_single_value()
return self._bls_bft.bls_crypto_signer.sign(message)
def _can_calculate_multi_sig(self,
key_3PC,
quorums) -> bool:
if key_3PC not in self._all_signatures:
return False
sigs_for_request = self._all_signatures[key_3PC]
sigs_invalid = list(
filter(
lambda item: not quorums.bls_signatures.is_reached(len(list(item[1].values()))),
sigs_for_request.items()
)
)
if sigs_invalid:
for lid, sigs in sigs_invalid:
logger.debug(
'{}Can not create bls signatures for batch {}: '
'There are only {} signatures for ledger {}, '
'while {} required for multi_signature'.format(BLS_PREFIX,
key_3PC,
len(list(sigs.values())),
quorums.bls_signatures.value,
lid)
)
return False
return True
def _calculate_all_multi_sigs(self, key_3PC, pre_prepare) -> Optional[list]:
sigs_for_request = self._all_signatures.get(key_3PC)
res = []
if sigs_for_request:
for lid in sigs_for_request:
sig = sigs_for_request[lid]
audit_txn = self._get_correct_audit_transaction(pre_prepare)
if audit_txn:
audit_payload = audit_txn[TXN_PAYLOAD][TXN_PAYLOAD_DATA]
fake_pp = BlsBftReplicaPlenum. \
_create_fake_pre_prepare_for_multi_sig(int(lid),
audit_payload[AUDIT_TXN_STATE_ROOT][int(lid)],
audit_payload[AUDIT_TXN_LEDGER_ROOT][int(lid)],
pre_prepare)
res.append(self._calculate_single_multi_sig(sig, fake_pp))
return res
def _calculate_single_multi_sig(self, sigs_for_request, pre_prepare) -> Optional[MultiSignature]:
bls_signatures = list(sigs_for_request.values())
participants = list(sigs_for_request.keys())
sig = self._bls_bft.bls_crypto_verifier.create_multi_sig(bls_signatures)
pool_root_hash_ser = self._get_pool_root_hash(pre_prepare)
multi_sig_value = self._create_multi_sig_value_for_pre_prepare(pre_prepare,
pool_root_hash_ser)
return MultiSignature(signature=sig,
participants=participants,
value=multi_sig_value)
def _get_pool_root_hash(self, pre_prepare, serialize=True):
if f.POOL_STATE_ROOT_HASH.nm in pre_prepare:
pool_root_hash = self.state_root_serializer.deserialize(pre_prepare.poolStateRootHash)
pool_root_hash_ser = pre_prepare.poolStateRootHash
else:
pool_root_hash = self._bls_bft.bls_key_register.get_pool_root_hash_committed()
pool_root_hash_ser = self.state_root_serializer.serialize(bytes(pool_root_hash))
return pool_root_hash_ser if serialize else pool_root_hash
def _save_multi_sig_local(self,
multi_sig: MultiSignature):
self._bls_bft.bls_store.put(multi_sig)
logger.debug("{}{} saved multi signature {} for root {} (locally calculated)"
.format(BLS_PREFIX, self, multi_sig,
multi_sig.value.state_root_hash))
def _save_multi_sig_shared(self, pre_prepare: PrePrepare):
if f.BLS_MULTI_SIGS.nm not in pre_prepare or pre_prepare.blsMultiSigs is None:
return
multi_sigs = pre_prepare.blsMultiSigs
for sig in multi_sigs:
multi_sig = MultiSignature.from_list(*sig)
self._bls_bft.bls_store.put(multi_sig)
logger.debug("{}{} saved multi signature {} for root {} (calculated by Primary)"
.format(BLS_PREFIX, self, multi_sig,
multi_sig.value.state_root_hash))
def _get_correct_audit_transaction(self, pp: PrePrepare):
ledger = self._database_manager.get_ledger(AUDIT_LEDGER_ID)
if ledger is None:
return None
seqNo = ledger.uncommitted_size
for curSeqNo in reversed(range(1, seqNo + 1)):
txn = ledger.get_by_seq_no_uncommitted(curSeqNo)
if txn:
payload = txn[TXN_PAYLOAD][TXN_PAYLOAD_DATA]
if pp.ppSeqNo == payload[AUDIT_TXN_PP_SEQ_NO]:
return txn
return None
@staticmethod
def _create_fake_pre_prepare_for_multi_sig(lid, state_root_hash, txn_root_hash, pre_prepare):
params = [
pre_prepare.instId,
pre_prepare.viewNo,
pre_prepare.ppSeqNo,
pre_prepare.ppTime,
pre_prepare.reqIdr,
pre_prepare.discarded,
pre_prepare.digest,
# doing it to work around the ledgers that are not in plenum -- it will fail the validation of pre-prepare
1,
state_root_hash,
txn_root_hash,
pre_prepare.sub_seq_no,
pre_prepare.final,
pre_prepare.poolStateRootHash,
pre_prepare.auditTxnRootHash,
]
pp = PrePrepare(*params)
pp.ledgerId = lid
return pp
@staticmethod
def get_node_name(replica_name: str):
# TODO: Remove this wrapper
return replica_name_to_node_name(replica_name)
def __str__(self, *args, **kwargs):
return self.node_id<|fim▁end|> | self.state_root_serializer = state_roots_serializer
self.metrics = metrics
def _can_process_ledger(self, ledger_id): |
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>pub mod container;
pub mod content;<|fim▁hole|><|fim▁end|> | pub mod repository; |
<|file_name|>test_financial_move.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright 2017 KMEE
# Hendrix Costa <[email protected]>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from openerp.addons.financial.tests.financial_test_classes import \
FinancialTestCase
class ManualFinancialProcess(FinancialTestCase):
def setUp(self):
self.financial_model = self.env['financial.move']
super(ManualFinancialProcess, self).setUp()
def test_01_check_return_views(self):
"""Check if view is correctly called for python code"""
# test for len(financial.move) == 1
financial_move_id = self.financial_model.search([], limit=1)
action = financial_move_id.action_view_financial('2receive')
self.assertEqual(
action.get('display_name'),
'financial.move.debt.2receive.form (in financial)')
self.assertEqual(
action.get('res_id'), financial_move_id.id)
<|fim▁hole|> action.get('display_name'),
'financial.move.debt.2pay.form (in financial)')
self.assertEqual(
action.get('res_id'), financial_move_id.id)
# test for len(financial.move) > 1
financial_move_id = self.financial_model.search([], limit=2)
action = financial_move_id.action_view_financial('2pay')
self.assertEqual(action.get('domain')[0][2], financial_move_id.ids)
# test for len(financial.move) < 1
action = self.financial_model.action_view_financial('2pay')
self.assertEqual(action.get('type'), 'ir.actions.act_window_close')<|fim▁end|> | action = financial_move_id.action_view_financial('2pay')
self.assertEqual( |
<|file_name|>webpack.config.prod.js<|end_file_name|><|fim▁begin|>'use strict'
const path = require('path')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const ManifestPlugin = require('webpack-manifest-plugin')
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin')
const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin')
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin')
const paths = require('./paths')
const getClientEnvironment = require('./env')
// Webpack uses `publicPath` to determine where the app is being served from.
// It requires a trailing slash, or the file assets will get an incorrect path.
const publicPath = paths.servedPath
// Some apps do not use client-side routing with pushState.
// For these, "homepage" can be set to "." to enable relative asset paths.
const shouldUseRelativeAssetPaths = publicPath === './'
// `publicUrl` is just like `publicPath`, but we will provide it to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
// Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
const publicUrl = publicPath.slice(0, -1)
// Get environment variables to inject into our app.
const env = getClientEnvironment(publicUrl)
// Assert this just to be safe.
// Development builds of React are slow and not intended for production.
if (env.stringified['process.env'].NODE_ENV !== '"production"') {
throw new Error('Production builds must have NODE_ENV=production.')
}
// Note: defined here because it will be used more than once.
const cssFilename = 'static/css/[name].[contenthash:8].css'
// ExtractTextPlugin expects the build output to be flat.
// (See https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/27)
// However, our output is structured with css, js and media folders.
// To have this structure working with relative paths, we have to use custom options.
const extractTextPluginOptions = shouldUseRelativeAssetPaths
// Making sure that the publicPath goes back to to build folder.
? { publicPath: Array(cssFilename.split('/').length).join('../') }
: {}
// This is the production configuration.
// It compiles slowly and is focused on producing a fast and minimal bundle.
// The development configuration is different and lives in a separate file.
module.exports = {
// Don't attempt to continue if there are any errors.
bail: true,
// We generate sourcemaps in production. This is slow but gives good results.
// You can exclude the *.map files from the build during deployment.
devtool: 'source-map',
// In production, we only want to load the polyfills and the app code.
entry: [require.resolve('./polyfills'), paths.appIndexJs],
output: {
// The build folder.
path: paths.appBuild,
// Generated JS file names (with nested folders).
// There will be one main bundle, and one file per asynchronous chunk.
// We don't currently advertise code splitting but Webpack supports it.
filename: 'static/js/[name].[chunkhash:8].js',
chunkFilename: 'static/js/[name].[chunkhash:8].chunk.js',
// We inferred the "public path" (such as / or /my-project) from homepage.
publicPath: publicPath,
// Point sourcemap entries to original disk location
devtoolModuleFilenameTemplate: info =>
path.relative(paths.appSrc, info.absoluteResourcePath)
},
resolve: {
// This allows you to set a fallback for where Webpack should look for modules.
// We placed these paths second because we want `node_modules` to "win"
// if there are any conflicts. This matches Node resolution mechanism.
// https://github.com/facebookincubator/create-react-app/issues/253
modules: ['node_modules', paths.appNodeModules].concat(
// It is guaranteed to exist because we tweak it in `env.js`
process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
),
// These are the reasonable defaults supported by the Node ecosystem.
// We also include JSX as a common component filename extension to support
// some tools, although we do not recommend using it, see:
// https://github.com/facebookincubator/create-react-app/issues/290
extensions: ['.js', '.json', '.jsx'],
alias: {
// Support React Native Web
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
'react-native': 'react-native-web',
Components: path.resolve(__dirname, '../src/components'),
Util: path.resolve(__dirname, '../src/util'),
Actions: path.resolve(__dirname, '../src/actions'),
Selectors: path.resolve(__dirname, '../src/selectors')
},
plugins: [
// Prevents users from importing files from outside of src/ (or node_modules/).
// This often causes confusion because we only process files within src/ with babel.
// To fix this, we prevent you from importing files out of src/ -- if you'd like to,
// please link the files into your node_modules/ and let module-resolution kick in.
// Make sure your source files are compiled, as they will not be processed in any way.
new ModuleScopePlugin(paths.appSrc)
]
},
module: {
strictExportPresence: true,<|fim▁hole|> rules: [
// TODO: Disable require.ensure as it's not a standard language feature.
// We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176.
// { parser: { requireEnsure: false } },
// First, run the linter.
// It's important to do this before Babel processes the JS.
{
test: /\.(js|jsx)$/,
enforce: 'pre',
loader: 'standard-loader',
options: {
error: true
},
include: paths.appSrc
},
// ** ADDING/UPDATING LOADERS **
// The "file" loader handles all assets unless explicitly excluded.
// The `exclude` list *must* be updated with every change to loader extensions.
// When adding a new loader, you must add its `test`
// as a new entry in the `exclude` list in the "file" loader.
// "file" loader makes sure those assets end up in the `build` folder.
// When you `import` an asset, you get its filename.
{
exclude: [
/\.html$/,
/\.(js|jsx)$/,
/\.css$/,
/\.scss$/,
/\.json$/,
/\.bmp$/,
/\.gif$/,
/\.jpe?g$/,
/\.png$/
],
loader: require.resolve('file-loader'),
options: {
name: 'static/media/[name].[hash:8].[ext]'
}
},
// "url" loader works just like "file" loader but it also embeds
// assets smaller than specified size as data URLs to avoid requests.
{
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
loader: require.resolve('url-loader'),
options: {
limit: 10000,
name: 'static/media/[name].[hash:8].[ext]'
}
},
// Process JS with Babel.
{
test: /\.(js|jsx)$/,
include: paths.appSrc,
loader: require.resolve('babel-loader')
},
// The notation here is somewhat confusing.
// "postcss" loader applies autoprefixer to our CSS.
// "css" loader resolves paths in CSS and adds assets as dependencies.
// "style" loader normally turns CSS into JS modules injecting <style>,
// but unlike in development configuration, we do something different.
// `ExtractTextPlugin` first applies the "postcss" and "css" loaders
// (second argument), then grabs the result CSS and puts it into a
// separate file in our build process. This way we actually ship
// a single CSS file in production instead of JS code injecting <style>
// tags. If you use code splitting, however, any async bundles will still
// use the "style" loader inside the async code so CSS from them won't be
// in the main CSS file.
{
test: /\.css$/,
loader: ExtractTextPlugin.extract(
Object.assign(
{
fallback: require.resolve('style-loader'),
use: [
{
loader: require.resolve('css-loader'),
options: {
importLoaders: 1,
minimize: true,
sourceMap: true
}
}
// {
// loader: require.resolve('postcss-loader'),
// options: {
// ident: 'postcss', // https://webpack.js.org/guides/migrating/#complex-options
// plugins: () => [
// require('postcss-flexbugs-fixes'),
// autoprefixer({
// browsers: [
// '>1%',
// 'last 4 versions',
// 'Firefox ESR',
// 'not ie < 9', // React doesn't support IE8 anyway
// ],
// flexbox: 'no-2009',
// }),
// ],
// },
// },
]
},
extractTextPluginOptions
)
)
// Note: this won't work without `new ExtractTextPlugin()` in `plugins`.
}
// ** STOP ** Are you adding a new loader?
// Remember to add the new extension(s) to the "file" loader exclusion list.
]
},
plugins: [
// Makes some environment variables available in index.html.
// The public URL is available as %PUBLIC_URL% in index.html, e.g.:
// <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
// In production, it will be an empty string unless you specify "homepage"
// in `package.json`, in which case it will be the pathname of that URL.
new InterpolateHtmlPlugin(env.raw),
// Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin({
inject: true,
template: paths.appHtml,
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true
}
}),
// Makes some environment variables available to the JS code, for example:
// if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
// It is absolutely essential that NODE_ENV was set to production here.
// Otherwise React will be compiled in the very slow development mode.
new webpack.DefinePlugin(env.stringified),
// Minify the code.
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
// This feature has been reported as buggy a few times, such as:
// https://github.com/mishoo/UglifyJS2/issues/1964
// We'll wait with enabling it by default until it is more solid.
reduce_vars: false
},
output: {
comments: false
},
sourceMap: true
}),
// Note: this won't work without ExtractTextPlugin.extract(..) in `loaders`.
new ExtractTextPlugin({
filename: cssFilename
}),
// Generate a manifest file which contains a mapping of all asset filenames
// to their corresponding output file so that tools can pick it up without
// having to parse `index.html`.
new ManifestPlugin({
fileName: 'asset-manifest.json'
}),
// Generate a service worker script that will precache, and keep up to date,
// the HTML & assets that are part of the Webpack build.
new SWPrecacheWebpackPlugin({
// By default, a cache-busting query parameter is appended to requests
// used to populate the caches, to ensure the responses are fresh.
// If a URL is already hashed by Webpack, then there is no concern
// about it being stale, and the cache-busting can be skipped.
dontCacheBustUrlsMatching: /\.\w{8}\./,
filename: 'service-worker.js',
logger (message) {
if (message.indexOf('Total precache size is') === 0) {
// This message occurs for every build and is a bit too noisy.
return
}
console.log(message)
},
minify: true,
navigateFallback: publicUrl + '/index.html',
staticFileGlobsIgnorePatterns: [/\.map$/, /asset-manifest\.json$/],
// Work around Windows path issue in SWPrecacheWebpackPlugin:
// https://github.com/facebookincubator/create-react-app/issues/2235
stripPrefix: paths.appBuild.replace(/\\/g, '/') + '/'
}),
// Moment.js is an extremely popular library that bundles large locale files
// by default due to how Webpack interprets its code. This is a practical
// solution that requires the user to opt into importing specific locales.
// https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
// You can remove this if you don't use Moment.js:
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)
],
// Some libraries import Node modules but don't use them in the browser.
// Tell Webpack to provide empty mocks for them so importing them works.
node: {
fs: 'empty',
net: 'empty',
tls: 'empty'
}
}<|fim▁end|> | |
<|file_name|>searchUserIDs.ts<|end_file_name|><|fim▁begin|>import { MethodEnum } from '@algolia/requester-common';
import { RequestOptions } from '@algolia/transporter';
import { SearchClient, SearchUserIDsOptions, SearchUserIDsResponse } from '../..';
export const searchUserIDs = (base: SearchClient) => {
return (
query: string,<|fim▁hole|> {
method: MethodEnum.Post,
path: '1/clusters/mapping/search',
data: {
query,
},
},
requestOptions
);
};
};<|fim▁end|> | requestOptions?: SearchUserIDsOptions & RequestOptions
): Readonly<Promise<SearchUserIDsResponse>> => {
return base.transporter.read( |
<|file_name|>gyp_node.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
import glob
import os
import shlex
import sys
script_dir = os.path.dirname(__file__)
node_root = os.path.normpath(os.path.join(script_dir, os.pardir))
sys.path.insert(0, os.path.join(node_root, 'tools', 'gyp', 'pylib'))
import gyp
# Directory within which we want all generated files (including Makefiles)
# to be written.
output_dir = os.path.join(os.path.abspath(node_root), 'out')
def run_gyp(args):
rc = gyp.main(args)
if rc != 0:
print 'Error running GYP'
sys.exit(rc)
if __name__ == '__main__':
args = sys.argv[1:]<|fim▁hole|> # On msvs it will crash if it gets an absolute path.
# On Mac/make it will crash if it doesn't get an absolute path.
if sys.platform == 'win32':
args.append(os.path.join(node_root, 'node.gyp'))
common_fn = os.path.join(node_root, 'common.gypi')
options_fn = os.path.join(node_root, 'config.gypi')
options_fips_fn = os.path.join(node_root, 'config_fips.gypi')
else:
args.append(os.path.join(os.path.abspath(node_root), 'node.gyp'))
common_fn = os.path.join(os.path.abspath(node_root), 'common.gypi')
options_fn = os.path.join(os.path.abspath(node_root), 'config.gypi')
options_fips_fn = os.path.join(os.path.abspath(node_root), 'config_fips.gypi')
if os.path.exists(common_fn):
args.extend(['-I', common_fn])
if os.path.exists(options_fn):
args.extend(['-I', options_fn])
if os.path.exists(options_fips_fn):
args.extend(['-I', options_fips_fn])
args.append('--depth=' + node_root)
# There's a bug with windows which doesn't allow this feature.
if sys.platform != 'win32' and 'ninja' not in args:
# Tell gyp to write the Makefiles into output_dir
args.extend(['--generator-output', output_dir])
# Tell make to write its output into the same dir
args.extend(['-Goutput_dir=' + output_dir])
args.append('-Dcomponent=static_library')
args.append('-Dlibrary=static_library')
gyp_args = list(args)
run_gyp(gyp_args)<|fim▁end|> |
# GYP bug. |
<|file_name|>msgblock_test.go<|end_file_name|><|fim▁begin|>// Copyright (c) 2013-2015 The btcsuite developers
// Copyright (c) 2015 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package wire_test
import (
"bytes"
"io"
"reflect"
"testing"
"time"
"github.com/davecgh/go-spew/spew"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/wire"
"github.com/decred/dcrutil"
)
// TestBlock tests the MsgBlock API.
func TestBlock(t *testing.T) {
pver := wire.ProtocolVersion
// Test block header.
bh := wire.NewBlockHeader(
int32(pver), // Version
&testBlock.Header.PrevBlock, // PrevHash
&testBlock.Header.MerkleRoot, // MerkleRoot
&testBlock.Header.StakeRoot, // StakeRoot
uint16(0x0000), // VoteBits
[6]byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // FinalState
uint16(0x0000), // Voters
uint8(0x00), // FreshStake
uint8(0x00), // Revocations
uint32(0), // Poolsize
testBlock.Header.Bits, // Bits
int64(0x0000000000000000), // Sbits
uint32(1), // Height
uint32(1), // Size
testBlock.Header.Nonce, // Nonce
[36]byte{}, // ExtraData
)
// Ensure the command is expected value.
wantCmd := "block"
msg := wire.NewMsgBlock(bh)
if cmd := msg.Command(); cmd != wantCmd {
t.Errorf("NewMsgBlock: wrong command - got %v want %v",
cmd, wantCmd)
}
// Ensure max payload is expected value for latest protocol version.
// Num addresses (varInt) + max allowed addresses.
wantPayload := uint32(1000000)
maxPayload := msg.MaxPayloadLength(pver)
if maxPayload != wantPayload {
t.Errorf("MaxPayloadLength: wrong max payload length for "+
"protocol version %d - got %v, want %v", pver,
maxPayload, wantPayload)
}
// Ensure we get the same block header data back out.
if !reflect.DeepEqual(&msg.Header, bh) {
t.Errorf("NewMsgBlock: wrong block header - got %v, want %v",
spew.Sdump(&msg.Header), spew.Sdump(bh))
}
// Ensure transactions are added properly.
tx := testBlock.Transactions[0].Copy()
msg.AddTransaction(tx)
if !reflect.DeepEqual(msg.Transactions, testBlock.Transactions) {
t.Errorf("AddTransaction: wrong transactions - got %v, want %v",
spew.Sdump(msg.Transactions),
spew.Sdump(testBlock.Transactions))
}
// Ensure transactions are properly cleared.
msg.ClearTransactions()
if len(msg.Transactions) != 0 {
t.Errorf("ClearTransactions: wrong transactions - got %v, want %v",
len(msg.Transactions), 0)
}
// Ensure stake transactions are added properly.
stx := testBlock.STransactions[0].Copy()
msg.AddSTransaction(stx)
if !reflect.DeepEqual(msg.STransactions, testBlock.STransactions) {
t.Errorf("AddSTransaction: wrong transactions - got %v, want %v",
spew.Sdump(msg.STransactions),
spew.Sdump(testBlock.STransactions))
}
// Ensure transactions are properly cleared.
msg.ClearSTransactions()
if len(msg.STransactions) != 0 {
t.Errorf("ClearTransactions: wrong transactions - got %v, want %v",
len(msg.STransactions), 0)
}
return
}
// TestBlockTxShas tests the ability to generate a slice of all transaction
// hashes from a block accurately.
func TestBlockTxShas(t *testing.T) {
// Block 1, transaction 1 hash.
hashStr := "55a25248c04dd8b6599ca2a708413c00d79ae90ce075c54e8a967a647d7e4bea"
wantHash, err := chainhash.NewHashFromStr(hashStr)
if err != nil {
t.Errorf("NewShaHashFromStr: %v", err)
return
}
wantShas := []chainhash.Hash{*wantHash}
shas := testBlock.TxShas()
if !reflect.DeepEqual(shas, wantShas) {
t.Errorf("TxShas: wrong transaction hashes - got %v, want %v",
spew.Sdump(shas), spew.Sdump(wantShas))
}
}
// TestBlockSTxShas tests the ability to generate a slice of all stake transaction
// hashes from a block accurately.
func TestBlockSTxShas(t *testing.T) {
// Block 1, transaction 1 hash.
hashStr := "ae208a69f3ee088d0328126e3d9bef7652b108d1904f27b166c5999233a801d4"
wantHash, err := chainhash.NewHashFromStr(hashStr)
if err != nil {
t.Errorf("NewShaHashFromStr: %v", err)
return
}
wantShas := []chainhash.Hash{*wantHash}
shas := testBlock.STxShas()
if !reflect.DeepEqual(shas, wantShas) {
t.Errorf("STxShas: wrong transaction hashes - got %v, want %v",
spew.Sdump(shas), spew.Sdump(wantShas))
}
}
// TestBlockSha tests the ability to generate the hash of a block accurately.
func TestBlockSha(t *testing.T) {
// Block 1 hash.
hashStr := "152437dada95368c42b19febc1702939fa9c1ccdb6fd7284e5b7a19d8fe6df7a"
wantHash, err := chainhash.NewHashFromStr(hashStr)
if err != nil {
t.Errorf("NewShaHashFromStr: %v", err)
}
// Ensure the hash produced is expected.
blockHash := testBlock.BlockSha()
if !blockHash.IsEqual(wantHash) {
t.Errorf("BlockSha: wrong hash - got %v, want %v",
spew.Sprint(blockHash), spew.Sprint(wantHash))
}
}
// TestBlockWire tests the MsgBlock wire encode and decode for various numbers
// of transaction inputs and outputs and protocol versions.
func TestBlockWire(t *testing.T) {
tests := []struct {
in *wire.MsgBlock // Message to encode
out *wire.MsgBlock // Expected decoded message
buf []byte // Wire encoding
txLocs []wire.TxLoc // Expected transaction locations
sTxLocs []wire.TxLoc // Expected stake transaction locations
pver uint32 // Protocol version for wire encoding
}{
// Latest protocol version.
{
&testBlock,
&testBlock,
testBlockBytes,
testBlockTxLocs,
testBlockSTxLocs,
wire.ProtocolVersion,
},
}
t.Logf("Running %d tests", len(tests))
for i, test := range tests {
// Encode the message to wire format.
var buf bytes.Buffer
err := test.in.BtcEncode(&buf, test.pver)
if err != nil {
t.Errorf("BtcEncode #%d error %v", i, err)
continue
}
if !bytes.Equal(buf.Bytes(), test.buf) {
t.Errorf("BtcEncode #%d\n got: %s want: %s", i,
spew.Sdump(buf.Bytes()), spew.Sdump(test.buf))
continue
}
// Decode the message from wire format.
var msg wire.MsgBlock
rbuf := bytes.NewReader(test.buf)
err = msg.BtcDecode(rbuf, test.pver)
if err != nil {
t.Errorf("BtcDecode #%d error %v", i, err)
continue
}
if !reflect.DeepEqual(&msg, test.out) {
t.Errorf("BtcDecode #%d\n got: %s want: %s", i,
spew.Sdump(&msg), spew.Sdump(test.out))
continue
}
}
}
// TestBlockWireErrors performs negative tests against wire encode and decode
// of MsgBlock to confirm error paths work correctly.
func TestBlockWireErrors(t *testing.T) {
// Use protocol version 60002 specifically here instead of the latest
// because the test data is using bytes encoded with that protocol
// version.
pver := uint32(60002)
tests := []struct {
in *wire.MsgBlock // Value to encode
buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding
max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error
readErr error // Expected read error
}{ // Force error in version.
{&testBlock, testBlockBytes, pver, 0, io.ErrShortWrite, io.EOF}, // 0
// Force error in prev block hash.
{&testBlock, testBlockBytes, pver, 4, io.ErrShortWrite, io.EOF}, // 1
// Force error in merkle root.
{&testBlock, testBlockBytes, pver, 36, io.ErrShortWrite, io.EOF}, // 2
// Force error in stake root.
{&testBlock, testBlockBytes, pver, 68, io.ErrShortWrite, io.EOF}, // 3
// Force error in vote bits.
{&testBlock, testBlockBytes, pver, 100, io.ErrShortWrite, io.EOF}, // 4
// Force error in finalState.
{&testBlock, testBlockBytes, pver, 102, io.ErrShortWrite, io.EOF}, // 5
// Force error in voters.
{&testBlock, testBlockBytes, pver, 108, io.ErrShortWrite, io.EOF}, // 6
// Force error in freshstake.
{&testBlock, testBlockBytes, pver, 110, io.ErrShortWrite, io.EOF}, // 7
// Force error in revocations.
{&testBlock, testBlockBytes, pver, 111, io.ErrShortWrite, io.EOF}, // 8
// Force error in poolsize.
{&testBlock, testBlockBytes, pver, 112, io.ErrShortWrite, io.EOF}, // 9
// Force error in difficulty bits.
{&testBlock, testBlockBytes, pver, 116, io.ErrShortWrite, io.EOF}, // 10
// Force error in stake difficulty bits.
{&testBlock, testBlockBytes, pver, 120, io.ErrShortWrite, io.EOF}, // 11
// Force error in height.
{&testBlock, testBlockBytes, pver, 128, io.ErrShortWrite, io.EOF}, // 12
// Force error in size.
{&testBlock, testBlockBytes, pver, 132, io.ErrShortWrite, io.EOF}, // 13
// Force error in timestamp.
{&testBlock, testBlockBytes, pver, 136, io.ErrShortWrite, io.EOF}, // 14
// Force error in nonce.
{&testBlock, testBlockBytes, pver, 140, io.ErrShortWrite, io.EOF}, // 15
// Force error in tx count.
{&testBlock, testBlockBytes, pver, 180, io.ErrShortWrite, io.EOF}, // 16
// Force error in tx.
{&testBlock, testBlockBytes, pver, 181, io.ErrShortWrite, io.EOF}, // 17
}
t.Logf("Running %d tests", len(tests))
for i, test := range tests {
// Encode to wire format.
w := newFixedWriter(test.max)
err := test.in.BtcEncode(w, test.pver)
if err != test.writeErr {
t.Errorf("BtcEncode #%d wrong error got: %v, want: %v",
i, err, test.writeErr)
continue
}
// Decode from wire format.
var msg wire.MsgBlock
r := newFixedReader(test.max, test.buf)
err = msg.BtcDecode(r, test.pver)
if err != test.readErr {
t.Errorf("BtcDecode #%d wrong error got: %v, want: %v",
i, err, test.readErr)
continue
}
}
}
// TestBlockSerialize tests MsgBlock serialize and deserialize.
func TestBlockSerialize(t *testing.T) {
tests := []struct {
in *wire.MsgBlock // Message to encode
out *wire.MsgBlock // Expected decoded message
buf []byte // Serialized data
txLocs []wire.TxLoc // Expected transaction locations
sTxLocs []wire.TxLoc // Expected stake transaction locations
}{
{
&testBlock,
&testBlock,
testBlockBytes,
testBlockTxLocs,
testBlockSTxLocs,
},
}
t.Logf("Running %d tests", len(tests))
for i, test := range tests {
// Serialize the block.
var buf bytes.Buffer
err := test.in.Serialize(&buf)
if err != nil {
t.Errorf("Serialize #%d error %v", i, err)
continue
}
if !bytes.Equal(buf.Bytes(), test.buf) {
t.Errorf("Serialize #%d\n got: %s want: %s", i,
spew.Sdump(buf.Bytes()), spew.Sdump(test.buf))
continue
}
// Deserialize the block.
var block wire.MsgBlock
rbuf := bytes.NewReader(test.buf)
err = block.Deserialize(rbuf)
if err != nil {
t.Errorf("Deserialize #%d error %v", i, err)
continue
}
if !reflect.DeepEqual(&block, test.out) {
t.Errorf("Deserialize #%d\n got: %s want: %s", i,
spew.Sdump(&block), spew.Sdump(test.out))
continue
}
// Deserialize the block while gathering transaction location
// information.
var txLocBlock wire.MsgBlock
br := bytes.NewBuffer(test.buf)
txLocs, sTxLocs, err := txLocBlock.DeserializeTxLoc(br)
if err != nil {
t.Errorf("DeserializeTxLoc #%d error %v", i, err)
continue
}
if !reflect.DeepEqual(&txLocBlock, test.out) {
t.Errorf("DeserializeTxLoc #%d\n got: %s want: %s", i,
spew.Sdump(&txLocBlock), spew.Sdump(test.out))
continue
}
if !reflect.DeepEqual(txLocs, test.txLocs) {
t.Errorf("DeserializeTxLoc #%d\n got: %s want: %s", i,
spew.Sdump(txLocs), spew.Sdump(test.txLocs))
continue
}
if !reflect.DeepEqual(sTxLocs, test.sTxLocs) {
t.Errorf("DeserializeTxLoc, sTxLocs #%d\n got: %s want: %s", i,
spew.Sdump(sTxLocs), spew.Sdump(test.sTxLocs))
continue
}
}
}
// TestBlockSerializeErrors performs negative tests against wire encode and
// decode of MsgBlock to confirm error paths work correctly.
func TestBlockSerializeErrors(t *testing.T) {
tests := []struct {
in *wire.MsgBlock // Value to encode
buf []byte // Serialized data
max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error
readErr error // Expected read error
}{
{&testBlock, testBlockBytes, 0, io.ErrShortWrite, io.EOF}, // 0
// Force error in prev block hash.
{&testBlock, testBlockBytes, 4, io.ErrShortWrite, io.EOF}, // 1
// Force error in merkle root.
{&testBlock, testBlockBytes, 36, io.ErrShortWrite, io.EOF}, // 2
// Force error in stake root.
{&testBlock, testBlockBytes, 68, io.ErrShortWrite, io.EOF}, // 3
// Force error in vote bits.
{&testBlock, testBlockBytes, 100, io.ErrShortWrite, io.EOF}, // 4
// Force error in finalState.
{&testBlock, testBlockBytes, 102, io.ErrShortWrite, io.EOF}, // 5
// Force error in voters.
{&testBlock, testBlockBytes, 108, io.ErrShortWrite, io.EOF}, // 8
// Force error in freshstake.
{&testBlock, testBlockBytes, 110, io.ErrShortWrite, io.EOF}, // 9
// Force error in revocations.
{&testBlock, testBlockBytes, 111, io.ErrShortWrite, io.EOF}, // 10
// Force error in poolsize.
{&testBlock, testBlockBytes, 112, io.ErrShortWrite, io.EOF}, // 11
// Force error in difficulty bits.
{&testBlock, testBlockBytes, 116, io.ErrShortWrite, io.EOF}, // 12
// Force error in stake difficulty bits.
{&testBlock, testBlockBytes, 120, io.ErrShortWrite, io.EOF}, // 13
// Force error in height.
{&testBlock, testBlockBytes, 128, io.ErrShortWrite, io.EOF}, // 14
// Force error in size.
{&testBlock, testBlockBytes, 132, io.ErrShortWrite, io.EOF}, // 15
// Force error in timestamp.
{&testBlock, testBlockBytes, 136, io.ErrShortWrite, io.EOF}, // 16
// Force error in nonce.
{&testBlock, testBlockBytes, 140, io.ErrShortWrite, io.EOF}, // 17
// Force error in tx count.
{&testBlock, testBlockBytes, 180, io.ErrShortWrite, io.EOF}, // 18
// Force error in tx.
{&testBlock, testBlockBytes, 181, io.ErrShortWrite, io.EOF}, // 19
}
t.Logf("Running %d tests", len(tests))
for i, test := range tests {
// Serialize the block.
w := newFixedWriter(test.max)
err := test.in.Serialize(w)
if err != test.writeErr {
t.Errorf("Serialize #%d wrong error got: %v, want: %v",
i, err, test.writeErr)
continue
}
// Deserialize the block.
var block wire.MsgBlock
r := newFixedReader(test.max, test.buf)
err = block.Deserialize(r)
if err != test.readErr {
t.Errorf("Deserialize #%d wrong error got: %v, want: %v",
i, err, test.readErr)
continue
}
var txLocBlock wire.MsgBlock
br := bytes.NewBuffer(test.buf[0:test.max])
_, _, err = txLocBlock.DeserializeTxLoc(br)
if err != test.readErr {
t.Errorf("DeserializeTxLoc #%d wrong error got: %v, want: %v",
i, err, test.readErr)
continue
}
}
}
// TestBlockOverflowErrors performs tests to ensure deserializing blocks which
// are intentionally crafted to use large values for the number of transactions
// are handled properly. This could otherwise potentially be used as an attack
// vector.
func TestBlockOverflowErrors(t *testing.T) {
// Use protocol version 70001 specifically here instead of the latest
// protocol version because the test data is using bytes encoded with
// that version.
pver := uint32(1)
tests := []struct {
buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding
err error // Expected error
}{
// Block that claims to have ~uint64(0) transactions.
{
[]byte{
0x01, 0x00, 0x00, 0x00, // Version 1
0x6f, 0xe2, 0x8c, 0x0a, 0xb6, 0xf1, 0xb3, 0x72,
0xc1, 0xa6, 0xa2, 0x46, 0xae, 0x63, 0xf7, 0x4f,
0x93, 0x1e, 0x83, 0x65, 0xe1, 0x5a, 0x08, 0x9c,
0x68, 0xd6, 0x19, 0x00, 0x00, 0x00, 0x00, 0x00, // PrevBlock
0x98, 0x20, 0x51, 0xfd, 0x1e, 0x4b, 0xa7, 0x44,
0xbb, 0xbe, 0x68, 0x0e, 0x1f, 0xee, 0x14, 0x67,
0x7b, 0xa1, 0xa3, 0xc3, 0x54, 0x0b, 0xf7, 0xb1,
0xcd, 0xb6, 0x06, 0xe8, 0x57, 0x23, 0x3e, 0x0e, // MerkleRoot
0x98, 0x20, 0x51, 0xfd, 0x1e, 0x4b, 0xa7, 0x44,
0xbb, 0xbe, 0x68, 0x0e, 0x1f, 0xee, 0x14, 0x67,
0x7b, 0xa1, 0xa3, 0xc3, 0x54, 0x0b, 0xf7, 0xb1,
0xcd, 0xb6, 0x06, 0xe8, 0x57, 0x23, 0x3e, 0x0e, // StakeRoot
0x00, 0x00, // VoteBits
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // FinalState
0x00, 0x00, // Voters
0x00, // FreshStake
0x00, // Revocations
0x00, 0x00, 0x00, 0x00, // Poolsize
0xff, 0xff, 0x00, 0x1d, // Bits
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // SBits
0x01, 0x00, 0x00, 0x00, // Height
0x01, 0x00, 0x00, 0x00, // Size
0x61, 0xbc, 0x66, 0x49, // Timestamp
0x01, 0xe3, 0x62, 0x99, // Nonce
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ExtraData
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, // TxnCount
}, pver, &wire.MessageError{},
},
}
t.Logf("Running %d tests", len(tests))
for i, test := range tests {
// Decode from wire format.
var msg wire.MsgBlock
r := bytes.NewReader(test.buf)
err := msg.BtcDecode(r, test.pver)
if reflect.TypeOf(err) != reflect.TypeOf(test.err) {
t.Errorf("BtcDecode #%d wrong error got: %v, want: %v",
i, err, reflect.TypeOf(test.err))
continue
}
// Deserialize from wire format.
r = bytes.NewReader(test.buf)
err = msg.Deserialize(r)
if reflect.TypeOf(err) != reflect.TypeOf(test.err) {
t.Errorf("Deserialize #%d wrong error got: %v, want: %v",
i, err, reflect.TypeOf(test.err))
continue
}
// Deserialize with transaction location info from wire format.
br := bytes.NewBuffer(test.buf)
_, _, err = msg.DeserializeTxLoc(br)
if reflect.TypeOf(err) != reflect.TypeOf(test.err) {
t.Errorf("DeserializeTxLoc #%d wrong error got: %v, "+
"want: %v", i, err, reflect.TypeOf(test.err))
continue
}
}
}
// TestBlockSerializeSize performs tests to ensure the serialize size for
// various blocks is accurate.
func TestBlockSerializeSize(t *testing.T) {
// Block with no transactions.
noTxBlock := wire.NewMsgBlock(&testBlock.Header)
tests := []struct {
in *wire.MsgBlock // Block to encode
size int // Expected serialized size
}{
// Block with no transactions (header + 2x numtx)
{noTxBlock, 182},
// First block in the mainnet block chain.
{&testBlock, len(testBlockBytes)},
}
t.Logf("Running %d tests", len(tests))
for i, test := range tests {
serializedSize := test.in.SerializeSize()
if serializedSize != test.size {
t.Errorf("MsgBlock.SerializeSize: #%d got: %d, want: "+
"%d", i, serializedSize, test.size)
continue
}
}
}
// testBlock is a basic normative block that is used throughout tests.
var testBlock = wire.MsgBlock{
Header: wire.BlockHeader{
Version: 1,
PrevBlock: chainhash.Hash([chainhash.HashSize]byte{ // Make go vet happy.
0x6f, 0xe2, 0x8c, 0x0a, 0xb6, 0xf1, 0xb3, 0x72,
0xc1, 0xa6, 0xa2, 0x46, 0xae, 0x63, 0xf7, 0x4f,
0x93, 0x1e, 0x83, 0x65, 0xe1, 0x5a, 0x08, 0x9c,
0x68, 0xd6, 0x19, 0x00, 0x00, 0x00, 0x00, 0x00,
}),
MerkleRoot: chainhash.Hash([chainhash.HashSize]byte{ // Make go vet happy.
0x98, 0x20, 0x51, 0xfd, 0x1e, 0x4b, 0xa7, 0x44,
0xbb, 0xbe, 0x68, 0x0e, 0x1f, 0xee, 0x14, 0x67,
0x7b, 0xa1, 0xa3, 0xc3, 0x54, 0x0b, 0xf7, 0xb1,
0xcd, 0xb6, 0x06, 0xe8, 0x57, 0x23, 0x3e, 0x0e,
}),
StakeRoot: chainhash.Hash([chainhash.HashSize]byte{ // Make go vet happy.
0x98, 0x20, 0x51, 0xfd, 0x1e, 0x4b, 0xa7, 0x44,
0xbb, 0xbe, 0x68, 0x0e, 0x1f, 0xee, 0x14, 0x67,
0x7b, 0xa1, 0xa3, 0xc3, 0x54, 0x0b, 0xf7, 0xb1,
0xcd, 0xb6, 0x06, 0xe8, 0x57, 0x23, 0x3e, 0x0e,
}),
VoteBits: uint16(0x0000),
FinalState: [6]byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
Voters: uint16(0x0000),
FreshStake: uint8(0x00),
Revocations: uint8(0x00),
PoolSize: uint32(0x00000000), // Poolsize
Bits: 0x1d00ffff, // 486604799
SBits: int64(0x0000000000000000),
Height: uint32(1),
Size: uint32(1),
Timestamp: time.Unix(0x4966bc61, 0), // 2009-01-08 20:54:25 -0600 CST
Nonce: 0x9962e301, // 2573394689
ExtraData: [36]byte{},
},
Transactions: []*wire.MsgTx{
{
Version: 1,
TxIn: []*wire.TxIn{
{
PreviousOutPoint: wire.OutPoint{
Hash: chainhash.Hash{},
Index: 0xffffffff,
Tree: dcrutil.TxTreeRegular,
},
Sequence: 0xffffffff,
ValueIn: 0x1616161616161616,
BlockHeight: 0x17171717,
BlockIndex: 0x18181818,
SignatureScript: []byte{
0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0xf2,
},
},
},
TxOut: []*wire.TxOut{
{
Value: 0x3333333333333333,
Version: 0x9898,
PkScript: []byte{
0x41, // OP_DATA_65
0x04, 0x96, 0xb5, 0x38, 0xe8, 0x53, 0x51, 0x9c,
0x72, 0x6a, 0x2c, 0x91, 0xe6, 0x1e, 0xc1, 0x16,
0x00, 0xae, 0x13, 0x90, 0x81, 0x3a, 0x62, 0x7c,
0x66, 0xfb, 0x8b, 0xe7, 0x94, 0x7b, 0xe6, 0x3c,
0x52, 0xda, 0x75, 0x89, 0x37, 0x95, 0x15, 0xd4,
0xe0, 0xa6, 0x04, 0xf8, 0x14, 0x17, 0x81, 0xe6,
0x22, 0x94, 0x72, 0x11, 0x66, 0xbf, 0x62, 0x1e,
0x73, 0xa8, 0x2c, 0xbf, 0x23, 0x42, 0xc8, 0x58,
0xee, // 65-byte signature
0xac, // OP_CHECKSIG
},
},
},
LockTime: 0x11111111,
Expiry: 0x22222222,
},
},
STransactions: []*wire.MsgTx{
{
Version: 1,
TxIn: []*wire.TxIn{
{
PreviousOutPoint: wire.OutPoint{
Hash: chainhash.Hash{},
Index: 0xffffffff,
Tree: dcrutil.TxTreeStake,
},
Sequence: 0xffffffff,
ValueIn: 0x1313131313131313,
BlockHeight: 0x14141414,
BlockIndex: 0x15151515,
SignatureScript: []byte{
0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0xf2,
},
},
},
TxOut: []*wire.TxOut{
{
Value: 0x3333333333333333,
Version: 0x1212,
PkScript: []byte{
0x41, // OP_DATA_65
0x04, 0x96, 0xb5, 0x38, 0xe8, 0x53, 0x51, 0x9c,
0x72, 0x6a, 0x2c, 0x91, 0xe6, 0x1e, 0xc1, 0x16,
0x00, 0xae, 0x13, 0x90, 0x81, 0x3a, 0x62, 0x7c,
0x66, 0xfb, 0x8b, 0xe7, 0x94, 0x7b, 0xe6, 0x3c,
0x52, 0xda, 0x75, 0x89, 0x37, 0x95, 0x15, 0xd4,
0xe0, 0xa6, 0x04, 0xf8, 0x14, 0x17, 0x81, 0xe6,
0x22, 0x94, 0x72, 0x11, 0x66, 0xbf, 0x62, 0x1e,
0x73, 0xa8, 0x2c, 0xbf, 0x23, 0x42, 0xc8, 0x58,
0xee, // 65-byte signature
0xac, // OP_CHECKSIG
},
},
},
LockTime: 0x11111111,
Expiry: 0x22222222,
},
},
}
// testBlockBytes is the serialized bytes for the above test block (testBlock).
var testBlockBytes = []byte{
// Begin block header
0x01, 0x00, 0x00, 0x00, // Version 1 [0]
0x6f, 0xe2, 0x8c, 0x0a, 0xb6, 0xf1, 0xb3, 0x72,
0xc1, 0xa6, 0xa2, 0x46, 0xae, 0x63, 0xf7, 0x4f,
0x93, 0x1e, 0x83, 0x65, 0xe1, 0x5a, 0x08, 0x9c,
0x68, 0xd6, 0x19, 0x00, 0x00, 0x00, 0x00, 0x00, // PrevBlock [4]
0x98, 0x20, 0x51, 0xfd, 0x1e, 0x4b, 0xa7, 0x44,
0xbb, 0xbe, 0x68, 0x0e, 0x1f, 0xee, 0x14, 0x67,
0x7b, 0xa1, 0xa3, 0xc3, 0x54, 0x0b, 0xf7, 0xb1,<|fim▁hole|> 0xbb, 0xbe, 0x68, 0x0e, 0x1f, 0xee, 0x14, 0x67,
0x7b, 0xa1, 0xa3, 0xc3, 0x54, 0x0b, 0xf7, 0xb1,
0xcd, 0xb6, 0x06, 0xe8, 0x57, 0x23, 0x3e, 0x0e, // StakeRoot [68]
0x00, 0x00, // VoteBits [100]
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // FinalState [102]
0x00, 0x00, // Voters [108]
0x00, // FreshStake [110]
0x00, // Revocations [111]
0x00, 0x00, 0x00, 0x00, // Poolsize [112]
0xff, 0xff, 0x00, 0x1d, // Bits [116]
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // SBits [120]
0x01, 0x00, 0x00, 0x00, // Height [128]
0x01, 0x00, 0x00, 0x00, // Size [132]
0x61, 0xbc, 0x66, 0x49, // Timestamp [136]
0x01, 0xe3, 0x62, 0x99, // Nonce [140]
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ExtraData [144]
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
// Announce number of txs
0x01, // TxnCount [180]
// Begin bogus normal txs
0x01, 0x00, 0x00, 0x00, // Version [181]
0x01, // Varint for number of transaction inputs [185]
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Previous output hash [186]
0xff, 0xff, 0xff, 0xff, // Prevous output index [218]
0x00, // Previous output tree [222]
0xff, 0xff, 0xff, 0xff, // Sequence [223]
0x01, // Varint for number of transaction outputs [227]
0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, // Transaction amount [228]
0x98, 0x98, // Script version
0x43, // Varint for length of pk script
0x41, // OP_DATA_65
0x04, 0x96, 0xb5, 0x38, 0xe8, 0x53, 0x51, 0x9c,
0x72, 0x6a, 0x2c, 0x91, 0xe6, 0x1e, 0xc1, 0x16,
0x00, 0xae, 0x13, 0x90, 0x81, 0x3a, 0x62, 0x7c,
0x66, 0xfb, 0x8b, 0xe7, 0x94, 0x7b, 0xe6, 0x3c,
0x52, 0xda, 0x75, 0x89, 0x37, 0x95, 0x15, 0xd4,
0xe0, 0xa6, 0x04, 0xf8, 0x14, 0x17, 0x81, 0xe6,
0x22, 0x94, 0x72, 0x11, 0x66, 0xbf, 0x62, 0x1e,
0x73, 0xa8, 0x2c, 0xbf, 0x23, 0x42, 0xc8, 0x58,
0xee, // 65-byte signature
0xac, // OP_CHECKSIG
0x11, 0x11, 0x11, 0x11, // Lock time
0x22, 0x22, 0x22, 0x22, // Expiry
0x01, // Varint for number of signatures
0x16, 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, // ValueIn
0x17, 0x17, 0x17, 0x17, // BlockHeight
0x18, 0x18, 0x18, 0x18, // BlockIndex
0x07, // SigScript length
0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0xf2, // Signature script (coinbase)
// Announce number of stake txs
0x01, // TxnCount for stake tx
// Begin bogus stake txs
0x01, 0x00, 0x00, 0x00, // Version
0x01, // Varint for number of transaction inputs
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Previous output hash
0xff, 0xff, 0xff, 0xff, // Prevous output index
0x01, // Previous output tree
0xff, 0xff, 0xff, 0xff, // Sequence
0x01, // Varint for number of transaction outputs
0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, // Transaction amount
0x12, 0x12, // Script version
0x43, // Varint for length of pk script
0x41, // OP_DATA_65
0x04, 0x96, 0xb5, 0x38, 0xe8, 0x53, 0x51, 0x9c,
0x72, 0x6a, 0x2c, 0x91, 0xe6, 0x1e, 0xc1, 0x16,
0x00, 0xae, 0x13, 0x90, 0x81, 0x3a, 0x62, 0x7c,
0x66, 0xfb, 0x8b, 0xe7, 0x94, 0x7b, 0xe6, 0x3c,
0x52, 0xda, 0x75, 0x89, 0x37, 0x95, 0x15, 0xd4,
0xe0, 0xa6, 0x04, 0xf8, 0x14, 0x17, 0x81, 0xe6,
0x22, 0x94, 0x72, 0x11, 0x66, 0xbf, 0x62, 0x1e,
0x73, 0xa8, 0x2c, 0xbf, 0x23, 0x42, 0xc8, 0x58,
0xee, // 65-byte signature
0xac, // OP_CHECKSIG
0x11, 0x11, 0x11, 0x11, // Lock time
0x22, 0x22, 0x22, 0x22, // Expiry
0x01, // Varint for number of signatures
0x13, 0x13, 0x13, 0x13, 0x13, 0x13, 0x13, 0x13, // ValueIn
0x14, 0x14, 0x14, 0x14, // BlockHeight
0x15, 0x15, 0x15, 0x15, // BlockIndex
0x07, // SigScript length
0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0xf2, // Signature script (coinbase)
}
// Transaction location information for the test block transactions.
var testBlockTxLocs = []wire.TxLoc{
{TxStart: 181, TxLen: 158},
}
// Transaction location information for the test block stake transactions.
var testBlockSTxLocs = []wire.TxLoc{
{TxStart: 340, TxLen: 158},
}<|fim▁end|> | 0xcd, 0xb6, 0x06, 0xe8, 0x57, 0x23, 0x3e, 0x0e, // MerkleRoot [36]
0x98, 0x20, 0x51, 0xfd, 0x1e, 0x4b, 0xa7, 0x44, |
<|file_name|>target_list.py<|end_file_name|><|fim▁begin|>'''
Copyright (C) 2014 Travis DeWolf
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/>.
'''
import numpy as np
class Shell(object):
"""
"""
def __init__(self, controller, target_list,
threshold=.01, pen_down=False):
"""
control Control instance: the controller to use
pen_down boolean: True if the end-effector is drawing
"""
self.controller = controller
self.pen_down = pen_down
self.target_list = target_list
self.threshold = threshold
self.not_at_start = True
self.target_index = 0
self.set_target()
def control(self, arm):
"""Move to a series of targets.
"""
if self.controller.check_distance(arm) < self.threshold:
if self.target_index < len(self.target_list)-1:
self.target_index += 1
self.set_target()
self.controller.apply_noise = True
self.not_at_start = not self.not_at_start
self.pen_down = not self.pen_down
self.u = self.controller.control(arm)
return self.u
def set_target(self):
"""
Set the current target for the controller.
"""
if self.target_index == len(self.target_list)-1:
target = [1, 2]
else:
target = self.target_list[self.target_index]
if target[0] != target[0]: # if it's NANs<|fim▁hole|> else:
self.controller.target = target<|fim▁end|> | self.target_index += 1
self.set_target() |
<|file_name|>utils.js<|end_file_name|><|fim▁begin|>'use strict';
var crypto = require('crypto');
exports.typeOf = function(obj) {
var classToType;
if (obj === void 0 || obj === null) {
return String(obj);
}
classToType = {
'[object Boolean]': 'boolean',
'[object Number]': 'number',
'[object String]': 'string',
'[object Function]': 'function',
'[object Array]': 'array',
'[object Date]': 'date',
'[object RegExp]': 'regexp',
'[object Object]': 'object'
};
return classToType[Object.prototype.toString.call(obj)];
};
exports.unauthResp = function(res) {
res.statusCode = 401;
res.setHeader('content-type', 'application/json; charset=UTF-8');
return res.end(JSON.stringify({ code: 401, error: 'Unauthorized.' }));
};
exports.signHook = function(masterKey, hookName, ts) {
return ts + ',' + crypto.createHmac('sha1', masterKey).update(hookName + ':' + ts).digest('hex');
};
exports.verifyHookSign = function(masterKey, hookName, sign) {
if (sign) {
return exports.signHook(masterKey, hookName, sign.split(',')[0]) === sign;
} else {
return false;
}
};
/* options: req, user, params, object*/
exports.prepareRequestObject = function(options) {
var req = options.req;
var user = options.user;
var currentUser = user || (req && req.AV && req.AV.user);
return {
expressReq: req,
params: options.params,
object: options.object,
meta: {
remoteAddress: req && req.headers && getRemoteAddress(req)
},
user: user,
currentUser: currentUser,<|fim▁hole|> };
};
exports.prepareResponseObject = function(res, callback) {
return {
success: function(result) {
callback(null, result);
},
error: function(error) {
callback(error);
}
};
};
var getRemoteAddress = exports.getRemoteAddress = function(req) {
return req.headers['x-real-ip'] || req.headers['x-forwarded-for'] || req.connection.remoteAddress
};
exports.endsWith = function(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
};<|fim▁end|> | sessionToken: (currentUser && currentUser.getSessionToken()) || (req && req.sessionToken) |
<|file_name|>browser_scanbox.py<|end_file_name|><|fim▁begin|># Copyright (C) 2015 Will Metcalf [email protected]
#
# 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,<|fim▁hole|># 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/>.
from lib.cuckoo.common.abstracts import Signature
class BrowserScanbox(Signature):
name = "browser_scanbox"
description = "Scanbox Activity in Browser"
weight = 3
severity = 3
categories = ["exploit"]
authors = ["Will Metcalf"]
minimum = "1.3"
evented = True
def __init__(self, *args, **kwargs):
Signature.__init__(self, *args, **kwargs)
filter_categories = set(["browser"])
# backward compat
filter_apinames = set(["JsEval", "COleScript_Compile", "COleScript_ParseScriptText"])
def on_call(self, call, process):
if call["api"] == "JsEval":
buf = self.get_argument(call, "Javascript")
else:
buf = self.get_argument(call, "Script")
if 'softwarelist.push(' in buf.lower() and 'indexof("-2147023083")' in buf.lower():
return True
elif 'var logger' in buf.lower() and 'document.onkeypress = keypress;' in buf.lower() and 'setinterval(sendchar,' in buf.lower():
return True<|fim▁end|> | |
<|file_name|>dtools.js<|end_file_name|><|fim▁begin|>function handleDialogRequest(dialogName, xhr, status, args) {
if (!args.success) {
PF(dialogName).jq.effect("shake", {times : 5}, 100);
} else {
PF(dialogName).hide();<|fim▁hole|>}<|fim▁end|> | } |
<|file_name|>vec-slices.rs<|end_file_name|><|fim▁begin|>// Copyright 2013-2014 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.
// ignore-android: FIXME(#10381)
// ignore-windows
// min-lldb-version: 310
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:run
// gdb-command:print empty.length
// gdb-check:$1 = 0
// gdb-command:print singleton.length
// gdb-check:$2 = 1
// gdb-command:print *((int64_t[1]*)(singleton.data_ptr))
// gdb-check:$3 = {1}
// gdb-command:print multiple.length
// gdb-check:$4 = 4
// gdb-command:print *((int64_t[4]*)(multiple.data_ptr))
// gdb-check:$5 = {2, 3, 4, 5}
// gdb-command:print slice_of_slice.length
// gdb-check:$6 = 2
// gdb-command:print *((int64_t[2]*)(slice_of_slice.data_ptr))
// gdb-check:$7 = {3, 4}
// gdb-command:print padded_tuple.length
// gdb-check:$8 = 2
// gdb-command:print padded_tuple.data_ptr[0]
// gdb-check:$9 = {6, 7}
// gdb-command:print padded_tuple.data_ptr[1]
// gdb-check:$10 = {8, 9}
// gdb-command:print padded_struct.length
// gdb-check:$11 = 2
// gdb-command:print padded_struct.data_ptr[0]
// gdb-check:$12 = {x = 10, y = 11, z = 12}
// gdb-command:print padded_struct.data_ptr[1]
// gdb-check:$13 = {x = 13, y = 14, z = 15}
// gdb-command:print 'vec_slices::MUT_VECT_SLICE'.length
// gdb-check:$14 = 2
// gdb-command:print *((int64_t[2]*)('vec_slices::MUT_VECT_SLICE'.data_ptr))
// gdb-check:$15 = {64, 65}
// === LLDB TESTS ==================================================================================
// lldb-command:run
// lldb-command:print empty
// lldb-check:[...]$0 = &[]
// lldb-command:print singleton
// lldb-check:[...]$1 = &[1]
// lldb-command:print multiple
// lldb-check:[...]$2 = &[2, 3, 4, 5]<|fim▁hole|>
// lldb-command:print slice_of_slice
// lldb-check:[...]$3 = &[3, 4]
// lldb-command:print padded_tuple
// lldb-check:[...]$4 = &[(6, 7), (8, 9)]
// lldb-command:print padded_struct
// lldb-check:[...]$5 = &[AStruct { x: 10, y: 11, z: 12 }, AStruct { x: 13, y: 14, z: 15 }]
#![allow(unused_variables)]
#![omit_gdb_pretty_printer_section]
struct AStruct {
x: i16,
y: i32,
z: i16
}
static VECT_SLICE: &'static [i64] = &[64, 65];
static mut MUT_VECT_SLICE: &'static [i64] = &[32];
fn main() {
let empty: &[i64] = &[];
let singleton: &[i64] = &[1];
let multiple: &[i64] = &[2, 3, 4, 5];
let slice_of_slice = &multiple[1..3];
let padded_tuple: &[(i32, i16)] = &[(6, 7), (8, 9)];
let padded_struct: &[AStruct] = &[
AStruct { x: 10, y: 11, z: 12 },
AStruct { x: 13, y: 14, z: 15 }
];
unsafe {
MUT_VECT_SLICE = VECT_SLICE;
}
zzz(); // #break
}
fn zzz() {()}<|fim▁end|> | |
<|file_name|>extensions.py<|end_file_name|><|fim▁begin|><|fim▁hole|>from notifications_utils.clients.redis.redis_client import RedisClient
from notifications_utils.clients.zendesk.zendesk_client import ZendeskClient
antivirus_client = AntivirusClient()
zendesk_client = ZendeskClient()
redis_client = RedisClient()<|fim▁end|> | from notifications_utils.clients.antivirus.antivirus_client import (
AntivirusClient,
) |
<|file_name|>test_basic_user_interaction_pending.py<|end_file_name|><|fim▁begin|>import time
from unittest import TestCase
from formalign.settings import CHROME_DRIVER, SERVER_URL
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import pyperclip
from helper_funcs.helpers_test import file_to_string
class BasicUserTestCaseChrome(TestCase):
def setUp(self):
self.browser = webdriver.Chrome(
CHROME_DRIVER
)
self.sleep = 0
def tearDown(self):
self.browser.quit()
def test_basic_user_experience(self):
"""
Tests basic user interaction with formalign.eu site
:return:
"""
# Lambda user is a biologist who has to make a nice figure containing a multiple alignment for a presentation.
# She visits the formalign.eu site.
self.browser.get(SERVER_URL + '/')
# User sees she's on the right page because she can see the name of the site in the heading.
self.assertEqual(self.browser.title, 'Formalign.eu Home', self.browser.title)
brand_element = self.browser.find_element_by_css_selector('.navbar-brand')
self.assertEqual('Formalign.eu', brand_element.text)
# She sees a form that says 'Paste in your alignment in FASTA format:'
alignment_input = self.browser.find_element_by_css_selector('textarea#id_align_input')
self.assertIsNotNone(self.browser.find_element_by_css_selector('label[for="id_align_input"]'))
self.assertEqual(
'Alignment (FASTA, clustalw, stockholm or phylip)',
alignment_input.get_attribute('placeholder'),
)
# She sees two radio buttons for DNA and protein
dna_button = self.browser.find_element_by_css_selector('input#id_seq_type_1')
self.assertIsNotNone(dna_button)
protein_button = self.browser.find_element_by_css_selector('input#id_seq_type_0')
self.assertIsNotNone(protein_button)
# She sees that the DNA button is selected by default
self.assertEqual(dna_button.is_selected(), True)
# She clicks the Protein radio button and sees that it gets selected and the DNA button gets unselected
protein_button.click()
self.assertEqual(protein_button.is_selected(), True)
self.assertEqual(dna_button.is_selected(), False)
# She pastes in a protein alignment to see what happens
alignment_string = file_to_string('spa_protein_alignment.fasta')
pyperclip.copy(alignment_string)
alignment_input = self.browser.find_element_by_css_selector('textarea#id_align_input')
alignment_input.send_keys(Keys.CONTROL, 'v')
self.browser.find_element_by_id('submit-align').click()
# Wait for Firefox
time.sleep(self.sleep)
# She is redirected to a page showing the submitted sequences from her alignment and a simple consensus sequence
self.assertEqual(self.browser.title, 'Formalign.eu Sequence Display', self.browser.title)
seq_content = self.browser.find_elements_by_css_selector('.query_seq_display')
self.assertIsNotNone(seq_content)
for f in seq_content:
self.assertTrue(len(f.text) <= 80)
first_seq_info = self.browser.find_elements_by_css_selector('.query_seq_meta')[0]
self.assertEqual(
'NP_175717 NP_175717.1 SPA1-related 4 protein [Arabidopsis thaliana].:',
first_seq_info.text,
first_seq_info.text
)
first_seq_content = self.browser.find_elements_by_css_selector('.query_seq_display')[0]
self.assertIsNotNone(first_seq_content)
self.assertEqual(first_seq_content.text, '-' * 80)
consensus_seq = self.browser.find_elements_by_xpath(
'//div[@class="query_seq bg-color-body"]'
)[-1].find_elements_by_xpath('./p[@class="query_seq_display"]')[0]
self.assertIsNotNone(consensus_seq)
cons_seq = file_to_string('consensus.txt')
self.assertEqual(consensus_seq.text, cons_seq[:80])<|fim▁hole|> render_button = self.browser.find_element_by_css_selector('button#render-align')
self.assertIsNotNone(render_button)
render_button.click()
# Wait for Firefox
time.sleep(self.sleep)
# She is redirected to the alignment display page
self.assertEqual('Formalign.eu Alignment Display', self.browser.title, self.browser.title)
# She sees the alignment displayed with 80 characters per line in blocks of 10 with sequence ids
s0 = self.browser.find_elements_by_xpath(
'//tr[@class="al_ln"]'
)[10].find_elements_by_xpath('./td[@class="residue S0"]')
s1 = self.browser.find_elements_by_xpath(
'//tr[@class="al_ln"]'
)[10].find_elements_by_xpath('./td[@class="residue S1"]')
self.assertEqual(len(s0) + len(s1), 80)
sep = self.browser.find_elements_by_xpath(
'//tr[@class="al_ln"]'
)[10].find_elements_by_xpath('./td[@class="block_sep"]')
self.assertEqual(len(sep), 8)
# She is quite happy with the result and decides to try with another alignment so she navigates back to the
# home page
home_button = self.browser.find_element_by_css_selector('.navbar-brand')
home_button.click()
self.assertEqual(self.browser.title, 'Formalign.eu Home', self.browser.title)
# She wants to upload a protein stockholm alignment this time from a file
# She clicks the Protein radio button and sees that it gets selected and the DNA button gets unselected
protein_button = self.browser.find_element_by_css_selector('input#id_seq_type_0')
protein_button.click()
self.assertEqual(protein_button.is_selected(), True)
# She sees a file upload button
self.fail('Incomplete Test')
def test_file_upload(self):
# User visits the formalign.eu site
self.browser.get(SERVER_URL + '/')
# She wants to upload a protein stockholm alignment this time from a file
# She clicks the Protein radio button and sees that it gets selected and the DNA button gets unselected
protein_button = self.browser.find_element_by_css_selector('input#id_seq_type_0')
protein_button.click()
self.assertEqual(protein_button.is_selected(), True)
# She sees a file upload button
alignment_input = self.browser.find_element_by_css_selector('file_upload#id_align_input')
alignment_input.click()
# She browses to her file and selects it
# She submits her file
self.browser.find_element_by_id('submit-align').click()
self.fail('Incomplete Test')<|fim▁end|> | consensus_meta = self.browser.find_elements_by_xpath('//h3[@class="query_seq_meta bg-color-body"]')[-1]
self.assertEqual(consensus_meta.text, 'consensus 70%:')
# She is happy with the result, sees a "Render" button and clicks it. |
<|file_name|>PlainCalendarDayNamesHeader.js<|end_file_name|><|fim▁begin|>import CalendarDayNamesHeader from "../base/CalendarDayNamesHeader.js";
import { template } from "../base/internal.js";
import { fragmentFrom } from "../core/htmlLiterals.js";
/**
* CalendarDayNamesHeader component in the Plain reference design system
*
* @inherits CalendarDayNamesHeader
*/
class PlainCalendarDayNamesHeader extends CalendarDayNamesHeader {
get [template]() {
const result = super[template];
result.content.append(
fragmentFrom.html`
<style>
:host {
font-size: smaller;
}
[part~="day-name"] {
padding: 0.3em;
text-align: center;<|fim▁hole|> [weekend] {
color: gray;
}
</style>
`
);
return result;
}
}
export default PlainCalendarDayNamesHeader;<|fim▁end|> | white-space: nowrap;
}
|
<|file_name|>DeregisterEcsClusterResult.java<|end_file_name|><|fim▁begin|>/*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
* <|fim▁hole|> * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.opsworks.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/opsworks-2013-02-18/DeregisterEcsCluster" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DeregisterEcsClusterResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof DeregisterEcsClusterResult == false)
return false;
DeregisterEcsClusterResult other = (DeregisterEcsClusterResult) obj;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
return hashCode;
}
@Override
public DeregisterEcsClusterResult clone() {
try {
return (DeregisterEcsClusterResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}<|fim▁end|> | * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR |
<|file_name|>test.rs<|end_file_name|><|fim▁begin|>#[macro_use]
extern crate nix;
#[macro_use]
extern crate lazy_static;
extern crate libc;
extern crate rand;
extern crate tempdir;
extern crate tempfile;
extern crate nix_test as nixtest;
mod sys;
mod test_fcntl;
#[cfg(target_os = "linux")]
mod test_mq;
mod test_net;
mod test_nix_path;
#[cfg(any(target_os = "linux", target_os = "macos"))]
mod test_poll;
mod test_pty;
#[cfg(any(target_os = "linux", target_os = "android"))]
mod test_sendfile;
mod test_stat;
mod test_unistd;<|fim▁hole|>use std::sync::Mutex;
use nix::unistd::read;
/// Helper function analogous to std::io::Read::read_exact, but for `RawFD`s
fn read_exact(f: RawFd, buf: &mut [u8]) {
let mut len = 0;
while len < buf.len() {
// get_mut would be better than split_at_mut, but it requires nightly
let (_, remaining) = buf.split_at_mut(len);
len += read(f, remaining).unwrap();
}
}
lazy_static! {
/// Any test that changes the process's current working directory must grab
/// this mutex
pub static ref CWD_MTX: Mutex<()> = Mutex::new(());
/// Any test that creates child processes must grab this mutex, regardless
/// of what it does with those children.
pub static ref FORK_MTX: Mutex<()> = Mutex::new(());
/// Any test that calls ptsname(3) must grab this mutex.
pub static ref PTSNAME_MTX: Mutex<()> = Mutex::new(());
/// Any test that alters signal handling must grab this mutex.
pub static ref SIGNAL_MTX: Mutex<()> = Mutex::new(());
}
#[test]
pub fn test_size_of_long() {
// This test is mostly here to ensure that 32bit CI is correctly
// functioning
assert_size_of::<usize>("long");
}<|fim▁end|> |
use nixtest::assert_size_of;
use std::os::unix::io::RawFd; |
<|file_name|>ember-cli-build-options.js<|end_file_name|><|fim▁begin|>'use strict';
/**
* Configuration options for Ember CLI App used to manage broccoli build tree for DataHub web.
* Returns a method to import build dependencies and an options
* object with configuration attributes
*
* @param {string} env current build application environment
* @returns { options: object }
*/
module.exports = function(env) {
const isTesting = env === 'test';
const isProduction = env === 'production';
return {
options: {
// Configuration options for ember-auto-import library
autoImport: {
// Note: restliparams has an outDir of lib, but autoImport looks for dist
alias: {
restliparams: 'restliparams/lib'
},
webpack: {
node: {
// this will add support for 'require('path')' in browsers
// this is needed by minimatch dependency
path: true
}
},
exclude: ['@glimmer/tracking']
},
// Configurations options for ember-ace editor library
ace: isTesting
? {}
: {
modes: ['json', 'graphqlschema', 'text'],
workers: ['json', 'graphqlschema', 'text'],
exts: ['searchbox']
},
babel: {
sourceMaps: env === 'development' ? 'inline' : false,
targets: {
browsers: ['last 3 versions']
}
},
'ember-cli-babel': {
includePolyfill: !isTesting
},
storeConfigInMeta: false,
SRI: {
enabled: false
},
fingerprint: {
enabled: isProduction
},
'ember-cli-uglify': {
enabled: isProduction,
// Improve build times by using the Fast Minify Mode
// For our internal use case, app load times are not a significant bottleneck currently
// https://github.com/mishoo/UglifyJS2#uglify-fast-minify-mode
uglify: {
compress: false,
mangle: true
}
},
outputPaths: {
app: {
html: 'index.html',
css: {
app: '/assets/datahub-web.css'
},<|fim▁hole|>
js: '/assets/datahub-web.js'
},
vendor: {
css: '/assets/vendor.css',
js: '/assets/vendor.js'
}
},
svgJar: {
sourceDirs: ['public/assets/images/svgs']
},
// Configuration options specifying inclusion of Mirage addon files in the application tree
'mirage-from-addon': {
includeAll: true,
exclude: [/scenarios\/default/, /config/]
}
}
};
};<|fim▁end|> | |
<|file_name|>align.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
"""
Copyright 2017 Ryan Wick ([email protected])
https://github.com/rrwick/Porechop
Porechop makes use of C++ functions which are compiled in cpp_functions.so. This module uses ctypes
to wrap them in similarly named Python functions.
This file is part of Porechop. Porechop 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. Porechop 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 Porechop. If
not, see <http://www.gnu.org/licenses/>.
"""
import os
import sys
from ctypes import CDLL, cast, c_char_p, c_int, c_void_p
from multiprocessing.dummy import Pool as ThreadPool
import numpy as np
import tqdm
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
SO_FILE = 'cpp_functions.so'
SO_FILE_FULL = os.path.join(os.path.dirname(os.path.realpath(__file__)), SO_FILE)
if not os.path.isfile(SO_FILE_FULL):
sys.exit('could not find ' + SO_FILE + ' - please reinstall')
C_LIB = CDLL(SO_FILE_FULL)<|fim▁hole|> c_int, # Mismatch score
c_int, # Gap open score
c_int] # Gap extension score
C_LIB.adapterAlignment.restype = c_void_p # String describing alignment
# This function cleans up the heap memory for the C strings returned by the other C functions. It
# must be called after them.
C_LIB.freeCString.argtypes = [c_void_p]
C_LIB.freeCString.restype = None
def adapter_alignment(read_sequence, adapter_sequence, scoring_scheme_vals, alignm_score_value, out_filename, threads, min_length):
#print(read_sequence, adapter_sequence, scoring_scheme_vals, alignm_score_value, out_filename, threads,
# min_length)
"""
Python wrapper for adapterAlignment C++ function.
"""
alignm_score_value = int(alignm_score_value)
sys.stdout.write("### STARTING ADAPTER ALIGNMENT AND READS ORIENTATION ###\n")
list_adapter = []
list_run = []
for adapter in SeqIO.parse(adapter_sequence, "fasta"):
list_adapter.append(adapter)
record = SeqRecord(adapter.seq.reverse_complement(), id=adapter.id + "_rev")
list_adapter.append(record)
dict_aln = {}
for sequence in SeqIO.parse(read_sequence, "fasta"):
dict_aln[sequence.id] = ""
for adapter in list_adapter:
match_score = scoring_scheme_vals[0]
mismatch_score = scoring_scheme_vals[1]
gap_open_score = scoring_scheme_vals[2]
gap_extend_score = scoring_scheme_vals[3]
list_run.append([str(sequence.seq).encode('utf-8'), str(adapter.seq).encode('utf-8'), match_score,
mismatch_score, gap_open_score, gap_extend_score, sequence.id, adapter.id])
#print(dict_aln)
with ThreadPool(int(threads)) as pool:
for out in pool.imap(align, tqdm.tqdm(list_run)):
out_list = out.split(",")
#print(out_list)
if dict_aln[out_list[0]] != "":
if (float(out.split(",")[9])) > float(dict_aln[out_list[0]].split(",")[9]):
dict_aln[out.split(",")[0]] = out
else:
dict_aln[out.split(",")[0]] = out
good_reads = [float(dict_aln[key].split(",")[9]) for key in dict_aln if float(dict_aln[key].split(",")[9]) > 80]
if len(good_reads)/len(dict_aln) < 0.1:
sys.stdout.write("### THERE ARE FEW READS (<10%) THAT MATCH WITH THE ADAPTER SEQUENCE WITH A GOOD IDENITTY (>80%). SWITCHING TO NON-STRANDED MODE ###\n")
stranded_value = False
return (len(dict_aln), read_sequence, stranded_value)
else:
sys.stdout.write("### ABOUT " + str((len(dict_aln)/len(list_run))*100) + " MATCH TO AN ADAPTER ###\n")
stranded_value = True
if alignm_score_value == 0:
alignm_score_mean = np.mean([float(dict_aln[key].split(",")[9]) for key in dict_aln])
alignm_score_std = np.std([float(dict_aln[key].split(",")[9]) for key in dict_aln])
alignm_score_value = alignm_score_mean - (alignm_score_std/10)
#print(alignm_score_mean, alignm_score_std, alignm_score_value)
seq_to_keep = {}
for key in dict_aln:
if (float(dict_aln[key].split(",")[9])) > alignm_score_value:
seq_to_keep[key] = dict_aln[key]
#print (seq_to_keep[key])
with open(out_filename, "w") as output_handle:
for sequence in tqdm.tqdm(SeqIO.parse(read_sequence, "fasta")):
count = 0
if sequence.id in seq_to_keep:
if seq_to_keep[sequence.id].split(",")[1].endswith("rev"):
position = [seq_to_keep[sequence.id].split(",")[2], seq_to_keep[sequence.id].split(",")[3]]
seq = str(sequence.seq)
sequence_match = seq[int(position[0]):int(position[1])]
multiple_seq = seq.split(sequence_match)
full_multiple_seq_all = [seq_full for seq_full in multiple_seq if seq_full != ""]
full_multiple_seq = [seq_full for seq_full in full_multiple_seq_all if len(seq_full) > int(min_length)]
if len(full_multiple_seq) > 1:
for split_seq in full_multiple_seq:
count += 1
sequence_new = SeqRecord(Seq(split_seq), id=sequence.id, description="REV")
rev_seq = SeqRecord(sequence_new.seq.reverse_complement(), id=sequence.id + "_rev." + str(count))
SeqIO.write(rev_seq, output_handle, "fasta")
elif len(full_multiple_seq) == 1:
sequence_new = SeqRecord(Seq(full_multiple_seq[0]), id=sequence.id)
rev_seq = SeqRecord(sequence_new.seq.reverse_complement(), id=sequence.id + "_rev")
SeqIO.write(rev_seq, output_handle, "fasta")
else:
continue
else:
position = [seq_to_keep[sequence.id].split(",")[2], seq_to_keep[sequence.id].split(",")[3]]
seq = str(sequence.seq)
sequence_match = seq[int(position[0]):int(position[1])]
multiple_seq = seq.split(sequence_match)
full_multiple_seq_all = [seq_full for seq_full in multiple_seq if seq_full != ""]
full_multiple_seq = [seq_full for seq_full in full_multiple_seq_all if len(seq_full) > int(min_length)]
if len(full_multiple_seq) > 1:
for split_seq in full_multiple_seq:
count += 1
sequence_new = SeqRecord(Seq(split_seq), id=sequence.id + "." + str(count))
SeqIO.write(sequence_new, output_handle, "fasta")
elif len(full_multiple_seq) == 1:
sequence_new = SeqRecord(Seq(full_multiple_seq[0]), id=sequence.id)
SeqIO.write(sequence_new, output_handle, "fasta")
else:
continue
return (len(seq_to_keep), out_filename, stranded_value)
def align(command_in):
ptr = C_LIB.adapterAlignment(str(command_in[0]).encode('utf-8'), str(command_in[1]).encode('utf-8'),
command_in[2], command_in[3], command_in[4], command_in[5])
result_string = c_string_to_python_string(ptr)
single_result_string = result_string.split(",")
average_score = (float(single_result_string[5]) + float(single_result_string[6])) / 2
result_string_name = ",".join([command_in[6], command_in[7], result_string, str(average_score)])
return result_string_name
def c_string_to_python_string(c_string):
"""
This function casts a C string to a Python string and then calls a function to delete the C
string from the heap.
"""
python_string = cast(c_string, c_char_p).value.decode()
C_LIB.freeCString(c_string)
return python_string
#if __name__ == '__main__':
# scoring = [3, -6, -5, -2]
# alignm_score_value = ""
# adapter_alignment(*sys.argv[1:], scoring, alignm_score_value)<|fim▁end|> |
C_LIB.adapterAlignment.argtypes = [c_char_p, # Read sequence
c_char_p, # Adapter sequence
c_int, # Match score |
<|file_name|>basicTimeSeries.js<|end_file_name|><|fim▁begin|>if (Highcharts != null) {
if (Highcharts.charts == null) {
Highcharts.charts = {};
}
if (Highcharts.getChart == null) {
Highcharts.getChart = function(chartId, containerId) {
var opts = Highcharts.charts[chartId];
opts.chart.renderTo = containerId;
return opts;
}
}
Highcharts.charts['basicTimeSeries'] = {
chart: {
renderTo: 'container',
type: 'spline',
animation: false
},
title: {
text: 'Sentiment'
},<|fim▁hole|> type: 'datetime'
},
yAxis: {
title: {
text: 'Coefficient (m)'
}
},
tooltip: {
shared: true
},
legend: {
enabled: false
}
}
}<|fim▁end|> | xAxis: { |
<|file_name|>spiflash.rs<|end_file_name|><|fim▁begin|>#![allow(dead_code)]
use core::cmp;
use csr;
const CMD_PP: u8 = 0x02;
const CMD_WRDI: u8 = 0x04;
const CMD_RDSR: u8 = 0x05;
const CMD_WREN: u8 = 0x06;
const CMD_SE: u8 = 0xd8;
const PIN_CLK: u8 = 1 << 1;
const PIN_CS_N: u8 = 1 << 2;
const PIN_DQ_I: u8 = 1 << 3;
const SR_WIP: u8 = 1;
fn write_byte(mut byte: u8) {
unsafe {
csr::spiflash::bitbang_write(0);
for _ in 0..8 {
csr::spiflash::bitbang_write((byte & 0x80) >> 7);
csr::spiflash::bitbang_write((byte & 0x80) >> 7 | PIN_CLK);
byte <<= 1;
}
csr::spiflash::bitbang_write(0);
}
}
fn write_addr(mut addr: usize) {
unsafe {
csr::spiflash::bitbang_write(0);
for _ in 0..24 {
csr::spiflash::bitbang_write(((addr & 0x800000) >> 23) as u8);
csr::spiflash::bitbang_write(((addr & 0x800000) >> 23) as u8 | PIN_CLK);
addr <<= 1;
}
csr::spiflash::bitbang_write(0);
}
}
fn wait_until_ready() {
unsafe {
loop {<|fim▁hole|> write_byte(CMD_RDSR);
for _ in 0..8 {
sr <<= 1;
csr::spiflash::bitbang_write(PIN_DQ_I | PIN_CLK);
sr |= csr::spiflash::miso_read();
csr::spiflash::bitbang_write(PIN_DQ_I);
}
csr::spiflash::bitbang_write(0);
csr::spiflash::bitbang_write(PIN_CS_N);
if sr & SR_WIP == 0 {
return
}
}
}
}
pub fn erase_sector(addr: usize) {
unsafe {
let sector_addr = addr & !(csr::CONFIG_SPIFLASH_SECTOR_SIZE as usize - 1);
csr::spiflash::bitbang_en_write(1);
wait_until_ready();
write_byte(CMD_WREN);
csr::spiflash::bitbang_write(PIN_CS_N);
write_byte(CMD_SE);
write_addr(sector_addr);
csr::spiflash::bitbang_write(PIN_CS_N);
wait_until_ready();
csr::spiflash::bitbang_en_write(0);
}
}
fn write_page(addr: usize, data: &[u8]) {
unsafe {
csr::spiflash::bitbang_en_write(1);
wait_until_ready();
write_byte(CMD_WREN);
csr::spiflash::bitbang_write(PIN_CS_N);
write_byte(CMD_PP);
write_addr(addr);
for &byte in data {
write_byte(byte)
}
csr::spiflash::bitbang_write(PIN_CS_N);
csr::spiflash::bitbang_write(0);
wait_until_ready();
csr::spiflash::bitbang_en_write(0);
}
}
const PAGE_SIZE: usize = csr::CONFIG_SPIFLASH_PAGE_SIZE as usize;
const PAGE_MASK: usize = PAGE_SIZE - 1;
pub fn write(mut addr: usize, mut data: &[u8]) {
if addr & PAGE_MASK != 0 {
let size = cmp::min((PAGE_SIZE - (addr & PAGE_MASK)) as usize, data.len());
write_page(addr, &data[..size]);
addr += size;
data = &data[size..];
}
while data.len() > 0 {
let size = cmp::min(PAGE_SIZE as usize, data.len());
write_page(addr, &data[..size]);
addr += size;
data = &data[size..];
}
}<|fim▁end|> | let mut sr = 0; |
<|file_name|>drag-and-drop.js<|end_file_name|><|fim▁begin|>/**
* @license Copyright 2017 Google Inc. All Rights Reserved.<|fim▁hole|> */
'use strict';
/**
* Manages drag and drop file input for the page.
*/
class DragAndDrop {
/**
* @param {function(!File)} fileHandlerCallback Invoked when the user chooses a new file.
*/
constructor(fileHandlerCallback) {
this._dropZone = document.querySelector('.drop_zone');
this._fileHandlerCallback = fileHandlerCallback;
this._dragging = false;
this._addListeners();
}
_addListeners() {
// The mouseleave event is more reliable than dragleave when the user drops
// the file outside the window.
document.addEventListener('mouseleave', _ => {
if (!this._dragging) {
return;
}
this._resetDraggingUI();
});
document.addEventListener('dragover', e => {
e.stopPropagation();
e.preventDefault();
e.dataTransfer.dropEffect = 'copy'; // Explicitly show as copy action.
});
document.addEventListener('dragenter', _ => {
this._dropZone.classList.add('dropping');
this._dragging = true;
});
document.addEventListener('drop', e => {
e.stopPropagation();
e.preventDefault();
this._resetDraggingUI();
// Note, this ignores multiple files in the drop, only taking the first.
this._fileHandlerCallback(e.dataTransfer.files[0]);
});
}
_resetDraggingUI() {
this._dropZone.classList.remove('dropping');
this._dragging = false;
}
}
if (typeof module !== 'undefined' && module.exports) {
module.exports = DragAndDrop;
}<|fim▁end|> | * 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. |
<|file_name|>index.d.ts<|end_file_name|><|fim▁begin|>// Type definitions for auth0-lock 10.9
// Project: http://auth0.com
// Definitions by: Brian Caruso <https://github.com/carusology>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="auth0-js/v7" />
interface Auth0LockAdditionalSignUpFieldOption {
value: string;
label: string;
}
type Auth0LockAdditionalSignUpFieldOptionsCallback =
(error: Auth0Error, options: Auth0LockAdditionalSignUpFieldOption[]) => void;
type Auth0LockAdditionalSignUpFieldOptionsFunction =
(callback: Auth0LockAdditionalSignUpFieldOptionsCallback) => void;
type Auth0LockAdditionalSignUpFieldPrefillCallback =
(error: Auth0Error, prefill: string) => void;
type Auth0LockAdditionalSignUpFieldPrefillFunction =
(callback: Auth0LockAdditionalSignUpFieldPrefillCallback) => void;
interface Auth0LockAdditionalSignUpField {
icon?: string;
name: string;
options?: Auth0LockAdditionalSignUpFieldOption[] | Auth0LockAdditionalSignUpFieldOptionsFunction;
placeholder: string;
prefill?: string | Auth0LockAdditionalSignUpFieldPrefillFunction;
type?: "select" | "text";
validator?: (input: string) => { valid: boolean; hint?: string };
}
type Auth0LockAvatarUrlCallback = (error: Auth0Error, url: string) => void;
type Auth0LockAvatarDisplayNameCallback = (error: Auth0Error, displayName: string) => void;
interface Auth0LockAvatarOptions {
url: (email: string, callback: Auth0LockAvatarUrlCallback) => void;
displayName: (email: string, callback: Auth0LockAvatarDisplayNameCallback) => void;
}
interface Auth0LockThemeOptions {
logo?: string;
primaryColor?: string;
}
// https://auth0.com/docs/libraries/lock/v10/sending-authentication-parameters
interface Auth0LockAuthParamsOptions {
access_token?: any;
connection_scopes?: any;
device?: any;
nonce?: any;
protocol?: any;
request_id?: any;
scope?: string;
state?: string;
}
interface Auth0LockAuthOptions {
params?: Auth0LockAuthParamsOptions;
redirect?: boolean;
redirectUrl?: string;
responseType?: string;
sso?: boolean;<|fim▁hole|>}
interface Auth0LockPopupOptions {
width: number;
height: number;
left: number;
top: number;
}
interface Auth0LockConstructorOptions {
additionalSignUpFields?: Auth0LockAdditionalSignUpField[];
allowedConnections?: string[];
allowForgotPassword?: boolean;
allowLogin?: boolean;
allowSignUp?: boolean;
assetsUrl?: string;
auth?: Auth0LockAuthOptions;
autoclose?: boolean;
autofocus?: boolean;
avatar?: Auth0LockAvatarOptions;
closable?: boolean;
container?: string;
defaultADUsernameFromEmailPrefix?: string;
defaultDatabaseConnection?: string;
defaultEnterpriseConnection?: string;
forgotPasswordLink?: string;
initialScreen?: "login" | "signUp" | "forgotPassword";
language?: string;
languageDictionary?: any;
loginAfterSignUp?: boolean;
mustAcceptTerms?: boolean;
popupOptions?: Auth0LockPopupOptions;
prefill?: { email?: string, username?: string};
rememberLastLogin?: boolean;
signupLink?: string;
socialButtonStyle?: "big" | "small";
theme?: Auth0LockThemeOptions;
usernameStyle?: string;
}
interface Auth0LockFlashMessageOptions {
type: "success" | "error";
text: string;
}
interface Auth0LockShowOptions {
allowedConnections?: string[];
allowForgotPassword?: boolean;
allowLogin?: boolean;
allowSignUp?: boolean;
auth?: Auth0LockAuthOptions;
initialScreen?: "login" | "signUp" | "forgotPassword";
flashMessage?: Auth0LockFlashMessageOptions;
rememberLastLogin?: boolean;
}
interface Auth0LockStatic {
new (clientId: string, domain: string, options?: Auth0LockConstructorOptions): Auth0LockStatic;
// deprecated
getProfile(token: string, callback: (error: Auth0Error, profile: Auth0UserProfile) => void): void;
getUserInfo(token: string, callback: (error: Auth0Error, profile: Auth0UserProfile) => void): void;
show(options?: Auth0LockShowOptions): void;
hide(): void;
logout(query: any): void;
on(event: "show" | "hide", callback: () => void): void;
on(event: "unrecoverable_error" | "authorization_error", callback: (error: Auth0Error) => void): void;
on(event: "authenticated", callback: (authResult: any) => void): void;
on(event: string, callback: (...args: any[]) => void): void;
}
declare var Auth0Lock: Auth0LockStatic;
declare module "auth0-lock" {
export default Auth0Lock;
}<|fim▁end|> | |
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>// Copyright 2013 The rust-gobject authors.
//<|fim▁hole|>// 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.
use glib;
use std::ptr;
mod native;
pub unsafe fn g_object_ref(object: glib::gpointer) -> glib::gpointer {
#[fixed_stack_segment]; #[inline(never)];
assert!(ptr::is_not_null(object));
native::g_object_ref(object)
}
pub unsafe fn g_object_ref_sink(object: glib::gpointer) -> glib::gpointer {
#[fixed_stack_segment]; #[inline(never)];
assert!(ptr::is_not_null(object));
native::g_object_ref_sink(object)
}
pub unsafe fn g_object_unref(object: glib::gpointer) {
#[fixed_stack_segment]; #[inline(never)];
assert!(ptr::is_not_null(object));
native::g_object_unref(object)
}<|fim▁end|> | |
<|file_name|>20.d.ts<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|> | export { LocationCompanyFilled20 as default } from "../../"; |
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>// Copyright 2017 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.
//! This code is kind of an alternate way of doing subtyping,
//! supertyping, and type equating, distinct from the `combine.rs`
//! code but very similar in its effect and design. Eventually the two
//! ought to be merged. This code is intended for use in NLL and chalk.
//!
//! Here are the key differences:
//!
//! - This code may choose to bypass some checks (e.g., the occurs check)
//! in the case where we know that there are no unbound type inference
//! variables. This is the case for NLL, because at NLL time types are fully
//! inferred up-to regions.
//! - This code uses "universes" to handle higher-ranked regions and
//! not the leak-check. This is "more correct" than what rustc does
//! and we are generally migrating in this direction, but NLL had to
//! get there first.
//!
//! Also, this code assumes that there are no bound types at all, not even
//! free ones. This is ok because:
//! - we are not relating anything quantified over some type variable
//! - we will have instantiated all the bound type vars already (the one
//! thing we relate in chalk are basically domain goals and their
//! constituents)
use crate::infer::InferCtxt;
use crate::ty::fold::{TypeFoldable, TypeVisitor};
use crate::ty::relate::{self, Relate, RelateResult, TypeRelation};
use crate::ty::subst::Kind;
use crate::ty::{self, Ty, TyCtxt};
use crate::ty::error::TypeError;
use crate::traits::DomainGoal;
use rustc_data_structures::fx::FxHashMap;
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub enum NormalizationStrategy {
Lazy,
Eager,
}
pub struct TypeRelating<'me, 'gcx: 'tcx, 'tcx: 'me, D>
where
D: TypeRelatingDelegate<'tcx>,
{
infcx: &'me InferCtxt<'me, 'gcx, 'tcx>,
/// Callback to use when we deduce an outlives relationship
delegate: D,
/// How are we relating `a` and `b`?
///
/// - covariant means `a <: b`
/// - contravariant means `b <: a`
/// - invariant means `a == b
/// - bivariant means that it doesn't matter
ambient_variance: ty::Variance,
/// When we pass through a set of binders (e.g., when looking into
/// a `fn` type), we push a new bound region scope onto here. This
/// will contain the instantiated region for each region in those
/// binders. When we then encounter a `ReLateBound(d, br)`, we can
/// use the debruijn index `d` to find the right scope, and then
/// bound region name `br` to find the specific instantiation from
/// within that scope. See `replace_bound_region`.
///
/// This field stores the instantiations for late-bound regions in
/// the `a` type.
a_scopes: Vec<BoundRegionScope<'tcx>>,
/// Same as `a_scopes`, but for the `b` type.
b_scopes: Vec<BoundRegionScope<'tcx>>,
}
pub trait TypeRelatingDelegate<'tcx> {
/// Push a constraint `sup: sub` -- this constraint must be
/// satisfied for the two types to be related. `sub` and `sup` may
/// be regions from the type or new variables created through the
/// delegate.
fn push_outlives(&mut self, sup: ty::Region<'tcx>, sub: ty::Region<'tcx>);
/// Push a domain goal that will need to be proved for the two types to
/// be related. Used for lazy normalization.
fn push_domain_goal(&mut self, domain_goal: DomainGoal<'tcx>);
/// Creates a new universe index. Used when instantiating placeholders.
fn create_next_universe(&mut self) -> ty::UniverseIndex;
/// Creates a new region variable representing a higher-ranked
/// region that is instantiated existentially. This creates an
/// inference variable, typically.
///
/// So e.g., if you have `for<'a> fn(..) <: for<'b> fn(..)`, then
/// we will invoke this method to instantiate `'a` with an
/// inference variable (though `'b` would be instantiated first,
/// as a placeholder).
fn next_existential_region_var(&mut self) -> ty::Region<'tcx>;
/// Creates a new region variable representing a
/// higher-ranked region that is instantiated universally.
/// This creates a new region placeholder, typically.
///
/// So e.g., if you have `for<'a> fn(..) <: for<'b> fn(..)`, then
/// we will invoke this method to instantiate `'b` with a
/// placeholder region.
fn next_placeholder_region(&mut self, placeholder: ty::PlaceholderRegion) -> ty::Region<'tcx>;
/// Creates a new existential region in the given universe. This
/// is used when handling subtyping and type variables -- if we
/// have that `?X <: Foo<'a>`, for example, we would instantiate
/// `?X` with a type like `Foo<'?0>` where `'?0` is a fresh
/// existential variable created by this function. We would then
/// relate `Foo<'?0>` with `Foo<'a>` (and probably add an outlives
/// relation stating that `'?0: 'a`).
fn generalize_existential(&mut self, universe: ty::UniverseIndex) -> ty::Region<'tcx>;
/// Define the normalization strategy to use, eager or lazy.
fn normalization() -> NormalizationStrategy;
/// Enable some optimizations if we do not expect inference variables
/// in the RHS of the relation.
fn forbid_inference_vars() -> bool;
}
#[derive(Clone, Debug)]
struct ScopesAndKind<'tcx> {
scopes: Vec<BoundRegionScope<'tcx>>,
kind: Kind<'tcx>,
}
#[derive(Clone, Debug, Default)]
struct BoundRegionScope<'tcx> {
map: FxHashMap<ty::BoundRegion, ty::Region<'tcx>>,
}
#[derive(Copy, Clone)]
struct UniversallyQuantified(bool);
impl<'me, 'gcx, 'tcx, D> TypeRelating<'me, 'gcx, 'tcx, D>
where
D: TypeRelatingDelegate<'tcx>,
{
pub fn new(
infcx: &'me InferCtxt<'me, 'gcx, 'tcx>,
delegate: D,
ambient_variance: ty::Variance,
) -> Self {
Self {
infcx,
delegate,
ambient_variance,
a_scopes: vec![],
b_scopes: vec![],
}
}
fn ambient_covariance(&self) -> bool {
match self.ambient_variance {
ty::Variance::Covariant | ty::Variance::Invariant => true,
ty::Variance::Contravariant | ty::Variance::Bivariant => false,
}
}
fn ambient_contravariance(&self) -> bool {
match self.ambient_variance {
ty::Variance::Contravariant | ty::Variance::Invariant => true,
ty::Variance::Covariant | ty::Variance::Bivariant => false,
}
}
fn create_scope(
&mut self,
value: &ty::Binder<impl TypeFoldable<'tcx>>,
universally_quantified: UniversallyQuantified,
) -> BoundRegionScope<'tcx> {
let mut scope = BoundRegionScope::default();
// Create a callback that creates (via the delegate) either an
// existential or placeholder region as needed.
let mut next_region = {
let delegate = &mut self.delegate;
let mut lazy_universe = None;
move |br: ty::BoundRegion| {
if universally_quantified.0 {
// The first time this closure is called, create a
// new universe for the placeholders we will make
// from here out.
let universe = lazy_universe.unwrap_or_else(|| {
let universe = delegate.create_next_universe();
lazy_universe = Some(universe);
universe
});
let placeholder = ty::PlaceholderRegion { universe, name: br };
delegate.next_placeholder_region(placeholder)
} else {
delegate.next_existential_region_var()
}
}
};
value.skip_binder().visit_with(&mut ScopeInstantiator {
next_region: &mut next_region,
target_index: ty::INNERMOST,
bound_region_scope: &mut scope,
});
scope
}
/// When we encounter binders during the type traversal, we record
/// the value to substitute for each of the things contained in
/// that binder. (This will be either a universal placeholder or
/// an existential inference variable.) Given the debruijn index
/// `debruijn` (and name `br`) of some binder we have now
/// encountered, this routine finds the value that we instantiated
/// the region with; to do so, it indexes backwards into the list
/// of ambient scopes `scopes`.
fn lookup_bound_region(
debruijn: ty::DebruijnIndex,
br: &ty::BoundRegion,
first_free_index: ty::DebruijnIndex,
scopes: &[BoundRegionScope<'tcx>],
) -> ty::Region<'tcx> {
// The debruijn index is a "reverse index" into the
// scopes listing. So when we have INNERMOST (0), we
// want the *last* scope pushed, and so forth.
let debruijn_index = debruijn.index() - first_free_index.index();
let scope = &scopes[scopes.len() - debruijn_index - 1];
// Find this bound region in that scope to map to a
// particular region.
scope.map[br]
}
/// If `r` is a bound region, find the scope in which it is bound
/// (from `scopes`) and return the value that we instantiated it
/// with. Otherwise just return `r`.
fn replace_bound_region(
&self,
r: ty::Region<'tcx>,
first_free_index: ty::DebruijnIndex,
scopes: &[BoundRegionScope<'tcx>],
) -> ty::Region<'tcx> {
if let ty::ReLateBound(debruijn, br) = r {
Self::lookup_bound_region(*debruijn, br, first_free_index, scopes)
} else {
r
}
}
/// Push a new outlives requirement into our output set of
/// constraints.
fn push_outlives(&mut self, sup: ty::Region<'tcx>, sub: ty::Region<'tcx>) {
debug!("push_outlives({:?}: {:?})", sup, sub);
self.delegate.push_outlives(sup, sub);
}
/// Relate a projection type and some value type lazily. This will always
/// succeed, but we push an additional `ProjectionEq` goal depending
/// on the value type:
/// - if the value type is any type `T` which is not a projection, we push
/// `ProjectionEq(projection = T)`.
/// - if the value type is another projection `other_projection`, we create
/// a new inference variable `?U` and push the two goals
/// `ProjectionEq(projection = ?U)`, `ProjectionEq(other_projection = ?U)`.
fn relate_projection_ty(
&mut self,
projection_ty: ty::ProjectionTy<'tcx>,
value_ty: ty::Ty<'tcx>
) -> Ty<'tcx> {
use crate::infer::type_variable::TypeVariableOrigin;
use crate::traits::WhereClause;
use syntax_pos::DUMMY_SP;
match value_ty.sty {
ty::Projection(other_projection_ty) => {
let var = self.infcx.next_ty_var(TypeVariableOrigin::MiscVariable(DUMMY_SP));
self.relate_projection_ty(projection_ty, var);
self.relate_projection_ty(other_projection_ty, var);
var
}
_ => {
let projection = ty::ProjectionPredicate {
projection_ty,
ty: value_ty,
};
self.delegate.push_domain_goal(
DomainGoal::Holds(WhereClause::ProjectionEq(projection))
);
value_ty
}
}
}
/// Relate a type inference variable with a value type.
fn relate_ty_var(
&mut self,
vid: ty::TyVid,
value_ty: Ty<'tcx>
) -> RelateResult<'tcx, Ty<'tcx>> {
debug!("relate_ty_var(vid={:?}, value_ty={:?})", vid, value_ty);
match value_ty.sty {
ty::Infer(ty::TyVar(value_vid)) => {
// Two type variables: just equate them.
self.infcx.type_variables.borrow_mut().equate(vid, value_vid);
return Ok(value_ty);
}
ty::Projection(projection_ty)
if D::normalization() == NormalizationStrategy::Lazy =>
{
return Ok(self.relate_projection_ty(projection_ty, self.infcx.tcx.mk_var(vid)));
}
_ => (),
}
let generalized_ty = self.generalize_value(value_ty, vid)?;
debug!("relate_ty_var: generalized_ty = {:?}", generalized_ty);
if D::forbid_inference_vars() {
// In NLL, we don't have type inference variables
// floating around, so we can do this rather imprecise
// variant of the occurs-check.
assert!(!generalized_ty.has_infer_types());
}
self.infcx.type_variables.borrow_mut().instantiate(vid, generalized_ty);
// The generalized values we extract from `canonical_var_values` have
// been fully instantiated and hence the set of scopes we have
// doesn't matter -- just to be sure, put an empty vector
// in there.
let old_a_scopes = ::std::mem::replace(&mut self.a_scopes, vec![]);
// Relate the generalized kind to the original one.
let result = self.relate(&generalized_ty, &value_ty);
// Restore the old scopes now.
self.a_scopes = old_a_scopes;
debug!("relate_ty_var: complete, result = {:?}", result);
result
}
fn generalize_value<T: Relate<'tcx>>(
&mut self,
value: T,
for_vid: ty::TyVid
) -> RelateResult<'tcx, T> {
let universe = self.infcx.probe_ty_var(for_vid).unwrap_err();
let mut generalizer = TypeGeneralizer {
infcx: self.infcx,
delegate: &mut self.delegate,
first_free_index: ty::INNERMOST,
ambient_variance: self.ambient_variance,
for_vid_sub_root: self.infcx.type_variables.borrow_mut().sub_root_var(for_vid),
universe,
};
generalizer.relate(&value, &value)
}
}
impl<D> TypeRelation<'me, 'gcx, 'tcx> for TypeRelating<'me, 'gcx, 'tcx, D>
where
D: TypeRelatingDelegate<'tcx>,
{
fn tcx(&self) -> TyCtxt<'me, 'gcx, 'tcx> {
self.infcx.tcx
}
fn tag(&self) -> &'static str {
"nll::subtype"
}
fn a_is_expected(&self) -> bool {
true
}
fn relate_with_variance<T: Relate<'tcx>>(
&mut self,
variance: ty::Variance,
a: &T,
b: &T,
) -> RelateResult<'tcx, T> {
debug!(
"relate_with_variance(variance={:?}, a={:?}, b={:?})",
variance, a, b
);
let old_ambient_variance = self.ambient_variance;
self.ambient_variance = self.ambient_variance.xform(variance);
debug!(
"relate_with_variance: ambient_variance = {:?}",
self.ambient_variance
);
let r = self.relate(a, b)?;
self.ambient_variance = old_ambient_variance;
debug!("relate_with_variance: r={:?}", r);
Ok(r)
}
fn tys(&mut self, a: Ty<'tcx>, mut b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
let a = self.infcx.shallow_resolve(a);
if !D::forbid_inference_vars() {
b = self.infcx.shallow_resolve(b);
}
match (&a.sty, &b.sty) {
(_, &ty::Infer(ty::TyVar(vid))) => {
if D::forbid_inference_vars() {
// Forbid inference variables in the RHS.
bug!("unexpected inference var {:?}", b)
} else {
self.relate_ty_var(vid, a)
}
}
(&ty::Infer(ty::TyVar(vid)), _) => self.relate_ty_var(vid, b),
(&ty::Projection(projection_ty), _)
if D::normalization() == NormalizationStrategy::Lazy =>
{
Ok(self.relate_projection_ty(projection_ty, b))
}
(_, &ty::Projection(projection_ty))
if D::normalization() == NormalizationStrategy::Lazy =>
{
Ok(self.relate_projection_ty(projection_ty, a))
}
_ => {
debug!(
"tys(a={:?}, b={:?}, variance={:?})",
a, b, self.ambient_variance
);
// Will also handle unification of `IntVar` and `FloatVar`.
self.infcx.super_combine_tys(self, a, b)
}
}
}
fn regions(
&mut self,
a: ty::Region<'tcx>,
b: ty::Region<'tcx>,
) -> RelateResult<'tcx, ty::Region<'tcx>> {
debug!(
"regions(a={:?}, b={:?}, variance={:?})",
a, b, self.ambient_variance
);
let v_a = self.replace_bound_region(a, ty::INNERMOST, &self.a_scopes);
let v_b = self.replace_bound_region(b, ty::INNERMOST, &self.b_scopes);
debug!("regions: v_a = {:?}", v_a);
debug!("regions: v_b = {:?}", v_b);
if self.ambient_covariance() {
// Covariance: a <= b. Hence, `b: a`.
self.push_outlives(v_b, v_a);
}
if self.ambient_contravariance() {
// Contravariant: b <= a. Hence, `a: b`.
self.push_outlives(v_a, v_b);
}
Ok(a)
}
fn binders<T>(
&mut self,
a: &ty::Binder<T>,
b: &ty::Binder<T>,
) -> RelateResult<'tcx, ty::Binder<T>>
where
T: Relate<'tcx>,
{
// We want that
//
// ```
// for<'a> fn(&'a u32) -> &'a u32 <:
// fn(&'b u32) -> &'b u32
// ```
//
// but not
//
// ```
// fn(&'a u32) -> &'a u32 <:
// for<'b> fn(&'b u32) -> &'b u32
// ```
//
// We therefore proceed as follows:
//
// - Instantiate binders on `b` universally, yielding a universe U1.
// - Instantiate binders on `a` existentially in U1.
debug!(
"binders({:?}: {:?}, ambient_variance={:?})",
a, b, self.ambient_variance
);
if self.ambient_covariance() {
// Covariance, so we want `for<..> A <: for<..> B` --
// therefore we compare any instantiation of A (i.e., A
// instantiated with existentials) against every
// instantiation of B (i.e., B instantiated with
// universals).
let b_scope = self.create_scope(b, UniversallyQuantified(true));
let a_scope = self.create_scope(a, UniversallyQuantified(false));
debug!("binders: a_scope = {:?} (existential)", a_scope);
debug!("binders: b_scope = {:?} (universal)", b_scope);
self.b_scopes.push(b_scope);
self.a_scopes.push(a_scope);
// Reset the ambient variance to covariant. This is needed
// to correctly handle cases like
//
// for<'a> fn(&'a u32, &'a u3) == for<'b, 'c> fn(&'b u32, &'c u32)
//
// Somewhat surprisingly, these two types are actually
// **equal**, even though the one on the right looks more
// polymorphic. The reason is due to subtyping. To see it,
// consider that each function can call the other:
//
// - The left function can call the right with `'b` and
// `'c` both equal to `'a`
//
// - The right function can call the left with `'a` set to
// `{P}`, where P is the point in the CFG where the call
// itself occurs. Note that `'b` and `'c` must both
// include P. At the point, the call works because of
// subtyping (i.e., `&'b u32 <: &{P} u32`).
let variance = ::std::mem::replace(&mut self.ambient_variance, ty::Variance::Covariant);
self.relate(a.skip_binder(), b.skip_binder())?;
self.ambient_variance = variance;
self.b_scopes.pop().unwrap();
self.a_scopes.pop().unwrap();
}
if self.ambient_contravariance() {
// Contravariance, so we want `for<..> A :> for<..> B`
// -- therefore we compare every instantiation of A (i.e.,
// A instantiated with universals) against any
// instantiation of B (i.e., B instantiated with
// existentials). Opposite of above.
let a_scope = self.create_scope(a, UniversallyQuantified(true));
let b_scope = self.create_scope(b, UniversallyQuantified(false));
debug!("binders: a_scope = {:?} (universal)", a_scope);
debug!("binders: b_scope = {:?} (existential)", b_scope);
self.a_scopes.push(a_scope);
self.b_scopes.push(b_scope);
// Reset ambient variance to contravariance. See the
// covariant case above for an explanation.
let variance =
::std::mem::replace(&mut self.ambient_variance, ty::Variance::Contravariant);
self.relate(a.skip_binder(), b.skip_binder())?;
self.ambient_variance = variance;
self.b_scopes.pop().unwrap();
self.a_scopes.pop().unwrap();
}
Ok(a.clone())
}
}
/// When we encounter a binder like `for<..> fn(..)`, we actually have
/// to walk the `fn` value to find all the values bound by the `for`
/// (these are not explicitly present in the ty representation right
/// now). This visitor handles that: it descends the type, tracking
/// binder depth, and finds late-bound regions targeting the
/// `for<..`>. For each of those, it creates an entry in
/// `bound_region_scope`.
struct ScopeInstantiator<'me, 'tcx: 'me> {
next_region: &'me mut dyn FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
// The debruijn index of the scope we are instantiating.
target_index: ty::DebruijnIndex,
bound_region_scope: &'me mut BoundRegionScope<'tcx>,
}
impl<'me, 'tcx> TypeVisitor<'tcx> for ScopeInstantiator<'me, 'tcx> {
fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &ty::Binder<T>) -> bool {
self.target_index.shift_in(1);
t.super_visit_with(self);
self.target_index.shift_out(1);
false
}
fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
let ScopeInstantiator {
bound_region_scope,
next_region,
..
} = self;
match r {
ty::ReLateBound(debruijn, br) if *debruijn == self.target_index => {
bound_region_scope
.map
.entry(*br)
.or_insert_with(|| next_region(*br));
}
_ => {}
}
false
}
}
/// The "type generalize" is used when handling inference variables.
///
/// The basic strategy for handling a constraint like `?A <: B` is to
/// apply a "generalization strategy" to the type `B` -- this replaces
/// all the lifetimes in the type `B` with fresh inference
/// variables. (You can read more about the strategy in this [blog
/// post].)
///
/// As an example, if we had `?A <: &'x u32`, we would generalize `&'x
/// u32` to `&'0 u32` where `'0` is a fresh variable. This becomes the
/// value of `A`. Finally, we relate `&'0 u32 <: &'x u32`, which
/// establishes `'0: 'x` as a constraint.
///
/// As a side-effect of this generalization procedure, we also replace
/// all the bound regions that we have traversed with concrete values,
/// so that the resulting generalized type is independent from the
/// scopes.
///
/// [blog post]: https://is.gd/0hKvIr
struct TypeGeneralizer<'me, 'gcx: 'tcx, 'tcx: 'me, D>
where
D: TypeRelatingDelegate<'tcx> + 'me,
{
infcx: &'me InferCtxt<'me, 'gcx, 'tcx>,
delegate: &'me mut D,
/// After we generalize this type, we are going to relative it to
/// some other type. What will be the variance at this point?
ambient_variance: ty::Variance,
first_free_index: ty::DebruijnIndex,
/// The vid of the type variable that is in the process of being
/// instantiated. If we find this within the value we are folding,
/// that means we would have created a cyclic value.
for_vid_sub_root: ty::TyVid,
/// The universe of the type variable that is in the process of being
/// instantiated. If we find anything that this universe cannot name,
/// we reject the relation.
universe: ty::UniverseIndex,
}
impl<D> TypeRelation<'me, 'gcx, 'tcx> for TypeGeneralizer<'me, 'gcx, 'tcx, D>
where
D: TypeRelatingDelegate<'tcx>,
{
fn tcx(&self) -> TyCtxt<'me, 'gcx, 'tcx> {
self.infcx.tcx
}
fn tag(&self) -> &'static str {
"nll::generalizer"
}
fn a_is_expected(&self) -> bool {
true
}
fn relate_with_variance<T: Relate<'tcx>>(
&mut self,
variance: ty::Variance,
a: &T,
b: &T,
) -> RelateResult<'tcx, T> {
debug!(
"TypeGeneralizer::relate_with_variance(variance={:?}, a={:?}, b={:?})",
variance, a, b
);
let old_ambient_variance = self.ambient_variance;
self.ambient_variance = self.ambient_variance.xform(variance);
debug!(
"TypeGeneralizer::relate_with_variance: ambient_variance = {:?}",
self.ambient_variance
);
let r = self.relate(a, b)?;
self.ambient_variance = old_ambient_variance;
debug!("TypeGeneralizer::relate_with_variance: r={:?}", r);
Ok(r)
}
fn tys(&mut self, a: Ty<'tcx>, _: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
use crate::infer::type_variable::TypeVariableValue;
debug!("TypeGeneralizer::tys(a={:?})", a,);
match a.sty {
ty::Infer(ty::TyVar(_)) | ty::Infer(ty::IntVar(_)) | ty::Infer(ty::FloatVar(_))
if D::forbid_inference_vars() =>
{
bug!(
"unexpected inference variable encountered in NLL generalization: {:?}",
a
);
}
ty::Infer(ty::TyVar(vid)) => {
let mut variables = self.infcx.type_variables.borrow_mut();
let vid = variables.root_var(vid);
let sub_vid = variables.sub_root_var(vid);
if sub_vid == self.for_vid_sub_root {
// If sub-roots are equal, then `for_vid` and
// `vid` are related via subtyping.
debug!("TypeGeneralizer::tys: occurs check failed");
return Err(TypeError::Mismatch);
} else {
match variables.probe(vid) {
TypeVariableValue::Known { value: u } => {
drop(variables);
self.relate(&u, &u)
}
TypeVariableValue::Unknown { universe: _universe } => {
if self.ambient_variance == ty::Bivariant {
// FIXME: we may need a WF predicate (related to #54105).
}
let origin = *variables.var_origin(vid);
// Replacing with a new variable in the universe `self.universe`,
// it will be unified later with the original type variable in
// the universe `_universe`.
let new_var_id = variables.new_var(self.universe, false, origin);
let u = self.tcx().mk_var(new_var_id);
debug!(
"generalize: replacing original vid={:?} with new={:?}",
vid,
u
);
return Ok(u);
}
}<|fim▁hole|> ty::Infer(ty::IntVar(_)) |
ty::Infer(ty::FloatVar(_)) => {
// No matter what mode we are in,
// integer/floating-point types must be equal to be
// relatable.
Ok(a)
}
ty::Placeholder(placeholder) => {
if self.universe.cannot_name(placeholder.universe) {
debug!(
"TypeGeneralizer::tys: root universe {:?} cannot name\
placeholder in universe {:?}",
self.universe,
placeholder.universe
);
Err(TypeError::Mismatch)
} else {
Ok(a)
}
}
_ => {
relate::super_relate_tys(self, a, a)
}
}
}
fn regions(
&mut self,
a: ty::Region<'tcx>,
_: ty::Region<'tcx>,
) -> RelateResult<'tcx, ty::Region<'tcx>> {
debug!("TypeGeneralizer::regions(a={:?})", a,);
if let ty::ReLateBound(debruijn, _) = a {
if *debruijn < self.first_free_index {
return Ok(a);
}
}
// For now, we just always create a fresh region variable to
// replace all the regions in the source type. In the main
// type checker, we special case the case where the ambient
// variance is `Invariant` and try to avoid creating a fresh
// region variable, but since this comes up so much less in
// NLL (only when users use `_` etc) it is much less
// important.
//
// As an aside, since these new variables are created in
// `self.universe` universe, this also serves to enforce the
// universe scoping rules.
//
// FIXME(#54105) -- if the ambient variance is bivariant,
// though, we may however need to check well-formedness or
// risk a problem like #41677 again.
let replacement_region_vid = self.delegate.generalize_existential(self.universe);
Ok(replacement_region_vid)
}
fn binders<T>(
&mut self,
a: &ty::Binder<T>,
_: &ty::Binder<T>,
) -> RelateResult<'tcx, ty::Binder<T>>
where
T: Relate<'tcx>,
{
debug!("TypeGeneralizer::binders(a={:?})", a,);
self.first_free_index.shift_in(1);
let result = self.relate(a.skip_binder(), a.skip_binder())?;
self.first_free_index.shift_out(1);
Ok(ty::Binder::bind(result))
}
}<|fim▁end|> | }
}
|
<|file_name|>header.rs<|end_file_name|><|fim▁begin|>// Copyright 2012-2013 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.
use common::config;
use common;
use util;
pub struct TestProps {
// Lines that should be expected, in order, on standard out
error_patterns: ~[~str],
// Extra flags to pass to the compiler
compile_flags: Option<~str>,
// If present, the name of a file that this test should match when
// pretty-printed
pp_exact: Option<Path>,
// Modules from aux directory that should be compiled
aux_builds: ~[~str],
// Environment settings to use during execution
exec_env: ~[(~str,~str)],
// Commands to be given to the debugger, when testing debug info
debugger_cmds: ~[~str],
// Lines to check if they appear in the expected debugger output
check_lines: ~[~str],
}
// Load any test directives embedded in the file
pub fn load_props(testfile: &Path) -> TestProps {
let mut error_patterns = ~[];
let mut aux_builds = ~[];
let mut exec_env = ~[];
let mut compile_flags = None;
let mut pp_exact = None;
let mut debugger_cmds = ~[];
let mut check_lines = ~[];
iter_header(testfile, |ln| {
match parse_error_pattern(ln) {
Some(ep) => error_patterns.push(ep),
None => ()
};
if compile_flags.is_none() {
compile_flags = parse_compile_flags(ln);
}
if pp_exact.is_none() {
pp_exact = parse_pp_exact(ln, testfile);
}
match parse_aux_build(ln) {
Some(ab) => { aux_builds.push(ab); }
None => {}
}
match parse_exec_env(ln) {
Some(ee) => { exec_env.push(ee); }
None => {}
}
match parse_debugger_cmd(ln) {
Some(dc) => debugger_cmds.push(dc),
None => ()
};
match parse_check_line(ln) {
Some(cl) => check_lines.push(cl),
None => ()
};
true
});
return TestProps {
error_patterns: error_patterns,
compile_flags: compile_flags,
pp_exact: pp_exact,
aux_builds: aux_builds,
exec_env: exec_env,
debugger_cmds: debugger_cmds,
check_lines: check_lines
};
}
pub fn is_test_ignored(config: &config, testfile: &Path) -> bool {
fn xfail_target(config: &config) -> ~str {
~"xfail-" + util::get_os(config.target)
}
let val = iter_header(testfile, |ln| {
if parse_name_directive(ln, "xfail-test") { false }
else if parse_name_directive(ln, xfail_target(config)) { false }
else if config.mode == common::mode_pretty &&
parse_name_directive(ln, "xfail-pretty") { false }
else { true }
});
!val
}
fn iter_header(testfile: &Path, it: |&str| -> bool) -> bool {
use std::io::buffered::BufferedReader;
use std::io::File;
let mut rdr = BufferedReader::new(File::open(testfile).unwrap());
for ln in rdr.lines() {
// Assume that any directives will be found before the first
// module or function. This doesn't seem to be an optimization
// with a warm page cache. Maybe with a cold one.
if ln.starts_with("fn") || ln.starts_with("mod") {
return true;
} else { if !(it(ln.trim())) { return false; } }
}
return true;
}
fn parse_error_pattern(line: &str) -> Option<~str> {
parse_name_value_directive(line, ~"error-pattern")
}
fn parse_aux_build(line: &str) -> Option<~str> {
parse_name_value_directive(line, ~"aux-build")
}
fn parse_compile_flags(line: &str) -> Option<~str> {
parse_name_value_directive(line, ~"compile-flags")
}
fn parse_debugger_cmd(line: &str) -> Option<~str> {
parse_name_value_directive(line, ~"debugger")
}
fn parse_check_line(line: &str) -> Option<~str> {
parse_name_value_directive(line, ~"check")
}
fn parse_exec_env(line: &str) -> Option<(~str, ~str)> {
parse_name_value_directive(line, ~"exec-env").map(|nv| {
// nv is either FOO or FOO=BAR
let mut strs: ~[~str] = nv.splitn('=', 1).map(|s| s.to_owned()).collect();
match strs.len() {
1u => (strs.pop(), ~""),
2u => {
let end = strs.pop();
(strs.pop(), end)
}
n => fail!("Expected 1 or 2 strings, not {}", n)
}
})
}
fn parse_pp_exact(line: &str, testfile: &Path) -> Option<Path> {
match parse_name_value_directive(line, ~"pp-exact") {
Some(s) => Some(Path::new(s)),
None => {
if parse_name_directive(line, "pp-exact") {
testfile.filename().map(|s| Path::new(s))
} else {
None
}
}
}
}
fn parse_name_directive(line: &str, directive: &str) -> bool {
line.contains(directive)
}
<|fim▁hole|> let keycolon = directive + ":";
match line.find_str(keycolon) {
Some(colon) => {
let value = line.slice(colon + keycolon.len(),
line.len()).to_owned();
debug!("{}: {}", directive, value);
Some(value)
}
None => None
}
}<|fim▁end|> | fn parse_name_value_directive(line: &str,
directive: ~str) -> Option<~str> { |
<|file_name|>node_provider.py<|end_file_name|><|fim▁begin|>import random
import threading
from collections import defaultdict
import logging
import time
from typing import Any, Dict, List, Optional
from ray.autoscaler.node_provider import NodeProvider
from ray.autoscaler.tags import TAG_RAY_CLUSTER_NAME, TAG_RAY_NODE_NAME, \
TAG_RAY_LAUNCH_CONFIG, TAG_RAY_NODE_KIND, \
TAG_RAY_USER_NODE_TYPE, TAG_RAY_NODE_STATUS
from ray.autoscaler._private.constants import BOTO_MAX_RETRIES
from ray.autoscaler._private.log_timer import LogTimer
from ray.autoscaler._private.cli_logger import cli_logger
from ray.autoscaler._private.aliyun.utils import AcsClient
from ray.autoscaler._private.aliyun.config import PENDING, STOPPED, \
STOPPING, RUNNING, bootstrap_aliyun
logger = logging.getLogger(__name__)
TAG_BATCH_DELAY = 1
STOPPING_NODE_DELAY = 1
class AliyunNodeProvider(NodeProvider):
def __init__(self, provider_config, cluster_name):
NodeProvider.__init__(self, provider_config, cluster_name)
self.cache_stopped_nodes = provider_config.get("cache_stopped_nodes",
True)
self.acs = AcsClient(
access_key=provider_config["access_key"],
access_key_secret=provider_config["access_key_secret"],
region_id=provider_config["region"],
max_retries=BOTO_MAX_RETRIES,
)
# Try availability zones round-robin, starting from random offset
self.subnet_idx = random.randint(0, 100)
# Tags that we believe to actually be on the node.
self.tag_cache = {}
# Tags that we will soon upload.
self.tag_cache_pending = defaultdict(dict)
# Number of threads waiting for a batched tag update.
self.batch_thread_count = 0
self.batch_update_done = threading.Event()
self.batch_update_done.set()
self.ready_for_new_batch = threading.Event()
self.ready_for_new_batch.set()
self.tag_cache_lock = threading.Lock()
self.count_lock = threading.Lock()
# Cache of node objects from the last nodes() call. This avoids
# excessive DescribeInstances requests.
self.cached_nodes = {}
def non_terminated_nodes(self, tag_filters: Dict[str, str]) -> List[str]:
tags = [
{
"Key": TAG_RAY_CLUSTER_NAME,
"Value": self.cluster_name,
},
]
for k, v in tag_filters.items():
tags.append({
"Key": k,
"Value": v,
})
instances = self.acs.describe_instances(tags=tags)
non_terminated_instance = []
for instance in instances:
if instance.get("Status") == RUNNING or instance.get(
"Status") == PENDING:
non_terminated_instance.append(instance.get("InstanceId"))
self.cached_nodes[instance.get("InstanceId")] = instance
return non_terminated_instance
def is_running(self, node_id: str) -> bool:
instances = self.acs.describe_instances(instance_ids=[node_id])
if instances is not None:
instance = instances[0]
return instance.get("Status") == "Running"
cli_logger.error("Invalid node id: %s", node_id)
return False
def is_terminated(self, node_id: str) -> bool:
instances = self.acs.describe_instances(instance_ids=[node_id])
if instances is not None:
assert len(instances) == 1
instance = instances[0]
return instance.get("Status") == "Stopped"
cli_logger.error("Invalid node id: %s", node_id)
return False
def node_tags(self, node_id: str) -> Dict[str, str]:
instances = self.acs.describe_instances(instance_ids=[node_id])
if instances is not None:
assert len(instances) == 1
instance = instances[0]
if instance.get("Tags") is not None:
node_tags = dict()
for tag in instance.get("Tags").get("Tag"):
node_tags[tag.get("TagKey")] = tag.get("TagValue")
return node_tags
return dict()
def external_ip(self, node_id: str) -> str:
while True:
instances = self.acs.describe_instances(instance_ids=[node_id])
if instances is not None:
assert len(instances)
instance = instances[0]
if instance.get("PublicIpAddress") is not None \
and instance.get(
"PublicIpAddress").get("IpAddress") is not None:
if len(instance.get("PublicIpAddress").get(
"IpAddress")) > 0:
return instance.get("PublicIpAddress").get(
"IpAddress")[0]
cli_logger.error(
"PublicIpAddress attribute is not exist. %s" % instance)
time.sleep(STOPPING_NODE_DELAY)
def internal_ip(self, node_id: str) -> str:
while True:
instances = self.acs.describe_instances(instance_ids=[node_id])
if instances is not None:
assert len(instances) == 1
instance = instances[0]
if instance.get("VpcAttributes") is not None and instance.get(
"VpcAttributes").get(
"PrivateIpAddress") is not None and len(
instance.get("VpcAttributes").get(
"PrivateIpAddress").get("IpAddress")) > 0:
return instance.get("VpcAttributes").get(
"PrivateIpAddress").get("IpAddress")[0]
cli_logger.error(
"InnerIpAddress attribute is not exist. %s" % instance)
time.sleep(STOPPING_NODE_DELAY)
def set_node_tags(self, node_id: str, tags: Dict[str, str]) -> None:
is_batching_thread = False
with self.tag_cache_lock:
if not self.tag_cache_pending:
is_batching_thread = True
# Wait for threads in the last batch to exit
self.ready_for_new_batch.wait()
self.ready_for_new_batch.clear()
self.batch_update_done.clear()
self.tag_cache_pending[node_id].update(tags)
if is_batching_thread:
time.sleep(TAG_BATCH_DELAY)
with self.tag_cache_lock:
self._update_node_tags()
self.batch_update_done.set()
with self.count_lock:
self.batch_thread_count += 1
self.batch_update_done.wait()
with self.count_lock:
self.batch_thread_count -= 1
if self.batch_thread_count == 0:
self.ready_for_new_batch.set()
def _update_node_tags(self):
batch_updates = defaultdict(list)
for node_id, tags in self.tag_cache_pending.items():
for x in tags.items():
batch_updates[x].append(node_id)
self.tag_cache[node_id] = tags
self.tag_cache_pending = defaultdict(dict)
self._create_tags(batch_updates)
def _create_tags(self, batch_updates):
for (k, v), node_ids in batch_updates.items():
m = "Set tag {}={} on {}".format(k, v, node_ids)
with LogTimer("AliyunNodeProvider: {}".format(m)):
if k == TAG_RAY_NODE_NAME:
k = "Name"
self.acs.tag_resource(node_ids, [{"Key": k, "Value": v}])
def create_node(self, node_config: Dict[str, Any], tags: Dict[str, str],
count: int) -> Optional[Dict[str, Any]]:
filter_tags = [{
"Key": TAG_RAY_CLUSTER_NAME,
"Value": self.cluster_name,
}, {
"Key": TAG_RAY_NODE_KIND,
"Value": tags[TAG_RAY_NODE_KIND]
}, {
"Key": TAG_RAY_USER_NODE_TYPE,
"Value": tags[TAG_RAY_USER_NODE_TYPE]
}, {
"Key": TAG_RAY_LAUNCH_CONFIG,
"Value": tags[TAG_RAY_LAUNCH_CONFIG]
}, {
"Key": TAG_RAY_NODE_NAME,
"Value": tags[TAG_RAY_NODE_NAME]
}]
reused_nodes_dict = {}
if self.cache_stopped_nodes:
reuse_nodes_candidate = self.acs.describe_instances(
tags=filter_tags)
if reuse_nodes_candidate:
with cli_logger.group("Stopping instances to reuse"):
reuse_node_ids = []
for node in reuse_nodes_candidate:
node_id = node.get("InstanceId")
status = node.get("Status")
if status != STOPPING and status != STOPPED:
continue
if status == STOPPING:
# wait for node stopped
while self.acs.describe_instances(
instance_ids=[node_id])[0].get(
"Status") == STOPPING:
logging.info("wait for %s stop" % node_id)
time.sleep(STOPPING_NODE_DELAY)
# logger.info("reuse %s" % node_id)
reuse_node_ids.append(node_id)
reused_nodes_dict[node.get("InstanceId")] = node
self.acs.start_instance(node_id)
self.tag_cache[node_id] = node.get("Tags")
self.set_node_tags(node_id, tags)
if len(reuse_node_ids) == count:
break
count -= len(reuse_node_ids)
created_nodes_dict = {}
if count > 0:
filter_tags.append({
"Key": TAG_RAY_NODE_STATUS,
"Value": tags[TAG_RAY_NODE_STATUS]
})
instance_id_sets = self.acs.run_instances(
instance_type=node_config["InstanceType"],
image_id=node_config["ImageId"],
tags=filter_tags,
amount=count,
vswitch_id=self.provider_config["v_switch_id"],
security_group_id=self.provider_config["security_group_id"],
key_pair_name=self.provider_config["key_name"])
instances = self.acs.describe_instances(
instance_ids=instance_id_sets)
if instances is not None:
for instance in instances:
created_nodes_dict[instance.get("InstanceId")] = instance
all_created_nodes = reused_nodes_dict
all_created_nodes.update(created_nodes_dict)
return all_created_nodes
def terminate_node(self, node_id: str) -> None:<|fim▁hole|> logger.info("terminate node: %s" % node_id)
if self.cache_stopped_nodes:
logger.info(
"Stopping instance {} (to terminate instead, "
"set `cache_stopped_nodes: False` "
"under `provider` in the cluster configuration)").format(
node_id)
self.acs.stop_instance(node_id)
else:
self.acs.delete_instance(node_id)
def terminate_nodes(self, node_ids: List[str]) -> None:
if not node_ids:
return
if self.cache_stopped_nodes:
logger.info(
"Stopping instances {} (to terminate instead, "
"set `cache_stopped_nodes: False` "
"under `provider` in the cluster configuration)".format(
node_ids))
self.acs.stop_instances(node_ids)
else:
self.acs.delete_instances(node_ids)
def _get_node(self, node_id):
"""Refresh and get info for this node, updating the cache."""
self.non_terminated_nodes({}) # Side effect: updates cache
if node_id in self.cached_nodes:
return self.cached_nodes[node_id]
# Node not in {pending, running} -- retry with a point query. This
# usually means the node was recently preempted or terminated.
matches = self.acs.describe_instances(instance_ids=[node_id])
assert len(matches) == 1, "Invalid instance id {}".format(node_id)
return matches[0]
def _get_cached_node(self, node_id):
"""Return node info from cache if possible, otherwise fetches it."""
if node_id in self.cached_nodes:
return self.cached_nodes[node_id]
return self._get_node(node_id)
@staticmethod
def bootstrap_config(cluster_config):
return bootstrap_aliyun(cluster_config)<|fim▁end|> | |
<|file_name|>vDialing.py<|end_file_name|><|fim▁begin|># vDial-up client
# Copyright (C) 2015 - 2017 Nathaniel Olsen
# 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/>.
from time import sleep
import socket
import libs.vDialupcore as core
from multiprocessing import Process
import sys
import struct
def MD5SUM_mismatch(vNumber_to_connect, sock):
print("*Warning: The server's MD5SUM does not match with the one listed on file, Do you wish to continue? (Y/N)")
if vNumber_to_connect == core.RegServ_vNumber:
MD5SUM_on_file = core.RegServ_MD5SUM
else:
pass # Right now, there is no way to retrieve a server's md5sum until I implement md5sum retriving in RegServ.
print("MD5SUM on file: %s" % (MD5SUM_on_file))
print("MD5SUM according to server: %s" % (received.split()[1]))
print("")
choice = input("Enter choice (Y/N): ")
if choice == 'Y' or choice == 'y':
init(sock, vNumber_to_connect)
if choice == 'N' or choice == 'n':
sys.exit() # Exit for now.
class main():
def send_msg(sock, msg):
# Prefix each message with a 4-byte length (network byte order)
msg = struct.pack('>I', len(msg)) + str.encode(msg)
sock.sendall(msg)
def recv_msg(sock):
# Read message length and unpack it into an integer
raw_msglen = main.recvall(sock, 4)
if not raw_msglen:
return None
msglen = struct.unpack('>I', str.encode(raw_msglen))[0]
return main.recvall(sock, msglen)
def recvall(sock, n):
# Helper function to recv n bytes or return None if EOF is hit
data = ''
while len(data) < n:
packet = (sock.recv(n - len(data)).decode('utf-8'))
if not packet:
return None
data += packet
return data
def servping(sock):
while 1:
sleep(20)
sock.sendall(bytes("SERVPING" + "\n", "utf-8"))
if main.listen_for_data(sock) == "PONG":
break
else:
print("Disconnected: Connection timeout.")
def vdialing(vNumber_to_connect, vNumber_IP):
if core.config['use_ipv6_when_possible']:
sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
else:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("vDialing %s..." % (vNumber_to_connect))
if core.config['vDial-up Settings']['vNumber'] == "000000000":
core.dialupnoise()
try:
sock.connect((vNumber_IP, 5000))
except ConnectionRefusedError:
print("Error: Connection Refused.")
sys.exit()
main.send_msg(sock, "INITPING")
if main.recv_msg(sock) == "PONG":
print("Connected.")
#Process(target=main.servping, args=[sock]).start() # The ability to check if a server connection is still alive is coming soon.
main.send_msg(sock, "MD5SUMCHECK")
if main.recv_msg(sock).split()[0] == "MD5SUM:":
if main.recv_msg(sock).split()[1] == core.RegServ_MD5SUM:
print("MD5SUM verification was succeeded.")
else:
MD5SUM_mismatch(vNumber_to_connect, sock)
else:
print("Error: Unable to retrieve MD5SUM.")
main.init(sock, vNumber_to_connect)
else:
print("Error: Server did not properly respond to INITPING, disconnecting.")
else:
Process(target=core.dialupnoise()).start()
sock.connect((vNumber_IP, 5000))
main.send_msg(sock, "INITPING")
if main.recv_msg(sock) == "PONG":
print("Connected to Registation Server!")
main.send_msg(sock, "MD5SUMCHECK")
if main.recv_msg(sock).split()[0] == "MD5SUM:":
if main.recv_msg(sock).split()[1] == core.RegServ_MD5SUM:
print("MD5SUM verification was succeeded.")
else:
MD5SUM_mismatch(vNumber_to_connect, sock)
else:
print("Error: Unable to retrieve MD5SUM.")
else:
print("Error: Server did not properly respond to INITPING, disconnecting.")
<|fim▁hole|> def init(sock, vNumber_to_connect):
main.send_msg(sock, "VNUMBER: {}".format(core.config['vDial-up Settings']['vNumber']))
if core.config['vDial-up Settings']['vNumber'] == "000000000":
main.send_msg(sock, "CLIENTREGISTER")
if main.recv_msg(sock).split()[0] == "CONFIG:":
if main.recv_msg(sock).split()[1] == "vNumber":
core.config['vDial-up Settings']['vNumber'] = main.recv_msg(sock).split()[2]
core.saveconfig()
if main.recv_msg(sock).split()[1] == "Key":
core.config['vDial-up Settings']['Key'] = main.recv_msg(sock).split()[2]
core.saveconfig()
if main.recv_msg(sock).split()[0] == "TOCLIENT:":
print(" ".join(main.recv_msg(sock).split()[2:]))
else:
main.send_msg(sock, "KEY: {}".format(core.config['vDial-up Settings']['Key']))
main.send_msg(sock, "INIT")<|fim▁end|> | |
<|file_name|>lifetime-update.rs<|end_file_name|><|fim▁begin|>#![feature(type_changing_struct_update)]
#![allow(incomplete_features)]
#[derive(Clone)]
struct Machine<'a, S> {
state: S,
lt_str: &'a str,
common_field: i32,
}
#[derive(Clone)]
struct State1;
#[derive(Clone)]
struct State2;
fn update_to_state2() {<|fim▁hole|> //~^ ERROR `s` does not live long enough [E0597]
// FIXME: The error here actually comes from line 34. The
// span of the error message should be corrected to line 34
common_field: 2,
};
// update lifetime
let m3: Machine<'static, State1> = Machine {
lt_str: "hello, too",
..m1.clone()
};
// update lifetime and type
let m4: Machine<'static, State2> = Machine {
state: State2,
lt_str: "hello, again",
..m1.clone()
};
// updating to `static should fail.
let m2: Machine<'static, State1> = Machine {
..m1
};
}
fn main() {}<|fim▁end|> | let s = String::from("hello");
let m1: Machine<State1> = Machine {
state: State1,
lt_str: &s, |
<|file_name|>qualitycontrol_analysesrepeated.py<|end_file_name|><|fim▁begin|>from dependencies.dependency import getToolByName
from lims.browser import BrowserView
from dependencies.dependency import ViewPageTemplateFile
from lims import bikaMessageFactory as _
from lims.utils import t
from lims.utils import formatDateQuery, formatDateParms
from dependencies.dependency import IViewView
from dependencies.dependency import implements
class Report(BrowserView):
implements(IViewView)
template = ViewPageTemplateFile("templates/report_out.pt")
def __init__(self, context, request, report=None):
self.report = report
BrowserView.__init__(self, context, request)
def __call__(self):
bac = getToolByName(self.context, 'bika_analysis_catalog')
self.report_content = {}
parm_lines = {}
parms = []
headings = {}
headings['header'] = _("Analyses retested")
headings['subheader'] = _("Analyses which have been retested")
count_all = 0
query = {'portal_type': 'Analysis',
'getRetested': True,
'sort_order': 'reverse'}
date_query = formatDateQuery(self.context, 'Received')
if date_query:
query['getDateReceived'] = date_query
received = formatDateParms(self.context, 'Received')
else:
received = 'Undefined'
parms.append(
{'title': _('Received'),
'value': received,
'type': 'text'})
wf_tool = getToolByName(self.context, 'portal_workflow')
if self.request.form.has_key('bika_analysis_workflow'):
query['review_state'] = self.request.form['bika_analysis_workflow']
review_state = wf_tool.getTitleForStateOnType(
self.request.form['bika_analysis_workflow'], 'Analysis')
else:
review_state = 'Undefined'
parms.append(
{'title': _('Status'),
'value': review_state,
'type': 'text'})
if self.request.form.has_key('bika_cancellation_workflow'):
query['cancellation_state'] = self.request.form[
'bika_cancellation_workflow']
cancellation_state = wf_tool.getTitleForStateOnType(
self.request.form['bika_cancellation_workflow'], 'Analysis')
else:
cancellation_state = 'Undefined'
parms.append(
{'title': _('Active'),
'value': cancellation_state,
'type': 'text'})
if self.request.form.has_key('bika_worksheetanalysis_workflow'):
query['worksheetanalysis_review_state'] = self.request.form[
'bika_worksheetanalysis_workflow']
ws_review_state = wf_tool.getTitleForStateOnType(
self.request.form['bika_worksheetanalysis_workflow'], 'Analysis')
else:
ws_review_state = 'Undefined'
parms.append(
{'title': _('Assigned to worksheet'),
'value': ws_review_state,
'type': 'text'})
# and now lets do the actual report lines
formats = {'columns': 8,
'col_heads': [_('Client'),
_('Request'),
_('Sample type'),
_('Sample point'),
_('Category'),
_('Analysis'),
_('Received'),
_('Status'),
],
'class': '',
}
datalines = []
clients = {}
sampletypes = {}
samplepoints = {}
categories = {}
services = {}
for a_proxy in bac(query):
analysis = a_proxy.getObject()
dataline = []
dataitem = {'value': analysis.getClientTitle()}
dataline.append(dataitem)
dataitem = {'value': analysis.getRequestID()}
dataline.append(dataitem)
dataitem = {'value': analysis.aq_parent.getSampleTypeTitle()}
dataline.append(dataitem)
dataitem = {'value': analysis.aq_parent.getSamplePointTitle()}
dataline.append(dataitem)
dataitem = {'value': analysis.getCategoryTitle()}
dataline.append(dataitem)
dataitem = {'value': analysis.getServiceTitle()}
dataline.append(dataitem)
dataitem = {'value': self.ulocalized_time(analysis.getDateReceived())}
dataline.append(dataitem)
state = wf_tool.getInfoFor(analysis, 'review_state', '')
review_state = wf_tool.getTitleForStateOnType(
state, 'Analysis')
dataitem = {'value': review_state}
dataline.append(dataitem)<|fim▁hole|> count_all += 1
# table footer data
footlines = []
footline = []
footitem = {'value': _('Number of analyses retested for period'),
'colspan': 7,
'class': 'total_label'}
footline.append(footitem)
footitem = {'value': count_all}
footline.append(footitem)
footlines.append(footline)
self.report_content = {
'headings': headings,
'parms': parms,
'formats': formats,
'datalines': datalines,
'footings': footlines}
title = t(headings['header'])
return {'report_title': title,
'report_data': self.template()}<|fim▁end|> |
datalines.append(dataline)
|
<|file_name|>cropTouch.js<|end_file_name|><|fim▁begin|>"use strict";<|fim▁hole|> this.id = id || 0;
this.x = x || 0;
this.y = y || 0;
this.dragHandle = null;
}
return CropTouch;
}());
exports.CropTouch = CropTouch;
//# sourceMappingURL=cropTouch.js.map<|fim▁end|> | var CropTouch = (function () {
function CropTouch(x, y, id) { |
<|file_name|>base.py<|end_file_name|><|fim▁begin|>import re
from django.db import models, transaction
from django.utils import timezone
from django.utils.six import iteritems, with_metaclass
from django.utils.translation import ugettext_lazy as _
from django.core.cache import cache
from django.core.exceptions import SuspiciousOperation
from django.contrib.contenttypes.models import ContentType
from djcelery.models import PeriodicTask, CrontabSchedule
import base64
import copy
try:
# noinspection PyPep8Naming
import cPickle as pickle
except ImportError:
import pickle
from vms.utils import PickleDict, RWMethods
from gui.models import User
from que.utils import owner_id_from_task_id
from que.user_tasks import UserTasks
class _DummyModelBase(type):
def __new__(mcs, name, bases, attrs):
meta = attrs.pop('Meta', None)
new_class = type.__new__(mcs, name, bases, attrs)
if meta:
meta.model_name = name.lower()
meta.concrete_model = new_class
setattr(new_class, '_meta', meta)
else:
raise AttributeError('Class %s has no "class Meta" definition' % name)
return new_class
class _DummyModel(with_metaclass(_DummyModelBase)):
"""
Dummy model simulating some properties of django models
"""
_pk_key = NotImplemented
class Meta:
pass
class _DummyDataModel(with_metaclass(_DummyModelBase)):
"""
Dummy model simulating some properties of django models + serialization of internal data dictionary.
"""
class Meta:
pass
def __new__(cls, *args, **kwargs):
# noinspection PyArgumentList
obj = super(_DummyDataModel, cls).__new__(cls, *args, **kwargs)
obj._data = {}
return obj
def __init__(self, data=None):
if data:
self._data.update(data)
def __getattr__(self, key):
if key.startswith('_'):
# noinspection PyUnresolvedReferences
return super(_DummyDataModel, self).__getattr__(key)
else:
return self._data[key]
def __setattr__(self, key, value):
if key.startswith('_'):
return super(_DummyDataModel, self).__setattr__(key, value)
else:
self._data[key] = value
def __delattr__(self, key):
if key.startswith('_'):
return super(_DummyDataModel, self).__delattr__(key)
else:
return self._data.__delitem__(key)
def __getstate__(self):
return self._data.copy()
def __setstate__(self, state):
self._data = state
def __iter__(self):
return iteritems(self._data)
def __getitem__(self, item):
return self._data.__getitem__(item)
def get(self, key, default=None):
return self._data.get(key, default)
def update(self, data):
self._data.update(data)
class _PickleModel(models.Model):
"""
Abstract class with pickle encoding and decoding of field attributes.
"""
class Meta:
app_label = 'vms'
abstract = True
@staticmethod
def _decode(xdata):
"""Unpickle data from DB and return a PickleDict object"""
data = pickle.loads(base64.decodestring(xdata))
if not isinstance(data, PickleDict):
data = PickleDict(data)
return data
@staticmethod
def _encode(xdata):
"""Pickle a dict object and return data, which can be saved in DB"""
if not isinstance(xdata, dict):
raise ValueError('json is not a dict')
return base64.encodestring(pickle.dumps(copy.copy(dict(xdata))))
class _JsonPickleModel(_PickleModel):
"""
Abstract _PickleModel with json attributes stored in enc_json field.
"""
EMPTY = 'KGRwMQou\n'
class Meta:
app_label = 'vms'
abstract = True
# don't access 'encoded_data' directly, use the 'data' property instead, etc
# default is an empty dict
enc_json = models.TextField(blank=False, editable=False, default=EMPTY)
# Access the json property to load/save/manipulate the dict object
# json is the dict which will be used for creating/updating the VM on SmartOS
@property
def json(self):
return self._decode(self.enc_json)
@json.setter
def json(self, data):
self.enc_json = self._encode(data)
def save_item(self, key, value, save=True, metadata=None, **kwargs):
"""Set one item in json"""
_json = self.json
if metadata:
if metadata not in _json:
_json[metadata] = {}
_json[metadata][key] = value
else:
_json[key] = value
self.json = _json
if save:
return self.save(**kwargs)
else:
return True
def save_items(self, save=True, metadata=None, **key_value):
"""Save multiple items in json"""
_json = self.json
if metadata:
if metadata not in _json:
_json[metadata] = {}
_json[metadata].update(key_value)
else:
_json.update(key_value)
self.json = _json
if save:
return self.save()
else:
return True
def delete_item(self, key, save=True, metadata=None, **kwargs):
"""Set one item in json"""
_json = self.json
try:
if metadata:
if metadata in _json:
del _json[metadata][key]
else:
del _json[key]
except KeyError:
pass
self.json = _json
if save:
return self.save(**kwargs)
else:
return True
class _StatusModel(models.Model):
"""
Abstract model class with basic status attributes.
Also tracks changes of status property and updates the status_change
attribute if changed. Status information is cached - the key is PK:status.
"""
_lock = False # Cannot be saved when True
_cache_status = False # Should we cache the status into redis after calling save()?
_orig_status = None # Original value of status
_update_changed = True # When True, the changed field will be updated at each save()
# status = models.SmallIntegerField(_('Status')) # You need this in descendant
status_change = models.DateTimeField(_('Last status change'), default=None, null=True, editable=False)
created = models.DateTimeField(_('Created'), editable=False)
changed = models.DateTimeField(_('Last changed'), editable=False)
class Meta:
app_label = 'vms'
abstract = True
def __init__(self, *args, **kwargs):
super(_StatusModel, self).__init__(*args, **kwargs)
self._orig_status = self.status
@staticmethod
def status_key(pk): # public helper for accessing the cache key
return str(pk) + ':status'
@staticmethod
def status_change_key(pk): # public helper for accessing the cache key
return str(pk) + ':status-change'
@property # just a helper, so we have one method to construct the cache key
def obj_status_key(self):
return _StatusModel.status_key(self.pk)
@property # just a helper, so we have one method to construct the cache key
def obj_status_change_key(self):
return _StatusModel.status_change_key(self.pk)
def lock(self):
self._lock = True
def unlock(self):
self._lock = False
def save(self, *args, **kwargs):
"""Update status_change and cache when needed"""
if self._lock: # Used for active json display in vm_define when the json is overwritten by active json
raise SuspiciousOperation('%s object "%s" is locked!' % (self.__class__.__name__, self))
now = timezone.now()
status_change_time = kwargs.pop('status_change_time', now)
update_fields = kwargs.get('update_fields', None)
if self._update_changed:
self.changed = now
if not self.created:
self.created = now
if self.status != self._orig_status:
self.status_change = status_change_time
res = super(_StatusModel, self).save(*args, **kwargs)
# update cache if status changed
if self.status != self._orig_status and (update_fields is None or 'status' in update_fields):
if self._cache_status:
cache.set(self.obj_status_key, self.status)
cache.set(self.obj_status_change_key, self.status_change)
self._orig_status = self.status
return res
def save_status(self, new_status=None, **kwargs):
"""Just update the status field (and other related fields)"""
if new_status is not None:
self.status = new_status
return self.save(update_fields=('status', 'status_change'), **kwargs)
# noinspection PyUnusedLocal
@staticmethod
def post_delete_status(sender, instance, **kwargs):
"""Clean cache after removing the object - call from signal"""
# noinspection PyProtectedMember
if instance._cache_status: # remove the cache entries
cache.delete(instance.obj_status_key)
cache.delete(instance.obj_status_change_key)
class _OSType(models.Model):
"""
Abstract class used for children to inherit OS type attributes and field.
"""
LINUX = 1
SUNOS = 2
BSD = 3
WINDOWS = 4
SUNOS_ZONE = 5
LINUX_ZONE = 6
OSTYPE = (
(LINUX, _('Linux VM')),
(SUNOS, _('SunOS VM')),
(BSD, _('BSD VM')),
(WINDOWS, _('Windows VM')),
(SUNOS_ZONE, _('SunOS Zone')),
(LINUX_ZONE, _('Linux Zone')),
)
# KVM = frozenset([LINUX, SUNOS, BSD, WINDOWS]) # to HVM
HVM_OSTYPES = frozenset([LINUX, SUNOS, BSD, WINDOWS])
ZONE_OSTYPES = frozenset([SUNOS_ZONE, LINUX_ZONE])
class Meta:
app_label = 'vms'
abstract = True
# ostype = models.SmallIntegerField(_('Guest OS type'), choices=OSTYPE)
class _HVMType(models.Model):
"""
Abstract class used for children to inherit hvm_type attributes and field.
"""
Hypervisor_KVM = 1
Hypervisor_BHYVE = 2
Hypervisor_NONE = 3 # for zones
HVM_TYPE = (
(Hypervisor_KVM, _('KVM hypervisor')),
(Hypervisor_BHYVE, _('BHYVE hypervisor')),
(Hypervisor_NONE, _('NO hypervisor')),
)
# used on VM create or when editing HVM VM
HVM_TYPE_GUI = (
(Hypervisor_KVM, _('KVM')),
(Hypervisor_BHYVE, _('BHYVE')),
)
# used in VM modal when editing already created zone
HVM_TYPE_GUI_NO_HYPERVISOR = (
(Hypervisor_NONE, _('NO hypervisor')),
)
<|fim▁hole|> abstract = True
class _VirtModel(models.Model):
"""
Abstract class used by any virtualization object/bucket, like Image and
Network. All this objects should have this common attributes for unified
access and naming strategy.
Example: Image access strategy
------------------------------
Public: Customers can purchase this image
Disabled: Shown to customers, but they are not able to purchase it
Private: Internal images shown only to image owners
Deleted: Do not show to anybody
"""
PUBLIC = 1
DISABLED = 2
PRIVATE = 3
DELETED = 4
INTERNAL = 9
ACCESS = (
(PUBLIC, _('Public')),
(DISABLED, _('Disabled')),
(PRIVATE, _('Private')),
(DELETED, _('Deleted')),
(INTERNAL, _('Internal')),
)
INVISIBLE = (DELETED, INTERNAL)
UNUSABLE = (DISABLED, DELETED, INTERNAL)
name = models.CharField(_('Name'), max_length=64, unique=True)
alias = models.CharField(_('Alias'), max_length=32)
desc = models.CharField(_('Description'), max_length=128, blank=True)
owner = models.ForeignKey(User, verbose_name=_('Owner'), on_delete=models.PROTECT)
access = models.SmallIntegerField(_('Access'), choices=ACCESS, default=PRIVATE)
created = models.DateTimeField(_('Created'), auto_now_add=True, editable=False)
changed = models.DateTimeField(_('Last changed'), auto_now=True, editable=False)
class Meta:
app_label = 'vms'
abstract = True
# unique_together = (('alias', 'owner'),)
# ^^^^ This is very important and should be placed in the descendant model.
def __unicode__(self):
return '%s' % self.name
class _UserTasksModel(object):
"""
Model for working (listing, adding, removing) with user tasks related to this object.
WARNING: this implementation depends on the owner attribute.
Object owner must _not_ change when a pending task exists!
"""
owner = None # This class is only useful in models that have a owner attribute
pk = NotImplemented # Should always exist in any django model
_pk_key = NotImplemented # Set in descendant class
_log_name_attr = 'name' # Name of object's attribute which will be used for the object_name field in TaskLogEntry
class Meta:
app_label = 'vms'
abstract = True
@staticmethod
def _add_task(user_id, task_id, info):
return UserTasks(user_id).add(task_id, info)
@staticmethod
def _pop_task(user_id, task_id):
return UserTasks(user_id).pop(task_id)
@staticmethod
def _get_tasks(user_id):
return UserTasks(user_id).tasks
# noinspection PyMethodMayBeStatic
def default_apiview(self):
"""Return dict with object related attributes which are always available in apiview"""
return {}
def get_tasks(self, match_dict=None):
"""Return pending tasks for this VM as a dict with task_id as keys.
If match_dict is specified then try to match key/values to current
tasks and if task is found return only the one task else return {}."""
res = {}
for tid, task in iteritems(self._get_tasks(self.owner.id)):
if task.get(self._pk_key, None) == self.pk:
res[tid] = task.get('apiview', {})
if match_dict:
subtasks = {}
for tid, task in iteritems(res):
match_found = all(task.get(k, None) == v for k, v in iteritems(match_dict))
if match_found:
subtasks[tid] = task
return subtasks
return res
@property # property to get_tasks() method
def tasks(self):
return self.get_tasks()
@property
def tasks_rw(self):
return self.get_tasks(match_dict={'method': RWMethods})
def tasks_ro(self):
return self.get_tasks(match_dict={'method': 'GET'})
@classmethod
def _create_task_info(cls, pk, apiview, msg, additional_apiview=None):
"""Prepare task info dict (will be stored in UserTasks cache)"""
if apiview is None:
apiview = {}
if additional_apiview:
apiview.update(additional_apiview)
if 'time' not in apiview:
apiview['time'] = timezone.now().isoformat()
return {cls._pk_key: pk, 'msg': msg, 'apiview': apiview}
@classmethod
def _tasks_add(cls, pk, task_id, apiview, msg='', **additional_apiview):
"""Add task to pending tasks dict in cache."""
info = cls._create_task_info(pk, apiview, msg, additional_apiview=additional_apiview)
return cls._add_task(owner_id_from_task_id(task_id), task_id, info)
def tasks_add(self, task_id, apiview, msg='', **additional_apiview):
"""Add task to pending tasks dict in cache."""
return self._tasks_add(self.pk, task_id, apiview, msg=msg, **additional_apiview)
@classmethod
def _tasks_del(cls, task_id, apiview=None, **additional_apiview):
"""Delete task from pending tasks dict in cache."""
if apiview is None:
info = cls._pop_task(owner_id_from_task_id(task_id), task_id)
apiview = info.get('apiview', {})
if additional_apiview:
apiview.update(additional_apiview)
# Store task info for socket.io que monitor
cache.set('sio-' + task_id, apiview, 60)
return apiview
def tasks_del(self, task_id, **additional_apiview):
"""Delete task from pending tasks dict in cache."""
info = self._pop_task(owner_id_from_task_id(task_id), task_id)
apiview = info.get('apiview', {})
apiview.update(self.default_apiview())
return self._tasks_del(task_id, apiview=apiview, **additional_apiview)
@classmethod
def get_log_name_lookup_kwargs(cls, log_name_value):
"""Return lookup_key=value DB pairs which can be used for retrieving objects by log_name value"""
return {cls._log_name_attr: log_name_value}
@classmethod
def get_content_type(cls):
# Warning: get_content_type will be deprecated soon. New models should implement get_object_type()
return ContentType.objects.get_for_model(cls)
@classmethod
def get_object_type(cls, content_type=None):
if content_type:
return content_type.model
return cls.get_content_type().model
@classmethod
def get_object_by_pk(cls, pk):
# noinspection PyUnresolvedReferences
return cls.objects.get(pk=pk)
@classmethod
def get_pk_key(cls):
return cls._pk_key
@property
def log_name(self):
return getattr(self, self._log_name_attr)
@property
def log_alias(self):
# noinspection PyUnresolvedReferences
return self.alias
@property
def log_list(self):
return self.log_name, self.log_alias, self.pk, self.__class__
class _VmDiskModel(models.Model):
"""
Abstract class with Virtual Machine disk_id and array_disk_id fields.
"""
_vm_disk_map = None # Cached real_disk_id -> disk_id mapping
_vm_disks = None # Cache vm.json_active_get_disks()
vm = None # declare in descendant class
disk_id = models.SmallIntegerField(_('Disk ID')) # Always store real_disk_id
class Meta:
app_label = 'vms'
abstract = True
def get_disk_map(self):
"""Return real_disk_id -> disk_id mapping"""
self._vm_disks = self.vm.json_active_get_disks()
return self.vm.get_disk_map(self._vm_disks)
@property # Fake disk_id
def array_disk_id(self):
if self._vm_disk_map is None:
self._vm_disk_map = self.get_disk_map()
return self._vm_disk_map[self.disk_id] + 1
@property
def disk_size(self):
disk_id = self.array_disk_id - 1
return self._vm_disks[disk_id]['size']
@property
def zfs_filesystem(self):
disk_id = self.array_disk_id - 1
return self._vm_disks[disk_id]['zfs_filesystem']
@staticmethod
def get_real_disk_id(disk_or_path):
"""Return integer disk suffix from json.disks.*.path attribute"""
if isinstance(disk_or_path, dict):
disk_path = disk_or_path['path']
else:
disk_path = disk_or_path
return int(re.split('-|/', disk_path)[-1].lstrip('disk'))
@classmethod
def get_disk_id(cls, vm, array_disk_id):
"""Return real_disk_id from vm's active_json"""
disk = vm.json_active_get_disks()[array_disk_id - 1]
return cls.get_real_disk_id(disk)
class _ScheduleModel(models.Model):
"""
Abstract class with relation to PeriodicTask and lazy cron schedule and active properties.
"""
PT = PeriodicTask
_active = None # cached enabled attribute
_schedule = None # cached crontab entry
periodic_task = models.ForeignKey(PT, null=True, blank=True)
class Meta:
app_label = 'vms'
abstract = True
# noinspection PyMethodMayBeStatic
def _new_periodic_task(self):
"""Return instance of PeriodicTask. Define in descendant class"""
return NotImplemented # return self.PT(name=, task=, args=, kwargs=, expires=)
def _save_crontab(self, c):
"""Save crontab instance"""
c.minute, c.hour, c.day_of_month, c.month_of_year, c.day_of_week = self.schedule.split()
c.save()
return c
@staticmethod
def crontab_to_schedule(c):
"""Return string representation of CrontabSchedule model"""
def s(f):
return f and str(f).replace(' ', '') or '*'
return '%s %s %s %s %s' % (s(c.minute), s(c.hour), s(c.day_of_month), s(c.month_of_year), s(c.day_of_week))
@property
def active(self):
"""Return enabled boolean from periodic task"""
if self._active is None: # init
if self.periodic_task:
self._active = self.periodic_task.enabled
else:
self._active = True # default
return self._active
@active.setter
def active(self, value):
"""Cache active attribute - will be updated/created later in save()"""
self._active = value
@property
def schedule(self):
"""Return cron entry from periodic task"""
if self._schedule is None and self.periodic_task and self.periodic_task.crontab: # init
self._schedule = self.crontab_to_schedule(self.periodic_task.crontab)
return self._schedule
@schedule.setter
def schedule(self, value):
"""Cache cron entry - will be updated/created later in save()"""
self._schedule = value
@transaction.atomic
def save(self, *args, **kwargs):
"""Create or update periodic task and cron schedule in DB"""
# Save first, because the periodic_task needs this object's ID
super(_ScheduleModel, self).save(*args, **kwargs)
do_save = False
pt = self.periodic_task
if not pt:
pt = self._new_periodic_task()
if not pt.crontab:
pt.crontab = self._save_crontab(CrontabSchedule())
do_save = True
elif self.schedule != self.crontab_to_schedule(pt.crontab):
self._save_crontab(pt.crontab)
do_save = True # Need to update PeriodicTask, because it will signal the Scheduler to reload
if self.active != pt.enabled:
pt.enabled = self.active
do_save = True
if not pt.pk:
pt.save() # New periodic task object
self.periodic_task = pt
self.save(update_fields=('periodic_task',)) # Update this object
elif do_save:
pt.save(update_fields=('enabled', 'crontab', 'date_changed')) # Update periodic task
# noinspection PyUnusedLocal
@staticmethod
def post_delete_schedule(sender, instance, **kwargs):
"""Cascade delete - call from signal"""
if instance.periodic_task:
if instance.periodic_task.crontab:
instance.periodic_task.crontab.delete()
else:
instance.periodic_task.delete()<|fim▁end|> | HVM = frozenset([Hypervisor_KVM, Hypervisor_BHYVE])
class Meta:
app_label = 'vms' |
<|file_name|>Volume.java<|end_file_name|><|fim▁begin|>/*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.<|fim▁hole|>
package com.amazonaws.services.ecs.model;
import java.io.Serializable;
/**
* <p>
* A data volume used in a task definition.
* </p>
*/
public class Volume implements Serializable, Cloneable {
/**
* <p>
* The name of the volume. Up to 255 letters (uppercase and lowercase),
* numbers, hyphens, and underscores are allowed. This name is referenced in
* the <code>sourceVolume</code> parameter of container definition
* <code>mountPoints</code>.
* </p>
*/
private String name;
/**
* <p>
* The contents of the <code>host</code> parameter determine whether your
* data volume persists on the host container instance and where it is
* stored. If the host parameter is empty, then the Docker daemon assigns a
* host path for your data volume, but the data is not guaranteed to persist
* after the containers associated with it stop running.
* </p>
*/
private HostVolumeProperties host;
/**
* <p>
* The name of the volume. Up to 255 letters (uppercase and lowercase),
* numbers, hyphens, and underscores are allowed. This name is referenced in
* the <code>sourceVolume</code> parameter of container definition
* <code>mountPoints</code>.
* </p>
*
* @param name
* The name of the volume. Up to 255 letters (uppercase and
* lowercase), numbers, hyphens, and underscores are allowed. This
* name is referenced in the <code>sourceVolume</code> parameter of
* container definition <code>mountPoints</code>.
*/
public void setName(String name) {
this.name = name;
}
/**
* <p>
* The name of the volume. Up to 255 letters (uppercase and lowercase),
* numbers, hyphens, and underscores are allowed. This name is referenced in
* the <code>sourceVolume</code> parameter of container definition
* <code>mountPoints</code>.
* </p>
*
* @return The name of the volume. Up to 255 letters (uppercase and
* lowercase), numbers, hyphens, and underscores are allowed. This
* name is referenced in the <code>sourceVolume</code> parameter of
* container definition <code>mountPoints</code>.
*/
public String getName() {
return this.name;
}
/**
* <p>
* The name of the volume. Up to 255 letters (uppercase and lowercase),
* numbers, hyphens, and underscores are allowed. This name is referenced in
* the <code>sourceVolume</code> parameter of container definition
* <code>mountPoints</code>.
* </p>
*
* @param name
* The name of the volume. Up to 255 letters (uppercase and
* lowercase), numbers, hyphens, and underscores are allowed. This
* name is referenced in the <code>sourceVolume</code> parameter of
* container definition <code>mountPoints</code>.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public Volume withName(String name) {
setName(name);
return this;
}
/**
* <p>
* The contents of the <code>host</code> parameter determine whether your
* data volume persists on the host container instance and where it is
* stored. If the host parameter is empty, then the Docker daemon assigns a
* host path for your data volume, but the data is not guaranteed to persist
* after the containers associated with it stop running.
* </p>
*
* @param host
* The contents of the <code>host</code> parameter determine whether
* your data volume persists on the host container instance and where
* it is stored. If the host parameter is empty, then the Docker
* daemon assigns a host path for your data volume, but the data is
* not guaranteed to persist after the containers associated with it
* stop running.
*/
public void setHost(HostVolumeProperties host) {
this.host = host;
}
/**
* <p>
* The contents of the <code>host</code> parameter determine whether your
* data volume persists on the host container instance and where it is
* stored. If the host parameter is empty, then the Docker daemon assigns a
* host path for your data volume, but the data is not guaranteed to persist
* after the containers associated with it stop running.
* </p>
*
* @return The contents of the <code>host</code> parameter determine whether
* your data volume persists on the host container instance and
* where it is stored. If the host parameter is empty, then the
* Docker daemon assigns a host path for your data volume, but the
* data is not guaranteed to persist after the containers associated
* with it stop running.
*/
public HostVolumeProperties getHost() {
return this.host;
}
/**
* <p>
* The contents of the <code>host</code> parameter determine whether your
* data volume persists on the host container instance and where it is
* stored. If the host parameter is empty, then the Docker daemon assigns a
* host path for your data volume, but the data is not guaranteed to persist
* after the containers associated with it stop running.
* </p>
*
* @param host
* The contents of the <code>host</code> parameter determine whether
* your data volume persists on the host container instance and where
* it is stored. If the host parameter is empty, then the Docker
* daemon assigns a host path for your data volume, but the data is
* not guaranteed to persist after the containers associated with it
* stop running.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public Volume withHost(HostVolumeProperties host) {
setHost(host);
return this;
}
/**
* Returns a string representation of this object; useful for testing and
* debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getName() != null)
sb.append("Name: " + getName() + ",");
if (getHost() != null)
sb.append("Host: " + getHost());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof Volume == false)
return false;
Volume other = (Volume) obj;
if (other.getName() == null ^ this.getName() == null)
return false;
if (other.getName() != null
&& other.getName().equals(this.getName()) == false)
return false;
if (other.getHost() == null ^ this.getHost() == null)
return false;
if (other.getHost() != null
&& other.getHost().equals(this.getHost()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode
+ ((getName() == null) ? 0 : getName().hashCode());
hashCode = prime * hashCode
+ ((getHost() == null) ? 0 : getHost().hashCode());
return hashCode;
}
@Override
public Volume clone() {
try {
return (Volume) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(
"Got a CloneNotSupportedException from Object.clone() "
+ "even though we're Cloneable!", e);
}
}
}<|fim▁end|> | */ |
<|file_name|>parser.rs<|end_file_name|><|fim▁begin|>/**
# AST DEFINITION
## Symbols
⁞literal⁞ means the token must be a literal, but it also has additional
mandatory hygiene metadata that must be carried along (i.e. the token
cannot be synthesized in the macro).
«bool» one of the literal true or false
«ident» a Rust identifier
«ty» a Rust type
«block» a Rust block
«CamelCased» is the name of a production defined in the grammar
‹production1 | production2 (| productionN)*› is a union of several
productions, all of which are valid.
All other literals are literal Rust tokens.
## Grammar
Class :
{
type: class,
rust_name: «ident»,
ruby_name: { string },
meta: «Meta»,
struct: ‹() | { «Field»,* }›
methods: [ «Method»,* ]
}
Meta :
{
pub: «bool»,
reopen: «bool»
}
Field :
«ident» : «ty»
Method :
{
type: «MethodType»,
rust_name: «ident»,
ruby_name: { string },
self: ‹() | «MethodSelf»›,
args: «MethodArgs»,
ret: { «ty» },
body: «block»
}
MethodType : ‹initializer | instance_method | class_method›
MethodSelf :
{
ownership: { «Ownership» },
name: ‹⁞helix⁞ | ⁞self⁞›
}
MethodArgs :
[ «MethodArg»,* ]
MethodArg :
«Name» : «ty»
Name : ‹_ | «ident»›
*/
#[doc(hidden)]
#[macro_export]
macro_rules! parse {
// STATE: top_level
{
state: top_level,
buffer: {},
stack: { ast: $ast:tt }
} => {
codegen! { $ast }
};
{
state: top_level,
buffer: $buffer:tt,
stack: { $($stack: tt)* }
} => {
parse! {
state: parse_class_attributes,
buffer: $buffer,
stack: {
ruby_name: uninitialized,
attributes: {},
pub: false,
reopen: false,
$($stack)*
}
}
};
// STATE: parse_class_attributes
{
state: parse_class_attributes,
buffer: { #[ruby_name = $ruby_name:tt] $($rest:tt)* },
stack: {
ruby_name: uninitialized,
$($stack:tt)*
}
} => {
parse! {
state: parse_class_attributes,
buffer: { $($rest)* },
stack: {
ruby_name: { $ruby_name },
$($stack)*
}
}
};
{
state: parse_class_attributes,
buffer: { #[$($attribute:tt)*] $($rest:tt)* },
stack: {
ruby_name: $ruby_name:tt,
attributes: { $($attributes:tt)* },
$($stack:tt)*
}
} => {
parse! {
state: parse_class_attributes,
buffer: { $($rest)* },
stack: {
ruby_name: $ruby_name,
attributes: { $($attributes)* #[$($attribute)*] },
$($stack)*
}
}
};
{
state: parse_class_attributes,
buffer: $buffer:tt,
stack: $stack:tt
} => {
parse! {
state: parse_class,
buffer: $buffer,
stack: $stack
}
};
// STATE: parse_class
{
state: parse_class,
buffer: { pub $($rest:tt)* },
stack: {
ruby_name: $ruby_name:tt,
attributes: $attributes:tt,
pub: false,
reopen: false,
$($stack:tt)*
}
} => {
parse! {
state: parse_class,
buffer: { $($rest)* },
stack: {
ruby_name: $ruby_name,
attributes: $attributes,
pub: true,
reopen: false,
$($stack)*
}
}
};
{
state: parse_class,
buffer: { reopen $($rest:tt)* },
stack: {
ruby_name: $ruby_name:tt,
attributes: $attributes:tt,
pub: $pub:tt,
reopen: false,
$($stack:tt)*
}
} => {
parse! {
state: parse_class,
buffer: { $($rest)* },
stack: {
ruby_name: $ruby_name,
attributes: $attributes,
pub: $pub,
reopen: true,
$($stack)*
}
}
};
{
state: parse_class,
buffer: { class $name:tt $($rest:tt)* },
stack: {
ruby_name: uninitialized,
$($stack:tt)*
}
} => {
parse! {
state: parse_class,
buffer: { class $name $($rest)* },
stack: {
ruby_name: { stringify!($name) },
$($stack)*
}
}
};
{
state: parse_class,
buffer: { class $name:tt { $($body:tt)* } $($rest:tt)* },
stack: {
ruby_name: $ruby_name:tt,
attributes: $attributes:tt,
pub: $pub:tt,
reopen: $reopen:tt,
$($stack:tt)*
}
} => {
parse! {
state: parse_struct,
buffer: { $($body)* },
stack: {
class: {
type: class,
rust_name: $name,
ruby_name: $ruby_name,
attributes: $attributes,
meta: { pub: $pub, reopen: $reopen },
struct: (),
methods: []
},
program: { $($rest)* },
$($stack)*
}
}
};
// STATE: parse_struct
{
state: parse_struct,
buffer: { struct { $($struct:tt)* } $($rest:tt)* },
stack: {
class: {
type: class,
rust_name: $rust_name:tt,
ruby_name: $ruby_name:tt,
attributes: $attributes:tt,
meta: { pub: $pub:tt, reopen: $reopen:tt },
struct: (),
methods: []
},
$($stack:tt)*
}
} => {
assert_not_reopen!({ reopen: $reopen }, "Cannot define a struct in `reopen class`");
parse! {
state: parse_methods,
buffer: { $($rest)* },
stack: {
class: {
type: class,
rust_name: $rust_name,
ruby_name: $ruby_name,
attributes: $attributes,
meta: { pub: $pub, reopen: $reopen },
struct: { $($struct)* },
methods: []
},
$($stack)*
}
}
};
{
state: parse_struct,
buffer: $buffer:tt,
stack: $stack:tt
} => {
parse! {
state: parse_methods,
buffer: $buffer,
stack: $stack
}
};
// STATE: parse_methods
{
state: parse_methods,
buffer: {},
stack: {
class: $class:tt,
program: $program:tt,
ast: [ $($ast:tt)* ]
}
} => {
assert_has_initialize!($class, "Classes defining a struct must implement `initialize`");
parse! {
state: top_level,
buffer: $program,
stack: {
ast: [ $($ast)* $class ]
}
}
};
{
state: parse_methods,
buffer: $buffer:tt,
stack: { $($stack:tt)* }
} => {
parse! {
state: parse_method_attributes,
buffer: $buffer,
stack: {
rust_name: uninitialized,
ruby_name: uninitialized,
ruby_visibility: public,
attributes: {},
$($stack)*
}
}
};
// STATE: parse_method_attributes
{
state: parse_method_attributes,
buffer: { #[ruby_name = $ruby_name:tt] $($rest:tt)* },
stack: {
rust_name: uninitialized,
ruby_name: uninitialized,
$($stack:tt)*
}
} => {
parse! {
state: parse_method_attributes,
buffer: { $($rest)* },
stack: {
rust_name: uninitialized,
ruby_name: { $ruby_name },
$($stack)*
}
}
};
{
state: parse_method_attributes,
buffer: { #[ruby_visibility = $ruby_visibility:tt] $($rest:tt)* },
stack: {
rust_name: uninitialized,
ruby_name: $ruby_name:tt,
ruby_visibility: public,
$($stack:tt)*
}
} => {
parse! {
state: parse_method_attributes,
buffer: { $($rest)* },
stack: {
rust_name: uninitialized,
ruby_name: $ruby_name,
ruby_visibility: $ruby_visibility,
$($stack)*
}
}
};
{
state: parse_method_attributes,
buffer: { #[$($attribute:tt)*] $($rest:tt)* },
stack: {
rust_name: uninitialized,
ruby_name: $ruby_name:tt,
ruby_visibility: $ruby_visibility:tt,
attributes: { $($attributes:tt)* },
$($stack:tt)*
}
} => {
parse! {
state: parse_method_attributes,
buffer: { $($rest)* },
stack: {
rust_name: uninitialized,
ruby_name: $ruby_name,
ruby_visibility: $ruby_visibility,
attributes: { $($attributes)* #[$($attribute)*] },
$($stack)*
}
}
};
{
state: parse_method_attributes,
buffer: $buffer:tt,
stack: $stack:tt
} => {
parse! {
state: parse_method_name,
buffer: $buffer,
stack: $stack
}
};
// STATE: parse_method_name
{
state: parse_method_name,
buffer: { def $name:tt $($rest:tt)* },
stack: {
rust_name: uninitialized,
ruby_name: uninitialized,
$($stack:tt)*
}
} => {
parse! {
state: parse_method,
buffer: { $($rest)* },
stack: {
rust_name: $name,
ruby_name: { stringify!($name) },
$($stack)*
}
}
};
{
state: parse_method_name,
buffer: { def $name:tt $($rest:tt)* },
stack: {
rust_name: uninitialized,
ruby_name: $ruby_name:tt,
$($stack:tt)*
}
} => {
parse! {
state: parse_method,
buffer: { $($rest)* },
stack: {
rust_name: $name,
ruby_name: $ruby_name,
$($stack)*
}
}
};
// STATE: parse_method
{
state: parse_method,
buffer: { ( $($args:tt)* ) $($rest:tt)* },
stack: {
rust_name: initialize,
ruby_name: $ruby_name:tt,
ruby_visibility: $ruby_visibility:tt,
attributes: $attributes:tt,
class: $class:tt,
$($stack:tt)*
}
} => {
assert_not_reopen!($class, "Cannot define `initialize` in `reopen class`");
assert_has_struct!($class, "Cannot define `initialize` without a `struct`");
parse! {
state: parse_arguments_initialize,
buffer: { $($args)* },
stack: {
ruby_visibility: $ruby_visibility,
attributes: $attributes,
class_body: { $($rest)* },
class: $class,
$($stack)*
}
}
};
{
state: parse_method,
buffer: { ( $($args:tt)* ) $($rest:tt)* },
stack: {
rust_name: $rust_name:tt,
ruby_name: $ruby_name:tt,
ruby_visibility: $ruby_visibility:tt,
attributes: $attributes:tt,
$($stack:tt)*
}
} => {
parse! {
state: parse_arguments,
buffer: { $($args)* },
stack: {
rust_name: $rust_name,
ruby_name: $ruby_name,
ruby_visibility: $ruby_visibility,
attributes: $attributes,
class_body: { $($rest)* },
$($stack)*
}
}
};
// STATE: parse_arguments_initialize
{
state: parse_arguments_initialize,
buffer: { $helix_arg:tt, $($args:tt)+ },
stack: {
ruby_visibility: $ruby_visibility:tt,
attributes: $attributes:tt,
class_body: $class_body:tt,
$($stack:tt)*
}
} => {
assert_valid_helix_arg!($helix_arg);
parse! {
state: parse_return_type,
buffer: $class_body,
stack: {
method: {
type: initializer,
rust_name: initialize,
ruby_name: { "initialize" },
ruby_visibility: $ruby_visibility,
attributes: $attributes,
self: {
ownership: { },
name: $helix_arg
},
args: [ $($args)* ],
ret: uninitialized,
body: uninitialized
},
$($stack)*
}
}
};
{
state: parse_arguments_initialize,
buffer: { $helix_arg:tt },
stack: {
ruby_visibility: $ruby_visibility:tt,
attributes: $attributes:tt,
class_body: $class_body:tt,
$($stack:tt)*
}
} => {
assert_valid_helix_arg!($helix_arg);
parse! {
state: parse_return_type,
buffer: $class_body,
stack: {
method: {
type: initializer,
rust_name: initialize,
ruby_name: { "initialize" },
ruby_visibility: $ruby_visibility,
attributes: $attributes,
self: {
ownership: { },
name: $helix_arg
},
args: [ ],
ret: uninitialized,
body: uninitialized
},
$($stack)*
}
}
};
// STATE: parse_arguments
{
state: parse_arguments,
buffer: { &mut $self_arg:tt, $($args:tt)+ },
stack: {
rust_name: $rust_name:tt,
ruby_name: $ruby_name:tt,
ruby_visibility: $ruby_visibility:tt,
attributes: $attributes:tt,
class_body: $class_body:tt,
$($stack:tt)*
}
} => {
assert_valid_self_arg!($self_arg);
parse! {
state: parse_return_type,
buffer: $class_body,
stack: {
method: {
type: instance_method,
rust_name: $rust_name,
ruby_name: $ruby_name,
ruby_visibility: $ruby_visibility,
attributes: $attributes,
self: {
ownership: { &mut },
name: $self_arg
},
args: [ $($args)* ],
ret: uninitialized,
body: uninitialized
},
$($stack)*
}
}
};
{
state: parse_arguments,
buffer: { &mut $self_arg:tt },
stack: {
rust_name: $rust_name:tt,
ruby_name: $ruby_name:tt,
ruby_visibility: $ruby_visibility:tt,
attributes: $attributes:tt,
class_body: $class_body:tt,
$($stack:tt)*
}
} => {
assert_valid_self_arg!($self_arg);
parse! {
state: parse_return_type,
buffer: $class_body,
stack: {
method: {
type: instance_method,
rust_name: $rust_name,
ruby_name: $ruby_name,
ruby_visibility: $ruby_visibility,
attributes: $attributes,
self: {
ownership: { &mut },
name: $self_arg
},
args: [ ],
ret: uninitialized,
body: uninitialized
},
$($stack)*
}
}
};
{
state: parse_arguments,
buffer: { & $self_arg:tt, $($args:tt)+ },
stack: {
rust_name: $rust_name:tt,
ruby_name: $ruby_name:tt,
ruby_visibility: $ruby_visibility:tt,
attributes: $attributes:tt,
class_body: $class_body:tt,
$($stack:tt)*
}
} => {
assert_valid_self_arg!($self_arg);
parse! {
state: parse_return_type,
buffer: $class_body,
stack: {
method: {
type: instance_method,
rust_name: $rust_name,
ruby_name: $ruby_name,
ruby_visibility: $ruby_visibility,
attributes: $attributes,
self: {
ownership: { & },
name: $self_arg
},
args: [ $($args)* ],
ret: uninitialized,
body: uninitialized
},
$($stack)*
}
}
};
{
state: parse_arguments,
buffer: { & $self_arg:tt },
stack: {
rust_name: $rust_name:tt,
ruby_name: $ruby_name:tt,
ruby_visibility: $ruby_visibility:tt,
attributes: $attributes:tt,
class_body: $class_body:tt,
$($stack:tt)*
}
} => {
assert_valid_self_arg!($self_arg);
parse! {
state: parse_return_type,
buffer: $class_body,
stack: {
method: {
type: instance_method,
rust_name: $rust_name,
ruby_name: $ruby_name,
ruby_visibility: $ruby_visibility,
attributes: $attributes,
self: {
ownership: { & },
name: $self_arg
},
args: [ ],
ret: uninitialized,
body: uninitialized
},
$($stack)*
}
}
};
{
state: parse_arguments,
buffer: { $self_arg:tt, $($args:tt)+ },
stack: {
rust_name: $rust_name:tt,
ruby_name: $ruby_name:tt,
ruby_visibility: $ruby_visibility:tt,
attributes: $attributes:tt,
class_body: $class_body:tt,
$($stack:tt)*
}
} => {
assert_valid_self_arg!($self_arg);
parse! {
state: parse_return_type,
buffer: $class_body,
stack: {
method: {
type: instance_method,
rust_name: $rust_name,
ruby_name: $ruby_name,
ruby_visibility: $ruby_visibility,
attributes: $attributes,
self: {
ownership: { },
name: $self_arg
},
args: [ $($args)* ],
ret: uninitialized,
body: uninitialized
},
$($stack)*
}
}
};
{
state: parse_arguments,
buffer: { $self_arg:tt },
stack: {
rust_name: $rust_name:tt,
ruby_name: $ruby_name:tt,
ruby_visibility: $ruby_visibility:tt,
attributes: $attributes:tt,
class_body: $class_body:tt,
$($stack:tt)*
}
} => {
assert_valid_self_arg!($self_arg);
parse! {
state: parse_return_type,
buffer: $class_body,
stack: {
method: {
type: instance_method,
rust_name: $rust_name,
ruby_name: $ruby_name,
ruby_visibility: $ruby_visibility,
attributes: $attributes,
self: {
ownership: { },
name: $self_arg
},
args: [ ],
ret: uninitialized,
body: uninitialized
},
$($stack)*
}
}
};
{
state: parse_arguments,
buffer: { $($args:tt)* },
stack: {
rust_name: $rust_name:tt,
ruby_name: $ruby_name:tt,
ruby_visibility: $ruby_visibility:tt,
attributes: $attributes:tt,
class_body: $class_body:tt,
$($stack:tt)*
}
} => {
parse! {
state: parse_return_type,
buffer: $class_body,
stack: {
method: {
type: class_method,
rust_name: $rust_name,
ruby_name: $ruby_name,
ruby_visibility: $ruby_visibility,
attributes: $attributes,
self: (),
args: [ $($args)* ],
ret: uninitialized,
body: uninitialized
},
$($stack)*
}
}
};
// STATE: parse_return_type
{
state: parse_return_type,
buffer: { -> $ret:ty $body:block $($rest:tt)* },
stack: {
method: {
type: $type:tt,
rust_name: $rust_name:tt,
ruby_name: $ruby_name:tt,
ruby_visibility: $ruby_visibility:tt,
attributes: $attributes:tt,
self: $self:tt,
args: $args:tt,
ret: uninitialized,
body: uninitialized
},
$($stack:tt)*
}
} => {
assert_no_explict_return_for_initializer!({ type: $type }, "`def initialize` cannot have an explicit return type");
parse! {
state: finish_method,
buffer: { $($rest)* },
stack: {
method: {
type: $type,
rust_name: $rust_name,
ruby_name: $ruby_name,
ruby_visibility: $ruby_visibility,
attributes: $attributes,
self: $self,
args: $args,
ret: { $ret },
body: $body
},
$($stack)*
}
}
};
{
state: parse_return_type,<|fim▁hole|> stack: {
method: {
type: initializer,
rust_name: $rust_method_name:tt,
ruby_name: $ruby_method_name:tt,
ruby_visibility: $ruby_visibility:tt,
attributes: $metod_attributes:tt,
self: $self:tt,
args: $args:tt,
ret: uninitialized,
body: uninitialized
},
class: {
type: class,
rust_name: $rust_class_name:ident,
ruby_name: $ruby_class_name:tt,
attributes: $class_attributes:tt,
meta: $meta:tt,
struct: $struct:tt,
methods: $methods:tt
},
$($stack:tt)*
}
} => {
parse! {
state: finish_method,
buffer: { $($rest)* },
stack: {
method: {
type: initializer,
rust_name: $rust_method_name,
ruby_name: $ruby_method_name,
ruby_visibility: $ruby_visibility,
attributes: $metod_attributes,
self: $self,
args: $args,
ret: { $rust_class_name },
body: $body
},
class: {
type: class,
rust_name: $rust_class_name,
ruby_name: $ruby_class_name,
attributes: $class_attributes,
meta: $meta,
struct: $struct,
methods: $methods
},
$($stack)*
}
}
};
{
state: parse_return_type,
buffer: { $body:block $($rest:tt)* },
stack: {
method: {
type: $type:tt,
rust_name: $rust_name:tt,
ruby_name: $ruby_name:tt,
ruby_visibility: $ruby_visibility:tt,
attributes: $attributes:tt,
self: $self:tt,
args: $args:tt,
ret: uninitialized,
body: uninitialized
},
$($stack:tt)*
}
} => {
parse! {
state: finish_method,
buffer: { $($rest)* },
stack: {
method: {
type: $type,
rust_name: $rust_name,
ruby_name: $ruby_name,
ruby_visibility: $ruby_visibility,
attributes: $attributes,
self: $self,
args: $args,
ret: { () },
body: $body
},
$($stack)*
}
}
};
// STATE: finish_method
{
state: finish_method,
buffer: $buffer:tt,
stack: {
method: $method:tt,
class: {
type: class,
rust_name: $rust_name:ident,
ruby_name: $ruby_name:tt,
attributes: $attributes:tt,
meta: $meta:tt,
struct: $struct:tt,
methods: [ $($methods:tt)* ]
},
$($stack:tt)*
}
} => {
parse! {
state: parse_methods,
buffer: $buffer,
stack: {
class: {
type: class,
rust_name: $rust_name,
ruby_name: $ruby_name,
attributes: $attributes,
meta: $meta,
struct: $struct,
methods: [ $($methods)* $method ]
},
$($stack)*
}
}
};
// Catch all
{
state: $state:tt,
buffer: { $($buffer:tt)* },
stack: $stack:tt
} => {
unexpected_token!($($buffer)*);
parse_error!(
"If you suspect this is a bug in Helix itself, please file an ",
"issue with the following debug information:\n\n",
"{\n",
" state: ", stringify!($state), ",\n",
" buffer: ", stringify!({ $($buffer)* }), ",\n",
" stack: ", stringify!($stack), ",\n",
"}"
);
};
{ $($state:tt)* } => {
parse_error!(
"Corrupted parser state. ",
"This is likely a bug in Helix itself, please file an issue ",
"with the following debug information:\n\n",
stringify!($($state)*)
);
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! unexpected_token {
() => {};
}
#[doc(hidden)]
#[macro_export]
macro_rules! parse_error {
($($message:expr),*) => { compile_error!(concat!("Parse Error! ", $($message),*)); };
}
#[doc(hidden)]
#[macro_export]
macro_rules! assert_not_reopen {
{
{
type: class,
rust_name: $rust_name:tt,
ruby_name: $ruby_name:tt,
attributes: $attributes:tt,
meta: { pub: $pub:tt, reopen: $reopen:tt },
struct: $struct:tt,
methods: $methods:tt
},
$($message:expr),*
} => { assert_not_reopen!({ reopen: $reopen }, $($message),*); };
{ { reopen: true }, $($message:expr),* } => { parse_error!($($message),*); };
{ { reopen: false }, $($message:expr),* } => {};
}
#[doc(hidden)]
#[macro_export]
macro_rules! assert_has_initialize {
{
{
type: class,
rust_name: $rust_name:tt,
ruby_name: $ruby_name:tt,
attributes: $attributes:tt,
meta: $meta:tt,
struct: $struct:tt,
methods: $methods:tt
},
$($message:expr),*
} => { assert_has_initialize!({ struct: $struct }, $methods, $($message),*); };
{ { struct: () }, $methods:tt, $($message:expr),* } => {};
{ { struct: $struct:tt }, [ ], $($message:expr),* } => { parse_error!($($message),*); };
{ { struct: $struct:tt }, [ { type: initializer, $($rest:tt)* } $($methods:tt)* ], $($message:expr),* } => {};
{ { struct: $struct:tt }, [ $method:tt $($methods:tt)* ], $($message:expr),* } => {
assert_has_initialize!({ struct: $struct }, [ $($methods)* ], $($message),*);
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! assert_has_struct {
{
{
type: class,
rust_name: $rust_name:tt,
ruby_name: $ruby_name:tt,
attributes: $attributes:tt,
meta: $meta:tt,
struct: $struct:tt,
methods: $methods:tt
},
$($message:expr),*
} => { assert_has_struct!({ struct: $struct }, $($message),*); };
{ { struct: () }, $($message:expr),* } => { parse_error!($($message),*); };
{ { struct: $struct:tt }, $($message:expr),* } => {};
}
#[doc(hidden)]
#[macro_export]
macro_rules! assert_valid_helix_arg {
(helix) => {};
}
#[doc(hidden)]
#[macro_export]
macro_rules! assert_valid_self_arg {
(self) => {};
}
#[doc(hidden)]
#[macro_export]
macro_rules! assert_no_explict_return_for_initializer {
({ type: instance_method }, $($message:expr),*) => {};
({ type: class_method }, $($message:expr),*) => {};
({ type: initializer }, $($message:expr),*) => { parse_error!($($message),*); };
}<|fim▁end|> | buffer: { $body:block $($rest:tt)* }, |
<|file_name|>FileIterator.cpp<|end_file_name|><|fim▁begin|>/*
* Copyright (C) 2009 University of Southern California and
* Andrew D. Smith
*
* Authors: Andrew D. Smith
*
* 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/>.
*/
#include "FileIterator.hpp"
#include "GenomicRegion.hpp"
#include "MappedRead.hpp"
#include <iostream>
<|fim▁hole|>
/* THIS FUNCTION FILLS A BUFFER FOR GenomicRegion OBJECTS
*/
void
fill_buffer(std::ifstream &in, const size_t buffer_start,
vector<GenomicRegion> &buffer) {
GenomicRegion tmp;
size_t i = buffer_start;
assert(buffer_start <= buffer.size());
for (; i != buffer.size() && !in.eof(); ++i) {
in >> tmp;
buffer[i].swap(tmp);
in.peek();
}
if (i < buffer.size())
buffer.erase(buffer.begin() + i, buffer.end());
}
/* THIS FUNCTION FILLS A BUFFER FOR THE ACTUAL READS, REPRESENTED AS
* STRINGS, AND MUST BE IN A FASTA FORMAT FILE
*/
void
fill_buffer(std::ifstream &in, const size_t buffer_start,
vector<string> &buffer) {
string tmp;
size_t i = buffer_start;
for (; i != buffer.size() && !in.eof(); ++i) {
// the read name...
in >> tmp; // DANGER: assumes that the name of the read has no
// spaces in it!!
// the read itself:
in >> buffer[i];
in.peek();
}
if (i < buffer.size())
buffer.erase(buffer.begin() + i, buffer.end());
}
/* THIS FUNCTION FILLS A BUFFER FOR THE ACTUAL READS, REPRESENTED AS
* RECORDS IN A FASTQ FILE, INCLUDING THE QUALITY SCORES
*/
void
fill_buffer(std::ifstream &in, const size_t buffer_start,
vector<FASTQRecord> &buffer) {
string tmp, read_seq, scores_seq;
size_t i = buffer_start;
for (; i != buffer.size() && !in.eof(); ++i) {
// the read name...
in >> tmp; // DANGER: assumes that the name of the read has no
// spaces in it!!
// the read itself:
in >> read_seq;
in >> tmp;
in >> scores_seq;
buffer[i] = std::make_pair(read_seq, scores_seq);
in.peek();
}
if (i < buffer.size())
buffer.erase(buffer.begin() + i, buffer.end());
}
/* THIS FUNCTION FILLS A BUFFER FOR THE ACTUAL READS, REPRESENTED AS
* RECORDS IN A FASTQ FILE, INCLUDING THE QUALITY SCORES
*/
void
fill_buffer(std::ifstream &in, const size_t buffer_start,
vector<MappedRead> &buffer) {
size_t i = buffer_start;
for (; i != buffer.size() && !in.eof(); ++i) {
in >> buffer[i];
in.peek();
}
if (i < buffer.size())
buffer.erase(buffer.begin() + i, buffer.end());
}<|fim▁end|> | using std::istream;
using std::vector;
using std::string; |
<|file_name|>DfaFromNfa.java<|end_file_name|><|fim▁begin|>/*
* Copyright 2015 Matthew Timmermans
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.nobigsoftware.dfalex;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import static backport.java.util.function.BackportFuncs.computeIfAbsent;<|fim▁hole|>
/**
* Turns an NFA into a non-minimal RawDfa by powerset construction
*/
class DfaFromNfa<RESULT> {
//inputs
private final Nfa<RESULT> m_nfa;
private final int[] m_nfaStartStates;
private final int[] m_dfaStartStates;
private final DfaAmbiguityResolver<? super RESULT> m_ambiguityResolver;
//utility
private final DfaStateSignatureCodec m_dfaSigCodec = new DfaStateSignatureCodec();
//These fields are scratch space
private final IntListKey m_tempStateSignature = new IntListKey();
private final ArrayDeque<Integer> m_tempNfaClosureList = new ArrayDeque<>();
private final HashSet<RESULT> m_tempResultSet = new HashSet<RESULT>();
//accumulators
private final HashMap<RESULT, Integer> m_acceptSetMap = new HashMap<>();
private final ArrayList<RESULT> m_acceptSets = new ArrayList<>();
private final HashMap<IntListKey, Integer> m_dfaStateSignatureMap = new HashMap<>();
private final ArrayList<IntListKey> m_dfaStateSignatures = new ArrayList<>();
private final ArrayList<DfaStateInfo> m_dfaStates = new ArrayList<>();
public DfaFromNfa(Nfa<RESULT> nfa, int[] nfaStartStates,
DfaAmbiguityResolver<? super RESULT> ambiguityResolver) {
m_nfa = nfa;
m_nfaStartStates = nfaStartStates;
m_dfaStartStates = new int[nfaStartStates.length];
m_ambiguityResolver = ambiguityResolver;
m_acceptSets.add(null);
_build();
}
public RawDfa<RESULT> getDfa() {
return new RawDfa<>(m_dfaStates, m_acceptSets, m_dfaStartStates);
}
private void _build() {
final CompactIntSubset nfaStateSet = new CompactIntSubset(m_nfa.numStates());
final ArrayList<NfaTransition> dfaStateTransitions = new ArrayList<>();
final ArrayList<NfaTransition> transitionQ = new ArrayList<>(1000);
//Create the DFA start states
for (int i = 0; i < m_dfaStartStates.length; ++i) {
nfaStateSet.clear();
_addNfaStateAndEpsilonsToSubset(nfaStateSet, m_nfaStartStates[i]);
m_dfaStartStates[i] = _getDfaState(nfaStateSet);
}
//Create the transitions and other DFA states.
//m_dfaStateSignatures grows as we discover new states.
//m_dfaStates grows as we complete them
for (int stateNum = 0; stateNum < m_dfaStateSignatures.size(); ++stateNum) {
final IntListKey dfaStateSig = m_dfaStateSignatures.get(stateNum);
dfaStateTransitions.clear();
//For each DFA state, combine the NFA transitions for each
//distinct character range into a DFA transiton, appending new DFA states
//as we discover them.
transitionQ.clear();
//dump all the NFA transitions for the state into the Q
DfaStateSignatureCodec.expand(dfaStateSig,
state -> m_nfa.forStateTransitions(state, transitionQ::add));
//sort all the transitions by first character
Collections.sort(transitionQ, (arg0, arg1) -> {
if (arg0.m_firstChar != arg1.m_firstChar) {
return (arg0.m_firstChar < arg1.m_firstChar ? -1 : 1);
}
return 0;
});
final int tqlen = transitionQ.size();
//first character we haven't accounted for yet
char minc = 0;
//NFA transitions at index < tqstart are no longer relevant
//NFA transitions at index >= tqstart are in first char order OR have first char <= minc
//The sequence of NFA transitions contributing the the previous DFA transition starts here
int tqstart = 0;
//make a range of NFA transitions corresponding to the next DFA transition
while (tqstart < tqlen) {
NfaTransition trans = transitionQ.get(tqstart);
if (trans.m_lastChar < minc) {
++tqstart;
continue;
}
//INVAR - trans contributes to the next DFA transition
nfaStateSet.clear();
_addNfaStateAndEpsilonsToSubset(nfaStateSet, trans.m_stateNum);
char startc = trans.m_firstChar;
char endc = trans.m_lastChar;
if (startc < minc) {
startc = minc;
}
//make range of all transitions that include the start character, removing ones
//that drop out
for (int tqend = tqstart + 1; tqend < tqlen; ++tqend) {
trans = transitionQ.get(tqend);
if (trans.m_lastChar < startc) {
//remove this one
transitionQ.set(tqend, transitionQ.get(tqstart++));
continue;
}
if (trans.m_firstChar > startc) {
//this one is for the next transition
if (trans.m_firstChar <= endc) {
endc = (char) (trans.m_firstChar - 1);
}
break;
}
//this one counts
if (trans.m_lastChar < endc) {
endc = trans.m_lastChar;
}
_addNfaStateAndEpsilonsToSubset(nfaStateSet, trans.m_stateNum);
}
dfaStateTransitions.add(new NfaTransition(startc, endc, _getDfaState(nfaStateSet)));
minc = (char) (endc + 1);
if (minc < endc) {
//wrapped around
break;
}
}
//INVARIANT: m_dfaStatesOut.size() == stateNum
m_dfaStates.add(_createStateInfo(dfaStateSig, dfaStateTransitions));
}
}
//Add an NFA state to m_currentNFASubset, along with the transitive
//closure over its epsilon transitions
private void _addNfaStateAndEpsilonsToSubset(CompactIntSubset dest, int stateNum) {
m_tempNfaClosureList.clear();
if (dest.add(stateNum)) {
m_tempNfaClosureList.add(stateNum);
}
Integer newNfaState;
while ((newNfaState = m_tempNfaClosureList.poll()) != null) {
m_nfa.forStateEpsilons(newNfaState, (Integer src) -> {
if (dest.add(src)) {
m_tempNfaClosureList.add(src);
}
});
}
}
private void _addNfaStateToSignatureCodec(int stateNum) {
if (m_nfa.hasTransitionsOrAccepts(stateNum)) {
m_dfaSigCodec.acceptInt(stateNum);
}
}
//Make a DFA state for a set of simultaneous NFA states
private Integer _getDfaState(CompactIntSubset nfaStateSet) {
//dump state combination into compressed form
m_tempStateSignature.clear();
m_dfaSigCodec.start(m_tempStateSignature::add, nfaStateSet.getSize(),
nfaStateSet.getRange());
nfaStateSet.dumpInOrder(this::_addNfaStateToSignatureCodec);
m_dfaSigCodec.finish();
//make sure it's in the map
Integer dfaStateNum = m_dfaStateSignatureMap.get(m_tempStateSignature);
if (dfaStateNum == null) {
dfaStateNum = m_dfaStateSignatures.size();
IntListKey newSig = new IntListKey(m_tempStateSignature);
m_dfaStateSignatures.add(newSig);
m_dfaStateSignatureMap.put(newSig, dfaStateNum);
}
return dfaStateNum;
}
@SuppressWarnings("unchecked")
private DfaStateInfo _createStateInfo(IntListKey sig, List<NfaTransition> transitions) {
//calculate the set of accepts
m_tempResultSet.clear();
DfaStateSignatureCodec.expand(sig, nfastate -> {
RESULT accept = m_nfa.getAccept(nfastate);
if (accept != null) {
m_tempResultSet.add(accept);
}
});
//and get an accept set index for it
RESULT dfaAccept = null;
if (m_tempResultSet.size() > 1) {
dfaAccept = (RESULT) m_ambiguityResolver.apply(m_tempResultSet);
} else if (!m_tempResultSet.isEmpty()) {
dfaAccept = m_tempResultSet.iterator().next();
}
int acceptSetIndex = 0;
if (dfaAccept != null) {
acceptSetIndex = computeIfAbsent(m_acceptSetMap, dfaAccept, keyset -> {
m_acceptSets.add(keyset);
return m_acceptSets.size() - 1;
});
}
return new DfaStateInfo(transitions, acceptSetIndex);
}
}<|fim▁end|> | |
<|file_name|>driver.rs<|end_file_name|><|fim▁begin|>use libc::c_int;
use std::ffi::CString;
use std::ptr::null_mut;
use std::sync::{Once, ONCE_INIT};
use utils::{_string, _last_null_pointer_err};
use raster::Dataset;
use raster::types::GdalType;
use gdal_major_object::MajorObject;
use metadata::Metadata;
use gdal_sys::{self, GDALDriverH, GDALMajorObjectH};
use errors::*;
static START: Once = ONCE_INIT;
pub fn _register_drivers() {
unsafe {
START.call_once(|| {
gdal_sys::GDALAllRegister();
});
}
}
#[allow(missing_copy_implementations)]
pub struct Driver {
c_driver: GDALDriverH,
}
impl Driver {
pub fn get(name: &str) -> Result<Driver> {
_register_drivers();
let c_name = CString::new(name)?;
let c_driver = unsafe { gdal_sys::GDALGetDriverByName(c_name.as_ptr()) };
if c_driver.is_null() {
Err(_last_null_pointer_err("GDALGetDriverByName"))?;
};
Ok(Driver{c_driver})
}
pub unsafe fn _with_c_ptr(c_driver: GDALDriverH) -> Driver {
Driver { c_driver }
}
pub unsafe fn _c_ptr(&self) -> GDALDriverH {
self.c_driver
}
pub fn short_name(&self) -> String {
let rv = unsafe { gdal_sys::GDALGetDriverShortName(self.c_driver) };
_string(rv)
}
pub fn long_name(&self) -> String {
let rv = unsafe { gdal_sys::GDALGetDriverLongName(self.c_driver) };
_string(rv)
}
pub fn create(
&self,
filename: &str,
size_x: isize,
size_y: isize,
bands: isize
) -> Result<Dataset> {
self.create_with_band_type::<u8>(
filename,
size_x,
size_y,
bands,
)
}
pub fn create_with_band_type<T: GdalType>(
&self,
filename: &str,<|fim▁hole|> ) -> Result<Dataset> {
let c_filename = CString::new(filename)?;
let c_dataset = unsafe { gdal_sys::GDALCreate(
self.c_driver,
c_filename.as_ptr(),
size_x as c_int,
size_y as c_int,
bands as c_int,
T::gdal_type(),
null_mut()
) };
if c_dataset.is_null() {
Err(_last_null_pointer_err("GDALCreate"))?;
};
Ok(unsafe { Dataset::_with_c_ptr(c_dataset) })
}
}
impl MajorObject for Driver {
unsafe fn gdal_object_ptr(&self) -> GDALMajorObjectH {
self.c_driver
}
}
impl Metadata for Driver {}<|fim▁end|> | size_x: isize,
size_y: isize,
bands: isize, |
<|file_name|>autoComplete.spec.js<|end_file_name|><|fim▁begin|>describe('autocomplete', function () {
beforeEach(function () {
browser.get('/bonita/preview/page/no-app-selected/autocomplete/');
});
describe('simple list', function() {
var input, p;
beforeEach(function() {
input = $('.test-simple input');
p = $('.test-simple p');
});
it('should allow to pick a suggestion dropdownlist and update the value', function() {
input.sendKeys('n');
var values = $$('.dropdown-menu a');
expect(values.count()).toBe(2);<|fim▁hole|> expect(p.getText()).toContain('London');
});
});
describe('Object list', function() {
var input, p;
beforeEach(function() {
input = $('.test-object input');
p = $('.test-object p');
});
it('should display the correct value', function() {
expect(p.getText()).toContain('{ "name": "Paul" }');
expect(input.getAttribute('value')).toContain('Paul');
});
it('should display the correct suggestions', function() {
input.clear().sendKeys('a');
var values = $$('.dropdown-menu a');
var labels = values.map(function(item) {
return item.getText();
});
expect(values.count()).toBe(3);
expect(labels).toEqual(['Paul', 'Hokusai', 'Pablo']);
});
it('should update the value when select a suggestion', function() {
input.clear().sendKeys('a');
var values = $$('.dropdown-menu a');
values.get(1).click();
expect(p.getText()).toContain('Hokusai');
});
});
const labels = () => {
return $$('.dropdown-menu a')
.map(function (item) {
return item.getText();
});
};
describe('async', () => {
// see https://bonitasoft.atlassian.net/browse/BS-16696
it('should display the right suggestions', () => {
const input = $('.test-async input');
input.clear().sendKeys('walt');
expect(labels()).toEqual([ 'walter.bates' ]);
input.sendKeys(protractor.Key.BACK_SPACE);
expect(labels()).toEqual([ 'walter.bates', 'thomas.wallis' ]);
});
it('should return the returned key of selection', () => {
const input = $('.test-async-with-returnedKey input');
input.clear().sendKeys('walter');
var values = $$('.dropdown-menu a');
values.get(0).click();
var p = $('.test-async-with-returnedKey p');
expect(p.getText()).toContain('4');
});
it('should return the full selected object if there is no returned key', () => {
const input = $('.test-async-without-returnedKey input');
input.clear().sendKeys('walter');
var values = $$('.dropdown-menu a');
values.get(0).click();
var p = $('.test-async-without-returnedKey p');
expect(p.getText()).toContain('walter.bates');
expect(p.getText()).toContain('4');
});
});
});<|fim▁end|> |
values.get(0).click(); |
<|file_name|>c-style-enum.rs<|end_file_name|><|fim▁begin|>// ignore-aarch64
// ignore-gdb // Test temporarily ignored due to debuginfo tests being disabled, see PR 47155
// min-lldb-version: 310
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdbg-command:print 'c_style_enum::SINGLE_VARIANT'
// gdbr-command:print c_style_enum::SINGLE_VARIANT
// gdbg-check:$1 = TheOnlyVariant
// gdbr-check:$1 = c_style_enum::SingleVariant::TheOnlyVariant
// gdbg-command:print 'c_style_enum::AUTO_ONE'
// gdbr-command:print c_style_enum::AUTO_ONE
// gdbg-check:$2 = One
// gdbr-check:$2 = c_style_enum::AutoDiscriminant::One
// gdbg-command:print 'c_style_enum::AUTO_TWO'
// gdbr-command:print c_style_enum::AUTO_TWO
// gdbg-check:$3 = One
// gdbr-check:$3 = c_style_enum::AutoDiscriminant::One
// gdbg-command:print 'c_style_enum::AUTO_THREE'
// gdbr-command:print c_style_enum::AUTO_THREE
// gdbg-check:$4 = One
// gdbr-check:$4 = c_style_enum::AutoDiscriminant::One
// gdbg-command:print 'c_style_enum::MANUAL_ONE'
// gdbr-command:print c_style_enum::MANUAL_ONE
// gdbg-check:$5 = OneHundred
// gdbr-check:$5 = c_style_enum::ManualDiscriminant::OneHundred
// gdbg-command:print 'c_style_enum::MANUAL_TWO'
// gdbr-command:print c_style_enum::MANUAL_TWO
// gdbg-check:$6 = OneHundred
// gdbr-check:$6 = c_style_enum::ManualDiscriminant::OneHundred
// gdbg-command:print 'c_style_enum::MANUAL_THREE'
// gdbr-command:print c_style_enum::MANUAL_THREE
// gdbg-check:$7 = OneHundred
// gdbr-check:$7 = c_style_enum::ManualDiscriminant::OneHundred
// gdb-command:run
// gdb-command:print auto_one
// gdbg-check:$8 = One
// gdbr-check:$8 = c_style_enum::AutoDiscriminant::One
// gdb-command:print auto_two
// gdbg-check:$9 = Two
// gdbr-check:$9 = c_style_enum::AutoDiscriminant::Two
// gdb-command:print auto_three
// gdbg-check:$10 = Three
// gdbr-check:$10 = c_style_enum::AutoDiscriminant::Three
// gdb-command:print manual_one_hundred
// gdbg-check:$11 = OneHundred
// gdbr-check:$11 = c_style_enum::ManualDiscriminant::OneHundred
// gdb-command:print manual_one_thousand
// gdbg-check:$12 = OneThousand
// gdbr-check:$12 = c_style_enum::ManualDiscriminant::OneThousand
// gdb-command:print manual_one_million
// gdbg-check:$13 = OneMillion
// gdbr-check:$13 = c_style_enum::ManualDiscriminant::OneMillion
// gdb-command:print single_variant
// gdbg-check:$14 = TheOnlyVariant
// gdbr-check:$14 = c_style_enum::SingleVariant::TheOnlyVariant
// gdbg-command:print 'c_style_enum::AUTO_TWO'
// gdbr-command:print AUTO_TWO
// gdbg-check:$15 = Two
// gdbr-check:$15 = c_style_enum::AutoDiscriminant::Two
// gdbg-command:print 'c_style_enum::AUTO_THREE'
// gdbr-command:print AUTO_THREE
// gdbg-check:$16 = Three
// gdbr-check:$16 = c_style_enum::AutoDiscriminant::Three
// gdbg-command:print 'c_style_enum::MANUAL_TWO'
// gdbr-command:print MANUAL_TWO
// gdbg-check:$17 = OneThousand
// gdbr-check:$17 = c_style_enum::ManualDiscriminant::OneThousand
// gdbg-command:print 'c_style_enum::MANUAL_THREE'
// gdbr-command:print MANUAL_THREE
// gdbg-check:$18 = OneMillion
// gdbr-check:$18 = c_style_enum::ManualDiscriminant::OneMillion
// === LLDB TESTS ==================================================================================
// lldb-command:run
// lldb-command:print auto_one
// lldbg-check:[...]$0 = One
// lldbr-check:(c_style_enum::AutoDiscriminant) auto_one = c_style_enum::AutoDiscriminant::One
// lldb-command:print auto_two
// lldbg-check:[...]$1 = Two
// lldbr-check:(c_style_enum::AutoDiscriminant) auto_two = c_style_enum::AutoDiscriminant::Two
// lldb-command:print auto_three
// lldbg-check:[...]$2 = Three
// lldbr-check:(c_style_enum::AutoDiscriminant) auto_three = c_style_enum::AutoDiscriminant::Three
// lldb-command:print manual_one_hundred
// lldbg-check:[...]$3 = OneHundred
// lldbr-check:(c_style_enum::ManualDiscriminant) manual_one_hundred = c_style_enum::ManualDiscriminant::OneHundred
// lldb-command:print manual_one_thousand
// lldbg-check:[...]$4 = OneThousand
// lldbr-check:(c_style_enum::ManualDiscriminant) manual_one_thousand = c_style_enum::ManualDiscriminant::OneThousand
// lldb-command:print manual_one_million
// lldbg-check:[...]$5 = OneMillion
// lldbr-check:(c_style_enum::ManualDiscriminant) manual_one_million = c_style_enum::ManualDiscriminant::OneMillion
// lldb-command:print single_variant
// lldbg-check:[...]$6 = TheOnlyVariant
// lldbr-check:(c_style_enum::SingleVariant) single_variant = c_style_enum::SingleVariant::TheOnlyVariant
#![allow(unused_variables)]
#![allow(dead_code)]
#![feature(omit_gdb_pretty_printer_section)]
#![omit_gdb_pretty_printer_section]
use self::AutoDiscriminant::{One, Two, Three};
use self::ManualDiscriminant::{OneHundred, OneThousand, OneMillion};
use self::SingleVariant::TheOnlyVariant;
#[derive(Copy, Clone)]
enum AutoDiscriminant {
One,
Two,
Three
}
#[derive(Copy, Clone)]
enum ManualDiscriminant {
OneHundred = 100,
OneThousand = 1000,
OneMillion = 1000000
}
#[derive(Copy, Clone)]
#[repr(u8)]
enum SingleVariant {
TheOnlyVariant
}
static SINGLE_VARIANT: SingleVariant = TheOnlyVariant;
static mut AUTO_ONE: AutoDiscriminant = One;
static mut AUTO_TWO: AutoDiscriminant = One;
static mut AUTO_THREE: AutoDiscriminant = One;
static mut MANUAL_ONE: ManualDiscriminant = OneHundred;
static mut MANUAL_TWO: ManualDiscriminant = OneHundred;
static mut MANUAL_THREE: ManualDiscriminant = OneHundred;
fn main() {
let auto_one = One;
let auto_two = Two;
let auto_three = Three;
let manual_one_hundred = OneHundred;
let manual_one_thousand = OneThousand;
let manual_one_million = OneMillion;
let single_variant = TheOnlyVariant;
unsafe {
AUTO_TWO = Two;
AUTO_THREE = Three;
MANUAL_TWO = OneThousand;
MANUAL_THREE = OneMillion;
};
zzz(); // #break
<|fim▁hole|> let a = &SINGLE_VARIANT;
let a = unsafe { AUTO_ONE };
let a = unsafe { MANUAL_ONE };
}
fn zzz() { () }<|fim▁end|> | // Borrow to avoid an eager load of the constant value in the static. |
<|file_name|>thread.rs<|end_file_name|><|fim▁begin|>use alloc::boxed::Box;
use core::mem;
use system::syscall::{sys_clone, sys_exit, sys_yield, sys_nanosleep, sys_waitpid, CLONE_VM, CLONE_FS, CLONE_FILES,
TimeSpec};
use time::Duration;
/// An owned permission to join on a thread (block on its termination).
///
/// A `JoinHandle` *detaches* the child thread when it is dropped.
///
/// Due to platform restrictions, it is not possible to `Clone` this
/// handle: the ability to join a child thread is a uniquely-owned
/// permission.
// TODO: Mutex the result
pub struct JoinHandle<T> {
pid: usize,
result_ptr: *mut Option<T>,
}
impl<T> JoinHandle<T> {
/// Waits for the associated thread to finish.
pub fn join(self) -> Option<T> where T: ::core::fmt::Debug {
let mut status = 0;
match sys_waitpid(self.pid, &mut status, 0) {
Ok(_) => unsafe { *Box::from_raw(self.result_ptr) },
Err(_) => None
}
}
}
/// Sleep for a duration
pub fn sleep(duration: Duration) {
let req = TimeSpec {
tv_sec: duration.secs,
tv_nsec: duration.nanos,
};
let mut rem = TimeSpec {
tv_sec: 0,
tv_nsec: 0,
};
let _ = sys_nanosleep(&req, &mut rem);
}
/// Sleep for a number of milliseconds
pub fn sleep_ms(ms: u32) {
let secs = ms as i64 / 1000;
let nanos = (ms % 1000) as i32 * 1000000;
sleep(Duration::new(secs, nanos))
}
/// Spawns a new thread, returning a `JoinHandle` for it.
///
/// The join handle will implicitly *detach* the child thread upon being
/// dropped. In this case, the child thread may outlive the parent (unless
/// the parent thread is the main thread; the whole process is terminated when
/// the main thread finishes.) Additionally, the join handle provides a `join`
/// method that can be used to join the child thread. If the child thread
/// panics, `join` will return an `Err` containing the argument given to
/// `panic`.
///
/// # Panics
///
/// Panics if the OS fails to create a thread; use `Builder::spawn`
/// to recover from such errors.
// TODO: Catch panic
pub fn spawn<F, T>(f: F) -> JoinHandle<T>
where F: FnOnce() -> T,
F: Send + 'static,
T: Send + 'static
{
let result_ptr: *mut Option<T> = Box::into_raw(box None);
//This must only be used by the child
let boxed_f = Box::new(f);
match unsafe { sys_clone(CLONE_VM | CLONE_FS | CLONE_FILES).unwrap() } {
0 => {
unsafe { *result_ptr = Some(boxed_f()) };
loop {
let _ = sys_exit(0);<|fim▁hole|> },
pid => {
//Forget so that the parent will not drop while the child is using
mem::forget(boxed_f);
JoinHandle {
pid: pid,
result_ptr: result_ptr
}
}
}
}
pub fn yield_now() {
let _ = sys_yield();
}<|fim▁end|> | } |
<|file_name|>getAll.js<|end_file_name|><|fim▁begin|>module.exports = (req, res, next) => {
const _registration = req.requestParams.registration
const match = {
_registration: _registration
}
return global.models.getAll(
global.db.registrations.RegistrationDebaters,<|fim▁hole|> res
)
}<|fim▁end|> | match,
global.utils.populate.registrationDebaters, |
<|file_name|>aes_ctr_hmac_test.rs<|end_file_name|><|fim▁begin|>// Copyright 2020 The Tink-Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
use tink_streaming_aead::subtle;
#[test]
fn test_aes_ctr_hmac_encrypt_decrypt() {
struct TestCase {
name: &'static str,
key_size_in_bytes: usize,
tag_size_in_bytes: usize,
segment_size: usize,
first_segment_offset: usize,
plaintext_size: usize,
chunk_size: usize,
}
let test_cases = vec![
TestCase {
name: "small-1",
key_size_in_bytes: 16,
tag_size_in_bytes: 12,
segment_size: 256,
first_segment_offset: 0,
plaintext_size: 20,
chunk_size: 64,
},
TestCase {
name: "small-2",
key_size_in_bytes: 16,
tag_size_in_bytes: 12,
segment_size: 512,
first_segment_offset: 0,
plaintext_size: 400,
chunk_size: 64,
},
TestCase {
name: "small-offset-1",
key_size_in_bytes: 16,
tag_size_in_bytes: 12,
segment_size: 256,
first_segment_offset: 8,
plaintext_size: 20,
chunk_size: 64,
},
TestCase {
name: "small-offset-2",
key_size_in_bytes: 16,
tag_size_in_bytes: 12,
segment_size: 512,
first_segment_offset: 8,
plaintext_size: 400,
chunk_size: 64,
},
TestCase {
name: "empty-1",
key_size_in_bytes: 16,
tag_size_in_bytes: 12,
segment_size: 256,
first_segment_offset: 0,
plaintext_size: 0,
chunk_size: 128,
},
TestCase {
name: "empty-2",
key_size_in_bytes: 16,
tag_size_in_bytes: 12,
segment_size: 256,
first_segment_offset: 8,
plaintext_size: 0,<|fim▁hole|> },
TestCase {
name: "medium-1",
key_size_in_bytes: 16,
tag_size_in_bytes: 12,
segment_size: 256,
first_segment_offset: 0,
plaintext_size: 1024,
chunk_size: 128,
},
TestCase {
name: "medium-2",
key_size_in_bytes: 16,
tag_size_in_bytes: 12,
segment_size: 512,
first_segment_offset: 0,
plaintext_size: 3086,
chunk_size: 128,
},
TestCase {
name: "medium-3",
key_size_in_bytes: 32,
tag_size_in_bytes: 12,
segment_size: 1024,
first_segment_offset: 0,
plaintext_size: 12345,
chunk_size: 128,
},
TestCase {
name: "large-chunks-1",
key_size_in_bytes: 16,
tag_size_in_bytes: 12,
segment_size: 256,
first_segment_offset: 0,
plaintext_size: 1024,
chunk_size: 4096,
},
TestCase {
name: "large-chunks-2",
key_size_in_bytes: 16,
tag_size_in_bytes: 12,
segment_size: 512,
first_segment_offset: 0,
plaintext_size: 5086,
chunk_size: 4096,
},
TestCase {
name: "large-chunks-3",
key_size_in_bytes: 32,
tag_size_in_bytes: 12,
segment_size: 1024,
first_segment_offset: 0,
plaintext_size: 12345,
chunk_size: 5000,
},
TestCase {
name: "medium-offset-1",
key_size_in_bytes: 16,
tag_size_in_bytes: 12,
segment_size: 256,
first_segment_offset: 8,
plaintext_size: 1024,
chunk_size: 64,
},
TestCase {
name: "medium-offset-2",
key_size_in_bytes: 16,
tag_size_in_bytes: 12,
segment_size: 512,
first_segment_offset: 20,
plaintext_size: 3086,
chunk_size: 256,
},
TestCase {
name: "medium-offset-3",
key_size_in_bytes: 32,
tag_size_in_bytes: 12,
segment_size: 1024,
first_segment_offset: 10,
plaintext_size: 12345,
chunk_size: 5000,
},
TestCase {
name: "last-segment-full-1",
key_size_in_bytes: 16,
tag_size_in_bytes: 12,
segment_size: 256,
first_segment_offset: 0,
plaintext_size: 216,
chunk_size: 64,
},
TestCase {
name: "last-segment-full-2",
key_size_in_bytes: 16,
tag_size_in_bytes: 12,
segment_size: 256,
first_segment_offset: 16,
plaintext_size: 200,
chunk_size: 256,
},
TestCase {
name: "last-segment-full-3",
key_size_in_bytes: 16,
tag_size_in_bytes: 12,
segment_size: 256,
first_segment_offset: 16,
plaintext_size: 440,
chunk_size: 1024,
},
TestCase {
name: "single-byte-1",
key_size_in_bytes: 16,
tag_size_in_bytes: 12,
segment_size: 256,
first_segment_offset: 0,
plaintext_size: 1024,
chunk_size: 1,
},
TestCase {
name: "single-byte-2",
key_size_in_bytes: 32,
tag_size_in_bytes: 12,
segment_size: 512,
first_segment_offset: 0,
plaintext_size: 5086,
chunk_size: 1,
},
];
for tc in test_cases {
let cipher = subtle::AesCtrHmac::new(
super::IKM,
tink_proto::HashType::Sha256,
tc.key_size_in_bytes,
tink_proto::HashType::Sha256,
tc.tag_size_in_bytes,
tc.segment_size,
tc.first_segment_offset,
)
.unwrap_or_else(|e| panic!("{}: cannot create cipher: {:?}", tc.name, e));
let (pt, ct) = super::encrypt(&cipher, super::AAD, tc.plaintext_size)
.unwrap_or_else(|e| panic!("{}: failure during encryption: {:?}", tc.name, e));
assert!(
super::decrypt(&cipher, super::AAD, &pt, &ct, tc.chunk_size).is_ok(),
"{}: failure during decryption",
tc.name
);
}
}
#[test]
fn test_aes_ctr_hmac_modified_ciphertext() {
let ikm =
hex::decode("000102030405060708090a0b0c0d0e0f00112233445566778899aabbccddeeff").unwrap();
let aad = hex::decode("aabbccddeeff").unwrap();
let key_size_in_bytes = 16;
let tag_size_in_bytes = 12;
let segment_size = 256;
let first_segment_offset = 8;
let plaintext_size = 1024;
let chunk_size = 128;
let cipher = subtle::AesCtrHmac::new(
&ikm,
tink_proto::HashType::Sha256,
key_size_in_bytes,
tink_proto::HashType::Sha256,
tag_size_in_bytes,
segment_size,
first_segment_offset,
)
.expect("Cannot create a cipher");
let (pt, ct) = super::encrypt(&cipher, &aad, plaintext_size).unwrap();
// truncate ciphertext
for i in (0..ct.len()).step_by(8) {
assert!(
super::decrypt(&cipher, &aad, &pt, &ct[..i], chunk_size).is_err(),
"expected error"
);
}
// append to ciphertext
let sizes = vec![1, segment_size - ct.len() % segment_size, segment_size];
for size in sizes {
let mut ct2 = ct.clone();
ct2.extend_from_slice(&vec![0; size]);
assert!(
super::decrypt(&cipher, &aad, &pt, &ct2, chunk_size).is_err(),
"expected error"
);
}
// flip bits
for i in 0..ct.len() {
let mut ct2 = ct.clone();
ct2[i] ^= 0x01;
assert!(
super::decrypt(&cipher, &aad, &pt, &ct2, chunk_size).is_err(),
"expected error"
);
}
// delete segments
for i in 0..ct.len() / segment_size + 1 {
let (start, mut end) = super::segment_pos(
segment_size,
first_segment_offset,
cipher.header_length(),
i,
);
if start > ct.len() {
break;
}
if end > ct.len() {
end = ct.len()
}
let mut ct2 = ct[..start].to_vec();
ct2.extend_from_slice(&ct[end..]);
assert!(
super::decrypt(&cipher, &aad, &pt, &ct2, chunk_size).is_err(),
"expected error"
);
}
// duplicate segments
for i in 0..ct.len() / segment_size + 1 {
let (start, mut end) = super::segment_pos(
segment_size,
first_segment_offset,
cipher.header_length(),
i,
);
if start > ct.len() {
break;
}
if end > ct.len() {
end = ct.len()
}
let mut ct2 = (&ct[..end]).to_vec();
ct2.extend_from_slice(&ct[start..]);
assert!(
super::decrypt(&cipher, &aad, &pt, &ct2, chunk_size).is_err(),
"expected error"
);
}
// modify aad
for i in 0..aad.len() {
let mut aad2 = aad.clone();
aad2[i] ^= 0x01;
assert!(
super::decrypt(&cipher, &aad2, &pt, &ct, chunk_size).is_err(),
"expected error"
);
}
}<|fim▁end|> | chunk_size: 128, |
<|file_name|>screenshot.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Converts A bunch of mac Screenshots to 24hour format
def to_24(string):
hour, minute, trail = string.split('.')
sec, period = trail.split(' ')
hour = int(hour)
minute = int(minute)
sec = int(sec)
is_pm = period.lower() == "pm"
if hour == 12:
if not is_pm:
hour += 12
elif is_pm:
hour += 12
return "%s.%s.%s" % (
str(hour).zfill(2),
str(minute).zfill(2),
str(sec).zfill(2),
)
if __name__ == '__main__':
from folder_list import FolderList
root = FolderList("/Users/Saevon/Pictures/Screenshots/Witch's House/")
for file in root:
# Check if the file's been renamed already
if "PM" not in file.name or "AM" not in file.name:
continue
# Convert to the new format
prefix, time = file.name.split(' at ')
suffix = to_24(time)<|fim▁hole|> new_name = '%s at %s' % (prefix, suffix)
file.rename(new_name)
# print to_24("12.05.20 PM")
# print to_24("12.05.20 AM")
# print to_24("1.05.20 AM")
# print to_24("1.05.20 PM")<|fim▁end|> | |
<|file_name|>Bow.java<|end_file_name|><|fim▁begin|>/**
* The MIT License
* Copyright (c) 2014-2016 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.<|fim▁hole|> *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.factorykit;
public class Bow implements Weapon {
@Override
public String toString() {
return "Bow";
}
}<|fim▁end|> | |
<|file_name|>test_api.py<|end_file_name|><|fim▁begin|>from __future__ import unicode_literals
from unittest import TestCase
from shutil import rmtree
from tempfile import mkdtemp
from os import makedirs
from os.path import join, exists, dirname
from awsfabrictasks.s3.api import dirlist_absfilenames
from awsfabrictasks.s3.api import localpath_to_s3path<|fim▁hole|>def makefile(tempdir, path, contents):
path = join(tempdir, *path.split('/'))
if not exists(dirname(path)):
makedirs(dirname(path))
open(path, 'wb').write(contents.encode('utf-8'))
return path
class TestDirlistAbsfilenames(TestCase):
def setUp(self):
self.tempdir = mkdtemp()
files = (('hello/world.txt', 'Hello world'),
('test.py', 'print "test"'),
('hello/cruel/world.txt', 'Cruel?'))
self.paths = set()
for path, contents in files:
realpath = makefile(self.tempdir, path, contents)
self.paths.add(realpath)
def tearDown(self):
rmtree(self.tempdir)
def test_dirlist_absfilenames(self):
result = dirlist_absfilenames(self.tempdir)
self.assertEquals(result, self.paths)
class TestLocalpathToS3path(TestCase):
def setUp(self):
self.tempdir = mkdtemp()
makefile(self.tempdir, 'hello/world.txt', '')
def tearDown(self):
rmtree(self.tempdir)
def test_localpath_to_s3path(self):
s3path = localpath_to_s3path(self.tempdir, join(self.tempdir, 'hello/world.txt'), 'my/test')
self.assertEquals(s3path, 'my/test/hello/world.txt')
def test_s3path_to_localpath(self):
localpath = s3path_to_localpath('mydir/', 'mydir/hello/world.txt', join(self.tempdir, 'my', 'test'))
self.assertEquals(localpath, join(self.tempdir, 'my', 'test', 'hello', 'world.txt'))<|fim▁end|> | from awsfabrictasks.s3.api import s3path_to_localpath
|
<|file_name|>imagedata.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::ImageDataBinding;
use crate::dom::bindings::codegen::Bindings::ImageDataBinding::ImageDataMethods;
use crate::dom::bindings::error::{Error, Fallible};
use crate::dom::bindings::reflector::{reflect_dom_object, Reflector};
use crate::dom::bindings::root::DomRoot;
use crate::dom::globalscope::GlobalScope;
use dom_struct::dom_struct;
use euclid::{Rect, Size2D};
use ipc_channel::ipc::IpcSharedMemory;
use js::jsapi::{Heap, JSContext, JSObject};
use js::rust::Runtime;
use js::typedarray::{CreateWith, Uint8ClampedArray};
use std::borrow::Cow;
use std::default::Default;
use std::ptr;
use std::ptr::NonNull;
use std::vec::Vec;
#[dom_struct]
pub struct ImageData {
reflector_: Reflector,
width: u32,
height: u32,
data: Heap<*mut JSObject>,
}
impl ImageData {
#[allow(unsafe_code)]
pub fn new(
global: &GlobalScope,
width: u32,
height: u32,
mut data: Option<Vec<u8>>,
) -> Fallible<DomRoot<ImageData>> {
let len = width * height * 4;
unsafe {
let cx = global.get_cx();
rooted!(in (cx) let mut js_object = ptr::null_mut::<JSObject>());
let data = match data {
Some(ref mut d) => {
d.resize(len as usize, 0);
CreateWith::Slice(&d[..])
},
None => CreateWith::Length(len),
};
Uint8ClampedArray::create(cx, data, js_object.handle_mut()).unwrap();
Self::new_with_jsobject(global, width, Some(height), Some(js_object.get()))
}
}
#[allow(unsafe_code)]
unsafe fn new_with_jsobject(
global: &GlobalScope,
width: u32,
mut opt_height: Option<u32>,
opt_jsobject: Option<*mut JSObject>,
) -> Fallible<DomRoot<ImageData>> {
assert!(opt_jsobject.is_some() || opt_height.is_some());
if width == 0 {
return Err(Error::IndexSize);
}
// checking jsobject type and verifying (height * width * 4 == jsobject.byte_len())
if let Some(jsobject) = opt_jsobject {
let cx = global.get_cx();
typedarray!(in(cx) let array_res: Uint8ClampedArray = jsobject);
let array = array_res.map_err(|_| {
Error::Type("Argument to Image data is not an Uint8ClampedArray".to_owned())
})?;
let byte_len = array.as_slice().len() as u32;
if byte_len % 4 != 0 {
return Err(Error::InvalidState);
}
let len = byte_len / 4;
if width == 0 || len % width != 0 {
return Err(Error::IndexSize);
}
let height = len / width;
if opt_height.map_or(false, |x| height != x) {
return Err(Error::IndexSize);
} else {
opt_height = Some(height);
}
}
let height = opt_height.unwrap();
if height == 0 {
return Err(Error::IndexSize);
}
let imagedata = Box::new(ImageData {
reflector_: Reflector::new(),
width: width,
height: height,
data: Heap::default(),
});
if let Some(jsobject) = opt_jsobject {
(*imagedata).data.set(jsobject);
} else {
let len = width * height * 4;
let cx = global.get_cx();
rooted!(in (cx) let mut array = ptr::null_mut::<JSObject>());<|fim▁hole|> Ok(reflect_dom_object(
imagedata,
global,
ImageDataBinding::Wrap,
))
}
// https://html.spec.whatwg.org/multipage/#pixel-manipulation:dom-imagedata-3
#[allow(unsafe_code)]
pub fn Constructor(global: &GlobalScope, width: u32, height: u32) -> Fallible<DomRoot<Self>> {
unsafe { Self::new_with_jsobject(global, width, Some(height), None) }
}
// https://html.spec.whatwg.org/multipage/#pixel-manipulation:dom-imagedata-4
#[allow(unsafe_code)]
#[allow(unused_variables)]
pub unsafe fn Constructor_(
cx: *mut JSContext,
global: &GlobalScope,
jsobject: *mut JSObject,
width: u32,
opt_height: Option<u32>,
) -> Fallible<DomRoot<Self>> {
Self::new_with_jsobject(global, width, opt_height, Some(jsobject))
}
/// Nothing must change the array on the JS side while the slice is live.
#[allow(unsafe_code)]
pub unsafe fn as_slice(&self) -> &[u8] {
assert!(!self.data.get().is_null());
let cx = Runtime::get();
assert!(!cx.is_null());
typedarray!(in(cx) let array: Uint8ClampedArray = self.data.get());
let array = array.as_ref().unwrap();
// NOTE(nox): This is just as unsafe as `as_slice` itself even though we
// are extending the lifetime of the slice, because the data in
// this ImageData instance will never change. The method is thus unsafe
// because the array may be manipulated from JS while the reference
// is live.
let ptr = array.as_slice() as *const _;
&*ptr
}
#[allow(unsafe_code)]
pub fn to_shared_memory(&self) -> IpcSharedMemory {
IpcSharedMemory::from_bytes(unsafe { self.as_slice() })
}
#[allow(unsafe_code)]
pub unsafe fn get_rect(&self, rect: Rect<u32>) -> Cow<[u8]> {
pixels::rgba8_get_rect(self.as_slice(), self.get_size(), rect)
}
pub fn get_size(&self) -> Size2D<u32> {
Size2D::new(self.Width(), self.Height())
}
}
impl ImageDataMethods for ImageData {
// https://html.spec.whatwg.org/multipage/#dom-imagedata-width
fn Width(&self) -> u32 {
self.width
}
// https://html.spec.whatwg.org/multipage/#dom-imagedata-height
fn Height(&self) -> u32 {
self.height
}
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-imagedata-data
unsafe fn Data(&self, _: *mut JSContext) -> NonNull<JSObject> {
NonNull::new(self.data.get()).expect("got a null pointer")
}
}<|fim▁end|> | Uint8ClampedArray::create(cx, CreateWith::Length(len), array.handle_mut()).unwrap();
(*imagedata).data.set(array.get());
}
|
<|file_name|>Histogram.py<|end_file_name|><|fim▁begin|>import copy
class Histogram( object ):
'''Histogram + a few things.
This class does not inherit from a ROOT class as we could want to use it
with a TH1D, TH1F, and even a 2D at some point.
Histogram contains the original ROOT histogram, obj, and a weighted version,
weigthed, originally set equal to obj (weight == 1).
- layer : can be used to order histograms
- stack : to decide whether the histogram
should be stacked or not (see the Stack class for more information)
- name : user defined histogram. Useful when manipulating several histograms with
the same GetName(), coming from different TDirectories.
'''
def __init__(self, name, obj, layer=0., legendLine=None, stack=True):
# name is a user defined name
self.name = name
self.realName = name # can be different if an alias is set
if legendLine is None:
self.legendLine = name
else:
self.legendLine = legendLine
self.obj = obj
# self.weighted = copy.deepcopy(self.obj)
self.layer = layer
self.stack = stack
self.on = True
self.style = None
# after construction, weighted histogram = base histogram
self.SetWeight(1)
def Clone(self, newName):
newHist = copy.deepcopy(self)
newHist.name = newName
newHist.legendLine = newName
return newHist
def __str__(self):
fmt = '{self.name:<10} / {hname:<50},\t Layer ={self.layer:8.1f}, w = {weighted:8.1f}, u = {unweighted:8.1f}'
tmp = fmt.format(self=self,
hname = self.realName,
weighted = self.Yield(weighted=True),
unweighted = self.Yield(weighted=False) )
return tmp
def Yield(self, weighted=True):
'''Returns the weighted number of entries in the histogram
(under and overflow not counted).
Use weighted=False if you want the unweighted number of entries'''
hist = self.weighted
if not weighted:
hist = self.obj
return hist.Integral( 0, hist.GetNbinsX()+1)
def GetBinning(self):
'''return nbins, xmin, xmax'''
return self.obj.GetNbinsX(), \
self.obj.GetXaxis().GetXmin(), \
self.obj.GetXaxis().GetXmax()
def Rebin(self, factor):
'''Rebins by factor'''
self.obj.Rebin( factor )
self.weighted.Rebin(factor)
def Divide(self, other):
self.obj.Divide( other.obj)
self.weighted.Divide( other.weighted )
def NormalizeToBinWidth(self):
'''Divides each bin content and error by the bin size'''
for i in range (1,self.obj.GetNbinsX()+1) :
self.obj.SetBinContent(i, self.obj.GetBinContent(i) / self.obj.GetBinWidth(i))
self.obj.SetBinError (i, self.obj.GetBinError(i) / self.obj.GetBinWidth(i))
for i in range (1,self.weighted.GetNbinsX()+1) :
self.weighted.SetBinContent(i, self.weighted.GetBinContent(i) / self.weighted.GetBinWidth(i))
self.weighted.SetBinError (i, self.weighted.GetBinError(i) / self.weighted.GetBinWidth(i))
def SetWeight(self, weight):
'''Set the weight and create the weighted histogram.'''
self.weighted = copy.deepcopy(self.obj)
self.weight = weight
self.weighted.Scale(weight)
def Scale(self, scale):
'''Scale the histogram (multiply the weight by scale)'''
self.SetWeight( self.weight * scale )
def SetStyle(self, style):
'''Set the style for the original and weighted histograms.'''
if style is None:
return
style.formatHisto( self.obj )
style.formatHisto( self.weighted )
self.style = style
def AddEntry(self, legend, legendLine=None):
'''By default the legend entry is set to self.legendLine of the histogram.'''
if legendLine is None:
legendLine = self.legendLine
if legendLine is None:
legendLine = self.name
opt = 'f'
if not self.stack:
opt = 'p'
legend.AddEntry(self.obj, legendLine, opt)
def Draw(self, opt='hist', weighted=True):
'''Draw the weighted (or original) histogram.'''
if weighted is True:
self.weighted.Draw(opt)
else:
self.obj.Draw(opt)
def GetXaxis(self, opt='', weighted=True):
'''All these functions could be written in a clever and compact way'''
if weighted is True:
return self.weighted.GetXaxis()
else:
return self.obj.GetXaxis()
def GetYaxis(self, opt='', weighted=True):
'''All these functions could be written in a clever and compact way'''
if weighted is True:
return self.weighted.GetYaxis()
else:
return self.obj.GetYaxis()
def GetMaximum(self, opt='', weighted=True):
'''All these functions could be written in a clever and compact way'''
if weighted is True:
return self.weighted.GetMaximum()
else:
return self.obj.GetMaximum()
def Add(self, other, coeff=1):
'''Add another histogram.
Provide the optional coeff argument for the coefficient factor (e.g. -1 to subtract)
'''
self.obj.Add( other.obj, coeff )
self.weighted.Add( other.weighted, coeff )
integral = self.obj.Integral(0, self.obj.GetNbinsX())
if integral > 0.:
self.weight = self.weighted.Integral(0, self.weighted.GetNbinsX()+1)/integral
return self
def Integral(self, weighted=True, xmin=None, xmax=None ):
'''
Returns the weighted or unweighted integral of this histogram.
If xmin and xmax are None, underflows and overflows are included.
'''
if type( weighted ) is not bool:
raise ValueError('weighted should be a boolean')
if xmin is not None:
bmin = self.obj.FindFixBin( xmin )
else:
bmin = None
if xmax is not None:
bmax = self.obj.FindFixBin( xmax ) - 1
else:
bmax = None
hist = self.weighted
if weighted is False:
hist = self.obj
if bmin is None and bmax is None:
return hist.Integral(0, hist.GetNbinsX()+1)
elif bmin is not None and bmax is not None:
# import pdb; pdb.set_trace()
if (xmax - xmin) % self.obj.GetBinWidth(1) != 0:
raise ValueError('boundaries should define an integer number of bins. nbins=%d, xmin=%3.3f, xmax=%3.3f' % (self.obj.GetNbinsX(), self.obj.GetXaxis().GetXmin(), self.obj.GetXaxis().GetXmax()) )
return hist.Integral(bmin, bmax)
else:
raise ValueError('if specifying one boundary, you must specify the other')
def DrawNormalized(self):
'''Draw a normalized version of this histogram.
The original and weighted histograms stay untouched.'''
self.obj.DrawNormalized()
def Normalize(self):
'''Sets the weight to normalize the weighted histogram to 1.
In other words, the original histogram stays untouched.'''
self.Scale( 1/self.Integral() )
def RemoveNegativeValues(self, hist=None):
# what about errors??
if hist is None:
self.RemoveNegativeValues(self.weighted)
self.RemoveNegativeValues(self.obj)<|fim▁hole|>
def Blind(self, minx, maxx):
whist = self.weighted
uwhist = self.weighted
minbin = whist.FindBin(minx)
maxbin = min(whist.FindBin(maxx), whist.GetNbinsX() + 1)
for bin in range(minbin, maxbin):
whist.SetBinContent(bin,0)
whist.SetBinError(bin,0)
uwhist.SetBinContent(bin,0)
uwhist.SetBinError(bin,0)<|fim▁end|> | else:
for ibin in range(1, hist.GetNbinsX()+1):
if hist.GetBinContent(ibin)<0:
hist.SetBinContent(ibin, 0) |
<|file_name|>bats_test.go<|end_file_name|><|fim▁begin|>package main
import (
"fmt"
"testing"
)
func TestBats(t *testing.T) {<|fim▁hole|> t.Errorf("failed: bats 22 2 2 9 11 is 3, got %d",
r)
}
if r := bats(835, 125, 1, []string{"113"}); r != 5 {
t.Errorf("failed: bats 835 125 1 113 is 5, got %d",
r)
}
if r := bats(47, 5, 0, []string{}); r != 8 {
t.Errorf("failed: bats 475 5 0 is 8, got %d",
r)
}
}
func bats(l, d, n int, s []string) (c int) {
var t int
tx := 6 - d
for i := 6; i <= l-6; i += d {
if i > tx-d {
i = tx
if t == n {
tx = l - 6 + d
} else {
fmt.Sscanf(s[t], "%d", &tx)
t++
}
} else {
c++
}
}
return c
}<|fim▁end|> | if r := bats(22, 2, 2, []string{"9", "11"}); r != 3 { |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf8 -*-
<|fim▁hole|><|fim▁end|> | from decode import decode |
<|file_name|>util.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
from __future__ import with_statement
import glob
import os
import hmac
import hashlib
import shutil
import socket
import subprocess
import struct
from twisted.internet import defer
from twisted.internet.interfaces import IProtocolFactory
from twisted.internet.endpoints import serverFromString
from zope.interface import implementer
try:
import GeoIP as _GeoIP
GeoIP = _GeoIP
except ImportError:
GeoIP = None
city = None
country = None
asn = None
# XXX probably better to depend on and use "six" for py2/3 stuff?
try:
unicode
except NameError:
py3k = True
basestring = str
else:
py3k = False
basestring = basestring
def create_geoip(fname):
# It's more "pythonic" to just wait for the exception,
# but GeoIP prints out "Can't open..." messages for you,
# which isn't desired here
if not os.path.isfile(fname):
raise IOError("Can't find %s" % fname)
if GeoIP is None:
return None
# just letting any errors make it out
return GeoIP.open(fname, GeoIP.GEOIP_STANDARD)
def maybe_create_db(path):
try:
return create_geoip(path)
except IOError:
return None
city, asn, country = list(map(maybe_create_db,
("/usr/share/GeoIP/GeoLiteCity.dat",
"/usr/share/GeoIP/GeoIPASNum.dat",
"/usr/share/GeoIP/GeoIP.dat")))
try:
import ipaddr as _ipaddr
ipaddr = _ipaddr
except ImportError:
ipaddr = None
def is_executable(path):
"""Checks if the given path points to an existing, executable file"""
return os.path.isfile(path) and os.access(path, os.X_OK)
def find_tor_binary(globs=('/usr/sbin/', '/usr/bin/',
'/Applications/TorBrowser_*.app/Contents/MacOS/'),
system_tor=True):
"""
Tries to find the tor executable using the shell first or in in the
paths whose glob-patterns is in the given 'globs'-tuple.
:param globs:
A tuple of shell-style globs of directories to use to find tor
(TODO consider making that globs to actual tor binary?)
:param system_tor:
This controls whether bash is used to seach for 'tor' or
not. If False, we skip that check and use only the 'globs'
tuple.
"""
# Try to find the tor executable using the shell
if system_tor:
try:
proc = subprocess.Popen(
('which tor'),
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
shell=True
)
except OSError:
pass
else:
stdout, _ = proc.communicate()
if proc.poll() == 0 and stdout != '':
return stdout.strip()
# the shell may not provide type and tor is usually not on PATH when using
# the browser-bundle. Look in specific places
for pattern in globs:
for path in glob.glob(pattern):
torbin = os.path.join(path, 'tor')
if is_executable(torbin):
return torbin
return None
def maybe_ip_addr(addr):
"""
Tries to return an IPAddress, otherwise returns a string.
TODO consider explicitly checking for .exit or .onion at the end?
"""
if ipaddr is not None:
try:
return ipaddr.IPAddress(addr)
except ValueError:
pass
return str(addr)
def find_keywords(args, key_filter=lambda x: not x.startswith("$")):
"""
This splits up strings like name=value, foo=bar into a dict. Does NOT deal
with quotes in value (e.g. key="value with space" will not work
By default, note that it takes OUT any key which starts with $ (i.e. a
single dollar sign) since for many use-cases the way Tor encodes nodes
with "$hash=name" looks like a keyword argument (but it isn't). If you
don't want this, override the "key_filter" argument to this method.
:return:
a dict of key->value (both strings) of all name=value type
keywords found in args.
"""
filtered = [x for x in args if '=' in x and key_filter(x.split('=')[0])]
return dict(x.split('=', 1) for x in filtered)
def delete_file_or_tree(*args):
"""
For every path in args, try to delete it as a file or a directory
tree. Ignores deletion errors.
"""
for f in args:
try:
os.unlink(f)
except OSError:
shutil.rmtree(f, ignore_errors=True)
def ip_from_int(ip):
""" Convert long int back to dotted quad string """
return socket.inet_ntoa(struct.pack('>I', ip))
def process_from_address(addr, port, torstate=None):
"""
Determines the PID from the address/port provided by using lsof
and returns it as an int (or None if it couldn't be
determined). In the special case the addr is '(Tor_internal)' then
the PID of the Tor process (as gotten from the torstate object) is
returned (or 0 if unavailable, e.g. a Tor which doesn't implement
'GETINFO process/pid'). In this case if no TorState instance is
given, None is returned.
"""
if addr is None:
return None
if "(tor_internal)" == str(addr).lower():
if torstate is None:
return None
return int(torstate.tor_pid)
proc = subprocess.Popen(['lsof', '-i', '4tcp@%s:%s' % (addr, port)],
stdout=subprocess.PIPE)
(stdout, stderr) = proc.communicate()
lines = stdout.split('\n')
if len(lines) > 1:
return int(lines[1].split()[1])
def hmac_sha256(key, msg):
"""
Adapted from rransom's tor-utils git repository. Returns the
digest (binary) of an HMAC with SHA256 over msg with key.<|fim▁hole|> """
return hmac.new(key, msg, hashlib.sha256).digest()
CRYPTOVARIABLE_EQUALITY_COMPARISON_NONCE = os.urandom(32)
def compare_via_hash(x, y):
"""
Taken from rransom's tor-utils git repository, to compare two
hashes in something resembling constant time (or at least, not
leaking timing info?)
"""
return (hmac_sha256(CRYPTOVARIABLE_EQUALITY_COMPARISON_NONCE, x) ==
hmac_sha256(CRYPTOVARIABLE_EQUALITY_COMPARISON_NONCE, y))
class NetLocation:
"""
Represents the location of an IP address, either city or country
level resolution depending on what GeoIP database was loaded. If
the ASN database is available you get that also.
"""
def __init__(self, ipaddr):
"ipaddr should be a dotted-quad"
self.ip = ipaddr
self.latlng = (None, None)
self.countrycode = None
self.city = None
self.asn = None
if self.ip is None or self.ip == 'unknown':
return
if city:
try:
r = city.record_by_addr(self.ip)
except:
r = None
if r is not None:
self.countrycode = r['country_code']
self.latlng = (r['latitude'], r['longitude'])
try:
self.city = (r['city'], r['region_code'])
except KeyError:
self.city = (r['city'], r['region_name'])
elif country:
self.countrycode = country.country_code_by_addr(ipaddr)
else:
self.countrycode = ''
if asn:
try:
self.asn = asn.org_by_addr(self.ip)
except:
self.asn = None
@implementer(IProtocolFactory)
class NoOpProtocolFactory:
"""
This is an IProtocolFactory that does nothing. Used for testing,
and for :method:`available_tcp_port`
"""
def noop(self, *args, **kw):
pass
buildProtocol = noop
doStart = noop
doStop = noop
@defer.inlineCallbacks
def available_tcp_port(reactor):
"""
Returns a Deferred firing an available TCP port on localhost.
It does so by listening on port 0; then stopListening and fires the
assigned port number.
"""
endpoint = serverFromString(reactor, 'tcp:0:interface=127.0.0.1')
port = yield endpoint.listen(NoOpProtocolFactory())
address = port.getHost()
yield port.stopListening()
defer.returnValue(address.port)<|fim▁end|> | |
<|file_name|>Controller.js<|end_file_name|><|fim▁begin|>(function() {
function Base(props) {
this.id = Ambient.getID();
<|fim▁hole|>
Base.extend = function(methods) {
if (typeof methods === "function") {
methods = methods();
}
methods = (methods || {});
var self = this;
var Controller = function() {
self.apply(this, arguments);
};
Controller.prototype = Object.create(self.prototype);
Controller.prototype.constructor = Controller;
for (var key in methods) {
Controller.prototype[key] = methods[key];
}
Controller.extend = Base.extend.bind(Controller);
return Controller;
};
window.Ambient.Controller = Base;
})();<|fim▁end|> |
$.extend(this, props || {});
}
|
<|file_name|>spectrometer_task.py<|end_file_name|><|fim▁begin|># ===============================================================================
# Copyright 2013 Jake Ross
#
# 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.
# ===============================================================================
# ============= enthought library imports =======================
from __future__ import absolute_import
import time
# ============= standard library imports ========================
from threading import Thread
from pyface.tasks.action.schema import SToolBar
from pyface.tasks.task_layout import TaskLayout, PaneItem, Splitter, VSplitter
from pyface.ui.qt4.tasks.advanced_editor_area_pane import EditorWidget
from traits.api import Any, Instance, on_trait_change
# ============= local library imports ==========================
from pychron.core.ui.gui import invoke_in_main_thread
from pychron.envisage.tasks.editor_task import EditorTask
from pychron.spectrometer.tasks.editor import PeakCenterEditor, ScanEditor, CoincidenceEditor, ScannerEditor
from pychron.spectrometer.tasks.spectrometer_actions import StopScanAction
from pychron.spectrometer.tasks.spectrometer_panes import ControlsPane, \
ReadoutPane, IntensitiesPane, RecordControlsPane, DACScannerPane, MassScannerPane
class SpectrometerTask(EditorTask):
scan_manager = Any
name = 'Spectrometer'
id = 'pychron.spectrometer'
_scan_editor = Instance(ScanEditor)
tool_bars = [SToolBar(StopScanAction(), )]
def info(self, msg, *args, **kw):
super(SpectrometerTask, self).info(msg)
def spy_position_magnet(self, *args, **kw):
self.scan_manager.position_magnet(*args, **kw)
def spy_peak_center(self, name):
peak_kw = dict(confirm_save=False, warn=True,
new_thread=False,
message='spectrometer script peakcenter',
on_end=self._on_peak_center_end)
setup_kw = dict(config_name=name)
return self._peak_center(setup_kw=setup_kw, peak_kw=peak_kw)
def populate_mftable(self):
sm = self.scan_manager
cfg = sm.setup_populate_mftable()
if cfg:
def func():
refiso = cfg.isotope
ion = sm.ion_optics_manager
ion.backup_mftable()
odefl = []
dets = cfg.get_detectors()
self.debug('setting deflections')
for det, defl in dets:
odefl.append((det, sm.spectrometer.get_deflection(det)))
sm.spectrometer.set_deflection(det, defl)
for di in dets:
ion.setup_peak_center(detector=[di.name], isotope=refiso,
config_name=cfg.peak_center_config.active_item.name,
standalone_graph=False,
new=True,
show_label=True, use_configuration_dac=False)
ion.peak_center.update_others = False
name = 'Pop MFTable {}-{}'.format(di.name, refiso)
invoke_in_main_thread(self._open_editor, PeakCenterEditor(model=ion.peak_center,
name=name))
self._on_peak_center_start()
ion.do_peak_center(new_thread=False, save=True, warn=True)
self._on_peak_center_end()
if not ion.peak_center.isAlive():
break
self.debug('unset deflections')
for det, defl in odefl:
sm.spectrometer.set_deflection(det, defl)
fp = cfg.get_finish_position()
self.debug('move to end position={}'.format(fp))
if fp:
iso, det = fp
if iso and det:
ion.position(iso, det)
t = Thread(target=func)
t.start()
def stop_scan(self):
self.debug('stop scan fired')
editor = self.active_editor
self.debug('active editor {}'.format(editor))
if editor:
if isinstance(editor, (ScanEditor, PeakCenterEditor, CoincidenceEditor)):
self.debug('editor stop')
editor.stop()
def do_coincidence(self):
es = [int(e.name.split(' ')[-1])
for e in self.editor_area.editors
if isinstance(e, CoincidenceEditor)]
i = max(es) + 1 if es else 1<|fim▁hole|> man = self.scan_manager.ion_optics_manager
name = 'Coincidence {:02d}'.format(i)
if man.setup_coincidence():
self._open_editor(CoincidenceEditor(model=man.coincidence, name=name))
man.do_coincidence_scan()
def do_peak_center(self):
peak_kw = dict(confirm_save=True, warn=True,
message='manual peakcenter',
on_end=self._on_peak_center_end)
self._peak_center(peak_kw=peak_kw)
def define_peak_center(self):
from pychron.spectrometer.ion_optics.define_peak_center_view import DefinePeakCenterView
man = self.scan_manager.ion_optics_manager
spec = man.spectrometer
dets = spec.detector_names
isos = spec.isotopes
dpc = DefinePeakCenterView(detectors=dets,
isotopes=isos,
detector=dets[0],
isotope=isos[0])
info = dpc.edit_traits()
if info.result:
det = dpc.detector
isotope = dpc.isotope
dac = dpc.dac
self.debug('manually setting mftable to {}:{}:{}'.format(det, isotope, dac))
message = 'manually define peak center {}:{}:{}'.format(det, isotope, dac)
man.spectrometer.magnet.update_field_table(det, isotope, dac, message)
def _on_peak_center_start(self):
self.scan_manager.log_events_enabled = False
self.scan_manager.scan_enabled = False
def _on_peak_center_end(self):
self.scan_manager.log_events_enabled = True
self.scan_manager.scan_enabled = True
def send_configuration(self):
self.scan_manager.spectrometer.send_configuration()
def prepare_destroy(self):
for e in self.editor_area.editors:
if hasattr(e, 'stop'):
e.stop()
self.scan_manager.prepare_destroy()
super(SpectrometerTask, self).prepare_destroy()
# def activated(self):
# self.scan_manager.activate()
# self._scan_factory()
# super(SpectrometerTask, self).activated()
def create_dock_panes(self):
panes = [
ControlsPane(model=self.scan_manager),
RecordControlsPane(model=self.scan_manager),
MassScannerPane(model=self.scan_manager),
DACScannerPane(model=self.scan_manager),
ReadoutPane(model=self.scan_manager),
IntensitiesPane(model=self.scan_manager)]
panes = self._add_canvas_pane(panes)
return panes
# def _active_editor_changed(self, new):
# if not new:
# try:
# self._scan_factory()
# except AttributeError:
# pass
# private
def _peak_center(self, setup_kw=None, peak_kw=None):
if setup_kw is None:
setup_kw = {}
if peak_kw is None:
peak_kw = {}
es = []
for e in self.editor_area.editors:
if isinstance(e, PeakCenterEditor):
try:
es.append(int(e.name.split(' ')[-1]))
except ValueError:
pass
i = max(es) + 1 if es else 1
ret = -1
ion = self.scan_manager.ion_optics_manager
self._peak_center_start_hook()
time.sleep(2)
name = 'Peak Center {:02d}'.format(i)
if ion.setup_peak_center(new=True, **setup_kw):
self._on_peak_center_start()
invoke_in_main_thread(self._open_editor, PeakCenterEditor(model=ion.peak_center, name=name))
ion.do_peak_center(**peak_kw)
ret = ion.peak_center_result
self._peak_center_stop_hook()
return ret
def _peak_center_start_hook(self):
pass
def _peak_center_stop_hook(self):
pass
def _scan_factory(self):
sim = self.scan_manager.spectrometer.simulation
name = 'Scan (Simulation)' if sim else 'Scan'
# self._open_editor(ScanEditor(model=self.scan_manager, name=name))
# print 'asdfas', self.editor_area.control
# print [e for e in self.editor_area.control.children() if isinstance(e, EditorWidget)]
# super(SpectrometerTask, self).activated()
se = ScanEditor(model=self.scan_manager, name=name)
self._open_editor(se)
def _default_layout_default(self):
return TaskLayout(
left=Splitter(
PaneItem('pychron.spectrometer.controls'),
orientation='vertical'),
right=VSplitter(PaneItem('pychron.spectrometer.intensities'),
PaneItem('pychron.spectrometer.readout')))
# def create_central_pane(self):
# g = ScanPane(model=self.scan_manager)
# return g
@on_trait_change('scan_manager:mass_scanner:new_scanner')
def _handle_mass_scan_event(self):
self._scan_event(self.scan_manager.mass_scanner)
@on_trait_change('scan_manager:dac_scanner:new_scanner')
def _handle_dac_scan_event(self):
self._scan_event(self.scan_manager.dac_scanner)
def _scan_event(self, scanner):
sim = self.scan_manager.spectrometer.simulation
name = 'Magnet Scan (Simulation)' if sim else 'Magnet Scan'
editor = next((e for e in self.editor_area.editors if e.id == 'pychron.scanner'), None)
if editor is not None:
scanner.reset()
else:
editor = ScannerEditor(model=scanner, name=name, id='pychron.scanner')
self._open_editor(editor, activate=False)
self.split_editors(0, 1, h2=300, orientation='vertical')
self.activate_editor(editor)
@on_trait_change('window:opened')
def _opened(self):
self.scan_manager.activate()
self._scan_factory()
ee = [e for e in self.editor_area.control.children() if isinstance(e, EditorWidget)][0]
# print int(ee.features())
# ee.setFeatures(QtGui.QDockWidget.NoDockWidgetFeatures)
# print int(ee.features())
# ee.update_title()
# ============= EOF =============================================<|fim▁end|> | |
<|file_name|>SnapshotManagerTest.java<|end_file_name|><|fim▁begin|>/*
* Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.controller.cluster.raft;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import akka.actor.ActorRef;
import akka.persistence.SnapshotSelectionCriteria;
import akka.testkit.TestActorRef;
import java.util.Arrays;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.opendaylight.controller.cluster.DataPersistenceProvider;
import org.opendaylight.controller.cluster.raft.SnapshotManager.LastAppliedTermInformationReader;
import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshot;
import org.opendaylight.controller.cluster.raft.base.messages.SendInstallSnapshot;
import org.opendaylight.controller.cluster.raft.base.messages.SnapshotComplete;
import org.opendaylight.controller.cluster.raft.behaviors.RaftActorBehavior;
import org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor;
import org.slf4j.LoggerFactory;
public class SnapshotManagerTest extends AbstractActorTest {
@Mock
private RaftActorContext mockRaftActorContext;
@Mock
private ConfigParams mockConfigParams;
@Mock
private ReplicatedLog mockReplicatedLog;
@Mock
private DataPersistenceProvider mockDataPersistenceProvider;
@Mock
private RaftActorBehavior mockRaftActorBehavior;
@Mock
private Runnable mockProcedure;
@Mock
private ElectionTerm mockElectionTerm;
private SnapshotManager snapshotManager;
private TestActorFactory factory;
private TestActorRef<MessageCollectorActor> actorRef;
@Before
public void setUp(){
MockitoAnnotations.initMocks(this);
doReturn(false).when(mockRaftActorContext).hasFollowers();
doReturn(mockConfigParams).when(mockRaftActorContext).getConfigParams();
doReturn(10L).when(mockConfigParams).getSnapshotBatchCount();
doReturn(70).when(mockConfigParams).getSnapshotDataThresholdPercentage();
doReturn(mockReplicatedLog).when(mockRaftActorContext).getReplicatedLog();
doReturn("123").when(mockRaftActorContext).getId();
doReturn(mockDataPersistenceProvider).when(mockRaftActorContext).getPersistenceProvider();
doReturn(mockRaftActorBehavior).when(mockRaftActorContext).getCurrentBehavior();
doReturn("123").when(mockRaftActorBehavior).getLeaderId();
doReturn(mockElectionTerm).when(mockRaftActorContext).getTermInformation();
doReturn(5L).when(mockElectionTerm).getCurrentTerm();
doReturn("member5").when(mockElectionTerm).getVotedFor();
snapshotManager = new SnapshotManager(mockRaftActorContext, LoggerFactory.getLogger(this.getClass()));
factory = new TestActorFactory(getSystem());
actorRef = factory.createTestActor(MessageCollectorActor.props(), factory.generateActorId("test-"));
doReturn(actorRef).when(mockRaftActorContext).getActor();
snapshotManager.setCreateSnapshotRunnable(mockProcedure);
}
@After
public void tearDown(){
factory.close();
}
@Test
public void testConstruction(){
assertEquals(false, snapshotManager.isCapturing());
}
@Test
public void testCaptureToInstall() throws Exception {
// Force capturing toInstall = true
snapshotManager.captureToInstall(new MockRaftActorContext.MockReplicatedLogEntry(1, 0,
new MockRaftActorContext.MockPayload()), 0, "follower-1");
assertEquals(true, snapshotManager.isCapturing());
verify(mockProcedure).run();
CaptureSnapshot captureSnapshot = snapshotManager.getCaptureSnapshot();
// LastIndex and LastTerm are picked up from the lastLogEntry
assertEquals(0L, captureSnapshot.getLastIndex());
assertEquals(1L, captureSnapshot.getLastTerm());
// Since the actor does not have any followers (no peer addresses) lastApplied will be from lastLogEntry
assertEquals(0L, captureSnapshot.getLastAppliedIndex());
assertEquals(1L, captureSnapshot.getLastAppliedTerm());
//
assertEquals(-1L, captureSnapshot.getReplicatedToAllIndex());
assertEquals(-1L, captureSnapshot.getReplicatedToAllTerm());
actorRef.underlyingActor().clear();
}
@Test
public void testCapture() throws Exception {
boolean capture = snapshotManager.capture(new MockRaftActorContext.MockReplicatedLogEntry(1,9,
new MockRaftActorContext.MockPayload()), 9);
assertTrue(capture);
assertEquals(true, snapshotManager.isCapturing());
verify(mockProcedure).run();
CaptureSnapshot captureSnapshot = snapshotManager.getCaptureSnapshot();
// LastIndex and LastTerm are picked up from the lastLogEntry
assertEquals(9L, captureSnapshot.getLastIndex());
assertEquals(1L, captureSnapshot.getLastTerm());
// Since the actor does not have any followers (no peer addresses) lastApplied will be from lastLogEntry
assertEquals(9L, captureSnapshot.getLastAppliedIndex());
assertEquals(1L, captureSnapshot.getLastAppliedTerm());
//
assertEquals(-1L, captureSnapshot.getReplicatedToAllIndex());
assertEquals(-1L, captureSnapshot.getReplicatedToAllTerm());
actorRef.underlyingActor().clear();
}
@Test
public void testCaptureWithNullLastLogEntry() throws Exception {
boolean capture = snapshotManager.capture(null, 1);
assertTrue(capture);
assertEquals(true, snapshotManager.isCapturing());
verify(mockProcedure).run();
CaptureSnapshot captureSnapshot = snapshotManager.getCaptureSnapshot();
System.out.println(captureSnapshot);
// LastIndex and LastTerm are picked up from the lastLogEntry
assertEquals(-1L, captureSnapshot.getLastIndex());
assertEquals(-1L, captureSnapshot.getLastTerm());
// Since the actor does not have any followers (no peer addresses) lastApplied will be from lastLogEntry
assertEquals(-1L, captureSnapshot.getLastAppliedIndex());
assertEquals(-1L, captureSnapshot.getLastAppliedTerm());
//
assertEquals(-1L, captureSnapshot.getReplicatedToAllIndex());
assertEquals(-1L, captureSnapshot.getReplicatedToAllTerm());
actorRef.underlyingActor().clear();
}
@Test
public void testCaptureWithCreateProcedureError () throws Exception {
doThrow(new RuntimeException("mock")).when(mockProcedure).run();
boolean capture = snapshotManager.capture(new MockRaftActorContext.MockReplicatedLogEntry(1,9,
new MockRaftActorContext.MockPayload()), 9);
assertFalse(capture);
assertEquals(false, snapshotManager.isCapturing());
verify(mockProcedure).run();
}
@Test
public void testIllegalCapture() throws Exception {
boolean capture = snapshotManager.capture(new MockRaftActorContext.MockReplicatedLogEntry(1,9,
new MockRaftActorContext.MockPayload()), 9);
assertTrue(capture);
verify(mockProcedure).run();
reset(mockProcedure);
// This will not cause snapshot capture to start again
capture = snapshotManager.capture(new MockRaftActorContext.MockReplicatedLogEntry(1,9,
new MockRaftActorContext.MockPayload()), 9);
assertFalse(capture);
verify(mockProcedure, never()).run();
}
@Test
public void testPersistWhenReplicatedToAllIndexMinusOne(){
doReturn(7L).when(mockReplicatedLog).getSnapshotIndex();
doReturn(1L).when(mockReplicatedLog).getSnapshotTerm();
doReturn(true).when(mockRaftActorContext).hasFollowers();
doReturn(8L).when(mockRaftActorContext).getLastApplied();
MockRaftActorContext.MockReplicatedLogEntry lastLogEntry = new MockRaftActorContext.MockReplicatedLogEntry(
3L, 9L, new MockRaftActorContext.MockPayload());
MockRaftActorContext.MockReplicatedLogEntry lastAppliedEntry = new MockRaftActorContext.MockReplicatedLogEntry(
2L, 8L, new MockRaftActorContext.MockPayload());
doReturn(lastAppliedEntry).when(mockReplicatedLog).get(8L);
doReturn(Arrays.asList(lastLogEntry)).when(mockReplicatedLog).getFrom(9L);
// when replicatedToAllIndex = -1
snapshotManager.capture(lastLogEntry, -1);
byte[] bytes = new byte[] {1,2,3,4,5,6,7,8,9,10};
snapshotManager.persist(bytes, Runtime.getRuntime().totalMemory());
ArgumentCaptor<Snapshot> snapshotArgumentCaptor = ArgumentCaptor.forClass(Snapshot.class);
verify(mockDataPersistenceProvider).saveSnapshot(snapshotArgumentCaptor.capture());
Snapshot snapshot = snapshotArgumentCaptor.getValue();
assertEquals("getLastTerm", 3L, snapshot.getLastTerm());
assertEquals("getLastIndex", 9L, snapshot.getLastIndex());
assertEquals("getLastAppliedTerm", 2L, snapshot.getLastAppliedTerm());
assertEquals("getLastAppliedIndex", 8L, snapshot.getLastAppliedIndex());
assertArrayEquals("getState", bytes, snapshot.getState());
assertEquals("getUnAppliedEntries", Arrays.asList(lastLogEntry), snapshot.getUnAppliedEntries());
assertEquals("electionTerm", mockElectionTerm.getCurrentTerm(), snapshot.getElectionTerm());
assertEquals("electionVotedFor", mockElectionTerm.getVotedFor(), snapshot.getElectionVotedFor());
verify(mockReplicatedLog).snapshotPreCommit(7L, 1L);
}
@Test
public void testPersistWhenReplicatedToAllIndexNotMinus(){
doReturn(45L).when(mockReplicatedLog).getSnapshotIndex();
doReturn(6L).when(mockReplicatedLog).getSnapshotTerm();
ReplicatedLogEntry replicatedLogEntry = mock(ReplicatedLogEntry.class);
doReturn(replicatedLogEntry).when(mockReplicatedLog).get(9);
doReturn(6L).when(replicatedLogEntry).getTerm();
doReturn(9L).when(replicatedLogEntry).getIndex();
// when replicatedToAllIndex != -1
snapshotManager.capture(new MockRaftActorContext.MockReplicatedLogEntry(6,9,
new MockRaftActorContext.MockPayload()), 9);
byte[] bytes = new byte[] {1,2,3,4,5,6,7,8,9,10};
snapshotManager.persist(bytes, Runtime.getRuntime().totalMemory());
ArgumentCaptor<Snapshot> snapshotArgumentCaptor = ArgumentCaptor.forClass(Snapshot.class);
verify(mockDataPersistenceProvider).saveSnapshot(snapshotArgumentCaptor.capture());
Snapshot snapshot = snapshotArgumentCaptor.getValue();
assertEquals("getLastTerm", 6L, snapshot.getLastTerm());
assertEquals("getLastIndex", 9L, snapshot.getLastIndex());
assertEquals("getLastAppliedTerm", 6L, snapshot.getLastAppliedTerm());
assertEquals("getLastAppliedIndex", 9L, snapshot.getLastAppliedIndex());
assertArrayEquals("getState", bytes, snapshot.getState());
assertEquals("getUnAppliedEntries size", 0, snapshot.getUnAppliedEntries().size());
verify(mockReplicatedLog).snapshotPreCommit(9L, 6L);
verify(mockRaftActorBehavior).setReplicatedToAllIndex(9);
}
@Test
public void testPersistWhenReplicatedLogDataSizeGreaterThanThreshold(){
doReturn(Integer.MAX_VALUE).when(mockReplicatedLog).dataSize();
// when replicatedToAllIndex = -1
snapshotManager.capture(new MockRaftActorContext.MockReplicatedLogEntry(6,9,
new MockRaftActorContext.MockPayload()), -1);
snapshotManager.persist(new byte[]{}, Runtime.getRuntime().totalMemory());
verify(mockDataPersistenceProvider).saveSnapshot(any(Snapshot.class));
verify(mockReplicatedLog).snapshotPreCommit(9L, 6L);
verify(mockRaftActorBehavior, never()).setReplicatedToAllIndex(anyLong());
}
@Test
public void testPersistWhenReplicatedLogSizeExceedsSnapshotBatchCount() {
doReturn(10L).when(mockReplicatedLog).size(); // matches snapshotBatchCount
doReturn(100).when(mockReplicatedLog).dataSize();
doReturn(5L).when(mockReplicatedLog).getSnapshotIndex();
doReturn(5L).when(mockReplicatedLog).getSnapshotTerm();
long replicatedToAllIndex = 1;
ReplicatedLogEntry replicatedLogEntry = mock(ReplicatedLogEntry.class);
doReturn(replicatedLogEntry).when(mockReplicatedLog).get(replicatedToAllIndex);
doReturn(6L).when(replicatedLogEntry).getTerm();
doReturn(replicatedToAllIndex).when(replicatedLogEntry).getIndex();
snapshotManager.capture(new MockRaftActorContext.MockReplicatedLogEntry(6, 9,
new MockRaftActorContext.MockPayload()), replicatedToAllIndex);
snapshotManager.persist(new byte[]{}, 2000000L);
verify(mockDataPersistenceProvider).saveSnapshot(any(Snapshot.class));
verify(mockReplicatedLog).snapshotPreCommit(9L, 6L);
verify(mockRaftActorBehavior).setReplicatedToAllIndex(replicatedToAllIndex);
}
@Test
public void testPersistSendInstallSnapshot(){
doReturn(Integer.MAX_VALUE).when(mockReplicatedLog).dataSize();
// when replicatedToAllIndex = -1
boolean capture = snapshotManager.captureToInstall(new MockRaftActorContext.MockReplicatedLogEntry(6, 9,
new MockRaftActorContext.MockPayload()), -1, "follower-1");
assertTrue(capture);
byte[] bytes = new byte[] {1,2,3,4,5,6,7,8,9,10};
snapshotManager.persist(bytes, Runtime.getRuntime().totalMemory());
assertEquals(true, snapshotManager.isCapturing());
verify(mockDataPersistenceProvider).saveSnapshot(any(Snapshot.class));
verify(mockReplicatedLog).snapshotPreCommit(9L, 6L);
ArgumentCaptor<SendInstallSnapshot> sendInstallSnapshotArgumentCaptor
= ArgumentCaptor.forClass(SendInstallSnapshot.class);
verify(mockRaftActorBehavior).handleMessage(any(ActorRef.class), sendInstallSnapshotArgumentCaptor.capture());
SendInstallSnapshot sendInstallSnapshot = sendInstallSnapshotArgumentCaptor.getValue();
assertTrue(Arrays.equals(bytes, sendInstallSnapshot.getSnapshot().getState()));
}
@Test
public void testCallingPersistWithoutCaptureWillDoNothing(){
snapshotManager.persist(new byte[]{}, Runtime.getRuntime().totalMemory());
verify(mockDataPersistenceProvider, never()).saveSnapshot(any(Snapshot.class));
verify(mockReplicatedLog, never()).snapshotPreCommit(9L, 6L);
verify(mockRaftActorBehavior, never()).handleMessage(any(ActorRef.class), any(SendInstallSnapshot.class));
}
@Test
public void testCallingPersistTwiceWillDoNoHarm(){
doReturn(Integer.MAX_VALUE).when(mockReplicatedLog).dataSize();
// when replicatedToAllIndex = -1
snapshotManager.captureToInstall(new MockRaftActorContext.MockReplicatedLogEntry(6, 9,
new MockRaftActorContext.MockPayload()), -1, "follower-1");
snapshotManager.persist(new byte[]{}, Runtime.getRuntime().totalMemory());
snapshotManager.persist(new byte[]{}, Runtime.getRuntime().totalMemory());
verify(mockDataPersistenceProvider).saveSnapshot(any(Snapshot.class));
verify(mockReplicatedLog).snapshotPreCommit(9L, 6L);
verify(mockRaftActorBehavior).handleMessage(any(ActorRef.class), any(SendInstallSnapshot.class));
}
@Test
public void testCommit(){
doReturn(50L).when(mockDataPersistenceProvider).getLastSequenceNumber();
// when replicatedToAllIndex = -1
snapshotManager.captureToInstall(new MockRaftActorContext.MockReplicatedLogEntry(6, 9,
new MockRaftActorContext.MockPayload()), -1, "follower-1");
snapshotManager.persist(new byte[]{}, Runtime.getRuntime().totalMemory());
assertEquals(true, snapshotManager.isCapturing());
snapshotManager.commit(100L, 1234L);
assertEquals(false, snapshotManager.isCapturing());
verify(mockReplicatedLog).snapshotCommit();
verify(mockDataPersistenceProvider).deleteMessages(50L);
ArgumentCaptor<SnapshotSelectionCriteria> criteriaCaptor = ArgumentCaptor.forClass(SnapshotSelectionCriteria.class);
verify(mockDataPersistenceProvider).deleteSnapshots(criteriaCaptor.capture());
assertEquals(100L, criteriaCaptor.getValue().maxSequenceNr());
assertEquals(1233L, criteriaCaptor.getValue().maxTimestamp());
MessageCollectorActor.expectFirstMatching(actorRef, SnapshotComplete.class);
}
@Test
public void testCommitBeforePersist(){
// when replicatedToAllIndex = -1
snapshotManager.captureToInstall(new MockRaftActorContext.MockReplicatedLogEntry(6, 9,
new MockRaftActorContext.MockPayload()), -1, "follower-1");
snapshotManager.commit(100L, 0);
verify(mockReplicatedLog, never()).snapshotCommit();
verify(mockDataPersistenceProvider, never()).deleteMessages(100L);
verify(mockDataPersistenceProvider, never()).deleteSnapshots(any(SnapshotSelectionCriteria.class));
}
@Test
public void testCommitBeforeCapture(){
snapshotManager.commit(100L, 0);
verify(mockReplicatedLog, never()).snapshotCommit();
verify(mockDataPersistenceProvider, never()).deleteMessages(anyLong());
verify(mockDataPersistenceProvider, never()).deleteSnapshots(any(SnapshotSelectionCriteria.class));
}
@Test
public void testCallingCommitMultipleTimesCausesNoHarm(){
doReturn(50L).when(mockDataPersistenceProvider).getLastSequenceNumber();
// when replicatedToAllIndex = -1
snapshotManager.captureToInstall(new MockRaftActorContext.MockReplicatedLogEntry(6, 9,
new MockRaftActorContext.MockPayload()), -1, "follower-1");
snapshotManager.persist(new byte[]{}, Runtime.getRuntime().totalMemory());
snapshotManager.commit(100L, 0);
snapshotManager.commit(100L, 0);
verify(mockReplicatedLog, times(1)).snapshotCommit();
verify(mockDataPersistenceProvider, times(1)).deleteMessages(50L);
verify(mockDataPersistenceProvider, times(1)).deleteSnapshots(any(SnapshotSelectionCriteria.class));
}
@Test
public void testRollback(){
// when replicatedToAllIndex = -1
snapshotManager.captureToInstall(new MockRaftActorContext.MockReplicatedLogEntry(6, 9,
new MockRaftActorContext.MockPayload()), -1, "follower-1");
snapshotManager.persist(new byte[]{}, Runtime.getRuntime().totalMemory());
snapshotManager.rollback();
verify(mockReplicatedLog).snapshotRollback();
MessageCollectorActor.expectFirstMatching(actorRef, SnapshotComplete.class);
}
@Test
public void testRollbackBeforePersist(){
// when replicatedToAllIndex = -1
snapshotManager.captureToInstall(new MockRaftActorContext.MockReplicatedLogEntry(6, 9,
new MockRaftActorContext.MockPayload()), -1, "follower-1");
snapshotManager.rollback();
verify(mockReplicatedLog, never()).snapshotRollback();
}
@Test
public void testRollbackBeforeCapture(){
snapshotManager.rollback();
verify(mockReplicatedLog, never()).snapshotRollback();
}
@Test
public void testCallingRollbackMultipleTimesCausesNoHarm(){
// when replicatedToAllIndex = -1
snapshotManager.captureToInstall(new MockRaftActorContext.MockReplicatedLogEntry(6, 9,
new MockRaftActorContext.MockPayload()), -1, "follower-1");
snapshotManager.persist(new byte[]{}, Runtime.getRuntime().totalMemory());
snapshotManager.rollback();
snapshotManager.rollback();
verify(mockReplicatedLog, times(1)).snapshotRollback();
}
@Test
public void testTrimLogWhenTrimIndexLessThanLastApplied() {
doReturn(20L).when(mockRaftActorContext).getLastApplied();
ReplicatedLogEntry replicatedLogEntry = mock(ReplicatedLogEntry.class);
doReturn(true).when(mockReplicatedLog).isPresent(10);
doReturn(replicatedLogEntry).when((mockReplicatedLog)).get(10);
doReturn(5L).when(replicatedLogEntry).getTerm();
long retIndex = snapshotManager.trimLog(10);
assertEquals("return index", 10L, retIndex);
verify(mockReplicatedLog).snapshotPreCommit(10, 5);
verify(mockReplicatedLog).snapshotCommit();
verify(mockRaftActorBehavior, never()).setReplicatedToAllIndex(anyLong());
}
@Test
public void testTrimLogWhenLastAppliedNotSet() {
doReturn(-1L).when(mockRaftActorContext).getLastApplied();
ReplicatedLogEntry replicatedLogEntry = mock(ReplicatedLogEntry.class);
doReturn(true).when(mockReplicatedLog).isPresent(10);
doReturn(replicatedLogEntry).when((mockReplicatedLog)).get(10);
doReturn(5L).when(replicatedLogEntry).getTerm();
long retIndex = snapshotManager.trimLog(10);
assertEquals("return index", -1L, retIndex);
verify(mockReplicatedLog, never()).snapshotPreCommit(anyLong(), anyLong());
verify(mockReplicatedLog, never()).snapshotCommit();
verify(mockRaftActorBehavior, never()).setReplicatedToAllIndex(anyLong());
}
@Test
public void testTrimLogWhenLastAppliedZero() {
doReturn(0L).when(mockRaftActorContext).getLastApplied();
ReplicatedLogEntry replicatedLogEntry = mock(ReplicatedLogEntry.class);
doReturn(true).when(mockReplicatedLog).isPresent(10);
doReturn(replicatedLogEntry).when((mockReplicatedLog)).get(10);
doReturn(5L).when(replicatedLogEntry).getTerm();
long retIndex = snapshotManager.trimLog(10);
assertEquals("return index", -1L, retIndex);
verify(mockReplicatedLog, never()).snapshotPreCommit(anyLong(), anyLong());
verify(mockReplicatedLog, never()).snapshotCommit();
verify(mockRaftActorBehavior, never()).setReplicatedToAllIndex(anyLong());
}
@Test
public void testTrimLogWhenTrimIndexNotPresent() {
doReturn(20L).when(mockRaftActorContext).getLastApplied();
doReturn(false).when(mockReplicatedLog).isPresent(10);
<|fim▁hole|>
verify(mockReplicatedLog, never()).snapshotPreCommit(anyLong(), anyLong());
verify(mockReplicatedLog, never()).snapshotCommit();
// Trim index is greater than replicatedToAllIndex so should update it.
verify(mockRaftActorBehavior).setReplicatedToAllIndex(10L);
}
@Test
public void testTrimLogAfterCapture(){
boolean capture = snapshotManager.capture(new MockRaftActorContext.MockReplicatedLogEntry(1,9,
new MockRaftActorContext.MockPayload()), 9);
assertTrue(capture);
assertEquals(true, snapshotManager.isCapturing());
ReplicatedLogEntry replicatedLogEntry = mock(ReplicatedLogEntry.class);
doReturn(20L).when(mockRaftActorContext).getLastApplied();
doReturn(true).when(mockReplicatedLog).isPresent(10);
doReturn(replicatedLogEntry).when((mockReplicatedLog)).get(10);
doReturn(5L).when(replicatedLogEntry).getTerm();
snapshotManager.trimLog(10);
verify(mockReplicatedLog, never()).snapshotPreCommit(anyLong(), anyLong());
verify(mockReplicatedLog, never()).snapshotCommit();
}
@Test
public void testTrimLogAfterCaptureToInstall(){
boolean capture = snapshotManager.captureToInstall(new MockRaftActorContext.MockReplicatedLogEntry(1,9,
new MockRaftActorContext.MockPayload()), 9, "follower-1");
assertTrue(capture);
assertEquals(true, snapshotManager.isCapturing());
ReplicatedLogEntry replicatedLogEntry = mock(ReplicatedLogEntry.class);
doReturn(20L).when(mockRaftActorContext).getLastApplied();
doReturn(true).when(mockReplicatedLog).isPresent(10);
doReturn(replicatedLogEntry).when((mockReplicatedLog)).get(10);
doReturn(5L).when(replicatedLogEntry).getTerm();
snapshotManager.trimLog(10);
verify(mockReplicatedLog, never()).snapshotPreCommit(10, 5);
verify(mockReplicatedLog, never()).snapshotCommit();
}
@Test
public void testLastAppliedTermInformationReader() {
LastAppliedTermInformationReader reader = new LastAppliedTermInformationReader();
doReturn(4L).when(mockReplicatedLog).getSnapshotTerm();
doReturn(7L).when(mockReplicatedLog).getSnapshotIndex();
ReplicatedLogEntry lastLogEntry = new MockRaftActorContext.MockReplicatedLogEntry(6L, 9L,
new MockRaftActorContext.MockPayload());
// No followers and valid lastLogEntry
reader.init(mockReplicatedLog, 1L, lastLogEntry, false);
assertEquals("getTerm", 6L, reader.getTerm());
assertEquals("getIndex", 9L, reader.getIndex());
// No followers and null lastLogEntry
reader.init(mockReplicatedLog, 1L, null, false);
assertEquals("getTerm", -1L, reader.getTerm());
assertEquals("getIndex", -1L, reader.getIndex());
// Followers and valid originalIndex entry
doReturn(new MockRaftActorContext.MockReplicatedLogEntry(5L, 8L,
new MockRaftActorContext.MockPayload())).when(mockReplicatedLog).get(8L);
reader.init(mockReplicatedLog, 8L, lastLogEntry, true);
assertEquals("getTerm", 5L, reader.getTerm());
assertEquals("getIndex", 8L, reader.getIndex());
// Followers and null originalIndex entry and valid snapshot index
reader.init(mockReplicatedLog, 7L, lastLogEntry, true);
assertEquals("getTerm", 4L, reader.getTerm());
assertEquals("getIndex", 7L, reader.getIndex());
// Followers and null originalIndex entry and invalid snapshot index
doReturn(-1L).when(mockReplicatedLog).getSnapshotIndex();
reader.init(mockReplicatedLog, 7L, lastLogEntry, true);
assertEquals("getTerm", -1L, reader.getTerm());
assertEquals("getIndex", -1L, reader.getIndex());
}
}<|fim▁end|> | long retIndex = snapshotManager.trimLog(10);
assertEquals("return index", -1L, retIndex); |
<|file_name|>index.js<|end_file_name|><|fim▁begin|>import 'babel-polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import promise from 'redux-promise';
import createLogger from 'redux-logger';
import allReducers from './reducers';
import App from './components/App';
const logger = createLogger();
const store = createStore(allReducers, applyMiddleware(thunk, promise, logger));
<|fim▁hole|>ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('app')
);<|fim▁end|> | |
<|file_name|>model.py<|end_file_name|><|fim▁begin|>import os
path = os.path.dirname(os.path.realpath(__file__))
sbmlFilePath = os.path.join(path, 'MODEL1006230003.xml')
<|fim▁hole|> try:
__import__(module_name)
except ImportError:
return False
else:
return True
if module_exists('libsbml'):
import libsbml
sbml = libsbml.readSBMLFromString(sbmlString)<|fim▁end|> | with open(sbmlFilePath,'r') as f:
sbmlString = f.read()
def module_exists(module_name): |
<|file_name|>test_useractive.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import
from datetime import timedelta
from django.utils import timezone
from django.test import RequestFactory
from exam import fixture
from sentry.middleware.user import UserActiveMiddleware
from sentry.testutils import TestCase
class UserActiveMiddlewareTest(TestCase):<|fim▁hole|> self.view = lambda x: None
user = self.user
req = self.factory.get('/')
req.user = user
resp = self.middleware.process_view(req, self.view, [], {})
assert resp is None
assert timezone.now() - user.last_active < timedelta(minutes=1)
user.last_active = None
resp = self.middleware.process_view(req, self.view, [], {})
assert resp is None
assert timezone.now() - user.last_active < timedelta(minutes=1)<|fim▁end|> | middleware = fixture(UserActiveMiddleware)
factory = fixture(RequestFactory)
def test_simple(self): |
<|file_name|>function2.js<|end_file_name|><|fim▁begin|>function Test() {
a = 1;
console.log(a);
try {
console.log(b);
} catch (e) {
console.log("null");
}
}
console.log("Test1");
Test();
a = 2;
b = 3;
console.log("Test2");
Test();
Test.a = 4;
Test.b = 4;
console.log("Test3");
Test();<|fim▁hole|>console.log(Test.a);
console.log(Test.b);<|fim▁end|> |
console.log("Test4");
|
<|file_name|>bouqueteditor_chanselect.cpp<|end_file_name|><|fim▁begin|>/*
neutrino bouquet editor - channel selection
Copyright (C) 2001 Steffen Hehn 'McClean'
Copyright (C) 2017 Sven Hoefer
License: GPL
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, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <unistd.h>
#include <global.h>
#include <neutrino.h>
#include <driver/fontrenderer.h>
#include <driver/screen_max.h>
#include <gui/widget/icons.h>
#include <zapit/getservices.h>
#include <zapit/zapit.h>
#include "bouqueteditor_chanselect.h"
extern CBouquetManager *g_bouquetManager;
CBEChannelSelectWidget::CBEChannelSelectWidget(const std::string & Caption, CZapitBouquet* Bouquet, CZapitClient::channelsMode Mode)
{
caption = Caption;
bouquet = Bouquet;
mode = Mode;
selected = 0;
liststart = 0;
channellist_sort_mode = SORT_ALPHA;
bouquetChannels = NULL;
int iw, ih;
action_icon_width = 0;
frameBuffer->getIconSize(NEUTRINO_ICON_BUTTON_DUMMY_SMALL, &action_icon_width, &ih);
status_icon_width = 0;
frameBuffer->getIconSize(NEUTRINO_ICON_MARKER_SCRAMBLED, &iw, &ih);
status_icon_width = std::max(status_icon_width, iw);
frameBuffer->getIconSize(NEUTRINO_ICON_MARKER_STREAMING, &iw, &ih);
status_icon_width = std::max(status_icon_width, iw);
}
CBEChannelSelectWidget::~CBEChannelSelectWidget()
{
}
void CBEChannelSelectWidget::paintItem(int pos)
{
int ypos = y + header_height + pos*item_height;
unsigned int current = liststart + pos;
bool i_selected = current == selected;
int i_radius = RADIUS_NONE;
fb_pixel_t color;
fb_pixel_t bgcolor;
getItemColors(color, bgcolor, i_selected);
if (i_selected)
{
if (current < Channels.size() || Channels.empty())
paintDetails(pos, current);
i_radius = RADIUS_LARGE;
}
else
{
if (current < Channels.size() && (Channels[current]->flags & CZapitChannel::NOT_PRESENT))
color = COL_MENUCONTENTINACTIVE_TEXT;
}
if (i_radius)
frameBuffer->paintBoxRel(x, ypos, width - SCROLLBAR_WIDTH, item_height, COL_MENUCONTENT_PLUS_0);
frameBuffer->paintBoxRel(x, ypos, width - SCROLLBAR_WIDTH, item_height, bgcolor, i_radius);
if (current < Channels.size())
{
if (isChannelInBouquet(current))
frameBuffer->paintIcon(NEUTRINO_ICON_BUTTON_GREEN, x + OFFSET_INNER_MID, ypos, item_height);
else
frameBuffer->paintIcon(NEUTRINO_ICON_BUTTON_DUMMY_SMALL, x + OFFSET_INNER_MID, ypos, item_height);
int text_offset = 2*OFFSET_INNER_MID + action_icon_width;
item_font->RenderString(x + text_offset, ypos + item_height, width - text_offset - SCROLLBAR_WIDTH - 2*OFFSET_INNER_MID - status_icon_width, Channels[current]->getName(), color);
if (Channels[current]->scrambled)
frameBuffer->paintIcon(NEUTRINO_ICON_MARKER_SCRAMBLED, x + width - SCROLLBAR_WIDTH - OFFSET_INNER_MID - status_icon_width, ypos, item_height);
else if (!Channels[current]->getUrl().empty())
frameBuffer->paintIcon(NEUTRINO_ICON_MARKER_STREAMING, x + width - SCROLLBAR_WIDTH - OFFSET_INNER_MID - status_icon_width, ypos, item_height);
}
frameBuffer->blit();
}
void CBEChannelSelectWidget::paintItems()
{
liststart = (selected/items_count)*items_count;
for(unsigned int count = 0; count < items_count; count++)
paintItem(count);
int total_pages;
int current_page;
getScrollBarData(&total_pages, ¤t_page, Channels.size(), items_count, selected);
paintScrollBar(x + width - SCROLLBAR_WIDTH, y + header_height, SCROLLBAR_WIDTH, body_height, total_pages, current_page);
}
void CBEChannelSelectWidget::paintHead()
{
CBEGlobals::paintHead(caption + (mode == CZapitClient::MODE_TV ? " - TV" : " - Radio"),
mode == CZapitClient::MODE_TV ? NEUTRINO_ICON_VIDEO : NEUTRINO_ICON_AUDIO);
}
<|fim▁hole|>struct button_label CBEChannelSelectButtons[] =
{
{ NEUTRINO_ICON_BUTTON_RED, LOCALE_CHANNELLIST_FOOT_SORT_ALPHA },
{ NEUTRINO_ICON_BUTTON_OKAY, LOCALE_BOUQUETEDITOR_SWITCH },
{ NEUTRINO_ICON_BUTTON_HOME, LOCALE_BOUQUETEDITOR_RETURN }
};
void CBEChannelSelectWidget::paintFoot()
{
switch (channellist_sort_mode)
{
case SORT_FREQ:
{
CBEChannelSelectButtons[0].locale = LOCALE_CHANNELLIST_FOOT_SORT_FREQ;
break;
}
case SORT_SAT:
{
CBEChannelSelectButtons[0].locale = LOCALE_CHANNELLIST_FOOT_SORT_SAT;
break;
}
case SORT_CH_NUMBER:
{
CBEChannelSelectButtons[0].locale = LOCALE_CHANNELLIST_FOOT_SORT_CHNUM;
break;
}
case SORT_ALPHA:
default:
{
CBEChannelSelectButtons[0].locale = LOCALE_CHANNELLIST_FOOT_SORT_ALPHA;
break;
}
}
const short numbuttons = sizeof(CBEChannelSelectButtons)/sizeof(CBEChannelSelectButtons[0]);
CBEGlobals::paintFoot(numbuttons, CBEChannelSelectButtons);
}
std::string CBEChannelSelectWidget::getInfoText(int index)
{
std::string res = "";
if (Channels.empty())
return res;
std::string satname = CServiceManager::getInstance()->GetSatelliteName(Channels[index]->getSatellitePosition());
if (IS_WEBCHAN(Channels[index]->getChannelID()))
satname = "Web-Channel"; // TODO split into WebTV/WebRadio
transponder t;
CServiceManager::getInstance()->GetTransponder(Channels[index]->getTransponderId(), t);
std::string desc = t.description();
if (Channels[index]->pname)
{
if (desc.empty())
desc = std::string(Channels[index]->pname);
else
desc += " (" + std::string(Channels[index]->pname) + ")";
}
if (!Channels[index]->getDesc().empty())
desc += "\n" + Channels[index]->getDesc();
res = satname + " - " + desc;
return res;
}
void CBEChannelSelectWidget::updateSelection(unsigned int newpos)
{
if (newpos == selected || newpos == (unsigned int)-1)
return;
unsigned int prev_selected = selected;
selected = newpos;
unsigned int oldliststart = liststart;
liststart = (selected/items_count)*items_count;
if (oldliststart != liststart)
{
paintItems();
}
else
{
paintItem(prev_selected - liststart);
paintItem(selected - liststart);
}
}
int CBEChannelSelectWidget::exec(CMenuTarget* parent, const std::string & /*actionKey*/)
{
neutrino_msg_t msg;
neutrino_msg_data_t data;
int res = menu_return::RETURN_REPAINT;
selected = 0;
if (parent)
parent->hide();
bouquetChannels = mode == CZapitClient::MODE_TV ? &(bouquet->tvChannels) : &(bouquet->radioChannels);
Channels.clear();
if (mode == CZapitClient::MODE_RADIO)
CServiceManager::getInstance()->GetAllRadioChannels(Channels);
else
CServiceManager::getInstance()->GetAllTvChannels(Channels);
sort(Channels.begin(), Channels.end(), CmpChannelByChName());
paintHead();
paintBody();
paintFoot();
paintItems();
uint64_t timeoutEnd = CRCInput::calcTimeoutEnd(*timeout_ptr);
channelChanged = false;
bool loop = true;
while (loop)
{
g_RCInput->getMsgAbsoluteTimeout(&msg, &data, &timeoutEnd);
if (msg <= CRCInput::RC_MaxRC)
timeoutEnd = CRCInput::calcTimeoutEnd(*timeout_ptr);
if ((msg == CRCInput::RC_timeout) || (msg == CRCInput::RC_home))
{
loop = false;
}
else if (msg == CRCInput::RC_up || msg == (neutrino_msg_t)g_settings.key_pageup ||
msg == CRCInput::RC_down || msg == (neutrino_msg_t)g_settings.key_pagedown)
{
int new_selected = UpDownKey(Channels, msg, items_count, selected);
updateSelection(new_selected);
}
else if (msg == (neutrino_msg_t) g_settings.key_list_start || msg == (neutrino_msg_t) g_settings.key_list_end)
{
if (!Channels.empty())
{
int new_selected = msg == (neutrino_msg_t) g_settings.key_list_start ? 0 : Channels.size() - 1;
updateSelection(new_selected);
}
}
else if (msg == CRCInput::RC_ok || msg == CRCInput::RC_green)
{
if (selected < Channels.size())
selectChannel();
}
else if (msg == CRCInput::RC_red)
{
if (selected < Channels.size())
sortChannels();
}
else if (CNeutrinoApp::getInstance()->listModeKey(msg))
{
// do nothing
}
else
{
CNeutrinoApp::getInstance()->handleMsg(msg, data);
}
}
hide();
return res;
}
void CBEChannelSelectWidget::sortChannels()
{
channellist_sort_mode++;
if (channellist_sort_mode >= SORT_END)
channellist_sort_mode = SORT_ALPHA;
switch (channellist_sort_mode)
{
case SORT_FREQ:
{
sort(Channels.begin(), Channels.end(), CmpChannelByFreq());
break;
}
case SORT_SAT:
{
sort(Channels.begin(), Channels.end(), CmpChannelBySat());
break;
}
case SORT_CH_NUMBER:
{
sort(Channels.begin(), Channels.end(), CmpChannelByChNum());
break;
}
case SORT_ALPHA:
default:
{
sort(Channels.begin(), Channels.end(), CmpChannelByChName());
break;
}
}
paintFoot();
paintItems();
}
void CBEChannelSelectWidget::selectChannel()
{
channelChanged = true;
if (isChannelInBouquet(selected))
bouquet->removeService(Channels[selected]);
else
bouquet->addService(Channels[selected]);
bouquetChannels = mode == CZapitClient::MODE_TV ? &(bouquet->tvChannels) : &(bouquet->radioChannels);
paintItem(selected - liststart);
g_RCInput->postMsg(CRCInput::RC_down, 0);
}
bool CBEChannelSelectWidget::isChannelInBouquet(int index)
{
for (unsigned int i=0; i< bouquetChannels->size(); i++)
{
if ((*bouquetChannels)[i]->getChannelID() == Channels[index]->getChannelID())
return true;
}
return false;
}
bool CBEChannelSelectWidget::hasChanged()
{
return channelChanged;
}<|fim▁end|> | |
<|file_name|>TarThread.py<|end_file_name|><|fim▁begin|>import os
import logging
from mongodb_consistent_backup.Common import LocalCommand
from mongodb_consistent_backup.Pipeline import PoolThread
class TarThread(PoolThread):
def __init__(self, backup_dir, output_file, compression='none', verbose=False, binary="tar"):
super(TarThread, self).__init__(self.__class__.__name__, compression)
self.compression_method = compression
self.backup_dir = backup_dir
self.output_file = output_file
self.verbose = verbose
self.binary = binary
self._command = None
def close(self, exit_code=None, frame=None):
if self._command and not self.stopped:
logging.debug("Stopping running tar command: %s" % self._command.command)
del exit_code
del frame
self._command.close()
self.stopped = True
def run(self):
if os.path.isdir(self.backup_dir):
if not os.path.isfile(self.output_file):
try:
backup_base_dir = os.path.dirname(self.backup_dir)
backup_base_name = os.path.basename(self.backup_dir)
log_msg = "Archiving directory: %s" % self.backup_dir
cmd_flags = ["-C", backup_base_dir, "-c", "-f", self.output_file, "--remove-files"]
if self.do_gzip():
log_msg = "Archiving and compressing directory: %s" % self.backup_dir
cmd_flags.append("-z")
cmd_flags.append(backup_base_name)
logging.info(log_msg)
self.running = True
self._command = LocalCommand(self.binary, cmd_flags, self.verbose)
self.exit_code = self._command.run()
except Exception, e:
return self.result(False, "Failed archiving file: %s!" % self.output_file, e)
finally:
self.running = False
self.stopped = True
self.completed = True
else:
return self.result(False, "Output file: %s already exists!" % self.output_file, None)
return self.result(True, "Archiving successful.", None)
def result(self, success, message, error):
return {
"success": success,
"message": message,<|fim▁hole|><|fim▁end|> | "error": error,
"directory": self.backup_dir,
"exit_code": self.exit_code
} |
<|file_name|>mail_utils.py<|end_file_name|><|fim▁begin|>import smtplib
from email.mime.text import MIMEText
from django.core.mail import EmailMultiAlternatives
from django.conf import settings
def send_message(message):
"""
* desc 快捷发送邮件
* input 要发送的邮件信息
* output None
"""
mail_handler = SendMail()
mail_handler.send_mail(settings.REPORT_USER, 'Error info', message)
class SendMail(object):
"""docstring for SendMail"""
def __init__(self):
self.mail_host = settings.MAIL_HOST
self.mail_host_user = settings.MAIL_HOST_USER
self.mail_host_pwd = settings.MAIL_HOST_PWD
self.smtp = smtplib.SMTP()
self.smtp_login()
def smtp_login(self):
# login the host
self.smtp.connect(self.mail_host)
self.smtp.login(self.mail_host_user, self.mail_host_pwd)
def send_file_mail(self, receiver_list, subject, file_info, file_name):
# 发送附件的方法
part = MIMEApplication(file_info)
part.add_header('Content-Disposition',
'attachment', filename=file_name)
msg.attach(part)
sender = self.mail_host_user<|fim▁hole|>
def send_mail(self, receiver_list, subject, context, mail_type="plain"):
"""
* desc 发送邮件的接口
* input receiver_list 收件人的地址列表 subject 主题 context 发送的内容 mail_type 邮件的格式 目前测试成功 plain 和 html
* output 发送成功与否
"""
sender = self.mail_host_user
msg = MIMEText(context, mail_type)
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = ";".join(receiver_list)
self.smtp.sendmail(sender, receiver_list, msg.as_string())
def close(self):
# 关闭建立的链接
self.smtp.close()
class MailHandler(object):
def __init__(self):
pass
def send_mail_message(self, to_user, msg, error=0):
"""
* desc 发送错误邮件
* input 要发送的人 发送的消息 错误还是告警
* output 0 发送成功 1 发送失败
"""
subject = settings.MSUBMAIL
if error:
text_content = 'Virtual Manager Error'
else:
text_content = 'Virtual Manager Warning'
from_email = settings.FMAIL
try:
to = [str(user) + "@hujiang.com" for user in to_user.split(',')]
print(to)
content_msg = EmailMultiAlternatives(
subject, text_content, from_email, to)
html_content = u'<b>' + msg + '</b>'
content_msg.attach_alternative(html_content, 'text/html')
content_msg.send()
return 0
except:
return 1<|fim▁end|> | msg['Subject'] = subject
msg['From'] = sender
msg['To'] = ";".join(receiver_list)
self.smtp.sendmail(sender, receiver_list, msg.as_string()) |
<|file_name|>bitcoin_es_CL.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="es_CL" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About Keplercoin</source>
<translation>Sobre Keplercoin</translation>
</message>
<message>
<location line="+39"/>
<source><b>Keplercoin</b> version</source>
<translation><b>Keplercoin</b> - versión </translation>
</message>
<message>
<location line="+57"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source>
<translation>
Este es un software experimental.
Distribuido bajo la licencia MIT/X11, vea el archivo adjunto
COPYING o http://www.opensource.org/licenses/mit-license.php.
Este producto incluye software desarrollado por OpenSSL Project para su uso en
el OpenSSL Toolkit (http://www.openssl.org/), software criptográfico escrito por
Eric Young ([email protected]) y UPnP software escrito por Thomas Bernard.</translation>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The Keplercoin developers</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Guia de direcciones</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>Haz doble clic para editar una dirección o etiqueta</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Crea una nueva dirección</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Copia la dirección seleccionada al portapapeles</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>&Nueva dirección</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your Keplercoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation>Estas son tus direcciones Keplercoin para recibir pagos. Puedes utilizar una diferente por cada persona emisora para saber quien te está pagando.</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation>&Copia dirección</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>Mostrar Código &QR </translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a Keplercoin address</source>
<translation>Firmar un mensaje para provar que usted es dueño de esta dirección</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>Firmar Mensaje</translation>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation>Exportar los datos de la pestaña actual a un archivo</translation>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified Keplercoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Borrar</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your Keplercoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation>Copia &etiqueta</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>&Editar</translation>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>Exporta datos de la guia de direcciones</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Archivos separados por coma (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Exportar errores</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>No se pudo escribir al archivo %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Etiqueta</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Dirección</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(sin etiqueta)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Introduce contraseña actual </translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Nueva contraseña</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Repite nueva contraseña:</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+33"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Introduce la nueva contraseña para la billetera.<br/>Por favor utiliza un contraseña <b>de 10 o mas caracteres aleatorios</b>, u <b>ocho o mas palabras</b>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Codificar billetera</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Esta operación necesita la contraseña para desbloquear la billetera.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Desbloquea billetera</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Esta operación necesita la contraseña para decodificar la billetara.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Decodificar cartera</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Cambia contraseña</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Introduce la contraseña anterior y la nueva de cartera</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Confirma la codificación de cartera</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR SAFFRONCOINS</b>!</source>
<translation>Atención: ¡Si codificas tu billetera y pierdes la contraseña perderás <b>TODOS TUS SAFFRONCOINS</b>!</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>¿Seguro que quieres seguir codificando la billetera?</translation>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Precaucion: Mayúsculas Activadas</translation>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>Billetera codificada</translation>
</message>
<message>
<location line="-56"/>
<source>Keplercoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your keplercoins from being stolen by malware infecting your computer.</source>
<translation>Keplercoin se cerrará para finalizar el proceso de encriptación. Recuerde que encriptar su billetera no protegera completatamente sus keplercoins de ser robados por malware que infecte su computador</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Falló la codificación de la billetera</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>La codificación de la billetera falló debido a un error interno. Tu billetera no ha sido codificada.</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>Las contraseñas no coinciden.</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>Ha fallado el desbloqueo de la billetera</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>La contraseña introducida para decodificar la billetera es incorrecta.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Ha fallado la decodificación de la billetera</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>La contraseña de billetera ha sido cambiada con éxito.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation>Firmar &Mensaje...</translation>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation>Sincronizando con la red...</translation>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation>&Vista general</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Muestra una vista general de la billetera</translation>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation>&Transacciónes</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Explora el historial de transacciónes</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Edita la lista de direcciones y etiquetas almacenadas</translation>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Muestra la lista de direcciónes utilizadas para recibir pagos</translation>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation>&Salir</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Salir del programa</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about Keplercoin</source>
<translation>Muestra información acerca de Keplercoin</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>Acerca de</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Mostrar Información sobre QT</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Opciones</translation>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation>&Codificar la billetera...</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>&Respaldar billetera...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>&Cambiar la contraseña...</translation>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-347"/>
<source>Send coins to a Keplercoin address</source>
<translation>Enviar monedas a una dirección keplercoin</translation>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for Keplercoin</source>
<translation>Modifica las opciones de configuración de keplercoin</translation>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation>Respaldar billetera en otra ubicación</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Cambiar la contraseña utilizada para la codificación de la billetera</translation>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>Keplercoin</source>
<translation>Keplercoin</translation>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation>Cartera</translation>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>&About Keplercoin</source>
<translation>&Sobre Keplercoin</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>&Mostrar/Ocultar</translation>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your Keplercoin addresses to prove you own them</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified Keplercoin addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>&Archivo</translation>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation>&Configuración</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>&Ayuda</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>Barra de pestañas</translation>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation>[red-de-pruebas]</translation>
</message>
<message>
<location line="+47"/>
<source>Keplercoin client</source>
<translation>Cliente Keplercoin</translation>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to Keplercoin network</source>
<translation><numerusform>%n conexión activa hacia la red Keplercoin</numerusform><numerusform>%n conexiones activas hacia la red Keplercoin</numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+70"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-140"/>
<source>Up to date</source>
<translation>Actualizado</translation>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation>Recuperando...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation>Transacción enviada</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>Transacción entrante</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Fecha: %1
Cantidad: %2
Tipo: %3
Dirección: %4</translation>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid Keplercoin address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>La billetera esta <b>codificada</b> y actualmente <b>desbloqueda</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>La billetera esta <b>codificada</b> y actualmente <b>bloqueda</b></translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. Keplercoin can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Editar dirección</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Etiqueta</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>La etiqueta asociada con esta entrada de la libreta de direcciones</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Dirección</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation>La dirección asociada con esta entrada en la libreta de direcciones. Solo puede ser modificada para direcciónes de envío.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>Nueva dirección para recibir</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Nueva dirección para enviar</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Editar dirección de recepción</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Editar dirección de envio</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>La dirección introducida "%1" ya esta guardada en la libreta de direcciones.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid Keplercoin address.</source>
<translation>La dirección introducida "%1" no es una dirección Keplercoin valida.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>No se pudo desbloquear la billetera.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>La generación de nueva clave falló.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>Keplercoin-Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>versión</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Uso:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>UI opciones</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Arranca minimizado
</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Opciones</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Principal</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>Comisión de &transacciónes</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start Keplercoin after logging in to the system.</source>
<translation>Inicia Keplercoin automáticamente despues de encender el computador</translation>
</message>
<message>
<location line="+3"/>
<source>&Start Keplercoin on system login</source>
<translation>&Inicia Keplercoin al iniciar el sistema</translation>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Automatically open the Keplercoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Abre automáticamente el puerto del cliente Keplercoin en el router. Esto funciona solo cuando tu router es compatible con UPnP y está habilitado.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Direcciona el puerto usando &UPnP</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the Keplercoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation>Conecta a la red Keplercoin a través de un proxy SOCKS (ej. cuando te conectas por la red Tor)</translation>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation>&Conecta a traves de un proxy SOCKS:</translation>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>&IP Proxy:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>Dirección IP del servidor proxy (ej. 127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Puerto:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Puerto del servidor proxy (ej. 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Muestra solo un ícono en la bandeja después de minimizar la ventana</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Minimiza a la bandeja en vez de la barra de tareas</translation>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation>Minimiza la ventana en lugar de salir del programa cuando la ventana se cierra. Cuando esta opción esta activa el programa solo se puede cerrar seleccionando Salir desde el menu.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>M&inimiza a la bandeja al cerrar</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>&Mostrado</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting Keplercoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>&Unidad en la que mostrar cantitades:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Elige la subdivisión por defecto para mostrar cantidaded en la interfaz cuando se envien monedas</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show Keplercoin addresses in the transaction list or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>&Muestra direcciones en el listado de transaccioines</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation>Atención</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting Keplercoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Formulario</translation>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Keplercoin network after a connection is established, but this process has not completed yet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation>Saldo:</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>No confirmados:</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation>Cartera</translation>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source><|fim▁hole|> <message>
<location line="-101"/>
<source>Your current balance</source>
<translation>Tu saldo actual</translation>
</message>
<message>
<location line="+29"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>Total de transacciones que no han sido confirmadas aun, y que no cuentan para el saldo actual.</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start keplercoin: click-to-pay handler</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>Solicitar Pago</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Cantidad:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Etiqueta</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Mensaje:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>&Guardar Como...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>Imágenes PNG (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+339"/>
<source>N/A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Show the Keplercoin-Qt help message to get a list with possible Keplercoin command-line options.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-104"/>
<source>Keplercoin - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Keplercoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Open the Keplercoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the Keplercoin RPC console.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+124"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Enviar monedas</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation>Enviar a múltiples destinatarios</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>&Agrega destinatario</translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation>Remover todos los campos de la transacción</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>&Borra todos</translation>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation>Balance:</translation>
</message>
<message>
<location line="+10"/>
<source>123.456 BTC</source>
<translation>123.456 BTC</translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>Confirma el envio</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>&Envía</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> to %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Confirmar el envio de monedas</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>Estas seguro que quieres enviar %1?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation>y</translation>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>La dirección de destinatarion no es valida, comprueba otra vez.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>La cantidad por pagar tiene que ser mayor 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>La cantidad sobrepasa tu saldo.</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>El total sobrepasa tu saldo cuando se incluyen %1 como tasa de envio.</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Tienes una dirección duplicada, solo puedes enviar a direcciónes individuales de una sola vez.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>Error: La transacción fue rechazada. Esto puede haber ocurrido si alguna de las monedas ya estaba gastada o si ha usado una copia de wallet.dat y las monedas se gastaron en la copia pero no se han marcado como gastadas aqui.</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>Envio</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>Cantidad:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>&Pagar a:</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Introduce una etiqueta a esta dirección para añadirla a tu guia</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>&Etiqueta:</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>Elije dirección de la guia</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>Pega dirección desde portapapeles</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation>Elimina destinatario</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a Keplercoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>Introduce una dirección Keplercoin (ej. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation>&Firmar Mensaje</translation>
</message>
<message>
<location line="+6"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>Introduce una dirección Keplercoin (ej. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation>Elije dirección de la guia</translation>
</message>
<message>
<location line="-203"/>
<location line="+213"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-203"/>
<source>Paste address from clipboard</source>
<translation>Pega dirección desde portapapeles</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation>Escriba el mensaje que desea firmar</translation>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this Keplercoin address</source>
<translation>Firmar un mensjage para probar que usted es dueño de esta dirección</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>&Borra todos</translation>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>Introduce una dirección Keplercoin (ej. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified Keplercoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a Keplercoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>Introduce una dirección Keplercoin (ej. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Click en "Firmar Mensage" para conseguir firma</translation>
</message>
<message>
<location line="+3"/>
<source>Enter Keplercoin signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+25"/>
<source>The Keplercoin developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation>[red-de-pruebas]</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation>Abierto hasta %1</translation>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation>%1/fuera de linea</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/no confirmado</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 confirmaciónes</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>Estado</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Fecha</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Generado</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>De</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>etiqueta</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Credito</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>no aceptada</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Debito</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Comisión transacción</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Cantidad total</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Mensaje</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Comentario</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>ID de Transacción</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation>Las monedas generadas deben esperar 120 bloques antes de ser gastadas. Cuando has generado este bloque se emitió a la red para ser agregado en la cadena de bloques. Si falla al incluirse en la cadena, cambiará a "no aceptado" y las monedas no se podrán gastar. Esto puede ocurrir ocasionalmente si otro nodo genera un bloque casi al mismo tiempo que el tuyo.</translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Transacción</translation>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Cantidad</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>, no ha sido emitido satisfactoriamente todavía</translation>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation>desconocido</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Detalles de transacción</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Esta ventana muestra información detallada sobre la transacción</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation>Fecha</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Tipo</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Dirección</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Cantidad</translation>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation>Abierto hasta %1</translation>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation>Fuera de linea (%1 confirmaciónes)</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>No confirmado (%1 de %2 confirmaciónes)</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Confirmado (%1 confirmaciones)</translation>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Este bloque no ha sido recibido por otros nodos y probablemente no sea aceptado !</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Generado pero no acceptado</translation>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation>Recibido con</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Recibido de</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Enviado a</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Pagar a usted mismo</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Minado</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(n/a)</translation>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Estado de transacción. Pasa el raton sobre este campo para ver el numero de confirmaciónes.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Fecha y hora cuando se recibió la transaccion</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Tipo de transacción.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Dirección de destino para la transacción</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Cantidad restada o añadida al balance</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation>Todo</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Hoy</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Esta semana</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Esta mes</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Mes pasado</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Este año</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Rango...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Recibido con</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Enviado a</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>A ti mismo</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Minado</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Otra</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Introduce una dirección o etiqueta para buscar</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Cantidad minima</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Copia dirección</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Copia etiqueta</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Copiar Cantidad</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Edita etiqueta</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation>Exportar datos de transacción</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Archivos separados por coma (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Confirmado</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Fecha</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Tipo</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Etiqueta</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Dirección</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Cantidad</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>Error exportando</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>No se pudo escribir en el archivo %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Rango:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>para</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation>Enviar monedas</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation>Exportar los datos de la pestaña actual a un archivo</translation>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+94"/>
<source>Keplercoin version</source>
<translation>Versión Keplercoin</translation>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation>Uso:</translation>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or keplercoind</source>
<translation>Envia comando a keplercoin lanzado con -server u keplercoind
</translation>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation>Muestra comandos
</translation>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation>Recibir ayuda para un comando
</translation>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation>Opciones:
</translation>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: keplercoin.conf)</source>
<translation>Especifica archivo de configuración (predeterminado: keplercoin.conf)
</translation>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: keplercoind.pid)</source>
<translation>Especifica archivo pid (predeterminado: keplercoin.pid)
</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Especifica directorio para los datos
</translation>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 8333 or testnet: 18333)</source>
<translation>Escuchar por conecciones en <puerto> (Por defecto: 8333 o red de prueba: 18333)</translation>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Mantener al menos <n> conecciones por cliente (por defecto: 125) </translation>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Umbral de desconección de clientes con mal comportamiento (por defecto: 100)</translation>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 8332 or testnet: 18332)</source>
<translation>Escucha conexiones JSON-RPC en el puerto <port> (predeterminado: 8332 or testnet: 18332)</translation>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Aceptar comandos consola y JSON-RPC
</translation>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Correr como demonio y acepta comandos
</translation>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation>Usa la red de pruebas
</translation>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=keplercoinrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "Keplercoin Alert" [email protected]
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. Keplercoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>Precaución: -paytxfee es muy alta. Esta es la comisión que pagarás si envias una transacción.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong Keplercoin will not work properly.</source>
<translation>Precaución: Por favor revise que la fecha y hora de tu ordenador son correctas. Si tu reloj está mal configurado Keplercoin no funcionará correctamente.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation>Conecta solo al nodo especificado
</translation>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-76"/>
<source>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation>Dirección -tor invalida: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation>Adjuntar informacion extra de depuracion. Implies all other -debug* options</translation>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp</source>
<translation>Anteponer salida de depuracion con marca de tiempo</translation>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the Keplercoin Wiki for SSL setup instructions)</source>
<translation>Opciones SSL: (ver la Keplercoin Wiki para instrucciones de configuración SSL)</translation>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Enviar informacion de seguimiento a la consola en vez del archivo debug.log</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>Enviar informacion de seguimiento al depurador</translation>
</message>
<message>
<location line="+5"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Especifica tiempo de espera para conexion en milisegundos (predeterminado: 5000)</translation>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Intenta usar UPnP para mapear el puerto de escucha (default: 0)</translation>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Intenta usar UPnP para mapear el puerto de escucha (default: 1 when listening)</translation>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation>Usuario para las conexiones JSON-RPC
</translation>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation>Contraseña para las conexiones JSON-RPC
</translation>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Permite conexiones JSON-RPC desde la dirección IP especificada
</translation>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Envia comando al nodo situado en <ip> (predeterminado: 127.0.0.1)
</translation>
</message>
<message>
<location line="-120"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation>Actualizar billetera al formato actual</translation>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Ajusta el numero de claves en reserva <n> (predeterminado: 100)
</translation>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Rescanea la cadena de bloques para transacciones perdidas de la cartera
</translation>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Usa OpenSSL (https) para las conexiones JSON-RPC
</translation>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Certificado del servidor (Predeterminado: server.cert)
</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Clave privada del servidor (Predeterminado: server.pem)
</translation>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Cifrados aceptados (Predeterminado: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)
</translation>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation>Este mensaje de ayuda
</translation>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>No es posible escuchar en el %s en este ordenador (bind returned error %d, %s)</translation>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation>Conecta mediante proxy socks</translation>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Permite búsqueda DNS para addnode y connect
</translation>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation>Cargando direcciónes...</translation>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Error cargando wallet.dat: Billetera corrupta</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of Keplercoin</source>
<translation>Error cargando wallet.dat: Billetera necesita una vercion reciente de Keplercoin</translation>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart Keplercoin to complete</source>
<translation>La billetera necesita ser reescrita: reinicie Keplercoin para completar</translation>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation>Error cargando wallet.dat</translation>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Dirección -proxy invalida: '%s'</translation>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Cantidad inválida para -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation>Cantidad inválida</translation>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation>Fondos insuficientes</translation>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation>Cargando el index de bloques...</translation>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Agrega un nodo para conectarse and attempt to keep the connection open</translation>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. Keplercoin is probably already running.</source>
<translation>No es posible escuchar en el %s en este ordenador. Probablemente Keplercoin ya se está ejecutando.</translation>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Comisión por kB para adicionarla a las transacciones enviadas</translation>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation>Cargando cartera...</translation>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation>Rescaneando...</translation>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation>Carga completa</translation>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation>Error</translation>
</message>
<message>
<location line="-31"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation type="unfinished"/>
</message>
</context>
</TS><|fim▁end|> | <translation><b>Transacciones recientes</b></translation>
</message> |
<|file_name|>ex2-18.cc<|end_file_name|><|fim▁begin|>#include <iostream>
int main(int argc, char const *argv[])
{
int i = 5, i2 = 20;
int *ptr1 = &i, *ptr2 = &i;<|fim▁hole|> std::cout << i << " " << i2 << std::endl;
std::cout << *ptr1 << " " << *ptr2 << std::endl;
return 0;
}<|fim▁end|> | ptr1 = &i2;
*ptr2 = 10; |
<|file_name|>ImageSlider.js<|end_file_name|><|fim▁begin|>// @flow
import React, { type Node, Component } from 'react';
import {
Image,
View,
ScrollView,
StyleSheet,
TouchableHighlight,
TouchableOpacity,
Dimensions,
} from 'react-native';
const reactNativePackage = require('react-native/package.json');
const splitVersion = reactNativePackage.version.split('.');
const majorVersion = +splitVersion[0];
const minorVersion = +splitVersion[1];
type Slide = {
index: number,
style?: any,
width?: number,
item?: any,
};
type PropsType = {
images: Array<number | string>,
style?: any,
loop?: boolean,
loopBothSides?: boolean,
autoPlayWithInterval?: number,
position?: number,
onPositionChanged?: number => void,
onPress?: Object => void,
customButtons?: (number, (number, animated?: boolean) => void) => Node,
customSlide?: Slide => Node,
imagesWidth: number
};
type StateType = {
position: number,
width: number,
interval: any,
onPositionChangedCalled: boolean,
};
class ImageSlider extends Component<PropsType, StateType> {
state = {
position: 0,
width: Dimensions.get('window').width,
onPositionChangedCalled: false,
interval: null,
};
_ref = null;
_panResponder = {};
_onRef = (ref: any) => {
this._ref = ref;
if (ref && this.state.position !== this._getPosition()) {
this._move(this._getPosition());
}
};
// In iOS you can pop view by swiping left, with active ScrollView
// you can't do that. This View on top of ScrollView enables call of
// pop function.
_popHelperView = () =>
!this.props.loopBothSides &&
this._getPosition() === 0 && (
<View style={{ position: 'absolute', width: 50, height: '100%' }} />
);
_move = (index: number, animated: boolean = true, autoCalled: boolean = true) => {
if (!this.autoPlayFlag && autoCalled) {
return;
}
const isUpdating = index !== this._getPosition();
const x = (this.props.imagesWidth ?
this.props.imagesWidth : Dimensions.get("window").width)
* index;
this._ref && this._ref.scrollTo({ y: 0, x, animated });
this.setState({ position: index });
if (
isUpdating &&
this.props.onPositionChanged &&
index < this.props.images.length &&
index > -1
) {
this.props.onPositionChanged(index);
this.setState({ onPositionChangedCalled: true });
}
this._setInterval();
};
_getPosition() {
if (typeof this.props.position === 'number') {
return this.props.position % this.props.images.length;
}
return this.state.position % this.props.images.length;
}
componentDidUpdate(prevProps: Object) {
const { position, autoPlayFlag } = this.props;
this.autoPlayFlag = autoPlayFlag;
if (position && prevProps.position !== position) {
this._move(position);
}
}
_clearInterval = () =>
this.state.interval && clearInterval(this.state.interval);
_setInterval = () => {
this._clearInterval();
const { autoPlayWithInterval, images, loop, loopBothSides } = this.props;
if (autoPlayWithInterval) {
this.setState({
interval: setInterval(
() =>
this._move(
!(loop || loopBothSides) &&
this.state.position === images.length - 1
? 0
: this.state.position + 1,
),
autoPlayWithInterval,
),
});
}
};
_handleScroll = (event: Object) => {
const { position, width } = this.state;
const { loop, loopBothSides, images, onPositionChanged } = this.props;
const { x } = event.nativeEvent.contentOffset;
if (
(loop || loopBothSides) &&
x.toFixed() >= +(width * images.length).toFixed()
) {
return this._move(0, false);
} else if (loopBothSides && x.toFixed() <= +(-width).toFixed()) {
return this._move(images.length - 1, false);
}
let newPosition = 0;
if (position !== -1 && position !== images.length) {
newPosition = Math.round(event.nativeEvent.contentOffset.x / width);
this.setState({ position: newPosition });
}
if (
onPositionChanged &&
!this.state.onPositionChangedCalled &&
newPosition < images.length &&
newPosition > -1
) {
onPositionChanged(newPosition);
} else {
this.setState({ onPositionChangedCalled: false });
}
this._setInterval();
};
componentDidMount() {
this._setInterval();
}
componentWillUnmount() {
this._clearInterval();
}
_onLayout = () => {
this.setState({ width: Dimensions.get('window').width });
this._move(this.state.position, false);
};
_renderImage = (image: any, index: number) => {
const { width } = Dimensions.get('window');
const { onPress, customSlide } = this.props;
const offset = { marginLeft: index === -1 ? -width : 0 };
const imageStyle = [styles.image, { width }, offset];
if (customSlide) {
return customSlide({ item: image, style: imageStyle, index, width });
}
const imageObject = typeof image === 'string' ? { uri: image } : image;
const imageComponent = (
<Image key={index} source={imageObject} style={[imageStyle]} />
);
if (onPress) {
return (
<TouchableOpacity
key={index}
style={[imageStyle, offset]}
onPress={() => onPress && onPress({ image, index })}
delayPressIn={200}
>
{imageComponent}
</TouchableOpacity>
);
}
return imageComponent;
};
// We make shure, that, when loop is active,
// fake images at the begin and at the end of ScrollView
// do not scroll.
_scrollEnabled = (position: number) =>
position !== -1 && position !== this.props.images.length;
moveNext = () => {
const next = (this.state.position + 1) % this.props.images.length;
this._move(next, true, false);
}
movePrev = () => {
const prev = (this.state.position + this.props.images.length - 1) % this.props.images.length;
this._move(prev, true, false);
}
render() {
const {
onPress,
customButtons,
style,
loop,
images,
loopBothSides,
} = this.props;
const position = this._getPosition();
const scrollEnabled = this._scrollEnabled(position);
return (
<View style={[styles.container, style]} onLayout={this._onLayout}>
<ScrollView
onLayout={this._onLayout}<|fim▁hole|> pagingEnabled={true}
bounces={loopBothSides}
contentInset={loopBothSides ? { left: this.state.width } : {}}
horizontal={true}
scrollEnabled={scrollEnabled}
showsHorizontalScrollIndicator={false}
style={[styles.scrollViewContainer, style]}
>
{loopBothSides && this._renderImage(images[images.length - 1], -1)}
{images.map(this._renderImage)}
{(loop || loopBothSides) &&
this._renderImage(images[0], images.length)}
</ScrollView>
{customButtons ? (
customButtons(position, this._move)
) : (
<View style={styles.buttons}>
{this.props.images.map((image, index) => (
<TouchableHighlight
key={index}
underlayColor="#ccc"
onPress={() => this._move(index)}
style={[
styles.button,
position === index && styles.buttonSelected,
]}
>
<View />
</TouchableHighlight>
))}
</View>
)}
{this._popHelperView()}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
scrollViewContainer: {
flexDirection: 'row',
backgroundColor: '#222',
},
image: {
width: 200,
height: '100%',
},
buttons: {
height: 15,
marginTop: -15,
justifyContent: 'center',
alignItems: 'center',
flexDirection: 'row',
},
button: {
margin: 3,
width: 8,
height: 8,
borderRadius: 8 / 2,
backgroundColor: '#ccc',
opacity: 0.9,
},
buttonSelected: {
opacity: 1,
backgroundColor: '#fff',
},
});
export default ImageSlider;<|fim▁end|> | ref={ref => this._onRef(ref)}
onMomentumScrollEnd={this._handleScroll}
scrollEventThrottle={16} |
<|file_name|>config.js<|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/. */
"use strict";
var convict = require('convict');
var format = require('util').format;
var getHashes = require('crypto').getHashes;
var path = require('path');
var fs = require('fs');
/**
* Validates the keys are present in the configuration object.
*
* @param {List} keys A list of keys that must be present.
* @param {Boolean} options List of options to use.
**/
function validateKeys(keys, options) {
options = options || {};
var optional = options.optional || false;
return function(val) {
if (JSON.stringify(val) === "{}" && optional === true) {
return;
}
if (!optional && !val)
throw new Error("Should be defined");
keys.forEach(function(key) {
if (!val.hasOwnProperty(key))
throw new Error(format("Should have a %s property", key));
});
};
}
/**
* Build a validator that makes sure of the size and hex format of a key.
*
* @param {Integer} size Number of bytes of the key.
**/
function hexKeyOfSize(size) {
return function check(val) {
if (val === "")
return;
if (!new RegExp(format('^[a-fA-FA0-9]{%d}$', size * 2)).test(val)) {
throw new Error("Should be an " + size +
" bytes key encoded as hexadecimal");
}
};
}
/**
* Validates that each channel has an apiKey and apiSecret as well as
* an optional apiUrl and nothing else. Alse make sure the default
* channel is defined.
**/
function tokBoxCredentials(credentials) {
if (!credentials.hasOwnProperty("default")) {
throw new Error("Please define the default TokBox channel credentials.");
}
var authorizedKeys = ["apiKey", "apiSecret", "apiUrl"];
function checkKeys(key) {
if (authorizedKeys.indexOf(key) === -1) {
throw new Error(key + " configuration value is unknown. " +
"Should be one of " + authorizedKeys.join(", ") + ".");
}
}
for (var channel in credentials) {
// Verify channel keys validity.
Object.keys(credentials[channel]).forEach(checkKeys);
if (!credentials[channel].hasOwnProperty("apiKey")) {
throw new Error(channel + " channel should define an apiKey.");
}
if (!credentials[channel].hasOwnProperty("apiSecret")) {
throw new Error(channel + " channel should define an apiSecret.");
}
}
}
var conf = convict({
env: {
doc: "The applicaton environment.",
format: [ "dev", "test", "stage", "prod", "loadtest"],
default: "dev",
env: "NODE_ENV"
},
ip: {
doc: "The IP address to bind.",
format: "ipaddress",
default: "127.0.0.1",
env: "IP_ADDRESS"
},
port: {
doc: "The port to bind.",
format: "port",
default: 5000,
env: "PORT"
},
acceptBacklog: {
doc: "The maximum length of the queue of pending connections",
format: Number,
default: 511,
env: "ACCEPT_BACKLOG"
},
publicServerAddress: {
doc: "The public-facing server address",
format: String,
default: "localhost:5000",
env: "SERVER_ADDRESS"
},
protocol: {
doc: "The protocol the server is behind. Should be https behind an ELB.",
format: String,
default: "http",
env: "PROTOCOL"
},
macSecret: {
doc: "The secret for MAC tokens (32 bytes key encoded as hex)",
format: hexKeyOfSize(32),
default: "",
env: "MAC_SECRET"
},
encryptionSecret: {
doc: "The secret for encrypting tokens (16 bytes key encoded as hex)",
format: hexKeyOfSize(16),
default: "",
env: "ENCRYPTING_SECRET"
},
userMacSecret: {
doc: "The secret for hmac-ing userIds (16 bytes key encoded as hex)",
format: hexKeyOfSize(16),
default: "",
env: "USER_MAC_SECRET"
},
userMacAlgorithm: {
doc: "The algorithm that should be used to mac userIds",
format: function(val) {
if (getHashes().indexOf(val) === -1) {
throw new Error("Given hmac algorithm is not supported");
}
},
default: "sha256",
env: "USER_MAC_ALGORITHM"
},
calls: {
maxSubjectSize: {
doc: "The maximum number of chars for the subject of a call",
format: Number,
default: 124
}
},
callUrls: {
tokenSize: {
doc: "The callUrl token size (in bytes).",
format: Number,
default: 8
},
timeout: {
doc: "How much time a token is valid for (in hours)",
format: Number,
default: 24 * 30 // One month.
},
maxTimeout: {
doc: "The maximum number of hours a token can be valid for.",
format: Number,
default: 24 * 30
},
webAppUrl: {
doc: "Loop Web App Home Page.",
format: "url",
default: "http://localhost:3000/c/{token}",
env: "WEB_APP_URL"
}
},
displayVersion: {
doc: "Display the server version on the homepage.",
default: true,
format: Boolean
},
storage: {
engine: {
doc: "engine type",
format: String,
default: "redis"
},
settings: {
doc: "js object of options to pass to the storage engine",
format: Object,
default: {
port: 6379,
host: 'localhost'
}
}
},
filestorage: {
engine: {
doc: "engine type",
format: ["filesystem", "aws"],
default: "filesystem"
},
settings: {
doc: "js object of options to pass to the files engine",
format: Object,
default: {
base_dir: "/tmp"
}
}
},
pubsub: {
doc: "js object of options to pass to the pubsub engine",
format: Object,
default: {
port: 6379,
host: 'localhost'
}
},
fakeTokBox: {
doc: "Mock TokBox calls",
format: Boolean,
default: false
},
fakeTokBoxURL: {
doc: "URL where to Mock TokBox calls",
format: String,
default: "https://call.stage.mozaws.net/"
},
tokBox: {
apiUrl: {
doc: 'api endpoint for tokbox',
format: String,
default: "https://api.opentok.com"
},
credentials: {
doc: "api credentials based on a channel.",
format: tokBoxCredentials,
default: {}
},
tokenDuration: {
doc: 'how long api tokens are valid for in seconds',
format: "nat",
default: 24 * 3600
},
retryOnError: {
doc: 'how many times to retry on error',
format: "nat",
default: 3
},
timeout: {
doc: "Timeout for requests when trying to create the session (ms)",
format: Number,
default: 2000<|fim▁hole|> sentryDSN: {
doc: "Sentry DSN",
format: function(val) {
if (!(typeof val === "string" || val === false)) {
throw new Error("should be either a sentryDSN or 'false'");
}
},
default: false,
env: "SENTRY_DSN"
},
statsd: {
doc: "Statsd configuration",
format: validateKeys(['port', 'host'], {'optional': true}),
default: {}
},
statsdEnabled: {
doc: "Defines if statsd is enabled or not",
format: Boolean,
default: false
},
allowedOrigins: {
doc: "Authorized origins for cross-origin requests.",
format: Array,
default: ['http://localhost:3000']
},
retryAfter: {
doc: "Seconds to wait for on 503",
format: Number,
default: 30
},
fxaAudiences: {
doc: "List of accepted fxa audiences.",
format: Array,
default: []
},
fxaVerifier: {
doc: "The Firefox Accounts verifier url",
format: String,
env: "FXA_VERIFIER",
default: "https://verifier.accounts.firefox.com/v2"
},
fxaTrustedIssuers: {
doc: "The list of Firefox Accounts trusted issuers",
format: Array,
default: ["api.accounts.firefox.com"]
},
hawkIdSecret: {
doc: "The secret for hmac-ing the hawk id (16 bytes key encoded as hex)",
format: hexKeyOfSize(16),
default: "",
env: "HAWK_ID_SECRET"
},
hawkSessionDuration: {
doc: "The duration of hawk credentials (in seconds)",
format: Number,
default: 3600 * 24 * 30 // One month.
},
callDuration: {
doc: "The duration we want to store the call info (in seconds)",
format: Number,
default: 60
},
maxHTTPSockets: {
doc: "The maximum of HTTP sockets to use when doing requests",
format: Number,
default: 10000000
},
heartbeatTimeout: {
doc: "Timeout for requests when doing heartbeat checks (ms)",
format: Number,
default: 2000
},
timers: {
supervisoryDuration: {
doc: "Websocket timeout for the supervisory timer (seconds)",
format: Number,
default: 10
},
ringingDuration: {
doc: "Websocket timeout for the ringing timer (seconds)",
format: Number,
default: 30
},
connectionDuration: {
doc: "Websocket timeout for the connection timer (seconds)",
format: Number,
default: 10
}
},
progressURLEndpoint: {
doc: "The endpoint to use for the progressURL.",
format: String,
default: "/websocket"
},
i18n: {
defaultLang: {
format: String,
default: 'en-US'
}
},
pushServerURIs: {
doc: "An array of push server URIs",
format: Array,
default: ["wss://push.services.mozilla.com/"]
},
fxaOAuth: {
activated: {
doc: "Set to false if you want to deactivate FxA-OAuth on this instance.",
format: Boolean,
default: true
},
client_id: {
doc: "The FxA client_id (8 bytes key encoded as hex)",
format: hexKeyOfSize(8),
default: ""
},
client_secret: {
doc: "The FxA client secret (32 bytes key encoded as hex)",
format: hexKeyOfSize(32),
default: ""
},
oauth_uri: {
doc: "The location of the FxA OAuth server.",
format: "url",
default: "https://oauth.accounts.firefox.com/v1"
},
content_uri: {
doc: "The location of the FxA content server.",
format: "url",
default: "https://accounts.firefox.com"
},
redirect_uri: {
doc: "The redirect_uri.",
format: String,
default: "urn:ietf:wg:oauth:2.0:fx:webchannel"
},
profile_uri: {
doc: "The FxA profile uri.",
format: "url",
default: "https://profile.firefox.com/v1"
},
scope: {
doc: "The scope we're requesting access to",
format: String,
default: "profile"
}
},
logRequests: {
activated: {
doc: "Defines if requests should be logged to Stdout",
default: false,
format: Boolean
},
consoleDateFormat: {
doc: "Date format of the logging line.",
format: String,
default: "%y/%b/%d %H:%M:%S"
}
},
hekaMetrics: {
activated: {
doc: "Defines if metrics should be directed to hekad",
default: false,
format: Boolean
},
debug: {
doc: "Heka logger display development logs",
format: Boolean,
default: false
},
level: {
doc: "Log level.",
format: String,
default: "INFO"
},
fmt: {
doc: "Log level.",
format: String,
default: "heka"
}
},
newRelic: {
activated: {
doc: "Defines if newrelic is activated or not",
default: false,
format: Boolean
},
licenceKey: {
doc: "New Relic licence key",
format: String,
default: ""
},
loggingLevel: {
doc: "Logging level to use",
format: String,
default: "info"
},
appName: {
doc: "New Relic application name",
format: String,
default: "Loop Server"
}
},
dumpHeap: {
activated: {
doc: "Defines if uncaught exceptions should dump snapshots",
default: true,
format: Boolean
},
location: {
doc: "Location where to output the files (directory).",
format: String,
default: '/tmp'
}
},
rooms: {
defaultTTL: {
doc: "The default TTL for a room (in hours)",
format: Number,
default: 8 * 7 * 24 // 8 weeks
},
maxTTL: {
doc: "The maximum TTL for a room (in hours) allowed by the server",
format: Number,
default: 8 * 7 * 24 // 8 weeks
},
extendTTL: {
doc: "The new TTL for a room (in hours) after a participant join.",
format: Number,
default: 8 * 7 * 24 // 8 weeks
},
participantTTL: {
doc: "The TTL (in seconds) for a participant in the room",
format: Number,
default: 5 * 60 // 5 minutes
},
deletedTTL: {
doc: "The TTL (in seconds) for a room delete notification to be saved",
format: Number,
default: 27 * 60 // 27 minutes
},
maxSize: {
doc: "The maximum size of a room",
format: Number,
default: 5
},
maxRoomNameSize: {
doc: "The maximum number of chars to name a room",
format: Number,
default: 100
},
maxRoomOwnerSize: {
doc: "The maximum number of chars for the owner of a room",
format: Number,
default: 255
},
tokenSize: {
doc: "The room token size (in bytes).",
format: Number,
default: 8
},
webAppUrl: {
doc: "Loop Web App rooms url.",
format: "url",
default: "http://localhost:3000/{token}",
env: "ROOMS_WEB_APP_URL"
},
HKDFSalt: {
doc: "The salt that will be used to cipher profile data " +
"(16 bytes key encoded as hex)",
format: hexKeyOfSize(16),
default: "",
env: "ROOMS_HKDF_SECRET"
}
},
ga: {
activated: {
doc: "Should we send POST /events data to Google Analytics while true.",
default: false,
format: Boolean
},
id: {
doc: "Google analytics ID.",
default: "",
format: String
}
}
});
// handle configuration files. you can specify a CSV list of configuration
// files to process, which will be overlayed in order, in the CONFIG_FILES
// environment variable. By default, the ../config/<env>.json file is loaded.
var envConfig = path.join(__dirname, '/../config', conf.get('env') + '.json');
var files = (envConfig + ',' + process.env.CONFIG_FILES)
.split(',')
.filter(fs.existsSync);
conf.loadFile(files);
conf.validate();
if (conf.get('macSecret') === "")
throw "Please define macSecret in your configuration file";
if (conf.get('rooms').HKDFSalt === "")
throw "Please define rooms.HKDFSalt in your configuration file";
if (conf.get('encryptionSecret') === "")
throw "Please define encryptionSecret in your configuration file";
if (conf.get('allowedOrigins') === "") {
throw "Please define the list of allowed origins for CORS.";
}
if (conf.get('fxaAudiences').length === 0) {
throw "Please define the list of allowed Firefox Accounts audiences";
}
if (conf.get('hawkSessionDuration') <
conf.get('callUrls').maxTimeout * 60 * 60) {
throw "hawkSessionDuration should be longer or equal to callUrls.maxTimeout";
}
if (conf.get('fxaOAuth').activated && conf.get('fxaOAuth').client_id === "") {
throw "fxaOAuth is activated but not well configured. " +
"Set fxaOAuth.activated config key to false to continue";
}
// Configure S3 the environment variable for tests.
if (conf.get('env') === 'test') {
process.env.AWS_ACCESS_KEY_ID = 'TESTME';
process.env.AWS_SECRET_ACCESS_KEY = 'TESTME';
}
// Verify timers
var timers = conf.get("timers");
var minCallDuration = timers.supervisoryDuration +
timers.ringingDuration +
timers.connectionDuration;
if (minCallDuration > conf.get("callDuration")) {
throw "the callDuration should be at least " + minCallDuration + " seconds";
}
module.exports = {
conf: conf,
hexKeyOfSize: hexKeyOfSize,
validateKeys: validateKeys
};<|fim▁end|> | }
}, |
<|file_name|>worker.js<|end_file_name|><|fim▁begin|>'use strict';
const async = require('async');
const getApp = require('../utils/utils.js').getApp;
module.exports = function(Worker) {
//Worker.validatesPresenceOf('title');
Worker.upsertItem = (data, cb) => {
let res = {};
getApp(Worker)
.then((app) => {
if (!!!data.person) cb({errCode: 'ERR_WORKER_NO_PERSON'});
if (!!!data.cargos || data.cargos.length === 0
) cb({errCode: 'ERR_WORKER_NO_CARGO'});
console.log(data);
return (!!!data.person.id ?
app.models.person.create(data.person) :
Promise.resolve(data.person)
)
.then((result) => {
res.person = result;
return app.models.worker.upsert({
personId: res.person.id
});
})
.then(results => {
res.worker = results;
res.cargoMapping = [];
return new Promise((resolve, reject) => async.each(data.cargos,
(cargoId, cbInner) => app.models.cargoMapping.create({
cargoId: cargoId,
workerId: res.worker.id
})
.then(r => cbInner(null, res.cargoMapping.push(r)))
.catch(err => async.each(res.cargoMapping,
(itemInner, cbInner2) => cbInner2(null, itemInner.destroy()),
err => cbInner({
errCode: 'ERR_WORKER_FAIL_CARGOS',
message: 'problem to save cargo in worker'
})
)),
err => !!err ? reject(err) : resolve(res)
));
})
.then(res => {
cb(null, res);<|fim▁hole|> .catch(err => {
if (!!res.person) res.person.destroy();
if (!!res.worker) res.worker.destroy();
cb({errCode: 'ERR_WORKER_NO_SAVE'});
});
});
};
Worker.remoteMethod('upsertItem', {
description: 'upsert client ',
http: {verb: 'post'},
accepts: {
arg: 'data',
type: 'object',
description: 'data from form to upsert client',
http: {source: 'body'},
required: true
},
returns: {
arg: 'res',
type: 'object',
root: true
}
});
};<|fim▁end|> | })
|
<|file_name|>sessions.py<|end_file_name|><|fim▁begin|>"""Mongodb implementations of repository sessions."""
# pylint: disable=no-init
# Numerous classes don't require __init__.
# pylint: disable=too-many-public-methods,too-few-public-methods
# Number of methods are defined in specification
# pylint: disable=protected-access
# Access to protected methods allowed in package mongo package scope
# pylint: disable=too-many-ancestors
# Inheritance defined in specification
from bson.objectid import ObjectId
from . import objects
from . import queries
from . import searches
from .. import MONGO_LISTENER
from .. import utilities
from ...abstract_osid.id.primitives import Id as ABCId
from ...abstract_osid.repository import sessions as abc_repository_sessions
from ...abstract_osid.repository.objects import AssetForm as ABCAssetForm
from ...abstract_osid.repository.objects import CompositionForm as ABCCompositionForm
from ...abstract_osid.repository.objects import RepositoryForm as ABCRepositoryForm
from ...abstract_osid.type.primitives import Type as ABCType
from ..id.objects import IdList
from ..list_utilities import move_id_ahead, move_id_behind, order_ids
from ..osid.sessions import OsidSession
from ..primitives import Id
from ..primitives import Type
from ..utilities import MongoClientValidated
from dlkit.abstract_osid.osid import errors
from dlkit.mongo.osid import sessions as osid_sessions
from dlkit.primordium.id.primitives import Id
DESCENDING = -1
ASCENDING = 1
CREATED = True
UPDATED = True
ENCLOSURE_RECORD_TYPE = Type(
identifier='enclosure',
namespace='osid-object',
authority='ODL.MIT.EDU')
CREATED = TrueUPDATED = True
COMPARATIVE = 0
PLENARY = 1
ACTIVE = 0
ANY_STATUS = 1
SEQUESTERED = 0
UNSEQUESTERED = 1
class AssetLookupSession(abc_repository_sessions.AssetLookupSession, osid_sessions.OsidSession):
"""This session defines methods for retrieving assets.
An ``Asset`` represents an element of content stored in a
Repository.
This lookup session defines several views:
* comparative view: elements may be silently omitted or re-ordered
* plenary view: provides a complete result set or is an error
condition
* isolated repository view: All asset methods in this session
operate, retrieve and pertain to assets defined explicitly in
the current repository. Using an isolated view is useful for
managing ``Assets`` with the ``AssetAdminSession.``
* federated repository view: All asset methods in this session
operate, retrieve and pertain to all assets defined in this
repository and any other assets implicitly available in this
repository through repository inheritence.
The methods ``use_federated_repository_view()`` and
``use_isolated_repository_view()`` behave as a radio group and one
should be selected before invoking any lookup methods.
Assets may have an additional records indicated by their respective
record types. The record may not be accessed through a cast of the
``Asset``.
"""
def __init__(self, catalog_id=None, proxy=None, runtime=None, **kwargs):
OsidSession.__init__(self)
self._catalog_class = objects.Repository
self._session_name = 'AssetLookupSession'
self._catalog_name = 'Repository'
OsidSession._init_object(
self,
catalog_id,
proxy,
runtime,
db_name='repository',
cat_name='Repository',
cat_class=objects.Repository)
self._kwargs = kwargs
def get_repository_id(self):
"""Gets the ``Repository`` ``Id`` associated with this session.
return: (osid.id.Id) - the ``Repository Id`` associated with
this session
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.resource.ResourceLookupSession.get_bin_id
return self._catalog_id
repository_id = property(fget=get_repository_id)
def get_repository(self):
"""Gets the ``Repository`` associated with this session.
return: (osid.repository.Repository) - the ``Repository``
associated with this session
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.resource.ResourceLookupSession.get_bin
return self._catalog
repository = property(fget=get_repository)
def can_lookup_assets(self):
"""Tests if this user can perform ``Asset`` lookups.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known all methods in this
session will result in a ``PermissionDenied``. This is intended
as a hint to an application that may opt not to offer lookup
operations.
return: (boolean) - ``false`` if lookup methods are not
authorized, ``true`` otherwise
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceLookupSession.can_lookup_resources
# NOTE: It is expected that real authentication hints will be
# handled in a service adapter above the pay grade of this impl.
return True
def use_comparative_asset_view(self):
"""The returns from the lookup methods may omit or translate elements based on this session, such as
authorization, and not result in an error.
This view is used when greater interoperability is desired at
the expense of precision.
*compliance: mandatory -- This method is must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceLookupSession.use_comparative_resource_view
self._use_comparative_object_view()
def use_plenary_asset_view(self):
"""A complete view of the ``Asset`` returns is desired.
Methods will return what is requested or result in an error.
This view is used when greater precision is desired at the
expense of interoperability.
*compliance: mandatory -- This method is must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceLookupSession.use_plenary_resource_view
self._use_plenary_object_view()
def use_federated_repository_view(self):
"""Federates the view for methods in this session.
A federated view will include assets in repositories which are
children of this repository in the repository hierarchy.
*compliance: mandatory -- This method is must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceLookupSession.use_federated_bin_view
self._use_federated_catalog_view()
def use_isolated_repository_view(self):
"""Isolates the view for methods in this session.
An isolated view restricts lookups to this repository only.
*compliance: mandatory -- This method is must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceLookupSession.use_isolated_bin_view
self._use_isolated_catalog_view()
@utilities.arguments_not_none
def get_asset(self, asset_id):
"""Gets the ``Asset`` specified by its ``Id``.
In plenary mode, the exact ``Id`` is found or a ``NotFound``
results. Otherwise, the returned ``Asset`` may have a different
``Id`` than requested, such as the case where a duplicate ``Id``
was assigned to an ``Asset`` and retained for compatibility.
arg: asset_id (osid.id.Id): the ``Id`` of the ``Asset`` to
retrieve
return: (osid.repository.Asset) - the returned ``Asset``
raise: NotFound - no ``Asset`` found with the given ``Id``
raise: NullArgument - ``asset_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceLookupSession.get_resource
# NOTE: This implementation currently ignores plenary view
collection = MongoClientValidated('repository',
collection='Asset',
runtime=self._runtime)
result = collection.find_one(
dict({'_id': ObjectId(self._get_id(asset_id, 'repository').get_identifier())},
**self._view_filter()))
return objects.Asset(result, runtime=self._runtime)
@utilities.arguments_not_none
def get_assets_by_ids(self, asset_ids):
"""Gets an ``AssetList`` corresponding to the given ``IdList``.
In plenary mode, the returned list contains all of the assets
specified in the ``Id`` list, in the order of the list,
including duplicates, or an error results if an ``Id`` in the
supplied list is not found or inaccessible. Otherwise,
inaccessible ``Assets`` may be omitted from the list and may
present the elements in any order including returning a unique
set.
arg: asset_ids (osid.id.IdList): the list of ``Ids`` to
retrieve
return: (osid.repository.AssetList) - the returned ``Asset
list``
raise: NotFound - an ``Id`` was not found
raise: NullArgument - ``asset_ids`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceLookupSession.get_resources_by_ids
# NOTE: This implementation currently ignores plenary view
collection = MongoClientValidated('repository',
collection='Asset',
runtime=self._runtime)
object_id_list = []
for i in asset_ids:
object_id_list.append(ObjectId(self._get_id(i, 'repository').get_identifier()))
result = collection.find(
dict({'_id': {'$in': object_id_list}},
**self._view_filter()))
result = list(result)
sorted_result = []
for object_id in object_id_list:
for object_map in result:
if object_map['_id'] == object_id:
sorted_result.append(object_map)
break
return objects.AssetList(sorted_result, runtime=self._runtime)
@utilities.arguments_not_none
def get_assets_by_genus_type(self, asset_genus_type):
"""Gets an ``AssetList`` corresponding to the given asset genus ``Type`` which does not include assets of types
derived from the specified ``Type``.
In plenary mode, the returned list contains all known assets or
an error results. Otherwise, the returned list may contain only
those assets that are accessible through this session.
arg: asset_genus_type (osid.type.Type): an asset genus type
return: (osid.repository.AssetList) - the returned ``Asset
list``
raise: NullArgument - ``asset_genus_type`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceLookupSession.get_resources_by_genus_type
# NOTE: This implementation currently ignores plenary view
collection = MongoClientValidated('repository',
collection='Asset',
runtime=self._runtime)
result = collection.find(
dict({'genusTypeId': str(asset_genus_type)},
**self._view_filter())).sort('_id', DESCENDING)
return objects.AssetList(result, runtime=self._runtime)
@utilities.arguments_not_none
def get_assets_by_parent_genus_type(self, asset_genus_type):
"""Gets an ``AssetList`` corresponding to the given asset genus ``Type`` and include any additional assets with
genus types derived from the specified ``Type``.
In plenary mode, the returned list contains all known assets or
an error results. Otherwise, the returned list may contain only
those assets that are accessible through this session.
arg: asset_genus_type (osid.type.Type): an asset genus type
return: (osid.repository.AssetList) - the returned ``Asset
list``
raise: NullArgument - ``asset_genus_type`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceLookupSession.get_resources_by_parent_genus_type
return objects.AssetList([])
@utilities.arguments_not_none
def get_assets_by_record_type(self, asset_record_type):
"""Gets an ``AssetList`` containing the given asset record ``Type``.
In plenary mode, the returned list contains all known assets or
an error results. Otherwise, the returned list may contain only
those assets that are accessible through this session.
arg: asset_record_type (osid.type.Type): an asset record type
return: (osid.repository.AssetList) - the returned ``Asset
list``
raise: NullArgument - ``asset_record_type`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceLookupSession.get_resources_by_record_type
# STILL NEED TO IMPLEMENT!!!
return objects.AssetList([])
@utilities.arguments_not_none
def get_assets_by_provider(self, resource_id):
"""Gets an ``AssetList`` from the given provider.
In plenary mode, the returned list contains all known assets or
an error results. Otherwise, the returned list may contain only
those assets that are accessible through this session.
arg: resource_id (osid.id.Id): a resource ``Id``
return: (osid.repository.AssetList) - the returned ``Asset
list``
raise: NullArgument - ``resource_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
raise errors.Unimplemented()
def get_assets(self):
"""Gets all ``Assets``.
In plenary mode, the returned list contains all known assets or
an error results. Otherwise, the returned list may contain only
those assets that are accessible through this session.
return: (osid.repository.AssetList) - a list of ``Assets``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceLookupSession.get_resources
# NOTE: This implementation currently ignores plenary view
collection = MongoClientValidated('repository',
collection='Asset',
runtime=self._runtime)
result = collection.find(self._view_filter()).sort('_id', DESCENDING)
return objects.AssetList(result, runtime=self._runtime)
assets = property(fget=get_assets)
class AssetQuerySession(abc_repository_sessions.AssetQuerySession, osid_sessions.OsidSession):
"""This session provides methods for searching among ``Asset`` objects.
The search query is constructed using the ``AssetQuery``.
This session defines views that offer differing behaviors for
searching.
* federated repository view: searches include assets in
repositories of which this repository is a ancestor in the
repository hierarchy
* isolated repository view: searches are restricted to assets in
this repository
Assets may have a query record indicated by their respective record
types. The query record is accessed via the ``AssetQuery``.
"""
def __init__(self, catalog_id=None, proxy=None, runtime=None, **kwargs):
OsidSession.__init__(self)
self._catalog_class = objects.Repository
self._session_name = 'AssetQuerySession'
self._catalog_name = 'Repository'
OsidSession._init_object(
self,
catalog_id,
proxy,
runtime,
db_name='repository',
cat_name='Repository',
cat_class=objects.Repository)
self._kwargs = kwargs
def get_repository_id(self):
"""Gets the ``Repository`` ``Id`` associated with this session.
return: (osid.id.Id) - the ``Repository Id`` associated with
this session
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.resource.ResourceLookupSession.get_bin_id
return self._catalog_id
repository_id = property(fget=get_repository_id)
def get_repository(self):
"""Gets the ``Repository`` associated with this session.
return: (osid.repository.Repository) - the ``Repository``
associated with this session
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.resource.ResourceLookupSession.get_bin
return self._catalog
repository = property(fget=get_repository)
def can_search_assets(self):
"""Tests if this user can perform ``Asset`` searches.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known all methods in this
session will result in a ``PermissionDenied``. This is intended
as a hint to an application that may opt not to offer search
operations to unauthorized users.
return: (boolean) - ``false`` if search methods are not
authorized, ``true`` otherwise
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceQuerySession.can_search_resources
# NOTE: It is expected that real authentication hints will be
# handled in a service adapter above the pay grade of this impl.
return True
def use_federated_repository_view(self):
"""Federates the view for methods in this session.
A federated view will include assets in repositories which are
children of this repository in the repository hierarchy.
*compliance: mandatory -- This method is must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceLookupSession.use_federated_bin_view
self._use_federated_catalog_view()
def use_isolated_repository_view(self):
"""Isolates the view for methods in this session.
An isolated view restricts lookups to this repository only.
*compliance: mandatory -- This method is must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceLookupSession.use_isolated_bin_view
self._use_isolated_catalog_view()
def get_asset_query(self):
"""Gets an asset query.
return: (osid.repository.AssetQuery) - the asset query
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceQuerySession.get_resource_query_template
return queries.AssetQuery(runtime=self._runtime)
asset_query = property(fget=get_asset_query)
@utilities.arguments_not_none
def get_assets_by_query(self, asset_query):
"""Gets a list of ``Assets`` matching the given asset query.
arg: asset_query (osid.repository.AssetQuery): the asset
query
return: (osid.repository.AssetList) - the returned ``AssetList``
raise: NullArgument - ``asset_query`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
raise: Unsupported - the ``asset_query`` is not of this service
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceQuerySession.get_resources_by_query
and_list = list()
or_list = list()
for term in asset_query._query_terms:
and_list.append({term: asset_query._query_terms[term]})
for term in asset_query._keyword_terms:
or_list.append({term: asset_query._keyword_terms[term]})
if or_list:
and_list.append({'$or': or_list})
view_filter = self._view_filter()
if view_filter:
and_list.append(view_filter)
if and_list:
query_terms = {'$and': and_list}
collection = MongoClientValidated('repository',
collection='Asset',
runtime=self._runtime)
result = collection.find(query_terms).sort('_id', DESCENDING)
return objects.AssetList(result, runtime=self._runtime)
class AssetSearchSession(abc_repository_sessions.AssetSearchSession, AssetQuerySession):
"""This session provides methods for searching among ``Asset`` objects.
The search query is constructed using the ``AssetQuery``.
``get_assets_by_query()`` is the basic search method and returns a
list of ``Assets``. A more advanced search may be performed with
``getAssetsBySearch()``. It accepts an ``AssetSearch`` in addition
to the query for the purpose of specifying additional options
affecting the entire search, such as ordering.
``get_assets_by_search()`` returns an ``AssetSearchResults`` that
can be used to access the resulting ``AssetList`` or be used to
perform a search within the result set through ``AssetList``.
This session defines views that offer differing behaviors for
searching.
* federated repository view: searches include assets in
repositories of which this repository is a ancestor in the
repository hierarchy
* isolated repository view: searches are restricted to assets in
this repository
Assets may have a query record indicated by their respective record
types. The query record is accessed via the ``AssetQuery``.
"""
def get_asset_search(self):
"""Gets an asset search.
return: (osid.repository.AssetSearch) - the asset search
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceSearchSession.get_resource_search_template
return searches.AssetSearch(runtime=self._runtime)
asset_search = property(fget=get_asset_search)
def get_asset_search_order(self):
"""Gets an asset search order.
The ``AssetSearchOrder`` is supplied to an ``AssetSearch`` to
specify the ordering of results.
return: (osid.repository.AssetSearchOrder) - the asset search
order
*compliance: mandatory -- This method must be implemented.*
"""
raise errors.Unimplemented()
asset_search_order = property(fget=get_asset_search_order)
@utilities.arguments_not_none
def get_assets_by_search(self, asset_query, asset_search):
"""Gets the search results matching the given search query using the given search.
arg: asset_query (osid.repository.AssetQuery): the asset
query
arg: asset_search (osid.repository.AssetSearch): the asset
search
return: (osid.repository.AssetSearchResults) - the asset search
results
raise: NullArgument - ``asset_query`` or ``asset_search`` is
``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
raise: Unsupported - ``asset_query`` or ``asset_search`` is not
of this service
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceSearchSession.get_resources_by_search_template
# Copied from osid.resource.ResourceQuerySession.get_resources_by_query_template
and_list = list()
or_list = list()
for term in asset_query._query_terms:
and_list.append({term: asset_query._query_terms[term]})
for term in asset_query._keyword_terms:
or_list.append({term: asset_query._keyword_terms[term]})
if asset_search._id_list is not None:
identifiers = [ObjectId(i.identifier) for i in asset_search._id_list]
and_list.append({'_id': {'$in': identifiers}})
if or_list:
and_list.append({'$or': or_list})
view_filter = self._view_filter()
if view_filter:
and_list.append(view_filter)
if and_list:
query_terms = {'$and': and_list}
collection = MongoClientValidated('repository',
collection='Asset',
runtime=self._runtime)
if asset_search.start is not None and asset_search.end is not None:
result = collection.find(query_terms)[asset_search.start:asset_search.end]
else:
result = collection.find(query_terms)
return searches.AssetSearchResults(result, runtime=self._runtime)
@utilities.arguments_not_none
def get_asset_query_from_inspector(self, asset_query_inspector):
"""Gets an asset query from an inspector.
The inspector is available from a ``AssetSearchResults``.
arg: asset_query_inspector
(osid.repository.AssetQueryInspector): an asset query
inspector
return: (osid.repository.AssetQuery) - the asset query
raise: NullArgument - ``asset_query_inspector`` is ``null``
raise: Unsupported - ``asset_query_inspector`` is not of this
service
*compliance: mandatory -- This method must be implemented.*
"""
raise errors.Unimplemented()
class AssetAdminSession(abc_repository_sessions.AssetAdminSession, osid_sessions.OsidSession):
"""This session creates, updates, and deletes ``Assets``.
The data for create and update is provided by the consumer via the
form object. ``OsidForms`` are requested for each create or update
and may not be reused.
Create and update operations differ in their usage. To create an
``Asset,`` an ``AssetForm`` is requested using
``get_asset_form_for_create()`` specifying the desired record
``Types`` or none if no record ``Types`` are needed. The returned
``AssetyForm`` will indicate that it is to be used with a create
operation and can be used to examine metdata or validate data prior
to creation. Once the ``AssetForm`` is submiited to a create
operation, it cannot be reused with another create operation unless
the first operation was unsuccessful. Each ``AssetForm`` corresponds
to an attempted transaction.
For updates, ``AssetForms`` are requested to the ``Asset`` ``Id``
that is to be updated using ``getAssetFormForUpdate()``. Similarly,
the ``AssetForm`` has metadata about the data that can be updated
and it can perform validation before submitting the update. The
``AssetForm`` can only be used once for a successful update and
cannot be reused.
The delete operations delete ``Assets``. To unmap an ``Asset`` from
the current ``Repository,`` the ``AssetRepositoryAssignmentSession``
should be used. These delete operations attempt to remove the
``Bid`` itself thus removing it from all known ``Repository``
catalogs.
This session includes an ``Id`` aliasing mechanism to assign an
external ``Id`` to an internally assigned Id.
The view of the administrative methods defined in this session is
determined by the provider. For an instance of this session where no
repository has been specified, it may not be parallel to the
``AssetLookupSession``. For example, a default
``AssetLookupSession`` may view the entire repository hierarchy
while the default ``AssetAdminSession`` uses an isolated
``Repository`` to create new ``Assets`` ora specific repository to
operate on a predetermined set of ``Assets``. Another scenario is a
federated provider who does not wish to permit administrative
operations for the federation unaware.
Example create:
if (!session.canCreateAssets()) {
return "asset creation not permitted";
}
Type types[1];
types[0] = assetPhotographType;
if (!session.canCreateAssetWithRecordTypes(types)) {
return "creating an asset with a photograph type is not supported";
}
AssetForm form = session.getAssetFormForCreate();
Metadata metadata = form.getDisplayNameMetadata();
if (metadata.isReadOnly()) {
return "cannot set display name";
}
form.setDisplayName("my photo");
PhotographRecordForm photoForm = (PhotographRecordForn) form.getRecordForm(assetPhotogaphType);
Metadata metadata = form.getApertureMetadata();
if (metadata.isReadOnly()) {
return ("cannot set aperture");
}
photoForm.setAperture("5.6");
if (!form.isValid()) {
return form.getValidationMessage();
}
Asset newAsset = session.createAsset(form);
"""
def __init__(self, catalog_id=None, proxy=None, runtime=None, **kwargs):
OsidSession.__init__(self)
self._catalog_class = objects.Repository
self._session_name = 'AssetAdminSession'
self._catalog_name = 'Repository'
OsidSession._init_object(
self,
catalog_id,
proxy,
runtime,
db_name='repository',
cat_name='Repository',
cat_class=objects.Repository)
self._forms = dict()
self._kwargs = kwargs
def get_repository_id(self):
"""Gets the ``Repository`` ``Id`` associated with this session.
return: (osid.id.Id) - the ``Repository Id`` associated with
this session
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.resource.ResourceLookupSession.get_bin_id
return self._catalog_id
repository_id = property(fget=get_repository_id)
def get_repository(self):
"""Gets the ``Repository`` associated with this session.
return: (osid.repository.Repository) - the ``Repository``
associated with this session
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
<|fim▁hole|>
repository = property(fget=get_repository)
def can_create_assets(self):
"""Tests if this user can create ``Assets``.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known creating an ``Asset``
will result in a ``PermissionDenied``. This is intended as a
hint to an application that may opt not to offer create
operations to an unauthorized user.
return: (boolean) - ``false`` if ``Asset`` creation is not
authorized, ``true`` otherwise
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceAdminSession.can_create_resources
# NOTE: It is expected that real authentication hints will be
# handled in a service adapter above the pay grade of this impl.
return True
@utilities.arguments_not_none
def can_create_asset_with_record_types(self, asset_record_types):
"""Tests if this user can create a single ``Asset`` using the desired record types.
While ``RepositoryManager.getAssetRecordTypes()`` can be used to
examine which records are supported, this method tests which
record(s) are required for creating a specific ``Asset``.
Providing an empty array tests if an ``Asset`` can be created
with no records.
arg: asset_record_types (osid.type.Type[]): array of asset
record types
return: (boolean) - ``true`` if ``Asset`` creation using the
specified record ``Types`` is supported, ``false``
otherwise
raise: NullArgument - ``asset_record_types`` is ``null``
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceAdminSession.can_create_resource_with_record_types
# NOTE: It is expected that real authentication hints will be
# handled in a service adapter above the pay grade of this impl.
return True
@utilities.arguments_not_none
def get_asset_form_for_create(self, asset_record_types):
"""Gets the asset form for creating new assets.
A new form should be requested for each create transaction.
arg: asset_record_types (osid.type.Type[]): array of asset
record types
return: (osid.repository.AssetForm) - the asset form
raise: NullArgument - ``asset_record_types`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
raise: Unsupported - unable to get form for requested record
types
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceAdminSession.get_resource_form_for_create_template
for arg in asset_record_types:
if not isinstance(arg, ABCType):
raise errors.InvalidArgument('one or more argument array elements is not a valid OSID Type')
if asset_record_types == []:
obj_form = objects.AssetForm(
repository_id=self._catalog_id,
runtime=self._runtime,
effective_agent_id=self.get_effective_agent_id())
else:
obj_form = objects.AssetForm(
repository_id=self._catalog_id,
record_types=asset_record_types,
runtime=self._runtime,
effective_agent_id=self.get_effective_agent_id())
self._forms[obj_form.get_id().get_identifier()] = not CREATED
return obj_form
@utilities.arguments_not_none
def create_asset(self, asset_form):
"""Creates a new ``Asset``.
arg: asset_form (osid.repository.AssetForm): the form for
this ``Asset``
return: (osid.repository.Asset) - the new ``Asset``
raise: IllegalState - ``asset_form`` already used in a create
transaction
raise: InvalidArgument - one or more of the form elements is
invalid
raise: NullArgument - ``asset_form`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
raise: Unsupported - ``asset_form`` did not originate from
``get_asset_form_for_create()``
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceAdminSession.create_resource_template
collection = MongoClientValidated('repository',
collection='Asset',
runtime=self._runtime)
if not isinstance(asset_form, ABCAssetForm):
raise errors.InvalidArgument('argument type is not an AssetForm')
if asset_form.is_for_update():
raise errors.InvalidArgument('the AssetForm is for update only, not create')
try:
if self._forms[asset_form.get_id().get_identifier()] == CREATED:
raise errors.IllegalState('asset_form already used in a create transaction')
except KeyError:
raise errors.Unsupported('asset_form did not originate from this session')
if not asset_form.is_valid():
raise errors.InvalidArgument('one or more of the form elements is invalid')
insert_result = collection.insert_one(asset_form._my_map)
self._forms[asset_form.get_id().get_identifier()] = CREATED
result = objects.Asset(
collection.find_one({'_id': insert_result.inserted_id}),
runtime=self._runtime)
return result
def can_update_assets(self):
"""Tests if this user can update ``Assets``.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known updating an ``Asset``
will result in a ``PermissionDenied``. This is intended as a
hint to an application that may opt not to offer update
operations to an unauthorized user.
return: (boolean) - ``false`` if ``Asset`` modification is not
authorized, ``true`` otherwise
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceAdminSession.can_create_resources
# NOTE: It is expected that real authentication hints will be
# handled in a service adapter above the pay grade of this impl.
return True
@utilities.arguments_not_none
def get_asset_form_for_update(self, asset_id):
"""Gets the asset form for updating an existing asset.
A new asset form should be requested for each update
transaction.
arg: asset_id (osid.id.Id): the ``Id`` of the ``Asset``
return: (osid.repository.AssetForm) - the asset form
raise: NotFound - ``asset_id`` is not found
raise: NullArgument - ``asset_id`` is null
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceAdminSession.get_resource_form_for_update_template
collection = MongoClientValidated('repository',
collection='Asset',
runtime=self._runtime)
if not isinstance(asset_id, ABCId):
raise errors.InvalidArgument('the argument is not a valid OSID Id')
if asset_id.get_identifier_namespace() != 'repository.Asset':
if asset_id.get_authority() != self._authority:
raise errors.InvalidArgument()
else:
asset_id = self._get_asset_id_with_enclosure(asset_id)
result = collection.find_one({'_id': ObjectId(asset_id.get_identifier())})
obj_form = objects.AssetForm(result, runtime=self._runtime)
self._forms[obj_form.get_id().get_identifier()] = not UPDATED
return obj_form
def _get_asset_id_with_enclosure(self, enclosure_id):
"""Create an Asset with an enclosed foreign object.
return: (osid.id.Id) - the id of the new Asset
"""
mgr = self._get_provider_manager('REPOSITORY')
query_session = mgr.get_asset_query_session_for_repository(self._catalog_id)
query_form = query_session.get_asset_query()
query_form.match_enclosed_object_id(enclosure_id)
query_result = query_session.get_assets_by_query(query_form)
if query_result.available() > 0:
asset_id = query_result.next().get_id()
else:
create_form = self.get_asset_form_for_create([ENCLOSURE_RECORD_TYPE])
create_form.set_enclosed_object(enclosure_id)
asset_id = self.create_asset(create_form).get_id()
return asset_id
@utilities.arguments_not_none
def duplicate_asset(self, asset_id):
collection = MongoClientValidated('repository',
collection='Asset',
runtime=self._runtime)
mgr = self._get_provider_manager('REPOSITORY')
lookup_session = mgr.get_asset_lookup_session()
lookup_session.use_federated_repository_view()
try:
lookup_session.use_unsequestered_asset_view()
except AttributeError:
pass
asset_map = dict(lookup_session.get_asset(asset_id)._my_map)
del asset_map['_id']
if 'repositoryId' in asset_map:
asset_map['repositoryId'] = str(self._catalog_id)
if 'assignedRepositoryIds' in asset_map:
asset_map['assignedRepositoryIds'] = [str(self._catalog_id)]
insert_result = collection.insert_one(asset_map)
result = objects.Asset(
collection.find_one({'_id': insert_result.inserted_id}),
runtime=self._runtime)
return result
@utilities.arguments_not_none
def update_asset(self, asset_form):
"""Updates an existing asset.
arg: asset_form (osid.repository.AssetForm): the form
containing the elements to be updated
raise: IllegalState - ``asset_form`` already used in anupdate
transaction
raise: InvalidArgument - the form contains an invalid value
raise: NullArgument - ``asset_form`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
raise: Unsupported - ``asset_form`` did not originate from
``get_asset_form_for_update()``
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceAdminSession.update_resource_template
collection = MongoClientValidated('repository',
collection='Asset',
runtime=self._runtime)
if not isinstance(asset_form, ABCAssetForm):
raise errors.InvalidArgument('argument type is not an AssetForm')
if not asset_form.is_for_update():
raise errors.InvalidArgument('the AssetForm is for update only, not create')
try:
if self._forms[asset_form.get_id().get_identifier()] == UPDATED:
raise errors.IllegalState('asset_form already used in an update transaction')
except KeyError:
raise errors.Unsupported('asset_form did not originate from this session')
if not asset_form.is_valid():
raise errors.InvalidArgument('one or more of the form elements is invalid')
collection.save(asset_form._my_map)
self._forms[asset_form.get_id().get_identifier()] = UPDATED
# Note: this is out of spec. The OSIDs don't require an object to be returned:
return objects.Asset(
asset_form._my_map,
runtime=self._runtime)
def can_delete_assets(self):
"""Tests if this user can delete ``Assets``.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known deleting an ``Asset``
will result in a ``PermissionDenied``. This is intended as a
hint to an application that may opt not to offer delete
operations to an unauthorized user.
return: (boolean) - ``false`` if ``Asset`` deletion is not
authorized, ``true`` otherwise
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceAdminSession.can_create_resources
# NOTE: It is expected that real authentication hints will be
# handled in a service adapter above the pay grade of this impl.
return True
@utilities.arguments_not_none
def delete_asset(self, asset_id):
"""Deletes an ``Asset``.
arg: asset_id (osid.id.Id): the ``Id`` of the ``Asset`` to
remove
raise: NotFound - ``asset_id`` not found
raise: NullArgument - ``asset_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceAdminSession.delete_resource_template
collection = MongoClientValidated('repository',
collection='Asset',
runtime=self._runtime)
if not isinstance(asset_id, ABCId):
raise errors.InvalidArgument('the argument is not a valid OSID Id')
asset_map = collection.find_one(
dict({'_id': ObjectId(asset_id.get_identifier())},
**self._view_filter()))
objects.Asset(asset_map, runtime=self._runtime)._delete()
collection.delete_one({'_id': ObjectId(asset_id.get_identifier())})
def can_manage_asset_aliases(self):
"""Tests if this user can manage ``Id`` aliases for ``Assets``.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known changing an alias
will result in a ``PermissionDenied``. This is intended as a
hint to an application that may opt not to offer alias
operations to an unauthorized user.
return: (boolean) - ``false`` if ``Asset`` aliasing is not
authorized, ``true`` otherwise
*compliance: mandatory -- This method must be implemented.*
"""
raise errors.Unimplemented()
@utilities.arguments_not_none
def alias_asset(self, asset_id, alias_id):
"""Adds an ``Id`` to an ``Asset`` for the purpose of creating compatibility.
The primary ``Id`` of the ``Asset`` is determined by the
provider. The new ``Id`` performs as an alias to the primary
``Id``. If the alias is a pointer to another asset, it is
reassigned to the given asset ``Id``.
arg: asset_id (osid.id.Id): the ``Id`` of an ``Asset``
arg: alias_id (osid.id.Id): the alias ``Id``
raise: AlreadyExists - ``alias_id`` is already assigned
raise: NotFound - ``asset_id`` not found
raise: NullArgument - ``asset_id`` or ``alias_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceAdminSession.alias_resources_template
self._alias_id(primary_id=asset_id, equivalent_id=alias_id)
def can_create_asset_content(self):
"""Tests if this user can create content for ``Assets``.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known creating an
``AssetContent`` will result in a ``PermissionDenied``. This is
intended as a hint to an application that may opt not to offer
create operations to an unauthorized user.
return: (boolean) - ``false`` if ``Asset`` content creation is
not authorized, ``true`` otherwise
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceAdminSession.can_create_resources
# NOTE: It is expected that real authentication hints will be
# handled in a service adapter above the pay grade of this impl.
return True
@utilities.arguments_not_none
def can_create_asset_content_with_record_types(self, asset_content_record_types):
"""Tests if this user can create an ``AssetContent`` using the desired record types.
While ``RepositoryManager.getAssetContentRecordTypes()`` can be
used to test which records are supported, this method tests
which records are required for creating a specific
``AssetContent``. Providing an empty array tests if an
``AssetContent`` can be created with no records.
arg: asset_content_record_types (osid.type.Type[]): array of
asset content record types
return: (boolean) - ``true`` if ``AssetContent`` creation using
the specified ``Types`` is supported, ``false``
otherwise
raise: NullArgument - ``asset_content_record_types`` is
``null``
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceAdminSession.can_create_resource_with_record_types
# NOTE: It is expected that real authentication hints will be
# handled in a service adapter above the pay grade of this impl.
return True
@utilities.arguments_not_none
def get_asset_content_form_for_create(self, asset_id, asset_content_record_types):
"""Gets an asset content form for creating new assets.
arg: asset_id (osid.id.Id): the ``Id`` of an ``Asset``
arg: asset_content_record_types (osid.type.Type[]): array of
asset content record types
return: (osid.repository.AssetContentForm) - the asset content
form
raise: NotFound - ``asset_id`` is not found
raise: NullArgument - ``asset_id`` or
``asset_content_record_types`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
raise: Unsupported - unable to get form for requested record
types
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.learning.ActivityAdminSession.get_activity_form_for_create_template
if not isinstance(asset_id, ABCId):
raise errors.InvalidArgument('argument is not a valid OSID Id')
for arg in asset_content_record_types:
if not isinstance(arg, ABCType):
raise errors.InvalidArgument('one or more argument array elements is not a valid OSID Type')
if asset_content_record_types == []:
## WHY are we passing repository_id = self._catalog_id below, seems redundant:
obj_form = objects.AssetContentForm(
repository_id=self._catalog_id,
asset_id=asset_id,
catalog_id=self._catalog_id,
runtime=self._runtime)
else:
obj_form = objects.AssetContentForm(
repository_id=self._catalog_id,
record_types=asset_content_record_types,
asset_id=asset_id,
catalog_id=self._catalog_id,
runtime=self._runtime)
obj_form._for_update = False
self._forms[obj_form.get_id().get_identifier()] = not CREATED
return obj_form
@utilities.arguments_not_none
def create_asset_content(self, asset_content_form):
"""Creates new ``AssetContent`` for a given asset.
arg: asset_content_form (osid.repository.AssetContentForm):
the form for this ``AssetContent``
return: (osid.repository.AssetContent) - the new
``AssetContent``
raise: IllegalState - ``asset_content_form`` already used in a
create transaction
raise: InvalidArgument - one or more of the form elements is
invalid
raise: NullArgument - ``asset_content_form`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
raise: Unsupported - ``asset_content_form`` did not originate
from ``get_asset_content_form_for_create()``
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.repository.AssetAdminSession.create_asset_content_template
from ...abstract_osid.repository.objects import AssetContentForm as ABCAssetContentForm
collection = MongoClientValidated('repository',
collection='Asset',
runtime=self._runtime)
if not isinstance(asset_content_form, ABCAssetContentForm):
raise errors.InvalidArgument('argument type is not an AssetContentForm')
if asset_content_form.is_for_update():
raise errors.InvalidArgument('the AssetContentForm is for update only, not create')
try:
if self._forms[asset_content_form.get_id().get_identifier()] == CREATED:
raise errors.IllegalState('asset_content_form already used in a create transaction')
except KeyError:
raise errors.Unsupported('asset_content_form did not originate from this session')
if not asset_content_form.is_valid():
raise errors.InvalidArgument('one or more of the form elements is invalid')
asset_content_form._my_map['_id'] = ObjectId()
asset_id = Id(asset_content_form._my_map['assetId']).get_identifier()
asset = collection.find_one(
{'$and': [{'_id': ObjectId(asset_id)},
{'assigned' + self._catalog_name + 'Ids': {'$in': [str(self._catalog_id)]}}]})
asset['assetContents'].append(asset_content_form._my_map)
result = collection.save(asset)
self._forms[asset_content_form.get_id().get_identifier()] = CREATED
from .objects import AssetContent
return AssetContent(asset_content_form._my_map, runtime=self._runtime)
def can_update_asset_contents(self):
"""Tests if this user can update ``AssetContent``.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known updating an
``AssetContent`` will result in a ``PermissionDenied``. This is
intended as a hint to an application that may opt not to offer
update operations to an unauthorized user.
return: (boolean) - ``false`` if ``AssetContent`` modification
is not authorized, ``true`` otherwise
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceAdminSession.can_create_resources
# NOTE: It is expected that real authentication hints will be
# handled in a service adapter above the pay grade of this impl.
return True
@utilities.arguments_not_none
def get_asset_content_form_for_update(self, asset_content_id):
"""Gets the asset content form for updating an existing asset content.
A new asset content form should be requested for each update
transaction.
arg: asset_content_id (osid.id.Id): the ``Id`` of the
``AssetContent``
return: (osid.repository.AssetContentForm) - the asset content
form
raise: NotFound - ``asset_content_id`` is not found
raise: NullArgument - ``asset_content_id`` is ``null``
raise: OperationFailed - unable to complete request
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.repository.AssetAdminSession.get_asset_content_form_for_update_template
from ...abstract_osid.id.primitives import Id as ABCId
from .objects import AssetContentForm
collection = MongoClientValidated('repository',
collection='Asset',
runtime=self._runtime)
if not isinstance(asset_content_id, ABCId):
raise errors.InvalidArgument('the argument is not a valid OSID Id')
document = collection.find_one({'assetContents._id': ObjectId(asset_content_id.get_identifier())})
for sub_doc in document['assetContents']: # There may be a MongoDB shortcut for this
if sub_doc['_id'] == ObjectId(asset_content_id.get_identifier()):
result = sub_doc
obj_form = AssetContentForm(result, runtime=self._runtime)
obj_form._for_update = True
self._forms[obj_form.get_id().get_identifier()] = not UPDATED
return obj_form
@utilities.arguments_not_none
def update_asset_content(self, asset_content_form):
"""Updates an existing asset content.
arg: asset_content_form (osid.repository.AssetContentForm):
the form containing the elements to be updated
raise: IllegalState - ``asset_content_form`` already used in an
update transaction
raise: InvalidArgument - the form contains an invalid value
raise: NullArgument - ``asset_form`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
raise: Unsupported - ``asset_content_form`` did not originate
from ``get_asset_content_form_for_update()``
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.repository.AssetAdminSession.update_asset_content_template
from ...abstract_osid.repository.objects import AssetContentForm as ABCAssetContentForm
collection = MongoClientValidated('repository',
collection='Asset',
runtime=self._runtime)
if not isinstance(asset_content_form, ABCAssetContentForm):
raise errors.InvalidArgument('argument type is not an AssetContentForm')
if not asset_content_form.is_for_update():
raise errors.InvalidArgument('the AssetContentForm is for update only, not create')
try:
if self._forms[asset_content_form.get_id().get_identifier()] == UPDATED:
raise errors.IllegalState('asset_content_form already used in an update transaction')
except KeyError:
raise errors.Unsupported('asset_content_form did not originate from this session')
if not asset_content_form.is_valid():
raise errors.InvalidArgument('one or more of the form elements is invalid')
asset_id = Id(asset_content_form._my_map['assetId']).get_identifier()
asset = collection.find_one(
{'$and': [{'_id': ObjectId(asset_id)},
{'assigned' + self._catalog_name + 'Ids': {'$in': [str(self._catalog_id)]}}]})
index = 0
found = False
for i in asset['assetContents']:
if i['_id'] == ObjectId(asset_content_form._my_map['_id']):
asset['assetContents'].pop(index)
asset['assetContents'].insert(index, asset_content_form._my_map)
found = True
break
index += 1
if not found:
raise errors.NotFound()
try:
collection.save(asset)
except: # what exceptions does mongodb save raise?
raise errors.OperationFailed()
self._forms[asset_content_form.get_id().get_identifier()] = UPDATED
# Note: this is out of spec. The OSIDs don't require an object to be returned:
from .objects import AssetContent
return AssetContent(asset_content_form._my_map, runtime=self._runtime)
def can_delete_asset_contents(self):
"""Tests if this user can delete ``AssetsContents``.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known deleting an
``AssetContent`` will result in a ``PermissionDenied``. This is
intended as a hint to an application that may opt not to offer
delete operations to an unauthorized user.
return: (boolean) - ``false`` if ``AssetContent`` deletion is
not authorized, ``true`` otherwise
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceAdminSession.can_create_resources
# NOTE: It is expected that real authentication hints will be
# handled in a service adapter above the pay grade of this impl.
return True
@utilities.arguments_not_none
def delete_asset_content(self, asset_content_id):
"""Deletes content from an ``Asset``.
arg: asset_content_id (osid.id.Id): the ``Id`` of the
``AssetContent``
raise: NotFound - ``asset_content_id`` is not found
raise: NullArgument - ``asset_content_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.repository.AssetAdminSession.delete_asset_content_template
from ...abstract_osid.id.primitives import Id as ABCId
from .objects import AssetContent
collection = MongoClientValidated('repository',
collection='Asset',
runtime=self._runtime)
if not isinstance(asset_content_id, ABCId):
raise errors.InvalidArgument('the argument is not a valid OSID Id')
asset = collection.find_one({'assetContents._id': ObjectId(asset_content_id.get_identifier())})
index = 0
found = False
for i in asset['assetContents']:
if i['_id'] == ObjectId(asset_content_id.get_identifier()):
asset_content_map = asset['assetContents'].pop(index)
index += 1
found = True
if not found:
raise errors.OperationFailed()
AssetContent(asset_content_map, runtime=self._runtime)._delete()
collection.save(asset)
class AssetNotificationSession(abc_repository_sessions.AssetNotificationSession, osid_sessions.OsidSession):
"""This session defines methods to receive notifications on adds/changes to ``Asset`` objects in this
``Repository``.
This also includes existing assets that may appear or disappear due
to changes in the ``Repository`` hierarchy, This session is intended
for consumers needing to synchronize their state with this service
without the use of polling. Notifications are cancelled when this
session is closed.
The two views defined in this session correspond to the views in the
``AssetLookupSession``.
"""
def __init__(self, catalog_id=None, proxy=None, runtime=None, **kwargs):
OsidSession.__init__(self)
self._catalog_class = objects.Repository
self._session_name = 'AssetNotificationSession'
self._catalog_name = 'Repository'
OsidSession._init_object(
self,
catalog_id,
proxy,
runtime,
db_name='repository',
cat_name='Repository',
cat_class=objects.Repository)
if not MONGO_LISTENER.is_alive():
MONGO_LISTENER.initialize(runtime)
MONGO_LISTENER.start()
self._receiver = kwargs['receiver']
db_prefix = ''
try:
db_prefix_param_id = Id('parameter:mongoDBNamePrefix@mongo')
db_prefix = runtime.get_configuration().get_value_by_parameter(db_prefix_param_id).get_string_value()
except (AttributeError, KeyError, errors.NotFound):
pass
self._ns='{0}repository.Asset'.format(db_prefix)
if self._ns not in MONGO_LISTENER.receivers:
MONGO_LISTENER.receivers[self._ns] = dict()
MONGO_LISTENER.receivers[self._ns][self._receiver] = {
'authority': self._authority,
'obj_name_plural': 'assets',
'i': False,
'u': False,
'd': False,
'reliable': False,
}
def __del__(self):
"""Make sure the receiver is removed from the listener"""
del MONGO_LISTENER.receivers[self._ns][self._receiver]
super(AssetNotificationSession, self).__del__()
def get_repository_id(self):
"""Gets the ``Repository`` ``Id`` associated with this session.
return: (osid.id.Id) - the ``Repository Id`` associated with
this session
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.resource.ResourceLookupSession.get_bin_id
return self._catalog_id
repository_id = property(fget=get_repository_id)
def get_repository(self):
"""Gets the ``Repository`` associated with this session.
return: (osid.repository.Repository) - the ``Repository``
associated with this session
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.resource.ResourceLookupSession.get_bin
return self._catalog
repository = property(fget=get_repository)
def can_register_for_asset_notifications(self):
"""Tests if this user can register for ``Asset`` notifications.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known all methods in this
session will result in a ``PermissionDenied``. This is intended
as a hint to an application that may opt not to offer
notification operations.
return: (boolean) - ``false`` if notification methods are not
authorized, ``true`` otherwise
*compliance: mandatory -- This method must be implemented.*
"""
raise errors.Unimplemented()
def use_federated_repository_view(self):
"""Federates the view for methods in this session.
A federated view will include assets in repositories which are
children of this repository in the repository hierarchy.
*compliance: mandatory -- This method is must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceLookupSession.use_federated_bin_view
self._use_federated_catalog_view()
def use_isolated_repository_view(self):
"""Isolates the view for methods in this session.
An isolated view restricts notifications to this repository
only.
*compliance: mandatory -- This method is must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceLookupSession.use_isolated_bin_view
self._use_isolated_catalog_view()
def register_for_new_assets(self):
"""Register for notifications of new assets.
``AssetReceiver.newAssets()`` is invoked when a new ``Asset``
appears in this repository.
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceNotificationSession.register_for_new_resources
MONGO_LISTENER.receivers[self._ns][self._receiver]['i'] = True
@utilities.arguments_not_none
def register_for_new_assets_by_genus_type(self, asset_genus_type):
"""Registers for notification of new assets of the given asset genus type.
``AssetReceiver.newAssets()`` is invoked when an asset is
appears in this repository.
arg: asset_genus_type (osid.type.Type): the genus type of the
``Asset`` to monitor
raise: NullArgument - ``asset_genus_type`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceNotificationSession.register_for_new_resources
MONGO_LISTENER.receivers[self._ns][self._receiver]['i'] = True
def register_for_changed_assets(self):
"""Registers for notification of updated assets.
``AssetReceiver.changedAssets()`` is invoked when an asset in
this repository is changed.
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceNotificationSession.register_for_changed_resources
MONGO_LISTENER.receivers[self._ns][self._receiver]['u'] = True
@utilities.arguments_not_none
def register_for_changed_assets_by_genus_type(self, asset_genus_type):
"""Registers for notification of updated assets of the given asset genus type.
``AssetReceiver.changedAssets()`` is invoked when an asset in
this repository is changed.
arg: asset_genus_type (osid.type.Type): the genus type of the
``Asset`` to monitor
raise: NullArgument - ``asset_genus_type`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceNotificationSession.register_for_changed_resource
if MONGO_LISTENER.receivers[self._ns][self._receiver]['u'] == False:
MONGO_LISTENER.receivers[self._ns][self._receiver]['u'] = []
if isinstance(MONGO_LISTENER.receivers[self._ns][self._receiver]['u'], list):
MONGO_LISTENER.receivers[self._ns][self._receiver]['u'].append(asset_genus_type.get_identifier())
@utilities.arguments_not_none
def register_for_changed_asset(self, asset_id):
"""Registers for notification of an updated asset.
``AssetReceiver.changedAssets()`` is invoked when the specified
asset in this repository is changed.
arg: asset_id (osid.id.Id): the ``Id`` of the ``Asset`` to
monitor
raise: NullArgument - ``asset_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceNotificationSession.register_for_changed_resource
if MONGO_LISTENER.receivers[self._ns][self._receiver]['u'] == False:
MONGO_LISTENER.receivers[self._ns][self._receiver]['u'] = []
if isinstance(MONGO_LISTENER.receivers[self._ns][self._receiver]['u'], list):
MONGO_LISTENER.receivers[self._ns][self._receiver]['u'].append(asset_id.get_identifier())
def register_for_deleted_assets(self):
"""Registers for notification of deleted assets.
``AssetReceiver.deletedAssets()`` is invoked when an asset is
deleted or removed from this repository.
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceNotificationSession.register_for_deleted_resources
MONGO_LISTENER.receivers[self._ns][self._receiver]['d'] = True
@utilities.arguments_not_none
def register_for_deleted_assets_by_genus_type(self, asset_genus_type):
"""Registers for notification of deleted assets of the given asset genus type.
``AssetReceiver.deletedAssets()`` is invoked when an asset is
deleted or removed from this repository.
arg: asset_genus_type (osid.type.Type): the genus type of the
``Asset`` to monitor
raise: NullArgument - ``asset_genus_type`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceNotificationSession.register_for_deleted_resource
if MONGO_LISTENER.receivers[self._ns][self._receiver]['d'] == False:
MONGO_LISTENER.receivers[self._ns][self._receiver]['d'] = []
if isinstance(MONGO_LISTENER.receivers[self._ns][self._receiver]['d'], list):
self.MONGO_LISTENER.receivers[self._ns][self._receiver]['d'].append(asset_genus_type.get_identifier())
@utilities.arguments_not_none
def register_for_deleted_asset(self, asset_id):
"""Registers for notification of a deleted asset.
``AssetReceiver.deletedAssets()`` is invoked when the specified
asset is deleted or removed from this repository.
arg: asset_id (osid.id.Id): the ``Id`` of the ``Asset`` to
monitor
raise: NullArgument - ``asset_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceNotificationSession.register_for_deleted_resource
if MONGO_LISTENER.receivers[self._ns][self._receiver]['d'] == False:
MONGO_LISTENER.receivers[self._ns][self._receiver]['d'] = []
if isinstance(MONGO_LISTENER.receivers[self._ns][self._receiver]['d'], list):
self.MONGO_LISTENER.receivers[self._ns][self._receiver]['d'].append(asset_id.get_identifier())
def reliable_asset_notifications(self):
"""Reliable notifications are desired.
In reliable mode, notifications are to be acknowledged using
``acknowledge_item_notification()`` .
*compliance: mandatory -- This method is must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceNotificationSession.reliable_resource_notifications
MONGO_LISTENER.receivers[self._ns][self._receiver]['reliable'] = True
def unreliable_asset_notifications(self):
"""Unreliable notifications are desired.
In unreliable mode, notifications do not need to be
acknowledged.
*compliance: mandatory -- This method is must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceNotificationSession.unreliable_resource_notifications
MONGO_LISTENER.receivers[self._ns][self._receiver]['reliable'] = False
@utilities.arguments_not_none
def acknowledge_asset_notification(self, notification_id):
"""Acknowledge an asset notification.
arg: notification_id (osid.id.Id): the ``Id`` of the
notification
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
raise errors.Unimplemented()
class AssetRepositorySession(abc_repository_sessions.AssetRepositorySession, osid_sessions.OsidSession):
"""This session provides methods to retrieve ``Assets`` to ``Repository`` mappings.
An ``Asset`` may appear in multiple ``Repository`` objects. Each
Repository may have its own authorizations governing who is allowed
to look at it.
This lookup session defines two views:
* comparative view: elements may be silently omitted or re-ordered
* plenary view: provides a complete result set or is an error
condition
"""
_session_name = 'AssetRepositorySession'
def __init__(self, proxy=None, runtime=None, **kwargs):
OsidSession._init_catalog(self, proxy, runtime)
self._catalog_view = COMPARATIVE
self._kwargs = kwargs
def can_lookup_asset_repository_mappings(self):
"""Tests if this user can perform lookups of asset/repository mappings.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known lookup methods in
this session will result in a ``PermissionDenied``. This is
intended as a hint to an application that may opt not to offer
lookup operations to unauthorized users.
return: (boolean) - ``false`` if looking up mappings is not
authorized, ``true`` otherwise
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceBinSession.can_lookup_resource_bin_mappings
# NOTE: It is expected that real authentication hints will be
# handled in a service adapter above the pay grade of this impl.
return True
def use_comparative_repository_view(self):
"""The returns from the lookup methods may omit or translate elements based on this session, such as
authorization, and not result in an error.
This view is used when greater interoperability is desired at
the expense of precision.
*compliance: mandatory -- This method is must be implemented.*
"""
# Implemented from template for
# osid.resource.BinLookupSession.use_comparative_bin_view
self._catalog_view = COMPARATIVE
def use_plenary_repository_view(self):
"""A complete view of the ``Asset`` and ``Repository`` returns is desired.
Methods will return what is requested or result in an error.
This view is used when greater precision is desired at the
expense of interoperability.
*compliance: mandatory -- This method is must be implemented.*
"""
# Implemented from template for
# osid.resource.BinLookupSession.use_plenary_bin_view
self._catalog_view = PLENARY
@utilities.arguments_not_none
def get_asset_ids_by_repository(self, repository_id):
"""Gets the list of ``Asset`` ``Ids`` associated with a ``Repository``.
arg: repository_id (osid.id.Id): ``Id`` of the ``Repository``
return: (osid.id.IdList) - list of related asset ``Ids``
raise: NotFound - ``repository_id`` is not found
raise: NullArgument - ``repository_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceBinSession.get_resource_ids_by_bin
id_list = []
for asset in self.get_assets_by_repository(repository_id):
id_list.append(asset.get_id())
return IdList(id_list)
@utilities.arguments_not_none
def get_assets_by_repository(self, repository_id):
"""Gets the list of ``Assets`` associated with a ``Repository``.
arg: repository_id (osid.id.Id): ``Id`` of the ``Repository``
return: (osid.repository.AssetList) - list of related assets
raise: NotFound - ``repository_id`` is not found
raise: NullArgument - ``repository_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceBinSession.get_resources_by_bin
mgr = self._get_provider_manager('REPOSITORY')
lookup_session = mgr.get_asset_lookup_session_for_repository(repository_id)
lookup_session.use_isolated_repository_view()
return lookup_session.get_assets()
@utilities.arguments_not_none
def get_asset_ids_by_repositories(self, repository_ids):
"""Gets the list of ``Asset Ids`` corresponding to a list of ``Repository`` objects.
arg: repository_ids (osid.id.IdList): list of repository
``Ids``
return: (osid.id.IdList) - list of asset ``Ids``
raise: NullArgument - ``repository_ids`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceBinSession.get_resource_ids_by_bins
id_list = []
for asset in self.get_assets_by_repositories(repository_ids):
id_list.append(asset.get_id())
return IdList(id_list)
@utilities.arguments_not_none
def get_assets_by_repositories(self, repository_ids):
"""Gets the list of ``Assets`` corresponding to a list of ``Repository`` objects.
arg: repository_ids (osid.id.IdList): list of repository
``Ids``
return: (osid.repository.AssetList) - list of assets
raise: NullArgument - ``repository_ids`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceBinSession.get_resources_by_bins
asset_list = []
for repository_id in repository_ids:
asset_list += list(
self.get_assets_by_repository(repository_id))
return objects.AssetList(asset_list)
@utilities.arguments_not_none
def get_repository_ids_by_asset(self, asset_id):
"""Gets the list of ``Repository`` ``Ids`` mapped to an ``Asset``.
arg: asset_id (osid.id.Id): ``Id`` of an ``Asset``
return: (osid.id.IdList) - list of repository ``Ids``
raise: NotFound - ``asset_id`` is not found
raise: NullArgument - ``asset_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceBinSession.get_bin_ids_by_resource
mgr = self._get_provider_manager('REPOSITORY', local=True)
lookup_session = mgr.get_asset_lookup_session()
lookup_session.use_federated_repository_view()
asset = lookup_session.get_asset(asset_id)
id_list = []
for idstr in asset._my_map['assignedRepositoryIds']:
id_list.append(Id(idstr))
return IdList(id_list)
@utilities.arguments_not_none
def get_repositories_by_asset(self, asset_id):
"""Gets the list of ``Repository`` objects mapped to an ``Asset``.
arg: asset_id (osid.id.Id): ``Id`` of an ``Asset``
return: (osid.repository.RepositoryList) - list of repositories
raise: NotFound - ``asset_id`` is not found
raise: NullArgument - ``asset_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceBinSession.get_bins_by_resource
mgr = self._get_provider_manager('REPOSITORY')
lookup_session = mgr.get_repository_lookup_session()
return lookup_session.get_repositories_by_ids(
self.get_repository_ids_by_asset(asset_id))
class AssetRepositoryAssignmentSession(abc_repository_sessions.AssetRepositoryAssignmentSession, osid_sessions.OsidSession):
"""This session provides methods to re-assign ``Assets`` to ``Repositories``.
An ``Asset`` may map to multiple ``Repository`` objects and removing
the last reference to an ``Asset`` is the equivalent of deleting it.
Each ``Repository`` may have its own authorizations governing who is
allowed to operate on it.
Moving or adding a reference of an ``Asset`` to another
``Repository`` is not a copy operation (eg: does not change its
``Id`` ).
"""
def __init__(self, proxy=None, runtime=None, **kwargs):
OsidSession._init_catalog(self, proxy, runtime)
self._session_name = 'AssetRepositoryAssignmentSession'
self._catalog_name = 'Repository'
self._forms = dict()
self._kwargs = kwargs
def can_assign_assets(self):
"""Tests if this user can alter asset/repository mappings.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known mapping methods in
this session will result in a ``PermissionDenied``. This is
intended as a hint to an application that may opt not to offer
assignment operations to unauthorized users.
return: (boolean) - ``false`` if mapping is not authorized,
``true`` otherwise
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceBinAssignmentSession.can_assign_resources
# NOTE: It is expected that real authentication hints will be
# handled in a service adapter above the pay grade of this impl.
return True
@utilities.arguments_not_none
def can_assign_assets_to_repository(self, repository_id):
"""Tests if this user can alter asset/repository mappings.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known mapping methods in
this session will result in a ``PermissionDenied``. This is
intended as a hint to an application that may opt not to offer
assignment operations to unauthorized users.
arg: repository_id (osid.id.Id): the ``Id`` of the
``Repository``
return: (boolean) - ``false`` if mapping is not authorized,
``true`` otherwise
raise: NullArgument - ``repository_id`` is ``null``
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceBinAssignmentSession.can_assign_resources_to_bin
# NOTE: It is expected that real authentication hints will be
# handled in a service adapter above the pay grade of this impl.
if repository_id.get_identifier() == '000000000000000000000000':
return False
return True
@utilities.arguments_not_none
def get_assignable_repository_ids(self, repository_id):
"""Gets a list of repositories including and under the given repository node in which any asset can be assigned.
arg: repository_id (osid.id.Id): the ``Id`` of the
``Repository``
return: (osid.id.IdList) - list of assignable repository ``Ids``
raise: NullArgument - ``repository_id`` is ``null``
raise: OperationFailed - unable to complete request
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceBinAssignmentSession.get_assignable_bin_ids
# This will likely be overridden by an authorization adapter
mgr = self._get_provider_manager('REPOSITORY', local=True)
lookup_session = mgr.get_repository_lookup_session()
assets = lookup_session.get_repositories()
id_list = []
for asset in assets:
id_list.append(assets.get_id())
return IdList(id_list)
@utilities.arguments_not_none
def get_assignable_repository_ids_for_asset(self, repository_id, asset_id):
"""Gets a list of repositories including and under the given repository node in which a specific asset can be
assigned.
arg: repository_id (osid.id.Id): the ``Id`` of the
``Repository``
arg: asset_id (osid.id.Id): the ``Id`` of the ``Asset``
return: (osid.id.IdList) - list of assignable repository ``Ids``
raise: NullArgument - ``repository_id`` or ``asset_id`` is
``null``
raise: OperationFailed - unable to complete request
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceBinAssignmentSession.get_assignable_bin_ids_for_resource
# This will likely be overridden by an authorization adapter
return self.get_assignable_bin_ids()
@utilities.arguments_not_none
def assign_asset_to_repository(self, asset_id, repository_id):
"""Adds an existing ``Asset`` to a ``Repository``.
arg: asset_id (osid.id.Id): the ``Id`` of the ``Asset``
arg: repository_id (osid.id.Id): the ``Id`` of the
``Repository``
raise: AlreadyExists - ``asset_id`` already assigned to
``repository_id``
raise: NotFound - ``asset_id`` or ``repository_id`` not found
raise: NullArgument - ``asset_id`` or ``repository_id`` is
``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceBinAssignmentSession.assign_resource_to_bin
mgr = self._get_provider_manager('REPOSITORY', local=True)
lookup_session = mgr.get_repository_lookup_session()
lookup_session.get_repository(repository_id) # to raise NotFound
self._assign_object_to_catalog(asset_id, repository_id)
@utilities.arguments_not_none
def unassign_asset_from_repository(self, asset_id, repository_id):
"""Removes an ``Asset`` from a ``Repository``.
arg: asset_id (osid.id.Id): the ``Id`` of the ``Asset``
arg: repository_id (osid.id.Id): the ``Id`` of the
``Repository``
raise: NotFound - ``asset_id`` or ``repository_id`` not found
or ``asset_id`` not assigned to ``repository_id``
raise: NullArgument - ``asset_id`` or ``repository_id`` is
``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceBinAssignmentSession.unassign_resource_from_bin
mgr = self._get_provider_manager('REPOSITORY', local=True)
lookup_session = mgr.get_repository_lookup_session()
cat = lookup_session.get_repository(repository_id) # to raise NotFound
self._unassign_object_from_catalog(asset_id, repository_id)
class AssetCompositionSession(abc_repository_sessions.AssetCompositionSession, osid_sessions.OsidSession):
"""This session defines methods for looking up ``Asset`` to ``Composition`` mappings.
A ``Composition`` represents a collection of ``Assets``.
This lookup session defines several views:
* comparative view: elements may be silently omitted or re-ordered
* plenary view: provides a complete result set or is an error
condition
* isolated repository view: All lookup methods in this session
operate, retrieve and pertain to asseta and compositions defined
explicitly in the current repository. Using an isolated view is
useful for managing compositions with the
CompositionAdminSession.
* federated repository view: All lookup methods in this session
operate, retrieve and pertain to all compositions and assets
defined in this repository and any other compositions implicitly
available in this repository through repository inheritence.
The methods ``use_federated_asset_composition_view()`` and
``use_isolated_asset_compositiont_view()`` behave as a radio group
and one should be selected before invoking any lookup methods.
"""
def __init__(self, catalog_id=None, proxy=None, runtime=None, **kwargs):
OsidSession.__init__(self)
self._catalog_class = objects.Repository
self._session_name = 'AssetCompositionSession'
self._catalog_name = 'Repository'
OsidSession._init_object(
self,
catalog_id,
proxy,
runtime,
db_name='repository',
cat_name='Repository',
cat_class=objects.Repository)
self._kwargs = kwargs
def get_repository_id(self):
"""Gets the ``Repository`` ``Id`` associated with this session.
return: (osid.id.Id) - the ``Repository Id`` associated with
this session
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.resource.ResourceLookupSession.get_bin_id
return self._catalog_id
repository_id = property(fget=get_repository_id)
def get_repository(self):
"""Gets the ``Repository`` associated with this session.
return: (osid.repository.Repository) - the ``Repository``
associated with this session
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.resource.ResourceLookupSession.get_bin
return self._catalog
repository = property(fget=get_repository)
def can_access_asset_compositions(self):
"""Tests if this user can perform composition lookups.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known all methods in this
session will result in a ``PermissionDenied``. This is intended
as a hint to an application that may opt not to offer lookup
operations to unauthorized users.
return: (boolean) - ``false`` if lookup methods are not
authorized, ``true`` otherwise
*compliance: mandatory -- This method must be implemented.*
"""
raise errors.Unimplemented()
def use_comparative_asset_composition_view(self):
"""The returns from the lookup methods may omit or translate elements based on this session, such as
authorization, and not result in an error.
This view is used when greater interoperability is desired at
the expense of precision.
*compliance: mandatory -- This method is must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceLookupSession.use_comparative_resource_view
self._use_comparative_object_view()
def use_plenary_asset_composition_view(self):
"""A complete view of the returns is desired.
Methods will return what is requested or result in an error.
This view is used when greater precision is desired at the
expense of interoperability.
*compliance: mandatory -- This method is must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceLookupSession.use_plenary_resource_view
self._use_plenary_object_view()
def use_federated_repository_view(self):
"""Federates the view for methods in this session.
A federated view will include compositions in repositories which
are children of this repository in the repository hierarchy.
*compliance: mandatory -- This method is must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceLookupSession.use_federated_bin_view
self._use_federated_catalog_view()
def use_isolated_repository_view(self):
"""Isolates the view for methods in this session.
An isolated view restricts lookups to this repository only.
*compliance: mandatory -- This method is must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceLookupSession.use_isolated_bin_view
self._use_isolated_catalog_view()
@utilities.arguments_not_none
def get_composition_assets(self, composition_id):
"""Gets the list of assets mapped to the given ``Composition``.
arg: composition_id (osid.id.Id): ``Id`` of the
``Composition``
return: (osid.repository.AssetList) - list of assets
raise: NotFound - ``composition_id`` not found
raise: NullArgument - ``composition_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method is must be implemented.*
"""
collection = MongoClientValidated('repository',
collection='Composition',
runtime=self._runtime)
composition = collection.find_one(
dict({'_id': ObjectId(composition_id.get_identifier())},
**self._view_filter()))
if 'assetIds' not in composition:
raise errors.NotFound('no Assets are assigned to this Composition')
asset_ids = []
for idstr in composition['assetIds']:
asset_ids.append(Id(idstr))
mgr = self._get_provider_manager('REPOSITORY')
als = mgr.get_asset_lookup_session()
als.use_federated_repository_view()
return als.get_assets_by_ids(asset_ids)
@utilities.arguments_not_none
def get_compositions_by_asset(self, asset_id):
"""Gets a list of compositions including the given asset.
arg: asset_id (osid.id.Id): ``Id`` of the ``Asset``
return: (osid.repository.CompositionList) - the returned
``Composition list``
raise: NotFound - ``asset_id`` is not found
raise: NullArgument - ``asset_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
collection = MongoClientValidated('repository',
collection='Composition',
runtime=self._runtime)
result = collection.find(
dict({'assetIds': {'$in': [str(asset_id)]}},
**self._view_filter())).sort('_id', DESCENDING)
return objects.CompositionList(result, runtime=self._runtime)
class AssetCompositionDesignSession(abc_repository_sessions.AssetCompositionDesignSession, osid_sessions.OsidSession):
"""This session provides the means for adding assets to an asset composiiton.
The asset is identified inside a composition using its own Id. To
add the same asset to the composition, multiple compositions should
be used and placed at the same level in the ``Composition``
hierarchy.
"""
def __init__(self, catalog_id=None, proxy=None, runtime=None, **kwargs):
OsidSession.__init__(self)
self._catalog_class = objects.Repository
self._session_name = 'AssetCompositionDesignSession'
self._catalog_name = 'Repository'
OsidSession._init_object(
self,
catalog_id,
proxy,
runtime,
db_name='repository',
cat_name='Repository',
cat_class=objects.Repository)
self._kwargs = kwargs
def get_repository_id(self):
"""Gets the ``Repository`` ``Id`` associated with this session.
return: (osid.id.Id) - the ``Repository Id`` associated with
this session
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.resource.ResourceLookupSession.get_bin_id
return self._catalog_id
repository_id = property(fget=get_repository_id)
def get_repository(self):
"""Gets the ``Repository`` associated with this session.
return: (osid.repository.Repository) - the ``Repository``
associated with this session
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.resource.ResourceLookupSession.get_bin
return self._catalog
repository = property(fget=get_repository)
def can_compose_assets(self):
"""Tests if this user can manage mapping of ``Assets`` to ``Compositions``.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known all methods in this
session will result in a ``PermissionDenied``. This is intended
as an application hint that may opt not to offer composition
operations.
return: (boolean) - ``false`` if asset composiion is not
authorized, ``true`` otherwise
*compliance: mandatory -- This method must be implemented.*
"""
return True
@utilities.arguments_not_none
def add_asset(self, asset_id, composition_id):
"""Appends an asset to a composition.
arg: asset_id (osid.id.Id): ``Id`` of the ``Asset``
arg: composition_id (osid.id.Id): ``Id`` of the
``Composition``
raise: AlreadyExists - ``asset_id`` already part
``composition_id``
raise: NotFound - ``asset_id`` or ``composition_id`` not found
raise: NullArgument - ``asset_id`` or ``composition_id`` is
``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization fauilure
*compliance: mandatory -- This method must be implemented.*
"""
# This asset found check may want to be run through _get_provider_manager
# so as to ensure assess control:
from ...abstract_osid.id.primitives import Id as ABCId
if not isinstance(asset_id, ABCId):
raise errors.InvalidArgument('the argument is not a valid OSID Id')
if asset_id.get_identifier_namespace() != 'repository.Asset':
if asset_id.get_authority() != self._authority:
raise errors.InvalidArgument()
else:
mgr = self._get_provider_manager('REPOSITORY')
admin_session = mgr.get_asset_admin_session_for_repository(self._catalog_id)
asset_id = admin_session._get_asset_id_with_enclosure(asset_id)
collection = MongoClientValidated('repository',
collection='Asset',
runtime=self._runtime)
asset = collection.find_one({'_id': ObjectId(asset_id.get_identifier())})
collection = MongoClientValidated('repository',
collection='Composition',
runtime=self._runtime)
composition = collection.find_one({'_id': ObjectId(composition_id.get_identifier())})
if 'assetIds' in composition:
if str(asset_id) not in composition['assetIds']:
composition['assetIds'].append(str(asset_id))
else:
composition['assetIds'] = [str(asset_id)]
collection.save(composition)
@utilities.arguments_not_none
def move_asset_ahead(self, asset_id, composition_id, reference_id):
"""Reorders assets in a composition by moving the specified asset in front of a reference asset.
arg: asset_id (osid.id.Id): ``Id`` of the ``Asset``
arg: composition_id (osid.id.Id): ``Id`` of the
``Composition``
arg: reference_id (osid.id.Id): ``Id`` of the reference
``Asset``
raise: NotFound - ``asset_id`` or ``reference_id`` ``not found
in composition_id``
raise: NullArgument - ``asset_id, reference_id`` or
``composition_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization fauilure
*compliance: mandatory -- This method must be implemented.*
"""
collection = MongoClientValidated('repository',
collection='Composition',
runtime=self._runtime)
composition = collection.find_one({'_id': ObjectId(composition_id.get_identifier())})
if 'assetIds' not in composition:
raise errors.NotFound('no Assets are assigned to this Composition')
composition['assetIds'] = move_id_ahead(asset_id, reference_id, composition['assetIds'])
collection.save(composition)
@utilities.arguments_not_none
def move_asset_behind(self, asset_id, composition_id, reference_id):
"""Reorders assets in a composition by moving the specified asset behind of a reference asset.
arg: asset_id (osid.id.Id): ``Id`` of the ``Asset``
arg: composition_id (osid.id.Id): ``Id`` of the
``Composition``
arg: reference_id (osid.id.Id): ``Id`` of the reference
``Asset``
raise: NotFound - ``asset_id`` or ``reference_id`` ``not found
in composition_id``
raise: NullArgument - ``asset_id, reference_id`` or
``composition_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization fauilure
*compliance: mandatory -- This method must be implemented.*
"""
collection = MongoClientValidated('repository',
collection='Composition',
runtime=self._runtime)
composition = collection.find_one({'_id': ObjectId(composition_id.get_identifier())})
if 'assetIds' not in composition:
raise errors.NotFound('no Assets are assigned to this Composition')
composition['assetIds'] = move_id_behind(asset_id, reference_id, composition['assetIds'])
collection.save(composition)
@utilities.arguments_not_none
def order_assets(self, asset_ids, composition_id):
"""Reorders a set of assets in a composition.
arg: asset_ids (osid.id.Id[]): ``Ids`` for a set of
``Assets``
arg: composition_id (osid.id.Id): ``Id`` of the
``Composition``
raise: NotFound - ``composition_id`` not found or, an
``asset_id`` not related to ``composition_id``
raise: NullArgument - ``instruction_ids`` or ``agenda_id`` is
``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
collection = MongoClientValidated('repository',
collection='Composition',
runtime=self._runtime)
composition = collection.find_one({'_id': ObjectId(composition_id.get_identifier())})
collection = MongoClientValidated('repository',
collection='Composition',
runtime=self._runtime)
if 'assetIds' not in composition:
raise errors.NotFound('no Assets are assigned to this Composition')
composition['assetIds'] = order_ids(asset_ids, composition['assetIds'])
collection.save(composition)
@utilities.arguments_not_none
def remove_asset(self, asset_id, composition_id):
"""Removes an ``Asset`` from a ``Composition``.
arg: asset_id (osid.id.Id): ``Id`` of the ``Asset``
arg: composition_id (osid.id.Id): ``Id`` of the
``Composition``
raise: NotFound - ``asset_id`` ``not found in composition_id``
raise: NullArgument - ``asset_id`` or ``composition_id`` is
``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization fauilure
*compliance: mandatory -- This method must be implemented.*
"""
collection = MongoClientValidated('repository',
collection='Composition',
runtime=self._runtime)
composition = collection.find_one({'_id': ObjectId(composition_id.get_identifier())})
try:
composition['assetIds'].remove(str(asset_id))
except (KeyError, ValueError):
raise errors.NotFound()
collection.save(composition)
class CompositionLookupSession(abc_repository_sessions.CompositionLookupSession, osid_sessions.OsidSession):
"""This session provides methods for retrieving ``Composition`` objects.
The ``Composition`` represents a collection of ``Assets``.
This session defines views that offer differing behaviors when
retrieving multiple objects.
* comparative view: elements may be silently omitted or re-ordered
* plenary view: provides a complete and ordered result set or is
an error condition
* isolated repository view: All lookup methods in this session
operate, retrieve and pertain to compositions defined explicitly
in the current repository. Using an isolated view is useful for
managing compositions with the ``CompositionAdminSession.``
* federated repository view: All composition methods in this
session operate, retrieve and pertain to all compositions
defined in this repository and any other compositions implicitly
available in this repository through repository inheritence.
* active composition view: All composition lookup methods return
active compositions.
* any status composition view: Compositions of any active or
inactive status are returned from methods.
* sequestered composition viiew: All composition methods suppress
sequestered compositions.
* unsequestered composition view: All composition methods return
all compositions.
Generally, the comparative view should be used for most applications
as it permits operation even if there is data that cannot be
accessed. For example, a browsing application may only need to
examine the ``Composition`` it can access, without breaking
execution. However, an administrative application may require a
complete set of ``Composition`` objects to be returned.
Compositions may have an additional records indicated by their
respective record types. The record may not be accessed through a
cast of the ``Composition``.
"""
def __init__(self, catalog_id=None, proxy=None, runtime=None, **kwargs):
OsidSession.__init__(self)
self._catalog_class = objects.Repository
self._session_name = 'CompositionLookupSession'
self._catalog_name = 'Repository'
OsidSession._init_object(
self,
catalog_id,
proxy,
runtime,
db_name='repository',
cat_name='Repository',
cat_class=objects.Repository)
self._kwargs = kwargs
self._status_view = ACTIVE
self._sequestered_view = SEQUESTERED
def _view_filter(self):
"""
Overrides OsidSession._view_filter to add sequestering filter.
"""
view_filter = OsidSession._view_filter(self)
if self._sequestered_view == SEQUESTERED:
view_filter['sequestered'] = False
return view_filter
def get_repository_id(self):
"""Gets the ``Repository`` ``Id`` associated with this session.
return: (osid.id.Id) - the ``Repository Id`` associated with
this session
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.resource.ResourceLookupSession.get_bin_id
return self._catalog_id
repository_id = property(fget=get_repository_id)
def get_repository(self):
"""Gets the ``Repository`` associated with this session.
return: (osid.repository.Repository) - the ``Repository``
associated with this session
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.resource.ResourceLookupSession.get_bin
return self._catalog
repository = property(fget=get_repository)
def can_lookup_compositions(self):
"""Tests if this user can perform ``Composition`` lookups.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known all methods in this
session will result in a ``PermissionDenied``. This is intended
as a hint to an application that may opt not to offer lookup
operations to unauthorized users.
return: (boolean) - ``false`` if lookup methods are not
authorized, ``true`` otherwise
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceLookupSession.can_lookup_resources
# NOTE: It is expected that real authentication hints will be
# handled in a service adapter above the pay grade of this impl.
return True
def use_comparative_composition_view(self):
"""The returns from the lookup methods may omit or translate elements based on this session, such as
authorization, and not result in an error.
This view is used when greater interoperability is desired at
the expense of precision.
*compliance: mandatory -- This method is must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceLookupSession.use_comparative_resource_view
self._use_comparative_object_view()
def use_plenary_composition_view(self):
"""A complete view of the ``Composition`` returns is desired.
Methods will return what is requested or result in an error.
This view is used when greater precision is desired at the
expense of interoperability.
*compliance: mandatory -- This method is must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceLookupSession.use_plenary_resource_view
self._use_plenary_object_view()
def use_federated_repository_view(self):
"""Federates the view for methods in this session.
A federated view will include compositions in repositories which
are children of this repository in the repository hierarchy.
*compliance: mandatory -- This method is must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceLookupSession.use_federated_bin_view
self._use_federated_catalog_view()
def use_isolated_repository_view(self):
"""Isolates the view for methods in this session.
An isolated view restricts lookups to this repository only.
*compliance: mandatory -- This method is must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceLookupSession.use_isolated_bin_view
self._use_isolated_catalog_view()
def use_active_composition_view(self):
"""Only active compositions are returned by methods in this session.
*compliance: mandatory -- This method is must be implemented.*
"""
self._status_view = ACTIVE
def use_any_status_composition_view(self):
"""All active and inactive compositions are returned by methods in this session.
*compliance: mandatory -- This method is must be implemented.*
"""
self._status_view = ANY_STATUS
def use_sequestered_composition_view(self):
"""The methods in this session omit sequestered compositions.
*compliance: mandatory -- This method is must be implemented.*
"""
self._sequestered_view = SEQUESTERED
def use_unsequestered_composition_view(self):
"""The methods in this session return all compositions, including sequestered compositions.
*compliance: mandatory -- This method is must be implemented.*
"""
self._sequestered_view = UNSEQUESTERED
@utilities.arguments_not_none
def get_composition(self, composition_id):
"""Gets the ``Composition`` specified by its ``Id``.
arg: composition_id (osid.id.Id): ``Id`` of the
``Composiiton``
return: (osid.repository.Composition) - the composition
raise: NotFound - ``composition_id`` not found
raise: NullArgument - ``composition_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method is must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceLookupSession.get_resource
# NOTE: This implementation currently ignores plenary view
collection = MongoClientValidated('repository',
collection='Composition',
runtime=self._runtime)
result = collection.find_one(
dict({'_id': ObjectId(self._get_id(composition_id, 'repository').get_identifier())},
**self._view_filter()))
return objects.Composition(result, runtime=self._runtime)
@utilities.arguments_not_none
def get_compositions_by_ids(self, composition_ids):
"""Gets a ``CompositionList`` corresponding to the given ``IdList``.
arg: composition_ids (osid.id.IdList): the list of ``Ids`` to
retrieve
return: (osid.repository.CompositionList) - the returned
``Composition list``
raise: NotFound - an ``Id`` was not found
raise: NullArgument - ``composition_ids`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceLookupSession.get_resources_by_ids
# NOTE: This implementation currently ignores plenary view
collection = MongoClientValidated('repository',
collection='Composition',
runtime=self._runtime)
object_id_list = []
for i in composition_ids:
object_id_list.append(ObjectId(self._get_id(i, 'repository').get_identifier()))
result = collection.find(
dict({'_id': {'$in': object_id_list}},
**self._view_filter()))
result = list(result)
sorted_result = []
for object_id in object_id_list:
for object_map in result:
if object_map['_id'] == object_id:
sorted_result.append(object_map)
break
return objects.CompositionList(sorted_result, runtime=self._runtime)
@utilities.arguments_not_none
def get_compositions_by_genus_type(self, composition_genus_type):
"""Gets a ``CompositionList`` corresponding to the given composition genus ``Type`` which does not include
compositions of types derived from the specified ``Type``.
arg: composition_genus_type (osid.type.Type): a composition
genus type
return: (osid.repository.CompositionList) - the returned
``Composition list``
raise: NullArgument - ``composition_genus_type`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceLookupSession.get_resources_by_genus_type
# NOTE: This implementation currently ignores plenary view
collection = MongoClientValidated('repository',
collection='Composition',
runtime=self._runtime)
result = collection.find(
dict({'genusTypeId': str(composition_genus_type)},
**self._view_filter())).sort('_id', DESCENDING)
return objects.CompositionList(result, runtime=self._runtime)
@utilities.arguments_not_none
def get_compositions_by_parent_genus_type(self, composition_genus_type):
"""Gets a ``CompositionList`` corresponding to the given composition genus ``Type`` and include any additional
compositions with genus types derived from the specified ``Type``.
arg: composition_genus_type (osid.type.Type): a composition
genus type
return: (osid.repository.CompositionList) - the returned
``Composition list``
raise: NullArgument - ``composition_genus_type`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceLookupSession.get_resources_by_parent_genus_type
return objects.CompositionList([])
@utilities.arguments_not_none
def get_compositions_by_record_type(self, composition_record_type):
"""Gets a ``CompositionList`` containing the given composition record ``Type``.
arg: composition_record_type (osid.type.Type): a composition
record type
return: (osid.repository.CompositionList) - the returned
``Composition list``
raise: NullArgument - ``composition_record_type`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceLookupSession.get_resources_by_record_type
# STILL NEED TO IMPLEMENT!!!
return objects.CompositionList([])
@utilities.arguments_not_none
def get_compositions_by_provider(self, resource_id):
"""Gets a ``CompositionList`` from the given provider ````.
In plenary mode, the returned list contains all known
compositions or an error results. Otherwise, the returned list
may contain only those compositions that are accessible through
this session.
In sequestered mode, no sequestered compositions are returned.
In unsequestered mode, all compositions are returned.
arg: resource_id (osid.id.Id): a resource ``Id``
return: (osid.repository.CompositionList) - the returned
``Composition list``
raise: NullArgument - ``resource_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
raise errors.Unimplemented()
def get_compositions(self):
"""Gets all ``Compositions``.
return: (osid.repository.CompositionList) - a list of
``Compositions``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceLookupSession.get_resources
# NOTE: This implementation currently ignores plenary view
collection = MongoClientValidated('repository',
collection='Composition',
runtime=self._runtime)
result = collection.find(self._view_filter()).sort('_id', DESCENDING)
return objects.CompositionList(result, runtime=self._runtime)
compositions = property(fget=get_compositions)
class CompositionQuerySession(abc_repository_sessions.CompositionQuerySession, osid_sessions.OsidSession):
"""This session provides methods for searching among ``Composition`` objects.
The search query is constructed using the ``CompositionQuery``.
This session defines views that offer differing behaviors when
searching.
* federated repository view: searches include compositions in
repositories of which this repository is an ancestor in the
repository hierarchy
* isolated repository view: searches are restricted to subjects in
this repository
* sequestered composition viiew: All composition methods suppress
sequestered compositions.
* unsequestered composition view: All composition methods return
all compositions.
Compositions may have a query record indicated by their respective
record types. The query record is accessed via the
``CompositionQuery``.
"""
def __init__(self, catalog_id=None, proxy=None, runtime=None, **kwargs):
OsidSession.__init__(self)
self._catalog_class = objects.Repository
self._session_name = 'CompositionQuerySession'
self._catalog_name = 'Repository'
OsidSession._init_object(
self,
catalog_id,
proxy,
runtime,
db_name='repository',
cat_name='Repository',
cat_class=objects.Repository)
self._kwargs = kwargs
self._status_view = ACTIVE
self._sequestered_view = SEQUESTERED
def _view_filter(self):
"""
Overrides OsidSession._view_filter to add sequestering filter.
"""
view_filter = OsidSession._view_filter(self)
if self._sequestered_view == SEQUESTERED:
view_filter['sequestered'] = False
return view_filter
def get_repository_id(self):
"""Gets the ``Repository`` ``Id`` associated with this session.
return: (osid.id.Id) - the ``Repository Id`` associated with
this session
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.resource.ResourceLookupSession.get_bin_id
return self._catalog_id
repository_id = property(fget=get_repository_id)
def get_repository(self):
"""Gets the ``Repository`` associated with this session.
return: (osid.repository.Repository) - the ``Repository``
associated with this session
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.resource.ResourceLookupSession.get_bin
return self._catalog
repository = property(fget=get_repository)
def can_search_compositions(self):
"""Tests if this user can perform ``Composition`` searches.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known all methods in this
session will result in a ``PermissionDenied``. This is intended
as a hint to an application that may opt not to offer search
operations to unauthorized users.
return: (boolean) - ``false`` if search methods are not
authorized, ``true`` otherwise
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceQuerySession.can_search_resources
# NOTE: It is expected that real authentication hints will be
# handled in a service adapter above the pay grade of this impl.
return True
def use_federated_repository_view(self):
"""Federates the view for methods in this session.
A federated view will include compositions in repositories which
are children of this repository in the repository hierarchy.
*compliance: mandatory -- This method is must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceLookupSession.use_federated_bin_view
self._use_federated_catalog_view()
def use_isolated_repository_view(self):
"""Isolates the view for methods in this session.
An isolated view restricts lookups to this repository only.
*compliance: mandatory -- This method is must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceLookupSession.use_isolated_bin_view
self._use_isolated_catalog_view()
def use_sequestered_composition_view(self):
"""The methods in this session omit sequestered compositions.
*compliance: mandatory -- This method is must be implemented.*
"""
self._sequestered_view = SEQUESTERED
def use_unsequestered_composition_view(self):
"""The methods in this session return all compositions, including sequestered compositions.
*compliance: mandatory -- This method is must be implemented.*
"""
self._sequestered_view = UNSEQUESTERED
def get_composition_query(self):
"""Gets a composition query.
return: (osid.repository.CompositionQuery) - the composition
query
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceQuerySession.get_resource_query_template
return queries.CompositionQuery(runtime=self._runtime)
composition_query = property(fget=get_composition_query)
@utilities.arguments_not_none
def get_compositions_by_query(self, composition_query):
"""Gets a list of ``Compositions`` matching the given composition query.
arg: composition_query (osid.repository.CompositionQuery):
the composition query
return: (osid.repository.CompositionList) - the returned
``CompositionList``
raise: NullArgument - ``composition_query`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
raise: Unsupported - ``composition_query`` is not of this
service
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceQuerySession.get_resources_by_query
and_list = list()
or_list = list()
for term in composition_query._query_terms:
and_list.append({term: composition_query._query_terms[term]})
for term in composition_query._keyword_terms:
or_list.append({term: composition_query._keyword_terms[term]})
if or_list:
and_list.append({'$or': or_list})
view_filter = self._view_filter()
if view_filter:
and_list.append(view_filter)
if and_list:
query_terms = {'$and': and_list}
collection = MongoClientValidated('repository',
collection='Composition',
runtime=self._runtime)
result = collection.find(query_terms).sort('_id', DESCENDING)
return objects.CompositionList(result, runtime=self._runtime)
class CompositionSearchSession(abc_repository_sessions.CompositionSearchSession, CompositionQuerySession):
"""This session provides methods for searching among ``Composition`` objects.
The search query is constructed using the ``CompositionQuery``.
``get_compositions_by_query()`` is the basic search method and
returns a list of ``Compositions``. A more advanced search may be
performed with ``getCompositionsBySearch()``. It accepts an
``Composition`` in addition to the query for the purpose of
specifying additional options affecting the entire search, such as
ordering. ``get_compositions_by_search()`` returns an
``CompositionSearchResults`` that can be used to access the
resulting ``Composition`` or be used to perform a search within the
result set through ``CompositionSearch``.
This session defines views that offer differing behaviors when
searching.
* federated repository view: searches include compositions in
repositories of which this repository is an ancestor in the
repository hierarchy
* isolated repository view: searches are restricted to subjects in
this repository
Compositions may have a query record indicated by their respective
record types. The query record is accessed via the
``CompositionQuery``.
"""
def get_composition_search(self):
"""Gets a composition search.
return: (osid.repository.CompositionSearch) - the composition
search
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceSearchSession.get_resource_search_template
return searches.CompositionSearch(runtime=self._runtime)
composition_search = property(fget=get_composition_search)
def get_composition_search_order(self):
"""Gets a composition search order.
The ``CompositionSearchOrder`` is supplied to an
``CompositionSearch`` to specify the ordering of results.
return: (osid.repository.CompositionSearchOrder) - the
composition search order
*compliance: mandatory -- This method must be implemented.*
"""
raise errors.Unimplemented()
composition_search_order = property(fget=get_composition_search_order)
@utilities.arguments_not_none
def get_compositions_by_search(self, composition_query, composition_search):
"""Gets the search results matching the given search query using the given search.
arg: composition_query (osid.repository.CompositionQuery):
the composition query
arg: composition_search (osid.repository.CompositionSearch):
the composition search
return: (osid.repository.CompositionSearchResults) - the
composition search results
raise: NullArgument - ``composition_query`` or
``composition_search`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
raise: Unsupported - ``composition_query`` or
``composition_search`` is not of this service
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceSearchSession.get_resources_by_search_template
# Copied from osid.resource.ResourceQuerySession.get_resources_by_query_template
and_list = list()
or_list = list()
for term in composition_query._query_terms:
and_list.append({term: composition_query._query_terms[term]})
for term in composition_query._keyword_terms:
or_list.append({term: composition_query._keyword_terms[term]})
if composition_search._id_list is not None:
identifiers = [ObjectId(i.identifier) for i in composition_search._id_list]
and_list.append({'_id': {'$in': identifiers}})
if or_list:
and_list.append({'$or': or_list})
view_filter = self._view_filter()
if view_filter:
and_list.append(view_filter)
if and_list:
query_terms = {'$and': and_list}
collection = MongoClientValidated('repository',
collection='Composition',
runtime=self._runtime)
if composition_search.start is not None and composition_search.end is not None:
result = collection.find(query_terms)[composition_search.start:composition_search.end]
else:
result = collection.find(query_terms)
return searches.CompositionSearchResults(result, runtime=self._runtime)
@utilities.arguments_not_none
def get_composition_query_from_inspector(self, composition_query_inspector):
"""Gets a composition query from an inspector.
The inspector is available from a ``CompositionSearchResults``.
arg: composition_query_inspector
(osid.repository.CompositionQueryInspector): a
composition query inspector
return: (osid.repository.CompositionQuery) - the composition
query
raise: NullArgument - ``composition_query_inspector`` is
``null``
raise: Unsupported - ``composition_query_inspector`` is not of
this service
*compliance: mandatory -- This method must be implemented.*
"""
raise errors.Unimplemented()
class CompositionAdminSession(abc_repository_sessions.CompositionAdminSession, osid_sessions.OsidSession):
"""This session creates, updates, and deletes ``Compositions``.
The data for create and update is provided by the consumer via the
form object. ``OsidForms`` are requested for each create or update
and may not be reused.
Create and update operations differ in their usage. To create a
``Composition,`` a ``CompositionForm`` is requested using
``get_composition_form_for_create()`` specifying the desired record
``Types`` or none if no record ``Types`` are needed. The returned
``CompositionForm`` will indicate that it is to be used with a
create operation and can be used to examine metdata or validate data
prior to creation. Once the ``CompositionForm`` is submiited to a
create operation, it cannot be reused with another create operation
unless the first operation was unsuccessful. Each
``CompositionForm`` corresponds to an attempted transaction.
For updates, ``CompositionForms`` are requested to the
``Composition`` ``Id`` that is to be updated using
``getCompositionFormForUpdate()``. Similarly, the
``CompositionForm`` has metadata about the data that can be updated
and it can perform validation before submitting the update. The
``CompositionForm`` can only be used once for a successful update
and cannot be reused.
The delete operations delete ``Compositions``. To unmap a
``Composition`` from the current ``Repository,`` the
``CompositionRepositoryAssignmentSession`` should be used. These
delete operations attempt to remove the ``Bid`` itself thus removing
it from all known ``Repository`` catalogs.
This session includes an ``Id`` aliasing mechanism to assign an
external ``Id`` to an internally assigned Id.
"""
def __init__(self, catalog_id=None, proxy=None, runtime=None, **kwargs):
OsidSession.__init__(self)
self._catalog_class = objects.Repository
self._session_name = 'CompositionAdminSession'
self._catalog_name = 'Repository'
OsidSession._init_object(
self,
catalog_id,
proxy,
runtime,
db_name='repository',
cat_name='Repository',
cat_class=objects.Repository)
self._forms = dict()
self._kwargs = kwargs
def get_repository_id(self):
"""Gets the ``Repository`` ``Id`` associated with this session.
return: (osid.id.Id) - the ``Repository Id`` associated with
this session
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.resource.ResourceLookupSession.get_bin_id
return self._catalog_id
repository_id = property(fget=get_repository_id)
def get_repository(self):
"""Gets the ``Repository`` associated with this session.
return: (osid.repository.Repository) - the ``Repository``
associated with this session
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.resource.ResourceLookupSession.get_bin
return self._catalog
repository = property(fget=get_repository)
def can_create_compositions(self):
"""Tests if this user can create ``Compositions``.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known creating a
``Composition`` will result in a ``PermissionDenied``. This is
intended as a hint to an application that may not wish to offer
create operations to unauthorized users.
return: (boolean) - ``false`` if ``Composition`` creation is not
authorized, ``true`` otherwise
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceAdminSession.can_create_resources
# NOTE: It is expected that real authentication hints will be
# handled in a service adapter above the pay grade of this impl.
return True
@utilities.arguments_not_none
def can_create_composition_with_record_types(self, composition_record_types):
"""Tests if this user can create a single ``Composition`` using the desired record types.
While ``RepositoryManager.getCompositionRecordTypes()`` can be
used to examine which records are supported, this method tests
which record(s) are required for creating a specific
``Composition``. Providing an empty array tests if a
``Composition`` can be created with no records.
arg: composition_record_types (osid.type.Type[]): array of
composition record types
return: (boolean) - ``true`` if ``Composition`` creation using
the specified ``Types`` is supported, ``false``
otherwise
raise: NullArgument - ``composition_record_types`` is ``null``
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceAdminSession.can_create_resource_with_record_types
# NOTE: It is expected that real authentication hints will be
# handled in a service adapter above the pay grade of this impl.
return True
@utilities.arguments_not_none
def get_composition_form_for_create(self, composition_record_types):
"""Gets the composition form for creating new compositions.
A new form should be requested for each create transaction.
arg: composition_record_types (osid.type.Type[]): array of
composition record types
return: (osid.repository.CompositionForm) - the composition form
raise: NullArgument - ``composition_record_types`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
raise: Unsupported - unable to get form for requested record
types
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceAdminSession.get_resource_form_for_create_template
for arg in composition_record_types:
if not isinstance(arg, ABCType):
raise errors.InvalidArgument('one or more argument array elements is not a valid OSID Type')
if composition_record_types == []:
obj_form = objects.CompositionForm(
repository_id=self._catalog_id,
runtime=self._runtime,
effective_agent_id=self.get_effective_agent_id())
else:
obj_form = objects.CompositionForm(
repository_id=self._catalog_id,
record_types=composition_record_types,
runtime=self._runtime,
effective_agent_id=self.get_effective_agent_id())
self._forms[obj_form.get_id().get_identifier()] = not CREATED
return obj_form
@utilities.arguments_not_none
def create_composition(self, composiiton_form):
"""Creates a new ``Composition``.
arg: composiiton_form (osid.repository.CompositionForm): the
form for this ``Composition``
return: (osid.repository.Composition) - the new ``Composition``
raise: IllegalState - ``composition_form`` already used in a
create transaction
raise: InvalidArgument - one or more of the form elements is
invalid
raise: NullArgument - ``composition_form`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
raise: Unsupported - ``composition_form`` did not originate
from ``get_composition_form_for_create()``
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceAdminSession.create_resource_template
collection = MongoClientValidated('repository',
collection='Composition',
runtime=self._runtime)
if not isinstance(composiiton_form, ABCCompositionForm):
raise errors.InvalidArgument('argument type is not an CompositionForm')
if composiiton_form.is_for_update():
raise errors.InvalidArgument('the CompositionForm is for update only, not create')
try:
if self._forms[composiiton_form.get_id().get_identifier()] == CREATED:
raise errors.IllegalState('composiiton_form already used in a create transaction')
except KeyError:
raise errors.Unsupported('composiiton_form did not originate from this session')
if not composiiton_form.is_valid():
raise errors.InvalidArgument('one or more of the form elements is invalid')
insert_result = collection.insert_one(composiiton_form._my_map)
self._forms[composiiton_form.get_id().get_identifier()] = CREATED
result = objects.Composition(
collection.find_one({'_id': insert_result.inserted_id}),
runtime=self._runtime)
return result
def can_update_compositions(self):
"""Tests if this user can update ``Compositions``.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known updating a
``Composition`` will result in a ``PermissionDenied``. This is
intended as a hint to an application that may not wish to offer
update operations to unauthorized users.
return: (boolean) - ``false`` if ``Composition`` modification is
not authorized, ``true`` otherwise
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceAdminSession.can_create_resources
# NOTE: It is expected that real authentication hints will be
# handled in a service adapter above the pay grade of this impl.
return True
@utilities.arguments_not_none
def get_composition_form_for_update(self, composition_id):
"""Gets the composition form for updating an existing composition.
A new composition form should be requested for each update
transaction.
arg: composition_id (osid.id.Id): the ``Id`` of the
``Composition``
return: (osid.repository.CompositionForm) - the composition form
raise: NotFound - ``composition_id`` is not found
raise: NullArgument - ``composition_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceAdminSession.get_resource_form_for_update_template
collection = MongoClientValidated('repository',
collection='Composition',
runtime=self._runtime)
if not isinstance(composition_id, ABCId):
raise errors.InvalidArgument('the argument is not a valid OSID Id')
if composition_id.get_identifier_namespace() != 'repository.Composition':
if composition_id.get_authority() != self._authority:
raise errors.InvalidArgument()
else:
composition_id = self._get_composition_id_with_enclosure(composition_id)
result = collection.find_one({'_id': ObjectId(composition_id.get_identifier())})
obj_form = objects.CompositionForm(result, runtime=self._runtime)
self._forms[obj_form.get_id().get_identifier()] = not UPDATED
return obj_form
def _get_composition_id_with_enclosure(self, enclosure_id):
"""Create an Composition with an enclosed foreign object.
return: (osid.id.Id) - the id of the new Composition
"""
mgr = self._get_provider_manager('REPOSITORY')
query_session = mgr.get_composition_query_session_for_repository(self._catalog_id)
query_form = query_session.get_composition_query()
query_form.match_enclosed_object_id(enclosure_id)
query_result = query_session.get_compositions_by_query(query_form)
if query_result.available() > 0:
composition_id = query_result.next().get_id()
else:
create_form = self.get_composition_form_for_create([ENCLOSURE_RECORD_TYPE])
create_form.set_enclosed_object(enclosure_id)
composition_id = self.create_composition(create_form).get_id()
return composition_id
@utilities.arguments_not_none
def duplicate_composition(self, composition_id):
collection = MongoClientValidated('repository',
collection='Composition',
runtime=self._runtime)
mgr = self._get_provider_manager('REPOSITORY')
lookup_session = mgr.get_composition_lookup_session()
lookup_session.use_federated_repository_view()
try:
lookup_session.use_unsequestered_composition_view()
except AttributeError:
pass
composition_map = dict(lookup_session.get_composition(composition_id)._my_map)
del composition_map['_id']
if 'repositoryId' in composition_map:
composition_map['repositoryId'] = str(self._catalog_id)
if 'assignedRepositoryIds' in composition_map:
composition_map['assignedRepositoryIds'] = [str(self._catalog_id)]
insert_result = collection.insert_one(composition_map)
result = objects.Composition(
collection.find_one({'_id': insert_result.inserted_id}),
runtime=self._runtime)
return result
@utilities.arguments_not_none
def update_composition(self, composiiton_form):
"""Updates an existing composition.
arg: composiiton_form (osid.repository.CompositionForm): the
form containing the elements to be updated
raise: IllegalState - ``composition_form`` already used in an
update transaction
raise: InvalidArgument - the form contains an invalid value
raise: NullArgument - ``composition_form`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
raise: Unsupported - ``composition_form`` did not originate
from ``get_composition_form_for_update()``
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceAdminSession.update_resource_template
collection = MongoClientValidated('repository',
collection='Composition',
runtime=self._runtime)
if not isinstance(composiiton_form, ABCCompositionForm):
raise errors.InvalidArgument('argument type is not an CompositionForm')
if not composiiton_form.is_for_update():
raise errors.InvalidArgument('the CompositionForm is for update only, not create')
try:
if self._forms[composiiton_form.get_id().get_identifier()] == UPDATED:
raise errors.IllegalState('composiiton_form already used in an update transaction')
except KeyError:
raise errors.Unsupported('composiiton_form did not originate from this session')
if not composiiton_form.is_valid():
raise errors.InvalidArgument('one or more of the form elements is invalid')
collection.save(composiiton_form._my_map)
self._forms[composiiton_form.get_id().get_identifier()] = UPDATED
# Note: this is out of spec. The OSIDs don't require an object to be returned:
return objects.Composition(
composiiton_form._my_map,
runtime=self._runtime)
def can_delete_compositions(self):
"""Tests if this user can delete ``Compositions``.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known deleting a
``Composition`` will result in a ``PermissionDenied``. This is
intended as a hint to an application that may not wish to offer
delete operations to unauthorized users.
return: (boolean) - ``false`` if ``Composition`` deletion is not
authorized, ``true`` otherwise
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceAdminSession.can_create_resources
# NOTE: It is expected that real authentication hints will be
# handled in a service adapter above the pay grade of this impl.
return True
@utilities.arguments_not_none
def delete_composition(self, composition_id):
"""Deletes a ``Composition``.
arg: composition_id (osid.id.Id): the ``Id`` of the
``Composition`` to remove
raise: NotFound - ``composition_id`` not found
raise: NullArgument - ``composition_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceAdminSession.delete_resource_template
collection = MongoClientValidated('repository',
collection='Composition',
runtime=self._runtime)
if not isinstance(composition_id, ABCId):
raise errors.InvalidArgument('the argument is not a valid OSID Id')
composition_map = collection.find_one(
dict({'_id': ObjectId(composition_id.get_identifier())},
**self._view_filter()))
objects.Composition(composition_map, runtime=self._runtime)._delete()
collection.delete_one({'_id': ObjectId(composition_id.get_identifier())})
@utilities.arguments_not_none
def delete_composition_node(self, composition_id):
"""Deletes a ``Composition`` and all contained children.
arg: composition_id (osid.id.Id): the ``Id`` of the
``Composition`` to remove
raise: NotFound - ``composition_id`` not found
raise: NullArgument - ``composition_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
raise errors.Unimplemented()
@utilities.arguments_not_none
def add_composition_child(self, composition_id, child_composition_id):
"""Adds a composition to a parent composition.
arg: composition_id (osid.id.Id): the ``Id`` of a parent
``Composition``
arg: child_composition_id (osid.id.Id): the ``Id`` of a child
``Composition``
raise: AlreadyExists - ``child_composition_id`` is already a
child of ``composition_id``
raise: NotFound - ``composition_id`` or
``child_composition_id`` is not found
raise: NullArgument - ``composition_id`` or
``child_composition_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
raise errors.Unimplemented()
@utilities.arguments_not_none
def remove_composition_child(self, composition_id, child_composition_id):
"""Removes a composition from a parent composition.
arg: composition_id (osid.id.Id): the ``Id`` of a parent
``Composition``
arg: child_composition_id (osid.id.Id): the ``Id`` of a child
``Composition``
raise: NotFound - ``composition_id`` or
``child_composition_id`` is not found or not related
raise: NullArgument - ``composition_id`` or
``child_composition_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
raise errors.Unimplemented()
def can_manage_composition_aliases(self):
"""Tests if this user can manage ``Id`` aliases for ``Compositions``.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known changing an alias
will result in a ``PermissionDenied``. This is intended as a
hint to an application that may opt not to offer alias
operations to an unauthorized user.
return: (boolean) - ``false`` if ``Composition`` aliasing is not
authorized, ``true`` otherwise
*compliance: mandatory -- This method must be implemented.*
"""
raise errors.Unimplemented()
@utilities.arguments_not_none
def alias_composition(self, composition_id, alias_id):
"""Adds an ``Id`` to a ``Composition`` for the purpose of creating compatibility.
The primary ``Id`` of the ``Composition`` is determined by the
provider. The new ``Id`` is an alias to the primary ``Id``. If
the alias is a pointer to another composition, it is reassigned
to the given composition ``Id``.
arg: composition_id (osid.id.Id): the ``Id`` of a
``Composition``
arg: alias_id (osid.id.Id): the alias ``Id``
raise: AlreadyExists - ``alias_id`` is in use as a primary
``Id``
raise: NotFound - ``composition_id`` not found
raise: NullArgument - ``composition_id`` or ``alias_id`` is
``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceAdminSession.alias_resources_template
self._alias_id(primary_id=composition_id, equivalent_id=alias_id)
class CompositionRepositorySession(abc_repository_sessions.CompositionRepositorySession, osid_sessions.OsidSession):
"""This session provides methods to retrieve ``Composition`` to ``Repository`` mappings.
A ``Composition`` may appear in multiple ``Repository`` objects.
Each ``Repository`` may have its own authorizations governing who is
allowed to look at it.
This lookup session defines several views:
* comparative view: elements may be silently omitted or re-ordered
* plenary view: provides a complete result set or is an error
condition
"""
_session_name = 'CompositionRepositorySession'
def __init__(self, proxy=None, runtime=None, **kwargs):
OsidSession._init_catalog(self, proxy, runtime)
self._catalog_view = COMPARATIVE
self._kwargs = kwargs
def use_comparative_composition_repository_view(self):
"""The returns from the lookup methods may omit or translate elements based on this session, such as
authorization, and not result in an error.
This view is used when greater interoperability is desired at
the expense of precision.
*compliance: mandatory -- This method is must be implemented.*
"""
# Implemented from template for
# osid.resource.BinLookupSession.use_comparative_bin_view
self._catalog_view = COMPARATIVE
def use_plenary_composition_repository_view(self):
"""A complete view of the ``Composition`` and ``Repository`` returns is desired.
Methods will return what is requested or result in an error.
This view is used when greater precision is desired at the
expense of interoperability.
*compliance: mandatory -- This method is must be implemented.*
"""
# Implemented from template for
# osid.resource.BinLookupSession.use_plenary_bin_view
self._catalog_view = PLENARY
def can_lookup_composition_repository_mappings(self):
"""Tests if this user can perform lookups of composition/repository mappings.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known lookup methods in
this session will result in a ``PermissionDenied``. This is
intended as a hint to an application that may opt not to offer
lookup operations to unauthorized users.
return: (boolean) - ``false`` if looking up mappings is not
authorized, ``true`` otherwise
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceBinSession.can_lookup_resource_bin_mappings
# NOTE: It is expected that real authentication hints will be
# handled in a service adapter above the pay grade of this impl.
return True
@utilities.arguments_not_none
def get_composition_ids_by_repository(self, repository_id):
"""Gets the list of ``Composition`` ``Ids`` associated with a ``Repository``.
arg: repository_id (osid.id.Id): ``Id`` of the ``Repository``
return: (osid.id.IdList) - list of related composition ``Ids``
raise: NotFound - ``repository_id`` is not found
raise: NullArgument - ``repository_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceBinSession.get_resource_ids_by_bin
id_list = []
for composition in self.get_compositions_by_repository(repository_id):
id_list.append(composition.get_id())
return IdList(id_list)
@utilities.arguments_not_none
def get_compositions_by_repository(self, repository_id):
"""Gets the list of ``Compositions`` associated with a ``Repository``.
arg: repository_id (osid.id.Id): ``Id`` of the ``Repository``
return: (osid.repository.CompositionList) - list of related
compositions
raise: NotFound - ``repository_id`` is not found
raise: NullArgument - ``repository_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceBinSession.get_resources_by_bin
mgr = self._get_provider_manager('REPOSITORY')
lookup_session = mgr.get_composition_lookup_session_for_repository(repository_id)
lookup_session.use_isolated_repository_view()
return lookup_session.get_compositions()
@utilities.arguments_not_none
def get_composition_ids_by_repositories(self, repository_ids):
"""Gets the list of ``Composition`` ``Ids`` corresponding to a list of ``Repository`` objects.
arg: repository_ids (osid.id.IdList): list of repository
``Ids``
return: (osid.id.IdList) - list of composition ``Ids``
raise: NullArgument - ``repository_ids`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceBinSession.get_resource_ids_by_bins
id_list = []
for composition in self.get_compositions_by_repositories(repository_ids):
id_list.append(composition.get_id())
return IdList(id_list)
@utilities.arguments_not_none
def get_compoitions_by_repositories(self, repository_ids):
"""Gets the list of ``Compositions`` corresponding to a list of ``Repository`` objects.
arg: repository_ids (osid.id.IdList): list of repository
``Ids``
return: (osid.repository.CompositionList) - list of Compositions
raise: NullArgument - ``repository_ids`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceBinSession.get_resources_by_bins
composition_list = []
for repository_id in repository_ids:
composition_list += list(
self.get_compositions_by_repository(repository_id))
return objects.CompositionList(composition_list)
@utilities.arguments_not_none
def get_repository_ids_by_composition(self, composition_id):
"""Gets the ``Repository`` ``Ids`` mapped to a ``Composition``.
arg: composition_id (osid.id.Id): ``Id`` of a ``Composition``
return: (osid.id.IdList) - list of repository ``Ids``
raise: NotFound - ``composition_id`` is not found
raise: NullArgument - ``composition_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
mgr = self._get_provider_manager('REPOSITORY', local=True)
lookup_session = mgr.get_composition_lookup_session()
lookup_session.use_federated_repository_view()
lookup_session.use_unsequestered_composition_view()
composition = lookup_session.get_composition(composition_id)
id_list = []
if 'assignedRepositoryIds' in composition._my_map:
for idstr in composition._my_map['assignedRepositoryIds']:
id_list.append(Id(idstr))
return IdList(id_list)
@utilities.arguments_not_none
def get_repositories_by_composition(self, composition_id):
"""Gets the ``Repository`` objects mapped to a ``Composition``.
arg: composition_id (osid.id.Id): ``Id`` of a ``Composition``
return: (osid.repository.RepositoryList) - list of repositories
raise: NotFound - ``composition_id`` is not found
raise: NullArgument - ``composition_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceBinSession.get_bins_by_resource
mgr = self._get_provider_manager('REPOSITORY')
lookup_session = mgr.get_repository_lookup_session()
return lookup_session.get_repositories_by_ids(
self.get_repository_ids_by_composition(composition_id))
class CompositionRepositoryAssignmentSession(abc_repository_sessions.CompositionRepositoryAssignmentSession, osid_sessions.OsidSession):
"""This session provides methods to re-assign ``Compositions`` to ``Repository`` objects.
A ``Composition`` may be associated with multiple ``Repository``
objects. Removing the last reference to a ``Composition`` is the
equivalent of deleting it. Each ``Repository`` may have its own
authorizations governing who is allowed to operate on it.
Moving or adding a reference of a ``Composition`` to another
``Repository`` is not a copy operation (eg: does not change its
``Id`` ).
"""
def __init__(self, proxy=None, runtime=None, **kwargs):
OsidSession._init_catalog(self, proxy, runtime)
self._session_name = 'CompositionRepositoryAssignmentSession'
self._catalog_name = 'Repository'
self._forms = dict()
self._kwargs = kwargs
def can_assign_compositions(self):
"""Tests if this user can alter composition/repository mappings.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known mapping methods in
this session will result in a ``PermissionDenied``. This is
intended as a hint to an application that may opt not to offer
assignment operations to unauthorized users.
return: (boolean) - ``false`` if mapping is not authorized,
``true`` otherwise
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceBinAssignmentSession.can_assign_resources
# NOTE: It is expected that real authentication hints will be
# handled in a service adapter above the pay grade of this impl.
return True
@utilities.arguments_not_none
def can_assign_compositions_to_repository(self, repository_id):
"""Tests if this user can alter composition/repository mappings.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known mapping methods in
this session will result in a ``PermissionDenied``. This is
intended as a hint to an application that may opt not to offer
assignment operations to unauthorized users.
arg: repository_id (osid.id.Id): the ``Id`` of the
``Repository``
return: (boolean) - ``false`` if mapping is not authorized,
``true`` otherwise
raise: NullArgument - ``repository_id`` is ``null``
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceBinAssignmentSession.can_assign_resources_to_bin
# NOTE: It is expected that real authentication hints will be
# handled in a service adapter above the pay grade of this impl.
if repository_id.get_identifier() == '000000000000000000000000':
return False
return True
@utilities.arguments_not_none
def get_assignable_repository_ids(self, repository_id):
"""Gets a list of repositories including and under the given repository node in which any composition can be
assigned.
arg: repository_id (osid.id.Id): the ``Id`` of the
``Repository``
return: (osid.id.IdList) - list of assignable repository ``Ids``
raise: NullArgument - ``repository_id`` is ``null``
raise: OperationFailed - unable to complete request
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceBinAssignmentSession.get_assignable_bin_ids
# This will likely be overridden by an authorization adapter
mgr = self._get_provider_manager('REPOSITORY', local=True)
lookup_session = mgr.get_repository_lookup_session()
compositions = lookup_session.get_repositories()
id_list = []
for composition in compositions:
id_list.append(compositions.get_id())
return IdList(id_list)
@utilities.arguments_not_none
def get_assignable_repository_ids_for_composition(self, repository_id, composition_id):
"""Gets a list of repositories including and under the given repository node in which a specific composition can
be assigned.
arg: repository_id (osid.id.Id): the ``Id`` of the
``Repository``
arg: composition_id (osid.id.Id): the ``Id`` of the
``Composition``
return: (osid.id.IdList) - list of assignable repository ``Ids``
raise: NullArgument - ``repository_id`` or ``composition_id``
is ``null``
raise: OperationFailed - unable to complete request
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceBinAssignmentSession.get_assignable_bin_ids_for_resource
# This will likely be overridden by an authorization adapter
return self.get_assignable_bin_ids()
@utilities.arguments_not_none
def assign_composition_to_repository(self, composition_id, repository_id):
"""Adds an existing ``Composition`` to a ``Repository``.
arg: composition_id (osid.id.Id): the ``Id`` of the
``Composition``
arg: repository_id (osid.id.Id): the ``Id`` of the
``Repository``
raise: AlreadyExists - ``composition_id`` already assigned to
``repository_id``
raise: NotFound - ``composition_id`` or ``repository_id`` not
found
raise: NullArgument - ``composition_id`` or ``repository_id``
is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceBinAssignmentSession.assign_resource_to_bin
mgr = self._get_provider_manager('REPOSITORY', local=True)
lookup_session = mgr.get_repository_lookup_session()
lookup_session.get_repository(repository_id) # to raise NotFound
self._assign_object_to_catalog(composition_id, repository_id)
@utilities.arguments_not_none
def unassign_composition_from_repository(self, composition_id, repository_id):
"""Removes ``Composition`` from a ``Repository``.
arg: composition_id (osid.id.Id): the ``Id`` of the
``Composition``
arg: repository_id (osid.id.Id): the ``Id`` of the
``Repository``
raise: NotFound - ``composition_id`` or ``repository_id`` not
found or ``composition_id`` not assigned to
``repository_id``
raise: NullArgument - ``composition_id`` or ``repository_id``
is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceBinAssignmentSession.unassign_resource_from_bin
mgr = self._get_provider_manager('REPOSITORY', local=True)
lookup_session = mgr.get_repository_lookup_session()
cat = lookup_session.get_repository(repository_id) # to raise NotFound
self._unassign_object_from_catalog(composition_id, repository_id)
class RepositoryLookupSession(abc_repository_sessions.RepositoryLookupSession, osid_sessions.OsidSession):
"""This session provides methods for retrieving ``Repository`` objects.
The ``Repository`` represents a collection of ``Assets`` and
``Compositions``.
This session defines views that offer differing behaviors when
retrieving multiple objects.
* comparative view: elements may be silently omitted or re-ordered
* plenary view: provides a complete set or is an error condition
Generally, the comparative view should be used for most applications
as it permits operation even if there is data that cannot be
accessed. For example, a browsing application may only need to
examine the ``Repositories`` it can access, without breaking
execution. However, an administrative application may require all
``Repository`` elements to be available.
Repositories may have an additional records indicated by their
respective record types. The record may not be accessed through a
cast of the ``Repository``.
"""
_session_name = 'RepositoryLookupSession'
def __init__(self, proxy=None, runtime=None, **kwargs):
OsidSession._init_catalog(self, proxy, runtime)
self._catalog_view = COMPARATIVE
self._kwargs = kwargs
def can_lookup_repositories(self):
"""Tests if this user can perform ``Repository`` lookups.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known all methods in this
session will result in a ``PermissionDenied``. This is intended
as a hint to an application that may opt not to offer lookup
operations to unauthorized users.
return: (boolean) - ``false`` if lookup methods are not
authorized, ``true`` otherwise
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceLookupSession.can_lookup_resources
# NOTE: It is expected that real authentication hints will be
# handled in a service adapter above the pay grade of this impl.
return True
def use_comparative_repository_view(self):
"""The returns from the lookup methods may omit or translate elements based on this session, such as
authorization, and not result in an error.
This view is used when greater interoperability is desired at
the expense of precision.
*compliance: mandatory -- This method is must be implemented.*
"""
# Implemented from template for
# osid.resource.BinLookupSession.use_comparative_bin_view
self._catalog_view = COMPARATIVE
def use_plenary_repository_view(self):
"""A complete view of the ``Repository`` returns is desired.
Methods will return what is requested or result in an error.
This view is used when greater precision is desired at the
expense of interoperability.
*compliance: mandatory -- This method is must be implemented.*
"""
# Implemented from template for
# osid.resource.BinLookupSession.use_plenary_bin_view
self._catalog_view = PLENARY
@utilities.arguments_not_none
def get_repository(self, repository_id):
"""Gets the ``Repository`` specified by its ``Id``.
In plenary mode, the exact ``Id`` is found or a ``NotFound``
results. Otherwise, the returned ``Repository`` may have a
different ``Id`` than requested, such as the case where a
duplicate ``Id`` was assigned to a ``Repository`` and retained
for compatibility.
arg: repository_id (osid.id.Id): ``Id`` of the ``Repository``
return: (osid.repository.Repository) - the repository
raise: NotFound - ``repository_id`` not found
raise: NullArgument - ``repository_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method is must be implemented.*
"""
# Implemented from template for
# osid.resource.BinLookupSession.get_bin
collection = MongoClientValidated('repository',
collection='Repository',
runtime=self._runtime)
# Need to consider how to best deal with the "phantom root" catalog issue
if repository_id.get_identifier() == '000000000000000000000000':
return self._get_phantom_root_catalog(cat_class=objects.Repository, cat_name='Repository')
try:
result = collection.find_one({'_id': ObjectId(repository_id.get_identifier())})
except errors.NotFound:
# Try creating an orchestrated Repository. Let it raise errors.NotFound()
result = self._create_orchestrated_cat(repository_id, 'repository', 'Repository')
return objects.Repository(result, runtime=self._runtime)
@utilities.arguments_not_none
def get_repositories_by_ids(self, repository_ids):
"""Gets a ``RepositoryList`` corresponding to the given ``IdList``.
In plenary mode, the returned list contains all of the
repositories specified in the ``Id`` list, in the order of the
list, including duplicates, or an error results if an ``Id`` in
the supplied list is not found or inaccessible. Otherwise,
inaccessible ``Repositories`` may be omitted from the list and
may present the elements in any order including returning a
unique set.
arg: repository_ids (osid.id.IdList): the list of ``Ids`` to
retrieve
return: (osid.repository.RepositoryList) - the returned
``Repository list``
raise: NotFound - an ``Id`` was not found
raise: NullArgument - ``repository_ids`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.BinLookupSession.get_bins_by_ids_template
# NOTE: This implementation currently ignores plenary view
# Also, this should be implemented to use get_Repository() instead of direct to database
catalog_id_list = []
for i in repository_ids:
catalog_id_list.append(ObjectId(i.get_identifier()))
collection = MongoClientValidated('repository',
collection='Repository',
runtime=self._runtime)
result = collection.find({'_id': {'$in': catalog_id_list}}).sort('_id', DESCENDING)
return objects.RepositoryList(result, runtime=self._runtime)
@utilities.arguments_not_none
def get_repositories_by_genus_type(self, repository_genus_type):
"""Gets a ``RepositoryList`` corresponding to the given repository genus ``Type`` which does not include
repositories of types derived from the specified ``Type``.
In plenary mode, the returned list contains all known
repositories or an error results. Otherwise, the returned list
may contain only those repositories that are accessible through
this session.
arg: repository_genus_type (osid.type.Type): a repository
genus type
return: (osid.repository.RepositoryList) - the returned
``Repository list``
raise: NullArgument - ``repository_genus_type`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
raise errors.Unimplemented()
@utilities.arguments_not_none
def get_repositories_by_parent_genus_type(self, repository_genus_type):
"""Gets a ``RepositoryList`` corresponding to the given repository genus ``Type`` and include any additional
repositories with genus types derived from the specified ``Type``.
In plenary mode, the returned list contains all known
repositories or an error results. Otherwise, the returned list
may contain only those repositories that are accessible through
this session.
arg: repository_genus_type (osid.type.Type): a repository
genus type
return: (osid.repository.RepositoryList) - the returned
``Repository list``
raise: NullArgument - ``repository_genus_type`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
raise errors.Unimplemented()
@utilities.arguments_not_none
def get_repositories_by_record_type(self, repository_record_type):
"""Gets a ``RepositoryList`` containing the given repository record ``Type``.
In plenary mode, the returned list contains all known
repositories or an error results. Otherwise, the returned list
may contain only those repositories that are accessible through
this session.
arg: repository_record_type (osid.type.Type): a repository
record type
return: (osid.repository.RepositoryList) - the returned
``Repository list``
raise: NullArgument - ``repository_record_type`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
raise errors.Unimplemented()
@utilities.arguments_not_none
def get_repositories_by_provider(self, resource_id):
"""Gets a ``RepositoryList`` from the given provider ````.
In plenary mode, the returned list contains all known
repositories or an error results. Otherwise, the returned list
may contain only those repositories that are accessible through
this session.
arg: resource_id (osid.id.Id): a resource ``Id``
return: (osid.repository.RepositoryList) - the returned
``Repository list``
raise: NullArgument - ``resource_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
raise errors.Unimplemented()
def get_repositories(self):
"""Gets all ``Repositories``.
In plenary mode, the returned list contains all known
repositories or an error results. Otherwise, the returned list
may contain only those repositories that are accessible through
this session.
return: (osid.repository.RepositoryList) - a list of
``Repositories``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.BinLookupSession.get_bins_template
# NOTE: This implementation currently ignores plenary view
collection = MongoClientValidated('repository',
collection='Repository',
runtime=self._runtime)
result = collection.find().sort('_id', DESCENDING)
return objects.RepositoryList(result, runtime=self._runtime)
repositories = property(fget=get_repositories)
class RepositoryQuerySession(abc_repository_sessions.RepositoryQuerySession, osid_sessions.OsidSession):
"""This session provides methods for searching among ``Repository`` objects.
The search query is constructed using the ``RepositoryQuery``.
Repositories may have a query record indicated by their respective
record types. The query record is accessed via the
``RepositoryQuery``.
"""
_session_name = 'RepositoryQuerySession'
def __init__(self, proxy=None, runtime=None, **kwargs):
OsidSession._init_catalog(self, proxy, runtime)
self._forms = dict()
self._kwargs = kwargs
def can_search_repositories(self):
"""Tests if this user can perform ``Repository`` searches.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known all methods in this
session will result in a ``PermissionDenied``. This is intended
as a hint to an application that may opt not to offer search
operations to unauthorized users.
return: (boolean) - ``false`` if search methods are not
authorized, ``true`` otherwise
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceQuerySession.can_search_resources
# NOTE: It is expected that real authentication hints will be
# handled in a service adapter above the pay grade of this impl.
return True
def get_repository_query(self):
"""Gets a repository query.
return: (osid.repository.RepositoryQuery) - the repository query
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.BinQuerySession.get_bin_query_template
return queries.RepositoryQuery(runtime=self._runtime)
repository_query = property(fget=get_repository_query)
@utilities.arguments_not_none
def get_repositories_by_query(self, repository_query):
"""Gets a list of ``Repositories`` matching the given repository query.
arg: repository_query (osid.repository.RepositoryQuery): the
repository query
return: (osid.repository.RepositoryList) - the returned
``RepositoryList``
raise: NullArgument - ``repository_query`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
raise: Unsupported - ``repository_query`` is not of this
service
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.BinQuerySession.get_bins_by_query_template
query_terms = dict(repository_query._query_terms)
collection = MongoClientValidated('repository',
collection='Repository',
runtime=self._runtime)
result = collection.find(query_terms).sort('_id', DESCENDING)
return objects.RepositoryList(result, runtime=self._runtime)
class RepositoryAdminSession(abc_repository_sessions.RepositoryAdminSession, osid_sessions.OsidSession):
"""This session creates, updates, and deletes ``Repositories``.
The data for create and update is provided by the consumer via the
form object. ``OsidForms`` are requested for each create or update
and may not be reused.
Create and update operations differ in their usage. To create a
``Repository,`` a ``RepositoryForm`` is requested using
``get_repository_form_for_create()`` specifying the desired record
``Types`` or none if no record ``Types`` are needed. The returned
``RepositoryForm`` will indicate that it is to be used with a create
operation and can be used to examine metdata or validate data prior
to creation. Once the ``RepositoryForm`` is submiited to a create
operation, it cannot be reused with another create operation unless
the first operation was unsuccessful. Each ``RepositoryForm``
corresponds to an attempted transaction.
For updates, ``RepositoryForms`` are requested to the ``Repository``
``Id`` that is to be updated using ``getRepositoryFormForUpdate()``.
Similarly, the ``RepositoryForm`` has metadata about the data that
can be updated and it can perform validation before submitting the
update. The ``RepositoryForm`` can only be used once for a
successful update and cannot be reused.
The delete operations delete ``Repositories``. This session includes
an ``Id`` aliasing mechanism to assign an external ``Id`` to an
internally assigned Id.
"""
_session_name = 'RepositoryAdminSession'
def __init__(self, proxy=None, runtime=None, **kwargs):
OsidSession._init_catalog(self, proxy, runtime)
self._forms = dict()
self._kwargs = kwargs
def can_create_repositories(self):
"""Tests if this user can create ``Repositories``.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known creating a
``Repository`` will result in a ``PermissionDenied``. This is
intended as a hint to an application that may not wish to offer
create operations to unauthorized users.
return: (boolean) - ``false`` if ``Repository`` creation is not
authorized, ``true`` otherwise
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceAdminSession.can_create_resources
# NOTE: It is expected that real authentication hints will be
# handled in a service adapter above the pay grade of this impl.
return True
@utilities.arguments_not_none
def can_create_repository_with_record_types(self, repository_record_types):
"""Tests if this user can create a single ``Repository`` using the desired record types.
While ``RepositoryManager.getRepositoryRecordTypes()`` can be
used to examine which records are supported, this method tests
which record(s) are required for creating a specific
``Repository``. Providing an empty array tests if a
``Repository`` can be created with no records.
arg: repository_record_types (osid.type.Type[]): array of
repository record types
return: (boolean) - ``true`` if ``Repository`` creation using
the specified ``Types`` is supported, ``false``
otherwise
raise: NullArgument - ``repository_record_types`` is ``null``
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceAdminSession.can_create_resource_with_record_types
# NOTE: It is expected that real authentication hints will be
# handled in a service adapter above the pay grade of this impl.
return True
@utilities.arguments_not_none
def get_repository_form_for_create(self, repository_record_types):
"""Gets the repository form for creating new repositories.
A new form should be requested for each create transaction.
arg: repository_record_types (osid.type.Type[]): array of
repository record types
return: (osid.repository.RepositoryForm) - the repository form
raise: NullArgument - ``repository_record_types`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
raise: Unsupported - unable to get form for requested record
types
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.BinAdminSession.get_bin_form_for_create_template
for arg in repository_record_types:
if not isinstance(arg, ABCType):
raise errors.InvalidArgument('one or more argument array elements is not a valid OSID Type')
if repository_record_types == []:
result = objects.RepositoryForm(
runtime=self._runtime,
effective_agent_id=self.get_effective_agent_id())
else:
result = objects.RepositoryForm(
record_types=repository_record_types,
runtime=self._runtime,
effective_agent_id=self.get_effective_agent_id())
self._forms[result.get_id().get_identifier()] = not CREATED
return result
@utilities.arguments_not_none
def create_repository(self, repository_form):
"""Creates a new ``Repository``.
arg: repository_form (osid.repository.RepositoryForm): the
form for this ``Repository``
return: (osid.repository.Repository) - the new ``Repository``
raise: IllegalState - ``repository_form`` already used in a
create transaction
raise: InvalidArgument - one or more of the form elements is
invalid
raise: NullArgument - ``repository_form`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
raise: Unsupported - ``repository_form`` did not originate from
``get_repository_form_for_create()``
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.BinAdminSession.create_bin_template
collection = MongoClientValidated('repository',
collection='Repository',
runtime=self._runtime)
if not isinstance(repository_form, ABCRepositoryForm):
raise errors.InvalidArgument('argument type is not an RepositoryForm')
if repository_form.is_for_update():
raise errors.InvalidArgument('the RepositoryForm is for update only, not create')
try:
if self._forms[repository_form.get_id().get_identifier()] == CREATED:
raise errors.IllegalState('repository_form already used in a create transaction')
except KeyError:
raise errors.Unsupported('repository_form did not originate from this session')
if not repository_form.is_valid():
raise errors.InvalidArgument('one or more of the form elements is invalid')
insert_result = collection.insert_one(repository_form._my_map)
self._forms[repository_form.get_id().get_identifier()] = CREATED
result = objects.Repository(
collection.find_one({'_id': insert_result.inserted_id}),
runtime=self._runtime)
return result
def can_update_repositories(self):
"""Tests if this user can update ``Repositories``.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known updating a
``Repository`` will result in a ``PermissionDenied``. This is
intended as a hint to an application that may not wish to offer
update operations to unauthorized users.
return: (boolean) - ``false`` if ``Repository`` modification is
not authorized, ``true`` otherwise
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceAdminSession.can_create_resources
# NOTE: It is expected that real authentication hints will be
# handled in a service adapter above the pay grade of this impl.
return True
@utilities.arguments_not_none
def get_repository_form_for_update(self, repository_id):
"""Gets the repository form for updating an existing repository.
A new repository form should be requested for each update
transaction.
arg: repository_id (osid.id.Id): the ``Id`` of the
``Repository``
return: (osid.repository.RepositoryForm) - the repository form
raise: NotFound - ``repository_id`` is not found
raise: NullArgument - ``repository_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.BinAdminSession.get_bin_form_for_update_template
collection = MongoClientValidated('repository',
collection='Repository',
runtime=self._runtime)
if not isinstance(repository_id, ABCId):
raise errors.InvalidArgument('the argument is not a valid OSID Id')
result = collection.find_one({'_id': ObjectId(repository_id.get_identifier())})
cat_form = objects.RepositoryForm(result, runtime=self._runtime)
self._forms[cat_form.get_id().get_identifier()] = not UPDATED
return cat_form
@utilities.arguments_not_none
def update_repository(self, repository_form):
"""Updates an existing repository.
arg: repository_form (osid.repository.RepositoryForm): the
form containing the elements to be updated
raise: IllegalState - ``repository_form`` already used in an
update transaction
raise: InvalidArgument - the form contains an invalid value
raise: NullArgument - ``repository_form`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
raise: Unsupported - ``repository_form`` did not originate from
``get_repository_form_for_update()``
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.BinAdminSession.update_bin_template
collection = MongoClientValidated('repository',
collection='Repository',
runtime=self._runtime)
if not isinstance(repository_form, ABCRepositoryForm):
raise errors.InvalidArgument('argument type is not an RepositoryForm')
if not repository_form.is_for_update():
raise errors.InvalidArgument('the RepositoryForm is for update only, not create')
try:
if self._forms[repository_form.get_id().get_identifier()] == UPDATED:
raise errors.IllegalState('repository_form already used in an update transaction')
except KeyError:
raise errors.Unsupported('repository_form did not originate from this session')
if not repository_form.is_valid():
raise errors.InvalidArgument('one or more of the form elements is invalid')
collection.save(repository_form._my_map) # save is deprecated - change to replace_one
self._forms[repository_form.get_id().get_identifier()] = UPDATED
# Note: this is out of spec. The OSIDs don't require an object to be returned
return objects.Repository(repository_form._my_map, runtime=self._runtime)
def can_delete_repositories(self):
"""Tests if this user can delete ``Repositories``.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known deleting a
``Repository`` will result in a ``PermissionDenied``. This is
intended as a hint to an application that may not wish to offer
delete operations to unauthorized users.
return: (boolean) - ``false`` if ``Repository`` deletion is not
authorized, ``true`` otherwise
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceAdminSession.can_create_resources
# NOTE: It is expected that real authentication hints will be
# handled in a service adapter above the pay grade of this impl.
return True
@utilities.arguments_not_none
def delete_repository(self, repository_id):
"""Deletes a ``Repository``.
arg: repository_id (osid.id.Id): the ``Id`` of the
``Repository`` to remove
raise: NotFound - ``repository_id`` not found
raise: NullArgument - ``repository_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.BinAdminSession.delete_bin_template
collection = MongoClientValidated('repository',
collection='Repository',
runtime=self._runtime)
if not isinstance(repository_id, ABCId):
raise errors.InvalidArgument('the argument is not a valid OSID Id')
for object_catalog in ['Asset', 'Composition', 'Repository']:
obj_collection = MongoClientValidated('repository',
collection=object_catalog,
runtime=self._runtime)
if obj_collection.find({'assignedRepositoryIds': {'$in': [str(repository_id)]}}).count() != 0:
raise errors.IllegalState('catalog is not empty')
collection.delete_one({'_id': ObjectId(repository_id.get_identifier())})
def can_manage_repository_aliases(self):
"""Tests if this user can manage ``Id`` aliases for repositories.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known changing an alias
will result in a ``PermissionDenied``. This is intended as a
hint to an application that may opt not to offer alias
operations to an unauthorized user.
return: (boolean) - ``false`` if ``Repository`` aliasing is not
authorized, ``true`` otherwise
*compliance: mandatory -- This method must be implemented.*
"""
raise errors.Unimplemented()
@utilities.arguments_not_none
def alias_repository(self, repository_id, alias_id):
"""Adds an ``Id`` to a ``Repository`` for the purpose of creating compatibility.
The primary ``Id`` of the ``Repository`` is determined by the
provider. The new ``Id`` is an alias to the primary ``Id``. If
the alias is a pointer to another repository, it is reassigned
to the given repository ``Id``.
arg: repository_id (osid.id.Id): the ``Id`` of a
``Repository``
arg: alias_id (osid.id.Id): the alias ``Id``
raise: AlreadyExists - ``alias_id`` is in use as a primary
``Id``
raise: NotFound - ``repository_id`` not found
raise: NullArgument - ``repository_id`` or ``alias_id`` is
``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.BinLookupSession.alias_bin_template
# NEED TO FIGURE OUT HOW TO IMPLEMENT THIS SOMEDAY
raise errors.Unimplemented()
class RepositoryHierarchySession(abc_repository_sessions.RepositoryHierarchySession, osid_sessions.OsidSession):
"""This session defines methods for traversing a hierarchy of ``Repository`` objects.
Each node in the hierarchy is a unique ``Repository``. The hierarchy
may be traversed recursively to establish the tree structure through
``get_parents()`` and ``getChildren()``. To relate these ``Ids`` to
another OSID, ``get_ancestors()`` and ``get_descendants()`` can be
used for retrievals that can be used for bulk lookups in other
OSIDs. Any ``Repository`` available in the Repository OSID is known
to this hierarchy but does not appear in the hierarchy traversal
until added as a root node or a child of another node.
A user may not be authorized to traverse the entire hierarchy. Parts
of the hierarchy may be made invisible through omission from the
returns of ``get_parents()`` or ``get_children()`` in lieu of a
``PermissionDenied`` error that may disrupt the traversal through
authorized pathways.
This session defines views that offer differing behaviors when
retrieving multiple objects.
* comparative view: repository elements may be silently omitted or
re-ordered
* plenary view: provides a complete set or is an error condition
"""
_session_name = 'RepositoryHierarchySession'
def __init__(self, proxy=None, runtime=None, **kwargs):
OsidSession.__init__(self)
OsidSession._init_catalog(self, proxy, runtime)
self._forms = dict()
self._kwargs = kwargs
hierarchy_mgr = self._get_provider_manager('HIERARCHY')
self._hierarchy_session = hierarchy_mgr.get_hierarchy_traversal_session_for_hierarchy(
Id(authority='REPOSITORY',
namespace='CATALOG',
identifier='REPOSITORY')
)
def get_repository_hierarchy_id(self):
"""Gets the hierarchy ``Id`` associated with this session.
return: (osid.id.Id) - the hierarchy ``Id`` associated with this
session
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceHierarchySession.get_bin_hierarchy_id
return self._hierarchy_session.get_hierarchy_id()
repository_hierarchy_id = property(fget=get_repository_hierarchy_id)
def get_repository_hierarchy(self):
"""Gets the hierarchy associated with this session.
return: (osid.hierarchy.Hierarchy) - the hierarchy associated
with this session
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceHierarchySession.get_bin_hierarchy
return self._hierarchy_session.get_hierarchy()
repository_hierarchy = property(fget=get_repository_hierarchy)
def can_access_repository_hierarchy(self):
"""Tests if this user can perform hierarchy queries.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known all methods in this
session will result in a ``PermissionDenied``. This is intended
as a hint to an application that may opt not to offer lookup
operations.
return: (boolean) - ``false`` if hierarchy traversal methods are
not authorized, ``true`` otherwise
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceHierarchySession.can_access_bin_hierarchy
# NOTE: It is expected that real authentication hints will be
# handled in a service adapter above the pay grade of this impl.
return True
def use_comparative_repository_view(self):
"""The returns from the repository methods may omit or translate elements based on this session, such as
authorization, and not result in an error.
This view is used when greater interoperability is desired at
the expense of precision.
*compliance: mandatory -- This method is must be implemented.*
"""
# Implemented from template for
# osid.resource.BinLookupSession.use_comparative_bin_view
self._catalog_view = COMPARATIVE
def use_plenary_repository_view(self):
"""A complete view of the ``Repository`` returns is desired.
Methods will return what is requested or result in an error.
This view is used when greater precision is desired at the
expense of interoperability.
*compliance: mandatory -- This method is must be implemented.*
"""
# Implemented from template for
# osid.resource.BinLookupSession.use_plenary_bin_view
self._catalog_view = PLENARY
def get_root_repository_ids(self):
"""Gets the root repository ``Ids`` in this hierarchy.
return: (osid.id.IdList) - the root repository ``Ids``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceHierarchySession.get_root_bin_ids
return self._hierarchy_session.get_roots()
root_repository_ids = property(fget=get_root_repository_ids)
def get_root_repositories(self):
"""Gets the root repositories in the repository hierarchy.
A node with no parents is an orphan. While all repository
``Ids`` are known to the hierarchy, an orphan does not appear in
the hierarchy unless explicitly added as a root node or child of
another node.
return: (osid.repository.RepositoryList) - the root repositories
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method is must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceHierarchySession.get_root_bins
return RepositoryLookupSession(
self._proxy,
self._runtime).get_repositories_by_ids(list(self.get_root_repository_ids()))
root_repositories = property(fget=get_root_repositories)
@utilities.arguments_not_none
def has_parent_repositories(self, repository_id):
"""Tests if the ``Repository`` has any parents.
arg: repository_id (osid.id.Id): a repository ``Id``
return: (boolean) - ``true`` if the repository has parents,
``false`` otherwise
raise: NotFound - ``repository_id`` is not found
raise: NullArgument - ``repository_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceHierarchySession.has_parent_bins
return self._hierarchy_session.has_parents(id_=repository_id)
@utilities.arguments_not_none
def is_parent_of_repository(self, id_, repository_id):
"""Tests if an ``Id`` is a direct parent of a repository.
arg: id (osid.id.Id): an ``Id``
arg: repository_id (osid.id.Id): the ``Id`` of a repository
return: (boolean) - ``true`` if this ``id`` is a parent of
``repository_id,`` ``false`` otherwise
raise: NotFound - ``repository_id`` is not found
raise: NullArgument - ``id`` or ``repository_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
*implementation notes*: If ``id`` not found return ``false``.
"""
# Implemented from template for
# osid.resource.ResourceHierarchySession.is_parent_of_bin
return self._hierarchy_session.is_parent(id_=repository_id, parent_id=id_)
@utilities.arguments_not_none
def get_parent_repository_ids(self, repository_id):
"""Gets the parent ``Ids`` of the given repository.
arg: repository_id (osid.id.Id): a repository ``Id``
return: (osid.id.IdList) - the parent ``Ids`` of the repository
raise: NotFound - ``repository_id`` is not found
raise: NullArgument - ``repository_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceHierarchySession.get_parent_bin_ids
return self._hierarchy_session.get_parents(id_=repository_id)
@utilities.arguments_not_none
def get_parent_repositories(self, repository_id):
"""Gets the parents of the given repository.
arg: repository_id (osid.id.Id): the ``Id`` to query
return: (osid.repository.RepositoryList) - the parents of the
repository
raise: NotFound - ``repository_id`` not found
raise: NullArgument - ``repository_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceHierarchySession.get_parent_bins
return RepositoryLookupSession(
self._proxy,
self._runtime).get_repositories_by_ids(
list(self.get_parent_repository_ids(repository_id)))
@utilities.arguments_not_none
def is_ancestor_of_repository(self, id_, repository_id):
"""Tests if an ``Id`` is an ancestor of a repository.
arg: id (osid.id.Id): an ``Id``
arg: repository_id (osid.id.Id): the Id of a repository
return: (boolean) - ``true`` if this ``id`` is an ancestor of
``repository_id,`` ``false`` otherwise
raise: NotFound - ``repository_id`` not found
raise: NullArgument - ``repository_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
*implementation notes*: If ``id`` not found return ``false``.
"""
# Implemented from template for
# osid.resource.ResourceHierarchySession.is_ancestor_of_bin
return self._hierarchy_session.is_ancestor(id_=id_, ancestor_id=repository_id)
@utilities.arguments_not_none
def has_child_repositories(self, repository_id):
"""Tests if a repository has any children.
arg: repository_id (osid.id.Id): a repository ``Id``
return: (boolean) - ``true`` if the ``repository_id`` has
children, ``false`` otherwise
raise: NotFound - ``repository_id`` not found
raise: NullArgument - ``repository_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceHierarchySession.has_child_bins
return self._hierarchy_session.has_children(id_=repository_id)
@utilities.arguments_not_none
def is_child_of_repository(self, id_, repository_id):
"""Tests if a node is a direct child of another.
arg: id (osid.id.Id): an ``Id``
arg: repository_id (osid.id.Id): the ``Id`` of a repository
return: (boolean) - ``true`` if the ``id`` is a child of
``repository_id,`` ``false`` otherwise
raise: NotFound - ``repository_id`` not found
raise: NullArgument - ``repository_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
*implementation notes*: If ``id`` not found return ``false``.
"""
# Implemented from template for
# osid.resource.ResourceHierarchySession.is_child_of_bin
return self._hierarchy_session.is_child(id_=repository_id, child_id=id_)
@utilities.arguments_not_none
def get_child_repository_ids(self, repository_id):
"""Gets the ``Ids`` of the children of the given repository.
arg: repository_id (osid.id.Id): the ``Id`` to query
return: (osid.id.IdList) - the children of the repository
raise: NotFound - ``repository_id`` not found
raise: NullArgument - ``repository_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceHierarchySession.get_child_bin_ids
return self._hierarchy_session.get_children(id_=repository_id)
@utilities.arguments_not_none
def get_child_repositories(self, repository_id):
"""Gets the children of the given repository.
arg: repository_id (osid.id.Id): the ``Id`` to query
return: (osid.repository.RepositoryList) - the children of the
repository
raise: NotFound - ``repository_id`` not found
raise: NullArgument - ``repository_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceHierarchySession.get_child_bins
return RepositoryLookupSession(
self._proxy,
self._runtime).get_repositories_by_ids(
list(self.get_child_repository_ids(repository_id)))
@utilities.arguments_not_none
def is_descendant_of_repository(self, id_, repository_id):
"""Tests if an ``Id`` is a descendant of a repository.
arg: id (osid.id.Id): an ``Id``
arg: repository_id (osid.id.Id): the ``Id`` of a repository
return: (boolean) - ``true`` if the ``id`` is a descendant of
the ``repository_id,`` ``false`` otherwise
raise: NotFound - ``repository_id`` not found
raise: NullArgument - ``repository_id`` or ``id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
*implementation notes*: If ``id`` is not found return ``false``.
"""
# Implemented from template for
# osid.resource.ResourceHierarchySession.is_descendant_of_bin
return self._hierarchy_session.is_descendant(id_=id_, descendant_id=repository_id)
@utilities.arguments_not_none
def get_repository_node_ids(self, repository_id, ancestor_levels, descendant_levels, include_siblings):
"""Gets a portion of the hierarchy for the given repository.
arg: repository_id (osid.id.Id): the ``Id`` to query
arg: ancestor_levels (cardinal): the maximum number of
ancestor levels to include. A value of 0 returns no
parents in the node.
arg: descendant_levels (cardinal): the maximum number of
descendant levels to include. A value of 0 returns no
children in the node.
arg: include_siblings (boolean): ``true`` to include the
siblings of the given node, ``false`` to omit the
siblings
return: (osid.hierarchy.Node) - the specified repository node
raise: NotFound - ``repository_id`` not found
raise: NullArgument - ``repository_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceHierarchySession.get_bin_node_ids
return self._hierarchy_session.get_nodes(
id_=repository_id,
ancestor_levels=ancestor_levels,
descendant_levels=descendant_levels,
include_siblings=include_siblings)
@utilities.arguments_not_none
def get_repository_nodes(self, repository_id, ancestor_levels, descendant_levels, include_siblings):
"""Gets a portion of the hierarchy for the given repository.
arg: repository_id (osid.id.Id): the ``Id`` to query
arg: ancestor_levels (cardinal): the maximum number of
ancestor levels to include. A value of 0 returns no
parents in the node.
arg: descendant_levels (cardinal): the maximum number of
descendant levels to include. A value of 0 returns no
children in the node.
arg: include_siblings (boolean): ``true`` to include the
siblings of the given node, ``false`` to omit the
siblings
return: (osid.repository.RepositoryNode) - the specified
repository node
raise: NotFound - ``repository_id`` not found
raise: NullArgument - ``repository_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceHierarchySession.get_bin_nodes
return objects.RepositoryNode(self.get_repository_node_ids(
repository_id=repository_id,
ancestor_levels=ancestor_levels,
descendant_levels=descendant_levels,
include_siblings=include_siblings)._my_map, runtime=self._runtime, proxy=self._proxy)
class RepositoryHierarchyDesignSession(abc_repository_sessions.RepositoryHierarchyDesignSession, osid_sessions.OsidSession):
"""This session defines methods for managing a hierarchy of ``Repository`` objects.
Each node in the hierarchy is a unique ``Repository``.
"""
_session_name = 'RepositoryHierarchyDesignSession'
def __init__(self, proxy=None, runtime=None, **kwargs):
OsidSession._init_catalog(self, proxy, runtime)
self._forms = dict()
self._kwargs = kwargs
hierarchy_mgr = self._get_provider_manager('HIERARCHY')
self._hierarchy_session = hierarchy_mgr.get_hierarchy_design_session_for_hierarchy(
Id(authority='REPOSITORY',
namespace='CATALOG',
identifier='REPOSITORY')
)
def get_repository_hierarchy_id(self):
"""Gets the hierarchy ``Id`` associated with this session.
return: (osid.id.Id) - the hierarchy ``Id`` associated with this
session
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceHierarchySession.get_bin_hierarchy_id
return self._hierarchy_session.get_hierarchy_id()
repository_hierarchy_id = property(fget=get_repository_hierarchy_id)
def get_repository_hierarchy(self):
"""Gets the hierarchy associated with this session.
return: (osid.hierarchy.Hierarchy) - the hierarchy associated
with this session
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceHierarchySession.get_bin_hierarchy
return self._hierarchy_session.get_hierarchy()
repository_hierarchy = property(fget=get_repository_hierarchy)
def can_modify_repository_hierarchy(self):
"""Tests if this user can change the hierarchy.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known performing any update
will result in a ``PermissionDenied``. This is intended as a
hint to an application that may opt not to offer these
operations to an unauthorized user.
return: (boolean) - ``false`` if changing this hierarchy is not
authorized, ``true`` otherwise
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceHierarchyDesignSession.can_modify_objective_bank_hierarchy
# NOTE: It is expected that real authentication hints will be
# handled in a service adapter above the pay grade of this impl.
return True
@utilities.arguments_not_none
def add_root_repository(self, repository_id):
"""Adds a root repository.
arg: repository_id (osid.id.Id): the ``Id`` of a repository
raise: AlreadyExists - ``repository_id`` is already in
hierarchy
raise: NotFound - ``repository_id`` not found
raise: NullArgument - ``repository_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceHierarchyDesignSession.add_root_bin_template
return self._hierarchy_session.add_root(id_=repository_id)
@utilities.arguments_not_none
def remove_root_repository(self, repository_id):
"""Removes a root repository.
arg: repository_id (osid.id.Id): the ``Id`` of a repository
raise: NotFound - ``repository_id`` not a root
raise: NullArgument - ``repository_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceHierarchyDesignSession.remove_root_bin_template
return self._hierarchy_session.remove_root(id_=repository_id)
@utilities.arguments_not_none
def add_child_repository(self, repository_id, child_id):
"""Adds a child to a repository.
arg: repository_id (osid.id.Id): the ``Id`` of a repository
arg: child_id (osid.id.Id): the ``Id`` of the new child
raise: AlreadyExists - ``repository_id`` is already a parent of
``child_id``
raise: NotFound - ``repository_id`` or ``child_id`` not found
raise: NullArgument - ``repository_id`` or ``child_id`` is
``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceHierarchyDesignSession.add_child_bin_template
return self._hierarchy_session.add_child(id_=repository_id, child_id=child_id)
@utilities.arguments_not_none
def remove_child_repository(self, repository_id, child_id):
"""Removes a child from a repository.
arg: repository_id (osid.id.Id): the ``Id`` of a repository
arg: child_id (osid.id.Id): the ``Id`` of the new child
raise: NotFound - ``repository_id`` not a parent of
``child_id``
raise: NullArgument - ``repository_id`` or ``child_id`` is
``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceHierarchyDesignSession.remove_child_bin_template
return self._hierarchy_session.remove_child(id_=repository_id, child_id=child_id)
@utilities.arguments_not_none
def remove_child_repositories(self, repository_id):
"""Removes all children from a repository.
arg: repository_id (osid.id.Id): the ``Id`` of a repository
raise: NotFound - ``repository_id`` not in hierarchy
raise: NullArgument - ``repository_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceHierarchyDesignSession.remove_child_bin_template
return self._hierarchy_session.remove_children(id_=repository_id)<|fim▁end|> |
"""
# Implemented from template for osid.resource.ResourceLookupSession.get_bin
return self._catalog |
<|file_name|>formating.py<|end_file_name|><|fim▁begin|># Copyright (c) OpenMMLab. All rights reserved.
# flake8: noqa
import warnings
from .formatting import *
warnings.warn('DeprecationWarning: mmdet.datasets.pipelines.formating will be '<|fim▁hole|><|fim▁end|> | 'deprecated, please replace it with '
'mmdet.datasets.pipelines.formatting.') |
<|file_name|>cert.go<|end_file_name|><|fim▁begin|>package autosignr
import (
"crypto/x509"
"encoding/pem"
"fmt"
"io/ioutil"
"os/exec"
"path/filepath"
"regexp"
"strings"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
)
// The OID for Puppet's pp_preshared_key in the Certificate Extensions
// https://docs.puppetlabs.com/puppet/latest/reference/ssl_attributes_extensions.html
const puppetPSKoid string = "1.3.6.1.4.1.34380.1.1.4"
// ErrNoPemData is returned when the data expected to be a PEM encoded cert is not actually a cert
var ErrNoPemData = errors.New("no PEM data found in block")
// ErrNoPSK is returned when a certificate does not contain a preshared key
var ErrNoPSK = errors.New("certificate did not contain a PSK")
// regexpPSK limits what the PSK can contain to alphanumeric chars plus '_', '-', and '.'
var regexpPSK = regexp.MustCompile("([a-zA-Z0-9_\\-\\.]+)")
// CertnameFromFilename returns the name of a cert given the path to the file
func CertnameFromFilename(file string) string {
return strings.TrimSuffix(filepath.Base(file), filepath.Ext(file))
}
// CheckCert checks if the cert is valid
func CheckCert(conf *Config, file string) (bool, error) {
name := CertnameFromFilename(file)
log.Debugf("CheckCert %s", name)
data, err := ioutil.ReadFile(file)
if err != nil {
return false, err
}
result, err := ValidateCert(conf, data, name)
if err != nil {
return false, err
}
if !result {
log.Warningf("Unable to validate instance %s", name)
}
return result, nil
}
// ValidateCert validates the cert
func ValidateCert(conf *Config, data []byte, certname string) (bool, error) {
log.Debugf("ValidateCert %s", certname)
if conf.CheckPSK {
psk, err := PuppetPSKFromCSR(data)
if err != nil {
log.WithFields(log.Fields{
"certname": certname,
"err": err,
}).Warning("psk-extract-error")
return false, err
}
if _, ok := conf.PresharedKeys[psk]; !ok {
log.WithFields(log.Fields{
"certname": certname,
"psk": psk,
}).Warning("invalid-psk")
return false, errors.New("Invalid PSK")
}
}
result := false
for _, acct := range conf.Accounts {
result = acct.Check(certname)
if result {
break
}
}
return result, nil
}
// SignCert will run the puppet command to sign the cert
func SignCert(conf *Config, certname string) {
cmd := fmt.Sprintf(conf.CmdSign, certname)
pieces := strings.Split(cmd, " ")
cmdOut, err := exec.Command(pieces[0], pieces[1:]...).CombinedOutput()
if err != nil {
log.WithFields(log.Fields{
"certname": certname,
"err": err,
"output": string(cmdOut),
}).Error("signing-failure")
return
}
log.WithFields(log.Fields{
"certname": certname,
}).Info("signing-success")
}
// ExistingCerts checks existing certs in directory
func ExistingCerts(conf *Config) error {
matches, err := filepath.Glob(fmt.Sprintf("%s/*.pem", conf.Dir))
if err != nil {
return errors.Wrap(err, "globbing")
}
for _, cert := range matches {
log.WithFields(log.Fields{
"file": cert,
}).Info("existing-csr")
result, _ := CheckCert(conf, cert)
if result {
SignCert(conf, CertnameFromFilename(cert))
}
}
return nil
}<|fim▁hole|>func PuppetPSKFromCSRFile(file string) (string, error) {
var f string
data, err := ioutil.ReadFile(file)
if err != nil {
return f, err
}
return PuppetPSKFromCSR(data)
}
// PuppetPSKFromCSR decodes and parses the cert data
func PuppetPSKFromCSR(data []byte) (string, error) {
block, _ := pem.Decode(data)
if block == nil {
return "", ErrNoPemData
}
parsedcsr, err := x509.ParseCertificateRequest(block.Bytes)
if err != nil {
return "", err
}
for _, e := range parsedcsr.Extensions {
if e.Id.String() == puppetPSKoid {
match := regexpPSK.FindStringSubmatch(string(e.Value))
if len(match) > 0 {
return match[1], nil
}
}
}
return "", ErrNoPSK
}<|fim▁end|> |
// PuppetPSKFromCSRFile return the CSR file data |
<|file_name|>xgb.py<|end_file_name|><|fim▁begin|># This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load in
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
# Input data files are available in the "data/" directory.
# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory
# Any results you write to the current directory are saved as output.
import numpy as np
import pandas as pd
import xgboost as xgb
import gc
import sklearn
print('Loading data ...')
train = pd.read_csv('data/train_2016.csv')
prop = pd.read_csv('data/properties_2016.csv')
for c, dtype in zip(prop.columns, prop.dtypes):
if dtype == np.float64:
prop[c] = prop[c].astype(np.float32)
df_train = train.merge(prop, how='left', on='parcelid')
x_train = df_train.drop(['parcelid', 'logerror', 'transactiondate', 'propertyzoningdesc', 'propertycountylandusecode'], axis=1)
y_train = df_train['logerror'].values
print(x_train.shape, y_train.shape)
train_columns = x_train.columns
for c in x_train.dtypes[x_train.dtypes == object].index.values:
x_train[c] = (x_train[c] == True)
del df_train; gc.collect()
split = 90000
x_train, y_train, x_valid, y_valid = x_train[:split], y_train[:split], x_train[split:], y_train[split:]
x_train = x_train.values.astype(np.float32, copy=False)
x_valid = x_valid.values.astype(np.float32, copy=False)
d_train = xgb.DMatrix(x_train, label=y_train)
d_valid = xgb.DMatrix(x_valid, label=y_valid)
del x_train, x_valid; gc.collect()
params = {}
params['eta'] = 0.02
params['objective'] = 'reg:linear'<|fim▁hole|>
watchlist = [(d_train, 'train'), (d_valid, 'valid')]
clf = xgb.train(params, d_train, 10000, watchlist, early_stopping_rounds=100, verbose_eval=10)
del d_train, d_valid; gc.collect()
print("Prepare for the prediction ...")
sample = pd.read_csv('data/sample_submission.csv')
sample['parcelid'] = sample['ParcelId']
df_test = sample.merge(prop, on='parcelid', how='left')
del sample, prop; gc.collect()
x_test = df_test[train_columns]
del df_test; gc.collect()
for c in x_test.dtypes[x_test.dtypes == object].index.values:
x_test[c] = (x_test[c] == True)
x_test = x_test.values.astype(np.float32, copy=False)
print("Start prediction ...")
d_test = xgb.DMatrix(x_test)
p_test = clf.predict(d_test)
del x_test; gc.collect()
print("Start write result ...")
sub = pd.read_csv('data/sample_submission.csv')
for c in sub.columns[sub.columns != 'ParcelId']:
sub[c] = p_test
sub.to_csv('out/xgb.csv', index=False, float_format='%.4f')<|fim▁end|> | params['eval_metric'] = 'mae'
params['max_depth'] = 10
params['silent'] = 0 |
<|file_name|>app.js<|end_file_name|><|fim▁begin|>angular.module('NetPlanningApp').controller('AppCtrl', function($mdSidenav, $mdDialog, $mdToast, $scope, $location, $localStorage, $translate, amMoment, settings, DataService) {
'use strict';
var vm = this;
vm.$storage = $localStorage;
vm.DataService = DataService;
vm.username = '';
vm.password = '';
vm.errorMessage = null;
vm.$localStorage = $localStorage;
vm.availableLanguages = {
'en': 'English',
'it': 'Italiano',
'fr': 'French'
};
$localStorage.$default({
language: settings.defaultLanguage
});
$scope.$watch(function() {
return $localStorage.language;
}, function(val) {
$translate.use(val);
amMoment.changeLocale(val);
});
vm.update = function() {
var errorMessage = '<md-icon md-svg-src="images/ic_settings_48px.svg" class="md-warn" aria-label="settings"></md-icon>';
errorMessage += $translate.instant('ERROR_LOADING_DATA');
DataService.loadItems(true).catch(function() {
$mdToast.show({
templateUrl: 'partials/toast-error.html',
position: 'top right',
hideDelay: 800
});
});
};
vm.login = function() {
vm.errorMessage = null;<|fim▁hole|> }).catch(function(reason) {
vm.errorMessage = reason.status > -1 ? reason.data.message : $translate.instant('NETWORK_ERROR');
}).finally(function() {
vm.username = '';
vm.password = '';
});
};
vm.logout = function() {
var title = $translate.instant('LOGOUT').capitalize();
var content = $translate.instant('ARE_YOU_SURE_YOU_WANT_TO_LOGOUT').capitalize() + ' ?';
var btnOk = $translate.instant('OK');
var btnCancel = $translate.instant('CANCEL');
var dialog = $mdDialog
.confirm()
.title(title)
.textContent(content)
.ariaLabel('Logout')
.ok(btnOk)
.cancel(btnCancel);
$mdDialog
.show(dialog)
.then(DataService.logout);
};
vm.toggleSidenav = function(menuId) {
$mdSidenav(menuId).toggle();
};
vm.navigateAndToggleSidenav = function(location, menuId) {
$mdSidenav(menuId).toggle();
$location.path(location);
};
});<|fim▁end|> | DataService.login(vm.username, vm.password).then(function() {
DataService.loadItems(false); |
<|file_name|>AndroidFoodBankOwnerServlet.java<|end_file_name|><|fim▁begin|>package cs499.examples.semesterproject;
import javax.servlet.*;
import javax.servlet.http.*;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
public class AndroidFoodBankOwnerServlet extends HttpServlet
{
boolean debug = false;
private String sqlliteDbUrl;
@Override
public void init(ServletConfig config) throws ServletException
{
sqlliteDbUrl = config.getInitParameter("sqlliteDbUrl");
}
public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
res.setContentType ("TEXT/HTML");
PrintWriter out = res.getWriter ();
if (debug)
{
out.println("<html> <head> <title> FoodBank Test </title> </head>");
out.println("<body> <h1> Food Bank Data </h1> </body>");
out.println("</html");
}
}
public void doPost (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
if (!debug)
res.setContentType("application/json");
else if (debug)
res.setContentType ("TEXT/HTML");
PrintWriter out = res.getWriter ();
String action = req.getParameter("action");
if (debug)
out.println("doPost Action: " + action);
if (action.equals("registerfoodplace"))
registerFoodPlace(out, req, res);
else if (action.equals("enterorganization"))
{
registerOrganization(out,req,res);
}
else if (action.equals("searchplaces"))
{
searchPlaces (out,req,res);
}
else if (action.equals("authenticate"))
{
authenticateUser (out,req,res);
}
else if (action.equals("additems"))
{
addItemsToPlace (out,req,res);
}
else if (action.equals("searchitems"))
{
searchItems (out,req,res);
}
else if (action.equals("requestitems"))
{
requestItem (out,req,res);
}
else if (action.equals("viewrequests"))
{
viewRequests (out,req,res);
}
}
public void viewRequests (PrintWriter out, HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
Statement s = null;
ResultSet rs = null;
//int queryExecuted = 0;
String query = "";
Connection c = getDBConnection();
if (c == null)
{
if (debug)
out.println("Could not connect to DB");
System.out.println("Could not connect to DB");
return;
}
try
{
s = c.createStatement();
System.out.println("ownername: " + req.getParameter("ownerName"));
query = "select sender, organization.name as org_name ,itemname from request, foodplace, organization where " +
"request.sender=organization.member and request.placename=foodplace.name and " +
"foodplace.ownername=" + "'" + req.getParameter("ownerName") + "'";
rs = s.executeQuery(query);
if (debug)
out.println("query: " + query);
rs = s.executeQuery(query);
if (rs != null)
{
System.out.println("Creating JSON....");
JSONArray jsonArray = this.convertToJSON(rs);
out.print(jsonArray);
out.flush();
}
else
{
out.println("Hey! Your resultset is null or empty");
out.flush();
}
c.close();
s.close();
out.println("</body> </html> ");
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void requestItem (PrintWriter out, HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
if (debug)
{
out.println("<html> <head> <title> FoodBank Test </title> </head>");
out.println("<body> <h1> Search Food Bank Data </h1>");
}
Statement s = null;
//ResultSet rs = null;
int queryExecuted = 0;
String query = "";
Connection c = getDBConnection();
if (c == null)
{
if (debug)
out.println("Could not connect to DB");
System.out.println("Could not connect to DB");
return;
}
try
{
String[] selectedItems = null;
System.out.println("senderName: " + req.getParameter("senderName"));
System.out.println("placeName: " + req.getParameter("placeName"));
System.out.println("selectedItems: " + req.getParameter("selectedItems"));
if (req.getParameter("selectedItems") != null)
{
selectedItems = req.getParameter("selectedItems").split(",");
}
if (selectedItems != null && selectedItems.length > 0)
{
s = c.createStatement();
for (int i = 0; i < selectedItems.length; i ++)
{
query = "insert into request (sender, placename, itemname)"
+ " values (" + "'" + req.getParameter("senderName")
+ "'" + ", " + "'" + req.getParameter("placeName")
+ "'" + ", " + "'" + selectedItems[i]
+ "'" + ")";
queryExecuted = s.executeUpdate(query);
}
c.close();
s.close();
out.println("Data inserted into db");
out.println("</body> </html> ");
System.out.println("Selected items inserted into db");
}
else
{
System.out.println("No selected items");
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void searchItems (PrintWriter out, HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
if (debug)
{
out.println("<html> <head> <title> FoodBank Test </title> </head>");
out.println("<body> <h1> Search Food Bank Data </h1>");
}
Statement s = null;
ResultSet rs = null;
//int queryExecuted = 0;
String query = "";
Connection c = getDBConnection();
if (c == null)
{
if (debug)
out.println("Could not connect to DB");
System.out.println("Could not connect to DB");
return;
}
try
{
System.out.println(req.getParameter("placeName"));
s = c.createStatement();
query = "select * from items where foodplacename=" + "'" + req.getParameter("placeName")
+ "'";
if (debug)
out.println("query: " + query);
rs = s.executeQuery(query);
if (rs != null)
{
System.out.println("Creating JSON....");
JSONArray jsonArray = this.convertToJSON(rs);
out.print(jsonArray);
out.flush();
}
else
{
out.println("Hey! Your resultset is null or empty");
out.flush();
}
c.close();
s.close();
out.println("</body> </html> ");
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void addItemsToPlace(PrintWriter out, HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
if (debug)
{
out.println("<html> <head> <title> FoodBank Test </title> </head>");
out.println("<body> <h1> Food Bank Data </h1>");
}
Statement s = null;
ResultSet rs = null;
int queryExecuted = 0;
String query = "";
Connection c = getDBConnection();
if (c == null)
{
if (debug)
out.println("Could not connect to DB");
System.out.println("Could not connect to DB");
return;
}
try
{
s = c.createStatement();
query = "select * from foodplace where ownername=" + "'" + req.getParameter("ownername") + "'";
if (debug)
out.println("query: " + query);
rs = s.executeQuery(query);
if (debug)
{
out.println("username: " + req.getParameter("ownername") + "<br/>");
out.println("itemName: " + req.getParameter("itemName") + "<br/>");
out.println("itemQuantity: " + req.getParameter("itemQuantity") + "<br/>");
out.println("Restaurant name: " + rs.getString("name") + "<br/>");
}
query = "insert into items (foodplacename, itemtype, itemname) values ("
+ "'" + rs.getString("name") + "'" + ", " + req.getParameter("itemQuantity")
+ ", " + "'" + req.getParameter("itemName") + "'" + ")";
queryExecuted = s.executeUpdate(query);
c.close();
s.close();
out.println("Data inserted into db");
out.println("</body> </html> ");
System.out.println("Data inserted into db");
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void authenticateUser(PrintWriter out, HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
if (debug)
{
out.println("<html> <head> <title> FoodBank Test </title> </head>");
out.println("<body> <h1> Food Bank Data </h1>");
}
Statement s = null;
ResultSet rs = null;
String query = "";
Connection c = getDBConnection();
if (c == null)
{
if (debug)
out.println("Could not connect to DB");
System.out.println("Could not connect to DB");
return;
}
try
{
s = c.createStatement();
query = "select * from foodappuser where username=" + "'" + req.getParameter("loginUser") + "'";
if (debug)
out.println("query: " + query);
rs = s.executeQuery(query);
JSONArray jsonArray = this.convertToJSON(rs);
out.print(jsonArray);
out.flush();
c.close();
s.close();
out.println("</body> </html> ");
}
catch (Exception e)
{
e.printStackTrace();
}
}
public JSONArray convertToJSON( ResultSet rs ) throws SQLException, JSONException
{
JSONArray json = new JSONArray();
ResultSetMetaData rsmd = rs.getMetaData();
while(rs.next())
{
int numColumns = rsmd.getColumnCount();
JSONObject obj = new JSONObject();
for (int i=1; i<numColumns+1; i++)
{
String column_name = rsmd.getColumnName(i);
if(rsmd.getColumnType(i)==java.sql.Types.ARRAY){
obj.put(column_name, rs.getArray(column_name));
}
else if(rsmd.getColumnType(i)==java.sql.Types.BIGINT){
obj.put(column_name, rs.getInt(column_name));
}
else if(rsmd.getColumnType(i)==java.sql.Types.BOOLEAN){
obj.put(column_name, rs.getBoolean(column_name));
}
else if(rsmd.getColumnType(i)==java.sql.Types.BLOB){
obj.put(column_name, rs.getBlob(column_name));
}
else if(rsmd.getColumnType(i)==java.sql.Types.DOUBLE){
obj.put(column_name, rs.getDouble(column_name));
}
else if(rsmd.getColumnType(i)==java.sql.Types.FLOAT){
obj.put(column_name, rs.getFloat(column_name));
}
else if(rsmd.getColumnType(i)==java.sql.Types.INTEGER){
obj.put(column_name, rs.getInt(column_name));
}
else if(rsmd.getColumnType(i)==java.sql.Types.NVARCHAR){
obj.put(column_name, rs.getNString(column_name));
}
else if(rsmd.getColumnType(i)==java.sql.Types.VARCHAR){
obj.put(column_name, rs.getString(column_name));
}
else if(rsmd.getColumnType(i)==java.sql.Types.TINYINT){
obj.put(column_name, rs.getInt(column_name));
}
else if(rsmd.getColumnType(i)==java.sql.Types.SMALLINT){
obj.put(column_name, rs.getInt(column_name));
}
else if(rsmd.getColumnType(i)==java.sql.Types.DATE){
obj.put(column_name, rs.getDate(column_name));
}
else if(rsmd.getColumnType(i)==java.sql.Types.TIMESTAMP){
obj.put(column_name, rs.getTimestamp(column_name));
}
else{
obj.put(column_name, rs.getObject(column_name));
}
}
json.put(obj);
}
return json;
}
public void searchPlaces(PrintWriter out, HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
if (debug)
{
out.println("<html> <head> <title> FoodBank Test </title> </head>");
out.println("<body> <h1> Food Bank Data </h1>");
}
Statement s = null;
ResultSet rs = null;
int queryExecuted = 0;
String query = "";
Connection c = getDBConnection();
if (c == null)
{
if (debug)
out.println("Could not connect to DB");
System.out.println("Could not connect to DB");
return;
}
try
{
s = c.createStatement();
if (req.getParameter("searchCity").trim().equals("") && !req.getParameter("searchZip").trim().equals(""))
query = "select * from foodplace where zip=" + req.getParameter("searchZip");
else if (!req.getParameter("searchCity").trim().equals("") && req.getParameter("searchZip").trim().equals(""))
query = "select * from foodplace where city=" + "'" + req.getParameter("searchCity") + "'";
else
{
query = "select * from foodplace where zip=" + req.getParameter("searchZip")
+ " and city=" + "'" + req.getParameter("searchCity") + "'";
}
if (debug)
out.println("query: " + query);
rs = s.executeQuery(query);
JSONArray jsonArray = this.convertToJSON(rs);
out.print(jsonArray);
out.flush();
c.close();
s.close();
out.println("</body> </html> ");
}
catch (Exception e)
{
e.printStackTrace();
}
}
public Connection getDBConnection()
{
Connection c = null;
try
{
//Class.forName("oracle.jdbc.driver.OracleDriver");
Class.forName("org.sqlite.JDBC");
String dbPath = "";
//c = DriverManager.getConnection("jdbc:sqlite:/Users/haaris/Workspace/SQLite/sqlite-shell-win32-x86-3080100/foodbank.db");
//c = DriverManager.getConnection("jdbc:sqlite:/Users/haaris/apache-tomcat-7.0.47/webapps/foodapp/foodbank.db");
c = DriverManager.getConnection(sqlliteDbUrl);
return c;
}
catch (Exception e)
{
System.out.println("Where is your Oracle JDBC Driver?");
e.printStackTrace();
return null;
}
}
public void registerFoodPlace(PrintWriter out, HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
Statement s = null;
int queryExecuted = 0;
String query = "";
Connection c = getDBConnection();
if (c == null)
{
out.println("Could not connect to DB");
System.out.println("Could not connect to DB");
return;
}
out.println("<html> <head> </head> <body> ");
out.println("Place name: " + req.getParameter("foodPlaceName"));
out.println("Place address: " + req.getParameter("foodPlaceStreetAddress")
+ ", " + req.getParameter("foodPlaceCity") + ","
+ req.getParameter("foodPlaceState") +
req.getParameter("foodPlaceZip"));
System.out.println("Place name: " + req.getParameter("foodPlaceName"));
System.out.println("Place address: " + req.getParameter("foodPlaceStreetAddress")
+ ", " + req.getParameter("foodPlaceCity") + ","
+ req.getParameter("foodPlaceState") +
req.getParameter("foodPlaceZip"));
try
{
//c = DriverManager.getConnection("jdbc:oracle:thin:@192.168.1.8:1521/XE", "system", "admin");
//c = DriverManager.getConnection("jdbc:oracle:thin:@10.159.226.169:1521/XE", "system", "admin");
s = c.createStatement();
query = "insert into foodappuser (username, password, usertype) values (" + "'"+ req.getParameter("foodPlaceOwnerName") + "'"
+ ", " + "'" + req.getParameter("foodPlaceOwnerPassword") + "'" + ", 'owner')";
out.println("query: " + query);
queryExecuted = s.executeUpdate(query);
query = "insert into foodplace (ownername, name, streetaddress, city, state, zip, phonenumber)"
+ "values (" +"'"+ req.getParameter("foodPlaceOwnerName") + "'"
+ ", " + "'" + req.getParameter("foodPlaceName") + "'" +", '" + req.getParameter("foodPlaceStreetAddress") + "', '"
+ req.getParameter("foodPlaceCity")
+ "'" + ", '" + req.getParameter("foodPlaceState") + "'" + ", " + req.getParameter("foodPlaceZip") + ", "
+ req.getParameter("foodPlacePhone") + ")";
out.println("query: " + query);
queryExecuted = s.executeUpdate(query);
c.close();
s.close();
out.println("Data inserted into db");
out.println("</body> </html> ");
System.out.println("Data inserted into db");
}
catch (SQLException e)
{
out.println("Exception: could not insert data" + e.getMessage());
out.println("</body> </html> ");
e.printStackTrace();
return;
}
}
public void registerOrganization(PrintWriter out, HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
Statement s = null;
String query = "";
int queryExecuted = 0;
Connection c = getDBConnection();
if (c == null)
{
out.println("Could not connect to DB");
System.out.println("Could not connect to DB");
return;
}
try
{
//c = DriverManager.getConnection("jdbc:oracle:thin:@192.168.1.8:1521/XE", "system", "admin");
<|fim▁hole|> query = "insert into foodappuser (username, password, usertype) values (" + "'"+ req.getParameter("memberName") + "'"
+ ", " + "'" + req.getParameter("memberPassword") + "'" + ", 'organization')";
out.println("query: " + query);
queryExecuted = s.executeUpdate(query);
query = "insert into organization (member, name) values (" + "'"
+req.getParameter("memberName")+"', " + "'" +
req.getParameter("name")+"')";
out.println("query: " + query);
queryExecuted = s.executeUpdate(query);
c.close();
s.close();
out.println("Data inserted into db");
out.println("</body> </html> ");
System.out.println("Data inserted into db");
}
catch (SQLException e)
{
out.println("Exception: could not insert data" + e.getMessage());
out.println("</body> </html> ");
e.printStackTrace();
return;
}
}
}<|fim▁end|> | //c = DriverManager.getConnection("jdbc:oracle:thin:@10.159.226.169:1521/XE", "system", "admin");
s = c.createStatement();
|
<|file_name|>taste.rs<|end_file_name|><|fim▁begin|>use config::{parse_config, Benchmark, Config};
use git2;
use repo::Workspace;
use Commit;
use Push;
use std::collections::HashMap;
use std::io;
use std::path::Path;
use std::process::{Command, ExitStatus, Output};
use std::str;
/// `(val, percentage_change)`
#[derive(Debug, Clone)]
pub enum BenchmarkResult<T> {
Improvement(T, f64),
Regression(T, f64),
Neutral(T, f64),
}
#[derive(Debug, Clone)]
pub struct TastingResult {
pub branch: Option<String>,
pub commit: Commit,
pub build: bool,
pub test: bool,
pub bench: bool,
pub results: Option<Vec<(Benchmark, ExitStatus, HashMap<String, BenchmarkResult<f64>>)>>,
}
fn run_benchmark(workdir: &str, cfg: &Config, bench: &Benchmark, timeout: Option<u64>) -> Output {
let mut cmd = if cfg.version.is_none() || cfg.version.unwrap() < 2 {
// older taster configs assume an implied "cargo" prefix on each benchmark command
match timeout {
None => {
let mut cmd = Command::new("cargo");
cmd.arg(&bench.cmd);
cmd
}
Some(timeout) => {
let mut cmd = Command::new("timeout");
cmd.arg("-k")
.arg(&format!("{}s", timeout + 30))
.arg(&format!("{}s", timeout))
.arg("cargo")
.arg(&bench.cmd);
cmd
}
}
} else {
// from taster config version 2, we no longer assume an implicit "cargo" prefix on
// benchmark commands
match timeout {
None => Command::new(&bench.cmd),
Some(timeout) => {
let mut cmd = Command::new("timeout");
cmd.arg("-k")
.arg(&format!("{}s", timeout + 30))
.arg(&format!("{}s", timeout))
.arg(&bench.cmd);
cmd
}
}
};
cmd.current_dir(workdir)
.env("RUST_BACKTRACE", "1")
.args(bench.args.as_slice());
cmd.output()
.expect(&format!("Failed to execute benchmark '{}'!", bench.name))
}
fn write_output(output: &Output, commit_id: git2::Oid, name: &str) {
use std::fs::File;
use std::io::Write;
let mut stdout_file =
File::create(&format!("{}-{}-stdout.log", commit_id, name)).expect(&format!(
"Failed to create stdout log file for '{}' at commit '{}'.",
name, commit_id
));
stdout_file
.write_all(output.stdout.as_slice())
.expect("Failed to write output to stdout log file!");
let mut stderr_file =
File::create(&format!("{}-{}-stderr.log", commit_id, name)).expect(&format!(
"Failed to create stderr log file for '{}' at commit '{}'.",
name, commit_id
));
stderr_file
.write_all(output.stderr.as_slice())
.expect("Failed to write output to stderr log file!");
}
fn benchmark(
workdir: &str,
cfg: &Config,
bench: &Benchmark,
commit_id: git2::Oid,
previous_result: Option<&HashMap<String, BenchmarkResult<f64>>>,
timeout: Option<u64>,
) -> (ExitStatus, HashMap<String, BenchmarkResult<f64>>) {
// Run the benchmark and collect its output
let output = run_benchmark(workdir, cfg, bench, timeout);
write_output(&output, commit_id, &bench.name);
let lines = str::from_utf8(output.stdout.as_slice())
.unwrap()
.lines()
.chain(str::from_utf8(output.stderr.as_slice()).unwrap().lines());
let mut res = HashMap::new();
// Don't try parsing the output if we didn't succeed
if !output.status.success() {
return (output.status, res);
}
// Success, so let's look for the results
for l in lines {
for (i, regex) in bench.result_expr.iter().enumerate() {
for cap in regex.captures_iter(l) {
let (metric, value) = if cap.len() > 2 {
(String::from(cap.at(1).unwrap()), cap.at(2))
} else {
(format!("{}", i), cap.at(1))
};
let bm_name = format!("{}/{}", bench.name, &metric);
if let Some(c) = value {
use std::str::FromStr;
let val = match f64::from_str(&c) {
Ok(f) => f,
Err(_) => {
println!(
"failed to parse value '{}' for {} into f64 number, ignoring",
c, bm_name
);
continue;
}
};
let new_result = match previous_result {
None => BenchmarkResult::Improvement(val, 0.0),
Some(prev_res) => {
let old_val = match prev_res.get(&bm_name) {
None => val,
Some(pv) => match *pv {
BenchmarkResult::Improvement(v, _) => v,
BenchmarkResult::Regression(v, _) => v,
BenchmarkResult::Neutral(v, _) => v,
},
};
let new_result = if bench.lower_is_better {
if val >= old_val * (1.0 + bench.regression_threshold) {
BenchmarkResult::Regression(val, (val / old_val) - 1.0)
} else if val < old_val * (1.0 - bench.improvement_threshold) {
BenchmarkResult::Improvement(val, (val / old_val) - 1.0)
} else {
BenchmarkResult::Neutral(val, (val / old_val) - 1.0)
}
} else {
if val >= old_val * (1.0 + bench.improvement_threshold) {
BenchmarkResult::Improvement(val, (val / old_val) - 1.0)
} else if val < old_val * (1.0 - bench.regression_threshold) {
BenchmarkResult::Regression(val, (val / old_val) - 1.0)
} else {
BenchmarkResult::Neutral(val, (val / old_val) - 1.0)
}
};
new_result
}
};
res.insert(bm_name, new_result);
}
}
}
}
(output.status, res)
}
fn build(workdir: &str) -> Output {
Command::new("cargo")
.current_dir(workdir)
.arg("check")
.arg("--all")
.arg("--all-targets")
.env("RUST_BACKTRACE", "1")
.output()
.expect("Failed to execute 'cargo build'!")
}
pub fn taste_commit(
ws: &Workspace,
history: &mut HashMap<String, HashMap<String, HashMap<String, BenchmarkResult<f64>>>>,
push: &Push,
commit: &Commit,
def_improvement_threshold: f64,
def_regression_threshold: f64,
timeout: Option<u64>,
) -> Result<(Option<Config>, TastingResult), String> {
println!("Tasting commit {}", commit.id);
ws.checkout_commit(&commit.id)?;
let branch = match push.push_ref {
None => None,
Some(ref pr) => match pr.rfind("/") {
None => None,
Some(i) => Some(String::from(&pr[i + 1..])),
},
};
let version_output = version(&ws.path);
write_output(&version_output, commit.id, "version");
let do_update = !Path::new(&format!("{}/Cargo.lock", ws.path)).exists();
let build_success = {
let update_success = if do_update {
println!("running 'cargo update'");
let update_output = update(&ws.path);
write_output(&update_output, commit.id, "update");
if !update_output.status.success() {
println!("update failed: output status is {:?}", update_output.status);
}
update_output.status.success()
} else {
// nothing to do, always succeeds
true
};
let build_output = build(&ws.path);
write_output(&build_output, commit.id, "build");
if !build_output.status.success() {
println!("build failed: output status is {:?}", build_output.status);
}
update_success && build_output.status.success()
};
let test_output = test(&ws.path, timeout);
write_output(&test_output, commit.id, "test");
if !test_output.status.success() {
println!("tests failed: output status is {:?}", test_output.status);
}
let cfg = match parse_config(
Path::new(&format!("{}/taster.toml", ws.path)),
def_improvement_threshold,
def_regression_threshold,
) {
Ok(c) => c,
Err(e) => match e.kind() {
io::ErrorKind::NotFound => {
println!(
"Skipping commit {} which doesn't have a Taster config.",
commit.id
);
return Ok((
None,
TastingResult {
branch: branch,
commit: commit.clone(),
build: build_success,
test: test_output.status.success(),
bench: false,
results: None,
},
));
}
io::ErrorKind::InvalidInput => {
println!(
"Skipping commit {} which has an invalid Taster config.",
commit.id
);
return Ok((
None,
TastingResult {
branch: branch,
commit: commit.clone(),
build: build_success,
test: test_output.status.success(),
bench: false,
results: None,
},
));
}
_ => unimplemented!(),
},
};
let bench_results = match branch {
Some(ref branch) => {
let branch_history = history.entry(branch.clone()).or_insert(HashMap::new());
cfg.benchmarks
.iter()
.map(|b| {
let (status, res) = benchmark(
&ws.path,
&cfg,
b,
commit.id,
branch_history.get(&b.name),
timeout,
);
branch_history.insert(b.name.clone(), res.clone());
(b.clone(), status, res)
})
.collect::<Vec<(Benchmark, ExitStatus, HashMap<String, BenchmarkResult<f64>>)>>()
}
None => cfg
.benchmarks
.iter()
.map(|b| {
let (status, res) = benchmark(&ws.path, &cfg, b, commit.id, None, timeout);
(b.clone(), status, res)
})
.collect::<Vec<(Benchmark, ExitStatus, HashMap<String, BenchmarkResult<f64>>)>>(),
};
let bench_success = bench_results.iter().all(|x| x.1.success());
Ok((
Some(cfg),
TastingResult {
branch: branch,
commit: commit.clone(),
build: build_success,
test: test_output.status.success(),
bench: bench_success,
results: Some(bench_results),
},
))
}
fn test(workdir: &str, timeout: Option<u64>) -> Output {
let mut cmd = match timeout {
None => {
let mut cmd = Command::new("cargo");
cmd.arg("test").arg("--all");
cmd
}
Some(timeout) => {
let mut cmd = Command::new("timeout");
cmd.arg("-k")
.arg(&format!("{}s", timeout + 30))
.arg(&format!("{}s", timeout))
.arg("cargo")
.arg("test")
.arg("--all");
cmd
}
};
cmd.current_dir(workdir)
.env("RUST_BACKTRACE", "1")
.env("RUST_TEST_THREADS", "1")
.output()
.expect("Failed to execute 'cargo test'!")
}
fn update(workdir: &str) -> Output {
Command::new("cargo")
.current_dir(workdir)<|fim▁hole|> .arg("update")
.output()
.expect("Failed to execute 'cargo update'!")
}
fn version(workdir: &str) -> Output {
Command::new("rustc")
.current_dir(workdir)
.arg("--version")
.output()
.expect("Failed to execute 'rustc --version'!")
}<|fim▁end|> | |
<|file_name|>validation_info.ts<|end_file_name|><|fim▁begin|>// Copyright 2021 Google LLC
//<|fim▁hole|>//
// 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 {Component} from '@angular/core';
import {MatDialogRef} from '@angular/material/dialog';
/** Displays the instruction for validation related actions */
@Component({
selector: 'validation-info-dialog',
templateUrl: 'validation_info.ng.html',
styleUrls: ['validation_info.css']
})
export class ValidationInfoDialogComponent {
constructor(
public dialogRef: MatDialogRef<ValidationInfoDialogComponent>,
) {}
onOkClick(): void {
this.dialogRef.close();
}
}<|fim▁end|> | // 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 |
<|file_name|>ocvOpticalFlowApp.cpp<|end_file_name|><|fim▁begin|>#include "cinder/app/AppNative.h"
#include "cinder/gl/Texture.h"
#include "cinder/Capture.h"
#include "cinder/params/Params.h"
#include "CinderOpenCV.h"
using namespace ci;
using namespace ci::app;
using namespace std;
class ocvOpticalFlowApp : public AppNative {
public:
void setup();
void update();
void draw();
void keyDown( KeyEvent event );
void chooseFeatures( cv::Mat currentFrame );
void trackFeatures( cv::Mat currentFrame );
gl::Texture mTexture;
Capture mCapture;
cv::Mat mPrevFrame;
vector<cv::Point2f> mPrevFeatures, mFeatures;
vector<uint8_t> mFeatureStatuses;
bool mDrawPoints;
static const int MAX_FEATURES = 300;
};
void ocvOpticalFlowApp::setup()
{
mDrawPoints = true;
mCapture = Capture( 640, 480 );
mCapture.start();
}
void ocvOpticalFlowApp::keyDown( KeyEvent event )
{
if( event.getChar() == 'p' ) {
mDrawPoints = ! mDrawPoints;
}
else if( event.getChar() == 'u' ) {
chooseFeatures( mPrevFrame );
}
}
void ocvOpticalFlowApp::chooseFeatures( cv::Mat currentFrame )
{
cv::goodFeaturesToTrack( currentFrame, mFeatures, MAX_FEATURES, 0.005, 3.0 );
}
void ocvOpticalFlowApp::trackFeatures( cv::Mat currentFrame )
{
vector<float> errors;
mPrevFeatures = mFeatures;
if( ! mFeatures.empty() )
cv::calcOpticalFlowPyrLK( mPrevFrame, currentFrame, mPrevFeatures, mFeatures, mFeatureStatuses, errors );
}
void ocvOpticalFlowApp::update()
{
if( mCapture.checkNewFrame() ) {
Surface surface( mCapture.getSurface() );
mTexture = gl::Texture( surface );<|fim▁hole|> trackFeatures( currentFrame );
}
mPrevFrame = currentFrame;
}
}
void ocvOpticalFlowApp::draw()
{
if( ( ! mTexture ) || mPrevFeatures.empty() )
return;
gl::clear();
gl::enableAlphaBlending();
gl::setMatricesWindow( getWindowSize() );
gl::color( 1, 1, 1 );
gl::draw( mTexture );
glDisable( GL_TEXTURE_2D );
glColor4f( 1, 1, 0, 0.5f );
if( mDrawPoints ) {
// draw all the old points
for( vector<cv::Point2f>::const_iterator featureIt = mPrevFeatures.begin(); featureIt != mPrevFeatures.end(); ++featureIt )
gl::drawStrokedCircle( fromOcv( *featureIt ), 4 );
// draw all the new points
for( vector<cv::Point2f>::const_iterator featureIt = mFeatures.begin(); featureIt != mFeatures.end(); ++featureIt )
gl::drawSolidCircle( fromOcv( *featureIt ), 4 );
}
// draw the lines connecting them
#if ! defined( CINDER_COCOA_TOUCH )
glColor4f( 0, 1, 0, 0.5f );
glBegin( GL_LINES );
for( size_t idx = 0; idx < mFeatures.size(); ++idx ) {
if( mFeatureStatuses[idx] ) {
gl::vertex( fromOcv( mFeatures[idx] ) );
gl::vertex( fromOcv( mPrevFeatures[idx] ) );
}
}
glEnd();
#endif
}
CINDER_APP_NATIVE( ocvOpticalFlowApp, RendererGl )<|fim▁end|> | cv::Mat currentFrame( toOcv( Channel( surface ) ) );
if( mPrevFrame.data ) {
if( mFeatures.empty() || getElapsedFrames() % 30 == 0 ) // pick new features once every 30 frames, or the first frame
chooseFeatures( mPrevFrame ); |
<|file_name|>_translation_utils.py<|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.
# coding: utf-8
"""Utilities used for translating operators from Onnx to Mxnet."""
# pylint: disable=protected-access
from __future__ import absolute_import as _abs
from .... import symbol
from .... import module
from .... import context
from .... import ndarray as nd
from .... import io
def _fix_attribute_names(attrs, change_map):
"""
Change attribute names as per values in change_map dictionary.
Parameters
----------
:param attrs : dict Dict of operator attributes
:param change_map : dict Dict of onnx attribute name to mxnet attribute names.
Returns
-------
:return new_attr : dict Converted dict of operator attributes.
"""
new_attr = {}
for k in attrs.keys():
if k in change_map:
new_attr[change_map[k]] = attrs[k]
else:
new_attr[k] = attrs[k]
return new_attr
def _remove_attributes(attrs, remove_list):
"""
Removes attributes in the remove list from the input attribute dict
:param attrs : Dict of operator attributes
:param remove_list : list of attributes to be removed
:return new_attr : Dict of operator attributes without the listed attributes.
"""
new_attrs = {}
for attr in attrs.keys():
if attr not in remove_list:
new_attrs[attr] = attrs[attr]
return new_attrs
def _add_extra_attributes(attrs, extra_attr_map):
"""
:param attrs: Current Attribute list
:param extraAttrMap: Additional attributes to be added
:return: new_attr<|fim▁hole|> if attr not in attrs:
attrs[attr] = extra_attr_map[attr]
return attrs
def _pad_sequence_fix(attr, kernel_dim=None):
"""Changing onnx's pads sequence to match with mxnet's pad_width
mxnet: (x1_begin, x1_end, ... , xn_begin, xn_end)
onnx: (x1_begin, x2_begin, ... , xn_end, xn_end)"""
new_attr = ()
if len(attr) % 2 == 0:
for index in range(int(len(attr) / 2)):
new_attr = new_attr + attr[index::int(len(attr) / 2)]
# Making sure pad values are in the attr for all axes.
if kernel_dim is not None:
while len(new_attr) < kernel_dim*2:
new_attr = new_attr + (0, 0)
return new_attr
def _fix_pooling(pool_type, inputs, new_attr):
"""onnx pooling operator supports asymmetrical padding
Adding pad operator before pooling in mxnet to work with onnx"""
stride = new_attr.get('stride')
kernel = new_attr.get('kernel')
padding = new_attr.get('pad')
p_value = new_attr.get('p_value')
# Adding default stride.
if stride is None:
stride = (1,) * len(kernel)
# Add padding attr if not provided.
if padding is None:
padding = (0,) * len(kernel) * 2
# Mxnet Pad operator supports only 4D/5D tensors.
# For 1D case, these are the steps:
# Step 1. Add extra dummy dimension to make it 4D. Adding to axis = 2
# Step 2. Apply padding to this changed tensor
# Step 3. Remove the extra dimension added in step 1.
if len(kernel) == 1:
dummy_axis = 2
# setting 0 padding to the new dim to be added.
padding = (0, padding[0], 0, padding[1])
pad_width = (0, 0, 0, 0) + _pad_sequence_fix(padding, kernel_dim=2)
# Step 1.
curr_sym = symbol.expand_dims(inputs[0], axis=dummy_axis)
# Step 2. Common for all tensor sizes
new_pad_op = symbol.pad(curr_sym, mode='edge', pad_width=pad_width)
# Step 3: Removing extra dim added.
new_pad_op = symbol.split(new_pad_op, axis=dummy_axis, num_outputs=1, squeeze_axis=1)
else:
# For 2D/3D cases:
# Apply padding
pad_width = (0, 0, 0, 0) + _pad_sequence_fix(padding, kernel_dim=len(kernel))
curr_sym = inputs[0]
if pool_type == 'max':
# For max pool : mode = 'edge', we should replicate the
# edge values to pad, so that we only include input data values
# for calculating 'max'
new_pad_op = symbol.pad(curr_sym, mode='edge', pad_width=pad_width)
else:
# For avg pool, we should add 'zeros' for padding so mode='constant'
new_pad_op = symbol.pad(curr_sym, mode='constant', pad_width=pad_width)
# Apply pooling without pads.
if pool_type == 'lp':
new_pooling_op = symbol.Pooling(new_pad_op, pool_type=pool_type, stride=stride, kernel=kernel, p_value=p_value)
else:
new_pooling_op = symbol.Pooling(new_pad_op, pool_type=pool_type, stride=stride, kernel=kernel)
return new_pooling_op
def _fix_bias(op_name, attrs, num_inputs):
"""A workaround for 'use_bias' attribute since onnx don't provide this attribute,
we have to check the number of inputs to decide it."""
if num_inputs == 3:
attrs['no_bias'] = False
elif num_inputs == 2:
attrs['no_bias'] = True
else:
raise ValueError("Unexpected number of inputs for: {}".format(op_name))
return attrs
def _fix_broadcast(op_name, inputs, broadcast_axis, proto_obj):
"""A workaround to reshape bias term to (1, num_channel)."""
if int(len(proto_obj._params)) > 0:
assert len(list(inputs)) == 2
input0_shape = get_input_shape(inputs[0], proto_obj)
#creating reshape shape
reshape_shape = list(len(input0_shape) * (1,))
reshape_shape[broadcast_axis] = -1
reshape_shape = tuple(reshape_shape)
reshape_op_sym = symbol.reshape(inputs[1], shape=reshape_shape)
op_sym = getattr(symbol, op_name)(inputs[0], reshape_op_sym)
else:
op_sym = op_name
return op_sym
def _fix_channels(op_name, attrs, inputs, proto_obj):
"""A workaround for getting 'channels' or 'units' since onnx don't provide
these attributes. We check the shape of weights provided to get the number.
"""
weight_name = inputs[1].name
if not weight_name in proto_obj._params:
raise ValueError("Unable to get channels/units attr from onnx graph.")
else:
wshape = proto_obj._params[weight_name].shape
assert len(wshape) >= 2, "Weights shape is invalid: {}".format(wshape)
if op_name == 'FullyConnected':
attrs['num_hidden'] = wshape[0]
else:
if op_name == 'Convolution':
# Weight shape for Conv and FC: (M x C x kH x kW) : M is number of
# feature maps/hidden and C is number of channels
attrs['num_filter'] = wshape[0]
elif op_name == 'Deconvolution':
# Weight shape for DeConv : (C x M x kH x kW) : M is number of
# feature maps/filters and C is number of channels
attrs['num_filter'] = wshape[1]
return attrs
def _fix_gemm(op_name, inputs, old_attr, proto_obj):
"""Using FullyConnected operator in place of linalg_gemm to perform same operation"""
op_sym = getattr(symbol, op_name, None)
alpha = float(old_attr.get('alpha', 1.0))
beta = float(old_attr.get('beta', 1.0))
trans_a = int(old_attr.get('transA', 0))
trans_b = int(old_attr.get('transB', 0))
if trans_a:
inputs[0] = symbol.transpose(inputs[0], axes=(1, 0))
if not trans_b:
inputs[1] = symbol.transpose(inputs[1], axes=(1, 0))
new_inputs = [alpha*inputs[0], inputs[1], beta*inputs[2]]
new_attr = {'num_hidden' : proto_obj._params[inputs[2].name].shape[0]}
return op_sym, new_attr, new_inputs
def get_input_shape(sym, proto_obj):
"""Helper function to obtain the shape of an array"""
arg_params = proto_obj.arg_dict
aux_params = proto_obj.aux_dict
model_input_shape = [data[1] for data in proto_obj.model_metadata.get('input_tensor_data')]
data_names = [data[0] for data in proto_obj.model_metadata.get('input_tensor_data')]
#creating dummy inputs
inputs = []
for in_shape in model_input_shape:
inputs.append(nd.ones(shape=in_shape))
data_shapes = []
for idx, input_name in enumerate(data_names):
data_shapes.append((input_name, inputs[idx].shape))
ctx = context.cpu()
# create a module
mod = module.Module(symbol=sym, data_names=data_names, context=ctx, label_names=None)
mod.bind(for_training=False, data_shapes=data_shapes, label_shapes=None)
mod.set_params(arg_params=arg_params, aux_params=aux_params)
data_forward = []
for idx, input_name in enumerate(data_names):
val = inputs[idx]
data_forward.append(val)
mod.forward(io.DataBatch(data_forward))
result = mod.get_outputs()[0].asnumpy()
return result.shape<|fim▁end|> | """
for attr in extra_attr_map: |
<|file_name|>mathUtils.ts<|end_file_name|><|fim▁begin|>///<reference path="../reference.ts" />
module Plottable {
export module Utils {
export module Math {
let nativeMath: Math = (<any>window).Math;
/**
* Checks if x is between a and b.
*
* @param {number} x The value to test if in range
* @param {number} a The beginning of the (inclusive) range
* @param {number} b The ending of the (inclusive) range
* @return {boolean} Whether x is in [a, b]
*/
export function inRange(x: number, a: number, b: number) {
return (nativeMath.min(a, b) <= x && x <= nativeMath.max(a, b));
}
/**
* Clamps x to the range [min, max].
*
* @param {number} x The value to be clamped.
* @param {number} min The minimum value.
* @param {number} max The maximum value.
* @return {number} A clamped value in the range [min, max].
*/
export function clamp(x: number, min: number, max: number) {
return nativeMath.min(nativeMath.max(min, x), max);
}
/**
* Applies the accessor, if provided, to each element of `array` and returns the maximum value.
* If no maximum value can be computed, returns defaultValue.
*/
export function max<C>(array: C[], defaultValue: C): C;
export function max<T, C>(array: T[], accessor: (t?: T, i?: number) => C, defaultValue: C): C;
export function max(array: any[], firstArg: any, secondArg?: any): any {
let accessor = typeof(firstArg) === "function" ? firstArg : null;
let defaultValue = accessor == null ? firstArg : secondArg;
/* tslint:disable:ban */
let maxValue = accessor == null ? d3.max(array) : d3.max(array, accessor);
/* tslint:enable:ban */
return maxValue !== undefined ? maxValue : defaultValue;
}
/**
* Applies the accessor, if provided, to each element of `array` and returns the minimum value.
* If no minimum value can be computed, returns defaultValue.
*/
export function min<C>(array: C[], defaultValue: C): C;
export function min<T, C>(array: T[], accessor: (t?: T, i?: number) => C, defaultValue: C): C;
export function min(array: any[], firstArg: any, secondArg?: any): any {
let accessor = typeof(firstArg) === "function" ? firstArg : null;
let defaultValue = accessor == null ? firstArg : secondArg;
/* tslint:disable:ban */
let minValue = accessor == null ? d3.min(array) : d3.min(array, accessor);
/* tslint:enable:ban */
return minValue !== undefined ? minValue : defaultValue;
}
/**
* Returns true **only** if x is NaN
*/
export function isNaN(n: any) {
return n !== n;
}
/**
* Returns true if the argument is a number, which is not NaN
* Numbers represented as strings do not pass this function
*/
export function isValidNumber(n: any) {
return typeof n === "number" && !Plottable.Utils.Math.isNaN(n) && isFinite(n);
}
/**<|fim▁hole|> * Generates an array of consecutive, strictly increasing numbers
* in the range [start, stop) separeted by step
*/
export function range(start: number, stop: number, step = 1): number[] {
if (step === 0) {
throw new Error("step cannot be 0");
}
let length = nativeMath.max(nativeMath.ceil((stop - start) / step), 0);
let range: number[] = [];
for (let i = 0; i < length; ++i) {
range[i] = start + step * i;
}
return range;
}
/**
* Returns the square of the distance between two points
*
* @param {Point} p1
* @param {Point} p2
* @return {number} dist(p1, p2)^2
*/
export function distanceSquared(p1: Point, p2: Point) {
return nativeMath.pow(p2.y - p1.y, 2) + nativeMath.pow(p2.x - p1.x, 2);
}
}
}
}<|fim▁end|> | |
<|file_name|>test_table_view.py<|end_file_name|><|fim▁begin|>'''Tests for helpers_views'''
from mysite import settings
from mysite.helpers.db_access import DBAccess
from mysite.helpers import testhelpers as th
from heatmap.helpers.table_view import (TableForm, QueryForm)
from heatmap.helpers import test_helpers_views as thv
from django.test import TestCase # Provides mocks for client interactions<|fim▁hole|>class TestTableViews(TestCase):
def setUp(self):
self.assertTrue(th.SetupTestDB())
self.db_path = th.TEST_DB_PATH
self.dba = DBAccess(db_path=self.db_path)
self.conn = sqlite3.connect(self.db_path)
self.cursor = self.conn.cursor()
def tearDown(self):
th.TearDownTestDB()
def testmaketable(self):
CLIENT_URL = '/heatmap/maketable/'
TABLE_LIST = ['data_rev', 'data']
response = self.client.get(CLIENT_URL)
self.assertEqual(response.status_code, 200)
form_data = {'numrows': 10, 'lastrow': 1}
form = TableForm(data=form_data)
post_dict = {'display_form': form,
'tablename': TABLE_LIST[0],
'table_list': TABLE_LIST}
response = self.client.post(CLIENT_URL, post_dict)
self.assertEqual(response.status_code, 200)
def testDeletetable(self):
# Put in the file to delete
CLIENT_URL = '/heatmap/upload/'
post_dict = {'filename': thv.TEST_DATA_FILENAME}
response = self.client.post(CLIENT_URL, post_dict)
# Delete the file
CLIENT_URL = '/heatmap/deletetable/'
response = self.client.get(CLIENT_URL)
self.assertEqual(response.status_code, 200)
post_dict = {'tablename': thv.TEST_DATA_TABLENAME}
response = self.client.post(CLIENT_URL, post_dict)
self.assertEqual(response.status_code, 200)
def testQuery(self):
CLIENT_URL = '/heatmap/query/'
TABLE_LIST = ['data_rev', 'data']
TABLE_NAME = "testQuery"
response = self.client.get(CLIENT_URL)
self.assertEqual(response.status_code, 200)
# Test the post
th.CreateTableWithData(TABLE_NAME, self.conn)
query_string = "SELECT * from %s" % TABLE_NAME
form = QueryForm(data={'query_string': query_string})
post_dict = {'form': form,
'table_list': TABLE_LIST}
response = self.client.post(CLIENT_URL, post_dict)
self.assertEqual(response.status_code, 200)
if __name__ == '__main__':
unittest.main()<|fim▁end|> | import os
import sqlite3
|
<|file_name|>junos.py<|end_file_name|><|fim▁begin|>#
# (c) 2016 Red Hat Inc.
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
#
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import sys
import copy
from ansible.module_utils.basic import AnsibleFallbackNotFound
from ansible.module_utils.junos import junos_argument_spec
from ansible.module_utils.six import iteritems
from ansible.plugins import connection_loader, module_loader
from ansible.plugins.action.normal import ActionModule as _ActionModule
from ansible.utils.path import unfrackpath
try:
from __main__ import display
except ImportError:
from ansible.utils.display import Display
display = Display()
class ActionModule(_ActionModule):
def run(self, tmp=None, task_vars=None):
if self._play_context.connection != 'local':
return dict(
failed=True,
msg='invalid connection specified, expected connection=local, '
'got %s' % self._play_context.connection
)
module = module_loader._load_module_source(self._task.action, module_loader.find_plugin(self._task.action))
if not getattr(module, 'USE_PERSISTENT_CONNECTION', False):
return super(ActionModule, self).run(tmp, task_vars)
provider = self.load_provider()
pc = copy.deepcopy(self._play_context)
pc.network_os = 'junos'
pc.remote_addr = provider['host'] or self._play_context.remote_addr
if self._task.action == 'junos_netconf':
pc.connection = 'network_cli'
pc.port = provider['port'] or self._play_context.port or 22
else:
pc.connection = 'netconf'
pc.port = provider['port'] or self._play_context.port or 830
pc.remote_user = provider['username'] or self._play_context.connection_user
pc.password = provider['password'] or self._play_context.password
pc.private_key_file = provider['ssh_keyfile'] or self._play_context.private_key_file
pc.timeout = provider['timeout'] or self._play_context.timeout
display.vvv('using connection plugin %s' % pc.connection, pc.remote_addr)
connection = self._shared_loader_obj.connection_loader.get('persistent', pc, sys.stdin)
socket_path = self._get_socket_path(pc)
display.vvvv('socket_path: %s' % socket_path, pc.remote_addr)
if not os.path.exists(socket_path):
# start the connection if it isn't started
if pc.connection == 'netconf':
rc, out, err = connection.exec_command('open_session()')
else:
rc, out, err = connection.exec_command('open_shell()')
if rc != 0:
return {'failed': True,
'msg': 'unable to open shell. Please see: ' +
'https://docs.ansible.com/ansible/network_debug_troubleshooting.html#unable-to-open-shell',
'rc': rc}
elif pc.connection == 'network_cli':
# make sure we are in the right cli context which should be
# enable mode and not config module
rc, out, err = connection.exec_command('prompt()')
while str(out).strip().endswith(')#'):
display.vvvv('wrong context, sending exit to device', self._play_context.remote_addr)
connection.exec_command('exit')
rc, out, err = connection.exec_command('prompt()')
task_vars['ansible_socket'] = socket_path
result = super(ActionModule, self).run(tmp, task_vars)
return result
def _get_socket_path(self, play_context):
ssh = connection_loader.get('ssh', class_only=True)
path = unfrackpath("$HOME/.ansible/pc")
# use play_context.connection instea of play_context.port to avoid
# collision if netconf is listening on port 22
#cp = ssh._create_control_path(play_context.remote_addr, play_context.connection, play_context.remote_user)
cp = ssh._create_control_path(play_context.remote_addr, play_context.port, play_context.remote_user)
return cp % dict(directory=path)
def load_provider(self):
provider = self._task.args.get('provider', {})
for key, value in iteritems(junos_argument_spec):
if key != 'provider' and key not in provider:
if key in self._task.args:
provider[key] = self._task.args[key]
elif 'fallback' in value:
provider[key] = self._fallback(value['fallback'])
elif key not in provider:
provider[key] = None
return provider
def _fallback(self, fallback):
strategy = fallback[0]
args = []
kwargs = {}
for item in fallback[1:]:
if isinstance(item, dict):
kwargs = item
else:
args = item<|fim▁hole|> pass<|fim▁end|> | try:
return strategy(*args, **kwargs)
except AnsibleFallbackNotFound: |
<|file_name|>KT2_J1_vahenda_tester.py<|end_file_name|><|fim▁begin|>"""
Task description (in Estonian):
3. Maatriksi vähendamine (6p)
Kirjuta funktsioon vähenda, mis võtab argumendiks arvumaatriksi, milles ridu ja
veerge on paarisarv, ning tagastab uue maatriksi, milles on kaks korda vähem
ridu ja kaks korda vähem veerge, ja kus iga element on esialgse maatriksi nelja
elemendi keskmine, järgnevas näites toodud skeemi järgi:
See tähendab, et
vähenda([[1,5,2,6,3,6], [1,3,2,7,3,3], [4,8,5,1,1,6], [4,4,9,5,6,1]])
peab tagastama
[[2.5, 4.25, 3.75], [5.0, 5.0, 3.5]].
"""
from grader import *
from KT2_util import make_checker
def vähenda(maatriks):
tulemus = []
for r in range(0, len(maatriks), 2):
rida = []
for c in range(0, len(maatriks[r]), 2):
tul = 0
for i in range(4):
tul += maatriks[r+i%2][c+i//2]
rida.append(tul / 4.0)
tulemus.append(rida)
return tulemus
checker = make_checker(vähenda)
checker([[1, 2], [3, 4]],
description="Ruudukujuline 2x2 maatriks- {function}({args}) == {expected}")
checker([[1, 2, 3, 4], [5, 6, 7, 8]],
description="Mitte-ruudukujuline maatriks - {function}({args}) == {expected}")
checker([[1,5,2,6,3,6], [1,3,2,7,3,3], [4,8,5,1,1,6], [4,4,9,5,6,1]])
checker([[1,5,2,6,3,6], [1,3,2,7,3,3], [4,8,5,1,1,6], [4,4,9,5,6,1]])
checker([],
description="Erijuht, tühi maatriks- {function}({args}) == {expected}")
random_tests = [
[[7, 5, 2, 6, 6, 9], [2, 8, 6, 3, 8, 7]],
[[3, 1, 0, 9], [0, 5, 1, 7]],
[[4, 4], [0, 8], [4, 9], [3, 0], [3, 6], [8, 2]],<|fim▁hole|> [8, 9, 8, 5, 0, 2],
[2, 7, 2, 4, 3, 5],
[2, 6, 8, 0, 2, 9],
[7, 4, 6, 4, 8, 2]],
[[-1, -3], [-6, 6], [5, -6], [1, 0]],
[[-5, -10, 6, -1], [-8, -10, -5, 7], [-7, 9, -5, -5], [-8, -7, -10, 8]],
[[-3, 6, -3, 6], [4, -6, 3, 8], [-9, -6, 7, -6], [6, 6, 4, -3]],
[[1, 6], [2, -6]]
]
for test_case in random_tests:
checker(test_case)<|fim▁end|> |
[[9, 4, 6, 5, 4, 6],
[3, 8, 7, 1, 2, 5], |
<|file_name|>dns_resolver.rs<|end_file_name|><|fim▁begin|>//! Asynchronous DNS resolver
use std::{
io::{self, ErrorKind},
net::SocketAddr,
};
use futures::Future;
use tokio;
use trust_dns_resolver::{config::ResolverConfig, AsyncResolver};
use crate::context::SharedContext;
pub fn create_resolver(dns: Option<ResolverConfig>) -> AsyncResolver {
let (resolver, bg) = {
// To make this independent, if targeting macOS, BSD, Linux, or Windows, we can use the system's configuration:<|fim▁hole|> if let Some(conf) = dns {
use trust_dns_resolver::config::ResolverOpts;
AsyncResolver::new(conf, ResolverOpts::default())
} else {
use trust_dns_resolver::system_conf::read_system_conf;
// use the system resolver configuration
let (config, opts) = read_system_conf().expect("Failed to read global dns sysconf");
AsyncResolver::new(config, opts)
}
}
// For other operating systems, we can use one of the preconfigured definitions
#[cfg(not(any(unix, windows)))]
{
// Directly reference the config types
use trust_dns_resolver::config::{ResolverConfig, ResolverOpts};
if let Some(conf) = dns {
AsyncResolver::new(conf, ResolverOpts::default())
} else {
// Get a new resolver with the google nameservers as the upstream recursive resolvers
AsyncResolver::new(ResolverConfig::google(), ResolverOpts::default())
}
}
};
// NOTE: resolving will always be called inside a future.
tokio::spawn(bg);
resolver
}
fn inner_resolve(
context: SharedContext,
addr: &str,
port: u16,
check_forbidden: bool,
) -> impl Future<Item = Vec<SocketAddr>, Error = io::Error> + Send {
// let owned_addr = addr.to_owned();
let cloned_context = context.clone();
context.dns_resolver().lookup_ip(addr).then(move |r| match r {
Err(err) => {
// error!("Failed to resolve {}, err: {}", owned_addr, err);
Err(io::Error::new(
io::ErrorKind::Other,
format!("dns resolve error: {}", err),
))
}
Ok(lookup_result) => {
let mut vaddr = Vec::new();
for ip in lookup_result.iter() {
if check_forbidden {
let forbidden_ip = &cloned_context.config().forbidden_ip;
if forbidden_ip.contains(&ip) {
// debug!("Resolved {} => {}, which is skipped by forbidden_ip", owned_addr, ip);
continue;
}
}
vaddr.push(SocketAddr::new(ip, port));
}
if vaddr.is_empty() {
let err = io::Error::new(
ErrorKind::Other,
// format!("resolved {} to empty address, all IPs are filtered", owned_addr),
"resolved to empty address, all IPs are filtered",
);
Err(err)
} else {
// debug!("Resolved {} => {:?}", owned_addr, vaddr);
Ok(vaddr)
}
}
})
}
/// Resolve address to IP
pub fn resolve(
context: SharedContext,
addr: &str,
port: u16,
check_forbidden: bool,
) -> impl Future<Item = Vec<SocketAddr>, Error = io::Error> + Send {
inner_resolve(context, addr, port, check_forbidden)
}<|fim▁end|> | #[cfg(any(unix, windows))]
{ |
<|file_name|>values.rs<|end_file_name|><|fim▁begin|>#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum MethodType {
Get,
Post,<|fim▁hole|>}<|fim▁end|> | Put,
Delete,
Patch, |
<|file_name|>iceberg.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-<|fim▁hole|>
import json
from django import template
from django.conf import settings
register = template.Library()
from django_iceberg.auth_utils import init_iceberg
@register.inclusion_tag('django_iceberg/javascript_sdk.html', takes_context=True)
def iceberg_javascript_sdk(context):
"""
To Finish
"""
if getattr(settings, 'ICEBERG_USE_LOCAL', False):
livrary_path = 'http://connect.local.iceberg-marketplace.com:9000/script.js'
else:
livrary_path = 'http://connect.iceberg-marketplace.com/script.js'
return {
'LIBRARY_URL': livrary_path
}
@register.inclusion_tag('django_iceberg/sso.html', takes_context=True)
def iceberg_sso(context):
api_handler = init_iceberg(context['request'])
if hasattr(api_handler, '_sso_response'):
return {
'appNamespace': api_handler.conf.ICEBERG_APPLICATION_NAMESPACE,
"sso_data": json.dumps(api_handler._sso_response)
}
else:
return {}
@register.inclusion_tag('django_iceberg/sso.html', takes_context=True)
def iceberg_sso_with_seller(context, seller_id):
api_handler = init_iceberg(context['request'])
if hasattr(api_handler, '_sso_response'):
return {
"modules": json.dumps(['client', 'seller']),
'appNamespace': api_handler.conf.ICEBERG_APPLICATION_NAMESPACE,
"sso_data": json.dumps(api_handler._sso_response),
"seller": json.dumps({"id": seller_id}),
}
else:
return {}<|fim▁end|> |