text
stringlengths
3
1.05M
import io import struct from helper import unittest, PillowTestCase, hopper from PIL import Image, TiffImagePlugin, TiffTags from PIL.TiffImagePlugin import _limit_rational, IFDRational tag_ids = {info.name: info.value for info in TiffTags.TAGS_V2.values()} class TestFileTiffMetadata(PillowTestCase): def test_rt_metadata(self): """ Test writing arbitrary metadata into the tiff image directory Use case is ImageJ private tags, one numeric, one arbitrary data. https://github.com/python-pillow/Pillow/issues/291 """ img = hopper() # Behaviour change: re #1416 # Pre ifd rewrite, ImageJMetaData was being written as a string(2), # Post ifd rewrite, it's defined as arbitrary bytes(7). It should # roundtrip with the actual bytes, rather than stripped text # of the premerge tests. # # For text items, we still have to decode('ascii','replace') because # the tiff file format can't take 8 bit bytes in that field. basetextdata = "This is some arbitrary metadata for a text field" bindata = basetextdata.encode('ascii') + b" \xff" textdata = basetextdata + " " + chr(255) reloaded_textdata = basetextdata + " ?" floatdata = 12.345 doubledata = 67.89 info = TiffImagePlugin.ImageFileDirectory() ImageJMetaData = tag_ids['ImageJMetaData'] ImageJMetaDataByteCounts = tag_ids['ImageJMetaDataByteCounts'] ImageDescription = tag_ids['ImageDescription'] info[ImageJMetaDataByteCounts] = len(bindata) info[ImageJMetaData] = bindata info[tag_ids['RollAngle']] = floatdata info.tagtype[tag_ids['RollAngle']] = 11 info[tag_ids['YawAngle']] = doubledata info.tagtype[tag_ids['YawAngle']] = 12 info[ImageDescription] = textdata f = self.tempfile("temp.tif") img.save(f, tiffinfo=info) loaded = Image.open(f) self.assertEqual(loaded.tag[ImageJMetaDataByteCounts], (len(bindata),)) self.assertEqual(loaded.tag_v2[ImageJMetaDataByteCounts], (len(bindata),)) self.assertEqual(loaded.tag[ImageJMetaData], bindata) self.assertEqual(loaded.tag_v2[ImageJMetaData], bindata) self.assertEqual(loaded.tag[ImageDescription], (reloaded_textdata,)) self.assertEqual(loaded.tag_v2[ImageDescription], reloaded_textdata) loaded_float = loaded.tag[tag_ids['RollAngle']][0] self.assertAlmostEqual(loaded_float, floatdata, places=5) loaded_double = loaded.tag[tag_ids['YawAngle']][0] self.assertAlmostEqual(loaded_double, doubledata) # check with 2 element ImageJMetaDataByteCounts, issue #2006 info[ImageJMetaDataByteCounts] = (8, len(bindata) - 8) img.save(f, tiffinfo=info) loaded = Image.open(f) self.assertEqual(loaded.tag[ImageJMetaDataByteCounts], (8, len(bindata) - 8)) self.assertEqual(loaded.tag_v2[ImageJMetaDataByteCounts], (8, len(bindata) - 8)) def test_read_metadata(self): img = Image.open('Tests/images/hopper_g4.tif') self.assertEqual({'YResolution': IFDRational(4294967295, 113653537), 'PlanarConfiguration': 1, 'BitsPerSample': (1,), 'ImageLength': 128, 'Compression': 4, 'FillOrder': 1, 'RowsPerStrip': 128, 'ResolutionUnit': 3, 'PhotometricInterpretation': 0, 'PageNumber': (0, 1), 'XResolution': IFDRational(4294967295, 113653537), 'ImageWidth': 128, 'Orientation': 1, 'StripByteCounts': (1968,), 'SamplesPerPixel': 1, 'StripOffsets': (8,) }, img.tag_v2.named()) self.assertEqual({'YResolution': ((4294967295, 113653537),), 'PlanarConfiguration': (1,), 'BitsPerSample': (1,), 'ImageLength': (128,), 'Compression': (4,), 'FillOrder': (1,), 'RowsPerStrip': (128,), 'ResolutionUnit': (3,), 'PhotometricInterpretation': (0,), 'PageNumber': (0, 1), 'XResolution': ((4294967295, 113653537),), 'ImageWidth': (128,), 'Orientation': (1,), 'StripByteCounts': (1968,), 'SamplesPerPixel': (1,), 'StripOffsets': (8,) }, img.tag.named()) def test_write_metadata(self): """ Test metadata writing through the python code """ img = Image.open('Tests/images/hopper.tif') f = self.tempfile('temp.tiff') img.save(f, tiffinfo=img.tag) loaded = Image.open(f) original = img.tag_v2.named() reloaded = loaded.tag_v2.named() for k, v in original.items(): if isinstance(v, IFDRational): original[k] = IFDRational(*_limit_rational(v, 2**31)) if isinstance(v, tuple) and isinstance(v[0], IFDRational): original[k] = tuple([IFDRational( *_limit_rational(elt, 2**31)) for elt in v]) ignored = ['StripByteCounts', 'RowsPerStrip', 'PageNumber', 'StripOffsets'] for tag, value in reloaded.items(): if tag in ignored: continue if (isinstance(original[tag], tuple) and isinstance(original[tag][0], IFDRational)): # Need to compare element by element in the tuple, # not comparing tuples of object references self.assert_deep_equal(original[tag], value, "%s didn't roundtrip, %s, %s" % (tag, original[tag], value)) else: self.assertEqual(original[tag], value, "%s didn't roundtrip, %s, %s" % (tag, original[tag], value)) for tag, value in original.items(): if tag not in ignored: self.assertEqual( value, reloaded[tag], "%s didn't roundtrip" % tag) def test_no_duplicate_50741_tag(self): self.assertEqual(tag_ids['MakerNoteSafety'], 50741) self.assertEqual(tag_ids['BestQualityScale'], 50780) def test_empty_metadata(self): f = io.BytesIO(b'II*\x00\x08\x00\x00\x00') head = f.read(8) info = TiffImagePlugin.ImageFileDirectory(head) try: self.assert_warning(UserWarning, info.load, f) except struct.error: self.fail("Should not be struct errors there.") def test_iccprofile(self): # https://github.com/python-pillow/Pillow/issues/1462 im = Image.open('Tests/images/hopper.iccprofile.tif') out = self.tempfile('temp.tiff') im.save(out) reloaded = Image.open(out) self.assertNotIsInstance(im.info['icc_profile'], tuple) self.assertEqual(im.info['icc_profile'], reloaded.info['icc_profile']) def test_iccprofile_binary(self): # https://github.com/python-pillow/Pillow/issues/1526 # We should be able to load this, but probably won't be able to save it. im = Image.open('Tests/images/hopper.iccprofile_binary.tif') self.assertEqual(im.tag_v2.tagtype[34675], 1) self.assertTrue(im.info['icc_profile']) def test_iccprofile_save_png(self): im = Image.open('Tests/images/hopper.iccprofile.tif') outfile = self.tempfile('temp.png') im.save(outfile) def test_iccprofile_binary_save_png(self): im = Image.open('Tests/images/hopper.iccprofile_binary.tif') outfile = self.tempfile('temp.png') im.save(outfile) def test_exif_div_zero(self): im = hopper() info = TiffImagePlugin.ImageFileDirectory_v2() info[41988] = TiffImagePlugin.IFDRational(0, 0) out = self.tempfile('temp.tiff') im.save(out, tiffinfo=info, compression='raw') reloaded = Image.open(out) self.assertEqual(0, reloaded.tag_v2[41988].numerator) self.assertEqual(0, reloaded.tag_v2[41988].denominator) def test_expty_values(self): data = io.BytesIO( b'II*\x00\x08\x00\x00\x00\x03\x00\x1a\x01\x05\x00\x00\x00\x00\x00' b'\x00\x00\x00\x00\x1b\x01\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00' b'\x98\x82\x02\x00\x07\x00\x00\x002\x00\x00\x00\x00\x00\x00\x00a ' b'text\x00\x00') head = data.read(8) info = TiffImagePlugin.ImageFileDirectory_v2(head) info.load(data) try: info = dict(info) except ValueError: self.fail("Should not be struct value error there.") self.assertIn(33432, info) def test_PhotoshopInfo(self): im = Image.open('Tests/images/issue_2278.tif') self.assertIsInstance(im.tag_v2[34377], bytes) out = self.tempfile('temp.tiff') im.save(out) reloaded = Image.open(out) self.assertIsInstance(reloaded.tag_v2[34377], bytes) def test_too_many_entries(self): ifd = TiffImagePlugin.ImageFileDirectory_v2() # 277: ("SamplesPerPixel", SHORT, 1), ifd._tagdata[277] = struct.pack('hh', 4,4) ifd.tagtype[277] = TiffTags.SHORT try: self.assert_warning(UserWarning, lambda: ifd[277]) except ValueError: self.fail("Invalid Metadata count should not cause a Value Error.") if __name__ == '__main__': unittest.main()
#ifdef __OBJC__ #import <Cocoa/Cocoa.h> #else #ifndef FOUNDATION_EXPORT #if defined(__cplusplus) #define FOUNDATION_EXPORT extern "C" #else #define FOUNDATION_EXPORT extern #endif #endif #endif FOUNDATION_EXPORT double TinaVersionNumber; FOUNDATION_EXPORT const unsigned char TinaVersionString[];
/*! * Copyright (c) 2015-2016, Okta, Inc. and/or its affiliates. All rights reserved. * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the "License.") * * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0. * 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 config from 'config/config.json'; import fetch from 'cross-fetch'; import country from 'nls/country.json'; import login from 'nls/login.json'; import Q from 'q'; import _ from 'underscore'; import BrowserFeatures from 'util/BrowserFeatures'; import Logger from 'util/Logger'; const STORAGE_KEY = 'osw.languages'; /** * Converts options to our internal format, which distinguishes between * login and country bundles. * * Example options.i18n passed in by the developer: * { * 'en': { * 'needhelp': 'need help override', * 'primaryauth.title': 'new sign in text', * 'country.JP' = 'Japan, Japan' * } * } * * Parsed: * { * 'en': { * 'login': { * 'needhelp': 'need help override', * 'primaryauth.title': 'new sign in text', * }, * 'country': { * 'JP': 'Japan, Japan' * } * } * } */ function parseOverrides (i18n) { if (!i18n) { return {}; } const i18nWithLowerCaseKeys = {}; _.each(_.keys(i18n), function (key) { i18nWithLowerCaseKeys[key.toLowerCase()] = i18n[key]; }); return _.mapObject(i18nWithLowerCaseKeys, function (props) { const mapped = { login: {}, country: {} }; if (!_.isObject(props)) { throw new Error('Invalid format for "i18n"'); } _.each(props, function (val, key) { const split = key.split(/^country\./); if (split.length > 1) { mapped.country[split[1]] = val; } else { mapped.login[split[0]] = val; } }); return mapped; }); } // Caching: We only bundle English by default in the Sign-In Widget. Other // languages are loaded on demand and cached in localStorage. These languages // are tied to the version of the widget - when it bumps, we reset the cache. function getCachedLanguages () { let storage = JSON.parse(localStorage.getItem(STORAGE_KEY)); if (!storage || storage.version !== config.version) { storage = { version: config.version, }; } return storage; } function addLanguageToCache (language, loginJson, countryJson) { const current = getCachedLanguages(); current[language] = { login: loginJson, country: countryJson, }; localStorage.setItem(STORAGE_KEY, JSON.stringify(current)); } // By default, the assets.bundleUrl is tied to the Okta CDN. // // There are two overrides available for modifying where we load the asset // bundles from: // // 1. assets.baseUrl // // This is the base path the OSW pulls assets from, which in this case is // the Okta CDN. Override this config option if you want to host the // files on your own domain, or if you're using a new version of the // widget whose language files haven't been published to the CDN yet. // // 2. assets.rewrite // // This is a function that can be used to modify the path + fileName of // the bundle we're loading, relative to the baseUrl. When called, it // will pass the current path, and expect the new path to be returned. // This is useful, for example, if your build process has an extra // cachebusting step, i.e: // // function rewrite(file) { // // file: /labels/json/login_ja.json // return file.replace('.json', '.' + md5file(file) + '.json'); // } // // Note: Most developers will not need to use these overrides - the default // is to use the Okta CDN and to use the same path + file structure the // widget module publishes by default. function fetchJson (bundle, language, assets) { let languageCode; let path; // Our bundles use _ to separate country and region, i.e: // zh-CN -> zh_CN languageCode = language.replace('-', '_'); path = assets.rewrite(encodeURI(`/labels/json/${bundle}_${languageCode}.json`)); const headers = { Accept: 'application/json', 'Content-Type': 'text/plain', }; const mode = 'no-cors'; return fetch(assets.baseUrl + path, { method: 'GET', headers, mode, }) .then(res => res.text()) .then(txt => JSON.parse(txt)); } function getBundles (language, assets) { // Two special cases: // 1. English is already bundled with the widget // 2. If the language is not in our config file, it means that they've // probably defined it on their own. if (language === 'en' || !_.contains(config.supportedLanguages, language)) { return Q({}); } //local storage does not work correctly with android web views (embeded browers) //so skip the caching and just make the request to get the local info const localStorageIsSupported = !BrowserFeatures.localStorageIsNotSupported(); if (localStorageIsSupported) { const cached = getCachedLanguages(); if (cached[language]) { return Q(cached[language]); } } return Q.all([fetchJson('login', language, assets), fetchJson('country', language, assets)]) .spread(function (loginJson, countryJson) { if (localStorageIsSupported) { addLanguageToCache(language, loginJson, countryJson); } return { login: loginJson, country: countryJson }; }) .catch(function () { // If there is an error, this will default to the bundled language and // we will no longer try to load the language this session. Logger.warn('Unable to load language: ' + language); return {}; }); } export default { login: login, country: country, // Courage components within the sign in widget point to courage bundle to look // up i18nkeys. Since we dont have courage.properties inside the sign in widget // we are pointing courage bundle to login. courage: login, currentLanguage: null, isLoaded: function (language) { return this.currentLanguage === language; }, remove: function () { this.currentLanguage = null; }, loadLanguage: function (language, overrides, assets) { const parsedOverrides = parseOverrides(overrides); const lowerCaseLanguage = language.toLowerCase(); return getBundles(language, assets).then(bundles => { // Always extend from the built in defaults in the event that some // properties are not translated this.login = _.extend({}, login, bundles.login); this.country = _.extend({}, country, bundles.country); this.courage = _.extend({}, login, bundles.login); if (parsedOverrides[lowerCaseLanguage]) { _.extend(this.login, parsedOverrides[lowerCaseLanguage]['login']); _.extend(this.country, parsedOverrides[lowerCaseLanguage]['country']); _.extend(this.courage, parsedOverrides[lowerCaseLanguage]['login']); } this.currentLanguage = language; }); }, };
import { useEffect, useRef } from "react"; import * as Notifications from "expo-notifications"; import expoPushTokensApi from "../api/expoPushTokens"; import { Platform } from "react-native"; import logger from "../utility/logger"; const useNotifications = (notificationListenerFn, responseListenerFn) => { const notificationListener = useRef(); const responseListener = useRef(); useEffect(() => { registerForPushNotifications(); // This listener is fired whenever a notification is received while the app is foregrounded if (notificationListenerFn) notificationListener.current = Notifications.addNotificationReceivedListener(notificationListenerFn); // This listener is fired whenever a user taps on or interacts with a notification (works when app is foregrounded, backgrounded, or killed) if (responseListenerFn) responseListener.current = Notifications.addNotificationResponseReceivedListener( responseListenerFn ); return () => { if (notificationListenerFn) Notifications.removeNotificationSubscription( notificationListener.current ); if (responseListenerFn) Notifications.removeNotificationSubscription(responseListener.current); }; }, []); const registerForPushNotifications = async () => { try { const permission = await Notifications.getPermissionsAsync(); if (!permission.granted) { return; } const token = (await Notifications.getExpoPushTokenAsync()).data; expoPushTokensApi.register(token); if (Platform.OS === "android") { Notifications.setNotificationChannelAsync("default", { name: "default", importance: Notifications.AndroidImportance.MAX, vibrationPattern: [0, 250, 250, 250], lightColor: "#FF231F7C", }); } } catch (error) { console.log("error getting push token"); logger.log(error); } }; }; export default useNotifications;
import { Component, Input, Output, EventEmitter, ChangeDetectionStrategy } from '@angular/core'; var TreeMapCellSeriesComponent = (function () { function TreeMapCellSeriesComponent() { this.tooltipDisabled = false; this.gradient = false; this.select = new EventEmitter(); } TreeMapCellSeriesComponent.prototype.ngOnChanges = function (changes) { this.cells = this.getCells(); }; TreeMapCellSeriesComponent.prototype.getCells = function () { var _this = this; return this.data.children .filter(function (d) { return d.depth === 1; }) .map(function (d, index) { var label = d.id; return { x: d.x0, y: d.y0, width: d.x1 - d.x0, height: d.y1 - d.y0, fill: _this.colors.getColor(label), label: label, value: d.value, valueType: d.valueType }; }); }; TreeMapCellSeriesComponent.prototype.getTooltipText = function (_a) { var label = _a.label, value = _a.value; return "\n <span class=\"tooltip-label\">" + label + "</span>\n <span class=\"tooltip-val\">" + value.toLocaleString() + "</span>\n "; }; TreeMapCellSeriesComponent.prototype.onClick = function (data) { this.select.emit(data); }; TreeMapCellSeriesComponent.prototype.trackBy = function (index, item) { return item.label; }; return TreeMapCellSeriesComponent; }()); export { TreeMapCellSeriesComponent }; TreeMapCellSeriesComponent.decorators = [ { type: Component, args: [{ selector: 'g[ngx-charts-tree-map-cell-series]', template: "\n <svg:g ngx-charts-tree-map-cell *ngFor=\"let c of cells; trackBy:trackBy\"\n [data]=\"c\"\n [x]=\"c.x\"\n [y]=\"c.y\"\n [width]=\"c.width\"\n [height]=\"c.height\"\n [fill]=\"c.fill\"\n [label]=\"c.label\"\n [value]=\"c.value\"\n [valueType]=\"c.valueType\"\n [valueFormatting]=\"valueFormatting\"\n [labelFormatting]=\"labelFormatting\"\n [gradient]=\"gradient\"\n (select)=\"onClick($event)\"\n ngx-tooltip\n [tooltipDisabled]=\"tooltipDisabled\"\n [tooltipPlacement]=\"'top'\"\n [tooltipType]=\"'tooltip'\"\n [tooltipTitle]=\"getTooltipText(c)\"\n />\n ", changeDetection: ChangeDetectionStrategy.OnPush },] }, ]; /** @nocollapse */ TreeMapCellSeriesComponent.ctorParameters = function () { return []; }; TreeMapCellSeriesComponent.propDecorators = { 'data': [{ type: Input },], 'dims': [{ type: Input },], 'colors': [{ type: Input },], 'tooltipDisabled': [{ type: Input },], 'valueFormatting': [{ type: Input },], 'labelFormatting': [{ type: Input },], 'gradient': [{ type: Input },], 'select': [{ type: Output },], }; //# sourceMappingURL=tree-map-cell-series.component.js.map
#!/usr/bin/env python # -*- coding: utf-8 -*- # ------ bug of rasterio -------- import os if "GDAL_DATA" in list(os.environ.keys()): del os.environ["GDAL_DATA"] if "PROJ_LIB" in list(os.environ.keys()): del os.environ["PROJ_LIB"] # ------ bug of rasterio -------- import json import urllib.request import urllib.parse import logging from pathlib import Path from datetime import datetime from multiprocessing import cpu_count import rasterio import geopandas as gpd from shapely.wkt import loads from ost.helpers import vector as vec, raster as ras from ost.helpers import scihub, helpers as h, srtm from ost.helpers.settings import set_log_level, setup_logfile, OST_ROOT from ost.helpers.settings import check_ard_parameters from ost.s1 import search, refine_inventory, download from ost.s1 import burst_inventory, burst_batch from ost.s1 import grd_batch # get the logger logger = logging.getLogger(__name__) # global variables OST_DATEFORMAT = "%Y-%m-%d" OST_INVENTORY_FILE = 'full.inventory.gpkg' class Generic: def __init__( self, project_dir, aoi, start='1978-06-28', end=datetime.today().strftime(OST_DATEFORMAT), data_mount=None, log_level=logging.INFO ): # ------------------------------------------ # 1 Start logger # set log level to logging.INFO as standard set_log_level(log_level) # ------------------------------------------ # 2 Handle directories # get absolute path to project directory self.project_dir = Path(project_dir).resolve() # create project directory if not existent try: self.project_dir.mkdir(parents=True, exist_ok=True) logger.info(f'Created project directory at {self.project_dir}') except FileExistsError: logger.info('Project directory already exists. ' 'No data has been deleted at this point but ' 'make sure you really want to use this folder.') # define project sub-directories if not set, and create folders self.download_dir = self.project_dir.joinpath('download') self.download_dir.mkdir(parents=True, exist_ok=True) logger.info( f'Downloaded data will be stored in: {self.download_dir}.' ) self.inventory_dir = self.project_dir.joinpath('inventory') self.inventory_dir.mkdir(parents=True, exist_ok=True) logger.info( f'Inventory files will be stored in: {self.inventory_dir}.' ) self.processing_dir = self.project_dir.joinpath('processing') self.processing_dir.mkdir(parents=True, exist_ok=True) logger.info( f'Processed data will be stored in: {self.processing_dir}.' ) self.temp_dir = self.project_dir.joinpath('temp') self.temp_dir.mkdir(parents=True, exist_ok=True) logger.info( f'Using {self.temp_dir} as directory for temporary files.' ) # ------------------------------------------ # 3 create a standard logfile setup_logfile(self.project_dir.joinpath('.processing.log')) # ------------------------------------------ # 4 handle AOI (read and get back WKT) self.aoi = vec.aoi_to_wkt(aoi) # ------------------------------------------ # 5 Handle Period of Interest try: datetime.strptime(start, OST_DATEFORMAT) self.start = start except ValueError: raise ValueError("Incorrect date format for start date. " "It should be YYYY-MM-DD") try: datetime.strptime(end, OST_DATEFORMAT) self.end = end except ValueError: raise ValueError("Incorrect date format for end date. " "It should be YYYY-MM-DD") # ------------------------------------------ # 6 Check data mount if data_mount: if Path(data_mount).exists(): self.data_mount = Path(data_mount) else: raise NotADirectoryError(f'{data_mount} is not a directory.') else: self.data_mount = None # ------------------------------------------ # 7 put all parameters in a dictionary self.config_dict = { 'project_dir': str(self.project_dir), 'download_dir': str(self.download_dir), 'inventory_dir': str(self.inventory_dir), 'processing_dir': str(self.processing_dir), 'temp_dir': str(self.temp_dir), 'data_mount': str(self.data_mount), 'aoi': self.aoi, 'start_date': self.start, 'end_date': self.end } class Sentinel1(Generic): """ A Sentinel-1 specific subclass of the Generic OST class This subclass creates a Sentinel-1 specific """ def __init__( self, project_dir, aoi, start='2014-10-01', end=datetime.today().strftime(OST_DATEFORMAT), data_mount=None, product_type='*', beam_mode='*', polarisation='*', log_level=logging.INFO ): # ------------------------------------------ # 1 Get Generic class attributes super().__init__(project_dir, aoi, start, end, data_mount, log_level) # ------------------------------------------ # 2 Check and set product type if product_type in ['*', 'RAW', 'SLC', 'GRD']: self.product_type = product_type else: raise ValueError( "Product type must be one out of '*', 'RAW', 'SLC', 'GRD'" ) # ------------------------------------------ # 3 Check and set beam mode if beam_mode in ['*', 'IW', 'EW', 'SM']: self.beam_mode = beam_mode else: raise ValueError("Beam mode must be one out of 'IW', 'EW', 'SM'") # ------------------------------------------ # 4 Check and set polarisations possible_pols = ['*', 'VV', 'VH', 'HV', 'HH', 'VV VH', 'HH HV'] if polarisation in possible_pols: self.polarisation = polarisation else: raise ValueError( f"Polarisation must be one out of {possible_pols}" ) # ------------------------------------------ # 5 Initialize the inventory file inventory_file = self.inventory_dir.joinpath(OST_INVENTORY_FILE) if inventory_file.exists(): self.inventory_file = inventory_file logging.info( 'Found an existing inventory file. This can be overwritten ' 'by re-executing the search.' ) self.read_inventory() else: self.inventory = None self.inventory_file = None # ------------------------------------------ # 6 Initialize refinements self.refined_inventory_dict = None self.coverages = None # ------------------------------------------ # 7 Initialize burst inventories self.burst_inventory = None self.burst_inventory_file = None # ------------------------------------------ # 7 Initialize uname and pword to None self.scihub_uname = None self.scihub_pword = None self.asf_uname = None self.asf_pword = None self.peps_uname = None self.peps_pword = None self.onda_uname = None self.onda_pword = None # ------------------------------------------ # methods def search(self, outfile=OST_INVENTORY_FILE, append=False, base_url='https://apihub.copernicus.eu/apihub'): """High Level search function :param outfile: :param append: :param base_url: :return: """ # create scihub conform aoi string aoi = scihub.create_aoi_str(self.aoi) # create scihub conform TOI toi = scihub.create_toi_str(self.start, self.end) # create scihub conform product specification product_specs = scihub.create_s1_product_specs( self.product_type, self.polarisation, self.beam_mode ) # construct the final query query = urllib.parse.quote( f'Sentinel-1 AND {product_specs} AND {aoi} AND {toi}' ) if not self.scihub_uname or not self.scihub_pword: # ask for username and password self.scihub_uname, self.scihub_pword = scihub.ask_credentials() # do the search if outfile == OST_INVENTORY_FILE: self.inventory_file = self.inventory_dir.joinpath( OST_INVENTORY_FILE ) else: self.inventory_file = outfile search.scihub_catalogue( query, self.inventory_file, append, self.scihub_uname, self.scihub_pword, base_url ) if self.inventory_file.exists(): # read inventory into the inventory attribute self.read_inventory() else: logger.info('No images found in the AOI for this date range') def read_inventory(self): """Read the Sentinel-1 data inventory from a OST invetory shapefile :param """ # define column names of inventory file (since in shp they are # truncated) column_names = ['id', 'identifier', 'polarisationmode', 'orbitdirection', 'acquisitiondate', 'relativeorbit', 'orbitnumber', 'product_type', 'slicenumber', 'size', 'beginposition', 'endposition', 'lastrelativeorbitnumber', 'lastorbitnumber', 'uuid', 'platformidentifier', 'missiondatatakeid', 'swathidentifier', 'ingestiondate', 'sensoroperationalmode', 'geometry'] geodataframe = gpd.read_file(self.inventory_file) geodataframe.columns = column_names # add download_path to inventory, so we can check if data needs to be # downloaded self.inventory = search.check_availability( geodataframe, self.download_dir, self.data_mount ) def download_size(self, inventory_df=None): """Function to get the total size of all products when extracted in GB :param inventory_df: :return: """ if inventory_df is None: download_size = self.inventory[ 'size'].str.replace(' GB', '').astype('float32').sum() else: download_size = inventory_df[ 'size'].str.replace(' GB', '').astype('float32').sum() logger.info( f'There are about {download_size} GB need to be downloaded.' ) def refine_inventory(self, exclude_marginal=True, full_aoi_crossing=True, mosaic_refine=True, area_reduce=0.05, complete_coverage=True): self.refined_inventory_dict, self.coverages = ( refine_inventory.search_refinement( self.aoi, self.inventory, self.inventory_dir, exclude_marginal=exclude_marginal, full_aoi_crossing=full_aoi_crossing, mosaic_refine=mosaic_refine, area_reduce=area_reduce, complete_coverage=complete_coverage ) ) # summing up information print('--------------------------------------------') print(' Summing up the info about mosaics') print('--------------------------------------------') for key in self.refined_inventory_dict: print('') print(f' {self.coverages[key]} mosaics for mosaic key {key}') def download(self, inventory_df, mirror=None, concurrent=2, uname=None, pword=None): # if an old inventory exists drop download_path if 'download_path' in inventory_df: inventory_df.drop('download_path', axis=1) # check if scenes exist inventory_df = search.check_availability( inventory_df, self.download_dir, self.data_mount) # extract only those scenes that need to be downloaded download_df = inventory_df[inventory_df.download_path == 'None'] # to download or not ot download - that is here the question if download_df.empty: logger.info('All scenes are ready for being processed.') else: logger.info('One or more scene(s) need(s) to be downloaded.') download.download_sentinel1( download_df, self.download_dir, mirror=mirror, concurrent=concurrent, uname=uname, pword=pword ) def create_burst_inventory( self, inventory_df=None, refine=True, outfile=None, uname=None, pword=None ): # assert SLC product type if not self.product_type == 'SLC': raise ValueError( 'Burst inventory is only possible for the SLC product type' ) # in case a custom inventory is given (e.g. a refined inventory) if inventory_df is None: inventory_df = self.inventory else: # assert that all products are SLCs if not inventory_df.product_type.unique() == 'SLC': raise ValueError( 'The inventory dataframe can only contain SLC products ' 'for the burst inventory ' ) if not outfile: outfile = self.inventory_dir.joinpath('burst_inventory.gpkg') # run the burst inventory self.burst_inventory = burst_inventory.burst_inventory( inventory_df, outfile, download_dir=self.download_dir, data_mount=self.data_mount, uname=uname, pword=pword ) # refine the burst inventory if refine: self.burst_inventory = burst_inventory.refine_burst_inventory( self.aoi, self.burst_inventory, f'{str(outfile)[:-5]}.refined.gpkg' ) def read_burst_inventory(self, burst_file=None): """ :param burst_file: a GeoPackage file created by OST holding a burst inventory :return: geodataframe """ if not burst_file: non_ref = self.inventory_dir.joinpath('burst_inventory.gpkg') refined = self.inventory_dir.joinpath( 'burst_inventory.refined.gpkg' ) if refined.exists(): logger.info( f'Importing refined burst inventory file {str(refined)}.') burst_file = refined elif non_ref.exists(): logger.info( f'Importing refined burst inventory file {str(non_ref)}.') burst_file = non_ref else: raise FileNotFoundError( 'No previously created burst inventory file ' 'has been found.' ) # define column names of file (since in shp they are truncated) # create column names for empty data frame column_names = ['SceneID', 'Track', 'Direction', 'Date', 'SwathID', 'AnxTime', 'BurstNr', 'geometry'] geodataframe = gpd.read_file(burst_file) geodataframe = geodataframe[column_names] self.burst_inventory = geodataframe return geodataframe def plot_inventory(self, inventory_df=None, transparency=0.05, annotate=False): if inventory_df is None: vec.plot_inventory( self.aoi, self.inventory, transparency, annotate ) else: vec.plot_inventory(self.aoi, inventory_df, transparency, annotate) class Sentinel1Batch(Sentinel1): """ A Sentinel-1 specific subclass of the Generic OST class This subclass creates a Sentinel-1 specific """ def __init__( self, project_dir, aoi, start='2014-10-01', end=datetime.today().strftime(OST_DATEFORMAT), data_mount=None, product_type='SLC', beam_mode='IW', polarisation='*', ard_type='OST-GTC', snap_cpu_parallelism=cpu_count(), max_workers=1, log_level=logging.INFO ): # ------------------------------------------ # 1 Initialize super class super().__init__( project_dir, aoi, start, end, data_mount, product_type, beam_mode, polarisation, log_level ) # --------------------------------------- # 1 Check and set ARD type # possible ard types to select from for GRD if product_type == 'GRD': ard_types_grd = ['CEOS', 'Earth-Engine', 'OST-GTC', 'OST-RTC'] if ard_type in ard_types_grd: self.ard_type = ard_type else: raise ValueError('No valid ARD type for product type GRD.' f'Select from {ard_types_grd}') # possible ard types to select from for GRD elif product_type == 'SLC': ard_types_slc = ['OST-GTC', 'OST-RTC', 'OST-COH', 'OST-RTCCOH', 'OST-POL', 'OST-ALL'] if ard_type in ard_types_slc: self.ard_type = ard_type else: raise ValueError('No valid ARD type for product type GRD.' f'Select from {ard_types_slc}') # otherwise the product type is not supported else: raise ValueError(f'Product type {self.product_type} not ' f'supported for processing. Only GRD and SLC ' f'are supported.') # --------------------------------------- # 2 Check beam mode if not beam_mode == 'IW': raise ValueError("Only 'IW' beam mode supported for processing.") # --------------------------------------- # 3 Add snap_cpu_parallelism self.config_dict['snap_cpu_parallelism'] = snap_cpu_parallelism self.config_dict['max_workers'] = max_workers self.config_dict['executor_type'] = 'billiard' # --------------------------------------- # 4 Set up project JSON self.config_file = self.project_dir.joinpath('config.json') self.ard_parameters = self.get_ard_parameters(ard_type) # re-create config dict with update ard parameters self.config_dict.update( processing=self.ard_parameters ) # --------------------------------------- # methods def get_ard_parameters(self, ard_type): # find respective template for selected ARD type template_file = OST_ROOT.joinpath( f"graphs/ard_json/{self.product_type.lower()}" f".{ard_type.replace('-', '_').lower()}.json" ) # open and load parameters with open(template_file, 'r') as ard_file: self.ard_parameters = json.load(ard_file)['processing'] # returning ard_parameters return self.ard_parameters def update_ard_parameters(self, ard_type=None): # if a ard type is selected, load if ard_type: self.get_ard_parameters(ard_type) # check for correctness of ard parameters check_ard_parameters(self.ard_parameters) # re-create project dict with update ard parameters self.config_dict.update( processing=self.ard_parameters ) # dump to json file with open(self.config_file, 'w') as outfile: json.dump(self.config_dict, outfile, indent=4) def set_external_dem(self, dem_file, ellipsoid_correction=True): # check if file exists if not Path(dem_file).exists(): raise FileNotFoundError(f'No file found at {dem_file}.') # get no data value with rasterio.open(dem_file) as file: dem_nodata = int(file.nodata) # get resampling adn projection‚ img_res = self.ard_parameters['single_ARD']['dem']['image_resampling'] dem_res = self.ard_parameters['single_ARD']['dem']['dem_resampling'] projection = self.ard_parameters['single_ARD']['dem']['out_projection'] # update ard parameters dem_dict = dict({'dem_name': 'External DEM', 'dem_file': dem_file, 'dem_nodata': dem_nodata, 'dem_resampling': dem_res, 'image_resampling': img_res, 'egm_correction': ellipsoid_correction, 'out_projection': projection }) # update ard_parameters self.ard_parameters['single_ARD']['dem'] = dem_dict def pre_download_srtm(self): logger.info('Pre-downloading SRTM tiles') srtm.download_srtm(self.aoi) def bursts_to_ards( self, timeseries=False, timescan=False, mosaic=False, overwrite=False ): """Batch processing function for full burst pre-processing workflow This function allows for the generation of the :param timeseries: if True, Time-series will be generated for each burst id :type timeseries: bool, optional :param timescan: if True, Timescans will be generated for each burst id type: timescan: bool, optional :param mosaic: if True, Mosaics will be generated from the Time-Series/Timescans of each burst id :type mosaic: bool, optional :param overwrite: (if True, the processing folder will be emptied :type overwrite: bool, optional :param max_workers: number of parallel burst :type max_workers: int, default=1 processing jobs :return: """ # -------------------------------------------- # 2 Check if within SRTM coverage # set ellipsoid correction and force GTC production # when outside SRTM center_lat = loads(self.aoi).centroid.y if float(center_lat) > 59 or float(center_lat) < -59: if 'SRTM' in self.ard_parameters['single_ARD']['dem']['dem_name']: logger.info( 'Scene is outside SRTM coverage. Snap will therefore use ' 'the Copernicus 30m Global DEM. ' ) self.ard_parameters['single_ARD']['dem'][ 'dem_name'] = 'Copernicus 30m Global DEM' if self.ard_parameters['single_ARD']['dem'][ 'out_projection' ] == 4326: logger.info( 'The scene\'s location is towards the poles. ' 'Consider to use a stereographic projection.' ) epsg = input( 'Type an alternative EPSG code for the projection of the ' 'output data or just press enter for keeping Lat/Lon ' 'coordinate system (e.g. 3413 for NSIDC Sea Ice Polar ' 'Stereographic North projection, or 3976 for ' 'NSIDC Sea Ice Polar Stereographic South projection' ) if not epsg: epsg = 4326 self.ard_parameters['single_ARD']['dem'][ 'out_projection'] = int(epsg) # -------------------------------------------- # 3 subset determination # we need a check function that checks self.config_dict['subset'] = False # This does not work at the moment, and maybe does not even make sense, # since for the co-registration we would need a sufficient # part of the image # self.config_dict['subset'] = vec.set_subset( # self.aoi, self.burst_inventory # ) # -------------------------------------------- # 4 Check ard parameters in case they have been updated, # and write them to json file self.update_ard_parameters() # -------------------------------------------- # 1 delete data from previous runnings # delete data in temporary directory in case there is # something left from previous runs h.remove_folder_content(self.config_dict['temp_dir']) # in case we strat from scratch, delete all data # within processing folder if overwrite: logger.info('Deleting processing folder to start from scratch') h.remove_folder_content(self.config_dict['processing_dir']) # -------------------------------------------- # 5 set resolution to degree # self.ard_parameters['resolution'] = h.resolution_in_degree( # self.center_lat, self.ard_parameters['resolution']) #if self.config_dict['max_workers'] > 1 and self.ard_parameters['single_ARD']['dem']['dem_name'] == 'SRTM 1Sec HGT': # self.pre_download_srtm() # -------------------------------------------- # 6 run the burst to ard batch routine (up to 3 times if needed) i = 1 while i < 4: processed_bursts_df = burst_batch.bursts_to_ards( self.burst_inventory, self.config_file ) if False in processed_bursts_df.error.isnull().tolist(): i += 1 else: i = 5 # write processed df to file processing_dir = Path(self.config_dict['processing_dir']) processed_bursts_df.to_pickle( processing_dir.joinpath('processed_bursts.pickle') ) # if not all have been processed, raise an error to avoid # false time-series processing if i == 4: raise RuntimeError( 'Not all all bursts have been successfully processed' ) # -------------------------------------------- # 6 run the timeseries creation if timeseries or timescan: tseries_df = burst_batch.ards_to_timeseries( self.burst_inventory, self.config_file ) # -------------------------------------------- # 7 run the timescan creation if timescan: burst_batch.timeseries_to_timescan( self.burst_inventory, self.config_file ) # -------------------------------------------- # 8 mosaic the time-series if mosaic and timeseries: burst_batch.mosaic_timeseries( self.burst_inventory, self.config_file ) # -------------------------------------------- # 9 mosaic the timescans if mosaic and timescan: burst_batch.mosaic_timescan( self.burst_inventory, self.config_file ) # return tseries_df @staticmethod def create_timeseries_animation( timeseries_dir, product_list, outfile, shrink_factor=1, resampling_factor=5, duration=1, add_dates=False, prefix=False ): ras.create_timeseries_animation(timeseries_dir, product_list, outfile, shrink_factor=shrink_factor, duration=duration, resampling_factor=resampling_factor, add_dates=add_dates, prefix=prefix) def grds_to_ards( self, inventory_df, timeseries=False, timescan=False, mosaic=False, overwrite=False, max_workers=1, executor_type='billiard' ): self.config_dict['max_workers'] = max_workers self.config_dict['executor_type'] = executor_type # in case we start from scratch, delete all data # within processing folder if overwrite: logger.info('Deleting processing folder to start from scratch') h.remove_folder_content(self.processing_dir) # -------------------------------------------- # 2 Check if within SRTM coverage # set ellipsoid correction and force GTC production # when outside SRTM center_lat = loads(self.aoi).centroid.y if float(center_lat) > 59 or float(center_lat) < -59: if 'SRTM' in self.ard_parameters['single_ARD']['dem']['dem_name']: logger.info( 'Scene is outside SRTM coverage. Snap will therefore use ' 'the Copernicus 30m Global DEM. ' ) self.ard_parameters['single_ARD']['dem'][ 'dem_name'] = 'Copernicus 30m Global DEM' if self.ard_parameters['single_ARD']['dem'][ 'out_projection' ] == 4326: logger.info( 'The scene\'s location is towards the poles. ' 'Consider to use a stereographic projection.' ) epsg = input( 'Type an alternative EPSG code for the projection of the ' 'output data or just press enter for keeping Lat/Lon ' 'coordinate system (e.g. 3413 for NSIDC Sea Ice Polar ' 'Stereographic North projection, or 3976 for ' 'NSIDC Sea Ice Polar Stereographic South projection' ) if not epsg: epsg = 4326 self.ard_parameters['single_ARD']['dem'][ 'out_projection'] = int(epsg) # -------------------------------------------- # 3 subset determination # we need a check function that checks self.config_dict.update( subset=vec.set_subset(self.aoi, inventory_df) ) # dump to json file with open(self.config_file, 'w') as outfile: json.dump(self.config_dict, outfile, indent=4) # -------------------------------------------- # 4 Check ard parameters in case they have been updated, # and write them to json file self.update_ard_parameters() # -------------------------------------------- # 1 delete data in case of previous runs # delete data in temporary directory in case there is # something left from aborted previous runs h.remove_folder_content(self.config_dict['temp_dir']) # -------------------------------------------- # 5 set resolution in degree # self.center_lat = loads(self.aoi).centroid.y # if float(self.center_lat) > 59 or float(self.center_lat) < -59: # logger.info( # 'Scene is outside SRTM coverage. Will use 30m # # 'ASTER DEM instead.' # ) # self.ard_parameters['dem'] = 'ASTER 1sec GDEM' # -------------------------------------------- # 5 set resolution in degree # the grd to ard batch routine processing_df = grd_batch.grd_to_ard_batch( inventory_df, self.config_file ) # time-series part if timeseries or timescan: grd_batch.ards_to_timeseries(inventory_df, self.config_file) if timescan: grd_batch.timeseries_to_timescan(inventory_df, self.config_file) if mosaic and timeseries: grd_batch.mosaic_timeseries(inventory_df, self.config_file) # -------------------------------------------- # 9 mosaic the timescans if mosaic and timescan: grd_batch.mosaic_timescan(self.config_file) return processing_df
const layout = require('../layout'); module.exports = ({ products }) => { const renderedProducts = products .map(product => { return ` <div class="column is-one-quarter"> <div class="card product-card"> <figure> <img src="data:image/png;base64, ${product.image}"/> </figure> <div class="card-content"> <h3 class="subtitle">${product.title}</h3> <h5>$${product.price}</h5> </div> <footer class="card-footer"> <form action="/cart/products" method="POST"> <input hidden value="${product.id}" name="productId"/> <button class="button has-icon is-inverted"> <i class="fa fa-shopping-cart"></i> Add to cart </button> </form> </footer> </div> </div> `; }) .join('\n'); return layout({ content: ` <section class="banner"> <div class="container"> <div class="columns is-centered"> <img src="/images/banner.jpg" /> </div> </div> </section> <section> <div class="container"> <div class="columns"> <div class="column "></div> <div class="column is-four-fifths"> <div> <h2 class="title text-center">Featured Items</h2> <div class="columns products"> ${renderedProducts} </div> </div> </div> <div class="column "></div> </div> </div> </section> ` }); };
import { readFileSync as fsReadFileSync, writeFileSync as fsWriteFileSync } from 'fs' import { dirname } from 'path' import mkdirp from 'mkdirp' import crypto from 'crypto' export function readFileSync (file) { return fsReadFileSync(file, 'utf8') } export function writeFileSync (file, content) { mkdirp.sync(dirname(file)) fsWriteFileSync(file, content, 'utf8') } export function copyFileSync (src, dest) { mkdirp.sync(dirname(dest)) writeFileSync(dest, readFileSync(src)) } const RE_EXT = /\.([^.]+)$/ export function replaceExtSync (file, ext) { return file.replace(RE_EXT, `.${ext}`) } export function hash (path) { let hash = crypto.createHash('sha1') hash.update(path) return hash.digest('hex').substring(0, 7) } export function upperFirst (str) { if (str.length === 0) { return str } return str[0].toUpperCase() + str.slice(1) }
// SPDX-License-Identifier: GPL-2.0 /* * linux/arch/parisc/mm/init.c * * Copyright (C) 1995 Linus Torvalds * Copyright 1999 SuSE GmbH * changed by Philipp Rumpf * Copyright 1999 Philipp Rumpf (prumpf@tux.org) * Copyright 2004 Randolph Chung (tausq@debian.org) * Copyright 2006-2007 Helge Deller (deller@gmx.de) * */ #include <linux/module.h> #include <linux/mm.h> #include <linux/memblock.h> #include <linux/gfp.h> #include <linux/delay.h> #include <linux/init.h> #include <linux/initrd.h> #include <linux/swap.h> #include <linux/unistd.h> #include <linux/nodemask.h> /* for node_online_map */ #include <linux/pagemap.h> /* for release_pages */ #include <linux/compat.h> #include <asm/pgalloc.h> #include <asm/tlb.h> #include <asm/pdc_chassis.h> #include <asm/mmzone.h> #include <asm/sections.h> #include <asm/msgbuf.h> #include <asm/sparsemem.h> extern int data_start; extern void parisc_kernel_start(void); /* Kernel entry point in head.S */ #if CONFIG_PGTABLE_LEVELS == 3 pmd_t pmd0[PTRS_PER_PMD] __section(".data..vm0.pmd") __attribute__ ((aligned(PAGE_SIZE))); #endif pgd_t swapper_pg_dir[PTRS_PER_PGD] __section(".data..vm0.pgd") __attribute__ ((aligned(PAGE_SIZE))); pte_t pg0[PT_INITIAL * PTRS_PER_PTE] __section(".data..vm0.pte") __attribute__ ((aligned(PAGE_SIZE))); static struct resource data_resource = { .name = "Kernel data", .flags = IORESOURCE_BUSY | IORESOURCE_SYSTEM_RAM, }; static struct resource code_resource = { .name = "Kernel code", .flags = IORESOURCE_BUSY | IORESOURCE_SYSTEM_RAM, }; static struct resource pdcdata_resource = { .name = "PDC data (Page Zero)", .start = 0, .end = 0x9ff, .flags = IORESOURCE_BUSY | IORESOURCE_MEM, }; static struct resource sysram_resources[MAX_PHYSMEM_RANGES] __ro_after_init; /* The following array is initialized from the firmware specific * information retrieved in kernel/inventory.c. */ physmem_range_t pmem_ranges[MAX_PHYSMEM_RANGES] __initdata; int npmem_ranges __initdata; #ifdef CONFIG_64BIT #define MAX_MEM (1UL << MAX_PHYSMEM_BITS) #else /* !CONFIG_64BIT */ #define MAX_MEM (3584U*1024U*1024U) #endif /* !CONFIG_64BIT */ static unsigned long mem_limit __read_mostly = MAX_MEM; static void __init mem_limit_func(void) { char *cp, *end; unsigned long limit; /* We need this before __setup() functions are called */ limit = MAX_MEM; for (cp = boot_command_line; *cp; ) { if (memcmp(cp, "mem=", 4) == 0) { cp += 4; limit = memparse(cp, &end); if (end != cp) break; cp = end; } else { while (*cp != ' ' && *cp) ++cp; while (*cp == ' ') ++cp; } } if (limit < mem_limit) mem_limit = limit; } #define MAX_GAP (0x40000000UL >> PAGE_SHIFT) static void __init setup_bootmem(void) { unsigned long mem_max; #ifndef CONFIG_SPARSEMEM physmem_range_t pmem_holes[MAX_PHYSMEM_RANGES - 1]; int npmem_holes; #endif int i, sysram_resource_count; disable_sr_hashing(); /* Turn off space register hashing */ /* * Sort the ranges. Since the number of ranges is typically * small, and performance is not an issue here, just do * a simple insertion sort. */ for (i = 1; i < npmem_ranges; i++) { int j; for (j = i; j > 0; j--) { physmem_range_t tmp; if (pmem_ranges[j-1].start_pfn < pmem_ranges[j].start_pfn) { break; } tmp = pmem_ranges[j-1]; pmem_ranges[j-1] = pmem_ranges[j]; pmem_ranges[j] = tmp; } } #ifndef CONFIG_SPARSEMEM /* * Throw out ranges that are too far apart (controlled by * MAX_GAP). */ for (i = 1; i < npmem_ranges; i++) { if (pmem_ranges[i].start_pfn - (pmem_ranges[i-1].start_pfn + pmem_ranges[i-1].pages) > MAX_GAP) { npmem_ranges = i; printk("Large gap in memory detected (%ld pages). " "Consider turning on CONFIG_SPARSEMEM\n", pmem_ranges[i].start_pfn - (pmem_ranges[i-1].start_pfn + pmem_ranges[i-1].pages)); break; } } #endif /* Print the memory ranges */ pr_info("Memory Ranges:\n"); for (i = 0; i < npmem_ranges; i++) { struct resource *res = &sysram_resources[i]; unsigned long start; unsigned long size; size = (pmem_ranges[i].pages << PAGE_SHIFT); start = (pmem_ranges[i].start_pfn << PAGE_SHIFT); pr_info("%2d) Start 0x%016lx End 0x%016lx Size %6ld MB\n", i, start, start + (size - 1), size >> 20); /* request memory resource */ res->name = "System RAM"; res->start = start; res->end = start + size - 1; res->flags = IORESOURCE_SYSTEM_RAM | IORESOURCE_BUSY; request_resource(&iomem_resource, res); } sysram_resource_count = npmem_ranges; /* * For 32 bit kernels we limit the amount of memory we can * support, in order to preserve enough kernel address space * for other purposes. For 64 bit kernels we don't normally * limit the memory, but this mechanism can be used to * artificially limit the amount of memory (and it is written * to work with multiple memory ranges). */ mem_limit_func(); /* check for "mem=" argument */ mem_max = 0; for (i = 0; i < npmem_ranges; i++) { unsigned long rsize; rsize = pmem_ranges[i].pages << PAGE_SHIFT; if ((mem_max + rsize) > mem_limit) { printk(KERN_WARNING "Memory truncated to %ld MB\n", mem_limit >> 20); if (mem_max == mem_limit) npmem_ranges = i; else { pmem_ranges[i].pages = (mem_limit >> PAGE_SHIFT) - (mem_max >> PAGE_SHIFT); npmem_ranges = i + 1; mem_max = mem_limit; } break; } mem_max += rsize; } printk(KERN_INFO "Total Memory: %ld MB\n",mem_max >> 20); #ifndef CONFIG_SPARSEMEM /* Merge the ranges, keeping track of the holes */ { unsigned long end_pfn; unsigned long hole_pages; npmem_holes = 0; end_pfn = pmem_ranges[0].start_pfn + pmem_ranges[0].pages; for (i = 1; i < npmem_ranges; i++) { hole_pages = pmem_ranges[i].start_pfn - end_pfn; if (hole_pages) { pmem_holes[npmem_holes].start_pfn = end_pfn; pmem_holes[npmem_holes++].pages = hole_pages; end_pfn += hole_pages; } end_pfn += pmem_ranges[i].pages; } pmem_ranges[0].pages = end_pfn - pmem_ranges[0].start_pfn; npmem_ranges = 1; } #endif /* * Initialize and free the full range of memory in each range. */ max_pfn = 0; for (i = 0; i < npmem_ranges; i++) { unsigned long start_pfn; unsigned long npages; unsigned long start; unsigned long size; start_pfn = pmem_ranges[i].start_pfn; npages = pmem_ranges[i].pages; start = start_pfn << PAGE_SHIFT; size = npages << PAGE_SHIFT; /* add system RAM memblock */ memblock_add(start, size); if ((start_pfn + npages) > max_pfn) max_pfn = start_pfn + npages; } /* * We can't use memblock top-down allocations because we only * created the initial mapping up to KERNEL_INITIAL_SIZE in * the assembly bootup code. */ memblock_set_bottom_up(true); /* IOMMU is always used to access "high mem" on those boxes * that can support enough mem that a PCI device couldn't * directly DMA to any physical addresses. * ISA DMA support will need to revisit this. */ max_low_pfn = max_pfn; /* reserve PAGE0 pdc memory, kernel text/data/bss & bootmap */ #define PDC_CONSOLE_IO_IODC_SIZE 32768 memblock_reserve(0UL, (unsigned long)(PAGE0->mem_free + PDC_CONSOLE_IO_IODC_SIZE)); memblock_reserve(__pa(KERNEL_BINARY_TEXT_START), (unsigned long)(_end - KERNEL_BINARY_TEXT_START)); #ifndef CONFIG_SPARSEMEM /* reserve the holes */ for (i = 0; i < npmem_holes; i++) { memblock_reserve((pmem_holes[i].start_pfn << PAGE_SHIFT), (pmem_holes[i].pages << PAGE_SHIFT)); } #endif #ifdef CONFIG_BLK_DEV_INITRD if (initrd_start) { printk(KERN_INFO "initrd: %08lx-%08lx\n", initrd_start, initrd_end); if (__pa(initrd_start) < mem_max) { unsigned long initrd_reserve; if (__pa(initrd_end) > mem_max) { initrd_reserve = mem_max - __pa(initrd_start); } else { initrd_reserve = initrd_end - initrd_start; } initrd_below_start_ok = 1; printk(KERN_INFO "initrd: reserving %08lx-%08lx (mem_max %08lx)\n", __pa(initrd_start), __pa(initrd_start) + initrd_reserve, mem_max); memblock_reserve(__pa(initrd_start), initrd_reserve); } } #endif data_resource.start = virt_to_phys(&data_start); data_resource.end = virt_to_phys(_end) - 1; code_resource.start = virt_to_phys(_text); code_resource.end = virt_to_phys(&data_start)-1; /* We don't know which region the kernel will be in, so try * all of them. */ for (i = 0; i < sysram_resource_count; i++) { struct resource *res = &sysram_resources[i]; request_resource(res, &code_resource); request_resource(res, &data_resource); } request_resource(&sysram_resources[0], &pdcdata_resource); /* Initialize Page Deallocation Table (PDT) and check for bad memory. */ pdc_pdt_init(); memblock_allow_resize(); memblock_dump_all(); } static bool kernel_set_to_readonly; static void __init map_pages(unsigned long start_vaddr, unsigned long start_paddr, unsigned long size, pgprot_t pgprot, int force) { pmd_t *pmd; pte_t *pg_table; unsigned long end_paddr; unsigned long start_pmd; unsigned long start_pte; unsigned long tmp1; unsigned long tmp2; unsigned long address; unsigned long vaddr; unsigned long ro_start; unsigned long ro_end; unsigned long kernel_start, kernel_end; ro_start = __pa((unsigned long)_text); ro_end = __pa((unsigned long)&data_start); kernel_start = __pa((unsigned long)&__init_begin); kernel_end = __pa((unsigned long)&_end); end_paddr = start_paddr + size; /* for 2-level configuration PTRS_PER_PMD is 0 so start_pmd will be 0 */ start_pmd = ((start_vaddr >> PMD_SHIFT) & (PTRS_PER_PMD - 1)); start_pte = ((start_vaddr >> PAGE_SHIFT) & (PTRS_PER_PTE - 1)); address = start_paddr; vaddr = start_vaddr; while (address < end_paddr) { pgd_t *pgd = pgd_offset_k(vaddr); p4d_t *p4d = p4d_offset(pgd, vaddr); pud_t *pud = pud_offset(p4d, vaddr); #if CONFIG_PGTABLE_LEVELS == 3 if (pud_none(*pud)) { pmd = memblock_alloc(PAGE_SIZE << PMD_TABLE_ORDER, PAGE_SIZE << PMD_TABLE_ORDER); if (!pmd) panic("pmd allocation failed.\n"); pud_populate(NULL, pud, pmd); } #endif pmd = pmd_offset(pud, vaddr); for (tmp1 = start_pmd; tmp1 < PTRS_PER_PMD; tmp1++, pmd++) { if (pmd_none(*pmd)) { pg_table = memblock_alloc(PAGE_SIZE, PAGE_SIZE); if (!pg_table) panic("page table allocation failed\n"); pmd_populate_kernel(NULL, pmd, pg_table); } pg_table = pte_offset_kernel(pmd, vaddr); for (tmp2 = start_pte; tmp2 < PTRS_PER_PTE; tmp2++, pg_table++) { pte_t pte; pgprot_t prot; bool huge = false; if (force) { prot = pgprot; } else if (address < kernel_start || address >= kernel_end) { /* outside kernel memory */ prot = PAGE_KERNEL; } else if (!kernel_set_to_readonly) { /* still initializing, allow writing to RO memory */ prot = PAGE_KERNEL_RWX; huge = true; } else if (address >= ro_start) { /* Code (ro) and Data areas */ prot = (address < ro_end) ? PAGE_KERNEL_EXEC : PAGE_KERNEL; huge = true; } else { prot = PAGE_KERNEL; } pte = __mk_pte(address, prot); if (huge) pte = pte_mkhuge(pte); if (address >= end_paddr) break; set_pte(pg_table, pte); address += PAGE_SIZE; vaddr += PAGE_SIZE; } start_pte = 0; if (address >= end_paddr) break; } start_pmd = 0; } } void __init set_kernel_text_rw(int enable_read_write) { unsigned long start = (unsigned long) __init_begin; unsigned long end = (unsigned long) &data_start; map_pages(start, __pa(start), end-start, PAGE_KERNEL_RWX, enable_read_write ? 1:0); /* force the kernel to see the new page table entries */ flush_cache_all(); flush_tlb_all(); } void __ref free_initmem(void) { unsigned long init_begin = (unsigned long)__init_begin; unsigned long init_end = (unsigned long)__init_end; unsigned long kernel_end = (unsigned long)&_end; /* Remap kernel text and data, but do not touch init section yet. */ kernel_set_to_readonly = true; map_pages(init_end, __pa(init_end), kernel_end - init_end, PAGE_KERNEL, 0); /* The init text pages are marked R-X. We have to * flush the icache and mark them RW- * * This is tricky, because map_pages is in the init section. * Do a dummy remap of the data section first (the data * section is already PAGE_KERNEL) to pull in the TLB entries * for map_kernel */ map_pages(init_begin, __pa(init_begin), init_end - init_begin, PAGE_KERNEL_RWX, 1); /* now remap at PAGE_KERNEL since the TLB is pre-primed to execute * map_pages */ map_pages(init_begin, __pa(init_begin), init_end - init_begin, PAGE_KERNEL, 1); /* force the kernel to see the new TLB entries */ __flush_tlb_range(0, init_begin, kernel_end); /* finally dump all the instructions which were cached, since the * pages are no-longer executable */ flush_icache_range(init_begin, init_end); free_initmem_default(POISON_FREE_INITMEM); /* set up a new led state on systems shipped LED State panel */ pdc_chassis_send_status(PDC_CHASSIS_DIRECT_BCOMPLETE); } #ifdef CONFIG_STRICT_KERNEL_RWX void mark_rodata_ro(void) { /* rodata memory was already mapped with KERNEL_RO access rights by pagetable_init() and map_pages(). No need to do additional stuff here */ unsigned long roai_size = __end_ro_after_init - __start_ro_after_init; pr_info("Write protected read-only-after-init data: %luk\n", roai_size >> 10); } #endif /* * Just an arbitrary offset to serve as a "hole" between mapping areas * (between top of physical memory and a potential pcxl dma mapping * area, and below the vmalloc mapping area). * * The current 32K value just means that there will be a 32K "hole" * between mapping areas. That means that any out-of-bounds memory * accesses will hopefully be caught. The vmalloc() routines leaves * a hole of 4kB between each vmalloced area for the same reason. */ /* Leave room for gateway page expansion */ #if KERNEL_MAP_START < GATEWAY_PAGE_SIZE #error KERNEL_MAP_START is in gateway reserved region #endif #define MAP_START (KERNEL_MAP_START) #define VM_MAP_OFFSET (32*1024) #define SET_MAP_OFFSET(x) ((void *)(((unsigned long)(x) + VM_MAP_OFFSET) \ & ~(VM_MAP_OFFSET-1))) void *parisc_vmalloc_start __ro_after_init; EXPORT_SYMBOL(parisc_vmalloc_start); #ifdef CONFIG_PA11 unsigned long pcxl_dma_start __ro_after_init; #endif void __init mem_init(void) { /* Do sanity checks on IPC (compat) structures */ BUILD_BUG_ON(sizeof(struct ipc64_perm) != 48); #ifndef CONFIG_64BIT BUILD_BUG_ON(sizeof(struct semid64_ds) != 80); BUILD_BUG_ON(sizeof(struct msqid64_ds) != 104); BUILD_BUG_ON(sizeof(struct shmid64_ds) != 104); #endif #ifdef CONFIG_COMPAT BUILD_BUG_ON(sizeof(struct compat_ipc64_perm) != sizeof(struct ipc64_perm)); BUILD_BUG_ON(sizeof(struct compat_semid64_ds) != 80); BUILD_BUG_ON(sizeof(struct compat_msqid64_ds) != 104); BUILD_BUG_ON(sizeof(struct compat_shmid64_ds) != 104); #endif /* Do sanity checks on page table constants */ BUILD_BUG_ON(PTE_ENTRY_SIZE != sizeof(pte_t)); BUILD_BUG_ON(PMD_ENTRY_SIZE != sizeof(pmd_t)); BUILD_BUG_ON(PGD_ENTRY_SIZE != sizeof(pgd_t)); BUILD_BUG_ON(PAGE_SHIFT + BITS_PER_PTE + BITS_PER_PMD + BITS_PER_PGD > BITS_PER_LONG); #if CONFIG_PGTABLE_LEVELS == 3 BUILD_BUG_ON(PT_INITIAL > PTRS_PER_PMD); #else BUILD_BUG_ON(PT_INITIAL > PTRS_PER_PGD); #endif high_memory = __va((max_pfn << PAGE_SHIFT)); set_max_mapnr(max_low_pfn); memblock_free_all(); #ifdef CONFIG_PA11 if (boot_cpu_data.cpu_type == pcxl2 || boot_cpu_data.cpu_type == pcxl) { pcxl_dma_start = (unsigned long)SET_MAP_OFFSET(MAP_START); parisc_vmalloc_start = SET_MAP_OFFSET(pcxl_dma_start + PCXL_DMA_MAP_SIZE); } else #endif parisc_vmalloc_start = SET_MAP_OFFSET(MAP_START); #if 0 /* * Do not expose the virtual kernel memory layout to userspace. * But keep code for debugging purposes. */ printk("virtual kernel memory layout:\n" " vmalloc : 0x%px - 0x%px (%4ld MB)\n" " fixmap : 0x%px - 0x%px (%4ld kB)\n" " memory : 0x%px - 0x%px (%4ld MB)\n" " .init : 0x%px - 0x%px (%4ld kB)\n" " .data : 0x%px - 0x%px (%4ld kB)\n" " .text : 0x%px - 0x%px (%4ld kB)\n", (void*)VMALLOC_START, (void*)VMALLOC_END, (VMALLOC_END - VMALLOC_START) >> 20, (void *)FIXMAP_START, (void *)(FIXMAP_START + FIXMAP_SIZE), (unsigned long)(FIXMAP_SIZE / 1024), __va(0), high_memory, ((unsigned long)high_memory - (unsigned long)__va(0)) >> 20, __init_begin, __init_end, ((unsigned long)__init_end - (unsigned long)__init_begin) >> 10, _etext, _edata, ((unsigned long)_edata - (unsigned long)_etext) >> 10, _text, _etext, ((unsigned long)_etext - (unsigned long)_text) >> 10); #endif } unsigned long *empty_zero_page __ro_after_init; EXPORT_SYMBOL(empty_zero_page); /* * pagetable_init() sets up the page tables * * Note that gateway_init() places the Linux gateway page at page 0. * Since gateway pages cannot be dereferenced this has the desirable * side effect of trapping those pesky NULL-reference errors in the * kernel. */ static void __init pagetable_init(void) { int range; /* Map each physical memory range to its kernel vaddr */ for (range = 0; range < npmem_ranges; range++) { unsigned long start_paddr; unsigned long end_paddr; unsigned long size; start_paddr = pmem_ranges[range].start_pfn << PAGE_SHIFT; size = pmem_ranges[range].pages << PAGE_SHIFT; end_paddr = start_paddr + size; map_pages((unsigned long)__va(start_paddr), start_paddr, size, PAGE_KERNEL, 0); } #ifdef CONFIG_BLK_DEV_INITRD if (initrd_end && initrd_end > mem_limit) { printk(KERN_INFO "initrd: mapping %08lx-%08lx\n", initrd_start, initrd_end); map_pages(initrd_start, __pa(initrd_start), initrd_end - initrd_start, PAGE_KERNEL, 0); } #endif empty_zero_page = memblock_alloc(PAGE_SIZE, PAGE_SIZE); if (!empty_zero_page) panic("zero page allocation failed.\n"); } static void __init gateway_init(void) { unsigned long linux_gateway_page_addr; /* FIXME: This is 'const' in order to trick the compiler into not treating it as DP-relative data. */ extern void * const linux_gateway_page; linux_gateway_page_addr = LINUX_GATEWAY_ADDR & PAGE_MASK; /* * Setup Linux Gateway page. * * The Linux gateway page will reside in kernel space (on virtual * page 0), so it doesn't need to be aliased into user space. */ map_pages(linux_gateway_page_addr, __pa(&linux_gateway_page), PAGE_SIZE, PAGE_GATEWAY, 1); } static void __init parisc_bootmem_free(void) { unsigned long max_zone_pfn[MAX_NR_ZONES] = { 0, }; max_zone_pfn[0] = memblock_end_of_DRAM(); free_area_init(max_zone_pfn); } void __init paging_init(void) { setup_bootmem(); pagetable_init(); gateway_init(); flush_cache_all_local(); /* start with known state */ flush_tlb_all_local(NULL); sparse_init(); parisc_bootmem_free(); } #ifdef CONFIG_PA20 /* * Currently, all PA20 chips have 18 bit protection IDs, which is the * limiting factor (space ids are 32 bits). */ #define NR_SPACE_IDS 262144 #else /* * Currently we have a one-to-one relationship between space IDs and * protection IDs. Older parisc chips (PCXS, PCXT, PCXL, PCXL2) only * support 15 bit protection IDs, so that is the limiting factor. * PCXT' has 18 bit protection IDs, but only 16 bit spaceids, so it's * probably not worth the effort for a special case here. */ #define NR_SPACE_IDS 32768 #endif /* !CONFIG_PA20 */ #define RECYCLE_THRESHOLD (NR_SPACE_IDS / 2) #define SID_ARRAY_SIZE (NR_SPACE_IDS / (8 * sizeof(long))) static unsigned long space_id[SID_ARRAY_SIZE] = { 1 }; /* disallow space 0 */ static unsigned long dirty_space_id[SID_ARRAY_SIZE]; static unsigned long space_id_index; static unsigned long free_space_ids = NR_SPACE_IDS - 1; static unsigned long dirty_space_ids = 0; static DEFINE_SPINLOCK(sid_lock); unsigned long alloc_sid(void) { unsigned long index; spin_lock(&sid_lock); if (free_space_ids == 0) { if (dirty_space_ids != 0) { spin_unlock(&sid_lock); flush_tlb_all(); /* flush_tlb_all() calls recycle_sids() */ spin_lock(&sid_lock); } BUG_ON(free_space_ids == 0); } free_space_ids--; index = find_next_zero_bit(space_id, NR_SPACE_IDS, space_id_index); space_id[BIT_WORD(index)] |= BIT_MASK(index); space_id_index = index; spin_unlock(&sid_lock); return index << SPACEID_SHIFT; } void free_sid(unsigned long spaceid) { unsigned long index = spaceid >> SPACEID_SHIFT; unsigned long *dirty_space_offset, mask; dirty_space_offset = &dirty_space_id[BIT_WORD(index)]; mask = BIT_MASK(index); spin_lock(&sid_lock); BUG_ON(*dirty_space_offset & mask); /* attempt to free space id twice */ *dirty_space_offset |= mask; dirty_space_ids++; spin_unlock(&sid_lock); } #ifdef CONFIG_SMP static void get_dirty_sids(unsigned long *ndirtyptr,unsigned long *dirty_array) { int i; /* NOTE: sid_lock must be held upon entry */ *ndirtyptr = dirty_space_ids; if (dirty_space_ids != 0) { for (i = 0; i < SID_ARRAY_SIZE; i++) { dirty_array[i] = dirty_space_id[i]; dirty_space_id[i] = 0; } dirty_space_ids = 0; } return; } static void recycle_sids(unsigned long ndirty,unsigned long *dirty_array) { int i; /* NOTE: sid_lock must be held upon entry */ if (ndirty != 0) { for (i = 0; i < SID_ARRAY_SIZE; i++) { space_id[i] ^= dirty_array[i]; } free_space_ids += ndirty; space_id_index = 0; } } #else /* CONFIG_SMP */ static void recycle_sids(void) { int i; /* NOTE: sid_lock must be held upon entry */ if (dirty_space_ids != 0) { for (i = 0; i < SID_ARRAY_SIZE; i++) { space_id[i] ^= dirty_space_id[i]; dirty_space_id[i] = 0; } free_space_ids += dirty_space_ids; dirty_space_ids = 0; space_id_index = 0; } } #endif /* * flush_tlb_all() calls recycle_sids(), since whenever the entire tlb is * purged, we can safely reuse the space ids that were released but * not flushed from the tlb. */ #ifdef CONFIG_SMP static unsigned long recycle_ndirty; static unsigned long recycle_dirty_array[SID_ARRAY_SIZE]; static unsigned int recycle_inuse; void flush_tlb_all(void) { int do_recycle; do_recycle = 0; spin_lock(&sid_lock); __inc_irq_stat(irq_tlb_count); if (dirty_space_ids > RECYCLE_THRESHOLD) { BUG_ON(recycle_inuse); /* FIXME: Use a semaphore/wait queue here */ get_dirty_sids(&recycle_ndirty,recycle_dirty_array); recycle_inuse++; do_recycle++; } spin_unlock(&sid_lock); on_each_cpu(flush_tlb_all_local, NULL, 1); if (do_recycle) { spin_lock(&sid_lock); recycle_sids(recycle_ndirty,recycle_dirty_array); recycle_inuse = 0; spin_unlock(&sid_lock); } } #else void flush_tlb_all(void) { spin_lock(&sid_lock); __inc_irq_stat(irq_tlb_count); flush_tlb_all_local(NULL); recycle_sids(); spin_unlock(&sid_lock); } #endif
var $ = jQuery; $(document).ready(function() { $('#menu-open').click(function() { $('#menu-open span').toggleClass('open'); $('.nav').slideToggle('slow'); }); //products sub menu $('.products-menu-link>a').click(function() { $('.downloads').removeClass('sub-menu-open'); $('.products').toggleClass('sub-menu-open'); }); //downloads sub menu $('.download-menu-link').click(function() { $('.products').removeClass('sub-menu-open'); $('.downloads').toggleClass('sub-menu-open'); }); //change product menu link on mobile let w = window.innerWidth; if(w < 1200) { $('.products-menu-link>a').attr('href', '/products'); $('.download-menu-link>a').attr('href', '/downloads'); } //collapsible menus function function setup_collapsible_submenus() { var $menu = $('#mobile_menu'), top_level_link = '#mobile_menu .menu-item-has-children > a'; console.log($menu); $menu.find('a').each(function() { $(this).off('click'); if ( $(this).is(top_level_link) ) { $(this).attr('href', '#'); } if ( ! $(this).siblings('.sub-menu').length ) { $(this).on('click', function(event) { $(this).parents('.menu-button').trigger('click'); }); } else { $(this).on('click', function(event) { event.preventDefault(); $(this).parent().toggleClass('visible'); }); } }); } $(window).load(function() { setTimeout(function() { setup_collapsible_submenus(); }, 700); }); });
// Jasmine Test for lib/movie.js describe('Movie', function() { // inject the HTML fixture for the test to run against beforeEach(function() { var fixture = '<div id="fixture" class="movie" data-idx="42">' + ' <dl>' + ' <dd><span id="votes">n/a</span></dd>' + ' </dl>' + ' <button id="upvote">Upvote</button>' + ' <button id="downvote">Downvote</button>' + '</div>'; // add the HTML fixture via hook document.body.insertAdjacentHTML('afterbegin', fixture); // init our class to add the event listeners AL.movie.init(); }); // remove the html fixture from the DOM when completed afterEach(function() { document.body.removeChild(document.getElementById('fixture')); }); // test the initial condition - 0 votes it('init should result in total votes = 0', function() { expect(document.getElementById('votes').innerHTML).toBe('0'); }); // test the upvote event, should result in 1 vote it('upvote should result in total votes = 1', function() { document.getElementById('upvote').click(); expect(document.getElementById('votes').innerHTML).toBe('1'); }); // test the downvote event, should result in 0 votes it('downvote should result in total votes = 0', function() { document.getElementById('downvote').click(); expect(document.getElementById('votes').innerHTML).toBe('0'); }); });
const Path = require('path'); // Import the core config const webpackConfig = require('@silverstripe/webpack-config'); const { moduleCSS, pluginCSS, } = webpackConfig; const ENV = process.env.NODE_ENV; const PATHS = { MODULES: 'node_modules', FILES_PATH: '../', ROOT: Path.resolve(), SRC: Path.resolve('client/src'), DIST: Path.resolve('client/dist'), }; const config = [ { name: 'css', entry: { bundle: `${PATHS.SRC}/styles/bundle.scss`, darkmode: `${PATHS.SRC}/styles/dark-mode.scss` }, output: { path: PATHS.DIST, filename: 'styles/[name].css', }, devtool: (ENV !== 'production') ? 'source-map' : '', module: moduleCSS(ENV, PATHS), plugins: pluginCSS(ENV, PATHS), }, ]; module.exports = config;
numero1 = 10 numero2 = 15 resultado = numero1+numero2 print(resultado) resultado = numero1-numero2 print(resultado) resultado = numero1*numero2 print(resultado) resultado = numero1/numero2 print(resultado) resultado = 'Pablo' + ' Schumacher' print(resultado)
// @flow import YAML from 'yaml'; import { globalBeforeEach } from '../../../__jest__/before-each'; import * as models from '../../../models'; import * as db from '../../../common/database'; import { assertAsyncError, setupDateMocks } from './util'; import NeDBPlugin from '../ne-db-plugin'; import path from 'path'; import { GIT_CLONE_DIR, GIT_INSOMNIA_DIR, GIT_INSOMNIA_DIR_NAME } from '../git-vcs'; describe('NeDBPlugin', () => { afterAll(() => jest.restoreAllMocks()); beforeEach(async () => { await globalBeforeEach(); setupDateMocks(); // Create some sample models await models.workspace.create({ _id: 'wrk_1' }); await models.request.create({ _id: 'req_1', parentId: 'wrk_1' }); await models.request.create({ _id: 'req_2', parentId: 'wrk_1' }); // Shouldn't list private docs await models.request.create({ id: 'req_x', isPrivate: true, parentId: 'wrk_1' }); }); describe('readdir()', () => { it('reads model IDs from model type folders', async () => { const pNeDB = new NeDBPlugin('wrk_1'); const reqDir = path.join(GIT_INSOMNIA_DIR, models.request.type); const wrkDir = path.join(GIT_INSOMNIA_DIR, models.workspace.type); expect(await pNeDB.readdir(GIT_CLONE_DIR)).toEqual([GIT_INSOMNIA_DIR_NAME]); expect(await pNeDB.readdir(GIT_INSOMNIA_DIR)).toEqual([ models.apiSpec.type, models.environment.type, models.grpcRequest.type, models.protoFile.type, models.request.type, models.requestGroup.type, models.unitTest.type, models.unitTestSuite.type, models.workspace.type, ]); expect(await pNeDB.readdir(reqDir)).toEqual(['req_1.yml', 'req_2.yml']); expect(await pNeDB.readdir(wrkDir)).toEqual(['wrk_1.yml']); }); }); describe('readFile()', () => { it('reads file from model/id folders', async () => { const wrk1Yml = path.join(GIT_INSOMNIA_DIR, models.workspace.type, 'wrk_1.yml'); const req1Yml = path.join(GIT_INSOMNIA_DIR, models.request.type, 'req_1.yml'); const reqXYml = path.join(GIT_INSOMNIA_DIR, models.request.type, 'req_x.yml'); const pNeDB = new NeDBPlugin('wrk_1'); expect(YAML.parse(await pNeDB.readFile(wrk1Yml, 'utf8'))).toEqual( expect.objectContaining({ _id: 'wrk_1', parentId: null }), ); expect(YAML.parse(await pNeDB.readFile(req1Yml, 'utf8'))).toEqual( expect.objectContaining({ _id: 'req_1', parentId: 'wrk_1' }), ); await assertAsyncError(pNeDB.readFile(reqXYml)); }); }); describe('stat()', () => { it('stats a dir', async () => { // Assemble const reqDir = path.join(GIT_INSOMNIA_DIR, models.request.type); const wrkDir = path.join(GIT_INSOMNIA_DIR, models.workspace.type); const dirType = expect.objectContaining({ type: 'dir' }); const fileType = expect.objectContaining({ type: 'file' }); // Act const pNeDB = new NeDBPlugin('wrk_1'); // Assert expect(await pNeDB.stat(GIT_CLONE_DIR)).toEqual(dirType); expect(await pNeDB.stat(GIT_INSOMNIA_DIR)).toEqual(dirType); expect(await pNeDB.stat(reqDir)).toEqual(dirType); expect(await pNeDB.stat(path.join(wrkDir, 'wrk_1.yml'))).toEqual(fileType); expect(await pNeDB.stat(path.join(reqDir, 'req_2.yml'))).toEqual(fileType); }); }); describe('writeFile()', () => { it('should ignore files not in GIT_INSOMNIA_DIR directory', async () => { // Assemble const upsertSpy = jest.spyOn(db, 'upsert'); const workspaceId = 'wrk_1'; const pNeDB = new NeDBPlugin(workspaceId); const env = { _id: 'env_1', type: models.environment.type, parentId: workspaceId }; const filePath = path.join('anotherDir', env.type, `${env._id}.yml`); // Act await pNeDB.writeFile(filePath, YAML.stringify(env)); // Assert expect(upsertSpy).not.toBeCalled(); // Cleanup upsertSpy.mockRestore(); }); it('should write files in GIT_INSOMNIA_DIR directory to db', async () => { // Assemble const workspaceId = 'wrk_1'; const pNeDB = new NeDBPlugin(workspaceId); const upsertSpy = jest.spyOn(db, 'upsert'); const env = { _id: 'env_1', type: models.environment.type, parentId: workspaceId }; const filePath = path.join(GIT_INSOMNIA_DIR, env.type, `${env._id}.yml`); // Act await pNeDB.writeFile(filePath, YAML.stringify(env)); // Assert expect(upsertSpy).toHaveBeenCalledTimes(1); expect(upsertSpy).toHaveBeenCalledWith(env, true); // Cleanup upsertSpy.mockRestore(); }); it('should throw error if id does not match', async () => { // Assemble const workspaceId = 'wrk_1'; const pNeDB = new NeDBPlugin(workspaceId); const env = { _id: 'env_1', type: models.environment.type, parentId: workspaceId }; const filePath = path.join(GIT_INSOMNIA_DIR, env.type, `env_2.yml`); // Act const promiseResult = pNeDB.writeFile(filePath, YAML.stringify(env)); // Assert await expect(promiseResult).rejects.toThrowError( `Doc _id does not match file path [env_1 != env_2]`, ); }); it('should throw error if type does not match', async () => { // Assemble const workspaceId = 'wrk_1'; const pNeDB = new NeDBPlugin(workspaceId); const env = { _id: 'env_1', type: models.environment.type, parentId: workspaceId }; const filePath = path.join(GIT_INSOMNIA_DIR, models.request.type, `${env._id}.yml`); // Act const promiseResult = pNeDB.writeFile(filePath, YAML.stringify(env)); // Assert await expect(promiseResult).rejects.toThrowError( `Doc type does not match file path [Environment != Request]`, ); }); }); describe('mkdir()', () => { it('should throw error', async () => { const workspaceId = 'wrk_1'; const pNeDB = new NeDBPlugin(workspaceId); const promiseResult = pNeDB.mkdir('', ''); await expect(promiseResult).rejects.toThrowError('NeDBPlugin is not writable'); }); }); });
// // WSqlRecorder.h // Pods // // Created by 吴志强 on 2018/7/30. // #import <Foundation/Foundation.h> #import "WSqlSession.h" @interface WSqlRecorder : NSObject /** 设置表名 */ @property (nonatomic,copy) NSString *tableName; /** 获取记录实例 @param tableName 表名 */ + (instancetype) recorderWithTableName:(NSString *)tableName; /** 创建记录模型 @param tableName 表名 @return 返回模型 */ - (instancetype) initWithTableName:(NSString *)tableName; /** 插入新数据或者更新旧的数据 @param string 条件 @return 返回是否成功 */ - (BOOL) insertOrUpdateOn:(NSString *)string; /** 插入新数据 @param fields 要过滤的字段 @return 返回操作结果 */ - (BOOL) insertWithoutFields:(NSArray *)fields; /** 插入新数据 @return 返回操作结果 */ - (BOOL) insert; /** 更新数据去掉字段 @param fields 要去掉的字段 @return 返回是否成功 */ - (BOOL) updateWithoutFields:(NSArray *)fields; /** 更新数据 @return 返回操作结果 */ - (BOOL) update; /** 删除数据 @return 返回操作结果 */ - (BOOL) remove; @end
import json import logging import sys from typing import Dict, Union, List import falcon import jwt from passlib.hash import argon2 from pymongo import MongoClient, ASCENDING from pymongo.collection import Collection from pymongo.errors import CollectionInvalid from common.consts import CONFIG_MONGO, CONFIG_MONGO_HOST, CONFIG_MONGO_PORT, CONFIG_MONGO_USER, CONFIG_MONGO_PASSWORD, FIELD_AUTH_TOKEN from common.consts import CONFIG_MONGO_AUTH_COLLECTION, CONFIG_MONGO_DB, CONFIG_MONGO_MECHANISM from common.consts import DEFAULT_AUTH_CONFIG, CONFIG_AUTH_JWT, CONFIG_AUTH_JWT_SECRET from common.consts import HTTP_IGNORE_METHODS from common.entities import UserAccessMeta from common.util import to_bool, is_public VALIDATION = {"$jsonSchema": { "bsonType": "object", "required": ["user", "password", "am"], "properties": { "user": { "bsonType": "string", "description": "username, required" }, "password": { "bsonType": "string", "description": "hashed password, required" }, "am": { "bsonType": "object", "required": ["read_groups", "write_groups", "admin_access"], "properties": { "read_groups": { "bsonType": "array", "items": { "bsonType": "string", }, "description": "read access groups, required" }, "write_groups": { "bsonType": "array", "items": { "bsonType": "string", }, "description": "write access groups, required" }, "admin_access": { "bsonType": "bool", "description": "has admin access? required" }, } } } }} class AuthManager: def __init__(self, config_file: str = DEFAULT_AUTH_CONFIG): self.jwt_secret = None self._client = None self._auth_collection = None self.load(config_file=config_file) def load(self, config_file: str = DEFAULT_AUTH_CONFIG): try: with open(config_file, mode="r") as fin: config = json.load(fin) jwt_config = config.get(CONFIG_AUTH_JWT, {}) or {} self.jwt_secret = jwt_config.get(CONFIG_AUTH_JWT_SECRET, None) mongo_config = config.get(CONFIG_MONGO, {}) or {} self._client = MongoClient(host=mongo_config.get(CONFIG_MONGO_HOST), port=mongo_config.get(CONFIG_MONGO_PORT), username=mongo_config.get(CONFIG_MONGO_USER), password=mongo_config.get(CONFIG_MONGO_PASSWORD), authSource=mongo_config.get(CONFIG_MONGO_DB), authMechanism=mongo_config.get(CONFIG_MONGO_MECHANISM)) self._auth_collection = self.setup(db_name=mongo_config.get(CONFIG_MONGO_DB), collection_name=mongo_config.get(CONFIG_MONGO_AUTH_COLLECTION)) logging.info("Loaded auth config...") except: logging.error("Error while trying to load auth config. Error: %s", sys.exc_info()[1]) def edit_user(self, access: UserAccessMeta, password: str = None, hashed: bool = False, add: bool = False) -> bool: db = access.to_db() if password: db["password"] = password if hashed else argon2.hash(password) if add: self._auth_collection.insert_one(db) return True else: result = self._auth_collection.update_one({"user": access.user}, {"$set": db}) return result.modified_count > 0 def remove_user(self, user: str) -> bool: result = self._auth_collection.delete_many({"user": user}) return result.deleted_count > 0 def get_groups(self) -> List[str]: try: result = set() result.update(self._auth_collection.distinct("am.read_groups")) result.update(self._auth_collection.distinct("am.write_groups")) return list(result) except: logging.error("Get groups Error: %s", sys.exc_info()[1]) return [] def get_users(self) -> List[UserAccessMeta]: try: return [self._from_db(doc) for doc in self._auth_collection.find()] except: logging.error("Get Users Error: %s", sys.exc_info()[1]) return [] def get_user(self, user: str) -> Union[UserAccessMeta, None]: try: return self._from_db(self._auth_collection.find_one({"user": user})) except: logging.error("Get user(%s) Error: %s", user, sys.exc_info()[1]) return None def auth_user(self, user: str, password: str) -> Union[UserAccessMeta, None]: try: auth = self._auth_collection.find_one({"user": user}) return self._from_db(auth) if argon2.verify(password, auth.get("password", None)) else None except: logging.error("Auth Error: %s", sys.exc_info()[1]) return None def auth_token(self, user: str, password: str) -> Union[str, None]: auth = self.auth_user(user=user, password=password) return jwt.encode(payload=auth.public_json(), key=self.jwt_secret, algorithm="HS256").decode("utf-8") if auth else None def decode_token(self, token: str) -> Union[UserAccessMeta, None]: if not token: return None try: payload = jwt.decode(jwt=token.encode("utf-8"), key=self.jwt_secret, verify=True) return self._from_public(payload) except: logging.error("Decode Error: %s", sys.exc_info()[1]) return None def setup(self, db_name: str, collection_name: str) -> Collection: db = self._client[db_name] try: collection = db.create_collection(collection_name, validator=VALIDATION) collection.create_index([("user", ASCENDING)], unique=True) return collection except CollectionInvalid: return db[collection_name] def close(self): if self._client: self._client.close() @staticmethod def _from_db(doc: Dict) -> UserAccessMeta: am = doc.get("am", {}) or {} return UserAccessMeta(user=doc.get("user", None), admin_access=to_bool(am.get("admin_access", False)), read_groups=am.get("read_groups", []) or [], write_groups=am.get("write_groups", []) or []) @staticmethod def _from_public(doc: Dict) -> UserAccessMeta: return UserAccessMeta(user=doc.get("user", None), admin_access=to_bool(doc.get("admin_access", False)), read_groups=doc.get("read_groups", []) or [], write_groups=doc.get("write_groups", []) or []) class AuthMiddleware: def __init__(self, auth: AuthManager, public_paths: set = None): self.auth = auth self.public_paths = public_paths if public_paths else set() def process_request(self, req: falcon.Request, _resp: falcon.Response): if is_public(req.path, self.public_paths): logging.debug("This is a public resource which does not need a valid token") return token = self.auth.decode_token(_get_token(req, field=FIELD_AUTH_TOKEN)) _check_access(method=req.method, token=token) req.user_access = UserAccessMeta(user=token.user, read_groups=token.read_groups or [], write_groups=token.write_groups or [], admin_access=token.admin_access or False) def _check_access(method: str, token: Union[UserAccessMeta, None]): if method in HTTP_IGNORE_METHODS: return if not token: raise falcon.HTTPUnauthorized(title='Access token required', description='Please provide a valid access token as part of the request.') def _get_token(req: falcon.Request, field: str) -> Union[str, None]: token = req.get_header(field, None) if token is not None: return token token = req.params.get(field, None) if token is not None: return token # Because every time you lose something, you always find it in the very last place you would look. return req.cookies.get(field, None)
from setuptools import setup, find_packages long_description = open("README.rst").read() setup( name="PyChromecast", version="12.1.4", license="MIT", url="https://github.com/balloob/pychromecast", author="Paulus Schoutsen", author_email="paulus@paulusschoutsen.nl", description="Python module to talk to Google Chromecast.", long_description=long_description, packages=find_packages(), zip_safe=False, include_package_data=True, platforms="any", install_requires=list(val.strip() for val in open("requirements.txt")), classifiers=[ "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 3", "Topic :: Software Development :: Libraries :: Python Modules", ], )
import React, { Component } from "react"; import { Row, Input, Button } from "react-materialize"; import { Link } from "react-router-dom"; class Login extends Component { constructor(props) { super(props); this.login(); this.state = { error: false, msg: null }; } formSubmit(e) { e.preventDefault(); this.props.socket.emit("user login", { username: e.target.querySelector('[type="text"]').value, password: e.target.querySelector('[type="password"]').value }); } login() { this.props.socket.on("user login", res => { if (res.error) { this.setState(res); return; } console.log(res.user[0]); //save session in state //and in browser cache this.props.reduxDispatchLogin(res.user[0]); sessionStorage.setItem("user", JSON.stringify(res.user[0])); //redirect to homepage this.props.history.push("/"); }); } render() { return ( <div> <h4>Login Page</h4> <Row> <form onSubmit={this.formSubmit.bind(this)}> <Input type="text" label="username" s={12} /> <Input type="password" label="password" s={12} /> <Button waves="light">Login</Button> <span style={{ marginLeft: "15px", color: "red" }}> {this.state.error ? this.state.msg : ""} </span> </form> </Row> <Link to="/register">New Users Register Here</Link> </div> ); } } export default Login;
# Funcao recursiva de MDC # O experimento traduzira a funcao mdcTR # -*- coding: utf-8 -*- import time as t import sys import os import string import random import traceback sys.setrecursionlimit(1000000) # **************** funcao em teste ******************* def mdcTR(a, b): if (b == 0): return a return mdcTR(b, (a % b)) # **************************************************** def main(): try: #versao="2_7_16" versao="3_7_9" nome_funcao="mdcTR" nomeArqResult="Results" +"_"+ versao+"_"+nome_funcao+".csv" resultsCSV = open(nomeArqResult, "w") resultsCSV.write("#Id;NomeFuncao;N;Tempo;Versao Python\n") id=1 for n in range(2,21,1): inicio=t.time() a=100+random.randint(1,1000) print("mdc de ",a,n,"=", mdcTR(a,n)) fim = t.time() tempo=(fim - inicio) resultsCSV.write("%d;%s;%d;%s;%s\n" % (id,nome_funcao, n, tempo, versao)) id=id+1 resultsCSV.flush() resultsCSV.close() fim = t.time() print("Tempo de Execucao: ", (fim - inicio)) except: print("ERRO na Execucao!!! ") traceback.print_exc() resultsCSV.close() os.remove(nomeArqResult) main()
AVAILABLE = "1" UNAVAILABLE = "2" PRODUCT_STATUS_CHOICES = [ (AVAILABLE, "Available"), (UNAVAILABLE, "Unavailable") ] PARATHA = 'PRT' MAGGIE = "MGG" BURGER = "BRG" SANDWICH = "SNW" TOAST = "TST" BEVERAGE = "BVR" OTHER = "OTH" PRODUCT_CATEGORY_CHOICES = [ (PARATHA, "Paratha"), (MAGGIE, "Maggie"), (BURGER, "Burger"), (SANDWICH, "Sandwich"), (TOAST, "Toast"), (BEVERAGE, "Beverage"), (OTHER, "Other") ]
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_EVENTS_OZONE_DEVICE_DEVICE_MANAGER_MANUAL_H_ #define UI_EVENTS_OZONE_DEVICE_DEVICE_MANAGER_MANUAL_H_ #include <set> #include <vector> #include "base/files/file_path_watcher.h" #include "base/macros.h" #include "base/observer_list.h" #include "ui/events/ozone/device/device_manager.h" namespace base { class FilePath; class SequencedTaskRunner; struct OnTaskRunnerDeleter; } // namespace base namespace ui { class DeviceManagerManual : public DeviceManager { public: DeviceManagerManual(); DeviceManagerManual(const DeviceManagerManual&) = delete; DeviceManagerManual& operator=(const DeviceManagerManual&) = delete; ~DeviceManagerManual() override; private: // DeviceManager overrides: void ScanDevices(DeviceEventObserver* observer) override; void AddObserver(DeviceEventObserver* observer) override; void RemoveObserver(DeviceEventObserver* observer) override; void StartWatching(); void InitiateScanDevices(); void OnDevicesScanned(std::vector<base::FilePath>* result); void OnWatcherEvent(const base::FilePath& path, bool error); static void OnWatcherEventOnUiSequence( scoped_refptr<base::TaskRunner> ui_thread_runner, base::WeakPtr<DeviceManagerManual> device_manager, const base::FilePath& path, bool error); std::set<base::FilePath> devices_; base::ObserverList<DeviceEventObserver>::Unchecked observers_; bool is_watching_ = false; const scoped_refptr<base::SequencedTaskRunner> blocking_task_runner_; std::unique_ptr<base::FilePathWatcher, base::OnTaskRunnerDeleter> watcher_; base::WeakPtrFactory<DeviceManagerManual> weak_ptr_factory_{this}; }; } // namespace ui #endif // UI_EVENTS_OZONE_DEVICE_DEVICE_MANAGER_MANUAL_H_
# -*- coding: utf-8 -*- # Copyright (c) 2010, 2011, 2012, Sebastian Wiesner <lunaryorn@gmail.com> # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """ sphinxcontrib.programoutput =========================== This extension provides a directive to include the output of commands as literal block while building the docs. .. moduleauthor:: Sebastian Wiesner <lunaryorn@gmail.com> """ from __future__ import print_function, division, absolute_import import sys import os import shlex from subprocess import Popen, PIPE, STDOUT from collections import defaultdict, namedtuple from docutils import nodes from docutils.parsers import rst from docutils.parsers.rst.directives import flag, unchanged, nonnegative_int from docutils.statemachine import StringList from sphinx.util import logging as sphinx_logging __version__ = '0.18.dev0' logger = sphinx_logging.getLogger('contrib.programoutput') class program_output(nodes.Element): pass def _container_wrapper(directive, literal_node, caption): container_node = nodes.container('', literal_block=True, classes=['literal-block-wrapper']) parsed = nodes.Element() directive.state.nested_parse(StringList([caption], source=''), directive.content_offset, parsed) if isinstance(parsed[0], nodes.system_message): # pragma: no cover # TODO: Figure out if this is really possible and how to produce # it in a test case. msg = 'Invalid caption: %s' % parsed[0].astext() raise ValueError(msg) assert isinstance(parsed[0], nodes.Element) caption_node = nodes.caption(parsed[0].rawsource, '', *parsed[0].children) caption_node.source = literal_node.source caption_node.line = literal_node.line container_node += caption_node container_node += literal_node return container_node def _slice(value): parts = [int(v.strip()) for v in value.split(',')] if len(parts) > 2: raise ValueError('too many slice parts') return tuple((parts + [None] * 2)[:2]) class ProgramOutputDirective(rst.Directive): has_content = False final_argument_whitespace = True required_arguments = 1 option_spec = dict(shell=flag, prompt=flag, nostderr=flag, ellipsis=_slice, extraargs=unchanged, returncode=nonnegative_int, cwd=unchanged, caption=unchanged, name=unchanged) def run(self): env = self.state.document.settings.env node = program_output() node.line = self.lineno node['command'] = self.arguments[0] if self.name == 'command-output': node['show_prompt'] = True else: node['show_prompt'] = 'prompt' in self.options node['hide_standard_error'] = 'nostderr' in self.options node['extraargs'] = self.options.get('extraargs', '') _, cwd = env.relfn2path(self.options.get('cwd', '/')) node['working_directory'] = cwd node['use_shell'] = 'shell' in self.options node['returncode'] = self.options.get('returncode', 0) if 'ellipsis' in self.options: node['strip_lines'] = self.options['ellipsis'] if 'caption' in self.options: caption = self.options['caption'] or self.arguments[0] node = _container_wrapper(self, node, caption) self.add_name(node) return [node] _Command = namedtuple( 'Command', 'command shell hide_standard_error working_directory') class Command(_Command): """ A command to be executed. """ def __new__(cls, command, shell=False, hide_standard_error=False, working_directory='/'): # `chdir()` resolves symlinks, so we need to resolve them too for # caching to make sure that different symlinks to the same directory # don't result in different cache keys. Also normalize paths to make # sure that identical paths are also equal as strings. working_directory = os.path.normpath(os.path.realpath( working_directory)) # Likewise, normalize the command now for better caching, and so # that we can present *exactly* what we run to the user. command = cls.__normalize_command(command, shell) return _Command.__new__(cls, command, shell, hide_standard_error, working_directory) @staticmethod def __normalize_command(command, shell): # pylint:disable=unused-private-member # Returns either a native string, to a tuple. if (bytes is str and not isinstance(command, str) and hasattr(command, 'encode')): # Python 2, given a unicode string command = command.encode(sys.getfilesystemencoding()) assert isinstance(command, str) if not shell and isinstance(command, str): command = shlex.split(command) if isinstance(command, list): command = tuple(command) assert isinstance(command, (str, tuple)), command return command @classmethod def from_program_output_node(cls, node): """ Create a command from a :class:`program_output` node. """ extraargs = node.get('extraargs', '') command = (node['command'] + ' ' + extraargs).strip() return cls(command, node['use_shell'], node['hide_standard_error'], node['working_directory']) def execute(self): """ Execute this command. Return the :class:`~subprocess.Popen` object representing the running command. """ command = self.command # Popen is a context manager only in Python 3, and we'd have to restructure # the code to work with it anyway. # pylint:disable=consider-using-with return Popen(command, shell=self.shell, stdout=PIPE, stderr=PIPE if self.hide_standard_error else STDOUT, cwd=self.working_directory) def get_output(self): """ Get the output of this command. Return a tuple ``(returncode, output)``. ``returncode`` is the integral return code of the process, ``output`` is the output as unicode string, with final trailing spaces and new lines stripped. """ process = self.execute() output = process.communicate()[0].decode( sys.getfilesystemencoding(), 'replace').rstrip() return process.returncode, output def __str__(self): command = self.command command = list(command) if isinstance(command, tuple) else command return repr(command) class ProgramOutputCache(defaultdict): """ Execute command and cache their output. This class is a mapping. Its keys are :class:`Command` objects represeting command invocations. Its values are tuples of the form ``(returncode, output)``, where ``returncode`` is the integral return code of the command, and ``output`` is the output as unicode string. The first time, a key is retrieved from this object, the command is invoked, and its result is cached. Subsequent access to the same key returns the cached value. """ def __missing__(self, command): """ Called, if a command was not found in the cache. ``command`` is an instance of :class:`Command`. """ result = command.get_output() self[command] = result return result def _prompt_template_as_unicode(app): tmpl = app.config.programoutput_prompt_template if isinstance(tmpl, bytes): for enc in 'utf-8', sys.getfilesystemencoding(): try: tmpl = tmpl.decode(enc) except UnicodeError: # pragma: no cover pass else: app.config.programoutput_prompt_template = tmpl break return tmpl def run_programs(app, doctree): """ Execute all programs represented by ``program_output`` nodes in ``doctree``. Each ``program_output`` node in ``doctree`` is then replaced with a node, that represents the output of this program. The program output is retrieved from the cache in ``app.env.programoutput_cache``. """ # The node_class used to be switchable to `sphinxcontrib.ansi.ansi_literal_block` # if `app.config.programoutput_use_ansi` was set. But sphinxcontrib.ansi # is no longer available on PyPI, so we can't test that. And if we can't test it, # we can't support it. node_class = nodes.literal_block cache = app.env.programoutput_cache for node in doctree.traverse(program_output): command = Command.from_program_output_node(node) try: returncode, output = cache[command] except EnvironmentError as error: error_message = 'Command {0} failed: {1}'.format(command, error) error_node = doctree.reporter.error(error_message, base_node=node) # Sphinx 1.8.0b1 started dropping all system_message nodes with a # level less than 5 by default (or 2 if `keep_warnings` is set to true). # This appears to be undocumented. Reporting failures is an important # part of what this extension does, so we raise the default level. error_node['level'] = 6 node.replace_self(error_node) else: if returncode != node['returncode']: logger.warning( 'Unexpected return code %s from command %r (output=%r)', returncode, command, output ) # replace lines with ..., if ellipsis is specified # Recall that `output` is guaranteed to be a unicode string on # all versions of Python. if 'strip_lines' in node: start, stop = node['strip_lines'] lines = output.splitlines() lines[start:stop] = [u'...'] output = u'\n'.join(lines) if node['show_prompt']: # The command in the node is also guaranteed to be # unicode, but the prompt template might not be. This # could be a native string on Python 2, or one with an # explicit b prefix on 2 or 3 (for some reason). # Attempt to decode it using UTF-8, preferentially, or # fallback to sys.getfilesystemencoding(). If all that fails, fall back # to the default encoding (which may have often worked before). prompt_template = _prompt_template_as_unicode(app) output = prompt_template.format( command=node['command'], output=output, returncode=returncode ) new_node = node_class(output, output) new_node['language'] = 'text' node.replace_self(new_node) def init_cache(app): """ Initialize the cache for program output at ``app.env.programoutput_cache``, if not already present (e.g. being loaded from a pickled environment). The cache is of type :class:`ProgramOutputCache`. """ if not hasattr(app.env, 'programoutput_cache'): app.env.programoutput_cache = ProgramOutputCache() def setup(app): app.add_config_value('programoutput_prompt_template', '$ {command}\n{output}', 'env') app.add_directive('program-output', ProgramOutputDirective) app.add_directive('command-output', ProgramOutputDirective) app.connect('builder-inited', init_cache) app.connect('doctree-read', run_programs) metadata = { 'parallel_read_safe': True } return metadata
/** The registrationController.js exposes methods regarding the registration view. @module Server_Controller.js @class Server_Controller_registrationController.js **/ // module dependencies var model = require("../model"), utils = require("../../utils"); /** Render the registration view. @param req @param res @method getRegistration **/ exports.getRegistration = function(req, res) { return res.render('./standalone/registration', { title: "Registration" }); }; /** Render the NotAuthorized view. @param req @param res @method getNotAuthorized **/ exports.getNotAuthorized = function(req, res) { return res.render("./standalone/notAuthorized", { title: "Not authorized" }); }; /** Registration of a user. This method is called via ajax from client side javascript. On a successful registration the function returns a JSON containing the newly created user's userId. If the registration is not successful, it returns a JSON containing the validation error(s): (validationError, databaseError, unknownError) @param req @param res @method getNotAuthorized @returns a JSON **/ exports.postRegister = function(req, res) { // get the id _id the request certificate var certId = req.connection.getPeerCertificate().subject.CN; // create user object var user = new model.UserModel({ _id : certId, first_name : req.body.first_name, last_name : req.body.last_name, email : req.body.email } ); // try to save the new user user.save(function(error, user) { /////////////////// // validation if (error) { var validationError, databaseError, unknownError; // validation error if (error.name === "ValidationError") { validationError = { first_name : error.errors.first_name, last_name : error.errors.last_name, email : error.errors.email }; } // duplicate key error // since the user object is created new, mongoose will check for the field "_id" (naming convention) to be unique. else if (error.code === 11000) { databaseError = "You are already registered!"; } // unknown error else { unknownError = "Something went wrong!"; } // registration failed, return validation errors return res.json( { validationError : validationError, databaseError : databaseError, unknownError : unknownError } ); } else { // registration successful, return newly user's created userId req.session.user = user; return res.send( { userId : user._id } ); } }); };
import curses import time screen = curses.initscr() screen.nodelay(1) dims = screen.getmaxyx() #should return max value of (y,x) q = -1 x,y = 0,0 Vertical = 1 Horizontal = 1 while q < 0: screen.clear() screen.addstr(int(y), int(x) , 'Hello World!') screen.refresh() y += Vertical x += Horizontal if y == dims[0] - 1: Vertical = -1 elif y == 0: Vertical = 1 if x == dims[1] - len('Hello World!') - 1: Horizontal = -1 elif x == 0: Horizontal = 1 q = screen.getch() time.sleep(0.05) screen.getch() curses.endwin()
from time import time from itertools import islice,count from math import floor,sqrt def prime(n): return n > 1 and all(n % i for i in islice(count(2), int(sqrt(n) - 1))) start = time() pLis, i = [], 2 while len(pLis) < 10001: if prime(i): pLis.append(i) i += 1 if __name__ == '__main__': print(f"\nAnswer: { pLis[-1] }") print(f"Time Taken: { time() - start }\n")
""" Encapsulate Transaction Type to storage keys """ from src.store.sql import ( TRANSACTION_TYPE_TABLE_CREATE, TRANSACTION_TYPE_DEFAULTS, TRANSACTION_TYPE_POPULATE, TRANSACTION_TYPES_READ ) from src.store.entities.utility import fetch_table_values __TRANSACTION_TYPES = {} __UNKNOWN_KEY = None __SALE_KEY = None __SALE_PARTIAL = 'Sale (Full)' __SALE_FULL = 'Sale (Partial)' __SALE_TYPES = [ __SALE_FULL, __SALE_PARTIAL, ] def __fetch_transaction_types(): if not __TRANSACTION_TYPES: global __UNKNOWN_KEY, __SALE_KEY # pylint: disable=global-statement transaction_types = fetch_table_values( TRANSACTION_TYPE_TABLE_CREATE, TRANSACTION_TYPE_DEFAULTS, TRANSACTION_TYPE_POPULATE, TRANSACTION_TYPES_READ ) for value in transaction_types: key, name, _, _, _ = value __TRANSACTION_TYPES[name] = key if name == 'UNKNOWN': __UNKNOWN_KEY = key elif name == 'Sale': __SALE_KEY = key def transaction_type_to_key(transaction_type: str) -> int: """ Convert dollar value ranges to storage keys Args: transaction_type: str - "Sale" Describes the direction of a transaction (Purchase, Exchange) """ __fetch_transaction_types() if transaction_type in __TRANSACTION_TYPES: return __TRANSACTION_TYPES[transaction_type] if transaction_type in __SALE_TYPES: return __SALE_KEY return __UNKNOWN_KEY
/* DATABASE CONFIGURATION FILE */ module.exports = { dialect: 'mysql', host: 'localhost', username: 'root', password: 'root@123', database: 'gympoint', define: { timestamps: true, underscored: true, underscored_All: true, }, };
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('crash', '0009_auto_20141224_0550'), ] operations = [ migrations.AddField( model_name='crash', name='archive', field=models.FileField(null=True, upload_to=b'minidump_archive/%Y/%m/%d', blank=True), preserve_default=True, ), ]
// Copyright (c) 2008-2018 LG Electronics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // SPDX-License-Identifier: Apache-2.0 #ifndef _TIME_SOURCE_H_ #define _TIME_SOURCE_H_ #include <stdbool.h> #ifdef __cplusplus extern "C" { #endif /** @cond INTERNAL */ typedef struct _GTimerSource GTimerSource; GTimerSource * g_timer_source_new(guint interval_ms, guint granularity_ms); GTimerSource *g_timer_source_new_seconds(guint interval_seconds); void g_timer_source_set_interval(GTimerSource *tsource, guint interval, gboolean from_poll); guint g_timer_source_get_interval_ms(GTimerSource *tsource); /** @endcond */ #ifdef __cplusplus } #endif #endif //_TIME_SOURCE_H_
# ---------------------------------------------------------------------------- # Copyright (c) 2017 Massachusetts Institute of Technology (MIT) # All rights reserved. # # Distributed under the terms of the BSD 3-clause license. # # The full license is in the LICENSE file, distributed with this software. # ---------------------------------------------------------------------------- """Module defining a Digital RF Source block.""" from __future__ import absolute_import, division, print_function import os import sys import traceback import warnings from collections import defaultdict from itertools import chain, tee import numpy as np import pmt import six from gnuradio import gr from six.moves import zip from digital_rf import DigitalMetadataWriter, DigitalRFWriter, _py_rf_write_hdf5, util def parse_time_pmt(val, samples_per_second): """Get (sec, frac, idx) from an rx_time pmt value.""" tsec = np.uint64(pmt.to_uint64(pmt.tuple_ref(val, 0))) tfrac = pmt.to_double(pmt.tuple_ref(val, 1)) # calculate sample index of time and floor to uint64 tidx = np.uint64(tsec * samples_per_second + tfrac * samples_per_second) return int(tsec), tfrac, int(tidx) def translate_rx_freq(tag): """Translate 'rx_freq' tag to 'center_frequencies' metadata sample.""" offset = tag.offset key = "center_frequencies" val = np.array(pmt.to_python(tag.value), ndmin=1) yield offset, key, val def translate_metadata(tag): """Translate 'metadata' dictionary tag to metadata samples.""" offset = tag.offset md = pmt.to_python(tag.value) try: for key, val in md.items(): yield offset, key, val except AttributeError: wrnstr = "Received 'metadata' stream tag that isn't a dictionary. Ignoring." warnings.warn(wrnstr) def collect_tags_in_dict(tags, translator, tag_dict=None): """Add the stream tags to `tag_dict` by their offset.""" if tag_dict is None: tag_dict = {} for tag in tags: for offset, key, val in translator(tag): # add tag as its own dictionary to tag_dict[offset] tag_dict.setdefault(offset, {}).update(((key, val),)) def recursive_dict_update(d, u): """Update d with values from u, recursing into sub-dictionaries.""" for k, v in u.items(): if isinstance(v, dict): try: # copy because we don't want to modify the sub-dictionary # just use its values to create an updated sub-dictionary subdict = d[k].copy() except KeyError: subdict = {} d[k] = recursive_dict_update(subdict, v) else: d[k] = v return d def pairwise(iterable): """Return iterable elements in pairs, e.g. range(3) -> (0, 1), (1, 2).""" a, b = tee(iterable) next(b, None) return zip(a, b) class digital_rf_channel_sink(gr.sync_block): """Sink block for writing a channel of Digital RF data.""" def __init__( self, channel_dir, dtype, subdir_cadence_secs, file_cadence_millisecs, sample_rate_numerator, sample_rate_denominator, start=None, ignore_tags=False, is_complex=True, num_subchannels=1, uuid_str=None, center_frequencies=None, metadata=None, is_continuous=True, compression_level=0, checksum=False, marching_periods=True, stop_on_skipped=False, stop_on_time_tag=False, debug=False, min_chunksize=None, ): """Write a channel of data in Digital RF format. In addition to storing the input samples in Digital RF format, this block also populates the channel's accompanying Digital Metadata at the sample indices when the metadata changes or a data skip occurs. See the Notes section for details on what metadata is stored. Parameters ---------- channel_dir : string The directory where this channel is to be written. It will be created if it does not exist. The basename (last component) of the path is considered the channel's name for reading purposes. dtype : np.dtype | object to be cast by np.dtype() Object that gives the numpy dtype of the data to be written. This value is passed into ``np.dtype`` to get the actual dtype (e.g. ``np.dtype('>i4')``). Scalar types, complex types, and structured complex types with 'r' and 'i' fields of scalar types are valid. subdir_cadence_secs : int The number of seconds of data to store in one subdirectory. The timestamp of any subdirectory will be an integer multiple of this value. file_cadence_millisecs : int The number of milliseconds of data to store in each file. Note that an integer number of files must exactly span a subdirectory, implying:: (subdir_cadence_secs*1000 % file_cadence_millisecs) == 0 sample_rate_numerator : int Numerator of sample rate in Hz. sample_rate_denominator : int Denominator of sample rate in Hz. Other Parameters ---------------- start : None | int | float | string, optional A value giving the time/index of the channel's first sample. When `ignore_tags` is False, 'rx_time' tags will be used to identify data gaps and skip the sample index forward appropriately (tags that refer to an earlier time will be ignored). If None or '' and `ignore_tags` is False, a default value of 0 is used (a ValueError is raised if `ignore_tags` is True). If an integer, it is interpreted as a sample index given in the number of samples since the epoch (time_since_epoch*sample_rate). If a float, it is interpreted as a UTC timestamp (seconds since epoch). If a string, three forms are permitted: 1) a string which can be evaluated to an integer/float and interpreted as above, 2) a time in ISO8601 format, e.g. '2016-01-01T16:24:00Z' 3) 'now' ('nowish'), indicating the current time (rounded up) ignore_tags : bool, optional If True, do not use 'rx_time' tags to set the sample index and do not write other tags as Digital Metadata. is_complex : bool, optional This parameter is only used when `dtype` is not complex. If True (the default), interpret supplied data as interleaved complex I/Q samples. If False, each sample has a single value. num_subchannels : int, optional Number of subchannels to write simultaneously. Default is 1. uuid_str : None | string, optional UUID string that will act as a unique identifier for the data and can be used to tie the data files to metadata. If None, a random UUID will be generated. center_frequencies : None | array_like of floats, optional List of subchannel center frequencies to include in initial metadata. If None, ``[0.0]*num_subchannels`` will be used. Subsequent center frequency metadata samples can be written using 'rx_freq' stream tags. metadata : dict, optional Dictionary of additional metadata to include in initial Digital Metadata sample. Subsequent metadata samples can be written using 'metadata' stream tags, but all keys intended to be included should be set here first even if their values are empty. is_continuous : bool, optional If True, data will be written in continuous blocks. If False data will be written with gapped blocks. Fastest write/read speed is achieved with `is_continuous` True, `checksum` False, and `compression_level` 0 (all defaults). compression_level : int, optional 0 for no compression (default), 1-9 for varying levels of gzip compression (1 == least compression, least CPU; 9 == most compression, most CPU). checksum : bool, optional If True, use HDF5 checksum capability. If False (default), no checksum. marching_periods : bool, optional If True, write a period to stdout for every subdirectory when writing. stop_on_skipped : bool, optional If True, stop writing when a sample would be skipped (such as from a dropped packet). stop_on_time_tag : bool, optional If True, stop writing when any but an initial 'rx_time' tag is received. debug : bool, optional If True, print debugging information. min_chunksize : None | int, optional Minimum number of samples to consume at once. This value can be used to adjust the sink's performance to reduce processing time. If None, a sensible default will be used. Notes ----- By convention, this block sets the following Digital Metadata fields: uuid_str : string Value provided by the `uuid_str` argument. sample_rate_numerator : int Value provided by the `sample_rate_numerator` argument. sample_rate_denominator : int Value provided by the `sample_rate_denominator` argument. center_frequencies : list of floats with length `num_subchannels` Subchannel center frequencies as specified by `center_frequencies` argument and 'rx_freq' stream tags. Additional metadata fields can be set using the `metadata` argument and stream tags. Nested dictionaries are permitted and are helpful for grouping properties. For example, receiver-specific metadata is typically specified with a sub-dictionary using the 'receiver' field. This block acts on the following stream tags when `ignore_tags` is False: rx_time : (int secs, float frac) tuple Used to set the sample index from the given time since epoch. rx_freq : float Used to set the 'center_frequencies' value in the channel's Digital Metadata as described above. metadata : dict Used to populate additional (key, value) pairs in the channel's Digital Metadata. Any keys passed in 'metadata' tags should be included in the `metadata` argument at initialization to ensure that they always exist in the Digital Metadata. """ dtype = np.dtype(dtype) # create structured dtype for interleaved samples if necessary if is_complex and ( not np.issubdtype(dtype, np.complexfloating) and not dtype.names ): realdtype = dtype dtype = np.dtype([("r", realdtype), ("i", realdtype)]) if num_subchannels == 1: in_sig = [dtype] else: in_sig = [(dtype, num_subchannels)] gr.sync_block.__init__( self, name="digital_rf_channel_sink", in_sig=in_sig, out_sig=None ) self._channel_dir = channel_dir self._channel_name = os.path.basename(channel_dir) self._dtype = dtype self._subdir_cadence_secs = subdir_cadence_secs self._file_cadence_millisecs = file_cadence_millisecs self._sample_rate_numerator = sample_rate_numerator self._sample_rate_denominator = sample_rate_denominator self._uuid_str = uuid_str self._ignore_tags = ignore_tags self._is_complex = is_complex self._num_subchannels = num_subchannels self._is_continuous = is_continuous self._compression_level = compression_level self._checksum = checksum self._marching_periods = marching_periods self._stop_on_skipped = stop_on_skipped self._stop_on_time_tag = stop_on_time_tag self._debug = debug self._work_done = False self._samples_per_second = np.longdouble( np.uint64(sample_rate_numerator) ) / np.longdouble(np.uint64(sample_rate_denominator)) if min_chunksize is None: self._min_chunksize = max(int(self._samples_per_second // 1000), 1) else: self._min_chunksize = min_chunksize # reduce CPU usage by setting a minimum number of samples to handle # at once # (really want to set_min_noutput_items, but no way to do that from # Python) try: self.set_output_multiple(self._min_chunksize) except RuntimeError: traceback.print_exc() errstr = "Failed to set sink block min_chunksize to {min_chunksize}." if min_chunksize is None: errstr += ( " This value was calculated automatically based on the sample rate." " You may have to specify min_chunksize manually." ) raise ValueError(errstr.format(min_chunksize=self._min_chunksize)) # will be None if start is None or '' self._start_sample = util.parse_identifier_to_sample( start, self._samples_per_second, None ) if self._start_sample is None: if self._ignore_tags: raise ValueError("Must specify start if ignore_tags is True.") # data without a time tag will be written starting at global index # of 0, i.e. the Unix epoch # we don't want to guess the start time because the user would # know better and it could obscure bugs by setting approximately # the correct time (samples in 1970 are immediately obvious) self._start_sample = 0 self._next_rel_sample = 0 if self._debug: tidx = self._start_sample timedelta = util.samples_to_timedelta(tidx, self._samples_per_second) tsec = int(timedelta.total_seconds() // 1) tfrac = timedelta.microseconds / 1e6 tagstr = ("|{0}|start @ sample 0: {1}+{2} ({3})\n").format( self._channel_name, tsec, tfrac, tidx ) sys.stdout.write(tagstr) sys.stdout.flush() # stream tags to read (in addition to rx_time, handled specially) self._stream_tag_translators = { # disable rx_freq until we figure out what to do with polyphase # also, USRP source in gr < 3.7.12 has bad rx_freq tags # pmt.intern('rx_freq'): translate_rx_freq, pmt.intern("metadata"): translate_metadata } # create metadata dictionary that will be updated and written whenever # new metadata is received in stream tags if metadata is None: metadata = {} self._metadata = metadata.copy() if not center_frequencies: center_frequencies = np.array([0.0] * self._num_subchannels) else: center_frequencies = np.ascontiguousarray(center_frequencies) self._metadata.update( # standard metadata by convention uuid_str="", sample_rate_numerator=self._sample_rate_numerator, sample_rate_denominator=self._sample_rate_denominator, center_frequencies=center_frequencies, ) # create directories for RF data channel and metadata self._metadata_dir = os.path.join(self._channel_dir, "metadata") if not os.path.exists(self._metadata_dir): os.makedirs(self._metadata_dir) # sets self._Writer, self._DMDWriter, and adds to self._metadata self._create_writer() # dict of metadata samples to be written, add for first sample # keys: absolute sample index for metadata # values: metadata dictionary to update self._metadata and then write self._md_queue = defaultdict(dict) self._md_queue[self._start_sample] = {} def _create_writer(self): # Digital RF writer self._Writer = DigitalRFWriter( self._channel_dir, self._dtype, self._subdir_cadence_secs, self._file_cadence_millisecs, self._start_sample, self._sample_rate_numerator, self._sample_rate_denominator, uuid_str=self._uuid_str, compression_level=self._compression_level, checksum=self._checksum, is_complex=self._is_complex, num_subchannels=self._num_subchannels, is_continuous=self._is_continuous, marching_periods=self._marching_periods, ) # update UUID in metadata after parsing by DigitalRFWriter self._metadata.update(uuid_str=self._Writer.uuid) # Digital Metadata writer self._DMDWriter = DigitalMetadataWriter( metadata_dir=self._metadata_dir, subdir_cadence_secs=self._subdir_cadence_secs, file_cadence_secs=1, sample_rate_numerator=self._sample_rate_numerator, sample_rate_denominator=self._sample_rate_denominator, file_name="metadata", ) def _read_tags(self, nsamples): """Read stream tags and set data blocks and metadata to write. Metadata from tags is added to the queue at ``self._md_queue``. """ nread = self.nitems_read(0) md_queue = self._md_queue # continue writing at next continuous sample with start of block # unless overridden by a time tag data_blk_idxs = [0] data_rel_samples = [self._next_rel_sample] # read time tags # get_tags_in_window convenience function is broken, so use get_tags_in_range time_tags = self.get_tags_in_range( 0, nread, nread + nsamples, pmt.intern("rx_time") ) if time_tags and self._stop_on_time_tag and self._next_rel_sample != 0: self._work_done = True # separate data into blocks to be written for tag in time_tags: offset = tag.offset tsec, tfrac, tidx = parse_time_pmt(tag.value, self._samples_per_second) # index into data block for this tag bidx = offset - nread # get sample index relative to start sidx = tidx - self._start_sample # add new data block if valid and it indicates a gap prev_bidx = data_blk_idxs[-1] prev_sidx = data_rel_samples[-1] next_continuous_sample = prev_sidx + (bidx - prev_bidx) if sidx < next_continuous_sample: if self._debug: errstr = ( "\n|{0}|rx_time tag @ sample {1}: {2}+{3} ({4})" "\n INVALID: time cannot go backwards from index {5}." " Skipping." ).format( self._channel_name, offset, tsec, tfrac, tidx, self._start_sample + next_continuous_sample, ) sys.stdout.write(errstr) sys.stdout.flush() continue elif sidx == next_continuous_sample: # don't create a new block because it's continuous if self._debug: tagstr = ("\n|{0}|rx_time tag @ sample {1}: {2}+{3} ({4})").format( self._channel_name, offset, tsec, tfrac, tidx ) sys.stdout.write(tagstr) sys.stdout.flush() continue else: # add new block to write based on time tag if self._debug: tagstr = ( "\n|{0}|rx_time tag @ sample {1}: {2}+{3} ({4})" "\n {5} dropped samples." ).format( self._channel_name, offset, tsec, tfrac, tidx, sidx - next_continuous_sample, ) sys.stdout.write(tagstr) sys.stdout.flush() # set flag to stop work when stop_on_skipped is set if self._stop_on_skipped and self._next_rel_sample != 0: self._work_done = True if bidx == 0: # override assumed continuous write # data_blk_idxs[0] is already 0 data_rel_samples[0] = sidx else: data_blk_idxs.append(bidx) data_rel_samples.append(sidx) # reset metadata queue with only valid values for md_idx in list(md_queue.keys()): md_sidx = md_idx - self._start_sample if next_continuous_sample <= md_sidx and md_sidx < sidx: del md_queue[md_idx] # new metadata sample to help flag data skip md_queue.setdefault(sidx + self._start_sample, {}) # read other tags by data block (so we know the sample index) for (bidx, bend), sidx in zip( pairwise(chain(data_blk_idxs, (nsamples,))), data_rel_samples ): tags_by_offset = {} # read tags, translate to metadata dict, add to tag dict for tag_name, translator in self._stream_tag_translators.items(): tags = self.get_tags_in_range(0, nread + bidx, nread + bend, tag_name) collect_tags_in_dict(tags, translator, tags_by_offset) # add tags to metadata sample dictionary for offset, tag_dict in tags_by_offset.items(): mbidx = offset - nread # get the absolute sample index for the metadata sample msidx = (sidx + (mbidx - bidx)) + self._start_sample md_queue[msidx].update(tag_dict) return data_blk_idxs, data_rel_samples def work(self, input_items, output_items): in_data = input_items[0] nsamples = len(in_data) if not self._ignore_tags: # break data into blocks from time tags # get metadata from other tags and add to self._md_queue data_blk_idxs, data_rel_samples = self._read_tags(nsamples) else: # continue writing at next continuous sample with start of block data_blk_idxs = [0] data_rel_samples = [self._next_rel_sample] # make index lists into uint64 arrays data_rel_samples = np.array(data_rel_samples, dtype=np.uint64, ndmin=1) data_blk_idxs = np.array(data_blk_idxs, dtype=np.uint64, ndmin=1) # get any metadata samples to be written from queue if self._md_queue: md_samples, md_dict_updates = zip( *sorted(self._md_queue.items(), key=lambda x: x[0]) ) md_samples = np.array(md_samples, dtype=np.uint64, ndmin=1) # fill out metadata to be written using stored metadata md_dicts = [ # function updates self._metadata in-place, want copy for list # to preserve the updated values at that particular state recursive_dict_update(self._metadata, md_update).copy() for md_update in md_dict_updates ] else: md_samples = [] md_dicts = [] self._md_queue.clear() # check if work_done has been flagged (stop on skipped or time tag) if self._work_done: if ( data_rel_samples[0] == self._next_rel_sample or self._next_rel_sample == 0 ): # write continuous data from this chunk first last_rel_sample = _py_rf_write_hdf5.rf_block_write( self._Writer._channelObj, in_data, data_rel_samples[:1], data_blk_idxs[:1], ) last_sample = last_rel_sample + self._start_sample idx = np.searchsorted(md_samples, last_sample, "right") for md_sample, md_dict in zip(md_samples[:idx], md_dicts[:idx]): self._DMDWriter.write(md_sample, md_dict) print("Stopping as requested.") # return WORK_DONE return -1 try: # write metadata if md_dicts: self._DMDWriter.write(md_samples, md_dicts) # write data using block writer self._next_rel_sample = _py_rf_write_hdf5.rf_block_write( self._Writer._channelObj, in_data, data_rel_samples, data_blk_idxs ) except (IOError, RuntimeError): # just print the exception so we can return WORK_DONE to notify # other blocks to shut down cleanly traceback.print_exc() errstr = ( "\n************************************************************" "\nWriting data failed in 'rf_block_write' with state:" "\n\tself._start_sample = {start_sample}" "\n\tself._next_rel_sample = {next_rel_sample}" "\nand inputs (in_data, data_rel_samples, data_blk_idxs):" "\n\tdata_rel_samples = {data_rel_samples}" "\n\tdata_blk_idxs = {data_blk_idxs}" "\n\tin_data.dtype = {dtype}" "\n\tin_data.shape = {shape}" "\n\tin_data[:10] = {head}" "\n************************************************************" ).format( start_sample=self._start_sample, next_rel_sample=self._next_rel_sample, dtype=in_data.dtype, shape=in_data.shape, head=in_data[:10], data_rel_samples=data_rel_samples, data_blk_idxs=data_blk_idxs, ) print(errstr) return -1 return nsamples def stop(self): if self._Writer is not None: self._Writer.close() return super(digital_rf_channel_sink, self).stop() def get_debug(self): return self._debug def set_debug(self, debug): self._debug = debug def get_ignore_tags(self): return self._ignore_tags def set_ignore_tags(self, ignore_tags): self._ignore_tags = ignore_tags def get_stop_on_skipped(self): return self._stop_on_skipped def set_stop_on_skipped(self, stop_on_skipped): self._stop_on_skipped = stop_on_skipped def get_stop_on_time_tag(self): return self._stop_on_time_tag def set_stop_on_time_tag(self, stop_on_time_tag): self._stop_on_time_tag = stop_on_time_tag class digital_rf_sink(gr.hier_block2): """Sink block for writing Digital RF data.""" def __init__( self, top_level_dir, channels, dtype, subdir_cadence_secs, file_cadence_millisecs, sample_rate_numerator, sample_rate_denominator, start=None, ignore_tags=False, is_complex=True, num_subchannels=1, uuid_str=None, center_frequencies=None, metadata=None, is_continuous=True, compression_level=0, checksum=False, marching_periods=True, stop_on_skipped=False, stop_on_time_tag=False, debug=False, min_chunksize=None, ): """Write data in Digital RF format. This block is useful for writing multiple channels of data that have the same parameters. If different parameters for each channel are needed, use multiple `digital_rf_channel_sink` blocks. In addition to storing the input samples in Digital RF format, this block also populates each channel's accompanying Digital Metadata at the sample indices when the metadata changes or a data skip occurs. See the Notes section for details on what metadata is stored. Parameters ---------- top_level_dir : string The top-level directory in which Digital RF channel directories will be created. It will be created if it does not exist. channels : list of strings | string List of channel names with length matching the number of channels to be written (and the number of inputs). Each channel name will be used as the directory name for the channel inside `top_level_dir`. If a string, a single channel will be written with that name. dtype : np.dtype | object to be cast by np.dtype() Object that gives the numpy dtype of the data to be written. This value is passed into ``np.dtype`` to get the actual dtype (e.g. ``np.dtype('>i4')``). Scalar types, complex types, and structured complex types with 'r' and 'i' fields of scalar types are valid. subdir_cadence_secs : int The number of seconds of data to store in one subdirectory. The timestamp of any subdirectory will be an integer multiple of this value. file_cadence_millisecs : int The number of milliseconds of data to store in each file. Note that an integer number of files must exactly span a subdirectory, implying:: (subdir_cadence_secs*1000 % file_cadence_millisecs) == 0 sample_rate_numerator : int Numerator of sample rate in Hz. sample_rate_denominator : int Denominator of sample rate in Hz. Other Parameters ---------------- start : None | int | float | string, optional A value giving the time/index of the channel's first sample. When `ignore_tags` is False, 'rx_time' tags will be used to identify data gaps and skip the sample index forward appropriately (tags that refer to an earlier time will be ignored). If None or '' and `ignore_tags` is False, a default value of 0 is used (a ValueError is raised if `ignore_tags` is True). If an integer, it is interpreted as a sample index given in the number of samples since the epoch (time_since_epoch*sample_rate). If a float, it is interpreted as a UTC timestamp (seconds since epoch). If a string, three forms are permitted: 1) a string which can be evaluated to an integer/float and interpreted as above, 2) a time in ISO8601 format, e.g. '2016-01-01T16:24:00Z' 3) 'now' ('nowish'), indicating the current time (rounded up) ignore_tags : bool, optional If True, do not use 'rx_time' tags to set the sample index and do not write other tags as Digital Metadata. is_complex : bool, optional This parameter is only used when `dtype` is not complex. If True (the default), interpret supplied data as interleaved complex I/Q samples. If False, each sample has a single value. num_subchannels : int, optional Number of subchannels to write simultaneously. Default is 1. uuid_str : None | string, optional UUID string that will act as a unique identifier for the data and can be used to tie the data files to metadata. If None, a random UUID will be generated. center_frequencies : None | array_like of floats, optional List of subchannel center frequencies to include in initial metadata. If None, ``[0.0]*num_subchannels`` will be used. Subsequent center frequency metadata samples can be written using 'rx_freq' stream tags. metadata : dict, optional Dictionary of additional metadata to include in initial Digital Metadata sample. Subsequent metadata samples can be written using 'metadata' stream tags, but all keys intended to be included should be set here first even if their values are empty. is_continuous : bool, optional If True, data will be written in continuous blocks. If False data will be written with gapped blocks. Fastest write/read speed is achieved with `is_continuous` True, `checksum` False, and `compression_level` 0 (all defaults). compression_level : int, optional 0 for no compression (default), 1-9 for varying levels of gzip compression (1 == least compression, least CPU; 9 == most compression, most CPU). checksum : bool, optional If True, use HDF5 checksum capability. If False (default), no checksum. marching_periods : bool, optional If True, write a period to stdout for every subdirectory when writing. stop_on_skipped : bool, optional If True, stop writing when a sample would be skipped (such as from a dropped packet). stop_on_time_tag : bool, optional If True, stop writing when any but an initial 'rx_time' tag is received. debug : bool, optional If True, print debugging information. min_chunksize : None | int, optional Minimum number of samples to consume at once. This value can be used to adjust the sink's performance to reduce processing time. If None, a sensible default will be used. Notes ----- By convention, this block sets the following Digital Metadata fields: uuid_str : string Value provided by the `uuid_str` argument. sample_rate_numerator : int Value provided by the `sample_rate_numerator` argument. sample_rate_denominator : int Value provided by the `sample_rate_denominator` argument. center_frequencies : list of floats with length `num_subchannels` Subchannel center frequencies as specified by `center_frequencies` argument and 'rx_rate' stream tags. Additional metadata fields can be set using the `metadata` argument and stream tags. Nested dictionaries are permitted and are helpful for grouping properties. For example, receiver-specific metadata is typically specified with a sub-dictionary using the 'receiver' field. This block acts on the following stream tags when `ignore_tags` is False: rx_time : (int secs, float frac) tuple Used to set the sample index from the given time since epoch. rx_freq : float Used to set the 'center_frequencies' value in the channel's Digital Metadata as described above. metadata : dict Used to populate additional (key, value) pairs in the channel's Digital Metadata. Any keys passed in 'metadata' tags should be included in the `metadata` argument at initialization to ensure that they always exist in the Digital Metadata. """ options = locals() del options["self"] del options["top_level_dir"] del options["channels"] self._top_level_dir = os.path.abspath(top_level_dir) if isinstance(channels, six.string_types): channels = [channels] self._channel_names = channels # make sinks for every channel self._channels = [] for ch in self._channel_names: channel_dir = os.path.join(self._top_level_dir, ch) chsink = digital_rf_channel_sink(channel_dir, **options) self._channels.append(chsink) in_sig_dtypes = [list(sink.in_sig())[0] for sink in self._channels] in_sig = gr.io_signaturev( len(in_sig_dtypes), len(in_sig_dtypes), [s.itemsize for s in in_sig_dtypes] ) out_sig = gr.io_signature(0, 0, 0) gr.hier_block2.__init__( self, name="digital_rf_sink", input_signature=in_sig, output_signature=out_sig, ) for k, sink in enumerate(self._channels): self.connect((self, k), sink) def get_debug(self): return self._channels[0].get_debug() def set_debug(self, debug): for ch in self._channels: ch.set_debug(debug) def get_ignore_tags(self): return self._channels[0].ignore_tags() def set_ignore_tags(self, ignore_tags): for ch in self._channels: ch.set_ignore_tags(ignore_tags) def get_stop_on_skipped(self): return self._channels[0].get_stop_on_skipped() def set_stop_on_skipped(self, stop_on_skipped): for ch in self._channels: ch.set_stop_on_skipped(stop_on_skipped) def get_stop_on_time_tag(self): return self._channels[0].get_stop_on_time_tag() def set_stop_on_time_tag(self, stop_on_time_tag): for ch in self._channels: ch.set_stop_on_time_tag(stop_on_time_tag)
{ fns.push(function() { return i; }); if (i === 1) { return "continue"; } else if (i === 2) { return "break"; } else if (i === 3) { return { v: i }; } }
from rest_framework.permissions import IsAuthenticated, IsAdminUser from bible.helpers import add_reading, cache_todays_reading, get_reading, delete_reading from orlem_connect.settings import STATIC_DIR from rest_framework.response import Response from rest_framework.views import APIView from django.shortcuts import render import pandas as pd import json # Create your views here. ''' Today's reading cached ''' TODAY_READINGS = False ### bible api, currently, the entire bible '''class Bible(APIView): permission_classes = () def get(self, request): df = pd.read_csv(STATIC_DIR / 'res/nrsv.csv') # res = df.head().to_json(orient='records') return Response(df.to_json())''' ### gets or sets today's reading class ReadingsToday(APIView): permission_classes = () def get(self, request): global TODAY_READINGS if not TODAY_READINGS: TODAY_READINGS = cache_todays_reading() return Response(TODAY_READINGS) class Readings(APIView): permission_classes = () def get(self, request, year, month, day): date = "%d-%d-%d"%(int(year), int(month), int(day)) result = get_reading(date) return Response(result) def post(self, request, year, month, day): global TODAY_READINGS date = "%d-%d-%d"%(int(year), int(month), int(day)) #if request.user.is_staff and request.user.is_authenticated: if True: reading = request.data["reading"] book = request.data["book"] content = request.data["content"] result = add_reading(date, reading, book, content) TODAY_READINGS = cache_todays_reading() return Response(result) return Response(False) def delete(self, request, year, month, day, reading="*"): global TODAY_READINGS date = "%d-%d-%d"%(int(year), int(month), int(day)) if True: result = delete_reading(date, reading) TODAY_READINGS = cache_todays_reading() return Response(result) return Response(False)
#ifndef _MTYPES_H_ #define _MTYPES_H_ /* StargateTestAudio 1 StargateTestVideo 2 StargateTestImage 3 */ bool StargateTestAudio (uint8_t value) { return value == 1; } bool StargateTestVideo (uint8_t value) { return value == 2; } bool TestVideo (uint8_t value) { return FALSE; } bool TestAudio (uint8_t value) { return FALSE; } bool StargateTestImage (uint8_t value) { return value == 3; } bool TestImage (uint8_t value) { return FALSE; } bool TestText (uint8_t value) { return FALSE; } #endif // _MTYPES_H_
# -*- coding: utf-8 -*- # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from bricks.openstack.common import gettextutils gettextutils.install('bricks')
"""This module contains the general information for PkiEp ManagedObject.""" from ...ucscmo import ManagedObject from ...ucsccoremeta import UcscVersion, MoPropertyMeta, MoMeta from ...ucscmeta import VersionMeta class PkiEpConsts(): FSM_PREV_NOP = "nop" FSM_PREV_UPDATE_EP_BEGIN = "updateEpBegin" FSM_PREV_UPDATE_EP_FAIL = "updateEpFail" FSM_PREV_UPDATE_EP_SET_CERT_CONF_LOCAL = "updateEpSetCertConfLocal" FSM_PREV_UPDATE_EP_SUCCESS = "updateEpSuccess" FSM_RMT_INV_ERR_CODE_ERR_DIAG_CANCELLED = "ERR-DIAG-cancelled" FSM_RMT_INV_ERR_CODE_ERR_DIAG_FSM_RESTARTED = "ERR-DIAG-fsm-restarted" FSM_RMT_INV_ERR_CODE_ERR_DIAG_TEST_FAILED = "ERR-DIAG-test-failed" FSM_RMT_INV_ERR_CODE_ERR_DNLD_AUTHENTICATION_FAILURE = "ERR-DNLD-authentication-failure" FSM_RMT_INV_ERR_CODE_ERR_DNLD_ERROR = "ERR-DNLD-error" FSM_RMT_INV_ERR_CODE_ERR_DNLD_HOSTKEY_MISMATCH = "ERR-DNLD-hostkey-mismatch" FSM_RMT_INV_ERR_CODE_ERR_DNLD_INVALID_IMAGE = "ERR-DNLD-invalid-image" FSM_RMT_INV_ERR_CODE_ERR_DNLD_NO_FILE = "ERR-DNLD-no-file" FSM_RMT_INV_ERR_CODE_ERR_DNLD_NO_SPACE = "ERR-DNLD-no-space" FSM_RMT_INV_ERR_CODE_ERR_DNS_DELETE_ERROR = "ERR-DNS-delete-error" FSM_RMT_INV_ERR_CODE_ERR_DNS_GET_ERROR = "ERR-DNS-get-error" FSM_RMT_INV_ERR_CODE_ERR_DNS_SET_ERROR = "ERR-DNS-set-error" FSM_RMT_INV_ERR_CODE_ERR_DIGEST_VALIDATION_ERROR = "ERR-Digest-Validation-error" FSM_RMT_INV_ERR_CODE_ERR_EXEC_GEN_CERT_ERROR = "ERR-Exec-Gen-Cert-error" FSM_RMT_INV_ERR_CODE_ERR_EXEC_GET_CA_CERT_ERROR = "ERR-Exec-Get-CA-Cert-error" FSM_RMT_INV_ERR_CODE_ERR_FILTER_ILLEGAL_FORMAT = "ERR-FILTER-illegal-format" FSM_RMT_INV_ERR_CODE_ERR_FSM_NO_SUCH_STATE = "ERR-FSM-no-such-state" FSM_RMT_INV_ERR_CODE_ERR_GET_CA_CERT_ERROR = "ERR-Get-CA-Cert-error" FSM_RMT_INV_ERR_CODE_ERR_GET_CERT_ERROR = "ERR-Get-Cert-error" FSM_RMT_INV_ERR_CODE_ERR_GET_OUT_DIGET_MESSAGE_ERROR = "ERR-Get-Out-Diget-Message-error" FSM_RMT_INV_ERR_CODE_ERR_HTTP_REQUEST_ERROR = "ERR-HTTP-Request-error" FSM_RMT_INV_ERR_CODE_ERR_HTTP_SET_ERROR = "ERR-HTTP-set-error" FSM_RMT_INV_ERR_CODE_ERR_HTTPS_SET_ERROR = "ERR-HTTPS-set-error" FSM_RMT_INV_ERR_CODE_ERR_IPV6_ADDR_CONFIGURED = "ERR-Ipv6-addr-configured" FSM_RMT_INV_ERR_CODE_ERR_MO_CONFIG_CHILD_OBJECT_CANT_BE_CONFIGURED = "ERR-MO-CONFIG-child-object-cant-be-configured" FSM_RMT_INV_ERR_CODE_ERR_MO_META_NO_SUCH_OBJECT_CLASS = "ERR-MO-META-no-such-object-class" FSM_RMT_INV_ERR_CODE_ERR_MO_PROPERTY_NO_SUCH_PROPERTY = "ERR-MO-PROPERTY-no-such-property" FSM_RMT_INV_ERR_CODE_ERR_MO_PROPERTY_VALUE_OUT_OF_RANGE = "ERR-MO-PROPERTY-value-out-of-range" FSM_RMT_INV_ERR_CODE_ERR_MO_ACCESS_DENIED = "ERR-MO-access-denied" FSM_RMT_INV_ERR_CODE_ERR_MO_DELETION_RULE_VIOLATION = "ERR-MO-deletion-rule-violation" FSM_RMT_INV_ERR_CODE_ERR_MO_DUPLICATE_OBJECT = "ERR-MO-duplicate-object" FSM_RMT_INV_ERR_CODE_ERR_MO_ILLEGAL_CONTAINMENT = "ERR-MO-illegal-containment" FSM_RMT_INV_ERR_CODE_ERR_MO_ILLEGAL_CREATION = "ERR-MO-illegal-creation" FSM_RMT_INV_ERR_CODE_ERR_MO_ILLEGAL_ITERATOR_STATE = "ERR-MO-illegal-iterator-state" FSM_RMT_INV_ERR_CODE_ERR_MO_ILLEGAL_OBJECT_LIFECYCLE_TRANSITION = "ERR-MO-illegal-object-lifecycle-transition" FSM_RMT_INV_ERR_CODE_ERR_MO_NAMING_RULE_VIOLATION = "ERR-MO-naming-rule-violation" FSM_RMT_INV_ERR_CODE_ERR_MO_OBJECT_NOT_FOUND = "ERR-MO-object-not-found" FSM_RMT_INV_ERR_CODE_ERR_MO_RESOURCE_ALLOCATION = "ERR-MO-resource-allocation" FSM_RMT_INV_ERR_CODE_ERR_NTP_DELETE_ERROR = "ERR-NTP-delete-error" FSM_RMT_INV_ERR_CODE_ERR_NTP_GET_ERROR = "ERR-NTP-get-error" FSM_RMT_INV_ERR_CODE_ERR_NTP_SET_ERROR = "ERR-NTP-set-error" FSM_RMT_INV_ERR_CODE_ERR_POLICY_RESOLUTION_IN_PROGRESS = "ERR-Policy-resolution-in-progress" FSM_RMT_INV_ERR_CODE_ERR_TOKEN_REQUEST_DENIED = "ERR-TOKEN-request-denied" FSM_RMT_INV_ERR_CODE_ERR_UPDATE_VM_IP_MASK_GATEWAY_ERROR = "ERR-Update-VM-IP-Mask-Gateway-error" FSM_RMT_INV_ERR_CODE_ERR_AAA_CONFIG_MODIFY_ERROR = "ERR-aaa-config-modify-error" FSM_RMT_INV_ERR_CODE_ERR_ACCT_REALM_SET_ERROR = "ERR-acct-realm-set-error" FSM_RMT_INV_ERR_CODE_ERR_ADMIN_PASSWD_SET = "ERR-admin-passwd-set" FSM_RMT_INV_ERR_CODE_ERR_AUTH_REALM_SET_ERROR = "ERR-auth-realm-set-error" FSM_RMT_INV_ERR_CODE_ERR_AUTHENTICATION = "ERR-authentication" FSM_RMT_INV_ERR_CODE_ERR_AUTHORIZATION_REQUIRED = "ERR-authorization-required" FSM_RMT_INV_ERR_CODE_ERR_CREATE_CHASSISPACK_UNDER_DG = "ERR-create-chassispack-under-dg" FSM_RMT_INV_ERR_CODE_ERR_CREATE_HFP_UNDER_DG = "ERR-create-hfp-under-dg" FSM_RMT_INV_ERR_CODE_ERR_CREATE_KEYRING = "ERR-create-keyring" FSM_RMT_INV_ERR_CODE_ERR_CREATE_LOCALE = "ERR-create-locale" FSM_RMT_INV_ERR_CODE_ERR_CREATE_ROLE = "ERR-create-role" FSM_RMT_INV_ERR_CODE_ERR_CREATE_USER = "ERR-create-user" FSM_RMT_INV_ERR_CODE_ERR_DELETE_LOCALE = "ERR-delete-locale" FSM_RMT_INV_ERR_CODE_ERR_DELETE_ROLE = "ERR-delete-role" FSM_RMT_INV_ERR_CODE_ERR_DELETE_SESSION = "ERR-delete-session" FSM_RMT_INV_ERR_CODE_ERR_DELETE_USER = "ERR-delete-user" FSM_RMT_INV_ERR_CODE_ERR_ESTIMATE_IMPACT_ON_RECONNECT = "ERR-estimate-impact-on-reconnect" FSM_RMT_INV_ERR_CODE_ERR_GET_MAX_HTTP_USER_SESSIONS = "ERR-get-max-http-user-sessions" FSM_RMT_INV_ERR_CODE_ERR_HTTP_INITIALIZING = "ERR-http-initializing" FSM_RMT_INV_ERR_CODE_ERR_INTERNAL_ERROR = "ERR-internal-error" FSM_RMT_INV_ERR_CODE_ERR_LDAP_DELETE_ERROR = "ERR-ldap-delete-error" FSM_RMT_INV_ERR_CODE_ERR_LDAP_GET_ERROR = "ERR-ldap-get-error" FSM_RMT_INV_ERR_CODE_ERR_LDAP_GROUP_MODIFY_ERROR = "ERR-ldap-group-modify-error" FSM_RMT_INV_ERR_CODE_ERR_LDAP_GROUP_SET_ERROR = "ERR-ldap-group-set-error" FSM_RMT_INV_ERR_CODE_ERR_LDAP_SET_ERROR = "ERR-ldap-set-error" FSM_RMT_INV_ERR_CODE_ERR_LOCALE_SET_ERROR = "ERR-locale-set-error" FSM_RMT_INV_ERR_CODE_ERR_MAX_USERID_SESSIONS_REACHED = "ERR-max-userid-sessions-reached" FSM_RMT_INV_ERR_CODE_ERR_MODIFY_LOCALE = "ERR-modify-locale" FSM_RMT_INV_ERR_CODE_ERR_MODIFY_ROLE = "ERR-modify-role" FSM_RMT_INV_ERR_CODE_ERR_MODIFY_USER = "ERR-modify-user" FSM_RMT_INV_ERR_CODE_ERR_MODIFY_USER_LOCALE = "ERR-modify-user-locale" FSM_RMT_INV_ERR_CODE_ERR_MODIFY_USER_ROLE = "ERR-modify-user-role" FSM_RMT_INV_ERR_CODE_ERR_NFS_DOWN = "ERR-nfs-down" FSM_RMT_INV_ERR_CODE_ERR_PROVIDER_GROUP_MODIFY_ERROR = "ERR-provider-group-modify-error" FSM_RMT_INV_ERR_CODE_ERR_PROVIDER_GROUP_SET_ERROR = "ERR-provider-group-set-error" FSM_RMT_INV_ERR_CODE_ERR_RADIUS_GLOBAL_SET_ERROR = "ERR-radius-global-set-error" FSM_RMT_INV_ERR_CODE_ERR_RADIUS_GROUP_SET_ERROR = "ERR-radius-group-set-error" FSM_RMT_INV_ERR_CODE_ERR_RADIUS_SET_ERROR = "ERR-radius-set-error" FSM_RMT_INV_ERR_CODE_ERR_ROLE_SET_ERROR = "ERR-role-set-error" FSM_RMT_INV_ERR_CODE_ERR_SERVICE_NOT_READY = "ERR-service-not-ready" FSM_RMT_INV_ERR_CODE_ERR_SESSION_CACHE_FULL = "ERR-session-cache-full" FSM_RMT_INV_ERR_CODE_ERR_SESSION_NOT_FOUND = "ERR-session-not-found" FSM_RMT_INV_ERR_CODE_ERR_SET_PASSWORD_STRENGTH_CHECK = "ERR-set-password-strength-check" FSM_RMT_INV_ERR_CODE_ERR_TACACS_ENABLE_ERROR = "ERR-tacacs-enable-error" FSM_RMT_INV_ERR_CODE_ERR_TACACS_GLOBAL_SET_ERROR = "ERR-tacacs-global-set-error" FSM_RMT_INV_ERR_CODE_ERR_TACACS_GROUP_SET_ERROR = "ERR-tacacs-group-set-error" FSM_RMT_INV_ERR_CODE_ERR_TACACS_SET_ERROR = "ERR-tacacs-set-error" FSM_RMT_INV_ERR_CODE_ERR_TIMEZONE_SET_ERROR = "ERR-timezone-set-error" FSM_RMT_INV_ERR_CODE_ERR_USER_ACCOUNT_EXPIRED = "ERR-user-account-expired" FSM_RMT_INV_ERR_CODE_ERR_USER_SET_ERROR = "ERR-user-set-error" FSM_RMT_INV_ERR_CODE_NONE = "none" FSM_STAMP_NEVER = "never" FSM_STATUS_NOP = "nop" FSM_STATUS_UPDATE_EP_BEGIN = "updateEpBegin" FSM_STATUS_UPDATE_EP_FAIL = "updateEpFail" FSM_STATUS_UPDATE_EP_SET_CERT_CONF_LOCAL = "updateEpSetCertConfLocal" FSM_STATUS_UPDATE_EP_SUCCESS = "updateEpSuccess" INT_ID_NONE = "none" POLICY_OWNER_LOCAL = "local" POLICY_OWNER_PENDING_POLICY = "pending-policy" POLICY_OWNER_POLICY = "policy" POLICY_OWNER_UNSPECIFIED = "unspecified" class PkiEp(ManagedObject): """This is PkiEp class.""" consts = PkiEpConsts() naming_props = set([]) mo_meta = MoMeta("PkiEp", "pkiEp", "pki-ext", VersionMeta.Version101a, "InputOutput", 0x3f, [], ["aaa", "admin"], [u'policyDeviceProfile', u'topSystem'], [u'eventInst', u'faultInst', u'pkiEpFsm', u'pkiEpFsmTask', u'pkiKeyRing', u'pkiTP'], ["Get"]) prop_meta = { "child_action": MoPropertyMeta("child_action", "childAction", "string", VersionMeta.Version101a, MoPropertyMeta.INTERNAL, None, None, None, r"""((deleteAll|ignore|deleteNonPresent),){0,2}(deleteAll|ignore|deleteNonPresent){0,1}""", [], []), "descr": MoPropertyMeta("descr", "descr", "string", VersionMeta.Version101a, MoPropertyMeta.READ_WRITE, 0x2, None, None, r"""[ !#$%&\(\)\*\+,\-\./:;\?@\[\]_\{\|\}~a-zA-Z0-9]{0,256}""", [], []), "dn": MoPropertyMeta("dn", "dn", "string", VersionMeta.Version101a, MoPropertyMeta.READ_ONLY, 0x4, 0, 256, None, [], []), "fsm_descr": MoPropertyMeta("fsm_descr", "fsmDescr", "string", VersionMeta.Version112a, MoPropertyMeta.INTERNAL, None, None, None, None, [], []), "fsm_prev": MoPropertyMeta("fsm_prev", "fsmPrev", "string", VersionMeta.Version112a, MoPropertyMeta.INTERNAL, None, None, None, None, ["nop", "updateEpBegin", "updateEpFail", "updateEpSetCertConfLocal", "updateEpSuccess"], []), "fsm_progr": MoPropertyMeta("fsm_progr", "fsmProgr", "byte", VersionMeta.Version112a, MoPropertyMeta.INTERNAL, None, None, None, None, [], ["0-100"]), "fsm_rmt_inv_err_code": MoPropertyMeta("fsm_rmt_inv_err_code", "fsmRmtInvErrCode", "string", VersionMeta.Version112a, MoPropertyMeta.INTERNAL, None, None, None, None, ["ERR-DIAG-cancelled", "ERR-DIAG-fsm-restarted", "ERR-DIAG-test-failed", "ERR-DNLD-authentication-failure", "ERR-DNLD-error", "ERR-DNLD-hostkey-mismatch", "ERR-DNLD-invalid-image", "ERR-DNLD-no-file", "ERR-DNLD-no-space", "ERR-DNS-delete-error", "ERR-DNS-get-error", "ERR-DNS-set-error", "ERR-Digest-Validation-error", "ERR-Exec-Gen-Cert-error", "ERR-Exec-Get-CA-Cert-error", "ERR-FILTER-illegal-format", "ERR-FSM-no-such-state", "ERR-Get-CA-Cert-error", "ERR-Get-Cert-error", "ERR-Get-Out-Diget-Message-error", "ERR-HTTP-Request-error", "ERR-HTTP-set-error", "ERR-HTTPS-set-error", "ERR-Ipv6-addr-configured", "ERR-MO-CONFIG-child-object-cant-be-configured", "ERR-MO-META-no-such-object-class", "ERR-MO-PROPERTY-no-such-property", "ERR-MO-PROPERTY-value-out-of-range", "ERR-MO-access-denied", "ERR-MO-deletion-rule-violation", "ERR-MO-duplicate-object", "ERR-MO-illegal-containment", "ERR-MO-illegal-creation", "ERR-MO-illegal-iterator-state", "ERR-MO-illegal-object-lifecycle-transition", "ERR-MO-naming-rule-violation", "ERR-MO-object-not-found", "ERR-MO-resource-allocation", "ERR-NTP-delete-error", "ERR-NTP-get-error", "ERR-NTP-set-error", "ERR-Policy-resolution-in-progress", "ERR-TOKEN-request-denied", "ERR-Update-VM-IP-Mask-Gateway-error", "ERR-aaa-config-modify-error", "ERR-acct-realm-set-error", "ERR-admin-passwd-set", "ERR-auth-realm-set-error", "ERR-authentication", "ERR-authorization-required", "ERR-create-chassispack-under-dg", "ERR-create-hfp-under-dg", "ERR-create-keyring", "ERR-create-locale", "ERR-create-role", "ERR-create-user", "ERR-delete-locale", "ERR-delete-role", "ERR-delete-session", "ERR-delete-user", "ERR-estimate-impact-on-reconnect", "ERR-get-max-http-user-sessions", "ERR-http-initializing", "ERR-internal-error", "ERR-ldap-delete-error", "ERR-ldap-get-error", "ERR-ldap-group-modify-error", "ERR-ldap-group-set-error", "ERR-ldap-set-error", "ERR-locale-set-error", "ERR-max-userid-sessions-reached", "ERR-modify-locale", "ERR-modify-role", "ERR-modify-user", "ERR-modify-user-locale", "ERR-modify-user-role", "ERR-nfs-down", "ERR-provider-group-modify-error", "ERR-provider-group-set-error", "ERR-radius-global-set-error", "ERR-radius-group-set-error", "ERR-radius-set-error", "ERR-role-set-error", "ERR-service-not-ready", "ERR-session-cache-full", "ERR-session-not-found", "ERR-set-password-strength-check", "ERR-tacacs-enable-error", "ERR-tacacs-global-set-error", "ERR-tacacs-group-set-error", "ERR-tacacs-set-error", "ERR-timezone-set-error", "ERR-user-account-expired", "ERR-user-set-error", "none"], ["0-4294967295"]), "fsm_rmt_inv_err_descr": MoPropertyMeta("fsm_rmt_inv_err_descr", "fsmRmtInvErrDescr", "string", VersionMeta.Version112a, MoPropertyMeta.INTERNAL, None, 0, 510, None, [], []), "fsm_rmt_inv_rslt": MoPropertyMeta("fsm_rmt_inv_rslt", "fsmRmtInvRslt", "string", VersionMeta.Version112a, MoPropertyMeta.INTERNAL, None, None, None, r"""((defaultValue|not-applicable|resource-unavailable|service-unavailable|intermittent-error|sw-defect|service-not-implemented-ignore|extend-timeout|capability-not-implemented-failure|illegal-fru|end-point-unavailable|failure|resource-capacity-exceeded|service-protocol-error|fw-defect|service-not-implemented-fail|task-reset|unidentified-fail|capability-not-supported|end-point-failed|fru-state-indeterminate|resource-dependency|fru-identity-indeterminate|internal-error|hw-defect|service-not-supported|fru-not-supported|end-point-protocol-error|capability-unavailable|fru-not-ready|capability-not-implemented-ignore|fru-info-malformed|timeout),){0,32}(defaultValue|not-applicable|resource-unavailable|service-unavailable|intermittent-error|sw-defect|service-not-implemented-ignore|extend-timeout|capability-not-implemented-failure|illegal-fru|end-point-unavailable|failure|resource-capacity-exceeded|service-protocol-error|fw-defect|service-not-implemented-fail|task-reset|unidentified-fail|capability-not-supported|end-point-failed|fru-state-indeterminate|resource-dependency|fru-identity-indeterminate|internal-error|hw-defect|service-not-supported|fru-not-supported|end-point-protocol-error|capability-unavailable|fru-not-ready|capability-not-implemented-ignore|fru-info-malformed|timeout){0,1}""", [], []), "fsm_stage_descr": MoPropertyMeta("fsm_stage_descr", "fsmStageDescr", "string", VersionMeta.Version112a, MoPropertyMeta.INTERNAL, None, None, None, None, [], []), "fsm_stamp": MoPropertyMeta("fsm_stamp", "fsmStamp", "string", VersionMeta.Version112a, MoPropertyMeta.INTERNAL, None, None, None, r"""([0-9]){4}-([0-9]){2}-([0-9]){2}T([0-9]){2}:([0-9]){2}:([0-9]){2}((\.([0-9]){3})){0,1}""", ["never"], []), "fsm_status": MoPropertyMeta("fsm_status", "fsmStatus", "string", VersionMeta.Version112a, MoPropertyMeta.INTERNAL, None, None, None, None, ["nop", "updateEpBegin", "updateEpFail", "updateEpSetCertConfLocal", "updateEpSuccess"], []), "fsm_try": MoPropertyMeta("fsm_try", "fsmTry", "byte", VersionMeta.Version112a, MoPropertyMeta.INTERNAL, None, None, None, None, [], []), "int_id": MoPropertyMeta("int_id", "intId", "string", VersionMeta.Version101a, MoPropertyMeta.INTERNAL, None, None, None, None, ["none"], ["0-4294967295"]), "name": MoPropertyMeta("name", "name", "string", VersionMeta.Version101a, MoPropertyMeta.CREATE_ONLY, 0x8, None, None, r"""[\-\.:_a-zA-Z0-9]{0,16}""", [], []), "policy_level": MoPropertyMeta("policy_level", "policyLevel", "uint", VersionMeta.Version101a, MoPropertyMeta.READ_ONLY, None, None, None, None, [], []), "policy_owner": MoPropertyMeta("policy_owner", "policyOwner", "string", VersionMeta.Version101a, MoPropertyMeta.READ_ONLY, None, None, None, None, ["local", "pending-policy", "policy", "unspecified"], []), "rn": MoPropertyMeta("rn", "rn", "string", VersionMeta.Version101a, MoPropertyMeta.READ_ONLY, 0x10, 0, 256, None, [], []), "status": MoPropertyMeta("status", "status", "string", VersionMeta.Version101a, MoPropertyMeta.READ_WRITE, 0x20, None, None, r"""((removed|created|modified|deleted),){0,3}(removed|created|modified|deleted){0,1}""", [], []), } prop_map = { "childAction": "child_action", "descr": "descr", "dn": "dn", "fsmDescr": "fsm_descr", "fsmPrev": "fsm_prev", "fsmProgr": "fsm_progr", "fsmRmtInvErrCode": "fsm_rmt_inv_err_code", "fsmRmtInvErrDescr": "fsm_rmt_inv_err_descr", "fsmRmtInvRslt": "fsm_rmt_inv_rslt", "fsmStageDescr": "fsm_stage_descr", "fsmStamp": "fsm_stamp", "fsmStatus": "fsm_status", "fsmTry": "fsm_try", "intId": "int_id", "name": "name", "policyLevel": "policy_level", "policyOwner": "policy_owner", "rn": "rn", "status": "status", } def __init__(self, parent_mo_or_dn, **kwargs): self._dirty_mask = 0 self.child_action = None self.descr = None self.fsm_descr = None self.fsm_prev = None self.fsm_progr = None self.fsm_rmt_inv_err_code = None self.fsm_rmt_inv_err_descr = None self.fsm_rmt_inv_rslt = None self.fsm_stage_descr = None self.fsm_stamp = None self.fsm_status = None self.fsm_try = None self.int_id = None self.name = None self.policy_level = None self.policy_owner = None self.status = None ManagedObject.__init__(self, "PkiEp", parent_mo_or_dn, **kwargs)
/* Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.lang['gl']={"wsc":{"btnIgnore":"Ignorar","btnIgnoreAll":"Ignorar Todas","btnReplace":"Substituir","btnReplaceAll":"Substituir Todas","btnUndo":"Desfacer","changeTo":"Cambiar a","errorLoading":"Error loading application Service host: %s.","ieSpellDownload":"O corrector ortográfico non está instalado. ¿Quere descargalo agora?","manyChanges":"Corrección ortográfica rematada: %1 verbas substituidas","noChanges":"Corrección ortográfica rematada: Non se substituiu nengunha verba","noMispell":"Corrección ortográfica rematada: Non se atoparon erros","noSuggestions":"- Sen candidatos -","notAvailable":"Sorry, but Service is unavailable now.","notInDic":"Non está no diccionario","oneChange":"Corrección ortográfica rematada: Unha verba substituida","progress":"Corrección ortográfica en progreso...","title":"Spell Checker","toolbar":"Corrección Ortográfica"},"undo":{"redo":"Refacer","undo":"Desfacer"},"toolbar":{"toolbarCollapse":"Contraer a barra de ferramentas","toolbarExpand":"Expandir a barra de ferramentas","toolbarGroups":{"document":"Documento","clipboard":"Portapapeis/desfacer","editing":"Edición","forms":"Formularios","basicstyles":"Estilos básicos","paragraph":"Paragrafo","links":"Ligazóns","insert":"Inserir","styles":"Estilos","colors":"Cores","tools":"Ferramentas"},"toolbars":"Barras de ferramentas do editor"},"table":{"border":"Tamaño do bordo","caption":"Título","cell":{"menu":"Cela","insertBefore":"Inserir a cela á esquerda","insertAfter":"Inserir a cela á dereita","deleteCell":"Eliminar celas","merge":"Combinar celas","mergeRight":"Combinar á dereita","mergeDown":"Combinar cara abaixo","splitHorizontal":"Dividir a cela en horizontal","splitVertical":"Dividir a cela en vertical","title":"Propiedades da cela","cellType":"Tipo de cela","rowSpan":"Expandir filas","colSpan":"Expandir columnas","wordWrap":"Axustar ao contido","hAlign":"Aliñación horizontal","vAlign":"Aliñación vertical","alignBaseline":"Liña de base","bgColor":"Cor do fondo","borderColor":"Cor do bordo","data":"Datos","header":"Cabeceira","yes":"Si","no":"Non","invalidWidth":"O largo da cela debe ser un número.","invalidHeight":"O alto da cela debe ser un número.","invalidRowSpan":"A expansión de filas debe ser un número enteiro.","invalidColSpan":"A expansión de columnas debe ser un número enteiro.","chooseColor":"Escoller"},"cellPad":"Marxe interior da cela","cellSpace":"Marxe entre celas","column":{"menu":"Columna","insertBefore":"Inserir a columna á esquerda","insertAfter":"Inserir a columna á dereita","deleteColumn":"Borrar Columnas"},"columns":"Columnas","deleteTable":"Borrar Táboa","headers":"Cabeceiras","headersBoth":"Ambas","headersColumn":"Primeira columna","headersNone":"Ningún","headersRow":"Primeira fila","invalidBorder":"O tamaño do bordo debe ser un número.","invalidCellPadding":"A marxe interior debe ser un número positivo.","invalidCellSpacing":"A marxe entre celas debe ser un número positivo.","invalidCols":"O número de columnas debe ser un número maior que 0.","invalidHeight":"O alto da táboa debe ser un número.","invalidRows":"O número de filas debe ser un número maior que 0","invalidWidth":"O largo da táboa debe ser un número.","menu":"Propiedades da táboa","row":{"menu":"Fila","insertBefore":"Inserir a fila por riba","insertAfter":"Inserir a fila por baixo","deleteRow":"Eliminar filas"},"rows":"Filas","summary":"Resumo","title":"Propiedades da táboa","toolbar":"Taboa","widthPc":"porcentaxe","widthPx":"píxeles","widthUnit":"unidade do largo"},"stylescombo":{"label":"Estilos","panelTitle":"Estilos de formatando","panelTitle1":"Estilos de bloque","panelTitle2":"Estilos de liña","panelTitle3":"Estilos de obxecto"},"specialchar":{"options":"Opcións de caracteres especiais","title":"Seleccione un carácter especial","toolbar":"Inserir un carácter especial"},"sourcearea":{"toolbar":"Orixe"},"scayt":{"btn_about":"About SCAYT","btn_dictionaries":"Dictionaries","btn_disable":"Disable SCAYT","btn_enable":"Enable SCAYT","btn_langs":"Languages","btn_options":"Options","text_title":"Spell Check As You Type"},"removeformat":{"toolbar":"Retirar o formato"},"pastetext":{"button":"Pegar como texto simple","pasteNotification":"O seu navegador non permite pegar texto simple deste xeito. Prema %1 para pegar."},"pastefromword":{"confirmCleanup":"O texto que quere pegar semella ser copiado desde o Word. Quere depuralo antes de pegalo?","error":"Non foi posíbel depurar os datos pegados por mor dun erro interno","title":"Pegar desde Word","toolbar":"Pegar desde Word"},"notification":{"closed":"Notificación pechada."},"maximize":{"maximize":"Maximizar","minimize":"Minimizar"},"magicline":{"title":"Inserir aquí o parágrafo"},"list":{"bulletedlist":"Inserir/retirar lista viñeteada","numberedlist":"Inserir/retirar lista numerada"},"link":{"acccessKey":"Chave de acceso","advanced":"Avanzado","advisoryContentType":"Tipo de contido informativo","advisoryTitle":"Título","anchor":{"toolbar":"Ancoraxe","menu":"Editar a ancoraxe","title":"Propiedades da ancoraxe","name":"Nome da ancoraxe","errorName":"Escriba o nome da ancoraxe","remove":"Retirar a ancoraxe"},"anchorId":"Polo ID do elemento","anchorName":"Polo nome da ancoraxe","charset":"Codificación do recurso ligado","cssClasses":"Clases da folla de estilos","download":"Forzar a descarga","displayText":"Amosar o texto","emailAddress":"Enderezo de correo","emailBody":"Corpo da mensaxe","emailSubject":"Asunto da mensaxe","id":"ID","info":"Información da ligazón","langCode":"Código do idioma","langDir":"Dirección de escritura do idioma","langDirLTR":"Esquerda a dereita (LTR)","langDirRTL":"Dereita a esquerda (RTL)","menu":"Editar a ligazón","name":"Nome","noAnchors":"(Non hai ancoraxes dispoñíbeis no documento)","noEmail":"Escriba o enderezo de correo","noUrl":"Escriba a ligazón URL","other":"<outro>","popupDependent":"Dependente (Netscape)","popupFeatures":"Características da xanela emerxente","popupFullScreen":"Pantalla completa (IE)","popupLeft":"Posición esquerda","popupLocationBar":"Barra de localización","popupMenuBar":"Barra do menú","popupResizable":"Redimensionábel","popupScrollBars":"Barras de desprazamento","popupStatusBar":"Barra de estado","popupToolbar":"Barra de ferramentas","popupTop":"Posición superior","rel":"Relación","selectAnchor":"Seleccionar unha ancoraxe","styles":"Estilo","tabIndex":"Índice de tabulación","target":"Destino","targetFrame":"<marco>","targetFrameName":"Nome do marco de destino","targetPopup":"<xanela emerxente>","targetPopupName":"Nome da xanela emerxente","title":"Ligazón","toAnchor":"Ligar coa ancoraxe no testo","toEmail":"Correo","toUrl":"URL","toolbar":"Ligazón","type":"Tipo de ligazón","unlink":"Eliminar a ligazón","upload":"Enviar"},"indent":{"indent":"Aumentar a sangría","outdent":"Reducir a sangría"},"image":{"alt":"Texto alternativo","border":"Bordo","btnUpload":"Enviar ao servidor","button2Img":"Quere converter o botón da imaxe seleccionada nunha imaxe sinxela?","hSpace":"Esp.Horiz.","img2Button":"Quere converter a imaxe seleccionada nun botón de imaxe?","infoTab":"Información da imaxe","linkTab":"Ligazón","lockRatio":"Proporcional","menu":"Propiedades da imaxe","resetSize":"Tamaño orixinal","title":"Propiedades da imaxe","titleButton":"Propiedades do botón de imaxe","upload":"Cargar","urlMissing":"Non se atopa o URL da imaxe.","vSpace":"Esp.Vert.","validateBorder":"O bordo debe ser un número.","validateHSpace":"O espazado horizontal debe ser un número.","validateVSpace":"O espazado vertical debe ser un número."},"horizontalrule":{"toolbar":"Inserir unha liña horizontal"},"format":{"label":"Formato","panelTitle":"Formato do parágrafo","tag_address":"Enderezo","tag_div":"Normal (DIV)","tag_h1":"Enacabezado 1","tag_h2":"Encabezado 2","tag_h3":"Encabezado 3","tag_h4":"Encabezado 4","tag_h5":"Encabezado 5","tag_h6":"Encabezado 6","tag_p":"Normal","tag_pre":"Formatado"},"fakeobjects":{"anchor":"Ancoraxe","flash":"Animación «Flash»","hiddenfield":"Campo agochado","iframe":"IFrame","unknown":"Obxecto descoñecido"},"elementspath":{"eleLabel":"Ruta dos elementos","eleTitle":"Elemento %1"},"contextmenu":{"options":"Opcións do menú contextual"},"clipboard":{"copy":"Copiar","copyError":"Os axustes de seguranza do seu navegador non permiten que o editor realice automaticamente as tarefas de copia. Use o teclado para iso (Ctrl/Cmd+C).","cut":"Cortar","cutError":"Os axustes de seguranza do seu navegador non permiten que o editor realice automaticamente as tarefas de corte. Use o teclado para iso (Ctrl/Cmd+X).","paste":"Pegar","pasteNotification":"O seu navegador non permite pegar deste xeito. Prema %1 para pegar."},"button":{"selectedLabel":"%1 (seleccionado)"},"blockquote":{"toolbar":"Cita"},"basicstyles":{"bold":"Negra","italic":"Cursiva","strike":"Riscado","subscript":"Subíndice","superscript":"Superíndice","underline":"Subliñado"},"about":{"copy":"Copyright &copy; $1. Todos os dereitos reservados.","dlgTitle":"Sobre o CKEditor","help":"Consulte $1 para obter axuda.","moreInfo":"Para obter información sobre a licenza, visite o noso sitio web:","title":"Sobre o CKEditor","userGuide":"Guía do usuario do CKEditor"},"editor":"Editor de texto mellorado","editorPanel":"Panel do editor de texto mellorado","common":{"editorHelp":"Prema ALT 0 para obter axuda","browseServer":"Examinar o servidor","url":"URL","protocol":"Protocolo","upload":"Enviar","uploadSubmit":"Enviar ao servidor","image":"Imaxe","flash":"Flash","form":"Formulario","checkbox":"Caixa de selección","radio":"Botón de opción","textField":"Campo de texto","textarea":"Área de texto","hiddenField":"Campo agochado","button":"Botón","select":"Campo de selección","imageButton":"Botón de imaxe","notSet":"<sen estabelecer>","id":"ID","name":"Nome","langDir":"Dirección de escritura do idioma","langDirLtr":"Esquerda a dereita (LTR)","langDirRtl":"Dereita a esquerda (RTL)","langCode":"Código do idioma","longDescr":"Descrición completa do URL","cssClass":"Clases da folla de estilos","advisoryTitle":"Título","cssStyle":"Estilo","ok":"Aceptar","cancel":"Cancelar","close":"Pechar","preview":"Vista previa","resize":"Redimensionar","generalTab":"Xeral","advancedTab":"Avanzado","validateNumberFailed":"Este valor non é un número.","confirmNewPage":"Calquera cambio que non gardara neste contido perderase.\r\nConfirma que quere cargar unha páxina nova?","confirmCancel":"Algunhas das opcións foron cambiadas.\r\nConfirma que quere pechar o diálogo?","options":"Opcións","target":"Destino","targetNew":"Nova xanela (_blank)","targetTop":"Xanela principal (_top)","targetSelf":"Mesma xanela (_self)","targetParent":"Xanela superior (_parent)","langDirLTR":"Esquerda a dereita (LTR)","langDirRTL":"Dereita a esquerda (RTL)","styles":"Estilo","cssClasses":"Clases da folla de estilos","width":"Largo","height":"Alto","align":"Aliñamento","alignLeft":"Esquerda","alignRight":"Dereita","alignCenter":"Centro","alignJustify":"Xustificado","alignTop":"Arriba","alignMiddle":"Centro","alignBottom":"Abaixo","alignNone":"Ningún","invalidValue":"Valor incorrecto.","invalidHeight":"O alto debe ser un número.","invalidWidth":"O largo debe ser un número.","invalidCssLength":"O valor especificado para o campo «%1» debe ser un número positivo con ou sen unha unidade de medida CSS correcta (px, %, in, cm, mm, em, ex, pt, ou pc).","invalidHtmlLength":"O valor especificado para o campo «%1» debe ser un número positivo con ou sen unha unidade de medida HTML correcta (px ou %).","invalidInlineStyle":"O valor especificado no estilo en liña debe consistir nunha ou máis tuplas co formato «nome : valor», separadas por punto e coma.","cssLengthTooltip":"Escriba un número para o valor en píxeles ou un número cunha unidade CSS correcta (px, %, in, cm, mm, em, ex, pt, ou pc).","unavailable":"%1<span class=\"cke_accessibility\">, non dispoñíbel</span>","keyboard":{"8":"Ir atrás","13":"Intro","16":"Maiús","17":"Ctrl","18":"Alt","32":"Espazo","35":"Fin","36":"Inicio","46":"Supr","224":"Orde"},"keyboardShortcut":"Atallo de teclado"}};
# Copyright 2020 The Bazel Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """macos_kernel_extension Starlark tests.""" load( ":rules/analysis_target_outputs_test.bzl", "analysis_target_outputs_test", ) load( ":rules/apple_verification_test.bzl", "apple_verification_test", ) load( ":rules/common_verification_tests.bzl", "archive_contents_test", ) load( "@bazel_skylib//lib:unittest.bzl", "analysistest", "unittest", ) def _analysis_macos_cpu_test_impl(ctx): "Test the architechure passed in to the rule is correctly passed to clang." env = analysistest.begin(ctx) no_kext = True for action in analysistest.target_actions(env): if hasattr(action, "argv") and action.argv: concat_action_argv = " ".join(action.argv) if not "/wrapped_clang " in concat_action_argv: continue if not " -kext " in concat_action_argv: continue if not " -target {}-".format(ctx.attr.clang_cpu) in concat_action_argv: unittest.fail(env, "\"{}\" not passed to clang \"{}\".".format( ctx.attr.clang_cpu, concat_action_argv, )) no_kext = False if no_kext: unittest.fail(env, "Did not find a clang kext action to test.") return analysistest.end(env) _analysis_arm64_macos_cpu_test = analysistest.make( _analysis_macos_cpu_test_impl, config_settings = {"//command_line_option:macos_cpus": "arm64"}, attrs = {"clang_cpu": attr.string(default = "arm64e")}, fragments = ["apple"], ) _analysis_x86_64_macos_cpu_test = analysistest.make( _analysis_macos_cpu_test_impl, config_settings = {"//command_line_option:macos_cpus": "x86_64"}, attrs = {"clang_cpu": attr.string(default = "x86_64")}, fragments = ["apple"], ) _analysis_default_macos_cpu_test = analysistest.make( _analysis_macos_cpu_test_impl, attrs = {"clang_cpu": attr.string(default = "x86_64")}, fragments = ["apple"], ) def macos_kernel_extension_test_suite(name): """Test suite for macos_kernel_extension. Args: name: the base name to be used in things created by this macro """ analysis_target_outputs_test( name = "{}_zip_file_output_test".format(name), target_under_test = "//test/starlark_tests/targets_under_test/macos:kext", expected_outputs = ["kext.zip"], tags = [name], ) _analysis_arm64_macos_cpu_test( name = "{}_arm64_macos_cpu_test".format(name), target_under_test = "//test/starlark_tests/targets_under_test/macos:kext", tags = [name], ) _analysis_x86_64_macos_cpu_test( name = "{}_x86_64_macos_cpu_test".format(name), target_under_test = "//test/starlark_tests/targets_under_test/macos:kext", tags = [name], ) _analysis_default_macos_cpu_test( name = "{}_default_macos_cpu_test".format(name), target_under_test = "//test/starlark_tests/targets_under_test/macos:kext", tags = [name], ) apple_verification_test( name = "{}_codesign_test".format(name), build_type = "device", target_under_test = "//test/starlark_tests/targets_under_test/macos:kext", verifier_script = "verifier_scripts/codesign_verifier.sh", tags = [name], ) archive_contents_test( name = "{}_plist_test".format(name), build_type = "device", plist_test_file = "$CONTENT_ROOT/Info.plist", plist_test_values = { "BuildMachineOSBuild": "*", "CFBundleExecutable": "kext", "CFBundleIdentifier": "com.google.kext", "CFBundleName": "kext", "CFBundlePackageType": "KEXT", "CFBundleSupportedPlatforms:0": "MacOSX", "DTCompiler": "com.apple.compilers.llvm.clang.1_0", "DTPlatformBuild": "*", "DTPlatformName": "macosx", "DTPlatformVersion": "*", "DTSDKBuild": "*", "DTSDKName": "macosx*", "DTXcode": "*", "DTXcodeBuild": "*", "LSMinimumSystemVersion": "10.13", "IOKitPersonalities": "*", "OSBundleLibraries": "*", }, target_under_test = "//test/starlark_tests/targets_under_test/macos:kext", tags = [name], ) archive_contents_test( name = "{}_exported_symbols_list_test".format(name), build_type = "device", target_under_test = "//test/starlark_tests/targets_under_test/macos:kext_dead_stripped", binary_test_file = "$CONTENT_ROOT/MacOS/kext_dead_stripped", compilation_mode = "opt", binary_test_architecture = "x86_64", binary_contains_symbols = ["_anotherFunctionShared"], binary_not_contains_symbols = ["_dontCallMeShared"], tags = [name], ) native.test_suite( name = name, tags = [name], )
# -*- coding: utf-8 -*- """Trace GUI.""" #------------------------------------------------------------------------------ # Imports #------------------------------------------------------------------------------ import logging from pathlib import Path import numpy as np from phylib.io.model import load_raw_data from phylib.utils import Bunch from phy.apps.template import get_template_params from phy.cluster.views.trace import TraceView, select_traces from phy.gui import create_app, run_app, GUI logger = logging.getLogger(__name__) #------------------------------------------------------------------------------ # Trace GUI #------------------------------------------------------------------------------ def create_trace_gui(dat_path, **kwargs): """Create the Trace GUI. Parameters ---------- dat_path : str or Path Path to the raw data file sample_rate : float The data sampling rate, in Hz. n_channels_dat : int The number of columns in the raw data file. dtype : str The NumPy data type of the raw binary file. """ gui_name = 'TraceGUI' dat_path = Path(dat_path) # Support passing a params.py file. if dat_path.suffix == '.py': params = get_template_params(str(dat_path)) return create_trace_gui(next(iter(params.pop('dat_path'))), **params) sample_rate = float(kwargs['sample_rate']) assert sample_rate > 0. n_channels_dat = int(kwargs['n_channels_dat']) dtype = np.dtype(kwargs['dtype']) offset = int(kwargs['offset'] or 0) order = kwargs.get('order', None) # Memmap the raw data file. data = load_raw_data( path=dat_path, n_channels_dat=n_channels_dat, dtype=dtype, offset=offset, order=order, ) duration = data.shape[0] / sample_rate create_app() gui = GUI(name=gui_name, subtitle=dat_path.resolve(), enable_threading=False) gui.set_default_actions() def _get_traces(interval): return Bunch( data=select_traces( data, interval, sample_rate=sample_rate)) # TODO: load channel information view = TraceView( traces=_get_traces, n_channels=n_channels_dat, sample_rate=sample_rate, duration=duration, enable_threading=False, ) view.attach(gui) return gui def trace_gui(dat_path, **kwargs): # pragma: no cover """Launch the Trace GUI. Parameters ---------- dat_path : str or Path Path to the raw data file sample_rate : float The data sampling rate, in Hz. n_channels_dat : int The number of columns in the raw data file. dtype : str The NumPy data type of the raw binary file. order : str Order of the data file: `C` or `F` (Fortran). """ gui = create_trace_gui(dat_path, **kwargs) gui.show() run_app() gui.close()
var delay_tab = 300, delay_show_mm = 300, delay_hide_mm = 300; $("body").append(getFullscreenBg()); $.fn.initMM = function() { var mmpanel = { $mobilemenu: $(".panel-menu"), external_con: 'externaf', mm_close_button: 'Close', mm_back_button: 'Back', mm_breakpoint: 768, mm_enable_breakpoint: false, mm_mobile_button: false, remember_state: false, second_button: false, // class init: function($button, data){ var _this = this; if(!_this.$mobilemenu.length){ console.log('You not have <nav class="panel-menu mobile-main-menu">menu</nav>. See Documentation') return false; } arguments[1] != undefined && _this.parse_arguments(data); _this.$mobilemenu.parse_mm(mmpanel);//_this.mm_close_button, _this.mm_back_button); _this.$mobilemenu.init_mm(mmpanel); _this.mm_enable_breakpoint && _this.$mobilemenu.check_resolution_mm(mmpanel);//_this.mm_breakpoint); $button.mm_handler(mmpanel); }, parse_arguments: function(data){ var _this = this; if(Object(data).hasOwnProperty("menu_class")) _this.$mobilemenu = $("."+data.menu_class); $.each(data, function( k, v ) { switch(k) { case 'right': v && _this.$mobilemenu.addClass("mm-right"); break; case 'close_button_name': _this.mm_close_button = v; break; case 'back_button_name': _this.mm_back_button = v; break; case 'width': _this.$mobilemenu.css("width", v); break; case 'breakpoint': _this.mm_breakpoint = v; break; case 'enable_breakpoint': _this.mm_enable_breakpoint = v; break; case 'mobile_button': _this.mm_mobile_button = v; break; case 'remember_state': _this.remember_state = v; break; case 'second_button': _this.second_button = v; break; case 'external_container': v && _this.$mobilemenu.addClass(_this.external_con); break; }; }); }, show_button_in_mobile: function($button){ var _this = this; if(_this.mm_mobile_button) { window.innerWidth > _this.mm_breakpoint ? $button.hide() : $button.show(); $(window).resize(function(){ window.innerWidth > _this.mm_breakpoint ? $button.hide() : $button.show(); }) } } } mmpanel.init($(this), arguments[0]); mmpanel.show_button_in_mobile($(this)); } $.fn.check_resolution_mm = function(mmpanel) { var _this = $(this); $(window).resize(function(){ if(!$("body").hasClass("mm-open") || !_this.hasClass("mmitemopen")) return false; window.innerWidth > mmpanel.mm_breakpoint && _this.closemm(mmpanel); }); } $.fn.mm_handler = function(mmpanel){ $(this).click(function(e){ e.preventDefault(); mmpanel.$mobilemenu.openmm(); }); if(mmpanel.second_button != false){ $(mmpanel.second_button).click(function(e){ e.preventDefault(); mmpanel.$mobilemenu.openmm(); }); }; } $.fn.parse_mm = function(mmpanel) { var $mm_curent = $(this).clone(), $mm_new = $(get_mm_parent()), $mm_block = false, count = 0, _this = false, $btnBack = false, $ul; $(this).empty(); $mm_curent.find('a').each(function(){ _this = $(this); $ul = _this.parent().find("ul").first(); if($ul.length) { count++; $ul.prepend("<li></li>").find("li").first().append(_this.clone().addClass("mm-original-link")); _this.attr("href", "#mm"+count).attr("data-target", "#mm"+count).addClass("mm-next-level"); } }); $mm_curent.find('ul').each(function(index){ $btnBack = false; $mm_block = $(get_mm_block()).attr("id", "mm"+index).append($(this)); if (index == 0) { $mm_block.addClass("mmopened").addClass("mmcurrent").removeClass("mmhidden"); $btnBack = getButtonClose($mm_curent.find(".mm-closebtn").html(), mmpanel.mm_close_button); mmpanel.$mobilemenu.hasClass(mmpanel.external_con) || $mm_block.find('ul').first().append('<li id="entrypoint-objects"></li>'); $.ajax({ url: 'ajax-content/include-mobile-layout.html', success: function(data) { var $item = $(data); $('#entrypoint-objects').append($item); } }); $mm_block.find("ul").first().prepend($btnBack); } else { $btnBack = getButtonBack($mm_curent.find(".mm-backbtn").html(), mmpanel.mm_back_button); $mm_block.find("ul").first().prepend($btnBack); } $mm_new.append($mm_block); }); $(this).append($mm_new); } $.fn.init_mm = function(mmpanel) { var _parent = $(this); _parent.find("a").each(function(){ $(this).click(function(e){ var _this = $(this); var $panel = false; var $currobj = false; var lv = ''; if(_this.hasClass("mm-next-level")){ e.preventDefault(); lv = _this.attr("href"); $currobj = _parent.find(".mmcurrent"); $currobj.addClass("mmsubopened").removeClass("mmcurrent"); _parent.find(lv).removeClass("mmhidden"); setTimeout(function(){_parent.find(lv).scrollTop(0).addClass("mmcurrent").addClass("mmopened");}, 0); setTimeout(function(){$currobj.addClass("mmhidden")}, delay_tab); return false; } if(_this.hasClass("mm-prev-level")){ e.preventDefault(); lv = _this.attr("href"); $currobj = _parent.find(".mmcurrent"); $currobj.removeClass("mmcurrent").removeClass("mmopened"); _parent.find(".mmsubopened").last().removeClass("mmhidden").scrollTop(0).removeClass("mmsubopened").addClass("mmcurrent"); setTimeout(function(){$currobj.addClass("mmhidden")}, delay_tab); return false; } if(_this.hasClass("mm-close")){ _parent.closemm(mmpanel); return false; } }) }); $(".mm-fullscreen-bg").click(function(e){ e.preventDefault(); _parent.closemm(mmpanel); }); } $.fn.openmm = function(){ var _this = $(this); _this.show(); setTimeout(function(){$("body").addClass("mm-open");_this.addClass("mmitemopen");$(".mm-fullscreen-bg").fadeIn(delay_show_mm);}, 0); } $.fn.closemm = function(mmpanel){ var _this = $(this); _this.addClass("mmhide"); $(".mm-fullscreen-bg").fadeOut(delay_hide_mm); setTimeout(function(){ mm_destroy(_this, mmpanel); }, delay_hide_mm); } function mm_destroy(_parent, mmpanel){ if(!mmpanel.remember_state) { _parent.find(".mmpanel").toggleClass("mmsubopened mmcurrent mmopened", false).addClass("mmhidden"); _parent.find("#mm0").addClass("mmopened").addClass("mmcurrent").removeClass("mmhidden"); } _parent.toggleClass("mmhide mmitemopen", false).hide(); $("body").removeClass("mm-open"); } function get_mm_parent(){ return '<div class="mmpanels"></div>'; } function get_mm_block(){ return '<div class="mmpanel mmhidden">'; } function getButtonBack(value, _default) { value = value == undefined ? _default : value; return '<li><a href="#" data-target="#" class="mm-prev-level">'+value+'</a></li>'; } function getButtonClose(value, _default) { value = value == undefined ? _default : value; return '<li class="mm-close-parent"><a href="#close" data-target="#close" class="mm-close">'+value+'</a></li>'; } function getFullscreenBg() { return '<div class="mm-fullscreen-bg"></div>'; }
/* * Copyright (c) 1997, 2001 Hellmuth Michaelis. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * *--------------------------------------------------------------------------- * * i4b - mbuf handling support routines * ------------------------------------ * * $FreeBSD: src/sys/i4b/layer2/i4b_mbuf.c,v 1.6.2.1 2001/08/10 14:08:41 obrien Exp $ * * last edit-date: [Sat Jan 13 13:15:45 2001] * *---------------------------------------------------------------------------*/ #include <sys/param.h> #include <sys/systm.h> #include <sys/mbuf.h> #include <sys/socket.h> #include <net/if.h> #include <i4b/include/i4b_mbuf.h> #define I4B_MBUF_DEBUG #undef I4B_MBUF_TYPE_DEBUG #ifdef I4B_MBUF_TYPE_DEBUG #ifdef __FreeBSD__ #define MT_DCHAN 42 #define MT_BCHAN 43 #else /* NetBSD */ #define MT_DCHAN MT_DATA #define MT_BCHAN MT_DATA #endif #define MT_I4B_D MT_DCHAN #define MT_I4B_B MT_BCHAN #else /* ! I4B_MBUF_TYPE_DEBUG */ #define MT_I4B_D MT_DATA #define MT_I4B_B MT_DATA #endif /* I4B_MBUF_TYPE_DEBUG */ /*---------------------------------------------------------------------------* * allocate D-channel mbuf space *---------------------------------------------------------------------------*/ struct mbuf* i4b_Dgetmbuf(int len) { struct mbuf *m; if(len > MCLBYTES) /* if length > max extension size */ { #ifdef I4B_MBUF_DEBUG printf("i4b_getmbuf: error - len(%d) > MCLBYTES(%d)\n", len, MCLBYTES); #endif return(NULL); } MGETHDR(m, M_DONTWAIT, MT_I4B_D); /* get mbuf with pkthdr */ /* did we actually get the mbuf ? */ if(!m) { #ifdef I4B_MBUF_DEBUG printf("i4b_getbuf: error - MGETHDR failed!\n"); #endif return(NULL); } if(len >= MHLEN) { MCLGET(m, M_DONTWAIT); if(!(m->m_flags & M_EXT)) { m_freem(m); #ifdef I4B_MBUF_DEBUG printf("i4b_getbuf: error - MCLGET failed, len(%d)\n", len); #endif return (NULL); } } m->m_len = len; return(m); } /*---------------------------------------------------------------------------* * free a D-channel mbuf *---------------------------------------------------------------------------*/ void i4b_Dfreembuf(struct mbuf *m) { if(m) m_freem(m); } /*---------------------------------------------------------------------------* * clear a D-channel ifqueue from data *---------------------------------------------------------------------------*/ void i4b_Dcleanifq(struct ifqueue *ifq) { int x = splimp(); #if defined (__FreeBSD__) && __FreeBSD__ > 4 IF_DRAIN(ifq); #else struct mbuf *m; while(!IF_QEMPTY(ifq)) { IF_DEQUEUE(ifq, m); i4b_Dfreembuf(m); } #endif splx(x); } /*---------------------------------------------------------------------------* * allocate B-channel mbuf space *---------------------------------------------------------------------------*/ struct mbuf* i4b_Bgetmbuf(int len) { struct mbuf *m; if(len > MCLBYTES) /* if length > max extension size */ { #ifdef I4B_MBUF_DEBUG printf("i4b_getmbuf: error - len(%d) > MCLBYTES(%d)\n", len, MCLBYTES); #endif return(NULL); } MGETHDR(m, M_DONTWAIT, MT_I4B_B); /* get mbuf with pkthdr */ /* did we actually get the mbuf ? */ if(!m) { #ifdef I4B_MBUF_DEBUG printf("i4b_getbuf: error - MGETHDR failed!\n"); #endif return(NULL); } if(len >= MHLEN) { MCLGET(m, M_DONTWAIT); if(!(m->m_flags & M_EXT)) { m_freem(m); #ifdef I4B_MBUF_DEBUG printf("i4b_getbuf: error - MCLGET failed, len(%d)\n", len); #endif return (NULL); } } m->m_len = len; return(m); } /*---------------------------------------------------------------------------* * free a B-channel mbuf *---------------------------------------------------------------------------*/ void i4b_Bfreembuf(struct mbuf *m) { if(m) m_freem(m); } /*---------------------------------------------------------------------------* * clear a B-channel ifqueue from data *---------------------------------------------------------------------------*/ void i4b_Bcleanifq(struct ifqueue *ifq) { int x = splimp(); #if defined (__FreeBSD__) && __FreeBSD__ > 4 IF_DRAIN(ifq); #else struct mbuf *m; while(!IF_QEMPTY(ifq)) { IF_DEQUEUE(ifq, m); i4b_Bfreembuf(m); } #endif splx(x); } /* EOF */
module.exports = { NODE_ENV: '"taian"' }
#!/usr/local/bin/python3.4 import os, sys, logging, json, argparse, time, datetime, requests, uuid from config_files import config_system as config_sys # POLICY FRAMEWORK EMULATED CONTENT_HEADER = {'Content-Type':'application/xml'} policies_list = [ { "ssla-capability":["5G_E2E_TRAFFIC_CONFIDENTIALITY_AND_INTEGRITY_PROTECTION"], "name": "Channel_Protection", "id": "mspl_9f1a88b4fc67421b98de270d5a63d35a", "monitoring-name": "Network_traffic_analysis", "monitoring-id":"mspl_eef61525d1594412bdcef34a4bfb7fc9" }, { "ssla-capability":["5G_SYSTEM_ANTI_DDOS_PROTECTION"], "name": "Channel_Protection", "id": "mspl_9f1a88b4fc67421b98de270d5a63d35a", "monitoring-name": "Network_traffic_analysis", "monitoring-id":"mspl_eef61525d1594412bdcef34a4bfb7fc9" }, { "ssla-capability":["DETECTION_OF_CRYPTOCURRENCY_MINING_IN_5G_TRAFFIC"], "name": "DDos_attack_protection", "id": "mspl_zzf61525d1594412bdcef34a4bfb7fc7", "monitoring-name": "Network_traffic_analysis", "monitoring-id":"mspl_aef61525d1594412bdcef34a4bfb7fc7" } ] # Retrieve policies based on the ssla capabilities # NOTE if two capabilities have the same policy associated, that policy is returned once associated to both cpabilities def get_policies_by_sla(ssla_caps): config_sys.logger.info('POLICY-FRAMEWORK: Retrieving Policis associated to the SSLA capabilities requested.') temp_list = [] selected_policies = [] #config_sys.logger.info('POLICY-FRAMEWORK: policies_list' + str(policies_list)) for policy_item in policies_list: for cap_item in ssla_caps: if cap_item in policy_item["ssla-capability"]: temp_list.append(policy_item) #config_sys.logger.info('POLICY-FRAMEWORK: temp_list' + str(temp_list)) for temp_item in temp_list: if selected_policies == []: selected_policies.append(temp_item) else: matched_policy = False for pol_ref_item in selected_policies: if (temp_item["id"] == pol_ref_item["id"] and temp_item["monitoring-id"] == pol_ref_item["monitoring-id"]): updated_cap_list = pol_ref_item["ssla-capability"] updated_cap_list.append(temp_item["ssla-capability"][0]) pol_ref_item["ssla-capability"] = updated_cap_list matched_policy = True if matched_policy == False: selected_policies.append(temp_item) #config_sys.logger.info('POLICY-FRAMEWORK: selected_policies' + str(selected_policies)) return selected_policies, 201
from argparse import ArgumentParser import datetime import os import numpy as np from sklearn.metrics import roc_auc_score, average_precision_score,accuracy_score, precision_score, recall_score import torch import torch.utils.data from torch import nn, optim from torch.nn import functional as F import pytorch_lightning as pl from pytorch_lightning.loggers import WandbLogger from pytorch_lightning.callbacks.early_stopping import EarlyStopping from gsae.utils import eval_metrics, load_splits class GSAE(pl.LightningModule): def __init__(self, hparams): super(GSAE, self).__init__() self.hparams = hparams self.input_dim = hparams.input_dim self.bottle_dim = hparams.bottle_dim if hparams.n_gpus > 0: self.dev_type = 'cuda' if hparams.n_gpus == 0: self.dev_type = 'cpu' self.eps = 1e-5 def kl_div(self,mu, logvar): KLD_element = mu.pow(2).add_(logvar.exp()).mul_(-1).add_(1).add_(logvar) KLD = torch.sum(KLD_element).mul_(-0.5) return KLD # main model functions def encode(self, x): h = self.bn11(F.relu(self.fc11(x))) h = self.bn12(F.relu(self.fc12(h))) return self.fc21(h), self.fc22(h) def reparameterize(self, mu, logvar): std = torch.exp(0.5*logvar) eps = torch.randn_like(std) return mu + eps*std def decode(self, z): h3 = F.relu(self.fc3(z)) return self.fc4(h3) def embed(self, x): h = self.bn11(F.relu(self.fc11(x))) h = self.bn12(F.relu(self.fc12(h))) mu = self.fc21(h) logvar = self.fc22(h) z = self.reparameterize(mu, logvar) return z, mu, logvar def predict(self,z): h = F.relu(self.regfc1(z)) y_pred = self.regfc2(h) return y_pred def predict_from_data(self,x): z = self.embed(x)[0] pred = self.predict(z) return pred def forward(self, x): # encoding z, mu, logvar = self.embed(x, adj) # predict y_pred = self.predict(z) # recon x_hat = self.decode(z) return x_hat, y_pred, mu, logvar, z def loss_multi_GSAE(self, recon_x, x, mu, logvar, y_pred, y, alpha, beta, batch_idx): # reconstruction loss recon_loss = nn.MSELoss()(recon_x.flatten(), x.flatten()) # regression loss reg_loss = nn.MSELoss()(y_pred.reshape(-1), y.reshape(-1)) # kl divergence KLD = self.kl_div(mu, logvar) num_epochs = self.hparams.max_epochs - 5 total_batches = self.len_ep * num_epochs # loss annealing weight = min(1, self.trainer.global_step / total_batches) reg_loss = weight * reg_loss kl_loss = weight* KLD reg_loss = alpha * reg_loss.mean() kl_loss + beta * kl_loss total_loss = recon_loss + reg_loss + kl_loss log_losses = {'train_loss' : total_loss.detach(), 'recon_loss' : recon_loss.detach(), 'pred_loss' :reg_loss.detach(), 'kl_loss': kl_loss.detach()} return total_loss, log_losses def training_step(self, batch, batch_idx): x, y = batch x_hat, y_hat, mu, logvar, z = self(x) loss, log_losses = self.loss_multi_GVAE(recon_x=x, x=x_hat, mu=mu, logvar=logvar, y_pred=y_hat, y=y, alpha=self.hparams.alpha, beta=self.hparams.beta, batch_idx=batch_idx) return {'loss': loss, 'log': log_losses} def prepare_data(self): _, train_tup, test_tup = eval('load_splits.load_{}()'.format(self.hparams.dataset)) # train dataset train_dataset = torch.utils.data.TensorDataset(*train_tup) # get valid set train_set, val_set = torch.utils.data.random_split(train_dataset, [55000, 15000]) # train loader train_loader = torch.utils.data.DataLoader(train_set, batch_size=self.hparams.batch_size, shuffle=True) # valid loader valid_loader = torch.utils.data.DataLoader(val_set, batch_size=self.hparams.batch_size, shuffle=False) # save to system self.len_ep = len(train_loader) self.train_data = train_loader self.valid_data = valid_loader def train_dataloader(self): return self.train_data def val_dataloader(self): return self.valid_data def validation_step(self, batch, batch_idx): x, y = batch x_hat, y_hat, mu, logvar,z = self(x) # reconstruction loss recon_loss = nn.MSELoss()(x_hat.flatten(), x.flatten()) # regression loss reg_loss = nn.MSELoss()(y_hat.reshape(-1), y.reshape(-1)) # kl loss kl_loss = self.kl_div(mu, logvar) total_loss = recon_loss + reg_loss + kl_loss log_losses = {'val_loss' : total_loss.detach(), 'val_recon_loss' : recon_loss.detach(), 'val_pred_loss' :reg_loss.detach(), 'val_kl_loss': kl_loss.detach()} return log_losses def validation_epoch_end(self, outputs): avg_loss = torch.stack([x['val_loss'] for x in outputs]).mean() avg_reconloss = torch.stack([x['val_recon_loss'] for x in outputs]).mean() avg_regloss = torch.stack([x['val_pred_loss'] for x in outputs]).mean() avg_klloss = torch.stack([x['val_kl_loss'] for x in outputs]).mean() tensorboard_logs = {'val_loss': avg_loss, 'val_avg_recon_loss': avg_reconloss, 'val_avg_pred_loss':avg_regloss, 'val_avg_kl_loss':avg_klloss} return {'val_loss': avg_loss, 'log': tensorboard_logs} def configure_optimizers(self): return torch.optim.Adam(self.parameters(), lr=self.hparams.learning_rate) if __name__ == '__main__': parser = ArgumentParser(add_help=False) parser.add_argument('--input_dim', default=32, type=int) parser.add_argument('--dataset', default='seq3', type=str) parser.add_argument('--bottle_dim', default=25, type=int) parser.add_argument('--hidden_dim', default=400, type=int) parser.add_argument('--learning_rate', default=0.0001, type=float) parser.add_argument('--alpha', default=0.5, type=float) parser.add_argument('--beta', default=0.0005, type=float) parser.add_argument('--n_epochs', default=100, type=int) parser.add_argument('--batch_size', default=100, type=int) parser.add_argument('--n_gpus', default=1, type=int) parser.add_argument('--save_dir', default='train_logs/', type=str) cl_args = parser.parse_args() # add args from trainer parser = pl.Trainer.add_argparse_args(parser) # parse params args = parser.parse_args() # get data # train_loader, train_tup, test_tup = eval('load_splits.load_{}(gnn=True)'.format(args.dataset)) # len_ep = len(train_loader) # logger now = datetime.datetime.now() date_suffix = now.strftime("%Y-%m-%d-%M") save_dir = args.save_dir + 'GSAE_logs_run_{}_{}/'.format(args.dataset,date_suffix) if not os.path.exists(save_dir): os.makedirs(save_dir) wandb_logger = WandbLogger(name='run_{}_{}_{}'.format(args.dataset, args.alpha, args.bottle_dim), project='rna_project_GSAE', log_model=True, save_dir=save_dir) wandb_logger.log_hyperparams(cl_args.__dict__) # early stopping early_stop_callback = EarlyStopping( monitor='val_loss', min_delta=0.00, patience=3, verbose=True, mode='min' ) # init module model = GSAE(hparams=args) # most basic trainer, uses good defaults trainer = pl.Trainer.from_argparse_args(args, max_epochs=args.n_epochs, gpus=args.n_gpus, callbacks=[early_stop_callback], logger=wandb_logger) trainer.fit(model) # 1. save embeddings _, train_tup, test_tup = eval('load_splits.load_{}()'.format(args.dataset)) model = model.cpu() model.dev_type = 'cpu' with torch.no_grad(): train_embed = model.embed(train_tup[0]) test_embed = model.embed(test_tup[0]) # save data print('saving embeddings') np.save(save_dir + "train_embedding.npy" , train_embed.cpu().detach().numpy() ) np.save(save_dir + "test_embedding.npy" , test_embed.cpu().detach().numpy() ) # EVALUATION ON TEST SET # energy pred mse print("getting test set predictions") with torch.no_grad(): x_recon_test = model(test_tup[0])[0] y_pred_test = model.predict_from_data(test_tup[0]) # print("adj type: {}".format(test_tup[1].flatten().numpy())) # print("adj_hat type: {}".format(adj_hat_test.flatten().detach().numpy())) recon_test_val = nn.MSELoss()(x_recon_test.flatten(), test_tup[0].flatten()) pred_test_val = nn.MSELoss()(y_pred_test.flatten(), test_tup[1].flatten()) print("logging test set metrics") wandb_logger.log_metrics({'test_recon_MSE':recon_test_val, 'test_pred_MSE': pred_test_val}) print("gathering eval subsets") eval_tup_list = [eval_metrics.compute_subsample([test_embed, test_tup[-1]], 10000)[0] for i in range(8)] # trainer.test() print("getting smoothness vals") embed_eval_array= np.expand_dims(np.array([x[0].numpy() for x in eval_tup_list]),0) energy_eval_array= np.array([x[1].numpy() for x in eval_tup_list]) print('embed_eval_array shape: {}'.format(embed_eval_array.shape)) print('energy_eval_array shape: {}'.format(energy_eval_array.shape)) energy_smoothness = eval_metrics.eval_over_replicates(embed_eval_array, energy_eval_array, eval_metrics.get_smoothnes_kNN, [5, 10])[0] energy_smoothness = eval_metrics.format_metric(energy_smoothness) wandb_logger.log_metrics({'e_smooth_k5_mean':energy_smoothness[0][0], 'e_smooth_k10_mean': energy_smoothness[0][1], 'e_smooth_k5_std': energy_smoothness[1][0], 'e_smooth_k10_std': energy_smoothness[1][1]})
import { createRateDate } from '../../../utils' import moment from 'moment' import axios from 'axios' const state = { advanceData: [{ date: null, currency: null, amount: 0, // totalAmountInPln totalAmount: 0, currencyRate: 1, rateDate: null, //total amount in delegation curr and rate for it totalAmountCurr: 0, delegationCurrRate: 1 }], advanceTableValidated: false }; const mutations = { SET_ADVANCE_DATA(state, list) { state.advanceData = list }, SET_ADVANCE_VALIDATED(state, isValidated) { state.advanceTableValidated = isValidated } }; const actions = { removeAdvanceRow({ commit, getters, dispatch }, index) { const advanceData = getters.getAdvanceData advanceData.splice(index, 1) dispatch('updateAdvance') dispatch('checkAdvanceFields') }, addAdvanceRow({getters,commit}) { const advanceData = getters.getAdvanceData advanceData.push({ date: null, currency: null, amount: 0, totalAmount: 0, currencyRate: 1, rateDate: null, totalAmountCurr: 0, delegationCurrRate: 1 }) commit('SET_ADVANCE_VALIDATED', false) }, checkAdvanceFields({ getters, commit }) { const advances = getters.getAdvanceData for (let i = 0; i < advances.length; i++) { let arrayItem = advances[i] for (let key in arrayItem) { if (!arrayItem[key] || arrayItem[key] === "") { commit('SET_ADVANCE_VALIDATED', false) return } else { commit('SET_ADVANCE_VALIDATED', true) } } } }, updateAdvance({getters, commit, dispatch}) { const advanceData = getters.getAdvanceData, totalCosts = getters.getTotalCosts, delegationRate = getters.getNewDelegation.currency, totalCostsInCurr = getters.getTotalCostsInCurr totalCosts.advance = 0 totalCostsInCurr.advance = 0 for(let i=0; i<advanceData.length; i++) { let amount = advanceData[i].amount, rate = parseFloat(advanceData[i].currencyRate).toFixed(2) amount = (amount === "") ? 0 : parseFloat(amount) advanceData[i].totalAmount = parseFloat(amount * rate) advanceData[i].totalAmountCurr = parseFloat(advanceData[i].totalAmount / advanceData[i].delegationCurrRate).toFixed(2) totalCosts.advance = totalCosts.advance + parseFloat(advanceData[i].totalAmount) totalCostsInCurr.advance = parseFloat(totalCostsInCurr.advance) + parseFloat(advanceData[i].totalAmountCurr) } dispatch('checkAdvanceFields') }, getAdvanceRate({commit, dispatch, getters}, index) { const data = getters.getAdvanceData, newDelegationCurr = getters.getNewDelegation.currency let row = data[index], rateDate = row.date rateDate = createRateDate(rateDate) row.rateDate = rateDate if (row.date && row.currency && row.currency !== "PLN") { const date = moment(rateDate).format('YYYY-MM-DD') const URL = 'http://api.nbp.pl/api/exchangerates/tables/a/' + date +'/' axios.get(URL).then(res => { let currRates = res.data[0].rates row.currencyRate = currRates.find(o => o.code === row.currency).mid row.delegationCurrRate = (newDelegationCurr !== 'PLN') ? currRates.find(o => o.code === newDelegationCurr).mid : 1.00 dispatch('updateAdvance') }).catch(error => { }) } else if (row.date && row.currency == "PLN"){ row.currencyRate = 1 row.delegationCurrRate = 1 dispatch('updateAdvance') } }, countAdvanceInCurr({commit, dispatch, getters}) { } }; const getters = { getAdvanceData(state) { return state.advanceData }, getAdvanceValidated(state) { return state.advanceTableValidated } }; export default { state, mutations, actions, getters }
/** * Driver for the ADXL362 accelerometer * * @author Aaron Parks * @date Aug 2013 */ #include "accel.h" #include "accel_registers.h" #include "../globals.h" #include "../timing/timer.h" #include "../wired/spi.h" /////////////////////////////////////////////////////////////////////////////// // TODO Translate these to a better format once SPI driver is fleshed out. Make them CONST. uint8_t const ADXL_READ_PARTID[] = {ADXL_CMD_READ_REG,ADXL_REG_PARTID,0x00}; uint8_t const ADXL_READ_DEVID[] = {ADXL_CMD_READ_REG,ADXL_REG_DEVID_AD,0x00}; uint8_t const ADXL_REAsxD_STATUS[] = {ADXL_CMD_READ_REG,ADXL_REG_STATUS,0x00}; uint8_t const ADXL_READ_XYZ_8BIT[] = {ADXL_CMD_READ_REG,ADXL_REG_XDATA,0x00,0x00,0x00}; uint8_t const ADXL_READ_XYZ_16BIT[] = {ADXL_CMD_READ_REG,ADXL_REG_XDATA_L,0x00,0x00,0x00,0x00,0x00,0x00}; uint8_t const ADXL_CONFIG_MEAS[] = {ADXL_CMD_WRITE_REG,ADXL_REG_POWER_CTL,0x02}; // Put the ADXL into measurement mode uint8_t const ADXL_CONFIG_STBY[] = {ADXL_CMD_WRITE_REG,ADXL_REG_POWER_CTL,0x00}; // Put the ADXL into standby mode uint8_t const ADXL_CONFIG_RESET[] = {ADXL_CMD_WRITE_REG,ADXL_REG_SOFT_RESET,0x52}; uint8_t const ADXL_CONFIG_FILTER[] = {ADXL_CMD_WRITE_REG,ADXL_REG_FILTER_CTL,0x17}; /////////////////////////////////////////////////////////////////////////////// /** * Turn on and start up the ADXL362 accelerometer. This leaves the ADXL running. */ BOOL ACCEL_reset() { // TODO Figure out optimal ADXL configuration for single measurement while(!SPI_acquirePort()); //BITSET(POUT_ACCEL_EN, PIN_ACCEL_EN); //BITSET(POUT_ACCEL_CS, PIN_ACCEL_CS); //TODO find the proper length of delay BITCLR(POUT_ACCEL_CS, PIN_ACCEL_CS); SPI_transaction(gpRxBuf, (uint8_t*)ADXL_CONFIG_RESET, sizeof(ADXL_CONFIG_RESET)); BITSET(POUT_ACCEL_CS, PIN_ACCEL_CS); SPI_releasePort(); //__delay_cycles(5000); //Timer_LooseDelay(LP_LSDLY_200MS);// To let ADXL start measuring? How much time is actually required here, if any? // TODO Use a pin interrupt to let us know when first measurement is ready return SUCCESS; } BOOL ACCEL_range() { // TODO Figure out optimal ADXL configuration for single measurement while(!SPI_acquirePort()); //BITSET(POUT_ACCEL_EN, PIN_ACCEL_EN); //BITSET(POUT_ACCEL_CS, PIN_ACCEL_CS); //TODO find the proper length of delay BITCLR(POUT_ACCEL_CS, PIN_ACCEL_CS); SPI_transaction(gpRxBuf, (uint8_t*)ADXL_CONFIG_FILTER, sizeof(ADXL_CONFIG_FILTER)); BITSET(POUT_ACCEL_CS, PIN_ACCEL_CS); SPI_releasePort(); //__delay_cycles(5000); //Timer_LooseDelay(LP_LSDLY_200MS);// To let ADXL start measuring? How much time is actually required here, if any? // TODO Use a pin interrupt to let us know when first measurement is ready return SUCCESS; } BOOL ACCEL_initialize() { // TODO Figure out optimal ADXL configuration for single measurement while(!SPI_acquirePort()); //BITSET(POUT_ACCEL_EN, PIN_ACCEL_EN); //BITSET(POUT_ACCEL_CS, PIN_ACCEL_CS); //TODO find the proper length of delay BITCLR(POUT_ACCEL_CS, PIN_ACCEL_CS); SPI_transaction(gpRxBuf, (uint8_t*)ADXL_CONFIG_MEAS, sizeof(ADXL_CONFIG_MEAS)); BITSET(POUT_ACCEL_CS, PIN_ACCEL_CS); SPI_releasePort(); //__delay_cycles(5000); //Timer_LooseDelay(LP_LSDLY_200MS);// To let ADXL start measuring? How much time is actually required here, if any? // TODO Use a pin interrupt to let us know when first measurement is ready return SUCCESS; } BOOL ACCEL_initialize_withoutWait() { // TODO Figure out optimal ADXL configuration for single measurement while(!SPI_acquirePort()); //BITSET(POUT_ACCEL_EN, PIN_ACCEL_EN); BITSET(POUT_ACCEL_CS, PIN_ACCEL_CS); BITCLR(POUT_ACCEL_CS, PIN_ACCEL_CS); SPI_transaction(gpRxBuf, (uint8_t*)ADXL_CONFIG_MEAS, sizeof(ADXL_CONFIG_MEAS)); BITSET(POUT_ACCEL_CS, PIN_ACCEL_CS); SPI_releasePort(); //Timer_LooseDelay(LP_LSDLY_200MS);// To let ADXL start measuring? How much time is actually required here, if any? // TODO Use a pin interrupt to let us know when first measurement is ready return SUCCESS; } /** * Put the ADXL362 into a lower power standby state without gating power * * @todo Implement this function */ void ACCEL_standby() { } /** * Grab one sample from the ADXL362 accelerometer */ BOOL ACCEL_singleSample(threeAxis_t_8* result) { while(!SPI_acquirePort()); BITCLR(POUT_ACCEL_CS, PIN_ACCEL_CS); SPI_transaction(gpRxBuf, (uint8_t*)ADXL_READ_XYZ_8BIT, sizeof(ADXL_READ_XYZ_8BIT)); BITSET(POUT_ACCEL_CS, PIN_ACCEL_CS); SPI_releasePort(); result->x = gpRxBuf[2]; result->y = gpRxBuf[3]; result->z = gpRxBuf[4]; return SUCCESS; } BOOL ACCEL_readStat(threeAxis_t_8* result) { while(!SPI_acquirePort()); BITCLR(POUT_ACCEL_CS, PIN_ACCEL_CS); SPI_transaction(gpRxBuf, (uint8_t*)ADXL_REAsxD_STATUS, sizeof(ADXL_REAsxD_STATUS)); BITSET(POUT_ACCEL_CS, PIN_ACCEL_CS); SPI_releasePort(); result->x = gpRxBuf[2]; return SUCCESS; } BOOL ACCEL_readID(threeAxis_t_8* result) { while(!SPI_acquirePort()); BITCLR(POUT_ACCEL_CS, PIN_ACCEL_CS); SPI_transaction(gpRxBuf, (uint8_t*)ADXL_READ_DEVID, sizeof(ADXL_READ_DEVID)); BITSET(POUT_ACCEL_CS, PIN_ACCEL_CS); SPI_releasePort(); result->x = gpRxBuf[2]; return SUCCESS; }
// Copyright 2009 the Sputnik authors. All rights reserved. /** * If Type(Primitive(x)) is not String or Type(Primitive(y)) is not String, then operator x < y returns ToNumber(x) < ToNumber(y) * * @path ch11/11.8/11.8.1/S11.8.1_A3.1_T2.2.js * @description Type(Primitive(x)) is different from Type(Primitive(y)) and both types vary between Number (primitive or object) and String (primitive and object) */ //CHECK#1 if ("1" < 1 !== false) { $ERROR('#1: "1" < 1 === false'); } //CHECK#2 if (1 < "1" !== false) { $ERROR('#2: 1 < "1" === false'); } //CHECK#3 if (new String("1") < 1 !== false) { $ERROR('#3: new String("1") < 1 === false'); } //CHECK#4 if (1 < new String("1") !== false) { $ERROR('#4: 1 < new String("1") === false'); } //CHECK#5 if ("1" < new Number(1) !== false) { $ERROR('#5: "1" < new Number(1) === false'); } //CHECK#6 if (new Number(1) < "1" !== false) { $ERROR('#6: new Number(1) < "1" === false'); } //CHECK#7 if (new String("1") < new Number(1) !== false) { $ERROR('#7: new String("1") < new Number(1) === false'); } //CHECK#8 if (new Number(1) < new String("1") !== false) { $ERROR('#8: new Number(1) < new String("1") === false'); } //CHECK#9 if ("x" < 1 !== false) { $ERROR('#9: "x" < 1 === false'); } //CHECK#10 if (1 < "x" !== false) { $ERROR('#10: 1 < "x" === false'); }
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables from . import outputs __all__ = [ 'ListIotHubResourceKeysResult', 'AwaitableListIotHubResourceKeysResult', 'list_iot_hub_resource_keys', ] @pulumi.output_type class ListIotHubResourceKeysResult: """ The list of shared access policies with a next link. """ def __init__(__self__, next_link=None, value=None): if next_link and not isinstance(next_link, str): raise TypeError("Expected argument 'next_link' to be a str") pulumi.set(__self__, "next_link", next_link) if value and not isinstance(value, list): raise TypeError("Expected argument 'value' to be a list") pulumi.set(__self__, "value", value) @property @pulumi.getter(name="nextLink") def next_link(self) -> str: """ The next link. """ return pulumi.get(self, "next_link") @property @pulumi.getter def value(self) -> Optional[Sequence['outputs.SharedAccessSignatureAuthorizationRuleResponse']]: """ The list of shared access policies. """ return pulumi.get(self, "value") class AwaitableListIotHubResourceKeysResult(ListIotHubResourceKeysResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return ListIotHubResourceKeysResult( next_link=self.next_link, value=self.value) def list_iot_hub_resource_keys(resource_group_name: Optional[str] = None, resource_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableListIotHubResourceKeysResult: """ Use this data source to access information about an existing resource. :param str resource_group_name: The name of the resource group that contains the IoT hub. :param str resource_name: The name of the IoT hub. """ __args__ = dict() __args__['resourceGroupName'] = resource_group_name __args__['resourceName'] = resource_name if opts is None: opts = pulumi.InvokeOptions() if opts.version is None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('azure-nextgen:devices/v20170119:listIotHubResourceKeys', __args__, opts=opts, typ=ListIotHubResourceKeysResult).value return AwaitableListIotHubResourceKeysResult( next_link=__ret__.next_link, value=__ret__.value)
"use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var __make_dart_analyzer_happy = null; /** * The `RouteConfig` decorator defines routes for a given component. * * It takes an array of {@link RouteDefinition}s. * @ts2dart_const */ var RouteConfig = (function () { function RouteConfig(configs) { this.configs = configs; } return RouteConfig; }()); exports.RouteConfig = RouteConfig; /* @ts2dart_const */ var AbstractRoute = (function () { function AbstractRoute(_a) { var name = _a.name, useAsDefault = _a.useAsDefault, path = _a.path, regex = _a.regex, serializer = _a.serializer, data = _a.data; this.name = name; this.useAsDefault = useAsDefault; this.path = path; this.regex = regex; this.serializer = serializer; this.data = data; } return AbstractRoute; }()); exports.AbstractRoute = AbstractRoute; /** * `Route` is a type of {@link RouteDefinition} used to route a path to a component. * * It has the following properties: * - `path` is a string that uses the route matcher DSL. * - `component` a component type. * - `name` is an optional `CamelCase` string representing the name of the route. * - `data` is an optional property of any type representing arbitrary route metadata for the given * route. It is injectable via {@link RouteData}. * - `useAsDefault` is a boolean value. If `true`, the child route will be navigated to if no child * route is specified during the navigation. * * ### Example * ``` * import {RouteConfig, Route} from '@angular/router-deprecated'; * * @RouteConfig([ * new Route({path: '/home', component: HomeCmp, name: 'HomeCmp' }) * ]) * class MyApp {} * ``` * @ts2dart_const */ var Route = (function (_super) { __extends(Route, _super); function Route(_a) { var name = _a.name, useAsDefault = _a.useAsDefault, path = _a.path, regex = _a.regex, serializer = _a.serializer, data = _a.data, component = _a.component; _super.call(this, { name: name, useAsDefault: useAsDefault, path: path, regex: regex, serializer: serializer, data: data }); this.aux = null; this.component = component; } return Route; }(AbstractRoute)); exports.Route = Route; /** * `AuxRoute` is a type of {@link RouteDefinition} used to define an auxiliary route. * * It takes an object with the following properties: * - `path` is a string that uses the route matcher DSL. * - `component` a component type. * - `name` is an optional `CamelCase` string representing the name of the route. * - `data` is an optional property of any type representing arbitrary route metadata for the given * route. It is injectable via {@link RouteData}. * * ### Example * ``` * import {RouteConfig, AuxRoute} from '@angular/router-deprecated'; * * @RouteConfig([ * new AuxRoute({path: '/home', component: HomeCmp}) * ]) * class MyApp {} * ``` * @ts2dart_const */ var AuxRoute = (function (_super) { __extends(AuxRoute, _super); function AuxRoute(_a) { var name = _a.name, useAsDefault = _a.useAsDefault, path = _a.path, regex = _a.regex, serializer = _a.serializer, data = _a.data, component = _a.component; _super.call(this, { name: name, useAsDefault: useAsDefault, path: path, regex: regex, serializer: serializer, data: data }); this.component = component; } return AuxRoute; }(AbstractRoute)); exports.AuxRoute = AuxRoute; /** * `AsyncRoute` is a type of {@link RouteDefinition} used to route a path to an asynchronously * loaded component. * * It has the following properties: * - `path` is a string that uses the route matcher DSL. * - `loader` is a function that returns a promise that resolves to a component. * - `name` is an optional `CamelCase` string representing the name of the route. * - `data` is an optional property of any type representing arbitrary route metadata for the given * route. It is injectable via {@link RouteData}. * - `useAsDefault` is a boolean value. If `true`, the child route will be navigated to if no child * route is specified during the navigation. * * ### Example * ``` * import {RouteConfig, AsyncRoute} from '@angular/router-deprecated'; * * @RouteConfig([ * new AsyncRoute({path: '/home', loader: () => Promise.resolve(MyLoadedCmp), name: * 'MyLoadedCmp'}) * ]) * class MyApp {} * ``` * @ts2dart_const */ var AsyncRoute = (function (_super) { __extends(AsyncRoute, _super); function AsyncRoute(_a) { var name = _a.name, useAsDefault = _a.useAsDefault, path = _a.path, regex = _a.regex, serializer = _a.serializer, data = _a.data, loader = _a.loader; _super.call(this, { name: name, useAsDefault: useAsDefault, path: path, regex: regex, serializer: serializer, data: data }); this.aux = null; this.loader = loader; } return AsyncRoute; }(AbstractRoute)); exports.AsyncRoute = AsyncRoute; /** * `Redirect` is a type of {@link RouteDefinition} used to route a path to a canonical route. * * It has the following properties: * - `path` is a string that uses the route matcher DSL. * - `redirectTo` is an array representing the link DSL. * * Note that redirects **do not** affect how links are generated. For that, see the `useAsDefault` * option. * * ### Example * ``` * import {RouteConfig, Route, Redirect} from '@angular/router-deprecated'; * * @RouteConfig([ * new Redirect({path: '/', redirectTo: ['/Home'] }), * new Route({path: '/home', component: HomeCmp, name: 'Home'}) * ]) * class MyApp {} * ``` * @ts2dart_const */ var Redirect = (function (_super) { __extends(Redirect, _super); function Redirect(_a) { var name = _a.name, useAsDefault = _a.useAsDefault, path = _a.path, regex = _a.regex, serializer = _a.serializer, data = _a.data, redirectTo = _a.redirectTo; _super.call(this, { name: name, useAsDefault: useAsDefault, path: path, regex: regex, serializer: serializer, data: data }); this.redirectTo = redirectTo; } return Redirect; }(AbstractRoute)); exports.Redirect = Redirect; //# sourceMappingURL=route_config_impl.js.map
# input a directory, each file is a document import sys from os import listdir from os.path import isfile, getmtime, exists from time import time import numpy as np from gensim import corpora, models, matutils from topic.topicio import TopicIO from preprocess.DocTokenizer import DirDocTokenizer, FileDocTokenizer from utils.corpus import BinaryCorpus # # syntax: python GenSimTweetTest1.py <input type> <directory name> <# of topics> <corpus type> <preprocess or not> <topics output> # <input type> 0: a file in which each line is a document. # Anything else or missing: a directory in which each file is a document # <directory/file name> input directory/file name # <# of topics> default to 8 # <corpus type> default to bag of words. b for binary, t for tf-idf, anything else or missing for bag of words # <preprocess or not>:0 = no preprocessing. Anything else or missing: preprocessing # <topics output> topic output directory name. default to topics_output # # each file in the directory is a document # # # # Read command line parameters # if len(sys.argv) <= 1: input_type = True else: if int(sys.argv[1]) == 0: input_type = False else: input_type = True if len(sys.argv) <= 2: src = "pp_data" else: src = sys.argv[2]; if len(sys.argv) <= 3: topics_count = 4; else: topics_count = int(sys.argv[3]); if len(sys.argv) <= 4: corpus_type = "c" else: corpus_type = sys.argv[4] if len(sys.argv) <= 5: preprocess = False else: if int(sys.argv[5]) == 0: preprocess = False else: preprocess = True if len(sys.argv) <= 6: t_output = "t_topics_output" else: t_output = sys.argv[6] print "input type :", if input_type: print "Input is a directory" else: print "Input is a file" print "source : " + src print "tcount : " + str(topics_count) print "corpus type :", if corpus_type == "t": print "tfidf" elif corpus_type == "b": print "binary" else: print "bow" print "preprocess : " + str(preprocess) print "topics output directory name : " + t_output # Check whether the directory exists or not if not exists(src): print ("Input source does not exist") exit() if input_type: # if input is a directory mdt = DirDocTokenizer() # According to the <preprocess> param, determine whether the input corpus should be preprocessed or not if not preprocess: doc_list, token_list = mdt.orig(src) else: # Execution in the past resulted in existing preprocessed directory. # Determine whether # a) an up-to-date preprocessed directory is available to use # or b) the original input directory should be used. pp_dir_use = True # indicate whether the preprocessed directory or the input directory should be used pp_dir = "pp_" + src # the name of a possibly existing preprocessed directory if not exists(pp_dir): # if the preprocessed directory does not exist, use the input directory pp_dir_use = False else: # When the preprocessed directory exists, # go through each file in the input directory and the found preprocessed directoary. # If the preprocessed directory satisfies these two requirements: # 1. Every original file has a corresponding preprocessed file # 2. Every preprocessed file 's last-modification time is later that that of the original file # Then ,the existing preprocessed directory will be used. # Else, the input directory will be used. for fname in listdir(src): orig_file_name = src + "/" + fname pp_file_name = pp_dir + "/" + fname if not isfile(pp_file_name) or getmtime(orig_file_name) > getmtime(pp_file_name): pp_dir_use = False break # Choose the appropriate directory to use if pp_dir_use: print ("PreProcessed Files exist and are up-to-date.\n") doc_list, token_list = mdt.orig(pp_dir) else: doc_list, token_list = mdt.preprocess(src) else: # if input is a file mdt = FileDocTokenizer() if not preprocess: doc_list, token_list = mdt.orig(src) else: mtime_input = getmtime(src) output_tokens = "pp_" + src output_docs = "docs_pp_" + src if isfile(output_tokens) and isfile(output_docs) and getmtime(output_tokens) > mtime_input and getmtime( output_docs) > mtime_input: print ("PreProcessed Files exist.\n") token_list = mdt.orig(src)[1] doc_list = mdt.read_pp_doc_list(src) else: doc_list, token_list = mdt.preprocess(src) # Prepare the directory dictionary = corpora.Dictionary(token_list) print(dictionary) # Generate the bow corpus corpus_bow = [dictionary.doc2bow(text) for text in token_list] # According to the argument corpus_type, select the suitable corpus to use in the following processing if corpus_type == 't': corpus_type = "tfidf" tfidf = models.TfidfModel(corpus_bow) corpus = tfidf[corpus_bow] elif corpus_type == 'b': corpus_type = "binary" corpus = BinaryCorpus(corpus_bow) else: corpus_type = "bow" corpus = corpus_bow # # Latent Semantic Indexing Model # (Notice we build the model based on TFIDF # print "=========== start LSI" lsi = models.LsiModel(corpus, id2word=dictionary, num_topics=topics_count) # # print LSI document vector for each document # # # print lsi # corpus_lsi = lsi[corpus] print corpus_lsi for doc in corpus_lsi: print doc # # print the topics for LSI # print "=========== topics" topic = lsi.print_topics(topics_count, 50) for x in topic: print x # # LDA # Pick the corpus to use # topics_io = TopicIO() print "=========== start LDA" start_time = time() lda = models.LdaModel(corpus, id2word=dictionary, num_topics=topics_count, minimum_probability=-1) corpus_lda = lda[corpus] print "======" # topic = lda.print_topics(topics_count, 10) # for x in topic: # print x topics_io.write_topics(model=lda, orig_dir=src, num_topics=topics_count, num_words=len(dictionary.keys()), output_dir=t_output) # # For each topic: print the top 20 words and all the tweets that has non-trivial probability associated with it (which is defined as (1.01/# of topics) # # convert LDA corpus back to dense matrix represnetation (to enable the argsort statement to work properly # now each row is a topic, so can use the argsort c1 = matutils.corpus2dense(corpus_lda, topics_count) i = 0 for q in c1: print "=======" x1 = [w for w in np.argsort(q) if q[w] > 1.01 / topics_count] print "LDATopic " + str(i) + " " + lda.print_topic(i, 20) print x1 for x2 in x1[::-1]: print str(x2) + " ", print doc_list[x2] + " ", # print token_list[x2], # print " ", print q[x2] i = i + 1 # Print the topics again (but with 50 words) # # print "======" topic = lda.print_topics(topics_count, 50) for x in topic: print x for i in range(1, 100): x2 = [(i, 1)] x3 = lda[x2] print repr(x3) # # HDPA (ignore for now) # # print "=========== start HDPA" # hdp = models.HdpModel(corpus_tfidf, id2word=dictionary) # hdp = models.HdpModel(corpus, id2word=dictionary) # hdp = models.HdpModel(corpus_binary, id2word=dictionary) # for l in hdp.show_topics(-1, 40): # print l
/* * Simple Open Pixel Control client for Node.js * * 2013-2014 Micah Elizabeth Scott * This file is released into the public domain. */ var net = require('net'); var fs = require('fs'); /******************************************************************************** * Core OPC Client */ var OPC = function(host, port) { this.host = host; this.port = port; this.pixelBuffer = null; }; OPC.prototype._reconnect = function() { var _this = this; this.socket = new net.Socket(); this.connected = false; this.socket.on('close', function() { console.log("Fadecandy Client - Connection closed"); _this.socket = null; _this.connected = false; }); this.socket.on('error', function(error) { console.error('Fadecandy Client - Could not connect to Fadecandy Server.'); }); this.socket.connect(this.port, this.host, function() { console.log("Fadecandy Client - Connected to " + _this.socket.remoteAddress); _this.connected = true; _this.socket.setNoDelay(); }); }; OPC.prototype.writePixels = function() { if (!this.socket) { this._reconnect(); } if (!this.connected) { return; } this.socket.write(this.pixelBuffer); }; OPC.prototype.setPixelCount = function(num) { var length = 4 + num*3; if (this.pixelBuffer === null || this.pixelBuffer.length != length) { this.pixelBuffer = new Buffer(length); } // Initialize OPC header this.pixelBuffer.writeUInt8(0, 0); // Channel this.pixelBuffer.writeUInt8(0, 1); // Command this.pixelBuffer.writeUInt16BE(num * 3, 2); // Length }; OPC.prototype.setPixel = function(num, r, g, b) { var offset = 4 + num*3; if (this.pixelBuffer === null || offset + 3 > this.pixelBuffer.length) { this.setPixelCount(num + 1); } this.pixelBuffer.writeUInt8(Math.max(0, Math.min(255, r | 0)), offset); this.pixelBuffer.writeUInt8(Math.max(0, Math.min(255, g | 0)), offset + 1); this.pixelBuffer.writeUInt8(Math.max(0, Math.min(255, b | 0)), offset + 2); }; OPC.prototype.mapPixels = function(fn, model) { // Set all pixels, by mapping each element of "model" through "fn" and setting the // corresponding pixel value. The function returns a tuple of three 8-bit RGB values. // Implies 'writePixels' as well. Has no effect if the OPC client is disconnected. if (!this.socket) { this._reconnect(); } if (!this.connected) { return; } this.setPixelCount(model.length); var offset = 4; var unused = [0, 0, 0]; // Color for unused channels (null model) for (var i = 0; i < model.length; i++) { var led = model[i]; var rgb = led ? fn(led) : unused; this.pixelBuffer.writeUInt8(Math.max(0, Math.min(255, rgb[0] | 0)), offset); this.pixelBuffer.writeUInt8(Math.max(0, Math.min(255, rgb[1] | 0)), offset + 1); this.pixelBuffer.writeUInt8(Math.max(0, Math.min(255, rgb[2] | 0)), offset + 2); offset += 3; } this.writePixels(); }; /******************************************************************************** * Client convenience methods */ OPC.prototype.mapParticles = function(particles, model) { // Set all pixels, by mapping a particle system to each element of "model". // The particles include parameters 'point', 'intensity', 'falloff', and 'color'. function shader(p) { var r = 0; var g = 0; var b = 0; for (var i = 0; i < particles.length; i++) { var particle = particles[i]; // Particle to sample distance var dx = (p.point[0] - particle.point[0]) || 0; var dy = (p.point[1] - particle.point[1]) || 0; var dz = (p.point[2] - particle.point[2]) || 0; var dist2 = dx * dx + dy * dy + dz * dz; // Particle edge falloff var intensity = particle.intensity / (1 + particle.falloff * dist2); // Intensity scaling r += particle.color[0] * intensity; g += particle.color[1] * intensity; b += particle.color[2] * intensity; } return [r, g, b]; } this.mapPixels(shader, model); }; /******************************************************************************** * Global convenience methods */ OPC.loadModel = function(filename) { // Synchronously load a JSON model from a file on disk return JSON.parse(fs.readFileSync(filename)); }; OPC.hsv = function(h, s, v) { /* * Converts an HSV color value to RGB. * * Normal hsv range is in [0, 1], RGB range is [0, 255]. * Colors may extend outside these bounds. Hue values will wrap. * * Based on tinycolor: * https://github.com/bgrins/TinyColor/blob/master/tinycolor.js * 2013-08-10, Brian Grinstead, MIT License */ h = (h % 1) * 6; if (h < 0) h += 6; var i = h | 0, f = h - i, p = v * (1 - s), q = v * (1 - f * s), t = v * (1 - (1 - f) * s), r = [v, q, p, p, t, v][i], g = [t, v, v, q, p, p][i], b = [p, p, t, v, v, q][i]; return [ r * 255, g * 255, b * 255 ]; }; module.exports = OPC;
from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import include, path from django.views import defaults as default_views from django.views.generic import TemplateView from rest_framework.authtoken.views import obtain_auth_token urlpatterns = [ path("", TemplateView.as_view(template_name="pages/home.html"), name="home"), path( "about/", TemplateView.as_view(template_name="pages/about.html"), name="about" ), # Django Admin, use {% url 'admin:index' %} path(settings.ADMIN_URL, admin.site.urls), # User management path("users/", include("django_jobs.users.urls", namespace="users")), path("accounts/", include("allauth.urls")), # Your stuff: custom urls includes go here path('jobs/',include('jobs.urls',namespace='jobs')), path('newsletter/',include('newsletter.urls',namespace='newsletter')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # API URLS urlpatterns += [ # API base url path("api/", include("config.api_router")), # DRF auth token path("auth-token/", obtain_auth_token), ] if settings.DEBUG: # This allows the error pages to be debugged during development, just visit # these url in browser to see how these error pages look like. urlpatterns += [ path( "400/", default_views.bad_request, kwargs={"exception": Exception("Bad Request!")}, ), path( "403/", default_views.permission_denied, kwargs={"exception": Exception("Permission Denied")}, ), path( "404/", default_views.page_not_found, kwargs={"exception": Exception("Page not Found")}, ), path("500/", default_views.server_error), ] if "debug_toolbar" in settings.INSTALLED_APPS: import debug_toolbar urlpatterns = [path("__debug__/", include(debug_toolbar.urls))] + urlpatterns
# 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. from aliyunsdkcore.request import RpcRequest from aliyunsdknas.endpoint import endpoint_data class DescribeAccessRulesRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'NAS', '2017-06-26', 'DescribeAccessRules','nas') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_FileSystemType(self): return self.get_query_params().get('FileSystemType') def set_FileSystemType(self,FileSystemType): self.add_query_param('FileSystemType',FileSystemType) def get_PageNumber(self): return self.get_query_params().get('PageNumber') def set_PageNumber(self,PageNumber): self.add_query_param('PageNumber',PageNumber) def get_PageSize(self): return self.get_query_params().get('PageSize') def set_PageSize(self,PageSize): self.add_query_param('PageSize',PageSize) def get_AccessRuleId(self): return self.get_query_params().get('AccessRuleId') def set_AccessRuleId(self,AccessRuleId): self.add_query_param('AccessRuleId',AccessRuleId) def get_AccessGroupName(self): return self.get_query_params().get('AccessGroupName') def set_AccessGroupName(self,AccessGroupName): self.add_query_param('AccessGroupName',AccessGroupName)
import React, { Component } from 'react' import Slider from "react-slick"; import SliderImage from './SliderImage'; import ArrowComponent from './ArrowComponent' export default class SimpleSlider extends Component { render() { let settings = { // className: "center", // centerMode: true, // nextArrow: <ArrowComponent direction={"right"}/>, // prevArrow: <ArrowComponent direction={"left"}/>, dots: true, infinite: true, speed: 500, slidesToShow: 4, slidesToScroll: 1, initialSlide: 3, responsive: [ { breakpoint: 1024, settings: { slidesToShow: 3, slidesToScroll: 3, infinite: true, dots: true } }, { breakpoint: 600, settings: { slidesToShow: 2, slidesToScroll: 2, initialSlide: 2 } }, { breakpoint: 480, settings: { slidesToShow: 1, slidesToScroll: 1 } } ] } return ( <Slider {...settings} > {photoArr.map((image, idx) => { return <SliderImage image={image} key={idx}/> }) } </Slider> ) } } let photoArr = [ `https://instagram.com/p/Bo17O2pFYf1/media/?size=l`, `https://instagram.com/p/BpXI3N7h4WQ/media/?size=l`, `https://instagram.com/p/Bl29CvAh21k/media/?size=l`, `https://instagram.com/p/Bk5JLJTHQHz/media/?size=l`, `https://instagram.com/p/BjjSVQ7jte4/media/?size=l`, `https://instagram.com/p/BpcRdthhCmR/media/?size=l`, `https://instagram.com/p/BlJBQgvHdMx/media/?size=l`, `https://instagram.com/p/BoKDd8PHkvM/media/?size=l` ] let wembie = 'https://www.instagram.com/vvembie/';
import React, { Fragment } from 'react' import PropTypes from 'prop-types' import styled from 'styled-components' import { Row, Col } from 'react-flexbox-grid' import Section from './common/Section' import media from '../theme/media' const ModuleSection = styled(Section)` padding: 100px 0; ${media.xs` padding: 40px 0 20px; `}; ` const ModuleNumber = styled.div` border: 1px solid ${({ theme }) => theme.colors.text}; border-radius: 50%; height: 120px; width: 120px; display: flex; justify-content: center; align-items: center; span { color: ${({ theme }) => theme.colors.text}; font-weight: ${({ theme }) => theme.font.weight.bold}; font-size: ${({ theme }) => theme.font.size.large}; } ${media.xs` height: 60px; width: 60px; span { font-size: 20px; } `}; ` const ModuleTitle = styled.h2` font-size: ${({ theme }) => theme.font.size.large}; font-weight: ${({ theme }) => theme.font.weight.bold}; line-height: 1.4; text-align: left; color: ${({ theme }) => theme.colors.primary}; ${media.xs` padding-left: 15px; font-size: 20px; `}; ` const ModuleDescription = styled.p` font-size: ${({ theme }) => theme.font.size.medium}; font-weight: ${({ theme }) => theme.font.weight.light}; line-height: 1.6; text-align: left; color: ${({ theme }) => theme.colors.text}; ${media.xs` font-size: ${({ theme }) => theme.font.size.regular}; padding: 25px 0 40px; `}; ` const Line = styled.span` position: relative; width: 100%; height: 100%; display: ${({ lastItem }) => (lastItem === 'last' ? 'none' : 'flex')}; ::before { content: ''; width: 1px; height: 100%; background: ${({ theme }) => theme.colors.darkText}; display: flex; position: absolute; top: 0; left: 60px; } ` const CourseModules = ({ modules }) => ( <ModuleSection bgColor="footer"> {modules.map(({ title, description }, index) => ( <Fragment key={title}> <Row middle="xs" center="xs"> <Col xs={2} md={2}> <ModuleNumber> <span>{index + 1}</span> </ModuleNumber> </Col> <Col xs={10} md={8}> <ModuleTitle>{title}</ModuleTitle> </Col> </Row> <Row center="xs"> <Col xs={0} md={2}> <Line lastItem={index === modules.length - 1 ? 'last' : 'none'} /> </Col> <Col xs={12} md={8}> <ModuleDescription>{description}</ModuleDescription> </Col> </Row> </Fragment> ))} </ModuleSection> ) CourseModules.propTypes = { modules: PropTypes.shape({ title: PropTypes.string, description: PropTypes.string, }).isRequired, } export default CourseModules
#!/usr/bin/env python3 import os import sys import subprocess import random import re import string from urllib.parse import urlparse REPLACEX = re.compile(r"[^-_a-zA-Z0-9]") TIME_LIMIT = float( os.environ.get("TIMEOUT", 300.0) ) # seconds (5 minutes, per seed-crawl) def main(argv): if len(argv) < 3: print(f"usage: {argv[0]} SCRIPT URL1 [URL2 [...]]") exit(2) script_name = argv[1] for url in argv[2:]: cmd_argv = [ "node", script_name, url, ] cmd_options = { "cwd": os.path.dirname(__file__), "stdout": sys.stdout, "stderr": sys.stderr, "check": True, "timeout": TIME_LIMIT, } try: subprocess.run(cmd_argv, **cmd_options) except subprocess.TimeoutExpired: print("TIMEOUT", flush=True, file=sys.stderr) if __name__ == "__main__": main(sys.argv)
# coding: utf-8 from util import laplacian_1D, laplacian_2D def schrodinger_flow_1D(t, psi, potential, dx): """ The flow part of the 2 dimensional Schrödinger equation. """ return 1j * laplacian_1D(psi, dx) - 1j * potential[1:-1] * psi[1:-1] def schrodinger_flow_2D(t, psi, potential, dx): """ The flow part of the 2 dimensional Schrödinger equation. """ return 1j * laplacian_2D(psi, dx) - 1j * potential[1:-1, 1:-1] * psi[1:-1, 1:-1]
from celery import Celery from .config import settings celery_app = Celery( "cava-data", broker=settings.RABBITMQ_URI, backend=settings.REDIS_URI ) celery_app.conf.task_routes = { "app.api.workers.tasks.perform_fetch_task": {"queue": "data-queue"} }
class Solution: def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]: res = [] greatest = max(candies) for p in candies: if p+extraCandies < greatest: res.append(False) else: res.append(True) return res
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # import os import sys sys.path.insert(0, os.path.abspath(os.path.join('..', 'resources', 'scripts'))) # -- Project information ----------------------------------------------------- project = 'JPL-Sphinx' copyright = '2021, Keysight Technologies' author = 'Keysight Labs DevOps Team' pygments_style = 'sphinx' # The full version, including alpha/beta/rc tags release = '1.0.0' # -- General configuration --------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinxarg.ext', 'sphinx.ext.autosectionlabel', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'sphinx_rtd_theme' # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # These paths are either relative to html_static_path # or fully qualified paths (eg. https://...) html_css_files = [ 'css/custom.css', ] html_theme_options = { 'display_version': True } ############################ # SETUP THE RTD LOWER-LEFT # ############################ html_context = { 'display_lower_left': True, 'current_language': 'en', 'current_version': release, 'version': release, 'languages': list(), 'versions': [('1.0.0', '/JPL-Sphinx/1.0.0/'), ('2.0.0', '/JPL-Sphinx/2.0.0/')], 'downloads': list(), } templates_path = ['_templates']
define(function (require, exports, module) { var $ = require('./jquery'); var ajax = require('./ajax'); var list = require("./list"); var option = require("./option"); var loading = require("./loading"); var dialog = require("./dialog"); var pub = require("./public"); $(document).ready(function () { pub.menuCollapseHandler(); pub.searchCollapseHandler(); pub.activeMenu("#oracle-map-export"); pub.bindDatePicker($("#q-submitBeginTime")); pub.bindDatePicker($("#q-submitEndTime")); pub.bindDatePicker($("#q-payBeginTime")); pub.bindDatePicker($("#q-payEndTime")); $("#q-expensecatalog").bind("change", function (e) { var catalog = $(this).val(); }); $("#export").bind("click", function () { var url = '/pc/expense/mappingExport?'; var params = ""; params += "&expenseCatalog=" + document.getElementById("q-expensecatalog").value; if (document.getElementById("q-submitBeginTime").value) { params += "&submitBeginTime=" + document.getElementById("q-submitBeginTime").value; } if (document.getElementById("q-submitEndTime").value) { params += "&submitEndTime=" + document.getElementById("q-submitEndTime").value; } if (document.getElementById("q-payBeginTime").value) { params += "&payBeginTime=" + document.getElementById("q-payBeginTime").value; } if (document.getElementById("q-payEndTime").value) { params += "&payEndTime=" + document.getElementById("q-payEndTime").value; } url+=params; window.open(url, '_blank'); }); $('#q-payBeginTime').val(pub.getDateThreeMonthBefore(pub.getNowFormatDate())); $('#q-payEndTime').val(pub.getNowFormatDate()); $("#q-expensecatalog").trigger("change"); }); function showDialog(dialog, title, content) { dialog.find(".ex-modal-title").text(title); dialog.find(".inner-content").html(content); dialog.show(); dialog.css({"position": "fixed"}); dialog.css({"top": "10px"}); dialog.css({"left": Math.max(0, (($(window).width() - dialog.width()) / 2) + $(window).scrollLeft()) + "px"}); var maskHtml = '<div class="ex-modal-backdrop"></div>'; $(maskHtml).prependTo(document.body); } });
const UserModel = require('./user.model'); const JobModel = require('./job.model'); module.exports = { UserModel, JobModel };
/* * Copyright (c) 2015 Martin Mitas * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "mousedrag.h" static mc_mutex_t mousedrag_mutex; static BOOL mousedrag_running = FALSE; static HWND mousedrag_win = NULL; int mousedrag_start_x; int mousedrag_start_y; int mousedrag_hotspot_x; int mousedrag_hotspot_y; int mousedrag_index; UINT_PTR mousedrag_extra; BOOL mousedrag_set_candidate(HWND win, int start_x, int start_y, int hotspot_x, int hotspot_y, int index, UINT_PTR extra) { BOOL ret = FALSE; mc_mutex_lock(&mousedrag_mutex); if(!mousedrag_running) { mousedrag_win = win; mousedrag_start_x = start_x; mousedrag_start_y = start_y; mousedrag_hotspot_x = hotspot_x; mousedrag_hotspot_y = hotspot_y; mousedrag_index = index; mousedrag_extra = extra; ret = TRUE; } else { /* Dragging (of different window?) is already running. Actually this * should happen normally only if the two windows live in different * threads, because the mousedrag_win should have the mouse captured. */ MC_ASSERT(mousedrag_win != NULL); MC_ASSERT(GetWindowThreadProcessId(win, NULL) != GetWindowThreadProcessId(mousedrag_win, NULL)); } mc_mutex_unlock(&mousedrag_mutex); return ret; } mousedrag_state_t mousedrag_consider_start(HWND win, int x, int y) { mousedrag_state_t ret; mc_mutex_lock(&mousedrag_mutex); if(!mousedrag_running && win == mousedrag_win) { int drag_cx, drag_cy; RECT rect; drag_cx = GetSystemMetrics(SM_CXDRAG); drag_cy = GetSystemMetrics(SM_CYDRAG); rect.left = mousedrag_start_x - drag_cx; rect.top = mousedrag_start_y - drag_cy; rect.right = mousedrag_start_x + drag_cx + 1; rect.bottom = mousedrag_start_y + drag_cy + 1; if(!mc_rect_contains_xy(&rect, x, y)) { mousedrag_running = TRUE; ret = MOUSEDRAG_STARTED; } else { /* Still not clear whether we should start the dragging. Maybe * next WM_MOUSEMOVE will finally decide it. */ ret = MOUSEDRAG_CONSIDERING; } } else { ret = MOUSEDRAG_CANCELED; } mc_mutex_unlock(&mousedrag_mutex); return ret; } mousedrag_state_t mousedrag_start(HWND win, int start_x, int start_y) { mousedrag_state_t ret; mc_mutex_lock(&mousedrag_mutex); if(!mousedrag_running) { mousedrag_running = TRUE; mousedrag_win = win; mousedrag_start_x = start_x; mousedrag_start_y = start_y; ret = MOUSEDRAG_STARTED; } else { ret = MOUSEDRAG_CANCELED; } mc_mutex_unlock(&mousedrag_mutex); return ret; } void mousedrag_stop(HWND win) { mc_mutex_lock(&mousedrag_mutex); MC_ASSERT(mousedrag_running); MC_ASSERT(win == mousedrag_win); mousedrag_running = FALSE; mc_mutex_unlock(&mousedrag_mutex); } BOOL mousedrag_lock(HWND win) { if(win != mousedrag_win) return FALSE; mc_mutex_lock(&mousedrag_mutex); if(win != mousedrag_win) { mc_mutex_unlock(&mousedrag_mutex); return FALSE; } return TRUE; } void mousedrag_unlock(void) { mc_mutex_unlock(&mousedrag_mutex); } void mousedrag_dllmain_init(void) { mc_mutex_init(&mousedrag_mutex); } void mousedrag_dllmain_fini(void) { mc_mutex_fini(&mousedrag_mutex); }
var searchData= [ ['jointinterpolations_300',['jointInterpolations',['../class_s_g_core_1_1_kinematics_1_1_hand_interpolator.html#a4b0e5cef2bc6b98b53af38930871b40b',1,'SGCore::Kinematics::HandInterpolator']]], ['jointkinematics_2ecs_301',['JointKinematics.cs',['../_joint_kinematics_8cs.html',1,'']]], ['jointpositions_302',['jointPositions',['../class_s_g_core_1_1_hand_pose.html#a02fe71bb8bd1e440878311f7fb7ca625',1,'SGCore::HandPose']]], ['jointpositions_303',['JointPositions',['../class_s_g_core_1_1_s_g_1_1_s_g___glove_pose.html#a06eec541d721ed45412cf20c44b30d28',1,'SGCore::SG::SG_GlovePose']]], ['jointrotations_304',['JointRotations',['../class_s_g_core_1_1_s_g_1_1_s_g___glove_pose.html#a4bf185843933856ddd785db0c7608f90',1,'SGCore::SG::SG_GlovePose']]], ['jointrotations_305',['jointRotations',['../class_s_g_core_1_1_hand_pose.html#a591fe7ee38c451dec82ecfdf53b5418c',1,'SGCore::HandPose']]] ];
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2014 Damien P. George * Copyright (c) 2014-2016 Paul Sokolovsky * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <string.h> #include <unistd.h> #include "py/objstr.h" #include "py/stream.h" #include "py/runtime.h" // This file defines generic Python stream read/write methods which // dispatch to the underlying stream interface of an object. // TODO: should be in mpconfig.h #define DEFAULT_BUFFER_SIZE 256 STATIC mp_obj_t stream_readall(mp_obj_t self_in); #define STREAM_CONTENT_TYPE(stream) (((stream)->is_text) ? &mp_type_str : &mp_type_bytes) // Returns error condition in *errcode, if non-zero, return value is number of bytes written // before error condition occurred. If *errcode == 0, returns total bytes written (which will // be equal to input size). mp_uint_t mp_stream_rw(mp_obj_t stream, void *buf_, mp_uint_t size, int *errcode, byte flags) { byte *buf = buf_; typedef mp_uint_t (*io_func_t)(mp_obj_t obj, void *buf, mp_uint_t size, int *errcode); io_func_t io_func; const mp_stream_p_t *stream_p = mp_get_stream(stream); if (flags & MP_STREAM_RW_WRITE) { io_func = (io_func_t)stream_p->write; } else { io_func = stream_p->read; } *errcode = 0; mp_uint_t done = 0; while (size > 0) { mp_uint_t out_sz = io_func(stream, buf, size, errcode); // For read, out_sz == 0 means EOF. For write, it's unspecified // what it means, but we don't make any progress, so returning // is still the best option. if (out_sz == 0) { return done; } if (out_sz == MP_STREAM_ERROR) { // If we read something before getting EAGAIN, don't leak it if (mp_is_nonblocking_error(*errcode) && done != 0) { *errcode = 0; } return done; } if (flags & MP_STREAM_RW_ONCE) { return out_sz; } buf += out_sz; size -= out_sz; done += out_sz; } return done; } const mp_stream_p_t *mp_get_stream_raise(mp_obj_t self_in, int flags) { const mp_obj_type_t *type = mp_obj_get_type(self_in); const mp_stream_p_t *stream_p = type->protocol; if (stream_p == NULL || ((flags & MP_STREAM_OP_READ) && stream_p->read == NULL) || ((flags & MP_STREAM_OP_WRITE) && stream_p->write == NULL) || ((flags & MP_STREAM_OP_IOCTL) && stream_p->ioctl == NULL)) { // CPython: io.UnsupportedOperation, OSError subclass mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("stream operation not supported")); } return stream_p; } STATIC mp_obj_t stream_read_generic(size_t n_args, const mp_obj_t *args, byte flags) { // What to do if sz < -1? Python docs don't specify this case. // CPython does a readall, but here we silently let negatives through, // and they will cause a MemoryError. mp_int_t sz; if (n_args == 1 || ((sz = mp_obj_get_int(args[1])) == -1)) { return stream_readall(args[0]); } const mp_stream_p_t *stream_p = mp_get_stream(args[0]); #if MICROPY_PY_BUILTINS_STR_UNICODE if (stream_p->is_text) { // We need to read sz number of unicode characters. Because we don't have any // buffering, and because the stream API can only read bytes, we must read here // in units of bytes and must never over read. If we want sz chars, then reading // sz bytes will never over-read, so we follow this approach, in a loop to keep // reading until we have exactly enough chars. This will be 1 read for text // with ASCII-only chars, and about 2 reads for text with a couple of non-ASCII // chars. For text with lots of non-ASCII chars, it'll be pretty inefficient // in time and memory. vstr_t vstr; vstr_init(&vstr, sz); mp_uint_t more_bytes = sz; mp_uint_t last_buf_offset = 0; while (more_bytes > 0) { char *p = vstr_add_len(&vstr, more_bytes); int error; mp_uint_t out_sz = mp_stream_read_exactly(args[0], p, more_bytes, &error); if (error != 0) { vstr_cut_tail_bytes(&vstr, more_bytes); if (mp_is_nonblocking_error(error)) { // With non-blocking streams, we read as much as we can. // If we read nothing, return None, just like read(). // Otherwise, return data read so far. // TODO what if we have read only half a non-ASCII char? if (vstr.len == 0) { vstr_clear(&vstr); return mp_const_none; } break; } mp_raise_OSError(error); } if (out_sz < more_bytes) { // Finish reading. // TODO what if we have read only half a non-ASCII char? vstr_cut_tail_bytes(&vstr, more_bytes - out_sz); if (out_sz == 0) { break; } } // count chars from bytes just read for (mp_uint_t off = last_buf_offset;;) { byte b = vstr.buf[off]; int n; if (!UTF8_IS_NONASCII(b)) { // 1-byte ASCII char n = 1; } else if ((b & 0xe0) == 0xc0) { // 2-byte char n = 2; } else if ((b & 0xf0) == 0xe0) { // 3-byte char n = 3; } else if ((b & 0xf8) == 0xf0) { // 4-byte char n = 4; } else { // TODO n = 5; } if (off + n <= vstr.len) { // got a whole char in n bytes off += n; sz -= 1; last_buf_offset = off; if (off >= vstr.len) { more_bytes = sz; break; } } else { // didn't get a whole char, so work out how many extra bytes are needed for // this partial char, plus bytes for additional chars that we want more_bytes = (off + n - vstr.len) + (sz - 1); break; } } } return mp_obj_new_str_from_vstr(&mp_type_str, &vstr); } #endif vstr_t vstr; vstr_init_len(&vstr, sz); int error; mp_uint_t out_sz = mp_stream_rw(args[0], vstr.buf, sz, &error, flags); if (error != 0) { vstr_clear(&vstr); if (mp_is_nonblocking_error(error)) { // https://docs.python.org/3.4/library/io.html#io.RawIOBase.read // "If the object is in non-blocking mode and no bytes are available, // None is returned." // This is actually very weird, as naive truth check will treat // this as EOF. return mp_const_none; } mp_raise_OSError(error); } else { vstr.len = out_sz; return mp_obj_new_str_from_vstr(STREAM_CONTENT_TYPE(stream_p), &vstr); } } STATIC mp_obj_t stream_read(size_t n_args, const mp_obj_t *args) { return stream_read_generic(n_args, args, MP_STREAM_RW_READ); } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_stream_read_obj, 1, 2, stream_read); STATIC mp_obj_t stream_read1(size_t n_args, const mp_obj_t *args) { return stream_read_generic(n_args, args, MP_STREAM_RW_READ | MP_STREAM_RW_ONCE); } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_stream_read1_obj, 1, 2, stream_read1); mp_obj_t mp_stream_write(mp_obj_t self_in, const void *buf, size_t len, byte flags) { int error; mp_uint_t out_sz = mp_stream_rw(self_in, (void *)buf, len, &error, flags); if (error != 0) { if (mp_is_nonblocking_error(error)) { // http://docs.python.org/3/library/io.html#io.RawIOBase.write // "None is returned if the raw stream is set not to block and // no single byte could be readily written to it." return mp_const_none; } mp_raise_OSError(error); } else { return MP_OBJ_NEW_SMALL_INT(out_sz); } } // This is used to adapt a stream object to an mp_print_t interface void mp_stream_write_adaptor(void *self, const char *buf, size_t len) { mp_stream_write(MP_OBJ_FROM_PTR(self), buf, len, MP_STREAM_RW_WRITE); } STATIC mp_obj_t stream_write_method(size_t n_args, const mp_obj_t *args) { mp_buffer_info_t bufinfo; mp_get_buffer_raise(args[1], &bufinfo, MP_BUFFER_READ); size_t max_len = (size_t)-1; size_t off = 0; if (n_args == 3) { max_len = mp_obj_get_int_truncated(args[2]); } else if (n_args == 4) { off = mp_obj_get_int_truncated(args[2]); max_len = mp_obj_get_int_truncated(args[3]); if (off > bufinfo.len) { off = bufinfo.len; } } bufinfo.len -= off; return mp_stream_write(args[0], (byte *)bufinfo.buf + off, MIN(bufinfo.len, max_len), MP_STREAM_RW_WRITE); } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_stream_write_obj, 2, 4, stream_write_method); STATIC mp_obj_t stream_write1_method(mp_obj_t self_in, mp_obj_t arg) { mp_buffer_info_t bufinfo; mp_get_buffer_raise(arg, &bufinfo, MP_BUFFER_READ); return mp_stream_write(self_in, bufinfo.buf, bufinfo.len, MP_STREAM_RW_WRITE | MP_STREAM_RW_ONCE); } MP_DEFINE_CONST_FUN_OBJ_2(mp_stream_write1_obj, stream_write1_method); STATIC mp_obj_t stream_readinto(size_t n_args, const mp_obj_t *args) { mp_buffer_info_t bufinfo; mp_get_buffer_raise(args[1], &bufinfo, MP_BUFFER_WRITE); // CPython extension: if 2nd arg is provided, that's max len to read, // instead of full buffer. Similar to // https://docs.python.org/3/library/socket.html#socket.socket.recv_into mp_uint_t len = bufinfo.len; if (n_args > 2) { len = mp_obj_get_int(args[2]); if (len > bufinfo.len) { len = bufinfo.len; } } int error; mp_uint_t out_sz = mp_stream_read_exactly(args[0], bufinfo.buf, len, &error); if (error != 0) { if (mp_is_nonblocking_error(error)) { return mp_const_none; } mp_raise_OSError(error); } else { return MP_OBJ_NEW_SMALL_INT(out_sz); } } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_stream_readinto_obj, 2, 3, stream_readinto); STATIC mp_obj_t stream_readall(mp_obj_t self_in) { const mp_stream_p_t *stream_p = mp_get_stream(self_in); mp_uint_t total_size = 0; vstr_t vstr; vstr_init(&vstr, DEFAULT_BUFFER_SIZE); char *p = vstr.buf; mp_uint_t current_read = DEFAULT_BUFFER_SIZE; while (true) { int error; mp_uint_t out_sz = stream_p->read(self_in, p, current_read, &error); if (out_sz == MP_STREAM_ERROR) { if (mp_is_nonblocking_error(error)) { // With non-blocking streams, we read as much as we can. // If we read nothing, return None, just like read(). // Otherwise, return data read so far. if (total_size == 0) { return mp_const_none; } break; } mp_raise_OSError(error); } if (out_sz == 0) { break; } total_size += out_sz; if (out_sz < current_read) { current_read -= out_sz; p += out_sz; } else { p = vstr_extend(&vstr, DEFAULT_BUFFER_SIZE); current_read = DEFAULT_BUFFER_SIZE; } } vstr.len = total_size; return mp_obj_new_str_from_vstr(STREAM_CONTENT_TYPE(stream_p), &vstr); } // Unbuffered, inefficient implementation of readline() for raw I/O files. STATIC mp_obj_t stream_unbuffered_readline(size_t n_args, const mp_obj_t *args) { const mp_stream_p_t *stream_p = mp_get_stream(args[0]); mp_int_t max_size = -1; if (n_args > 1) { max_size = MP_OBJ_SMALL_INT_VALUE(args[1]); } vstr_t vstr; if (max_size != -1) { vstr_init(&vstr, max_size); } else { vstr_init(&vstr, 16); } while (max_size == -1 || max_size-- != 0) { char *p = vstr_add_len(&vstr, 1); int error; mp_uint_t out_sz = stream_p->read(args[0], p, 1, &error); if (out_sz == MP_STREAM_ERROR) { if (mp_is_nonblocking_error(error)) { if (vstr.len == 1) { // We just incremented it, but otherwise we read nothing // and immediately got EAGAIN. This case is not well // specified in // https://docs.python.org/3/library/io.html#io.IOBase.readline // unlike similar case for read(). But we follow the latter's // behavior - return None. vstr_clear(&vstr); return mp_const_none; } else { goto done; } } mp_raise_OSError(error); } if (out_sz == 0) { done: // Back out previously added byte // Consider, what's better - read a char and get OutOfMemory (so read // char is lost), or allocate first as we do. vstr_cut_tail_bytes(&vstr, 1); break; } if (*p == '\n') { break; } } return mp_obj_new_str_from_vstr(STREAM_CONTENT_TYPE(stream_p), &vstr); } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_stream_unbuffered_readline_obj, 1, 2, stream_unbuffered_readline); // TODO take an optional extra argument (what does it do exactly?) STATIC mp_obj_t stream_unbuffered_readlines(mp_obj_t self) { mp_obj_t lines = mp_obj_new_list(0, NULL); for (;;) { mp_obj_t line = stream_unbuffered_readline(1, &self); if (!mp_obj_is_true(line)) { break; } mp_obj_list_append(lines, line); } return lines; } MP_DEFINE_CONST_FUN_OBJ_1(mp_stream_unbuffered_readlines_obj, stream_unbuffered_readlines); mp_obj_t mp_stream_unbuffered_iter(mp_obj_t self) { mp_obj_t l_in = stream_unbuffered_readline(1, &self); if (mp_obj_is_true(l_in)) { return l_in; } return MP_OBJ_STOP_ITERATION; } mp_obj_t mp_stream_close(mp_obj_t stream) { const mp_stream_p_t *stream_p = mp_get_stream(stream); int error; mp_uint_t res = stream_p->ioctl(stream, MP_STREAM_CLOSE, 0, &error); if (res == MP_STREAM_ERROR) { mp_raise_OSError(error); } return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_1(mp_stream_close_obj, mp_stream_close); STATIC mp_obj_t stream_seek(size_t n_args, const mp_obj_t *args) { struct mp_stream_seek_t seek_s; // TODO: Could be uint64 seek_s.offset = mp_obj_get_int(args[1]); seek_s.whence = MP_SEEK_SET; if (n_args == 3) { seek_s.whence = mp_obj_get_int(args[2]); } // In POSIX, it's error to seek before end of stream, we enforce it here. if (seek_s.whence == MP_SEEK_SET && seek_s.offset < 0) { mp_raise_OSError(MP_EINVAL); } const mp_stream_p_t *stream_p = mp_get_stream(args[0]); int error; mp_uint_t res = stream_p->ioctl(args[0], MP_STREAM_SEEK, (mp_uint_t)(uintptr_t)&seek_s, &error); if (res == MP_STREAM_ERROR) { mp_raise_OSError(error); } // TODO: Could be uint64 return mp_obj_new_int_from_uint(seek_s.offset); } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_stream_seek_obj, 2, 3, stream_seek); STATIC mp_obj_t stream_tell(mp_obj_t self) { mp_obj_t offset = MP_OBJ_NEW_SMALL_INT(0); mp_obj_t whence = MP_OBJ_NEW_SMALL_INT(MP_SEEK_CUR); const mp_obj_t args[3] = {self, offset, whence}; return stream_seek(3, args); } MP_DEFINE_CONST_FUN_OBJ_1(mp_stream_tell_obj, stream_tell); STATIC mp_obj_t stream_flush(mp_obj_t self) { const mp_stream_p_t *stream_p = mp_get_stream(self); int error; mp_uint_t res = stream_p->ioctl(self, MP_STREAM_FLUSH, 0, &error); if (res == MP_STREAM_ERROR) { mp_raise_OSError(error); } return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_1(mp_stream_flush_obj, stream_flush); STATIC mp_obj_t stream_ioctl(size_t n_args, const mp_obj_t *args) { mp_buffer_info_t bufinfo; uintptr_t val = 0; if (n_args > 2) { if (mp_get_buffer(args[2], &bufinfo, MP_BUFFER_WRITE)) { val = (uintptr_t)bufinfo.buf; } else { val = mp_obj_get_int_truncated(args[2]); } } const mp_stream_p_t *stream_p = mp_get_stream(args[0]); int error; mp_uint_t res = stream_p->ioctl(args[0], mp_obj_get_int(args[1]), val, &error); if (res == MP_STREAM_ERROR) { mp_raise_OSError(error); } return mp_obj_new_int(res); } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_stream_ioctl_obj, 2, 3, stream_ioctl); #if MICROPY_STREAMS_POSIX_API /* * POSIX-like functions * * These functions have POSIX-compatible signature (except for "void *stream" * first argument instead of "int fd"). They are useful to port existing * POSIX-compatible software to work with MicroPython streams. */ #include <errno.h> ssize_t mp_stream_posix_write(void *stream, const void *buf, size_t len) { mp_obj_base_t *o = stream; const mp_stream_p_t *stream_p = o->type->protocol; mp_uint_t out_sz = stream_p->write(MP_OBJ_FROM_PTR(stream), buf, len, &errno); if (out_sz == MP_STREAM_ERROR) { return -1; } else { return out_sz; } } ssize_t mp_stream_posix_read(void *stream, void *buf, size_t len) { mp_obj_base_t *o = stream; const mp_stream_p_t *stream_p = o->type->protocol; mp_uint_t out_sz = stream_p->read(MP_OBJ_FROM_PTR(stream), buf, len, &errno); if (out_sz == MP_STREAM_ERROR) { return -1; } else { return out_sz; } } off_t mp_stream_posix_lseek(void *stream, off_t offset, int whence) { const mp_obj_base_t *o = stream; const mp_stream_p_t *stream_p = o->type->protocol; struct mp_stream_seek_t seek_s; seek_s.offset = offset; seek_s.whence = whence; mp_uint_t res = stream_p->ioctl(MP_OBJ_FROM_PTR(stream), MP_STREAM_SEEK, (mp_uint_t)(uintptr_t)&seek_s, &errno); if (res == MP_STREAM_ERROR) { return -1; } return seek_s.offset; } int mp_stream_posix_fsync(void *stream) { mp_obj_base_t *o = stream; const mp_stream_p_t *stream_p = o->type->protocol; mp_uint_t res = stream_p->ioctl(MP_OBJ_FROM_PTR(stream), MP_STREAM_FLUSH, 0, &errno); if (res == MP_STREAM_ERROR) { return -1; } return res; } #endif
import doLookup from "./../../ui/utils/doLookup"; export default { Query: { searchPreviews(_, { searchTerm }) { return doLookup(searchTerm); } } };
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jul 15 15:32:11 2020 @author: liudongjin """ from URLManager import UrlManager from HTMLDownloader import HtmlDownloader from HTMLParser import HtmlParser from DataOutput import DataOutput class SpiderMan(object): '''爬虫调度器 Attributes: manager: URL管理器 downloader: HTML下载器 parser: HTML解析器 output: 数据存储器 ''' def __init__(self): self.manager = UrlManager() self.downloader = HtmlDownloader() self.parser = HtmlParser() self.output = DataOutput() def crawl(self, root_url): '''爬虫调度函数 Args: root_url: 爬虫入口URL Raises: Expection: 'NoneType' object has no attribute ''' self.manager.add_new_url(root_url) while(self.manager.has_new_url() and self.manager.old_url_size() < 100): try: new_url = self.manager.get_new_url() html = self.downloader.download(new_url) new_urls, data = self.parser.parser(new_url, html) self.manager.add_new_urls(new_urls) self.output.store_data(data) print('已经抓取了%s个链接' % self.manager.old_url_size()) except Exception as e: print('Crawl failed: %s' % e) self.output.output_html() if __name__ == '__main__': spider_man = SpiderMan() spider_man.crawl( 'https://baike.baidu.com/item/%E7%BD%91%E7%BB%9C%E7%88%AC%E8%99%AB/5162711?fr=aladdin')
# # SPDX-License-Identifier: Apache-2.0 # # Set default logging handler to avoid "No handler found" warnings. import logging try: # Python 2.7+ from logging import NullHandler except ImportError: class NullHandler(logging.Handler): def emit(self, record): pass logging.getLogger(__name__).addHandler(NullHandler())
""" * * Author: Juarez Paulino(coderemite) * Email: juarez.paulino@gmail.com * """ n=int(input()) p=[*map(int,input().split())] for k in range(n): print(p.index(k+1)+1,end=' ')
// Copyright 2010 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileOverview Functions for manipulating message channels. */ goog.provide('goog.messaging'); goog.forwardDeclare('goog.messaging.MessageChannel'); /** * Creates a bidirectional pipe between two message channels. * * @param {goog.messaging.MessageChannel} channel1 The first channel. * @param {goog.messaging.MessageChannel} channel2 The second channel. */ goog.messaging.pipe = function(channel1, channel2) { channel1.registerDefaultService(goog.bind(channel2.send, channel2)); channel2.registerDefaultService(goog.bind(channel1.send, channel1)); };
# -*- coding: utf-8 -*- """ Created on Tue Jul 7 18:40:37 CEST 2015 @author: Elena Cuoco simple starting script, without the use of MNE Thanks to @author: alexandrebarachant for his wornderful starting script """ import numpy as np import pandas as pd from scipy.signal import butter, lfilter, boxcar from numpy import convolve import matplotlib.pyplot as plt from sklearn.linear_model import LogisticRegression from glob import glob import os from sklearn.preprocessing import StandardScaler from sklearn.cross_validation import LeaveOneLabelOut from sklearn.metrics import roc_auc_score from sklearn.lda import LDA from sklearn.qda import QDA from sklearn.svm import SVC from sklearn import ensemble #from joblib import Parallel, delayed #############function to read data########### def prepare_data_train(fname): """ read and prepare training data """ # Read data data = pd.read_csv(fname) # events file events_fname = fname.replace('_data','_events') # read event file labels= pd.read_csv(events_fname) clean=data.drop(['id' ], axis=1)#remove id labels=labels.drop(['id' ], axis=1)#remove id return clean,labels def butterworth_filter(X,t,k,l): if t==0: freq=[k, l] b,a = butter(3,np.array(freq)/500.0,btype='bandpass') X = lfilter(b,a,X) elif t==1: b,a = butter(3,k/500.0,btype='lowpass') X = lfilter(b,a,X) elif t==2: b,a = butter(3,l/500.0,btype='highpass') X = lfilter(b,a,X) return X def prepare_data_test(fname): """ read and prepare test data """ # Read data data = pd.read_csv(fname) return data def get_fea(X, rand_num=0): m1,m2,m3,m4=150,300,600,1000 Xm=np.zeros(X.shape) Xs=np.zeros(X.shape) Xt=np.zeros(X.shape) Xu=np.zeros(X.shape) Xv=np.zeros(X.shape) for i in range(X.shape[0]): if i<m1: pass elif i<m2: Xu[i,:]=np.mean(X[i-m1:i,:],axis=0) elif i<m3: Xm[i,:]=np.mean(X[i-m2:i-m1,:],axis=0) Xu[i,:]=np.mean(X[i-m1:i,:],axis=0) elif i<m4: Xm[i,:]=np.mean(X[i-m2:i-m1,:],axis=0) Xu[i,:]=np.mean(X[i-m1:i,:],axis=0) Xt[i,:]=np.mean(X[i-m3:i-m2,:],axis=0) else: Xm[i,:]=np.mean(X[i-m2:i-m1,:],axis=0) Xu[i,:]=np.mean(X[i-m1:i,:],axis=0) Xt[i,:]=np.mean(X[i-m3:i-m2,:],axis=0) Xs[i,:]=np.mean(X[i-m4:i-m3,:],axis=0) tmp=np.hstack((X,Xm,Xt,Xu,Xs)) return tmp scaler= StandardScaler() l1 = [i-1 for i in [1,3,5,6,9,16,18,20,25,27,29,32]] #l1 = [i-1 for i in [2,4,7,10,12,14,20,22,23,26,28,30]] #l1 = [i-1 for i in [2,5,8,11,13,15,17,19,21,24,30,31]] #for j in [0,1,2,4,6,11,13,15,16,21,23,25,27,29,31]: #for j in [3,5,7,9,12,14,18,20,22,24,26,28,30]: #l1 = range(32) #l1 = [0] for j in l1: for i in range(10): exec("scaler"+str(j)+"_"+str(i)+"= StandardScaler()") def data_preprocess_train(X): X_prep = scaler.fit_transform(X) #X_prep2 = np.diff(X_prep, axis=0) #X_prep2 = np.vstack([X_prep[0],X_prep[:-1]]) #X_prep3 = np.vstack([X_prep[0],X_prep[0],X_prep[:-2]]) ##for j in [0,1,2,4,6,11,13,15,16,21,23,25,27,29,31]: ##for j in [3,5,7,9,12,14,18,20,22,24,26,28,30]: for j in l1: X_prep_low = np.zeros((np.shape(X_prep)[0],10)) for i in range(10): X_prep_low[:,i] = butterworth_filter(X[:,j],1,2-(i*0.2),3) exec("X_prep_low[:,i] = scaler"+str(j)+"_"+str(i)+".fit_transform(X_prep_low[:,i])") X_prep_low_pow = X_prep_low ** 2 X_prep = np.concatenate((X_prep_low,X_prep,X_prep_low_pow),axis=1) #X_prep = np.concatenate((X_prep, X_prep2, X_prep3), axis=1) #X_prep = np.concatenate((X_prep_low,X_prep_normal,X_prep_low_pow,X_prep_low1,X_prep_low_pow1, X_prep_low2,X_prep_low_pow2),axis=1) return get_fea( X_prep) def data_preprocess_test(X): X_prep = scaler.transform(X) #X_prep2 = np.vstack([X_prep[0],X_prep[:-1]]) #X_prep3 = np.vstack([X_prep[0],X_prep[0],X_prep[:-2]]) ##for j in [0,1,2,4,6,11,13,15,16,21,23,25,27,29,31]: ##for j in [3,5,7,9,12,14,18,20,22,24,26,28,30]: for j in l1: X_prep_low = np.zeros((np.shape(X_prep)[0],10)) for i in range(10): X_prep_low[:,i] = butterworth_filter(X[:,j],1,2-(i*0.2),3) exec("X_prep_low[:,i] = scaler"+str(j)+"_"+str(i)+".transform(X_prep_low[:,i])") X_prep_low_pow = X_prep_low ** 2 X_prep = np.concatenate((X_prep_low,X_prep,X_prep_low_pow),axis=1) #X_prep = np.concatenate((X_prep, X_prep2, X_prep3), axis=1) return get_fea( X_prep ) def fit(X,y): # Do here you training #clf = LogisticRegression(penalty="l2") #clf = SVC(kernel='linear', probability=True, random_state=0) clf1 = LDA() #clf = ensemble.RandomForestClassifier(n_estimators=10, max_depth=8, min_samples_leaf=4, n_jobs=4, random_state=0) clf1.fit(X,y) #pred_y = clf1.predict_proba(X)[:,[1]] #pred_y2 = np.vstack([pred_y[0],pred_y[:-1]]) #pred_y3 = np.vstack([pred_y[0],pred_y[0],pred_y[:-2]]) #pred_y = np.concatenate((pred_y, pred_y2, pred_y3),axis=1) #clf2 = LDA() #clf2.fit(pred_y, y) return clf1 def predict(clf,X): #clf1, clf2 = clf[0], clf[1] # do here your prediction preds = clf.predict_proba(X) #pred_y2 = np.vstack([pred_y[0],pred_y[:-1]]) #pred_y3 = np.vstack([pred_y[0],pred_y[0],pred_y[:-2]]) #pred_y = np.concatenate((pred_y, pred_y2, pred_y3),axis=1) #preds = clf2.predict_proba(pred_y) return preds[:,1] #return np.atleast_2d(preds[:,clf.classes_==1]) # training subsample.if you want to downsample the training data subsample = 79 subsample2 = 98 subsample3 = 61 #series used for CV series = list(range(2,9)) #######columns name for labels############# cols = ['HandStart','FirstDigitTouch', 'BothStartLoadPhase','LiftOff', 'Replace','BothReleased'] #######number of subjects############### subjects = list(range(1,13)) #subjects = range(1,3) auc_tot = [] pred_tot = [] y_tot = [] ###loop on subjects and 8 series for train data + 2 series for test data for subject in subjects: print("Subject : ", subject) y_raw= [] raw = [] sequence = [] ################ READ DATA ################################################ for ser in series: fname = '../Data/train/subj%d_series%d_data.csv' % (subject,ser) data,labels=prepare_data_train(fname) raw.append(data) y_raw.append(labels) sequence.extend([ser]*len(data)) X = pd.concat(raw) y = pd.concat(y_raw) #transform in numpy array #transform train data in numpy array X = np.asarray(X.astype(float)) y = np.asarray(y.astype(float)) sequence = np.asarray(sequence) ################ Train classifiers ######################################## cv = LeaveOneLabelOut(sequence) pred = np.zeros((X.shape[0],6)) for train, test in cv: print("cv") X_train = X[train] X_test = X[test] y_train = y[train] #apply preprocessing X_train=data_preprocess_train(X_train) X_test=data_preprocess_test(X_test) for i in range(6): #print "i" clf = fit(X_train[::subsample,:],y_train[::subsample,i]) preds1 = predict(clf, X_test) clf = fit(X_train[::subsample2,:],y_train[::subsample2,i]) preds2 = predict(clf, X_test) clf = fit(X_train[::subsample3,:],y_train[::subsample3,i]) preds3 = predict(clf, X_test) pred[test,i] = (preds1 + preds2 + preds3) / 3.0 #clfs = Parallel(n_jobs=6)(delayed(fit)(X_train[::subsample,:],y_train[::subsample,i]) for i in range(6)) #preds = Parallel(n_jobs=6)(delayed(predict)(clfs[i],X_test) for i in range(6)) #pred[test,:] = np.concatenate(preds,axis=1) pred_tot.append(pred) y_tot.append(y) # get AUC auc = [roc_auc_score(y[:,i],pred[:,i]) for i in range(6)] auc_tot.append(auc) print(auc) pred_tot = np.concatenate(pred_tot) y_tot = np.concatenate(y_tot) global_auc = [roc_auc_score(y_tot[:,i],pred_tot[:,i]) for i in range(6)] print(('Global AUC : %.4f' % np.mean(global_auc)))
var json_parse=(function(){"use strict";var at,ch,escapee={'"':'"','\\':'\\','/':'/',b:'\b',f:'\f',n:'\n',r:'\r',t:'\t'},text,error=function(m){throw{name:'SyntaxError',message:m,at:at,text:text}},next=function(c){if(c&&c!==ch){error("Expected '"+c+"' instead of '"+ch+"'")}ch=text.charAt(at);at+=1;return ch},number=function(){var number,string='';if(ch==='-'){string='-';next('-')}while(ch>='0'&&ch<='9'){string+=ch;next()}if(ch==='.'){string+='.';while(next()&&ch>='0'&&ch<='9'){string+=ch}}if(ch==='e'||ch==='E'){string+=ch;next();if(ch==='-'||ch==='+'){string+=ch;next()}while(ch>='0'&&ch<='9'){string+=ch;next()}}number=+string;if(!isFinite(number)){error("Bad number")}else{return number}},string=function(){var hex,i,string='',uffff;if(ch==='"'){while(next()){if(ch==='"'){next();return string}if(ch==='\\'){next();if(ch==='u'){uffff=0;for(i=0;i<4;i+=1){hex=parseInt(next(),16);if(!isFinite(hex)){break}uffff=uffff*16+hex}string+=String.fromCharCode(uffff)}else if(typeof escapee[ch]==='string'){string+=escapee[ch]}else{break}}else{string+=ch}}}error("Bad string")},white=function(){while(ch&&ch<=' '){next()}},word=function(){switch(ch){case't':next('t');next('r');next('u');next('e');return true;case'f':next('f');next('a');next('l');next('s');next('e');return false;case'n':next('n');next('u');next('l');next('l');return null}error("Unexpected '"+ch+"'")},value,array=function(){var array=[];if(ch==='['){next('[');white();if(ch===']'){next(']');return array}while(ch){array.push(value());white();if(ch===']'){next(']');return array}next(',');white()}}error("Bad array")},object=function(){var key,object={};if(ch==='{'){next('{');white();if(ch==='}'){next('}');return object}while(ch){key=string();white();next(':');if(Object.hasOwnProperty.call(object,key)){error('Duplicate key "'+key+'"')}object[key]=value();white();if(ch==='}'){next('}');return object}next(',');white()}}error("Bad object")};value=function(){white();switch(ch){case'{':return object();case'[':return array();case'"':return string();case'-':return number();default:return ch>='0'&&ch<='9'?number():word()}};return function(source,reviver){var result;text=source;at=0;ch=' ';result=value();white();if(ch){error("Syntax error")}return typeof reviver==='function'?(function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==='object'){for(k in value){if(Object.prototype.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v}else{delete value[k]}}}}return reviver.call(holder,key,value)}({'':result},'')):result}}());
const fs = require("fs") const path = require("path") const crypto = require("crypto") const log = require("./ulka-log") const { existsSync } = require("fs") const { allFiles, mkdir } = require("./ulka-fs") /** @typedef {{ buildPath: String; pagesPath: String; templatesPath: String; contents: any[]; plugins: any[] }} Configs */ /** * Get absolute path * * @param {String} pathInString path in string separated by / from cwd * @param {String} [cwd] Current working directory (default: process.cwd()) * @return {String} absolute path */ function absolutePath(pathInString, cwd = process.cwd()) { if (typeof pathInString !== "string") { throw new Error("Path provided should be string") } return path.join(cwd, ...pathInString.split("/")) } /** * Get configs from ulka-config.js * * @param {String} cwd * @return {Configs} configs */ function getConfigs(cwd) { const defaultConfigs = { buildPath: "build", pagesPath: "pages", templatesPath: "templates", contents: [], plugins: [] } let reqConfigs = {} const configExists = fs.existsSync(path.join(cwd, "ulka-config.js")) if (configExists) { reqConfigs = require(path.join(cwd, "ulka-config.js")) } else { console.log("") log.error("ERROR: Config file not found.", true) log.warning( "Please make sure you have ulka-config.js file in your root directory.", true ) process.exit(0) } const configs = { ...defaultConfigs, ...reqConfigs } const buildPath = absolutePath(configs.buildPath, cwd) const pagesPath = absolutePath(`src/${configs.pagesPath}`, cwd) const templatesPath = absolutePath(`src/${configs.templatesPath}`, cwd) const plugins = getPlugins(configs.plugins, cwd) const contents = configs.contents.map(content => ({ ...content, path: absolutePath(`src/${content.path}`, cwd), template: path.join(templatesPath, content.template) })) return { ...configs, plugins, buildPath, pagesPath, templatesPath, contents } } const hashCache = {} /** * Generates hex hash from a string * * @param {String} str * @return {String} Hex hash from given string */ function generateHash(str = "") { if (hashCache[str]) return hashCache[str] const hash = crypto.createHash("sha1").update(str.toString()).digest("hex") hashCache[str] = hash return hash } /** * Spinner function * @param {String} text *@return {Function} Stop Spinner */ function spinner(text = "") { const words = ["| ", "/ ", "- ", "\\ "] let i = 0 const interval = setInterval(() => { process.stdout.write(`\r${words[i++]} ${text}`) i %= words.length }, 100) return () => clearInterval(interval) } const getPlugins = (pluginArr, cwd) => { try { const plugins = { beforeSetup: [], beforeBuild: [], afterBuild: [], remarkablePlugin: [], beforeContentRender: [], afterContentRender: [], beforePageRender: [], afterPageRender: [] } for (let plugin of pluginArr) { let pPath = "" let options = {} if (typeof plugin === "string") { if (existsSync(path.join(cwd, plugin))) { plugin = path.join(cwd, plugin) } pPath = require.resolve(plugin) } else if (typeof plugin === "object" && plugin.resolve) { if (existsSync(path.join(cwd, plugin.resolve))) plugin.resolve = path.join(cwd, plugin.resolve) pPath = require.resolve(plugin.resolve) options = plugin.options || {} } else { log.error("Invalid plugin: ", true) console.log(plugin) process.exit(0) } const pluginObj = require(pPath) for (const key in pluginObj) { if (pluginObj.hasOwnProperty(key)) { const somePlugin = pluginObj[key] if (plugins[key]) { const pluginFunc = async (...args) => { return await somePlugin(...args, options) } plugins[key].push(pluginFunc) } } } } return plugins } catch (e) { console.log(e.message) log.error("Error while getting plugins") process.exit(0) } } const changeCssUrlPath = (css, dir, info) => { return css.replace(/ url\((.*?)\)/gs, (...args) => { const pathGiven = args[1].replace(/'|"/gs, "") if ( pathGiven.startsWith("http:") || pathGiven.startsWith("https:") || pathGiven.startsWith("//") ) return ` url("${pathGiven}")` const realPath = path.join(dir, pathGiven) const salt = path.relative(info.cwd, realPath).split(path.sep).join("") const fileName = generateHash(salt) return ` url("${fileName + path.parse(pathGiven).ext}")` }) } /** * @param {Object} info info */ function copyAssets(info) { const allFilesinSrc = allFiles(path.join(info.cwd, "src")) const staticPath = path.join(info.cwd, "static") if (existsSync(staticPath)) { const allStaticFiles = allFiles(staticPath) for (const file of allStaticFiles) { const generateP = path.join( info.configs.buildPath, path.relative(staticPath, file) ) const parsedBP = path.parse(generateP) if (!fs.existsSync(parsedBP.dir)) { mkdir(parsedBP.dir) } fs.copyFileSync(file, generateP) } } const ignoreExt = info.ignoreExtensions mkdir(path.join(info.configs.buildPath, "__assets__")) for (const file of allFilesinSrc) { const parsed = path.parse(file) if (!parsed.name.endsWith("ignore") && !ignoreExt.includes(parsed.ext)) { try { const strToHash = path.relative(info.cwd, file).split(path.sep).join("") const newName = generateHash(strToHash) + parsed.ext const writepath = path.join( info.configs.buildPath, "__assets__", newName ) let readData = "" if (parsed.ext === ".css") { readData = fs.readFileSync(file, "utf-8") readData = changeCssUrlPath(readData, parsed.dir, info) } else { readData = fs.readFileSync(file) } fs.writeFileSync(writepath, readData) } catch (e) { log.error(`Error while copying assets: ${file}\n`, true) console.log(e) } } } } module.exports = { absolutePath, getConfigs, generateHash, spinner, copyAssets }
// @flow import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import Component from './component'; import { } from '../actions'; import { makeBillingTelephoneState } from '../selectors'; import type { Dispatch } from '../types'; const makeMapStateToProps = (): Object => { const getBillingTelephoneState = makeBillingTelephoneState(); const mapStateToProps = (state: Object): Object => ({ billingTelephone: getBillingTelephoneState(state), }); return mapStateToProps; }; const mapDispatchToProps = (dispatch: Dispatch): Object => ( bindActionCreators({ }, dispatch) ); export default connect(makeMapStateToProps, mapDispatchToProps)(Component);
# -*- coding: utf-8 -*- """ Provides an oauthlib compatible JWT Authorization grant type. This module provides a grant type implementation that can be used for the oauthlib token endpoint. It needs to provide a `create_token_response` method. The implementation is based on `RFC 7523`_. Example of how to register the ``JWTAuthorizationGrant`` with oauthlib alongside the authorization code grant, and the refresh token grant: :: class OAuthProvider(AuthorizationEndpoint, TokenEndpoint): def __init__(self, oauth_validator, user_svc, domain): ... jwt_auth_grant = JWTAuthorizationGrant(oauth_validator, user_svc, domain) TokenEndpoint.__init__(self, default_grant_type='authorization_code', grant_types={'authorization_code': ..., 'refresh_token': ..., 'urn:ietf:params:oauth:grant-type:jwt-bearer': jwt_auth_grant}, default_token_type=...) ... For more information, see the `oauthlib documentation`_ on grant types. .. _`RFC 7523`: https://tools.ietf.org/html/rfc7523 .. _`oauthlib documentation`: http://oauthlib.readthedocs.io/en/latest/oauth2/grants/grants.html """ from __future__ import unicode_literals import json from oauthlib.oauth2.rfc6749 import errors from oauthlib.oauth2.rfc6749.grant_types.base import GrantTypeBase from h.oauth.jwt_grant_token import JWTGrantToken class JWTAuthorizationGrant(GrantTypeBase): def __init__(self, request_validator, user_svc, domain): self.request_validator = request_validator self.user_svc = user_svc self.domain = domain def create_token_response(self, request, token_handler): """ Create a new token from a JWT authorization grant. If valid and authorized, this creates a new access token and returns the token. Otherwise it returns an error response. :param request: the oauthlib request :type request: oauthlib.common.Request :param token_handler: Token generator responding to `create_token`. :type token_handler: oauthlib.oauth2.rfc6749.tokens.TokenBase :returns: HTTP response tuple: headers, body, status :rtype: headers (dict), body (unicode), status (int) """ headers = { "Content-Type": "application/json", "Cache-Control": "no-store", "Pragma": "no-cache", } try: self.validate_token_request(request) except errors.OAuth2Error as e: return headers, e.json, e.status_code token = token_handler.create_token( request, refresh_token=True, save_token=False ) self.request_validator.save_token(token, request) return headers, json.dumps(token), 200 def validate_token_request(self, request): """ Validates a token request. Sets the ``client_id`` property on the passed-in request to the JWT issuer, and finds the user based on the JWT subject and sets it as the ``user`` property. Raises subclasses of ``oauthlib.oauth2.rfc6749.OAuth2Error`` when validation fails. :param request: the oauthlib request :type request: oauthlib.common.Request """ try: assertion = request.assertion except AttributeError: raise errors.InvalidRequestFatalError("Missing assertion.") token = JWTGrantToken(assertion) # Update client_id in oauthlib request request.client_id = token.issuer if not self.request_validator.authenticate_client_id( request.client_id, request ): raise errors.InvalidClientError(request=request) # Ensure client is authorized use of this grant type self.validate_grant_type(request) authclient = request.client.authclient verified_token = token.verified(key=authclient.secret, audience=self.domain) user = self.user_svc.fetch(verified_token.subject) if user is None: raise errors.InvalidGrantError( "Grant token subject (sub) could not be found." ) if user.authority != authclient.authority: raise errors.InvalidGrantError( "Grant token subject (sub) does not match issuer (iss)." ) request.user = user
import $ from 'jquery'; import _ from 'underscore'; import AccessWidget from '@girder/core/views/widgets/AccessWidget'; import CollectionModel from '@girder/core/models/CollectionModel'; import EditCollectionWidget from '@girder/core/views/widgets/EditCollectionWidget'; import FolderModel from '@girder/core/models/FolderModel'; import HierarchyWidget from '@girder/core/views/widgets/HierarchyWidget'; import router from '@girder/core/router'; import View from '@girder/core/views/View'; import { AccessType } from '@girder/core/constants'; import { cancelRestRequests } from '@girder/core/rest'; import { confirm } from '@girder/core/dialog'; import { renderMarkdown, formatSize } from '@girder/core/misc'; import events from '@girder/core/events'; import CollectionPageTemplate from '@girder/core/templates/body/collectionPage.pug'; import '@girder/core/stylesheets/body/collectionPage.styl'; import 'bootstrap/js/dropdown'; /** * This view shows a single collection's page. */ var CollectionView = View.extend({ events: { 'click .g-edit-collection': 'editCollection', 'click .g-collection-access-control': 'editAccess', 'click .g-delete-collection': 'deleteConfirmation' }, initialize: function (settings) { cancelRestRequests('fetch'); this.upload = settings.upload || false; this.access = settings.access || false; this.edit = settings.edit || false; this.folderAccess = settings.folderAccess || false; this.folderCreate = settings.folderCreate || false; this.folderEdit = settings.folderEdit || false; this.itemCreate = settings.itemCreate || false; // If collection model is already passed, there is no need to fetch. if (settings.collection) { this.model = settings.collection; if (settings.folderId) { this.folder = new FolderModel(); this.folder.set({ _id: settings.folderId }).on('g:fetched', function () { this.render(); }, this).on('g:error', function () { this.folder = null; this.render(); }, this).fetch(); } else { this.render(); } } else if (settings.id) { this.model = new CollectionModel(); this.model.set('_id', settings.id); this.model.on('g:fetched', function () { this.render(); }, this).fetch(); } }, editCollection: function () { var container = $('#g-dialog-container'); if (!this.editCollectionWidget) { this.editCollectionWidget = new EditCollectionWidget({ el: container, model: this.model, parentView: this }).on('g:saved', function () { this.render(); }, this); } this.editCollectionWidget.render(); }, render: function () { this.$el.html(CollectionPageTemplate({ collection: this.model, AccessType: AccessType, renderMarkdown: renderMarkdown })); if (!this.hierarchyWidget) { // The HierarchyWidget will self-render when instantiated this.hierarchyWidget = new HierarchyWidget({ el: this.$('.g-collection-hierarchy-container'), parentModel: this.folder || this.model, upload: this.upload, folderAccess: this.folderAccess, folderEdit: this.folderEdit, folderCreate: this.folderCreate, itemCreate: this.itemCreate, parentView: this }).on('g:setCurrentModel', () => { // When a user descends into the hierarchy, hide the collection // actions list to avoid confusion. this.$('.g-collection-header .g-collection-actions-button').hide(); }); } else { this.hierarchyWidget .setElement(this.$('.g-collection-hierarchy-container')) .render(); } this.upload = false; this.folderAccess = false; this.folderEdit = false; this.folderCreate = false; this.itemCreate = false; if (this.edit) { this.editCollection(); } else if (this.access) { this.editAccess(); } return this; }, editAccess: function () { new AccessWidget({ el: $('#g-dialog-container'), modelType: 'collection', model: this.model, parentView: this }).on('g:accessListSaved', function (params) { if (params.recurse) { this.hierarchyWidget.refreshFolderList(); } }, this); }, deleteConfirmation: function () { let params = { text: 'Are you sure you want to delete the collection <b>' + this.model.escape('name') + this.model.escape('nFolders') + '</b>?', yesText: 'Delete', escapedHtml: true, confirmCallback: () => { this.model.on('g:deleted', function () { events.trigger('g:alert', { icon: 'ok', text: 'Collection deleted.', type: 'success', timeout: 4000 }); router.navigate('collections', { trigger: true }); }).destroy(); } }; if (this.model.get('nFolders') !== 0 || this.model.get('size') !== 0) { params = _.extend({ additionalText: '<b>' + this.model.escape('name') + '</b>' + ' contains <b>' + this.model.escape('nFolders') + ' folders</b> taking up <b>' + formatSize(parseInt(this.model.get('size'), 10)) + '</b>', msgConfirmation: true, name: this.model.escape('name') }, params); } confirm(params); } }, { /** * Helper function for fetching the user and rendering the view with * an arbitrary set of extra parameters. */ fetchAndInit: function (cid, params) { var collection = new CollectionModel(); collection.set({ _id: cid }).on('g:fetched', function () { events.trigger('g:navigateTo', CollectionView, _.extend({ collection: collection }, params || {})); }, this).fetch(); } }); export default CollectionView;
/*Exercise 2 - Selection Write a program to calculate the amount to be paid for a rented vehicle. • Input the distance the van has travelled • The first 30 km is at a rate of 50/= per km. • The remaining distance is calculated at the rate of 40/= per km. e.g. Distance -> 20 Amount = 20 x 50 = 1000 Distance -> 50 Amount = 30 x 50 + (50-30) x 40 = 2300*/ #include <stdio.h> int main() { int distance; int amount=0; printf("Enter the distance the van has travelled(km): "); scanf("%d", &distance); if(distance<=30) { amount=distance * 50; } if(distance>30) { amount=30 * 50+ (distance-30) * 40; } printf("The amount is: %d",amount); return 0; }
export const CONNECTION_DEFAULT_NAME = 'local' export const CONNECTION_DEFAULT_HOST = 'localhost' export const CONNECTION_DEFAULT_PORT = 28015 export const CONNECTION_DEFAULT_USERNAME = 'admin' export const CONNECTION_DEFAULT_PASSWORD = ''
__author__ = 'buec' import re from pyspeechgrammar import parser from pyspeechgrammar.jsgf import grammars class JSGFParser(parser.BaseParser): def parse_string(self, data): p = grammars.Grammar.parser() # remove newlines after alternative separator (performance issue) jsgf_string = self._remove_newlines_within_alternatives(data) # add whitespace before groups, rulerefs (easier and faster in parsing) jsgf_string = self._add_space_around_rule_expansions(jsgf_string) parsed_jsgf_data = p.parse_string(jsgf_string) return parsed_jsgf_data.model def _remove_newlines_within_alternatives(self, jsgf_string): regex = re.compile(r"\s*\|\s*") return regex.sub(" | ", jsgf_string) def _add_space_around_rule_expansions(self, jsgf_string): result = str(jsgf_string).replace("(", " (") result = str(result).replace(")", ") ") result = str(result).replace("[", " [") result = str(result).replace("]", "] ") result = str(result).replace("<", " <") result = str(result).replace(">", "> ") return result def write_string(self, model): pass
import discord from discord.ext import commands from discord.ext.commands import cooldown from discord.ext.commands.cooldowns import BucketType import time import asyncio import asyncpg from datetime import datetime from utils import errorhandler import aioredis class functions: def __init__(self, bot): self.bot = bot async def set_cooldown(self, ctx, user: discord.Member, time: int): await self.bot.redis.execute( "SET", f"{ctx.author.id}-{ctx.command.qualified_name}", "cooldown", "EX", time, ) async def check4cooldown(self, ctx, user: discord.Member): cooldown = await self.bot.redis.execute( "TTL", f"{ctx.author.id}-{ctx.command.qualified_name}" ) if cooldown == -2 or cooldown is None: return True return cooldown def setup(bot): bot.add_cog(functions(bot))
import React, { Component } from 'react'; import 'bootstrap/dist/css/bootstrap.css'; import 'jquery/dist/jquery'; import Modal from 'react-bootstrap/Modal'; import AddTransactionForm from './AddTransactionForm'; class FormModal extends Component{ submitMyForm = null; children = null; handleSubmitForm = (e) => { if(this.submitMyForm){ this.submitMyForm(e); } } bindSubmitForm = (submitForm) => { this.submitMyForm = submitForm; }; render() { const child = React.cloneElement(this.props.children,{bindSubmitForm : this.bindSubmitForm, ...this.props}); if(!this.props.show){ return null; } return( <div> <Modal show={this.props.show} onHide={this.props.close} aria-labelledby="contained-modal-title-vcenter" centered size="md" > <Modal.Header> <Modal.Title id='contained-modal-title-vcenter'> <h2>{this.props.header}</h2> </Modal.Title> </Modal.Header> <Modal.Body> {child} {/*<AddTransactionForm bindSubmitFrom={this.bindSubmitForm} accountId={this.props.accountId} submitClicked={this.props.submitClicked}/>*/} </Modal.Body> <Modal.Footer> <button type="submit" className="btn btn-secondary" onClick={this.handleSubmitForm}>Save </button> <button type="button" className="btn btn-danger" onClick={this.props.close} >Close </button> </Modal.Footer> </Modal> </div> ); } } export default FormModal;
from .first_module import firstObject another_reference = firstObject aInt = 5
# Copyright 2020 MONAI Consortium # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch import logging import re import unittest from io import StringIO from ignite.engine import Engine, Events from monai.handlers import StatsHandler class TestHandlerStats(unittest.TestCase): def test_metrics_print(self): log_stream = StringIO() logging.basicConfig(stream=log_stream, level=logging.INFO) key_to_handler = "test_logging" key_to_print = "testing_metric" # set up engine def _train_func(engine, batch): return torch.tensor(0.0) engine = Engine(_train_func) # set up dummy metric @engine.on(Events.EPOCH_COMPLETED) def _update_metric(engine): current_metric = engine.state.metrics.get(key_to_print, 0.1) engine.state.metrics[key_to_print] = current_metric + 0.1 # set up testing handler stats_handler = StatsHandler(name=key_to_handler) stats_handler.attach(engine) engine.run(range(3), max_epochs=2) # check logging output output_str = log_stream.getvalue() grep = re.compile(f".*{key_to_handler}.*") has_key_word = re.compile(f".*{key_to_print}.*") for idx, line in enumerate(output_str.split("\n")): if grep.match(line): if idx in [5, 10]: self.assertTrue(has_key_word.match(line)) def test_loss_print(self): log_stream = StringIO() logging.basicConfig(stream=log_stream, level=logging.INFO) key_to_handler = "test_logging" key_to_print = "myLoss" # set up engine def _train_func(engine, batch): return torch.tensor(0.0) engine = Engine(_train_func) # set up testing handler stats_handler = StatsHandler(name=key_to_handler, tag_name=key_to_print) stats_handler.attach(engine) engine.run(range(3), max_epochs=2) # check logging output output_str = log_stream.getvalue() grep = re.compile(f".*{key_to_handler}.*") has_key_word = re.compile(f".*{key_to_print}.*") for idx, line in enumerate(output_str.split("\n")): if grep.match(line): if idx in [1, 2, 3, 6, 7, 8]: self.assertTrue(has_key_word.match(line)) def test_loss_dict(self): log_stream = StringIO() logging.basicConfig(stream=log_stream, level=logging.INFO) key_to_handler = "test_logging" key_to_print = "myLoss1" # set up engine def _train_func(engine, batch): return torch.tensor(0.0) engine = Engine(_train_func) # set up testing handler stats_handler = StatsHandler(name=key_to_handler, output_transform=lambda x: {key_to_print: x}) stats_handler.attach(engine) engine.run(range(3), max_epochs=2) # check logging output output_str = log_stream.getvalue() grep = re.compile(f".*{key_to_handler}.*") has_key_word = re.compile(f".*{key_to_print}.*") for idx, line in enumerate(output_str.split("\n")): if grep.match(line): if idx in [1, 2, 3, 6, 7, 8]: self.assertTrue(has_key_word.match(line)) if __name__ == "__main__": unittest.main()
import unittest from ejercicio_1 import * class PistaTest(unittest.TestCase): def test_stars(self): anime_opening = Pista('Anime opening', True, 100,'2020-01-01') anime_opening.add_star() anime_opening.add_star() anime_opening.add_star() self.assertEqual("Stars: ★★★", anime_opening.get_stars()) def test_favorite_song(self): anime_ending = Pista('Anime ending', True, 100,'2020-01-01') self.assertEqual("This is one of your favorite songs", anime_ending.is_favorite()) def test_not_a_favorite_song(self): anime_ending = Pista('Anime ending', False, 100,'2020-01-01') self.assertEqual("This is not one of your favorite songs", anime_ending.is_favorite()) class ReproductorMusicalTest(unittest.TestCase): def test_duration(self): reproductor = ReproductorMusical('Icelandic', 'https://i.ytimg.com/vi/uVFGmjzQgW4/maxresdefault.jpg', 911) self.assertEqual(911, reproductor.get_duration()) def test_background(self): reproductor = ReproductorMusical('Icelandic', 'https://i.ytimg.com/vi/uVFGmjzQgW4/maxresdefault.jpg', 911) self.assertEqual('https://i.ytimg.com/vi/uVFGmjzQgW4/maxresdefault.jpg', reproductor.get_background()) def test_no_starred_songs(self): test_cases = [ Pista('Naruto opening 5', False, 100,'2020-01-01'), Pista('Full metal alchemist brotherhood', False, 1,'2019-01-01'), Pista('Saint seiya lost canvas opening', False, 10,'2019-01-01'), Pista('Zankyou no terror ending', False, 1050,'2030-01-01') ] reproductor = ReproductorMusical('Icelandic', 'https://i.ytimg.com/vi/uVFGmjzQgW4/maxresdefault.jpg', 911) for case in test_cases: reproductor.add_song(case) self.assertEqual("", reproductor.get_favorite_songs()) def test_remove_last_song(self): test_cases = [ Pista('Naruto opening 5', True, 100,'2020-01-01'), Pista('Full metal alchemist brotherhood', True, 1,'2019-01-01'), Pista('Saint seiya lost canvas opening', True, 10,'2019-01-01'), Pista('Zankyou no terror ending', True, 1050,'2030-01-01') ] reproductor = ReproductorMusical('Icelandic', 'https://i.ytimg.com/vi/uVFGmjzQgW4/maxresdefault.jpg', 911) for case in test_cases: reproductor.add_song(case) reproductor.remove_last_song() self.assertEqual("Full metal alchemist brotherhood, Saint seiya lost canvas opening, Naruto opening 5", reproductor.get_favorite_songs()) def test_four_songs(self): test_cases = [ Pista('Naruto opening 5', True, 100,'2020-01-01'), Pista('Full metal alchemist brotherhood', True, 1,'2019-01-01'), Pista('Saint seiya lost canvas opening', True, 10,'2019-01-01'), Pista('Zankyou no terror ending', True, 1050,'2030-01-01') ] reproductor = ReproductorMusical('Icelandic', 'https://i.ytimg.com/vi/uVFGmjzQgW4/maxresdefault.jpg', 911) for case in test_cases: reproductor.add_song(case) self.assertEqual("Full metal alchemist brotherhood, Saint seiya lost canvas opening, Naruto opening 5, Zankyou no terror ending", reproductor.get_favorite_songs()) def test_three_songs(self): test_cases = [ Pista('Naruto opening 5', True, 100,'2020-01-01'), Pista('Saint seiya lost canvas opening', True, 10,'2019-01-01'), Pista('Zankyou no terror ending', True, 1050,'2030-01-01') ] reproductor = ReproductorMusical('Icelandic', 'https://i.ytimg.com/vi/uVFGmjzQgW4/maxresdefault.jpg', 911) for case in test_cases: reproductor.add_song(case) self.assertEqual("Saint seiya lost canvas opening, Naruto opening 5, Zankyou no terror ending", reproductor.get_favorite_songs()) def test_two_songs(self): test_cases = [ Pista('Naruto opening 5', True, 100,'2020-01-01'), Pista('Saint seiya lost canvas opening', True, 10,'2019-01-01'), ] reproductor = ReproductorMusical('Icelandic', 'https://i.ytimg.com/vi/uVFGmjzQgW4/maxresdefault.jpg', 911) for case in test_cases: reproductor.add_song(case) self.assertEqual("Saint seiya lost canvas opening, Naruto opening 5", reproductor.get_favorite_songs()) def test_one_songs(self): test_cases = [ Pista('Naruto opening 5', True, 100,'2020-01-01'), ] reproductor = ReproductorMusical('Icelandic', 'https://i.ytimg.com/vi/uVFGmjzQgW4/maxresdefault.jpg', 911) for case in test_cases: reproductor.add_song(case) self.assertEqual("Naruto opening 5", reproductor.get_favorite_songs()) def test_no_songs(self): test_cases = [] reproductor = ReproductorMusical('Icelandic', 'https://i.ytimg.com/vi/uVFGmjzQgW4/maxresdefault.jpg', 911) for case in test_cases: reproductor.add_song(case) self.assertEqual("", reproductor.get_favorite_songs()) if __name__ == "__main__": unittest.main()
from selenium import webdriver import pandas as pd import time """[Initial Setting] 初期設定 """ options = webdriver.ChromeOptions() options.add_argument('--headeless') options.add_argument('--disable-gpu') options.add_argument('--lang-ja') browser = webdriver.Chrome(chrome_options=options, executable_path='./chromedriver') df = pd.DataFrame(columns=['name', 'image', 'price', 'category', 'car']) url = 'https://motorz-garage.com/parts/' """[CSS Selector Setting] CSSセレクターの設定 """ PAGER_NEXT = "li.select-page.arrow a[rel='next']" POSTS = ".product-item-list__item" PRODUCT_NAME = ".product-item-list__item-name" IMAGE = ".product-item-list__item-image img" PRICE = ".product-item-list__item-price" CATEGORY = ".product-item-list__item-category" CAR = ".product-item-list__item-car-name" """[Activate Section] 実行部分 """ browser.get(url) while True: #Continue until getting the last page. if len(browser.find_elements_by_css_selector(PAGER_NEXT)) > 0: print('Starting to get posts...') posts = browser.find_element_by_css_selector(POSTS) print(len(posts)) for post in posts: try: name = post.find_element_by_css_selector(PRODUCT_NAME).text print(name) thumbnailURL = post.find_element_by_css_selector(IMAGE).get_attribute('src') print(thumbnailURL) price = post.find_element_by_css_selector(PRICE).text print(price) category = post.find_element_by_css_selector(CATEGORY).text
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- """Blob helper functions.""" import numpy as np # from scipy.misc import imread, imresize import cv2 from model.utils.config import cfg import random try: xrange # Python 2 except NameError: xrange = range # Python 3 def im_list_to_blob(ims): """Convert a list of images into a network input. Assumes images are already prepared (means subtracted, BGR order, ...). """ max_shape = np.array([im.shape for im in ims]).max(axis=0) num_images = len(ims) if cfg.TRAIN.USE_DEPTH: # Custom blob = np.zeros((num_images, max_shape[0], max_shape[1], 4), dtype=np.float32) else: blob = np.zeros((num_images, max_shape[0], max_shape[1], 3), dtype=np.float32) for i in xrange(num_images): im = ims[i] blob[i, 0:im.shape[0], 0:im.shape[1], :] = im return blob def prep_im_for_blob(im, pixel_means, target_size, max_size): """Mean subtract and scale an image for use in a blob.""" im = im.astype(np.float32, copy=False) im -= pixel_means im_shape = im.shape im_size_min = np.min(im_shape[0:2]) im_size_max = np.max(im_shape[0:2]) im_scale = float(target_size) / float(im_size_min) # Prevent the biggest axis from being more than MAX_SIZE # if np.round(im_scale * im_size_max) > max_size: # im_scale = float(max_size) / float(im_size_max) # im = imresize(im, im_scale) im = cv2.resize(im, None, None, fx=im_scale, fy=im_scale, interpolation=cv2.INTER_LINEAR) #rn = str(random.randint(0,100))+'.jpg' #cv2.imwrite(rn,im) return im, im_scale
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-03-18 00:39 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('ratings', '0002_userrating'), ] operations = [ migrations.AddField( model_name='book', name='added_by', field=models.ForeignKey(blank=True, default=None, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), preserve_default=False, ), ]
# Copyright (C) 2018-2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import numpy as np from mo.front.caffe.extractors.utils import embed_input, weights_biases from mo.front.common.partial_infer.elemental import copy_shape_infer from mo.front.extractor import FrontExtractorOp from mo.ops.scale_shift import ScaleShiftOp from mo.utils.utils import NamedAttrsClass class ScaleFrontExtractor(FrontExtractorOp): op = 'scale' enabled = True @classmethod def extract(cls, node): pb = node.pb model = node.model_pb param = pb.scale_param attrs = { 'axis': param.axis, } if model is None and len(pb.bottom) == 1: # default weights and biases for scale layer if the caffemodel file doesn't contain them model = NamedAttrsClass({'blobs': np.array([NamedAttrsClass({'data': np.array([1])}), NamedAttrsClass({'data': np.array([0])})])}) # scale with 1 input and 1 or 2 blobs if model and len(model.blobs) != 0 and len(pb.bottom) == 1: attrs.update(weights_biases(param.bias_term, model)) # 2 inputs + bias elif len(pb.bottom) == 2 and param.bias_term: if model is None or len(model.blobs) == 0: # default bias for scale layer with 2 inputs if the caffemodel file doesn't contain them model = NamedAttrsClass({'blobs': np.array([NamedAttrsClass({'data': np.array([0])})])}) embed_input(attrs, 1, 'biases', model.blobs[0].data) ScaleShiftOp.update_node_stat(node, attrs) return cls.enabled
/** * The module responsible for the single task. * It knows how to load a task and activate it. * It also supplies the basic task directive. * @return {module} pi.task module. */ define(function(require){ var angular = require('angular'); var module = angular.module('pi.task',[]); var _ = require('underscore'); var managerToCsv = require('./managerToCsv'); module.provider('taskActivate', require('./taskActivateProvider')); module.directive('piTask', require('./taskDirective')); // the tasks defined here essentialy activate the default players for quest/message/pip. module.config(['taskActivateProvider', function(activateProvider){ activateQuest.$inject = ['done', '$element', '$scope', '$compile', 'script','task']; function activateQuest(done, $canvas, $scope, $compile, script, task){ var $el; // update script name task.name && (script.name = task.name); $scope.script = script; $canvas.append('<div pi-quest></div>'); $el = $canvas.contents(); $compile($el)($scope); // clean up piQuest $el.controller('piQuest').task.promise['finally'](done); return function questDestroy(){ $el.scope().$destroy(); $el.remove(); }; } activateProvider.set('quest', activateQuest); }]); module.config(['taskActivateProvider', function(activateProvider){ activateMessage.$inject = ['done', '$element', 'task', '$scope','$compile']; function activateMessage(done, $canvas, task, $scope, $compile){ var $el; $scope.script = task; $canvas.append('<div pi-message></div>'); $el = $canvas.contents(); $compile($el)($scope); // clean up $scope.$on('message:done', function(){ done(); }); return function destroyMessage(){ $scope.$destroy(); $el.remove(); }; } activateProvider.set('message', activateMessage); }]); module.config(['taskActivateProvider', function(activateProvider){ activatePost.$inject = ['done', 'task', '$http','$q', '$rootScope']; function activatePost(done, task, $http, $q, $rootScope){ var canceler = $q.defer(); // http://stackoverflow.com/questions/13928057/how-to-cancel-an-http-request-in-angularjs var global = $rootScope.global; var data = task.path ? _.get(global, task.path) : task.data; $http .post(task.url, data, {timeout: canceler.promise}) .then(done,fail); return canceler.resolve; function fail(response){ done(); // continue with the task throw new Error('Post error("'+task.url+'"): ' + response.statusText); // but shout about the failure } } activateProvider.set('post', activatePost); }]); module.config(['taskActivateProvider', function(activateProvider){ activatePostCsv.$inject = ['done', 'task', '$http','$q', '$rootScope']; function activatePostCsv(done, task, $http, $q, $rootScope){ var canceler = $q.defer(); // http://stackoverflow.com/questions/13928057/how-to-cancel-an-http-request-in-angularjs var global = $rootScope.global; var csv = managerToCsv(global); $http .post(task.url, csv, {timeout: canceler.promise}) .then(done,done); return canceler.resolve; } activateProvider.set('postCsv', activatePostCsv); }]); module.config(['taskActivateProvider', function(activateProvider){ activateRedirect.$inject = ['done', 'task', 'managerBeforeUnload']; function activateRedirect(done, task, beforeUnload){ if (_.result(task,'condition',true)){ beforeUnload.deactivate(); location.href = task.url; } else { done(); } } activateProvider.set('redirect', activateRedirect); }]); module.config(['taskActivateProvider', function(activateProvider){ activatePIP.$inject = ['done', '$element', 'task', 'script']; function activatePIP(done, $canvas, task, script){ var $el, req; var newVersion = task.version > 0.3; var pipSink; // load PIP req = requirejs.config({ context: _.uniqueId(), baseUrl: task.baseUrl || '../bower_components/PIPlayer/dist/js', // can't use packages yet as urls in pip aren't relative... paths: { //plugins text: ['//cdnjs.cloudflare.com/ajax/libs/require-text/2.0.3/text.min', '../../bower_components/requirejs-text/text'], // Core Libraries jquery: ['//cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min','../../bower_components/jquery/dist/jquery.min'], underscore: ['//cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.min','../../bower_components/lodash-compat/lodash.min'], backbone: ['//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min', '../../bower_components/backbone/backbone'] }, deps: newVersion ? ['underscore'] : ['jquery', 'backbone', 'underscore'] }); // update script name task.name && (script.name = task.name); $canvas.append('<div pi-player></div>'); $el = $canvas.contents(); $el.addClass('pi-spinner'); req(['activatePIP'], function(activate){ $el.removeClass('pi-spinner'); if (newVersion) { pipSink = activate($el[0], script); pipSink.end.map(done); } else activate(script, done); }); return function destroyPIP(){ $el.remove(); if (newVersion) pipSink.end(true); else req(['app/task/main_view'], function(main){ main.deferred.resolve(); main.destroy(); }); }; } activateProvider.set('pip', activatePIP); }]); return module; });
// SDLSyncMsgVersion.h // #import "SDLRPCMessage.h" /** * Specifies the version number of the SDL V4 interface. This is used by both the application and SDL to declare what interface version each is using. * * @since SDL 1.0 */ @interface SDLSyncMsgVersion : SDLRPCStruct { } /** * @abstract Constructs a newly allocated SDLSyncMsgVersion object */ - (instancetype)init; /** * @abstract Constructs a newly allocated SDLSyncMsgVersion object indicated by the dictionary parameter * @param dict The dictionary to use */ - (instancetype)initWithDictionary:(NSMutableDictionary *)dict; // TODO: (Alex M.)[2016-12-1] Change from NSInteger to UInt8 - (instancetype)initWithMajorVersion:(NSInteger)majorVersion minorVersion:(NSInteger)minorVersion __deprecated_msg("Use initWithMajorVersion:minorVersion:patchVersion: instead"); - (instancetype)initWithMajorVersion:(NSInteger)majorVersion minorVersion:(NSInteger)minorVersion patchVersion:(NSInteger)patchVersion; /** * @abstract The major version indicates versions that is not-compatible to previous versions * * Required, Integer, 1 - 10 */ @property (strong) NSNumber *majorVersion; /** * @abstract The minor version indicates a change to a previous version that should still allow to be run on an older version (with limited functionality) * * Required, Integer, 0 - 1000 */ @property (strong) NSNumber *minorVersion; /** * @abstract Optional, allows backward-compatible fixes to the API without increasing the minor version of the interface * */ @property (strong) NSNumber *patchVersion; @end
/* SDSLib 2.0 -- A C dynamic strings library * * Copyright (c) 2006-2015, Salvatore Sanfilippo <antirez at gmail dot com> * Copyright (c) 2015, Oran Agra * Copyright (c) 2015, Redis Labs, Inc * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Redis nor the names of its contributors may be used * to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <assert.h> #include <limits.h> #include "sds.h" #include "sdsalloc.h" const char *SDS_NOINIT = "SDS_NOINIT"; static inline int sdsHdrSize(char type) { switch(type&SDS_TYPE_MASK) { case SDS_TYPE_5: return sizeof(struct sdshdr5); case SDS_TYPE_8: return sizeof(struct sdshdr8); case SDS_TYPE_16: return sizeof(struct sdshdr16); case SDS_TYPE_32: return sizeof(struct sdshdr32); case SDS_TYPE_64: return sizeof(struct sdshdr64); } return 0; } static inline char sdsReqType(size_t string_size) { if (string_size < 1<<5) return SDS_TYPE_5; if (string_size < 1<<8) return SDS_TYPE_8; if (string_size < 1<<16) return SDS_TYPE_16; #if (LONG_MAX == LLONG_MAX) if (string_size < 1ll<<32) return SDS_TYPE_32; return SDS_TYPE_64; #else return SDS_TYPE_32; #endif } static inline size_t sdsTypeMaxSize(char type) { if (type == SDS_TYPE_5) return (1<<5) - 1; if (type == SDS_TYPE_8) return (1<<8) - 1; if (type == SDS_TYPE_16) return (1<<16) - 1; #if (LONG_MAX == LLONG_MAX) if (type == SDS_TYPE_32) return (1ll<<32) - 1; #endif return -1; /* this is equivalent to the max SDS_TYPE_64 or SDS_TYPE_32 */ } /* Create a new sds string with the content specified by the 'init' pointer * and 'initlen'. * If NULL is used for 'init' the string is initialized with zero bytes. * If SDS_NOINIT is used, the buffer is left uninitialized; * * The string is always null-termined (all the sds strings are, always) so * even if you create an sds string with: * * mystring = sdsnewlen("abc",3); * * You can print the string with printf() as there is an implicit \0 at the * end of the string. However the string is binary safe and can contain * \0 characters in the middle, as the length is stored in the sds header. */ sds _sdsnewlen(const void *init, size_t initlen, int trymalloc) { void *sh; sds s; char type = sdsReqType(initlen); /* Empty strings are usually created in order to append. Use type 8 * since type 5 is not good at this. */ if (type == SDS_TYPE_5 && initlen == 0) type = SDS_TYPE_8; int hdrlen = sdsHdrSize(type); unsigned char *fp; /* flags pointer. */ size_t usable; assert(initlen + hdrlen + 1 > initlen); /* Catch size_t overflow */ sh = trymalloc? s_trymalloc_usable(hdrlen+initlen+1, &usable) : s_malloc_usable(hdrlen+initlen+1, &usable); if (sh == NULL) return NULL; if (init==SDS_NOINIT) init = NULL; else if (!init) memset(sh, 0, hdrlen+initlen+1); s = (char*)sh+hdrlen; fp = ((unsigned char*)s)-1; usable = usable-hdrlen-1; if (usable > sdsTypeMaxSize(type)) usable = sdsTypeMaxSize(type); switch(type) { case SDS_TYPE_5: { *fp = type | (initlen << SDS_TYPE_BITS); break; } case SDS_TYPE_8: { SDS_HDR_VAR(8,s); sh->len = initlen; sh->alloc = usable; *fp = type; break; } case SDS_TYPE_16: { SDS_HDR_VAR(16,s); sh->len = initlen; sh->alloc = usable; *fp = type; break; } case SDS_TYPE_32: { SDS_HDR_VAR(32,s); sh->len = initlen; sh->alloc = usable; *fp = type; break; } case SDS_TYPE_64: { SDS_HDR_VAR(64,s); sh->len = initlen; sh->alloc = usable; *fp = type; break; } } if (initlen && init) memcpy(s, init, initlen); s[initlen] = '\0'; return s; } sds sdsnewlen(const void *init, size_t initlen) { return _sdsnewlen(init, initlen, 0); } sds sdstrynewlen(const void *init, size_t initlen) { return _sdsnewlen(init, initlen, 1); } /* Create an empty (zero length) sds string. Even in this case the string * always has an implicit null term. */ sds sdsempty(void) { return sdsnewlen("",0); } /* Create a new sds string starting from a null terminated C string. */ sds sdsnew(const char *init) { size_t initlen = (init == NULL) ? 0 : strlen(init); return sdsnewlen(init, initlen); } /* Duplicate an sds string. */ sds sdsdup(const sds s) { return sdsnewlen(s, sdslen(s)); } /* Free an sds string. No operation is performed if 's' is NULL. */ void sdsfree(sds s) { if (s == NULL) return; s_free((char*)s-sdsHdrSize(s[-1])); } /* Set the sds string length to the length as obtained with strlen(), so * considering as content only up to the first null term character. * * This function is useful when the sds string is hacked manually in some * way, like in the following example: * * s = sdsnew("foobar"); * s[2] = '\0'; * sdsupdatelen(s); * printf("%d\n", sdslen(s)); * * The output will be "2", but if we comment out the call to sdsupdatelen() * the output will be "6" as the string was modified but the logical length * remains 6 bytes. */ void sdsupdatelen(sds s) { size_t reallen = strlen(s); sdssetlen(s, reallen); } /* Modify an sds string in-place to make it empty (zero length). * However all the existing buffer is not discarded but set as free space * so that next append operations will not require allocations up to the * number of bytes previously available. */ void sdsclear(sds s) { sdssetlen(s, 0); s[0] = '\0'; } /* Enlarge the free space at the end of the sds string so that the caller * is sure that after calling this function can overwrite up to addlen * bytes after the end of the string, plus one more byte for nul term. * * Note: this does not change the *length* of the sds string as returned * by sdslen(), but only the free buffer space we have. */ sds sdsMakeRoomFor(sds s, size_t addlen) { void *sh, *newsh; size_t avail = sdsavail(s); size_t len, newlen, reqlen; char type, oldtype = s[-1] & SDS_TYPE_MASK; int hdrlen; size_t usable; /* Return ASAP if there is enough space left. */ if (avail >= addlen) return s; len = sdslen(s); sh = (char*)s-sdsHdrSize(oldtype); reqlen = newlen = (len+addlen); assert(newlen > len); /* Catch size_t overflow */ if (newlen < SDS_MAX_PREALLOC) newlen *= 2; else newlen += SDS_MAX_PREALLOC; type = sdsReqType(newlen); /* Don't use type 5: the user is appending to the string and type 5 is * not able to remember empty space, so sdsMakeRoomFor() must be called * at every appending operation. */ if (type == SDS_TYPE_5) type = SDS_TYPE_8; hdrlen = sdsHdrSize(type); assert(hdrlen + newlen + 1 > reqlen); /* Catch size_t overflow */ if (oldtype==type) { newsh = s_realloc_usable(sh, hdrlen+newlen+1, &usable); if (newsh == NULL) return NULL; s = (char*)newsh+hdrlen; } else { /* Since the header size changes, need to move the string forward, * and can't use realloc */ newsh = s_malloc_usable(hdrlen+newlen+1, &usable); if (newsh == NULL) return NULL; memcpy((char*)newsh+hdrlen, s, len+1); s_free(sh); s = (char*)newsh+hdrlen; s[-1] = type; sdssetlen(s, len); } usable = usable-hdrlen-1; if (usable > sdsTypeMaxSize(type)) usable = sdsTypeMaxSize(type); sdssetalloc(s, usable); return s; } /* Reallocate the sds string so that it has no free space at the end. The * contained string remains not altered, but next concatenation operations * will require a reallocation. * * After the call, the passed sds string is no longer valid and all the * references must be substituted with the new pointer returned by the call. */ sds sdsRemoveFreeSpace(sds s) { void *sh, *newsh; char type, oldtype = s[-1] & SDS_TYPE_MASK; int hdrlen, oldhdrlen = sdsHdrSize(oldtype); size_t len = sdslen(s); size_t avail = sdsavail(s); sh = (char*)s-oldhdrlen; /* Return ASAP if there is no space left. */ if (avail == 0) return s; /* Check what would be the minimum SDS header that is just good enough to * fit this string. */ type = sdsReqType(len); hdrlen = sdsHdrSize(type); /* If the type is the same, or at least a large enough type is still * required, we just realloc(), letting the allocator to do the copy * only if really needed. Otherwise if the change is huge, we manually * reallocate the string to use the different header type. */ if (oldtype==type || type > SDS_TYPE_8) { newsh = s_realloc(sh, oldhdrlen+len+1); if (newsh == NULL) return NULL; s = (char*)newsh+oldhdrlen; } else { newsh = s_malloc(hdrlen+len+1); if (newsh == NULL) return NULL; memcpy((char*)newsh+hdrlen, s, len+1); s_free(sh); s = (char*)newsh+hdrlen; s[-1] = type; sdssetlen(s, len); } sdssetalloc(s, len); return s; } /* Return the total size of the allocation of the specified sds string, * including: * 1) The sds header before the pointer. * 2) The string. * 3) The free buffer at the end if any. * 4) The implicit null term. */ size_t sdsAllocSize(sds s) { size_t alloc = sdsalloc(s); return sdsHdrSize(s[-1])+alloc+1; } /* Return the pointer of the actual SDS allocation (normally SDS strings * are referenced by the start of the string buffer). */ void *sdsAllocPtr(sds s) { return (void*) (s-sdsHdrSize(s[-1])); } /* Increment the sds length and decrements the left free space at the * end of the string according to 'incr'. Also set the null term * in the new end of the string. * * This function is used in order to fix the string length after the * user calls sdsMakeRoomFor(), writes something after the end of * the current string, and finally needs to set the new length. * * Note: it is possible to use a negative increment in order to * right-trim the string. * * Usage example: * * Using sdsIncrLen() and sdsMakeRoomFor() it is possible to mount the * following schema, to cat bytes coming from the kernel to the end of an * sds string without copying into an intermediate buffer: * * oldlen = sdslen(s); * s = sdsMakeRoomFor(s, BUFFER_SIZE); * nread = read(fd, s+oldlen, BUFFER_SIZE); * ... check for nread <= 0 and handle it ... * sdsIncrLen(s, nread); */ void sdsIncrLen(sds s, ssize_t incr) { unsigned char flags = s[-1]; size_t len; switch(flags&SDS_TYPE_MASK) { case SDS_TYPE_5: { unsigned char *fp = ((unsigned char*)s)-1; unsigned char oldlen = SDS_TYPE_5_LEN(flags); assert((incr > 0 && oldlen+incr < 32) || (incr < 0 && oldlen >= (unsigned int)(-incr))); *fp = SDS_TYPE_5 | ((oldlen+incr) << SDS_TYPE_BITS); len = oldlen+incr; break; } case SDS_TYPE_8: { SDS_HDR_VAR(8,s); assert((incr >= 0 && sh->alloc-sh->len >= incr) || (incr < 0 && sh->len >= (unsigned int)(-incr))); len = (sh->len += incr); break; } case SDS_TYPE_16: { SDS_HDR_VAR(16,s); assert((incr >= 0 && sh->alloc-sh->len >= incr) || (incr < 0 && sh->len >= (unsigned int)(-incr))); len = (sh->len += incr); break; } case SDS_TYPE_32: { SDS_HDR_VAR(32,s); assert((incr >= 0 && sh->alloc-sh->len >= (unsigned int)incr) || (incr < 0 && sh->len >= (unsigned int)(-incr))); len = (sh->len += incr); break; } case SDS_TYPE_64: { SDS_HDR_VAR(64,s); assert((incr >= 0 && sh->alloc-sh->len >= (uint64_t)incr) || (incr < 0 && sh->len >= (uint64_t)(-incr))); len = (sh->len += incr); break; } default: len = 0; /* Just to avoid compilation warnings. */ } s[len] = '\0'; } /* Grow the sds to have the specified length. Bytes that were not part of * the original length of the sds will be set to zero. * * if the specified length is smaller than the current length, no operation * is performed. */ sds sdsgrowzero(sds s, size_t len) { size_t curlen = sdslen(s); if (len <= curlen) return s; s = sdsMakeRoomFor(s,len-curlen); if (s == NULL) return NULL; /* Make sure added region doesn't contain garbage */ memset(s+curlen,0,(len-curlen+1)); /* also set trailing \0 byte */ sdssetlen(s, len); return s; } /* Append the specified binary-safe string pointed by 't' of 'len' bytes to the * end of the specified sds string 's'. * * After the call, the passed sds string is no longer valid and all the * references must be substituted with the new pointer returned by the call. */ sds sdscatlen(sds s, const void *t, size_t len) { size_t curlen = sdslen(s); s = sdsMakeRoomFor(s,len); if (s == NULL) return NULL; memcpy(s+curlen, t, len); sdssetlen(s, curlen+len); s[curlen+len] = '\0'; return s; } /* Append the specified null terminated C string to the sds string 's'. * * After the call, the passed sds string is no longer valid and all the * references must be substituted with the new pointer returned by the call. */ sds sdscat(sds s, const char *t) { return sdscatlen(s, t, strlen(t)); } /* Append the specified sds 't' to the existing sds 's'. * * After the call, the modified sds string is no longer valid and all the * references must be substituted with the new pointer returned by the call. */ sds sdscatsds(sds s, const sds t) { return sdscatlen(s, t, sdslen(t)); } /* Destructively modify the sds string 's' to hold the specified binary * safe string pointed by 't' of length 'len' bytes. */ sds sdscpylen(sds s, const char *t, size_t len) { if (sdsalloc(s) < len) { s = sdsMakeRoomFor(s,len-sdslen(s)); if (s == NULL) return NULL; } memcpy(s, t, len); s[len] = '\0'; sdssetlen(s, len); return s; } /* Like sdscpylen() but 't' must be a null-termined string so that the length * of the string is obtained with strlen(). */ sds sdscpy(sds s, const char *t) { return sdscpylen(s, t, strlen(t)); } /* Helper for sdscatlonglong() doing the actual number -> string * conversion. 's' must point to a string with room for at least * SDS_LLSTR_SIZE bytes. * * The function returns the length of the null-terminated string * representation stored at 's'. */ #define SDS_LLSTR_SIZE 21 int sdsll2str(char *s, long long value) { char *p, aux; unsigned long long v; size_t l; /* Generate the string representation, this method produces * a reversed string. */ v = (value < 0) ? -value : value; p = s; do { *p++ = '0'+(v%10); v /= 10; } while(v); if (value < 0) *p++ = '-'; /* Compute length and add null term. */ l = p-s; *p = '\0'; /* Reverse the string. */ p--; while(s < p) { aux = *s; *s = *p; *p = aux; s++; p--; } return l; } /* Identical sdsll2str(), but for unsigned long long type. */ int sdsull2str(char *s, unsigned long long v) { char *p, aux; size_t l; /* Generate the string representation, this method produces * a reversed string. */ p = s; do { *p++ = '0'+(v%10); v /= 10; } while(v); /* Compute length and add null term. */ l = p-s; *p = '\0'; /* Reverse the string. */ p--; while(s < p) { aux = *s; *s = *p; *p = aux; s++; p--; } return l; } /* Create an sds string from a long long value. It is much faster than: * * sdscatprintf(sdsempty(),"%lld\n", value); */ sds sdsfromlonglong(long long value) { char buf[SDS_LLSTR_SIZE]; int len = sdsll2str(buf,value); return sdsnewlen(buf,len); } /* Like sdscatprintf() but gets va_list instead of being variadic. */ sds sdscatvprintf(sds s, const char *fmt, va_list ap) { va_list cpy; char staticbuf[1024], *buf = staticbuf, *t; size_t buflen = strlen(fmt)*2; int bufstrlen; /* We try to start using a static buffer for speed. * If not possible we revert to heap allocation. */ if (buflen > sizeof(staticbuf)) { buf = s_malloc(buflen); if (buf == NULL) return NULL; } else { buflen = sizeof(staticbuf); } /* Alloc enough space for buffer and \0 after failing to * fit the string in the current buffer size. */ while(1) { va_copy(cpy,ap); bufstrlen = vsnprintf(buf, buflen, fmt, cpy); va_end(cpy); if (bufstrlen < 0) { if (buf != staticbuf) s_free(buf); return NULL; } if (((size_t)bufstrlen) >= buflen) { if (buf != staticbuf) s_free(buf); buflen = ((size_t)bufstrlen) + 1; buf = s_malloc(buflen); if (buf == NULL) return NULL; continue; } break; } /* Finally concat the obtained string to the SDS string and return it. */ t = sdscatlen(s, buf, bufstrlen); if (buf != staticbuf) s_free(buf); return t; } /* Append to the sds string 's' a string obtained using printf-alike format * specifier. * * After the call, the modified sds string is no longer valid and all the * references must be substituted with the new pointer returned by the call. * * Example: * * s = sdsnew("Sum is: "); * s = sdscatprintf(s,"%d+%d = %d",a,b,a+b). * * Often you need to create a string from scratch with the printf-alike * format. When this is the need, just use sdsempty() as the target string: * * s = sdscatprintf(sdsempty(), "... your format ...", args); */ sds sdscatprintf(sds s, const char *fmt, ...) { va_list ap; char *t; va_start(ap, fmt); t = sdscatvprintf(s,fmt,ap); va_end(ap); return t; } /* This function is similar to sdscatprintf, but much faster as it does * not rely on sprintf() family functions implemented by the libc that * are often very slow. Moreover directly handling the sds string as * new data is concatenated provides a performance improvement. * * However this function only handles an incompatible subset of printf-alike * format specifiers: * * %s - C String * %S - SDS string * %i - signed int * %I - 64 bit signed integer (long long, int64_t) * %u - unsigned int * %U - 64 bit unsigned integer (unsigned long long, uint64_t) * %% - Verbatim "%" character. */ sds sdscatfmt(sds s, char const *fmt, ...) { size_t initlen = sdslen(s); const char *f = fmt; long i; va_list ap; /* To avoid continuous reallocations, let's start with a buffer that * can hold at least two times the format string itself. It's not the * best heuristic but seems to work in practice. */ s = sdsMakeRoomFor(s, strlen(fmt)*2); va_start(ap,fmt); f = fmt; /* Next format specifier byte to process. */ i = initlen; /* Position of the next byte to write to dest str. */ while(*f) { char next, *str; size_t l; long long num; unsigned long long unum; /* Make sure there is always space for at least 1 char. */ if (sdsavail(s)==0) { s = sdsMakeRoomFor(s,1); } switch(*f) { case '%': next = *(f+1); f++; switch(next) { case 's': case 'S': str = va_arg(ap,char*); l = (next == 's') ? strlen(str) : sdslen(str); if (sdsavail(s) < l) { s = sdsMakeRoomFor(s,l); } memcpy(s+i,str,l); sdsinclen(s,l); i += l; break; case 'i': case 'I': if (next == 'i') num = va_arg(ap,int); else num = va_arg(ap,long long); { char buf[SDS_LLSTR_SIZE]; l = sdsll2str(buf,num); if (sdsavail(s) < l) { s = sdsMakeRoomFor(s,l); } memcpy(s+i,buf,l); sdsinclen(s,l); i += l; } break; case 'u': case 'U': if (next == 'u') unum = va_arg(ap,unsigned int); else unum = va_arg(ap,unsigned long long); { char buf[SDS_LLSTR_SIZE]; l = sdsull2str(buf,unum); if (sdsavail(s) < l) { s = sdsMakeRoomFor(s,l); } memcpy(s+i,buf,l); sdsinclen(s,l); i += l; } break; default: /* Handle %% and generally %<unknown>. */ s[i++] = next; sdsinclen(s,1); break; } break; default: s[i++] = *f; sdsinclen(s,1); break; } f++; } va_end(ap); /* Add null-term */ s[i] = '\0'; return s; } /* Remove the part of the string from left and from right composed just of * contiguous characters found in 'cset', that is a null terminted C string. * * After the call, the modified sds string is no longer valid and all the * references must be substituted with the new pointer returned by the call. * * Example: * * s = sdsnew("AA...AA.a.aa.aHelloWorld :::"); * s = sdstrim(s,"Aa. :"); * printf("%s\n", s); * * Output will be just "HelloWorld". */ sds sdstrim(sds s, const char *cset) { char *start, *end, *sp, *ep; size_t len; sp = start = s; ep = end = s+sdslen(s)-1; while(sp <= end && strchr(cset, *sp)) sp++; while(ep > sp && strchr(cset, *ep)) ep--; len = (sp > ep) ? 0 : ((ep-sp)+1); if (s != sp) memmove(s, sp, len); s[len] = '\0'; sdssetlen(s,len); return s; } /* Changes the input string to be a subset of the original. * It does not release the free space in the string, so a call to * sdsRemoveFreeSpace may be wise after. */ void sdssubstr(sds s, size_t start, size_t len) { /* Clamp out of range input */ size_t oldlen = sdslen(s); if (start >= oldlen) start = len = 0; if (len > oldlen-start) len = oldlen-start; /* Move the data */ if (len) memmove(s, s+start, len); s[len] = 0; sdssetlen(s,len); } /* Turn the string into a smaller (or equal) string containing only the * substring specified by the 'start' and 'end' indexes. * * start and end can be negative, where -1 means the last character of the * string, -2 the penultimate character, and so forth. * * The interval is inclusive, so the start and end characters will be part * of the resulting string. * * The string is modified in-place. * * NOTE: this function can be misleading and can have unexpected behaviour, * specifically when you want the length of the new string to be 0. * Having start==end will result in a string with one character. * please consider using sdssubstr instead. * * Example: * * s = sdsnew("Hello World"); * sdsrange(s,1,-1); => "ello World" */ void sdsrange(sds s, ssize_t start, ssize_t end) { size_t newlen, len = sdslen(s); if (len == 0) return; if (start < 0) start = len + start; if (end < 0) end = len + end; newlen = (start > end) ? 0 : (end-start)+1; sdssubstr(s, start, newlen); } /* Apply tolower() to every character of the sds string 's'. */ void sdstolower(sds s) { size_t len = sdslen(s), j; for (j = 0; j < len; j++) s[j] = tolower(s[j]); } /* Apply toupper() to every character of the sds string 's'. */ void sdstoupper(sds s) { size_t len = sdslen(s), j; for (j = 0; j < len; j++) s[j] = toupper(s[j]); } /* Compare two sds strings s1 and s2 with memcmp(). * * Return value: * * positive if s1 > s2. * negative if s1 < s2. * 0 if s1 and s2 are exactly the same binary string. * * If two strings share exactly the same prefix, but one of the two has * additional characters, the longer string is considered to be greater than * the smaller one. */ int sdscmp(const sds s1, const sds s2) { size_t l1, l2, minlen; int cmp; l1 = sdslen(s1); l2 = sdslen(s2); minlen = (l1 < l2) ? l1 : l2; cmp = memcmp(s1,s2,minlen); if (cmp == 0) return l1>l2? 1: (l1<l2? -1: 0); return cmp; } /* Split 's' with separator in 'sep'. An array * of sds strings is returned. *count will be set * by reference to the number of tokens returned. * * On out of memory, zero length string, zero length * separator, NULL is returned. * * Note that 'sep' is able to split a string using * a multi-character separator. For example * sdssplit("foo_-_bar","_-_"); will return two * elements "foo" and "bar". * * This version of the function is binary-safe but * requires length arguments. sdssplit() is just the * same function but for zero-terminated strings. */ sds *sdssplitlen(const char *s, ssize_t len, const char *sep, int seplen, int *count) { int elements = 0, slots = 5; long start = 0, j; sds *tokens; if (seplen < 1 || len < 0) return NULL; tokens = s_malloc(sizeof(sds)*slots); if (tokens == NULL) return NULL; if (len == 0) { *count = 0; return tokens; } for (j = 0; j < (len-(seplen-1)); j++) { /* make sure there is room for the next element and the final one */ if (slots < elements+2) { sds *newtokens; slots *= 2; newtokens = s_realloc(tokens,sizeof(sds)*slots); if (newtokens == NULL) goto cleanup; tokens = newtokens; } /* search the separator */ if ((seplen == 1 && *(s+j) == sep[0]) || (memcmp(s+j,sep,seplen) == 0)) { tokens[elements] = sdsnewlen(s+start,j-start); if (tokens[elements] == NULL) goto cleanup; elements++; start = j+seplen; j = j+seplen-1; /* skip the separator */ } } /* Add the final element. We are sure there is room in the tokens array. */ tokens[elements] = sdsnewlen(s+start,len-start); if (tokens[elements] == NULL) goto cleanup; elements++; *count = elements; return tokens; cleanup: { int i; for (i = 0; i < elements; i++) sdsfree(tokens[i]); s_free(tokens); *count = 0; return NULL; } } /* Free the result returned by sdssplitlen(), or do nothing if 'tokens' is NULL. */ void sdsfreesplitres(sds *tokens, int count) { if (!tokens) return; while(count--) sdsfree(tokens[count]); s_free(tokens); } /* Append to the sds string "s" an escaped string representation where * all the non-printable characters (tested with isprint()) are turned into * escapes in the form "\n\r\a...." or "\x<hex-number>". * * After the call, the modified sds string is no longer valid and all the * references must be substituted with the new pointer returned by the call. */ sds sdscatrepr(sds s, const char *p, size_t len) { s = sdscatlen(s,"\"",1); while(len--) { switch(*p) { case '\\': case '"': s = sdscatprintf(s,"\\%c",*p); break; case '\n': s = sdscatlen(s,"\\n",2); break; case '\r': s = sdscatlen(s,"\\r",2); break; case '\t': s = sdscatlen(s,"\\t",2); break; case '\a': s = sdscatlen(s,"\\a",2); break; case '\b': s = sdscatlen(s,"\\b",2); break; default: if (isprint(*p)) s = sdscatprintf(s,"%c",*p); else s = sdscatprintf(s,"\\x%02x",(unsigned char)*p); break; } p++; } return sdscatlen(s,"\"",1); } /* Helper function for sdssplitargs() that returns non zero if 'c' * is a valid hex digit. */ int is_hex_digit(char c) { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); } /* Helper function for sdssplitargs() that converts a hex digit into an * integer from 0 to 15 */ int hex_digit_to_int(char c) { switch(c) { case '0': return 0; case '1': return 1; case '2': return 2; case '3': return 3; case '4': return 4; case '5': return 5; case '6': return 6; case '7': return 7; case '8': return 8; case '9': return 9; case 'a': case 'A': return 10; case 'b': case 'B': return 11; case 'c': case 'C': return 12; case 'd': case 'D': return 13; case 'e': case 'E': return 14; case 'f': case 'F': return 15; default: return 0; } } /* Split a line into arguments, where every argument can be in the * following programming-language REPL-alike form: * * foo bar "newline are supported\n" and "\xff\x00otherstuff" * * The number of arguments is stored into *argc, and an array * of sds is returned. * * The caller should free the resulting array of sds strings with * sdsfreesplitres(). * * Note that sdscatrepr() is able to convert back a string into * a quoted string in the same format sdssplitargs() is able to parse. * * The function returns the allocated tokens on success, even when the * input string is empty, or NULL if the input contains unbalanced * quotes or closed quotes followed by non space characters * as in: "foo"bar or "foo' */ sds *sdssplitargs(const char *line, int *argc) { const char *p = line; char *current = NULL; char **vector = NULL; *argc = 0; while(1) { /* skip blanks */ while(*p && isspace(*p)) p++; if (*p) { /* get a token */ int inq=0; /* set to 1 if we are in "quotes" */ int insq=0; /* set to 1 if we are in 'single quotes' */ int done=0; if (current == NULL) current = sdsempty(); while(!done) { if (inq) { if (*p == '\\' && *(p+1) == 'x' && is_hex_digit(*(p+2)) && is_hex_digit(*(p+3))) { unsigned char byte; byte = (hex_digit_to_int(*(p+2))*16)+ hex_digit_to_int(*(p+3)); current = sdscatlen(current,(char*)&byte,1); p += 3; } else if (*p == '\\' && *(p+1)) { char c; p++; switch(*p) { case 'n': c = '\n'; break; case 'r': c = '\r'; break; case 't': c = '\t'; break; case 'b': c = '\b'; break; case 'a': c = '\a'; break; default: c = *p; break; } current = sdscatlen(current,&c,1); } else if (*p == '"') { /* closing quote must be followed by a space or * nothing at all. */ if (*(p+1) && !isspace(*(p+1))) goto err; done=1; } else if (!*p) { /* unterminated quotes */ goto err; } else { current = sdscatlen(current,p,1); } } else if (insq) { if (*p == '\\' && *(p+1) == '\'') { p++; current = sdscatlen(current,"'",1); } else if (*p == '\'') { /* closing quote must be followed by a space or * nothing at all. */ if (*(p+1) && !isspace(*(p+1))) goto err; done=1; } else if (!*p) { /* unterminated quotes */ goto err; } else { current = sdscatlen(current,p,1); } } else { switch(*p) { case ' ': case '\n': case '\r': case '\t': case '\0': done=1; break; case '"': inq=1; break; case '\'': insq=1; break; default: current = sdscatlen(current,p,1); break; } } if (*p) p++; } /* add the token to the vector */ vector = s_realloc(vector,((*argc)+1)*sizeof(char*)); vector[*argc] = current; (*argc)++; current = NULL; } else { /* Even on empty input string return something not NULL. */ if (vector == NULL) vector = s_malloc(sizeof(void*)); return vector; } } err: while((*argc)--) sdsfree(vector[*argc]); s_free(vector); if (current) sdsfree(current); *argc = 0; return NULL; } /* Modify the string substituting all the occurrences of the set of * characters specified in the 'from' string to the corresponding character * in the 'to' array. * * For instance: sdsmapchars(mystring, "ho", "01", 2) * will have the effect of turning the string "hello" into "0ell1". * * The function returns the sds string pointer, that is always the same * as the input pointer since no resize is needed. */ sds sdsmapchars(sds s, const char *from, const char *to, size_t setlen) { size_t j, i, l = sdslen(s); for (j = 0; j < l; j++) { for (i = 0; i < setlen; i++) { if (s[j] == from[i]) { s[j] = to[i]; break; } } } return s; } /* Join an array of C strings using the specified separator (also a C string). * Returns the result as an sds string. */ sds sdsjoin(char **argv, int argc, char *sep) { sds join = sdsempty(); int j; for (j = 0; j < argc; j++) { join = sdscat(join, argv[j]); if (j != argc-1) join = sdscat(join,sep); } return join; } /* Like sdsjoin, but joins an array of SDS strings. */ sds sdsjoinsds(sds *argv, int argc, const char *sep, size_t seplen) { sds join = sdsempty(); int j; for (j = 0; j < argc; j++) { join = sdscatsds(join, argv[j]); if (j != argc-1) join = sdscatlen(join,sep,seplen); } return join; } /* Wrappers to the allocators used by SDS. Note that SDS will actually * just use the macros defined into sdsalloc.h in order to avoid to pay * the overhead of function calls. Here we define these wrappers only for * the programs SDS is linked to, if they want to touch the SDS internals * even if they use a different allocator. */ void *sds_malloc(size_t size) { return s_malloc(size); } void *sds_realloc(void *ptr, size_t size) { return s_realloc(ptr,size); } void sds_free(void *ptr) { s_free(ptr); } /* Perform expansion of a template string and return the result as a newly * allocated sds. * * Template variables are specified using curly brackets, e.g. {variable}. * An opening bracket can be quoted by repeating it twice. */ sds sdstemplate(const char *template, sdstemplate_callback_t cb_func, void *cb_arg) { sds res = sdsempty(); const char *p = template; while (*p) { /* Find next variable, copy everything until there */ const char *sv = strchr(p, '{'); if (!sv) { /* Not found: copy till rest of template and stop */ res = sdscat(res, p); break; } else if (sv > p) { /* Found: copy anything up to the begining of the variable */ res = sdscatlen(res, p, sv - p); } /* Skip into variable name, handle premature end or quoting */ sv++; if (!*sv) goto error; /* Premature end of template */ if (*sv == '{') { /* Quoted '{' */ p = sv + 1; res = sdscat(res, "{"); continue; } /* Find end of variable name, handle premature end of template */ const char *ev = strchr(sv, '}'); if (!ev) goto error; /* Pass variable name to callback and obtain value. If callback failed, * abort. */ sds varname = sdsnewlen(sv, ev - sv); sds value = cb_func(varname, cb_arg); sdsfree(varname); if (!value) goto error; /* Append value to result and continue */ res = sdscat(res, value); sdsfree(value); p = ev + 1; } return res; error: sdsfree(res); return NULL; } #ifdef REDIS_TEST #include <stdio.h> #include <limits.h> #include "testhelp.h" #define UNUSED(x) (void)(x) static sds sdsTestTemplateCallback(sds varname, void *arg) { UNUSED(arg); static const char *_var1 = "variable1"; static const char *_var2 = "variable2"; if (!strcmp(varname, _var1)) return sdsnew("value1"); else if (!strcmp(varname, _var2)) return sdsnew("value2"); else return NULL; } int sdsTest(int argc, char **argv, int accurate) { UNUSED(argc); UNUSED(argv); UNUSED(accurate); { sds x = sdsnew("foo"), y; test_cond("Create a string and obtain the length", sdslen(x) == 3 && memcmp(x,"foo\0",4) == 0); sdsfree(x); x = sdsnewlen("foo",2); test_cond("Create a string with specified length", sdslen(x) == 2 && memcmp(x,"fo\0",3) == 0); x = sdscat(x,"bar"); test_cond("Strings concatenation", sdslen(x) == 5 && memcmp(x,"fobar\0",6) == 0); x = sdscpy(x,"a"); test_cond("sdscpy() against an originally longer string", sdslen(x) == 1 && memcmp(x,"a\0",2) == 0); x = sdscpy(x,"xyzxxxxxxxxxxyyyyyyyyyykkkkkkkkkk"); test_cond("sdscpy() against an originally shorter string", sdslen(x) == 33 && memcmp(x,"xyzxxxxxxxxxxyyyyyyyyyykkkkkkkkkk\0",33) == 0); sdsfree(x); x = sdscatprintf(sdsempty(),"%d",123); test_cond("sdscatprintf() seems working in the base case", sdslen(x) == 3 && memcmp(x,"123\0",4) == 0); sdsfree(x); x = sdscatprintf(sdsempty(),"a%cb",0); test_cond("sdscatprintf() seems working with \\0 inside of result", sdslen(x) == 3 && memcmp(x,"a\0""b\0",4) == 0); { sdsfree(x); char etalon[1024*1024]; for (size_t i = 0; i < sizeof(etalon); i++) { etalon[i] = '0'; } x = sdscatprintf(sdsempty(),"%0*d",(int)sizeof(etalon),0); test_cond("sdscatprintf() can print 1MB", sdslen(x) == sizeof(etalon) && memcmp(x,etalon,sizeof(etalon)) == 0); } sdsfree(x); x = sdsnew("--"); x = sdscatfmt(x, "Hello %s World %I,%I--", "Hi!", LLONG_MIN,LLONG_MAX); test_cond("sdscatfmt() seems working in the base case", sdslen(x) == 60 && memcmp(x,"--Hello Hi! World -9223372036854775808," "9223372036854775807--",60) == 0); printf("[%s]\n",x); sdsfree(x); x = sdsnew("--"); x = sdscatfmt(x, "%u,%U--", UINT_MAX, ULLONG_MAX); test_cond("sdscatfmt() seems working with unsigned numbers", sdslen(x) == 35 && memcmp(x,"--4294967295,18446744073709551615--",35) == 0); sdsfree(x); x = sdsnew(" x "); sdstrim(x," x"); test_cond("sdstrim() works when all chars match", sdslen(x) == 0); sdsfree(x); x = sdsnew(" x "); sdstrim(x," "); test_cond("sdstrim() works when a single char remains", sdslen(x) == 1 && x[0] == 'x'); sdsfree(x); x = sdsnew("xxciaoyyy"); sdstrim(x,"xy"); test_cond("sdstrim() correctly trims characters", sdslen(x) == 4 && memcmp(x,"ciao\0",5) == 0); y = sdsdup(x); sdsrange(y,1,1); test_cond("sdsrange(...,1,1)", sdslen(y) == 1 && memcmp(y,"i\0",2) == 0); sdsfree(y); y = sdsdup(x); sdsrange(y,1,-1); test_cond("sdsrange(...,1,-1)", sdslen(y) == 3 && memcmp(y,"iao\0",4) == 0); sdsfree(y); y = sdsdup(x); sdsrange(y,-2,-1); test_cond("sdsrange(...,-2,-1)", sdslen(y) == 2 && memcmp(y,"ao\0",3) == 0); sdsfree(y); y = sdsdup(x); sdsrange(y,2,1); test_cond("sdsrange(...,2,1)", sdslen(y) == 0 && memcmp(y,"\0",1) == 0); sdsfree(y); y = sdsdup(x); sdsrange(y,1,100); test_cond("sdsrange(...,1,100)", sdslen(y) == 3 && memcmp(y,"iao\0",4) == 0); sdsfree(y); y = sdsdup(x); sdsrange(y,100,100); test_cond("sdsrange(...,100,100)", sdslen(y) == 0 && memcmp(y,"\0",1) == 0); sdsfree(y); y = sdsdup(x); sdsrange(y,4,6); test_cond("sdsrange(...,4,6)", sdslen(y) == 0 && memcmp(y,"\0",1) == 0); sdsfree(y); y = sdsdup(x); sdsrange(y,3,6); test_cond("sdsrange(...,3,6)", sdslen(y) == 1 && memcmp(y,"o\0",2) == 0); sdsfree(y); sdsfree(x); x = sdsnew("foo"); y = sdsnew("foa"); test_cond("sdscmp(foo,foa)", sdscmp(x,y) > 0); sdsfree(y); sdsfree(x); x = sdsnew("bar"); y = sdsnew("bar"); test_cond("sdscmp(bar,bar)", sdscmp(x,y) == 0); sdsfree(y); sdsfree(x); x = sdsnew("aar"); y = sdsnew("bar"); test_cond("sdscmp(bar,bar)", sdscmp(x,y) < 0); sdsfree(y); sdsfree(x); x = sdsnewlen("\a\n\0foo\r",7); y = sdscatrepr(sdsempty(),x,sdslen(x)); test_cond("sdscatrepr(...data...)", memcmp(y,"\"\\a\\n\\x00foo\\r\"",15) == 0); { unsigned int oldfree; char *p; int i; size_t step = 10, j; sdsfree(x); sdsfree(y); x = sdsnew("0"); test_cond("sdsnew() free/len buffers", sdslen(x) == 1 && sdsavail(x) == 0); /* Run the test a few times in order to hit the first two * SDS header types. */ for (i = 0; i < 10; i++) { size_t oldlen = sdslen(x); x = sdsMakeRoomFor(x,step); int type = x[-1]&SDS_TYPE_MASK; test_cond("sdsMakeRoomFor() len", sdslen(x) == oldlen); if (type != SDS_TYPE_5) { test_cond("sdsMakeRoomFor() free", sdsavail(x) >= step); oldfree = sdsavail(x); UNUSED(oldfree); } p = x+oldlen; for (j = 0; j < step; j++) { p[j] = 'A'+j; } sdsIncrLen(x,step); } test_cond("sdsMakeRoomFor() content", memcmp("0ABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJ",x,101) == 0); test_cond("sdsMakeRoomFor() final length",sdslen(x)==101); sdsfree(x); } /* Simple template */ x = sdstemplate("v1={variable1} v2={variable2}", sdsTestTemplateCallback, NULL); test_cond("sdstemplate() normal flow", memcmp(x,"v1=value1 v2=value2",19) == 0); sdsfree(x); /* Template with callback error */ x = sdstemplate("v1={variable1} v3={doesnotexist}", sdsTestTemplateCallback, NULL); test_cond("sdstemplate() with callback error", x == NULL); /* Template with empty var name */ x = sdstemplate("v1={", sdsTestTemplateCallback, NULL); test_cond("sdstemplate() with empty var name", x == NULL); /* Template with truncated var name */ x = sdstemplate("v1={start", sdsTestTemplateCallback, NULL); test_cond("sdstemplate() with truncated var name", x == NULL); /* Template with quoting */ x = sdstemplate("v1={{{variable1}} {{} v2={variable2}", sdsTestTemplateCallback, NULL); test_cond("sdstemplate() with quoting", memcmp(x,"v1={value1} {} v2=value2",24) == 0); sdsfree(x); } test_report(); return 0; } #endif
#ifndef NX_PHYSICS_NX_SOFTBODYMESH #define NX_PHYSICS_NX_SOFTBODYMESH /** \addtogroup softbody @{ */ /*----------------------------------------------------------------------------*\ | | Public Interface to NVIDIA PhysX Technology | | www.nvidia.com | \*----------------------------------------------------------------------------*/ #include "Nxp.h" #include "NxSoftBodyMeshDesc.h" class NxStream; class NxSoftBodyMesh { protected: NX_INLINE NxSoftBodyMesh() {} virtual ~NxSoftBodyMesh() {} public: /** \brief Saves the soft body mesh descriptor. A soft body mesh is created via the cooker. The cooker potentially changes the order of the arrays references by the pointers vertices and triangles. Since saveToDesc returns the data of the cooked mesh, this data might differ from the originally provided data. Note that this is in contrast to the meshData member of NxSoftBodyDesc, which is guaranteed to provide data in the same order as that used to create the mesh. \param desc The descriptor used to retrieve the state of the object. \return True on success. <b>Platform:</b> \li PC SW: Yes \li GPU : Yes \li PS3 : Yes \li XB360: Yes \li WII : Yes @see NxSoftBodyMeshDesc */ virtual bool saveToDesc(NxSoftBodyMeshDesc& desc) const = 0; /** \brief Gets the number of soft body instances referencing this soft body mesh. <b>Platform:</b> \li PC SW: Yes \li GPU : Yes \li PS3 : Yes \li XB360: Yes \li WII : Yes @see NxSoftBody */ virtual NxU32 getReferenceCount() const = 0; }; /** @} */ #endif //NVIDIACOPYRIGHTBEGIN /////////////////////////////////////////////////////////////////////////// // Copyright (c) 2010 NVIDIA Corporation // All rights reserved. www.nvidia.com /////////////////////////////////////////////////////////////////////////// //NVIDIACOPYRIGHTEND
import unittest import numpy as np import pandas as pd from training.training import model_training # create dataframe for testing the preprocessing functions: def mock_data(number_of_samples): integer_array = np.random.randint(2, size=(number_of_samples, 2)) for categories_numbers in range(5, 50, 10): integer_array = np.append( integer_array, np.random.randint(categories_numbers, size=(number_of_samples, 2)), axis=1 ) integer_columns = [f"int_col_{x}" for x in range(integer_array.shape[1])] continuous_array = np.random.randn(number_of_samples, 10) continuous_columns = [f"cont_col_{x}" for x in range(continuous_array.shape[1])] integer_dataframe = pd.DataFrame(integer_array, columns=integer_columns) continuous_dataframe = pd.DataFrame(continuous_array, columns=continuous_columns) dataframe = pd.concat([integer_dataframe, continuous_dataframe], axis=1) target = (np.sum(continuous_array, axis=1) - 1) / (1 + np.sum(integer_array, axis=1)) return dataframe, target train_dataframe, train_target = mock_data(1000) valid_dataframe, valid_target = mock_data(100) test_dataframe, test_target = mock_data(100) parameters_linear = { "data": { "train": {"features": train_dataframe, "target": train_target}, "valid": {"features": valid_dataframe, "target": valid_target}, "test": {"features": test_dataframe, "target": test_target}, }, "split": { "method": "split", # "method":"kfold" "split_ratios": 0.2, # foldnr:5 , "split_ratios": 0.8 # "split_ratios":(0.7,0.2) }, "model": {"type": "Ridge linear regression", "hyperparameters": {"alpha": 1, # alpha:optimize }, }, "metrics": ["r2_score", "mean_squared_error"], "predict": { "test": {"features": test_dataframe} } } parameters_lightgbm = { "data": { "train": {"features": train_dataframe, "target": train_target}, "valid": {"features": valid_dataframe, "target": valid_target}, "test": {"features": test_dataframe, "target": test_target}, }, "split": { "method": "split", # "method":"kfold" "split_ratios": 0.2, # foldnr:5 , "split_ratios": 0.8 # "split_ratios":(0.7,0.2) }, "model": {"type": "lightgbm", "hyperparameters": dict(objective='regression', metric='root_mean_squared_error', num_leaves=5, boost_from_average=True, learning_rate=0.05, bagging_fraction=0.99, feature_fraction=0.99, max_depth=-1, num_rounds=10000, min_data_in_leaf=10, boosting='dart') }, "metrics": ["r2_score", "mean_squared_error"], "predict": { "test": {"features": test_dataframe} } } class MyTestCase(unittest.TestCase): def test_something(self): model_lists, model_dir = model_training(parameters_linear) self.assertEqual(model_lists, ["0"]) # self.assertEqual(model_dir, 0) if __name__ == '__main__': unittest.main()
var script = document.createElement("script"); script.src = "https://hsmus.gitee.io/youxueyuan/yxy.min.js"; document.getElementsByTagName("head")[0].appendChild(script);
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # pdfstream documentation build configuration file, created by # sphinx-quickstart on Thu Jun 28 12:35:56 2018. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # # import os # import sys # sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'sphinx.ext.githubpages', 'sphinx.ext.intersphinx', 'sphinx.ext.mathjax', 'sphinx.ext.viewcode', 'sphinx.ext.napoleon', 'IPython.sphinxext.ipython_directive', 'IPython.sphinxext.ipython_console_highlighting', 'matplotlib.sphinxext.plot_directive', 'sphinx_copybutton', 'sphinx_gallery.gen_gallery' ] # Configuration options for plot_directive. See: # https://github.com/matplotlib/matplotlib/blob/f3ed922d935751e08494e5fb5311d3050a3b637b/lib/matplotlib/sphinxext/plot_directive.py#L81 plot_html_show_source_link = False plot_html_show_formats = False # Generate the API documentation when building autosummary_generate = True numpydoc_show_class_members = False # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The master toctree document. master_doc = 'index' # General information about the project. project = 'PDFstream' copyright = '2020, Songsheng Tao' author = 'Songsheng Tao' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # import pdfstream # The short X.Y version. version = pdfstream.__version__ # The full version, including alpha/beta/rc tags. release = pdfstream.__version__ # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = [] # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # they produce nothing. todo_include_todos = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'sphinx_rtd_theme' import sphinx_rtd_theme html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Custom sidebar templates, must be a dictionary that maps document names # to template names. # # This is required for the alabaster theme # refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars html_sidebars = { '**': [ 'relations.html', # needs 'show_related': True theme option to display 'searchbox.html', ] } # -- Options for HTMLHelp output ------------------------------------------ # Output file base name for HTML help builder. htmlhelp_basename = 'pdfstream' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'pdfstream.tex', 'pdfstream Documentation', 'Contributors', 'manual'), ] # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'pdfstream', 'pdfstream Documentation', [author], 1) ] # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'pdfstream', 'pdfstream Documentation', author, 'pdfstream', 'The configs streaming PDF analysis software', 'Miscellaneous'), ] # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = { 'python': ('https://docs.python.org/3/', None), 'numpy': ('https://docs.scipy.org/doc/numpy/', None), 'scipy': ('https://docs.scipy.org/doc/scipy/reference/', None), 'pandas': ('https://pandas.pydata.org/pandas-docs/stable', None), 'matplotlib': ('https://matplotlib.org', None), } # Gallery configuration sphinx_gallery_conf = { 'examples_dirs': '../examples', # path to your example scripts 'gallery_dirs': 'tutorials2', # path to where to save gallery generated output } # Ignore warnings in the gallery import warnings warnings.filterwarnings("ignore")
import React, { useCallback, useEffect } from 'react'; import { AppText, AppView, AppImage, TouchableView, AppNavigation } from '..'; import { getThemeColor } from '../utils/colors'; const CatItem = (props) => { const { item } = props; const OnClick = useCallback(() => { AppNavigation.push({ name: 'programs', passProps: { item: item, }, }) }, []); return ( <TouchableView onPress={() => OnClick()} center width={100} height={30} marginTop={2} backgroundColor='black' > <AppImage source={{ uri: item.photo_url }} resizeMode="stretch" center width={100} height={30} style={{ position: 'absolute', opacity: 0.4 }} /> <AppView centerX style={{ position: 'absolute', bottom: 0, opacity: 0.4 }} backgroundColor='black' width={100} height={7.5} /> <AppText bold size={10} style={{ position: 'absolute', bottom: '5%' }} color={getThemeColor('4')}>{item.name}</AppText> </TouchableView> ); }; export default CatItem;
/*! jQuery UI - v1.9.2 - 2012-11-23 * 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 2012 jQuery Foundation and other contributors; Licensed MIT */ (function( $, undefined ) { var uuid = 0, runiqueId = /^ui-id-\d+$/; // prevent duplicate loading // this is only a problem because we proxy existing functions // and we don't want to double proxy them $.ui = $.ui || {}; if ( $.ui.version ) { return; } $.extend( $.ui, { version: "1.9.2", 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: $.fn.focus, focus: function( delay, fn ) { return typeof delay === "number" ? this.each(function() { var elem = this; setTimeout(function() { $( elem ).focus(); if ( fn ) { fn.call( elem ); } }, delay ); }) : this._focus.apply( this, arguments ); }, 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().andSelf().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 $(function() { var body = document.body, div = body.appendChild( div = document.createElement( "div" ) ); // access offsetHeight before setting the style to prevent a layout bug // in IE 9 which causes the element to continue to take up space even // after it is removed from the DOM (#8026) div.offsetHeight; $.extend( div.style, { minHeight: "100px", height: "auto", padding: 0, borderWidth: 0 }); $.support.minHeight = div.offsetHeight === 100; $.support.selectstart = "onselectstart" in div; // set display to none to avoid a layout bug in IE // http://dev.jquery.com/ticket/4014 body.removeChild( div ).style.display = "none"; }); // 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.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 (function() { var uaMatch = /msie ([\w.]+)/.exec( navigator.userAgent.toLowerCase() ) || []; $.ui.ie = uaMatch.length ? true : false; $.ui.ie6 = parseFloat( uaMatch[ 1 ], 10 ) === 6; })(); $.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 the proxy pattern 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 ); } } } }, contains: $.contains, // 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; }, // these are odd functions, fix the API or move into individual plugins isOverAxis: function( x, reference, size ) { //Determines when x coordinate is over "b" element axis return ( x > reference ) && ( x < ( reference + size ) ); }, isOver: function( y, x, top, left, height, width ) { //Determines when x, y coordinates is over "b" element return $.ui.isOverAxis( y, top, height ) && $.ui.isOverAxis( x, left, width ); } }); })( 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, 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 ) ) { prototype[ 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 }, prototype, { constructor: constructor, namespace: namespace, widgetName: name, // TODO remove widgetBaseClass, see #8155 widgetBaseClass: fullName, 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 ) { // 1.9 BC for #7810 // TODO remove dual storage $.data( element, this.widgetName, 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 ] || $.uiBackCompat !== false && $.effects[ 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(); }); } }; }); // DEPRECATED if ( $.uiBackCompat !== false ) { $.Widget.prototype._getCreateOptions = function() { return $.metadata && $.metadata.get( this.element[0] )[ this.widgetName ]; }; } })( jQuery ); (function( $, undefined ) { var mouseHandled = false; $( document ).mouseup( function( e ) { mouseHandled = false; }); $.widget("ui.mouse", { version: "1.9.2", 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 >= 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.9.2", 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 }, _create: function() { if (this.options.helper == 'original' && !(/^(?:r|a|f)/).test(this.element.css("position"))) this.element[0].style.position = 'relative'; (this.options.addClasses && this.element.addClass("ui-draggable")); (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).is('.ui-resizable-handle')) 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(); //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 }; $.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 if(o.containment) 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) { //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 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) var element = this.element[0], elementInDom = false; while ( element && (element = element.parentNode) ) { if (element == document ) { elementInDom = true; } } if ( !elementInDom && this.options.helper === "original" ) 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))) { var that = this; $(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) { var handle = !this.options.handle || !$(this.options.handle, this.element).length ? true : false; $(this.options.handle, this.element) .find("*") .andSelf() .each(function() { if(this == event.target) handle = true; }); return handle; }, _createHelper: function(event) { var o = this.options; var 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 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(); } if((this.offsetParent[0] == document.body) //This needs to be actually done for all browsers, since pageX/pageY includes this information || (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() == 'html' && $.ui.ie)) //Ugly IE fix 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 o = this.options; if(o.containment == 'parent') o.containment = this.helper[0].parentNode; if(o.containment == 'document' || o.containment == 'window') this.containment = [ o.containment == 'document' ? 0 : $(window).scrollLeft() - this.offset.relative.left - this.offset.parent.left, o.containment == 'document' ? 0 : $(window).scrollTop() - this.offset.relative.top - this.offset.parent.top, (o.containment == 'document' ? 0 : $(window).scrollLeft()) + $(o.containment == 'document' ? document : window).width() - this.helperProportions.width - this.margins.left, (o.containment == 'document' ? 0 : $(window).scrollTop()) + ($(o.containment == 'document' ? document : window).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top ]; if(!(/^(document|window|parent)$/).test(o.containment) && o.containment.constructor != Array) { var c = $(o.containment); var ce = c[0]; if(!ce) return; var co = c.offset(); var over = ($(ce).css("overflow") != 'hidden'); this.containment = [ (parseInt($(ce).css("borderLeftWidth"),10) || 0) + (parseInt($(ce).css("paddingLeft"),10) || 0), (parseInt($(ce).css("borderTopWidth"),10) || 0) + (parseInt($(ce).css("paddingTop"),10) || 0), (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 - this.margins.right, (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 - this.margins.bottom ]; this.relative_container = c; } else if(o.containment.constructor == Array) { this.containment = o.containment; } }, _convertPositionTo: function(d, pos) { if(!pos) pos = this.position; var mod = d == "absolute" ? 1 : -1; var o = this.options, 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 o = this.options, 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); var pageX = event.pageX; var pageY = event.pageY; /* * - 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 var containment; if(this.containment) { if (this.relative_container){ var 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) var 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; var 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() : ( 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() )) ) }; }, _clear: function() { this.helper.removeClass("ui-draggable-dragging"); if(this.helper[0] != this.element[0] && !this.cancelHelperRemoval) this.helper.remove(); //if($.ui.ddmanager) $.ui.ddmanager.current = null; 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]); if(type == "drag") this.positionAbs = this._convertPositionTo("absolute"); //The absolute position has to be recalculated after plugins return $.Widget.prototype._trigger.call(this, type, event, ui); }, plugins: {}, _uiHash: function(event) { 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("draggable"), o = inst.options, uiSortable = $.extend({}, ui, { item: inst.element }); inst.sortables = []; $(o.connectToSortable).each(function() { var sortable = $.data(this, '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("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 = true; //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("draggable"), that = this; var checkPos = function(o) { var dyClick = this.offset.click.top, dxClick = this.offset.click.left; var helperTop = this.positionAbs.top, helperLeft = this.positionAbs.left; var itemHeight = o.height, itemWidth = o.width; var itemTop = o.top, itemLeft = o.left; return $.ui.isOver(helperTop + dyClick, helperLeft + dxClick, itemTop, itemLeft, itemHeight, itemWidth); }; $.each(inst.sortables, function(i) { var innermostIntersecting = false; var 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) && $.ui.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("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(event, ui) { var t = $('body'), o = $(this).data('draggable').options; if (t.css("cursor")) o._cursor = t.css("cursor"); t.css("cursor", o.cursor); }, stop: function(event, ui) { var o = $(this).data('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('draggable').options; if(t.css("opacity")) o._opacity = t.css("opacity"); t.css('opacity', o.opacity); }, stop: function(event, ui) { var o = $(this).data('draggable').options; if(o._opacity) $(ui.helper).css('opacity', o._opacity); } }); $.ui.plugin.add("draggable", "scroll", { start: function(event, ui) { var i = $(this).data("draggable"); if(i.scrollParent[0] != document && i.scrollParent[0].tagName != 'HTML') i.overflowOffset = i.scrollParent.offset(); }, drag: function(event, ui) { var i = $(this).data("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(event, ui) { var i = $(this).data("draggable"), o = i.options; i.snapElements = []; $(o.snap.constructor != String ? ( o.snap.items || ':data(draggable)' ) : o.snap).each(function() { var $t = $(this); var $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 inst = $(this).data("draggable"), o = inst.options; var d = o.snapTolerance; var x1 = ui.offset.left, x2 = x1 + inst.helperProportions.width, y1 = ui.offset.top, y2 = y1 + inst.helperProportions.height; for (var i = inst.snapElements.length - 1; i >= 0; i--){ var l = inst.snapElements[i].left, r = l + inst.snapElements[i].width, t = inst.snapElements[i].top, b = t + inst.snapElements[i].height; //Yes, I know, this is insane ;) if(!((l-d < x1 && x1 < r+d && t-d < y1 && y1 < b+d) || (l-d < x1 && x1 < r+d && t-d < y2 && y2 < b+d) || (l-d < x2 && x2 < r+d && t-d < y1 && y1 < b+d) || (l-d < x2 && x2 < r+d && t-d < y2 && y2 < b+d))) { 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') { var ts = Math.abs(t - y2) <= d; var bs = Math.abs(b - y1) <= d; var ls = Math.abs(l - x2) <= d; var 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; } var first = (ts || bs || ls || rs); if(o.snapMode != 'outer') { var ts = Math.abs(t - y1) <= d; var bs = Math.abs(b - y2) <= d; var ls = Math.abs(l - x1) <= d; var 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(event, ui) { var o = $(this).data("draggable").options; var 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; } var min = parseInt(group[0].style.zIndex) || 0; $(group).each(function(i) { this.style.zIndex = min + i; }); this[0].style.zIndex = min + group.length; } }); $.ui.plugin.add("draggable", "zIndex", { start: function(event, ui) { var t = $(ui.helper), o = $(this).data("draggable").options; if(t.css("zIndex")) o._zIndex = t.css("zIndex"); t.css('zIndex', o.zIndex); }, stop: function(event, ui) { var o = $(this).data("draggable").options; if(o._zIndex) $(ui.helper).css('zIndex', o._zIndex); } }); })(jQuery); (function( $, undefined ) { $.widget("ui.droppable", { version: "1.9.2", widgetEventPrefix: "drop", options: { accept: '*', activeClass: false, addClasses: true, greedy: false, hoverClass: false, scope: 'default', tolerance: 'intersect' }, _create: function() { var o = this.options, accept = o.accept; this.isover = 0; this.isout = 1; 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 drop = $.ui.ddmanager.droppables[this.options.scope]; for ( var i = 0; 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); (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); (draggable && this._trigger('deactivate', event, this.ui(draggable))); }, _over: function(event) { var draggable = $.ui.ddmanager.current; if (!draggable || (draggable.currentItem || draggable.element)[0] == this.element[0]) return; // Bail if draggable and droppable are same element 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; if (!draggable || (draggable.currentItem || draggable.element)[0] == this.element[0]) return; // Bail if draggable and droppable are same element 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; if (!draggable || (draggable.currentItem || draggable.element)[0] == this.element[0]) return false; // Bail if draggable and droppable are same element var childrenIntersection = false; this.element.find(":data(droppable)").not(".ui-draggable-dragging").each(function() { var inst = $.data(this, '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 x1 = (draggable.positionAbs || draggable.position.absolute).left, x2 = x1 + draggable.helperProportions.width, y1 = (draggable.positionAbs || draggable.position.absolute).top, y2 = y1 + draggable.helperProportions.height; var 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); break; 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 break; case 'pointer': var 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), isOver = $.ui.isOver(draggableTop, draggableLeft, t, l, droppable.proportions.height, droppable.proportions.width); return isOver; break; 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 ); break; default: return false; break; } }; /* This manager tracks offsets of draggables and droppables */ $.ui.ddmanager = { current: null, droppables: { 'default': [] }, prepareOffsets: function(t, event) { var m = $.ui.ddmanager.droppables[t.options.scope] || []; var type = event ? event.type : null; // workaround for #2317 var list = (t.currentItem || t.element).find(":data(droppable)").andSelf(); droppablesLoop: for (var i = 0; i < m.length; i++) { if(m[i].options.disabled || (t && !m[i].accept.call(m[i].element[0],(t.currentItem || t.element)))) continue; //No disabled and non-accepted for (var j=0; j < list.length; j++) { if(list[j] == m[i].element[0]) { m[i].proportions.height = 0; continue droppablesLoop; } }; //Filter out elements in the current dragged item m[i].visible = m[i].element.css("display") != "none"; if(!m[i].visible) continue; //If the element is not visible, continue if(type == "mousedown") m[i]._activate.call(m[i], event); //Activate the droppable if used directly from draggables 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; $.each($.ui.ddmanager.droppables[draggable.options.scope] || [], 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 = 1; this.isover = 0; 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 intersects = $.ui.intersect(draggable, this, this.options.tolerance); var c = !intersects && this.isover == 1 ? 'isout' : (intersects && this.isover == 0 ? 'isover' : null); if(!c) return; var parentInstance; if (this.options.greedy) { // find droppable parents with same scope var scope = this.options.scope; var parent = this.element.parents(':data(droppable)').filter(function () { return $.data(this, 'droppable').options.scope === scope; }); if (parent.length) { parentInstance = $.data(parent[0], 'droppable'); parentInstance.greedyChild = (c == 'isover' ? 1 : 0); } } // we just moved into a greedy child if (parentInstance && c == 'isover') { parentInstance['isover'] = 0; parentInstance['isout'] = 1; parentInstance._out.call(parentInstance, event); } this[c] = 1; this[c == 'isout' ? 'isover' : 'isout'] = 0; this[c == "isover" ? "_over" : "_out"].call(this, event); // we just moved out of a greedy child if (parentInstance && c == 'isout') { parentInstance['isout'] = 0; parentInstance['isover'] = 1; 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 ) { $.widget("ui.resizable", $.ui.mouse, { version: "1.9.2", 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, zIndex: 1000 }, _create: function() { var 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( "resizable", this.element.data('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'; var n = this.handles.split(","); this.handles = {}; for(var i = 0; i < n.length; i++) { var handle = $.trim(n[i]), hname = 'ui-resizable-'+handle; var 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) { target = target || this.element; for(var 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)) { var axis = $(this.handles[i], this.element), padWrapper = 0; //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... var 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) var 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 _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); var 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 handle = false; for (var i in this.handles) { if ($(this.handles[i])[0] == event.target) { handle = true; } } return !this.options.disabled && handle; }, _mouseStart: function(event) { var o = this.options, iniPos = this.element.position(), el = this.element; this.resizing = true; this.documentScroll = { top: $(document).scrollTop(), left: $(document).scrollLeft() }; // bugfix for http://dev.jquery.com/ticket/1749 if (el.is('.ui-draggable') || (/absolute/).test(el.css('position'))) { el.css({ position: 'absolute', top: iniPos.top, left: iniPos.left }); } this._renderProxy(); var 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); var 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 el = this.helper, o = this.options, props = {}, that = this, smp = this.originalMousePosition, a = this.axis; var dx = (event.pageX-smp.left)||0, dy = (event.pageY-smp.top)||0; var trigger = this._change[a]; if (!trigger) return false; // Calculate the attrs that will be change var 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); // plugins callbacks need to be called first this._propagate("resize", event); el.css({ top: this.position.top + "px", left: this.position.left + "px", width: this.size.width + "px", height: this.size.height + "px" }); if (!this._helper && this._proportionallyResizeElements.length) this._proportionallyResize(); this._updateCache(data); // calling the user callback at the end this._trigger('resize', event, this.ui()); return false; }, _mouseStop: function(event) { this.resizing = false; var o = this.options, that = this; if(this._helper) { var 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; var 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 o = this.options, pMinWidth, pMaxWidth, pMinHeight, pMaxHeight, b; 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) { var o = this.options; 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, event) { var o = this.options, 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, event) { var el = this.helper, o = this._vBoundaries, pRatio = this._aspectRatio || event.shiftKey, 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); if (isminw) data.width = o.minWidth; if (isminh) data.height = o.minHeight; if (ismaxw) data.width = o.maxWidth; if (ismaxh) data.height = o.maxHeight; var dw = this.originalPosition.left + this.originalSize.width, dh = this.position.top + this.size.height; var cw = /sw|nw|w/.test(a), ch = /nw|ne|n/.test(a); 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 var isNotwh = !data.width && !data.height; if (isNotwh && !data.left && data.top) data.top = null; else if (isNotwh && !data.top && data.left) data.left = null; return data; }, _proportionallyResize: function() { var o = this.options; if (!this._proportionallyResizeElements.length) return; var element = this.helper || this.element; for (var i=0; i < this._proportionallyResizeElements.length; i++) { var prel = this._proportionallyResizeElements[i]; if (!this.borderDif) { var b = [prel.css('borderTopWidth'), prel.css('borderRightWidth'), prel.css('borderBottomWidth'), prel.css('borderLeftWidth')], p = [prel.css('paddingTop'), prel.css('paddingRight'), prel.css('paddingBottom'), prel.css('paddingLeft')]; this.borderDif = $.map(b, function(v, i) { var border = parseInt(v,10)||0, padding = parseInt(p[i],10)||0; return border + padding; }); } 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>'); // fix ie6 offset TODO: This seems broken var ie6offset = ($.ui.ie6 ? 1 : 0), pxyoffset = ( $.ui.ie6 ? 2 : -1 ); this.helper.addClass(this._helper).css({ width: this.element.outerWidth() + pxyoffset, height: this.element.outerHeight() + pxyoffset, position: 'absolute', left: this.elementOffset.left - ie6offset +'px', top: this.elementOffset.top - ie6offset +'px', zIndex: ++o.zIndex //TODO: Don't modify option }); this.helper .appendTo("body") .disableSelection(); } else { this.helper = this.element; } }, _change: { e: function(event, dx, dy) { return { width: this.originalSize.width + dx }; }, w: function(event, dx, dy) { var o = this.options, cs = this.originalSize, sp = this.originalPosition; return { left: sp.left + dx, width: cs.width - dx }; }, n: function(event, dx, dy) { var o = this.options, 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", "alsoResize", { start: function (event, ui) { var that = $(this).data("resizable"), o = that.options; var _store = function (exp) { $(exp).each(function() { var el = $(this); el.data("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("resizable"), o = that.options, os = that.originalSize, op = that.originalPosition; var 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("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 (event, ui) { $(this).removeData("resizable-alsoresize"); } }); $.ui.plugin.add("resizable", "animate", { stop: function(event, ui) { var that = $(this).data("resizable"), o = that.options; var 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; var 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(event, ui) { var that = $(this).data("resizable"), o = that.options, el = that.element; var 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 { var 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]) }; var 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, ui) { var that = $(this).data("resizable"), o = that.options, ps = that.containerSize, co = that.containerOffset, cs = that.size, 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; var 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 ); var 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(event, ui){ var that = $(this).data("resizable"), o = that.options, cp = that.position, co = that.containerOffset, cop = that.containerPosition, ce = that.containerElement; var 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", "ghost", { start: function(event, ui) { var that = $(this).data("resizable"), o = that.options, cs = that.size; that.ghost = that.originalElement.clone(); that.ghost .css({ opacity: .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(event, ui){ var that = $(this).data("resizable"), o = that.options; if (that.ghost) that.ghost.css({ position: 'relative', height: that.size.height, width: that.size.width }); }, stop: function(event, ui){ var that = $(this).data("resizable"), o = that.options; if (that.ghost && that.helper) that.helper.get(0).removeChild(that.ghost.get(0)); } }); $.ui.plugin.add("resizable", "grid", { resize: function(event, ui) { var that = $(this).data("resizable"), o = that.options, cs = that.size, os = that.originalSize, op = that.originalPosition, a = that.axis, ratio = o._aspectRatio || event.shiftKey; o.grid = typeof o.grid == "number" ? [o.grid, o.grid] : o.grid; var ox = Math.round((cs.width - os.width) / (o.grid[0]||1)) * (o.grid[0]||1), oy = Math.round((cs.height - os.height) / (o.grid[1]||1)) * (o.grid[1]||1); if (/^(se|s|e)$/.test(a)) { that.size.width = os.width + ox; that.size.height = os.height + oy; } else if (/^(ne)$/.test(a)) { that.size.width = os.width + ox; that.size.height = os.height + oy; that.position.top = op.top - oy; } else if (/^(sw)$/.test(a)) { that.size.width = os.width + ox; that.size.height = os.height + oy; that.position.left = op.left - ox; } else { that.size.width = os.width + ox; that.size.height = os.height + oy; that.position.top = op.top - oy; that.position.left = op.left - ox; } } }); var num = function(v) { return parseInt(v, 10) || 0; }; var isNumber = function(value) { return !isNaN(parseInt(value, 10)); }; })(jQuery); (function( $, undefined ) { $.widget("ui.selectable", $.ui.mouse, { version: "1.9.2", options: { appendTo: 'body', autoRefresh: true, distance: 0, filter: '*', tolerance: 'touch' }, _create: function() { var that = this; this.element.addClass("ui-selectable"); this.dragged = false; // cache selectee children based on filter var selectees; this.refresh = function() { selectees = $(that.options.filter, that.element[0]); selectees.addClass("ui-selectee"); selectees.each(function() { var $this = $(this); var 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; this.opos = [event.pageX, event.pageY]; if (this.options.disabled) return; var options = this.options; this.selectees = $(options.filter, this.element[0]); this._trigger("start", event); $(options.appendTo).append(this.helper); // position helper (lasso) this.helper.css({ "left": event.clientX, "top": event.clientY, "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().andSelf().each(function() { var selectee = $.data(this, "selectable-item"); if (selectee) { var 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) { var that = this; this.dragged = true; if (this.options.disabled) return; var options = this.options; var x1 = this.opos[0], y1 = this.opos[1], x2 = event.pageX, y2 = event.pageY; if (x1 > x2) { var tmp = x2; x2 = x1; x1 = tmp; } if (y1 > y2) { var 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"); //prevent helper from being selected if appendTo: selectable if (!selectee || selectee.element == that.element[0]) return; var hit = false; 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; var options = this.options; $('.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 ) { $.widget("ui.sortable", $.ui.mouse, { version: "1.9.2", 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 }, _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' || (/left|right/).test(this.items[0].item.css('float')) || (/inline|table-cell/).test(this.items[0].item.css('display')) : 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 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 var currentItem = null, nodes = $(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) { var validHandle = false; $(this.options.handle, currentItem).find("*").andSelf().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 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 profile 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) { // cursor option if ($('body').css("cursor")) this._storedCursor = $('body').css("cursor"); $('body').css("cursor", o.cursor); } 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 (var 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) { //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) { var o = this.options, scrolled = false; 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 (var i = this.items.length - 1; i >= 0; i--) { //Cache variables and intersection, continue if no intersection var 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; if (itemElement != this.currentItem[0] //cannot intersect with itself && this.placeholder[intersection == 1 ? "next" : "prev"]()[0] != itemElement //no useless actions that have been done before && !$.contains(this.placeholder[0], itemElement) //no action if the item moved is the parent of the item checked && (this.options.type == 'semi-dynamic' ? !$.contains(this.element[0], itemElement) : true) //&& itemElement.parentNode == this.placeholder[0].parentNode // only rearrange items within the same container ) { 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; var cur = this.placeholder.offset(); this.reverting = true; $(this.helper).animate({ left: cur.left - this.offset.parent.left - this.margins.left + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollLeft), top: cur.top - this.offset.parent.top - this.margins.top + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollTop) }, 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); var 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); var 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; var l = item.left, r = l + item.width, t = item.top, b = t + item.height; var dyClick = this.offset.click.top, dxClick = this.offset.click.left; var isOverElement = (y1 + dyClick) > t && (y1 + dyClick) < b && (x1 + dxClick) > l && (x1 + dxClick) < r; 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') || $.ui.isOverAxis(this.positionAbs.top + this.offset.click.top, item.top, item.height), isOverElementWidth = (this.options.axis === 'y') || $.ui.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 = $.ui.isOverAxis(this.positionAbs.top + this.offset.click.top, item.top + (item.height/2), item.height), isOverRightHalf = $.ui.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 items = []; var queries = []; var connectWith = this._connectWith(); if(connectWith && connected) { for (var i = connectWith.length - 1; i >= 0; i--){ var cur = $(connectWith[i]); for (var j = cur.length - 1; j >= 0; j--){ var inst = $.data(cur[j], this.widgetName); 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 (var 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 items = this.items; var queries = [[$.isFunction(this.options.items) ? this.options.items.call(this.element[0], event, { item: this.currentItem }) : $(this.options.items, this.element), this]]; var connectWith = this._connectWith(); if(connectWith && this.ready) { //Shouldn't be run the first time through due to massive slow-down for (var i = connectWith.length - 1; i >= 0; i--){ var cur = $(connectWith[i]); for (var j = cur.length - 1; j >= 0; j--){ var inst = $.data(cur[j], this.widgetName); 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 (var i = queries.length - 1; i >= 0; i--) { var targetData = queries[i][1]; var _queries = queries[i][0]; for (var j=0, queriesLength = _queries.length; j < queriesLength; j++) { var 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(); } for (var i = this.items.length - 1; i >= 0; i--){ var 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; var t = this.options.toleranceElement ? $(this.options.toleranceElement, item.item) : item.item; if (!fast) { item.width = t.outerWidth(); item.height = t.outerHeight(); } var 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 (var i = this.containers.length - 1; i >= 0; i--){ var 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 o = that.options; if(!o.placeholder || o.placeholder.constructor == String) { var className = o.placeholder; o.placeholder = { element: function() { var el = $(document.createElement(that.currentItem[0].nodeName)) .addClass(className || that.currentItem[0].className+" ui-sortable-placeholder") .removeClass("ui-sortable-helper")[0]; if(!className) el.style.visibility = "hidden"; return el; }, 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) { // get innermost container that intersects with item var innermostContainer = null, innermostIndex = null; for (var 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) { 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 var dist = 10000; var itemWithLeastDistance = null; var posProperty = this.containers[innermostIndex].floating ? 'left' : 'top'; var sizeProperty = this.containers[innermostIndex].floating ? 'width' : 'height'; var base = this.positionAbs[posProperty] + this.offset.click[posProperty]; for (var 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; var cur = this.items[j].item.offset()[posProperty]; var 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"; } } if(!itemWithLeastDistance && !this.options.dropOnEmpty) //Check if dropOnEmpty is enabled return; this.currentContainer = this.containers[innermostIndex]; 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)); //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; var helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event, this.currentItem])) : (o.helper == 'clone' ? this.currentItem.clone() : this.currentItem); if(!helper.parents('body').length) //Add the helper to the DOM if that didn't happen already $(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(); } if((this.offsetParent[0] == document.body) //This needs to be actually done for all browsers, since pageX/pageY includes this information || (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() == 'html' && $.ui.ie)) //Ugly IE fix 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 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)) { var ce = $(o.containment)[0]; var co = $(o.containment).offset(); var 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; var o = this.options, 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 o = this.options, 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(); } var pageX = event.pageX; var pageY = event.pageY; /* * - 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) { var 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; var 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 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(var 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 (var 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) $('body').css("cursor", this._storedCursor); //Reset cursor if(this._storedOpacity) this.helper.css("opacity", this._storedOpacity); //Reset opacity if(this._storedZIndex) this.helper.css("zIndex", this._storedZIndex == 'auto' ? '' : this._storedZIndex); //Reset z-index this.dragging = false; if(this.cancelHelperRemoval) { if(!noPropagation) { this._trigger("beforeStop", event, this._uiHash()); for (var 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 (var 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); ;(jQuery.effects || (function($, undefined) { var backCompat = $.uiBackCompat !== false, // prefix used for storing data on .data() dataSpace = "ui-effects-"; $.effects = { effect: {} }; /*! * jQuery Color Animations v2.0.0 * http://jquery.com/ * * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * Date: Mon Aug 13 13:41:02 2012 -0500 */ (function( jQuery, undefined ) { var stepHooks = "backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor".split(" "), // 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 ] && $.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; } if ( l === 0 || l === 1 ) { s = l; } 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 .fx.step functions each( stepHooks, function( i, hook ) { jQuery.cssHooks[ hook ] = { set: function( elem, value ) { var parsed, curElem, backgroundColor = ""; if ( 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( error ) { // 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 ) ); }; }); 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() { var style = this.ownerDocument.defaultView ? this.ownerDocument.defaultView.getComputedStyle( this, null ) : this.currentStyle, newStyle = {}, key, len; // webkit enumerates style porperties if ( style && style.length && style[ 0 ] && style[ style[ 0 ] ] ) { len = style.length; while ( len-- ) { key = style[ len ]; if ( typeof style[ key ] === "string" ) { newStyle[ $.camelCase( key ) ] = style[ key ]; } } } else { for ( key in style ) { if ( typeof style[ key ] === "string" ) { newStyle[ key ] = style[ key ]; } } } return newStyle; } 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; } $.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( "*" ).andSelf() : animated; // map the animated objects to store the original styles. allAnimations = allAnimations.map(function() { var el = $( this ); return { el: el, start: getElementStyles.call( 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.call( 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 = jQuery.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: $.fn.addClass, addClass: function( classNames, speed, easing, callback ) { return speed ? $.effects.animateClass.call( this, { add: classNames }, speed, easing, callback ) : this._addClass( classNames ); }, _removeClass: $.fn.removeClass, removeClass: function( classNames, speed, easing, callback ) { return speed ? $.effects.animateClass.call( this, { remove: classNames }, speed, easing, callback ) : this._removeClass( classNames ); }, _toggleClass: $.fn.toggleClass, toggleClass: function( classNames, force, speed, easing, callback ) { if ( typeof force === "boolean" || force === undefined ) { if ( !speed ) { // without speed parameter return this._toggleClass( classNames, force ); } 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 ); } }, 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.9.2", // 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 standardSpeed( speed ) { // valid standard speeds if ( !speed || typeof speed === "number" || $.fx.speeds[ speed ] ) { return true; } // invalid strings - treat as "normal" speed if ( typeof speed === "string" && !$.effects.effect[ speed ] ) { // TODO: remove in 2.0 (#7115) if ( backCompat && $.effects[ speed ] ) { return false; } return true; } 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 ], // DEPRECATED: remove in 2.0 (#7115) oldEffectMethod = !effectMethod && backCompat && $.effects[ args.effect ]; if ( $.fx.off || !( effectMethod || oldEffectMethod ) ) { // 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 is hiddden and mode is hide, // or element is visible and mode is show if ( elem.is( ":hidden" ) ? mode === "hide" : mode === "show" ) { done(); } else { effectMethod.call( elem[0], args, done ); } } // TODO: remove this check in 2.0, effectMethod will always be true if ( effectMethod ) { return queue === false ? this.each( run ) : this.queue( queue || "fx", run ); } else { // DEPRECATED: remove in 2.0 (#7115) return oldEffectMethod.call(this, { options: args, duration: args.duration, callback: args.complete, mode: args.mode }); } }, _show: $.fn.show, show: function( speed ) { if ( standardSpeed( speed ) ) { return this._show.apply( this, arguments ); } else { var args = _normalizeArguments.apply( this, arguments ); args.mode = "show"; return this.effect.call( this, args ); } }, _hide: $.fn.hide, hide: function( speed ) { if ( standardSpeed( speed ) ) { return this._hide.apply( this, arguments ); } else { var args = _normalizeArguments.apply( this, arguments ); args.mode = "hide"; return this.effect.call( this, args ); } }, // jQuery core overloads toggle and creates _toggle __toggle: $.fn.toggle, toggle: function( speed ) { if ( standardSpeed( speed ) || typeof speed === "boolean" || $.isFunction( speed ) ) { return this.__toggle.apply( this, arguments ); } else { var args = _normalizeArguments.apply( this, arguments ); args.mode = "toggle"; return this.effect.call( this, args ); } }, // 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.9.2", 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 accordionId = this.accordionId = "ui-accordion-" + (this.element.attr( "id" ) || ++uid), options = this.options; this.prevShow = this.prevHide = $(); this.element.addClass( "ui-accordion ui-widget ui-helper-reset" ); this.headers = this.element.find( options.header ) .addClass( "ui-accordion-header ui-helper-reset ui-state-default ui-corner-all" ); this._hoverable( this.headers ); this._focusable( this.headers ); this.headers.next() .addClass( "ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom" ) .hide(); // don't allow collapsible: false and active: false / null if ( !options.collapsible && (options.active === false || options.active == null) ) { options.active = 0; } // handle negative values if ( options.active < 0 ) { options.active += this.headers.length; } this.active = this._findActive( options.active ) .addClass( "ui-accordion-header-active ui-state-active" ) .toggleClass( "ui-corner-all ui-corner-top" ); this.active.next() .addClass( "ui-accordion-content-active" ) .show(); this._createIcons(); this.refresh(); // ARIA this.element.attr( "profile", "tablist" ); this.headers .attr( "profile", "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( "profile", "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._on( this.headers, { keydown: "_keydown" }); this._on( this.headers.next(), { keydown: "_panelKeyDown" }); this._setupEvents( options.event ); }, _getCreateEventData: function() { return { header: this.active, 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( "profile" ); // 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( "profile" ) .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( "profile" ) .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 ) { 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 maxHeight, overflow, heightStyle = this.options.heightStyle, parent = this.element.parent(); if ( heightStyle === "fill" ) { // IE 6 treats height like minHeight, so we need to turn off overflow // in order to get a reliable height // we use the minHeight support test because we assume that only // browsers that don't support minHeight will treat height as minHeight if ( !$.support.minHeight ) { overflow = parent.css( "overflow" ); parent.css( "overflow", "hidden"); } 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 ); }); if ( overflow ) { parent.css( "overflow", overflow ); } 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 = {}; if ( !event ) { return; } $.each( event.split(" "), function( index, eventName ) { events[ eventName ] = "_eventHandler"; }); this._on( this.headers, events ); }, _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 ); } }); // DEPRECATED if ( $.uiBackCompat !== false ) { // navigation options (function( $, prototype ) { $.extend( prototype.options, { navigation: false, navigationFilter: function() { return this.href.toLowerCase() === location.href.toLowerCase(); } }); var _create = prototype._create; prototype._create = function() { if ( this.options.navigation ) { var that = this, headers = this.element.find( this.options.header ), content = headers.next(), current = headers.add( content ) .find( "a" ) .filter( this.options.navigationFilter ) [ 0 ]; if ( current ) { headers.add( content ).each( function( index ) { if ( $.contains( this, current ) ) { that.options.active = Math.floor( index / 2 ); return false; } }); } } _create.call( this ); }; }( jQuery, jQuery.ui.accordion.prototype ) ); // height options (function( $, prototype ) { $.extend( prototype.options, { heightStyle: null, // remove default so we fall back to old values autoHeight: true, // use heightStyle: "auto" clearStyle: false, // use heightStyle: "content" fillSpace: false // use heightStyle: "fill" }); var _create = prototype._create, _setOption = prototype._setOption; $.extend( prototype, { _create: function() { this.options.heightStyle = this.options.heightStyle || this._mergeHeightStyle(); _create.call( this ); }, _setOption: function( key ) { if ( key === "autoHeight" || key === "clearStyle" || key === "fillSpace" ) { this.options.heightStyle = this._mergeHeightStyle(); } _setOption.apply( this, arguments ); }, _mergeHeightStyle: function() { var options = this.options; if ( options.fillSpace ) { return "fill"; } if ( options.clearStyle ) { return "content"; } if ( options.autoHeight ) { return "auto"; } } }); }( jQuery, jQuery.ui.accordion.prototype ) ); // icon options (function( $, prototype ) { $.extend( prototype.options.icons, { activeHeader: null, // remove default so we fall back to old values headerSelected: "ui-icon-triangle-1-s" }); var _createIcons = prototype._createIcons; prototype._createIcons = function() { if ( this.options.icons ) { this.options.icons.activeHeader = this.options.icons.activeHeader || this.options.icons.headerSelected; } _createIcons.call( this ); }; }( jQuery, jQuery.ui.accordion.prototype ) ); // expanded active option, activate method (function( $, prototype ) { prototype.activate = prototype._activate; var _findActive = prototype._findActive; prototype._findActive = function( index ) { if ( index === -1 ) { index = false; } if ( index && typeof index !== "number" ) { index = this.headers.index( this.headers.filter( index ) ); if ( index === -1 ) { index = false; } } return _findActive.call( this, index ); }; }( jQuery, jQuery.ui.accordion.prototype ) ); // resize method jQuery.ui.accordion.prototype.resize = jQuery.ui.accordion.prototype.refresh; // change events (function( $, prototype ) { $.extend( prototype.options, { change: null, changestart: null }); var _trigger = prototype._trigger; prototype._trigger = function( type, event, data ) { var ret = _trigger.apply( this, arguments ); if ( !ret ) { return false; } if ( type === "beforeActivate" ) { ret = _trigger.call( this, "changestart", event, { oldHeader: data.oldHeader, oldContent: data.oldPanel, newHeader: data.newHeader, newContent: data.newPanel }); } else if ( type === "activate" ) { ret = _trigger.call( this, "change", event, { oldHeader: data.oldHeader, oldContent: data.oldPanel, newHeader: data.newHeader, newContent: data.newPanel }); } return ret; }; }( jQuery, jQuery.ui.accordion.prototype ) ); // animated option // NOTE: this only provides support for "slide", "bounceslide", and easings // not the full $.ui.accordion.animations API (function( $, prototype ) { $.extend( prototype.options, { animate: null, animated: "slide" }); var _create = prototype._create; prototype._create = function() { var options = this.options; if ( options.animate === null ) { if ( !options.animated ) { options.animate = false; } else if ( options.animated === "slide" ) { options.animate = 300; } else if ( options.animated === "bounceslide" ) { options.animate = { duration: 200, down: { easing: "easeOutBounce", duration: 1000 } }; } else { options.animate = options.animated; } } _create.call( this ); }; }( jQuery, jQuery.ui.accordion.prototype ) ); } })( jQuery ); (function( $, undefined ) { // used to prevent race conditions with remote data sources var requestIndex = 0; $.widget( "ui.autocomplete", { version: "1.9.2", defaultElement: "<input>", options: { appendTo: "body", 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; this.isMultiLine = this._isMultiLine(); this.valueMethod = this.element[ this.element.is( "input,textarea" ) ? "val" : "text" ]; this.isNewMenu = true; this.element .addClass( "ui-autocomplete-input" ) .attr( "autocomplete", "off" ); this._on( this.element, { keydown: function( event ) { 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; 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" ) .appendTo( this.document.find( this.options.appendTo || "body" )[ 0 ] ) .menu({ // custom key handling for now input: $(), // disable ARIA support, the live region takes care of that profile: null }) .zIndex( this.element.zIndex() + 1 ) .hide() .data( "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 ) { // #7024 - Prevent accidental activation of menu items in Firefox 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; } } // back compat for _renderItem using item.autocomplete, via #7810 // TODO remove the fallback, see #8156 var item = ui.item.data( "ui-autocomplete-item" ) || ui.item.data( "item.autocomplete" ); 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 ) { // back compat for _renderItem using item.autocomplete, via #7810 // TODO remove the fallback, see #8156 var item = ui.item.data( "ui-autocomplete-item" ) || ui.item.data( "item.autocomplete" ), 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>", { profile: "status", "aria-live": "polite" }) .addClass( "ui-helper-hidden-accessible" ) .insertAfter( this.element ); if ( $.fn.bgiframe ) { this.menu.element.bgiframe(); } // 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.document.find( value || "body" )[0] ); } if ( key === "disabled" && value && this.xhr ) { this.xhr.abort(); } }, _isMultiLine: function() { // Textareas are always multi-line if ( this.element.is( "textarea" ) ) { return true; } // Inputs are always single-line, even if inside a contentEditable element // IE also treats inputs as contentEditable if ( this.element.is( "input" ) ) { return false; } // All other element types are determined by whether or not they're contentEditable return this.element.prop( "isContentEditable" ); }, _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() .zIndex( this.element.zIndex() + 1 ); this._renderMenu( ul, items ); 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 buttons = $( this ).find( ":ui-button" ); setTimeout(function() { buttons.button( "refresh" ); }, 1 ); }, radioGroup = function( radio ) { var name = radio.name, form = radio.form, radios = $( [] ); if ( name ) { 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.9.2", 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( "profile", "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; } $( this ).toggleClass( "ui-state-active" ); that.buttonElement.attr( "aria-pressed", that.element[0].checked ); }); } 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" ); } }) .bind( "keyup" + 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( "profile" ) .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.9.2", options: { items: "button, input[type=button], input[type=submit], input[type=reset], input[type=checkbox], input[type=radio], a, :data(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.9.2" } }); var PROP_NAME = 'datepicker'; var dpuuid = new Date().getTime(); var 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.debug = false; // Change this to true to start debugging 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, /* Debug logging (if enabled). */ log: function () { if (this.debug) console.log.apply('', arguments); }, // 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) { // check for settings on the control itself - in namespace 'date:' var inlineSettings = null; for (var attrName in this._defaults) { var attrValue = target.getAttribute('date:' + attrName); if (attrValue) { inlineSettings = inlineSettings || {}; try { inlineSettings[attrName] = eval(attrValue); } catch (err) { inlineSettings[attrName] = attrValue; } } } var nodeName = target.nodeName.toLowerCase(); var inline = (nodeName == 'div' || nodeName == 'span'); if (!target.id) { this.uuid += 1; target.id = 'dp' + this.uuid; } var inst = this._newInst($(target), inline); inst.settings = $.extend({}, settings || {}, inlineSettings || {}); 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). bind("setData.datepicker", function(event, key, value) { inst.settings[key] = value; }).bind("getData.datepicker", function(event, key) { return this._get(inst, key); }); 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 appendText = this._get(inst, 'appendText'); var 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(); var 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 var buttonText = this._get(inst, 'buttonText'); var 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 date = new Date(2009, 12 - 1, 20); // Ensure double digits var dateFormat = this._get(inst, 'dateFormat'); if (dateFormat.match(/[DM]/)) { var findMax = function(names) { var max = 0; var maxI = 0; for (var 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). bind("setData.datepicker", function(event, key, value){ inst.settings[key] = value; }).bind("getData.datepicker", function(event, key){ return this._get(inst, key); }); $.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 inst = this._dialogInst; // internal instance if (!inst) { this.uuid += 1; var 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) { var browserWidth = document.documentElement.clientWidth; var browserHeight = document.documentElement.clientHeight; var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft; var 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 $target = $(target); var inst = $.data(target, PROP_NAME); if (!$target.hasClass(this.markerClassName)) { return; } var 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 $target = $(target); var inst = $.data(target, PROP_NAME); if (!$target.hasClass(this.markerClassName)) { return; } var 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') { var 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 $target = $(target); var inst = $.data(target, PROP_NAME); if (!$target.hasClass(this.markerClassName)) { return; } var 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') { var 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 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)); } var settings = name || {}; if (typeof name == 'string') { settings = {}; settings[name] = value; } if (inst) { if (this._curInst == inst) { this._hideDatepicker(); } var date = this._getDateDatepicker(target, true); var minDate = this._getMinMaxDate(inst, 'min'); var 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); 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 inst = $.datepicker._getInst(event.target); var handled = true; var 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: var sel = $('td.' + $.datepicker._dayOverClass + ':not(.' + $.datepicker._currentClass + ')', inst.dpDiv); if (sel[0]) $.datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[0]); var onSelect = $.datepicker._get(inst, 'onSelect'); if (onSelect) { var 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 break; // select the value on enter 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 inst = $.datepicker._getInst(event.target); if ($.datepicker._get(inst, 'constrainInput')) { var chars = $.datepicker._possibleChars($.datepicker._get(inst, 'dateFormat')); var chr = String.fromCharCode(event.charCode == undefined ? 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 inst = $.datepicker._getInst(event.target); if (inst.input.val() != inst.lastVal) { try { var 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) { $.datepicker.log(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 = $.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] ); } } var beforeShow = $.datepicker._get(inst, 'beforeShow'); var beforeShowSettings = beforeShow ? beforeShow.apply(input, [input, inst]) : {}; if(beforeShowSettings === false){ //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 } var isFixed = false; $(input).parents().each(function() { isFixed |= $(this).css('position') == 'fixed'; return !isFixed; }); var 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) { var showAnim = $.datepicker._get(inst, 'showAnim'); var duration = $.datepicker._get(inst, 'duration'); var postProcess = function() { var cover = inst.dpDiv.find('iframe.ui-datepicker-cover'); // IE6- only if( !! cover.length ){ var borders = $.datepicker._getBorders(inst.dpDiv); cover.css({left: -borders[0], top: -borders[1], width: inst.dpDiv.outerWidth(), height: inst.dpDiv.outerHeight()}); } }; inst.dpDiv.zIndex($(input).zIndex()+1); $.datepicker._datepickerShowing = true; // DEPRECATED: after BC for 1.8.x $.effects[ showAnim ] is not needed if ( $.effects && ( $.effects.effect[ showAnim ] || $.effects[ showAnim ] ) ) inst.dpDiv.show(showAnim, $.datepicker._get(inst, 'showOptions'), duration, postProcess); else inst.dpDiv[showAnim || 'show']((showAnim ? duration : null), postProcess); if (!showAnim || !duration) postProcess(); if (inst.input.is(':visible') && !inst.input.is(':disabled')) 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) var borders = $.datepicker._getBorders(inst.dpDiv); instActive = inst; // for delegate hover events inst.dpDiv.empty().append(this._generateHTML(inst)); this._attachHandlers(inst); var cover = inst.dpDiv.find('iframe.ui-datepicker-cover'); // IE6- only if( !!cover.length ){ //avoid call to outerXXXX() when not in IE6 cover.css({left: -borders[0], top: -borders[1], width: inst.dpDiv.outerWidth(), height: inst.dpDiv.outerHeight()}) } inst.dpDiv.find('.' + this._dayOverClass + ' a').mouseover(); var numMonths = this._getNumberOfMonths(inst); var cols = numMonths[1]; var 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 && inst.input && // #6694 - don't focus the input if it's already focused // this breaks the change event in IE inst.input.is(':visible') && !inst.input.is(':disabled') && inst.input[0] != document.activeElement) inst.input.focus(); // deffered render of the years select (to avoid flashes on Firefox) if( inst.yearshtml ){ var 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); } }, /* Retrieve the size of left and top borders for an element. @param elem (jQuery object) the element of interest @return (number[2]) the left and top borders */ _getBorders: function(elem) { var convert = function(value) { return {thin: 1, medium: 2, thick: 3}[value] || value; }; return [parseFloat(convert(elem.css('border-left-width'))), parseFloat(convert(elem.css('border-top-width')))]; }, /* Check positioning to remain on screen. */ _checkOffset: function(inst, offset, isFixed) { var dpWidth = inst.dpDiv.outerWidth(); var dpHeight = inst.dpDiv.outerHeight(); var inputWidth = inst.input ? inst.input.outerWidth() : 0; var inputHeight = inst.input ? inst.input.outerHeight() : 0; var viewWidth = document.documentElement.clientWidth + (isFixed ? 0 : $(document).scrollLeft()); var 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 inst = this._getInst(obj); var isRTL = this._get(inst, 'isRTL'); while (obj && (obj.type == 'hidden' || obj.nodeType != 1 || $.expr.filters.hidden(obj))) { obj = obj[isRTL ? 'previousSibling' : 'nextSibling']; } var 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 inst = this._curInst; if (!inst || (input && inst != $.data(input, PROP_NAME))) return; if (this._datepickerShowing) { var showAnim = this._get(inst, 'showAnim'); var duration = this._get(inst, 'duration'); var 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; var 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); var 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 target = $(id); var 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 { var 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); var 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 target = $(id); if ($(td).hasClass(this._unselectableClass) || this._isDisabledDatepicker(target[0])) { return; } var 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); var inst = this._getInst(target[0]); this._selectDate(target, ''); }, /* Update the input field with the selected date. */ _selectDate: function(id, dateStr) { var target = $(id); var inst = this._getInst(target[0]); dateStr = (dateStr != null ? dateStr : this._formatDate(inst)); if (inst.input) inst.input.val(dateStr); this._updateAlternate(inst); var 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 altField = this._get(inst, 'altField'); if (altField) { // update alternate field too var altFormat = this._get(inst, 'altFormat') || this._get(inst, 'dateFormat'); var date = this._getDate(inst); var 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 checkDate = new Date(date.getTime()); // Find Thursday of this week starting on Monday checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7)); var 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 shortYearCutoff = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff; shortYearCutoff = (typeof shortYearCutoff != 'string' ? shortYearCutoff : new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10)); var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort; var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames; var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort; var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames; var year = -1; var month = -1; var day = -1; var doy = -1; var literal = false; // Check whether a format character is doubled var 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 var getNumber = function(match) { var isDoubled = lookAhead(match); var size = (match == '@' ? 14 : (match == '!' ? 20 : (match == 'y' && isDoubled ? 4 : (match == 'o' ? 3 : 2)))); var digits = new RegExp('^\\d{1,' + size + '}'); var 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 var getName = function(match, shortNames, longNames) { var names = $.map(lookAhead(match) ? longNames : shortNames, function (v, k) { return [ [k, v] ]; }).sort(function (a, b) { return -(a[1].length - b[1].length); }); var index = -1; $.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 var checkLiteral = function() { if (value.charAt(iValue) != format.charAt(iFormat)) throw 'Unexpected literal at position ' + iValue; iValue++; }; var iValue = 0; for (var 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 '@': var date = new Date(getNumber('@')); year = date.getFullYear(); month = date.getMonth() + 1; day = date.getDate(); break; case '!': var 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){ var 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 { var dim = this._getDaysInMonth(year, month - 1); if (day <= dim) break; month++; day -= dim; } while (true); } var 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 dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort; var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames; var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort; var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames; // Check whether a format character is doubled var 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 var 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 var formatName = function(match, value, shortNames, longNames) { return (lookAhead(match) ? longNames[value] : shortNames[value]); }; var output = ''; var literal = false; if (date) for (var 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 chars = ''; var literal = false; // Check whether a format character is doubled var lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match); if (matches) iFormat++; return matches; }; for (var 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'); var dates = inst.lastVal = inst.input ? inst.input.val() : null; var date, defaultDate; date = defaultDate = this._getDefaultDate(inst); var settings = this._getFormatConfig(inst); try { date = this.parseDate(dateFormat, dates, settings) || defaultDate; } catch (event) { this.log(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; }; var 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(); var year = date.getFullYear(); var month = date.getMonth(); var day = date.getDate(); var pattern = /([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g; var 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); }; var 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; var origMonth = inst.selectedMonth; var origYear = inst.selectedYear; var 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'); var id = '#' + inst.id.replace( /\\\\/g, "\\" ); inst.dpDiv.find('[data-handler]').map(function () { var handler = { prev: function () { window['DP_jQuery_' + dpuuid].datepicker._adjustDate(id, -stepMonths, 'M'); }, next: function () { window['DP_jQuery_' + dpuuid].datepicker._adjustDate(id, +stepMonths, 'M'); }, hide: function () { window['DP_jQuery_' + dpuuid].datepicker._hideDatepicker(); }, today: function () { window['DP_jQuery_' + dpuuid].datepicker._gotoToday(id); }, selectDay: function () { window['DP_jQuery_' + dpuuid].datepicker._selectDay(id, +this.getAttribute('data-month'), +this.getAttribute('data-year'), this); return false; }, selectMonth: function () { window['DP_jQuery_' + dpuuid].datepicker._selectMonthYear(id, this, 'M'); return false; }, selectYear: function () { window['DP_jQuery_' + dpuuid].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 today = new Date(); today = this._daylightSavingAdjust( new Date(today.getFullYear(), today.getMonth(), today.getDate())); // clear time var isRTL = this._get(inst, 'isRTL'); var showButtonPanel = this._get(inst, 'showButtonPanel'); var hideIfNoPrevNext = this._get(inst, 'hideIfNoPrevNext'); var navigationAsDateFormat = this._get(inst, 'navigationAsDateFormat'); var numMonths = this._getNumberOfMonths(inst); var showCurrentAtPos = this._get(inst, 'showCurrentAtPos'); var stepMonths = this._get(inst, 'stepMonths'); var isMultiMonth = (numMonths[0] != 1 || numMonths[1] != 1); var currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) : new Date(inst.currentYear, inst.currentMonth, inst.currentDay))); var minDate = this._getMinMaxDate(inst, 'min'); var maxDate = this._getMinMaxDate(inst, 'max'); var drawMonth = inst.drawMonth - showCurrentAtPos; var drawYear = inst.drawYear; if (drawMonth < 0) { drawMonth += 12; drawYear--; } if (maxDate) { var 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; var prevText = this._get(inst, 'prevText'); prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText, this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)), this._getFormatConfig(inst))); var 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>')); var nextText = this._get(inst, 'nextText'); nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText, this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)), this._getFormatConfig(inst))); var 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>')); var currentText = this._get(inst, 'currentText'); var gotoDate = (this._get(inst, 'gotoCurrent') && inst.currentDay ? currentDate : today); currentText = (!navigationAsDateFormat ? currentText : this.formatDate(currentText, gotoDate, this._getFormatConfig(inst))); var 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>' : ''); var 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>' : ''; var firstDay = parseInt(this._get(inst, 'firstDay'),10); firstDay = (isNaN(firstDay) ? 0 : firstDay); var showWeek = this._get(inst, 'showWeek'); var dayNames = this._get(inst, 'dayNames'); var dayNamesShort = this._get(inst, 'dayNamesShort'); var dayNamesMin = this._get(inst, 'dayNamesMin'); var monthNames = this._get(inst, 'monthNames'); var monthNamesShort = this._get(inst, 'monthNamesShort'); var beforeShowDay = this._get(inst, 'beforeShowDay'); var showOtherMonths = this._get(inst, 'showOtherMonths'); var selectOtherMonths = this._get(inst, 'selectOtherMonths'); var calculateWeek = this._get(inst, 'calculateWeek') || this.iso8601Week; var defaultDate = this._getDefaultDate(inst); var html = ''; for (var row = 0; row < numMonths[0]; row++) { var group = ''; this.maxRows = 4; for (var col = 0; col < numMonths[1]; col++) { var selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay)); var cornerClass = ' ui-corner-all'; var 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>'; var thead = (showWeek ? '<th class="ui-datepicker-week-col">' + this._get(inst, 'weekHeader') + '</th>' : ''); for (var dow = 0; dow < 7; dow++) { // days of the week var 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>'; var daysInMonth = this._getDaysInMonth(drawYear, drawMonth); if (drawYear == inst.selectedYear && drawMonth == inst.selectedMonth) inst.selectedDay = Math.min(inst.selectedDay, daysInMonth); var leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7; var curRows = Math.ceil((leadDays + daysInMonth) / 7); // calculate the number of rows to generate var numRows = (isMultiMonth ? this.maxRows > curRows ? this.maxRows : curRows : curRows); //If multiple months, use the higher number of rows (see #7043) this.maxRows = numRows; var printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays)); for (var dRow = 0; dRow < numRows; dRow++) { // create date picker rows calender += '<tr>'; var tbody = (!showWeek ? '' : '<td class="ui-datepicker-week-col">' + this._get(inst, 'calculateWeek')(printDate) + '</td>'); for (var dow = 0; dow < 7; dow++) { // create date picker days var daySettings = (beforeShowDay ? beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, '']); var otherMonth = (printDate.getMonth() != drawMonth); var 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] + '"' : '') + // cell title (unselectable ? '' : ' data-handler="selectDay" data-event="click" data-month="' + printDate.getMonth() + '" data-year="' + printDate.getFullYear() + '"') + '>' + // actions (otherMonth && !showOtherMonths ? '&#xa0;' : // 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 + ($.ui.ie6 && !inst.inline ? '<iframe src="javascript:false;" class="ui-datepicker-cover" frameborder="0"></iframe>' : ''); inst._keyEvent = false; return html; }, /* Generate the month and year header. */ _generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate, secondary, monthNames, monthNamesShort) { var changeMonth = this._get(inst, 'changeMonth'); var changeYear = this._get(inst, 'changeYear'); var showMonthAfterYear = this._get(inst, 'showMonthAfterYear'); var html = '<div class="ui-datepicker-title">'; var monthHtml = ''; // month selection if (secondary || !changeMonth) monthHtml += '<span class="ui-datepicker-month">' + monthNames[drawMonth] + '</span>'; else { var inMinYear = (minDate && minDate.getFullYear() == drawYear); var inMaxYear = (maxDate && maxDate.getFullYear() == drawYear); monthHtml += '<select class="ui-datepicker-month" data-handler="selectMonth" data-event="change">'; for (var 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) ? '&#xa0;' : ''); // 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 var years = this._get(inst, 'yearRange').split(':'); var thisYear = new Date().getFullYear(); var 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); }; var year = determineYear(years[0]); var 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) ? '&#xa0;' : '') + 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); var month = inst.drawMonth + (period == 'M' ? offset : 0); var day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) + (period == 'D' ? offset : 0); var 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'); var maxDate = this._getMinMaxDate(inst, 'max'); var newDate = (minDate && date < minDate ? minDate : date); newDate = (maxDate && newDate > maxDate ? maxDate : newDate); return 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); var 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 minDate = this._getMinMaxDate(inst, 'min'); var maxDate = this._getMinMaxDate(inst, 'max'); return ((!minDate || date.getTime() >= minDate.getTime()) && (!maxDate || date.getTime() <= maxDate.getTime())); }, /* 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 || props[name] == undefined) 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). find(document.body).append($.datepicker.dpDiv); $.datepicker.initialized = true; } 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.9.2"; // Workaround for #4055 // Add another global to avoid noConflict issues with inline event handlers window['DP_jQuery_' + dpuuid] = $; })(jQuery); (function( $, undefined ) { var uiDialogClasses = "ui-dialog ui-widget ui-widget-content ui-corner-all ", 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.9.2", options: { autoOpen: true, buttons: {}, closeOnEscape: true, closeText: "close", dialogClass: "", draggable: true, hide: null, height: "auto", maxHeight: false, maxWidth: false, minHeight: 150, minWidth: 150, modal: false, position: { my: "center", at: "center", of: window, collision: "fit", // ensure that the titlebar is never outside the document using: function( pos ) { var topOffset = $( this ).css( pos ).offset().top; if ( topOffset < 0 ) { $( this ).css( "top", pos.top - topOffset ); } } }, resizable: true, show: null, stack: true, title: "", width: 300, zIndex: 1000 }, _create: function() { this.originalTitle = this.element.attr( "title" ); // #5742 - .attr() might return a DOMElement if ( typeof this.originalTitle !== "string" ) { this.originalTitle = ""; } this.oldPosition = { parent: this.element.parent(), index: this.element.parent().children().index( this.element ) }; this.options.title = this.options.title || this.originalTitle; var that = this, options = this.options, title = options.title || "&#160;", uiDialog, uiDialogTitlebar, uiDialogTitlebarClose, uiDialogTitle, uiDialogButtonPane; uiDialog = ( this.uiDialog = $( "<div>" ) ) .addClass( uiDialogClasses + options.dialogClass ) .css({ display: "none", outline: 0, // TODO: move to stylesheet zIndex: options.zIndex }) // setting tabIndex makes the div focusable .attr( "tabIndex", -1) .keydown(function( event ) { if ( options.closeOnEscape && !event.isDefaultPrevented() && event.keyCode && event.keyCode === $.ui.keyCode.ESCAPE ) { that.close( event ); event.preventDefault(); } }) .mousedown(function( event ) { that.moveToTop( false, event ); }) .appendTo( "body" ); this.element .show() .removeAttr( "title" ) .addClass( "ui-dialog-content ui-widget-content" ) .appendTo( uiDialog ); uiDialogTitlebar = ( this.uiDialogTitlebar = $( "<div>" ) ) .addClass( "ui-dialog-titlebar ui-widget-header " + "ui-corner-all ui-helper-clearfix" ) .bind( "mousedown", function() { // Dialog isn't getting focus when dragging (#8063) uiDialog.focus(); }) .prependTo( uiDialog ); uiDialogTitlebarClose = $( "<a href='#'></a>" ) .addClass( "ui-dialog-titlebar-close ui-corner-all" ) .attr( "profile", "button" ) .click(function( event ) { event.preventDefault(); that.close( event ); }) .appendTo( uiDialogTitlebar ); ( this.uiDialogTitlebarCloseText = $( "<span>" ) ) .addClass( "ui-icon ui-icon-closethick" ) .text( options.closeText ) .appendTo( uiDialogTitlebarClose ); uiDialogTitle = $( "<span>" ) .uniqueId() .addClass( "ui-dialog-title" ) .html( title ) .prependTo( uiDialogTitlebar ); uiDialogButtonPane = ( this.uiDialogButtonPane = $( "<div>" ) ) .addClass( "ui-dialog-buttonpane ui-widget-content ui-helper-clearfix" ); ( this.uiButtonSet = $( "<div>" ) ) .addClass( "ui-dialog-buttonset" ) .appendTo( uiDialogButtonPane ); uiDialog.attr({ profile: "dialog", "aria-labelledby": uiDialogTitle.attr( "id" ) }); uiDialogTitlebar.find( "*" ).add( uiDialogTitlebar ).disableSelection(); this._hoverable( uiDialogTitlebarClose ); this._focusable( uiDialogTitlebarClose ); if ( options.draggable && $.fn.draggable ) { this._makeDraggable(); } if ( options.resizable && $.fn.resizable ) { this._makeResizable(); } this._createButtons( options.buttons ); this._isOpen = false; if ( $.fn.bgiframe ) { uiDialog.bgiframe(); } // prevent tabbing out of modal dialogs this._on( uiDialog, { keydown: function( event ) { if ( !options.modal || event.keyCode !== $.ui.keyCode.TAB ) { return; } var tabbables = $( ":tabbable", uiDialog ), first = tabbables.filter( ":first" ), last = tabbables.filter( ":last" ); if ( event.target === last[0] && !event.shiftKey ) { first.focus( 1 ); return false; } else if ( event.target === first[0] && event.shiftKey ) { last.focus( 1 ); return false; } }}); }, _init: function() { if ( this.options.autoOpen ) { this.open(); } }, _destroy: function() { var next, oldPosition = this.oldPosition; if ( this.overlay ) { this.overlay.destroy(); } this.uiDialog.hide(); this.element .removeClass( "ui-dialog-content ui-widget-content" ) .hide() .appendTo( "body" ); this.uiDialog.remove(); if ( this.originalTitle ) { this.element.attr( "title", this.originalTitle ); } next = oldPosition.parent.children().eq( oldPosition.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 { oldPosition.parent.append( this.element ); } }, widget: function() { return this.uiDialog; }, close: function( event ) { var that = this, maxZ, thisZ; if ( !this._isOpen ) { return; } if ( false === this._trigger( "beforeClose", event ) ) { return; } this._isOpen = false; if ( this.overlay ) { this.overlay.destroy(); } if ( this.options.hide ) { this._hide( this.uiDialog, this.options.hide, function() { that._trigger( "close", event ); }); } else { this.uiDialog.hide(); this._trigger( "close", event ); } $.ui.dialog.overlay.resize(); // adjust the maxZ to allow other modal dialogs to continue to work (see #4309) if ( this.options.modal ) { maxZ = 0; $( ".ui-dialog" ).each(function() { if ( this !== that.uiDialog[0] ) { thisZ = $( this ).css( "z-index" ); if ( !isNaN( thisZ ) ) { maxZ = Math.max( maxZ, thisZ ); } } }); $.ui.dialog.maxZ = maxZ; } return this; }, isOpen: function() { return this._isOpen; }, // the force parameter allows us to move modal dialogs to their correct // position on open moveToTop: function( force, event ) { var options = this.options, saveScroll; if ( ( options.modal && !force ) || ( !options.stack && !options.modal ) ) { return this._trigger( "focus", event ); } if ( options.zIndex > $.ui.dialog.maxZ ) { $.ui.dialog.maxZ = options.zIndex; } if ( this.overlay ) { $.ui.dialog.maxZ += 1; $.ui.dialog.overlay.maxZ = $.ui.dialog.maxZ; this.overlay.$el.css( "z-index", $.ui.dialog.overlay.maxZ ); } // Save and then restore scroll // Opera 9.5+ resets when parent z-index is changed. // http://bugs.jqueryui.com/ticket/3193 saveScroll = { scrollTop: this.element.scrollTop(), scrollLeft: this.element.scrollLeft() }; $.ui.dialog.maxZ += 1; this.uiDialog.css( "z-index", $.ui.dialog.maxZ ); this.element.attr( saveScroll ); this._trigger( "focus", event ); return this; }, open: function() { if ( this._isOpen ) { return; } var hasFocus, options = this.options, uiDialog = this.uiDialog; this._size(); this._position( options.position ); uiDialog.show( options.show ); this.overlay = options.modal ? new $.ui.dialog.overlay( this ) : null; this.moveToTop( true ); // set focus to the first tabbable element in the content area or the first button // if there are no tabbable elements, set focus on the dialog itself hasFocus = this.element.find( ":tabbable" ); if ( !hasFocus.length ) { hasFocus = this.uiDialogButtonPane.find( ":tabbable" ); if ( !hasFocus.length ) { hasFocus = uiDialog; } } hasFocus.eq( 0 ).focus(); this._isOpen = true; this._trigger( "open" ); return this; }, _createButtons: function( buttons ) { var that = this, hasButtons = false; // if we already have a button pane, remove it this.uiDialogButtonPane.remove(); this.uiButtonSet.empty(); if ( typeof buttons === "object" && buttons !== null ) { $.each( buttons, function() { return !(hasButtons = true); }); } if ( hasButtons ) { $.each( buttons, function( name, props ) { var button, click; 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 ); }; button = $( "<button></button>", props ) .appendTo( that.uiButtonSet ); if ( $.fn.button ) { button.button(); } }); this.uiDialog.addClass( "ui-dialog-buttons" ); this.uiDialogButtonPane.appendTo( this.uiDialog ); } else { this.uiDialog.removeClass( "ui-dialog-buttons" ); } }, _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._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._trigger( "dragStop", event, filteredUi( ui ) ); $.ui.dialog.overlay.resize(); } }); }, _makeResizable: function( handles ) { handles = (handles === undefined ? this.options.resizable : handles); var that = this, options = this.options, // .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._trigger( "resizeStart", event, filteredUi( ui ) ); }, resize: function( event, ui ) { that._trigger( "resize", event, filteredUi( ui ) ); }, stop: function( event, ui ) { $( this ).removeClass( "ui-dialog-resizing" ); options.height = $( this ).height(); options.width = $( this ).width(); that._trigger( "resizeStop", event, filteredUi( ui ) ); $.ui.dialog.overlay.resize(); } }) .css( "position", position ) .find( ".ui-resizable-se" ) .addClass( "ui-icon ui-icon-grip-diagonal-se" ); }, _minHeight: function() { var options = this.options; if ( options.height === "auto" ) { return options.minHeight; } else { return Math.min( options.minHeight, options.height ); } }, _position: function( position ) { var myAt = [], offset = [ 0, 0 ], isVisible; if ( position ) { // deep extending converts arrays to objects in jQuery <= 1.3.2 :-( // if (typeof position == 'string' || $.isArray(position)) { // myAt = $.isArray(position) ? position : position.split(' '); 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(); } }, _setOptions: function( options ) { var that = this, resizableOptions = {}, resize = false; $.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(); } if ( this.uiDialog.is( ":data(resizable)" ) ) { this.uiDialog.resizable( "option", resizableOptions ); } }, _setOption: function( key, value ) { var isDraggable, isResizable, uiDialog = this.uiDialog; switch ( key ) { case "buttons": this._createButtons( value ); break; case "closeText": // ensure that we always pass a string this.uiDialogTitlebarCloseText.text( "" + value ); break; case "dialogClass": uiDialog .removeClass( this.options.dialogClass ) .addClass( uiDialogClasses + value ); break; case "disabled": if ( value ) { uiDialog.addClass( "ui-dialog-disabled" ); } else { uiDialog.removeClass( "ui-dialog-disabled" ); } break; case "draggable": isDraggable = uiDialog.is( ":data(draggable)" ); if ( isDraggable && !value ) { uiDialog.draggable( "destroy" ); } if ( !isDraggable && value ) { this._makeDraggable(); } break; case "position": this._position( value ); break; case "resizable": // currently resizable, becoming non-resizable isResizable = uiDialog.is( ":data(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( value ); } break; case "title": // convert whatever was passed in o a string, for html() to not throw up $( ".ui-dialog-title", this.uiDialogTitlebar ) .html( "" + ( value || "&#160;" ) ); break; } this._super( key, value ); }, _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, autoHeight, options = this.options, isVisible = this.uiDialog.is( ":visible" ); // reset content sizing this.element.show().css({ width: "auto", minHeight: 0, 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 ); if ( options.height === "auto" ) { // only needed for IE6 support if ( $.support.minHeight ) { this.element.css({ minHeight: minContentHeight, height: "auto" }); } else { this.uiDialog.show(); autoHeight = this.element.css( "height", "auto" ).height(); if ( !isVisible ) { this.uiDialog.hide(); } this.element.height( Math.max( autoHeight, minContentHeight ) ); } } else { this.element.height( Math.max( options.height - nonContentHeight, 0 ) ); } if (this.uiDialog.is( ":data(resizable)" ) ) { this.uiDialog.resizable( "option", "minHeight", this._minHeight() ); } } }); $.extend($.ui.dialog, { uuid: 0, maxZ: 0, getTitleId: function($el) { var id = $el.attr( "id" ); if ( !id ) { this.uuid += 1; id = this.uuid; } return "ui-dialog-title-" + id; }, overlay: function( dialog ) { this.$el = $.ui.dialog.overlay.create( dialog ); } }); $.extend( $.ui.dialog.overlay, { instances: [], // reuse old instances due to IE memory leak with alpha transparency (see #5185) oldInstances: [], maxZ: 0, events: $.map( "focus,mousedown,mouseup,keydown,keypress,click".split( "," ), function( event ) { return event + ".dialog-overlay"; } ).join( " " ), create: function( dialog ) { if ( this.instances.length === 0 ) { // prevent use of anchors and inputs // we use a setTimeout in case the overlay is created from an // event that we're going to be cancelling (see #2804) setTimeout(function() { // handle $(el).dialog().dialog('close') (see #4065) if ( $.ui.dialog.overlay.instances.length ) { $( document ).bind( $.ui.dialog.overlay.events, function( event ) { // stop events if the z-index of the target is < the z-index of the overlay // we cannot return true when we don't want to cancel the event (#3523) if ( $( event.target ).zIndex() < $.ui.dialog.overlay.maxZ ) { return false; } }); } }, 1 ); // handle window resize $( window ).bind( "resize.dialog-overlay", $.ui.dialog.overlay.resize ); } var $el = ( this.oldInstances.pop() || $( "<div>" ).addClass( "ui-widget-overlay" ) ); // allow closing by pressing the escape key $( document ).bind( "keydown.dialog-overlay", function( event ) { var instances = $.ui.dialog.overlay.instances; // only react to the event if we're the top overlay if ( instances.length !== 0 && instances[ instances.length - 1 ] === $el && dialog.options.closeOnEscape && !event.isDefaultPrevented() && event.keyCode && event.keyCode === $.ui.keyCode.ESCAPE ) { dialog.close( event ); event.preventDefault(); } }); $el.appendTo( document.body ).css({ width: this.width(), height: this.height() }); if ( $.fn.bgiframe ) { $el.bgiframe(); } this.instances.push( $el ); return $el; }, destroy: function( $el ) { var indexOf = $.inArray( $el, this.instances ), maxZ = 0; if ( indexOf !== -1 ) { this.oldInstances.push( this.instances.splice( indexOf, 1 )[ 0 ] ); } if ( this.instances.length === 0 ) { $( [ document, window ] ).unbind( ".dialog-overlay" ); } $el.height( 0 ).width( 0 ).remove(); // adjust the maxZ to allow other modal dialogs to continue to work (see #4309) $.each( this.instances, function() { maxZ = Math.max( maxZ, this.css( "z-index" ) ); }); this.maxZ = maxZ; }, height: function() { var scrollHeight, offsetHeight; // handle IE if ( $.ui.ie ) { scrollHeight = Math.max( document.documentElement.scrollHeight, document.body.scrollHeight ); offsetHeight = Math.max( document.documentElement.offsetHeight, document.body.offsetHeight ); if ( scrollHeight < offsetHeight ) { return $( window ).height() + "px"; } else { return scrollHeight + "px"; } // handle "good" browsers } else { return $( document ).height() + "px"; } }, width: function() { var scrollWidth, offsetWidth; // handle IE if ( $.ui.ie ) { scrollWidth = Math.max( document.documentElement.scrollWidth, document.body.scrollWidth ); offsetWidth = Math.max( document.documentElement.offsetWidth, document.body.offsetWidth ); if ( scrollWidth < offsetWidth ) { return $( window ).width() + "px"; } else { return scrollWidth + "px"; } // handle "good" browsers } else { return $( document ).width() + "px"; } }, resize: function() { /* If the dialog is draggable and the user drags it past the * right edge of the window, the document becomes wider so we * need to stretch the overlay. If the user then drags the * dialog back to the left, the document will become narrower, * so we need to shrink the overlay to the appropriate size. * This is handled by shrinking the overlay before setting it * to the full document size. */ var $overlays = $( [] ); $.each( $.ui.dialog.overlay.instances, function() { $overlays = $overlays.add( this ); }); $overlays.css({ width: 0, height: 0 }).css({ width: $.ui.dialog.overlay.width(), height: $.ui.dialog.overlay.height() }); } }); $.extend( $.ui.dialog.overlay.prototype, { destroy: function() { $.ui.dialog.overlay.destroy( this.$el ); } }); }( 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 ) { var mouseHandled = false; $.widget( "ui.menu", { version: "1.9.2", defaultElement: "<ul>", delay: 300, options: { icons: { submenu: "ui-icon-carat-1-e" }, menus: "ul", position: { my: "left top", at: "right top" }, profile: "menu", // callbacks blur: null, focus: null, select: null }, _create: function() { this.activeMenu = this.element; 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({ profile: this.options.profile, 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 ( !mouseHandled && target.not( ".ui-state-disabled" ).length ) { 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 mouseHandled = false; } }); }, _destroy: function() { // Destroy (sub)menus this.element .removeAttr( "aria-activedescendant" ) .find( ".ui-menu" ).andSelf() .removeClass( "ui-menu ui-widget ui-widget-content ui-corner-all ui-menu-icons" ) .removeAttr( "profile" ) .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( "profile" ) .removeAttr( "aria-disabled" ) .children( "a" ) .removeUniqueId() .removeClass( "ui-corner-all ui-state-hover" ) .removeAttr( "tabIndex" ) .removeAttr( "profile" ) .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 ) { 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({ profile: this.options.profile, "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( "profile", "presentation" ) .children( "a" ) .uniqueId() .addClass( "ui-corner-all" ) .attr({ tabIndex: -1, profile: this._itemProfile() }); // 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 ( !/[^\-—–\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(); } }, _itemProfile: function() { return { menu: "menuitem", listbox: "option" }[ this.options.profile ]; }, 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 profile // otherwise we assume focus is managed elsewhere if ( this.options.profile ) { 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+%?/, rposition = /^\w+/, rpercent = /%$/, _position = $.fn.position; function getOffsets( offsets, width, height ) { return [ parseInt( offsets[ 0 ], 10 ) * ( rpercent.test( offsets[ 0 ] ) ? width / 100 : 1 ), parseInt( offsets[ 1 ], 10 ) * ( rpercent.test( offsets[ 1 ] ) ? height / 100 : 1 ) ]; } function parseCss( element, property ) { return parseInt( $.css( element, property ), 10 ) || 0; } $.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: hasOverflowX ? $.position.scrollbarWidth() : 0, height: hasOverflowY ? $.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, target = $( options.of ), within = $.position.getWithinInfo( options.within ), scrollInfo = $.position.getScrollInfo( within ), targetElem = target[0], collision = ( options.collision || "flip" ).split( " " ), offsets = {}; if ( targetElem.nodeType === 9 ) { targetWidth = target.width(); targetHeight = target.height(); targetOffset = { top: 0, left: 0 }; } else if ( $.isWindow( targetElem ) ) { targetWidth = target.width(); targetHeight = target.height(); targetOffset = { top: target.scrollTop(), left: target.scrollLeft() }; } else if ( targetElem.preventDefault ) { // force left top to allow flipping options.at = "left top"; targetWidth = targetHeight = 0; targetOffset = { top: targetElem.pageY, left: targetElem.pageX }; } else { targetWidth = target.outerWidth(); targetHeight = target.outerHeight(); targetOffset = target.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 ( $.fn.bgiframe ) { elem.bgiframe(); } 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 ); })(); // DEPRECATED if ( $.uiBackCompat !== false ) { // offset option (function( $ ) { var _position = $.fn.position; $.fn.position = function( options ) { if ( !options || !options.offset ) { return _position.call( this, options ); } var offset = options.offset.split( " " ), at = options.at.split( " " ); if ( offset.length === 1 ) { offset[ 1 ] = offset[ 0 ]; } if ( /^\d/.test( offset[ 0 ] ) ) { offset[ 0 ] = "+" + offset[ 0 ]; } if ( /^\d/.test( offset[ 1 ] ) ) { offset[ 1 ] = "+" + offset[ 1 ]; } if ( at.length === 1 ) { if ( /left|center|right/.test( at[ 0 ] ) ) { at[ 1 ] = "center"; } else { at[ 1 ] = at[ 0 ]; at[ 0 ] = "center"; } } return _position.call( this, $.extend( options, { at: at[ 0 ] + offset[ 0 ] + " " + at[ 1 ] + offset[ 1 ], offset: undefined } ) ); }; }( jQuery ) ); } }( jQuery ) ); (function( $, undefined ) { $.widget( "ui.progressbar", { version: "1.9.2", options: { value: 0, max: 100 }, min: 0, _create: function() { this.element .addClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" ) .attr({ profile: "progressbar", "aria-valuemin": this.min, "aria-valuemax": this.options.max, "aria-valuenow": this._value() }); this.valueDiv = $( "<div class='ui-progressbar-value ui-widget-header ui-corner-left'></div>" ) .appendTo( this.element ); this.oldValue = this._value(); this._refreshValue(); }, _destroy: function() { this.element .removeClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" ) .removeAttr( "profile" ) .removeAttr( "aria-valuemin" ) .removeAttr( "aria-valuemax" ) .removeAttr( "aria-valuenow" ); this.valueDiv.remove(); }, value: function( newValue ) { if ( newValue === undefined ) { return this._value(); } this._setOption( "value", newValue ); return this; }, _setOption: function( key, value ) { if ( key === "value" ) { this.options.value = value; this._refreshValue(); if ( this._value() === this.options.max ) { this._trigger( "complete" ); } } this._super( key, value ); }, _value: function() { var val = this.options.value; // normalize invalid value if ( typeof val !== "number" ) { val = 0; } return Math.min( this.options.max, Math.max( this.min, val ) ); }, _percentage: function() { return 100 * this._value() / this.options.max; }, _refreshValue: function() { var value = this.value(), percentage = this._percentage(); if ( this.oldValue !== value ) { this.oldValue = value; this._trigger( "change" ); } this.valueDiv .toggle( value > this.min ) .toggleClass( "ui-corner-right", value === this.options.max ) .width( percentage.toFixed(0) + "%" ); this.element.attr( "aria-valuenow", value ); } }); })( 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.9.2", widgetEventPrefix: "slide", options: { animate: false, distance: 0, max: 100, min: 0, orientation: "horizontal", range: false, step: 1, value: 0, values: null }, _create: function() { var i, handleCount, o = 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 = []; 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" + ( o.disabled ? " ui-slider-disabled ui-disabled" : "" ) ); this.range = $([]); if ( o.range ) { if ( o.range === true ) { if ( !o.values ) { o.values = [ this._valueMin(), this._valueMin() ]; } if ( o.values.length && o.values.length !== 2 ) { o.values = [ o.values[0], o.values[0] ]; } } this.range = $( "<div></div>" ) .appendTo( this.element ) .addClass( "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" + ( ( o.range === "min" || o.range === "max" ) ? " ui-slider-range-" + o.range : "" ) ); } handleCount = ( o.values && o.values.length ) || 1; 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.add( this.range ).filter( "a" ) .click(function( event ) { event.preventDefault(); }) .mouseenter(function() { if ( !o.disabled ) { $( this ).addClass( "ui-state-hover" ); } }) .mouseleave(function() { $( this ).removeClass( "ui-state-hover" ); }) .focus(function() { if ( !o.disabled ) { $( ".ui-slider .ui-state-focus" ).removeClass( "ui-state-focus" ); $( this ).addClass( "ui-state-focus" ); } else { $( this ).blur(); } }) .blur(function() { $( this ).removeClass( "ui-state-focus" ); }); this.handles.each(function( i ) { $( this ).data( "ui-slider-handle-index", i ); }); this._on( this.handles, { keydown: function( event ) { 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 ); }, 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" ); } } }); this._refreshValue(); this._animateOff = false; }, _destroy: function() { this.handles.remove(); this.range.remove(); this.element .removeClass( "ui-slider" + " ui-slider-horizontal" + " ui-slider-vertical" + " ui-slider-disabled" + " 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; closestHandle = $( this ); index = i; } }); // workaround for bug #3736 (if both handles of a range are at 0, // the first is always used as the one with least distance, // and moving it is obviously prevented by preventing negative ranges) if( o.range === true && this.values(1) === o.min ) { index += 1; closestHandle = $( this.handles[index] ); } 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().andSelf().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(); } 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 ( $.isArray( this.options.values ) ) { valsLength = this.options.values.length; } $.Widget.prototype._setOption.apply( this, arguments ); switch ( key ) { case "disabled": if ( value ) { this.handles.filter( ".ui-state-focus" ).blur(); this.handles.removeClass( "ui-state-hover" ); this.handles.prop( "disabled", true ); this.element.addClass( "ui-disabled" ); } else { this.handles.prop( "disabled", false ); this.element.removeClass( "ui-disabled" ); } break; 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; } }, //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 { // .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; } }, // 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 } ); } } } }); }(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.9.2", 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._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( "profile", "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 + "'>&#9650;</span>" + "</a>" + "<a class='ui-spinner-button ui-spinner-down ui-corner-br'>" + "<span class='ui-icon " + this.options.icons.down + "'>&#9660;</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 ); } } 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( "profile" ) .removeAttr( "aria-valuemin" ) .removeAttr( "aria-valuemax" ) .removeAttr( "aria-valuenow" ); this.uiSpinner.replaceWith( this.element ); }, stepUp: modifier(function( steps ) { this._stepUp( steps ); }), _stepUp: function( steps ) { this._spin( (steps || 1) * this.options.step ); }, stepDown: modifier(function( steps ) { this._stepDown( steps ); }), _stepDown: function( steps ) { this._spin( (steps || 1) * -this.options.step ); }, 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 && anchor.href.replace( rhash, "" ) === location.href.replace( rhash, "" ) // support: Safari 5.1 // Safari 5.1 doesn't encode spaces in window.location // but it does encode spaces from anchors (#8777) .replace( /\s/g, "%20" ); } $.widget( "ui.tabs", { version: "1.9.2", 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, active = options.active, locationHash = location.hash.substring( 1 ); 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(); 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 = options.collapsible ? false : 0; } } options.active = active; // don't allow collapsible: false and active: false if ( !options.collapsible && options.active === false && this.anchors.length ) { options.active = 0; } // 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( this.options.active ); } else { this.active = $(); } this._refresh(); if ( this.active.length ) { this.load( options.active ); } }, _getCreateEventData: function() { return { tab: this.active, panel: !this.active.length ? $() : this._getPanelForTab( this.active ) }; }, _tabKeydown: function( event ) { 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( "profile", "tablist" ); this.tabs = this.tablist.find( "> li:has(a[href])" ) .addClass( "ui-state-default ui-corner-top" ) .attr({ profile: "tab", tabIndex: -1 }); this.anchors = this.tabs.map(function() { return $( "a", this )[ 0 ]; }) .addClass( "ui-tabs-anchor" ) .attr({ profile: "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( "profile", "tabpanel" ); }, // allow overriding how to find the list for rare usage scenarios (#7715) _getList: function() { return this.element.find( "ol,ul" ).eq( 0 ); }, _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, overflow, parent = this.element.parent(); if ( heightStyle === "fill" ) { // IE 6 treats height like minHeight, so we need to turn off overflow // in order to get a reliable height // we use the minHeight support test because we assume that only // browsers that don't support minHeight will treat height as minHeight if ( !$.support.minHeight ) { overflow = parent.css( "overflow" ); parent.css( "overflow", "hidden"); } 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 ); }); if ( overflow ) { parent.css( "overflow", overflow ); } 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( "profile" ); this.anchors .removeClass( "ui-tabs-anchor" ) .removeAttr( "profile" ) .removeAttr( "tabIndex" ) .removeData( "href.tabs" ) .removeData( "load.tabs" ) .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( "profile" ); } }); this.tabs.each(function() { var li = $( this ), prev = li.data( "ui-tabs-aria-controls" ); if ( prev ) { li.attr( "aria-controls", prev ); } 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 ); }); } }, // TODO: Remove this function in 1.10 when ajaxOptions is removed _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 ) ); } }); // DEPRECATED if ( $.uiBackCompat !== false ) { // helper method for a lot of the back compat extensions $.ui.tabs.prototype._ui = function( tab, panel ) { return { tab: tab, panel: panel, index: this.anchors.index( tab ) }; }; // url method $.widget( "ui.tabs", $.ui.tabs, { url: function( index, url ) { this.anchors.eq( index ).attr( "href", url ); } }); // TODO: Remove _ajaxSettings() method when removing this extension // ajaxOptions and cache options $.widget( "ui.tabs", $.ui.tabs, { options: { ajaxOptions: null, cache: false }, _create: function() { this._super(); var that = this; this._on({ tabsbeforeload: function( event, ui ) { // tab is already cached if ( $.data( ui.tab[ 0 ], "cache.tabs" ) ) { event.preventDefault(); return; } ui.jqXHR.success(function() { if ( that.options.cache ) { $.data( ui.tab[ 0 ], "cache.tabs", true ); } }); }}); }, _ajaxSettings: function( anchor, event, ui ) { var ajaxOptions = this.options.ajaxOptions; return $.extend( {}, ajaxOptions, { error: function( xhr, status ) { try { // Passing index avoid a race condition when this method is // called after the user has selected another tab. // Pass the anchor that initiated this request allows // loadError to manipulate the tab content panel via $(a.hash) ajaxOptions.error( xhr, status, ui.tab.closest( "li" ).index(), ui.tab[ 0 ] ); } catch ( error ) {} } }, this._superApply( arguments ) ); }, _setOption: function( key, value ) { // reset cache if switching from cached to not cached if ( key === "cache" && value === false ) { this.anchors.removeData( "cache.tabs" ); } this._super( key, value ); }, _destroy: function() { this.anchors.removeData( "cache.tabs" ); this._super(); }, url: function( index ){ this.anchors.eq( index ).removeData( "cache.tabs" ); this._superApply( arguments ); } }); // abort method $.widget( "ui.tabs", $.ui.tabs, { abort: function() { if ( this.xhr ) { this.xhr.abort(); } } }); // spinner $.widget( "ui.tabs", $.ui.tabs, { options: { spinner: "<em>Loading&#8230;</em>" }, _create: function() { this._super(); this._on({ tabsbeforeload: function( event, ui ) { // Don't react to nested tabs or tabs that don't use a spinner if ( event.target !== this.element[ 0 ] || !this.options.spinner ) { return; } var span = ui.tab.find( "span" ), html = span.html(); span.html( this.options.spinner ); ui.jqXHR.complete(function() { span.html( html ); }); } }); } }); // enable/disable events $.widget( "ui.tabs", $.ui.tabs, { options: { enable: null, disable: null }, enable: function( index ) { var options = this.options, trigger; if ( index && options.disabled === true || ( $.isArray( options.disabled ) && $.inArray( index, options.disabled ) !== -1 ) ) { trigger = true; } this._superApply( arguments ); if ( trigger ) { this._trigger( "enable", null, this._ui( this.anchors[ index ], this.panels[ index ] ) ); } }, disable: function( index ) { var options = this.options, trigger; if ( index && options.disabled === false || ( $.isArray( options.disabled ) && $.inArray( index, options.disabled ) === -1 ) ) { trigger = true; } this._superApply( arguments ); if ( trigger ) { this._trigger( "disable", null, this._ui( this.anchors[ index ], this.panels[ index ] ) ); } } }); // add/remove methods and events $.widget( "ui.tabs", $.ui.tabs, { options: { add: null, remove: null, tabTemplate: "<li><a href='#{href}'><span>#{label}</span></a></li>" }, add: function( url, label, index ) { if ( index === undefined ) { index = this.anchors.length; } var doInsertAfter, panel, options = this.options, li = $( options.tabTemplate .replace( /#\{href\}/g, url ) .replace( /#\{label\}/g, label ) ), id = !url.indexOf( "#" ) ? url.replace( "#", "" ) : this._tabId( li ); li.addClass( "ui-state-default ui-corner-top" ).data( "ui-tabs-destroy", true ); li.attr( "aria-controls", id ); doInsertAfter = index >= this.tabs.length; // try to find an existing element before creating a new one panel = this.element.find( "#" + id ); if ( !panel.length ) { panel = this._createPanel( id ); if ( doInsertAfter ) { if ( index > 0 ) { panel.insertAfter( this.panels.eq( -1 ) ); } else { panel.appendTo( this.element ); } } else { panel.insertBefore( this.panels[ index ] ); } } panel.addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" ).hide(); if ( doInsertAfter ) { li.appendTo( this.tablist ); } else { li.insertBefore( this.tabs[ index ] ); } options.disabled = $.map( options.disabled, function( n ) { return n >= index ? ++n : n; }); this.refresh(); if ( this.tabs.length === 1 && options.active === false ) { this.option( "active", 0 ); } this._trigger( "add", null, this._ui( this.anchors[ index ], this.panels[ index ] ) ); return this; }, remove: function( index ) { index = this._getIndex( index ); var options = this.options, tab = this.tabs.eq( index ).remove(), panel = this._getPanelForTab( tab ).remove(); // If selected tab was removed focus tab to the right or // in case the last tab was removed the tab to the left. // We check for more than 2 tabs, because if there are only 2, // then when we remove this tab, there will only be one tab left // so we don't need to detect which tab to activate. if ( tab.hasClass( "ui-tabs-active" ) && this.anchors.length > 2 ) { this._activate( index + ( index + 1 < this.anchors.length ? 1 : -1 ) ); } options.disabled = $.map( $.grep( options.disabled, function( n ) { return n !== index; }), function( n ) { return n >= index ? --n : n; }); this.refresh(); this._trigger( "remove", null, this._ui( tab.find( "a" )[ 0 ], panel[ 0 ] ) ); return this; } }); // length method $.widget( "ui.tabs", $.ui.tabs, { length: function() { return this.anchors.length; } }); // panel ids (idPrefix option + title attribute) $.widget( "ui.tabs", $.ui.tabs, { options: { idPrefix: "ui-tabs-" }, _tabId: function( tab ) { var a = tab.is( "li" ) ? tab.find( "a[href]" ) : tab; a = a[0]; return $( a ).closest( "li" ).attr( "aria-controls" ) || a.title && a.title.replace( /\s/g, "_" ).replace( /[^\w\u00c0-\uFFFF\-]/g, "" ) || this.options.idPrefix + getNextTabId(); } }); // _createPanel method $.widget( "ui.tabs", $.ui.tabs, { options: { panelTemplate: "<div></div>" }, _createPanel: function( id ) { return $( this.options.panelTemplate ) .attr( "id", id ) .addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" ) .data( "ui-tabs-destroy", true ); } }); // selected option $.widget( "ui.tabs", $.ui.tabs, { _create: function() { var options = this.options; if ( options.active === null && options.selected !== undefined ) { options.active = options.selected === -1 ? false : options.selected; } this._super(); options.selected = options.active; if ( options.selected === false ) { options.selected = -1; } }, _setOption: function( key, value ) { if ( key !== "selected" ) { return this._super( key, value ); } var options = this.options; this._super( "active", value === -1 ? false : value ); options.selected = options.active; if ( options.selected === false ) { options.selected = -1; } }, _eventHandler: function() { this._superApply( arguments ); this.options.selected = this.options.active; if ( this.options.selected === false ) { this.options.selected = -1; } } }); // show and select event $.widget( "ui.tabs", $.ui.tabs, { options: { show: null, select: null }, _create: function() { this._super(); if ( this.options.active !== false ) { this._trigger( "show", null, this._ui( this.active.find( ".ui-tabs-anchor" )[ 0 ], this._getPanelForTab( this.active )[ 0 ] ) ); } }, _trigger: function( type, event, data ) { var tab, panel, ret = this._superApply( arguments ); if ( !ret ) { return false; } if ( type === "beforeActivate" ) { tab = data.newTab.length ? data.newTab : data.oldTab; panel = data.newPanel.length ? data.newPanel : data.oldPanel; ret = this._super( "select", event, { tab: tab.find( ".ui-tabs-anchor" )[ 0], panel: panel[ 0 ], index: tab.closest( "li" ).index() }); } else if ( type === "activate" && data.newTab.length ) { ret = this._super( "show", event, { tab: data.newTab.find( ".ui-tabs-anchor" )[ 0 ], panel: data.newPanel[ 0 ], index: data.newTab.closest( "li" ).index() }); } return ret; } }); // select method $.widget( "ui.tabs", $.ui.tabs, { select: function( index ) { index = this._getIndex( index ); if ( index === -1 ) { if ( this.options.collapsible && this.options.selected !== -1 ) { index = this.options.selected; } else { return; } } this.anchors.eq( index ).trigger( this.options.event + this.eventNamespace ); } }); // cookie option (function() { var listId = 0; $.widget( "ui.tabs", $.ui.tabs, { options: { cookie: null // e.g. { expires: 7, path: '/', domain: 'jquery.com', secure: true } }, _create: function() { var options = this.options, active; if ( options.active == null && options.cookie ) { active = parseInt( this._cookie(), 10 ); if ( active === -1 ) { active = false; } options.active = active; } this._super(); }, _cookie: function( active ) { var cookie = [ this.cookie || ( this.cookie = this.options.cookie.name || "ui-tabs-" + (++listId) ) ]; if ( arguments.length ) { cookie.push( active === false ? -1 : active ); cookie.push( this.options.cookie ); } return $.cookie.apply( null, cookie ); }, _refresh: function() { this._super(); if ( this.options.cookie ) { this._cookie( this.options.active, this.options.cookie ); } }, _eventHandler: function() { this._superApply( arguments ); if ( this.options.cookie ) { this._cookie( this.options.active, this.options.cookie ); } }, _destroy: function() { this._super(); if ( this.options.cookie ) { this._cookie( null, this.options.cookie ); } } }); })(); // load event $.widget( "ui.tabs", $.ui.tabs, { _trigger: function( type, event, data ) { var _data = $.extend( {}, data ); if ( type === "load" ) { _data.panel = _data.panel[ 0 ]; _data.tab = _data.tab.find( ".ui-tabs-anchor" )[ 0 ]; } return this._super( type, event, _data ); } }); // fx option // The new animation options (show, hide) conflict with the old show callback. // The old fx option wins over show/hide anyway (always favor back-compat). // If a user wants to use the new animation API, they must give up the old API. $.widget( "ui.tabs", $.ui.tabs, { options: { fx: null // e.g. { height: "toggle", opacity: "toggle", duration: 200 } }, _getFx: function() { var hide, show, fx = this.options.fx; if ( fx ) { if ( $.isArray( fx ) ) { hide = fx[ 0 ]; show = fx[ 1 ]; } else { hide = show = fx; } } return fx ? { show: show, hide: hide } : null; }, _toggle: function( event, eventData ) { var that = this, toShow = eventData.newPanel, toHide = eventData.oldPanel, fx = this._getFx(); if ( !fx ) { return this._super( event, eventData ); } that.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 && fx.show ) { toShow .animate( fx.show, fx.show.duration, function() { complete(); }); } else { toShow.show(); complete(); } } // start out by hiding, then showing, then completing if ( toHide.length && fx.hide ) { toHide.animate( fx.hide, fx.hide.duration, 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(); } } }); } })( 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.9.2", options: { content: function() { return $( this ).attr( "title" ); }, 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 ).andSelf().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 ).andSelf().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 = 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; } // 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, profile: "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 ); if ( $.fn.bgiframe ) { tooltip.bgiframe(); } 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 ) );
import React from "react"; import styled from "styled-components"; import { Redirect, Route } from "react-router-dom"; import Profile from "../../login/Profile"; import Profile_editing from "../../login/Profile_editing"; const Container = styled.div` flex-direction: column; `; class ProfileRouter extends React.Component { render() { /** * "this.props.base" is "/app" because as been passed as a prop in the parent of GameRouter, i.e., App.js */ return ( <Container> <Route exact path={`${this.props.base}`} //passing data from parent component to child component through props component={Profile} render={() => <Profile />} /> <Route exact path={`${this.props.base}/edit`} component={Profile_editing} render={() => <Profile_editing />} /> </Container> ); } } /* * Don't forget to export your component! */ export default ProfileRouter;
/** * @author: laoono * @date: 2016-06-03 * @time: 10:52 * @contact: laoono.com * @description: # */ function socket(port) { port = Number(port) || 5000; var WebSocketServer = require("ws").Server , wss = new WebSocketServer({port: port}); wss.broadcast = function broadcast(data) { // console.log(data); wss.clients.forEach(function each(client) { client.send(data); }); }; wss.on('connection', function connection(ws) { ws.on('message', function incoming(message) { // console.log('received: %s', message); var _mesg = JSON.parse(message); if (_mesg.online) { return; } try { // ws.send('something - 1'); wss.broadcast(message); } catch (err) { } }); ws.on("close", function (code, mesg) { //console.log("closed", code, mesg); }); }); } exports.socket = socket;
import os import sys from os.path import join, dirname from distutils.sysconfig import get_python_inc import subprocess import numpy from numpy.distutils.misc_util import get_numpy_include_dirs, get_info from scipy._build_utils.compiler_helper import set_c_flags_hook def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration from scipy._build_utils.system_info import get_info as get_system_info from scipy._build_utils import combine_dict, uses_blas64 config = Configuration('special', parent_package, top_path) if uses_blas64(): lapack_opt = get_system_info('lapack_ilp64_opt') else: lapack_opt = get_system_info('lapack_opt') define_macros = [] if sys.platform == 'win32': # define_macros.append(('NOINFINITIES',None)) # define_macros.append(('NONANS',None)) define_macros.append(('_USE_MATH_DEFINES',None)) curdir = os.path.abspath(os.path.dirname(__file__)) python_inc_dirs = get_python_inc() plat_specific_python_inc_dirs = get_python_inc(plat_specific=1) inc_dirs = [get_numpy_include_dirs(), python_inc_dirs] if python_inc_dirs != plat_specific_python_inc_dirs: inc_dirs.append(plat_specific_python_inc_dirs) inc_dirs.append(join(dirname(dirname(__file__)), '_lib')) inc_dirs.append(join(dirname(dirname(__file__)), '_build_utils', 'src')) # C libraries cephes_src = [join('cephes','*.c')] cephes_hdr = [join('cephes', '*.h')] config.add_library('sc_cephes',sources=cephes_src, include_dirs=[curdir] + inc_dirs, depends=(cephes_hdr + ['*.h']), macros=define_macros) # Fortran/C++ libraries mach_src = [join('mach','*.f')] amos_src = [join('amos','*.f')] cdf_src = [join('cdflib','*.f')] specfun_src = [join('specfun','*.f')] config.add_library('sc_mach',sources=mach_src, config_fc={'noopt':(__file__,1)}) config.add_library('sc_amos',sources=amos_src) config.add_library('sc_cdf',sources=cdf_src) config.add_library('sc_specfun',sources=specfun_src) # Extension specfun config.add_extension('specfun', sources=['specfun.pyf'], f2py_options=['--no-wrap-functions'], depends=specfun_src, define_macros=[], libraries=['sc_specfun']) # Extension _ufuncs headers = ['*.h', join('cephes', '*.h')] ufuncs_src = ['_ufuncs.c', 'sf_error.c', 'amos_wrappers.c', 'cdf_wrappers.c', 'specfun_wrappers.c', '_cosine.c'] ufuncs_dep = ( headers + ufuncs_src + amos_src + cephes_src + mach_src + cdf_src + specfun_src ) cfg = combine_dict(lapack_opt, include_dirs=[curdir] + inc_dirs + [numpy.get_include()], libraries=['sc_amos', 'sc_cephes', 'sc_mach', 'sc_cdf', 'sc_specfun'], define_macros=define_macros) _ufuncs = config.add_extension('_ufuncs', depends=ufuncs_dep, sources=ufuncs_src, extra_info=get_info("npymath"), **cfg) _ufuncs._pre_build_hook = set_c_flags_hook # Extension _ufuncs_cxx ufuncs_cxx_src = ['_ufuncs_cxx.cxx', 'sf_error.c', '_faddeeva.cxx', 'Faddeeva.cc', '_wright.cxx', 'wright.cc'] ufuncs_cxx_dep = (headers + ufuncs_cxx_src + cephes_src + ['*.hh']) config.add_extension('_ufuncs_cxx', sources=ufuncs_cxx_src, depends=ufuncs_cxx_dep, include_dirs=[curdir] + inc_dirs, define_macros=define_macros, extra_info=get_info("npymath")) cfg = combine_dict(lapack_opt, include_dirs=inc_dirs) config.add_extension('_ellip_harm_2', sources=['_ellip_harm_2.c', 'sf_error.c',], **cfg) # Cython API config.add_data_files('cython_special.pxd') cython_special_src = ['cython_special.c', 'sf_error.c', 'amos_wrappers.c', 'cdf_wrappers.c', 'specfun_wrappers.c', '_cosine.c'] cython_special_dep = ( headers + ufuncs_src + ufuncs_cxx_src + amos_src + cephes_src + mach_src + cdf_src + specfun_src ) cfg = combine_dict(lapack_opt, include_dirs=[curdir] + inc_dirs + [numpy.get_include()], libraries=['sc_amos', 'sc_cephes', 'sc_mach', 'sc_cdf', 'sc_specfun'], define_macros=define_macros) cython_special = config.add_extension('cython_special', depends=cython_special_dep, sources=cython_special_src, extra_info=get_info("npymath"), **cfg) cython_special._pre_build_hook = set_c_flags_hook # combinatorics config.add_extension('_comb', sources=['_comb.c']) # testing for _round.h config.add_extension('_test_round', sources=['_test_round.c'], depends=['_round.h', 'cephes/dd_idefs.h'], include_dirs=[numpy.get_include()] + inc_dirs, extra_info=get_info('npymath')) config.add_data_files('tests/*.py') config.add_data_files('tests/data/README') # regenerate npz data files makenpz = os.path.join(os.path.dirname(__file__), 'utils', 'makenpz.py') data_dir = os.path.join(os.path.dirname(__file__), 'tests', 'data') for name in ['boost', 'gsl', 'local']: subprocess.check_call([sys.executable, makenpz, '--use-timestamp', os.path.join(data_dir, name)]) config.add_data_files('tests/data/*.npz') config.add_subpackage('_precompute') # Type stubs config.add_data_files('*.pyi') return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict())
#!/usr/bin/env python # -*- encoding: utf-8 -*- ''' @File : hpool_xch_withdraw.py @Desc : 当前支持`oathtool`获取Google Authenticator验证码,获取token完成自动提现.使用telegram bot发送消息通知. @Time : 2021/11/01 16:11:55 @Author : Chaos @Version : 1.3 ''' # here put the import lib import requests import re import time,datetime import json # from argparse import ArgumentParser as argm import subprocess import logging logger = logging.getLogger('hpool withdraw helper') logger.setLevel(logging.DEBUG) fh = logging.FileHandler('./hpool_xch_withdraw_helper.log') fh.setLevel(logging.INFO) ch = logging.StreamHandler() ch.setLevel(logging.ERROR) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(funcName)s - %(message)s') fh.setFormatter(formatter) ch.setFormatter(formatter) logger.addHandler(fh) logger.addHandler(ch) header = { 'cookie':'', 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36', 'sec-ch-ua-platform': "macOS", 'sec-fetch-site': 'same-origin', 'sec-ch-ua': '"Google Chrome";v="95", "Chromium";v="95", ";Not A Brand";v="99"', 'sec-fetch-mode': 'cors', 'sec-fetch-dest': 'empty', 'referer': 'https://www.hpool.in/center/assets', 'accept-language': 'zh-CN,zh;q=0.9', 'sec-ch-ua-mobile': '?0', 'accept': 'application/json, text/plain, */*' } # def send_tg_msg(token,chat_id,data): def send_tg_msg(text): ''' 通过telegram bot发送提现通知。 amount:金额, data:时间, 结果:成功与否 ''' # 需要替换该处`bot token` token='' chat_id='' url = f'https://api.telegram.org/bot{token}/sendMessage' dataJson={ "chat_id":'chat_id', "text": "XCH到账啦!", } now=datetime.datetime.now() dataJson['text']=text dataJson['chat_id']=chat_id try: r =requests.post(url, data=dataJson,timeout=5) return r.text except requests.exceptions.ConnectionError: msg='报错了,无法访问telegram.' logger.error(f"{msg}") exit(2) except Exception as e: logger.error(f"报错了,报错信息是:{e}") # print('报错了,报错信息是:',e) exit(3) def get_total_assets(url): totalassets_url = url res = requests.get(url=totalassets_url, headers=header) # res=res.text # currency_list=res['data']['list'] ## failed currency_list = json.loads(res.text).get('data').get('list') # print(currency_list) for i in currency_list: if i['name'] == 'CHIA': total_xch = i['total_assets'] total_xch = float(total_xch) break if total_xch < 0.01: msg = (f'提现失败.不够最低提现额度.当前xch资产金额为:{total_xch} xch') logger.error(f"{msg}") send_tg_msg(text=msg) exit(1) return total_xch def get_token(): t1=int(time.time() * 1000) # 此处有坑,需要先请求`/api/security/requestverify`,再获取session requests.get(url=f'https://www.hpool.in/api/security/requestverify?_t={t1}', headers=header) t2=int(time.time() * 1000) res = requests.get(url=f'https://www.hpool.in/api/security/requestsession?_t={t2}', headers=header) session = json.loads(res.text).get('data') return session def get_google_auth_code(path): ''' 使用`oathtool`生成谷歌验证码,脚本需要有执行权限, 脚本内容:`oathtool -b --totp 'key'`. 非最佳方案,注意保护好`key`谨防泄密,造成财产损失. ''' code = subprocess.getoutput(path) # return int(code) print(code) return code def xch_withdraw(url, session, code, amount, address, **kwargs): ''' session:请求session接口的返回, code:谷歌验证码, aomount:剩余全部xch, address:提现钱包地址 提现到指定钱包地址payload: '{"session":"","code":"","type":"chia","address":"","amount":""}' ''' type = 'chia' payload = { "session": f"{session}", "code": f"{code}", "type": "chia", "address": f"{address}", "amount": f"{amount}" } payload = json.dumps(payload) # print(payload) res = requests.post(url=url, headers=header, data=payload) result_code = json.loads(res.text).get('code') print(res.text) if result_code == 200: msg=f'提现成功,本次提现金额为:{amount}xch,请注意查收.' logger.info(f'{msg}') send_tg_msg(text=msg) return result_code else: msg='提现失败,未知错误.' logger.error(f"{msg}") send_tg_msg(text=msg) return None if __name__ == "__main__": # parser = argm(prog='hpool_xch_withdraw',description="hpool xch withdraw helper") # parser.add_argument("-K", "--code", dest='code', type=int,help="Google Authenticator Code.") # parser.add_argument("-P","--percent", dest='withdraw_percent', default=1,help="Withdraw ratio.") # parser.add_argument("-M","--tg",help="Send telegram message.") # args = parser.parse_args() # code = args.code # withdraw_percent = args.withdraw_percent # if len(str(code)) == 6: # remain_xch=get_total_assets('https://www.hpool.in/api/assets/totalassets') # #sign_url=f'https://www.hpool.in/api/assets/totalassets' # # print(sign_url) # t = int(time.time() * 1000) # session=get_token(f'https://www.hpool.in/api/security/requestsession?_t={t}') # ## 防止被劫持,强制写死提现address.也可以通过接口获取 # xch_withdraw(session=session,code=code,amount=remain_xch,address='') # else: # parser.print_help() remain_xch = get_total_assets( 'https://www.hpool.in/api/assets/totalassets') # t = int(time.time() * 1000) session = get_token() code = get_google_auth_code('/home/chaos/lab/scripts/totp.sh') withdraw_url = 'https://www.hpool.in/api/assets/withdraw' ## 防止被劫持,强制写死提现address.也可以通过接口获取 pay_address = '' xch_withdraw(url=withdraw_url, session=session, code=code, amount=remain_xch, address=pay_address)