prompt
large_stringlengths
70
991k
completion
large_stringlengths
0
1.02k
<|file_name|>restor.py<|end_file_name|><|fim▁begin|># Copyright (c) 2014 by Ecreall under licence AGPL terms # available on http://www.gnu.org/licenses/agpl.html # licence: AGPL # author: Amen Souissi import deform from pyramid.view import view_config from dace.processinstance.core import DEFAULTMAPPING_ACTIONS_VIEWS from pontus.default_behavior import Cancel from pontus.form import FormView from pontus.view import BasicView from pontus.view_operation import MultipleView from novaideo.content.processes.reports_management.behaviors import Restor from novaideo.core import SignalableEntity from novaideo import _ class RestorViewStudyRestor(BasicView): title = _('Alert for restoring') name = 'alertforpublication' template = 'novaideo:views/reports_management/templates/alert_restor.pt' def update(self): result = {} values = {'context': self.context} body = self.content(args=values, template=self.template)['body'] item = self.adapt_item(body, self.viewid) result['coordinates'] = {self.coordinates: [item]} return result class RestorFormView(FormView): title = _('Restore') behaviors = [Restor, Cancel] formid = 'formrestor' name = 'formrestor' def before_update(self): self.action = self.request.resource_url( self.context, 'novaideoapi', query={'op': 'update_action_view', 'node_id': Restor.node_definition.id}) self.schema.widget = deform.widget.FormWidget( css_class='deform novaideo-ajax-form') @view_config( name='restor', context=SignalableEntity, renderer='pontus:templates/views_templates/grid.pt', ) class RestorView(MultipleView): title = _('Restore') name = 'restor' behaviors = [Restor] viewid = 'restorentity' template = 'pontus:templates/views_templates/simple_multipleview.pt' views = (RestorViewStudyRestor, RestorFormView) validators = [Restor.get_validator()] <|fim▁hole|><|fim▁end|>
DEFAULTMAPPING_ACTIONS_VIEWS.update( {Restor: RestorView})
<|file_name|>password_test.go<|end_file_name|><|fim▁begin|>package password_test import ( "net/http" "net/http/httptest" "time" "github.com/cloudfoundry/cli/cf/api/apifakes" "github.com/cloudfoundry/cli/cf/net" "github.com/cloudfoundry/cli/cf/terminal/terminalfakes" testconfig "github.com/cloudfoundry/cli/testhelpers/configuration" testnet "github.com/cloudfoundry/cli/testhelpers/net" . "github.com/cloudfoundry/cli/cf/api/password" "github.com/cloudfoundry/cli/cf/trace/tracefakes" . "github.com/cloudfoundry/cli/testhelpers/matchers" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("CloudControllerPasswordRepository", func() { It("updates your password", func() { req := apifakes.NewCloudControllerTestRequest(testnet.TestRequest{ Method: "PUT", Path: "/Users/my-user-guid/password", Matcher: testnet.RequestBodyMatcher(`{"password":"new-password","oldPassword":"old-password"}`), Response: testnet.TestResponse{Status: http.StatusOK}, }) passwordUpdateServer, handler, repo := createPasswordRepo(req) defer passwordUpdateServer.Close() apiErr := repo.UpdatePassword("old-password", "new-password") Expect(handler).To(HaveAllRequestsCalled()) Expect(apiErr).NotTo(HaveOccurred())<|fim▁hole|> }) }) func createPasswordRepo(req testnet.TestRequest) (passwordServer *httptest.Server, handler *testnet.TestHandler, repo Repository) { passwordServer, handler = testnet.NewServer([]testnet.TestRequest{req}) configRepo := testconfig.NewRepositoryWithDefaults() configRepo.SetUaaEndpoint(passwordServer.URL) gateway := net.NewCloudControllerGateway(configRepo, time.Now, new(terminalfakes.FakeUI), new(tracefakes.FakePrinter)) repo = NewCloudControllerRepository(configRepo, gateway) return }<|fim▁end|>
<|file_name|>basic-types.unit.test.js<|end_file_name|><|fim▁begin|>const clone = require('lodash/clone'); const testHelpers = require('@quoin/node-test-helpers'); const BasicTypes = require('./basic-types'); const expect = testHelpers.expect; describe("lib/core/basic-types", () => { it("should export an object", () => { expect(BasicTypes).to.be.an('object'); }); it("should expose known properties", () => { const aClone = clone(BasicTypes); testHelpers.verifyProperties(aClone, 'string', [ 'Boolean', 'Date', 'File',<|fim▁hole|> 'Text' ]); testHelpers.verifyProperties(aClone, 'function', [ 'defaultValue', 'isValid', 'typesCheck' ]); expect(aClone).to.deep.equal({}); }); describe("isValid()", () => { const isValid = BasicTypes.isValid; it("should accept 1 param", () => { expect(isValid).to.have.lengthOf(1); }); it("should recognize an existing type", () => { expect(isValid(BasicTypes.String)).to.be.true(); }); it("should not recognize an invalid type", () => { expect(isValid('foobar')).to.be.false(); }); }); });<|fim▁end|>
'Password', 'Number', 'String',
<|file_name|>schemamigration.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- import sys INSTALLED_APPS = [ 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'mptt', 'cms', 'menus', 'djangocms_inherit', 'south', ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } } TEMPLATE_CONTEXT_PROCESSORS = [ 'django.core.context_processors.auth', 'django.core.context_processors.i18n', 'django.core.context_processors.request', 'django.core.context_processors.media', 'django.core.context_processors.static', 'cms.context_processors.media', 'sekizai.context_processors.sekizai', ] ROOT_URLCONF = 'cms.urls' def schemamigration():<|fim▁hole|> # turn ``schemamigration.py --initial`` into # ``manage.py schemamigration cmsplugin_disqus --initial`` and setup the # enviroment from django.conf import settings from django.core.management import ManagementUtility settings.configure( INSTALLED_APPS=INSTALLED_APPS, ROOT_URLCONF=ROOT_URLCONF, DATABASES=DATABASES, TEMPLATE_CONTEXT_PROCESSORS=TEMPLATE_CONTEXT_PROCESSORS ) argv = list(sys.argv) argv.insert(1, 'schemamigration') argv.insert(2, 'djangocms_inherit') utility = ManagementUtility(argv) utility.execute() if __name__ == "__main__": schemamigration()<|fim▁end|>
<|file_name|>20140912211135_1efacad0fff5_index_for_object_folders.py<|end_file_name|><|fim▁begin|># Copyright (C) 2016 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> <|fim▁hole|> """Index for object_folders Revision ID: 1efacad0fff5 Revises: 4d7ce1eaddf2 Create Date: 2014-09-12 21:11:35.908034 """ # revision identifiers, used by Alembic. revision = '1efacad0fff5' down_revision = '4d7ce1eaddf2' from alembic import op import sqlalchemy as sa def upgrade(): op.create_index('ix_folderable_id_type', 'object_folders', ['folderable_type','folderable_id']) pass def downgrade(): op.drop_index('ix_folderable_id_type', table_name='object_folders') pass<|fim▁end|>
<|file_name|>test_sender.py<|end_file_name|><|fim▁begin|>import socket import sys import time server_add = './bob_system_socket' sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) message = sys.argv[1]+" "+sys.argv[2] if sys.argv[1] == 'set': message+= " "+sys.argv[3] else: message+= " null" try: sock.connect(server_add) except socket.error, msg: print >>sys.stderr, msg<|fim▁hole|> sock.send(message) data = sock.recv(1024) if data: print 'reply from server:', data time.sleep(1) sock.close()<|fim▁end|>
sys.exit(1)
<|file_name|>functions.ts<|end_file_name|><|fim▁begin|>import { TupleType } from './tuples.ts' import { Kind } from './types/kinds.ts' import { Type } from './types/types.ts' import { pairHash } from './utils/hash.ts' import { Value } from './values.ts' export interface FunctionType extends Type { input: TupleType output: Type } /** * A function value consists of a function type and a Javascript function with parameters fitting the function type. */ export interface FunctionValue<R> extends Value { callable: (...args: any) => R lore$type: FunctionType } export const Function = {<|fim▁hole|> }, value<R>(callable: (...args: any) => R, type: FunctionType): FunctionValue<R> { return { callable, lore$type: type } }, call<R>(value: FunctionValue<R>, ...args: any): R { return value.callable(...args) }, }<|fim▁end|>
type(input: TupleType, output: Type): FunctionType { return { kind: Kind.Function, input, output, hash: pairHash(input, output, 0xf4527105) }
<|file_name|>publishconf.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # from __future__ import unicode_literals<|fim▁hole|># explicitly specify it as your config file. import os import sys sys.path.append(os.curdir) from pelicanconf import * SITEURL = 'http://mpdev.mattew.se' RELATIVE_URLS = False FEED_ALL_ATOM = 'feeds/all.atom.xml' CATEGORY_FEED_ATOM = 'feeds/%s.atom.xml' DELETE_OUTPUT_DIRECTORY = False # Following items are often useful when publishing #DISQUS_SITENAME = "" #GOOGLE_ANALYTICS = ""<|fim▁end|>
# This file is only used if you use `make publish` or
<|file_name|>coherence_copy_like_err_tuple.rs<|end_file_name|><|fim▁begin|>// Test that we are able to introduce a negative constraint that // `MyType: !MyTrait` along with other "fundamental" wrappers. // aux-build:coherence_copy_like_lib.rs extern crate coherence_copy_like_lib as lib; struct MyType { x: i32 } trait MyTrait { fn foo() {} } impl<T: lib::MyCopy> MyTrait for T { } // Tuples are not fundamental, therefore this would require that //<|fim▁hole|>// (MyType,): !MyTrait // // which we cannot approve. impl MyTrait for (MyType,) { } //~^ ERROR E0119 fn main() { }<|fim▁end|>
<|file_name|>mqttplugin.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # vim: set encoding=utf-8 tabstop=4 softtabstop=4 shiftwidth=4 expandtab ######################################################################### # Copyright 2019- Martin Sinn m.sinn@gmx.de ######################################################################### # This file is part of SmartHomeNG # # SmartHomeNG is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # SmartHomeNG is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with SmartHomeNG If not, see <http://www.gnu.org/licenses/>. ######################################################################### import threading from lib.module import Modules from lib.model.smartplugin import SmartPlugin from lib.shtime import Shtime class MqttPlugin(SmartPlugin): _item_values = {} # dict of dicts # Initialization of SmartPlugin class called by super().__init__() from the plugin's __init__() method def __init__(self): """ Initialization Routine for the mqtt extension class to SmartPlugin """ SmartPlugin.__init__(self) # get instance of MQTT module try: self.mod_mqtt = Modules.get_instance().get_module('mqtt') # try/except to handle running in a core version that does not support modules except: self.mod_mqtt = None if self.mod_mqtt == None: self.logger.error("Module 'mqtt' not loaded. The plugin is not starting") self._init_complete = False return False self._subscribed_topics_lock = threading.Lock() self._subscribed_topics = {} # subscribed topics (a dict of dicts) self._subscribe_current_number = 0 # current number of the subscription entry self._subscriptions_started = False # get broker configuration (for display in web interface) self.broker_config = self.mod_mqtt.get_broker_config() return True def start_subscriptions(self): """ Start subscription to all topics Should be called from the run method of a plugin """ if self.mod_mqtt: with self._subscribed_topics_lock: for topic in self._subscribed_topics: # start subscription to all items for this topic for item_path in self._subscribed_topics[topic]: self._start_subscription(topic, item_path) self._subscriptions_started = True return def stop_subscriptions(self): """ Stop subscription to all topics Should be called from the stop method of a plugin """ if self.mod_mqtt: with self._subscribed_topics_lock: for topic in self._subscribed_topics: # stop subscription to all items for this topic for item_path in self._subscribed_topics[topic]: current = str(self._subscribed_topics[topic][item_path]['current']) self.logger.info("stop(): Unsubscribing from topic {} for item {}".format(topic, item_path)) self.mod_mqtt.unsubscribe_topic(self.get_shortname() + '-' + current, topic) self._subscriptions_started = False return def _start_subscription(self, topic, item_path): current = str(self._subscribed_topics[topic][item_path]['current']) qos = self._subscribed_topics[topic][item_path].get('qos', None) payload_type = self._subscribed_topics[topic][item_path].get('payload_type', None) callback = self._subscribed_topics[topic][item_path].get('callback', None) bool_values = self._subscribed_topics[topic][item_path].get('bool_values', None) self.logger.info("_start_subscription: Subscribing to topic {}, payload_type '{}' for item {} (callback={})".format(topic, payload_type, item_path, callback)) self.mod_mqtt.subscribe_topic(self.get_shortname() + '-' + current, topic, callback=callback, qos=qos, payload_type=payload_type, bool_values=bool_values) return def add_subscription(self, topic, payload_type, bool_values=None, item=None, callback=None): """ Add mqtt subscription to subscribed_topics list subscribing is done directly, if subscriptions have been started by self.start_subscriptions() :param topic: topic to subscribe to :param payload_type: payload type of the topic (for this subscription to the topic) :param bool_values: bool values (for this subscription to the topic) :param item: item that should receive the payload as value. Used by the standard handler (if no callback function is specified) :param callback: a plugin can provide an own callback function, if special handling of the payload is needed :return: """ with self._subscribed_topics_lock: # test if topic is new if not self._subscribed_topics.get(topic, None): self._subscribed_topics[topic] = {} # add this item to topic if item is None: item_path = '*no_item*' else: item_path = item.path() self._subscribed_topics[topic][item_path] = {} self._subscribe_current_number += 1 self._subscribed_topics[topic][item_path]['current'] = self._subscribe_current_number self._subscribed_topics[topic][item_path]['item'] = item self._subscribed_topics[topic][item_path]['qos'] = None self._subscribed_topics[topic][item_path]['payload_type'] = payload_type if callback: self._subscribed_topics[topic][item_path]['callback'] = callback else: self._subscribed_topics[topic][item_path]['callback'] = self._on_mqtt_message self._subscribed_topics[topic][item_path]['bool_values'] = bool_values if self._subscriptions_started: # directly subscribe to added subscription, if subscribtions are started self._start_subscription(topic, item_path) return def publish_topic(self, topic, payload, item=None, qos=None, retain=False, bool_values=None): """ Publish a topic to mqtt :param topic: topic to publish :param payload: payload to publish :param item: item (if relevant) :param qos: qos for this message (optional) :param retain: retain flag for this message (optional) :param bool_values: bool values (for publishing this topic, optional) :return: """ self.mod_mqtt.publish_topic(self.get_shortname(), topic, payload, qos, retain, bool_values) if item is not None: self.logger.info("publish_topic: Item '{}' -> topic '{}', payload '{}', QoS '{}', retain '{}'".format(item.id(), topic, payload, qos, retain)) # Update dict for periodic updates of the web interface self._update_item_values(item, payload) else: self.logger.info("publish_topic: topic '{}', payload '{}', QoS '{}', retain '{}'".format(topic, payload, qos, retain)) return # ---------------------------------------------------------------------------------------- # methods to handle the broker connection # ---------------------------------------------------------------------------------------- _broker_version = '?' _broker = {} broker_config = {} broker_monitoring = False def get_broker_info(self): if self.mod_mqtt: (self._broker, self.broker_monitoring) = self.mod_mqtt.get_broker_info() def broker_uptime(self): """ Return formatted uptime of broker """ if self.shtime is None: self.shtime = Shtime.get_instance() try: return self.shtime.seconds_to_displaystring(int(self._broker['uptime'])) except Exception as e: return '-' <|fim▁hole|> :return: Bool value True :rtype: bool """ self.logger.warning("'mqtt_init()' method called. it is not used anymore. The Plugin should remove the call to mqtt_init(), use 'super.__init__()' instead") pass return True # ----------------------------------------------------------------------- def _on_mqtt_message(self, topic, payload, qos=None, retain=None): """ Callback function to handle received messages :param topic: :param payload: :param qos: :param retain: """ self.logger.debug("_on_mqtt_message: Received topic '{}', payload '{} (type {})', QoS '{}', retain '{}' ".format(topic, payload, type(payload), qos, retain)) # get item for topic if self._subscribed_topics.get(topic, None): # at least 1 item has subscribed to this topic for item_path in self._subscribed_topics[topic]: item = self._subscribed_topics[topic][item_path].get('item', None) if item != None: try: log_info = (float(payload) != float(item())) except: log_info = (str(payload) != str(item())) if log_info: self.logger.info("_on_mqtt_message: Received topic '{}', payload '{}' (type {}), QoS '{}', retain '{}' for item '{}'".format( topic, payload, item.type(), qos, retain, item.id() )) else: self.logger.debug("_on_mqtt_message: Received topic '{}', payload '{}' (type {}), QoS '{}', retain '{}' for item '{}'".format(topic, payload, item.type(), qos, retain, item.id())) item(payload, self.get_shortname()) # Update dict for periodic updates of the web interface self._update_item_values(item, payload) else: self.logger.error("_on_mqtt_message: No definition found for subscribed topic '{}'".format(topic)) return def _update_item_values(self, item, payload): """ Update dict for periodic updates of the web interface :param item: :param payload: """ if not self._item_values.get(item.id()): self._item_values[item.id()] = {} if isinstance(payload, bool): self._item_values[item.id()]['value'] = str(payload) else: self._item_values[item.id()]['value'] = payload self._item_values[item.id()]['last_update'] = item.last_update().strftime('%d.%m.%Y %H:%M:%S') self._item_values[item.id()]['last_change'] = item.last_change().strftime('%d.%m.%Y %H:%M:%S') return<|fim▁end|>
def mqtt_init(self): """ Dummy method - should not be called any more
<|file_name|>conversion.go<|end_file_name|><|fim▁begin|>/* Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package runtime defines conversions between generic types and structs to map query strings // to struct objects. package runtime import ( "fmt" "reflect" "strconv" "strings" "k8s.io/apimachinery/pkg/conversion" ) // DefaultMetaV1FieldSelectorConversion auto-accepts metav1 values for name and namespace. // A cluster scoped resource specifying namespace empty works fine and specifying a particular // namespace will return no results, as expected. func DefaultMetaV1FieldSelectorConversion(label, value string) (string, string, error) { switch label { case "metadata.name": return label, value, nil case "metadata.namespace": return label, value, nil default: return "", "", fmt.Errorf("%q is not a known field selector: only %q, %q", label, "metadata.name", "metadata.namespace") } } // JSONKeyMapper uses the struct tags on a conversion to determine the key value for // the other side. Use when mapping from a map[string]* to a struct or vice versa. func JSONKeyMapper(key string, sourceTag, destTag reflect.StructTag) (string, string) { if s := destTag.Get("json"); len(s) > 0 { return strings.SplitN(s, ",", 2)[0], key } if s := sourceTag.Get("json"); len(s) > 0 { return key, strings.SplitN(s, ",", 2)[0] } return key, key } // DefaultStringConversions are helpers for converting []string and string to real values. var DefaultStringConversions = []interface{}{ Convert_Slice_string_To_string, Convert_Slice_string_To_int, Convert_Slice_string_To_bool, Convert_Slice_string_To_int64, } func Convert_Slice_string_To_string(in *[]string, out *string, s conversion.Scope) error { if len(*in) == 0 { *out = "" return nil } *out = (*in)[0] return nil } func Convert_Slice_string_To_int(in *[]string, out *int, s conversion.Scope) error { if len(*in) == 0 { *out = 0 return nil } str := (*in)[0] i, err := strconv.Atoi(str) if err != nil { return err } *out = i return nil } // Convert_Slice_string_To_bool will convert a string parameter to boolean. // Only the absence of a value (i.e. zero-length slice), a value of "false", or a<|fim▁hole|>// value of "0" resolve to false. // Any other value (including empty string) resolves to true. func Convert_Slice_string_To_bool(in *[]string, out *bool, s conversion.Scope) error { if len(*in) == 0 { *out = false return nil } switch { case (*in)[0] == "0", strings.EqualFold((*in)[0], "false"): *out = false default: *out = true } return nil } func string_to_int64(in string) (int64, error) { return strconv.ParseInt(in, 10, 64) } func Convert_string_To_int64(in *string, out *int64, s conversion.Scope) error { if in == nil { *out = 0 return nil } i, err := string_to_int64(*in) if err != nil { return err } *out = i return nil } func Convert_Slice_string_To_int64(in *[]string, out *int64, s conversion.Scope) error { if len(*in) == 0 { *out = 0 return nil } i, err := string_to_int64((*in)[0]) if err != nil { return err } *out = i return nil } func Convert_string_To_Pointer_int64(in *string, out **int64, s conversion.Scope) error { if in == nil { *out = nil return nil } i, err := string_to_int64(*in) if err != nil { return err } *out = &i return nil } func Convert_Slice_string_To_Pointer_int64(in *[]string, out **int64, s conversion.Scope) error { if len(*in) == 0 { *out = nil return nil } i, err := string_to_int64((*in)[0]) if err != nil { return err } *out = &i return nil }<|fim▁end|>
<|file_name|>constants.py<|end_file_name|><|fim▁begin|># -*- coding: UTF-8 -*- ''' virtualbox_const_support.py Constants for VirtualBox. ''' __author__ = "Karol Będkowski <karol.bedkowski@gmail.com>" __version__ = '0.3' # virtual machine states VM_STATE_POWEROFF = 0 VM_STATE_POWERON = 1 VM_STATE_PAUSED = 2<|fim▁hole|> # virtual machine actions VM_START_NORMAL = 1 VM_START_HEADLESS = 2 VM_PAUSE = 3 VM_POWEROFF = 4 VM_ACPI_POWEROFF = 5 VM_REBOOT = 6 VM_RESUME = 7 VM_SAVE = 8<|fim▁end|>
<|file_name|>test_ssd1306.py<|end_file_name|><|fim▁begin|>import sys sys.path.append("../../") from unittest.mock import patch, MagicMock MockRPi = MagicMock() MockSpidev = MagicMock() modules = { "RPi": MockRPi, "RPi.GPIO": MockRPi.GPIO, "spidev": MockSpidev } <|fim▁hole|> from gfxlcd.driver.ssd1306.spi import SPI from gfxlcd.driver.ssd1306.ssd1306 import SSD1306 class TestNJU6450(object): def test_initialize(self): SSD1306(128, 64, SPI())<|fim▁end|>
patcher = patch.dict("sys.modules", modules) patcher.start()
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|>from osweb.projects.ManageProject import ManageProject from osweb.projects.projects_data import ProjectsData<|fim▁end|>
<|file_name|>lexical-scope-in-if.rs<|end_file_name|><|fim▁begin|>// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // xfail-win32 // compile-flags:-Z extra-debug-info // debugger:rbreak zzz // debugger:run // BEFORE if // debugger:finish // debugger:print x // check:$1 = 999 // debugger:print y // check:$2 = -1 // debugger:continue // AT BEGINNING of 'then' block // debugger:finish // debugger:print x // check:$3 = 999 // debugger:print y // check:$4 = -1 // debugger:continue // AFTER 1st redeclaration of 'x' // debugger:finish // debugger:print x // check:$5 = 1001 // debugger:print y // check:$6 = -1 // debugger:continue // AFTER 2st redeclaration of 'x' // debugger:finish // debugger:print x // check:$7 = 1002 // debugger:print y // check:$8 = 1003 // debugger:continue // AFTER 1st if expression // debugger:finish // debugger:print x // check:$9 = 999 // debugger:print y // check:$10 = -1 // debugger:continue // BEGINNING of else branch // debugger:finish // debugger:print x // check:$11 = 999 // debugger:print y // check:$12 = -1 // debugger:continue // BEGINNING of else branch // debugger:finish // debugger:print x // check:$13 = 1004 // debugger:print y // check:$14 = 1005 // debugger:continue // BEGINNING of else branch // debugger:finish // debugger:print x // check:$15 = 999 // debugger:print y // check:$16 = -1 // debugger:continue fn main() { let x = 999; let y = -1;<|fim▁hole|> zzz(); sentinel(); if x < 1000 { zzz(); sentinel(); let x = 1001; zzz(); sentinel(); let x = 1002; let y = 1003; zzz(); sentinel(); } else { unreachable!(); } zzz(); sentinel(); if x > 1000 { unreachable!(); } else { zzz(); sentinel(); let x = 1004; let y = 1005; zzz(); sentinel(); } zzz(); sentinel(); } fn zzz() {()} fn sentinel() {()}<|fim▁end|>
<|file_name|>macros.rs<|end_file_name|><|fim▁begin|><|fim▁hole|> () => (3); } /*macro_rules! BOARD_MAX { () => { BOARD_SIZE!()-1 }; }*/<|fim▁end|>
#[macro_export] macro_rules! BOARD_SIZE {
<|file_name|>jquery.tablesorter.widgets.js<|end_file_name|><|fim▁begin|>/*! tableSorter (FORK) 2.16+ widgets - updated 12/22/2014 (v2.18.4) * * Column Styles * Column Filters * Column Resizing * Sticky Header * UI Theme (generalized) * Save Sort * [ "columns", "filter", "resizable", "stickyHeaders", "uitheme", "saveSort" ] */ /*jshint browser:true, jquery:true, unused:false, loopfunc:true */ /*global jQuery: false, localStorage: false */ ;(function ($, window) { "use strict"; var ts = $.tablesorter = $.tablesorter || {}; ts.themes = { "bootstrap" : { table : 'table table-bordered table-striped', caption : 'caption', header : 'bootstrap-header', // give the header a gradient background footerRow : '', footerCells: '', icons : '', // add "icon-white" to make them white; this icon class is added to the <i> in the header sortNone : 'bootstrap-icon-unsorted', sortAsc : 'icon-chevron-up glyphicon glyphicon-chevron-up', sortDesc : 'icon-chevron-down glyphicon glyphicon-chevron-down', active : '', // applied when column is sorted hover : '', // use custom css here - bootstrap class may not override it filterRow : '', // filter row class even : '', // even row zebra striping odd : '' // odd row zebra striping }, "jui" : { table : 'ui-widget ui-widget-content ui-corner-all', // table classes caption : 'ui-widget-content', header : 'ui-widget-header ui-corner-all ui-state-default', // header classes footerRow : '', footerCells: '', icons : 'ui-icon', // icon class added to the <i> in the header sortNone : 'ui-icon-carat-2-n-s', sortAsc : 'ui-icon-carat-1-n', sortDesc : 'ui-icon-carat-1-s', active : 'ui-state-active', // applied when column is sorted hover : 'ui-state-hover', // hover class filterRow : '', even : 'ui-widget-content', // even row zebra striping odd : 'ui-state-default' // odd row zebra striping } }; $.extend(ts.css, { filterRow : 'tablesorter-filter-row', // filter filter : 'tablesorter-filter', wrapper : 'tablesorter-wrapper', // ui theme & resizable resizer : 'tablesorter-resizer', // resizable sticky : 'tablesorter-stickyHeader', // stickyHeader stickyVis : 'tablesorter-sticky-visible', stickyWrap: 'tablesorter-sticky-wrapper' }); // *** Store data in local storage, with a cookie fallback *** /* IE7 needs JSON library for JSON.stringify - (http://caniuse.com/#search=json) if you need it, then include https://github.com/douglascrockford/JSON-js $.parseJSON is not available is jQuery versions older than 1.4.1, using older versions will only allow storing information for one page at a time // *** Save data (JSON format only) *** // val must be valid JSON... use http://jsonlint.com/ to ensure it is valid var val = { "mywidget" : "data1" }; // valid JSON uses double quotes // $.tablesorter.storage(table, key, val); $.tablesorter.storage(table, 'tablesorter-mywidget', val); // *** Get data: $.tablesorter.storage(table, key); *** v = $.tablesorter.storage(table, 'tablesorter-mywidget'); // val may be empty, so also check for your data val = (v && v.hasOwnProperty('mywidget')) ? v.mywidget : ''; alert(val); // "data1" if saved, or "" if not */ ts.storage = function(table, key, value, options) { table = $(table)[0]; var cookieIndex, cookies, date, hasLocalStorage = false, values = {}, c = table.config, $table = $(table), id = options && options.id || $table.attr(options && options.group || 'data-table-group') || table.id || $('.tablesorter').index( $table ), url = options && options.url || $table.attr(options && options.page || 'data-table-page') || c && c.fixedUrl || window.location.pathname; // https://gist.github.com/paulirish/5558557 if ("localStorage" in window) { try { window.localStorage.setItem('_tmptest', 'temp'); hasLocalStorage = true; window.localStorage.removeItem('_tmptest'); } catch(error) {} } // *** get value *** if ($.parseJSON) { if (hasLocalStorage) { values = $.parseJSON(localStorage[key] || '{}'); } else { // old browser, using cookies cookies = document.cookie.split(/[;\s|=]/); // add one to get from the key to the value cookieIndex = $.inArray(key, cookies) + 1; values = (cookieIndex !== 0) ? $.parseJSON(cookies[cookieIndex] || '{}') : {}; } } // allow value to be an empty string too if ((value || value === '') && window.JSON && JSON.hasOwnProperty('stringify')) { // add unique identifiers = url pathname > table ID/index on page > data if (!values[url]) { values[url] = {}; } values[url][id] = value; // *** set value *** if (hasLocalStorage) { localStorage[key] = JSON.stringify(values); } else { date = new Date(); date.setTime(date.getTime() + (31536e+6)); // 365 days document.cookie = key + '=' + (JSON.stringify(values)).replace(/\"/g,'\"') + '; expires=' + date.toGMTString() + '; path=/'; } } else { return values && values[url] ? values[url][id] : ''; } }; // Add a resize event to table headers // ************************** ts.addHeaderResizeEvent = function(table, disable, settings) { table = $(table)[0]; // make sure we're usig a dom element var headers, defaults = { timer : 250 }, options = $.extend({}, defaults, settings), c = table.config, wo = c.widgetOptions, checkSizes = function(triggerEvent) { wo.resize_flag = true; headers = []; c.$headers.each(function() { var $header = $(this), sizes = $header.data('savedSizes') || [0,0], // fixes #394 width = this.offsetWidth, height = this.offsetHeight; if (width !== sizes[0] || height !== sizes[1]) { $header.data('savedSizes', [ width, height ]); headers.push(this); } }); if (headers.length && triggerEvent !== false) { c.$table.trigger('resize', [ headers ]); } wo.resize_flag = false; }; checkSizes(false); clearInterval(wo.resize_timer); if (disable) { wo.resize_flag = false; return false; } wo.resize_timer = setInterval(function() { if (wo.resize_flag) { return; } checkSizes(); }, options.timer); }; // Widget: General UI theme // "uitheme" option in "widgetOptions" // ************************** ts.addWidget({ id: "uitheme", priority: 10, format: function(table, c, wo) { var i, time, classes, $header, $icon, $tfoot, $h, oldtheme, oldremove, themesAll = ts.themes, $table = c.$table, $headers = c.$headers, theme = c.theme || 'jui', themes = themesAll[theme] || themesAll.jui, remove = [ themes.sortNone, themes.sortDesc, themes.sortAsc, themes.active ].join( ' ' ); if (c.debug) { time = new Date(); } // initialization code - run once if (!$table.hasClass('tablesorter-' + theme) || c.theme !== c.appliedTheme || !table.hasInitialized) { oldtheme = themes[c.appliedTheme] || {}; oldremove = oldtheme ? [ oldtheme.sortNone, oldtheme.sortDesc, oldtheme.sortAsc, oldtheme.active ].join( ' ' ) : ''; if (oldtheme) { wo.zebra[0] = wo.zebra[0].replace(' ' + oldtheme.even, ''); wo.zebra[1] = wo.zebra[1].replace(' ' + oldtheme.odd, ''); } // update zebra stripes if (themes.even !== '') { wo.zebra[0] += ' ' + themes.even; } if (themes.odd !== '') { wo.zebra[1] += ' ' + themes.odd; } // add caption style $table.children('caption').removeClass(oldtheme.caption).addClass(themes.caption); // add table/footer class names $tfoot = $table // remove other selected themes .removeClass( c.appliedTheme ? 'tablesorter-' + ( c.appliedTheme || '' ) : '' ) .addClass('tablesorter-' + theme + ' ' + themes.table) // add theme widget class name .children('tfoot'); if ($tfoot.length) { $tfoot // if oldtheme.footerRow or oldtheme.footerCells are undefined, all class names are removed .children('tr').removeClass(oldtheme.footerRow || '').addClass(themes.footerRow) .children('th, td').removeClass(oldtheme.footerCells || '').addClass(themes.footerCells); } // update header classes $headers .add(c.$extraHeaders) .removeClass(oldtheme.header + ' ' + oldtheme.hover + ' ' + oldremove) .addClass(themes.header) .not('.sorter-false') .bind('mouseenter.tsuitheme mouseleave.tsuitheme', function(event) { // toggleClass with switch added in jQuery 1.3 $(this)[ event.type === 'mouseenter' ? 'addClass' : 'removeClass' ](themes.hover); }); if (!$headers.find('.' + ts.css.wrapper).length) { // Firefox needs this inner div to position the resizer correctly $headers.wrapInner('<div class="' + ts.css.wrapper + '" style="position:relative;height:100%;width:100%"></div>'); } if (c.cssIcon) { // if c.cssIcon is '', then no <i> is added to the header $headers.find('.' + ts.css.icon).removeClass(oldtheme.icons + ' ' + oldremove).addClass(themes.icons); } if ($table.hasClass('hasFilters')) { $table.children('thead').children('.' + ts.css.filterRow).removeClass(oldtheme.filterRow).addClass(themes.filterRow); } c.appliedTheme = c.theme; } for (i = 0; i < c.columns; i++) { $header = c.$headers.add(c.$extraHeaders).not('.sorter-false').filter('[data-column="' + i + '"]'); $icon = (ts.css.icon) ? $header.find('.' + ts.css.icon) : $header; $h = $headers.not('.sorter-false').filter('[data-column="' + i + '"]:last'); if ($h.length) { if ($h[0].sortDisabled) { // no sort arrows for disabled columns! $header.removeClass(remove); $icon.removeClass(remove + ' ' + themes.icons); } else { classes = ($header.hasClass(ts.css.sortAsc)) ? themes.sortAsc : ($header.hasClass(ts.css.sortDesc)) ? themes.sortDesc : $header.hasClass(ts.css.header) ? themes.sortNone : ''; $header[classes === themes.sortNone ? 'removeClass' : 'addClass'](themes.active); $icon.removeClass(remove).addClass(classes); } } } if (c.debug) { ts.benchmark("Applying " + theme + " theme", time); } }, remove: function(table, c) { var $table = c.$table, theme = c.theme || 'jui', themes = ts.themes[ theme ] || ts.themes.jui, $headers = $table.children('thead').children(), remove = themes.sortNone + ' ' + themes.sortDesc + ' ' + themes.sortAsc; $table .removeClass('tablesorter-' + theme + ' ' + themes.table) .find(ts.css.header).removeClass(themes.header); $headers .unbind('mouseenter.tsuitheme mouseleave.tsuitheme') // remove hover .removeClass(themes.hover + ' ' + remove + ' ' + themes.active) .find('.' + ts.css.filterRow) .removeClass(themes.filterRow); $headers.find('.' + ts.css.icon).removeClass(themes.icons); } }); // Widget: Column styles // "columns", "columns_thead" (true) and // "columns_tfoot" (true) options in "widgetOptions" // ************************** ts.addWidget({ id: "columns", priority: 30, options : { columns : [ "primary", "secondary", "tertiary" ] }, format: function(table, c, wo) { var $tbody, tbodyIndex, $rows, rows, $row, $cells, remove, indx, $table = c.$table, $tbodies = c.$tbodies, sortList = c.sortList, len = sortList.length, // removed c.widgetColumns support css = wo && wo.columns || [ "primary", "secondary", "tertiary" ], last = css.length - 1; remove = css.join(' '); // check if there is a sort (on initialization there may not be one) for (tbodyIndex = 0; tbodyIndex < $tbodies.length; tbodyIndex++ ) { $tbody = ts.processTbody(table, $tbodies.eq(tbodyIndex), true); // detach tbody $rows = $tbody.children('tr'); // loop through the visible rows $rows.each(function() { $row = $(this); if (this.style.display !== 'none') { // remove all columns class names $cells = $row.children().removeClass(remove); // add appropriate column class names if (sortList && sortList[0]) { // primary sort column class $cells.eq(sortList[0][0]).addClass(css[0]); if (len > 1) { for (indx = 1; indx < len; indx++) { // secondary, tertiary, etc sort column classes $cells.eq(sortList[indx][0]).addClass( css[indx] || css[last] ); } } } } }); ts.processTbody(table, $tbody, false); } // add classes to thead and tfoot rows = wo.columns_thead !== false ? ['thead tr'] : []; if (wo.columns_tfoot !== false) { rows.push('tfoot tr'); } if (rows.length) { $rows = $table.find( rows.join(',') ).children().removeClass(remove); if (len) { for (indx = 0; indx < len; indx++) { // add primary. secondary, tertiary, etc sort column classes $rows.filter('[data-column="' + sortList[indx][0] + '"]').addClass(css[indx] || css[last]); } } } }, remove: function(table, c, wo) { var tbodyIndex, $tbody, $tbodies = c.$tbodies, remove = (wo.columns || [ "primary", "secondary", "tertiary" ]).join(' '); c.$headers.removeClass(remove); c.$table.children('tfoot').children('tr').children('th, td').removeClass(remove); for (tbodyIndex = 0; tbodyIndex < $tbodies.length; tbodyIndex++ ) { $tbody = ts.processTbody(table, $tbodies.eq(tbodyIndex), true); // remove tbody $tbody.children('tr').each(function() { $(this).children().removeClass(remove); }); ts.processTbody(table, $tbody, false); // restore tbody } } }); // Widget: filter // ************************** ts.addWidget({ id: "filter", priority: 50, options : { filter_childRows : false, // if true, filter includes child row content in the search filter_columnFilters : true, // if true, a filter will be added to the top of each table column filter_cellFilter : '', // css class name added to the filter cell (string or array) filter_cssFilter : '', // css class name added to the filter row & each input in the row (tablesorter-filter is ALWAYS added) filter_defaultFilter : {}, // add a default column filter type "~{query}" to make fuzzy searches default; "{q1} AND {q2}" to make all searches use a logical AND. filter_excludeFilter : {}, // filters to exclude, per column filter_external : '', // jQuery selector string (or jQuery object) of external filters filter_filteredRow : 'filtered', // class added to filtered rows; needed by pager plugin filter_formatter : null, // add custom filter elements to the filter row filter_functions : null, // add custom filter functions using this option filter_hideEmpty : true, // hide filter row when table is empty filter_hideFilters : false, // collapse filter row when mouse leaves the area filter_ignoreCase : true, // if true, make all searches case-insensitive filter_liveSearch : true, // if true, search column content while the user types (with a delay) filter_onlyAvail : 'filter-onlyAvail', // a header with a select dropdown & this class name will only show available (visible) options within the drop down filter_placeholder : { search : '', select : '' }, // default placeholder text (overridden by any header "data-placeholder" setting) filter_reset : null, // jQuery selector string of an element used to reset the filters filter_saveFilters : false, // Use the $.tablesorter.storage utility to save the most recent filters filter_searchDelay : 300, // typing delay in milliseconds before starting a search filter_searchFiltered: true, // allow searching through already filtered rows in special circumstances; will speed up searching in large tables if true filter_selectSource : null, // include a function to return an array of values to be added to the column filter select filter_startsWith : false, // if true, filter start from the beginning of the cell contents filter_useParsedData : false, // filter all data using parsed content filter_serversideFiltering : false, // if true, server-side filtering should be performed because client-side filtering will be disabled, but the ui and events will still be used. filter_defaultAttrib : 'data-value', // data attribute in the header cell that contains the default filter value filter_selectSourceSeparator : '|' // filter_selectSource array text left of the separator is added to the option value, right into the option text }, format: function(table, c, wo) { if (!c.$table.hasClass('hasFilters')) { ts.filter.init(table, c, wo); } }, remove: function(table, c, wo) { var tbodyIndex, $tbody, $table = c.$table, $tbodies = c.$tbodies; $table .removeClass('hasFilters') // add .tsfilter namespace to all BUT search .unbind('addRows updateCell update updateRows updateComplete appendCache filterReset filterEnd search '.split(' ').join(c.namespace + 'filter ')) .find('.' + ts.css.filterRow).remove(); for (tbodyIndex = 0; tbodyIndex < $tbodies.length; tbodyIndex++ ) { $tbody = ts.processTbody(table, $tbodies.eq(tbodyIndex), true); // remove tbody $tbody.children().removeClass(wo.filter_filteredRow).show(); ts.processTbody(table, $tbody, false); // restore tbody } if (wo.filter_reset) { $(document).undelegate(wo.filter_reset, 'click.tsfilter'); } } }); ts.filter = { // regex used in filter "check" functions - not for general use and not documented regex: { regex : /^\/((?:\\\/|[^\/])+)\/([mig]{0,3})?$/, // regex to test for regex child : /tablesorter-childRow/, // child row class name; this gets updated in the script filtered : /filtered/, // filtered (hidden) row class name; updated in the script type : /undefined|number/, // check type exact : /(^[\"\'=]+)|([\"\'=]+$)/g, // exact match (allow '==') nondigit : /[^\w,. \-()]/g, // replace non-digits (from digit & currency parser) operators : /[<>=]/g, // replace operators query : '(q|query)' // replace filter queries }, // function( c, data ) { } // c = table.config // data.filter = array of filter input values; // data.iFilter = same array, except lowercase (if wo.filter_ignoreCase is true) // data.exact = table cell text (or parsed data if column parser enabled) // data.iExact = same as data.exact, except lowercase (if wo.filter_ignoreCase is true) // data.cache = table cell text from cache, so it has been parsed (& in all lower case if config.ignoreCase is true) // data.index = column index; table = table element (DOM) // data.parsed = array (by column) of boolean values (from filter_useParsedData or "filter-parsed" class) types: { // Look for regex regex: function( c, data ) { if ( ts.filter.regex.regex.test(data.iFilter) ) { var matches, regex = ts.filter.regex.regex.exec(data.iFilter); try { matches = new RegExp(regex[1], regex[2]).test( data.iExact ); } catch (error) { matches = false; } return matches; } return null; }, // Look for operators >, >=, < or <= operators: function( c, data ) { if ( /^[<>]=?/.test(data.iFilter) ) { var cachedValue, result, table = c.table, index = data.index, parsed = data.parsed[index], query = ts.formatFloat( data.iFilter.replace(ts.filter.regex.operators, ''), table ), parser = c.parsers[index], savedSearch = query; // parse filter value in case we're comparing numbers (dates) if (parsed || parser.type === 'numeric') { result = ts.filter.parseFilter(c, $.trim('' + data.iFilter.replace(ts.filter.regex.operators, '')), index, parsed, true); query = ( typeof result === "number" && result !== '' && !isNaN(result) ) ? result : query; } // iExact may be numeric - see issue #149; // check if cached is defined, because sometimes j goes out of range? (numeric columns) cachedValue = ( parsed || parser.type === 'numeric' ) && !isNaN(query) && typeof data.cache !== 'undefined' ? data.cache : isNaN(data.iExact) ? ts.formatFloat( data.iExact.replace(ts.filter.regex.nondigit, ''), table) : ts.formatFloat( data.iExact, table ); if ( />/.test(data.iFilter) ) { result = />=/.test(data.iFilter) ? cachedValue >= query : cachedValue > query; } if ( /</.test(data.iFilter) ) { result = /<=/.test(data.iFilter) ? cachedValue <= query : cachedValue < query; } // keep showing all rows if nothing follows the operator if ( !result && savedSearch === '' ) { result = true; } return result; } return null; }, // Look for a not match notMatch: function( c, data ) { if ( /^\!/.test(data.iFilter) ) { var indx, filter = ts.filter.parseFilter(c, data.iFilter.replace('!', ''), data.index, data.parsed[data.index]); if (ts.filter.regex.exact.test(filter)) { // look for exact not matches - see #628 filter = filter.replace(ts.filter.regex.exact, ''); return filter === '' ? true : $.trim(filter) !== data.iExact; } else { indx = data.iExact.search( $.trim(filter) );<|fim▁hole|> } } return null; }, // Look for quotes or equals to get an exact match; ignore type since iExact could be numeric exact: function( c, data ) { /*jshint eqeqeq:false */ if (ts.filter.regex.exact.test(data.iFilter)) { var filter = ts.filter.parseFilter(c, data.iFilter.replace(ts.filter.regex.exact, ''), data.index, data.parsed[data.index]); return data.anyMatch ? $.inArray(filter, data.rowArray) >= 0 : filter == data.iExact; } return null; }, // Look for an AND or && operator (logical and) and : function( c, data ) { if ( ts.filter.regex.andTest.test(data.filter) ) { var index = data.index, parsed = data.parsed[index], query = data.iFilter.split( ts.filter.regex.andSplit ), result = data.iExact.search( $.trim( ts.filter.parseFilter(c, query[0], index, parsed) ) ) >= 0, indx = query.length - 1; while (result && indx) { result = result && data.iExact.search( $.trim( ts.filter.parseFilter(c, query[indx], index, parsed) ) ) >= 0; indx--; } return result; } return null; }, // Look for a range (using " to " or " - ") - see issue #166; thanks matzhu! range : function( c, data ) { if ( ts.filter.regex.toTest.test(data.iFilter) ) { var result, tmp, table = c.table, index = data.index, parsed = data.parsed[index], // make sure the dash is for a range and not indicating a negative number query = data.iFilter.split( ts.filter.regex.toSplit ), range1 = ts.formatFloat( ts.filter.parseFilter(c, query[0].replace(ts.filter.regex.nondigit, ''), index, parsed), table ), range2 = ts.formatFloat( ts.filter.parseFilter(c, query[1].replace(ts.filter.regex.nondigit, ''), index, parsed), table ); // parse filter value in case we're comparing numbers (dates) if (parsed || c.parsers[index].type === 'numeric') { result = c.parsers[index].format('' + query[0], table, c.$headers.eq(index), index); range1 = (result !== '' && !isNaN(result)) ? result : range1; result = c.parsers[index].format('' + query[1], table, c.$headers.eq(index), index); range2 = (result !== '' && !isNaN(result)) ? result : range2; } result = ( parsed || c.parsers[index].type === 'numeric' ) && !isNaN(range1) && !isNaN(range2) ? data.cache : isNaN(data.iExact) ? ts.formatFloat( data.iExact.replace(ts.filter.regex.nondigit, ''), table) : ts.formatFloat( data.iExact, table ); if (range1 > range2) { tmp = range1; range1 = range2; range2 = tmp; } // swap return (result >= range1 && result <= range2) || (range1 === '' || range2 === ''); } return null; }, // Look for wild card: ? = single, * = multiple, or | = logical OR wild : function( c, data ) { if ( /[\?\*\|]/.test(data.iFilter) || ts.filter.regex.orReplace.test(data.filter) ) { var index = data.index, parsed = data.parsed[index], query = ts.filter.parseFilter(c, data.iFilter.replace(ts.filter.regex.orReplace, "|"), index, parsed); // look for an exact match with the "or" unless the "filter-match" class is found if (!c.$headers.filter('[data-column="' + index + '"]:last').hasClass('filter-match') && /\|/.test(query)) { // show all results while using filter match. Fixes #727 if (query[ query.length - 1 ] === '|') { query += '*'; } query = data.anyMatch && $.isArray(data.rowArray) ? '(' + query + ')' : '^(' + query + ')$'; } // parsing the filter may not work properly when using wildcards =/ return new RegExp( query.replace(/\?/g, '\\S{1}').replace(/\*/g, '\\S*') ).test(data.iExact); } return null; }, // fuzzy text search; modified from https://github.com/mattyork/fuzzy (MIT license) fuzzy: function( c, data ) { if ( /^~/.test(data.iFilter) ) { var indx, patternIndx = 0, len = data.iExact.length, pattern = ts.filter.parseFilter(c, data.iFilter.slice(1), data.index, data.parsed[data.index]); for (indx = 0; indx < len; indx++) { if (data.iExact[indx] === pattern[patternIndx]) { patternIndx += 1; } } if (patternIndx === pattern.length) { return true; } return false; } return null; } }, init: function(table, c, wo) { // filter language options ts.language = $.extend(true, {}, { to : 'to', or : 'or', and : 'and' }, ts.language); var options, string, txt, $header, column, filters, val, fxn, noSelect, regex = ts.filter.regex; c.$table.addClass('hasFilters'); // define timers so using clearTimeout won't cause an undefined error wo.searchTimer = null; wo.filter_initTimer = null; wo.filter_formatterCount = 0; wo.filter_formatterInit = []; wo.filter_anyColumnSelector = '[data-column="all"],[data-column="any"]'; wo.filter_multipleColumnSelector = '[data-column*="-"],[data-column*=","]'; txt = '\\{' + ts.filter.regex.query + '\\}'; $.extend( regex, { child : new RegExp(c.cssChildRow), filtered : new RegExp(wo.filter_filteredRow), alreadyFiltered : new RegExp('(\\s+(' + ts.language.or + '|-|' + ts.language.to + ')\\s+)', 'i'), toTest : new RegExp('\\s+(-|' + ts.language.to + ')\\s+', 'i'), toSplit : new RegExp('(?:\\s+(?:-|' + ts.language.to + ')\\s+)' ,'gi'), andTest : new RegExp('\\s+(' + ts.language.and + '|&&)\\s+', 'i'), andSplit : new RegExp('(?:\\s+(?:' + ts.language.and + '|&&)\\s+)', 'gi'), orReplace : new RegExp('\\s+(' + ts.language.or + ')\\s+', 'gi'), iQuery : new RegExp(txt, 'i'), igQuery : new RegExp(txt, 'ig') }); // don't build filter row if columnFilters is false or all columns are set to "filter-false" - issue #156 if (wo.filter_columnFilters !== false && c.$headers.filter('.filter-false, .parser-false').length !== c.$headers.length) { // build filter row ts.filter.buildRow(table, c, wo); } c.$table.bind('addRows updateCell update updateRows updateComplete appendCache filterReset filterEnd search '.split(' ').join(c.namespace + 'filter '), function(event, filter) { c.$table.find('.' + ts.css.filterRow).toggle( !(wo.filter_hideEmpty && $.isEmptyObject(c.cache) && !(c.delayInit && event.type === 'appendCache')) ); // fixes #450 if ( !/(search|filter)/.test(event.type) ) { event.stopPropagation(); ts.filter.buildDefault(table, true); } if (event.type === 'filterReset') { c.$table.find('.' + ts.css.filter).add(wo.filter_$externalFilters).val(''); ts.filter.searching(table, []); } else if (event.type === 'filterEnd') { ts.filter.buildDefault(table, true); } else { // send false argument to force a new search; otherwise if the filter hasn't changed, it will return filter = event.type === 'search' ? filter : event.type === 'updateComplete' ? c.$table.data('lastSearch') : ''; if (/(update|add)/.test(event.type) && event.type !== "updateComplete") { // force a new search since content has changed c.lastCombinedFilter = null; c.lastSearch = []; } // pass true (skipFirst) to prevent the tablesorter.setFilters function from skipping the first input // ensures all inputs are updated when a search is triggered on the table $('table').trigger('search', [...]); ts.filter.searching(table, filter, true); } return false; }); // reset button/link if (wo.filter_reset) { if (wo.filter_reset instanceof $) { // reset contains a jQuery object, bind to it wo.filter_reset.click(function(){ c.$table.trigger('filterReset'); }); } else if ($(wo.filter_reset).length) { // reset is a jQuery selector, use event delegation $(document) .undelegate(wo.filter_reset, 'click.tsfilter') .delegate(wo.filter_reset, 'click.tsfilter', function() { // trigger a reset event, so other functions (filter_formatter) know when to reset c.$table.trigger('filterReset'); }); } } if (wo.filter_functions) { for (column = 0; column < c.columns; column++) { fxn = ts.getColumnData( table, wo.filter_functions, column ); if (fxn) { // remove "filter-select" from header otherwise the options added here are replaced with all options $header = c.$headers.filter('[data-column="' + column + '"]:last').removeClass('filter-select'); // don't build select if "filter-false" or "parser-false" set noSelect = !($header.hasClass('filter-false') || $header.hasClass('parser-false')); options = ''; if ( fxn === true && noSelect ) { ts.filter.buildSelect(table, column); } else if ( typeof fxn === 'object' && noSelect ) { // add custom drop down list for (string in fxn) { if (typeof string === 'string') { options += options === '' ? '<option value="">' + ($header.data('placeholder') || $header.attr('data-placeholder') || wo.filter_placeholder.select || '') + '</option>' : ''; val = string; txt = string; if (string.indexOf(wo.filter_selectSourceSeparator) >= 0) { val = string.split(wo.filter_selectSourceSeparator); txt = val[1]; val = val[0]; } options += '<option ' + (txt === val ? '' : 'data-function-name="' + string + '" ') + 'value="' + val + '">' + txt + '</option>'; } } c.$table.find('thead').find('select.' + ts.css.filter + '[data-column="' + column + '"]').append(options); } } } } // not really updating, but if the column has both the "filter-select" class & filter_functions set to true, // it would append the same options twice. ts.filter.buildDefault(table, true); ts.filter.bindSearch( table, c.$table.find('.' + ts.css.filter), true ); if (wo.filter_external) { ts.filter.bindSearch( table, wo.filter_external ); } if (wo.filter_hideFilters) { ts.filter.hideFilters(table, c); } // show processing icon if (c.showProcessing) { c.$table.bind('filterStart' + c.namespace + 'filter filterEnd' + c.namespace + 'filter', function(event, columns) { // only add processing to certain columns to all columns $header = (columns) ? c.$table.find('.' + ts.css.header).filter('[data-column]').filter(function() { return columns[$(this).data('column')] !== ''; }) : ''; ts.isProcessing(table, event.type === 'filterStart', columns ? $header : ''); }); } // set filtered rows count (intially unfiltered) c.filteredRows = c.totalRows; // add default values c.$table.bind('tablesorter-initialized pagerBeforeInitialized', function() { // redefine "wo" as it does not update properly inside this callback var wo = this.config.widgetOptions; filters = ts.filter.setDefaults(table, c, wo) || []; if (filters.length) { // prevent delayInit from triggering a cache build if filters are empty if ( !(c.delayInit && filters.join('') === '') ) { ts.setFilters(table, filters, true); } } c.$table.trigger('filterFomatterUpdate'); // trigger init after setTimeout to prevent multiple filterStart/End/Init triggers setTimeout(function(){ if (!wo.filter_initialized) { ts.filter.filterInitComplete(c); } }, 100); }); // if filter widget is added after pager has initialized; then set filter init flag if (c.pager && c.pager.initialized && !wo.filter_initialized) { c.$table.trigger('filterFomatterUpdate'); setTimeout(function(){ ts.filter.filterInitComplete(c); }, 100); } }, // $cell parameter, but not the config, is passed to the // filter_formatters, so we have to work with it instead formatterUpdated: function($cell, column) { var wo = $cell.closest('table')[0].config.widgetOptions; if (!wo.filter_initialized) { // add updates by column since this function // may be called numerous times before initialization wo.filter_formatterInit[column] = 1; } }, filterInitComplete: function(c){ var wo = c.widgetOptions, count = 0, completed = function(){ wo.filter_initialized = true; c.$table.trigger('filterInit', c); ts.filter.findRows(c.table, c.$table.data('lastSearch') || []); }; if ( $.isEmptyObject( wo.filter_formatter ) ) { completed(); } else { $.each( wo.filter_formatterInit, function(i, val) { if (val === 1) { count++; } }); clearTimeout(wo.filter_initTimer); if (!wo.filter_initialized && count === wo.filter_formatterCount) { // filter widget initialized completed(); } else if (!wo.filter_initialized) { // fall back in case a filter_formatter doesn't call // $.tablesorter.filter.formatterUpdated($cell, column), and the count is off wo.filter_initTimer = setTimeout(function(){ completed(); }, 500); } } }, setDefaults: function(table, c, wo) { var isArray, saved, indx, // get current (default) filters filters = ts.getFilters(table) || []; if (wo.filter_saveFilters && ts.storage) { saved = ts.storage( table, 'tablesorter-filters' ) || []; isArray = $.isArray(saved); // make sure we're not just getting an empty array if ( !(isArray && saved.join('') === '' || !isArray) ) { filters = saved; } } // if no filters saved, then check default settings if (filters.join('') === '') { for (indx = 0; indx < c.columns; indx++) { filters[indx] = c.$headers.filter('[data-column="' + indx + '"]:last').attr(wo.filter_defaultAttrib) || filters[indx]; } } c.$table.data('lastSearch', filters); return filters; }, parseFilter: function(c, filter, column, parsed, forceParse){ return forceParse || parsed ? c.parsers[column].format( filter, c.table, [], column ) : filter; }, buildRow: function(table, c, wo) { var col, column, $header, buildSelect, disabled, name, ffxn, // c.columns defined in computeThIndexes() columns = c.columns, arry = $.isArray(wo.filter_cellFilter), buildFilter = '<tr role="row" class="' + ts.css.filterRow + '">'; for (column = 0; column < columns; column++) { if (arry) { buildFilter += '<td' + ( wo.filter_cellFilter[column] ? ' class="' + wo.filter_cellFilter[column] + '"' : '' ) + '></td>'; } else { buildFilter += '<td' + ( wo.filter_cellFilter !== '' ? ' class="' + wo.filter_cellFilter + '"' : '' ) + '></td>'; } } c.$filters = $(buildFilter += '</tr>').appendTo( c.$table.children('thead').eq(0) ).find('td'); // build each filter input for (column = 0; column < columns; column++) { disabled = false; // assuming last cell of a column is the main column $header = c.$headers.filter('[data-column="' + column + '"]:last'); ffxn = ts.getColumnData( table, wo.filter_functions, column ); buildSelect = (wo.filter_functions && ffxn && typeof ffxn !== "function" ) || $header.hasClass('filter-select'); // get data from jQuery data, metadata, headers option or header class name col = ts.getColumnData( table, c.headers, column ); disabled = ts.getData($header[0], col, 'filter') === 'false' || ts.getData($header[0], col, 'parser') === 'false'; if (buildSelect) { buildFilter = $('<select>').appendTo( c.$filters.eq(column) ); } else { ffxn = ts.getColumnData( table, wo.filter_formatter, column ); if (ffxn) { wo.filter_formatterCount++; buildFilter = ffxn( c.$filters.eq(column), column ); // no element returned, so lets go find it if (buildFilter && buildFilter.length === 0) { buildFilter = c.$filters.eq(column).children('input'); } // element not in DOM, so lets attach it if ( buildFilter && (buildFilter.parent().length === 0 || (buildFilter.parent().length && buildFilter.parent()[0] !== c.$filters[column])) ) { c.$filters.eq(column).append(buildFilter); } } else { buildFilter = $('<input type="search">').appendTo( c.$filters.eq(column) ); } if (buildFilter) { buildFilter.attr('placeholder', $header.data('placeholder') || $header.attr('data-placeholder') || wo.filter_placeholder.search || ''); } } if (buildFilter) { // add filter class name name = ( $.isArray(wo.filter_cssFilter) ? (typeof wo.filter_cssFilter[column] !== 'undefined' ? wo.filter_cssFilter[column] || '' : '') : wo.filter_cssFilter ) || ''; buildFilter.addClass( ts.css.filter + ' ' + name ).attr('data-column', column); if (disabled) { buildFilter.attr('placeholder', '').addClass('disabled')[0].disabled = true; // disabled! } } } }, bindSearch: function(table, $el, internal) { table = $(table)[0]; $el = $($el); // allow passing a selector string if (!$el.length) { return; } var c = table.config, wo = c.widgetOptions, $ext = wo.filter_$externalFilters; if (internal !== true) { // save anyMatch element wo.filter_$anyMatch = $el.filter(wo.filter_anyColumnSelector + ',' + wo.filter_multipleColumnSelector); if ($ext && $ext.length) { wo.filter_$externalFilters = wo.filter_$externalFilters.add( $el ); } else { wo.filter_$externalFilters = $el; } // update values (external filters added after table initialization) ts.setFilters(table, c.$table.data('lastSearch') || [], internal === false); } $el // use data attribute instead of jQuery data since the head is cloned without including the data/binding .attr('data-lastSearchTime', new Date().getTime()) .unbind('keypress keyup search change '.split(' ').join(c.namespace + 'filter ')) // include change for select - fixes #473 .bind('keyup' + c.namespace + 'filter', function(event) { $(this).attr('data-lastSearchTime', new Date().getTime()); // emulate what webkit does.... escape clears the filter if (event.which === 27) { this.value = ''; // live search } else if ( wo.filter_liveSearch === false ) { return; // don't return if the search value is empty (all rows need to be revealed) } else if ( this.value !== '' && ( // liveSearch can contain a min value length; ignore arrow and meta keys, but allow backspace ( typeof wo.filter_liveSearch === 'number' && this.value.length < wo.filter_liveSearch ) || // let return & backspace continue on, but ignore arrows & non-valid characters ( event.which !== 13 && event.which !== 8 && ( event.which < 32 || (event.which >= 37 && event.which <= 40) ) ) ) ) { return; } // change event = no delay; last true flag tells getFilters to skip newest timed input ts.filter.searching( table, true, true ); }) .bind('search change keypress '.split(' ').join(c.namespace + 'filter '), function(event){ var column = $(this).data('column'); // don't allow "change" event to process if the input value is the same - fixes #685 if (event.which === 13 || event.type === 'search' || event.type === 'change' && this.value !== c.lastSearch[column]) { event.preventDefault(); // init search with no delay $(this).attr('data-lastSearchTime', new Date().getTime()); ts.filter.searching( table, false, true ); } }); }, searching: function(table, filter, skipFirst) { var wo = table.config.widgetOptions; clearTimeout(wo.searchTimer); if (typeof filter === 'undefined' || filter === true) { // delay filtering wo.searchTimer = setTimeout(function() { ts.filter.checkFilters(table, filter, skipFirst ); }, wo.filter_liveSearch ? wo.filter_searchDelay : 10); } else { // skip delay ts.filter.checkFilters(table, filter, skipFirst); } }, checkFilters: function(table, filter, skipFirst) { var c = table.config, wo = c.widgetOptions, filterArray = $.isArray(filter), filters = (filterArray) ? filter : ts.getFilters(table, true), combinedFilters = (filters || []).join(''); // combined filter values // prevent errors if delay init is set if ($.isEmptyObject(c.cache)) { // update cache if delayInit set & pager has initialized (after user initiates a search) if (c.delayInit && c.pager && c.pager.initialized) { c.$table.trigger('updateCache', [function(){ ts.filter.checkFilters(table, false, skipFirst); }] ); } return; } // add filter array back into inputs if (filterArray) { ts.setFilters( table, filters, false, skipFirst !== true ); if (!wo.filter_initialized) { c.lastCombinedFilter = ''; } } if (wo.filter_hideFilters) { // show/hide filter row as needed c.$table.find('.' + ts.css.filterRow).trigger( combinedFilters === '' ? 'mouseleave' : 'mouseenter' ); } // return if the last search is the same; but filter === false when updating the search // see example-widget-filter.html filter toggle buttons if (c.lastCombinedFilter === combinedFilters && filter !== false) { return; } else if (filter === false) { // force filter refresh c.lastCombinedFilter = null; c.lastSearch = []; } if (wo.filter_initialized) { c.$table.trigger('filterStart', [filters]); } if (c.showProcessing) { // give it time for the processing icon to kick in setTimeout(function() { ts.filter.findRows(table, filters, combinedFilters); return false; }, 30); } else { ts.filter.findRows(table, filters, combinedFilters); return false; } }, hideFilters: function(table, c) { var $filterRow, $filterRow2, timer; $(table) .find('.' + ts.css.filterRow) .addClass('hideme') .bind('mouseenter mouseleave', function(e) { // save event object - http://bugs.jquery.com/ticket/12140 var event = e; $filterRow = $(this); clearTimeout(timer); timer = setTimeout(function() { if ( /enter|over/.test(event.type) ) { $filterRow.removeClass('hideme'); } else { // don't hide if input has focus // $(':focus') needs jQuery 1.6+ if ( $(document.activeElement).closest('tr')[0] !== $filterRow[0] ) { // don't hide row if any filter has a value if (c.lastCombinedFilter === '') { $filterRow.addClass('hideme'); } } } }, 200); }) .find('input, select').bind('focus blur', function(e) { $filterRow2 = $(this).closest('tr'); clearTimeout(timer); var event = e; timer = setTimeout(function() { // don't hide row if any filter has a value if (ts.getFilters(c.$table).join('') === '') { $filterRow2[ event.type === 'focus' ? 'removeClass' : 'addClass']('hideme'); } }, 200); }); }, defaultFilter: function(filter, mask){ if (filter === '') { return filter; } var regex = ts.filter.regex.iQuery, maskLen = mask.match( ts.filter.regex.igQuery ).length, query = maskLen > 1 ? $.trim(filter).split(/\s/) : [ $.trim(filter) ], len = query.length - 1, indx = 0, val = mask; if ( len < 1 && maskLen > 1 ) { // only one "word" in query but mask has >1 slots query[1] = query[0]; } // replace all {query} with query words... // if query = "Bob", then convert mask from "!{query}" to "!Bob" // if query = "Bob Joe Frank", then convert mask "{q} OR {q}" to "Bob OR Joe OR Frank" while (regex.test(val)) { val = val.replace(regex, query[indx++] || ''); if (regex.test(val) && indx < len && (query[indx] || '') !== '') { val = mask.replace(regex, val); } } return val; }, getLatestSearch: function( $input ) { return $input.sort(function(a, b) { return $(b).attr('data-lastSearchTime') - $(a).attr('data-lastSearchTime'); }); }, multipleColumns: function( c, $input ) { // look for multiple columns "1-3,4-6,8" in data-column var ranges, singles, indx, wo = c.widgetOptions, // only target "all" column inputs on initialization // & don't target "all" column inputs if they don't exist targets = wo.filter_initialized || !$input.filter(wo.filter_anyColumnSelector).length, columns = [], val = $.trim( ts.filter.getLatestSearch( $input ).attr('data-column') ); // process column range if ( targets && /-/.test( val ) ) { ranges = val.match( /(\d+)\s*-\s*(\d+)/g ); $.each(ranges, function(i,v){ var t, range = v.split( /\s*-\s*/ ), start = parseInt( range[0], 10 ) || 0, end = parseInt( range[1], 10 ) || ( c.columns - 1 ); if ( start > end ) { t = start; start = end; end = t; } // swap if ( end >= c.columns ) { end = c.columns - 1; } for ( ; start <= end; start++ ) { columns.push(start); } // remove processed range from val val = val.replace( v, '' ); }); } // process single columns if ( targets && /,/.test( val ) ) { singles = val.split( /\s*,\s*/ ); $.each( singles, function(i,v) { if (v !== '') { indx = parseInt( v, 10 ); if ( indx < c.columns ) { columns.push( indx ); } } }); } // return all columns if (!columns.length) { for ( indx = 0; indx < c.columns; indx++ ) { columns.push( indx ); } } return columns; }, findRows: function(table, filters, combinedFilters) { if (table.config.lastCombinedFilter === combinedFilters || !table.config.widgetOptions.filter_initialized) { return; } var len, $rows, rowIndex, tbodyIndex, $tbody, $cells, $cell, columnIndex, childRow, lastSearch, hasSelect, matches, result, showRow, time, val, indx, notFiltered, searchFiltered, filterMatched, excludeMatch, fxn, ffxn, regex = ts.filter.regex, c = table.config, wo = c.widgetOptions, $tbodies = c.$table.children('tbody'), // target all tbodies #568 // data object passed to filters; anyMatch is a flag for the filters data = { anyMatch: false }, // anyMatch really screws up with these types of filters noAnyMatch = [ 'range', 'notMatch', 'operators' ]; // parse columns after formatter, in case the class is added at that point data.parsed = c.$headers.map(function(columnIndex) { return c.parsers && c.parsers[columnIndex] && c.parsers[columnIndex].parsed || // getData won't return "parsed" if other "filter-" class names exist (e.g. <th class="filter-select filter-parsed">) ts.getData && ts.getData(c.$headers.filter('[data-column="' + columnIndex + '"]:last'), ts.getColumnData( table, c.headers, columnIndex ), 'filter') === 'parsed' || $(this).hasClass('filter-parsed'); }).get(); if (c.debug) { ts.log('Starting filter widget search', filters); time = new Date(); } // filtered rows count c.filteredRows = 0; c.totalRows = 0; // combindedFilters are undefined on init combinedFilters = (filters || []).join(''); for (tbodyIndex = 0; tbodyIndex < $tbodies.length; tbodyIndex++ ) { if ($tbodies.eq(tbodyIndex).hasClass(c.cssInfoBlock || ts.css.info)) { continue; } // ignore info blocks, issue #264 $tbody = ts.processTbody(table, $tbodies.eq(tbodyIndex), true); // skip child rows & widget added (removable) rows - fixes #448 thanks to @hempel! // $rows = $tbody.children('tr').not(c.selectorRemove); columnIndex = c.columns; // convert stored rows into a jQuery object $rows = $( $.map(c.cache[tbodyIndex].normalized, function(el){ return el[columnIndex].$row.get(); }) ); if (combinedFilters === '' || wo.filter_serversideFiltering) { $rows.removeClass(wo.filter_filteredRow).not('.' + c.cssChildRow).show(); } else { // filter out child rows $rows = $rows.not('.' + c.cssChildRow); len = $rows.length; // optimize searching only through already filtered rows - see #313 searchFiltered = wo.filter_searchFiltered; lastSearch = c.lastSearch || c.$table.data('lastSearch') || []; if (searchFiltered) { // cycle through all filters; include last (columnIndex + 1 = match any column). Fixes #669 for (indx = 0; indx < columnIndex + 1; indx++) { val = filters[indx] || ''; // break out of loop if we've already determined not to search filtered rows if (!searchFiltered) { indx = columnIndex; } // search already filtered rows if... searchFiltered = searchFiltered && lastSearch.length && // there are no changes from beginning of filter val.indexOf(lastSearch[indx] || '') === 0 && // if there is NOT a logical "or", or range ("to" or "-") in the string !regex.alreadyFiltered.test(val) && // if we are not doing exact matches, using "|" (logical or) or not "!" !/[=\"\|!]/.test(val) && // don't search only filtered if the value is negative ('> -10' => '> -100' will ignore hidden rows) !(/(>=?\s*-\d)/.test(val) || /(<=?\s*\d)/.test(val)) && // if filtering using a select without a "filter-match" class (exact match) - fixes #593 !( val !== '' && c.$filters && c.$filters.eq(indx).find('select').length && !c.$headers.filter('[data-column="' + indx + '"]:last').hasClass('filter-match') ); } } notFiltered = $rows.not('.' + wo.filter_filteredRow).length; // can't search when all rows are hidden - this happens when looking for exact matches if (searchFiltered && notFiltered === 0) { searchFiltered = false; } if (c.debug) { ts.log( "Searching through " + ( searchFiltered && notFiltered < len ? notFiltered : "all" ) + " rows" ); } if ((wo.filter_$anyMatch && wo.filter_$anyMatch.length) || filters[c.columns]) { data.anyMatchFlag = true; data.anyMatchFilter = wo.filter_$anyMatch && ts.filter.getLatestSearch( wo.filter_$anyMatch ).val() || filters[c.columns] || ''; if (c.sortLocaleCompare) { // replace accents data.anyMatchFilter = ts.replaceAccents(data.anyMatchFilter); } if (wo.filter_defaultFilter && regex.iQuery.test( ts.getColumnData( table, wo.filter_defaultFilter, c.columns, true ) || '')) { data.anyMatchFilter = ts.filter.defaultFilter( data.anyMatchFilter, ts.getColumnData( table, wo.filter_defaultFilter, c.columns, true ) ); // clear search filtered flag because default filters are not saved to the last search searchFiltered = false; } // make iAnyMatchFilter lowercase unless both filter widget & core ignoreCase options are true // when c.ignoreCase is true, the cache contains all lower case data data.iAnyMatchFilter = !(wo.filter_ignoreCase && c.ignoreCase) ? data.anyMatchFilter : data.anyMatchFilter.toLocaleLowerCase(); } // loop through the rows for (rowIndex = 0; rowIndex < len; rowIndex++) { data.cacheArray = c.cache[tbodyIndex].normalized[rowIndex]; childRow = $rows[rowIndex].className; // skip child rows & already filtered rows if ( regex.child.test(childRow) || (searchFiltered && regex.filtered.test(childRow)) ) { continue; } showRow = true; // *** nextAll/nextUntil not supported by Zepto! *** childRow = $rows.eq(rowIndex).nextUntil('tr:not(.' + c.cssChildRow + ')'); // so, if "table.config.widgetOptions.filter_childRows" is true and there is // a match anywhere in the child row, then it will make the row visible // checked here so the option can be changed dynamically data.childRowText = (childRow.length && wo.filter_childRows) ? childRow.text() : ''; data.childRowText = wo.filter_ignoreCase ? data.childRowText.toLocaleLowerCase() : data.childRowText; $cells = $rows.eq(rowIndex).children(); if (data.anyMatchFlag) { // look for multiple columns "1-3,4-6,8" columnIndex = ts.filter.multipleColumns( c, wo.filter_$anyMatch ); data.anyMatch = true; data.rowArray = $cells.map(function(i){ if ( $.inArray(i, columnIndex) > -1 ) { var txt; if (data.parsed[i]) { txt = data.cacheArray[i]; } else { txt = wo.filter_ignoreCase ? $(this).text().toLowerCase() : $(this).text(); if (c.sortLocaleCompare) { txt = ts.replaceAccents(txt); } } return txt; } }).get(); data.filter = data.anyMatchFilter; data.iFilter = data.iAnyMatchFilter; data.exact = data.rowArray.join(' '); data.iExact = wo.filter_ignoreCase ? data.exact.toLowerCase() : data.exact; data.cache = data.cacheArray.slice(0,-1).join(' '); filterMatched = null; $.each(ts.filter.types, function(type, typeFunction) { if ($.inArray(type, noAnyMatch) < 0) { matches = typeFunction( c, data ); if (matches !== null) { filterMatched = matches; return false; } } }); if (filterMatched !== null) { showRow = filterMatched; } else { if (wo.filter_startsWith) { showRow = false; columnIndex = c.columns; while (!showRow && columnIndex > 0) { columnIndex--; showRow = showRow || data.rowArray[columnIndex].indexOf(data.iFilter) === 0; } } else { showRow = (data.iExact + data.childRowText).indexOf(data.iFilter) >= 0; } } data.anyMatch = false; } for (columnIndex = 0; columnIndex < c.columns; columnIndex++) { data.filter = filters[columnIndex]; data.index = columnIndex; // filter types to exclude, per column excludeMatch = ( ts.getColumnData( table, wo.filter_excludeFilter, columnIndex, true ) || '' ).split(/\s+/); // ignore if filter is empty or disabled if (data.filter) { data.cache = data.cacheArray[columnIndex]; // check if column data should be from the cell or from parsed data if (wo.filter_useParsedData || data.parsed[columnIndex]) { data.exact = data.cache; } else { // using older or original tablesorter data.exact = $.trim( $cells.eq(columnIndex).text() ); data.exact = c.sortLocaleCompare ? ts.replaceAccents(data.exact) : data.exact; // issue #405 } data.iExact = !regex.type.test(typeof data.exact) && wo.filter_ignoreCase ? data.exact.toLocaleLowerCase() : data.exact; result = showRow; // if showRow is true, show that row // in case select filter option has a different value vs text "a - z|A through Z" ffxn = wo.filter_columnFilters ? c.$filters.add(c.$externalFilters).filter('[data-column="'+ columnIndex + '"]').find('select option:selected').attr('data-function-name') || '' : ''; // replace accents - see #357 data.filter = c.sortLocaleCompare ? ts.replaceAccents(data.filter) : data.filter; val = true; if (wo.filter_defaultFilter && regex.iQuery.test( ts.getColumnData( table, wo.filter_defaultFilter, columnIndex ) || '')) { data.filter = ts.filter.defaultFilter( data.filter, ts.getColumnData( table, wo.filter_defaultFilter, columnIndex ) ); // val is used to indicate that a filter select is using a default filter; so we override the exact & partial matches val = false; } // data.iFilter = case insensitive (if wo.filter_ignoreCase is true), data.filter = case sensitive data.iFilter = wo.filter_ignoreCase ? (data.filter || '').toLocaleLowerCase() : data.filter; fxn = ts.getColumnData( table, wo.filter_functions, columnIndex ); $cell = c.$headers.filter('[data-column="' + columnIndex + '"]:last'); hasSelect = $cell.hasClass('filter-select'); if ( fxn || ( hasSelect && val ) ) { if (fxn === true || hasSelect) { // default selector uses exact match unless "filter-match" class is found result = ($cell.hasClass('filter-match')) ? data.iExact.search(data.iFilter) >= 0 : data.filter === data.exact; } else if (typeof fxn === 'function') { // filter callback( exact cell content, parser normalized content, filter input value, column index, jQuery row object ) result = fxn(data.exact, data.cache, data.filter, columnIndex, $rows.eq(rowIndex)); } else if (typeof fxn[ffxn || data.filter] === 'function') { // selector option function result = fxn[ffxn || data.filter](data.exact, data.cache, data.filter, columnIndex, $rows.eq(rowIndex)); } } else { filterMatched = null; // cycle through the different filters // filters return a boolean or null if nothing matches $.each(ts.filter.types, function(type, typeFunction) { if ($.inArray(type, excludeMatch) < 0) { matches = typeFunction( c, data ); if (matches !== null) { filterMatched = matches; return false; } } }); if (filterMatched !== null) { result = filterMatched; // Look for match, and add child row data for matching } else { data.exact = (data.iExact + data.childRowText).indexOf( ts.filter.parseFilter(c, data.iFilter, columnIndex, data.parsed[columnIndex]) ); result = ( (!wo.filter_startsWith && data.exact >= 0) || (wo.filter_startsWith && data.exact === 0) ); } } showRow = (result) ? showRow : false; } } $rows.eq(rowIndex) .toggle(showRow) .toggleClass(wo.filter_filteredRow, !showRow); if (childRow.length) { childRow.toggleClass(wo.filter_filteredRow, !showRow); } } } c.filteredRows += $rows.not('.' + wo.filter_filteredRow).length; c.totalRows += $rows.length; ts.processTbody(table, $tbody, false); } c.lastCombinedFilter = combinedFilters; // save last search c.lastSearch = filters; c.$table.data('lastSearch', filters); if (wo.filter_saveFilters && ts.storage) { ts.storage( table, 'tablesorter-filters', filters ); } if (c.debug) { ts.benchmark("Completed filter widget search", time); } if (wo.filter_initialized) { c.$table.trigger('filterEnd', c ); } setTimeout(function(){ c.$table.trigger('applyWidgets'); // make sure zebra widget is applied }, 0); }, getOptionSource: function(table, column, onlyAvail) { var cts, c = table.config, wo = c.widgetOptions, parsed = [], arry = false, source = wo.filter_selectSource, last = c.$table.data('lastSearch') || [], fxn = $.isFunction(source) ? true : ts.getColumnData( table, source, column ); if (onlyAvail && last[column] !== '') { onlyAvail = false; } // filter select source option if (fxn === true) { // OVERALL source arry = source(table, column, onlyAvail); } else if ( fxn instanceof $ || ($.type(fxn) === 'string' && fxn.indexOf('</option>') >= 0) ) { // selectSource is a jQuery object or string of options return fxn; } else if ($.isArray(fxn)) { arry = fxn; } else if ($.type(source) === 'object' && fxn) { // custom select source function for a SPECIFIC COLUMN arry = fxn(table, column, onlyAvail); } if (arry === false) { // fall back to original method arry = ts.filter.getOptions(table, column, onlyAvail); } // get unique elements and sort the list // if $.tablesorter.sortText exists (not in the original tablesorter), // then natural sort the list otherwise use a basic sort arry = $.grep(arry, function(value, indx) { return $.inArray(value, arry) === indx; }); if (c.$headers.filter('[data-column="' + column + '"]:last').hasClass('filter-select-nosort')) { // unsorted select options return arry; } else { // parse select option values $.each(arry, function(i, v){ // parse array data using set column parser; this DOES NOT pass the original // table cell to the parser format function parsed.push({ t : v, p : c.parsers && c.parsers[column].format( v, table, [], column ) }); }); // sort parsed select options cts = c.textSorter || ''; parsed.sort(function(a, b){ // sortNatural breaks if you don't pass it strings var x = a.p.toString(), y = b.p.toString(); if ($.isFunction(cts)) { // custom OVERALL text sorter return cts(x, y, true, column, table); } else if (typeof(cts) === 'object' && cts.hasOwnProperty(column)) { // custom text sorter for a SPECIFIC COLUMN return cts[column](x, y, true, column, table); } else if (ts.sortNatural) { // fall back to natural sort return ts.sortNatural(x, y); } // using an older version! do a basic sort return true; }); // rebuild arry from sorted parsed data arry = []; $.each(parsed, function(i, v){ arry.push(v.t); }); return arry; } }, getOptions: function(table, column, onlyAvail) { var rowIndex, tbodyIndex, len, row, cache, cell, c = table.config, wo = c.widgetOptions, $tbodies = c.$table.children('tbody'), arry = []; for (tbodyIndex = 0; tbodyIndex < $tbodies.length; tbodyIndex++ ) { if (!$tbodies.eq(tbodyIndex).hasClass(c.cssInfoBlock)) { cache = c.cache[tbodyIndex]; len = c.cache[tbodyIndex].normalized.length; // loop through the rows for (rowIndex = 0; rowIndex < len; rowIndex++) { // get cached row from cache.row (old) or row data object (new; last item in normalized array) row = cache.row ? cache.row[rowIndex] : cache.normalized[rowIndex][c.columns].$row[0]; // check if has class filtered if (onlyAvail && row.className.match(wo.filter_filteredRow)) { continue; } // get non-normalized cell content if (wo.filter_useParsedData || c.parsers[column].parsed || c.$headers.filter('[data-column="' + column + '"]:last').hasClass('filter-parsed')) { arry.push( '' + cache.normalized[rowIndex][column] ); } else { cell = row.cells[column]; if (cell) { arry.push( $.trim( cell.textContent || cell.innerText || $(cell).text() ) ); } } } } } return arry; }, buildSelect: function(table, column, arry, updating, onlyAvail) { table = $(table)[0]; column = parseInt(column, 10); if (!table.config.cache || $.isEmptyObject(table.config.cache)) { return; } var indx, val, txt, t, $filters, $filter, c = table.config, wo = c.widgetOptions, node = c.$headers.filter('[data-column="' + column + '"]:last'), // t.data('placeholder') won't work in jQuery older than 1.4.3 options = '<option value="">' + ( node.data('placeholder') || node.attr('data-placeholder') || wo.filter_placeholder.select || '' ) + '</option>', // Get curent filter value currentValue = c.$table.find('thead').find('select.' + ts.css.filter + '[data-column="' + column + '"]').val(); // nothing included in arry (external source), so get the options from filter_selectSource or column data if (typeof arry === 'undefined' || arry === '') { arry = ts.filter.getOptionSource(table, column, onlyAvail); } if ($.isArray(arry)) { // build option list for (indx = 0; indx < arry.length; indx++) { txt = arry[indx] = ('' + arry[indx]).replace(/\"/g, "&quot;"); val = txt; // allow including a symbol in the selectSource array // "a-z|A through Z" so that "a-z" becomes the option value // and "A through Z" becomes the option text if (txt.indexOf(wo.filter_selectSourceSeparator) >= 0) { t = txt.split(wo.filter_selectSourceSeparator); val = t[0]; txt = t[1]; } // replace quotes - fixes #242 & ignore empty strings - see http://stackoverflow.com/q/14990971/145346 options += arry[indx] !== '' ? '<option ' + (val === txt ? '' : 'data-function-name="' + arry[indx] + '" ') + 'value="' + val + '">' + txt + '</option>' : ''; } // clear arry so it doesn't get appended twice arry = []; } // update all selects in the same column (clone thead in sticky headers & any external selects) - fixes 473 $filters = ( c.$filters ? c.$filters : c.$table.children('thead') ).find('.' + ts.css.filter); if (wo.filter_$externalFilters) { $filters = $filters && $filters.length ? $filters.add(wo.filter_$externalFilters) : wo.filter_$externalFilters; } $filter = $filters.filter('select[data-column="' + column + '"]'); // make sure there is a select there! if ($filter.length) { $filter[ updating ? 'html' : 'append' ](options); if (!$.isArray(arry)) { // append options if arry is provided externally as a string or jQuery object // options (default value) was already added $filter.append(arry).val(currentValue); } $filter.val(currentValue); } }, buildDefault: function(table, updating) { var columnIndex, $header, noSelect, c = table.config, wo = c.widgetOptions, columns = c.columns; // build default select dropdown for (columnIndex = 0; columnIndex < columns; columnIndex++) { $header = c.$headers.filter('[data-column="' + columnIndex + '"]:last'); noSelect = !($header.hasClass('filter-false') || $header.hasClass('parser-false')); // look for the filter-select class; build/update it if found if (($header.hasClass('filter-select') || ts.getColumnData( table, wo.filter_functions, columnIndex ) === true) && noSelect) { ts.filter.buildSelect(table, columnIndex, '', updating, $header.hasClass(wo.filter_onlyAvail)); } } } }; ts.getFilters = function(table, getRaw, setFilters, skipFirst) { var i, $filters, $column, cols, filters = false, c = table ? $(table)[0].config : '', wo = c ? c.widgetOptions : ''; if (getRaw !== true && wo && !wo.filter_columnFilters) { return $(table).data('lastSearch'); } if (c) { if (c.$filters) { $filters = c.$filters.find('.' + ts.css.filter); } if (wo.filter_$externalFilters) { $filters = $filters && $filters.length ? $filters.add(wo.filter_$externalFilters) : wo.filter_$externalFilters; } if ($filters && $filters.length) { filters = setFilters || []; for (i = 0; i < c.columns + 1; i++) { cols = ( i === c.columns ? // "all" columns can now include a range or set of columms (data-column="0-2,4,6-7") wo.filter_anyColumnSelector + ',' + wo.filter_multipleColumnSelector : '[data-column="' + i + '"]' ); $column = $filters.filter(cols); if ($column.length) { // move the latest search to the first slot in the array $column = ts.filter.getLatestSearch( $column ); if ($.isArray(setFilters)) { // skip first (latest input) to maintain cursor position while typing if (skipFirst) { $column.slice(1); } if (i === c.columns) { // prevent data-column="all" from filling data-column="0,1" (etc) cols = $column.filter(wo.filter_anyColumnSelector); $column = cols.length ? cols : $column; } $column .val( setFilters[i] ) .trigger('change.tsfilter'); } else { filters[i] = $column.val() || ''; // don't change the first... it will move the cursor if (i === c.columns) { // don't update range columns from "all" setting $column.slice(1).filter('[data-column*="' + $column.attr('data-column') + '"]').val( filters[i] ); } else { $column.slice(1).val( filters[i] ); } } // save any match input dynamically if (i === c.columns && $column.length) { wo.filter_$anyMatch = $column; } } } } } if (filters.length === 0) { filters = false; } return filters; }; ts.setFilters = function(table, filter, apply, skipFirst) { var c = table ? $(table)[0].config : '', valid = ts.getFilters(table, true, filter, skipFirst); if (c && apply) { // ensure new set filters are applied, even if the search is the same c.lastCombinedFilter = null; c.lastSearch = []; ts.filter.searching(c.$table[0], filter, skipFirst); c.$table.trigger('filterFomatterUpdate'); } return !!valid; }; // Widget: Sticky headers // based on this awesome article: // http://css-tricks.com/13465-persistent-headers/ // and https://github.com/jmosbech/StickyTableHeaders by Jonas Mosbech // ************************** ts.addWidget({ id: "stickyHeaders", priority: 60, // sticky widget must be initialized after the filter widget! options: { stickyHeaders : '', // extra class name added to the sticky header row stickyHeaders_attachTo : null, // jQuery selector or object to attach sticky header to stickyHeaders_xScroll : null, // jQuery selector or object to monitor horizontal scroll position (defaults: xScroll > attachTo > window) stickyHeaders_yScroll : null, // jQuery selector or object to monitor vertical scroll position (defaults: yScroll > attachTo > window) stickyHeaders_offset : 0, // number or jquery selector targeting the position:fixed element stickyHeaders_filteredToTop: true, // scroll table top into view after filtering stickyHeaders_cloneId : '-sticky', // added to table ID, if it exists stickyHeaders_addResizeEvent : true, // trigger "resize" event on headers stickyHeaders_includeCaption : true, // if false and a caption exist, it won't be included in the sticky header stickyHeaders_zIndex : 2 // The zIndex of the stickyHeaders, allows the user to adjust this to their needs }, format: function(table, c, wo) { // filter widget doesn't initialize on an empty table. Fixes #449 if ( c.$table.hasClass('hasStickyHeaders') || ($.inArray('filter', c.widgets) >= 0 && !c.$table.hasClass('hasFilters')) ) { return; } var $table = c.$table, $attach = $(wo.stickyHeaders_attachTo), namespace = c.namespace + 'stickyheaders ', // element to watch for the scroll event $yScroll = $(wo.stickyHeaders_yScroll || wo.stickyHeaders_attachTo || window), $xScroll = $(wo.stickyHeaders_xScroll || wo.stickyHeaders_attachTo || window), $thead = $table.children('thead:first'), $header = $thead.children('tr').not('.sticky-false').children(), $tfoot = $table.children('tfoot'), $stickyOffset = isNaN(wo.stickyHeaders_offset) ? $(wo.stickyHeaders_offset) : '', stickyOffset = $attach.length ? 0 : $stickyOffset.length ? $stickyOffset.height() || 0 : parseInt(wo.stickyHeaders_offset, 10) || 0, // is this table nested? If so, find parent sticky header wrapper (div, not table) $nestedSticky = $table.parent().closest('.' + ts.css.table).hasClass('hasStickyHeaders') ? $table.parent().closest('table.tablesorter')[0].config.widgetOptions.$sticky.parent() : [], nestedStickyTop = $nestedSticky.length ? $nestedSticky.height() : 0, // clone table, then wrap to make sticky header $stickyTable = wo.$sticky = $table.clone() .addClass('containsStickyHeaders ' + ts.css.sticky + ' ' + wo.stickyHeaders) .wrap('<div class="' + ts.css.stickyWrap + '">'), $stickyWrap = $stickyTable.parent().css({ position : $attach.length ? 'absolute' : 'fixed', padding : parseInt( $stickyTable.parent().parent().css('padding-left'), 10 ), top : stickyOffset + nestedStickyTop, left : 0, visibility : 'hidden', zIndex : wo.stickyHeaders_zIndex || 2 }), $stickyThead = $stickyTable.children('thead:first'), $stickyCells, laststate = '', spacing = 0, setWidth = function($orig, $clone){ $orig.filter(':visible').each(function(i) { var width, border, $cell = $clone.filter(':visible').eq(i), $this = $(this); // code from https://github.com/jmosbech/StickyTableHeaders if ($this.css('box-sizing') === 'border-box') { width = $this.outerWidth(); } else { if ($cell.css('border-collapse') === 'collapse') { if (window.getComputedStyle) { width = parseFloat( window.getComputedStyle(this, null).width ); } else { // ie8 only border = parseFloat( $this.css('border-width') ); width = $this.outerWidth() - parseFloat( $this.css('padding-left') ) - parseFloat( $this.css('padding-right') ) - border; } } else { width = $this.width(); } } $cell.css({ 'min-width': width, 'max-width': width }); }); }, resizeHeader = function() { stickyOffset = $stickyOffset.length ? $stickyOffset.height() || 0 : parseInt(wo.stickyHeaders_offset, 10) || 0; spacing = 0; $stickyWrap.css({ left : $attach.length ? parseInt($attach.css('padding-left'), 10) || 0 : $table.offset().left - parseInt($table.css('margin-left'), 10) - $xScroll.scrollLeft() - spacing, width: $table.outerWidth() }); setWidth( $table, $stickyTable ); setWidth( $header, $stickyCells ); }; // fix clone ID, if it exists - fixes #271 if ($stickyTable.attr('id')) { $stickyTable[0].id += wo.stickyHeaders_cloneId; } // clear out cloned table, except for sticky header // include caption & filter row (fixes #126 & #249) - don't remove cells to get correct cell indexing $stickyTable.find('thead:gt(0), tr.sticky-false').hide(); $stickyTable.find('tbody, tfoot').remove(); $stickyTable.find('caption').toggle(wo.stickyHeaders_includeCaption); // issue #172 - find td/th in sticky header $stickyCells = $stickyThead.children().children(); $stickyTable.css({ height:0, width:0, margin: 0 }); // remove resizable block $stickyCells.find('.' + ts.css.resizer).remove(); // update sticky header class names to match real header after sorting $table .addClass('hasStickyHeaders') .bind('pagerComplete' + namespace, function() { resizeHeader(); }); ts.bindEvents(table, $stickyThead.children().children('.tablesorter-header')); // add stickyheaders AFTER the table. If the table is selected by ID, the original one (first) will be returned. $table.after( $stickyWrap ); // onRenderHeader is defined, we need to do something about it (fixes #641) if (c.onRenderHeader) { $stickyThead.children('tr').children().each(function(index){ // send second parameter c.onRenderHeader.apply( $(this), [ index, c, $stickyTable ] ); }); } // make it sticky! $xScroll.add($yScroll) .unbind('scroll resize '.split(' ').join( namespace ) ) .bind('scroll resize '.split(' ').join( namespace ), function(event) { if (!$table.is(':visible')) { return; } // fixes #278 // Detect nested tables - fixes #724 nestedStickyTop = $nestedSticky.length ? $nestedSticky.offset().top - $yScroll.scrollTop() + $nestedSticky.height() : 0; var prefix = 'tablesorter-sticky-', offset = $table.offset(), yWindow = $.isWindow( $yScroll[0] ), // $.isWindow needs jQuery 1.4.3 xWindow = $.isWindow( $xScroll[0] ), // scrollTop = ( $attach.length ? $attach.offset().top : $yScroll.scrollTop() ) + stickyOffset + nestedStickyTop, scrollTop = ( $attach.length ? ( yWindow ? $yScroll.scrollTop() : $yScroll.offset().top ) : $yScroll.scrollTop() ) + stickyOffset + nestedStickyTop, tableHeight = $table.height() - ($stickyWrap.height() + ($tfoot.height() || 0)), isVisible = ( scrollTop > offset.top ) && ( scrollTop < offset.top + tableHeight ) ? 'visible' : 'hidden', cssSettings = { visibility : isVisible }; if ($attach.length) { cssSettings.top = yWindow ? scrollTop : $attach.scrollTop(); } if (xWindow) { // adjust when scrolling horizontally - fixes issue #143 cssSettings.left = $table.offset().left - parseInt($table.css('margin-left'), 10) - $xScroll.scrollLeft() - spacing; } if ($nestedSticky.length) { cssSettings.top = ( cssSettings.top || 0 ) + stickyOffset + nestedStickyTop; } $stickyWrap .removeClass(prefix + 'visible ' + prefix + 'hidden') .addClass(prefix + isVisible) .css(cssSettings); if (isVisible !== laststate || event.type === 'resize') { // make sure the column widths match resizeHeader(); laststate = isVisible; } }); if (wo.stickyHeaders_addResizeEvent) { ts.addHeaderResizeEvent(table); } // look for filter widget if ($table.hasClass('hasFilters') && wo.filter_columnFilters) { // scroll table into view after filtering, if sticky header is active - #482 $table.bind('filterEnd' + namespace, function() { // $(':focus') needs jQuery 1.6+ var $td = $(document.activeElement).closest('td'), column = $td.parent().children().index($td); // only scroll if sticky header is active if ($stickyWrap.hasClass(ts.css.stickyVis) && wo.stickyHeaders_filteredToTop) { // scroll to original table (not sticky clone) window.scrollTo(0, $table.position().top); // give same input/select focus; check if c.$filters exists; fixes #594 if (column >= 0 && c.$filters) { c.$filters.eq(column).find('a, select, input').filter(':visible').focus(); } } }); ts.filter.bindSearch( $table, $stickyCells.find('.' + ts.css.filter) ); // support hideFilters if (wo.filter_hideFilters) { ts.filter.hideFilters($stickyTable, c); } } $table.trigger('stickyHeadersInit'); }, remove: function(table, c, wo) { var namespace = c.namespace + 'stickyheaders '; c.$table .removeClass('hasStickyHeaders') .unbind( 'pagerComplete filterEnd '.split(' ').join(namespace) ) .next('.' + ts.css.stickyWrap).remove(); if (wo.$sticky && wo.$sticky.length) { wo.$sticky.remove(); } // remove cloned table // don't unbind if any table on the page still has stickyheaders applied if (!$('.hasStickyHeaders').length) { $(window).add(wo.stickyHeaders_xScroll).add(wo.stickyHeaders_yScroll).add(wo.stickyHeaders_attachTo) .unbind( 'scroll resize '.split(' ').join(namespace) ); } ts.addHeaderResizeEvent(table, false); } }); // Add Column resizing widget // this widget saves the column widths if // $.tablesorter.storage function is included // ************************** ts.addWidget({ id: "resizable", priority: 40, options: { resizable : true, resizable_addLastColumn : false, resizable_widths : [], resizable_throttle : false // set to true (5ms) or any number 0-10 range }, format: function(table, c, wo) { if (c.$table.hasClass('hasResizable')) { return; } c.$table.addClass('hasResizable'); ts.resizableReset(table, true); // set default widths var $rows, $columns, $column, column, timer, storedSizes = {}, $table = c.$table, $wrap = $table.parent(), overflow = $table.parent().css('overflow') === 'auto', mouseXPosition = 0, $target = null, $next = null, fullWidth = Math.abs($table.parent().width() - $table.width()) < 20, mouseMove = function(event){ if (mouseXPosition === 0 || !$target) { return; } // resize columns var leftEdge = event.pageX - mouseXPosition, targetWidth = $target.width(); $target.width( targetWidth + leftEdge ); if ($target.width() !== targetWidth && fullWidth) { $next.width( $next.width() - leftEdge ); } else if (overflow) { $table.width(function(i, w){ return w + leftEdge; }); if (!$next.length) { // if expanding right-most column, scroll the wrapper $wrap[0].scrollLeft = $table.width(); } } mouseXPosition = event.pageX; }, stopResize = function() { if (ts.storage && $target && $next) { storedSizes = {}; storedSizes[$target.index()] = $target.width(); storedSizes[$next.index()] = $next.width(); $target.width( storedSizes[$target.index()] ); $next.width( storedSizes[$next.index()] ); if (wo.resizable !== false) { // save all column widths ts.storage(table, 'tablesorter-resizable', c.$headers.map(function(){ return $(this).width(); }).get() ); } } mouseXPosition = 0; $target = $next = null; $(window).trigger('resize'); // will update stickyHeaders, just in case }; storedSizes = (ts.storage && wo.resizable !== false) ? ts.storage(table, 'tablesorter-resizable') : {}; // process only if table ID or url match if (storedSizes) { for (column in storedSizes) { if (!isNaN(column) && column < c.$headers.length) { c.$headers.eq(column).width(storedSizes[column]); // set saved resizable widths } } } $rows = $table.children('thead:first').children('tr'); // add resizable-false class name to headers (across rows as needed) $rows.children().each(function() { var canResize, $column = $(this); column = $column.attr('data-column'); canResize = ts.getData( $column, ts.getColumnData( table, c.headers, column ), 'resizable') === "false"; $rows.children().filter('[data-column="' + column + '"]')[canResize ? 'addClass' : 'removeClass']('resizable-false'); }); // add wrapper inside each cell to allow for positioning of the resizable target block $rows.each(function() { $column = $(this).children().not('.resizable-false'); if (!$(this).find('.' + ts.css.wrapper).length) { // Firefox needs this inner div to position the resizer correctly $column.wrapInner('<div class="' + ts.css.wrapper + '" style="position:relative;height:100%;width:100%"></div>'); } // don't include the last column of the row if (!wo.resizable_addLastColumn) { $column = $column.slice(0,-1); } $columns = $columns ? $columns.add($column) : $column; }); $columns .each(function() { var $column = $(this), padding = parseInt($column.css('padding-right'), 10) + 10; // 10 is 1/2 of the 20px wide resizer $column .find('.' + ts.css.wrapper) .append('<div class="' + ts.css.resizer + '" style="cursor:w-resize;position:absolute;z-index:1;right:-' + padding + 'px;top:0;height:100%;width:20px;"></div>'); }) .find('.' + ts.css.resizer) .bind('mousedown', function(event) { // save header cell and mouse position $target = $(event.target).closest('th'); var $header = c.$headers.filter('[data-column="' + $target.attr('data-column') + '"]'); if ($header.length > 1) { $target = $target.add($header); } // if table is not as wide as it's parent, then resize the table $next = event.shiftKey ? $target.parent().find('th').not('.resizable-false').filter(':last') : $target.nextAll(':not(.resizable-false)').eq(0); mouseXPosition = event.pageX; }); $(document) .bind('mousemove.tsresize', function(event) { // ignore mousemove if no mousedown if (mouseXPosition === 0 || !$target) { return; } if (wo.resizable_throttle) { clearTimeout(timer); timer = setTimeout(function(){ mouseMove(event); }, isNaN(wo.resizable_throttle) ? 5 : wo.resizable_throttle ); } else { mouseMove(event); } }) .bind('mouseup.tsresize', function() { stopResize(); }); // right click to reset columns to default widths $table.find('thead:first').bind('contextmenu.tsresize', function() { ts.resizableReset(table); // $.isEmptyObject() needs jQuery 1.4+; allow right click if already reset var allowClick = $.isEmptyObject ? $.isEmptyObject(storedSizes) : true; storedSizes = {}; return allowClick; }); }, remove: function(table, c) { c.$table .removeClass('hasResizable') .children('thead') .unbind('mouseup.tsresize mouseleave.tsresize contextmenu.tsresize') .children('tr').children() .unbind('mousemove.tsresize mouseup.tsresize') // don't remove "tablesorter-wrapper" as uitheme uses it too .find('.' + ts.css.resizer).remove(); ts.resizableReset(table); } }); ts.resizableReset = function(table, nosave) { $(table).each(function(){ var $t, c = this.config, wo = c && c.widgetOptions; if (table && c) { c.$headers.each(function(i){ $t = $(this); if (wo.resizable_widths[i]) { $t.css('width', wo.resizable_widths[i]); } else if (!$t.hasClass('resizable-false')) { // don't clear the width of any column that is not resizable $t.css('width',''); } }); if (ts.storage && !nosave) { ts.storage(this, 'tablesorter-resizable', {}); } } }); }; // Save table sort widget // this widget saves the last sort only if the // saveSort widget option is true AND the // $.tablesorter.storage function is included // ************************** ts.addWidget({ id: 'saveSort', priority: 20, options: { saveSort : true }, init: function(table, thisWidget, c, wo) { // run widget format before all other widgets are applied to the table thisWidget.format(table, c, wo, true); }, format: function(table, c, wo, init) { var stored, time, $table = c.$table, saveSort = wo.saveSort !== false, // make saveSort active/inactive; default to true sortList = { "sortList" : c.sortList }; if (c.debug) { time = new Date(); } if ($table.hasClass('hasSaveSort')) { if (saveSort && table.hasInitialized && ts.storage) { ts.storage( table, 'tablesorter-savesort', sortList ); if (c.debug) { ts.benchmark('saveSort widget: Saving last sort: ' + c.sortList, time); } } } else { // set table sort on initial run of the widget $table.addClass('hasSaveSort'); sortList = ''; // get data if (ts.storage) { stored = ts.storage( table, 'tablesorter-savesort' ); sortList = (stored && stored.hasOwnProperty('sortList') && $.isArray(stored.sortList)) ? stored.sortList : ''; if (c.debug) { ts.benchmark('saveSort: Last sort loaded: "' + sortList + '"', time); } $table.bind('saveSortReset', function(event) { event.stopPropagation(); ts.storage( table, 'tablesorter-savesort', '' ); }); } // init is true when widget init is run, this will run this widget before all other widgets have initialized // this method allows using this widget in the original tablesorter plugin; but then it will run all widgets twice. if (init && sortList && sortList.length > 0) { c.sortList = sortList; } else if (table.hasInitialized && sortList && sortList.length > 0) { // update sort change $table.trigger('sorton', [sortList]); } } }, remove: function(table) { // clear storage if (ts.storage) { ts.storage( table, 'tablesorter-savesort', '' ); } } }); })(jQuery, window);<|fim▁end|>
return filter === '' ? true : !(c.widgetOptions.filter_startsWith ? indx === 0 : indx >= 0);
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from app import app from flask import render_template @app.route('/') def index(): return render_template('index.html') @app.route('/story/') def story(): return render_template('story.html') @app.route('/bio/') def bio():<|fim▁hole|> return render_template('contact.html') # @app.route('/fun/') # def fun(): # return render_template('fun.html') # @app.route('/portfolio/') # def portfolio(): # return render_template('portfolio.html') # @app.route('/boot_index/') # def boot_index(): # return render_template('bootstrap_index.html')<|fim▁end|>
return render_template('bio.html') @app.route('/contact/') def contact():
<|file_name|>stream_frame_identifier.py<|end_file_name|><|fim▁begin|>import av import logging import random import sys import time import warnings from livestreamer import Livestreamer from experiments.test_detecting_in_lol_or_not import get_classifier, process_image from ocr import ocr_image logging.getLogger("libav.http").setLevel(logging.ERROR) # Hide warnings from SKLearn from flooding screen warnings.filterwarnings("ignore", category=DeprecationWarning) if __name__ == "__main__": if len(sys.argv) > 1: streamer = sys.argv[1] else: print "Randomly selecting a streamer..." streamer = random.choice(( "tsm_doublelift", "grossie_gore", "wingsofdeath" )) classifier = get_classifier() is_in_lol = False print "Waiting for streamer %s to join a game..." % streamer while True: session = Livestreamer() streams = session.streams('http://www.twitch.tv/%s' % streamer) if streams: stream = streams['source'] container = av.open(stream.url) video_stream = next(s for s in container.streams if s.type == b'video') image = None for packet in container.demux(video_stream): for frame in packet.decode(): image = frame.to_image() features = process_image(image) # save our old state before checking new state, only show message when state changes old_is_in_lol = is_in_lol<|fim▁hole|> is_in_lol = classifier.predict(features) if not old_is_in_lol and is_in_lol: timestr = time.strftime("%Y%m%d-%I:%M %p") print "@@@@@@@@@@ Joined game: %s" % timestr elif old_is_in_lol and not is_in_lol: timestr = time.strftime("%Y%m%d-%I:%M %p") print "@@@@@@@@@@ Left game: %s" % timestr if is_in_lol: print "OCR from image, trying to read character name:", ocr_image(image) # As soon as we get a full image, we're done if image: break time.sleep(1) else: print "Player not streaming, sleeping for 15 minutes" time.sleep(15 * 60)<|fim▁end|>
<|file_name|>qdelegatingnamespaceresolver.cpp<|end_file_name|><|fim▁begin|>/**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtXmlPatterns module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qnamepool_p.h" #include "qdelegatingnamespaceresolver_p.h" QT_BEGIN_NAMESPACE using namespace QPatternist; DelegatingNamespaceResolver::DelegatingNamespaceResolver(const NamespaceResolver::Ptr &resolver) : m_nsResolver(resolver) { Q_ASSERT(m_nsResolver); } DelegatingNamespaceResolver::DelegatingNamespaceResolver(const NamespaceResolver::Ptr &ns, const Bindings &overrides) : m_nsResolver(ns) , m_bindings(overrides) { Q_ASSERT(m_nsResolver); }<|fim▁hole|>{ const QXmlName::NamespaceCode val(m_bindings.value(prefix, NoBinding)); if(val == NoBinding) return m_nsResolver->lookupNamespaceURI(prefix); else return val; } NamespaceResolver::Bindings DelegatingNamespaceResolver::bindings() const { Bindings bs(m_nsResolver->bindings()); const Bindings::const_iterator end(m_bindings.constEnd()); Bindings::const_iterator it(m_bindings.constBegin()); for(; it != end; ++it) bs.insert(it.key(), it.value()); return bs; } void DelegatingNamespaceResolver::addBinding(const QXmlName nb) { if(nb.namespaceURI() == StandardNamespaces::UndeclarePrefix) m_bindings.remove(nb.prefix()); else m_bindings.insert(nb.prefix(), nb.namespaceURI()); } QT_END_NAMESPACE<|fim▁end|>
QXmlName::NamespaceCode DelegatingNamespaceResolver::lookupNamespaceURI(const QXmlName::PrefixCode prefix) const
<|file_name|>_connectors.py<|end_file_name|><|fim▁begin|>"""Connectors""" __copyright__ = "Copyright (C) 2014 Ivan D Vasin" __docformat__ = "restructuredtext" import abc as _abc import re as _re from ... import plain as _plain from .. import _std as _std_http _BASIC_USER_TOKENS = ('user', 'password') class HttpBasicClerk(_std_http.HttpStandardClerk): """An authentication clerk for HTTP Basic authentication""" __metaclass__ = _abc.ABCMeta _BASIC_USER_TOKENS = _BASIC_USER_TOKENS def _inputs(self, upstream_affordances, downstream_affordances): return ((),) def _append_response_auth_challenge(self, realm, input=None, affordances=None): self._append_response_auth_challenge_header('Basic realm="{}"' .format(realm))<|fim▁hole|> return (_BASIC_USER_TOKENS,) def _provisionsets(self, upstream_affordances, downstream_affordances): return (_plain.PlainAuth.PROVISIONS,) class HttpBasicScanner(_std_http.HttpStandardScanner): """An authentication scanner for HTTP Basic authentication""" __metaclass__ = _abc.ABCMeta _AUTHORIZATION_HEADER_RE = \ _re.compile(r'\s*Basic\s*(?P<creds_base64>[^\s]*)') _BASIC_USER_TOKENS = _BASIC_USER_TOKENS def _outputs(self, upstream_affordances, downstream_affordances): return (self._BASIC_USER_TOKENS,) def _provisionsets(self, upstream_affordances, downstream_affordances): return (_plain.PlainAuth.PROVISIONS,)<|fim▁end|>
def _outputs(self, upstream_affordances, downstream_affordances):
<|file_name|>composer.py<|end_file_name|><|fim▁begin|>from yaml.composer import Composer from yaml.nodes import MappingNode class AnsibleComposer(Composer): def __init__(self): self.__mapping_starts = [] super(Composer, self).__init__() def compose_node(self, parent, index): # the line number where the previous token has ended (plus empty lines) node = Composer.compose_node(self, parent, index) if isinstance(node, MappingNode): node.__datasource__ = self.name try: (cur_line, cur_column) = self.__mapping_starts.pop() except: cur_line = None cur_column = None<|fim▁hole|> return node def compose_mapping_node(self, anchor): # the column here will point at the position in the file immediately # after the first key is found, which could be a space or a newline. # We could back this up to find the beginning of the key, but this # should be good enough to determine the error location. self.__mapping_starts.append((self.line + 1, self.column + 1)) return Composer.compose_mapping_node(self, anchor)<|fim▁end|>
node.__line__ = cur_line node.__column__ = cur_column
<|file_name|>app.js<|end_file_name|><|fim▁begin|>var express = require('express'), compression = require('compression'), path = require('path'), favicon = require('serve-favicon'), logger = require('morgan'), cookieParser = require('cookie-parser'), bodyParser = require('body-parser'), session = require('express-session'), session = require('express-session'), flash = require('connect-flash'), moment = require('moment'), mongoose = require('mongoose'), MongoStore = require('connect-mongo')(session), Pclog = require('./models/pclog.js'), configDB = require('./config/database.js'); mongoose.Promise = global.Promise = require('bluebird'); mongoose.connect(configDB.uri); var routes = require('./routes/index'), reports = require('./routes/reports'), statistics = require('./routes/statistics'), charts = require('./routes/charts'), logs = require('./routes/logs'),<|fim▁hole|> users = require('./routes/users'); var app = express(); //var rootFolder = __dirname; // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); app.use(compression()); // uncomment after placing your favicon in /public app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(session({ secret: 'safe_session_cat', resave: true, rolling: true, saveUninitialized: false, cookie: {secure: false, maxAge: 900000}, store: new MongoStore({ url: configDB.uri }) })); app.use(flash()); app.use(express.static(path.join(__dirname, 'public'))); app.use('/', function(req,res,next){ app.locals.currentUrl = req.path; app.locals.moment = moment; res.locals.messages = require('express-messages')(req, res); if(req.session & req.session.user){ app.locals.user = req.session.user; } console.log(app.locals.user); next(); }); app.use('/', routes); app.use('/reports', reports); app.use('/statistics', statistics); app.use('/charts', charts); app.use('/logs', logs); app.use('/organization', organization); app.use('/users', users); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Page Not Found.'); err.status = 404; next(err); }); // error handlers // development error handler // will print stacktrace // if (app.get('env') === 'development') { // app.use(function(err, req, res, next) { // res.status(err.status || 500); // res.render('error', { // message: err.message, // error: err // }); // }); // } // production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { if(err.status){ res.status(err.status); }else{ err.status = 500; err.message = "Internal Server Error." res.status(500); } res.render('404', {error: err}); }); module.exports = app;<|fim▁end|>
organization = require('./routes/organization'),
<|file_name|>flyaround_cube_animate.py<|end_file_name|><|fim▁begin|>import os import numpy as np import matplotlib.pyplot as plt from hyperion.model import ModelOutput from hyperion.util.constants import pc # Create output directory if it does not already exist if not os.path.exists('frames'): os.mkdir('frames') # Open model m = ModelOutput('flyaround_cube.rtout') # Read image from model image = m.get_image(distance=300 * pc, units='MJy/sr') # image.val is now an array with four dimensions (n_view, n_y, n_x, n_wav) for iview in range(image.val.shape[0]): # Open figure and create axes fig = plt.figure(figsize=(3, 3)) ax = fig.add_subplot(1, 1, 1) # This is the command to show the image. The parameters vmin and vmax are # the min and max levels for the grayscale (remove for default values). # The colormap is set here to be a heat map. Other possible heat maps # include plt.cm.gray (grayscale), plt.cm.gist_yarg (inverted grayscale), # plt.cm.jet (default, colorful). The np.sqrt() is used to plot the # images on a sqrt stretch. ax.imshow(np.sqrt(image.val[iview, :, :, 0]), vmin=0, vmax=np.sqrt(2000.), cmap=plt.cm.gist_heat, origin='lower') # Save figure. The facecolor='black' and edgecolor='black' are for # esthetics, and hide the axes fig.savefig('frames/frame_%05i.png' % iview, facecolor='black', edgecolor='black')<|fim▁hole|><|fim▁end|>
# Close figure plt.close(fig)
<|file_name|>unary.rs<|end_file_name|><|fim▁begin|>//! Module implementing evaluation of unary operator AST nodes. use eval::{self, api, Eval, Context, Value}; use parse::ast::UnaryOpNode; impl Eval for UnaryOpNode { fn eval(&self, context: &mut Context) -> eval::Result { let arg = try!(self.arg.eval(context)); match &self.op[..] { "+" => UnaryOpNode::eval_plus(arg), "-" => UnaryOpNode::eval_minus(arg), "!" => UnaryOpNode::eval_bang(arg), _ => Err(eval::Error::new( &format!("unknown unary operator: `{}`", self.op) )) } }<|fim▁hole|> fn eval_plus(arg: Value) -> eval::Result { eval1!(arg : Integer { arg }); eval1!(arg : Float { arg }); UnaryOpNode::err("+", &arg) } /// Evaluate the "-" operator for one value. fn eval_minus(arg: Value) -> eval::Result { eval1!(arg : Integer { -arg }); eval1!(arg : Float { -arg }); UnaryOpNode::err("-", &arg) } /// Evaluate the "!" operator for one value. #[inline] fn eval_bang(arg: Value) -> eval::Result { let arg = try!(api::conv::bool(arg)).unwrap_bool(); Ok(Value::Boolean(!arg)) } } impl UnaryOpNode { /// Produce an error about invalid argument for an operator. #[inline] fn err(op: &str, arg: &Value) -> eval::Result { Err(eval::Error::new(&format!( "invalid argument for `{}` operator: `{:?}`", op, arg ))) } }<|fim▁end|>
} impl UnaryOpNode { /// Evaluate the "+" operator for one value.
<|file_name|>isDate.js<|end_file_name|><|fim▁begin|>"use strict"; exports.__esModule = true;<|fim▁hole|> function isDate(value) { return value instanceof Date && !isNaN(+value); } //# sourceMappingURL=isDate.js.map module.exports = exports["default"]; //# sourceMappingURL=isDate.js.map<|fim▁end|>
exports["default"] = isDate;
<|file_name|>DataUtilsTest.java<|end_file_name|><|fim▁begin|>package ca.six.tomato.util; import org.json.JSONArray; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import org.robolectric.shadows.ShadowEnvironment; import java.io.File; import ca.six.tomato.BuildConfig; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNotNull; import static junit.framework.Assert.assertTrue; <|fim▁hole|>@RunWith(RobolectricTestRunner.class) @Config(constants = BuildConfig.class, sdk = 21) public class DataUtilsTest { @Test public void testFile() { File dstFile = ShadowEnvironment.getExternalStorageDirectory(); assertTrue(dstFile.exists()); System.out.println("szw isDirectory = " + dstFile.isDirectory()); //=> true System.out.println("szw isExisting = " + dstFile.exists()); //=> true System.out.println("szw path = " + dstFile.getPath()); //=> C:\Users\***\AppData\Local\Temp\android-tmp-robolectric7195966122073188215 } @Test public void testWriteString(){ File dstFile = ShadowEnvironment.getExternalStorageDirectory(); String path = dstFile.getPath() +"/tmp"; DataUtilKt.write("abc", path); String ret = DataUtilKt.read(path, false); assertEquals("abc", ret); } @Test public void testWriteJSON(){ File dstFile = ShadowEnvironment.getExternalStorageDirectory(); String path = dstFile.getPath() +"/tmp"; String content = " {\"clock\": \"clock1\", \"work\": 40, \"short\": 5, \"long\": 15}\n" + " {\"clock\": \"clock2\", \"work\": 30, \"short\": 5, \"long\": 15}\n" + " {\"clock\": \"clock3\", \"work\": 45, \"short\": 5, \"long\": 15}"; DataUtilKt.write(content, path); JSONArray ret = DataUtilKt.read(path); System.out.println("szw, ret = "+ret.toString()); assertNotNull(ret); } }<|fim▁end|>
/** * Created by songzhw on 2016-10-03 */
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// //! COSE_Key functionality. use crate::{ cbor::value::Value, common::AsCborValue, iana, iana::EnumI64, util::{to_cbor_array, ValueTryAs}, Algorithm, CoseError, Label, Result, }; use alloc::{collections::BTreeSet, vec, vec::Vec}; #[cfg(test)] mod tests; /// Key type. pub type KeyType = crate::RegisteredLabel<iana::KeyType>; impl Default for KeyType { fn default() -> Self { KeyType::Assigned(iana::KeyType::Reserved) } } /// Key operation. pub type KeyOperation = crate::RegisteredLabel<iana::KeyOperation>; /// A collection of [`CoseKey`] objects. #[derive(Clone, Debug, Default, PartialEq)] pub struct CoseKeySet(pub Vec<CoseKey>); impl crate::CborSerializable for CoseKeySet {} impl AsCborValue for CoseKeySet { fn from_cbor_value(value: Value) -> Result<Self> { Ok(Self( value.try_as_array_then_convert(CoseKey::from_cbor_value)?, )) } fn to_cbor_value(self) -> Result<Value> { to_cbor_array(self.0) } } /// Structure representing a cryptographic key. /// /// ```cddl /// COSE_Key = { /// 1 => tstr / int, ; kty /// ? 2 => bstr, ; kid /// ? 3 => tstr / int, ; alg /// ? 4 => [+ (tstr / int) ], ; key_ops /// ? 5 => bstr, ; Base IV /// * label => values /// } /// ``` #[derive(Clone, Debug, Default, PartialEq)] pub struct CoseKey { /// Key type identification. pub kty: KeyType, /// Key identification. pub key_id: Vec<u8>, /// Key use restriction to this algorithm. pub alg: Option<Algorithm>, /// Restrict set of possible operations. pub key_ops: BTreeSet<KeyOperation>, /// Base IV to be xor-ed with partial IVs. pub base_iv: Vec<u8>, /// Any additional parameter (label,value) pairs. If duplicate labels are present, /// CBOR-encoding will fail. pub params: Vec<(Label, Value)>, } impl crate::CborSerializable for CoseKey {} const KTY: Label = Label::Int(iana::KeyParameter::Kty as i64); const KID: Label = Label::Int(iana::KeyParameter::Kid as i64); const ALG: Label = Label::Int(iana::KeyParameter::Alg as i64); const KEY_OPS: Label = Label::Int(iana::KeyParameter::KeyOps as i64); const BASE_IV: Label = Label::Int(iana::KeyParameter::BaseIv as i64); impl AsCborValue for CoseKey { fn from_cbor_value(value: Value) -> Result<Self> { let m = value.try_as_map()?; let mut key = Self::default(); let mut seen = BTreeSet::new(); for (l, value) in m.into_iter() { // The `ciborium` CBOR library does not police duplicate map keys. // RFC 8152 section 14 requires that COSE does police duplicates, so do it here. let label = Label::from_cbor_value(l)?; if seen.contains(&label) { return Err(CoseError::DuplicateMapKey); } seen.insert(label.clone()); match label { KTY => key.kty = KeyType::from_cbor_value(value)?, KID => { key.key_id = value.try_as_nonempty_bytes()?; } ALG => key.alg = Some(Algorithm::from_cbor_value(value)?), KEY_OPS => { let key_ops = value.try_as_array()?; for key_op in key_ops.into_iter() { if !key.key_ops.insert(KeyOperation::from_cbor_value(key_op)?) { return Err(CoseError::UnexpectedItem( "repeated array entry", "unique array label", )); } } if key.key_ops.is_empty() { return Err(CoseError::UnexpectedItem("empty array", "non-empty array")); } } BASE_IV => { key.base_iv = value.try_as_nonempty_bytes()?; } label => key.params.push((label, value)), } } // Check that key type has been set. if key.kty == KeyType::Assigned(iana::KeyType::Reserved) { return Err(CoseError::UnexpectedItem( "no kty label", "mandatory kty label", )); } Ok(key) } fn to_cbor_value(self) -> Result<Value> { let mut map: Vec<(Value, Value)> = vec![(KTY.to_cbor_value()?, self.kty.to_cbor_value()?)]; if !self.key_id.is_empty() { map.push((KID.to_cbor_value()?, Value::Bytes(self.key_id))); } if let Some(alg) = self.alg { map.push((ALG.to_cbor_value()?, alg.to_cbor_value()?)); } if !self.key_ops.is_empty() { map.push((KEY_OPS.to_cbor_value()?, to_cbor_array(self.key_ops)?)); } if !self.base_iv.is_empty() { map.push((BASE_IV.to_cbor_value()?, Value::Bytes(self.base_iv))); } let mut seen = BTreeSet::new(); for (label, value) in self.params { if seen.contains(&label) { return Err(CoseError::DuplicateMapKey); } seen.insert(label.clone()); map.push((label.to_cbor_value()?, value)); } Ok(Value::Map(map)) } } /// Builder for [`CoseKey`] objects. #[derive(Debug, Default)] pub struct CoseKeyBuilder(CoseKey); impl CoseKeyBuilder { builder! {CoseKey} builder_set! {key_id: Vec<u8>} builder_set! {base_iv: Vec<u8>} /// Constructor for an elliptic curve public key specified by `x` and `y` coordinates. pub fn new_ec2_pub_key(curve: iana::EllipticCurve, x: Vec<u8>, y: Vec<u8>) -> Self { Self(CoseKey { kty: KeyType::Assigned(iana::KeyType::EC2), params: vec![ ( Label::Int(iana::Ec2KeyParameter::Crv as i64), Value::from(curve as u64), ), (Label::Int(iana::Ec2KeyParameter::X as i64), Value::Bytes(x)), (Label::Int(iana::Ec2KeyParameter::Y as i64), Value::Bytes(y)), ], ..Default::default() }) } /// Constructor for an elliptic curve public key specified by `x` coordinate plus sign of `y` /// coordinate. pub fn new_ec2_pub_key_y_sign(curve: iana::EllipticCurve, x: Vec<u8>, y_sign: bool) -> Self { Self(CoseKey { kty: KeyType::Assigned(iana::KeyType::EC2), params: vec![ ( Label::Int(iana::Ec2KeyParameter::Crv as i64), Value::from(curve as u64), ), (Label::Int(iana::Ec2KeyParameter::X as i64), Value::Bytes(x)), ( Label::Int(iana::Ec2KeyParameter::Y as i64), Value::Bool(y_sign), ), ], ..Default::default() }) } /// Constructor for an elliptic curve private key specified by `d`, together with public `x` and /// `y` coordinates. pub fn new_ec2_priv_key( curve: iana::EllipticCurve, x: Vec<u8>, y: Vec<u8>, d: Vec<u8>,<|fim▁hole|> ) -> Self { let mut builder = Self::new_ec2_pub_key(curve, x, y); builder .0 .params .push((Label::Int(iana::Ec2KeyParameter::D as i64), Value::Bytes(d))); builder } /// Constructor for a symmetric key specified by `k`. pub fn new_symmetric_key(k: Vec<u8>) -> Self { Self(CoseKey { kty: KeyType::Assigned(iana::KeyType::Symmetric), params: vec![( Label::Int(iana::SymmetricKeyParameter::K as i64), Value::Bytes(k), )], ..Default::default() }) } /// Set the algorithm. #[must_use] pub fn algorithm(mut self, alg: iana::Algorithm) -> Self { self.0.alg = Some(Algorithm::Assigned(alg)); self } /// Add a key operation. #[must_use] pub fn add_key_op(mut self, op: iana::KeyOperation) -> Self { self.0.key_ops.insert(KeyOperation::Assigned(op)); self } /// Set a parameter value. /// /// # Panics /// /// This function will panic if it used to set a parameter label from the [`iana::KeyParameter`] /// range. #[must_use] pub fn param(mut self, label: i64, value: Value) -> Self { if iana::KeyParameter::from_i64(label).is_some() { panic!("param() method used to set KeyParameter"); // safe: invalid input } self.0.params.push((Label::Int(label), value)); self } }<|fim▁end|>
<|file_name|>HighPassFilter.py<|end_file_name|><|fim▁begin|>'''Created by rj as part of the Pytnam Project''' from analysis.Reportable import Reportable <|fim▁hole|> pass # TODO<|fim▁end|>
class HighPassFilter(Reportable): def return_as_node(self):
<|file_name|>FinancialInstrument11.go<|end_file_name|><|fim▁begin|>package iso20022 // Security that is a sub-set of an investment fund, and is governed by the same investment fund policy, eg, dividend option or valuation currency. type FinancialInstrument11 struct { // Unique and unambiguous identifier of a security, assigned under a formal or proprietary identification scheme. Identification *SecurityIdentification3Choice `xml:"Id"` // Name of the financial instrument in free format text. Name *Max350Text `xml:"Nm,omitempty"` // Specifies whether the financial instrument is transferred as an asset or as cash.<|fim▁hole|>func (f *FinancialInstrument11) AddIdentification() *SecurityIdentification3Choice { f.Identification = new(SecurityIdentification3Choice) return f.Identification } func (f *FinancialInstrument11) SetName(value string) { f.Name = (*Max350Text)(&value) } func (f *FinancialInstrument11) SetTransferType(value string) { f.TransferType = (*TransferType1Code)(&value) }<|fim▁end|>
TransferType *TransferType1Code `xml:"TrfTp"` }
<|file_name|>haiku.ts<|end_file_name|><|fim▁begin|>export const font = [ [0x00,0x00,0x00,0x00,0x00,0x00], // [0x00,0x5e,0x00,0x00,0x00,0x00], // ! [0x00,0x0e,0x0e,0x00,0x00,0x00], // " [0x00,0x7f,0x40,0x40,0x7f,0x00], // # [0x00,0x7e,0x52,0xd2,0x52,0x76], // $ [0x00,0x7f,0x40,0x40,0x7f,0x00], // % [0x00,0x70,0x7c,0x52,0x7e,0x40], // & [0x00,0x0e,0x00,0x00,0x00,0x00], // ' [0x00,0xfe,0x82,0x00,0x00,0x00], // ( <|fim▁hole|> [0x00,0x10,0x10,0x10,0x00,0x00], // - [0x00,0x40,0x00,0x00,0x00,0x00], // . [0x00,0xfe,0x00,0x00,0x00,0x00], // / [0x00,0x7e,0x42,0x7e,0x00,0x00], // 0 [0x00,0x02,0x7e,0x00,0x00,0x00], // 1 [0x00,0x76,0x52,0x52,0x7e,0x00], // 2 [0x00,0x66,0x42,0x52,0x7e,0x42], // 3 [0x00,0x1e,0x50,0x78,0x50,0x00], // 4 [0x00,0x7e,0x52,0x52,0x72,0x00], // 5 [0x00,0x7e,0x52,0x52,0x76,0x00], // 6 [0x00,0x06,0x02,0x42,0x7e,0x42], // 7 [0x00,0x7e,0x52,0x52,0x7e,0x00], // 8 [0x00,0x7e,0x52,0x52,0x7e,0x00], // 9 [0x00,0x50,0x00,0x00,0x00,0x00], // : [0x00,0x90,0x00,0x00,0x00,0x00], // ; [0x00,0x7f,0x40,0x40,0x7f,0x00], // < [0x00,0x18,0x18,0x18,0x00,0x00], // = [0x00,0x7f,0x40,0x40,0x7f,0x00], // > [0x00,0x06,0x72,0x12,0x1e,0x00], // ? [0x00,0x78,0x48,0x78,0x48,0x00], // @ [0x00,0x42,0x7e,0x12,0x12,0x7e], // A [0x00,0x52,0x7e,0x52,0x5e,0x70], // B [0x00,0x42,0x7e,0x42,0x42,0xe6], // C [0x00,0x42,0x7e,0x42,0x42,0x7e], // D [0x00,0x42,0x7e,0x5a,0x42,0xe6], // E [0x42,0x7e,0x52,0x3a,0x02,0x06], // F [0x00,0x42,0x7e,0x42,0x52,0x76], // G [0x00,0x42,0x7e,0x10,0x10,0x7e], // H [0x00,0x42,0x7e,0x42,0x00,0x00], // I [0x00,0x02,0xfe,0x02,0x00,0x00], // J [0x00,0x52,0x7e,0x10,0x1e,0x72], // K [0x00,0x42,0x7e,0x42,0x40,0xe0], // L [0x00,0x42,0x7e,0x02,0xfe,0x02], // M [0x42,0x42,0x7e,0x02,0x02,0x7e], // N [0x00,0x7e,0x42,0x42,0x7e,0x00], // O [0x00,0x52,0x7e,0x52,0x12,0x1e], // P [0x00,0x7e,0x42,0xc2,0x7e,0x00], // Q [0x00,0x52,0x7e,0x52,0x32,0x5e], // R [0x00,0xfe,0x52,0x52,0x76,0x00], // S [0x00,0x06,0x42,0x7e,0x42,0x02], // T [0x00,0x42,0x7e,0x40,0x40,0x7e], // U [0x00,0x02,0x1e,0x20,0x20,0x1e], // V [0x00,0x02,0x7e,0x40,0x7e,0x40], // W [0x02,0x42,0x6e,0x10,0x10,0x6e], // X [0x02,0x1e,0x50,0x70,0x50,0x1e], // Y [0x66,0x52,0x4a,0x4a,0xe6,0x00], // Z [0x00,0xfe,0x82,0x00,0x00,0x00], // [ [0x00,0x7f,0x40,0x40,0x7f,0x00], // "\" [0x00,0x82,0xfe,0x00,0x00,0x00], // ] [0x00,0x7f,0x40,0x40,0x7f,0x00], // ^ [0x00,0x40,0x40,0x40,0x00,0x00], // _ [0x00,0x7f,0x40,0x40,0x7f,0x00], // ` [0x00,0x70,0x5c,0x58,0x78,0x00], // a [0x00,0x42,0x7e,0x48,0x48,0x78], // b [0x00,0x78,0x48,0x48,0xfc,0x00], // c [0x00,0x78,0x48,0x48,0x7e,0x42], // d [0x00,0x78,0x68,0x68,0xf8,0x00], // e [0x00,0x50,0x7e,0x52,0x00,0x00], // f [0x00,0x78,0x48,0x48,0xf8,0x08], // g [0x00,0x42,0x7e,0x08,0x08,0x78], // h [0x00,0x48,0x7a,0x48,0x00,0x00], // i [0x00,0x08,0xfa,0x08,0x00,0x00], // j [0x00,0x42,0x7e,0x50,0x1c,0x70], // k [0x00,0x42,0x7e,0x40,0x00,0x00], // l [0x00,0x48,0x78,0x08,0xf8,0x08], // m [0x48,0x48,0x78,0x08,0x08,0x78], // n [0x00,0x78,0x48,0x48,0x78,0x00], // o [0x00,0x08,0xf8,0x48,0x48,0x78], // p [0x00,0x78,0x48,0x48,0xf8,0x08], // q [0x00,0x48,0x78,0x48,0x18,0x00], // r [0x00,0xd8,0x58,0x58,0x7c,0x00], // s [0x00,0x08,0x48,0x7e,0x48,0x08], // t [0x00,0x48,0x78,0x40,0x40,0x78], // u [0x08,0x18,0x28,0x40,0x28,0x18], // v [0x00,0x08,0x78,0x40,0x78,0x40], // w [0x08,0x48,0x58,0x20,0x58,0x48], // x [0x00,0x08,0x78,0xc0,0x40,0x78], // y [0x00,0x6c,0x58,0x58,0xc8,0x00], // z [0x00,0x7f,0x40,0x40,0x7f,0x00], // [ [0x00,0xfe,0x00,0x00,0x00,0x00], // | [0x00,0x7f,0x40,0x40,0x7f,0x00], // ] [0x00,0x7f,0x40,0x40,0x7f,0x00], // ~ [0x00,0x00,0x00,0x00,0x00,0x00] ];<|fim▁end|>
[0x00,0x82,0xfe,0x00,0x00,0x00], // ) [0x00,0x14,0x0e,0x14,0x00,0x00], // * [0x10,0x10,0x38,0x10,0x10,0x00], // + [0x00,0xc0,0x00,0x00,0x00,0x00], // ,
<|file_name|>HomeJourney.js<|end_file_name|><|fim▁begin|>/*global QUnit*/ sap.ui.define([ "sap/ui/test/opaQunit", "./pages/Home", "./pages/Overview" ], function (opaTest) { "use strict"; QUnit.module("Home"); opaTest("Should see the homepage displayed", function (Given, When, Then) { // Arrangements Given.iStartMyApp({ hash: "" }); // Assertions Then.onTheHomePage.iShouldSeeSomeFontTiles(); }); opaTest("Should navigate to SAP icon TNT", function (Given, When, Then) { // Actions When.onTheHomePage.iClickOnTheTNTTitleLink(); // Assertions Then.onTheOverviewPage.iShouldSeeTheTNTFontPage(); }); <|fim▁hole|> // Assertions Then.onTheHomePage.iShouldSeeSomeFontTiles(); // Cleanup Then.iTeardownMyApp(); }); });<|fim▁end|>
opaTest("Should be on the Home page when back button is pressed", function (Given, When, Then) { //Actions When.onTheOverviewPage.iPressTheNavigationBackButton();
<|file_name|>measure_dialog.py<|end_file_name|><|fim▁begin|>import datetime as dt import threading from serial_device.or_event import OrEvent import numpy as np import pandas as pd import gobject import gtk import matplotlib as mpl from streaming_plot import StreamingPlot from ...max11210_adc_ui import MAX11210_read import logging def _generate_data(stop_event, data_ready, data): ''' Generate random data to emulate, e.g., reading data from ADC. The function is an example implementation of a ``f_data`` function suitable for use with the :func:`measure_dialog` function. Example usage ------------- The following launches a measurement dialog which plots 5 points every 0.5 seconds, runs for 5 seconds, after which the dialog closes automatically: >>> data = measure_dialog(_generate_data, duration_s=5000, auto_close=True) Parameters ---------- stop_event : threading.Event Function returns when :data:`stop_event` is set. data_ready : threading.Event Function sets :data:`data_ready` whenever new data is available. data : list Function appends new data to :data:`data` before setting :data:`data_ready`. ''' delta_t = dt.timedelta(seconds=.1) samples_per_plot = 5 while True: time_0 = dt.datetime.now() values_i = np.random.rand(samples_per_plot) absolute_times_i = pd.Series([time_0 + i * delta_t for i in xrange(len(values_i))]) data_i = pd.Series(values_i, index=absolute_times_i) data.append(data_i) data_ready.set() if stop_event.wait(samples_per_plot * delta_t.total_seconds()): break def measure_dialog(f_data, duration_s=None, auto_start=True, auto_close=True, **kwargs): ''' Launch a GTK dialog and plot data Parameters ---------- f_data : function(stop_event, data_ready, data) Function to run to generate data, e.g., read data from ADC. The function is run in its own thread and is provided the following parameters: - :data:`stop_event` : threading.Event - :data:`data_ready` : threading.Event - :data:`data` : list The function **MUST**: - Return when the :data:`stop_event` is set. - Set :data:`data_ready` event whenever new data is available. duration_s : float, optional Length of time to measure for (in seconds). If duration is not specified, measure until window is closed or ``Pause`` button is pressed. auto_start : bool, optional Automatically start measuring when the dialog is launched. Default is ``True``. auto_close : bool, optional If ``duration_s`` is specified, automatically close window once the measurement duration has passed (unless the ``Pause`` button has been pressed. Default is ``True``. **kwargs : dict<|fim▁hole|> Additional keyword arguments are passed to the construction of the :class:`streaming_plot.StreamingPlot` view. ''' # `StreamingPlot` class uses threads. Need to initialize GTK to use # threads. See [here][1] for more information. # # [1]: http://faq.pygtk.org/index.py?req=show&file=faq20.001.htp gtk.gdk.threads_init() with mpl.style.context('seaborn', {'image.cmap': 'gray', 'image.interpolation' : 'none'}): # Create dialog window to wrap PMT measurement view widget. dialog = gtk.Dialog() dialog.set_default_size(800, 600) view = StreamingPlot(data_func=f_data, **kwargs) dialog.get_content_area().pack_start(view.widget, True, True) dialog.connect('check-resize', lambda *args: view.on_resize()) dialog.set_position(gtk.WIN_POS_MOUSE) dialog.show_all() view.fig.tight_layout() if auto_start: gobject.idle_add(view.start) def _auto_close(*args): if not view.stop_event.is_set(): # User did not explicitly pause the measurement. Automatically # close the measurement and continue. dialog.destroy() measurement_complete = threading.Event() view.widget.connect('destroy', lambda *args: measurement_complete.set()) if duration_s is not None: def _schedule_stop(*args): event = OrEvent(view.stop_event, view.started, measurement_complete) event.wait() if view.started.is_set(): stop_func = _auto_close if auto_close else view.pause gobject.timeout_add(duration_s * 1000, stop_func) stop_schedule_thread = threading.Thread(target=_schedule_stop) stop_schedule_thread.daemon = True stop_schedule_thread.start() dialog.run() dialog.destroy() measurement_complete.wait() if view.data: return pd.concat(view.data) else: return None return False def adc_data_func_factory(proxy, delta_t=dt.timedelta(seconds=1), adc_rate=1, resistor_val = False): ''' Parameters ---------- proxy : mr_box_peripheral_board.SerialProxy delta_t : datetime.timedelta Time between ADC measurements. Returns ------- function Function suitable for use with the :func:`measure_dialog` function. ''' #set the adc digital gain # proxy.MAX11210_setGain(adc_dgain) #Set the pmt shutter pin to output proxy.pin_mode(9, 1) logger = logging.getLogger(__name__) def _read_adc(stop_event, data_ready, data): ''' Parameters ---------- stop_event : threading.Event Function returns when :data:`stop_event` is set. data_ready : threading.Event Function sets :data:`data_ready` whenever new data is available. data : list Function appends new data to :data:`data` before setting :data:`data_ready`. delta_t = dt.timedelta(seconds=.1) ''' #Start the ADC try: proxy.pmt_open_shutter() logger.info('PMT Shutter Opened') adc_dgain = 1 while True: data_i = MAX11210_read(proxy, rate=adc_rate, duration_s=delta_t.total_seconds()) #Convert data to Voltage, 24bit ADC with Vref = 3.0 V data_i /= ((2 ** 24 - 1)/(3.0/adc_dgain)) if (resistor_val): #Convert Voltage to Current, 30kOhm Resistor data_i /= 30e3 else: #Convert Voltage to Current, 300kOhm Resistor data_i /= 300e3 # Set name to display units. data_i.name = 'Current (A)' data.append(data_i) data_ready.set() if stop_event.is_set(): break finally: proxy.pmt_close_shutter() logger.info('PMT Shutter Closed') return _read_adc<|fim▁end|>
<|file_name|>delegates.rs<|end_file_name|><|fim▁begin|>use std::sync::Arc; use std::collections::HashMap; use jsonrpc_core::{Params, Value, Error}; use jsonrpc_core::{BoxFuture, Metadata, RemoteProcedure, RpcMethod, RpcNotification}; use jsonrpc_core::futures::IntoFuture; use jsonrpc_pubsub::{self, SubscriptionId, Subscriber, PubSubMetadata}; struct DelegateAsyncMethod<T, F> { delegate: Arc<T>, closure: F, } impl<T, M, F, I> RpcMethod<M> for DelegateAsyncMethod<T, F> where M: Metadata, F: Fn(&T, Params) -> I, I: IntoFuture<Item = Value, Error = Error>, T: Send + Sync + 'static, F: Send + Sync + 'static, I::Future: Send + 'static, { fn call(&self, params: Params, _meta: M) -> BoxFuture<Value> { let closure = &self.closure; Box::new(closure(&self.delegate, params).into_future()) } } struct DelegateMethodWithMeta<T, F> { delegate: Arc<T>, closure: F, } impl<T, M, F, I> RpcMethod<M> for DelegateMethodWithMeta<T, F> where M: Metadata, F: Fn(&T, Params, M) -> I, I: IntoFuture<Item = Value, Error = Error>, T: Send + Sync + 'static, F: Send + Sync + 'static, I::Future: Send + 'static, { fn call(&self, params: Params, meta: M) -> BoxFuture<Value> { let closure = &self.closure; Box::new(closure(&self.delegate, params, meta).into_future()) } } struct DelegateNotification<T, F> { delegate: Arc<T>, closure: F, } impl<T, M, F> RpcNotification<M> for DelegateNotification<T, F> where F: Fn(&T, Params) + 'static, F: Send + Sync + 'static, T: Send + Sync + 'static, M: Metadata, { fn execute(&self, params: Params, _meta: M) { let closure = &self.closure; closure(&self.delegate, params) } } struct DelegateSubscribe<T, F> { delegate: Arc<T>, closure: F, } impl<T, M, F> jsonrpc_pubsub::SubscribeRpcMethod<M> for DelegateSubscribe<T, F> where M: PubSubMetadata, F: Fn(&T, Params, M, Subscriber), T: Send + Sync + 'static, F: Send + Sync + 'static, { fn call(&self, params: Params, meta: M, subscriber: Subscriber) { let closure = &self.closure; closure(&self.delegate, params, meta, subscriber) } } struct DelegateUnsubscribe<T, F> { delegate: Arc<T>, closure: F, } impl<T, F, I> jsonrpc_pubsub::UnsubscribeRpcMethod for DelegateUnsubscribe<T, F> where F: Fn(&T, SubscriptionId) -> I, I: IntoFuture<Item = Value, Error = Error>, T: Send + Sync + 'static, F: Send + Sync + 'static, I::Future: Send + 'static, { type Out = I::Future; fn call(&self, id: SubscriptionId) -> Self::Out { let closure = &self.closure; closure(&self.delegate, id).into_future() } } /// A set of RPC methods and notifications tied to single `delegate` struct. pub struct IoDelegate<T, M = ()> where T: Send + Sync + 'static, M: Metadata, { delegate: Arc<T>, methods: HashMap<String, RemoteProcedure<M>>, } impl<T, M> IoDelegate<T, M> where T: Send + Sync + 'static, M: Metadata, { /// Creates new `IoDelegate` pub fn new(delegate: Arc<T>) -> Self { IoDelegate { delegate: delegate, methods: HashMap::new(), } } /// Adds an alias to existing method. /// NOTE: Aliases are not transitive, i.e. you cannot create alias to an alias. pub fn add_alias(&mut self, from: &str, to: &str) { self.methods.insert(from.into(), RemoteProcedure::Alias(to.into())); } /// Adds async method to the delegate. pub fn add_method<F, I>(&mut self, name: &str, method: F) where F: Fn(&T, Params) -> I, I: IntoFuture<Item = Value, Error = Error>, F: Send + Sync + 'static, I::Future: Send + 'static, { self.methods.insert(name.into(), RemoteProcedure::Method(Arc::new( DelegateAsyncMethod { delegate: self.delegate.clone(), closure: method, } ))); } /// Adds async method with metadata to the delegate. pub fn add_method_with_meta<F, I>(&mut self, name: &str, method: F) where F: Fn(&T, Params, M) -> I, I: IntoFuture<Item = Value, Error = Error>, F: Send + Sync + 'static, I::Future: Send + 'static, { self.methods.insert(name.into(), RemoteProcedure::Method(Arc::new( DelegateMethodWithMeta { delegate: self.delegate.clone(), closure: method, } ))); } /// Adds notification to the delegate. pub fn add_notification<F>(&mut self, name: &str, notification: F) where F: Fn(&T, Params), F: Send + Sync + 'static, { self.methods.insert(name.into(), RemoteProcedure::Notification(Arc::new( DelegateNotification { delegate: self.delegate.clone(), closure: notification, } ))); } } impl<T, M> IoDelegate<T, M> where T: Send + Sync + 'static, M: PubSubMetadata, { /// Adds subscription to the delegate. pub fn add_subscription<Sub, Unsub, I>( &mut self, name: &str, subscribe: (&str, Sub), unsubscribe: (&str, Unsub), ) where Sub: Fn(&T, Params, M, Subscriber), Sub: Send + Sync + 'static, Unsub: Fn(&T, SubscriptionId) -> I, I: IntoFuture<Item = Value, Error = Error>,<|fim▁hole|> I::Future: Send + 'static, { let (sub, unsub) = jsonrpc_pubsub::new_subscription( name, DelegateSubscribe { delegate: self.delegate.clone(), closure: subscribe.1, }, DelegateUnsubscribe { delegate: self.delegate.clone(), closure: unsubscribe.1, } ); self.add_method_with_meta(subscribe.0, move |_, params, meta| sub.call(params, meta)); self.add_method_with_meta(unsubscribe.0, move |_, params, meta| unsub.call(params, meta)); } } impl<T, M> Into<HashMap<String, RemoteProcedure<M>>> for IoDelegate<T, M> where T: Send + Sync + 'static, M: Metadata, { fn into(self) -> HashMap<String, RemoteProcedure<M>> { self.methods } }<|fim▁end|>
Unsub: Send + Sync + 'static,
<|file_name|>serial.cpp<|end_file_name|><|fim▁begin|>/* ScummVM - Graphic Adventure Engine * * ScummVM is the legal property of its developers, whose names * are too numerous to list here. Please refer to the COPYRIGHT * file distributed with this source distribution. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "glk/glulx/glulx.h" namespace Glk { namespace Glulx { #define IFFID(c1, c2, c3, c4) MKTAG(c1, c2, c3, c4) bool Glulx::init_serial() { undo_chain_num = 0; undo_chain_size = max_undo_level; undo_chain = (unsigned char **)glulx_malloc(sizeof(unsigned char *) * undo_chain_size); if (!undo_chain) return false; #ifdef SERIALIZE_CACHE_RAM { uint len = (endmem - ramstart); uint res; ramcache = (unsigned char *)glulx_malloc(sizeof(unsigned char *) * len); if (!ramcache) return false; _gameFile.seek(gamefile_start + ramstart); res = _gameFile.read(ramcache, len); if (res != len) return false; } #endif /* SERIALIZE_CACHE_RAM */ return true; } void Glulx::final_serial() { if (undo_chain) { int ix; for (ix = 0; ix < undo_chain_num; ix++) { glulx_free(undo_chain[ix]); } glulx_free(undo_chain); } undo_chain = nullptr; undo_chain_size = 0; undo_chain_num = 0; #ifdef SERIALIZE_CACHE_RAM if (ramcache) { glulx_free(ramcache); ramcache = nullptr; } #endif /* SERIALIZE_CACHE_RAM */ } uint Glulx::perform_saveundo() { dest_t dest; uint res; uint memstart = 0, memlen = 0, heapstart = 0, heaplen = 0; uint stackstart = 0, stacklen = 0; /* The format for undo-saves is simpler than for saves on disk. We just have a memory chunk, a heap chunk, and a stack chunk, in that order. We skip the IFF chunk headers (although the size fields are still there.) We also don't bother with IFF's 16-bit alignment. */ if (undo_chain_size == 0) return 1; dest._isMem = true; res = 0; if (res == 0) { res = write_long(&dest, 0); /* space for chunk length */ } if (res == 0) { memstart = dest._pos; res = write_memstate(&dest); memlen = dest._pos - memstart; } if (res == 0) { res = write_long(&dest, 0); /* space for chunk length */ } if (res == 0) { heapstart = dest._pos; res = write_heapstate(&dest, false); heaplen = dest._pos - heapstart; } if (res == 0) { res = write_long(&dest, 0); /* space for chunk length */ } if (res == 0) { stackstart = dest._pos; res = write_stackstate(&dest, false); stacklen = dest._pos - stackstart; } if (res == 0) { /* Trim it down to the perfect size. */ dest._ptr = (byte *)glulx_realloc(dest._ptr, dest._pos); if (!dest._ptr) res = 1; } if (res == 0) { res = reposition_write(&dest, memstart - 4); } if (res == 0) { res = write_long(&dest, memlen); } if (res == 0) { res = reposition_write(&dest, heapstart - 4); } if (res == 0) { res = write_long(&dest, heaplen); } if (res == 0) { res = reposition_write(&dest, stackstart - 4); } if (res == 0) { res = write_long(&dest, stacklen); } if (res == 0) { /* It worked. */ if (undo_chain_num >= undo_chain_size) { glulx_free(undo_chain[undo_chain_num - 1]); undo_chain[undo_chain_num - 1] = nullptr; } if (undo_chain_size > 1) memmove(undo_chain + 1, undo_chain, (undo_chain_size - 1) * sizeof(unsigned char *)); undo_chain[0] = dest._ptr; if (undo_chain_num < undo_chain_size) undo_chain_num += 1; dest._ptr = nullptr; } else { /* It didn't work. */ if (dest._ptr) { glulx_free(dest._ptr); dest._ptr = nullptr; } } return res; } uint Glulx::perform_restoreundo() { dest_t dest; uint res, val = 0; uint heapsumlen = 0; uint *heapsumarr = nullptr; /* If profiling is enabled and active then fail. */ #if VM_PROFILING if (profile_profiling_active()) return 1; #endif /* VM_PROFILING */ if (undo_chain_size == 0 || undo_chain_num == 0) return 1; dest._isMem = true; dest._ptr = undo_chain[0]; res = 0; if (res == 0) { res = read_long(&dest, &val); } if (res == 0) { res = read_memstate(&dest, val); } if (res == 0) { res = read_long(&dest, &val); } if (res == 0) { res = read_heapstate(&dest, val, false, &heapsumlen, &heapsumarr); } if (res == 0) { res = read_long(&dest, &val); } if (res == 0) { res = read_stackstate(&dest, val, false); } /* ### really, many of the failure modes of those calls ought to cause fatal errors. The stack or main memory may be damaged now. */ if (res == 0) { if (heapsumarr) res = heap_apply_summary(heapsumlen, heapsumarr); } if (res == 0) { /* It worked. */ if (undo_chain_size > 1) memmove(undo_chain, undo_chain + 1, (undo_chain_size - 1) * sizeof(unsigned char *)); undo_chain_num -= 1; glulx_free(dest._ptr); dest._ptr = nullptr; } else { /* It didn't work. */ dest._ptr = nullptr; } return res; } Common::Error Glulx::readSaveData(Common::SeekableReadStream *rs) { Common::ErrorCode errCode = Common::kNoError; QuetzalReader r; if (r.open(rs)) // Load in the savegame chunks errCode = loadGameChunks(r).getCode(); return errCode; } Common::Error Glulx::writeGameData(Common::WriteStream *ws) { QuetzalWriter w; Common::ErrorCode errCode = saveGameChunks(w).getCode(); if (errCode == Common::kNoError) { w.save(ws, _savegameDescription); } return errCode; } Common::Error Glulx::loadGameChunks(QuetzalReader &quetzal) { uint res = 0; uint heapsumlen = 0; uint *heapsumarr = nullptr; for (QuetzalReader::Iterator it = quetzal.begin(); it != quetzal.end() && !res; ++it) { Common::SeekableReadStream *rs = it.getStream(); dest_t dest; dest._src = rs; switch ((*it)._id) { case ID_IFhd: for (int ix = 0; ix < 128 && !res; ix++) { byte v = rs->readByte(); if (Mem1(ix) != v) // ### non-matching header res = 1; } break; case ID_CMem: res = read_memstate(&dest, rs->size()); break; case MKTAG('M', 'A', 'l', 'l'): res = read_heapstate(&dest, rs->size(), true, &heapsumlen, &heapsumarr); break; case ID_Stks: res = read_stackstate(&dest, rs->size(), true); break; default: break; } delete rs; } if (!res) { if (heapsumarr) { /* The summary might have come from any interpreter, so it could be out of order. We'll sort it. */ glulx_sort(heapsumarr + 2, (heapsumlen - 2) / 2, 2 * sizeof(uint), &sort_heap_summary); res = heap_apply_summary(heapsumlen, heapsumarr); } } return res ? Common::kReadingFailed : Common::kNoError; } Common::Error Glulx::saveGameChunks(QuetzalWriter &quetzal) { uint res = 0; // IFHd if (!res) { Common::WriteStream &ws = quetzal.add(ID_IFhd); for (int ix = 0; res == 0 && ix < 128; ix++) ws.writeByte(Mem1(ix)); } // CMem if (!res) { Common::WriteStream &ws = quetzal.add(ID_CMem); dest_t dest; dest._dest = &ws; res = write_memstate(&dest); } // MAll if (!res) { Common::WriteStream &ws = quetzal.add(MKTAG('M', 'A', 'l', 'l')); dest_t dest; dest._dest = &ws; res = write_heapstate(&dest, true); } // Stks if (!res) { Common::WriteStream &ws = quetzal.add(ID_Stks); dest_t dest; dest._dest = &ws; res = write_stackstate(&dest, true); } // All done return res ? Common::kUnknownError : Common::kNoError; } int Glulx::reposition_write(dest_t *dest, uint pos) { if (dest->_isMem) {<|fim▁hole|> return 0; } int Glulx::write_buffer(dest_t *dest, const byte *ptr, uint len) { if (dest->_isMem) { if (dest->_pos + len > dest->_size) { dest->_size = dest->_pos + len + 1024; if (!dest->_ptr) { dest->_ptr = (byte *)glulx_malloc(dest->_size); } else { dest->_ptr = (byte *)glulx_realloc(dest->_ptr, dest->_size); } if (!dest->_ptr) return 1; } memcpy(dest->_ptr + dest->_pos, ptr, len); } else { dest->_dest->write(ptr, len); } dest->_pos += len; return 0; } int Glulx::read_buffer(dest_t *dest, byte *ptr, uint len) { uint newlen; if (dest->_isMem) { memcpy(ptr, dest->_ptr + dest->_pos, len); } else { newlen = dest->_src->read(ptr, len); if (newlen != len) return 1; } dest->_pos += len; return 0; } int Glulx::write_long(dest_t *dest, uint val) { unsigned char buf[4]; Write4(buf, val); return write_buffer(dest, buf, 4); } int Glulx::write_short(dest_t *dest, uint16 val) { unsigned char buf[2]; Write2(buf, val); return write_buffer(dest, buf, 2); } int Glulx::write_byte(dest_t *dest, byte val) { return write_buffer(dest, &val, 1); } int Glulx::read_long(dest_t *dest, uint *val) { unsigned char buf[4]; int res = read_buffer(dest, buf, 4); if (res) return res; *val = Read4(buf); return 0; } int Glulx::read_short(dest_t *dest, uint16 *val) { unsigned char buf[2]; int res = read_buffer(dest, buf, 2); if (res) return res; *val = Read2(buf); return 0; } int Glulx::read_byte(dest_t *dest, byte *val) { return read_buffer(dest, val, 1); } uint Glulx::write_memstate(dest_t *dest) { uint res, pos; int val; int runlen; unsigned char ch; #ifdef SERIALIZE_CACHE_RAM uint cachepos; #endif /* SERIALIZE_CACHE_RAM */ res = write_long(dest, endmem); if (res) return res; runlen = 0; #ifdef SERIALIZE_CACHE_RAM cachepos = 0; #else /* SERIALIZE_CACHE_RAM */ _gameFile.seek(gamefile_start + ramstart); #endif /* SERIALIZE_CACHE_RAM */ for (pos = ramstart; pos < endmem; pos++) { ch = Mem1(pos); if (pos < endgamefile) { #ifdef SERIALIZE_CACHE_RAM val = ramcache[cachepos]; cachepos++; #else /* SERIALIZE_CACHE_RAM */ val = glk_get_char_stream(gamefile); if (val == -1) { fatal_error("The game file ended unexpectedly while saving."); } #endif /* SERIALIZE_CACHE_RAM */ ch ^= (unsigned char)val; } if (ch == 0) { runlen++; } else { /* Write any run we've got. */ while (runlen) { if (runlen >= 0x100) val = 0x100; else val = runlen; res = write_byte(dest, 0); if (res) return res; res = write_byte(dest, (val - 1)); if (res) return res; runlen -= val; } /* Write the byte we got. */ res = write_byte(dest, ch); if (res) return res; } } /* It's possible we've got a run left over, but we don't write it. */ return 0; } uint Glulx::read_memstate(dest_t *dest, uint chunklen) { uint chunkend = dest->_pos + chunklen; uint newlen; uint res, pos; int val; int runlen; unsigned char ch, ch2; #ifdef SERIALIZE_CACHE_RAM uint cachepos; #endif /* SERIALIZE_CACHE_RAM */ heap_clear(); res = read_long(dest, &newlen); if (res) return res; res = change_memsize(newlen, false); if (res) return res; runlen = 0; #ifdef SERIALIZE_CACHE_RAM cachepos = 0; #else /* SERIALIZE_CACHE_RAM */ _gameFile.seek(gamefile_start + ramstart); #endif /* SERIALIZE_CACHE_RAM */ for (pos = ramstart; pos < endmem; pos++) { if (pos < endgamefile) { #ifdef SERIALIZE_CACHE_RAM val = ramcache[cachepos]; cachepos++; #else /* SERIALIZE_CACHE_RAM */ if (_gameFile.pos() >= _gameFile.size()) { fatal_error("The game file ended unexpectedly while restoring."); val = _gameFile.readByte(); } #endif /* SERIALIZE_CACHE_RAM */ ch = (unsigned char)val; } else { ch = 0; } if (dest->_pos >= chunkend) { /* we're into the final, unstored run. */ } else if (runlen) { runlen--; } else { res = read_byte(dest, &ch2); if (res) return res; if (ch2 == 0) { res = read_byte(dest, &ch2); if (res) return res; runlen = (uint)ch2; } else { ch ^= ch2; } } if (pos >= protectstart && pos < protectend) continue; MemW1(pos, ch); } return 0; } uint Glulx::write_heapstate(dest_t *dest, int portable) { uint res; uint sumlen; uint *sumarray; res = heap_get_summary(&sumlen, &sumarray); if (res) return res; if (!sumarray) return 0; /* no heap */ res = write_heapstate_sub(sumlen, sumarray, dest, portable); glulx_free(sumarray); return res; } uint Glulx::write_heapstate_sub(uint sumlen, uint *sumarray, dest_t *dest, int portable) { uint res, lx; /* If we're storing for the purpose of undo, we don't need to do any byte-swapping, because the result will only be used by this session. */ if (!portable) { res = write_buffer(dest, (const byte *)sumarray, sumlen * sizeof(uint)); if (res) return res; return 0; } for (lx = 0; lx < sumlen; lx++) { res = write_long(dest, sumarray[lx]); if (res) return res; } return 0; } int Glulx::sort_heap_summary(const void *p1, const void *p2) { uint v1 = *(const uint *)p1; uint v2 = *(const uint *)p2; if (v1 < v2) return -1; if (v1 > v2) return 1; return 0; } uint Glulx::read_heapstate(dest_t *dest, uint chunklen, int portable, uint *sumlen, uint **summary) { uint res, count, lx; uint *arr; *sumlen = 0; *summary = nullptr; if (chunklen == 0) return 0; /* no heap */ if (!portable) { count = chunklen / sizeof(uint); arr = (uint *)glulx_malloc(chunklen); if (!arr) return 1; res = read_buffer(dest, (byte *)arr, chunklen); if (res) return res; *sumlen = count; *summary = arr; return 0; } count = chunklen / 4; arr = (uint *)glulx_malloc(count * sizeof(uint)); if (!arr) return 1; for (lx = 0; lx < count; lx++) { res = read_long(dest, arr + lx); if (res) return res; } *sumlen = count; *summary = arr; return 0; } uint Glulx::write_stackstate(dest_t *dest, int portable) { uint res; uint lx; uint lastframe; /* If we're storing for the purpose of undo, we don't need to do any byte-swapping, because the result will only be used by this session. */ if (!portable) { res = write_buffer(dest, stack, stackptr); if (res) return res; return 0; } /* Write a portable stack image. To do this, we have to write stack frames in order, bottom to top. Remember that the last word of every stack frame is a pointer to the beginning of that stack frame. (This includes the last frame, because the save opcode pushes on a call stub before it calls perform_save().) */ lastframe = (uint)(-1); while (1) { uint frameend, frm, frm2, frm3; unsigned char loctype, loccount; uint numlocals, frlen, locpos; /* Find the next stack frame (after the one in lastframe). Sadly, this requires searching the stack from the top down. We have to do this for *every* frame, which takes N^2 time overall. But save routines usually aren't nested very deep. If it becomes a practical problem, we can build a stack-frame array, which requires dynamic allocation. */ for (frm = stackptr, frameend = stackptr; frm != 0 && (frm2 = Stk4(frm - 4)) != lastframe; frameend = frm, frm = frm2) { }; /* Write out the frame. */ frm2 = frm; frlen = Stk4(frm2); frm2 += 4; res = write_long(dest, frlen); if (res) return res; locpos = Stk4(frm2); frm2 += 4; res = write_long(dest, locpos); if (res) return res; frm3 = frm2; numlocals = 0; while (1) { loctype = Stk1(frm2); frm2 += 1; loccount = Stk1(frm2); frm2 += 1; res = write_byte(dest, loctype); if (res) return res; res = write_byte(dest, loccount); if (res) return res; if (loctype == 0 && loccount == 0) break; numlocals++; } if ((numlocals & 1) == 0) { res = write_byte(dest, 0); if (res) return res; res = write_byte(dest, 0); if (res) return res; frm2 += 2; } if (frm2 != frm + locpos) fatal_error("Inconsistent stack frame during save."); /* Write out the locals. */ for (lx = 0; lx < numlocals; lx++) { loctype = Stk1(frm3); frm3 += 1; loccount = Stk1(frm3); frm3 += 1; if (loctype == 0 && loccount == 0) break; /* Put in up to 0, 1, or 3 bytes of padding, depending on loctype. */ while (frm2 & (loctype - 1)) { res = write_byte(dest, 0); if (res) return res; frm2 += 1; } /* Put in this set of locals. */ switch (loctype) { case 1: do { res = write_byte(dest, Stk1(frm2)); if (res) return res; frm2 += 1; loccount--; } while (loccount); break; case 2: do { res = write_short(dest, Stk2(frm2)); if (res) return res; frm2 += 2; loccount--; } while (loccount); break; case 4: do { res = write_long(dest, Stk4(frm2)); if (res) return res; frm2 += 4; loccount--; } while (loccount); break; } } if (frm2 != frm + frlen) fatal_error("Inconsistent stack frame during save."); while (frm2 < frameend) { res = write_long(dest, Stk4(frm2)); if (res) return res; frm2 += 4; } /* Go on to the next frame. */ if (frameend == stackptr) break; /* All done. */ lastframe = frm; } return 0; } uint Glulx::read_stackstate(dest_t *dest, uint chunklen, int portable) { uint res; uint frameend, frm, frm2, frm3, locpos, frlen, numlocals; if (chunklen > stacksize) return 1; stackptr = chunklen; frameptr = 0; valstackbase = 0; localsbase = 0; if (!portable) { res = read_buffer(dest, stack, stackptr); if (res) return res; return 0; } /* This isn't going to be pleasant; we're going to read the data in as a block, and then convert it in-place. */ res = read_buffer(dest, stack, stackptr); if (res) return res; frameend = stackptr; while (frameend != 0) { /* Read the beginning-of-frame pointer. Remember, right now, the whole frame is stored big-endian. So we have to read with the Read*() macros, and then write with the StkW*() macros. */ frm = Read4(stack + (frameend - 4)); frm2 = frm; frlen = Read4(stack + frm2); StkW4(frm2, frlen); frm2 += 4; locpos = Read4(stack + frm2); StkW4(frm2, locpos); frm2 += 4; /* The locals-format list is in bytes, so we don't have to convert it. */ frm3 = frm2; frm2 = frm + locpos; numlocals = 0; while (1) { unsigned char loctype, loccount; loctype = Read1(stack + frm3); frm3 += 1; loccount = Read1(stack + frm3); frm3 += 1; if (loctype == 0 && loccount == 0) break; /* Skip up to 0, 1, or 3 bytes of padding, depending on loctype. */ while (frm2 & (loctype - 1)) { StkW1(frm2, 0); frm2++; } /* Convert this set of locals. */ switch (loctype) { case 1: do { /* Don't need to convert bytes. */ frm2 += 1; loccount--; } while (loccount); break; case 2: do { uint16 loc = Read2(stack + frm2); StkW2(frm2, loc); frm2 += 2; loccount--; } while (loccount); break; case 4: do { uint loc = Read4(stack + frm2); StkW4(frm2, loc); frm2 += 4; loccount--; } while (loccount); break; } numlocals++; } if ((numlocals & 1) == 0) { StkW1(frm3, 0); frm3++; StkW1(frm3, 0); frm3++; } if (frm3 != frm + locpos) { return 1; } while (frm2 & 3) { StkW1(frm2, 0); frm2++; } if (frm2 != frm + frlen) { return 1; } /* Now, the values pushed on the stack after the call frame itself. This includes the stub. */ while (frm2 < frameend) { uint loc = Read4(stack + frm2); StkW4(frm2, loc); frm2 += 4; } frameend = frm; } return 0; } uint Glulx::perform_verify() { uint len, chksum = 0, newlen; unsigned char buf[4]; uint val, newsum, ix; len = gamefile_len; if (len < 256 || (len & 0xFF) != 0) return 1; _gameFile.seek(gamefile_start); newsum = 0; /* Read the header */ for (ix = 0; ix < 9; ix++) { newlen = _gameFile.read(buf, 4); if (newlen != 4) return 1; val = Read4(buf); if (ix == 3) { if (len != val) return 1; } if (ix == 8) chksum = val; else newsum += val; } /* Read everything else */ for (; ix < len / 4; ix++) { newlen = _gameFile.read(buf, 4); if (newlen != 4) return 1; val = Read4(buf); newsum += val; } if (newsum != chksum) return 1; return 0; } } // End of namespace Glulx } // End of namespace Glk<|fim▁end|>
dest->_pos = pos; } else { error("Seeking a WriteStream isn't allowed"); }
<|file_name|>16878_H2.rs<|end_file_name|><|fim▁begin|>Per(s)PSA @ damp 02% PSA @ damp 05% PSA @ damp 07% PSA @ damp 10% PSA @ damp 20% PSA @ damp 30% (m/s/s) 0.000 3.8242000E-002 3.8242000E-002 3.8242000E-002 3.8242000E-002 3.8242000E-002 3.8242000E-002 0.010 3.8247300E-002 3.8247550E-002 3.8247650E-002 3.8247790E-002 3.8247690E-002 3.8246990E-002 0.020 3.8268110E-002 3.8267090E-002 3.8266640E-002 3.8266270E-002 3.8264470E-002 3.8261810E-002 0.030 3.8302570E-002 3.8299090E-002 3.8298020E-002 3.8296770E-002 3.8292670E-002 3.8286790E-002 0.040 3.8345210E-002 3.8335900E-002 3.8334200E-002 3.8332450E-002 3.8327130E-002 3.8319180E-002 0.050 3.8397830E-002 3.8372580E-002 3.8368060E-002 3.8366580E-002 3.8366350E-002 3.8359600E-002 0.075 3.8466810E-002 3.8506020E-002 3.8521610E-002 3.8532760E-002 3.8539640E-002 3.8529550E-002 0.100 3.8420510E-002 3.8545250E-002 3.8601160E-002 3.8666680E-002 3.8807730E-002 3.8844960E-002 0.110 3.8380250E-002 3.8602060E-002 3.8741040E-002 3.8863020E-002 3.9051890E-002 3.9074930E-002 0.120 3.9594950E-002 3.9280790E-002 3.9284470E-002 3.9351790E-002 3.9467290E-002 3.9397480E-002 0.130 4.1279140E-002 4.0195120E-002 4.0248430E-002 4.0260800E-002 4.0068870E-002 3.9805210E-002 0.140 4.5885810E-002 4.3134650E-002 4.2341970E-002 4.1684010E-002 4.0782070E-002 4.0266880E-002 0.150 4.2383010E-002 4.2630480E-002 4.2601680E-002 4.2383550E-002 4.1479710E-002 4.0745470E-002 0.160 4.3761320E-002 4.3570550E-002 4.3445530E-002 4.3206240E-002 4.2161500E-002 4.1216940E-002 0.170 4.3996000E-002 4.4919430E-002 4.4792980E-002 4.4369930E-002 4.2842430E-002 4.1665050E-002 0.180 5.1370830E-002 4.7977580E-002 4.6887720E-002 4.5761710E-002 4.3470720E-002 4.2072230E-002 0.190 5.2597260E-002 4.9332580E-002 4.8192070E-002 4.6772010E-002 4.3961320E-002 4.2425200E-002 0.200 5.5895610E-002 5.0635520E-002 4.8910280E-002 4.7175740E-002 4.4263110E-002 4.2722030E-002 0.220 5.2662290E-002 4.6631480E-002 4.6217260E-002 4.5643050E-002 4.4445400E-002 4.3213490E-002 0.240 6.3183720E-002 4.8928260E-002 4.5888080E-002 4.4147480E-002 4.4805820E-002 4.3726310E-002 0.260 5.9324230E-002 5.0933870E-002 4.8901260E-002 4.7489010E-002 4.5765260E-002 4.4339010E-002 0.280 9.2257250E-002 6.1173110E-002 5.2166260E-002 4.9227530E-002 4.6772540E-002 4.4986520E-002 0.300 8.1671920E-002 5.6962460E-002 5.3153600E-002 5.0655550E-002 4.7495760E-002 4.5617000E-002 0.320 8.1720030E-002 5.6366940E-002 5.1707150E-002 4.9615260E-002 4.7953370E-002 4.6258740E-002 0.340 8.5328280E-002 5.9401640E-002 5.4291420E-002 5.1108440E-002 4.8525960E-002 4.6990920E-002 0.360 8.4730340E-002 6.3965560E-002 5.7429710E-002 5.1954390E-002 4.9739730E-002 4.7872310E-002 0.380 7.8352410E-002 6.0101830E-002 5.6416170E-002 5.4153600E-002 5.1695270E-002 4.8890790E-002 0.400 7.8909200E-002 6.6341650E-002 6.3456300E-002 6.0029160E-002 5.3930700E-002 4.9958210E-002 0.420 9.0467980E-002 7.1163770E-002 6.8254020E-002 6.4242580E-002 5.5982800E-002 5.0983660E-002 0.440 1.0269950E-001 7.7493090E-002 7.1944050E-002 6.7050280E-002 5.7646890E-002 5.1896310E-002 0.460 1.0018871E-001 7.6246110E-002 7.1007100E-002 6.8454670E-002 5.8889720E-002 5.2673130E-002 0.480 1.0531908E-001 7.7976760E-002 7.5393020E-002 7.0805770E-002 5.9701790E-002 5.3324760E-002 0.500 1.4001079E-001 9.5348600E-002 8.2845870E-002 7.2703240E-002 6.0049180E-002 5.3883870E-002 0.550 1.3095635E-001 1.0764300E-001 9.5785800E-002 8.2949560E-002 6.0246910E-002 5.5293720E-002 0.600 1.2964475E-001 9.9104720E-002 9.1046910E-002 8.3784380E-002 6.3295980E-002 5.7447980E-002 0.650 1.6133781E-001 1.2017433E-001 1.1039165E-001 9.6894470E-002 7.1364950E-002 6.0241830E-002 0.700 2.7326986E-001 1.7452382E-001 1.4362304E-001 1.1688869E-001 7.9654120E-002 6.2688210E-002 0.750 1.9225843E-001 1.6397107E-001 1.4719637E-001 1.2592697E-001 8.4323240E-002 6.4006690E-002 0.800 1.9219083E-001 1.5768450E-001 1.4243412E-001 1.2419949E-001 8.5280300E-002 6.4066930E-002 0.850 1.7897442E-001 1.4839451E-001 1.3442877E-001 1.1870615E-001 8.4034950E-002 6.3133080E-002 0.900 1.3779239E-001 1.2132726E-001 1.1912633E-001 1.1128287E-001 8.1832810E-002 6.1517460E-002 0.950 1.5691651E-001 1.2811875E-001 1.2104983E-001 1.1023682E-001 7.9308730E-002 5.9423780E-002 1.000 1.7999424E-001 1.4198877E-001 1.2793802E-001 1.1127115E-001 7.6298250E-002 5.6963790E-002 1.100 1.9708160E-001 1.4222716E-001 1.1965576E-001 9.9814830E-002 6.7744060E-002 5.1256240E-002 1.200 1.2699226E-001 9.1899600E-002 8.5061630E-002 7.6379470E-002 5.7791630E-002 4.5296040E-002 1.300 1.2194011E-001 8.6357680E-002 7.6256600E-002 6.5229680E-002 4.9403280E-002 3.9878030E-002 1.400 1.1291787E-001 7.1863070E-002 5.8194140E-002 5.2405000E-002 4.2496630E-002 3.5277610E-002 1.500 1.1752018E-001 6.3872390E-002 4.9076400E-002 4.2630530E-002 3.7033310E-002 3.1494710E-002 1.600 7.7692330E-002 5.4162190E-002 4.7178120E-002 4.1723230E-002 3.3021020E-002 2.8417350E-002 1.700 8.0101910E-002 5.9903770E-002 5.1508800E-002 4.2722280E-002 3.0106610E-002 2.5866940E-002 1.800 6.9781570E-002 5.2069850E-002 4.6228380E-002 3.8784390E-002 2.7768930E-002 2.3666210E-002 1.900 6.1084790E-002 4.4284430E-002 3.9534180E-002 3.4599640E-002 2.5481050E-002 2.1683020E-002 2.000 5.0735380E-002 4.0796980E-002 3.6560970E-002 3.1789000E-002 2.3100370E-002 1.9863860E-002 2.200 4.4652350E-002 2.8166860E-002 2.6907500E-002 2.5482500E-002 1.9881470E-002 1.6735010E-002 2.400 4.0343710E-002 2.8809060E-002 2.5159870E-002 2.1834170E-002 1.7529460E-002 1.4340530E-002 2.600 2.3567990E-002 2.4113660E-002 2.2443410E-002 1.9478490E-002 1.5575520E-002 1.2569720E-002 2.800 3.6228170E-002 2.7070130E-002 2.3751060E-002 2.0673660E-002 1.4571640E-002 1.1258900E-002 3.000 3.9609270E-002 2.7810580E-002 2.4564930E-002 2.0972910E-002 1.4194850E-002 1.0764650E-002 3.200 2.4092460E-002 2.2324030E-002 2.0688010E-002 1.8356710E-002 1.2918410E-002 9.8856600E-003 3.400 2.1856250E-002 1.8372150E-002 1.6883090E-002 1.5138650E-002 1.1201400E-002 8.8040700E-003 3.600 2.6430980E-002 1.5462060E-002 1.3788970E-002 1.2142970E-002 9.4169200E-003 7.6742000E-003 3.800 2.1902060E-002 1.6750230E-002 1.4491310E-002 1.2035930E-002 8.6105500E-003 7.2928700E-003 4.000 2.3784240E-002 1.7764580E-002 1.4949720E-002 1.1905710E-002 8.4585900E-003 6.9367100E-003 4.200 2.2915810E-002 1.6294520E-002 1.3631060E-002 1.1407290E-002 8.0532200E-003 6.5318400E-003 4.400 1.8788340E-002 1.2880310E-002 1.1520800E-002 1.0081380E-002 7.4504700E-003 6.0891200E-003 4.600 1.4124900E-002 1.1302790E-002 9.7836600E-003 8.4246900E-003 6.7772600E-003 5.6337000E-003 <|fim▁hole|>5.000 1.2776300E-002 9.5400500E-003 8.4462200E-003 7.1671500E-003 5.5425600E-003 4.7711900E-003 5.500 9.2882600E-003 7.7200700E-003 7.3186100E-003 6.6693500E-003 4.9473900E-003 3.9293400E-003 6.000 1.0484100E-002 8.4256400E-003 7.4711000E-003 6.4018100E-003 4.3779000E-003 3.3833600E-003 6.500 8.8009400E-003 6.1911000E-003 5.5876700E-003 4.8711600E-003 3.4114600E-003 2.7564300E-003 7.000 7.5625500E-003 5.4523400E-003 4.7359100E-003 4.1935300E-003 2.8861900E-003 2.4078600E-003 7.500 6.4098800E-003 4.9161200E-003 4.2270800E-003 3.6095800E-003 2.5713500E-003 2.0799700E-003 8.000 5.2159200E-003 4.3984100E-003 3.9643000E-003 3.4341500E-003 2.3354800E-003 1.7943100E-003 8.500 4.3221700E-003 3.7081600E-003 3.3791100E-003 2.9778800E-003 2.1140500E-003 1.6426400E-003 9.000 3.1897700E-003 2.8637400E-003 2.6693200E-003 2.4125900E-003 1.8187800E-003 1.4635900E-003 9.500 2.1977200E-003 2.0688200E-003 1.9911700E-003 1.8716300E-003 1.5195500E-003 1.2774700E-003 10.00 1.9059100E-003 1.7138900E-003 1.6436400E-003 1.5453800E-003 1.2673800E-003 1.1023100E-003 -1 7.4274180E-003 7.4274180E-003 7.4274180E-003 7.4274180E-003 7.4274180E-003 7.4274180E-003<|fim▁end|>
4.800 1.5809870E-002 9.9182000E-003 8.8440400E-003 7.3632600E-003 6.1308200E-003 5.1893300E-003
<|file_name|>weather.py<|end_file_name|><|fim▁begin|>"""Support for HomematicIP Cloud weather devices.""" import logging from homematicip.aio.device import ( AsyncWeatherSensor, AsyncWeatherSensorPlus, AsyncWeatherSensorPro) from homematicip.aio.home import AsyncHome from homeassistant.components.weather import WeatherEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import TEMP_CELSIUS from homeassistant.core import HomeAssistant from . import DOMAIN as HMIPC_DOMAIN, HMIPC_HAPID, HomematicipGenericDevice _LOGGER = logging.getLogger(__name__) async def async_setup_platform( hass, config, async_add_entities, discovery_info=None): """Set up the HomematicIP Cloud weather sensor.""" pass async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities) -> None: """Set up the HomematicIP weather sensor from a config entry.""" home = hass.data[HMIPC_DOMAIN][config_entry.data[HMIPC_HAPID]].home devices = [] for device in home.devices: if isinstance(device, AsyncWeatherSensorPro): devices.append(HomematicipWeatherSensorPro(home, device)) elif isinstance(device, (AsyncWeatherSensor, AsyncWeatherSensorPlus)): devices.append(HomematicipWeatherSensor(home, device)) if devices: async_add_entities(devices) class HomematicipWeatherSensor(HomematicipGenericDevice, WeatherEntity): """representation of a HomematicIP Cloud weather sensor plus & basic.""" def __init__(self, home: AsyncHome, device) -> None: """Initialize the weather sensor.""" super().__init__(home, device) @property def name(self) -> str: """Return the name of the sensor.""" return self._device.label @property def temperature(self) -> float: """Return the platform temperature.""" return self._device.actualTemperature @property def temperature_unit(self) -> str: """Return the unit of measurement.""" return TEMP_CELSIUS @property def humidity(self) -> int: """Return the humidity.""" return self._device.humidity @property def wind_speed(self) -> float: """Return the wind speed.""" return self._device.windSpeed @property def attribution(self) -> str: """Return the attribution.""" return "Powered by Homematic IP" @property def condition(self) -> str: """Return the current condition."""<|fim▁hole|> return 'rainy' if self._device.storm: return 'windy' if self._device.sunshine: return 'sunny' return '' class HomematicipWeatherSensorPro(HomematicipWeatherSensor): """representation of a HomematicIP weather sensor pro.""" @property def wind_bearing(self) -> float: """Return the wind bearing.""" return self._device.windDirection<|fim▁end|>
if hasattr(self._device, "raining") and self._device.raining:
<|file_name|>translate.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Translator module that uses the Google Translate API. Adapted from Terry Yin's google-translate-python. Language detection added by Steven Loria. """ from __future__ import absolute_import import json import re import codecs from textblob.compat import PY2, request, urlencode from textblob.exceptions import TranslatorError class Translator(object): """A language translator and detector. Usage: :: >>> from textblob.translate import Translator >>> t = Translator() >>> t.translate('hello', from_lang='en', to_lang='fr') u'bonjour' >>> t.detect("hola") u'es' """ url = "http://translate.google.com/translate_a/t" headers = {'User-Agent': ('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) ' 'AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.168 Safari/535.19')} def translate(self, source, from_lang=None, to_lang='en', host=None, type_=None): """Translate the source text from one language to another.""" if PY2: source = source.encode('utf-8') data = {"client": "p", "ie": "UTF-8", "oe": "UTF-8", "sl": from_lang, "tl": to_lang, "text": source} json5 = self._get_json5(self.url, host=host, type_=type_, data=data) return self._get_translation_from_json5(json5) def detect(self, source, host=None, type_=None): """Detect the source text's language.""" if PY2: source = source.encode('utf-8') if len(source) < 3: raise TranslatorError('Must provide a string with at least 3 characters.') data = {"client": "p", "ie": "UTF-8", "oe": "UTF-8", "text": source} json5 = self._get_json5(self.url, host=host, type_=type_, data=data) lang = self._get_language_from_json5(json5) return lang def _get_language_from_json5(self, content):<|fim▁hole|> return json_data['src'] return None def _get_translation_from_json5(self, content): result = u"" json_data = json.loads(content) if 'sentences' in json_data: result = ''.join([s['trans'] for s in json_data['sentences']]) return _unescape(result) def _get_json5(self, url, host=None, type_=None, data=None): encoded_data = urlencode(data).encode('utf-8') req = request.Request(url=url, headers=self.headers, data=encoded_data) if host or type_: req.set_proxy(host=host, type=type_) resp = request.urlopen(req) content = resp.read() return content.decode('utf-8') def _unescape(text): """Unescape unicode character codes within a string. """ pattern = r'\\{1,2}u[0-9a-fA-F]{4}' decode = lambda x: codecs.getdecoder('unicode_escape')(x.group())[0] return re.sub(pattern, decode, text)<|fim▁end|>
json_data = json.loads(content) if 'src' in json_data:
<|file_name|>fast_consensus.py<|end_file_name|><|fim▁begin|>""" @author waziz """ import logging import sys import traceback import os import argparse import numpy as np from functools import partial from multiprocessing import Pool from chisel.decoder import MBR, MAP, consensus from chisel.util.iotools import read_sampled_derivations, read_block, list_numbered_files from chisel.decoder.estimates import EmpiricalDistribution from chisel.smt import groupby, KBestSolution from chisel.util import scaled_fmap, dict2str from chisel.util.config import configure from chisel.util.wmap import WMap from chisel.util.iotools import smart_ropen, smart_wopen from chisel.learning.newestimates import py from chisel.mteval.fast_bleu import DecodingBLEU import chisel.mteval as mteval def cmpYLPQ(lhs, rhs): if lhs[1] != rhs[1]: # loss return cmp(lhs[1], rhs[1]) elif lhs[2] != rhs[2]: # posterior return cmp(rhs[2], lhs[2]) elif lhs[3] != rhs[3]: # proxy return cmp(rhs[3], lhs[3]) else: # yield<|fim▁hole|> if metric_name is None: output_dir = '{0}/decisions/{1}'.format(workspace, decision_rule) else: output_dir = '{0}/decisions/{1}-{2}'.format(workspace, decision_rule, metric_name) if not os.path.isdir(output_dir): os.makedirs(output_dir) return output_dir def make_decisions(job_desc, headers, options): # this code runs in a Pool, thus we wrap in try/except in order to have more informative exceptions jid, path = job_desc try: derivations, q_wmap, p_wmap = read_sampled_derivations(smart_ropen(path)) logging.debug('job=%d derivations=%d empdist...', jid, len(derivations)) support, posterior, proxy = py(derivations, q_wmap, p_wmap, get_yield=lambda d: d.tree.projection, empirical_q=True, alpha=1.0, beta=1.0) # TODO: make option logging.info('job=%d derivations=%d strings=%d', jid, len(derivations), len(support)) logging.debug('job=%s consensus...', jid) scorer = DecodingBLEU([Dy.leaves for Dy in support], posterior) losses = np.array([scorer.loss(Dy.leaves) for Dy in support], float) return sorted(zip((Dy.projection for Dy in support), losses, posterior, proxy), cmp=cmpYLPQ) except: raise Exception(''.join(traceback.format_exception(*sys.exc_info()))) def decide_and_save(job_desc, headers, options, output_dir): # this code runs in a Pool, thus we wrap in try/except in order to have more informative exceptions jid, path = job_desc try: # make decisions ranking = make_decisions(job_desc, headers, options) # write to file if necessary with smart_wopen('{0}/{1}.gz'.format(output_dir, jid)) as out: # TODO: save nbest out.write('{0}\n'.format('\t'.join(['#target', '#p', '#q', '#yield']))) if options.nbest > 0: for y, l, p, q in ranking[0:options.nbest]: out.write('{0}\n'.format('\t'.join(str(x) for x in [l, p, q, y]))) else: for y, l, p, q in ranking: out.write('{0}\n'.format('\t'.join(str(x) for x in [l, p, q, y]))) return ranking[0] except: raise Exception('job={0} exception={1}'.format(jid, ''.join(traceback.format_exception(*sys.exc_info())))) def argparse_and_config(): parser = argparse.ArgumentParser(description='Applies a decision rule to a sample.', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('config', type=str, help="configuration file") parser.add_argument("workspace", type=str, default=None, help="where samples can be found and where decisions are placed") parser.add_argument("--nbest", '-k', type=int, default=1, help="number of solutions") parser.add_argument("--jobs", '-j', type=int, default=2, help="number of processes") parser.add_argument('--verbose', '-v', action='store_true', help='increases verbosity') args, config, failed = configure(parser, set_defaults=['chisel:model', 'chisel:decision'], required_sections=['proxy', 'target'], configure_logging=True) logging.debug('arguments: %s', vars(args)) if failed: sys.exit(1) return args, config def main(): options, config = argparse_and_config() # check for input folder samples_dir = '{0}/samples'.format(options.workspace) if not os.path.isdir(samples_dir): raise Exception('If a workspace is set, samples are expected to be found under $workspace/samples') logging.info('Reading samples from %s', samples_dir) # create output folders if not os.path.isdir('{0}/output'.format(options.workspace)): os.makedirs('{0}/output'.format(options.workspace)) output_dir = create_decision_rule_dir(options.workspace, 'consensus', 'bleu') one_best_file = '{0}/output/{1}-{2}'.format(options.workspace, 'consensus', 'bleu') logging.info("Writing '%s' solutions to %s", 'consensus', output_dir) logging.info("Writing 1-best '%s' yields to %s", 'consensus', one_best_file) # TODO: generalise this headers = {'derivation': 'd', 'vector': 'v', 'count': 'n', 'log_ur': 'log_ur', 'importance': 'importance'} # read jobs from workspace input_files = list_numbered_files(samples_dir) jobs = [(fid, input_file) for fid, input_file in input_files] logging.info('%d jobs', len(jobs)) # run jobs in parallel pool = Pool(options.jobs) # run decision rules and save them to files results = pool.map(partial(decide_and_save, headers=headers, options=options, output_dir=output_dir), jobs) # save the 1-best solution for each decision rule in a separate file with smart_wopen(one_best_file) as fout: for y, l, p, q in results: fout.write('{0}\n'.format(y)) if __name__ == '__main__': main()<|fim▁end|>
return cmp(lhs[0], rhs[0]) def create_decision_rule_dir(workspace, decision_rule, metric_name=None):
<|file_name|>IMoveModel.java<|end_file_name|><|fim▁begin|>/* * Copyright (c) 2012-2013 Open Source Community - <http://www.peerfact.org> * Copyright (c) 2011-2012 University of Paderborn - UPB * Copyright (c) 2005-2011 KOM - Multimedia Communications Lab * * This file is part of PeerfactSim.KOM. * * PeerfactSim.KOM is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * PeerfactSim.KOM is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with PeerfactSim.KOM. If not, see <http://www.gnu.org/licenses/>. * */ package org.peerfact.impl.application.infodissemination.moveModels; import java.awt.Point; import org.peerfact.impl.application.infodissemination.IDOApplication; /** * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! * This part of the Simulator is not maintained in the current version of * PeerfactSim.KOM. There is no intention of the authors to fix this * circumstances, since the changes needed are huge compared to overall benefit. * * If you want it to work correctly, you are free to make the specific changes * and provide it to the community. * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!!!!!!!!!!!!!!!!! * * This interface is used to allow the interchangeability of the move model for * the peers. * * @author Julius Rueckert <peerfact@kom.tu-darmstadt.de> * @version 01/06/2011 * */ public interface IMoveModel {<|fim▁hole|> }<|fim▁end|>
public Point getNextPosition(IDOApplication app);
<|file_name|>index.js<|end_file_name|><|fim▁begin|>// this is just a demo. To run it execute from the root of repository: // // > npm start // // Then open ./example/index.html // module.exports.main = function () { var graph = require('ngraph.generators').balancedBinTree(6); var createPixiGraphics = require('../'); var pixiGraphics = createPixiGraphics(graph); var layout = pixiGraphics.layout; // just make sure first node does not move: layout.pinNode(graph.getNode(1), true); // begin animation loop: pixiGraphics.run();<|fim▁hole|><|fim▁end|>
}
<|file_name|>resource_task.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! A task that takes a URL and streams back the binary data. use about_loader; use data_loader; use file_loader; use http_loader; use cookie_storage::CookieStorage; use cookie; use mime_classifier::MIMEClassifier; use net_traits::{ControlMsg, LoadData, LoadResponse, LoadConsumer, CookieSource}; use net_traits::{Metadata, ProgressMsg, ResourceTask, AsyncResponseTarget, ResponseAction}; use net_traits::ProgressMsg::Done; use util::opts; use util::task::spawn_named; use url::Url; use hsts::{HSTSList, HSTSEntry, preload_hsts_domains}; use devtools_traits::{DevtoolsControlMsg}; use hyper::header::{ContentType, Header, SetCookie, UserAgent}; use hyper::mime::{Mime, TopLevel, SubLevel}; use ipc_channel::ipc::{self, IpcReceiver, IpcSender}; use std::borrow::ToOwned; use std::boxed::FnBox; use std::sync::Arc; use std::sync::Mutex; use std::sync::mpsc::{channel, Sender}; pub enum ProgressSender { Channel(IpcSender<ProgressMsg>), Listener(AsyncResponseTarget), } impl ProgressSender { //XXXjdm return actual error pub fn send(&self, msg: ProgressMsg) -> Result<(), ()> { match *self { ProgressSender::Channel(ref c) => c.send(msg).map_err(|_| ()), ProgressSender::Listener(ref b) => { let action = match msg { ProgressMsg::Payload(buf) => ResponseAction::DataAvailable(buf), ProgressMsg::Done(status) => ResponseAction::ResponseComplete(status), }; b.invoke_with_listener(action); Ok(()) } } } } /// For use by loaders in responding to a Load message. pub fn start_sending(start_chan: LoadConsumer, metadata: Metadata) -> ProgressSender { start_sending_opt(start_chan, metadata).ok().unwrap() } /// For use by loaders in responding to a Load message that allows content sniffing. pub fn start_sending_sniffed(start_chan: LoadConsumer, metadata: Metadata, classifier: Arc<MIMEClassifier>, partial_body: &Vec<u8>) -> ProgressSender { start_sending_sniffed_opt(start_chan, metadata, classifier, partial_body).ok().unwrap() } /// For use by loaders in responding to a Load message that allows content sniffing. pub fn start_sending_sniffed_opt(start_chan: LoadConsumer, mut metadata: Metadata, classifier: Arc<MIMEClassifier>, partial_body: &Vec<u8>) -> Result<ProgressSender, ()> { if opts::get().sniff_mime_types { // TODO: should be calculated in the resource loader, from pull requeset #4094 let mut nosniff = false; let mut check_for_apache_bug = false; if let Some(ref headers) = metadata.headers { if let Some(ref raw_content_type) = headers.get_raw("content-type") { if raw_content_type.len() > 0 { let ref last_raw_content_type = raw_content_type[raw_content_type.len() - 1]; check_for_apache_bug = last_raw_content_type == b"text/plain" || last_raw_content_type == b"text/plain; charset=ISO-8859-1" || last_raw_content_type == b"text/plain; charset=iso-8859-1" || last_raw_content_type == b"text/plain; charset=UTF-8"; } } if let Some(ref raw_content_type_options) = headers.get_raw("X-content-type-options") { nosniff = raw_content_type_options.iter().any(|ref opt| *opt == b"nosniff"); } } let supplied_type = metadata.content_type.map(|ContentType(Mime(toplevel, sublevel, _))| { (format!("{}", toplevel), format!("{}", sublevel)) }); metadata.content_type = classifier.classify(nosniff, check_for_apache_bug, &supplied_type, &partial_body).map(|(toplevel, sublevel)| { let mime_tp: TopLevel = toplevel.parse().unwrap(); let mime_sb: SubLevel = sublevel.parse().unwrap(); ContentType(Mime(mime_tp, mime_sb, vec!())) }); } start_sending_opt(start_chan, metadata) } /// For use by loaders in responding to a Load message. pub fn start_sending_opt(start_chan: LoadConsumer, metadata: Metadata) -> Result<ProgressSender, ()> { match start_chan { LoadConsumer::Channel(start_chan) => { let (progress_chan, progress_port) = ipc::channel().unwrap(); let result = start_chan.send(LoadResponse { metadata: metadata, progress_port: progress_port, }); match result { Ok(_) => Ok(ProgressSender::Channel(progress_chan)), Err(_) => Err(()) } } LoadConsumer::Listener(target) => { target.invoke_with_listener(ResponseAction::HeadersAvailable(metadata)); Ok(ProgressSender::Listener(target)) } } } /// Create a ResourceTask pub fn new_resource_task(user_agent: Option<String>, devtools_chan: Option<Sender<DevtoolsControlMsg>>) -> ResourceTask { let hsts_preload = match preload_hsts_domains() { Some(list) => list, None => HSTSList::new() }; let (setup_chan, setup_port) = ipc::channel().unwrap(); let setup_chan_clone = setup_chan.clone(); spawn_named("ResourceManager".to_owned(), move || { let resource_manager = ResourceManager::new( user_agent, setup_chan_clone, hsts_preload, devtools_chan ); let mut channel_manager = ResourceChannelManager { from_client: setup_port, resource_manager: resource_manager }; channel_manager.start(); }); setup_chan } struct ResourceChannelManager { from_client: IpcReceiver<ControlMsg>, resource_manager: ResourceManager } impl ResourceChannelManager { fn start(&mut self) { loop { match self.from_client.recv().unwrap() { ControlMsg::Load(load_data, consumer) => { self.resource_manager.load(load_data, consumer) } ControlMsg::SetCookiesForUrl(request, cookie_list, source) => { self.resource_manager.set_cookies_for_url(request, cookie_list, source) } ControlMsg::GetCookiesForUrl(url, consumer, source) => { consumer.send(self.resource_manager.cookie_storage.cookies_for_url(&url, source)).unwrap(); } ControlMsg::SetHSTSEntryForHost(host, include_subdomains, max_age) => { if let Some(entry) = HSTSEntry::new(host, include_subdomains, Some(max_age)) { self.resource_manager.add_hsts_entry(entry) } } ControlMsg::Exit => { break } } } } } pub struct ResourceManager { user_agent: Option<String>, cookie_storage: CookieStorage, resource_task: IpcSender<ControlMsg>, mime_classifier: Arc<MIMEClassifier>, devtools_chan: Option<Sender<DevtoolsControlMsg>>, hsts_list: Arc<Mutex<HSTSList>> } impl ResourceManager { pub fn new(user_agent: Option<String>, resource_task: IpcSender<ControlMsg>, hsts_list: HSTSList, devtools_channel: Option<Sender<DevtoolsControlMsg>>) -> ResourceManager { ResourceManager { user_agent: user_agent, cookie_storage: CookieStorage::new(), resource_task: resource_task, mime_classifier: Arc::new(MIMEClassifier::new()), devtools_chan: devtools_channel, hsts_list: Arc::new(Mutex::new(hsts_list)) } } }<|fim▁hole|> if let Ok(SetCookie(cookies)) = header { for bare_cookie in cookies.into_iter() { if let Some(cookie) = cookie::Cookie::new_wrapped(bare_cookie, &request, source) { self.cookie_storage.push(cookie, source); } } } } pub fn add_hsts_entry(&mut self, entry: HSTSEntry) { self.hsts_list.lock().unwrap().push(entry); } pub fn is_host_sts(&self, host: &str) -> bool { self.hsts_list.lock().unwrap().is_host_secure(host) } fn load(&mut self, mut load_data: LoadData, consumer: LoadConsumer) { self.user_agent.as_ref().map(|ua| { load_data.preserved_headers.set(UserAgent(ua.clone())); }); fn from_factory(factory: fn(LoadData, LoadConsumer, Arc<MIMEClassifier>)) -> Box<FnBox(LoadData, LoadConsumer, Arc<MIMEClassifier>) + Send> { box move |load_data, senders, classifier| { factory(load_data, senders, classifier) } } let loader = match &*load_data.url.scheme { "file" => from_factory(file_loader::factory), "http" | "https" | "view-source" => http_loader::factory(self.resource_task.clone(), self.devtools_chan.clone(), self.hsts_list.clone()), "data" => from_factory(data_loader::factory), "about" => from_factory(about_loader::factory), _ => { debug!("resource_task: no loader for scheme {}", load_data.url.scheme); start_sending(consumer, Metadata::default(load_data.url)) .send(ProgressMsg::Done(Err("no loader for scheme".to_string()))).unwrap(); return } }; debug!("resource_task: loading url: {}", load_data.url.serialize()); loader.call_box((load_data, consumer, self.mime_classifier.clone())); } }<|fim▁end|>
impl ResourceManager { fn set_cookies_for_url(&mut self, request: Url, cookie_list: String, source: CookieSource) { let header = Header::parse_header(&[cookie_list.into_bytes()]);
<|file_name|>SettableDisposable.ts<|end_file_name|><|fim▁begin|>/** @license MIT License (c) copyright 2010-2017 original author or authors */ import { Disposable } from '@most/types' export default class SettableDisposable implements Disposable { private disposable?: Disposable; private disposed: boolean; constructor() { this.disposable = undefined this.disposed = false } setDisposable(disposable: Disposable): void { if (this.disposable !== undefined) { throw new Error('setDisposable called more than once') } this.disposable = disposable if (this.disposed) { disposable.dispose() } } dispose(): void { if (this.disposed) { return } this.disposed = true if (this.disposable !== undefined) { this.disposable.dispose()<|fim▁hole|><|fim▁end|>
} } }
<|file_name|>monitor.cpp<|end_file_name|><|fim▁begin|>#include <QDebug> #include <net/if.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/ioctl.h> #include "monitor.h"<|fim▁hole|>Monitor::Monitor() { running = 0; } void Monitor::start() { int rc; int s; fd_set rdfs; int nbytes; struct sockaddr_can addr; struct canfd_frame frame; struct iovec iov; char ctrlmsg[CMSG_SPACE(sizeof(struct timeval)) + CMSG_SPACE(sizeof(__u32))]; struct msghdr msg; struct ifreq ifr; char* ifname = "can0"; running = 1; s = socket(PF_CAN, SOCK_RAW, CAN_RAW); if (s < 0) { qDebug() << "Error opening socket: " << s; stop(); return; } strcpy(ifr.ifr_name, ifname); ioctl(s, SIOCGIFINDEX, &ifr); addr.can_family = AF_CAN; addr.can_ifindex = ifr.ifr_ifindex; rc = bind(s, (struct sockaddr*)&addr, sizeof(addr)); if (rc < 0) { qDebug() << "Error binding to interface: " << rc; stop(); return; } iov.iov_base = &frame; msg.msg_name = &addr; msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_control = &ctrlmsg; while (running) { FD_ZERO(&rdfs); FD_SET(s, &rdfs); rc = select(s, &rdfs, NULL, NULL, NULL); if (rc < 0) { qDebug() << "Error calling select" << rc; stop(); continue; } if (FD_ISSET(s, &rdfs)) { int maxdlen; // These can apparently get changed, so set before each read iov.iov_len = sizeof(frame); msg.msg_namelen = sizeof(addr); msg.msg_controllen = sizeof(ctrlmsg); msg.msg_flags = 0; nbytes = recvmsg(s, &msg, 0); if (nbytes < 0) { qDebug() << "Error calling recvmsg : " << nbytes; stop(); continue; } if ((size_t)nbytes == CAN_MTU) maxdlen = CAN_MAX_DLEN; else if ((size_t)nbytes == CANFD_MTU) maxdlen = CANFD_MAX_DLEN; else { qDebug() << "Warning: read incomplete CAN frame : " << nbytes; continue; } // TODO get timestamp from message sendMsg(&frame, maxdlen); } } } void Monitor::stop() { running = 0; } void Monitor::sendMsg(struct canfd_frame *frame, int maxdlen) { canMessage msg; char buf[200]; int pBuf = 0; int i; int len = (frame->len > maxdlen) ? maxdlen : frame->len; msg.interface = 1; // TODO set in constructor at some point msg.identifier = QString("%1:%03X") .arg(msg.interface) .arg(frame->can_id & CAN_SFF_MASK); msg.time = QTime::currentTime(); pBuf += sprintf(buf + pBuf, "[%d]", frame->len); if (frame->can_id & CAN_RTR_FLAG) { pBuf += sprintf(buf + pBuf, " remote request"); emit messageInBuffer(&msg); return; } for (i = 0; i < len; i++) { pBuf += sprintf(buf + pBuf, " [%02X]", frame->data[i]); } msg.content = QString("%1").arg(buf); emit messageInBuffer(&msg); }<|fim▁end|>
<|file_name|>user.server.model.js<|end_file_name|><|fim▁begin|><|fim▁hole|> bcrypt = require('bcrypt'), userSchema = mongoose.Schema({ fullName: { type: String }, email: { type: String, required: true, unique: true, lowercase: true }, password: { type: String, required: true }, user_avatar: { type: String, default: 'http://s3.amazonaws.com/37assets/svn/765-default-avatar.png' }, registered_on: { type: Date, default: Date.now } }); userSchema.pre('save', function(next) { var user = this; if (!user.isModified('password')) { return next(); } bcrypt.genSalt(10, function(err, salt) { bcrypt.hash(user.password, salt, function(err, hash) { user.password = hash; next(); }); }); }); userSchema.methods.comparePassword = function(password, done) { bcrypt.compare(password, this.password, function(err, isMatch) { done(err, isMatch); }); }; module.exports = mongoose.model('User', userSchema, 'users');<|fim▁end|>
var mongoose = require('mongoose'),
<|file_name|>translate.ts<|end_file_name|><|fim▁begin|>import { getVendorPrefixedName } from './prefixes'; import { camelCase } from './camel-case'; // browser detection and prefixing tools const transform = typeof window !== 'undefined' ? getVendorPrefixedName('transform') : undefined; const backfaceVisibility = typeof window !== 'undefined' ? getVendorPrefixedName('backfaceVisibility') : undefined; const hasCSSTransforms = typeof window !== 'undefined' ? !!getVendorPrefixedName('transform') : undefined; const hasCSS3DTransforms = typeof window !== 'undefined' ? !!getVendorPrefixedName('perspective') : undefined; const ua = typeof window !== 'undefined' ? window.navigator.userAgent : 'Chrome'; const isSafari = /Safari\//.test(ua) && !/Chrome\//.test(ua); export function translateXY(styles: any, x: number, y: number) { if (typeof transform !== 'undefined' && hasCSSTransforms) { if (!isSafari && hasCSS3DTransforms) { styles[transform] = `translate3d(${x}px, ${y}px, 0)`; styles[backfaceVisibility] = 'hidden'; } else { styles[camelCase(transform)] = `translate(${x}px, ${y}px)`; } } else { styles.top = `${y}px`; styles.left = `${x}px`;<|fim▁hole|><|fim▁end|>
} }
<|file_name|>IfcMember.cpp<|end_file_name|><|fim▁begin|>/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */ #include <sstream> #include <limits> #include "ifcpp/model/AttributeObject.h" #include "ifcpp/model/BuildingException.h" #include "ifcpp/model/BuildingGuid.h" #include "ifcpp/reader/ReaderUtil.h" #include "ifcpp/writer/WriterUtil.h" #include "ifcpp/IFC4/include/IfcGloballyUniqueId.h" #include "ifcpp/IFC4/include/IfcIdentifier.h" #include "ifcpp/IFC4/include/IfcLabel.h" #include "ifcpp/IFC4/include/IfcMember.h" #include "ifcpp/IFC4/include/IfcMemberTypeEnum.h" #include "ifcpp/IFC4/include/IfcObjectPlacement.h" #include "ifcpp/IFC4/include/IfcOwnerHistory.h" #include "ifcpp/IFC4/include/IfcProductRepresentation.h" #include "ifcpp/IFC4/include/IfcRelAggregates.h" #include "ifcpp/IFC4/include/IfcRelAssigns.h" #include "ifcpp/IFC4/include/IfcRelAssignsToProduct.h" #include "ifcpp/IFC4/include/IfcRelAssociates.h" #include "ifcpp/IFC4/include/IfcRelConnectsElements.h" #include "ifcpp/IFC4/include/IfcRelConnectsWithRealizingElements.h" #include "ifcpp/IFC4/include/IfcRelContainedInSpatialStructure.h" #include "ifcpp/IFC4/include/IfcRelCoversBldgElements.h" #include "ifcpp/IFC4/include/IfcRelDeclares.h" #include "ifcpp/IFC4/include/IfcRelDefinesByObject.h" #include "ifcpp/IFC4/include/IfcRelDefinesByProperties.h" #include "ifcpp/IFC4/include/IfcRelDefinesByType.h" #include "ifcpp/IFC4/include/IfcRelFillsElement.h" #include "ifcpp/IFC4/include/IfcRelInterferesElements.h" #include "ifcpp/IFC4/include/IfcRelNests.h" #include "ifcpp/IFC4/include/IfcRelProjectsElement.h" #include "ifcpp/IFC4/include/IfcRelReferencedInSpatialStructure.h" #include "ifcpp/IFC4/include/IfcRelSpaceBoundary.h" #include "ifcpp/IFC4/include/IfcRelVoidsElement.h" #include "ifcpp/IFC4/include/IfcText.h" // ENTITY IfcMember IfcMember::IfcMember( int id ) { m_entity_id = id; } shared_ptr<BuildingObject> IfcMember::getDeepCopy( BuildingCopyOptions& options ) { shared_ptr<IfcMember> copy_self( new IfcMember() ); if( m_GlobalId ) <|fim▁hole|> if( options.create_new_IfcGloballyUniqueId ) { copy_self->m_GlobalId = make_shared<IfcGloballyUniqueId>( createBase64Uuid_wstr().data() ); } else { copy_self->m_GlobalId = dynamic_pointer_cast<IfcGloballyUniqueId>( m_GlobalId->getDeepCopy(options) ); } } if( m_OwnerHistory ) { if( options.shallow_copy_IfcOwnerHistory ) { copy_self->m_OwnerHistory = m_OwnerHistory; } else { copy_self->m_OwnerHistory = dynamic_pointer_cast<IfcOwnerHistory>( m_OwnerHistory->getDeepCopy(options) ); } } if( m_Name ) { copy_self->m_Name = dynamic_pointer_cast<IfcLabel>( m_Name->getDeepCopy(options) ); } if( m_Description ) { copy_self->m_Description = dynamic_pointer_cast<IfcText>( m_Description->getDeepCopy(options) ); } if( m_ObjectType ) { copy_self->m_ObjectType = dynamic_pointer_cast<IfcLabel>( m_ObjectType->getDeepCopy(options) ); } if( m_ObjectPlacement ) { copy_self->m_ObjectPlacement = dynamic_pointer_cast<IfcObjectPlacement>( m_ObjectPlacement->getDeepCopy(options) ); } if( m_Representation ) { copy_self->m_Representation = dynamic_pointer_cast<IfcProductRepresentation>( m_Representation->getDeepCopy(options) ); } if( m_Tag ) { copy_self->m_Tag = dynamic_pointer_cast<IfcIdentifier>( m_Tag->getDeepCopy(options) ); } if( m_PredefinedType ) { copy_self->m_PredefinedType = dynamic_pointer_cast<IfcMemberTypeEnum>( m_PredefinedType->getDeepCopy(options) ); } return copy_self; } void IfcMember::getStepLine( std::stringstream& stream ) const { stream << "#" << m_entity_id << "= IFCMEMBER" << "("; if( m_GlobalId ) { m_GlobalId->getStepParameter( stream ); } else { stream << "$"; } stream << ","; if( m_OwnerHistory ) { stream << "#" << m_OwnerHistory->m_entity_id; } else { stream << "$"; } stream << ","; if( m_Name ) { m_Name->getStepParameter( stream ); } else { stream << "$"; } stream << ","; if( m_Description ) { m_Description->getStepParameter( stream ); } else { stream << "$"; } stream << ","; if( m_ObjectType ) { m_ObjectType->getStepParameter( stream ); } else { stream << "$"; } stream << ","; if( m_ObjectPlacement ) { stream << "#" << m_ObjectPlacement->m_entity_id; } else { stream << "$"; } stream << ","; if( m_Representation ) { stream << "#" << m_Representation->m_entity_id; } else { stream << "$"; } stream << ","; if( m_Tag ) { m_Tag->getStepParameter( stream ); } else { stream << "$"; } stream << ","; if( m_PredefinedType ) { m_PredefinedType->getStepParameter( stream ); } else { stream << "$"; } stream << ");"; } void IfcMember::getStepParameter( std::stringstream& stream, bool /*is_select_type*/ ) const { stream << "#" << m_entity_id; } const std::wstring IfcMember::toString() const { return L"IfcMember"; } void IfcMember::readStepArguments( const std::vector<std::wstring>& args, const std::map<int,shared_ptr<BuildingEntity> >& map ) { const size_t num_args = args.size(); if( num_args != 9 ){ std::stringstream err; err << "Wrong parameter count for entity IfcMember, expecting 9, having " << num_args << ". Entity ID: " << m_entity_id << std::endl; throw BuildingException( err.str().c_str() ); } m_GlobalId = IfcGloballyUniqueId::createObjectFromSTEP( args[0], map ); readEntityReference( args[1], m_OwnerHistory, map ); m_Name = IfcLabel::createObjectFromSTEP( args[2], map ); m_Description = IfcText::createObjectFromSTEP( args[3], map ); m_ObjectType = IfcLabel::createObjectFromSTEP( args[4], map ); readEntityReference( args[5], m_ObjectPlacement, map ); readEntityReference( args[6], m_Representation, map ); m_Tag = IfcIdentifier::createObjectFromSTEP( args[7], map ); m_PredefinedType = IfcMemberTypeEnum::createObjectFromSTEP( args[8], map ); } void IfcMember::getAttributes( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes ) const { IfcBuildingElement::getAttributes( vec_attributes ); vec_attributes.emplace_back( std::make_pair( "PredefinedType", m_PredefinedType ) ); } void IfcMember::getAttributesInverse( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes_inverse ) const { IfcBuildingElement::getAttributesInverse( vec_attributes_inverse ); } void IfcMember::setInverseCounterparts( shared_ptr<BuildingEntity> ptr_self_entity ) { IfcBuildingElement::setInverseCounterparts( ptr_self_entity ); } void IfcMember::unlinkFromInverseCounterparts() { IfcBuildingElement::unlinkFromInverseCounterparts(); }<|fim▁end|>
{
<|file_name|>main.js<|end_file_name|><|fim▁begin|>/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var Readable = require( 'readable-stream' ).Readable; var isPositiveNumber = require( '@stdlib/assert/is-positive-number' ).isPrimitive; var isProbability = require( '@stdlib/assert/is-probability' ).isPrimitive; var isError = require( '@stdlib/assert/is-error' ); var copy = require( '@stdlib/utils/copy' ); var inherit = require( '@stdlib/utils/inherit' ); var setNonEnumerable = require( '@stdlib/utils/define-nonenumerable-property' ); var setNonEnumerableReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var setReadOnlyAccessor = require( '@stdlib/utils/define-read-only-accessor' ); var setReadWriteAccessor = require( '@stdlib/utils/define-read-write-accessor' ); var rnbinom = require( '@stdlib/random/base/negative-binomial' ).factory; var string2buffer = require( '@stdlib/buffer/from-string' ); var nextTick = require( '@stdlib/utils/next-tick' ); var DEFAULTS = require( './defaults.json' ); var validate = require( './validate.js' ); var debug = require( './debug.js' ); // FUNCTIONS // /** * Returns the PRNG seed. * * @private * @returns {(PRNGSeedMT19937|null)} seed */ function getSeed() { return this._prng.seed; // eslint-disable-line no-invalid-this } /** * Returns the PRNG seed length. * * @private * @returns {(PositiveInteger|null)} seed length */ function getSeedLength() { return this._prng.seedLength; // eslint-disable-line no-invalid-this } /** * Returns the PRNG state length. * * @private * @returns {(PositiveInteger|null)} state length */ function getStateLength() { return this._prng.stateLength; // eslint-disable-line no-invalid-this } /** * Returns the PRNG state size (in bytes). * * @private * @returns {(PositiveInteger|null)} state size (in bytes) */ function getStateSize() { return this._prng.byteLength; // eslint-disable-line no-invalid-this } /** * Returns the current PRNG state. * * @private * @returns {(PRNGStateMT19937|null)} current state */ function getState() { return this._prng.state; // eslint-disable-line no-invalid-this } /** * Sets the PRNG state. * * @private * @param {PRNGStateMT19937} s - generator state * @throws {Error} must provide a valid state */ function setState( s ) { this._prng.state = s; // eslint-disable-line no-invalid-this } /** * Implements the `_read` method. * * @private * @param {number} size - number (of bytes) to read * @returns {void} */ function read() { /* eslint-disable no-invalid-this */ var FLG; var r; if ( this._destroyed ) { return; } FLG = true; while ( FLG ) { this._i += 1; if ( this._i > this._iter ) { debug( 'Finished generating pseudorandom numbers.' ); return this.push( null ); } r = this._prng(); debug( 'Generated a new pseudorandom number. Value: %d. Iter: %d.', r, this._i ); if ( this._objectMode === false ) { r = r.toString(); if ( this._i === 1 ) { r = string2buffer( r ); } else { r = string2buffer( this._sep+r ); } } FLG = this.push( r ); if ( this._i%this._siter === 0 ) { this.emit( 'state', this.state ); } } /* eslint-enable no-invalid-this */ } /** * Gracefully destroys a stream, providing backward compatibility. * * @private * @param {(string|Object|Error)} [error] - error * @returns {RandomStream} Stream instance */ function destroy( error ) { /* eslint-disable no-invalid-this */ var self; if ( this._destroyed ) { debug( 'Attempted to destroy an already destroyed stream.' ); return this; } self = this; this._destroyed = true; nextTick( close ); return this; /** * Closes a stream. * * @private */ function close() { if ( error ) { debug( 'Stream was destroyed due to an error. Error: %s.', ( isError( error ) ) ? error.message : JSON.stringify( error ) ); self.emit( 'error', error ); } debug( 'Closing the stream...' ); self.emit( 'close' ); } /* eslint-enable no-invalid-this */ } // MAIN // /** * Stream constructor for generating a stream of pseudorandom numbers drawn from a binomial distribution. * * @constructor * @param {PositiveNumber} r - number of successes until experiment is stopped * @param {Probability} p - success probability * @param {Options} [options] - stream options * @param {boolean} [options.objectMode=false] - specifies whether the stream should operate in object mode * @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to strings * @param {NonNegativeNumber} [options.highWaterMark] - specifies the maximum number of bytes to store in an internal buffer before ceasing to generate additional pseudorandom numbers * @param {string} [options.sep='\n'] - separator used to join streamed data * @param {NonNegativeInteger} [options.iter] - number of iterations * @param {PRNG} [options.prng] - pseudorandom number generator which generates uniformly distributed pseudorandom numbers * @param {PRNGSeedMT19937} [options.seed] - pseudorandom number generator seed * @param {PRNGStateMT19937} [options.state] - pseudorandom number generator state * @param {boolean} [options.copy=true] - boolean indicating whether to copy a provided pseudorandom number generator state * @param {PositiveInteger} [options.siter] - number of iterations after which to emit the PRNG state * @throws {TypeError} `r` must be a positive number * @throws {TypeError} `p` must be a probability * @throws {TypeError} options argument must be an object * @throws {TypeError} must provide valid options * @throws {Error} must provide a valid state * @returns {RandomStream} Stream instance * * @example * var inspectStream = require( '@stdlib/streams/node/inspect-sink' );<|fim▁hole|>* console.log( chunk.toString() ); * } * * var opts = { * 'iter': 10 * }; * * var stream = new RandomStream( 20.0, 0.2, opts ); * * stream.pipe( inspectStream( log ) ); */ function RandomStream( r, p, options ) { var opts; var err; if ( !( this instanceof RandomStream ) ) { if ( arguments.length > 2 ) { return new RandomStream( r, p, options ); } return new RandomStream( r, p ); } if ( !isPositiveNumber( r ) ) { throw new TypeError( 'invalid argument. First argument must be a positive number. Value: `'+r+'`.' ); } if ( !isProbability( p ) ) { throw new TypeError( 'invalid argument. Second argument must be a probability. Value: `'+p+'`.' ); } opts = copy( DEFAULTS ); if ( arguments.length > 2 ) { err = validate( opts, options ); if ( err ) { throw err; } } // Make the stream a readable stream: debug( 'Creating a readable stream configured with the following options: %s.', JSON.stringify( opts ) ); Readable.call( this, opts ); // Destruction state: setNonEnumerable( this, '_destroyed', false ); // Cache whether the stream is operating in object mode: setNonEnumerableReadOnly( this, '_objectMode', opts.objectMode ); // Cache the separator: setNonEnumerableReadOnly( this, '_sep', opts.sep ); // Cache the total number of iterations: setNonEnumerableReadOnly( this, '_iter', opts.iter ); // Cache the number of iterations after which to emit the underlying PRNG state: setNonEnumerableReadOnly( this, '_siter', opts.siter ); // Initialize an iteration counter: setNonEnumerable( this, '_i', 0 ); // Create the underlying PRNG: setNonEnumerableReadOnly( this, '_prng', rnbinom( r, p, opts ) ); setNonEnumerableReadOnly( this, 'PRNG', this._prng.PRNG ); return this; } /* * Inherit from the `Readable` prototype. */ inherit( RandomStream, Readable ); /** * PRNG seed. * * @name seed * @memberof RandomStream.prototype * @type {(PRNGSeedMT19937|null)} */ setReadOnlyAccessor( RandomStream.prototype, 'seed', getSeed ); /** * PRNG seed length. * * @name seedLength * @memberof RandomStream.prototype * @type {(PositiveInteger|null)} */ setReadOnlyAccessor( RandomStream.prototype, 'seedLength', getSeedLength ); /** * PRNG state getter/setter. * * @name state * @memberof RandomStream.prototype * @type {(PRNGStateMT19937|null)} * @throws {Error} must provide a valid state */ setReadWriteAccessor( RandomStream.prototype, 'state', getState, setState ); /** * PRNG state length. * * @name stateLength * @memberof RandomStream.prototype * @type {(PositiveInteger|null)} */ setReadOnlyAccessor( RandomStream.prototype, 'stateLength', getStateLength ); /** * PRNG state size (in bytes). * * @name byteLength * @memberof RandomStream.prototype * @type {(PositiveInteger|null)} */ setReadOnlyAccessor( RandomStream.prototype, 'byteLength', getStateSize ); /** * Implements the `_read` method. * * @private * @name _read * @memberof RandomStream.prototype * @type {Function} * @param {number} size - number (of bytes) to read * @returns {void} */ setNonEnumerableReadOnly( RandomStream.prototype, '_read', read ); /** * Gracefully destroys a stream, providing backward compatibility. * * @name destroy * @memberof RandomStream.prototype * @type {Function} * @param {(string|Object|Error)} [error] - error * @returns {RandomStream} Stream instance */ setNonEnumerableReadOnly( RandomStream.prototype, 'destroy', destroy ); // EXPORTS // module.exports = RandomStream;<|fim▁end|>
* * function log( chunk ) {
<|file_name|>datacenter.js<|end_file_name|><|fim▁begin|>import emotion from 'preact-emotion'; import remcalc from 'remcalc'; import { Category } from './service';<|fim▁hole|> export const Place = emotion(Category)` margin-bottom: ${remcalc(10)}; `; export const Region = emotion('h6')` margin: ${remcalc(6)} 0; font-size: ${remcalc(13)}; line-height: ${remcalc(18)}; font-weight: ${props => props.theme.font.weight.normal}; color: #494949; `; export { Name as default } from './service';<|fim▁end|>
<|file_name|>operations.go<|end_file_name|><|fim▁begin|>package desktopvirtualization // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "context" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/tracing" "net/http" ) // OperationsClient is the client for the Operations methods of the Desktopvirtualization service. type OperationsClient struct { BaseClient } // NewOperationsClient creates an instance of the OperationsClient client. func NewOperationsClient(subscriptionID string) OperationsClient { return NewOperationsClientWithBaseURI(DefaultBaseURI, subscriptionID) } // NewOperationsClientWithBaseURI creates an instance of the OperationsClient client using a custom endpoint. Use this // when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). func NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) OperationsClient { return OperationsClient{NewWithBaseURI(baseURI, subscriptionID)} } // List list all of the available operations the Desktop Virtualization resource provider supports. func (client OperationsClient) List(ctx context.Context) (result ResourceProviderOperationList, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/OperationsClient.List") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.ListPreparer(ctx) if err != nil { err = autorest.NewErrorWithError(err, "desktopvirtualization.OperationsClient", "List", nil, "Failure preparing request") return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "desktopvirtualization.OperationsClient", "List", resp, "Failure sending request") return } result, err = client.ListResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "desktopvirtualization.OperationsClient", "List", resp, "Failure responding to request") return } return } // ListPreparer prepares the List request. func (client OperationsClient) ListPreparer(ctx context.Context) (*http.Request, error) { const APIVersion = "2020-11-02-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPath("/providers/Microsoft.DesktopVirtualization/operations"), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client OperationsClient) ListSender(req *http.Request) (*http.Response, error) { return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) } // ListResponder handles the response to the List request. The method always // closes the http.Response Body. func (client OperationsClient) ListResponder(resp *http.Response) (result ResourceProviderOperationList, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp}<|fim▁hole|><|fim▁end|>
return }
<|file_name|>pos_receipt.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import time from openerp.osv import osv from openerp.report import report_sxw def titlize(journal_name): words = journal_name.split() while words.pop() != 'journal': continue return ' '.join(words) class order(report_sxw.rml_parse): def __init__(self, cr, uid, name, context): super(order, self).__init__(cr, uid, name, context=context) user = self.pool['res.users'].browse(cr, uid, uid, context=context) partner = user.company_id.partner_id <|fim▁hole|> 'net': self.netamount, 'get_journal_amt': self._get_journal_amt, 'address': partner or False, 'titlize': titlize }) def netamount(self, order_line_id): sql = 'select (qty*price_unit) as net_price from pos_order_line where id = %s' self.cr.execute(sql, (order_line_id,)) res = self.cr.fetchone() return res[0] def discount(self, order_id): sql = 'select discount, price_unit, qty from pos_order_line where order_id = %s ' self.cr.execute(sql, (order_id,)) res = self.cr.fetchall() dsum = 0 for line in res: if line[0] != 0: dsum = dsum +(line[2] * (line[0]*line[1]/100)) return dsum def _get_journal_amt(self, order_id): data={} sql = """ select aj.name,absl.amount as amt from account_bank_statement as abs LEFT JOIN account_bank_statement_line as absl ON abs.id = absl.statement_id LEFT JOIN account_journal as aj ON aj.id = abs.journal_id WHERE absl.pos_statement_id =%d"""%(order_id) self.cr.execute(sql) data = self.cr.dictfetchall() return data class report_order_receipt(osv.AbstractModel): _name = 'report.point_of_sale.report_receipt' _inherit = 'report.abstract_report' _template = 'point_of_sale.report_receipt' _wrapped_report_class = order<|fim▁end|>
self.localcontext.update({ 'time': time, 'disc': self.discount,
<|file_name|>tests.rs<|end_file_name|><|fim▁begin|>use crate::Server; use std::path::PathBuf; use std::sync::Arc; use std::time::Duration; use futures::future; use nails::execution::{child_channel, ChildInput, Command, ExitCode}; use nails::Config; use task_executor::Executor; use tokio::net::TcpStream; use tokio::runtime::Handle; use tokio::sync::Notify; use tokio::time::delay_for; #[tokio::test] async fn spawn_and_bind() { let server = Server::new(Executor::new(), 0, |_| ExitCode(0)) .await .unwrap(); // Should have bound a random port. assert!(0 != server.port()); server.shutdown().await.unwrap(); } #[tokio::test] async fn accept() { let exit_code = ExitCode(42); let server = Server::new(Executor::new(), 0, move |_| exit_code) .await .unwrap(); // And connect with a client. This Nail will ignore the content of the command, so we're // only validating the exit code. let actual_exit_code = run_client(server.port()).await.unwrap(); assert_eq!(exit_code, actual_exit_code); server.shutdown().await.unwrap(); } #[tokio::test] async fn shutdown_awaits_ongoing() { // A server that waits for a signal to complete a connection. let connection_accepted = Arc::new(Notify::new()); let should_complete_connection = Arc::new(Notify::new()); let exit_code = ExitCode(42); let server = Server::new(Executor::new(), 0, { let connection_accepted = connection_accepted.clone(); let should_complete_connection = should_complete_connection.clone(); move |_| { connection_accepted.notify(); Handle::current().block_on(should_complete_connection.notified()); exit_code } }) .await .unwrap(); // Spawn a connection in the background, and once it has been established, kick off shutdown of // the server. let mut client_completed = tokio::spawn(run_client(server.port())); connection_accepted.notified().await; let mut server_shutdown = tokio::spawn(server.shutdown()); // Confirm that the client doesn't return, and that the server doesn't shutdown. match future::select(client_completed, delay_for(Duration::from_millis(500))).await { future::Either::Right((_, c_c)) => client_completed = c_c, x => panic!("Client should not have completed: {:?}", x), } match future::select(server_shutdown, delay_for(Duration::from_millis(500))).await {<|fim▁hole|> // Then signal completion of the connection, and confirm that both the client and server exit // cleanly. should_complete_connection.notify(); assert_eq!(exit_code, client_completed.await.unwrap().unwrap()); server_shutdown.await.unwrap().unwrap(); } async fn run_client(port: u16) -> Result<ExitCode, String> { let cmd = Command { command: "nothing".to_owned(), args: vec![], env: vec![], working_dir: PathBuf::from("/dev/null"), }; let stream = TcpStream::connect(("127.0.0.1", port)).await.unwrap(); let child = nails::client::handle_connection(Config::default(), stream, cmd, async { let (_stdin_write, stdin_read) = child_channel::<ChildInput>(); stdin_read }) .await .map_err(|e| e.to_string())?; child.wait().await.map_err(|e| e.to_string()) }<|fim▁end|>
future::Either::Right((_, s_s)) => server_shutdown = s_s, x => panic!("Server should not have shut down: {:?}", x), }
<|file_name|>user.py<|end_file_name|><|fim▁begin|>import factory from zeus import models from zeus.utils import timezone<|fim▁hole|> class UserFactory(ModelFactory): id = GUIDFactory() email = factory.Faker("email") date_created = factory.LazyAttribute(lambda o: timezone.now()) date_active = factory.LazyAttribute(lambda o: o.date_created) class Meta: model = models.User<|fim▁end|>
from .base import ModelFactory from .types import GUIDFactory
<|file_name|>connectors.py<|end_file_name|><|fim▁begin|>from asyncio import AbstractEventLoop import aiomysql.sa import asyncpg from asyncio_extras import async_contextmanager from cetus.types import (ConnectionType, MySQLConnectionType, PostgresConnectionType) from sqlalchemy.engine.url import URL DEFAULT_MYSQL_PORT = 3306 DEFAULT_POSTGRES_PORT = 5432 DEFAULT_MIN_CONNECTIONS_LIMIT = 10 DEFAULT_CONNECTION_TIMEOUT = 60 @async_contextmanager async def get_connection_pool( *, db_uri: URL, is_mysql: bool, timeout: float = DEFAULT_CONNECTION_TIMEOUT, min_size: int = DEFAULT_MIN_CONNECTIONS_LIMIT, max_size: int, loop: AbstractEventLoop): if is_mysql: async with get_mysql_connection_pool( db_uri, timeout=timeout, min_size=min_size, max_size=max_size, loop=loop) as connection_pool: yield connection_pool else: async with get_postgres_connection_pool( db_uri, timeout=timeout, min_size=min_size, max_size=max_size, loop=loop) as connection_pool: yield connection_pool @async_contextmanager async def get_mysql_connection_pool( db_uri: URL, *, timeout: float = DEFAULT_CONNECTION_TIMEOUT, min_size: int = DEFAULT_MIN_CONNECTIONS_LIMIT, max_size: int, loop: AbstractEventLoop): # `None` port causes exceptions port = db_uri.port or DEFAULT_MYSQL_PORT # we use engine instead of plain connection pool # because `aiomysql` has transactions API # only for engine-based connections async with aiomysql.sa.create_engine( host=db_uri.host, port=port, user=db_uri.username, password=db_uri.password, db=db_uri.database, charset='utf8', connect_timeout=timeout, # TODO: check if `asyncpg` connections # are autocommit by default autocommit=True, minsize=min_size, maxsize=max_size, loop=loop) as engine: yield engine @async_contextmanager async def get_postgres_connection_pool( db_uri: URL, *, timeout: float = DEFAULT_CONNECTION_TIMEOUT, min_size: int = DEFAULT_MIN_CONNECTIONS_LIMIT, max_size: int, loop: AbstractEventLoop): # for symmetry with MySQL case port = db_uri.port or DEFAULT_POSTGRES_PORT async with asyncpg.create_pool( host=db_uri.host, port=port, user=db_uri.username, password=db_uri.password, database=db_uri.database, timeout=timeout, min_size=min_size, max_size=max_size, loop=loop) as pool: yield pool @async_contextmanager async def begin_transaction( *, connection: ConnectionType, is_mysql: bool): if is_mysql: async with begin_mysql_transaction(connection): yield else: async with begin_postgres_transaction(connection): yield @async_contextmanager async def begin_mysql_transaction( connection: MySQLConnectionType): transaction = connection.begin() async with transaction: yield @async_contextmanager async def begin_postgres_transaction( connection: PostgresConnectionType, *, isolation: str = 'read_committed', read_only: bool = False, deferrable: bool = False): transaction = connection.transaction( isolation=isolation, readonly=read_only, deferrable=deferrable) async with transaction: yield @async_contextmanager async def get_connection( *, db_uri: URL, is_mysql: bool, timeout: float = DEFAULT_CONNECTION_TIMEOUT, loop: AbstractEventLoop): if is_mysql: async with get_mysql_connection( db_uri, timeout=timeout, loop=loop) as connection: yield connection else: async with get_postgres_connection( db_uri, timeout=timeout, loop=loop) as connection: yield connection @async_contextmanager async def get_mysql_connection( db_uri: URL, *, timeout: float = DEFAULT_CONNECTION_TIMEOUT, loop: AbstractEventLoop): # `None` port causes exceptions port = db_uri.port or DEFAULT_MYSQL_PORT # we use engine-based connection # instead of plain connection # because `aiomysql` has transactions API # only for engine-based connections async with aiomysql.sa.create_engine(<|fim▁hole|> port=port, user=db_uri.username, password=db_uri.password, db=db_uri.database, charset='utf8', connect_timeout=timeout, # TODO: check if `asyncpg` connections # are autocommit by default autocommit=True, minsize=1, maxsize=1, loop=loop) as engine: async with engine.acquire() as connection: yield connection @async_contextmanager async def get_postgres_connection( db_uri: URL, *, timeout: float = DEFAULT_CONNECTION_TIMEOUT, loop: AbstractEventLoop): # for symmetry with MySQL case port = db_uri.port or DEFAULT_POSTGRES_PORT connection = await asyncpg.connect( host=db_uri.host, port=port, user=db_uri.username, password=db_uri.password, database=db_uri.database, timeout=timeout, loop=loop) try: yield connection finally: await connection.close()<|fim▁end|>
host=db_uri.host,
<|file_name|>data.js<|end_file_name|><|fim▁begin|>import { apiUrl } from '../../constants'; export default class DataService { /** @ngInject */ constructor($http, $q) { this.$http = $http; this.$q = $q; this.dataStore = { categories: [], providers: [], resources: [], services: [], stages: [], currentFilters: { stages: [], categories: [], providers: [], resources: [] } }; } getCategories() { return getItems.bind(this)('categories'); } createProvider (provider) { return createItem.bind(this)(provider, 'providers'); } deleteProvider (id) { return deleteItem.bind(this)(id, 'providers'); } getProvider(id) { return getItem.bind(this)(id, 'providers'); } getProviders() { return getItems.bind(this)('providers'); } updateProvider (provider) { return updateItem.bind(this)(provider, 'providers'); } createResource (resource) { return createItem.bind(this)(resource, 'resources'); } deleteResource (id) { return deleteItem.bind(this)(id, 'resources'); } getResource(id) { return getItem.bind(this)(id, 'resources'); } getResources() { return getItems.bind(this)('resources'); } updateResource (resource) { return updateItem.bind(this)(resource, 'resources'); } createService (service) { return createItem.bind(this)(service, 'services'); } deleteService(id) { return deleteItem.bind(this)(id, 'services'); } getService(id) { return getItem.bind(this)(id, 'services'); } getServices() { return getItems.bind(this)('services'); } updateService (service) { return updateItem.bind(this)(service, 'services'); } getStages() { return getItems.bind(this)('stages'); } resetCurrentFilters() { return this.dataStore.currentFilters = { stages: [],<|fim▁hole|> categories: [], providers: [], resources: [] } } getNonEmptyFilters() { const nonEmptyFilters = {}; if (this.dataStore.currentFilters.stages.length) { nonEmptyFilters.stages = angular.copy(this.dataStore.currentFilters.stages); } if (this.dataStore.currentFilters.categories.length) { nonEmptyFilters.categories = angular.copy(this.dataStore.currentFilters.categories); } if (this.dataStore.currentFilters.providers.length) { nonEmptyFilters.providers = angular.copy(this.dataStore.currentFilters.providers); } if (this.dataStore.currentFilters.resources.length) { nonEmptyFilters.resources = angular.copy(this.dataStore.currentFilters.resources); } return nonEmptyFilters; } } function createItem (item, type) { const deferred = this.$q.defer(); return this.$http.post(`${apiUrl}${type}`, item).then((response) => { const location = response.headers().location; const id = location.split(`/${type}/`).pop(); if (this.dataStore[type].length) { item.id = id; this.dataStore[type].push(item); } deferred.resolve(item.id); return deferred.promise; }, error => { deferred.reject(error); return deferred.promise; }); } function deleteItem (id, type) { const deferred = this.$q.defer(); return this.$http.delete(`${apiUrl}${type}/${id}`).then(() => { const index = this.dataStore[type].map((x) => {return x.id; }).indexOf(id); this.dataStore[type].splice(index, 1); deferred.resolve(); return deferred.promise; }, error => { deferred.reject(error); return deferred.promise; }); } function getItem (id, type) { const deferred = this.$q.defer(); const item = this.dataStore[type].filter(s => { return s.id === id; })[0]; if (item) { deferred.resolve(item); return deferred.promise; } return this.$http.get(`${apiUrl}${type}/${id}`).then(response => { deferred.resolve(response.data); return deferred.promise; }, error => { deferred.reject(error); return deferred.promise; }); } function getItems (type) { const deferred = this.$q.defer(); if (this.dataStore[type].length) { deferred.resolve(); return deferred.promise; } return this.$http.get(`${apiUrl}${type}`).then(response => { this.dataStore[type] = angular.copy(response.data._embedded[type]); deferred.resolve(); return deferred.promise; }, error => { deferred.reject(error); return deferred.promise; }); } function updateItem (item, type) { const deferred = this.$q.defer(); return this.$http.put(`${apiUrl}${type}/${item.id}`, item).then(() => { if (this.dataStore[type].length) { const index = this.dataStore[type].map((x) => {return x.id; }).indexOf(item.id); this.dataStore[type][index] = item; } deferred.resolve(); return deferred.promise; }, error => { deferred.reject(error); return deferred.promise; }); }<|fim▁end|>
<|file_name|>SpringDataVisitRepository.java<|end_file_name|><|fim▁begin|>/* * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 *<|fim▁hole|> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eu.solidcraft.starter.examples.example2.repository.springdatajpa; import eu.solidcraft.starter.examples.example2.model.Visit; import eu.solidcraft.starter.examples.example2.repository.VisitRepository; import org.springframework.data.repository.Repository; /** * Spring Data JPA specialization of the {@link VisitRepository} interface * * @author Michael Isvy * @since 15.1.2013 */ public interface SpringDataVisitRepository extends VisitRepository, Repository<Visit, Integer> { }<|fim▁end|>
* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS,
<|file_name|>EntityConverter.java<|end_file_name|><|fim▁begin|>/*- * See the file LICENSE for redistribution information. * * Copyright (c) 2002,2008 Oracle. All rights reserved. * * $Id: EntityConverter.java,v 1.11 2008/01/07 14:28:58 cwl Exp $ */ package com.sleepycat.persist.evolve; import java.util.Collections; import java.util.HashSet; import java.util.Set; /** * A subclass of Converter that allows specifying keys to be deleted. * * <p>When a Converter is used with an entity class, secondary keys cannot be<|fim▁hole|> * * <p>It is not currently possible to rename or insert secondary keys when * using a Converter mutation with an entity class.</p> * * @see Converter * @see com.sleepycat.persist.evolve Class Evolution * @author Mark Hayes */ public class EntityConverter extends Converter { private static final long serialVersionUID = -988428985370593743L; private Set<String> deletedKeys; /** * Creates a mutation for converting all instances of the given entity * class version to the current version of the class. */ public EntityConverter(String entityClassName, int classVersion, Conversion conversion, Set<String> deletedKeys) { super(entityClassName, classVersion, null, conversion); /* Eclipse objects to assigning with a ternary operator. */ if (deletedKeys != null) { this.deletedKeys = new HashSet(deletedKeys); } else { this.deletedKeys = Collections.emptySet(); } } /** * Returns the set of key names that are to be deleted. */ public Set<String> getDeletedKeys() { return Collections.unmodifiableSet(deletedKeys); } /** * Returns true if the deleted and renamed keys are equal in this object * and given object, and if the {@link Converter#equals} superclass method * returns true. */ @Override public boolean equals(Object other) { if (other instanceof EntityConverter) { EntityConverter o = (EntityConverter) other; return deletedKeys.equals(o.deletedKeys) && super.equals(other); } else { return false; } } @Override public int hashCode() { return deletedKeys.hashCode() + super.hashCode(); } @Override public String toString() { return "[EntityConverter " + super.toString() + " DeletedKeys: " + deletedKeys + ']'; } }<|fim▁end|>
* automatically deleted based on field deletion, because field Deleter objects * are not used in conjunction with a Converter mutation. The EntityConverter * can be used instead of a plain Converter to specify the key names to be * deleted.</p>
<|file_name|>urls.py<|end_file_name|><|fim▁begin|>from django.conf.urls.defaults import patterns, url urlpatterns = patterns('webapp', url(r'^/?$', 'views.home', name='home'), url(r'^auth_redirect$', 'views.auth_redirect', name='auth_redirect'), url(r'^nights$', 'views.night_index', name='night_index'), url(r'^song$', 'views.song_index', name='song_index'), url(r'^create_song$', 'views.song_create', name='song_create'), url(r'^song/(?P<key>[\w\d]+)$', 'views.song', name='song'), url(r'^song/(?P<key>[\w\d]+).mp3$', 'views.song_mp3', name='song_mp3'), url(r'^song/(?P<key>[\w\d]+)/edit$', 'views.song_edit', name='song_edit'), url(r'^song/(?P<key>[\w\d]+)/wait$', 'views.song_wait_finished', name='song_wait_finished'), url(r'^sign_out$', 'views.sign_out', name='sign_out'), <|fim▁hole|><|fim▁end|>
)
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.db import models<|fim▁hole|>class Language(models.Model): code = models.CharField(max_length=50, null=False, unique=True, verbose_name='Code', help_text='http://www.w3.org/International/articles/language-tags') display_name = models.CharField(max_length=255, null=False, verbose_name='Display Name') class Meta: ordering = ['code'] def __str__(self): return u"{0} - {1}".format(self.display_name, self.code)<|fim▁end|>
from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible
<|file_name|>guest-form.component.ts<|end_file_name|><|fim▁begin|>import { Component, Input, Output, EventEmitter } from '@angular/core'; import { IGuest } from '../../core'; @Component({ selector: 'wd-guest-form', styles: [require('./guest-form.css').toString()], template: require('./guest-form.html') })<|fim▁hole|> @Input() submitting: boolean; @Output() submitForm: EventEmitter<any> = new EventEmitter(); @Output() cancel: EventEmitter<any> = new EventEmitter(); constructor() { } }<|fim▁end|>
export class GuestFormComponent { @Input() title: string; @Input() guest: IGuest;
<|file_name|>qa.js<|end_file_name|><|fim▁begin|>import React, { Component } from 'react'; import Steps from './widgets/steps/steps'; import PropTypes from 'prop-types'; import { withStyles } from '@material-ui/core/styles'; const styles = { container: { display: 'flex', justifyContent: 'space-around', flexDirection: 'column', marginBottom: '1vh', flex: 1, }, green: { display: 'inline-block', verticalAlign: 'top', width: '10px', height: '10px', borderRadius: '50%', border: 'solid 1px #333', background: '#008000', fontSize: 0, textIndent: '-9999em', }, yellow: { display: 'inline-block', verticalAlign: 'top', width: '10px', height: '10px', borderRadius: '50%', border: 'solid 1px #333', background: '#ffff00', fontSize: 0, textIndent: '-9999em', }, red: { display: 'inline-block', verticalAlign: 'top', width: '10px', height: '10px', borderRadius: '50%', border: 'solid 1px #333', background: '#ff0000', fontSize: 0, textIndent: '-9999em', }, lightgray: { display: 'inline-block', verticalAlign: 'top', width: '10px', height: '10px', borderRadius: '50%', border: 'solid 1px #333', background: '#d3d3d3', fontSize: 0, textIndent: '-9999em', }, black: { display: 'inline-block', verticalAlign: 'top', width: '10px', height: '10px', borderRadius: '50%', border: 'solid 1px #333', background: '#000000', fontSize: 0, textIndent: '-9999em', }, }; class QA extends Component { static propTypes = { exposureId: PropTypes.string, qaTests: PropTypes.array, arms: PropTypes.array.isRequired, spectrographs: PropTypes.array.isRequired, mjd: PropTypes.string, date: PropTypes.string, time: PropTypes.string, navigateToMetrics: PropTypes.func, navigateToProcessingHistory: PropTypes.func, petalSizeFactor: PropTypes.number.isRequired, processId: PropTypes.number, monitor: PropTypes.bool, flavor: PropTypes.string, }; componentDidMount() { document.title = 'QA'; } renderMetrics = (step, spectrographNumber, arm) => { if (this.props.navigateToMetrics) { this.props.navigateToMetrics( step, spectrographNumber, arm, this.props.exposureId ); } }; renderSteps = () => { return ( <Steps navigateToProcessingHistory={this.props.navigateToProcessingHistory} qaTests={this.props.qaTests} renderMetrics={this.renderMetrics} mjd={this.props.mjd} exposureId={this.props.exposureId} date={this.props.date} time={this.props.time} petalSizeFactor={this.props.petalSizeFactor} processId={this.props.processId} monitor={this.props.monitor} flavor={this.props.flavor} /> ); }; <|fim▁hole|> render() { return <div style={styles.container}>{this.renderSteps()}</div>; } } export default withStyles(styles)(QA);<|fim▁end|>
<|file_name|>urls.py<|end_file_name|><|fim▁begin|>from django.conf.urls import include, url from django.views.generic.base import RedirectView from cms.models import * from cms.views import show # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover()<|fim▁hole|> url(r'^%s/$'%settings.HOME_SLUG, RedirectView.as_view(url='/', permanent=False)), # redirect url(r'(?P<slug>.*)/$', show,name='cms.show'), ]<|fim▁end|>
urlpatterns = [ url(r'^$', show,{'slug':"/%s"%settings.HOME_SLUG}, name='cms.home'), # contenido definido en home slug
<|file_name|>speech_client_example_test.go<|end_file_name|><|fim▁begin|>// Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // AUTO-GENERATED CODE. DO NOT EDIT. package speech_test import ( "io" "cloud.google.com/go/speech/apiv1beta1" "github.com/golang/protobuf/ptypes" "golang.org/x/net/context" speechpb "google.golang.org/genproto/googleapis/cloud/speech/v1beta1" ) func ExampleNewClient() { ctx := context.Background() c, err := speech.NewClient(ctx) if err != nil { // TODO: Handle error. } // TODO: Use client. _ = c } func ExampleClient_SyncRecognize() { ctx := context.Background() c, err := speech.NewClient(ctx) if err != nil { // TODO: Handle error. } req := &speechpb.SyncRecognizeRequest{ // TODO: Fill request struct fields. } resp, err := c.SyncRecognize(ctx, req) if err != nil { // TODO: Handle error. } // TODO: Use resp. _ = resp } func ExampleClient_AsyncRecognize() { ctx := context.Background() c, err := speech.NewClient(ctx) if err != nil { // TODO: Handle error. } req := &speechpb.AsyncRecognizeRequest{ // TODO: Fill request struct fields. } op, err := c.AsyncRecognize(ctx, req) if err != nil { // TODO: Handle error. } var resp ptypes.DynamicAny // resp can also be concrete protobuf-generated types. if err := op.Wait(ctx, &resp); err != nil { // TODO: Handle error. } // TODO: Use resp. } func StreamingRecognize() { ctx := context.Background() c, err := speech.NewClient(ctx) if err != nil { // TODO: Handle error.<|fim▁hole|> if err != nil { // TODO: Handle error. } go func() { reqs := []*speechpb.StreamingRecognizeRequest{ // TODO: Create requests. } for _, req := range reqs { if err := stream.Send(req); err != nil { // TODO: Handle error. } } stream.CloseSend() }() for { resp, err := stream.Recv() if err == io.EOF { break } if err != nil { // TODO: handle error. } // TODO: Use resp. _ = resp } }<|fim▁end|>
} stream, err := c.StreamingRecognize(ctx)
<|file_name|>precond-tests.ts<|end_file_name|><|fim▁begin|>import precond = require('precond'); precond.checkArgument(true); precond.checkArgument(true, "msg"); precond.checkArgument(true, "%s %s %s", 1, "two"); precond.checkState(true); precond.checkState(true, "msg"); precond.checkState(true, "%s %s %s", 1, "two"); precond.checkIsDef(true); precond.checkIsDef(true, "msg"); precond.checkIsDef(true, "%s %s %s", 1, "two"); precond.checkIsDefAndNotNull(true); precond.checkIsDefAndNotNull(true, "msg"); precond.checkIsDefAndNotNull(true, "%s %s %s", 1, "two");<|fim▁hole|>precond.checkIsString(true, "%s %s %s", 1, "two"); precond.checkIsArray(true); precond.checkIsArray(true, "msg"); precond.checkIsArray(true, "%s %s %s", 1, "two"); precond.checkIsNumber(true); precond.checkIsNumber(true, "msg"); precond.checkIsNumber(true, "%s %s %s", 1, "two"); precond.checkIsBoolean(true); precond.checkIsBoolean(true, "msg"); precond.checkIsBoolean(true, "%s %s %s", 1, "two"); precond.checkIsFunction(true); precond.checkIsFunction(true, "msg"); precond.checkIsFunction(true, "%s %s %s", 1, "two"); precond.checkIsObject(true); precond.checkIsObject(true, "msg"); precond.checkIsObject(true, "%s %s %s", 1, "two");<|fim▁end|>
precond.checkIsString(true); precond.checkIsString(true, "msg");
<|file_name|>home.component.ts<|end_file_name|><|fim▁begin|>/*import { Component } from '@angular/core';*/ import { Http, Headers } from '@angular/http'; import { AppState } from '../app.service'; import { HomeService } from './home.service'; import { CourseComponent } from '../course'; import { Course } from '../course/course.service'; import { ActivatedRoute, Params, Router } from '@angular/router'; import { User } from '../user/user/user.service'; import { AppStore } from '../app.store'; import { Thread, ThreadService } from '../thread/thread.service'; import { CourseService } from '../course/course.service'; import { ForumService, Forum } from '../forum/forum.service'; import { APIService } from '../shared/services/api.service'; import * as _ from 'underscore' import {Component, ElementRef, ViewChild, ViewEncapsulation } from '@angular/core'; import {DataSource} from '@angular/cdk/collections'; import {BehaviorSubject} from 'rxjs/BehaviorSubject'; import {Observable} from 'rxjs/Observable'; import { MatPaginator } from '@angular/material'; import { AppDataSource } from '../shared/services/data.service'; @Component({ selector: 'home', //encapsulation: ViewEncapsulation.None, styleUrls: [ './home.component.scss' ], templateUrl: './home.component.html' }) export class HomeComponent { // Set our default values public user: User; private myCourses : Course[] = []; private myForums : Forum[] = []; public threads : Thread[] = []; public courses: Array<Course> = null; public faculties : Array<any>; public groupedCourses: Array<any>; public displayMode : string = 'accordion'; public state; matButtonToggleGroup : string = 'list'; constructor(private api : APIService, private forumService : ForumService, private courseService : CourseService, public service: HomeService, public appState : AppState, public router: Router , public route: ActivatedRoute , public store : AppStore, public threadService : ThreadService) { } ngOnInit() { let self = this; this.store .changes .pluck('user') .filter((user: User) => user !== undefined && user !== null) .subscribe((user: User) => { this.user = user; this.route.data.forEach((data) => { this.faculties = data.institution.faculties; this.api.findMany({parent_id : data.institution}, 'course') .subscribe((courses : Course[]) => { this.courses = courses; }) }) this.api.findMany({participants : user._id}, 'course') .subscribe(courses => { this.myCourses = courses; }) this.api.findMany({parent_id : {$in : user.courses}}, 'forum') .subscribe(forums => { this.myForums = forums; }) this.api.findMany({child_to : {$in : user.courses}}, 'thread') .subscribe((threads: Array<Thread>) => { this.threads = threads; }) }) } setDisplayMode(mode:string):void{ this.displayMode = mode; } navigateToCourse(course : Course) { if(course['subscribed']) this.router.navigate(['/course', course._id]);<|fim▁hole|>}<|fim▁end|>
}
<|file_name|>ButtonSet.tsx<|end_file_name|><|fim▁begin|>/* MIT License Copyright (c) 2022 Looker Data Sciences, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all<|fim▁hole|> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import type { ForwardRefExoticComponent, MouseEvent, ReactNode, Ref, } from 'react' import React, { forwardRef, useCallback, useRef, useState } from 'react' import styled from 'styled-components' import type { CompatibleHTMLProps } from '@looker/design-tokens' import { inputHeightNumber } from '../Form/Inputs/height' import type { SimpleLayoutProps } from '../Layout/utils/simple' import { simpleLayoutCSS } from '../Layout/utils/simple' import { useForkedRef } from '../utils' import type { ButtonSetCallback } from './ButtonSetContext' import { ButtonSetContext } from './ButtonSetContext' import { ButtonItem } from './ButtonItem' export interface ButtonSetOption { value: string label?: string disabled?: boolean } interface ButtonSetProps<TValue extends string | string[] = string[]> extends SimpleLayoutProps, Omit<CompatibleHTMLProps<HTMLDivElement>, 'value' | 'defaultValue'> { /** * One or more ButtonItem (do not use if using options) */ children?: ReactNode /** * Available options (do not use if using ButtonItem children) */ options?: ButtonSetOption[] /** * Value for controlling the component */ value?: TValue onItemClick?: (e: MouseEvent<HTMLButtonElement>) => void } export interface ButtonGroupOrToggleBaseProps< TValue extends string | string[] = string[] > extends Omit<ButtonSetProps<TValue>, 'onChange' | 'onItemClick'> { onChange?: ButtonSetCallback<TValue> } export type ButtonSetType< TValue extends string | string[] = string[] > = ForwardRefExoticComponent< ButtonSetProps<TValue> & { ref: Ref<HTMLDivElement> } > export const ButtonSetLayout = forwardRef( ( { children, className, disabled, onItemClick, options, value, ...props }: ButtonSetProps, forwardedRef: Ref<HTMLDivElement> ) => { if (children && options) { // eslint-disable-next-line no-console console.warn('Use children or options but not both at the same time.') } const context = { disabled, onItemClick, value, } const [isWrapping, setIsWrapping] = useState(false) const timeoutRef = useRef<ReturnType<typeof setTimeout>>() const measureRef = useCallback( (node: HTMLElement | null) => { if (node) { const { height } = node.getBoundingClientRect() const getIsWrapping = () => { const firstItem = node.childNodes[0] as HTMLElement const rowHeight = firstItem ? firstItem.getBoundingClientRect().height : inputHeightNumber if (height >= rowHeight * 2) { setIsWrapping(true) } else { setIsWrapping(false) } } if (height > 0) { getIsWrapping() } else { timeoutRef.current = setTimeout(getIsWrapping, 10) } } else if (timeoutRef.current) { clearTimeout(timeoutRef.current) } }, // eslint-disable-next-line react-hooks/exhaustive-deps [options] ) const ref = useForkedRef(measureRef, forwardedRef) const optionItems = options && options.map(({ disabled, label, value }) => { return ( <ButtonItem key={value} disabled={disabled} value={value}> {label || value} </ButtonItem> ) }) return ( <ButtonSetContext.Provider value={context}> <div role="group" className={`${isWrapping ? 'wrapping ' : ''}${className}`} ref={ref} {...props} > {children || optionItems} </div> </ButtonSetContext.Provider> ) } ) ButtonSetLayout.displayName = 'ButtonSetLayout' export const ButtonSet = styled(ButtonSetLayout)` ${simpleLayoutCSS} align-items: center; display: inline-flex; flex-wrap: wrap; font-size: ${({ theme }) => theme.fontSizes.small}; text-align: center; `<|fim▁end|>
copies or substantial portions of the Software.
<|file_name|>chatbot.py<|end_file_name|><|fim▁begin|>import urllib import urllib2 import xml.dom.minidom import re import socket from util import hook chatbot_re = (r'(^.*\b(taiga|taigabot)\b.*$)', re.I) @hook.regex(*chatbot_re) @hook.command def chatbot(inp, reply=None, nick=None, conn=None): inp = inp.group(1).lower().replace('taigabot', '').replace('taiga', '').replace(':', '')<|fim▁hole|> response = url_response.read() response_dom = xml.dom.minidom.parseString(response) text = response_dom.getElementsByTagName('response')[0].childNodes[0].data.strip() return nick + ': ' + str(text.lower().replace('programo', 'taiga').replace('program-o', 'taigabot').replace('elizabeth', 'wednesday'))<|fim▁end|>
args = {'bot_id': '6', 'say': inp.strip(), 'convo_id': conn.nick, 'format': 'xml'} data = urllib.urlencode(args) resp = False url_response = urllib2.urlopen('http://api.program-o.com/v2/chatbot/?', data)
<|file_name|>struct-in-struct.rs<|end_file_name|><|fim▁begin|>// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-android: FIXME(#10381) // compile-flags:-g // debugger:set print pretty off // debugger:rbreak zzz // debugger:run // debugger:finish // debugger:print three_simple_structs // check:$1 = {x = {x = 1}, y = {x = 2}, z = {x = 3}} // debugger:print internal_padding_parent // check:$2 = {x = {x = 4, y = 5}, y = {x = 6, y = 7}, z = {x = 8, y = 9}} // debugger:print padding_at_end_parent // check:$3 = {x = {x = 10, y = 11}, y = {x = 12, y = 13}, z = {x = 14, y = 15}} #[allow(unused_variable)]; struct Simple { x: i32 } struct InternalPadding { x: i32, y: i64 } struct PaddingAtEnd { x: i64, y: i32 } struct ThreeSimpleStructs { x: Simple, y: Simple, z: Simple } struct InternalPaddingParent { x: InternalPadding, y: InternalPadding, z: InternalPadding } struct PaddingAtEndParent { x: PaddingAtEnd, y: PaddingAtEnd, z: PaddingAtEnd } struct Mixed { x: PaddingAtEnd, y: InternalPadding, z: Simple, w: i16 } struct Bag { x: Simple } struct BagInBag { x: Bag } struct ThatsJustOverkill { x: BagInBag } struct Tree { x: Simple, y: InternalPaddingParent, z: BagInBag } fn main() { let three_simple_structs = ThreeSimpleStructs { x: Simple { x: 1 }, y: Simple { x: 2 }, z: Simple { x: 3 } }; let internal_padding_parent = InternalPaddingParent { x: InternalPadding { x: 4, y: 5 }, y: InternalPadding { x: 6, y: 7 }, z: InternalPadding { x: 8, y: 9 } }; let padding_at_end_parent = PaddingAtEndParent { x: PaddingAtEnd { x: 10, y: 11 }, y: PaddingAtEnd { x: 12, y: 13 }, z: PaddingAtEnd { x: 14, y: 15 } }; let mixed = Mixed { x: PaddingAtEnd { x: 16, y: 17 }, y: InternalPadding { x: 18, y: 19 }, z: Simple { x: 20 }, w: 21 }; let bag = Bag { x: Simple { x: 22 } }; let bag_in_bag = BagInBag { x: Bag { x: Simple { x: 23 } } }; let tjo = ThatsJustOverkill { x: BagInBag { x: Bag { x: Simple { x: 24 } } } }; let tree = Tree { x: Simple { x: 25 }, y: InternalPaddingParent { x: InternalPadding { x: 26, y: 27 }, y: InternalPadding { x: 28, y: 29 }, z: InternalPadding { x: 30, y: 31 } }, z: BagInBag { x: Bag { x: Simple { x: 32 }<|fim▁hole|> }; zzz(); } fn zzz() {()}<|fim▁end|>
} }
<|file_name|>migrator.py<|end_file_name|><|fim▁begin|>from __future__ import print_function import os import ssl import sys import cassandra from cassandra import auth from cassandra.cluster import Cluster import yaml from cdeploy import cqlexecutor class Migrator: def __init__(self, migrations_path, session): print('Reading migrations from {0}'.format(migrations_path)) self.migrations_path = migrations_path self.session = session def run_migrations(self): cqlexecutor.CQLExecutor.init_table(self.session) top_version = self.get_top_version() def new_migration_filter(f): return ( os.path.isfile(os.path.join(self.migrations_path, f)) and self.migration_version(f) > top_version ) new_migrations = self.filter_migrations(new_migration_filter) [self.apply_migration(file_name) for file_name in new_migrations] def undo(self): top_version = self.get_top_version() if top_version == 0: return def top_version_filter(f): return ( os.path.isfile(os.path.join(self.migrations_path, f)) and self.migration_version(f) == top_version ) top_migration = list(self.filter_migrations(top_version_filter))[0] cqlexecutor.CQLExecutor.execute_undo( self.session, self.read_migration(top_migration) ) cqlexecutor.CQLExecutor.rollback_schema_migration(self.session) print(' -> Migration {0} undone ({1})\n'.format(top_version, top_migration)) def get_top_version(self): result = cqlexecutor.CQLExecutor.get_top_version(self.session) top_version = result[0].version if len(result) > 0 else 0 print('Current version is {0}'.format(top_version)) return top_version def filter_migrations(self, filter_func): dir_list = os.listdir(self.migrations_path) if 'config' in dir_list: dir_list.remove('config') migration_dir_listing = sorted(dir_list, key=self.migration_version) return filter( filter_func,<|fim▁hole|> def apply_migration(self, file_name): migration_script = self.read_migration(file_name) version = self.migration_version(file_name) cqlexecutor.CQLExecutor.execute(self.session, migration_script) cqlexecutor.CQLExecutor.add_schema_migration(self.session, version) print(' -> Migration {0} applied ({1})\n'.format(version, file_name)) def read_migration(self, file_name): migration_file = open(os.path.join(self.migrations_path, file_name)) return migration_file.read() DEFAULT_MIGRATIONS_PATH = './migrations' CONFIG_FILE_PATH = 'config/cassandra.yml' def main(): if '--help' in sys.argv or '-h' in sys.argv: print('Usage: cdeploy [path/to/migrations] [--undo]') return undo = False if '--undo' in sys.argv: undo = True sys.argv.remove('--undo') migrations_path = ( DEFAULT_MIGRATIONS_PATH if len(sys.argv) == 1 else sys.argv[1] ) if (invalid_migrations_dir(migrations_path) or missing_config(migrations_path)): return config = load_config(migrations_path, os.getenv('ENV')) session = get_session(config) migrator = Migrator(migrations_path, session) if undo: migrator.undo() else: migrator.run_migrations() def get_session(config): auth_provider = None if 'auth_enabled' in config and config['auth_enabled']: auth_provider = auth.PlainTextAuthProvider( username=config['auth_username'], password=config['auth_password'], ) ssl_options = None if 'ssl_enabled' in config and config['ssl_enabled']: ssl_options = { 'ca_certs': config['ssl_ca_certs'], 'ssl_version': ssl.PROTOCOL_TLSv1, # pylint: disable=E1101 } cluster = Cluster( config['hosts'], auth_provider=auth_provider, ssl_options=ssl_options, ) session = cluster.connect() try: session.set_keyspace(config['keyspace']) except cassandra.InvalidRequest: # Keyspace doesn't exist yet if 'create_keyspace' in config and config['create_keyspace']: create_keyspace(config, session) else: raise if 'consistency_level' in config: consistency_level = getattr( cassandra.ConsistencyLevel, config['consistency_level'], ) session.default_consistency_level = consistency_level return session def create_keyspace(config, session): session.execute( "CREATE KEYSPACE {0} WITH REPLICATION = {1};".format( config['keyspace'], config['replication_strategy'] ) ) session.set_keyspace(config['keyspace']) def invalid_migrations_dir(migrations_path): if not os.path.isdir(migrations_path): print('"{0}" is not a directory'.format(migrations_path)) return True else: return False def missing_config(migrations_path): config_path = config_file_path(migrations_path) if not os.path.exists(os.path.join(config_path)): print('Missing configuration file "{0}"'.format(config_path)) return True else: return False def config_file_path(migrations_path): return os.path.join(migrations_path, CONFIG_FILE_PATH) def load_config(migrations_path, env): config_file = open(config_file_path(migrations_path)) config = yaml.load(config_file) return config[env or 'development'] if __name__ == '__main__': main()<|fim▁end|>
migration_dir_listing) def migration_version(self, file_name): return int(file_name.split('.')[0].split('_')[0])
<|file_name|>test_codecmaps_cn.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # # test_codecmaps_cn.py # Codec mapping tests for PRC encodings # from test import support from test import test_multibytecodec_support import unittest class TestGB2312Map(test_multibytecodec_support.TestBase_Mapping, unittest.TestCase): encoding = 'gb2312' mapfileurl = 'http://people.freebsd.org/~perky/i18n/EUC-CN.TXT' <|fim▁hole|> unittest.TestCase): encoding = 'gbk' mapfileurl = 'http://www.unicode.org/Public/MAPPINGS/VENDORS/' \ 'MICSFT/WINDOWS/CP936.TXT' class TestGB18030Map(test_multibytecodec_support.TestBase_Mapping, unittest.TestCase): encoding = 'gb18030' mapfileurl = 'http://source.icu-project.org/repos/icu/data/' \ 'trunk/charset/data/xml/gb-18030-2000.xml' def test_main(): support.run_unittest(__name__) if __name__ == "__main__": test_main()<|fim▁end|>
class TestGBKMap(test_multibytecodec_support.TestBase_Mapping,
<|file_name|>dvs_manager_dvs_config_target.py<|end_file_name|><|fim▁begin|>import logging from pyvisdk.exceptions import InvalidArgumentError ######################################## # Automatically generated, do not edit. ######################################## log = logging.getLogger(__name__) def DVSManagerDvsConfigTarget(vim, *args, **kwargs): '''Configuration specification for a DistributedVirtualSwitch or DistributedVirtualPortgroup.'''<|fim▁hole|> if (len(args) + len(kwargs)) < 0: raise IndexError('Expected at least 1 arguments got: %d' % len(args)) required = [ ] optional = [ 'distributedVirtualPortgroup', 'distributedVirtualSwitch', 'dynamicProperty', 'dynamicType' ] for name, arg in zip(required+optional, args): setattr(obj, name, arg) for name, value in kwargs.items(): if name in required + optional: setattr(obj, name, value) else: raise InvalidArgumentError("Invalid argument: %s. Expected one of %s" % (name, ", ".join(required + optional))) return obj<|fim▁end|>
obj = vim.client.factory.create('ns0:DVSManagerDvsConfigTarget') # do some validation checking...
<|file_name|>TimedFilter.java<|end_file_name|><|fim▁begin|>/*************************************************************************** * Project file: NPlugins - NTalk - TimedFilter.java * * Full Class name: fr.ribesg.bukkit.ntalk.filter.bean.TimedFilter * * * * Copyright (c) 2012-2015 Ribesg - www.ribesg.fr * * This file is under GPLv3 -> http://www.gnu.org/licenses/gpl-3.0.txt * * Please contact me at ribesg[at]yahoo.fr if you improve this file! * ***************************************************************************/ package fr.ribesg.bukkit.ntalk.filter.bean; import fr.ribesg.bukkit.ntalk.filter.ChatFilterResult; import java.util.Map; /** * @author Ribesg */ public abstract class TimedFilter extends Filter { private final long duration; protected TimedFilter(final String outputString, final String filteredString, final boolean regex, final ChatFilterResult responseType, final long duration) { super(outputString, filteredString, regex, responseType); this.duration = duration; } public long getDuration() { return this.duration;<|fim▁hole|> // ############ // // ## Saving ## // // ############ // @Override public Map<String, Object> getConfigMap() { final Map<String, Object> map = super.getConfigMap(); map.put("duration", this.duration); return map; } }<|fim▁end|>
}
<|file_name|>category.model.ts<|end_file_name|><|fim▁begin|>export interface CategoryInterface { id?: number, name: string, created: Date } export class CategoriesModel implements CategoryInterface { id?: number; name: string;<|fim▁hole|><|fim▁end|>
created: Date; }
<|file_name|>assembunny.rs<|end_file_name|><|fim▁begin|>use std::io::prelude::*; use std::fs::File; struct Registers { a: i32, b: i32, c: i32, d: i32 } impl Registers { fn new() -> Registers { Registers{a: 0, b: 0, c: 0, d: 0} } fn get(&self, name: &str) -> i32 { match name { "a" => self.a, "b" => self.b, "c" => self.c, "d" => self.d, _ => panic!("invalid register {}!", name), } } fn inc(&mut self, name: &str) { let curr_val = self.get(name); self.set(name, curr_val + 1); } fn dec(&mut self, name: &str) { let curr_val = self.get(name); self.set(name, curr_val - 1); } fn set(&mut self, name: &str, val: i32) { match name { "a" => self.a = val, "b" => self.b = val, "c" => self.c = val, "d" => self.d = val, _ => panic!("invalid register {}!", name), } } } fn main() { let mut f = File::open("data.txt").expect("unable to open file"); let mut data = String::new(); f.read_to_string(&mut data).expect("unable to read file"); let mut instructions: Vec<&str> = data.split("\n").collect(); instructions.pop(); let mut regs = Registers::new(); let mut current_ins: i32 = 0; loop { if current_ins < 0 || current_ins as usize >= instructions.len() { break; } let (op, args_str) = instructions[current_ins as usize].split_at(3); let args: Vec<&str> = args_str.trim().split(" ").collect(); match op { "cpy" => match args[0].parse::<i32>() { Ok(n) => regs.set(args[1], n), Err(_) => {<|fim▁hole|> let val = regs.get(args[0]); regs.set(args[1], val); }, }, "inc" => regs.inc(args[0]), "dec" => regs.dec(args[0]), "jnz" => if match args[0].parse::<i32>() { Ok(n) => n != 0, Err(_) => regs.get(args[0]) != 0, } { current_ins += args[1].parse::<i32>().unwrap(); continue; }, _ => (), } current_ins += 1; } println!("{}", regs.a); }<|fim▁end|>
<|file_name|>tessellation.rs<|end_file_name|><|fim▁begin|>#[macro_use] extern crate glium; use glium::Surface; use glium::glutin; use glium::index::PrimitiveType; mod support; fn main() { use glium::DisplayBuild; // building the display, ie. the main object let display = glutin::WindowBuilder::new() .build_glium() .unwrap(); // building the vertex buffer, which contains all the vertices that we will draw let vertex_buffer = { #[derive(Copy, Clone)] struct Vertex { position: [f32; 2], } implement_vertex!(Vertex, position); glium::VertexBuffer::new(&display, vec![ Vertex { position: [-0.5, -0.5] }, Vertex { position: [ 0.0, 0.5] }, Vertex { position: [ 0.5, -0.5] }, ] ) }; // building the index buffer let index_buffer = glium::IndexBuffer::new(&display, PrimitiveType::Patches { vertices_per_patch: 3 }, vec![0u16, 1, 2]); // compiling shaders and linking them together let program = glium::Program::new(&display, glium::program::SourceCode { vertex_shader: " #version 140 in vec2 position; void main() { gl_Position = vec4(position, 0.0, 1.0); } ", fragment_shader: " #version 140 in vec3 color; out vec4 f_color; void main() { f_color = vec4(color, 1.0); } ", geometry_shader: Some("<|fim▁hole|> uniform mat4 matrix; layout(triangles) in; layout(triangle_strip, max_vertices=3) out; out vec3 color; float rand(vec2 co) { return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453); } void main() { vec3 all_color = vec3( rand(gl_in[0].gl_Position.xy + gl_in[1].gl_Position.yz), rand(gl_in[1].gl_Position.yx + gl_in[2].gl_Position.zx), rand(gl_in[0].gl_Position.xz + gl_in[2].gl_Position.zy) ); gl_Position = matrix * gl_in[0].gl_Position; color = all_color; EmitVertex(); gl_Position = matrix * gl_in[1].gl_Position; color = all_color; EmitVertex(); gl_Position = matrix * gl_in[2].gl_Position; color = all_color; EmitVertex(); } "), tessellation_control_shader: Some(" #version 400 layout(vertices = 3) out; uniform int tess_level = 5; void main() { gl_out[gl_InvocationID].gl_Position = gl_in[gl_InvocationID].gl_Position; gl_TessLevelOuter[0] = tess_level; gl_TessLevelOuter[1] = tess_level; gl_TessLevelOuter[2] = tess_level; gl_TessLevelInner[0] = tess_level; } "), tessellation_evaluation_shader: Some(" #version 400 layout(triangles, equal_spacing) in; void main() { vec3 position = vec3(gl_TessCoord.x) * gl_in[0].gl_Position.xyz + vec3(gl_TessCoord.y) * gl_in[1].gl_Position.xyz + vec3(gl_TessCoord.z) * gl_in[2].gl_Position.xyz; gl_Position = vec4(position, 1.0); } "), }).unwrap(); // level of tessellation let mut tess_level: i32 = 5; println!("The current tessellation level is {} ; use the Up and Down keys to change it", tess_level); // the main loop support::start_loop(|| { // building the uniforms let uniforms = uniform! { matrix: [ [1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0f32] ], tess_level: tess_level }; // drawing a frame let mut target = display.draw(); target.clear_color(0.0, 0.0, 0.0, 0.0); target.draw(&vertex_buffer, &index_buffer, &program, &uniforms, &Default::default()).unwrap(); target.finish().unwrap(); // polling and handling the events received by the window for event in display.poll_events() { match event { glutin::Event::Closed => return support::Action::Stop, glutin::Event::KeyboardInput(glutin::ElementState::Pressed, _, Some(glutin::VirtualKeyCode::Up)) => { tess_level += 1; println!("New tessellation level: {}", tess_level); }, glutin::Event::KeyboardInput(glutin::ElementState::Pressed, _, Some(glutin::VirtualKeyCode::Down)) => { if tess_level >= 2 { tess_level -= 1; println!("New tessellation level: {}", tess_level); } }, _ => () } } support::Action::Continue }); }<|fim▁end|>
#version 330
<|file_name|>holiday.module.ts<|end_file_name|><|fim▁begin|>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterModule, Routes } from '@angular/router'; import { IconModule } from './../shared/icon/icon.module'; import { ListModule } from './../shared/list/list.module'; import { FormdefModule, FormdefRegistry } from './../shared/formdef/index'; import { WorkflowModule } from '../workflow/workflow.module'; import { HolidayComponent } from './holiday.component'; import { HolidayDashboardComponent } from './holiday-dashboard.component'; import { HolidayService } from './holiday.service'; import { ApplyHolidayDetailSlot, ApproveHolidayDetailSlot } from './models'; const ROUTES: Routes = [ { path: '', component: HolidayDashboardComponent, children: [ { path: 'detail/:id', component: HolidayComponent }, { path: 'detail/new', component: HolidayComponent } ] } ]; @NgModule({ imports: [ CommonModule, RouterModule.forChild(ROUTES), FormdefModule, WorkflowModule, IconModule, ListModule ], declarations: [ HolidayDashboardComponent, HolidayComponent ], providers: [ HolidayService ], exports: [ RouterModule ] }) export class HolidayModule { public constructor( private _slotRegistry: FormdefRegistry ) { this._slotRegistry.register(new ApplyHolidayDetailSlot());<|fim▁hole|><|fim▁end|>
this._slotRegistry.register(new ApproveHolidayDetailSlot()); } }
<|file_name|>Select-test.js<|end_file_name|><|fim▁begin|>'use strict'; /* global describe, it, beforeEach */ var jsdomHelper = require('../testHelpers/jsdomHelper'); var sinon = require('sinon'); var unexpected = require('unexpected'); var unexpectedDom = require('unexpected-dom'); var unexpectedSinon = require('unexpected-sinon'); var expect = unexpected .clone() .installPlugin(unexpectedDom) .installPlugin(unexpectedSinon) .installPlugin(require('../testHelpers/nodeListType')); jsdomHelper(); var React = require('react'); var ReactDOM = require('react-dom'); var TestUtils = require('react-addons-test-utils'); var Select = require('../src/Select'); // The displayed text of the currently selected item, when items collapsed var DISPLAYED_SELECTION_SELECTOR = '.Select-value'; var FORM_VALUE_SELECTOR = '.Select > input'; var PLACEHOLDER_SELECTOR = '.Select-placeholder'; class PropsWrapper extends React.Component { constructor(props) { super(props); this.state = props || {}; } setPropsForChild(props) { this.setState(props); } getChild() { return this.refs.child; } render() { var Component = this.props.childComponent; // eslint-disable-line react/prop-types return <Component {...this.state} ref="child" />; } } describe('Select', () => { var options, onChange, onInputChange; var instance, wrapper; var searchInputNode; var getSelectControl = (instance) => { return ReactDOM.findDOMNode(instance).querySelector('.Select-control'); }; var enterSingleCharacter = () =>{ TestUtils.Simulate.keyDown(searchInputNode, { keyCode: 65, key: 'a' }); }; var pressEnterToAccept = () => { TestUtils.Simulate.keyDown(searchInputNode, { keyCode: 13, key: 'Enter' }); }; var pressTabToAccept = () => { TestUtils.Simulate.keyDown(searchInputNode, { keyCode: 9, key: 'Tab' }); }; var pressEscape = () => { TestUtils.Simulate.keyDown(searchInputNode, { keyCode: 27, key: 'Escape' }); }; var pressBackspace = () => { TestUtils.Simulate.keyDown(searchInputNode, { keyCode: 8, key: 'Backspace' }); }; var pressUp = () => { TestUtils.Simulate.keyDown(getSelectControl(instance), { keyCode: 38, key: 'ArrowUp' }); }; var pressDown = () => { TestUtils.Simulate.keyDown(getSelectControl(instance), { keyCode: 40, key: 'ArrowDown' }); }; var typeSearchText = (text) => { TestUtils.Simulate.change(searchInputNode, { target: { value: text } }); }; var clickArrowToOpen = () => { var selectArrow = ReactDOM.findDOMNode(instance).querySelector('.Select-arrow'); TestUtils.Simulate.mouseDown(selectArrow); }; var clickDocument = () => { var clickEvent = document.createEvent('MouseEvents'); clickEvent.initEvent('click', true, true); document.dispatchEvent(clickEvent); }; var findAndFocusInputControl = () => { // Focus on the input, such that mouse events are accepted var searchInstance = ReactDOM.findDOMNode(instance.refs.input); searchInputNode = null; if (searchInstance) { searchInputNode = searchInstance.querySelector('input'); if (searchInputNode) { TestUtils.Simulate.focus(searchInputNode); } } }; var createControl = (props) => { onChange = sinon.spy(); onInputChange = sinon.spy(); // Render an instance of the component instance = TestUtils.renderIntoDocument( <Select onChange={onChange} onInputChange={onInputChange} {...props} /> ); findAndFocusInputControl(); return instance; }; var createControlWithWrapper = (props) => { onChange = sinon.spy(); onInputChange = sinon.spy(); wrapper = TestUtils.renderIntoDocument( <PropsWrapper childComponent={Select} onChange={onChange} onInputChange={onInputChange} {...props} /> ); instance = wrapper.getChild(); findAndFocusInputControl(); return wrapper; }; var defaultOptions = [ { value: 'one', label: 'One' }, { value: 'two', label: '222' }, { value: 'three', label: 'Three' }, { value: 'four', label: 'AbcDef' } ]; describe('with simple options', () => { beforeEach(() => { options = [ { value: 'one', label: 'One' }, { value: 'two', label: 'Two' }, { value: 'three', label: 'Three' } ]; instance = createControl({ name: 'form-field-name', value: 'one', options: options, simpleValue: true, }); }); it('should assign the given name', () => { var selectInputElement = TestUtils.scryRenderedDOMComponentsWithTag(instance, 'input')[0]; expect(ReactDOM.findDOMNode(selectInputElement).name, 'to equal', 'form-field-name'); }); it('should show the options on mouse click', function () { TestUtils.Simulate.mouseDown(ReactDOM.findDOMNode(instance).querySelector('.Select-control')); var node = ReactDOM.findDOMNode(instance); expect(node, 'queried for', '.Select-option', 'to have length', 3); }); it('should display the labels on mouse click', () => { TestUtils.Simulate.mouseDown(ReactDOM.findDOMNode(instance).querySelector('.Select-control')); var node = ReactDOM.findDOMNode(instance); expect(node, 'queried for', '.Select-option:nth-child(1)', 'to have items satisfying', 'to have text', 'One'); expect(node, 'queried for', '.Select-option:nth-child(2)', 'to have items satisfying', 'to have text', 'Two'); expect(node, 'queried for', '.Select-option:nth-child(3)', 'to have items satisfying', 'to have text', 'Three'); }); it('should filter after entering some text', () => { typeSearchText('T'); var node = ReactDOM.findDOMNode(instance); expect(node, 'queried for', '.Select-option:nth-child(1)', 'to have items satisfying', 'to have text', 'Two'); expect(node, 'queried for', '.Select-option:nth-child(2)', 'to have items satisfying', 'to have text', 'Three'); expect(node, 'queried for', '.Select-option', 'to have length', 2); }); it('should pass input value when entering text', () => { typeSearchText('a'); enterSingleCharacter('a'); expect(onInputChange, 'was called with', 'a'); }); it('should filter case insensitively', () => { typeSearchText('t'); var node = ReactDOM.findDOMNode(instance); expect(node, 'queried for', '.Select-option:nth-child(1)', 'to have items satisfying', 'to have text', 'Two'); expect(node, 'queried for', '.Select-option:nth-child(2)', 'to have items satisfying', 'to have text', 'Three'); expect(node, 'queried for', '.Select-option', 'to have length', 2); }); it('should filter using "contains"', () => { // Search 'h', should only show 'Three' typeSearchText('h'); var node = ReactDOM.findDOMNode(instance); expect(node, 'queried for', '.Select-option:nth-child(1)', 'to have items satisfying', 'to have text', 'Three'); expect(node, 'queried for', '.Select-option', 'to have length', 1); }); it('should accept when enter is pressed', () => { // Search 'h', should only show 'Three' typeSearchText('h'); pressEnterToAccept(); expect(onChange, 'was called with', 'three'); }); it('should accept when tab is pressed', () => { // Search 'h', should only show 'Three' typeSearchText('h'); pressTabToAccept(); expect(onChange, 'was called with', 'three'); }); describe('pressing escape', () => { beforeEach(() => { typeSearchText('h'); pressTabToAccept(); expect(onChange, 'was called with', 'three'); onChange.reset(); pressEscape(); });<|fim▁hole|> expect(onChange, 'was called with', null); }); it('should clear the display', () => { expect(ReactDOM.findDOMNode(instance), 'queried for', PLACEHOLDER_SELECTOR, 'to have text', 'Select...'); }); }); it('should focus the first value on mouse click', () => { TestUtils.Simulate.mouseDown(ReactDOM.findDOMNode(instance).querySelector('.Select-control')); expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option.is-focused', 'to have items satisfying', 'to have text', 'One'); }); it('should move the focused value to the second value when down pressed', () => { var selectControl = getSelectControl(instance); TestUtils.Simulate.mouseDown(selectControl); TestUtils.Simulate.keyDown(selectControl, { keyCode: 40, key: 'ArrowDown' }); expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option.is-focused', 'to have items satisfying', 'to have text', 'Two'); }); it('should move the focused value to the second value when down pressed', () => { var selectControl = getSelectControl(instance); TestUtils.Simulate.mouseDown(selectControl); TestUtils.Simulate.keyDown(selectControl, { keyCode: 40, key: 'ArrowDown' }); TestUtils.Simulate.keyDown(selectControl, { keyCode: 40, key: 'ArrowDown' }); expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option.is-focused', 'to have items satisfying', 'to have text', 'Three'); }); it('should loop round to top item when down is pressed on the last item', () => { var selectControl = getSelectControl(instance); TestUtils.Simulate.mouseDown(selectControl); TestUtils.Simulate.keyDown(selectControl, { keyCode: 40, key: 'ArrowDown' }); TestUtils.Simulate.keyDown(selectControl, { keyCode: 40, key: 'ArrowDown' }); TestUtils.Simulate.keyDown(selectControl, { keyCode: 40, key: 'ArrowDown' }); expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option.is-focused', 'to have items satisfying', 'to have text', 'One'); }); it('should loop round to bottom item when up is pressed on the first item', () => { var selectControl = getSelectControl(instance); TestUtils.Simulate.mouseDown(selectControl); TestUtils.Simulate.keyDown(selectControl, { keyCode: 38, key: 'ArrowUp' }); expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option.is-focused', 'to have items satisfying', 'to have text', 'Three'); }); it('should move the focused value to the second item when up pressed twice', () => { var selectControl = getSelectControl(instance); TestUtils.Simulate.mouseDown(selectControl); TestUtils.Simulate.keyDown(selectControl, { keyCode: 38, key: 'ArrowUp' }); TestUtils.Simulate.keyDown(selectControl, { keyCode: 38, key: 'ArrowUp' }); expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option.is-focused', 'to have items satisfying', 'to have text', 'Two'); }); it('should clear the selection on escape', () => { var selectControl = getSelectControl(instance); TestUtils.Simulate.mouseDown(selectControl); TestUtils.Simulate.keyDown(selectControl, { keyCode: 27, key: 'Escape' }); expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-option'); }); it('should open the options on arrow down with the top option focused, when the options are closed', () => { var selectControl = getSelectControl(instance); var domNode = ReactDOM.findDOMNode(instance); TestUtils.Simulate.keyDown(selectControl, { keyCode: 38, key: 'ArrowDown' }); expect(domNode, 'queried for', '.Select-option.is-focused', 'to have items satisfying', 'to have text', 'One'); }); it('should open the options on arrow up with the top option focused, when the options are closed', () => { var selectControl = getSelectControl(instance); var domNode = ReactDOM.findDOMNode(instance); TestUtils.Simulate.keyDown(selectControl, { keyCode: 40, key: 'ArrowDown' }); expect(domNode, 'queried for', '.Select-option.is-focused', 'to have items satisfying', 'to have text', 'One'); }); it('should close the options one the second click on the arrow', () => { var selectArrow = ReactDOM.findDOMNode(instance).querySelector('.Select-arrow'); TestUtils.Simulate.mouseDown(selectArrow); expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'), 'to have length', 3); TestUtils.Simulate.mouseDown(selectArrow); expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-option'); }); it('should ignore a right mouse click on the arrow', () => { var selectArrow = ReactDOM.findDOMNode(instance).querySelector('.Select-arrow'); TestUtils.Simulate.mouseDown(selectArrow, { type: 'mousedown', button: 1 }); expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-option'); }); describe('after mouseEnter and leave of an option', () => { // TODO: this behaviour has changed, and we no longer lose option focus on mouse out return; beforeEach(() => { // Show the options var selectControl = getSelectControl(instance); TestUtils.Simulate.keyDown(selectControl, { keyCode: 40, key: 'ArrowDown' }); var optionTwo = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option')[1]; TestUtils.SimulateNative.mouseOver(optionTwo); TestUtils.SimulateNative.mouseOut(optionTwo); }); it('should have no focused options', () => { var domNode = ReactDOM.findDOMNode(instance); expect(domNode, 'to contain no elements matching', '.Select-option.is-focused'); }); it('should focus top option after down arrow pressed', () => { var selectControl = getSelectControl(instance); TestUtils.Simulate.keyDown(selectControl, { keyCode: 40, key: 'ArrowDown' }); var domNode = ReactDOM.findDOMNode(instance); expect(domNode, 'queried for', '.Select-option.is-focused', 'to have items satisfying', 'to have text', 'One'); }); it('should focus last option after up arrow pressed', () => { var selectControl = getSelectControl(instance); TestUtils.Simulate.keyDown(selectControl, { keyCode: 38, key: 'ArrowUp' }); var domNode = ReactDOM.findDOMNode(instance); expect(domNode, 'queried for', '.Select-option.is-focused', 'to have items satisfying', 'to have text', 'Three'); }); }); }); describe('with values as numbers', () => { beforeEach(() => { options = [ { value: 0, label: 'Zero' }, { value: 1, label: 'One' }, { value: 2, label: 'Two' }, { value: 3, label: 'Three' } ]; wrapper = createControlWithWrapper({ value: 2, name: 'field', options: options, simpleValue: true, }); }); it('selects the initial value', () => { expect(ReactDOM.findDOMNode(instance), 'queried for first', DISPLAYED_SELECTION_SELECTOR, 'to have text', 'Two'); }); it('set the initial value of the hidden input control', () => { return; // TODO; broken test? expect(ReactDOM.findDOMNode(wrapper).querySelector(FORM_VALUE_SELECTOR).value, 'to equal', '2' ); }); it('updates the value when the value prop is set', () => { wrapper.setPropsForChild({ value: 3 }); expect(ReactDOM.findDOMNode(instance), 'queried for first', DISPLAYED_SELECTION_SELECTOR, 'to have text', 'Three'); }); it('updates the value of the hidden input control after new value prop', () => { return; // TODO; broken test? wrapper.setPropsForChild({ value: 3 }); expect(ReactDOM.findDOMNode(wrapper).querySelector(FORM_VALUE_SELECTOR).value, 'to equal', '3' ); }); it('calls onChange with the new value as a number', () => { clickArrowToOpen(); pressDown(); pressEnterToAccept(); expect(onChange, 'was called with', 3); }); it('supports setting the value to 0 via prop', () => { wrapper.setPropsForChild({ value: 0 }); expect(ReactDOM.findDOMNode(instance), 'queried for first', DISPLAYED_SELECTION_SELECTOR, 'to have text', 'Zero'); }); it('supports selecting the zero value', () => { clickArrowToOpen(); pressUp(); pressUp(); pressEnterToAccept(); expect(onChange, 'was called with', 0); }); describe('with multi=true', () => { beforeEach(() => { options = [ { value: 0, label: 'Zero' }, { value: 1, label: 'One' }, { value: 2, label: 'Two' }, { value: 3, label: 'Three' }, { value: 4, label: 'Four' } ]; wrapper = createControlWithWrapper({ value: '2,1', options: options, multi: true, searchable: true }); }); it('selects the initial value', () => { expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-value .Select-value-label', 'to satisfy', [ expect.it('to have text', 'Two'), expect.it('to have text', 'One') ]); }); it('calls onChange with the correct value when 1 option is selected', () => { var removeIcons = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-value .Select-value-icon'); TestUtils.Simulate.click(removeIcons[0]); // For multi-select, the "value" (first arg) to onChange is always a string expect(onChange, 'was called with', '1', [{ value: 1, label: 'One' }]); }); it('supports updating the values via props', () => { wrapper.setPropsForChild({ value: '3,4' }); expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-value .Select-value-label', 'to satisfy', [ expect.it('to have text', 'Three'), expect.it('to have text', 'Four') ]); }); it('supports updating the value to 0', () => { // This test is specifically in case there's a "if (value) {... " somewhere wrapper.setPropsForChild({ value: 0 }); expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-value .Select-value-label', 'to satisfy', [ expect.it('to have text', 'Zero') ]); }); it('calls onChange with the correct values when multiple options are selected', () => { typeSearchText('fo'); pressEnterToAccept(); // Select 'Four' expect(onChange, 'was called with', '2,1,4', [ { value: 2, label: 'Two' }, { value: 1, label: 'One' }, { value: 4, label: 'Four' } ]); }); }); describe('searching', () => { let searchOptions = [ { value: 1, label: 'One' }, { value: 2, label: 'Two' }, { value: 10, label: 'Ten' }, { value: 20, label: 'Twenty' }, { value: 21, label: 'Twenty-one' }, { value: 34, label: 'Thirty-four' }, { value: 54, label: 'Fifty-four' } ]; describe('with matchPos=any and matchProp=any', () => { beforeEach(() => { instance = createControl({ matchPos: 'any', matchProp: 'any', options: searchOptions }); }); it('finds text anywhere in value', () => { typeSearchText('1'); expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option', 'to satisfy', [ expect.it('to have text', 'One'), expect.it('to have text', 'Ten'), expect.it('to have text', 'Twenty-one') ]); }); it('finds text at end', () => { typeSearchText('4'); expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option', 'to satisfy', [ expect.it('to have text', 'Thirty-four'), expect.it('to have text', 'Fifty-four') ]); }); }); describe('with matchPos=start and matchProp=any', () => { beforeEach(() => { instance = createControl({ matchPos: 'start', matchProp: 'any', options: searchOptions }); }); it('finds text at the start of the value', () => { typeSearchText('1'); expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option', 'to satisfy', [ expect.it('to have text', 'One'), expect.it('to have text', 'Ten') ]); }); it('does not match text at end', () => { typeSearchText('4'); expect(ReactDOM.findDOMNode(instance), 'to contain elements matching', '.Select-noresults'); expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-option'); }); }); describe('with matchPos=any and matchProp=value', () => { beforeEach(() => { instance = createControl({ matchPos: 'any', matchProp: 'value', options: searchOptions }); }); it('finds text anywhere in value', () => { typeSearchText('1'); expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option', 'to satisfy', [ expect.it('to have text', 'One'), expect.it('to have text', 'Ten'), expect.it('to have text', 'Twenty-one') ]); }); it('finds text at end', () => { typeSearchText('4'); expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option', 'to satisfy', [ expect.it('to have text', 'Thirty-four'), expect.it('to have text', 'Fifty-four') ]); }); }); describe('with matchPos=start and matchProp=value', () => { beforeEach(() => { instance = createControl({ matchPos: 'start', matchProp: 'value', options: searchOptions }); }); it('finds text at the start of the value', () => { typeSearchText('1'); expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option', 'to satisfy', [ expect.it('to have text', 'One'), expect.it('to have text', 'Ten') ]); }); it('does not match text at end', () => { typeSearchText('4'); expect(ReactDOM.findDOMNode(instance), 'to contain elements matching', '.Select-noresults'); expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-option'); }); }); }); }); describe('with options and value', () => { beforeEach(() => { options = [ { value: 'one', label: 'One' }, { value: 'two', label: 'Two' }, { value: 'three', label: 'Three' } ]; // Render an instance of the component wrapper = createControlWithWrapper({ value: 'one', options: options, searchable: true }); }); it('starts with the given value', () => { var node = ReactDOM.findDOMNode(instance); expect(node, 'queried for', DISPLAYED_SELECTION_SELECTOR, 'to have items satisfying', 'to have text', 'One'); }); it('supports setting the value via prop', () => { wrapper.setPropsForChild({ value: 'three' }); expect(ReactDOM.findDOMNode(instance), 'queried for', DISPLAYED_SELECTION_SELECTOR, 'to have items satisfying', 'to have text', 'Three'); }); it('sets the value of the hidden form node', () => { wrapper.setPropsForChild({ value: 'three' }); expect(ReactDOM.findDOMNode(wrapper).querySelector(FORM_VALUE_SELECTOR).value, 'to equal', 'three' ); }); it('display the raw value if the option is not available', () => { wrapper.setPropsForChild({ value: 'something new' }); expect(ReactDOM.findDOMNode(instance), 'queried for', DISPLAYED_SELECTION_SELECTOR, 'to have items satisfying', 'to have text', 'something new'); }); it('updates the display text if the option appears later', () => { wrapper.setPropsForChild({ value: 'new' }); wrapper.setPropsForChild({ options: [ { value: 'one', label: 'One' }, { value: 'two', labal: 'Two' }, { value: 'new', label: 'New item in the options' }, { value: 'three', label: 'Three' } ] }); expect(ReactDOM.findDOMNode(instance), 'queried for', DISPLAYED_SELECTION_SELECTOR, 'to have items satisfying', 'to have text', 'New item in the options'); }); }); describe('with a disabled option', () => { beforeEach(() => { options = [ { value: 'one', label: 'One' }, { value: 'two', label: 'Two', disabled: true }, { value: 'three', label: 'Three' } ]; wrapper = createControlWithWrapper({ options: options, searchable: true }); }); it('adds the is-disabled class to the disabled option', () => { clickArrowToOpen(); expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option')[1], 'to have attributes', { class: 'is-disabled' }); }); it('is not selectable by clicking', () => { clickArrowToOpen(); TestUtils.Simulate.mouseDown(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option')[1]); expect(onChange, 'was not called'); expect(ReactDOM.findDOMNode(instance), 'queried for first', DISPLAYED_SELECTION_SELECTOR, 'to have text', 'Select...'); }); it('is not selectable by keyboard', () => { clickArrowToOpen(); // Press down to get to the second option TestUtils.Simulate.keyDown(getSelectControl(instance), { keyCode: 40, key: 'ArrowDown' }); // Check the disable option is not focused expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-option.is-disabled.is-focused'); }); it('jumps over the disabled option', () => { clickArrowToOpen(); // Press down to get to the second option TestUtils.Simulate.keyDown(getSelectControl(instance), { keyCode: 40, key: 'ArrowDown' }); // Check the focused option is the one after the disabled option expect(ReactDOM.findDOMNode(instance), 'queried for first', '.Select-option.is-focused', 'to have text', 'Three'); }); it('jumps back to beginning when disabled option is last option', () => { wrapper = createControlWithWrapper({ options: [ { value: 'one', label: 'One' }, { value: 'two', label: 'Two' }, { value: 'three', label: 'Three', disabled: true } ] }); clickArrowToOpen(); // Down twice TestUtils.Simulate.keyDown(getSelectControl(instance), { keyCode: 40, key: 'ArrowDown' }); TestUtils.Simulate.keyDown(getSelectControl(instance), { keyCode: 40, key: 'ArrowDown' }); // Selected option should be back to 'One' expect(ReactDOM.findDOMNode(instance), 'queried for first', '.Select-option.is-focused', 'to have text', 'One'); }); it('skips over last option when looping round when last option is disabled', () => { wrapper = createControlWithWrapper({ options: [ { value: 'one', label: 'One' }, { value: 'two', label: 'Two' }, { value: 'three', label: 'Three', disabled: true } ] }); clickArrowToOpen(); // Press up, should skip the bottom entry 'Three'... TestUtils.Simulate.keyDown(getSelectControl(instance), { keyCode: 38, key: 'ArrowUp' }); // ... and land on 'Two' expect(ReactDOM.findDOMNode(instance), 'queried for first', '.Select-option.is-focused', 'to have text', 'Two'); }); it('focuses initially on the second option when the first is disabled', () => { wrapper = createControlWithWrapper({ options: [ { value: 'one', label: 'One', disabled: true }, { value: 'two', label: 'Two' }, { value: 'three', label: 'Three' } ] }); clickArrowToOpen(); expect(ReactDOM.findDOMNode(instance), 'queried for first', '.Select-option.is-focused', 'to have text', 'Two'); }); it('doesn\'t focus anything when all options are disabled', () => { wrapper = createControlWithWrapper({ options: [ { value: 'one', label: 'One', disabled: true }, { value: 'two', label: 'Two', disabled: true }, { value: 'three', label: 'Three', disabled: true } ] }); clickArrowToOpen(); TestUtils.Simulate.keyDown(getSelectControl(instance), { keyCode: 40, key: 'ArrowDown' }); expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-option.is-focused'); }); it('doesn\'t select anything when all options are disabled and enter is pressed', () => { wrapper = createControlWithWrapper({ options: [ { value: 'one', label: 'One', disabled: true }, { value: 'two', label: 'Two', disabled: true }, { value: 'three', label: 'Three', disabled: true } ] }); clickArrowToOpen(); TestUtils.Simulate.keyDown(getSelectControl(instance), { keyCode: 13, key: 'Enter' }); expect(onChange, 'was not called'); expect(ReactDOM.findDOMNode(instance), 'queried for first', DISPLAYED_SELECTION_SELECTOR, 'to have text', 'Select...'); }); it("doesn't select anything when a disabled option is the only item in the list after a search", () => { typeSearchText('tw'); // Only 'two' in the list pressEnterToAccept(); expect(onChange, 'was not called'); // And the menu is still open expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', DISPLAYED_SELECTION_SELECTOR); expect(ReactDOM.findDOMNode(instance), 'queried for' , '.Select-option', 'to satisfy', [ expect.it('to have text', 'Two') ]); }); it("doesn't select anything when a disabled option value matches the entered text", () => { typeSearchText('two'); // Matches value pressEnterToAccept(); expect(onChange, 'was not called'); // And the menu is still open expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', DISPLAYED_SELECTION_SELECTOR); expect(ReactDOM.findDOMNode(instance), 'queried for' , '.Select-option', 'to satisfy', [ expect.it('to have text', 'Two') ]); }); it("doesn't select anything when a disabled option label matches the entered text", () => { typeSearchText('Two'); // Matches label pressEnterToAccept(); expect(onChange, 'was not called'); // And the menu is still open expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', DISPLAYED_SELECTION_SELECTOR); expect(ReactDOM.findDOMNode(instance), 'queried for' , '.Select-option', 'to satisfy', [ expect.it('to have text', 'Two') ]); }); it('shows disabled results in a search', () => { typeSearchText('t'); var options = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'); expect(options[0], 'to have text', 'Two'); expect(options[0], 'to have attributes', { class: 'is-disabled' }); expect(options[1], 'to have text', 'Three'); }); it('is does not close menu when disabled option is clicked', () => { clickArrowToOpen(); TestUtils.Simulate.mouseDown(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option')[1]); var options = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'); expect(options.length, 'to equal', 3); }); }); describe('with styled options', () => { beforeEach(() => { options = [ { value: 'one', label: 'One', className: 'extra-one', title: 'Eins' }, { value: 'two', label: 'Two', className: 'extra-two', title: 'Zwei' }, { value: 'three', label: 'Three', style: { fontSize: 25 } } ]; wrapper = createControlWithWrapper({ options: options }); }); it('uses the given className for an option', () => { clickArrowToOpen(); expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option')[0], 'to have attributes', { class: 'extra-one' }); }); it('uses the given style for an option', () => { clickArrowToOpen(); expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option')[2], 'to have attributes', { style: { 'font-size': '25px' } }); }); it('uses the given title for an option', () => { clickArrowToOpen(); expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option')[1], 'to have attributes', { title: 'Zwei' }); }); it('uses the given className for a single selection', () => { typeSearchText('tw'); pressEnterToAccept(); expect(ReactDOM.findDOMNode(instance), 'queried for first', DISPLAYED_SELECTION_SELECTOR, 'to have attributes', { class: 'extra-two' }); }); it('uses the given style for a single selection', () => { typeSearchText('th'); pressEnterToAccept(); expect(ReactDOM.findDOMNode(instance), 'queried for first', DISPLAYED_SELECTION_SELECTOR, 'to have attributes', { style: { 'font-size': '25px' } }); }); it('uses the given title for a single selection', () => { typeSearchText('tw'); pressEnterToAccept(); expect(ReactDOM.findDOMNode(instance), 'queried for first', DISPLAYED_SELECTION_SELECTOR, 'to have attributes', { title: 'Zwei' }); }); describe('with multi', () => { beforeEach(() => { wrapper.setPropsForChild({ multi: true }); }); it('uses the given className for a selected value', () => { typeSearchText('tw'); pressEnterToAccept(); expect(ReactDOM.findDOMNode(instance), 'queried for first', '.Select-value', 'to have attributes', { class: 'extra-two' }); }); it('uses the given style for a selected value', () => { typeSearchText('th'); pressEnterToAccept(); expect(ReactDOM.findDOMNode(instance), 'queried for first', '.Select-value', 'to have attributes', { style: { 'font-size': '25px' } }); }); it('uses the given title for a selected value', () => { typeSearchText('tw'); pressEnterToAccept(); expect(ReactDOM.findDOMNode(instance), 'queried for first', '.Select-value', 'to have attributes', { title: 'Zwei' }); }); }); }); describe('with allowCreate=true', () => { // TODO: allowCreate hasn't been implemented yet in 1.x return; beforeEach(() => { options = [ { value: 'one', label: 'One' }, { value: 'two', label: 'Two' }, { value: 'got spaces', label: 'Label for spaces' }, { value: 'gotnospaces', label: 'Label for gotnospaces' }, { value: 'abc 123', label: 'Label for abc 123' }, { value: 'three', label: 'Three' }, { value: 'zzzzz', label: 'test value' } ]; // Render an instance of the component wrapper = createControlWithWrapper({ value: 'one', options: options, allowCreate: true, searchable: true, addLabelText: 'Add {label} to values?' }); }); it('has an "Add xyz" option when entering xyz', () => { typeSearchText('xyz'); expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-menu .Select-option', 'to have items satisfying', 'to have text', 'Add xyz to values?'); }); it('fires an onChange with the new value when selecting the Add option', () => { typeSearchText('xyz'); TestUtils.Simulate.click(ReactDOM.findDOMNode(instance).querySelector('.Select-menu .Select-option')); expect(onChange, 'was called with', 'xyz'); }); it('allows updating the options with a new label, following the onChange', () => { typeSearchText('xyz'); TestUtils.Simulate.click(ReactDOM.findDOMNode(instance).querySelector('.Select-menu .Select-option')); expect(onChange, 'was called with', 'xyz'); // Now the client adds the option, with a new label wrapper.setPropsForChild({ options: [ { value: 'one', label: 'One' }, { value: 'xyz', label: 'XYZ Label' } ], value: 'xyz' }); expect(ReactDOM.findDOMNode(instance).querySelector(DISPLAYED_SELECTION_SELECTOR), 'to have text', 'XYZ Label'); }); it('displays an add option when a value with spaces is entered', () => { typeSearchText('got'); expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-menu .Select-option')[0], 'to have text', 'Add got to values?'); }); it('displays an add option when a value with spaces is entered', () => { typeSearchText('got'); expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-menu .Select-option')[0], 'to have text', 'Add got to values?'); }); it('displays an add option when a label with spaces is entered', () => { typeSearchText('test'); expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-menu .Select-option')[0], 'to have text', 'Add test to values?'); }); it('does not display the option label when an existing value is entered', () => { typeSearchText('zzzzz'); expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-menu .Select-option'), 'to have length', 1); expect(ReactDOM.findDOMNode(instance), 'queried for first', '.Select-menu .Select-option', 'to have text', 'Add zzzzz to values?'); }); it('renders the existing option and an add option when an existing display label is entered', () => { typeSearchText('test value'); // First item should be the add option (as the "value" is not in the collection) expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-menu .Select-option')[0], 'to have text', 'Add test value to values?'); // Second item should be the existing option with the matching label expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-menu .Select-option')[1], 'to have text', 'test value'); expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-menu .Select-option'), 'to have length', 2); }); }); describe('with async options', () => { // TODO: Need to use the new Select.Async control for this return; var asyncOptions; beforeEach(() => { asyncOptions = sinon.stub(); asyncOptions.withArgs('te').callsArgWith(1, null, { options: [ { value: 'test', label: 'TEST one' }, { value: 'test2', label: 'TEST two' }, { value: 'tell', label: 'TELL three' } ] }); asyncOptions.withArgs('tes').callsArgWith(1, null, { options: [ { value: 'test', label: 'TEST one' }, { value: 'test2', label: 'TEST two' } ] }); }); describe('with autoload=true', () => { beforeEach(() => { // Render an instance of the component wrapper = createControlWithWrapper({ value: '', asyncOptions: asyncOptions, autoload: true }); }); it('calls the asyncOptions initially with autoload=true', () => { expect(asyncOptions, 'was called with', ''); }); it('calls the asyncOptions again when the input changes', () => { typeSearchText('ab'); expect(asyncOptions, 'was called twice'); expect(asyncOptions, 'was called with', 'ab'); }); it('shows the returned options after asyncOptions calls back', () => { typeSearchText('te'); var optionList = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-menu .Select-option'); expect(optionList, 'to have length', 3); expect(optionList[0], 'to have text', 'TEST one'); expect(optionList[1], 'to have text', 'TEST two'); expect(optionList[2], 'to have text', 'TELL three'); }); it('uses the options cache when the same text is entered again', () => { typeSearchText('te'); typeSearchText('tes'); expect(asyncOptions, 'was called times', 3); typeSearchText('te'); expect(asyncOptions, 'was called times', 3); }); it('displays the correct options from the cache after the input is changed back to a previous value', () => { typeSearchText('te'); typeSearchText('tes'); typeSearchText('te'); // Double check the options list is still correct var optionList = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-menu .Select-option'); expect(optionList, 'to have length', 3); expect(optionList[0], 'to have text', 'TEST one'); expect(optionList[1], 'to have text', 'TEST two'); expect(optionList[2], 'to have text', 'TELL three'); }); it('re-filters an existing options list if complete:true is provided', () => { asyncOptions.withArgs('te').callsArgWith(1, null, { options: [ { value: 'test', label: 'TEST one' }, { value: 'test2', label: 'TEST two' }, { value: 'tell', label: 'TELL three' } ], complete: true }); typeSearchText('te'); expect(asyncOptions, 'was called times', 2); typeSearchText('tel'); expect(asyncOptions, 'was called times', 2); var optionList = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-menu .Select-option'); expect(optionList, 'to have length', 1); expect(optionList[0], 'to have text', 'TELL three'); }); it('rethrows the error if err is set in the callback', () => { asyncOptions.withArgs('tes').callsArgWith(1, new Error('Something\'s wrong jim'), { options: [ { value: 'test', label: 'TEST one' }, { value: 'test2', label: 'TEST two' } ] }); expect(() => { typeSearchText('tes'); }, 'to throw exception', new Error('Something\'s wrong jim')); }); it('calls the asyncOptions function when the value prop changes', () => { expect(asyncOptions, 'was called once'); wrapper.setPropsForChild({ value: 'test2' }); expect(asyncOptions, 'was called twice'); }); }); describe('with autoload=false', () => { beforeEach(() => { // Render an instance of the component instance = createControl({ value: '', asyncOptions: asyncOptions, autoload: false }); }); it('does not initially call asyncOptions', () => { expect(asyncOptions, 'was not called'); }); it('calls the asyncOptions on first key entry', () => { typeSearchText('a'); expect(asyncOptions, 'was called with', 'a'); }); }); describe('with cacheAsyncResults=false', () => { beforeEach(() => { // Render an instance of the component wrapper = createControlWithWrapper({ value: '', asyncOptions: asyncOptions, cacheAsyncResults: false }); // Focus on the input, such that mouse events are accepted searchInputNode = ReactDOM.findDOMNode(instance.getInputNode()).querySelector('input'); TestUtils.Simulate.focus(searchInputNode); }); it('does not use cache when the same text is entered again', () => { typeSearchText('te'); typeSearchText('tes'); expect(asyncOptions, 'was called times', 3); typeSearchText('te'); expect(asyncOptions, 'was called times', 4); }); it('updates the displayed value after changing value and refreshing from asyncOptions', () => { asyncOptions.reset(); asyncOptions.callsArgWith(1, null, { options: [ { value: 'newValue', label: 'New Value from Server' }, { value: 'test', label: 'TEST one' } ] }); wrapper.setPropsForChild({ value: 'newValue' }); expect(ReactDOM.findDOMNode(instance), 'queried for first', DISPLAYED_SELECTION_SELECTOR, 'to have text', 'New Value from Server'); }); }); }); describe('with async options (using promises)', () => { var asyncOptions, callCount, callInput; beforeEach(() => { asyncOptions = sinon.spy((input) => { const options = [ { value: 'test', label: 'TEST one' }, { value: 'test2', label: 'TEST two' }, { value: 'tell', label: 'TELL three' } ].filter((elm) => { return (elm.value.indexOf(input) !== -1 || elm.label.indexOf(input) !== -1); }); return new Promise((resolve, reject) => { input === '_FAIL'? reject('nope') : resolve({options: options}); }) }); }); describe('[mocked promise]', () => { beforeEach(() => { // Render an instance of the component wrapper = createControlWithWrapper({ value: '', asyncOptions: asyncOptions, autoload: true }); }); it('should fulfill asyncOptions promise', () => { return expect(instance.props.asyncOptions(''), 'to be fulfilled'); }); it('should fulfill with 3 options when asyncOptions promise with input = "te"', () => { return expect(instance.props.asyncOptions('te'), 'to be fulfilled with', { options: [ { value: 'test', label: 'TEST one' }, { value: 'test2', label: 'TEST two' }, { value: 'tell', label: 'TELL three' } ] }); }); it('should fulfill with 2 options when asyncOptions promise with input = "tes"', () => { return expect(instance.props.asyncOptions('tes'), 'to be fulfilled with', { options: [ { value: 'test', label: 'TEST one' }, { value: 'test2', label: 'TEST two' } ] }); }); it('should reject when asyncOptions promise with input = "_FAIL"', () => { return expect(instance.props.asyncOptions('_FAIL'), 'to be rejected'); }); }); describe('with autoload=true', () => { beforeEach(() => { // Render an instance of the component wrapper = createControlWithWrapper({ value: '', asyncOptions: asyncOptions, autoload: true }); }); it('should be called once at the beginning', () => { expect(asyncOptions, 'was called'); }); it('calls the asyncOptions again when the input changes', () => { typeSearchText('ab'); expect(asyncOptions, 'was called twice'); expect(asyncOptions, 'was called with', 'ab'); }); it('shows the returned options after asyncOptions promise is resolved', (done) => { typeSearchText('te'); return asyncOptions.secondCall.returnValue.then(() => { setTimeout(() => { expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option', 'to satisfy', [ expect.it('to have text', 'TEST one'), expect.it('to have text', 'TEST two'), expect.it('to have text', 'TELL three') ]); done(); }); }); }); it('doesn\'t update the returned options when asyncOptions is rejected', (done) => { typeSearchText('te'); expect(asyncOptions, 'was called with', 'te'); asyncOptions.secondCall.returnValue.then(() => { setTimeout(() => { expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option', 'to satisfy', [ expect.it('to have text', 'TEST one'), expect.it('to have text', 'TEST two'), expect.it('to have text', 'TELL three') ]); // asyncOptions mock is set to reject the promise when invoked with '_FAIL' typeSearchText('_FAIL'); expect(asyncOptions, 'was called with', '_FAIL'); asyncOptions.thirdCall.returnValue.then(null, () => { setTimeout(() => { expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option', 'to satisfy', [ expect.it('to have text', 'TEST one'), expect.it('to have text', 'TEST two'), expect.it('to have text', 'TELL three') ]); done(); }); }); }); }); }); }); describe('with autoload=false', () => { beforeEach(() => { // Render an instance of the component instance = createControl({ value: '', asyncOptions: asyncOptions, autoload: false }); }); it('does not initially call asyncOptions', () => { expect(asyncOptions, 'was not called'); }); it('calls the asyncOptions on first key entry', () => { typeSearchText('a'); expect(asyncOptions, 'was called once'); expect(asyncOptions, 'was called with', 'a'); }); }); }); describe('with multi-select', () => { beforeEach(() => { options = [ { value: 'one', label: 'One' }, { value: 'two', label: 'Two' }, { value: 'three', label: 'Three' }, { value: 'four', label: 'Four' } ]; // Render an instance of the component wrapper = createControlWithWrapper({ value: '', options: options, searchable: true, allowCreate: true, multi: true }); }); it('selects a single option on enter', () => { typeSearchText('fo'); pressEnterToAccept(); expect(onChange, 'was called with', 'four', [{ label: 'Four', value: 'four' }]); }); it('selects a second option', () => { typeSearchText('fo'); pressEnterToAccept(); typeSearchText('th'); onChange.reset(); // Ignore previous onChange calls pressEnterToAccept(); expect(onChange, 'was called with', 'four,three', [{ label: 'Four', value: 'four' }, { label: 'Three', value: 'three' }]); }); it('displays both selected options', () => { typeSearchText('fo'); pressEnterToAccept(); typeSearchText('th'); pressEnterToAccept(); expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-value-label')[0], 'to have text', 'Four'); expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-value-label')[1], 'to have text', 'Three'); }); it('filters the existing selections from the options', () => { wrapper.setPropsForChild({ value: 'four,three' }); typeSearchText('o'); var options = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'); expect(options[0], 'to have text', 'Add "o"?'); expect(options[1], 'to have text', 'One'); expect(options[2], 'to have text', 'Two'); expect(options, 'to have length', 3); // No "Four", as already selected }); it('removes the last selected option with backspace', () => { typeSearchText('fo'); pressEnterToAccept(); typeSearchText('th'); pressEnterToAccept(); onChange.reset(); // Ignore previous onChange calls pressBackspace(); expect(onChange, 'was called with', 'four', [{ label: 'Four', value: 'four' }]); }); it('does not remove the last selected option with backspace when backspaceRemoves=false', () => { // Disable backspace wrapper.setPropsForChild({ backspaceRemoves: false }); typeSearchText('fo'); pressEnterToAccept(); typeSearchText('th'); pressEnterToAccept(); onChange.reset(); // Ignore previous onChange calls pressBackspace(); expect(onChange, 'was not called'); var items = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-value-label'); expect(items[0], 'to have text', 'Four'); expect(items[1], 'to have text', 'Three'); }); it('removes an item when clicking on the X', () => { typeSearchText('fo'); pressEnterToAccept(); typeSearchText('th'); pressEnterToAccept(); typeSearchText('tw'); pressEnterToAccept(); onChange.reset(); // Ignore previous onChange calls var threeDeleteButton = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-value-icon')[1]; TestUtils.Simulate.click(threeDeleteButton); expect(onChange, 'was called with', 'four,two', [ { label: 'Four', value: 'four' }, { label: 'Two', value: 'two' } ]); }); it('uses the selected text as an item when comma is pressed', () => { typeSearchText('fo'); pressEnterToAccept(); typeSearchText('new item'); onChange.reset(); TestUtils.Simulate.keyDown(searchInputNode, { keyCode: 188, key: ',' }); expect(onChange, 'was called with', 'four,new item', [ { value: 'four', label: 'Four' }, { value: 'new item', label: 'new item' } ]); }); describe('with late options', () => { beforeEach(() => { wrapper = createControlWithWrapper({ multi: true, options: options, value: 'one,two' }); }); it('updates the label when the options are updated', () => { wrapper.setPropsForChild({ options: [ { value: 'one', label: 'new label for One' }, { value: 'two', label: 'new label for Two' }, { value: 'three', label: 'new label for Three' } ] }); var items = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-value'); expect(items[0], 'queried for', '.Select-value-label', 'to have items satisfying', 'to have text', 'new label for One'); expect(items[1], 'queried for', '.Select-value-label', 'to have items satisfying', 'to have text', 'new label for Two'); }); }); }); describe('with multi=true and searchable=false', () => { beforeEach(() => { options = [ { value: 'one', label: 'One' }, { value: 'two', label: 'Two' }, { value: 'three', label: 'Three' }, { value: 'four', label: 'Four' } ]; // Render an instance of the component wrapper = createControlWithWrapper({ value: '', options: options, searchable: false, multi: true }); // We need a hack here. // JSDOM (at least v3.x) doesn't appear to support div's with tabindex // This just hacks that we are focused // This is (obviously) implementation dependent, and may need to change instance.setState({ isFocused: true }); }); it('selects multiple options', () => { clickArrowToOpen(); var items = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'); TestUtils.Simulate.mouseDown(items[1]); // The menu is now closed, click the arrow to open it again clickArrowToOpen(); items = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'); TestUtils.Simulate.mouseDown(items[0]); var selectedItems = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-value-label'); expect(selectedItems[0], 'to have text', 'Two'); expect(selectedItems[1], 'to have text', 'One'); expect(selectedItems, 'to have length', 2); }); it('calls onChange when each option is selected', () => { clickArrowToOpen(); // First item var items = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'); TestUtils.Simulate.mouseDown(items[1]); expect(onChange, 'was called once'); expect(onChange, 'was called with', 'two', [{ value: 'two', label: 'Two' }]); // Second item // The menu is now closed, click the arrow to open it again clickArrowToOpen(); items = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'); TestUtils.Simulate.mouseDown(items[0]); expect(onChange, 'was called twice'); }); it('removes the selected options from the menu', () => { clickArrowToOpen(); var items = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'); // Click the option "Two" to select it expect(items[1], 'to have text', 'Two'); TestUtils.Simulate.mouseDown(items[1]); expect(onChange, 'was called times', 1); // Now get the list again, // The menu is now closed, click the arrow to open it again clickArrowToOpen(); items = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'); expect(items[0], 'to have text', 'One'); expect(items[1], 'to have text', 'Three'); expect(items[2], 'to have text', 'Four'); expect(items, 'to have length', 3); // Click first item, 'One' TestUtils.Simulate.mouseDown(items[0]); expect(onChange, 'was called times', 2); // The menu is now closed, click the arrow to open it again clickArrowToOpen(); items = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'); expect(items[0], 'to have text', 'Three'); expect(items[1], 'to have text', 'Four'); expect(items, 'to have length', 2); // Click second item, 'Four' TestUtils.Simulate.mouseDown(items[1]); expect(onChange, 'was called times', 3); // The menu is now closed, click the arrow to open it again clickArrowToOpen(); items = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'); expect(items[0], 'to have text', 'Three'); expect(items, 'to have length', 1); }); }); describe('with props', () => { describe('className', () => { it('assigns the className to the outer-most element', () => { var instance = createControl({ className: 'test-class' }); expect(ReactDOM.findDOMNode(instance), 'to have attributes', { class: 'test-class' }); }); }); describe('clearable=true', () => { beforeEach(() => { var instance = createControl({ clearable: true, options: defaultOptions, value: 'three' }); expect(ReactDOM.findDOMNode(instance), 'queried for', DISPLAYED_SELECTION_SELECTOR, 'to have items satisfying', 'to have text', 'Three'); }); describe('on pressing escape', () => { beforeEach(() => { pressEscape(); }); it('calls onChange with empty', () => { expect(onChange, 'was called with', ''); }); it('resets the display value', () => { expect(ReactDOM.findDOMNode(instance), 'queried for', DISPLAYED_SELECTION_SELECTOR, 'to have items satisfying', 'to have text', 'Select...'); }); it('resets the control value', () => { expect(ReactDOM.findDOMNode(instance).querySelector('input').value, 'to equal', ''); }); }); describe('on clicking `clear`', () => { beforeEach(() => { TestUtils.Simulate.click(ReactDOM.findDOMNode(instance).querySelector('.Select-clear')); }); it('calls onChange with empty', () => { expect(onChange, 'was called with', ''); }); it('resets the display value', () => { expect(ReactDOM.findDOMNode(instance), 'queried for', DISPLAYED_SELECTION_SELECTOR, 'to have items satisfying', 'to have text', 'Select...'); }); it('resets the control value', () => { expect(ReactDOM.findDOMNode(instance).querySelector('input').value, 'to equal', ''); }); }); }); describe('clearable=false', () => { beforeEach(() => { var instance = createControl({ clearable: false, options: defaultOptions, value: 'three' }); expect(ReactDOM.findDOMNode(instance), 'queried for', DISPLAYED_SELECTION_SELECTOR, 'to have items satisfying', 'to have text', 'Three'); }); it('does not render a clear button', () => { expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-clear'); }); describe('on escape', () => { beforeEach(() => { pressEscape(); }); it('does not call onChange', () => { expect(onChange, 'was not called'); }); it('does not reset the display value', () => { expect(ReactDOM.findDOMNode(instance), 'queried for', DISPLAYED_SELECTION_SELECTOR, 'to have items satisfying', 'to have text', 'Three'); }); it('does not reset the control value', () => { expect(ReactDOM.findDOMNode(instance).querySelector('input').value, 'to equal', 'three'); }); }); describe('when open', () => { beforeEach(() => { typeSearchText('abc'); }); describe('on escape', () => { beforeEach(() => { pressEscape(); }); it('closes the menu', () => { expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-menu'); }); it('resets the control value to the original', () => { expect(ReactDOM.findDOMNode(instance).querySelector('input').value, 'to equal', 'three'); }); it('renders the original display label', () => { expect(ReactDOM.findDOMNode(instance), 'queried for', DISPLAYED_SELECTION_SELECTOR, 'to have items satisfying', 'to have text', 'Three'); }); }); }); }); describe('clearAllText', () => { beforeEach(() => { instance = createControl({ multi: true, clearable: true, value: 'three', clearAllText: 'Remove All Items Test Title', clearValueText: 'Remove Value Test Title', // Should be ignored, multi=true options: defaultOptions }); }); it('uses the prop as the title for clear', () => { expect(ReactDOM.findDOMNode(instance).querySelector('.Select-clear-zone'), 'to have attributes', { title: 'Remove All Items Test Title' }); }); }); describe('clearValueText', () => { beforeEach(() => { instance = createControl({ multi: false, clearable: true, value: 'three', clearAllText: 'Remove All Items Test Title', // Should be ignored, multi=false clearValueText: 'Remove Value Test Title', options: defaultOptions }); }); it('uses the prop as the title for clear', () => { expect(ReactDOM.findDOMNode(instance).querySelector('.Select-clear-zone'), 'to have attributes', { title: 'Remove Value Test Title' }); }); }); describe('delimiter', () => { describe('is ;', () => { beforeEach(() => { instance = createControl({ multi: true, value: 'four;three', delimiter: ';', options: defaultOptions }); }); it('interprets the initial options correctly', () => { var values = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-value'); expect(values[0], 'queried for', '.Select-value-label', 'to have items satisfying', 'to have text', 'AbcDef'); expect(values[1], 'queried for', '.Select-value-label', 'to have items satisfying', 'to have text', 'Three'); expect(values, 'to have length', 2); }); it('adds an additional option with the correct delimiter', () => { typeSearchText('one'); pressEnterToAccept(); expect(onChange, 'was called with', 'four;three;one', [ { value: 'four', label: 'AbcDef' }, { value: 'three', label: 'Three' }, { value: 'one', label: 'One' } ]); }); }); describe('is a multi-character string (`==XXX==`)', () => { beforeEach(() => { instance = createControl({ multi: true, value: 'four==XXX==three', delimiter: '==XXX==', options: defaultOptions }); }); it('interprets the initial options correctly', () => { var values = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-value'); expect(values[0], 'queried for', '.Select-value-label', 'to have items satisfying', 'to have text', 'AbcDef'); expect(values[1], 'queried for', '.Select-value-label', 'to have items satisfying', 'to have text', 'Three'); expect(values, 'to have length', 2); }); it('adds an additional option with the correct delimiter', () => { typeSearchText('one'); pressEnterToAccept(); expect(onChange, 'was called with', 'four==XXX==three==XXX==one', [ { value: 'four', label: 'AbcDef' }, { value: 'three', label: 'Three' }, { value: 'one', label: 'One' } ]); }); }); }); describe('disabled=true', () => { beforeEach(() => { instance = createControl({ options: defaultOptions, value: 'three', disabled: true, searchable: true }); }); it('does not render an input search control', () => { expect(searchInputNode, 'to be null'); }); it('does not react to keyDown', () => { TestUtils.Simulate.keyDown(getSelectControl(instance), { keyCode: 40, key: 'ArrowDown' }); expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-option'); }); it('does not respond to mouseDown', () => { TestUtils.Simulate.mouseDown(getSelectControl(instance)); expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-option'); }); it('does not respond to mouseDown on the arrow', () => { TestUtils.Simulate.mouseDown(getSelectControl(instance).querySelector('.Select-arrow')); expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-option'); }); it('renders the given value', () => { expect(ReactDOM.findDOMNode(instance).querySelector(DISPLAYED_SELECTION_SELECTOR), 'to have text', 'Three'); }); }); describe('custom filterOption function', () => { // Custom function returns true only for value "four" var filterOption = (option) => { if (option.value === 'four') { return true; } return false; }; var spyFilterOption; beforeEach(() => { spyFilterOption = sinon.spy(filterOption); instance = createControl({ options: defaultOptions, filterOption: spyFilterOption }); }); it('calls the filter with each option', () => { expect(spyFilterOption, 'was called times', 4); expect(spyFilterOption, 'was called with', defaultOptions[0], ''); expect(spyFilterOption, 'was called with', defaultOptions[1], ''); expect(spyFilterOption, 'was called with', defaultOptions[2], ''); expect(spyFilterOption, 'was called with', defaultOptions[3], ''); }); describe('when entering text', () => { beforeEach(() => { spyFilterOption.reset(); typeSearchText('xyz'); }); it('calls the filterOption function for each option', () => { expect(spyFilterOption, 'was called times', 4); expect(spyFilterOption, 'was called with', defaultOptions[0], 'xyz'); expect(spyFilterOption, 'was called with', defaultOptions[1], 'xyz'); expect(spyFilterOption, 'was called with', defaultOptions[2], 'xyz'); expect(spyFilterOption, 'was called with', defaultOptions[3], 'xyz'); }); it('only shows the filtered option', () => { expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'), 'to have length', 1); expect(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'), 'to have items satisfying', 'to have text', 'AbcDef'); }); }); }); describe('custom filterOptions function', () => { var spyFilterOptions; beforeEach(() => { spyFilterOptions = sinon.stub(); spyFilterOptions.returns([ { label: 'Return One', value: 'one' }, { label: 'Return Two', value: 'two' } ]); instance = createControl({ options: defaultOptions, filterOptions: spyFilterOptions, searchable: true }); }); it('calls the filterOptions function initially', () => { expect(spyFilterOptions, 'was called'); }); it('calls the filterOptions function initially with the initial options', () => { expect(spyFilterOptions, 'was called with', defaultOptions, ''); }); it('uses the returned options', () => { TestUtils.Simulate.mouseDown(ReactDOM.findDOMNode(instance).querySelector('.Select-arrow')); var options = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'); expect(options[0], 'to have text', 'Return One'); expect(options[1], 'to have text', 'Return Two'); expect(options, 'to have length', 2); }); it('calls the filterOptions function on text change', () => { typeSearchText('xyz'); expect(spyFilterOptions, 'was called with', defaultOptions, 'xyz'); }); it('uses new options after text change', () => { spyFilterOptions.returns([ { value: 'abc', label: 'AAbbcc' }, { value: 'def', label: 'DDeeff' } ]); typeSearchText('xyz'); var options = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'); expect(options[0], 'to have text', 'AAbbcc'); expect(options[1], 'to have text', 'DDeeff'); expect(options, 'to have length', 2); }); }); describe('ignoreCase=false', () => { beforeEach(() => { instance = createControl({ searchable: true, ignoreCase: false, options: defaultOptions }); }); it('does not find options in a different case', () => { typeSearchText('def'); expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-option'); }); it('finds options in the same case', () => { typeSearchText('Def'); var options = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'); expect(options[0], 'to have text', 'AbcDef'); expect(options, 'to have length', 1); }); }); describe('inputProps', () => { beforeEach(() => { instance = createControl({ searchable: true, inputProps: { inputClassName: 'extra-input-class', className: 'extra-class-name', id: 'search-input-id' }, options: defaultOptions }); }); it('passes id through to the search input box', () => { expect(searchInputNode, 'to have attributes', { id: 'search-input-id' }); }); it('passes the inputClassName to the search input box', () => { expect(searchInputNode, 'to have attributes', { class: 'extra-input-class' }); }); it('adds the className on to the auto-size input', () => { expect(ReactDOM.findDOMNode(instance.getInputNode()), 'to have attributes', { class: ['extra-class-name', 'Select-input'] }); }); describe('and not searchable', () => { beforeEach(() => { instance = createControl({ searchable: false, inputProps: { inputClassName: 'extra-input-class', className: 'extra-class-name', id: 'search-input-id' }, options: defaultOptions }); }); it('sets the className and id on the placeholder for the input', () => { expect(ReactDOM.findDOMNode(instance).querySelector('.extra-class-name'), 'to have attributes', { id: 'search-input-id' }); }); }); describe('and disabled', () => { beforeEach(() => { instance = createControl({ searchable: true, disabled: true, inputProps: { inputClassName: 'extra-input-class', className: 'extra-class-name', id: 'search-input-id' }, options: defaultOptions }); }); it('doesn\'t pass the inputProps through', () => { expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.extra-class-name'); expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '#search-input-id'); }); }); }); describe('matchPos=start', () => { beforeEach(() => { instance = createControl({ searchable: true, matchPos: 'start', options: defaultOptions }); }); it('searches only at the start', () => { typeSearchText('o'); var options = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'); expect(options[0], 'to have text', 'One'); expect(options, 'to have length', 1); }); }); describe('matchProp=value', () => { beforeEach(() => { instance = createControl({ searchable: true, matchProp: 'value', options: [ { value: 'aaa', label: '111' }, { value: 'bbb', label: '222' }, { value: 'ccc', label: 'Three' }, { value: 'four', label: 'Abcaaa' } ] }); }); it('searches only the value', () => { typeSearchText('aa'); // Matches value "three", and label "AbcDef" var options = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'); expect(options, 'to have length', 1); expect(options[0], 'to have text', '111'); }); }); describe('matchProp=label', () => { beforeEach(() => { instance = createControl({ searchable: true, matchProp: 'label', options: [ { value: 'aaa', label: 'bbb' }, { value: 'bbb', label: '222' }, { value: 'ccc', label: 'Three' }, { value: 'four', label: 'Abcaaa' } ] }); }); it('searches only the value', () => { typeSearchText('bb'); // Matches value "three", and label "AbcDef" var options = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'); expect(options, 'to have length', 1); expect(options[0], 'to have text', 'bbb'); }); }); describe('matchPos=start and matchProp=value', () => { beforeEach(() => { instance = createControl({ searchable: true, matchProp: 'value', matchPos: 'start', options: [ { value: 'aaa', label: '111' }, { value: 'bbb', label: '222' }, { value: 'cccaa', label: 'Three' }, { value: 'four', label: 'aaAbca' } ] }); }); it('searches only the value', () => { typeSearchText('aa'); // Matches value "three", and label "AbcDef" var options = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'); expect(options, 'to have length', 1); expect(options[0], 'to have text', '111'); }); }); describe('matchPos=start and matchProp=label', () => { beforeEach(() => { instance = createControl({ searchable: true, matchProp: 'label', matchPos: 'start', options: [ { value: 'aaa', label: 'bbb' }, { value: 'bbb', label: '222' }, { value: 'cccbbb', label: 'Three' }, { value: 'four', label: 'Abcbbb' } ] }); }); it('searches only the label', () => { typeSearchText('bb'); // Matches value "three", and label "AbcDef" var options = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'); expect(options, 'to have length', 1); expect(options[0], 'to have text', 'bbb'); }); }); describe('noResultsText', () => { beforeEach(() => { wrapper = createControlWithWrapper({ searchable: true, options: defaultOptions, noResultsText: 'No results unit test' }); }); it('displays the text when no results are found', () => { typeSearchText('DOES NOT EXIST'); expect(ReactDOM.findDOMNode(instance).querySelector('.Select-menu'), 'to have text', 'No results unit test'); }); it('supports updating the text', () => { wrapper.setPropsForChild({ noResultsText: 'Updated no results text' }); typeSearchText('DOES NOT EXIST'); expect(ReactDOM.findDOMNode(instance).querySelector('.Select-menu'), 'to have text', 'Updated no results text'); }); }); describe('onBlur', () => { var onBlur; it('calls the onBlur prop when blurring the input', () => { onBlur = sinon.spy(); instance = createControl({ options: defaultOptions, onBlur: onBlur }); TestUtils.Simulate.blur(searchInputNode); expect(onBlur, 'was called once'); }); }); describe('onFocus', () => { var onFocus; beforeEach(() => { onFocus = sinon.spy(); instance = createControl({ options: defaultOptions, onFocus: onFocus }); }); it('calls the onFocus prop when focusing the control', () => { expect(onFocus, 'was called once'); }); }); describe('onValueClick', () => { var onValueClick; beforeEach(() => { onValueClick = sinon.spy(); instance = createControl({ options: defaultOptions, multi: true, value: 'two,one', onValueClick: onValueClick }); }); it('calls the function when clicking on a label', () => { TestUtils.Simulate.click(ReactDOM.findDOMNode(instance).querySelector('.Select-value-label a')); expect(onValueClick, 'was called once'); }); it('calls the function with the value', () => { TestUtils.Simulate.click(ReactDOM.findDOMNode(instance).querySelectorAll('.Select-value-label a')[0]); expect(onValueClick, 'was called with', { value: 'two', label: '222' }); }); }); describe('optionRenderer', () => { var optionRenderer; beforeEach(() => { optionRenderer = (option) => { return ( <span id={'TESTOPTION_' + option.value}>{option.label.toUpperCase()}</span> ); }; optionRenderer = sinon.spy(optionRenderer); instance = createControl({ options: defaultOptions, optionRenderer: optionRenderer }); }); it('renders the options using the optionRenderer', () => { var selectArrow = ReactDOM.findDOMNode(instance).querySelector('.Select-arrow'); TestUtils.Simulate.mouseDown(selectArrow); var options = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'); expect(options[0].querySelector('span'), 'to have attributes', { id: 'TESTOPTION_one' }); expect(options[0].querySelector('span'), 'to have text', 'ONE'); expect(options[1].querySelector('span'), 'to have attributes', { id: 'TESTOPTION_two' }); expect(options[1].querySelector('span'), 'to have text', '222'); }); it('calls the renderer exactly once for each option', () => { var selectArrow = ReactDOM.findDOMNode(instance).querySelector('.Select-arrow'); TestUtils.Simulate.mouseDown(selectArrow); expect(optionRenderer, 'was called times', 4); }); }); describe('optionRendererDisabled', () => { var optionRenderer; var renderLink = (props) => { return <a {...props} >Upgrade here!</a>; }; var links = [ { href: '/link' }, { href: '/link2', target: '_blank' } ]; var ops = [ { label: 'Disabled', value: 'disabled', disabled: true, link: renderLink(links[0]) }, { label: 'Disabled 2', value: 'disabled_2', disabled: true, link: renderLink(links[1]) }, { label: 'Enabled', value: 'enabled' } ]; /** * Since we don't have access to an actual Location object, * this method will test a string (path) by the end of global.window.location.href * @param {string} path Ending href path to check * @return {Boolean} Whether the location is at the path */ var isNavigated = (path) => { var window_location = global.window.location.href; return window_location.indexOf(path, window_location.length - path.length) !== -1; }; var startUrl = 'http://dummy/startLink'; beforeEach(() => { window.location.href = startUrl; optionRenderer = (option) => { return ( <span>{option.label} {option.link} </span> ); }; optionRenderer = sinon.spy(optionRenderer); instance = createControl({ options: ops, optionRenderer: optionRenderer }); }); it('disabled option link is still clickable', () => { var selectArrow = ReactDOM.findDOMNode(instance).querySelector('.Select-arrow'); var selectArrow = ReactDOM.findDOMNode(instance).querySelector('.Select-arrow'); TestUtils.Simulate.mouseDown(selectArrow); var options = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'); var link = options[0].querySelector('a'); expect(link, 'to have attributes', { href: links[0].href }); expect(isNavigated(links[0].href), 'to be false'); TestUtils.Simulate.click(link); expect(isNavigated(links[0].href), 'to be true'); }); it('disabled option link with target doesn\'t navigate the current window', () => { var selectArrow = ReactDOM.findDOMNode(instance).querySelector('.Select-arrow'); TestUtils.Simulate.mouseDown(selectArrow); var options = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-option'); var link = options[1].querySelector('a'); expect(link, 'to have attributes', { href: links[1].href, target: '_blank' }); expect(isNavigated(startUrl), 'to be true'); TestUtils.Simulate.click(link); expect(isNavigated(links[1].href), 'to be false'); }); }); describe('placeholder', () => { beforeEach(() => { wrapper = createControlWithWrapper({ value: null, options: defaultOptions, placeholder: 'Choose Option Placeholder test' }); }); it('uses the placeholder initially', () => { expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-placeholder', 'to have items satisfying', 'to have text', 'Choose Option Placeholder test'); }); it('displays a selected value', () => { wrapper.setPropsForChild({ value: 'three' }); expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-placeholder', 'to have items satisfying', 'to have text', 'Three'); }); it('returns to the default placeholder when value is cleared', () => { wrapper.setPropsForChild({ value: 'three' }); wrapper.setPropsForChild({ value: null }); expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-placeholder', 'to have items satisfying', 'to have text', 'Choose Option Placeholder test'); }); it('allows changing the placeholder via props', () => { wrapper.setPropsForChild({ placeholder: 'New placeholder from props' }); expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-placeholder', 'to have items satisfying', 'to have text', 'New placeholder from props'); }); it('allows setting the placeholder to the selected value', () => { /* This is an unlikely scenario, but given that the current * implementation uses the placeholder to display the selected value, * it seems prudent to check that this obscure case still works * * We set the value via props, then change the placeholder to the * same as the display label for the chosen option, then reset * the value (to null). * * The expected result is that the display does NOT change, as the * placeholder is now the same as label. */ wrapper.setPropsForChild({ value: 'three' }); wrapper.setPropsForChild({ placeholder: 'Three' // Label for value 'three' }); wrapper.setPropsForChild({ value: null }); expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-placeholder', 'to have items satisfying', 'to have text', 'Three'); }); }); describe('searchingText', () => { // TODO: Need to use the new Select.Async control for this return; var asyncOptions; var asyncOptionsCallback; beforeEach(() => { asyncOptions = sinon.spy(); instance = createControl({ asyncOptions: asyncOptions, autoload: false, searchingText: 'Testing async loading...', noResultsText: 'Testing No results found', searchPromptText: 'Testing enter search query' }); }); it('uses the searchingText whilst the asyncOptions are loading', () => { clickArrowToOpen(); expect(asyncOptions, 'was not called'); typeSearchText('abc'); expect(asyncOptions, 'was called'); expect(ReactDOM.findDOMNode(instance), 'to contain elements matching', '.Select-loading'); expect(ReactDOM.findDOMNode(instance), 'queried for first', '.Select-searching', 'to have text', 'Testing async loading...'); }); it('clears the searchingText when results arrive', () => { clickArrowToOpen(); typeSearchText('abc'); expect(ReactDOM.findDOMNode(instance), 'queried for first', '.Select-searching', 'to have text', 'Testing async loading...'); asyncOptions.args[0][1](null, { options: [{ value: 'abc', label: 'Abc' }] }); expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-noresults'); }); it('switches the searchingText to noResultsText when options arrive, but empty', () => { clickArrowToOpen(); typeSearchText('abc'); expect(ReactDOM.findDOMNode(instance), 'queried for first', '.Select-searching', 'to have text', 'Testing async loading...'); expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-noresults'); asyncOptions.args[0][1](null, { options: [] }); expect(ReactDOM.findDOMNode(instance), 'queried for first', '.Select-noresults', 'to have text', 'Testing No results found'); expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-searching'); }); }); describe('searchPromptText', () => { // TODO: Need to use the new Select.Async control for this return; var asyncOptions; beforeEach(() => { asyncOptions = sinon.stub(); instance = createControl({ asyncOptions: asyncOptions, autoload: false, searchPromptText: 'Unit test prompt text' }); }); it('uses the searchPromptText before text is entered', () => { var selectArrow = ReactDOM.findDOMNode(instance).querySelector('.Select-arrow'); TestUtils.Simulate.mouseDown(selectArrow); expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-search-prompt', 'to have items satisfying', 'to have text', 'Unit test prompt text'); }); it('clears the searchPromptText when results arrive', () => { asyncOptions.callsArgWith(1, null, { options: [{ value: 'abcd', label: 'ABCD' }] }); var selectArrow = ReactDOM.findDOMNode(instance).querySelector('.Select-arrow'); TestUtils.Simulate.mouseDown(selectArrow); typeSearchText('abc'); expect(asyncOptions, 'was called once'); expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-prompt'); expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-noresults'); }); }); describe('valueRenderer', () => { var valueRenderer; beforeEach(() => { valueRenderer = (option) => { return ( <span id={'TESTOPTION_' + option.value}>{option.label.toUpperCase()}</span> ); }; valueRenderer = sinon.spy(valueRenderer); instance = createControl({ options: defaultOptions, value: 'three', valueRenderer: valueRenderer }); }); it('renders the value using the provided renderer', () => { var labelNode = ReactDOM.findDOMNode(instance).querySelector('.Select-value span'); expect(labelNode, 'to have text', 'THREE'); expect(labelNode, 'to have attributes', { id: 'TESTOPTION_three' }); }); }); describe('valueRenderer and multi=true', () => { var valueRenderer; beforeEach(() => { valueRenderer = (option) => { return ( <span id={'TESTOPTION_' + option.value}>{option.label.toUpperCase()}</span> ); }; valueRenderer = sinon.spy(valueRenderer); instance = createControl({ options: defaultOptions, value: 'three,two', multi: true, valueRenderer: valueRenderer }); }); it('renders the values using the provided renderer', () => { var labelNode = ReactDOM.findDOMNode(instance).querySelectorAll('.Select-value-label span'); expect(labelNode[0], 'to have text', 'THREE'); expect(labelNode[0], 'to have attributes', { id: 'TESTOPTION_three' }); expect(labelNode[1], 'to have text', '222'); expect(labelNode[1], 'to have attributes', { id: 'TESTOPTION_two' }); }); }); }); describe('clicking outside', () => { beforeEach(() => { instance = createControl({ options: defaultOptions }); }); it('closes the menu', () => { TestUtils.Simulate.mouseDown(getSelectControl(instance)); expect(ReactDOM.findDOMNode(instance), 'queried for', '.Select-option', 'to have length', 4); clickDocument(); expect(ReactDOM.findDOMNode(instance), 'to contain no elements matching', '.Select-option'); }); }); });<|fim▁end|>
it('should call onChange with a empty value', () => {
<|file_name|>InputFileReader.java<|end_file_name|><|fim▁begin|>package com.yngvark.communicate_through_named_pipes.input; import org.slf4j.Logger; import java.io.BufferedReader; import java.io.IOException; import static org.slf4j.LoggerFactory.getLogger; public class InputFileReader { private final Logger logger = getLogger(getClass()); private final BufferedReader bufferedReader; private boolean run = true; private boolean streamClosed = false; public InputFileReader(BufferedReader bufferedReader) { this.bufferedReader = bufferedReader; } /** * @throws IORuntimeException If an {@link java.io.IOException} occurs. */ public void consume(MessageListener messageListener) throws RuntimeException { logger.debug("Consume: start."); try { tryToConsume(messageListener); } catch (IOException e) { throw new IORuntimeException(e); } logger.debug(""); logger.debug("Consume: done."); } private void tryToConsume(MessageListener messageListener) throws IOException { String msg = null; while (run) { msg = bufferedReader.readLine(); if (msg == null) break; logger.trace("<<< From other side: " + msg); messageListener.messageReceived(msg); } if (msg == null) { logger.debug("Consume file stream was closed from other side."); } bufferedReader.close(); } public synchronized void closeStream() { logger.debug("Stopping consuming input file..."); if (streamClosed) { logger.info("Already stopped.");<|fim▁hole|> return; } run = false; try { logger.trace("Closing buffered reader."); bufferedReader.close(); streamClosed = true; } catch (IOException e) { logger.error("Caught exception when closing stream: {}", e); } logger.debug("Stopping consuming input file... done"); } }<|fim▁end|>
<|file_name|>create_messages.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3 # Generate .js files defining Blockly core and language messages. # # Copyright 2013 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse<|fim▁hole|>import re import sys from common import read_json_file _NEWLINE_PATTERN = re.compile('[\n\r]') def string_is_ascii(s): try: # This approach is better for compatibility return all(ord(c) < 128 for c in s) except TypeError: return False def load_constants(filename): """Read in constants file, which must be output in every language.""" constant_defs = read_json_file(filename) constants_text = '\n' for key in constant_defs: value = constant_defs[key] value = value.replace('"', '\\"') constants_text += u'\nBlockly.Msg["{0}"] = \"{1}\";'.format( key, value) return constants_text def main(): """Generate .js files defining Blockly core and language messages.""" # Process command-line arguments. parser = argparse.ArgumentParser(description='Convert JSON files to JS.') parser.add_argument('--source_lang', default='en', help='ISO 639-1 source language code') parser.add_argument('--source_lang_file', default=os.path.join('json', 'en.json'), help='Path to .json file for source language') parser.add_argument('--source_synonym_file', default=os.path.join('json', 'synonyms.json'), help='Path to .json file with synonym definitions') parser.add_argument('--source_constants_file', default=os.path.join('json', 'constants.json'), help='Path to .json file with constant definitions') parser.add_argument('--output_dir', default='js/', help='relative directory for output files') parser.add_argument('--key_file', default='keys.json', help='relative path to input keys file') parser.add_argument('--quiet', action='store_true', default=False, help='do not write anything to standard output') parser.add_argument('files', nargs='+', help='input files') args = parser.parse_args() if not args.output_dir.endswith(os.path.sep): args.output_dir += os.path.sep # Read in source language .json file, which provides any values missing # in target languages' .json files. source_defs = read_json_file(os.path.join(os.curdir, args.source_lang_file)) # Make sure the source file doesn't contain a newline or carriage return. for key, value in source_defs.items(): if _NEWLINE_PATTERN.search(value): print('ERROR: definition of {0} in {1} contained a newline character.'. format(key, args.source_lang_file)) sys.exit(1) sorted_keys = sorted(source_defs.keys()) # Read in synonyms file, which must be output in every language. synonym_defs = read_json_file(os.path.join( os.curdir, args.source_synonym_file)) # synonym_defs is also being sorted to ensure the same order is kept synonym_text = '\n'.join([u'Blockly.Msg["{0}"] = Blockly.Msg["{1}"];' .format(key, synonym_defs[key]) for key in sorted(synonym_defs)]) # Read in constants file, which must be output in every language. constants_text = load_constants(os.path.join(os.curdir, args.source_constants_file)) # Create each output file. for arg_file in args.files: (_, filename) = os.path.split(arg_file) target_lang = filename[:filename.index('.')] if target_lang not in ('qqq', 'keys', 'synonyms', 'constants'): target_defs = read_json_file(os.path.join(os.curdir, arg_file)) # Verify that keys are 'ascii' bad_keys = [key for key in target_defs if not string_is_ascii(key)] if bad_keys: print(u'These keys in {0} contain non ascii characters: {1}'.format( filename, ', '.join(bad_keys))) # If there's a '\n' or '\r', remove it and print a warning. for key, value in target_defs.items(): if _NEWLINE_PATTERN.search(value): print(u'WARNING: definition of {0} in {1} contained ' 'a newline character.'. format(key, arg_file)) target_defs[key] = _NEWLINE_PATTERN.sub(' ', value) # Output file. outname = os.path.join(os.curdir, args.output_dir, target_lang + '.js') with codecs.open(outname, 'w', 'utf-8') as outfile: outfile.write( """// This file was automatically generated. Do not modify. 'use strict'; """.format(target_lang.replace('-', '.'))) # For each key in the source language file, output the target value # if present; otherwise, output the source language value with a # warning comment. for key in sorted_keys: if key in target_defs: value = target_defs[key] comment = '' del target_defs[key] else: value = source_defs[key] comment = ' // untranslated' value = value.replace('"', '\\"') outfile.write(u'Blockly.Msg["{0}"] = "{1}";{2}\n' .format(key, value, comment)) # Announce any keys defined only for target language. if target_defs: extra_keys = [key for key in target_defs if key not in synonym_defs] synonym_keys = [key for key in target_defs if key in synonym_defs] if not args.quiet: if extra_keys: print(u'These extra keys appeared in {0}: {1}'.format( filename, ', '.join(extra_keys))) if synonym_keys: print(u'These synonym keys appeared in {0}: {1}'.format( filename, ', '.join(synonym_keys))) outfile.write(synonym_text) outfile.write(constants_text) if not args.quiet: print('Created {0}'.format(outname)) if __name__ == '__main__': main()<|fim▁end|>
import codecs import os
<|file_name|>display.rs<|end_file_name|><|fim▁begin|>use alloc::boxed::Box; use collections::String; use common::event::Event; use core::{cmp, ptr}; use core::mem::size_of; use fs::{KScheme, Resource, ResourceSeek, Url}; use system::error::{Error, Result, EACCES, EBADF, ENOENT, EINVAL}; use system::graphics::fast_copy; /// A display resource pub struct DisplayResource { /// Path path: String, /// Seek seek: usize, } impl Resource for DisplayResource { fn dup(&self) -> Result<Box<Resource>> { Ok(Box::new(DisplayResource { path: self.path.clone(), seek: self.seek })) } /// Return the URL for display resource fn path(&self, buf: &mut [u8]) -> Result<usize> { let path = self.path.as_bytes(); for (b, p) in buf.iter_mut().zip(path.iter()) { *b = *p; } Ok(cmp::min(buf.len(), path.len())) } fn read(&mut self, buf: &mut [u8]) -> Result<usize> { if buf.len() >= size_of::<Event>() { let event = ::env().events.receive("DisplayResource::read"); unsafe { ptr::write(buf.as_mut_ptr().offset(0isize) as *mut Event, event) }; let mut i = size_of::<Event>(); while i + size_of::<Event>() <= buf.len() { if let Some(event) = unsafe { ::env().events.inner() }.pop_front() { unsafe { ptr::write(buf.as_mut_ptr().offset(i as isize) as *mut Event, event) }; i += size_of::<Event>(); } else { break; } } Ok(i) } else { Err(Error::new(EINVAL)) } } fn write(&mut self, buf: &[u8]) -> Result<usize> { let console = unsafe { & *::env().console.get() }; if let Some(ref display) = console.display { let size = cmp::max(0, cmp::min(display.size as isize - self.seek as isize, (buf.len()/4) as isize)) as usize; if size > 0 { unsafe { fast_copy(display.onscreen.offset(self.seek as isize), buf.as_ptr() as *const u32, size); } } Ok(size) } else {<|fim▁hole|> fn seek(&mut self, pos: ResourceSeek) -> Result<usize> { let console = unsafe { & *::env().console.get() }; if let Some(ref display) = console.display { self.seek = match pos { ResourceSeek::Start(offset) => cmp::min(display.size, cmp::max(0, offset)), ResourceSeek::Current(offset) => cmp::min(display.size, cmp::max(0, self.seek as isize + offset) as usize), ResourceSeek::End(offset) => cmp::min(display.size, cmp::max(0, display.size as isize + offset) as usize), }; Ok(self.seek) } else { Err(Error::new(EBADF)) } } fn sync(&mut self) -> Result<()> { Ok(()) } } pub struct DisplayScheme; impl KScheme for DisplayScheme { fn scheme(&self) -> &str { "display" } fn open(&mut self, url: Url, _: usize) -> Result<Box<Resource>> { if url.reference() == "manager" { let console = unsafe { &mut *::env().console.get() }; if console.draw { console.draw = false; if let Some(ref display) = console.display { Ok(box DisplayResource { path: format!("display:{}/{}", display.width, display.height), seek: 0, }) } else { Err(Error::new(ENOENT)) } } else { Err(Error::new(EACCES)) } } else { let console = unsafe { & *::env().console.get() }; if let Some(ref display) = console.display { Ok(box DisplayResource { path: format!("display:{}/{}", display.width, display.height), seek: 0, }) } else { Err(Error::new(ENOENT)) } } } }<|fim▁end|>
Err(Error::new(EBADF)) } }
<|file_name|>issue-5572.rs<|end_file_name|><|fim▁begin|>fn foo<T: ::std::cmp::Eq>(t: T) { } <|fim▁hole|><|fim▁end|>
fn main() { }
<|file_name|>JustPremium.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import re from module.plugins.internal.Addon import Addon class JustPremium(Addon): __name__ = "JustPremium" __type__ = "hook" __version__ = "0.25" __status__ = "testing" __config__ = [("activated", "bool", "Activated" , False), ("excluded" , "str" , "Exclude hosters (comma separated)", "" ), ("included" , "str" , "Include hosters (comma separated)", "" )] __description__ = """Remove not-premium links from added urls""" __license__ = "GPLv3" __authors__ = [("mazleu" , "mazleica@gmail.com"), ("Walter Purcaro", "vuolter@gmail.com" ), ("immenz" , "immenz@gmx.net" )] def init(self): self.event_map = {'linksAdded': "links_added"} def links_added(self, links, pid): hosterdict = self.pyload.pluginManager.hosterPlugins linkdict = self.pyload.api.checkURLs(links) premiumplugins = set(account.type for account in self.pyload.api.getAccounts(False) \ if account.valid and account.premium) multihosters = set(hoster for hoster in self.pyload.pluginManager.hosterPlugins \ if 'new_name' in hosterdict[hoster] \ and hosterdict[hoster]['new_name'] in premiumplugins) excluded = map(lambda domain: "".join(part.capitalize() for part in re.split(r'(\.|\d+)', domain) if part != '.'), self.get_config('excluded').replace(' ', '').replace(',', '|').replace(';', '|').split('|')) included = map(lambda domain: "".join(part.capitalize() for part in re.split(r'(\.|\d+)', domain) if part != '.'), self.get_config('included').replace(' ', '').replace(',', '|').replace(';', '|').split('|')) hosterlist = (premiumplugins | multihosters).union(excluded).difference(included) #: Found at least one hoster with account or multihoster if not any( True for pluginname in linkdict if pluginname in hosterlist ): return<|fim▁hole|> self.log_info(_("Remove links of plugin: %s") % pluginname) for link in linkdict[pluginname]: self.log_debug("Remove link: %s" % link) links.remove(link)<|fim▁end|>
for pluginname in set(linkdict.keys()) - hosterlist:
<|file_name|>IssueTrackerConfig.java<|end_file_name|><|fim▁begin|>/****************************************************************************** * * Copyright 2013-2019 Paphus Solutions Inc. * * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.botlibre.web.rest; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import org.botlibre.util.Utils; import org.botlibre.web.admin.AccessMode; import org.botlibre.web.bean.IssueTrackerBean; import org.botlibre.web.bean.LoginBean; /** * DTO for XML IssueTracker config. */ @XmlRootElement(name="issuetracker") @XmlAccessorType(XmlAccessType.FIELD) public class IssueTrackerConfig extends WebMediumConfig { @XmlAttribute public String createAccessMode; @XmlAttribute public String issues;<|fim▁hole|> if (this.createAccessMode == null || this.createAccessMode.isEmpty()) { return AccessMode.Everyone.name(); } return this.createAccessMode; } public IssueTrackerBean getBean(LoginBean loginBean) { return loginBean.getBean(IssueTrackerBean.class); } public void sanitize() { createAccessMode = Utils.sanitize(createAccessMode); issues = Utils.sanitize(issues); } }<|fim▁end|>
public String getCreateAccessMode() {
<|file_name|>ckeygen.py<|end_file_name|><|fim▁begin|># -*- test-case-name: twisted.conch.test.test_ckeygen -*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Implementation module for the `ckeygen` command. """ import sys, os, getpass, socket if getpass.getpass == getpass.unix_getpass: try: import termios # hack around broken termios termios.tcgetattr, termios.tcsetattr except (ImportError, AttributeError): sys.modules['termios'] = None reload(getpass) from twisted.conch.ssh import keys from twisted.python import failure, filepath, log, usage, randbytes class GeneralOptions(usage.Options): synopsis = """Usage: ckeygen [options] """ longdesc = "ckeygen manipulates public/private keys in various ways." optParameters = [['bits', 'b', 1024, 'Number of bits in the key to create.'], ['filename', 'f', None, 'Filename of the key file.'], ['type', 't', None, 'Specify type of key to create.'], ['comment', 'C', None, 'Provide new comment.'], ['newpass', 'N', None, 'Provide new passphrase.'], ['pass', 'P', None, 'Provide old passphrase.']] optFlags = [['fingerprint', 'l', 'Show fingerprint of key file.'], ['changepass', 'p', 'Change passphrase of private key file.'], ['quiet', 'q', 'Quiet.'], ['no-passphrase', None, "Create the key with no passphrase."], ['showpub', 'y', 'Read private key file and print public key.']] compData = usage.Completions( optActions={"type": usage.CompleteList(["rsa", "dsa"])})<|fim▁hole|> options = GeneralOptions() try: options.parseOptions(sys.argv[1:]) except usage.UsageError, u: print 'ERROR: %s' % u options.opt_help() sys.exit(1) log.discardLogs() log.deferr = handleError # HACK if options['type']: if options['type'] == 'rsa': generateRSAkey(options) elif options['type'] == 'dsa': generateDSAkey(options) else: sys.exit('Key type was %s, must be one of: rsa, dsa' % options['type']) elif options['fingerprint']: printFingerprint(options) elif options['changepass']: changePassPhrase(options) elif options['showpub']: displayPublicKey(options) else: options.opt_help() sys.exit(1) def handleError(): global exitStatus exitStatus = 2 log.err(failure.Failure()) raise def generateRSAkey(options): from Crypto.PublicKey import RSA print 'Generating public/private rsa key pair.' key = RSA.generate(int(options['bits']), randbytes.secureRandom) _saveKey(key, options) def generateDSAkey(options): from Crypto.PublicKey import DSA print 'Generating public/private dsa key pair.' key = DSA.generate(int(options['bits']), randbytes.secureRandom) _saveKey(key, options) def printFingerprint(options): if not options['filename']: filename = os.path.expanduser('~/.ssh/id_rsa') options['filename'] = raw_input('Enter file in which the key is (%s): ' % filename) if os.path.exists(options['filename']+'.pub'): options['filename'] += '.pub' try: key = keys.Key.fromFile(options['filename']) obj = key.keyObject print '%s %s %s' % ( obj.size() + 1, key.fingerprint(), os.path.basename(options['filename'])) except: sys.exit('bad key') def changePassPhrase(options): if not options['filename']: filename = os.path.expanduser('~/.ssh/id_rsa') options['filename'] = raw_input( 'Enter file in which the key is (%s): ' % filename) try: key = keys.Key.fromFile(options['filename']).keyObject except keys.EncryptedKeyError as e: # Raised if password not supplied for an encrypted key if not options.get('pass'): options['pass'] = getpass.getpass('Enter old passphrase: ') try: key = keys.Key.fromFile( options['filename'], passphrase=options['pass']).keyObject except keys.BadKeyError: sys.exit('Could not change passphrase: old passphrase error') except keys.EncryptedKeyError as e: sys.exit('Could not change passphrase: %s' % (e,)) except keys.BadKeyError as e: sys.exit('Could not change passphrase: %s' % (e,)) if not options.get('newpass'): while 1: p1 = getpass.getpass( 'Enter new passphrase (empty for no passphrase): ') p2 = getpass.getpass('Enter same passphrase again: ') if p1 == p2: break print 'Passphrases do not match. Try again.' options['newpass'] = p1 try: newkeydata = keys.Key(key).toString('openssh', extra=options['newpass']) except Exception as e: sys.exit('Could not change passphrase: %s' % (e,)) try: keys.Key.fromString(newkeydata, passphrase=options['newpass']) except (keys.EncryptedKeyError, keys.BadKeyError) as e: sys.exit('Could not change passphrase: %s' % (e,)) fd = open(options['filename'], 'w') fd.write(newkeydata) fd.close() print 'Your identification has been saved with the new passphrase.' def displayPublicKey(options): if not options['filename']: filename = os.path.expanduser('~/.ssh/id_rsa') options['filename'] = raw_input('Enter file in which the key is (%s): ' % filename) try: key = keys.Key.fromFile(options['filename']).keyObject except keys.EncryptedKeyError: if not options.get('pass'): options['pass'] = getpass.getpass('Enter passphrase: ') key = keys.Key.fromFile( options['filename'], passphrase = options['pass']).keyObject print keys.Key(key).public().toString('openssh') def _saveKey(key, options): if not options['filename']: kind = keys.objectType(key) kind = {'ssh-rsa':'rsa','ssh-dss':'dsa'}[kind] filename = os.path.expanduser('~/.ssh/id_%s'%kind) options['filename'] = raw_input('Enter file in which to save the key (%s): '%filename).strip() or filename if os.path.exists(options['filename']): print '%s already exists.' % options['filename'] yn = raw_input('Overwrite (y/n)? ') if yn[0].lower() != 'y': sys.exit() if options.get('no-passphrase'): options['pass'] = b'' elif not options['pass']: while 1: p1 = getpass.getpass('Enter passphrase (empty for no passphrase): ') p2 = getpass.getpass('Enter same passphrase again: ') if p1 == p2: break print 'Passphrases do not match. Try again.' options['pass'] = p1 keyObj = keys.Key(key) comment = '%s@%s' % (getpass.getuser(), socket.gethostname()) filepath.FilePath(options['filename']).setContent( keyObj.toString('openssh', options['pass'])) os.chmod(options['filename'], 33152) filepath.FilePath(options['filename'] + '.pub').setContent( keyObj.public().toString('openssh', comment)) print 'Your identification has been saved in %s' % options['filename'] print 'Your public key has been saved in %s.pub' % options['filename'] print 'The key fingerprint is:' print keyObj.fingerprint() if __name__ == '__main__': run()<|fim▁end|>
def run():
<|file_name|>0047_auto_20170525_2011.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Generated by Django 1.9.12 on 2017-05-25 20:11 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('anagrafica', '0046_delega_stato'), ] operations = [ migrations.AlterIndexTogether( name='delega', index_together=set([('persona', 'tipo', 'stato'), ('inizio', 'fine', 'tipo', 'oggetto_id', 'oggetto_tipo'), ('tipo', 'oggetto_tipo', 'oggetto_id'), ('persona', 'inizio', 'fine', 'tipo'), ('persona', 'inizio', 'fine', 'tipo', 'stato'), ('persona', 'stato'), ('persona', 'inizio', 'fine'), ('inizio', 'fine', 'tipo'), ('persona', 'inizio', 'fine', 'tipo', 'oggetto_id', 'oggetto_tipo'), ('persona', 'tipo'), ('oggetto_tipo', 'oggetto_id'), ('inizio', 'fine', 'stato'), ('inizio', 'fine')]),<|fim▁hole|><|fim▁end|>
), ]
<|file_name|>frame_x86.cpp<|end_file_name|><|fim▁begin|>/* * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #include "precompiled.hpp" #include "interpreter/interpreter.hpp" #include "memory/resourceArea.hpp" #include "oops/markOop.hpp" #include "oops/method.hpp" #include "oops/oop.inline.hpp" #include "prims/methodHandles.hpp" #include "runtime/frame.inline.hpp" #include "runtime/handles.inline.hpp" #include "runtime/javaCalls.hpp" #include "runtime/monitorChunk.hpp" #include "runtime/os.hpp" #include "runtime/signature.hpp" #include "runtime/stubCodeGenerator.hpp" #include "runtime/stubRoutines.hpp" #include "vmreg_x86.inline.hpp" #ifdef COMPILER1 #include "c1/c1_Runtime1.hpp" #include "runtime/vframeArray.hpp" #endif #ifdef ASSERT void RegisterMap::check_location_valid() { } #endif PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC // Profiling/safepoint support bool frame::safe_for_sender(JavaThread *thread) { address sp = (address)_sp; address fp = (address)_fp; address unextended_sp = (address)_unextended_sp; // consider stack guards when trying to determine "safe" stack pointers static size_t stack_guard_size = os::uses_stack_guard_pages() ? (StackYellowPages + StackRedPages) * os::vm_page_size() : 0; size_t usable_stack_size = thread->stack_size() - stack_guard_size; // sp must be within the usable part of the stack (not in guards) bool sp_safe = (sp < thread->stack_base()) && (sp >= thread->stack_base() - usable_stack_size); if (!sp_safe) { return false; } // unextended sp must be within the stack and above or equal sp bool unextended_sp_safe = (unextended_sp < thread->stack_base()) && (unextended_sp >= sp); if (!unextended_sp_safe) { return false; } // an fp must be within the stack and above (but not equal) sp // second evaluation on fp+ is added to handle situation where fp is -1 bool fp_safe = (fp < thread->stack_base() && (fp > sp) && (((fp + (return_addr_offset * sizeof(void*))) < thread->stack_base()))); // We know sp/unextended_sp are safe only fp is questionable here // If the current frame is known to the code cache then we can attempt to // to construct the sender and do some validation of it. This goes a long way // toward eliminating issues when we get in frame construction code if (_cb != NULL ) { // First check if frame is complete and tester is reliable // Unfortunately we can only check frame complete for runtime stubs and nmethod // other generic buffer blobs are more problematic so we just assume they are // ok. adapter blobs never have a frame complete and are never ok. if (!_cb->is_frame_complete_at(_pc)) { if (_cb->is_nmethod() || _cb->is_adapter_blob() || _cb->is_runtime_stub()) { return false; } } // Could just be some random pointer within the codeBlob if (!_cb->code_contains(_pc)) { return false; } // Entry frame checks if (is_entry_frame()) { // an entry frame must have a valid fp. if (!fp_safe) return false; // Validate the JavaCallWrapper an entry frame must have address jcw = (address)entry_frame_call_wrapper(); bool jcw_safe = (jcw < thread->stack_base()) && ( jcw > fp); return jcw_safe; } intptr_t* sender_sp = NULL; address sender_pc = NULL; if (is_interpreted_frame()) { // fp must be safe if (!fp_safe) { return false; } sender_pc = (address) this->fp()[return_addr_offset]; sender_sp = (intptr_t*) addr_at(sender_sp_offset); } else { // must be some sort of compiled/runtime frame // fp does not have to be safe (although it could be check for c1?) // check for a valid frame_size, otherwise we are unlikely to get a valid sender_pc if (_cb->frame_size() <= 0) { return false; } sender_sp = _unextended_sp + _cb->frame_size(); // On Intel the return_address is always the word on the stack sender_pc = (address) *(sender_sp-1); } // If the potential sender is the interpreter then we can do some more checking if (Interpreter::contains(sender_pc)) { // ebp is always saved in a recognizable place in any code we generate. However // only if the sender is interpreted/call_stub (c1 too?) are we certain that the saved ebp // is really a frame pointer. intptr_t *saved_fp = (intptr_t*)*(sender_sp - frame::sender_sp_offset); bool saved_fp_safe = ((address)saved_fp < thread->stack_base()) && (saved_fp > sender_sp); if (!saved_fp_safe) { return false; } // construct the potential sender frame sender(sender_sp, saved_fp, sender_pc); return sender.is_interpreted_frame_valid(thread); } // We must always be able to find a recognizable pc CodeBlob* sender_blob = CodeCache::find_blob_unsafe(sender_pc); if (sender_pc == NULL || sender_blob == NULL) { return false; } // Could be a zombie method if (sender_blob->is_zombie() || sender_blob->is_unloaded()) { return false; } // Could just be some random pointer within the codeBlob if (!sender_blob->code_contains(sender_pc)) { return false; } // We should never be able to see an adapter if the current frame is something from code cache if (sender_blob->is_adapter_blob()) { return false; } // Could be the call_stub if (StubRoutines::returns_to_call_stub(sender_pc)) { intptr_t *saved_fp = (intptr_t*)*(sender_sp - frame::sender_sp_offset); bool saved_fp_safe = ((address)saved_fp < thread->stack_base()) && (saved_fp > sender_sp); if (!saved_fp_safe) { return false; } // construct the potential sender frame sender(sender_sp, saved_fp, sender_pc); // Validate the JavaCallWrapper an entry frame must have address jcw = (address)sender.entry_frame_call_wrapper(); bool jcw_safe = (jcw < thread->stack_base()) && ( jcw > (address)sender.fp()); return jcw_safe; } if (sender_blob->is_nmethod()) { nmethod* nm = sender_blob->as_nmethod_or_null(); if (nm != NULL) { if (nm->is_deopt_mh_entry(sender_pc) || nm->is_deopt_entry(sender_pc)) { return false; } } } // If the frame size is 0 something (or less) is bad because every nmethod has a non-zero frame size // because the return address counts against the callee's frame. if (sender_blob->frame_size() <= 0) { assert(!sender_blob->is_nmethod(), "should count return address at least"); return false; } // We should never be able to see anything here except an nmethod. If something in the // code cache (current frame) is called by an entity within the code cache that entity // should not be anything but the call stub (already covered), the interpreter (already covered) // or an nmethod. if (!sender_blob->is_nmethod()) { return false; } // Could put some more validation for the potential non-interpreted sender // frame we'd create by calling sender if I could think of any. Wait for next crash in forte... // One idea is seeing if the sender_pc we have is one that we'd expect to call to current cb // We've validated the potential sender that would be created return true; } // Must be native-compiled frame. Since sender will try and use fp to find // linkages it must be safe if (!fp_safe) { return false; } // Will the pc we fetch be non-zero (which we'll find at the oldest frame) if ( (address) this->fp()[return_addr_offset] == NULL) return false; // could try and do some more potential verification of native frame if we could think of some... return true; } void frame::patch_pc(Thread* thread, address pc) { address* pc_addr = &(((address*) sp())[-1]); if (TracePcPatching) { tty->print_cr("patch_pc at address " INTPTR_FORMAT " [" INTPTR_FORMAT " -> " INTPTR_FORMAT "]", pc_addr, *pc_addr, pc); } // Either the return address is the original one or we are going to // patch in the same address that's already there. assert(_pc == *pc_addr || pc == *pc_addr, "must be"); *pc_addr = pc; _cb = CodeCache::find_blob(pc); address original_pc = nmethod::get_deopt_original_pc(this); if (original_pc != NULL) { assert(original_pc == _pc, "expected original PC to be stored before patching"); _deopt_state = is_deoptimized; // leave _pc as is } else { _deopt_state = not_deoptimized; _pc = pc; } } bool frame::is_interpreted_frame() const { return Interpreter::contains(pc()); } int frame::frame_size(RegisterMap* map) const { frame sender = this->sender(map); return sender.sp() - sp(); } intptr_t* frame::entry_frame_argument_at(int offset) const { // convert offset to index to deal with tsi int index = (Interpreter::expr_offset_in_bytes(offset)/wordSize); // Entry frame's arguments are always in relation to unextended_sp() return &unextended_sp()[index]; } // sender_sp #ifdef CC_INTERP intptr_t* frame::interpreter_frame_sender_sp() const { assert(is_interpreted_frame(), "interpreted frame expected"); // QQQ why does this specialize method exist if frame::sender_sp() does same thing? // seems odd and if we always know interpreted vs. non then sender_sp() is really // doing too much work. return get_interpreterState()->sender_sp(); } // monitor elements BasicObjectLock* frame::interpreter_frame_monitor_begin() const { return get_interpreterState()->monitor_base(); } BasicObjectLock* frame::interpreter_frame_monitor_end() const { return (BasicObjectLock*) get_interpreterState()->stack_base(); } #else // CC_INTERP intptr_t* frame::interpreter_frame_sender_sp() const { assert(is_interpreted_frame(), "interpreted frame expected"); return (intptr_t*) at(interpreter_frame_sender_sp_offset); } void frame::set_interpreter_frame_sender_sp(intptr_t* sender_sp) { assert(is_interpreted_frame(), "interpreted frame expected"); ptr_at_put(interpreter_frame_sender_sp_offset, (intptr_t) sender_sp); } // monitor elements BasicObjectLock* frame::interpreter_frame_monitor_begin() const { return (BasicObjectLock*) addr_at(interpreter_frame_monitor_block_bottom_offset); } BasicObjectLock* frame::interpreter_frame_monitor_end() const { BasicObjectLock* result = (BasicObjectLock*) *addr_at(interpreter_frame_monitor_block_top_offset); // make sure the pointer points inside the frame assert(sp() <= (intptr_t*) result, "monitor end should be above the stack pointer"); assert((intptr_t*) result < fp(), "monitor end should be strictly below the frame pointer"); return result; } void frame::interpreter_frame_set_monitor_end(BasicObjectLock* value) { *((BasicObjectLock**)addr_at(interpreter_frame_monitor_block_top_offset)) = value; } // Used by template based interpreter deoptimization void frame::interpreter_frame_set_last_sp(intptr_t* sp) { *((intptr_t**)addr_at(interpreter_frame_last_sp_offset)) = sp; } #endif // CC_INTERP frame frame::sender_for_entry_frame(RegisterMap* map) const { assert(map != NULL, "map must be set"); // Java frame called from C; skip all C frames and return top C // frame of that chunk as the sender JavaFrameAnchor* jfa = entry_frame_call_wrapper()->anchor(); assert(!entry_frame_is_first(), "next Java fp must be non zero"); assert(jfa->last_Java_sp() > sp(), "must be above this frame on stack"); map->clear(); assert(map->include_argument_oops(), "should be set by clear"); if (jfa->last_Java_pc() != NULL ) { frame fr(jfa->last_Java_sp(), jfa->last_Java_fp(), jfa->last_Java_pc()); return fr; } frame fr(jfa->last_Java_sp(), jfa->last_Java_fp()); return fr; } //------------------------------------------------------------------------------ // frame::verify_deopt_original_pc // // Verifies the calculated original PC of a deoptimization PC for the // given unextended SP. The unextended SP might also be the saved SP // for MethodHandle call sites. #ifdef ASSERT void frame::verify_deopt_original_pc(nmethod* nm, intptr_t* unextended_sp, bool is_method_handle_return) { frame fr; // This is ugly but it's better than to change {get,set}_original_pc // to take an SP value as argument. And it's only a debugging // method anyway. fr._unextended_sp = unextended_sp; address original_pc = nm->get_original_pc(&fr); assert(nm->insts_contains(original_pc), "original PC must be in nmethod"); assert(nm->is_method_handle_return(original_pc) == is_method_handle_return, "must be"); } #endif //------------------------------------------------------------------------------ // frame::adjust_unextended_sp void frame::adjust_unextended_sp() { // If we are returning to a compiled MethodHandle call site, the // saved_fp will in fact be a saved value of the unextended SP. The // simplest way to tell whether we are returning to such a call site // is as follows: nmethod* sender_nm = (_cb == NULL) ? NULL : _cb->as_nmethod_or_null(); if (sender_nm != NULL) { // If the sender PC is a deoptimization point, get the original // PC. For MethodHandle call site the unextended_sp is stored in // saved_fp. if (sender_nm->is_deopt_mh_entry(_pc)) { DEBUG_ONLY(verify_deopt_mh_original_pc(sender_nm, _fp)); _unextended_sp = _fp; } else if (sender_nm->is_deopt_entry(_pc)) { DEBUG_ONLY(verify_deopt_original_pc(sender_nm, _unextended_sp)); } else if (sender_nm->is_method_handle_return(_pc)) { _unextended_sp = _fp; } } } //------------------------------------------------------------------------------ // frame::update_map_with_saved_link void frame::update_map_with_saved_link(RegisterMap* map, intptr_t** link_addr) { // The interpreter and compiler(s) always save EBP/RBP in a known // location on entry. We must record where that location is // so this if EBP/RBP was live on callout from c2 we can find // the saved copy no matter what it called. // Since the interpreter always saves EBP/RBP if we record where it is then // we don't have to always save EBP/RBP on entry and exit to c2 compiled // code, on entry will be enough.<|fim▁hole|>#ifdef AMD64 // this is weird "H" ought to be at a higher address however the // oopMaps seems to have the "H" regs at the same address and the // vanilla register. // XXXX make this go away if (true) { map->set_location(rbp->as_VMReg()->next(), (address) link_addr); } #endif // AMD64 } //------------------------------------------------------------------------------ // frame::sender_for_interpreter_frame frame frame::sender_for_interpreter_frame(RegisterMap* map) const { // SP is the raw SP from the sender after adapter or interpreter // extension. intptr_t* sender_sp = this->sender_sp(); // This is the sp before any possible extension (adapter/locals). intptr_t* unextended_sp = interpreter_frame_sender_sp(); #if defined(COMPILER2) || defined(JVMCI) if (map->update_map()) { update_map_with_saved_link(map, (intptr_t**) addr_at(link_offset)); } #endif // COMPILER2 || JVMCI return frame(sender_sp, unextended_sp, link(), sender_pc()); } //------------------------------------------------------------------------------ // frame::sender_for_compiled_frame frame frame::sender_for_compiled_frame(RegisterMap* map) const { assert(map != NULL, "map must be set"); // frame owned by optimizing compiler assert(_cb->frame_size() >= 0, "must have non-zero frame size"); intptr_t* sender_sp = unextended_sp() + _cb->frame_size(); intptr_t* unextended_sp = sender_sp; // On Intel the return_address is always the word on the stack address sender_pc = (address) *(sender_sp-1); // This is the saved value of EBP which may or may not really be an FP. // It is only an FP if the sender is an interpreter frame (or C1?). intptr_t** saved_fp_addr = (intptr_t**) (sender_sp - frame::sender_sp_offset); if (map->update_map()) { // Tell GC to use argument oopmaps for some runtime stubs that need it. // For C1, the runtime stub might not have oop maps, so set this flag // outside of update_register_map. map->set_include_argument_oops(_cb->caller_must_gc_arguments(map->thread())); if (_cb->oop_maps() != NULL) { OopMapSet::update_register_map(this, map); } // Since the prolog does the save and restore of EBP there is no oopmap // for it so we must fill in its location as if there was an oopmap entry // since if our caller was compiled code there could be live jvm state in it. update_map_with_saved_link(map, saved_fp_addr); } assert(sender_sp != sp(), "must have changed"); return frame(sender_sp, unextended_sp, *saved_fp_addr, sender_pc); } //------------------------------------------------------------------------------ // frame::sender frame frame::sender(RegisterMap* map) const { // Default is we done have to follow them. The sender_for_xxx will // update it accordingly map->set_include_argument_oops(false); if (is_entry_frame()) return sender_for_entry_frame(map); if (is_interpreted_frame()) return sender_for_interpreter_frame(map); assert(_cb == CodeCache::find_blob(pc()),"Must be the same"); if (_cb != NULL) { return sender_for_compiled_frame(map); } // Must be native-compiled frame, i.e. the marshaling code for native // methods that exists in the core system. return frame(sender_sp(), link(), sender_pc()); } bool frame::interpreter_frame_equals_unpacked_fp(intptr_t* fp) { assert(is_interpreted_frame(), "must be interpreter frame"); Method* method = interpreter_frame_method(); // When unpacking an optimized frame the frame pointer is // adjusted with: int diff = (method->max_locals() - method->size_of_parameters()) * Interpreter::stackElementWords; return _fp == (fp - diff); } void frame::pd_gc_epilog() { // nothing done here now } bool frame::is_interpreted_frame_valid(JavaThread* thread) const { // QQQ #ifdef CC_INTERP #else assert(is_interpreted_frame(), "Not an interpreted frame"); // These are reasonable sanity checks if (fp() == 0 || (intptr_t(fp()) & (wordSize-1)) != 0) { return false; } if (sp() == 0 || (intptr_t(sp()) & (wordSize-1)) != 0) { return false; } if (fp() + interpreter_frame_initial_sp_offset < sp()) { return false; } // These are hacks to keep us out of trouble. // The problem with these is that they mask other problems if (fp() <= sp()) { // this attempts to deal with unsigned comparison above return false; } // do some validation of frame elements // first the method Method* m = *interpreter_frame_method_addr(); // validate the method we'd find in this potential sender if (!m->is_valid_method()) return false; // stack frames shouldn't be much larger than max_stack elements if (fp() - sp() > 1024 + m->max_stack()*Interpreter::stackElementSize) { return false; } // validate bci/bcx intptr_t bcx = interpreter_frame_bcx(); if (m->validate_bci_from_bcx(bcx) < 0) { return false; } // validate ConstantPoolCache* ConstantPoolCache* cp = *interpreter_frame_cache_addr(); if (cp == NULL || !cp->is_metaspace_object()) return false; // validate locals address locals = (address) *interpreter_frame_locals_addr(); if (locals > thread->stack_base() || locals < (address) fp()) return false; // We'd have to be pretty unlucky to be mislead at this point #endif // CC_INTERP return true; } BasicType frame::interpreter_frame_result(oop* oop_result, jvalue* value_result) { #ifdef CC_INTERP // Needed for JVMTI. The result should always be in the // interpreterState object interpreterState istate = get_interpreterState(); #endif // CC_INTERP assert(is_interpreted_frame(), "interpreted frame expected"); Method* method = interpreter_frame_method(); BasicType type = method->result_type(); intptr_t* tos_addr; if (method->is_native()) { // Prior to calling into the runtime to report the method_exit the possible // return value is pushed to the native stack. If the result is a jfloat/jdouble // then ST0 is saved before EAX/EDX. See the note in generate_native_result tos_addr = (intptr_t*)sp(); if (type == T_FLOAT || type == T_DOUBLE) { // QQQ seems like this code is equivalent on the two platforms #ifdef AMD64 // This is times two because we do a push(ltos) after pushing XMM0 // and that takes two interpreter stack slots. tos_addr += 2 * Interpreter::stackElementWords; #else tos_addr += 2; #endif // AMD64 } } else { tos_addr = (intptr_t*)interpreter_frame_tos_address(); } switch (type) { case T_OBJECT : case T_ARRAY : { oop obj; if (method->is_native()) { #ifdef CC_INTERP obj = istate->_oop_temp; #else obj = cast_to_oop(at(interpreter_frame_oop_temp_offset)); #endif // CC_INTERP } else { oop* obj_p = (oop*)tos_addr; obj = (obj_p == NULL) ? (oop)NULL : *obj_p; } assert(obj == NULL || Universe::heap()->is_in(obj), "sanity check"); *oop_result = obj; break; } case T_BOOLEAN : value_result->z = *(jboolean*)tos_addr; break; case T_BYTE : value_result->b = *(jbyte*)tos_addr; break; case T_CHAR : value_result->c = *(jchar*)tos_addr; break; case T_SHORT : value_result->s = *(jshort*)tos_addr; break; case T_INT : value_result->i = *(jint*)tos_addr; break; case T_LONG : value_result->j = *(jlong*)tos_addr; break; case T_FLOAT : { #ifdef AMD64 value_result->f = *(jfloat*)tos_addr; #else if (method->is_native()) { jdouble d = *(jdouble*)tos_addr; // Result was in ST0 so need to convert to jfloat value_result->f = (jfloat)d; } else { value_result->f = *(jfloat*)tos_addr; } #endif // AMD64 break; } case T_DOUBLE : value_result->d = *(jdouble*)tos_addr; break; case T_VOID : /* Nothing to do */ break; default : ShouldNotReachHere(); } return type; } intptr_t* frame::interpreter_frame_tos_at(jint offset) const { int index = (Interpreter::expr_offset_in_bytes(offset)/wordSize); return &interpreter_frame_tos_address()[index]; } #ifndef PRODUCT #define DESCRIBE_FP_OFFSET(name) \ values.describe(frame_no, fp() + frame::name##_offset, #name) void frame::describe_pd(FrameValues& values, int frame_no) { if (is_interpreted_frame()) { DESCRIBE_FP_OFFSET(interpreter_frame_sender_sp); DESCRIBE_FP_OFFSET(interpreter_frame_last_sp); DESCRIBE_FP_OFFSET(interpreter_frame_method); DESCRIBE_FP_OFFSET(interpreter_frame_mdx); DESCRIBE_FP_OFFSET(interpreter_frame_cache); DESCRIBE_FP_OFFSET(interpreter_frame_locals); DESCRIBE_FP_OFFSET(interpreter_frame_bcx); DESCRIBE_FP_OFFSET(interpreter_frame_initial_sp); #ifdef AMD64 } else if (is_entry_frame()) { // This could be more descriptive if we use the enum in // stubGenerator to map to real names but it's most important to // claim these frame slots so the error checking works. for (int i = 0; i < entry_frame_after_call_words; i++) { values.describe(frame_no, fp() - i, err_msg("call_stub word fp - %d", i)); } #endif // AMD64 } } #endif // !PRODUCT intptr_t *frame::initial_deoptimization_info() { // used to reset the saved FP return fp(); } intptr_t* frame::real_fp() const { if (_cb != NULL) { // use the frame size if valid int size = _cb->frame_size(); if (size > 0) { return unextended_sp() + size; } } // else rely on fp() assert(! is_compiled_frame(), "unknown compiled frame size"); return fp(); }<|fim▁end|>
map->set_location(rbp->as_VMReg(), (address) link_addr);
<|file_name|>tools.d.ts<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
export { enableDebugTools, disableDebugTools } from 'angular2/src/tools/tools';
<|file_name|>sqs_transport.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import boto.sqs import uuid from beaver.transports.base_transport import BaseTransport from beaver.transports.exception import TransportException class SqsTransport(BaseTransport):<|fim▁hole|> def __init__(self, beaver_config, logger=None): super(SqsTransport, self).__init__(beaver_config, logger=logger) self._access_key = beaver_config.get('sqs_aws_access_key') self._secret_key = beaver_config.get('sqs_aws_secret_key') self._region = beaver_config.get('sqs_aws_region') self._queue_name = beaver_config.get('sqs_aws_queue') try: if self._access_key is None and self._secret_key is None: self._connection = boto.sqs.connect_to_region(self._region) else: self._connection = boto.sqs.connect_to_region(self._region, aws_access_key_id=self._access_key, aws_secret_access_key=self._secret_key) if self._connection is None: self._logger.warn('Unable to connect to AWS - check your AWS credentials') raise TransportException('Unable to connect to AWS - check your AWS credentials') self._queue = self._connection.get_queue(self._queue_name) if self._queue is None: raise TransportException('Unable to access queue with name {0}'.format(self._queue_name)) except Exception, e: raise TransportException(e.message) def callback(self, filename, lines, **kwargs): timestamp = self.get_timestamp(**kwargs) if kwargs.get('timestamp', False): del kwargs['timestamp'] message_batch = [] for line in lines: message_batch.append((uuid.uuid4(), self.format(filename, line, timestamp, **kwargs), 0)) if len(message_batch) == 10: # SQS can only handle up to 10 messages in batch send self._logger.debug('Flushing 10 messages to SQS queue') self._send_message_batch(message_batch) message_batch = [] if len(message_batch) > 0: self._logger.debug('Flushing last {0} messages to SQS queue'.format(len(message_batch))) self._send_message_batch(message_batch) return True def _send_message_batch(self, message_batch): try: result = self._queue.write_batch(message_batch) if not result: self._logger.error('Error occurred sending messages to SQS queue {0}. result: {1}'.format( self._queue_name, result)) raise TransportException('Error occurred sending message to queue {0}'.format(self._queue_name)) except Exception, e: self._logger.exception('Exception occurred sending batch to SQS queue') raise TransportException(e.message) def interrupt(self): return True def unhandled(self): return True<|fim▁end|>
<|file_name|>15.9.5.30-1.js<|end_file_name|><|fim▁begin|>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ gTestfile = '15.9.5.30-1.js'; /** File Name: 15.9.5.30-1.js ECMA Section: 15.9.5.30 Date.prototype.setHours(hour [, min [, sec [, ms ]]] ) Description:<|fim▁hole|> 1. Let t be the result of LocalTime(this time value). 2. Call ToNumber(hour). 3. If min is not specified, compute MinFromTime(t); otherwise, call ToNumber(min). 4. If sec is not specified, compute SecFromTime(t); otherwise, call ToNumber(sec). 5. If ms is not specified, compute msFromTime(t); otherwise, call ToNumber(ms). 6. Compute MakeTime(Result(2), Result(3), Result(4), Result(5)). 7. Compute UTC(MakeDate(Day(t), Result(6))). 8. Set the [[Value]] property of the this value to TimeClip(Result(7)). 9. Return the value of the [[Value]] property of the this value. Author: christine@netscape.com Date: 12 november 1997 */ var SECTION = "15.9.5.30-1"; var VERSION = "ECMA_1"; startTest(); writeHeaderToLog( SECTION + " Date.prototype.setHours( hour [, min, sec, ms] )"); addNewTestCase( 0,0,0,0,void 0, "TDATE = new Date(0);(TDATE).setHours(0);TDATE" ); addNewTestCase( 28800000, 23, 59, 999,void 0, "TDATE = new Date(28800000);(TDATE).setHours(23,59,999);TDATE" ); addNewTestCase( 28800000, 999, 999, void 0, void 0, "TDATE = new Date(28800000);(TDATE).setHours(999,999);TDATE" ); addNewTestCase( 28800000,999,0, void 0, void 0, "TDATE = new Date(28800000);(TDATE).setHours(999);TDATE" ); addNewTestCase( 28800000,-8, void 0, void 0, void 0, "TDATE = new Date(28800000);(TDATE).setHours(-8);TDATE" ); addNewTestCase( 946684800000,8760, void 0, void 0, void 0, "TDATE = new Date(946684800000);(TDATE).setHours(8760);TDATE" ); addNewTestCase( TIME_2000 - msPerDay, 23, 59, 59, 999, "d = new Date( " + (TIME_2000-msPerDay) +"); d.setHours(23,59,59,999)" ); addNewTestCase( TIME_2000 - msPerDay, 23, 59, 59, 1000, "d = new Date( " + (TIME_2000-msPerDay) +"); d.setHours(23,59,59,1000)" ); test(); function addNewTestCase( time, hours, min, sec, ms, DateString) { var UTCDate = UTCDateFromTime( SetHours( time, hours, min, sec, ms )); var LocalDate = LocalDateFromTime( SetHours( time, hours, min, sec, ms )); var DateCase = new Date( time ); if ( min == void 0 ) { DateCase.setHours( hours ); } else { if ( sec == void 0 ) { DateCase.setHours( hours, min ); } else { if ( ms == void 0 ) { DateCase.setHours( hours, min, sec ); } else { DateCase.setHours( hours, min, sec, ms ); } } } new TestCase( SECTION, DateString+".getTime()", UTCDate.value, DateCase.getTime() ); new TestCase( SECTION, DateString+".valueOf()", UTCDate.value, DateCase.valueOf() ); new TestCase( SECTION, DateString+".getUTCFullYear()", UTCDate.year, DateCase.getUTCFullYear() ); new TestCase( SECTION, DateString+".getUTCMonth()", UTCDate.month, DateCase.getUTCMonth() ); new TestCase( SECTION, DateString+".getUTCDate()", UTCDate.date, DateCase.getUTCDate() ); new TestCase( SECTION, DateString+".getUTCDay()", UTCDate.day, DateCase.getUTCDay() ); new TestCase( SECTION, DateString+".getUTCHours()", UTCDate.hours, DateCase.getUTCHours() ); new TestCase( SECTION, DateString+".getUTCMinutes()", UTCDate.minutes,DateCase.getUTCMinutes() ); new TestCase( SECTION, DateString+".getUTCSeconds()", UTCDate.seconds,DateCase.getUTCSeconds() ); new TestCase( SECTION, DateString+".getUTCMilliseconds()", UTCDate.ms, DateCase.getUTCMilliseconds() ); new TestCase( SECTION, DateString+".getFullYear()", LocalDate.year, DateCase.getFullYear() ); new TestCase( SECTION, DateString+".getMonth()", LocalDate.month, DateCase.getMonth() ); new TestCase( SECTION, DateString+".getDate()", LocalDate.date, DateCase.getDate() ); new TestCase( SECTION, DateString+".getDay()", LocalDate.day, DateCase.getDay() ); new TestCase( SECTION, DateString+".getHours()", LocalDate.hours, DateCase.getHours() ); new TestCase( SECTION, DateString+".getMinutes()", LocalDate.minutes, DateCase.getMinutes() ); new TestCase( SECTION, DateString+".getSeconds()", LocalDate.seconds, DateCase.getSeconds() ); new TestCase( SECTION, DateString+".getMilliseconds()", LocalDate.ms, DateCase.getMilliseconds() ); DateCase.toString = Object.prototype.toString; new TestCase( SECTION, DateString+".toString=Object.prototype.toString;"+DateString+".toString()", "[object Date]", DateCase.toString() ); } function MyDate() { this.year = 0; this.month = 0; this.date = 0; this.hours = 0; this.minutes = 0; this.seconds = 0; this.ms = 0; } function LocalDateFromTime(t) { t = LocalTime(t); return ( MyDateFromTime(t) ); } function UTCDateFromTime(t) { return ( MyDateFromTime(t) ); } function MyDateFromTime( t ) { var d = new MyDate(); d.year = YearFromTime(t); d.month = MonthFromTime(t); d.date = DateFromTime(t); d.hours = HourFromTime(t); d.minutes = MinFromTime(t); d.seconds = SecFromTime(t); d.ms = msFromTime(t); d.day = WeekDay( t ); d.time = MakeTime( d.hours, d.minutes, d.seconds, d.ms ); d.value = TimeClip( MakeDate( MakeDay( d.year, d.month, d.date ), d.time ) ); return (d); } function SetHours( t, hour, min, sec, ms ) { var TIME = LocalTime(t); var HOUR = Number(hour); var MIN = ( min == void 0) ? MinFromTime(TIME) : Number(min); var SEC = ( sec == void 0) ? SecFromTime(TIME) : Number(sec); var MS = ( ms == void 0 ) ? msFromTime(TIME) : Number(ms); var RESULT6 = MakeTime( HOUR, MIN, SEC, MS ); var UTC_TIME = UTC( MakeDate(Day(TIME), RESULT6) ); return ( TimeClip(UTC_TIME) ); }<|fim▁end|>
If min is not specified, this behaves as if min were specified with the value getMinutes( ). If sec is not specified, this behaves as if sec were specified with the value getSeconds ( ). If ms is not specified, this behaves as if ms were specified with the value getMilliseconds( ).
<|file_name|>test_shared_folders.py<|end_file_name|><|fim▁begin|>from nxdrive.tests.common_unit_test import UnitTestCase from nxdrive.client import RemoteDocumentClient from nxdrive.client import LocalClient class TestSharedFolders(UnitTestCase): def test_move_sync_root_child_to_user_workspace(self): """See https://jira.nuxeo.com/browse/NXP-14870""" admin_remote_client = self.root_remote_client user1_workspace_path = ('/default-domain/UserWorkspaces/' 'nuxeoDriveTestUser-user-1') try: # Get remote and local clients remote_user1 = RemoteDocumentClient( self.nuxeo_url, self.user_1, u'nxdrive-test-device-1', self.version, password=self.password_1, upload_tmp_dir=self.upload_tmp_dir) remote_user2 = RemoteDocumentClient( self.nuxeo_url, self.user_2, u'nxdrive-test-device-2', self.version, password=self.password_2, upload_tmp_dir=self.upload_tmp_dir) local_user2 = LocalClient(self.local_nxdrive_folder_2) # Make sure personal workspace is created for user1 remote_user1.make_file_in_user_workspace('File in user workspace', filename='UWFile.txt') # As user1 register personal workspace as a sync root remote_user1.register_as_root(user1_workspace_path) # As user1 create a parent folder in user1's personal workspace remote_user1.make_folder(user1_workspace_path, 'Parent') # As user1 grant Everything permission to user2 on parent folder parent_folder_path = user1_workspace_path + '/Parent' op_input = "doc:" + parent_folder_path admin_remote_client.execute("Document.SetACE", op_input=op_input, user="nuxeoDriveTestUser_user_2", permission="Everything", grant="true") # As user1 create a child folder in parent folder remote_user1.make_folder(parent_folder_path, 'Child') # As user2 register parent folder as a sync root remote_user2.register_as_root(parent_folder_path) remote_user2.unregister_as_root(self.workspace) # Start engine for user2<|fim▁hole|> # Wait for synchronization self.wait_sync(wait_for_async=True, wait_for_engine_1=False, wait_for_engine_2=True) # Check locally synchronized content self.assertEquals(len(local_user2.get_children_info('/')), 1) self.assertTrue(local_user2.exists('/Parent')) self.assertTrue(local_user2.exists('/Parent/Child')) # As user1 move child folder to user1's personal workspace remote_user1.move(parent_folder_path + '/Child', user1_workspace_path) # Wait for synchronization self.wait_sync(wait_for_async=True, wait_for_engine_1=False, wait_for_engine_2=True) # Check locally synchronized content self.assertFalse(local_user2.exists('/Parent/Child')) finally: # Cleanup user1 personal workspace if admin_remote_client.exists(user1_workspace_path): admin_remote_client.delete(user1_workspace_path, use_trash=False)<|fim▁end|>
self.engine_2.start()
<|file_name|>zip.py<|end_file_name|><|fim▁begin|>def zip(*arg): Result = [] Check = 1 #check if every item in arg has the same length for i in arg: if len(i) != len(arg[0]): print 'please make sure enter all items with the same length' Check = 0 break while (Check): for j in range(0,len(arg[0])): result = () for item in arg: result = result + (item[j],) Result.append(result) Check = 0 return Result def unzip(x): Length = len(x[0]) result = () LIST = [] for i in range(0,len(x[0])): LIST.append([],) for item in x: for j in range(0,len(LIST)): LIST[j].append(item[j]) for k in LIST: result = result + (k,) return result def Test(): print '#1 test: ' print ' zip([1,1,1],[2,2,2],[3,3,3],[4,4,4]) -->', zip([1,1,1],[2,2,2],[3,3,3],[4,4,4]) print '\n' print ' unzip([(1,2,3,4,5),(2,3,4,5,6),(3,4,5,6,7)]) -->', unzip([(1,2,3,4,5),(2,3,4,5,6),(3,4,5,6,7)]) print '\n' print '#2 test: unzip(zip([100,200,300],[200,300,400],[0,0,0]))'<|fim▁hole|> Test()<|fim▁end|>
print unzip(zip([100,200,300],[200,300,400], [0,0,0])) print '\n' if __name__ == '__main__':
<|file_name|>indexer.rs<|end_file_name|><|fim▁begin|>// Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation // Copyright (C) 2020 Stacks Open Internet Foundation // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. use burnchains::BurnchainBlock; use burnchains::Error as burnchain_error; use burnchains::*; use crate::types::chainstate::BurnchainHeaderHash; use core::StacksEpoch; // IPC messages between threads pub trait BurnHeaderIPC { type H: Send + Sync + Clone; fn height(&self) -> u64; fn header(&self) -> Self::H; fn header_hash(&self) -> [u8; 32]; } pub trait BurnBlockIPC { type H: BurnHeaderIPC + Sync + Send + Clone; type B: Send + Sync + Clone; fn height(&self) -> u64; fn header(&self) -> Self::H; fn block(&self) -> Self::B; } <|fim▁hole|> fn download(&mut self, header: &Self::H) -> Result<Self::B, burnchain_error>; } pub trait BurnchainBlockParser { type D: BurnchainBlockDownloader + Sync + Send; fn parse( &mut self, block: &<<Self as BurnchainBlockParser>::D as BurnchainBlockDownloader>::B, ) -> Result<BurnchainBlock, burnchain_error>; } pub trait BurnchainIndexer { type P: BurnchainBlockParser + Send + Sync; fn connect(&mut self) -> Result<(), burnchain_error>; fn get_first_block_height(&self) -> u64; fn get_first_block_header_hash(&self) -> Result<BurnchainHeaderHash, burnchain_error>; fn get_first_block_header_timestamp(&self) -> Result<u64, burnchain_error>; fn get_stacks_epochs(&self) -> Vec<StacksEpoch>; fn get_headers_path(&self) -> String; fn get_headers_height(&self) -> Result<u64, burnchain_error>; fn get_highest_header_height(&self) -> Result<u64, burnchain_error>; fn find_chain_reorg(&mut self) -> Result<u64, burnchain_error>; fn sync_headers( &mut self, start_height: u64, end_height: Option<u64>, ) -> Result<u64, burnchain_error>; fn drop_headers(&mut self, new_height: u64) -> Result<(), burnchain_error>; fn read_headers(&self, start_block: u64, end_block: u64) -> Result<Vec<<<<Self as BurnchainIndexer>::P as BurnchainBlockParser>::D as BurnchainBlockDownloader>::H>, burnchain_error>; fn downloader(&self) -> <<Self as BurnchainIndexer>::P as BurnchainBlockParser>::D; fn parser(&self) -> Self::P; }<|fim▁end|>
pub trait BurnchainBlockDownloader { type H: BurnHeaderIPC + Sync + Send + Clone; type B: BurnBlockIPC + Sync + Send + Clone;
<|file_name|>wsgi.py<|end_file_name|><|fim▁begin|>""" WSGI config for django_mailing project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see<|fim▁hole|> import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_mailing.settings") application = get_wsgi_application()<|fim▁end|>
https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/ """
<|file_name|>macho_analysis.py<|end_file_name|><|fim▁begin|># !/usr/bin/python # coding=utf-8 import logging import lief logger = logging.getLogger(__name__) class Checksec: def __init__(self, macho): self.macho = lief.parse(macho.as_posix()) def checksec(self): macho_dict = {} macho_dict['name'] = self.macho.name has_nx = self.has_nx() has_pie = self.has_pie() has_canary = self.has_canary() has_rpath = self.has_rpath() has_code_signature = self.has_code_signature() has_arc = self.has_arc() is_encrypted = self.is_encrypted() is_stripped = self.is_symbols_stripped() if has_nx: severity = 'info' desc = ( 'The binary has NX bit set. This marks a ' 'memory page non-executable making attacker ' 'injected shellcode non-executable.') else: severity = 'info' desc = ( 'The binary does not have NX bit set. NX bit ' 'offer protection against exploitation of memory corruption ' 'vulnerabilities by marking memory page as non-executable. ' 'However iOS never allows an app to execute from writeable ' 'memory. You do not need to specifically enable the ' '‘NX bit’ because it’s always enabled for all ' 'third-party code.') macho_dict['nx'] = { 'has_nx': has_nx, 'severity': severity, 'description': desc, } if has_pie: severity = 'info' desc = ( 'The binary is build with -fPIC flag which ' 'enables Position independent code. This makes Return ' 'Oriented Programming (ROP) attacks much more difficult ' 'to execute reliably.') else: severity = 'high' desc = ( 'The binary is built without Position ' 'Independent Code flag. In order to prevent ' 'an attacker from reliably jumping to, for example, a ' 'particular exploited function in memory, Address ' 'space layout randomization (ASLR) randomly arranges ' 'the address space positions of key data areas of a ' 'process, including the base of the executable and the ' 'positions of the stack,heap and libraries. Use compiler ' 'option -fPIC to enable Position Independent Code.') macho_dict['pie'] = { 'has_pie': has_pie, 'severity': severity, 'description': desc, } if has_canary: severity = 'info' desc = ( 'This binary has a stack canary value ' 'added to the stack so that it will be overwritten by ' 'a stack buffer that overflows the return address. ' 'This allows detection of overflows by verifying the ' 'integrity of the canary before function return.') elif is_stripped: severity = 'warning' desc = ( 'This binary has symbols stripped. We cannot identify ' 'whether stack canary is enabled or not.') else: severity = 'high' desc = ( 'This binary does not have a stack ' 'canary value added to the stack. Stack canaries ' 'are used to detect and prevent exploits from ' 'overwriting return address. Use the option ' '-fstack-protector-all to enable stack canaries.') macho_dict['stack_canary'] = { 'has_canary': has_canary, 'severity': severity, 'description': desc, } if has_arc: severity = 'info' desc = ( 'The binary is compiled with Automatic Reference ' 'Counting (ARC) flag. ARC is a compiler ' 'feature that provides automatic memory ' 'management of Objective-C objects and is an ' 'exploit mitigation mechanism against memory ' 'corruption vulnerabilities.' ) elif is_stripped: severity = 'warning' desc = ( 'This binary has symbols stripped. We cannot identify ' 'whether ARC is enabled or not.') else: severity = 'high' desc = ( 'The binary is not compiled with Automatic ' 'Reference Counting (ARC) flag. ARC is a compiler ' 'feature that provides automatic memory ' 'management of Objective-C objects and ' 'protects from memory corruption ' 'vulnerabilities. Use compiler option ' '-fobjc-arc to enable ARC.') macho_dict['arc'] = { 'has_arc': has_arc, 'severity': severity, 'description': desc, } if has_rpath: severity = 'warning' desc = ( 'The binary has Runpath Search Path (@rpath) set. ' 'In certain cases an attacker can abuse this ' 'feature to run arbitrary executable for code ' 'execution and privilege escalation. Remove the ' 'compiler option -rpath to remove @rpath.') else: severity = 'info' desc = ( 'The binary does not have Runpath Search ' 'Path (@rpath) set.') macho_dict['rpath'] = { 'has_rpath': has_rpath, 'severity': severity, 'description': desc, } if has_code_signature: severity = 'info' desc = 'This binary has a code signature.' else: severity = 'warning' desc = 'This binary does not have a code signature.' macho_dict['code_signature'] = { 'has_code_signature': has_code_signature, 'severity': severity, 'description': desc, } if is_encrypted: severity = 'info' desc = 'This binary is encrypted.' else: severity = 'warning' desc = 'This binary is not encrypted.' macho_dict['encrypted'] = { 'is_encrypted': is_encrypted, 'severity': severity, 'description': desc, } if is_stripped: severity = 'info' desc = 'Symbols are stripped' else: severity = 'warning' desc = ( 'Symbols are available. To strip ' 'debugging symbols, set Strip Debug ' 'Symbols During Copy to YES, '<|fim▁hole|> 'and Strip Linked Product to YES in ' 'project\'s build settings.') macho_dict['symbol'] = { 'is_stripped': is_stripped, 'severity': severity, 'description': desc, } return macho_dict def has_nx(self): return self.macho.has_nx def has_pie(self): return self.macho.is_pie def has_canary(self): stk_check = '___stack_chk_fail' stk_guard = '___stack_chk_guard' ipt_list = set() for ipt in self.macho.imported_functions: ipt_list.add(str(ipt)) return stk_check in ipt_list and stk_guard in ipt_list def has_arc(self): for func in self.macho.imported_functions: if str(func).strip() == '_objc_release': return True return False def has_rpath(self): return self.macho.has_rpath def has_code_signature(self): try: return self.macho.code_signature.data_size > 0 except Exception: return False def is_encrypted(self): return bool(self.macho.encryption_info.crypt_id) def is_symbols_stripped(self): for i in self.macho.symbols: if i: return False return True def get_libraries(self): libs = [] for i in self.macho.libraries: curr = '.'.join(str(x) for x in i.current_version) comp = '.'.join(str(x) for x in i.compatibility_version) lib = (f'{i.name} (compatibility version: {comp}' f', current version: {curr})') libs.append(lib) return libs def get_symbols(self): symbols = [] for i in self.macho.symbols: symbols.append(i.name) return symbols def macho_analysis(binary): try: logger.info('Running MachO Analysis on %s', binary.name) cs = Checksec(binary) chksec = cs.checksec() symbols = cs.get_symbols() libs = cs.get_libraries() return { 'checksec': chksec, 'symbols': symbols, 'libraries': libs, } except Exception: logger.exception('Running MachO Analysis') return {}<|fim▁end|>
'Deployment Postprocessing to YES, '
<|file_name|>gen_generic.py<|end_file_name|><|fim▁begin|>extensions = dict( required_params=[], # empty to override defaults in gen_defaults validate_required_params=""" # Required args: either model_key or path if (is.null(model_key) && is.null(path)) stop("argument 'model_key' or 'path' must be provided") """, set_required_params="", ) doc = dict( preamble=""" Imports a generic model into H2O. Such model can be used then used for scoring and obtaining additional information about the model. The imported model has to be supported by H2O. """, examples=""" # library(h2o) # h2o.init() # generic_model <- h2o.genericModel(path="/path/to/model.zip", model_id="my_model") # predictions <- h2o.predict(generic_model, dataset) """<|fim▁hole|>)<|fim▁end|>
<|file_name|>mootools-core-1.4.5.js<|end_file_name|><|fim▁begin|>/* --- MooTools: the javascript framework web build: - http://mootools.net/core/8423c12ffd6a6bfcde9ea22554aec795 packager build: - packager build Core/Core Core/Array Core/String Core/Number Core/Function Core/Object Core/Event Core/Browser Core/Class Core/Class.Extras Core/Slick.Parser Core/Slick.Finder Core/Element Core/Element.Style Core/Element.Event Core/Element.Delegation Core/Element.Dimensions Core/Fx Core/Fx.CSS Core/Fx.Tween Core/Fx.Morph Core/Fx.Transitions Core/Request Core/Request.HTML Core/Request.JSON Core/Cookie Core/JSON Core/DOMReady ... */ /* --- name: Core description: The heart of MooTools. license: MIT-style license. copyright: Copyright (c) 2006-2012 [Valerio Proietti](http://mad4milk.net/). authors: The MooTools production team (http://mootools.net/developers/) inspiration: - Class implementation inspired by [Base.js](http://dean.edwards.name/weblog/2006/03/base/) Copyright (c) 2006 Dean Edwards, [GNU Lesser General Public License](http://opensource.org/licenses/lgpl-license.php) - Some functionality inspired by [Prototype.js](http://prototypejs.org) Copyright (c) 2005-2007 Sam Stephenson, [MIT License](http://opensource.org/licenses/mit-license.php) provides: [Core, MooTools, Type, typeOf, instanceOf, Native] ... */ (function(){ this.MooTools = { version: '1.4.5', build: 'ab8ea8824dc3b24b6666867a2c4ed58ebb762cf0' }; // typeOf, instanceOf var typeOf = this.typeOf = function(item){ if (item == null) return 'null'; if (item.$family != null) return item.$family(); if (item.nodeName){ if (item.nodeType == 1) return 'element'; if (item.nodeType == 3) return (/\S/).test(item.nodeValue) ? 'textnode' : 'whitespace'; } else if (typeof item.length == 'number'){ if (item.callee) return 'arguments'; if ('item' in item) return 'collection'; } return typeof item; }; var instanceOf = this.instanceOf = function(item, object){ if (item == null) return false; var constructor = item.$constructor || item.constructor; while (constructor){ if (constructor === object) return true; constructor = constructor.parent; } /*<ltIE8>*/ if (!item.hasOwnProperty) return false; /*</ltIE8>*/ return item instanceof object; }; // Function overloading var Function = this.Function; var enumerables = true; for (var i in {toString: 1}) enumerables = null; if (enumerables) enumerables = ['hasOwnProperty', 'valueOf', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'constructor']; Function.prototype.overloadSetter = function(usePlural){ var self = this; return function(a, b){ if (a == null) return this; if (usePlural || typeof a != 'string'){ for (var k in a) self.call(this, k, a[k]); if (enumerables) for (var i = enumerables.length; i--;){ k = enumerables[i]; if (a.hasOwnProperty(k)) self.call(this, k, a[k]); } } else { self.call(this, a, b); } return this; }; }; Function.prototype.overloadGetter = function(usePlural){ var self = this; return function(a){ var args, result; if (typeof a != 'string') args = a; else if (arguments.length > 1) args = arguments; else if (usePlural) args = [a]; if (args){ result = {}; for (var i = 0; i < args.length; i++) result[args[i]] = self.call(this, args[i]); } else { result = self.call(this, a); } return result; }; }; Function.prototype.extend = function(key, value){ this[key] = value; }.overloadSetter(); Function.prototype.implement = function(key, value){ this.prototype[key] = value; }.overloadSetter(); // From var slice = Array.prototype.slice; Function.from = function(item){ return (typeOf(item) == 'function') ? item : function(){ return item; }; }; Array.from = function(item){ if (item == null) return []; return (Type.isEnumerable(item) && typeof item != 'string') ? (typeOf(item) == 'array') ? item : slice.call(item) : [item]; }; Number.from = function(item){ var number = parseFloat(item); return isFinite(number) ? number : null; }; String.from = function(item){ return item + ''; }; // hide, protect Function.implement({ hide: function(){ this.$hidden = true; return this; }, protect: function(){ this.$protected = true; return this; } }); // Type var Type = this.Type = function(name, object){ if (name){ var lower = name.toLowerCase(); var typeCheck = function(item){ return (typeOf(item) == lower); }; Type['is' + name] = typeCheck; if (object != null){ object.prototype.$family = (function(){ return lower; }).hide(); } } if (object == null) return null; object.extend(this); object.$constructor = Type; object.prototype.$constructor = object; return object; }; var toString = Object.prototype.toString; Type.isEnumerable = function(item){ return (item != null && typeof item.length == 'number' && toString.call(item) != '[object Function]' ); }; var hooks = {}; var hooksOf = function(object){ var type = typeOf(object.prototype); return hooks[type] || (hooks[type] = []); }; var implement = function(name, method){ if (method && method.$hidden) return; var hooks = hooksOf(this); for (var i = 0; i < hooks.length; i++){ var hook = hooks[i]; if (typeOf(hook) == 'type') implement.call(hook, name, method); else hook.call(this, name, method); } var previous = this.prototype[name]; if (previous == null || !previous.$protected) this.prototype[name] = method; if (this[name] == null && typeOf(method) == 'function') extend.call(this, name, function(item){ return method.apply(item, slice.call(arguments, 1)); }); }; var extend = function(name, method){ if (method && method.$hidden) return; var previous = this[name]; if (previous == null || !previous.$protected) this[name] = method; }; Type.implement({ implement: implement.overloadSetter(), extend: extend.overloadSetter(), alias: function(name, existing){ implement.call(this, name, this.prototype[existing]); }.overloadSetter(), mirror: function(hook){ hooksOf(this).push(hook); return this; } }); new Type('Type', Type); // Default Types var force = function(name, object, methods){ var isType = (object != Object), prototype = object.prototype; if (isType) object = new Type(name, object); for (var i = 0, l = methods.length; i < l; i++){ var key = methods[i], generic = object[key], proto = prototype[key]; if (generic) generic.protect(); if (isType && proto) object.implement(key, proto.protect()); } if (isType){ var methodsEnumerable = prototype.propertyIsEnumerable(methods[0]); object.forEachMethod = function(fn){ if (!methodsEnumerable) for (var i = 0, l = methods.length; i < l; i++){ fn.call(prototype, prototype[methods[i]], methods[i]); } for (var key in prototype) fn.call(prototype, prototype[key], key) }; } return force; }; force('String', String, [ 'charAt', 'charCodeAt', 'concat', 'indexOf', 'lastIndexOf', 'match', 'quote', 'replace', 'search', 'slice', 'split', 'substr', 'substring', 'trim', 'toLowerCase', 'toUpperCase' ])('Array', Array, [ 'pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift', 'concat', 'join', 'slice', 'indexOf', 'lastIndexOf', 'filter', 'forEach', 'every', 'map', 'some', 'reduce', 'reduceRight' ])('Number', Number, [ 'toExponential', 'toFixed', 'toLocaleString', 'toPrecision' ])('Function', Function, [ 'apply', 'call', 'bind' ])('RegExp', RegExp, [ 'exec', 'test' ])('Object', Object, [ 'create', 'defineProperty', 'defineProperties', 'keys', 'getPrototypeOf', 'getOwnPropertyDescriptor', 'getOwnPropertyNames', 'preventExtensions', 'isExtensible', 'seal', 'isSealed', 'freeze', 'isFrozen' ])('Date', Date, ['now']); Object.extend = extend.overloadSetter(); Date.extend('now', function(){ return +(new Date); }); new Type('Boolean', Boolean); // fixes NaN returning as Number Number.prototype.$family = function(){ return isFinite(this) ? 'number' : 'null'; }.hide(); // Number.random Number.extend('random', function(min, max){ return Math.floor(Math.random() * (max - min + 1) + min); }); // forEach, each var hasOwnProperty = Object.prototype.hasOwnProperty; Object.extend('forEach', function(object, fn, bind){ for (var key in object){ if (hasOwnProperty.call(object, key)) fn.call(bind, object[key], key, object); } }); Object.each = Object.forEach; Array.implement({ forEach: function(fn, bind){ for (var i = 0, l = this.length; i < l; i++){ if (i in this) fn.call(bind, this[i], i, this); } }, each: function(fn, bind){ Array.forEach(this, fn, bind); return this; } }); // Array & Object cloning, Object merging and appending var cloneOf = function(item){ switch (typeOf(item)){ case 'array': return item.clone(); case 'object': return Object.clone(item); default: return item; } }; Array.implement('clone', function(){ var i = this.length, clone = new Array(i); while (i--) clone[i] = cloneOf(this[i]); return clone; }); var mergeOne = function(source, key, current){ switch (typeOf(current)){ case 'object': if (typeOf(source[key]) == 'object') Object.merge(source[key], current); else source[key] = Object.clone(current); break; case 'array': source[key] = current.clone(); break; default: source[key] = current; } return source; }; Object.extend({ merge: function(source, k, v){ if (typeOf(k) == 'string') return mergeOne(source, k, v); for (var i = 1, l = arguments.length; i < l; i++){ var object = arguments[i]; for (var key in object) mergeOne(source, key, object[key]); } return source; }, clone: function(object){ var clone = {}; for (var key in object) clone[key] = cloneOf(object[key]); return clone; }, append: function(original){ for (var i = 1, l = arguments.length; i < l; i++){ var extended = arguments[i] || {}; for (var key in extended) original[key] = extended[key]; } return original; } }); // Object-less types ['Object', 'WhiteSpace', 'TextNode', 'Collection', 'Arguments'].each(function(name){ new Type(name); }); // Unique ID var UID = Date.now(); String.extend('uniqueID', function(){ return (UID++).toString(36); }); })(); /* --- name: Array description: Contains Array Prototypes like each, contains, and erase. license: MIT-style license. requires: Type provides: Array ... */ Array.implement({ /*<!ES5>*/ every: function(fn, bind){ for (var i = 0, l = this.length >>> 0; i < l; i++){ if ((i in this) && !fn.call(bind, this[i], i, this)) return false; } return true; }, filter: function(fn, bind){ var results = []; for (var value, i = 0, l = this.length >>> 0; i < l; i++) if (i in this){ value = this[i]; if (fn.call(bind, value, i, this)) results.push(value); } return results; }, indexOf: function(item, from){ var length = this.length >>> 0; for (var i = (from < 0) ? Math.max(0, length + from) : from || 0; i < length; i++){ if (this[i] === item) return i; } return -1; }, map: function(fn, bind){ var length = this.length >>> 0, results = Array(length); for (var i = 0; i < length; i++){ if (i in this) results[i] = fn.call(bind, this[i], i, this); } return results; }, some: function(fn, bind){ for (var i = 0, l = this.length >>> 0; i < l; i++){ if ((i in this) && fn.call(bind, this[i], i, this)) return true; } return false; }, /*</!ES5>*/ clean: function(){ return this.filter(function(item){ return item != null; }); }, invoke: function(methodName){ var args = Array.slice(arguments, 1); return this.map(function(item){ return item[methodName].apply(item, args); }); }, associate: function(keys){ var obj = {}, length = Math.min(this.length, keys.length); for (var i = 0; i < length; i++) obj[keys[i]] = this[i]; return obj; }, link: function(object){ var result = {}; for (var i = 0, l = this.length; i < l; i++){ for (var key in object){ if (object[key](this[i])){ result[key] = this[i]; delete object[key]; break; } } } return result; }, contains: function(item, from){ return this.indexOf(item, from) != -1; }, append: function(array){ this.push.apply(this, array); return this; }, getLast: function(){ return (this.length) ? this[this.length - 1] : null; }, getRandom: function(){ return (this.length) ? this[Number.random(0, this.length - 1)] : null; }, include: function(item){ if (!this.contains(item)) this.push(item); return this; }, combine: function(array){ for (var i = 0, l = array.length; i < l; i++) this.include(array[i]); return this; }, erase: function(item){ for (var i = this.length; i--;){ if (this[i] === item) this.splice(i, 1); } return this; }, empty: function(){ this.length = 0; return this; }, flatten: function(){ var array = []; for (var i = 0, l = this.length; i < l; i++){ var type = typeOf(this[i]); if (type == 'null') continue; array = array.concat((type == 'array' || type == 'collection' || type == 'arguments' || instanceOf(this[i], Array)) ? Array.flatten(this[i]) : this[i]); } return array; }, pick: function(){ for (var i = 0, l = this.length; i < l; i++){ if (this[i] != null) return this[i]; } return null; }, hexToRgb: function(array){ if (this.length != 3) return null; var rgb = this.map(function(value){ if (value.length == 1) value += value; return value.toInt(16); }); return (array) ? rgb : 'rgb(' + rgb + ')'; }, rgbToHex: function(array){ if (this.length < 3) return null; if (this.length == 4 && this[3] == 0 && !array) return 'transparent'; var hex = []; for (var i = 0; i < 3; i++){ var bit = (this[i] - 0).toString(16); hex.push((bit.length == 1) ? '0' + bit : bit); } return (array) ? hex : '#' + hex.join(''); } }); /* --- name: String description: Contains String Prototypes like camelCase, capitalize, test, and toInt. license: MIT-style license. requires: Type provides: String ... */ String.implement({ test: function(regex, params){ return ((typeOf(regex) == 'regexp') ? regex : new RegExp('' + regex, params)).test(this); }, contains: function(string, separator){ return (separator) ? (separator + this + separator).indexOf(separator + string + separator) > -1 : String(this).indexOf(string) > -1; }, trim: function(){ return String(this).replace(/^\s+|\s+$/g, ''); }, clean: function(){ return String(this).replace(/\s+/g, ' ').trim(); }, camelCase: function(){ return String(this).replace(/-\D/g, function(match){ return match.charAt(1).toUpperCase(); }); }, hyphenate: function(){ return String(this).replace(/[A-Z]/g, function(match){ return ('-' + match.charAt(0).toLowerCase()); }); }, capitalize: function(){ return String(this).replace(/\b[a-z]/g, function(match){ return match.toUpperCase(); }); }, escapeRegExp: function(){ return String(this).replace(/([-.*+?^${}()|[\]\/\\])/g, '\\$1'); }, toInt: function(base){ return parseInt(this, base || 10); }, toFloat: function(){ return parseFloat(this); }, hexToRgb: function(array){ var hex = String(this).match(/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/); return (hex) ? hex.slice(1).hexToRgb(array) : null; }, rgbToHex: function(array){ var rgb = String(this).match(/\d{1,3}/g); return (rgb) ? rgb.rgbToHex(array) : null; }, substitute: function(object, regexp){ return String(this).replace(regexp || (/\\?\{([^{}]+)\}/g), function(match, name){ if (match.charAt(0) == '\\') return match.slice(1); return (object[name] != null) ? object[name] : ''; }); } }); /* --- name: Number description: Contains Number Prototypes like limit, round, times, and ceil. license: MIT-style license. requires: Type provides: Number ... */ Number.implement({ limit: function(min, max){ return Math.min(max, Math.max(min, this)); }, round: function(precision){ precision = Math.pow(10, precision || 0).toFixed(precision < 0 ? -precision : 0); return Math.round(this * precision) / precision; }, times: function(fn, bind){ for (var i = 0; i < this; i++) fn.call(bind, i, this); }, toFloat: function(){ return parseFloat(this); }, toInt: function(base){ return parseInt(this, base || 10); } }); Number.alias('each', 'times'); (function(math){ var methods = {}; math.each(function(name){ if (!Number[name]) methods[name] = function(){ return Math[name].apply(null, [this].concat(Array.from(arguments))); }; }); Number.implement(methods); })(['abs', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'exp', 'floor', 'log', 'max', 'min', 'pow', 'sin', 'sqrt', 'tan']); /* --- name: Function description: Contains Function Prototypes like create, bind, pass, and delay. license: MIT-style license. requires: Type provides: Function ... */ Function.extend({ attempt: function(){ for (var i = 0, l = arguments.length; i < l; i++){ try { return arguments[i](); } catch (e){} } return null; } }); Function.implement({ attempt: function(args, bind){ try { return this.apply(bind, Array.from(args)); } catch (e){} return null; }, /*<!ES5-bind>*/ bind: function(that){ var self = this, args = arguments.length > 1 ? Array.slice(arguments, 1) : null, F = function(){}; var bound = function(){ var context = that, length = arguments.length; if (this instanceof bound){ F.prototype = self.prototype; context = new F; } var result = (!args && !length) ? self.call(context) : self.apply(context, args && length ? args.concat(Array.slice(arguments)) : args || arguments); return context == that ? result : context; }; return bound; }, /*</!ES5-bind>*/ pass: function(args, bind){ var self = this; if (args != null) args = Array.from(args); return function(){ return self.apply(bind, args || arguments); }; }, delay: function(delay, bind, args){ return setTimeout(this.pass((args == null ? [] : args), bind), delay); }, periodical: function(periodical, bind, args){ return setInterval(this.pass((args == null ? [] : args), bind), periodical); } }); /* --- name: Object description: Object generic methods license: MIT-style license. requires: Type provides: [Object, Hash] ... */ (function(){ var hasOwnProperty = Object.prototype.hasOwnProperty; Object.extend({ subset: function(object, keys){ var results = {}; for (var i = 0, l = keys.length; i < l; i++){ var k = keys[i]; if (k in object) results[k] = object[k]; } return results; }, map: function(object, fn, bind){ var results = {}; for (var key in object){ if (hasOwnProperty.call(object, key)) results[key] = fn.call(bind, object[key], key, object); } return results; }, filter: function(object, fn, bind){ var results = {}; for (var key in object){ var value = object[key]; if (hasOwnProperty.call(object, key) && fn.call(bind, value, key, object)) results[key] = value; } return results; }, every: function(object, fn, bind){ for (var key in object){ if (hasOwnProperty.call(object, key) && !fn.call(bind, object[key], key)) return false; } return true; }, some: function(object, fn, bind){ for (var key in object){ if (hasOwnProperty.call(object, key) && fn.call(bind, object[key], key)) return true; } return false; }, keys: function(object){ var keys = []; for (var key in object){ if (hasOwnProperty.call(object, key)) keys.push(key); } return keys; }, values: function(object){ var values = []; for (var key in object){ if (hasOwnProperty.call(object, key)) values.push(object[key]); } return values; }, getLength: function(object){ return Object.keys(object).length; }, keyOf: function(object, value){ for (var key in object){ if (hasOwnProperty.call(object, key) && object[key] === value) return key; } return null; }, contains: function(object, value){ return Object.keyOf(object, value) != null; }, toQueryString: function(object, base){ var queryString = []; Object.each(object, function(value, key){ if (base) key = base + '[' + key + ']'; var result; switch (typeOf(value)){ case 'object': result = Object.toQueryString(value, key); break; case 'array': var qs = {}; value.each(function(val, i){ qs[i] = val; }); result = Object.toQueryString(qs, key); break; default: result = key + '=' + encodeURIComponent(value); } if (value != null) queryString.push(result); }); return queryString.join('&'); } }); })(); /* --- name: Browser description: The Browser Object. Contains Browser initialization, Window and Document, and the Browser Hash. license: MIT-style license. requires: [Array, Function, Number, String] provides: [Browser, Window, Document] ... */ (function(){ var document = this.document; var window = document.window = this; var ua = navigator.userAgent.toLowerCase(), platform = navigator.platform.toLowerCase(), UA = ua.match(/(opera|ie|firefox|chrome|version)[\s\/:]([\w\d\.]+)?.*?(safari|version[\s\/:]([\w\d\.]+)|$)/) || [null, 'unknown', 0], mode = UA[1] == 'ie' && document.documentMode; var Browser = this.Browser = { extend: Function.prototype.extend, name: (UA[1] == 'version') ? UA[3] : UA[1], version: mode || parseFloat((UA[1] == 'opera' && UA[4]) ? UA[4] : UA[2]), Platform: { name: ua.match(/ip(?:ad|od|hone)/) ? 'ios' : (ua.match(/(?:webos|android)/) || platform.match(/mac|win|linux/) || ['other'])[0] }, Features: { xpath: !!(document.evaluate), air: !!(window.runtime), query: !!(document.querySelector), json: !!(window.JSON) }, Plugins: {} }; Browser[Browser.name] = true; Browser[Browser.name + parseInt(Browser.version, 10)] = true; Browser.Platform[Browser.Platform.name] = true; // Request Browser.Request = (function(){ var XMLHTTP = function(){ return new XMLHttpRequest(); }; var MSXML2 = function(){ return new ActiveXObject('MSXML2.XMLHTTP'); }; var MSXML = function(){ return new ActiveXObject('Microsoft.XMLHTTP');<|fim▁hole|> }; return Function.attempt(function(){ XMLHTTP(); return XMLHTTP; }, function(){ MSXML2(); return MSXML2; }, function(){ MSXML(); return MSXML; }); })(); Browser.Features.xhr = !!(Browser.Request); // Flash detection var version = (Function.attempt(function(){ return navigator.plugins['Shockwave Flash'].description; }, function(){ return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version'); }) || '0 r0').match(/\d+/g); Browser.Plugins.Flash = { version: Number(version[0] || '0.' + version[1]) || 0, build: Number(version[2]) || 0 }; // String scripts Browser.exec = function(text){ if (!text) return text; if (window.execScript){ window.execScript(text); } else { var script = document.createElement('script'); script.setAttribute('type', 'text/javascript'); script.text = text; document.head.appendChild(script); document.head.removeChild(script); } return text; }; String.implement('stripScripts', function(exec){ var scripts = ''; var text = this.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi, function(all, code){ scripts += code + '\n'; return ''; }); if (exec === true) Browser.exec(scripts); else if (typeOf(exec) == 'function') exec(scripts, text); return text; }); // Window, Document Browser.extend({ Document: this.Document, Window: this.Window, Element: this.Element, Event: this.Event }); this.Window = this.$constructor = new Type('Window', function(){}); this.$family = Function.from('window').hide(); Window.mirror(function(name, method){ window[name] = method; }); this.Document = document.$constructor = new Type('Document', function(){}); document.$family = Function.from('document').hide(); Document.mirror(function(name, method){ document[name] = method; }); document.html = document.documentElement; if (!document.head) document.head = document.getElementsByTagName('head')[0]; if (document.execCommand) try { document.execCommand("BackgroundImageCache", false, true); } catch (e){} /*<ltIE9>*/ if (this.attachEvent && !this.addEventListener){ var unloadEvent = function(){ this.detachEvent('onunload', unloadEvent); document.head = document.html = document.window = null; }; this.attachEvent('onunload', unloadEvent); } // IE fails on collections and <select>.options (refers to <select>) var arrayFrom = Array.from; try { arrayFrom(document.html.childNodes); } catch(e){ Array.from = function(item){ if (typeof item != 'string' && Type.isEnumerable(item) && typeOf(item) != 'array'){ var i = item.length, array = new Array(i); while (i--) array[i] = item[i]; return array; } return arrayFrom(item); }; var prototype = Array.prototype, slice = prototype.slice; ['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift', 'concat', 'join', 'slice'].each(function(name){ var method = prototype[name]; Array[name] = function(item){ return method.apply(Array.from(item), slice.call(arguments, 1)); }; }); } /*</ltIE9>*/ })(); /* --- name: Event description: Contains the Event Type, to make the event object cross-browser. license: MIT-style license. requires: [Window, Document, Array, Function, String, Object] provides: Event ... */ (function() { var _keys = {}; var DOMEvent = this.DOMEvent = new Type('DOMEvent', function(event, win){ if (!win) win = window; event = event || win.event; if (event.$extended) return event; this.event = event; this.$extended = true; this.shift = event.shiftKey; this.control = event.ctrlKey; this.alt = event.altKey; this.meta = event.metaKey; var type = this.type = event.type; var target = event.target || event.srcElement; while (target && target.nodeType == 3) target = target.parentNode; this.target = document.id(target); if (type.indexOf('key') == 0){ var code = this.code = (event.which || event.keyCode); this.key = _keys[code]; if (type == 'keydown'){ if (code > 111 && code < 124) this.key = 'f' + (code - 111); else if (code > 95 && code < 106) this.key = code - 96; } if (this.key == null) this.key = String.fromCharCode(code).toLowerCase(); } else if (type == 'click' || type == 'dblclick' || type == 'contextmenu' || type == 'DOMMouseScroll' || type.indexOf('mouse') == 0){ var doc = win.document; doc = (!doc.compatMode || doc.compatMode == 'CSS1Compat') ? doc.html : doc.body; this.page = { x: (event.pageX != null) ? event.pageX : event.clientX + doc.scrollLeft, y: (event.pageY != null) ? event.pageY : event.clientY + doc.scrollTop }; this.client = { x: (event.pageX != null) ? event.pageX - win.pageXOffset : event.clientX, y: (event.pageY != null) ? event.pageY - win.pageYOffset : event.clientY }; if (type == 'DOMMouseScroll' || type == 'mousewheel') this.wheel = (event.wheelDelta) ? event.wheelDelta / 120 : -(event.detail || 0) / 3; this.rightClick = (event.which == 3 || event.button == 2); if (type == 'mouseover' || type == 'mouseout'){ var related = event.relatedTarget || event[(type == 'mouseover' ? 'from' : 'to') + 'Element']; while (related && related.nodeType == 3) related = related.parentNode; this.relatedTarget = document.id(related); } } else if (type.indexOf('touch') == 0 || type.indexOf('gesture') == 0){ this.rotation = event.rotation; this.scale = event.scale; this.targetTouches = event.targetTouches; this.changedTouches = event.changedTouches; var touches = this.touches = event.touches; if (touches && touches[0]){ var touch = touches[0]; this.page = {x: touch.pageX, y: touch.pageY}; this.client = {x: touch.clientX, y: touch.clientY}; } } if (!this.client) this.client = {}; if (!this.page) this.page = {}; }); DOMEvent.implement({ stop: function(){ return this.preventDefault().stopPropagation(); }, stopPropagation: function(){ if (this.event.stopPropagation) this.event.stopPropagation(); else this.event.cancelBubble = true; return this; }, preventDefault: function(){ if (this.event.preventDefault) this.event.preventDefault(); else this.event.returnValue = false; return this; } }); DOMEvent.defineKey = function(code, key){ _keys[code] = key; return this; }; DOMEvent.defineKeys = DOMEvent.defineKey.overloadSetter(true); DOMEvent.defineKeys({ '38': 'up', '40': 'down', '37': 'left', '39': 'right', '27': 'esc', '32': 'space', '8': 'backspace', '9': 'tab', '46': 'delete', '13': 'enter' }); })(); /* --- name: Class description: Contains the Class Function for easily creating, extending, and implementing reusable Classes. license: MIT-style license. requires: [Array, String, Function, Number] provides: Class ... */ (function(){ var Class = this.Class = new Type('Class', function(params){ if (instanceOf(params, Function)) params = {initialize: params}; var newClass = function(){ reset(this); if (newClass.$prototyping) return this; this.$caller = null; var value = (this.initialize) ? this.initialize.apply(this, arguments) : this; this.$caller = this.caller = null; return value; }.extend(this).implement(params); newClass.$constructor = Class; newClass.prototype.$constructor = newClass; newClass.prototype.parent = parent; return newClass; }); var parent = function(){ if (!this.$caller) throw new Error('The method "parent" cannot be called.'); var name = this.$caller.$name, parent = this.$caller.$owner.parent, previous = (parent) ? parent.prototype[name] : null; if (!previous) throw new Error('The method "' + name + '" has no parent.'); return previous.apply(this, arguments); }; var reset = function(object){ for (var key in object){ var value = object[key]; switch (typeOf(value)){ case 'object': var F = function(){}; F.prototype = value; object[key] = reset(new F); break; case 'array': object[key] = value.clone(); break; } } return object; }; var wrap = function(self, key, method){ if (method.$origin) method = method.$origin; var wrapper = function(){ if (method.$protected && this.$caller == null) throw new Error('The method "' + key + '" cannot be called.'); var caller = this.caller, current = this.$caller; this.caller = current; this.$caller = wrapper; var result = method.apply(this, arguments); this.$caller = current; this.caller = caller; return result; }.extend({$owner: self, $origin: method, $name: key}); return wrapper; }; var implement = function(key, value, retain){ if (Class.Mutators.hasOwnProperty(key)){ value = Class.Mutators[key].call(this, value); if (value == null) return this; } if (typeOf(value) == 'function'){ if (value.$hidden) return this; this.prototype[key] = (retain) ? value : wrap(this, key, value); } else { Object.merge(this.prototype, key, value); } return this; }; var getInstance = function(klass){ klass.$prototyping = true; var proto = new klass; delete klass.$prototyping; return proto; }; Class.implement('implement', implement.overloadSetter()); Class.Mutators = { Extends: function(parent){ this.parent = parent; this.prototype = getInstance(parent); }, Implements: function(items){ Array.from(items).each(function(item){ var instance = new item; for (var key in instance) implement.call(this, key, instance[key], true); }, this); } }; })(); /* --- name: Class.Extras description: Contains Utility Classes that can be implemented into your own Classes to ease the execution of many common tasks. license: MIT-style license. requires: Class provides: [Class.Extras, Chain, Events, Options] ... */ (function(){ this.Chain = new Class({ $chain: [], chain: function(){ this.$chain.append(Array.flatten(arguments)); return this; }, callChain: function(){ return (this.$chain.length) ? this.$chain.shift().apply(this, arguments) : false; }, clearChain: function(){ this.$chain.empty(); return this; } }); var removeOn = function(string){ return string.replace(/^on([A-Z])/, function(full, first){ return first.toLowerCase(); }); }; this.Events = new Class({ $events: {}, addEvent: function(type, fn, internal){ type = removeOn(type); this.$events[type] = (this.$events[type] || []).include(fn); if (internal) fn.internal = true; return this; }, addEvents: function(events){ for (var type in events) this.addEvent(type, events[type]); return this; }, fireEvent: function(type, args, delay){ type = removeOn(type); var events = this.$events[type]; if (!events) return this; args = Array.from(args); events.each(function(fn){ if (delay) fn.delay(delay, this, args); else fn.apply(this, args); }, this); return this; }, removeEvent: function(type, fn){ type = removeOn(type); var events = this.$events[type]; if (events && !fn.internal){ var index = events.indexOf(fn); if (index != -1) delete events[index]; } return this; }, removeEvents: function(events){ var type; if (typeOf(events) == 'object'){ for (type in events) this.removeEvent(type, events[type]); return this; } if (events) events = removeOn(events); for (type in this.$events){ if (events && events != type) continue; var fns = this.$events[type]; for (var i = fns.length; i--;) if (i in fns){ this.removeEvent(type, fns[i]); } } return this; } }); this.Options = new Class({ setOptions: function(){ var options = this.options = Object.merge.apply(null, [{}, this.options].append(arguments)); if (this.addEvent) for (var option in options){ if (typeOf(options[option]) != 'function' || !(/^on[A-Z]/).test(option)) continue; this.addEvent(option, options[option]); delete options[option]; } return this; } }); })(); /* --- name: Slick.Parser description: Standalone CSS3 Selector parser provides: Slick.Parser ... */ ;(function(){ var parsed, separatorIndex, combinatorIndex, reversed, cache = {}, reverseCache = {}, reUnescape = /\\/g; var parse = function(expression, isReversed){ if (expression == null) return null; if (expression.Slick === true) return expression; expression = ('' + expression).replace(/^\s+|\s+$/g, ''); reversed = !!isReversed; var currentCache = (reversed) ? reverseCache : cache; if (currentCache[expression]) return currentCache[expression]; parsed = { Slick: true, expressions: [], raw: expression, reverse: function(){ return parse(this.raw, true); } }; separatorIndex = -1; while (expression != (expression = expression.replace(regexp, parser))); parsed.length = parsed.expressions.length; return currentCache[parsed.raw] = (reversed) ? reverse(parsed) : parsed; }; var reverseCombinator = function(combinator){ if (combinator === '!') return ' '; else if (combinator === ' ') return '!'; else if ((/^!/).test(combinator)) return combinator.replace(/^!/, ''); else return '!' + combinator; }; var reverse = function(expression){ var expressions = expression.expressions; for (var i = 0; i < expressions.length; i++){ var exp = expressions[i]; var last = {parts: [], tag: '*', combinator: reverseCombinator(exp[0].combinator)}; for (var j = 0; j < exp.length; j++){ var cexp = exp[j]; if (!cexp.reverseCombinator) cexp.reverseCombinator = ' '; cexp.combinator = cexp.reverseCombinator; delete cexp.reverseCombinator; } exp.reverse().push(last); } return expression; }; var escapeRegExp = function(string){// Credit: XRegExp 0.6.1 (c) 2007-2008 Steven Levithan <http://stevenlevithan.com/regex/xregexp/> MIT License return string.replace(/[-[\]{}()*+?.\\^$|,#\s]/g, function(match){ return '\\' + match; }); }; var regexp = new RegExp( /* #!/usr/bin/env ruby puts "\t\t" + DATA.read.gsub(/\(\?x\)|\s+#.*$|\s+|\\$|\\n/,'') __END__ "(?x)^(?:\ \\s* ( , ) \\s* # Separator \n\ | \\s* ( <combinator>+ ) \\s* # Combinator \n\ | ( \\s+ ) # CombinatorChildren \n\ | ( <unicode>+ | \\* ) # Tag \n\ | \\# ( <unicode>+ ) # ID \n\ | \\. ( <unicode>+ ) # ClassName \n\ | # Attribute \n\ \\[ \ \\s* (<unicode1>+) (?: \ \\s* ([*^$!~|]?=) (?: \ \\s* (?:\ ([\"']?)(.*?)\\9 \ )\ ) \ )? \\s* \ \\](?!\\]) \n\ | :+ ( <unicode>+ )(?:\ \\( (?:\ (?:([\"'])([^\\12]*)\\12)|((?:\\([^)]+\\)|[^()]*)+)\ ) \\)\ )?\ )" */ "^(?:\\s*(,)\\s*|\\s*(<combinator>+)\\s*|(\\s+)|(<unicode>+|\\*)|\\#(<unicode>+)|\\.(<unicode>+)|\\[\\s*(<unicode1>+)(?:\\s*([*^$!~|]?=)(?:\\s*(?:([\"']?)(.*?)\\9)))?\\s*\\](?!\\])|(:+)(<unicode>+)(?:\\((?:(?:([\"'])([^\\13]*)\\13)|((?:\\([^)]+\\)|[^()]*)+))\\))?)" .replace(/<combinator>/, '[' + escapeRegExp(">+~`!@$%^&={}\\;</") + ']') .replace(/<unicode>/g, '(?:[\\w\\u00a1-\\uFFFF-]|\\\\[^\\s0-9a-f])') .replace(/<unicode1>/g, '(?:[:\\w\\u00a1-\\uFFFF-]|\\\\[^\\s0-9a-f])') ); function parser( rawMatch, separator, combinator, combinatorChildren, tagName, id, className, attributeKey, attributeOperator, attributeQuote, attributeValue, pseudoMarker, pseudoClass, pseudoQuote, pseudoClassQuotedValue, pseudoClassValue ){ if (separator || separatorIndex === -1){ parsed.expressions[++separatorIndex] = []; combinatorIndex = -1; if (separator) return ''; } if (combinator || combinatorChildren || combinatorIndex === -1){ combinator = combinator || ' '; var currentSeparator = parsed.expressions[separatorIndex]; if (reversed && currentSeparator[combinatorIndex]) currentSeparator[combinatorIndex].reverseCombinator = reverseCombinator(combinator); currentSeparator[++combinatorIndex] = {combinator: combinator, tag: '*'}; } var currentParsed = parsed.expressions[separatorIndex][combinatorIndex]; if (tagName){ currentParsed.tag = tagName.replace(reUnescape, ''); } else if (id){ currentParsed.id = id.replace(reUnescape, ''); } else if (className){ className = className.replace(reUnescape, ''); if (!currentParsed.classList) currentParsed.classList = []; if (!currentParsed.classes) currentParsed.classes = []; currentParsed.classList.push(className); currentParsed.classes.push({ value: className, regexp: new RegExp('(^|\\s)' + escapeRegExp(className) + '(\\s|$)') }); } else if (pseudoClass){ pseudoClassValue = pseudoClassValue || pseudoClassQuotedValue; pseudoClassValue = pseudoClassValue ? pseudoClassValue.replace(reUnescape, '') : null; if (!currentParsed.pseudos) currentParsed.pseudos = []; currentParsed.pseudos.push({ key: pseudoClass.replace(reUnescape, ''), value: pseudoClassValue, type: pseudoMarker.length == 1 ? 'class' : 'element' }); } else if (attributeKey){ attributeKey = attributeKey.replace(reUnescape, ''); attributeValue = (attributeValue || '').replace(reUnescape, ''); var test, regexp; switch (attributeOperator){ case '^=' : regexp = new RegExp( '^'+ escapeRegExp(attributeValue) ); break; case '$=' : regexp = new RegExp( escapeRegExp(attributeValue) +'$' ); break; case '~=' : regexp = new RegExp( '(^|\\s)'+ escapeRegExp(attributeValue) +'(\\s|$)' ); break; case '|=' : regexp = new RegExp( '^'+ escapeRegExp(attributeValue) +'(-|$)' ); break; case '=' : test = function(value){ return attributeValue == value; }; break; case '*=' : test = function(value){ return value && value.indexOf(attributeValue) > -1; }; break; case '!=' : test = function(value){ return attributeValue != value; }; break; default : test = function(value){ return !!value; }; } if (attributeValue == '' && (/^[*$^]=$/).test(attributeOperator)) test = function(){ return false; }; if (!test) test = function(value){ return value && regexp.test(value); }; if (!currentParsed.attributes) currentParsed.attributes = []; currentParsed.attributes.push({ key: attributeKey, operator: attributeOperator, value: attributeValue, test: test }); } return ''; }; // Slick NS var Slick = (this.Slick || {}); Slick.parse = function(expression){ return parse(expression); }; Slick.escapeRegExp = escapeRegExp; if (!this.Slick) this.Slick = Slick; }).apply(/*<CommonJS>*/(typeof exports != 'undefined') ? exports : /*</CommonJS>*/this); /* --- name: Slick.Finder description: The new, superfast css selector engine. provides: Slick.Finder requires: Slick.Parser ... */ ;(function(){ var local = {}, featuresCache = {}, toString = Object.prototype.toString; // Feature / Bug detection local.isNativeCode = function(fn){ return (/\{\s*\[native code\]\s*\}/).test('' + fn); }; local.isXML = function(document){ return (!!document.xmlVersion) || (!!document.xml) || (toString.call(document) == '[object XMLDocument]') || (document.nodeType == 9 && document.documentElement.nodeName != 'HTML'); }; local.setDocument = function(document){ // convert elements / window arguments to document. if document cannot be extrapolated, the function returns. var nodeType = document.nodeType; if (nodeType == 9); // document else if (nodeType) document = document.ownerDocument; // node else if (document.navigator) document = document.document; // window else return; // check if it's the old document if (this.document === document) return; this.document = document; // check if we have done feature detection on this document before var root = document.documentElement, rootUid = this.getUIDXML(root), features = featuresCache[rootUid], feature; if (features){ for (feature in features){ this[feature] = features[feature]; } return; } features = featuresCache[rootUid] = {}; features.root = root; features.isXMLDocument = this.isXML(document); features.brokenStarGEBTN = features.starSelectsClosedQSA = features.idGetsName = features.brokenMixedCaseQSA = features.brokenGEBCN = features.brokenCheckedQSA = features.brokenEmptyAttributeQSA = features.isHTMLDocument = features.nativeMatchesSelector = false; var starSelectsClosed, starSelectsComments, brokenSecondClassNameGEBCN, cachedGetElementsByClassName, brokenFormAttributeGetter; var selected, id = 'slick_uniqueid'; var testNode = document.createElement('div'); var testRoot = document.body || document.getElementsByTagName('body')[0] || root; testRoot.appendChild(testNode); // on non-HTML documents innerHTML and getElementsById doesnt work properly try { testNode.innerHTML = '<a id="'+id+'"></a>'; features.isHTMLDocument = !!document.getElementById(id); } catch(e){}; if (features.isHTMLDocument){ testNode.style.display = 'none'; // IE returns comment nodes for getElementsByTagName('*') for some documents testNode.appendChild(document.createComment('')); starSelectsComments = (testNode.getElementsByTagName('*').length > 1); // IE returns closed nodes (EG:"</foo>") for getElementsByTagName('*') for some documents try { testNode.innerHTML = 'foo</foo>'; selected = testNode.getElementsByTagName('*'); starSelectsClosed = (selected && !!selected.length && selected[0].nodeName.charAt(0) == '/'); } catch(e){}; features.brokenStarGEBTN = starSelectsComments || starSelectsClosed; // IE returns elements with the name instead of just id for getElementsById for some documents try { testNode.innerHTML = '<a name="'+ id +'"></a><b id="'+ id +'"></b>'; features.idGetsName = document.getElementById(id) === testNode.firstChild; } catch(e){}; if (testNode.getElementsByClassName){ // Safari 3.2 getElementsByClassName caches results try { testNode.innerHTML = '<a class="f"></a><a class="b"></a>'; testNode.getElementsByClassName('b').length; testNode.firstChild.className = 'b'; cachedGetElementsByClassName = (testNode.getElementsByClassName('b').length != 2); } catch(e){}; // Opera 9.6 getElementsByClassName doesnt detects the class if its not the first one try { testNode.innerHTML = '<a class="a"></a><a class="f b a"></a>'; brokenSecondClassNameGEBCN = (testNode.getElementsByClassName('a').length != 2); } catch(e){}; features.brokenGEBCN = cachedGetElementsByClassName || brokenSecondClassNameGEBCN; } if (testNode.querySelectorAll){ // IE 8 returns closed nodes (EG:"</foo>") for querySelectorAll('*') for some documents try { testNode.innerHTML = 'foo</foo>'; selected = testNode.querySelectorAll('*'); features.starSelectsClosedQSA = (selected && !!selected.length && selected[0].nodeName.charAt(0) == '/'); } catch(e){}; // Safari 3.2 querySelectorAll doesnt work with mixedcase on quirksmode try { testNode.innerHTML = '<a class="MiX"></a>'; features.brokenMixedCaseQSA = !testNode.querySelectorAll('.MiX').length; } catch(e){}; // Webkit and Opera dont return selected options on querySelectorAll try { testNode.innerHTML = '<select><option selected="selected">a</option></select>'; features.brokenCheckedQSA = (testNode.querySelectorAll(':checked').length == 0); } catch(e){}; // IE returns incorrect results for attr[*^$]="" selectors on querySelectorAll try { testNode.innerHTML = '<a class=""></a>'; features.brokenEmptyAttributeQSA = (testNode.querySelectorAll('[class*=""]').length != 0); } catch(e){}; } // IE6-7, if a form has an input of id x, form.getAttribute(x) returns a reference to the input try { testNode.innerHTML = '<form action="s"><input id="action"/></form>'; brokenFormAttributeGetter = (testNode.firstChild.getAttribute('action') != 's'); } catch(e){}; // native matchesSelector function features.nativeMatchesSelector = root.matchesSelector || /*root.msMatchesSelector ||*/ root.mozMatchesSelector || root.webkitMatchesSelector; if (features.nativeMatchesSelector) try { // if matchesSelector trows errors on incorrect sintaxes we can use it features.nativeMatchesSelector.call(root, ':slick'); features.nativeMatchesSelector = null; } catch(e){}; } try { root.slick_expando = 1; delete root.slick_expando; features.getUID = this.getUIDHTML; } catch(e) { features.getUID = this.getUIDXML; } testRoot.removeChild(testNode); testNode = selected = testRoot = null; // getAttribute features.getAttribute = (features.isHTMLDocument && brokenFormAttributeGetter) ? function(node, name){ var method = this.attributeGetters[name]; if (method) return method.call(node); var attributeNode = node.getAttributeNode(name); return (attributeNode) ? attributeNode.nodeValue : null; } : function(node, name){ var method = this.attributeGetters[name]; return (method) ? method.call(node) : node.getAttribute(name); }; // hasAttribute features.hasAttribute = (root && this.isNativeCode(root.hasAttribute)) ? function(node, attribute) { return node.hasAttribute(attribute); } : function(node, attribute) { node = node.getAttributeNode(attribute); return !!(node && (node.specified || node.nodeValue)); }; // contains // FIXME: Add specs: local.contains should be different for xml and html documents? var nativeRootContains = root && this.isNativeCode(root.contains), nativeDocumentContains = document && this.isNativeCode(document.contains); features.contains = (nativeRootContains && nativeDocumentContains) ? function(context, node){ return context.contains(node); } : (nativeRootContains && !nativeDocumentContains) ? function(context, node){ // IE8 does not have .contains on document. return context === node || ((context === document) ? document.documentElement : context).contains(node); } : (root && root.compareDocumentPosition) ? function(context, node){ return context === node || !!(context.compareDocumentPosition(node) & 16); } : function(context, node){ if (node) do { if (node === context) return true; } while ((node = node.parentNode)); return false; }; // document order sorting // credits to Sizzle (http://sizzlejs.com/) features.documentSorter = (root.compareDocumentPosition) ? function(a, b){ if (!a.compareDocumentPosition || !b.compareDocumentPosition) return 0; return a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1; } : ('sourceIndex' in root) ? function(a, b){ if (!a.sourceIndex || !b.sourceIndex) return 0; return a.sourceIndex - b.sourceIndex; } : (document.createRange) ? function(a, b){ if (!a.ownerDocument || !b.ownerDocument) return 0; var aRange = a.ownerDocument.createRange(), bRange = b.ownerDocument.createRange(); aRange.setStart(a, 0); aRange.setEnd(a, 0); bRange.setStart(b, 0); bRange.setEnd(b, 0); return aRange.compareBoundaryPoints(Range.START_TO_END, bRange); } : null ; root = null; for (feature in features){ this[feature] = features[feature]; } }; // Main Method var reSimpleSelector = /^([#.]?)((?:[\w-]+|\*))$/, reEmptyAttribute = /\[.+[*$^]=(?:""|'')?\]/, qsaFailExpCache = {}; local.search = function(context, expression, append, first){ var found = this.found = (first) ? null : (append || []); if (!context) return found; else if (context.navigator) context = context.document; // Convert the node from a window to a document else if (!context.nodeType) return found; // setup var parsed, i, uniques = this.uniques = {}, hasOthers = !!(append && append.length), contextIsDocument = (context.nodeType == 9); if (this.document !== (contextIsDocument ? context : context.ownerDocument)) this.setDocument(context); // avoid duplicating items already in the append array if (hasOthers) for (i = found.length; i--;) uniques[this.getUID(found[i])] = true; // expression checks if (typeof expression == 'string'){ // expression is a string /*<simple-selectors-override>*/ var simpleSelector = expression.match(reSimpleSelector); simpleSelectors: if (simpleSelector) { var symbol = simpleSelector[1], name = simpleSelector[2], node, nodes; if (!symbol){ if (name == '*' && this.brokenStarGEBTN) break simpleSelectors; nodes = context.getElementsByTagName(name); if (first) return nodes[0] || null; for (i = 0; node = nodes[i++];){ if (!(hasOthers && uniques[this.getUID(node)])) found.push(node); } } else if (symbol == '#'){ if (!this.isHTMLDocument || !contextIsDocument) break simpleSelectors; node = context.getElementById(name); if (!node) return found; if (this.idGetsName && node.getAttributeNode('id').nodeValue != name) break simpleSelectors; if (first) return node || null; if (!(hasOthers && uniques[this.getUID(node)])) found.push(node); } else if (symbol == '.'){ if (!this.isHTMLDocument || ((!context.getElementsByClassName || this.brokenGEBCN) && context.querySelectorAll)) break simpleSelectors; if (context.getElementsByClassName && !this.brokenGEBCN){ nodes = context.getElementsByClassName(name); if (first) return nodes[0] || null; for (i = 0; node = nodes[i++];){ if (!(hasOthers && uniques[this.getUID(node)])) found.push(node); } } else { var matchClass = new RegExp('(^|\\s)'+ Slick.escapeRegExp(name) +'(\\s|$)'); nodes = context.getElementsByTagName('*'); for (i = 0; node = nodes[i++];){ className = node.className; if (!(className && matchClass.test(className))) continue; if (first) return node; if (!(hasOthers && uniques[this.getUID(node)])) found.push(node); } } } if (hasOthers) this.sort(found); return (first) ? null : found; } /*</simple-selectors-override>*/ /*<query-selector-override>*/ querySelector: if (context.querySelectorAll) { if (!this.isHTMLDocument || qsaFailExpCache[expression] //TODO: only skip when expression is actually mixed case || this.brokenMixedCaseQSA || (this.brokenCheckedQSA && expression.indexOf(':checked') > -1) || (this.brokenEmptyAttributeQSA && reEmptyAttribute.test(expression)) || (!contextIsDocument //Abort when !contextIsDocument and... // there are multiple expressions in the selector // since we currently only fix non-document rooted QSA for single expression selectors && expression.indexOf(',') > -1 ) || Slick.disableQSA ) break querySelector; var _expression = expression, _context = context; if (!contextIsDocument){ // non-document rooted QSA // credits to Andrew Dupont var currentId = _context.getAttribute('id'), slickid = 'slickid__'; _context.setAttribute('id', slickid); _expression = '#' + slickid + ' ' + _expression; context = _context.parentNode; } try { if (first) return context.querySelector(_expression) || null; else nodes = context.querySelectorAll(_expression); } catch(e) { qsaFailExpCache[expression] = 1; break querySelector; } finally { if (!contextIsDocument){ if (currentId) _context.setAttribute('id', currentId); else _context.removeAttribute('id'); context = _context; } } if (this.starSelectsClosedQSA) for (i = 0; node = nodes[i++];){ if (node.nodeName > '@' && !(hasOthers && uniques[this.getUID(node)])) found.push(node); } else for (i = 0; node = nodes[i++];){ if (!(hasOthers && uniques[this.getUID(node)])) found.push(node); } if (hasOthers) this.sort(found); return found; } /*</query-selector-override>*/ parsed = this.Slick.parse(expression); if (!parsed.length) return found; } else if (expression == null){ // there is no expression return found; } else if (expression.Slick){ // expression is a parsed Slick object parsed = expression; } else if (this.contains(context.documentElement || context, expression)){ // expression is a node (found) ? found.push(expression) : found = expression; return found; } else { // other junk return found; } /*<pseudo-selectors>*//*<nth-pseudo-selectors>*/ // cache elements for the nth selectors this.posNTH = {}; this.posNTHLast = {}; this.posNTHType = {}; this.posNTHTypeLast = {}; /*</nth-pseudo-selectors>*//*</pseudo-selectors>*/ // if append is null and there is only a single selector with one expression use pushArray, else use pushUID this.push = (!hasOthers && (first || (parsed.length == 1 && parsed.expressions[0].length == 1))) ? this.pushArray : this.pushUID; if (found == null) found = []; // default engine var j, m, n; var combinator, tag, id, classList, classes, attributes, pseudos; var currentItems, currentExpression, currentBit, lastBit, expressions = parsed.expressions; search: for (i = 0; (currentExpression = expressions[i]); i++) for (j = 0; (currentBit = currentExpression[j]); j++){ combinator = 'combinator:' + currentBit.combinator; if (!this[combinator]) continue search; tag = (this.isXMLDocument) ? currentBit.tag : currentBit.tag.toUpperCase(); id = currentBit.id; classList = currentBit.classList; classes = currentBit.classes; attributes = currentBit.attributes; pseudos = currentBit.pseudos; lastBit = (j === (currentExpression.length - 1)); this.bitUniques = {}; if (lastBit){ this.uniques = uniques; this.found = found; } else { this.uniques = {}; this.found = []; } if (j === 0){ this[combinator](context, tag, id, classes, attributes, pseudos, classList); if (first && lastBit && found.length) break search; } else { if (first && lastBit) for (m = 0, n = currentItems.length; m < n; m++){ this[combinator](currentItems[m], tag, id, classes, attributes, pseudos, classList); if (found.length) break search; } else for (m = 0, n = currentItems.length; m < n; m++) this[combinator](currentItems[m], tag, id, classes, attributes, pseudos, classList); } currentItems = this.found; } // should sort if there are nodes in append and if you pass multiple expressions. if (hasOthers || (parsed.expressions.length > 1)) this.sort(found); return (first) ? (found[0] || null) : found; }; // Utils local.uidx = 1; local.uidk = 'slick-uniqueid'; local.getUIDXML = function(node){ var uid = node.getAttribute(this.uidk); if (!uid){ uid = this.uidx++; node.setAttribute(this.uidk, uid); } return uid; }; local.getUIDHTML = function(node){ return node.uniqueNumber || (node.uniqueNumber = this.uidx++); }; // sort based on the setDocument documentSorter method. local.sort = function(results){ if (!this.documentSorter) return results; results.sort(this.documentSorter); return results; }; /*<pseudo-selectors>*//*<nth-pseudo-selectors>*/ local.cacheNTH = {}; local.matchNTH = /^([+-]?\d*)?([a-z]+)?([+-]\d+)?$/; local.parseNTHArgument = function(argument){ var parsed = argument.match(this.matchNTH); if (!parsed) return false; var special = parsed[2] || false; var a = parsed[1] || 1; if (a == '-') a = -1; var b = +parsed[3] || 0; parsed = (special == 'n') ? {a: a, b: b} : (special == 'odd') ? {a: 2, b: 1} : (special == 'even') ? {a: 2, b: 0} : {a: 0, b: a}; return (this.cacheNTH[argument] = parsed); }; local.createNTHPseudo = function(child, sibling, positions, ofType){ return function(node, argument){ var uid = this.getUID(node); if (!this[positions][uid]){ var parent = node.parentNode; if (!parent) return false; var el = parent[child], count = 1; if (ofType){ var nodeName = node.nodeName; do { if (el.nodeName != nodeName) continue; this[positions][this.getUID(el)] = count++; } while ((el = el[sibling])); } else { do { if (el.nodeType != 1) continue; this[positions][this.getUID(el)] = count++; } while ((el = el[sibling])); } } argument = argument || 'n'; var parsed = this.cacheNTH[argument] || this.parseNTHArgument(argument); if (!parsed) return false; var a = parsed.a, b = parsed.b, pos = this[positions][uid]; if (a == 0) return b == pos; if (a > 0){ if (pos < b) return false; } else { if (b < pos) return false; } return ((pos - b) % a) == 0; }; }; /*</nth-pseudo-selectors>*//*</pseudo-selectors>*/ local.pushArray = function(node, tag, id, classes, attributes, pseudos){ if (this.matchSelector(node, tag, id, classes, attributes, pseudos)) this.found.push(node); }; local.pushUID = function(node, tag, id, classes, attributes, pseudos){ var uid = this.getUID(node); if (!this.uniques[uid] && this.matchSelector(node, tag, id, classes, attributes, pseudos)){ this.uniques[uid] = true; this.found.push(node); } }; local.matchNode = function(node, selector){ if (this.isHTMLDocument && this.nativeMatchesSelector){ try { return this.nativeMatchesSelector.call(node, selector.replace(/\[([^=]+)=\s*([^'"\]]+?)\s*\]/g, '[$1="$2"]')); } catch(matchError) {} } var parsed = this.Slick.parse(selector); if (!parsed) return true; // simple (single) selectors var expressions = parsed.expressions, simpleExpCounter = 0, i; for (i = 0; (currentExpression = expressions[i]); i++){ if (currentExpression.length == 1){ var exp = currentExpression[0]; if (this.matchSelector(node, (this.isXMLDocument) ? exp.tag : exp.tag.toUpperCase(), exp.id, exp.classes, exp.attributes, exp.pseudos)) return true; simpleExpCounter++; } } if (simpleExpCounter == parsed.length) return false; var nodes = this.search(this.document, parsed), item; for (i = 0; item = nodes[i++];){ if (item === node) return true; } return false; }; local.matchPseudo = function(node, name, argument){ var pseudoName = 'pseudo:' + name; if (this[pseudoName]) return this[pseudoName](node, argument); var attribute = this.getAttribute(node, name); return (argument) ? argument == attribute : !!attribute; }; local.matchSelector = function(node, tag, id, classes, attributes, pseudos){ if (tag){ var nodeName = (this.isXMLDocument) ? node.nodeName : node.nodeName.toUpperCase(); if (tag == '*'){ if (nodeName < '@') return false; // Fix for comment nodes and closed nodes } else { if (nodeName != tag) return false; } } if (id && node.getAttribute('id') != id) return false; var i, part, cls; if (classes) for (i = classes.length; i--;){ cls = this.getAttribute(node, 'class'); if (!(cls && classes[i].regexp.test(cls))) return false; } if (attributes) for (i = attributes.length; i--;){ part = attributes[i]; if (part.operator ? !part.test(this.getAttribute(node, part.key)) : !this.hasAttribute(node, part.key)) return false; } if (pseudos) for (i = pseudos.length; i--;){ part = pseudos[i]; if (!this.matchPseudo(node, part.key, part.value)) return false; } return true; }; var combinators = { ' ': function(node, tag, id, classes, attributes, pseudos, classList){ // all child nodes, any level var i, item, children; if (this.isHTMLDocument){ getById: if (id){ item = this.document.getElementById(id); if ((!item && node.all) || (this.idGetsName && item && item.getAttributeNode('id').nodeValue != id)){ // all[id] returns all the elements with that name or id inside node // if theres just one it will return the element, else it will be a collection children = node.all[id]; if (!children) return; if (!children[0]) children = [children]; for (i = 0; item = children[i++];){ var idNode = item.getAttributeNode('id'); if (idNode && idNode.nodeValue == id){ this.push(item, tag, null, classes, attributes, pseudos); break; } } return; } if (!item){ // if the context is in the dom we return, else we will try GEBTN, breaking the getById label if (this.contains(this.root, node)) return; else break getById; } else if (this.document !== node && !this.contains(node, item)) return; this.push(item, tag, null, classes, attributes, pseudos); return; } getByClass: if (classes && node.getElementsByClassName && !this.brokenGEBCN){ children = node.getElementsByClassName(classList.join(' ')); if (!(children && children.length)) break getByClass; for (i = 0; item = children[i++];) this.push(item, tag, id, null, attributes, pseudos); return; } } getByTag: { children = node.getElementsByTagName(tag); if (!(children && children.length)) break getByTag; if (!this.brokenStarGEBTN) tag = null; for (i = 0; item = children[i++];) this.push(item, tag, id, classes, attributes, pseudos); } }, '>': function(node, tag, id, classes, attributes, pseudos){ // direct children if ((node = node.firstChild)) do { if (node.nodeType == 1) this.push(node, tag, id, classes, attributes, pseudos); } while ((node = node.nextSibling)); }, '+': function(node, tag, id, classes, attributes, pseudos){ // next sibling while ((node = node.nextSibling)) if (node.nodeType == 1){ this.push(node, tag, id, classes, attributes, pseudos); break; } }, '^': function(node, tag, id, classes, attributes, pseudos){ // first child node = node.firstChild; if (node){ if (node.nodeType == 1) this.push(node, tag, id, classes, attributes, pseudos); else this['combinator:+'](node, tag, id, classes, attributes, pseudos); } }, '~': function(node, tag, id, classes, attributes, pseudos){ // next siblings while ((node = node.nextSibling)){ if (node.nodeType != 1) continue; var uid = this.getUID(node); if (this.bitUniques[uid]) break; this.bitUniques[uid] = true; this.push(node, tag, id, classes, attributes, pseudos); } }, '++': function(node, tag, id, classes, attributes, pseudos){ // next sibling and previous sibling this['combinator:+'](node, tag, id, classes, attributes, pseudos); this['combinator:!+'](node, tag, id, classes, attributes, pseudos); }, '~~': function(node, tag, id, classes, attributes, pseudos){ // next siblings and previous siblings this['combinator:~'](node, tag, id, classes, attributes, pseudos); this['combinator:!~'](node, tag, id, classes, attributes, pseudos); }, '!': function(node, tag, id, classes, attributes, pseudos){ // all parent nodes up to document while ((node = node.parentNode)) if (node !== this.document) this.push(node, tag, id, classes, attributes, pseudos); }, '!>': function(node, tag, id, classes, attributes, pseudos){ // direct parent (one level) node = node.parentNode; if (node !== this.document) this.push(node, tag, id, classes, attributes, pseudos); }, '!+': function(node, tag, id, classes, attributes, pseudos){ // previous sibling while ((node = node.previousSibling)) if (node.nodeType == 1){ this.push(node, tag, id, classes, attributes, pseudos); break; } }, '!^': function(node, tag, id, classes, attributes, pseudos){ // last child node = node.lastChild; if (node){ if (node.nodeType == 1) this.push(node, tag, id, classes, attributes, pseudos); else this['combinator:!+'](node, tag, id, classes, attributes, pseudos); } }, '!~': function(node, tag, id, classes, attributes, pseudos){ // previous siblings while ((node = node.previousSibling)){ if (node.nodeType != 1) continue; var uid = this.getUID(node); if (this.bitUniques[uid]) break; this.bitUniques[uid] = true; this.push(node, tag, id, classes, attributes, pseudos); } } }; for (var c in combinators) local['combinator:' + c] = combinators[c]; var pseudos = { /*<pseudo-selectors>*/ 'empty': function(node){ var child = node.firstChild; return !(child && child.nodeType == 1) && !(node.innerText || node.textContent || '').length; }, 'not': function(node, expression){ return !this.matchNode(node, expression); }, 'contains': function(node, text){ return (node.innerText || node.textContent || '').indexOf(text) > -1; }, 'first-child': function(node){ while ((node = node.previousSibling)) if (node.nodeType == 1) return false; return true; }, 'last-child': function(node){ while ((node = node.nextSibling)) if (node.nodeType == 1) return false; return true; }, 'only-child': function(node){ var prev = node; while ((prev = prev.previousSibling)) if (prev.nodeType == 1) return false; var next = node; while ((next = next.nextSibling)) if (next.nodeType == 1) return false; return true; }, /*<nth-pseudo-selectors>*/ 'nth-child': local.createNTHPseudo('firstChild', 'nextSibling', 'posNTH'), 'nth-last-child': local.createNTHPseudo('lastChild', 'previousSibling', 'posNTHLast'), 'nth-of-type': local.createNTHPseudo('firstChild', 'nextSibling', 'posNTHType', true), 'nth-last-of-type': local.createNTHPseudo('lastChild', 'previousSibling', 'posNTHTypeLast', true), 'index': function(node, index){ return this['pseudo:nth-child'](node, '' + (index + 1)); }, 'even': function(node){ return this['pseudo:nth-child'](node, '2n'); }, 'odd': function(node){ return this['pseudo:nth-child'](node, '2n+1'); }, /*</nth-pseudo-selectors>*/ /*<of-type-pseudo-selectors>*/ 'first-of-type': function(node){ var nodeName = node.nodeName; while ((node = node.previousSibling)) if (node.nodeName == nodeName) return false; return true; }, 'last-of-type': function(node){ var nodeName = node.nodeName; while ((node = node.nextSibling)) if (node.nodeName == nodeName) return false; return true; }, 'only-of-type': function(node){ var prev = node, nodeName = node.nodeName; while ((prev = prev.previousSibling)) if (prev.nodeName == nodeName) return false; var next = node; while ((next = next.nextSibling)) if (next.nodeName == nodeName) return false; return true; }, /*</of-type-pseudo-selectors>*/ // custom pseudos 'enabled': function(node){ return !node.disabled; }, 'disabled': function(node){ return node.disabled; }, 'checked': function(node){ return node.checked || node.selected; }, 'focus': function(node){ return this.isHTMLDocument && this.document.activeElement === node && (node.href || node.type || this.hasAttribute(node, 'tabindex')); }, 'root': function(node){ return (node === this.root); }, 'selected': function(node){ return node.selected; } /*</pseudo-selectors>*/ }; for (var p in pseudos) local['pseudo:' + p] = pseudos[p]; // attributes methods var attributeGetters = local.attributeGetters = { 'for': function(){ return ('htmlFor' in this) ? this.htmlFor : this.getAttribute('for'); }, 'href': function(){ return ('href' in this) ? this.getAttribute('href', 2) : this.getAttribute('href'); }, 'style': function(){ return (this.style) ? this.style.cssText : this.getAttribute('style'); }, 'tabindex': function(){ var attributeNode = this.getAttributeNode('tabindex'); return (attributeNode && attributeNode.specified) ? attributeNode.nodeValue : null; }, 'type': function(){ return this.getAttribute('type'); }, 'maxlength': function(){ var attributeNode = this.getAttributeNode('maxLength'); return (attributeNode && attributeNode.specified) ? attributeNode.nodeValue : null; } }; attributeGetters.MAXLENGTH = attributeGetters.maxLength = attributeGetters.maxlength; // Slick var Slick = local.Slick = (this.Slick || {}); Slick.version = '1.1.7'; // Slick finder Slick.search = function(context, expression, append){ return local.search(context, expression, append); }; Slick.find = function(context, expression){ return local.search(context, expression, null, true); }; // Slick containment checker Slick.contains = function(container, node){ local.setDocument(container); return local.contains(container, node); }; // Slick attribute getter Slick.getAttribute = function(node, name){ local.setDocument(node); return local.getAttribute(node, name); }; Slick.hasAttribute = function(node, name){ local.setDocument(node); return local.hasAttribute(node, name); }; // Slick matcher Slick.match = function(node, selector){ if (!(node && selector)) return false; if (!selector || selector === node) return true; local.setDocument(node); return local.matchNode(node, selector); }; // Slick attribute accessor Slick.defineAttributeGetter = function(name, fn){ local.attributeGetters[name] = fn; return this; }; Slick.lookupAttributeGetter = function(name){ return local.attributeGetters[name]; }; // Slick pseudo accessor Slick.definePseudo = function(name, fn){ local['pseudo:' + name] = function(node, argument){ return fn.call(node, argument); }; return this; }; Slick.lookupPseudo = function(name){ var pseudo = local['pseudo:' + name]; if (pseudo) return function(argument){ return pseudo.call(this, argument); }; return null; }; // Slick overrides accessor Slick.override = function(regexp, fn){ local.override(regexp, fn); return this; }; Slick.isXML = local.isXML; Slick.uidOf = function(node){ return local.getUIDHTML(node); }; if (!this.Slick) this.Slick = Slick; }).apply(/*<CommonJS>*/(typeof exports != 'undefined') ? exports : /*</CommonJS>*/this); /* --- name: Element description: One of the most important items in MooTools. Contains the dollar function, the dollars function, and an handful of cross-browser, time-saver methods to let you easily work with HTML Elements. license: MIT-style license. requires: [Window, Document, Array, String, Function, Object, Number, Slick.Parser, Slick.Finder] provides: [Element, Elements, $, $$, Iframe, Selectors] ... */ var Element = function(tag, props){ var konstructor = Element.Constructors[tag]; if (konstructor) return konstructor(props); if (typeof tag != 'string') return document.id(tag).set(props); if (!props) props = {}; if (!(/^[\w-]+$/).test(tag)){ var parsed = Slick.parse(tag).expressions[0][0]; tag = (parsed.tag == '*') ? 'div' : parsed.tag; if (parsed.id && props.id == null) props.id = parsed.id; var attributes = parsed.attributes; if (attributes) for (var attr, i = 0, l = attributes.length; i < l; i++){ attr = attributes[i]; if (props[attr.key] != null) continue; if (attr.value != null && attr.operator == '=') props[attr.key] = attr.value; else if (!attr.value && !attr.operator) props[attr.key] = true; } if (parsed.classList && props['class'] == null) props['class'] = parsed.classList.join(' '); } return document.newElement(tag, props); }; if (Browser.Element){ Element.prototype = Browser.Element.prototype; // IE8 and IE9 require the wrapping. Element.prototype._fireEvent = (function(fireEvent){ return function(type, event){ return fireEvent.call(this, type, event); }; })(Element.prototype.fireEvent); } new Type('Element', Element).mirror(function(name){ if (Array.prototype[name]) return; var obj = {}; obj[name] = function(){ var results = [], args = arguments, elements = true; for (var i = 0, l = this.length; i < l; i++){ var element = this[i], result = results[i] = element[name].apply(element, args); elements = (elements && typeOf(result) == 'element'); } return (elements) ? new Elements(results) : results; }; Elements.implement(obj); }); if (!Browser.Element){ Element.parent = Object; Element.Prototype = { '$constructor': Element, '$family': Function.from('element').hide() }; Element.mirror(function(name, method){ Element.Prototype[name] = method; }); } Element.Constructors = {}; var IFrame = new Type('IFrame', function(){ var params = Array.link(arguments, { properties: Type.isObject, iframe: function(obj){ return (obj != null); } }); var props = params.properties || {}, iframe; if (params.iframe) iframe = document.id(params.iframe); var onload = props.onload || function(){}; delete props.onload; props.id = props.name = [props.id, props.name, iframe ? (iframe.id || iframe.name) : 'IFrame_' + String.uniqueID()].pick(); iframe = new Element(iframe || 'iframe', props); var onLoad = function(){ onload.call(iframe.contentWindow); }; if (window.frames[props.id]) onLoad(); else iframe.addListener('load', onLoad); return iframe; }); var Elements = this.Elements = function(nodes){ if (nodes && nodes.length){ var uniques = {}, node; for (var i = 0; node = nodes[i++];){ var uid = Slick.uidOf(node); if (!uniques[uid]){ uniques[uid] = true; this.push(node); } } } }; Elements.prototype = {length: 0}; Elements.parent = Array; new Type('Elements', Elements).implement({ filter: function(filter, bind){ if (!filter) return this; return new Elements(Array.filter(this, (typeOf(filter) == 'string') ? function(item){ return item.match(filter); } : filter, bind)); }.protect(), push: function(){ var length = this.length; for (var i = 0, l = arguments.length; i < l; i++){ var item = document.id(arguments[i]); if (item) this[length++] = item; } return (this.length = length); }.protect(), unshift: function(){ var items = []; for (var i = 0, l = arguments.length; i < l; i++){ var item = document.id(arguments[i]); if (item) items.push(item); } return Array.prototype.unshift.apply(this, items); }.protect(), concat: function(){ var newElements = new Elements(this); for (var i = 0, l = arguments.length; i < l; i++){ var item = arguments[i]; if (Type.isEnumerable(item)) newElements.append(item); else newElements.push(item); } return newElements; }.protect(), append: function(collection){ for (var i = 0, l = collection.length; i < l; i++) this.push(collection[i]); return this; }.protect(), empty: function(){ while (this.length) delete this[--this.length]; return this; }.protect() }); (function(){ // FF, IE var splice = Array.prototype.splice, object = {'0': 0, '1': 1, length: 2}; splice.call(object, 1, 1); if (object[1] == 1) Elements.implement('splice', function(){ var length = this.length; var result = splice.apply(this, arguments); while (length >= this.length) delete this[length--]; return result; }.protect()); Array.forEachMethod(function(method, name){ Elements.implement(name, method); }); Array.mirror(Elements); /*<ltIE8>*/ var createElementAcceptsHTML; try { createElementAcceptsHTML = (document.createElement('<input name=x>').name == 'x'); } catch (e){} var escapeQuotes = function(html){ return ('' + html).replace(/&/g, '&amp;').replace(/"/g, '&quot;'); }; /*</ltIE8>*/ Document.implement({ newElement: function(tag, props){ if (props && props.checked != null) props.defaultChecked = props.checked; /*<ltIE8>*/// Fix for readonly name and type properties in IE < 8 if (createElementAcceptsHTML && props){ tag = '<' + tag; if (props.name) tag += ' name="' + escapeQuotes(props.name) + '"'; if (props.type) tag += ' type="' + escapeQuotes(props.type) + '"'; tag += '>'; delete props.name; delete props.type; } /*</ltIE8>*/ return this.id(this.createElement(tag)).set(props); } }); })(); (function(){ Slick.uidOf(window); Slick.uidOf(document); Document.implement({ newTextNode: function(text){ return this.createTextNode(text); }, getDocument: function(){ return this; }, getWindow: function(){ return this.window; }, id: (function(){ var types = { string: function(id, nocash, doc){ id = Slick.find(doc, '#' + id.replace(/(\W)/g, '\\$1')); return (id) ? types.element(id, nocash) : null; }, element: function(el, nocash){ Slick.uidOf(el); if (!nocash && !el.$family && !(/^(?:object|embed)$/i).test(el.tagName)){ var fireEvent = el.fireEvent; // wrapping needed in IE7, or else crash el._fireEvent = function(type, event){ return fireEvent(type, event); }; Object.append(el, Element.Prototype); } return el; }, object: function(obj, nocash, doc){ if (obj.toElement) return types.element(obj.toElement(doc), nocash); return null; } }; types.textnode = types.whitespace = types.window = types.document = function(zero){ return zero; }; return function(el, nocash, doc){ if (el && el.$family && el.uniqueNumber) return el; var type = typeOf(el); return (types[type]) ? types[type](el, nocash, doc || document) : null; }; })() }); if (window.$ == null) Window.implement('$', function(el, nc){ return document.id(el, nc, this.document); }); Window.implement({ getDocument: function(){ return this.document; }, getWindow: function(){ return this; } }); [Document, Element].invoke('implement', { getElements: function(expression){ return Slick.search(this, expression, new Elements); }, getElement: function(expression){ return document.id(Slick.find(this, expression)); } }); var contains = {contains: function(element){ return Slick.contains(this, element); }}; if (!document.contains) Document.implement(contains); if (!document.createElement('div').contains) Element.implement(contains); // tree walking var injectCombinator = function(expression, combinator){ if (!expression) return combinator; expression = Object.clone(Slick.parse(expression)); var expressions = expression.expressions; for (var i = expressions.length; i--;) expressions[i][0].combinator = combinator; return expression; }; Object.forEach({ getNext: '~', getPrevious: '!~', getParent: '!' }, function(combinator, method){ Element.implement(method, function(expression){ return this.getElement(injectCombinator(expression, combinator)); }); }); Object.forEach({ getAllNext: '~', getAllPrevious: '!~', getSiblings: '~~', getChildren: '>', getParents: '!' }, function(combinator, method){ Element.implement(method, function(expression){ return this.getElements(injectCombinator(expression, combinator)); }); }); Element.implement({ getFirst: function(expression){ return document.id(Slick.search(this, injectCombinator(expression, '>'))[0]); }, getLast: function(expression){ return document.id(Slick.search(this, injectCombinator(expression, '>')).getLast()); }, getWindow: function(){ return this.ownerDocument.window; }, getDocument: function(){ return this.ownerDocument; }, getElementById: function(id){ return document.id(Slick.find(this, '#' + ('' + id).replace(/(\W)/g, '\\$1'))); }, match: function(expression){ return !expression || Slick.match(this, expression); } }); if (window.$$ == null) Window.implement('$$', function(selector){ if (arguments.length == 1){ if (typeof selector == 'string') return Slick.search(this.document, selector, new Elements); else if (Type.isEnumerable(selector)) return new Elements(selector); } return new Elements(arguments); }); // Inserters var inserters = { before: function(context, element){ var parent = element.parentNode; if (parent) parent.insertBefore(context, element); }, after: function(context, element){ var parent = element.parentNode; if (parent) parent.insertBefore(context, element.nextSibling); }, bottom: function(context, element){ element.appendChild(context); }, top: function(context, element){ element.insertBefore(context, element.firstChild); } }; inserters.inside = inserters.bottom; // getProperty / setProperty var propertyGetters = {}, propertySetters = {}; // properties var properties = {}; Array.forEach([ 'type', 'value', 'defaultValue', 'accessKey', 'cellPadding', 'cellSpacing', 'colSpan', 'frameBorder', 'rowSpan', 'tabIndex', 'useMap' ], function(property){ properties[property.toLowerCase()] = property; }); properties.html = 'innerHTML'; properties.text = (document.createElement('div').textContent == null) ? 'innerText': 'textContent'; Object.forEach(properties, function(real, key){ propertySetters[key] = function(node, value){ node[real] = value; }; propertyGetters[key] = function(node){ return node[real]; }; }); // Booleans var bools = [ 'compact', 'nowrap', 'ismap', 'declare', 'noshade', 'checked', 'disabled', 'readOnly', 'multiple', 'selected', 'noresize', 'defer', 'defaultChecked', 'autofocus', 'controls', 'autoplay', 'loop' ]; var booleans = {}; Array.forEach(bools, function(bool){ var lower = bool.toLowerCase(); booleans[lower] = bool; propertySetters[lower] = function(node, value){ node[bool] = !!value; }; propertyGetters[lower] = function(node){ return !!node[bool]; }; }); // Special cases Object.append(propertySetters, { 'class': function(node, value){ ('className' in node) ? node.className = (value || '') : node.setAttribute('class', value); }, 'for': function(node, value){ ('htmlFor' in node) ? node.htmlFor = value : node.setAttribute('for', value); }, 'style': function(node, value){ (node.style) ? node.style.cssText = value : node.setAttribute('style', value); }, 'value': function(node, value){ node.value = (value != null) ? value : ''; } }); propertyGetters['class'] = function(node){ return ('className' in node) ? node.className || null : node.getAttribute('class'); }; /* <webkit> */ var el = document.createElement('button'); // IE sets type as readonly and throws try { el.type = 'button'; } catch(e){} if (el.type != 'button') propertySetters.type = function(node, value){ node.setAttribute('type', value); }; el = null; /* </webkit> */ /*<IE>*/ var input = document.createElement('input'); input.value = 't'; input.type = 'submit'; if (input.value != 't') propertySetters.type = function(node, type){ var value = node.value; node.type = type; node.value = value; }; input = null; /*</IE>*/ /* getProperty, setProperty */ /* <ltIE9> */ var pollutesGetAttribute = (function(div){ div.random = 'attribute'; return (div.getAttribute('random') == 'attribute'); })(document.createElement('div')); /* <ltIE9> */ Element.implement({ setProperty: function(name, value){ var setter = propertySetters[name.toLowerCase()]; if (setter){ setter(this, value); } else { /* <ltIE9> */ if (pollutesGetAttribute) var attributeWhiteList = this.retrieve('$attributeWhiteList', {}); /* </ltIE9> */ if (value == null){ this.removeAttribute(name); /* <ltIE9> */ if (pollutesGetAttribute) delete attributeWhiteList[name]; /* </ltIE9> */ } else { this.setAttribute(name, '' + value); /* <ltIE9> */ if (pollutesGetAttribute) attributeWhiteList[name] = true; /* </ltIE9> */ } } return this; }, setProperties: function(attributes){ for (var attribute in attributes) this.setProperty(attribute, attributes[attribute]); return this; }, getProperty: function(name){ var getter = propertyGetters[name.toLowerCase()]; if (getter) return getter(this); /* <ltIE9> */ if (pollutesGetAttribute){ var attr = this.getAttributeNode(name), attributeWhiteList = this.retrieve('$attributeWhiteList', {}); if (!attr) return null; if (attr.expando && !attributeWhiteList[name]){ var outer = this.outerHTML; // segment by the opening tag and find mention of attribute name if (outer.substr(0, outer.search(/\/?['"]?>(?![^<]*<['"])/)).indexOf(name) < 0) return null; attributeWhiteList[name] = true; } } /* </ltIE9> */ var result = Slick.getAttribute(this, name); return (!result && !Slick.hasAttribute(this, name)) ? null : result; }, getProperties: function(){ var args = Array.from(arguments); return args.map(this.getProperty, this).associate(args); }, removeProperty: function(name){ return this.setProperty(name, null); }, removeProperties: function(){ Array.each(arguments, this.removeProperty, this); return this; }, set: function(prop, value){ var property = Element.Properties[prop]; (property && property.set) ? property.set.call(this, value) : this.setProperty(prop, value); }.overloadSetter(), get: function(prop){ var property = Element.Properties[prop]; return (property && property.get) ? property.get.apply(this) : this.getProperty(prop); }.overloadGetter(), erase: function(prop){ var property = Element.Properties[prop]; (property && property.erase) ? property.erase.apply(this) : this.removeProperty(prop); return this; }, hasClass: function(className){ return this.className.clean().contains(className, ' '); }, addClass: function(className){ if (!this.hasClass(className)) this.className = (this.className + ' ' + className).clean(); return this; }, removeClass: function(className){ this.className = this.className.replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)'), '$1'); return this; }, toggleClass: function(className, force){ if (force == null) force = !this.hasClass(className); return (force) ? this.addClass(className) : this.removeClass(className); }, adopt: function(){ var parent = this, fragment, elements = Array.flatten(arguments), length = elements.length; if (length > 1) parent = fragment = document.createDocumentFragment(); for (var i = 0; i < length; i++){ var element = document.id(elements[i], true); if (element) parent.appendChild(element); } if (fragment) this.appendChild(fragment); return this; }, appendText: function(text, where){ return this.grab(this.getDocument().newTextNode(text), where); }, grab: function(el, where){ inserters[where || 'bottom'](document.id(el, true), this); return this; }, inject: function(el, where){ inserters[where || 'bottom'](this, document.id(el, true)); return this; }, replaces: function(el){ el = document.id(el, true); el.parentNode.replaceChild(this, el); return this; }, wraps: function(el, where){ el = document.id(el, true); return this.replaces(el).grab(el, where); }, getSelected: function(){ this.selectedIndex; // Safari 3.2.1 return new Elements(Array.from(this.options).filter(function(option){ return option.selected; })); }, toQueryString: function(){ var queryString = []; this.getElements('input, select, textarea').each(function(el){ var type = el.type; if (!el.name || el.disabled || type == 'submit' || type == 'reset' || type == 'file' || type == 'image') return; var value = (el.get('tag') == 'select') ? el.getSelected().map(function(opt){ // IE return document.id(opt).get('value'); }) : ((type == 'radio' || type == 'checkbox') && !el.checked) ? null : el.get('value'); Array.from(value).each(function(val){ if (typeof val != 'undefined') queryString.push(encodeURIComponent(el.name) + '=' + encodeURIComponent(val)); }); }); return queryString.join('&'); } }); var collected = {}, storage = {}; var get = function(uid){ return (storage[uid] || (storage[uid] = {})); }; var clean = function(item){ var uid = item.uniqueNumber; if (item.removeEvents) item.removeEvents(); if (item.clearAttributes) item.clearAttributes(); if (uid != null){ delete collected[uid]; delete storage[uid]; } return item; }; var formProps = {input: 'checked', option: 'selected', textarea: 'value'}; Element.implement({ destroy: function(){ var children = clean(this).getElementsByTagName('*'); Array.each(children, clean); Element.dispose(this); return null; }, empty: function(){ Array.from(this.childNodes).each(Element.dispose); return this; }, dispose: function(){ return (this.parentNode) ? this.parentNode.removeChild(this) : this; }, clone: function(contents, keepid){ contents = contents !== false; var clone = this.cloneNode(contents), ce = [clone], te = [this], i; if (contents){ ce.append(Array.from(clone.getElementsByTagName('*'))); te.append(Array.from(this.getElementsByTagName('*'))); } for (i = ce.length; i--;){ var node = ce[i], element = te[i]; if (!keepid) node.removeAttribute('id'); /*<ltIE9>*/ if (node.clearAttributes){ node.clearAttributes(); node.mergeAttributes(element); node.removeAttribute('uniqueNumber'); if (node.options){ var no = node.options, eo = element.options; for (var j = no.length; j--;) no[j].selected = eo[j].selected; } } /*</ltIE9>*/ var prop = formProps[element.tagName.toLowerCase()]; if (prop && element[prop]) node[prop] = element[prop]; } /*<ltIE9>*/ if (Browser.ie){ var co = clone.getElementsByTagName('object'), to = this.getElementsByTagName('object'); for (i = co.length; i--;) co[i].outerHTML = to[i].outerHTML; } /*</ltIE9>*/ return document.id(clone); } }); [Element, Window, Document].invoke('implement', { addListener: function(type, fn){ if (type == 'unload'){ var old = fn, self = this; fn = function(){ self.removeListener('unload', fn); old(); }; } else { collected[Slick.uidOf(this)] = this; } if (this.addEventListener) this.addEventListener(type, fn, !!arguments[2]); else this.attachEvent('on' + type, fn); return this; }, removeListener: function(type, fn){ if (this.removeEventListener) this.removeEventListener(type, fn, !!arguments[2]); else this.detachEvent('on' + type, fn); return this; }, retrieve: function(property, dflt){ var storage = get(Slick.uidOf(this)), prop = storage[property]; if (dflt != null && prop == null) prop = storage[property] = dflt; return prop != null ? prop : null; }, store: function(property, value){ var storage = get(Slick.uidOf(this)); storage[property] = value; return this; }, eliminate: function(property){ var storage = get(Slick.uidOf(this)); delete storage[property]; return this; } }); /*<ltIE9>*/ if (window.attachEvent && !window.addEventListener) window.addListener('unload', function(){ Object.each(collected, clean); if (window.CollectGarbage) CollectGarbage(); }); /*</ltIE9>*/ Element.Properties = {}; Element.Properties.style = { set: function(style){ this.style.cssText = style; }, get: function(){ return this.style.cssText; }, erase: function(){ this.style.cssText = ''; } }; Element.Properties.tag = { get: function(){ return this.tagName.toLowerCase(); } }; Element.Properties.html = { set: function(html){ if (html == null) html = ''; else if (typeOf(html) == 'array') html = html.join(''); this.innerHTML = html; }, erase: function(){ this.innerHTML = ''; } }; /*<ltIE9>*/ // technique by jdbarlett - http://jdbartlett.com/innershiv/ var div = document.createElement('div'); div.innerHTML = '<nav></nav>'; var supportsHTML5Elements = (div.childNodes.length == 1); if (!supportsHTML5Elements){ var tags = 'abbr article aside audio canvas datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video'.split(' '), fragment = document.createDocumentFragment(), l = tags.length; while (l--) fragment.createElement(tags[l]); } div = null; /*</ltIE9>*/ /*<IE>*/ var supportsTableInnerHTML = Function.attempt(function(){ var table = document.createElement('table'); table.innerHTML = '<tr><td></td></tr>'; return true; }); /*<ltFF4>*/ var tr = document.createElement('tr'), html = '<td></td>'; tr.innerHTML = html; var supportsTRInnerHTML = (tr.innerHTML == html); tr = null; /*</ltFF4>*/ if (!supportsTableInnerHTML || !supportsTRInnerHTML || !supportsHTML5Elements){ Element.Properties.html.set = (function(set){ var translations = { table: [1, '<table>', '</table>'], select: [1, '<select>', '</select>'], tbody: [2, '<table><tbody>', '</tbody></table>'], tr: [3, '<table><tbody><tr>', '</tr></tbody></table>'] }; translations.thead = translations.tfoot = translations.tbody; return function(html){ var wrap = translations[this.get('tag')]; if (!wrap && !supportsHTML5Elements) wrap = [0, '', '']; if (!wrap) return set.call(this, html); var level = wrap[0], wrapper = document.createElement('div'), target = wrapper; if (!supportsHTML5Elements) fragment.appendChild(wrapper); wrapper.innerHTML = [wrap[1], html, wrap[2]].flatten().join(''); while (level--) target = target.firstChild; this.empty().adopt(target.childNodes); if (!supportsHTML5Elements) fragment.removeChild(wrapper); wrapper = null; }; })(Element.Properties.html.set); } /*</IE>*/ /*<ltIE9>*/ var testForm = document.createElement('form'); testForm.innerHTML = '<select><option>s</option></select>'; if (testForm.firstChild.value != 's') Element.Properties.value = { set: function(value){ var tag = this.get('tag'); if (tag != 'select') return this.setProperty('value', value); var options = this.getElements('option'); for (var i = 0; i < options.length; i++){ var option = options[i], attr = option.getAttributeNode('value'), optionValue = (attr && attr.specified) ? option.value : option.get('text'); if (optionValue == value) return option.selected = true; } }, get: function(){ var option = this, tag = option.get('tag'); if (tag != 'select' && tag != 'option') return this.getProperty('value'); if (tag == 'select' && !(option = option.getSelected()[0])) return ''; var attr = option.getAttributeNode('value'); return (attr && attr.specified) ? option.value : option.get('text'); } }; testForm = null; /*</ltIE9>*/ /*<IE>*/ if (document.createElement('div').getAttributeNode('id')) Element.Properties.id = { set: function(id){ this.id = this.getAttributeNode('id').value = id; }, get: function(){ return this.id || null; }, erase: function(){ this.id = this.getAttributeNode('id').value = ''; } }; /*</IE>*/ })(); /* --- name: Element.Style description: Contains methods for interacting with the styles of Elements in a fashionable way. license: MIT-style license. requires: Element provides: Element.Style ... */ (function(){ var html = document.html; //<ltIE9> // Check for oldIE, which does not remove styles when they're set to null var el = document.createElement('div'); el.style.color = 'red'; el.style.color = null; var doesNotRemoveStyles = el.style.color == 'red'; el = null; //</ltIE9> Element.Properties.styles = {set: function(styles){ this.setStyles(styles); }}; var hasOpacity = (html.style.opacity != null), hasFilter = (html.style.filter != null), reAlpha = /alpha\(opacity=([\d.]+)\)/i; var setVisibility = function(element, opacity){ element.store('$opacity', opacity); element.style.visibility = opacity > 0 || opacity == null ? 'visible' : 'hidden'; }; var setOpacity = (hasOpacity ? function(element, opacity){ element.style.opacity = opacity; } : (hasFilter ? function(element, opacity){ var style = element.style; if (!element.currentStyle || !element.currentStyle.hasLayout) style.zoom = 1; if (opacity == null || opacity == 1) opacity = ''; else opacity = 'alpha(opacity=' + (opacity * 100).limit(0, 100).round() + ')'; var filter = style.filter || element.getComputedStyle('filter') || ''; style.filter = reAlpha.test(filter) ? filter.replace(reAlpha, opacity) : filter + opacity; if (!style.filter) style.removeAttribute('filter'); } : setVisibility)); var getOpacity = (hasOpacity ? function(element){ var opacity = element.style.opacity || element.getComputedStyle('opacity'); return (opacity == '') ? 1 : opacity.toFloat(); } : (hasFilter ? function(element){ var filter = (element.style.filter || element.getComputedStyle('filter')), opacity; if (filter) opacity = filter.match(reAlpha); return (opacity == null || filter == null) ? 1 : (opacity[1] / 100); } : function(element){ var opacity = element.retrieve('$opacity'); if (opacity == null) opacity = (element.style.visibility == 'hidden' ? 0 : 1); return opacity; })); var floatName = (html.style.cssFloat == null) ? 'styleFloat' : 'cssFloat'; Element.implement({ getComputedStyle: function(property){ if (this.currentStyle) return this.currentStyle[property.camelCase()]; var defaultView = Element.getDocument(this).defaultView, computed = defaultView ? defaultView.getComputedStyle(this, null) : null; return (computed) ? computed.getPropertyValue((property == floatName) ? 'float' : property.hyphenate()) : null; }, setStyle: function(property, value){ if (property == 'opacity'){ if (value != null) value = parseFloat(value); setOpacity(this, value); return this; } property = (property == 'float' ? floatName : property).camelCase(); if (typeOf(value) != 'string'){ var map = (Element.Styles[property] || '@').split(' '); value = Array.from(value).map(function(val, i){ if (!map[i]) return ''; return (typeOf(val) == 'number') ? map[i].replace('@', Math.round(val)) : val; }).join(' '); } else if (value == String(Number(value))){ value = Math.round(value); } this.style[property] = value; //<ltIE9> if ((value == '' || value == null) && doesNotRemoveStyles && this.style.removeAttribute){ this.style.removeAttribute(property); } //</ltIE9> return this; }, getStyle: function(property){ if (property == 'opacity') return getOpacity(this); property = (property == 'float' ? floatName : property).camelCase(); var result = this.style[property]; if (!result || property == 'zIndex'){ result = []; for (var style in Element.ShortStyles){ if (property != style) continue; for (var s in Element.ShortStyles[style]) result.push(this.getStyle(s)); return result.join(' '); } result = this.getComputedStyle(property); } if (result){ result = String(result); var color = result.match(/rgba?\([\d\s,]+\)/); if (color) result = result.replace(color[0], color[0].rgbToHex()); } if (Browser.opera || Browser.ie){ if ((/^(height|width)$/).test(property) && !(/px$/.test(result))){ var values = (property == 'width') ? ['left', 'right'] : ['top', 'bottom'], size = 0; values.each(function(value){ size += this.getStyle('border-' + value + '-width').toInt() + this.getStyle('padding-' + value).toInt(); }, this); return this['offset' + property.capitalize()] - size + 'px'; } if (Browser.ie && (/^border(.+)Width|margin|padding/).test(property) && isNaN(parseFloat(result))){ return '0px'; } } return result; }, setStyles: function(styles){ for (var style in styles) this.setStyle(style, styles[style]); return this; }, getStyles: function(){ var result = {}; Array.flatten(arguments).each(function(key){ result[key] = this.getStyle(key); }, this); return result; } }); Element.Styles = { left: '@px', top: '@px', bottom: '@px', right: '@px', width: '@px', height: '@px', maxWidth: '@px', maxHeight: '@px', minWidth: '@px', minHeight: '@px', backgroundColor: 'rgb(@, @, @)', backgroundPosition: '@px @px', color: 'rgb(@, @, @)', fontSize: '@px', letterSpacing: '@px', lineHeight: '@px', clip: 'rect(@px @px @px @px)', margin: '@px @px @px @px', padding: '@px @px @px @px', border: '@px @ rgb(@, @, @) @px @ rgb(@, @, @) @px @ rgb(@, @, @)', borderWidth: '@px @px @px @px', borderStyle: '@ @ @ @', borderColor: 'rgb(@, @, @) rgb(@, @, @) rgb(@, @, @) rgb(@, @, @)', zIndex: '@', 'zoom': '@', fontWeight: '@', textIndent: '@px', opacity: '@' }; Element.ShortStyles = {margin: {}, padding: {}, border: {}, borderWidth: {}, borderStyle: {}, borderColor: {}}; ['Top', 'Right', 'Bottom', 'Left'].each(function(direction){ var Short = Element.ShortStyles; var All = Element.Styles; ['margin', 'padding'].each(function(style){ var sd = style + direction; Short[style][sd] = All[sd] = '@px'; }); var bd = 'border' + direction; Short.border[bd] = All[bd] = '@px @ rgb(@, @, @)'; var bdw = bd + 'Width', bds = bd + 'Style', bdc = bd + 'Color'; Short[bd] = {}; Short.borderWidth[bdw] = Short[bd][bdw] = All[bdw] = '@px'; Short.borderStyle[bds] = Short[bd][bds] = All[bds] = '@'; Short.borderColor[bdc] = Short[bd][bdc] = All[bdc] = 'rgb(@, @, @)'; }); })(); /* --- name: Element.Event description: Contains Element methods for dealing with events. This file also includes mouseenter and mouseleave custom Element Events, if necessary. license: MIT-style license. requires: [Element, Event] provides: Element.Event ... */ (function(){ Element.Properties.events = {set: function(events){ this.addEvents(events); }}; [Element, Window, Document].invoke('implement', { addEvent: function(type, fn){ var events = this.retrieve('events', {}); if (!events[type]) events[type] = {keys: [], values: []}; if (events[type].keys.contains(fn)) return this; events[type].keys.push(fn); var realType = type, custom = Element.Events[type], condition = fn, self = this; if (custom){ if (custom.onAdd) custom.onAdd.call(this, fn, type); if (custom.condition){ condition = function(event){ if (custom.condition.call(this, event, type)) return fn.call(this, event); return true; }; } if (custom.base) realType = Function.from(custom.base).call(this, type); } var defn = function(){ return fn.call(self); }; var nativeEvent = Element.NativeEvents[realType]; if (nativeEvent){ if (nativeEvent == 2){ defn = function(event){ event = new DOMEvent(event, self.getWindow()); if (condition.call(self, event) === false) event.stop(); }; } this.addListener(realType, defn, arguments[2]); } events[type].values.push(defn); return this; }, removeEvent: function(type, fn){ var events = this.retrieve('events'); if (!events || !events[type]) return this; var list = events[type]; var index = list.keys.indexOf(fn); if (index == -1) return this; var value = list.values[index]; delete list.keys[index]; delete list.values[index]; var custom = Element.Events[type]; if (custom){ if (custom.onRemove) custom.onRemove.call(this, fn, type); if (custom.base) type = Function.from(custom.base).call(this, type); } return (Element.NativeEvents[type]) ? this.removeListener(type, value, arguments[2]) : this; }, addEvents: function(events){ for (var event in events) this.addEvent(event, events[event]); return this; }, removeEvents: function(events){ var type; if (typeOf(events) == 'object'){ for (type in events) this.removeEvent(type, events[type]); return this; } var attached = this.retrieve('events'); if (!attached) return this; if (!events){ for (type in attached) this.removeEvents(type); this.eliminate('events'); } else if (attached[events]){ attached[events].keys.each(function(fn){ this.removeEvent(events, fn); }, this); delete attached[events]; } return this; }, fireEvent: function(type, args, delay){ var events = this.retrieve('events'); if (!events || !events[type]) return this; args = Array.from(args); events[type].keys.each(function(fn){ if (delay) fn.delay(delay, this, args); else fn.apply(this, args); }, this); return this; }, cloneEvents: function(from, type){ from = document.id(from); var events = from.retrieve('events'); if (!events) return this; if (!type){ for (var eventType in events) this.cloneEvents(from, eventType); } else if (events[type]){ events[type].keys.each(function(fn){ this.addEvent(type, fn); }, this); } return this; } }); Element.NativeEvents = { click: 2, dblclick: 2, mouseup: 2, mousedown: 2, contextmenu: 2, //mouse buttons mousewheel: 2, DOMMouseScroll: 2, //mouse wheel mouseover: 2, mouseout: 2, mousemove: 2, selectstart: 2, selectend: 2, //mouse movement keydown: 2, keypress: 2, keyup: 2, //keyboard orientationchange: 2, // mobile touchstart: 2, touchmove: 2, touchend: 2, touchcancel: 2, // touch gesturestart: 2, gesturechange: 2, gestureend: 2, // gesture focus: 2, blur: 2, change: 2, reset: 2, select: 2, submit: 2, paste: 2, input: 2, //form elements load: 2, unload: 1, beforeunload: 2, resize: 1, move: 1, DOMContentLoaded: 1, readystatechange: 1, //window error: 1, abort: 1, scroll: 1 //misc }; Element.Events = {mousewheel: { base: (Browser.firefox) ? 'DOMMouseScroll' : 'mousewheel' }}; if ('onmouseenter' in document.documentElement){ Element.NativeEvents.mouseenter = Element.NativeEvents.mouseleave = 2; } else { var check = function(event){ var related = event.relatedTarget; if (related == null) return true; if (!related) return false; return (related != this && related.prefix != 'xul' && typeOf(this) != 'document' && !this.contains(related)); }; Element.Events.mouseenter = { base: 'mouseover', condition: check }; Element.Events.mouseleave = { base: 'mouseout', condition: check }; } /*<ltIE9>*/ if (!window.addEventListener){ Element.NativeEvents.propertychange = 2; Element.Events.change = { base: function(){ var type = this.type; return (this.get('tag') == 'input' && (type == 'radio' || type == 'checkbox')) ? 'propertychange' : 'change' }, condition: function(event){ return this.type != 'radio' || (event.event.propertyName == 'checked' && this.checked); } } } /*</ltIE9>*/ })(); /* --- name: Element.Delegation description: Extends the Element native object to include the delegate method for more efficient event management. license: MIT-style license. requires: [Element.Event] provides: [Element.Delegation] ... */ (function(){ var eventListenerSupport = !!window.addEventListener; Element.NativeEvents.focusin = Element.NativeEvents.focusout = 2; var bubbleUp = function(self, match, fn, event, target){ while (target && target != self){ if (match(target, event)) return fn.call(target, event, target); target = document.id(target.parentNode); } }; var map = { mouseenter: { base: 'mouseover' }, mouseleave: { base: 'mouseout' }, focus: { base: 'focus' + (eventListenerSupport ? '' : 'in'), capture: true }, blur: { base: eventListenerSupport ? 'blur' : 'focusout', capture: true } }; /*<ltIE9>*/ var _key = '$delegation:'; var formObserver = function(type){ return { base: 'focusin', remove: function(self, uid){ var list = self.retrieve(_key + type + 'listeners', {})[uid]; if (list && list.forms) for (var i = list.forms.length; i--;){ list.forms[i].removeEvent(type, list.fns[i]); } }, listen: function(self, match, fn, event, target, uid){ var form = (target.get('tag') == 'form') ? target : event.target.getParent('form'); if (!form) return; var listeners = self.retrieve(_key + type + 'listeners', {}), listener = listeners[uid] || {forms: [], fns: []}, forms = listener.forms, fns = listener.fns; if (forms.indexOf(form) != -1) return; forms.push(form); var _fn = function(event){ bubbleUp(self, match, fn, event, target); }; form.addEvent(type, _fn); fns.push(_fn); listeners[uid] = listener; self.store(_key + type + 'listeners', listeners); } }; }; var inputObserver = function(type){ return { base: 'focusin', listen: function(self, match, fn, event, target){ var events = {blur: function(){ this.removeEvents(events); }}; events[type] = function(event){ bubbleUp(self, match, fn, event, target); }; event.target.addEvents(events); } }; }; if (!eventListenerSupport) Object.append(map, { submit: formObserver('submit'), reset: formObserver('reset'), change: inputObserver('change'), select: inputObserver('select') }); /*</ltIE9>*/ var proto = Element.prototype, addEvent = proto.addEvent, removeEvent = proto.removeEvent; var relay = function(old, method){ return function(type, fn, useCapture){ if (type.indexOf(':relay') == -1) return old.call(this, type, fn, useCapture); var parsed = Slick.parse(type).expressions[0][0]; if (parsed.pseudos[0].key != 'relay') return old.call(this, type, fn, useCapture); var newType = parsed.tag; parsed.pseudos.slice(1).each(function(pseudo){ newType += ':' + pseudo.key + (pseudo.value ? '(' + pseudo.value + ')' : ''); }); old.call(this, type, fn); return method.call(this, newType, parsed.pseudos[0].value, fn); }; }; var delegation = { addEvent: function(type, match, fn){ var storage = this.retrieve('$delegates', {}), stored = storage[type]; if (stored) for (var _uid in stored){ if (stored[_uid].fn == fn && stored[_uid].match == match) return this; } var _type = type, _match = match, _fn = fn, _map = map[type] || {}; type = _map.base || _type; match = function(target){ return Slick.match(target, _match); }; var elementEvent = Element.Events[_type]; if (elementEvent && elementEvent.condition){ var __match = match, condition = elementEvent.condition; match = function(target, event){ return __match(target, event) && condition.call(target, event, type); }; } var self = this, uid = String.uniqueID(); var delegator = _map.listen ? function(event, target){ if (!target && event && event.target) target = event.target; if (target) _map.listen(self, match, fn, event, target, uid); } : function(event, target){ if (!target && event && event.target) target = event.target; if (target) bubbleUp(self, match, fn, event, target); }; if (!stored) stored = {}; stored[uid] = { match: _match, fn: _fn, delegator: delegator }; storage[_type] = stored; return addEvent.call(this, type, delegator, _map.capture); }, removeEvent: function(type, match, fn, _uid){ var storage = this.retrieve('$delegates', {}), stored = storage[type]; if (!stored) return this; if (_uid){ var _type = type, delegator = stored[_uid].delegator, _map = map[type] || {}; type = _map.base || _type; if (_map.remove) _map.remove(this, _uid); delete stored[_uid]; storage[_type] = stored; return removeEvent.call(this, type, delegator); } var __uid, s; if (fn) for (__uid in stored){ s = stored[__uid]; if (s.match == match && s.fn == fn) return delegation.removeEvent.call(this, type, match, fn, __uid); } else for (__uid in stored){ s = stored[__uid]; if (s.match == match) delegation.removeEvent.call(this, type, match, s.fn, __uid); } return this; } }; [Element, Window, Document].invoke('implement', { addEvent: relay(addEvent, delegation.addEvent), removeEvent: relay(removeEvent, delegation.removeEvent) }); })(); /* --- name: Element.Dimensions description: Contains methods to work with size, scroll, or positioning of Elements and the window object. license: MIT-style license. credits: - Element positioning based on the [qooxdoo](http://qooxdoo.org/) code and smart browser fixes, [LGPL License](http://www.gnu.org/licenses/lgpl.html). - Viewport dimensions based on [YUI](http://developer.yahoo.com/yui/) code, [BSD License](http://developer.yahoo.com/yui/license.html). requires: [Element, Element.Style] provides: [Element.Dimensions] ... */ (function(){ var element = document.createElement('div'), child = document.createElement('div'); element.style.height = '0'; element.appendChild(child); var brokenOffsetParent = (child.offsetParent === element); element = child = null; var isOffset = function(el){ return styleString(el, 'position') != 'static' || isBody(el); }; var isOffsetStatic = function(el){ return isOffset(el) || (/^(?:table|td|th)$/i).test(el.tagName); }; Element.implement({ scrollTo: function(x, y){ if (isBody(this)){ this.getWindow().scrollTo(x, y); } else { this.scrollLeft = x; this.scrollTop = y; } return this; }, getSize: function(){ if (isBody(this)) return this.getWindow().getSize(); return {x: this.offsetWidth, y: this.offsetHeight}; }, getScrollSize: function(){ if (isBody(this)) return this.getWindow().getScrollSize(); return {x: this.scrollWidth, y: this.scrollHeight}; }, getScroll: function(){ if (isBody(this)) return this.getWindow().getScroll(); return {x: this.scrollLeft, y: this.scrollTop}; }, getScrolls: function(){ var element = this.parentNode, position = {x: 0, y: 0}; while (element && !isBody(element)){ position.x += element.scrollLeft; position.y += element.scrollTop; element = element.parentNode; } return position; }, getOffsetParent: brokenOffsetParent ? function(){ var element = this; if (isBody(element) || styleString(element, 'position') == 'fixed') return null; var isOffsetCheck = (styleString(element, 'position') == 'static') ? isOffsetStatic : isOffset; while ((element = element.parentNode)){ if (isOffsetCheck(element)) return element; } return null; } : function(){ var element = this; if (isBody(element) || styleString(element, 'position') == 'fixed') return null; try { return element.offsetParent; } catch(e) {} return null; }, getOffsets: function(){ if (this.getBoundingClientRect && !Browser.Platform.ios){ var bound = this.getBoundingClientRect(), html = document.id(this.getDocument().documentElement), htmlScroll = html.getScroll(), elemScrolls = this.getScrolls(), isFixed = (styleString(this, 'position') == 'fixed'); return { x: bound.left.toInt() + elemScrolls.x + ((isFixed) ? 0 : htmlScroll.x) - html.clientLeft, y: bound.top.toInt() + elemScrolls.y + ((isFixed) ? 0 : htmlScroll.y) - html.clientTop }; } var element = this, position = {x: 0, y: 0}; if (isBody(this)) return position; while (element && !isBody(element)){ position.x += element.offsetLeft; position.y += element.offsetTop; if (Browser.firefox){ if (!borderBox(element)){ position.x += leftBorder(element); position.y += topBorder(element); } var parent = element.parentNode; if (parent && styleString(parent, 'overflow') != 'visible'){ position.x += leftBorder(parent); position.y += topBorder(parent); } } else if (element != this && Browser.safari){ position.x += leftBorder(element); position.y += topBorder(element); } element = element.offsetParent; } if (Browser.firefox && !borderBox(this)){ position.x -= leftBorder(this); position.y -= topBorder(this); } return position; }, getPosition: function(relative){ var offset = this.getOffsets(), scroll = this.getScrolls(); var position = { x: offset.x - scroll.x, y: offset.y - scroll.y }; if (relative && (relative = document.id(relative))){ var relativePosition = relative.getPosition(); return {x: position.x - relativePosition.x - leftBorder(relative), y: position.y - relativePosition.y - topBorder(relative)}; } return position; }, getCoordinates: function(element){ if (isBody(this)) return this.getWindow().getCoordinates(); var position = this.getPosition(element), size = this.getSize(); var obj = { left: position.x, top: position.y, width: size.x, height: size.y }; obj.right = obj.left + obj.width; obj.bottom = obj.top + obj.height; return obj; }, computePosition: function(obj){ return { left: obj.x - styleNumber(this, 'margin-left'), top: obj.y - styleNumber(this, 'margin-top') }; }, setPosition: function(obj){ return this.setStyles(this.computePosition(obj)); } }); [Document, Window].invoke('implement', { getSize: function(){ var doc = getCompatElement(this); return {x: doc.clientWidth, y: doc.clientHeight}; }, getScroll: function(){ var win = this.getWindow(), doc = getCompatElement(this); return {x: win.pageXOffset || doc.scrollLeft, y: win.pageYOffset || doc.scrollTop}; }, getScrollSize: function(){ var doc = getCompatElement(this), min = this.getSize(), body = this.getDocument().body; return {x: Math.max(doc.scrollWidth, body.scrollWidth, min.x), y: Math.max(doc.scrollHeight, body.scrollHeight, min.y)}; }, getPosition: function(){ return {x: 0, y: 0}; }, getCoordinates: function(){ var size = this.getSize(); return {top: 0, left: 0, bottom: size.y, right: size.x, height: size.y, width: size.x}; } }); // private methods var styleString = Element.getComputedStyle; function styleNumber(element, style){ return styleString(element, style).toInt() || 0; } function borderBox(element){ return styleString(element, '-moz-box-sizing') == 'border-box'; } function topBorder(element){ return styleNumber(element, 'border-top-width'); } function leftBorder(element){ return styleNumber(element, 'border-left-width'); } function isBody(element){ return (/^(?:body|html)$/i).test(element.tagName); } function getCompatElement(element){ var doc = element.getDocument(); return (!doc.compatMode || doc.compatMode == 'CSS1Compat') ? doc.html : doc.body; } })(); //aliases Element.alias({position: 'setPosition'}); //compatability [Window, Document, Element].invoke('implement', { getHeight: function(){ return this.getSize().y; }, getWidth: function(){ return this.getSize().x; }, getScrollTop: function(){ return this.getScroll().y; }, getScrollLeft: function(){ return this.getScroll().x; }, getScrollHeight: function(){ return this.getScrollSize().y; }, getScrollWidth: function(){ return this.getScrollSize().x; }, getTop: function(){ return this.getPosition().y; }, getLeft: function(){ return this.getPosition().x; } }); /* --- name: Fx description: Contains the basic animation logic to be extended by all other Fx Classes. license: MIT-style license. requires: [Chain, Events, Options] provides: Fx ... */ (function(){ var Fx = this.Fx = new Class({ Implements: [Chain, Events, Options], options: { /* onStart: nil, onCancel: nil, onComplete: nil, */ fps: 60, unit: false, duration: 500, frames: null, frameSkip: true, link: 'ignore' }, initialize: function(options){ this.subject = this.subject || this; this.setOptions(options); }, getTransition: function(){ return function(p){ return -(Math.cos(Math.PI * p) - 1) / 2; }; }, step: function(now){ if (this.options.frameSkip){ var diff = (this.time != null) ? (now - this.time) : 0, frames = diff / this.frameInterval; this.time = now; this.frame += frames; } else { this.frame++; } if (this.frame < this.frames){ var delta = this.transition(this.frame / this.frames); this.set(this.compute(this.from, this.to, delta)); } else { this.frame = this.frames; this.set(this.compute(this.from, this.to, 1)); this.stop(); } }, set: function(now){ return now; }, compute: function(from, to, delta){ return Fx.compute(from, to, delta); }, check: function(){ if (!this.isRunning()) return true; switch (this.options.link){ case 'cancel': this.cancel(); return true; case 'chain': this.chain(this.caller.pass(arguments, this)); return false; } return false; }, start: function(from, to){ if (!this.check(from, to)) return this; this.from = from; this.to = to; this.frame = (this.options.frameSkip) ? 0 : -1; this.time = null; this.transition = this.getTransition(); var frames = this.options.frames, fps = this.options.fps, duration = this.options.duration; this.duration = Fx.Durations[duration] || duration.toInt(); this.frameInterval = 1000 / fps; this.frames = frames || Math.round(this.duration / this.frameInterval); this.fireEvent('start', this.subject); pushInstance.call(this, fps); return this; }, stop: function(){ if (this.isRunning()){ this.time = null; pullInstance.call(this, this.options.fps); if (this.frames == this.frame){ this.fireEvent('complete', this.subject); if (!this.callChain()) this.fireEvent('chainComplete', this.subject); } else { this.fireEvent('stop', this.subject); } } return this; }, cancel: function(){ if (this.isRunning()){ this.time = null; pullInstance.call(this, this.options.fps); this.frame = this.frames; this.fireEvent('cancel', this.subject).clearChain(); } return this; }, pause: function(){ if (this.isRunning()){ this.time = null; pullInstance.call(this, this.options.fps); } return this; }, resume: function(){ if ((this.frame < this.frames) && !this.isRunning()) pushInstance.call(this, this.options.fps); return this; }, isRunning: function(){ var list = instances[this.options.fps]; return list && list.contains(this); } }); Fx.compute = function(from, to, delta){ return (to - from) * delta + from; }; Fx.Durations = {'short': 250, 'normal': 500, 'long': 1000}; // global timers var instances = {}, timers = {}; var loop = function(){ var now = Date.now(); for (var i = this.length; i--;){ var instance = this[i]; if (instance) instance.step(now); } }; var pushInstance = function(fps){ var list = instances[fps] || (instances[fps] = []); list.push(this); if (!timers[fps]) timers[fps] = loop.periodical(Math.round(1000 / fps), list); }; var pullInstance = function(fps){ var list = instances[fps]; if (list){ list.erase(this); if (!list.length && timers[fps]){ delete instances[fps]; timers[fps] = clearInterval(timers[fps]); } } }; })(); /* --- name: Fx.CSS description: Contains the CSS animation logic. Used by Fx.Tween, Fx.Morph, Fx.Elements. license: MIT-style license. requires: [Fx, Element.Style] provides: Fx.CSS ... */ Fx.CSS = new Class({ Extends: Fx, //prepares the base from/to object prepare: function(element, property, values){ values = Array.from(values); var from = values[0], to = values[1]; if (to == null){ to = from; from = element.getStyle(property); var unit = this.options.unit; // adapted from: https://github.com/ryanmorr/fx/blob/master/fx.js#L299 if (unit && from.slice(-unit.length) != unit && parseFloat(from) != 0){ element.setStyle(property, to + unit); var value = element.getComputedStyle(property); // IE and Opera support pixelLeft or pixelWidth if (!(/px$/.test(value))){ value = element.style[('pixel-' + property).camelCase()]; if (value == null){ // adapted from Dean Edwards' http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 var left = element.style.left; element.style.left = to + unit; value = element.style.pixelLeft; element.style.left = left; } } from = (to || 1) / (parseFloat(value) || 1) * (parseFloat(from) || 0); element.setStyle(property, from + unit); } } return {from: this.parse(from), to: this.parse(to)}; }, //parses a value into an array parse: function(value){ value = Function.from(value)(); value = (typeof value == 'string') ? value.split(' ') : Array.from(value); return value.map(function(val){ val = String(val); var found = false; Object.each(Fx.CSS.Parsers, function(parser, key){ if (found) return; var parsed = parser.parse(val); if (parsed || parsed === 0) found = {value: parsed, parser: parser}; }); found = found || {value: val, parser: Fx.CSS.Parsers.String}; return found; }); }, //computes by a from and to prepared objects, using their parsers. compute: function(from, to, delta){ var computed = []; (Math.min(from.length, to.length)).times(function(i){ computed.push({value: from[i].parser.compute(from[i].value, to[i].value, delta), parser: from[i].parser}); }); computed.$family = Function.from('fx:css:value'); return computed; }, //serves the value as settable serve: function(value, unit){ if (typeOf(value) != 'fx:css:value') value = this.parse(value); var returned = []; value.each(function(bit){ returned = returned.concat(bit.parser.serve(bit.value, unit)); }); return returned; }, //renders the change to an element render: function(element, property, value, unit){ element.setStyle(property, this.serve(value, unit)); }, //searches inside the page css to find the values for a selector search: function(selector){ if (Fx.CSS.Cache[selector]) return Fx.CSS.Cache[selector]; var to = {}, selectorTest = new RegExp('^' + selector.escapeRegExp() + '$'); Array.each(document.styleSheets, function(sheet, j){ var href = sheet.href; if (href && href.contains('://') && !href.contains(document.domain)) return; var rules = sheet.rules || sheet.cssRules; Array.each(rules, function(rule, i){ if (!rule.style) return; var selectorText = (rule.selectorText) ? rule.selectorText.replace(/^\w+/, function(m){ return m.toLowerCase(); }) : null; if (!selectorText || !selectorTest.test(selectorText)) return; Object.each(Element.Styles, function(value, style){ if (!rule.style[style] || Element.ShortStyles[style]) return; value = String(rule.style[style]); to[style] = ((/^rgb/).test(value)) ? value.rgbToHex() : value; }); }); }); return Fx.CSS.Cache[selector] = to; } }); Fx.CSS.Cache = {}; Fx.CSS.Parsers = { Color: { parse: function(value){ if (value.match(/^#[0-9a-f]{3,6}$/i)) return value.hexToRgb(true); return ((value = value.match(/(\d+),\s*(\d+),\s*(\d+)/))) ? [value[1], value[2], value[3]] : false; }, compute: function(from, to, delta){ return from.map(function(value, i){ return Math.round(Fx.compute(from[i], to[i], delta)); }); }, serve: function(value){ return value.map(Number); } }, Number: { parse: parseFloat, compute: Fx.compute, serve: function(value, unit){ return (unit) ? value + unit : value; } }, String: { parse: Function.from(false), compute: function(zero, one){ return one; }, serve: function(zero){ return zero; } } }; /* --- name: Fx.Tween description: Formerly Fx.Style, effect to transition any CSS property for an element. license: MIT-style license. requires: Fx.CSS provides: [Fx.Tween, Element.fade, Element.highlight] ... */ Fx.Tween = new Class({ Extends: Fx.CSS, initialize: function(element, options){ this.element = this.subject = document.id(element); this.parent(options); }, set: function(property, now){ if (arguments.length == 1){ now = property; property = this.property || this.options.property; } this.render(this.element, property, now, this.options.unit); return this; }, start: function(property, from, to){ if (!this.check(property, from, to)) return this; var args = Array.flatten(arguments); this.property = this.options.property || args.shift(); var parsed = this.prepare(this.element, this.property, args); return this.parent(parsed.from, parsed.to); } }); Element.Properties.tween = { set: function(options){ this.get('tween').cancel().setOptions(options); return this; }, get: function(){ var tween = this.retrieve('tween'); if (!tween){ tween = new Fx.Tween(this, {link: 'cancel'}); this.store('tween', tween); } return tween; } }; Element.implement({ tween: function(property, from, to){ this.get('tween').start(property, from, to); return this; }, fade: function(how){ var fade = this.get('tween'), method, args = ['opacity'].append(arguments), toggle; if (args[1] == null) args[1] = 'toggle'; switch (args[1]){ case 'in': method = 'start'; args[1] = 1; break; case 'out': method = 'start'; args[1] = 0; break; case 'show': method = 'set'; args[1] = 1; break; case 'hide': method = 'set'; args[1] = 0; break; case 'toggle': var flag = this.retrieve('fade:flag', this.getStyle('opacity') == 1); method = 'start'; args[1] = flag ? 0 : 1; this.store('fade:flag', !flag); toggle = true; break; default: method = 'start'; } if (!toggle) this.eliminate('fade:flag'); fade[method].apply(fade, args); var to = args[args.length - 1]; if (method == 'set' || to != 0) this.setStyle('visibility', to == 0 ? 'hidden' : 'visible'); else fade.chain(function(){ this.element.setStyle('visibility', 'hidden'); this.callChain(); }); return this; }, highlight: function(start, end){ if (!end){ end = this.retrieve('highlight:original', this.getStyle('background-color')); end = (end == 'transparent') ? '#fff' : end; } var tween = this.get('tween'); tween.start('background-color', start || '#ffff88', end).chain(function(){ this.setStyle('background-color', this.retrieve('highlight:original')); tween.callChain(); }.bind(this)); return this; } }); /* --- name: Fx.Morph description: Formerly Fx.Styles, effect to transition any number of CSS properties for an element using an object of rules, or CSS based selector rules. license: MIT-style license. requires: Fx.CSS provides: Fx.Morph ... */ Fx.Morph = new Class({ Extends: Fx.CSS, initialize: function(element, options){ this.element = this.subject = document.id(element); this.parent(options); }, set: function(now){ if (typeof now == 'string') now = this.search(now); for (var p in now) this.render(this.element, p, now[p], this.options.unit); return this; }, compute: function(from, to, delta){ var now = {}; for (var p in from) now[p] = this.parent(from[p], to[p], delta); return now; }, start: function(properties){ if (!this.check(properties)) return this; if (typeof properties == 'string') properties = this.search(properties); var from = {}, to = {}; for (var p in properties){ var parsed = this.prepare(this.element, p, properties[p]); from[p] = parsed.from; to[p] = parsed.to; } return this.parent(from, to); } }); Element.Properties.morph = { set: function(options){ this.get('morph').cancel().setOptions(options); return this; }, get: function(){ var morph = this.retrieve('morph'); if (!morph){ morph = new Fx.Morph(this, {link: 'cancel'}); this.store('morph', morph); } return morph; } }; Element.implement({ morph: function(props){ this.get('morph').start(props); return this; } }); /* --- name: Fx.Transitions description: Contains a set of advanced transitions to be used with any of the Fx Classes. license: MIT-style license. credits: - Easing Equations by Robert Penner, <http://www.robertpenner.com/easing/>, modified and optimized to be used with MooTools. requires: Fx provides: Fx.Transitions ... */ Fx.implement({ getTransition: function(){ var trans = this.options.transition || Fx.Transitions.Sine.easeInOut; if (typeof trans == 'string'){ var data = trans.split(':'); trans = Fx.Transitions; trans = trans[data[0]] || trans[data[0].capitalize()]; if (data[1]) trans = trans['ease' + data[1].capitalize() + (data[2] ? data[2].capitalize() : '')]; } return trans; } }); Fx.Transition = function(transition, params){ params = Array.from(params); var easeIn = function(pos){ return transition(pos, params); }; return Object.append(easeIn, { easeIn: easeIn, easeOut: function(pos){ return 1 - transition(1 - pos, params); }, easeInOut: function(pos){ return (pos <= 0.5 ? transition(2 * pos, params) : (2 - transition(2 * (1 - pos), params))) / 2; } }); }; Fx.Transitions = { linear: function(zero){ return zero; } }; Fx.Transitions.extend = function(transitions){ for (var transition in transitions) Fx.Transitions[transition] = new Fx.Transition(transitions[transition]); }; Fx.Transitions.extend({ Pow: function(p, x){ return Math.pow(p, x && x[0] || 6); }, Expo: function(p){ return Math.pow(2, 8 * (p - 1)); }, Circ: function(p){ return 1 - Math.sin(Math.acos(p)); }, Sine: function(p){ return 1 - Math.cos(p * Math.PI / 2); }, Back: function(p, x){ x = x && x[0] || 1.618; return Math.pow(p, 2) * ((x + 1) * p - x); }, Bounce: function(p){ var value; for (var a = 0, b = 1; 1; a += b, b /= 2){ if (p >= (7 - 4 * a) / 11){ value = b * b - Math.pow((11 - 6 * a - 11 * p) / 4, 2); break; } } return value; }, Elastic: function(p, x){ return Math.pow(2, 10 * --p) * Math.cos(20 * p * Math.PI * (x && x[0] || 1) / 3); } }); ['Quad', 'Cubic', 'Quart', 'Quint'].each(function(transition, i){ Fx.Transitions[transition] = new Fx.Transition(function(p){ return Math.pow(p, i + 2); }); }); /* --- name: Request description: Powerful all purpose Request Class. Uses XMLHTTPRequest. license: MIT-style license. requires: [Object, Element, Chain, Events, Options, Browser] provides: Request ... */ (function(){ var empty = function(){}, progressSupport = ('onprogress' in new Browser.Request); var Request = this.Request = new Class({ Implements: [Chain, Events, Options], options: {/* onRequest: function(){}, onLoadstart: function(event, xhr){}, onProgress: function(event, xhr){}, onUploadProgress: function(event, xhr){}, onComplete: function(){}, onCancel: function(){}, onSuccess: function(responseText, responseXML){}, onFailure: function(xhr){}, onException: function(headerName, value){}, onTimeout: function(){}, user: '', password: '',*/ url: '', data: '', processData: true, responseType: null, headers: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'text/javascript, text/html, application/xml, text/xml, */*' }, async: true, format: false, method: 'post', link: 'ignore', isSuccess: null, emulation: true, urlEncoded: true, encoding: 'utf-8', evalScripts: false, evalResponse: false, timeout: 0, noCache: false }, initialize: function(options){ this.xhr = new Browser.Request(); this.setOptions(options); if ((typeof ArrayBuffer != 'undefined' && options.data instanceof ArrayBuffer) || (typeof Blob != 'undefined' && options.data instanceof Blob) || (typeof Uint8Array != 'undefined' && options.data instanceof Uint8Array)){ // set data in directly if we're passing binary data because // otherwise setOptions will convert the data into an empty object this.options.data = options.data; } this.headers = this.options.headers; }, onStateChange: function(){ var xhr = this.xhr; if (xhr.readyState != 4 || !this.running) return; this.running = false; this.status = 0; Function.attempt(function(){ var status = xhr.status; this.status = (status == 1223) ? 204 : status; }.bind(this)); xhr.onreadystatechange = empty; if (progressSupport) xhr.onprogress = xhr.onloadstart = empty; clearTimeout(this.timer); this.response = {text: (!this.options.responseType && this.xhr.responseText) || '', xml: (!this.options.responseType && this.xhr.responseXML)}; if (this.options.isSuccess.call(this, this.status)) this.success(this.options.responseType ? this.xhr.response : this.response.text, this.response.xml); else this.failure(); }, isSuccess: function(){ var status = this.status; return (status >= 200 && status < 300); }, isRunning: function(){ return !!this.running; }, processScripts: function(text){ if (typeof text != 'string') return text; if (this.options.evalResponse || (/(ecma|java)script/).test(this.getHeader('Content-type'))) return Browser.exec(text); return text.stripScripts(this.options.evalScripts); }, success: function(text, xml){ this.onSuccess(this.processScripts(text), xml); }, onSuccess: function(){ this.fireEvent('complete', arguments).fireEvent('success', arguments).callChain(); }, failure: function(){ this.onFailure(); }, onFailure: function(){ this.fireEvent('complete').fireEvent('failure', this.xhr); }, loadstart: function(event){ this.fireEvent('loadstart', [event, this.xhr]); }, progress: function(event){ this.fireEvent('progress', [event, this.xhr]); }, uploadprogress: function(event){ this.fireEvent('uploadprogress', [event, this.xhr]); }, timeout: function(){ this.fireEvent('timeout', this.xhr); }, setHeader: function(name, value){ this.headers[name] = value; return this; }, getHeader: function(name){ return Function.attempt(function(){ return this.xhr.getResponseHeader(name); }.bind(this)); }, check: function(){ if (!this.running) return true; switch (this.options.link){ case 'cancel': this.cancel(); return true; case 'chain': this.chain(this.caller.pass(arguments, this)); return false; } return false; }, send: function(options){ if (!this.check(options)) return this; this.options.isSuccess = this.options.isSuccess || this.isSuccess; this.running = true; var type = typeOf(options); if (type == 'string' || type == 'element') options = {data: options}; var old = this.options; options = Object.append({data: old.data, url: old.url, method: old.method}, options); var data = options.data, url = String(options.url), method = options.method.toLowerCase(); if (this.options.processData || method == 'get' || method == 'delete'){ switch (typeOf(data)){ case 'element': data = document.id(data).toQueryString(); break; case 'object': case 'hash': data = Object.toQueryString(data); } if (this.options.format){ var format = 'format=' + this.options.format; data = (data) ? format + '&' + data : format; } if (this.options.emulation && !['get', 'post'].contains(method)){ var _method = '_method=' + method; data = (data) ? _method + '&' + data : _method; method = 'post'; } } if (this.options.urlEncoded && ['post', 'put'].contains(method)){ var encoding = (this.options.encoding) ? '; charset=' + this.options.encoding : ''; this.headers['Content-type'] = 'application/x-www-form-urlencoded' + encoding; } if (!url) url = document.location.pathname; var trimPosition = url.lastIndexOf('/'); if (trimPosition > -1 && (trimPosition = url.indexOf('#')) > -1) url = url.substr(0, trimPosition); if (this.options.noCache) url += (url.contains('?') ? '&' : '?') + String.uniqueID(); if (data && method == 'get'){ url += (url.contains('?') ? '&' : '?') + data; data = null; } var xhr = this.xhr; if (progressSupport){ xhr.onloadstart = this.loadstart.bind(this); xhr.onprogress = this.progress.bind(this); if(xhr.upload) xhr.upload.onprogress = this.uploadprogress.bind(this); } xhr.open(method.toUpperCase(), url, this.options.async, this.options.user, this.options.password); if (this.options.user && 'withCredentials' in xhr) xhr.withCredentials = true; xhr.onreadystatechange = this.onStateChange.bind(this); Object.each(this.headers, function(value, key){ try { xhr.setRequestHeader(key, value); } catch (e){ this.fireEvent('exception', [key, value]); } }, this); if (this.options.responseType){ xhr.responseType = this.options.responseType.toLowerCase(); } this.fireEvent('request'); xhr.send(data); if (!this.options.async) this.onStateChange(); else if (this.options.timeout) this.timer = this.timeout.delay(this.options.timeout, this); return this; }, cancel: function(){ if (!this.running) return this; this.running = false; var xhr = this.xhr; xhr.abort(); clearTimeout(this.timer); xhr.onreadystatechange = empty; if (progressSupport) xhr.onprogress = xhr.onloadstart = empty; this.xhr = new Browser.Request(); this.fireEvent('cancel'); return this; } }); var methods = {}; ['get', 'post', 'put', 'delete', 'GET', 'POST', 'PUT', 'DELETE'].each(function(method){ methods[method] = function(data){ var object = { method: method }; if (data != null) object.data = data; return this.send(object); }; }); Request.implement(methods); Element.Properties.send = { set: function(options){ var send = this.get('send').cancel(); send.setOptions(options); return this; }, get: function(){ var send = this.retrieve('send'); if (!send){ send = new Request({ data: this, link: 'cancel', method: this.get('method') || 'post', url: this.get('action') }); this.store('send', send); } return send; } }; Element.implement({ send: function(url){ var sender = this.get('send'); sender.send({data: this, url: url || sender.options.url}); return this; } }); })(); /* --- name: Request.HTML description: Extends the basic Request Class with additional methods for interacting with HTML responses. license: MIT-style license. requires: [Element, Request] provides: Request.HTML ... */ Request.HTML = new Class({ Extends: Request, options: { update: false, append: false, evalScripts: true, filter: false, headers: { Accept: 'text/html, application/xml, text/xml, */*' } }, success: function(text){ var options = this.options, response = this.response; response.html = text.stripScripts(function(script){ response.javascript = script; }); var match = response.html.match(/<body[^>]*>([\s\S]*?)<\/body>/i); if (match) response.html = match[1]; var temp = new Element('div').set('html', response.html); response.tree = temp.childNodes; response.elements = temp.getElements(options.filter || '*'); if (options.filter) response.tree = response.elements; if (options.update){ var update = document.id(options.update).empty(); if (options.filter) update.adopt(response.elements); else update.set('html', response.html); } else if (options.append){ var append = document.id(options.append); if (options.filter) response.elements.reverse().inject(append); else append.adopt(temp.getChildren()); } if (options.evalScripts) Browser.exec(response.javascript); this.onSuccess(response.tree, response.elements, response.html, response.javascript); } }); Element.Properties.load = { set: function(options){ var load = this.get('load').cancel(); load.setOptions(options); return this; }, get: function(){ var load = this.retrieve('load'); if (!load){ load = new Request.HTML({data: this, link: 'cancel', update: this, method: 'get'}); this.store('load', load); } return load; } }; Element.implement({ load: function(){ this.get('load').send(Array.link(arguments, {data: Type.isObject, url: Type.isString})); return this; } }); /* --- name: JSON description: JSON encoder and decoder. license: MIT-style license. SeeAlso: <http://www.json.org/> requires: [Array, String, Number, Function] provides: JSON ... */ if (typeof JSON == 'undefined') this.JSON = {}; (function(){ var special = {'\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\'}; var escape = function(chr){ return special[chr] || '\\u' + ('0000' + chr.charCodeAt(0).toString(16)).slice(-4); }; JSON.validate = function(string){ string = string.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@'). replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']'). replace(/(?:^|:|,)(?:\s*\[)+/g, ''); return (/^[\],:{}\s]*$/).test(string); }; JSON.encode = JSON.stringify ? function(obj){ return JSON.stringify(obj); } : function(obj){ if (obj && obj.toJSON) obj = obj.toJSON(); switch (typeOf(obj)){ case 'string': return '"' + obj.replace(/[\x00-\x1f\\"]/g, escape) + '"'; case 'array': return '[' + obj.map(JSON.encode).clean() + ']'; case 'object': case 'hash': var string = []; Object.each(obj, function(value, key){ var json = JSON.encode(value); if (json) string.push(JSON.encode(key) + ':' + json); }); return '{' + string + '}'; case 'number': case 'boolean': return '' + obj; case 'null': return 'null'; } return null; }; JSON.decode = function(string, secure){ if (!string || typeOf(string) != 'string') return null; if (secure || JSON.secure){ if (JSON.parse) return JSON.parse(string); if (!JSON.validate(string)) throw new Error('JSON could not decode the input; security is enabled and the value is not secure.'); } return eval('(' + string + ')'); }; })(); /* --- name: Request.JSON description: Extends the basic Request Class with additional methods for sending and receiving JSON data. license: MIT-style license. requires: [Request, JSON] provides: Request.JSON ... */ Request.JSON = new Class({ Extends: Request, options: { /*onError: function(text, error){},*/ secure: true }, initialize: function(options){ this.parent(options); Object.append(this.headers, { 'Accept': 'application/json', 'X-Request': 'JSON' }); }, success: function(text){ var json; try { json = this.response.json = JSON.decode(text, this.options.secure); } catch (error){ this.fireEvent('error', [text, error]); return; } if (json == null) this.onFailure(); else this.onSuccess(json, text); } }); /* --- name: Cookie description: Class for creating, reading, and deleting browser Cookies. license: MIT-style license. credits: - Based on the functions by Peter-Paul Koch (http://quirksmode.org). requires: [Options, Browser] provides: Cookie ... */ var Cookie = new Class({ Implements: Options, options: { path: '/', domain: false, duration: false, secure: false, document: document, encode: true }, initialize: function(key, options){ this.key = key; this.setOptions(options); }, write: function(value){ if (this.options.encode) value = encodeURIComponent(value); if (this.options.domain) value += '; domain=' + this.options.domain; if (this.options.path) value += '; path=' + this.options.path; if (this.options.duration){ var date = new Date(); date.setTime(date.getTime() + this.options.duration * 24 * 60 * 60 * 1000); value += '; expires=' + date.toGMTString(); } if (this.options.secure) value += '; secure'; this.options.document.cookie = this.key + '=' + value; return this; }, read: function(){ var value = this.options.document.cookie.match('(?:^|;)\\s*' + this.key.escapeRegExp() + '=([^;]*)'); return (value) ? decodeURIComponent(value[1]) : null; }, dispose: function(){ new Cookie(this.key, Object.merge({}, this.options, {duration: -1})).write(''); return this; } }); Cookie.write = function(key, value, options){ return new Cookie(key, options).write(value); }; Cookie.read = function(key){ return new Cookie(key).read(); }; Cookie.dispose = function(key, options){ return new Cookie(key, options).dispose(); }; /* --- name: DOMReady description: Contains the custom event domready. license: MIT-style license. requires: [Browser, Element, Element.Event] provides: [DOMReady, DomReady] ... */ (function(window, document){ var ready, loaded, checks = [], shouldPoll, timer, testElement = document.createElement('div'); var domready = function(){ clearTimeout(timer); if (ready) return; Browser.loaded = ready = true; document.removeListener('DOMContentLoaded', domready).removeListener('readystatechange', check); document.fireEvent('domready'); window.fireEvent('domready'); }; var check = function(){ for (var i = checks.length; i--;) if (checks[i]()){ domready(); return true; } return false; }; var poll = function(){ clearTimeout(timer); if (!check()) timer = setTimeout(poll, 10); }; document.addListener('DOMContentLoaded', domready); /*<ltIE8>*/ // doScroll technique by Diego Perini http://javascript.nwbox.com/IEContentLoaded/ // testElement.doScroll() throws when the DOM is not ready, only in the top window var doScrollWorks = function(){ try { testElement.doScroll(); return true; } catch (e){} return false; }; // If doScroll works already, it can't be used to determine domready // e.g. in an iframe if (testElement.doScroll && !doScrollWorks()){ checks.push(doScrollWorks); shouldPoll = true; } /*</ltIE8>*/ if (document.readyState) checks.push(function(){ var state = document.readyState; return (state == 'loaded' || state == 'complete'); }); if ('onreadystatechange' in document) document.addListener('readystatechange', check); else shouldPoll = true; if (shouldPoll) poll(); Element.Events.domready = { onAdd: function(fn){ if (ready) fn.call(this); } }; // Make sure that domready fires before load Element.Events.load = { base: 'load', onAdd: function(fn){ if (loaded && this == window) fn.call(this); }, condition: function(){ if (this == window){ domready(); delete Element.Events.load; } return true; } }; // This is based on the custom load event window.addEvent('load', function(){ loaded = true; }); })(window, document);<|fim▁end|>
<|file_name|>nova.py<|end_file_name|><|fim▁begin|># Copyright 2013: Mirantis Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_config import cfg OPTS = {"benchmark": [ # prepoll delay, timeout, poll interval # "start": (0, 300, 1) cfg.FloatOpt("nova_server_%s_prepoll_delay" % "start", default=float(0), help="Time to sleep after %s before polling" " for status" % "start"), cfg.FloatOpt("nova_server_%s_timeout" % "start", default=float(300), help="Server %s timeout" % "start"), cfg.FloatOpt("nova_server_%s_poll_interval" % "start", default=float(1), help="Server %s poll interval" % "start"), # "stop": (0, 300, 2) cfg.FloatOpt("nova_server_%s_prepoll_delay" % "stop", default=float(0), help="Time to sleep after %s before polling" " for status" % "stop"), cfg.FloatOpt("nova_server_%s_timeout" % "stop", default=float(300), help="Server %s timeout" % "stop"), cfg.FloatOpt("nova_server_%s_poll_interval" % "stop", default=float(2), help="Server %s poll interval" % "stop"), # "boot": (1, 300, 1) cfg.FloatOpt("nova_server_%s_prepoll_delay" % "boot", default=float(1), help="Time to sleep after %s before polling" " for status" % "boot"), cfg.FloatOpt("nova_server_%s_timeout" % "boot", default=float(300), help="Server %s timeout" % "boot"), cfg.FloatOpt("nova_server_%s_poll_interval" % "boot", default=float(2), help="Server %s poll interval" % "boot"), # "delete": (2, 300, 2) cfg.FloatOpt("nova_server_%s_prepoll_delay" % "delete", default=float(2), help="Time to sleep after %s before polling" " for status" % "delete"),<|fim▁hole|> cfg.FloatOpt("nova_server_%s_timeout" % "delete", default=float(300), help="Server %s timeout" % "delete"), cfg.FloatOpt("nova_server_%s_poll_interval" % "delete", default=float(2), help="Server %s poll interval" % "delete"), # "reboot": (2, 300, 2) cfg.FloatOpt("nova_server_%s_prepoll_delay" % "reboot", default=float(2), help="Time to sleep after %s before polling" " for status" % "reboot"), cfg.FloatOpt("nova_server_%s_timeout" % "reboot", default=float(300), help="Server %s timeout" % "reboot"), cfg.FloatOpt("nova_server_%s_poll_interval" % "reboot", default=float(2), help="Server %s poll interval" % "reboot"), # "rebuild": (1, 300, 1) cfg.FloatOpt("nova_server_%s_prepoll_delay" % "rebuild", default=float(1), help="Time to sleep after %s before polling" " for status" % "rebuild"), cfg.FloatOpt("nova_server_%s_timeout" % "rebuild", default=float(300), help="Server %s timeout" % "rebuild"), cfg.FloatOpt("nova_server_%s_poll_interval" % "rebuild", default=float(1), help="Server %s poll interval" % "rebuild"), # "rescue": (2, 300, 2) cfg.FloatOpt("nova_server_%s_prepoll_delay" % "rescue", default=float(2), help="Time to sleep after %s before polling" " for status" % "rescue"), cfg.FloatOpt("nova_server_%s_timeout" % "rescue", default=float(300), help="Server %s timeout" % "rescue"), cfg.FloatOpt("nova_server_%s_poll_interval" % "rescue", default=float(2), help="Server %s poll interval" % "rescue"), # "unrescue": (2, 300, 2) cfg.FloatOpt("nova_server_%s_prepoll_delay" % "unrescue", default=float(2), help="Time to sleep after %s before polling" " for status" % "unrescue"), cfg.FloatOpt("nova_server_%s_timeout" % "unrescue", default=float(300), help="Server %s timeout" % "unrescue"), cfg.FloatOpt("nova_server_%s_poll_interval" % "unrescue", default=float(2), help="Server %s poll interval" % "unrescue"), # "suspend": (2, 300, 2) cfg.FloatOpt("nova_server_%s_prepoll_delay" % "suspend", default=float(2), help="Time to sleep after %s before polling" " for status" % "suspend"), cfg.FloatOpt("nova_server_%s_timeout" % "suspend", default=float(300), help="Server %s timeout" % "suspend"), cfg.FloatOpt("nova_server_%s_poll_interval" % "suspend", default=float(2), help="Server %s poll interval" % "suspend"), # "resume": (2, 300, 2) cfg.FloatOpt("nova_server_%s_prepoll_delay" % "resume", default=float(2), help="Time to sleep after %s before polling" " for status" % "resume"), cfg.FloatOpt("nova_server_%s_timeout" % "resume", default=float(300), help="Server %s timeout" % "resume"), cfg.FloatOpt("nova_server_%s_poll_interval" % "resume", default=float(2), help="Server %s poll interval" % "resume"), # "pause": (2, 300, 2) cfg.FloatOpt("nova_server_%s_prepoll_delay" % "pause", default=float(2), help="Time to sleep after %s before polling" " for status" % "pause"), cfg.FloatOpt("nova_server_%s_timeout" % "pause", default=float(300), help="Server %s timeout" % "pause"), cfg.FloatOpt("nova_server_%s_poll_interval" % "pause", default=float(2), help="Server %s poll interval" % "pause"), # "unpause": (2, 300, 2) cfg.FloatOpt("nova_server_%s_prepoll_delay" % "unpause", default=float(2), help="Time to sleep after %s before polling" " for status" % "unpause"), cfg.FloatOpt("nova_server_%s_timeout" % "unpause", default=float(300), help="Server %s timeout" % "unpause"), cfg.FloatOpt("nova_server_%s_poll_interval" % "unpause", default=float(2), help="Server %s poll interval" % "unpause"), # "shelve": (2, 300, 2) cfg.FloatOpt("nova_server_%s_prepoll_delay" % "shelve", default=float(2), help="Time to sleep after %s before polling" " for status" % "shelve"), cfg.FloatOpt("nova_server_%s_timeout" % "shelve", default=float(300), help="Server %s timeout" % "shelve"), cfg.FloatOpt("nova_server_%s_poll_interval" % "shelve", default=float(2), help="Server %s poll interval" % "shelve"), # "unshelve": (2, 300, 2) cfg.FloatOpt("nova_server_%s_prepoll_delay" % "unshelve", default=float(2), help="Time to sleep after %s before polling" " for status" % "unshelve"), cfg.FloatOpt("nova_server_%s_timeout" % "unshelve", default=float(300), help="Server %s timeout" % "unshelve"), cfg.FloatOpt("nova_server_%s_poll_interval" % "unshelve", default=float(2), help="Server %s poll interval" % "unshelve"), # "image_create": (0, 300, 2) cfg.FloatOpt("nova_server_%s_prepoll_delay" % "image_create", default=float(0), help="Time to sleep after %s before polling" " for status" % "image_create"), cfg.FloatOpt("nova_server_%s_timeout" % "image_create", default=float(300), help="Server %s timeout" % "image_create"), cfg.FloatOpt("nova_server_%s_poll_interval" % "image_create", default=float(2), help="Server %s poll interval" % "image_create"), # "image_delete": (0, 300, 2) cfg.FloatOpt("nova_server_%s_prepoll_delay" % "image_delete", default=float(0), help="Time to sleep after %s before polling" " for status" % "image_delete"), cfg.FloatOpt("nova_server_%s_timeout" % "image_delete", default=float(300), help="Server %s timeout" % "image_delete"), cfg.FloatOpt("nova_server_%s_poll_interval" % "image_delete", default=float(2), help="Server %s poll interval" % "image_delete"), # "resize": (2, 400, 5) cfg.FloatOpt("nova_server_%s_prepoll_delay" % "resize", default=float(2), help="Time to sleep after %s before polling" " for status" % "resize"), cfg.FloatOpt("nova_server_%s_timeout" % "resize", default=float(400), help="Server %s timeout" % "resize"), cfg.FloatOpt("nova_server_%s_poll_interval" % "resize", default=float(5), help="Server %s poll interval" % "resize"), # "resize_confirm": (0, 200, 2) cfg.FloatOpt("nova_server_%s_prepoll_delay" % "resize_confirm", default=float(0), help="Time to sleep after %s before polling" " for status" % "resize_confirm"), cfg.FloatOpt("nova_server_%s_timeout" % "resize_confirm", default=float(200), help="Server %s timeout" % "resize_confirm"), cfg.FloatOpt("nova_server_%s_poll_interval" % "resize_confirm", default=float(2), help="Server %s poll interval" % "resize_confirm"), # "resize_revert": (0, 200, 2) cfg.FloatOpt("nova_server_%s_prepoll_delay" % "resize_revert", default=float(0), help="Time to sleep after %s before polling" " for status" % "resize_revert"), cfg.FloatOpt("nova_server_%s_timeout" % "resize_revert", default=float(200), help="Server %s timeout" % "resize_revert"), cfg.FloatOpt("nova_server_%s_poll_interval" % "resize_revert", default=float(2), help="Server %s poll interval" % "resize_revert"), # "live_migrate": (1, 400, 2) cfg.FloatOpt("nova_server_%s_prepoll_delay" % "live_migrate", default=float(1), help="Time to sleep after %s before polling" " for status" % "live_migrate"), cfg.FloatOpt("nova_server_%s_timeout" % "live_migrate", default=float(400), help="Server %s timeout" % "live_migrate"), cfg.FloatOpt("nova_server_%s_poll_interval" % "live_migrate", default=float(2), help="Server %s poll interval" % "live_migrate"), # "migrate": (1, 400, 2) cfg.FloatOpt("nova_server_%s_prepoll_delay" % "migrate", default=float(1), help="Time to sleep after %s before polling" " for status" % "migrate"), cfg.FloatOpt("nova_server_%s_timeout" % "migrate", default=float(400), help="Server %s timeout" % "migrate"), cfg.FloatOpt("nova_server_%s_poll_interval" % "migrate", default=float(2), help="Server %s poll interval" % "migrate"), # "detach": cfg.FloatOpt("nova_detach_volume_timeout", default=float(200), help="Nova volume detach timeout"), cfg.FloatOpt("nova_detach_volume_poll_interval", default=float(2), help="Nova volume detach poll interval") ]}<|fim▁end|>
<|file_name|>test_unit_gpcheckcat.py<|end_file_name|><|fim▁begin|>import imp import logging import os import sys from mock import * from .gp_unittest import * from gppylib.gpcatalog import GPCatalogTable class GpCheckCatTestCase(GpTestCase): def setUp(self): # because gpcheckcat does not have a .py extension, we have to use imp to import it # if we had a gpcheckcat.py, this is equivalent to: # import gpcheckcat # self.subject = gpcheckcat gpcheckcat_file = os.path.abspath(os.path.dirname(__file__) + "/../../../gpcheckcat") self.subject = imp.load_source('gpcheckcat', gpcheckcat_file) self.subject.check_gpexpand = lambda : (True, "") self.db_connection = Mock(spec=['close', 'query']) self.unique_index_violation_check = Mock(spec=['runCheck']) self.foreign_key_check = Mock(spec=['runCheck', 'checkTableForeignKey']) self.apply_patches([ patch("gpcheckcat.pg.connect", return_value=self.db_connection), patch("gpcheckcat.UniqueIndexViolationCheck", return_value=self.unique_index_violation_check), patch("gpcheckcat.ForeignKeyCheck", return_value=self.foreign_key_check), patch('os.environ', new={}), ]) self.subject.logger = Mock(spec=['log', 'info', 'debug', 'error', 'fatal']) self.unique_index_violation_check.runCheck.return_value = [] self.leaked_schema_dropper = Mock(spec=['drop_leaked_schemas']) self.leaked_schema_dropper.drop_leaked_schemas.return_value = [] issues_list = dict() issues_list['cat1'] = [('pg_class', ['pkey1', 'pkey2'], [('r1', 'r2'), ('r3', 'r4')]), ('arbitrary_catalog_table', ['pkey1', 'pkey2'], [('r1', 'r2'), ('r3', 'r4')])] issues_list['cat2'] = [('pg_type', ['pkey1', 'pkey2'], [('r1', 'r2'), ('r3', 'r4')]), ('arbitrary_catalog_table', ['pkey1', 'pkey2'], [('r1', 'r2'), ('r3', 'r4')])] self.foreign_key_check.runCheck.return_value = issues_list self.subject.GV.coordinator_dbid = 0 self.subject.GV.cfg = {0:dict(hostname='host0', port=123, id=1, address='123', datadir='dir', content=-1, dbid=0), 1:dict(hostname='host1', port=123, id=1, address='123', datadir='dir', content=1, dbid=1)} self.subject.GV.checkStatus = True self.subject.GV.foreignKeyStatus = True self.subject.GV.missingEntryStatus = True self.subject.setError = Mock() self.subject.print_repair_issues = Mock() def test_running_unknown_check__raises_exception(self): with self.assertRaises(LookupError): self.subject.runOneCheck('some_unknown_check') # @skip("order of checks") # def test_run_all_checks__runs_all_checks_in_correct_order(self): # self.subject.runAllChecks() # # self.unique_index_violation_check.runCheck.assert_any_call(self.db_connection) # # add other checks here # # figure out how to enforce the order of calls; # # at a minimum, check the order number of the static list gpcheckcat.all_checks def test_running_unique_index_violation_check__makes_the_check(self): self.subject.runOneCheck('unique_index_violation') self.unique_index_violation_check.runCheck.assert_called_with(self.db_connection) def test_running_unique_index_violation_check__when_no_violations_are_found__passes_the_check(self): self.subject.runOneCheck('unique_index_violation') self.assertTrue(self.subject.GV.checkStatus) self.subject.setError.assert_not_called() def test_running_unique_index_violation_check__when_violations_are_found__fails_the_check(self): self.unique_index_violation_check.runCheck.return_value = [ dict(table_oid=123, table_name='stephen_table', index_name='finger', column_names='c1, c2', violated_segments=[-1,8]), dict(table_oid=456, table_name='larry_table', index_name='stock', column_names='c1', violated_segments=[-1]), ] self.subject.runOneCheck('unique_index_violation') self.assertFalse(self.subject.GV.checkStatus) self.subject.setError.assert_any_call(self.subject.ERROR_NOREPAIR) def test_checkcat_report__after_running_unique_index_violations_check__reports_violations(self): self.unique_index_violation_check.runCheck.return_value = [ dict(table_oid=123, table_name='stephen_table', index_name='finger', column_names='c1, c2', violated_segments=[-1,8]), dict(table_oid=456, table_name='larry_table', index_name='stock', column_names='c1', violated_segments=[-1]), ] self.subject.runOneCheck('unique_index_violation') self.subject.checkcatReport() expected_message1 = ' Table stephen_table has a violated unique index: finger' expected_message2 = ' Table larry_table has a violated unique index: stock' log_messages = [args[0][1] for args in self.subject.logger.log.call_args_list] self.assertIn(expected_message1, log_messages) self.assertIn(expected_message2, log_messages) def test_drop_leaked_schemas__when_no_leaked_schemas_exist__passes_gpcheckcat(self): self.subject.drop_leaked_schemas(self.leaked_schema_dropper, self.db_connection) self.subject.setError.assert_not_called() def test_drop_leaked_schemas____when_leaked_schemas_exist__finds_and_drops_leaked_schemas(self): self.leaked_schema_dropper.drop_leaked_schemas.return_value = ['schema1', 'schema2'] self.subject.drop_leaked_schemas(self.leaked_schema_dropper, self.db_connection) self.leaked_schema_dropper.drop_leaked_schemas.assert_called_once_with(self.db_connection) def test_drop_leaked_schemas__when_leaked_schemas_exist__passes_gpcheckcat(self): self.leaked_schema_dropper.drop_leaked_schemas.return_value = ['schema1', 'schema2'] self.subject.drop_leaked_schemas(self.leaked_schema_dropper, self.db_connection) self.subject.setError.assert_not_called() def test_drop_leaked_schemas__when_leaked_schemas_exist__reports_which_schemas_are_dropped(self): self.leaked_schema_dropper.drop_leaked_schemas.return_value = ['schema1', 'schema2'] self.subject.drop_leaked_schemas(self.leaked_schema_dropper, "some_db_name") expected_message = "Found and dropped 2 unbound temporary schemas" log_messages = [args[0][1] for args in self.subject.logger.log.call_args_list] self.assertIn(expected_message, log_messages) def test_automatic_thread_count(self): self.db_connection.query.return_value.getresult.return_value = [[0]] self._run_batch_size_experiment(100) self._run_batch_size_experiment(101) @patch('gpcheckcat.GPCatalog', return_value=Mock()) @patch('sys.exit') @patch('gppylib.gplog.log_literal') def test_truncate_batch_size(self, mock_log, mock_gpcheckcat, mock_sys_exit): self.subject.GV.opt['-B'] = 300 # override the setting from available memory # setup conditions for 50 primaries and plenty of RAM such that max threads > 50 primaries = [dict(hostname='host0', port=123, id=1, address='123', datadir='dir', content=-1, dbid=0, isprimary='t')] for i in range(1, 50): primaries.append(dict(hostname='host0', port=123, id=1, address='123', datadir='dir', content=1, dbid=i, isprimary='t')) self.db_connection.query.return_value.getresult.return_value = [['4.3']] self.db_connection.query.return_value.dictresult.return_value = primaries testargs = ['some_string','-port 1', '-R foo'] # GOOD_MOCK_EXAMPLE for testing functionality in "__main__": put all code inside a method "main()", # which can then be mocked as necessary. with patch.object(sys, 'argv', testargs): self.subject.main() self.assertEqual(self.subject.GV.opt['-B'], len(primaries)) #mock_log.assert_any_call(50, "Truncated batch size to number of primaries: 50") # I am confused that .assert_any_call() did not seem to work as expected --Larry last_call = mock_log.call_args_list[0][0][2] self.assertEqual(last_call, "Truncated batch size to number of primaries: 50") @patch('gpcheckcat_modules.repair.Repair', return_value=Mock()) @patch('gpcheckcat_modules.repair.Repair.create_repair_for_extra_missing', return_value="/tmp") def test_do_repair_for_extra__issues_repair(self, mock1, mock2): issues = {("pg_class", "oid"):"extra"} self.subject.GV.opt['-E'] = True self.subject.do_repair_for_extra(issues) self.subject.setError.assert_any_call(self.subject.ERROR_REMOVE) self.subject.print_repair_issues.assert_any_call("/tmp") @patch('gpcheckcat.removeFastSequence') @patch('gpcheckcat.processForeignKeyResult')<|fim▁hole|> gp_fastsequence_issue = dict() gp_fastsequence_issue['gp_fastsequence'] = [('pg_class', ['pkey1', 'pkey2'], [('r1', 'r2'), ('r3', 'r4')]), ('arbitrary_catalog_table', ['pkey1', 'pkey2'], [('r1', 'r2'), ('r3', 'r4')])] gp_fastsequence_issue['cat2'] = [('pg_type', ['pkey1', 'pkey2'], [('r1', 'r2'), ('r3', 'r4')]), ('arbitrary_catalog_table', ['pkey1', 'pkey2'], [('r1', 'r2'), ('r3', 'r4')])] self.foreign_key_check.runCheck.return_value = gp_fastsequence_issue cat_tables = ["input1", "input2"] self.subject.checkForeignKey(cat_tables) self.assertEqual(cat_mock.getCatalogTables.call_count, 0) self.assertFalse(self.subject.GV.checkStatus) self.assertTrue(self.subject.GV.foreignKeyStatus) self.subject.setError.assert_any_call(self.subject.ERROR_REMOVE) self.foreign_key_check.runCheck.assert_called_once_with(cat_tables) fast_seq_mock.assert_called_once_with(self.db_connection) @patch('gpcheckcat.processForeignKeyResult') def test_checkForeignKey__with_arg(self, process_foreign_key_mock): cat_mock = Mock() self.subject.GV.catalog = cat_mock cat_tables = ["input1", "input2"] self.subject.checkForeignKey(cat_tables) self.assertEqual(cat_mock.getCatalogTables.call_count, 0) self.assertFalse(self.subject.GV.checkStatus) self.assertTrue(self.subject.GV.foreignKeyStatus) self.subject.setError.assert_any_call(self.subject.ERROR_NOREPAIR) self.foreign_key_check.runCheck.assert_called_once_with(cat_tables) @patch('gpcheckcat.processForeignKeyResult') def test_checkForeignKey__no_arg(self, process_foreign_key_mock): cat_mock = Mock(spec=['getCatalogTables']) cat_tables = ["input1", "input2"] cat_mock.getCatalogTables.return_value = cat_tables self.subject.GV.catalog = cat_mock self.subject.checkForeignKey() self.assertEqual(cat_mock.getCatalogTables.call_count, 1) self.assertFalse(self.subject.GV.checkStatus) self.assertTrue(self.subject.GV.foreignKeyStatus) self.subject.setError.assert_any_call(self.subject.ERROR_NOREPAIR) self.foreign_key_check.runCheck.assert_called_once_with(cat_tables) # Test gpcheckat -C option with checkForeignKey @patch('gpcheckcat.GPCatalog', return_value=Mock()) @patch('sys.exit') @patch('gpcheckcat.checkTableMissingEntry') def test_runCheckCatname__for_checkForeignKey(self, mock1, mock2, mock3): self.subject.checkForeignKey = Mock() gpcat_class_mock = Mock(spec=['getCatalogTable']) cat_obj_mock = Mock() self.subject.getCatObj = gpcat_class_mock self.subject.getCatObj.return_value = cat_obj_mock primaries = [dict(hostname='host0', port=123, id=1, address='123', datadir='dir', content=-1, dbid=0, isprimary='t')] for i in range(1, 50): primaries.append(dict(hostname='host0', port=123, id=1, address='123', datadir='dir', content=1, dbid=i, isprimary='t')) self.db_connection.query.return_value.getresult.return_value = [['4.3']] self.db_connection.query.return_value.dictresult.return_value = primaries self.subject.GV.opt['-C'] = 'pg_class' testargs = ['gpcheckcat', '-port 1', '-C pg_class'] with patch.object(sys, 'argv', testargs): self.subject.main() self.subject.getCatObj.assert_called_once_with(' pg_class') self.subject.checkForeignKey.assert_called_once_with([cat_obj_mock]) @patch('gpcheckcat.checkTableMissingEntry', return_value = None) def test_checkMissingEntry__no_issues(self, mock1): cat_mock = Mock() cat_tables = ["input1", "input2"] cat_mock.getCatalogTables.return_value = cat_tables self.subject.GV.catalog = cat_mock self.subject.runOneCheck("missing_extraneous") self.assertTrue(self.subject.GV.missingEntryStatus) self.subject.setError.assert_not_called() @patch('gpcheckcat.checkTableMissingEntry', return_value= {("pg_clas", "oid"): "extra"}) @patch('gpcheckcat.getPrimaryKeyColumn', return_value = (None,"oid")) def test_checkMissingEntry__uses_oid(self, mock1, mock2): self.subject.GV.opt['-E'] = True aTable = Mock(spec=GPCatalogTable) cat_mock = Mock() cat_mock.getCatalogTables.return_value = [aTable] self.subject.GV.catalog = cat_mock self.subject.runOneCheck("missing_extraneous") self.assertEqual(aTable.getPrimaryKey.call_count, 1) self.subject.setError.assert_called_once_with(self.subject.ERROR_REMOVE) @patch('gpcheckcat.checkTableMissingEntry', return_value= {("pg_operator", "typename, typenamespace"): "extra"}) @patch('gpcheckcat.getPrimaryKeyColumn', return_value = (None,None)) def test_checkMissingEntry__uses_pkeys(self, mock1, mock2): self.subject.GV.opt['-E'] = True aTable = MagicMock(spec=GPCatalogTable) aTable.tableHasConsistentOids.return_value = False cat_mock = Mock() cat_mock.getCatalogTables.return_value = [aTable] self.subject.GV.catalog = cat_mock self.subject.runOneCheck("missing_extraneous") self.assertEqual(aTable.getPrimaryKey.call_count, 1) self.subject.setError.assert_called_once_with(self.subject.ERROR_REMOVE) def test_getReportConfiguration_uses_contentid(self): report_cfg = self.subject.getReportConfiguration() self.assertEqual("content -1", report_cfg[-1]['segname']) def test_RelationObject_reportAllIssues_handles_None_fields(self): uut = self.subject.RelationObject(None, 'pg_class') uut.setRelInfo(relname=None, nspname=None, relkind='t', paroid=0) uut.reportAllIssues() log_messages = [args[0][1].strip() for args in self.subject.logger.log.call_args_list] self.assertIn('Relation oid: N/A', log_messages) self.assertIn('Relation schema: N/A', log_messages) self.assertIn('Relation name: N/A', log_messages) ####################### PRIVATE METHODS ####################### def _run_batch_size_experiment(self, num_primaries): BATCH_SIZE = 4 self.subject.GV.opt['-B'] = BATCH_SIZE self.num_batches = 0 self.num_joins = 0 self.num_starts = 0 self.is_remainder_case = False for i in range(2, num_primaries): self.subject.GV.cfg[i] = dict(hostname='host1', port=123, id=1, address='123', datadir='dir', content=1, dbid=i) def count_starts(): self.num_starts += 1 def count_joins(): if self.num_starts != BATCH_SIZE: self.is_remainder_case = True self.num_joins += 1 if self.num_joins == BATCH_SIZE: self.num_batches += 1 self.num_joins = 0 self.num_starts = 0 if __name__ == '__main__': run_tests()<|fim▁end|>
def test_checkForeignKey__with_arg_gp_fastsequence(self, process_foreign_key_mock,fast_seq_mock): cat_mock = Mock() self.subject.GV.catalog = cat_mock
<|file_name|>StationEquipmentAlarmActionCreators.js<|end_file_name|><|fim▁begin|>// "use strict"; var AppDispatcher = require('../dispatcher/AppDispatcher'); var StationEquipmentAlarmConstants = require('../constants/StationEquipmentAlarmConstants');<|fim▁hole|>var StationEquipmentAlarmActionCreators = { loadDefectData: function(station){ console.assert(station instanceof Station); AppDispatcher.dispatch({ action: StationEquipmentAlarmConstants.ActionTypes.GET_EQUIPMENT_ALARMS, payload: station }); StationEquipmentAlarmsWebApiUtils.getEquipmentAlarms(station); } }; module.exports = StationEquipmentAlarmActionCreators;<|fim▁end|>
var StationEquipmentAlarmsWebApiUtils = require('../webapiutils/StationEquipmentAlarmsWebApiUtils') var Station = require('../domain/Station');
<|file_name|>rotate_matrix.py<|end_file_name|><|fim▁begin|>import unittest def rotate_matrix(matrix): end = len(matrix) - 1 # The index of the last row # Rotating the matrix layer by layer for row in range((end + 1) / 2): for col in range(row, end - row): temp = matrix[row][col] matrix[row][col] = matrix[end - col][row] matrix[end - col][row] = matrix[end - row][end - col] matrix[end - row][end - col] = matrix[col][end - row] matrix[col][end - row] = temp class TestRotateMatrix(unittest.TestCase): def test_empty_matrix(self): matrix = [] rotate_matrix(matrix) self.assertEquals(matrix, []) def test_rotate_matrix_1(self): matrix = [[1]] rotate_matrix(matrix) self.assertEqual(matrix, [[1]]) def test_rotate_matrix_2(self): matrix = [[1, 2], [2, 1]] rotated = [[2, 1], [1, 2]] rotate_matrix(matrix) self.assertEqual(matrix, rotated) def test_rotate_matrix_4(self): matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] rotated = [[13, 9, 5, 1], [14, 10, 6, 2], [15, 11, 7, 3], [16, 12, 8, 4]] rotate_matrix(matrix) self.assertEquals(matrix, rotated) def test_rotate_matrix_6(self): matrix = [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12], [13, 14, 15, 16, 17, 18], [19, 20, 21, 22, 23, 24], [25, 26, 27, 28, 29, 30], [31, 32, 33, 34, 35, 36]] rotated = [[31, 25, 19, 13, 7, 1], [32, 26, 20, 14, 8, 2], [33, 27, 21, 15, 9, 3], [34, 28, 22, 16, 10, 4], [35, 29, 23, 17, 11, 5], [36, 30, 24, 18, 12, 6]] rotate_matrix(matrix) self.assertEquals(matrix, rotated)<|fim▁hole|>if __name__ == '__main__': unittest.main()<|fim▁end|>