code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.metrics; import javax.management.ObjectName; /** * Object that will register an mbean with the underlying metrics implementation. */ public interface MBeanSource { /** * Register an mbean with the underlying metrics system * @param serviceName Metrics service/system name * @param metricsName name of the metrics object to expose * @param theMbean the actual MBean * @return ObjectName from jmx */ ObjectName register(String serviceName, String metricsName, Object theMbean); }
Guavus/hbase
hbase-hadoop-compat/src/main/java/org/apache/hadoop/hbase/metrics/MBeanSource.java
Java
apache-2.0
1,377
import * as browser from './browser'; import * as browserDomAdapter from './browser/browser_adapter'; import * as location from './browser/location/browser_platform_location'; import * as testability from './browser/testability'; import * as ng_probe from './dom/debug/ng_probe'; import * as dom_adapter from './dom/dom_adapter'; import * as dom_renderer from './dom/dom_renderer'; import * as dom_events from './dom/events/dom_events'; import * as hammer_gesture from './dom/events/hammer_gestures'; import * as key_events from './dom/events/key_events'; import * as shared_styles_host from './dom/shared_styles_host'; export declare var __platform_browser_private__: { _BrowserPlatformLocation?: location.BrowserPlatformLocation; BrowserPlatformLocation: typeof location.BrowserPlatformLocation; _DomAdapter?: dom_adapter.DomAdapter; DomAdapter: typeof dom_adapter.DomAdapter; _BrowserDomAdapter?: browserDomAdapter.BrowserDomAdapter; BrowserDomAdapter: typeof browserDomAdapter.BrowserDomAdapter; _BrowserGetTestability?: testability.BrowserGetTestability; BrowserGetTestability: typeof testability.BrowserGetTestability; getDOM: typeof dom_adapter.getDOM; setRootDomAdapter: typeof dom_adapter.setRootDomAdapter; _DomRootRenderer?: dom_renderer.DomRootRenderer; DomRootRenderer: typeof dom_renderer.DomRootRenderer; _DomRootRenderer_?: dom_renderer.DomRootRenderer; DomRootRenderer_: typeof dom_renderer.DomRootRenderer_; _DomSharedStylesHost?: shared_styles_host.DomSharedStylesHost; DomSharedStylesHost: typeof shared_styles_host.DomSharedStylesHost; _SharedStylesHost?: shared_styles_host.SharedStylesHost; SharedStylesHost: typeof shared_styles_host.SharedStylesHost; ELEMENT_PROBE_PROVIDERS: typeof ng_probe.ELEMENT_PROBE_PROVIDERS; _DomEventsPlugin?: dom_events.DomEventsPlugin; DomEventsPlugin: typeof dom_events.DomEventsPlugin; _KeyEventsPlugin?: key_events.KeyEventsPlugin; KeyEventsPlugin: typeof key_events.KeyEventsPlugin; _HammerGesturesPlugin?: hammer_gesture.HammerGesturesPlugin; HammerGesturesPlugin: typeof hammer_gesture.HammerGesturesPlugin; initDomAdapter: typeof browser.initDomAdapter; INTERNAL_BROWSER_PLATFORM_PROVIDERS: typeof browser.INTERNAL_BROWSER_PLATFORM_PROVIDERS; BROWSER_SANITIZATION_PROVIDERS: typeof browser.BROWSER_SANITIZATION_PROVIDERS; };
psumkin/northshore
ui/node_modules/@angular/platform-browser/src/private_export.d.ts
TypeScript
apache-2.0
2,397
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # This helps you preview the apps and extensions docs. # # ./preview.py --help # # There are two modes: server- and render- mode. The default is server, in which # a webserver is started on a port (default 8000). Navigating to paths on # http://localhost:8000, for example # # http://localhost:8000/extensions/tabs.html # # will render the documentation for the extension tabs API. # # On the other hand, render mode statically renders docs to stdout. Use this # to save the output (more convenient than needing to save the page in a # browser), handy when uploading the docs somewhere (e.g. for a review), # and for profiling the server. For example, # # ./preview.py -r extensions/tabs.html # # will output the documentation for the tabs API on stdout and exit immediately. # NOTE: RUN THIS FIRST. Or all third_party imports will fail. import build_server # Copy all the files necessary to run the server. These are cleaned up when the # server quits. build_server.main() from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer import logging import optparse import posixpath import time from local_renderer import LocalRenderer class _RequestHandler(BaseHTTPRequestHandler): '''A HTTPRequestHandler that outputs the docs page generated by Handler. ''' def do_GET(self): # Sanitize path to guarantee that it stays within the server. if not posixpath.abspath(self.path.lstrip('/')).startswith( posixpath.abspath('')): return # Rewrite paths that would otherwise be served from app.yaml. self.path = { '/robots.txt': '../../server2/robots.txt', '/favicon.ico': '../../server2/chrome-32.ico', '/apple-touch-icon-precomposed.png': '../../server2/chrome-128.png' }.get(self.path, self.path) response = LocalRenderer.Render(self.path, headers=dict(self.headers)) self.protocol_version = 'HTTP/1.1' self.send_response(response.status) for k, v in response.headers.iteritems(): self.send_header(k, v) self.end_headers() self.wfile.write(response.content.ToString()) if __name__ == '__main__': parser = optparse.OptionParser( description='Runs a server to preview the extension documentation.', usage='usage: %prog [option]...') parser.add_option('-a', '--address', default='127.0.0.1', help='the local interface address to bind the server to') parser.add_option('-p', '--port', default='8000', help='port to run the server on') parser.add_option('-r', '--render', default='', help='statically render a page and print to stdout rather than starting ' 'the server, e.g. apps/storage.html. The path may optionally end ' 'with #n where n is the number of times to render the page before ' 'printing it, e.g. apps/storage.html#50, to use for profiling.') parser.add_option('-s', '--stat', help='Print profile stats at the end of the run using the given ' 'profiling option (like "tottime"). -t is ignored if this is set.') parser.add_option('-t', '--time', action='store_true', help='Print the time taken rendering rather than the result.') (opts, argv) = parser.parse_args() if opts.render: if opts.render.find('#') >= 0: (path, iterations) = opts.render.rsplit('#', 1) extra_iterations = int(iterations) - 1 else: path = opts.render extra_iterations = 0 if opts.stat: import cProfile, pstats, StringIO pr = cProfile.Profile() pr.enable() elif opts.time: start_time = time.time() response = LocalRenderer.Render(path) if response.status != 200: print('Error status: %s' % response.status) exit(1) for _ in range(extra_iterations): LocalRenderer.Render(path) if opts.stat: pr.disable() s = StringIO.StringIO() pstats.Stats(pr, stream=s).sort_stats(opts.stat).print_stats() print(s.getvalue()) elif opts.time: print('Took %s seconds' % (time.time() - start_time)) else: print(response.content.ToString()) exit() print('Starting previewserver on port %s' % opts.port) print('') print('The extension documentation can be found at:') print('') print(' http://localhost:%s/extensions/' % opts.port) print('') print('The apps documentation can be found at:') print('') print(' http://localhost:%s/apps/' % opts.port) print('') logging.getLogger().setLevel(logging.INFO) server = HTTPServer((opts.address, int(opts.port)), _RequestHandler) try: server.serve_forever() finally: server.socket.close()
ds-hwang/chromium-crosswalk
chrome/common/extensions/docs/server2/preview.py
Python
bsd-3-clause
4,795
/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule RelayRecordState * @flow * @typechecks */ 'use strict'; export type RecordState = $Enum<typeof RelayRecordState>; var RelayRecordState = { /** * Record exists (either fetched from the server or produced by a local, * optimistic update). */ EXISTENT: 'EXISTENT', /** * Record is known not to exist (either as the result of a mutation, or * because the server returned `null` when queried for the record). */ NONEXISTENT: 'NONEXISTENT', /** * Record State is unknown because it has not yet been fetched from the * server. */ UNKNOWN: 'UNKNOWN', }; module.exports = RelayRecordState;
quazzie/relay
src/store/RelayRecordState.js
JavaScript
bsd-3-clause
949
// Copyright 2014 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/v8.h" #if V8_TARGET_ARCH_ARM #include "src/ic/call-optimization.h" #include "src/ic/handler-compiler.h" #include "src/ic/ic.h" namespace v8 { namespace internal { #define __ ACCESS_MASM(masm) void NamedLoadHandlerCompiler::GenerateLoadViaGetter( MacroAssembler* masm, Handle<HeapType> type, Register receiver, Handle<JSFunction> getter) { // ----------- S t a t e ------------- // -- r0 : receiver // -- r2 : name // -- lr : return address // ----------------------------------- { FrameAndConstantPoolScope scope(masm, StackFrame::INTERNAL); if (!getter.is_null()) { // Call the JavaScript getter with the receiver on the stack. if (IC::TypeToMap(*type, masm->isolate())->IsJSGlobalObjectMap()) { // Swap in the global receiver. __ ldr(receiver, FieldMemOperand(receiver, JSGlobalObject::kGlobalProxyOffset)); } __ push(receiver); ParameterCount actual(0); ParameterCount expected(getter); __ InvokeFunction(getter, expected, actual, CALL_FUNCTION, NullCallWrapper()); } else { // If we generate a global code snippet for deoptimization only, remember // the place to continue after deoptimization. masm->isolate()->heap()->SetGetterStubDeoptPCOffset(masm->pc_offset()); } // Restore context register. __ ldr(cp, MemOperand(fp, StandardFrameConstants::kContextOffset)); } __ Ret(); } void NamedStoreHandlerCompiler::GenerateStoreViaSetter( MacroAssembler* masm, Handle<HeapType> type, Register receiver, Handle<JSFunction> setter) { // ----------- S t a t e ------------- // -- lr : return address // ----------------------------------- { FrameAndConstantPoolScope scope(masm, StackFrame::INTERNAL); // Save value register, so we can restore it later. __ push(value()); if (!setter.is_null()) { // Call the JavaScript setter with receiver and value on the stack. if (IC::TypeToMap(*type, masm->isolate())->IsJSGlobalObjectMap()) { // Swap in the global receiver. __ ldr(receiver, FieldMemOperand(receiver, JSGlobalObject::kGlobalProxyOffset)); } __ Push(receiver, value()); ParameterCount actual(1); ParameterCount expected(setter); __ InvokeFunction(setter, expected, actual, CALL_FUNCTION, NullCallWrapper()); } else { // If we generate a global code snippet for deoptimization only, remember // the place to continue after deoptimization. masm->isolate()->heap()->SetSetterStubDeoptPCOffset(masm->pc_offset()); } // We have to return the passed value, not the return value of the setter. __ pop(r0); // Restore context register. __ ldr(cp, MemOperand(fp, StandardFrameConstants::kContextOffset)); } __ Ret(); } void PropertyHandlerCompiler::GenerateDictionaryNegativeLookup( MacroAssembler* masm, Label* miss_label, Register receiver, Handle<Name> name, Register scratch0, Register scratch1) { DCHECK(name->IsUniqueName()); DCHECK(!receiver.is(scratch0)); Counters* counters = masm->isolate()->counters(); __ IncrementCounter(counters->negative_lookups(), 1, scratch0, scratch1); __ IncrementCounter(counters->negative_lookups_miss(), 1, scratch0, scratch1); Label done; const int kInterceptorOrAccessCheckNeededMask = (1 << Map::kHasNamedInterceptor) | (1 << Map::kIsAccessCheckNeeded); // Bail out if the receiver has a named interceptor or requires access checks. Register map = scratch1; __ ldr(map, FieldMemOperand(receiver, HeapObject::kMapOffset)); __ ldrb(scratch0, FieldMemOperand(map, Map::kBitFieldOffset)); __ tst(scratch0, Operand(kInterceptorOrAccessCheckNeededMask)); __ b(ne, miss_label); // Check that receiver is a JSObject. __ ldrb(scratch0, FieldMemOperand(map, Map::kInstanceTypeOffset)); __ cmp(scratch0, Operand(FIRST_SPEC_OBJECT_TYPE)); __ b(lt, miss_label); // Load properties array. Register properties = scratch0; __ ldr(properties, FieldMemOperand(receiver, JSObject::kPropertiesOffset)); // Check that the properties array is a dictionary. __ ldr(map, FieldMemOperand(properties, HeapObject::kMapOffset)); Register tmp = properties; __ LoadRoot(tmp, Heap::kHashTableMapRootIndex); __ cmp(map, tmp); __ b(ne, miss_label); // Restore the temporarily used register. __ ldr(properties, FieldMemOperand(receiver, JSObject::kPropertiesOffset)); NameDictionaryLookupStub::GenerateNegativeLookup( masm, miss_label, &done, receiver, properties, name, scratch1); __ bind(&done); __ DecrementCounter(counters->negative_lookups_miss(), 1, scratch0, scratch1); } void NamedLoadHandlerCompiler::GenerateDirectLoadGlobalFunctionPrototype( MacroAssembler* masm, int index, Register prototype, Label* miss) { Isolate* isolate = masm->isolate(); // Get the global function with the given index. Handle<JSFunction> function( JSFunction::cast(isolate->native_context()->get(index))); // Check we're still in the same context. Register scratch = prototype; const int offset = Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX); __ ldr(scratch, MemOperand(cp, offset)); __ ldr(scratch, FieldMemOperand(scratch, GlobalObject::kNativeContextOffset)); __ ldr(scratch, MemOperand(scratch, Context::SlotOffset(index))); __ Move(ip, function); __ cmp(ip, scratch); __ b(ne, miss); // Load its initial map. The global functions all have initial maps. __ Move(prototype, Handle<Map>(function->initial_map())); // Load the prototype from the initial map. __ ldr(prototype, FieldMemOperand(prototype, Map::kPrototypeOffset)); } void NamedLoadHandlerCompiler::GenerateLoadFunctionPrototype( MacroAssembler* masm, Register receiver, Register scratch1, Register scratch2, Label* miss_label) { __ TryGetFunctionPrototype(receiver, scratch1, scratch2, miss_label); __ mov(r0, scratch1); __ Ret(); } // Generate code to check that a global property cell is empty. Create // the property cell at compilation time if no cell exists for the // property. void PropertyHandlerCompiler::GenerateCheckPropertyCell( MacroAssembler* masm, Handle<JSGlobalObject> global, Handle<Name> name, Register scratch, Label* miss) { Handle<Cell> cell = JSGlobalObject::EnsurePropertyCell(global, name); DCHECK(cell->value()->IsTheHole()); __ mov(scratch, Operand(cell)); __ ldr(scratch, FieldMemOperand(scratch, Cell::kValueOffset)); __ LoadRoot(ip, Heap::kTheHoleValueRootIndex); __ cmp(scratch, ip); __ b(ne, miss); } static void PushInterceptorArguments(MacroAssembler* masm, Register receiver, Register holder, Register name, Handle<JSObject> holder_obj) { STATIC_ASSERT(NamedLoadHandlerCompiler::kInterceptorArgsNameIndex == 0); STATIC_ASSERT(NamedLoadHandlerCompiler::kInterceptorArgsInfoIndex == 1); STATIC_ASSERT(NamedLoadHandlerCompiler::kInterceptorArgsThisIndex == 2); STATIC_ASSERT(NamedLoadHandlerCompiler::kInterceptorArgsHolderIndex == 3); STATIC_ASSERT(NamedLoadHandlerCompiler::kInterceptorArgsLength == 4); __ push(name); Handle<InterceptorInfo> interceptor(holder_obj->GetNamedInterceptor()); DCHECK(!masm->isolate()->heap()->InNewSpace(*interceptor)); Register scratch = name; __ mov(scratch, Operand(interceptor)); __ push(scratch); __ push(receiver); __ push(holder); } static void CompileCallLoadPropertyWithInterceptor( MacroAssembler* masm, Register receiver, Register holder, Register name, Handle<JSObject> holder_obj, IC::UtilityId id) { PushInterceptorArguments(masm, receiver, holder, name, holder_obj); __ CallExternalReference(ExternalReference(IC_Utility(id), masm->isolate()), NamedLoadHandlerCompiler::kInterceptorArgsLength); } // Generate call to api function. void PropertyHandlerCompiler::GenerateFastApiCall( MacroAssembler* masm, const CallOptimization& optimization, Handle<Map> receiver_map, Register receiver, Register scratch_in, bool is_store, int argc, Register* values) { DCHECK(!receiver.is(scratch_in)); __ push(receiver); // Write the arguments to stack frame. for (int i = 0; i < argc; i++) { Register arg = values[argc - 1 - i]; DCHECK(!receiver.is(arg)); DCHECK(!scratch_in.is(arg)); __ push(arg); } DCHECK(optimization.is_simple_api_call()); // Abi for CallApiFunctionStub. Register callee = r0; Register call_data = r4; Register holder = r2; Register api_function_address = r1; // Put holder in place. CallOptimization::HolderLookup holder_lookup; Handle<JSObject> api_holder = optimization.LookupHolderOfExpectedType(receiver_map, &holder_lookup); switch (holder_lookup) { case CallOptimization::kHolderIsReceiver: __ Move(holder, receiver); break; case CallOptimization::kHolderFound: __ Move(holder, api_holder); break; case CallOptimization::kHolderNotFound: UNREACHABLE(); break; } Isolate* isolate = masm->isolate(); Handle<JSFunction> function = optimization.constant_function(); Handle<CallHandlerInfo> api_call_info = optimization.api_call_info(); Handle<Object> call_data_obj(api_call_info->data(), isolate); // Put callee in place. __ Move(callee, function); bool call_data_undefined = false; // Put call_data in place. if (isolate->heap()->InNewSpace(*call_data_obj)) { __ Move(call_data, api_call_info); __ ldr(call_data, FieldMemOperand(call_data, CallHandlerInfo::kDataOffset)); } else if (call_data_obj->IsUndefined()) { call_data_undefined = true; __ LoadRoot(call_data, Heap::kUndefinedValueRootIndex); } else { __ Move(call_data, call_data_obj); } // Put api_function_address in place. Address function_address = v8::ToCData<Address>(api_call_info->callback()); ApiFunction fun(function_address); ExternalReference::Type type = ExternalReference::DIRECT_API_CALL; ExternalReference ref = ExternalReference(&fun, type, masm->isolate()); __ mov(api_function_address, Operand(ref)); // Jump to stub. CallApiFunctionStub stub(isolate, is_store, call_data_undefined, argc); __ TailCallStub(&stub); } void NamedStoreHandlerCompiler::GenerateSlow(MacroAssembler* masm) { // Push receiver, key and value for runtime call. __ Push(StoreDescriptor::ReceiverRegister(), StoreDescriptor::NameRegister(), StoreDescriptor::ValueRegister()); // The slow case calls into the runtime to complete the store without causing // an IC miss that would otherwise cause a transition to the generic stub. ExternalReference ref = ExternalReference(IC_Utility(IC::kStoreIC_Slow), masm->isolate()); __ TailCallExternalReference(ref, 3, 1); } void ElementHandlerCompiler::GenerateStoreSlow(MacroAssembler* masm) { // Push receiver, key and value for runtime call. __ Push(StoreDescriptor::ReceiverRegister(), StoreDescriptor::NameRegister(), StoreDescriptor::ValueRegister()); // The slow case calls into the runtime to complete the store without causing // an IC miss that would otherwise cause a transition to the generic stub. ExternalReference ref = ExternalReference(IC_Utility(IC::kKeyedStoreIC_Slow), masm->isolate()); __ TailCallExternalReference(ref, 3, 1); } #undef __ #define __ ACCESS_MASM(masm()) void NamedStoreHandlerCompiler::GenerateRestoreName(Label* label, Handle<Name> name) { if (!label->is_unused()) { __ bind(label); __ mov(this->name(), Operand(name)); } } void NamedStoreHandlerCompiler::GenerateRestoreNameAndMap( Handle<Name> name, Handle<Map> transition) { __ mov(this->name(), Operand(name)); __ mov(StoreTransitionDescriptor::MapRegister(), Operand(transition)); } void NamedStoreHandlerCompiler::GenerateConstantCheck(Object* constant, Register value_reg, Label* miss_label) { __ Move(scratch1(), handle(constant, isolate())); __ cmp(value_reg, scratch1()); __ b(ne, miss_label); } void NamedStoreHandlerCompiler::GenerateFieldTypeChecks(HeapType* field_type, Register value_reg, Label* miss_label) { __ JumpIfSmi(value_reg, miss_label); HeapType::Iterator<Map> it = field_type->Classes(); if (!it.Done()) { __ ldr(scratch1(), FieldMemOperand(value_reg, HeapObject::kMapOffset)); Label do_store; while (true) { __ CompareMap(scratch1(), it.Current(), &do_store); it.Advance(); if (it.Done()) { __ b(ne, miss_label); break; } __ b(eq, &do_store); } __ bind(&do_store); } } Register PropertyHandlerCompiler::CheckPrototypes( Register object_reg, Register holder_reg, Register scratch1, Register scratch2, Handle<Name> name, Label* miss, PrototypeCheckType check) { Handle<Map> receiver_map(IC::TypeToMap(*type(), isolate())); // Make sure there's no overlap between holder and object registers. DCHECK(!scratch1.is(object_reg) && !scratch1.is(holder_reg)); DCHECK(!scratch2.is(object_reg) && !scratch2.is(holder_reg) && !scratch2.is(scratch1)); // Keep track of the current object in register reg. Register reg = object_reg; int depth = 0; Handle<JSObject> current = Handle<JSObject>::null(); if (type()->IsConstant()) { current = Handle<JSObject>::cast(type()->AsConstant()->Value()); } Handle<JSObject> prototype = Handle<JSObject>::null(); Handle<Map> current_map = receiver_map; Handle<Map> holder_map(holder()->map()); // Traverse the prototype chain and check the maps in the prototype chain for // fast and global objects or do negative lookup for normal objects. while (!current_map.is_identical_to(holder_map)) { ++depth; // Only global objects and objects that do not require access // checks are allowed in stubs. DCHECK(current_map->IsJSGlobalProxyMap() || !current_map->is_access_check_needed()); prototype = handle(JSObject::cast(current_map->prototype())); if (current_map->is_dictionary_map() && !current_map->IsJSGlobalObjectMap()) { DCHECK(!current_map->IsJSGlobalProxyMap()); // Proxy maps are fast. if (!name->IsUniqueName()) { DCHECK(name->IsString()); name = factory()->InternalizeString(Handle<String>::cast(name)); } DCHECK(current.is_null() || current->property_dictionary()->FindEntry(name) == NameDictionary::kNotFound); GenerateDictionaryNegativeLookup(masm(), miss, reg, name, scratch1, scratch2); __ ldr(scratch1, FieldMemOperand(reg, HeapObject::kMapOffset)); reg = holder_reg; // From now on the object will be in holder_reg. __ ldr(reg, FieldMemOperand(scratch1, Map::kPrototypeOffset)); } else { Register map_reg = scratch1; if (depth != 1 || check == CHECK_ALL_MAPS) { // CheckMap implicitly loads the map of |reg| into |map_reg|. __ CheckMap(reg, map_reg, current_map, miss, DONT_DO_SMI_CHECK); } else { __ ldr(map_reg, FieldMemOperand(reg, HeapObject::kMapOffset)); } // Check access rights to the global object. This has to happen after // the map check so that we know that the object is actually a global // object. // This allows us to install generated handlers for accesses to the // global proxy (as opposed to using slow ICs). See corresponding code // in LookupForRead(). if (current_map->IsJSGlobalProxyMap()) { __ CheckAccessGlobalProxy(reg, scratch2, miss); } else if (current_map->IsJSGlobalObjectMap()) { GenerateCheckPropertyCell(masm(), Handle<JSGlobalObject>::cast(current), name, scratch2, miss); } reg = holder_reg; // From now on the object will be in holder_reg. // Two possible reasons for loading the prototype from the map: // (1) Can't store references to new space in code. // (2) Handler is shared for all receivers with the same prototype // map (but not necessarily the same prototype instance). bool load_prototype_from_map = heap()->InNewSpace(*prototype) || depth == 1; if (load_prototype_from_map) { __ ldr(reg, FieldMemOperand(map_reg, Map::kPrototypeOffset)); } else { __ mov(reg, Operand(prototype)); } } // Go to the next object in the prototype chain. current = prototype; current_map = handle(current->map()); } // Log the check depth. LOG(isolate(), IntEvent("check-maps-depth", depth + 1)); if (depth != 0 || check == CHECK_ALL_MAPS) { // Check the holder map. __ CheckMap(reg, scratch1, current_map, miss, DONT_DO_SMI_CHECK); } // Perform security check for access to the global object. DCHECK(current_map->IsJSGlobalProxyMap() || !current_map->is_access_check_needed()); if (current_map->IsJSGlobalProxyMap()) { __ CheckAccessGlobalProxy(reg, scratch1, miss); } // Return the register containing the holder. return reg; } void NamedLoadHandlerCompiler::FrontendFooter(Handle<Name> name, Label* miss) { if (!miss->is_unused()) { Label success; __ b(&success); __ bind(miss); TailCallBuiltin(masm(), MissBuiltin(kind())); __ bind(&success); } } void NamedStoreHandlerCompiler::FrontendFooter(Handle<Name> name, Label* miss) { if (!miss->is_unused()) { Label success; __ b(&success); GenerateRestoreName(miss, name); TailCallBuiltin(masm(), MissBuiltin(kind())); __ bind(&success); } } void NamedLoadHandlerCompiler::GenerateLoadConstant(Handle<Object> value) { // Return the constant value. __ Move(r0, value); __ Ret(); } void NamedLoadHandlerCompiler::GenerateLoadCallback( Register reg, Handle<ExecutableAccessorInfo> callback) { // Build AccessorInfo::args_ list on the stack and push property name below // the exit frame to make GC aware of them and store pointers to them. STATIC_ASSERT(PropertyCallbackArguments::kHolderIndex == 0); STATIC_ASSERT(PropertyCallbackArguments::kIsolateIndex == 1); STATIC_ASSERT(PropertyCallbackArguments::kReturnValueDefaultValueIndex == 2); STATIC_ASSERT(PropertyCallbackArguments::kReturnValueOffset == 3); STATIC_ASSERT(PropertyCallbackArguments::kDataIndex == 4); STATIC_ASSERT(PropertyCallbackArguments::kThisIndex == 5); STATIC_ASSERT(PropertyCallbackArguments::kArgsLength == 6); DCHECK(!scratch2().is(reg)); DCHECK(!scratch3().is(reg)); DCHECK(!scratch4().is(reg)); __ push(receiver()); if (heap()->InNewSpace(callback->data())) { __ Move(scratch3(), callback); __ ldr(scratch3(), FieldMemOperand(scratch3(), ExecutableAccessorInfo::kDataOffset)); } else { __ Move(scratch3(), Handle<Object>(callback->data(), isolate())); } __ push(scratch3()); __ LoadRoot(scratch3(), Heap::kUndefinedValueRootIndex); __ mov(scratch4(), scratch3()); __ Push(scratch3(), scratch4()); __ mov(scratch4(), Operand(ExternalReference::isolate_address(isolate()))); __ Push(scratch4(), reg); __ mov(scratch2(), sp); // scratch2 = PropertyAccessorInfo::args_ __ push(name()); // Abi for CallApiGetter Register getter_address_reg = ApiGetterDescriptor::function_address(); Address getter_address = v8::ToCData<Address>(callback->getter()); ApiFunction fun(getter_address); ExternalReference::Type type = ExternalReference::DIRECT_GETTER_CALL; ExternalReference ref = ExternalReference(&fun, type, isolate()); __ mov(getter_address_reg, Operand(ref)); CallApiGetterStub stub(isolate()); __ TailCallStub(&stub); } void NamedLoadHandlerCompiler::GenerateLoadInterceptorWithFollowup( LookupIterator* it, Register holder_reg) { DCHECK(holder()->HasNamedInterceptor()); DCHECK(!holder()->GetNamedInterceptor()->getter()->IsUndefined()); // Compile the interceptor call, followed by inline code to load the // property from further up the prototype chain if the call fails. // Check that the maps haven't changed. DCHECK(holder_reg.is(receiver()) || holder_reg.is(scratch1())); // Preserve the receiver register explicitly whenever it is different from the // holder and it is needed should the interceptor return without any result. // The ACCESSOR case needs the receiver to be passed into C++ code, the FIELD // case might cause a miss during the prototype check. bool must_perform_prototype_check = !holder().is_identical_to(it->GetHolder<JSObject>()); bool must_preserve_receiver_reg = !receiver().is(holder_reg) && (it->state() == LookupIterator::ACCESSOR || must_perform_prototype_check); // Save necessary data before invoking an interceptor. // Requires a frame to make GC aware of pushed pointers. { FrameAndConstantPoolScope frame_scope(masm(), StackFrame::INTERNAL); if (must_preserve_receiver_reg) { __ Push(receiver(), holder_reg, this->name()); } else { __ Push(holder_reg, this->name()); } // Invoke an interceptor. Note: map checks from receiver to // interceptor's holder has been compiled before (see a caller // of this method.) CompileCallLoadPropertyWithInterceptor( masm(), receiver(), holder_reg, this->name(), holder(), IC::kLoadPropertyWithInterceptorOnly); // Check if interceptor provided a value for property. If it's // the case, return immediately. Label interceptor_failed; __ LoadRoot(scratch1(), Heap::kNoInterceptorResultSentinelRootIndex); __ cmp(r0, scratch1()); __ b(eq, &interceptor_failed); frame_scope.GenerateLeaveFrame(); __ Ret(); __ bind(&interceptor_failed); __ pop(this->name()); __ pop(holder_reg); if (must_preserve_receiver_reg) { __ pop(receiver()); } // Leave the internal frame. } GenerateLoadPostInterceptor(it, holder_reg); } void NamedLoadHandlerCompiler::GenerateLoadInterceptor(Register holder_reg) { // Call the runtime system to load the interceptor. DCHECK(holder()->HasNamedInterceptor()); DCHECK(!holder()->GetNamedInterceptor()->getter()->IsUndefined()); PushInterceptorArguments(masm(), receiver(), holder_reg, this->name(), holder()); ExternalReference ref = ExternalReference( IC_Utility(IC::kLoadPropertyWithInterceptor), isolate()); __ TailCallExternalReference( ref, NamedLoadHandlerCompiler::kInterceptorArgsLength, 1); } Handle<Code> NamedStoreHandlerCompiler::CompileStoreCallback( Handle<JSObject> object, Handle<Name> name, Handle<ExecutableAccessorInfo> callback) { Register holder_reg = Frontend(receiver(), name); __ push(receiver()); // receiver __ push(holder_reg); __ mov(ip, Operand(callback)); // callback info __ push(ip); __ mov(ip, Operand(name)); __ Push(ip, value()); // Do tail-call to the runtime system. ExternalReference store_callback_property = ExternalReference(IC_Utility(IC::kStoreCallbackProperty), isolate()); __ TailCallExternalReference(store_callback_property, 5, 1); // Return the generated code. return GetCode(kind(), Code::FAST, name); } Handle<Code> NamedStoreHandlerCompiler::CompileStoreInterceptor( Handle<Name> name) { __ Push(receiver(), this->name(), value()); // Do tail-call to the runtime system. ExternalReference store_ic_property = ExternalReference( IC_Utility(IC::kStorePropertyWithInterceptor), isolate()); __ TailCallExternalReference(store_ic_property, 3, 1); // Return the generated code. return GetCode(kind(), Code::FAST, name); } Register NamedStoreHandlerCompiler::value() { return StoreDescriptor::ValueRegister(); } Handle<Code> NamedLoadHandlerCompiler::CompileLoadGlobal( Handle<PropertyCell> cell, Handle<Name> name, bool is_configurable) { Label miss; FrontendHeader(receiver(), name, &miss); // Get the value from the cell. Register result = StoreDescriptor::ValueRegister(); __ mov(result, Operand(cell)); __ ldr(result, FieldMemOperand(result, Cell::kValueOffset)); // Check for deleted property if property can actually be deleted. if (is_configurable) { __ LoadRoot(ip, Heap::kTheHoleValueRootIndex); __ cmp(result, ip); __ b(eq, &miss); } Counters* counters = isolate()->counters(); __ IncrementCounter(counters->named_load_global_stub(), 1, r1, r3); __ Ret(); FrontendFooter(name, &miss); // Return the generated code. return GetCode(kind(), Code::NORMAL, name); } #undef __ } } // namespace v8::internal #endif // V8_TARGET_ARCH_ARM
tempbottle/v8.rs
src/ic/arm/handler-compiler-arm.cc
C++
isc
25,105
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule PerformanceOverlay * @flow */ 'use strict'; var PerformanceLogger = require('PerformanceLogger'); var React = require('React'); var StyleSheet = require('StyleSheet'); var Text = require('Text'); var View = require('View'); var PerformanceOverlay = React.createClass({ render: function() { var perfLogs = PerformanceLogger.getTimespans(); var items = []; for (var key in perfLogs) { if (perfLogs[key].totalTime) { var unit = (key === 'BundleSize') ? 'b' : 'ms'; items.push( <View style={styles.row} key={key}> <Text style={[styles.text, styles.label]}>{key}</Text> <Text style={[styles.text, styles.totalTime]}> {perfLogs[key].totalTime + unit} </Text> </View> ); } } return ( <View style={styles.container}> {items} </View> ); } }); var styles = StyleSheet.create({ container: { height: 100, paddingTop: 10, }, label: { flex: 1, }, row: { flexDirection: 'row', paddingHorizontal: 10, }, text: { color: 'white', fontSize: 12, }, totalTime: { paddingRight: 100, }, }); module.exports = PerformanceOverlay;
paulunits/tiptap
node_modules/react-native/Libraries/Inspector/PerformanceOverlay.js
JavaScript
mit
1,546
class Electron < ActiveRecord::Base belongs_to :molecule validates_presence_of :name end
rumblefishinc/ruby-ibmdb
test/models/electron.rb
Ruby
mit
94
var crypto = require('crypto'); var EventEmitter = require('events').EventEmitter; var util = require('util'); var pgPass = require('pgpass'); var TypeOverrides = require('./type-overrides'); var ConnectionParameters = require('./connection-parameters'); var Query = require('./query'); var defaults = require('./defaults'); var Connection = require('./connection'); var Client = function(config) { EventEmitter.call(this); this.connectionParameters = new ConnectionParameters(config); this.user = this.connectionParameters.user; this.database = this.connectionParameters.database; this.port = this.connectionParameters.port; this.host = this.connectionParameters.host; this.password = this.connectionParameters.password; var c = config || {}; this._types = new TypeOverrides(c.types); this.connection = c.connection || new Connection({ stream: c.stream, ssl: this.connectionParameters.ssl }); this.queryQueue = []; this.binary = c.binary || defaults.binary; this.encoding = 'utf8'; this.processID = null; this.secretKey = null; this.ssl = this.connectionParameters.ssl || false; }; util.inherits(Client, EventEmitter); Client.prototype.connect = function(callback) { var self = this; var con = this.connection; if(this.host && this.host.indexOf('/') === 0) { con.connect(this.host + '/.s.PGSQL.' + this.port); } else { con.connect(this.port, this.host); } //once connection is established send startup message con.on('connect', function() { if(self.ssl) { con.requestSsl(); } else { con.startup(self.getStartupConf()); } }); con.on('sslconnect', function() { con.startup(self.getStartupConf()); }); function checkPgPass(cb) { return function(msg) { if (null !== self.password) { cb(msg); } else { pgPass(self.connectionParameters, function(pass){ if (undefined !== pass) { self.connectionParameters.password = self.password = pass; } cb(msg); }); } }; } //password request handling con.on('authenticationCleartextPassword', checkPgPass(function() { con.password(self.password); })); //password request handling con.on('authenticationMD5Password', checkPgPass(function(msg) { var inner = Client.md5(self.password + self.user); var outer = Client.md5(Buffer.concat([new Buffer(inner), msg.salt])); var md5password = "md5" + outer; con.password(md5password); })); con.once('backendKeyData', function(msg) { self.processID = msg.processID; self.secretKey = msg.secretKey; }); //hook up query handling events to connection //after the connection initially becomes ready for queries con.once('readyForQuery', function() { //delegate rowDescription to active query con.on('rowDescription', function(msg) { self.activeQuery.handleRowDescription(msg); }); //delegate dataRow to active query con.on('dataRow', function(msg) { self.activeQuery.handleDataRow(msg); }); //delegate portalSuspended to active query con.on('portalSuspended', function(msg) { self.activeQuery.handlePortalSuspended(con); }); //deletagate emptyQuery to active query con.on('emptyQuery', function(msg) { self.activeQuery.handleEmptyQuery(con); }); //delegate commandComplete to active query con.on('commandComplete', function(msg) { self.activeQuery.handleCommandComplete(msg, con); }); //if a prepared statement has a name and properly parses //we track that its already been executed so we don't parse //it again on the same client con.on('parseComplete', function(msg) { if(self.activeQuery.name) { con.parsedStatements[self.activeQuery.name] = true; } }); con.on('copyInResponse', function(msg) { self.activeQuery.handleCopyInResponse(self.connection); }); con.on('copyData', function (msg) { self.activeQuery.handleCopyData(msg, self.connection); }); con.on('notification', function(msg) { self.emit('notification', msg); }); //process possible callback argument to Client#connect if (callback) { callback(null, self); //remove callback for proper error handling //after the connect event callback = null; } self.emit('connect'); }); con.on('readyForQuery', function() { var activeQuery = self.activeQuery; self.activeQuery = null; self.readyForQuery = true; self._pulseQueryQueue(); if(activeQuery) { activeQuery.handleReadyForQuery(); } }); con.on('error', function(error) { if(self.activeQuery) { var activeQuery = self.activeQuery; self.activeQuery = null; return activeQuery.handleError(error, con); } if(!callback) { return self.emit('error', error); } callback(error); callback = null; }); con.once('end', function() { if ( callback ) { // haven't received a connection message yet ! var err = new Error('Connection terminated'); callback(err); callback = null; return; } if(self.activeQuery) { var disconnectError = new Error('Connection terminated'); self.activeQuery.handleError(disconnectError, con); self.activeQuery = null; } self.emit('end'); }); con.on('notice', function(msg) { self.emit('notice', msg); }); }; Client.prototype.getStartupConf = function() { var params = this.connectionParameters; var data = { user: params.user, database: params.database }; var appName = params.application_name || params.fallback_application_name; if (appName) { data.application_name = appName; } return data; }; Client.prototype.cancel = function(client, query) { if(client.activeQuery == query) { var con = this.connection; if(this.host && this.host.indexOf('/') === 0) { con.connect(this.host + '/.s.PGSQL.' + this.port); } else { con.connect(this.port, this.host); } //once connection is established send cancel message con.on('connect', function() { con.cancel(client.processID, client.secretKey); }); } else if(client.queryQueue.indexOf(query) != -1) { client.queryQueue.splice(client.queryQueue.indexOf(query), 1); } }; Client.prototype.setTypeParser = function(oid, format, parseFn) { return this._types.setTypeParser(oid, format, parseFn); }; Client.prototype.getTypeParser = function(oid, format) { return this._types.getTypeParser(oid, format); }; // Ported from PostgreSQL 9.2.4 source code in src/interfaces/libpq/fe-exec.c Client.prototype.escapeIdentifier = function(str) { var escaped = '"'; for(var i = 0; i < str.length; i++) { var c = str[i]; if(c === '"') { escaped += c + c; } else { escaped += c; } } escaped += '"'; return escaped; }; // Ported from PostgreSQL 9.2.4 source code in src/interfaces/libpq/fe-exec.c Client.prototype.escapeLiteral = function(str) { var hasBackslash = false; var escaped = '\''; for(var i = 0; i < str.length; i++) { var c = str[i]; if(c === '\'') { escaped += c + c; } else if (c === '\\') { escaped += c + c; hasBackslash = true; } else { escaped += c; } } escaped += '\''; if(hasBackslash === true) { escaped = ' E' + escaped; } return escaped; }; Client.prototype._pulseQueryQueue = function() { if(this.readyForQuery===true) { this.activeQuery = this.queryQueue.shift(); if(this.activeQuery) { this.readyForQuery = false; this.hasExecuted = true; this.activeQuery.submit(this.connection); } else if(this.hasExecuted) { this.activeQuery = null; this.emit('drain'); } } }; Client.prototype.copyFrom = function (text) { throw new Error("For PostgreSQL COPY TO/COPY FROM support npm install pg-copy-streams"); }; Client.prototype.copyTo = function (text) { throw new Error("For PostgreSQL COPY TO/COPY FROM support npm install pg-copy-streams"); }; Client.prototype.query = function(config, values, callback) { //can take in strings, config object or query object var query = (typeof config.submit == 'function') ? config : new Query(config, values, callback); if(this.binary && !query.binary) { query.binary = true; } if(query._result) { query._result._getTypeParser = this._types.getTypeParser.bind(this._types); } this.queryQueue.push(query); this._pulseQueryQueue(); return query; }; Client.prototype.end = function() { this.connection.end(); }; Client.md5 = function(string) { return crypto.createHash('md5').update(string).digest('hex'); }; // expose a Query constructor Client.Query = Query; module.exports = Client;
DianaVashti/talented-baboon
testApp/node_modules/pg/lib/client.js
JavaScript
mit
8,813
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle 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. // // Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Defines the version of workshop comments grading strategy subplugin * * This code fragment is called by moodle_needs_upgrading() and * /admin/index.php * * @package workshopform_comments * @copyright 2009 David Mudrak <david.mudrak@gmail.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); $plugin->version = 2014111000; $plugin->requires = 2014110400; // Requires this Moodle version $plugin->component = 'workshopform_comments';
charroferrari/moodle
mod/workshop/form/comments/version.php
PHP
gpl-3.0
1,209
tinyMCE.addI18n('ja.emotions_dlg',{ title:"\u30B9\u30DE\u30A4\u30EA\u30FC\u306E\u633F\u5165", desc:"\u30B9\u30DE\u30A4\u30EA\u30FC", cool:"Cool", cry:"Cry", embarassed:"Embarassed", foot_in_mouth:"Foot in mouth", frown:"Frown", innocent:"Innocent", kiss:"Kiss", laughing:"Laughing", money_mouth:"Money mouth", sealed:"Sealed", smile:"Smile", surprised:"Surprised", tongue_out:"Tongue out", undecided:"Undecided", wink:"Wink", yell:"Yell" });
griggsk/Library-a-la-Carte
vendor/plugins/tiny_mce/public/javascripts/tiny_mce/plugins/emotions/langs/ja_dlg.js
JavaScript
agpl-3.0
460
/* * Copyright (C) 2009 The Android Open Source Project * * 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. */ #define _CODEGEN_C #define _ARMV7_A_NEON #define TGT_LIR ArmLIR #include "Dalvik.h" #include "interp/InterpDefs.h" #include "libdex/DexOpcodes.h" #include "compiler/CompilerInternals.h" #include "compiler/codegen/arm/ArmLIR.h" #include "mterp/common/FindInterface.h" #include "compiler/codegen/Ralloc.h" #include "compiler/codegen/arm/Codegen.h" #include "compiler/Loop.h" #include "ArchVariant.h" /* Arm codegen building blocks */ #include "../CodegenCommon.cpp" /* Thumb2-specific factory utilities */ #include "../Thumb2/Factory.cpp" /* Target indepedent factory utilities */ #include "../../CodegenFactory.cpp" /* Arm-specific factory utilities */ #include "../ArchFactory.cpp" /* Thumb2-specific codegen routines */ #include "../Thumb2/Gen.cpp" /* Thumb2+VFP codegen routines */ #include "../FP/Thumb2VFP.cpp" /* Thumb2-specific register allocation */ #include "../Thumb2/Ralloc.cpp" /* MIR2LIR dispatcher and architectural independent codegen routines */ #include "../CodegenDriver.cpp" /* Driver for method-based JIT */ #include "MethodCodegenDriver.cpp" /* Architecture manifest */ #include "ArchVariant.cpp"
enimey/DexHunter
dalvik/vm/compiler/codegen/arm/armv7-a-neon/Codegen.cpp
C++
apache-2.0
1,745
/** * Copyright 2018 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import {dev} from '../log'; /** @const {string} */ const TAG = 'lru-cache'; /** * @template T */ export class LruCache { /** * @param {number} capacity */ constructor(capacity) { /** @private @const {number} */ this.capacity_ = capacity; /** @private {number} */ this.size_ = 0; /** * An incrementing counter to define the last access. * @private {number} */ this.access_ = 0; /** @private {!Object<(number|string), {payload: T, access: number}>} */ this.cache_ = Object.create(null); } /** * Returns whether key is cached. * * @param {number|string} key * @return {boolean} */ has(key) { return !!this.cache_[key]; } /** * @param {number|string} key * @return {T} The cached payload. */ get(key) { const cacheable = this.cache_[key]; if (cacheable) { cacheable.access = ++this.access_; return cacheable.payload; } return undefined; } /** * @param {number|string} key * @param {T} payload The payload to cache. */ put(key, payload) { if (!this.has(key)) { this.size_++; } this.cache_[key] = {payload, access: this.access_}; this.evict_(); } /** * Evicts the oldest cache entry, if we've exceeded capacity. */ evict_() { if (this.size_ <= this.capacity_) { return; } dev().warn(TAG, 'Trimming LRU cache'); const cache = this.cache_; let oldest = this.access_ + 1; let oldestKey; for (const key in cache) { const {access} = cache[key]; if (access < oldest) { oldest = access; oldestKey = key; } } if (oldestKey !== undefined) { delete cache[oldestKey]; this.size_--; } } }
lannka/amphtml
src/utils/lru-cache.js
JavaScript
apache-2.0
2,381
# -*- coding: utf-8 -*- import os import httplib import logging import functools from modularodm.exceptions import ValidationValueError from framework.exceptions import HTTPError from framework.analytics import update_counter from website.addons.osfstorage import settings logger = logging.getLogger(__name__) LOCATION_KEYS = ['service', settings.WATERBUTLER_RESOURCE, 'object'] def update_analytics(node, file_id, version_idx): """ :param Node node: Root node to update :param str file_id: The _id field of a filenode :param int version_idx: Zero-based version index """ update_counter(u'download:{0}:{1}'.format(node._id, file_id)) update_counter(u'download:{0}:{1}:{2}'.format(node._id, file_id, version_idx)) def serialize_revision(node, record, version, index, anon=False): """Serialize revision for use in revisions table. :param Node node: Root node :param FileRecord record: Root file record :param FileVersion version: The version to serialize :param int index: One-based index of version """ if anon: user = None else: user = { 'name': version.creator.fullname, 'url': version.creator.url, } return { 'user': user, 'index': index + 1, 'date': version.date_created.isoformat(), 'downloads': record.get_download_count(version=index), 'md5': version.metadata.get('md5'), 'sha256': version.metadata.get('sha256'), } SIGNED_REQUEST_ERROR = HTTPError( httplib.SERVICE_UNAVAILABLE, data={ 'message_short': 'Upload service unavailable', 'message_long': ( 'Upload service is not available; please retry ' 'your upload in a moment' ), }, ) def get_filename(version_idx, file_version, file_record): """Build name for downloaded file, appending version date if not latest. :param int version_idx: One-based version index :param FileVersion file_version: Version to name :param FileRecord file_record: Root file object """ if version_idx == len(file_record.versions): return file_record.name name, ext = os.path.splitext(file_record.name) return u'{name}-{date}{ext}'.format( name=name, date=file_version.date_created.isoformat(), ext=ext, ) def validate_location(value): for key in LOCATION_KEYS: if key not in value: raise ValidationValueError def must_be(_type): """A small decorator factory for OsfStorageFileNode. Acts as a poor mans polymorphic inheritance, ensures that the given instance is of "kind" folder or file """ def _must_be(func): @functools.wraps(func) def wrapped(self, *args, **kwargs): if not self.kind == _type: raise ValueError('This instance is not a {}'.format(_type)) return func(self, *args, **kwargs) return wrapped return _must_be def copy_files(src, target_settings, parent=None, name=None): """Copy the files from src to the target nodesettings :param OsfStorageFileNode src: The source to copy children from :param OsfStorageNodeSettings target_settings: The node settings of the project to copy files to :param OsfStorageFileNode parent: The parent of to attach the clone of src to, if applicable """ cloned = src.clone() cloned.parent = parent cloned.name = name or cloned.name cloned.node_settings = target_settings if src.is_file: cloned.versions = src.versions cloned.save() if src.is_folder: for child in src.children: copy_files(child, target_settings, parent=cloned) return cloned
ticklemepierce/osf.io
website/addons/osfstorage/utils.py
Python
apache-2.0
3,726
/* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.api.support; public class SafeExceptionRethrower { public static void safeRethrow(Throwable t) { SafeExceptionRethrower.<RuntimeException> safeRethrow0(t); } @SuppressWarnings("unchecked") private static <T extends Throwable> void safeRethrow0(Throwable t) throws T { throw (T) t; } }
jayway/powermock
powermock-api/powermock-api-support/src/main/java/org/powermock/api/support/SafeExceptionRethrower.java
Java
apache-2.0
936
# # Cookbook Name:: tuning # Description:: Applies tuning for Ubuntu systems # Recipe:: ubuntu # Author:: Philip (flip) Kromer - Infochimps, Inc # # Copyright 2011, Philip (flip) Kromer - Infochimps, Inc # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # def set_proc_sys_limit desc, proc_path, limit bash "set #{desc} to #{limit}" do only_if{ File.exists?(proc_path) } not_if{ File.read(proc_path).chomp.strip == limit.to_s } code "echo #{limit} > #{proc_path}" end end set_proc_sys_limit "VM overcommit ratio", '/proc/sys/vm/overcommit_memory', node[:tuning][:overcommit_memory] set_proc_sys_limit "VM overcommit memory", '/proc/sys/vm/overcommit_ratio', node[:tuning][:overcommit_ratio] set_proc_sys_limit "VM swappiness", '/proc/sys/vm/swappiness', node[:tuning][:swappiness] node[:tuning][:ulimit].each do |user, ulimits| conf_file = user.gsub(/^@/, 'group_') template "/etc/security/limits.d/#{conf_file}.conf" do owner "root" mode "0644" variables({ :user => user, :ulimits => ulimits }) source "etc_security_limits_overrides.conf.erb" end end
RandyHollandsworth/debbie
cookbooks/tuning/recipes/ubuntu.rb
Ruby
apache-2.0
1,651
/************************************************************* * * MathJax/fonts/HTML-CSS/TeX/png/Main/Bold/LatinExtendedA.js * * Defines the image size data needed for the HTML-CSS OutputJax * to display mathematics using fallback images when the fonts * are not availble to the client browser. * * --------------------------------------------------------------------- * * Copyright (c) 2009-2013 The MathJax Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ MathJax.OutputJax["HTML-CSS"].defineImageData({ "MathJax_Main-bold": { 0x131: [ // LATIN SMALL LETTER DOTLESS I [3,3,0],[4,4,0],[4,5,0],[5,5,0],[6,6,0],[7,8,0],[8,9,0],[9,11,0], [11,13,0],[12,15,0],[15,18,0],[17,21,0],[21,25,0],[24,30,0] ] } }); MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].imgDir+"/Main/Bold"+ MathJax.OutputJax["HTML-CSS"].imgPacked+"/LatinExtendedA.js");
AndrewSyktyvkar/Math
wysivig/MathJax/fonts/HTML-CSS/TeX/png/Main/Bold/unpacked/LatinExtendedA.js
JavaScript
bsd-3-clause
1,440
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jetbrains.python.psi.impl; import com.intellij.extapi.psi.StubBasedPsiElementBase; import com.intellij.lang.ASTNode; import com.intellij.openapi.util.TextRange; import com.intellij.psi.*; import com.intellij.psi.impl.source.resolve.reference.impl.PsiMultiReference; import com.intellij.psi.stubs.IStubElementType; import com.intellij.psi.stubs.StubElement; import com.intellij.psi.templateLanguages.OuterLanguageElement; import com.intellij.psi.tree.IElementType; import com.intellij.psi.tree.TokenSet; import com.jetbrains.python.PythonFileType; import com.jetbrains.python.PythonLanguage; import com.jetbrains.python.psi.PyElement; import com.jetbrains.python.psi.PyElementVisitor; import com.jetbrains.python.psi.PyReferenceOwner; import com.jetbrains.python.psi.resolve.PyResolveContext; import com.jetbrains.python.psi.types.TypeEvalContext; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * @author max */ public class PyBaseElementImpl<T extends StubElement> extends StubBasedPsiElementBase<T> implements PyElement { public PyBaseElementImpl(final T stub, IStubElementType nodeType) { super(stub, nodeType); } public PyBaseElementImpl(final ASTNode node) { super(node); } @NotNull @Override public PythonLanguage getLanguage() { return (PythonLanguage)PythonFileType.INSTANCE.getLanguage(); } @Override public String toString() { String className = getClass().getName(); int pos = className.lastIndexOf('.'); if (pos >= 0) { className = className.substring(pos + 1); } if (className.endsWith("Impl")) { className = className.substring(0, className.length() - 4); } return className; } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof PyElementVisitor) { acceptPyVisitor(((PyElementVisitor)visitor)); } else { super.accept(visitor); } } protected void acceptPyVisitor(PyElementVisitor pyVisitor) { pyVisitor.visitPyElement(this); } @NotNull protected <T extends PyElement> T[] childrenToPsi(TokenSet filterSet, T[] array) { final ASTNode[] nodes = getNode().getChildren(filterSet); return PyPsiUtils.nodesToPsi(nodes, array); } @Nullable protected <T extends PyElement> T childToPsi(TokenSet filterSet, int index) { final ASTNode[] nodes = getNode().getChildren(filterSet); if (nodes.length <= index) { return null; } //noinspection unchecked return (T)nodes[index].getPsi(); } @Nullable protected <T extends PyElement> T childToPsi(IElementType elType) { final ASTNode node = getNode().findChildByType(elType); if (node == null) { return null; } //noinspection unchecked return (T)node.getPsi(); } @Nullable protected <T extends PyElement> T childToPsi(@NotNull TokenSet elTypes) { final ASTNode node = getNode().findChildByType(elTypes); //noinspection unchecked return node != null ? (T)node.getPsi() : null; } @NotNull protected <T extends PyElement> T childToPsiNotNull(TokenSet filterSet, int index) { final PyElement child = childToPsi(filterSet, index); if (child == null) { throw new RuntimeException("child must not be null: expression text " + getText()); } //noinspection unchecked return (T)child; } @NotNull protected <T extends PyElement> T childToPsiNotNull(IElementType elType) { final PyElement child = childToPsi(elType); if (child == null) { throw new RuntimeException("child must not be null; expression text " + getText()); } //noinspection unchecked return (T)child; } /** * Overrides the findReferenceAt() logic in order to provide a resolve context with origin file for returned references. * The findReferenceAt() is usually invoked from UI operations, and it helps to be able to do deeper analysis in the * current file for such operations. * * @param offset the offset to find the reference at * @return the reference or null. */ @Override public PsiReference findReferenceAt(int offset) { // copy/paste from SharedPsiElementImplUtil PsiElement element = findElementAt(offset); if (element == null || element instanceof OuterLanguageElement) return null; offset = getTextRange().getStartOffset() + offset - element.getTextRange().getStartOffset(); List<PsiReference> referencesList = new ArrayList<PsiReference>(); final PsiFile file = element.getContainingFile(); final PyResolveContext resolveContext = file != null ? PyResolveContext.defaultContext().withTypeEvalContext(TypeEvalContext.codeAnalysis(file.getProject(), file)) : PyResolveContext.defaultContext(); while (element != null) { addReferences(offset, element, referencesList, resolveContext); offset = element.getStartOffsetInParent() + offset; if (element instanceof PsiFile) break; element = element.getParent(); } if (referencesList.isEmpty()) return null; if (referencesList.size() == 1) return referencesList.get(0); return new PsiMultiReference(referencesList.toArray(new PsiReference[referencesList.size()]), referencesList.get(referencesList.size() - 1).getElement()); } private static void addReferences(int offset, PsiElement element, final Collection<PsiReference> outReferences, PyResolveContext resolveContext) { final PsiReference[] references; if (element instanceof PyReferenceOwner) { final PsiPolyVariantReference reference = ((PyReferenceOwner)element).getReference(resolveContext); references = reference == null ? PsiReference.EMPTY_ARRAY : new PsiReference[] {reference}; } else { references = element.getReferences(); } for (final PsiReference reference : references) { for (TextRange range : ReferenceRange.getRanges(reference)) { assert range != null : reference; if (range.containsOffset(offset)) { outReferences.add(reference); } } } } }
ivan-fedorov/intellij-community
python/src/com/jetbrains/python/psi/impl/PyBaseElementImpl.java
Java
apache-2.0
6,862
// PR c++/35315 typedef union { int i; } U __attribute__((transparent_union)); static void foo(U) {} static void foo(int) {} void bar() { foo(0); } typedef union U1 { int i; } U2 __attribute__((transparent_union)); // { dg-warning "ignored" } static void foo2(U1) {} // { dg-error "previously defined" } static void foo2(U2) {} // { dg-error "redefinition" } void bar2(U1 u1, U2 u2) { foo2(u1); foo2(u2); } // PR c++/36410 struct A { typedef union { int i; } B __attribute__((transparent_union)); }; void foo(A::B b) { b.i; }
the-linix-project/linix-kernel-source
gccsrc/gcc-4.7.2/gcc/testsuite/g++.dg/ext/attrib32.C
C++
bsd-2-clause
554
<?php /** Kongo (Kongo) * * See MessagesQqq.php for message documentation incl. usage of parameters * To improve a translation please visit http://translatewiki.net * * @ingroup Language * @file * * @author Rkupsala * @author לערי ריינהארט */ $messages = array( 'underline-always' => 'Bambala nyonso', 'underline-never' => 'Ata mbala mosi ve', # Dates 'sunday' => 'Lumîngu', 'monday' => 'Kimosi', 'tuesday' => 'Kizôle', 'wednesday' => 'Kitatu', 'thursday' => 'Kîya', 'friday' => 'Kitânu', 'saturday' => 'Sabala', 'sun' => 'Lum', 'mon' => 'ki-1', 'tue' => 'ki-2', 'wed' => 'ki-3', 'thu' => 'ki-4', 'fri' => 'ki-5', 'sat' => 'Sab', 'january' => 'ngônda ya ntete', 'february' => 'ngônda ya zôle', 'march' => 'ngônda ya tatu', 'april' => 'ngônda ya yiya', 'may_long' => 'ngônda ya tânu', 'june' => 'ngônda ya sambânu', 'july' => 'ngônda ya nsambwâdi', 'august' => 'ngônda ya nâna', 'september' => 'ngônda ya yivwa', 'october' => 'ngônda ya kûmi', 'november' => 'ngônda ya kûmi na mosi', 'december' => 'ngôida ya kûmi na zôle', 'january-gen' => 'ngônda ya ntete', 'february-gen' => 'ngônda ya zôle', 'march-gen' => 'ngônda ya tatu', 'april-gen' => 'ngônda ya yiya', 'may-gen' => 'ngônda ya tânu', 'june-gen' => 'ngônda ya sambânu', 'july-gen' => 'ngônda ya nsambwâdi', 'august-gen' => 'ngônda ya nâna', 'september-gen' => 'ngônda ya yivwa', 'october-gen' => 'ngônda ya kûmi', 'november-gen' => 'ngônda ya kûmi na mosi', 'december-gen' => 'ngônda ya kûmi na zôle', 'jan' => 'ng1', 'feb' => 'ng2', 'mar' => 'ng3', 'apr' => 'ng4', 'may' => 'ng5', 'jun' => 'ng6', 'jul' => 'ng7', 'aug' => 'ng8', 'sep' => 'ng9', 'oct' => 'ng10', 'nov' => 'ng11', 'dec' => 'ng12', # Categories related messages 'pagecategories' => '{{PLURAL:$1|Kalasi|Bakalasi}}', 'category_header' => 'Mikanda na kalasi "$1"', 'article' => 'Pagina contenta continens', 'cancel' => 'Katula', 'mypage' => 'Lukaya ya munu', 'mytalk' => 'Disolo ya munu', 'and' => '&#32;mpe', # Cologne Blue skin 'qbfind' => 'Sosa', 'qbbrowse' => 'Tala', 'qbedit' => 'Soba', # Vector skin 'vector-action-delete' => 'Kufwa', 'vector-action-move' => 'Nata', 'vector-view-edit' => 'Sonika', 'vector-view-history' => 'Tala bansoba', 'vector-view-view' => 'Tânga', 'errorpagetitle' => 'Foti', 'returnto' => 'Vutukila $1', 'help' => 'Nsadisa', 'search' => 'Sosa', 'searchbutton' => 'Sosa', 'searcharticle' => 'Kwenda', 'history' => 'Bansoba ya mukanda', 'history_short' => 'Bansoba', 'view' => 'Tala', 'edit' => 'Sonika', 'editthispage' => 'Soba mukanda yayi', 'delete' => 'Kufwa', 'deletethispage' => 'Kufwa mukanda yayi', 'talkpagelinktext' => 'Disolo', 'talk' => 'Disolo', 'views' => 'Bantadilu', 'toolbox' => 'Bisadilu', 'viewtalkpage' => 'Tala disolo', 'otherlanguages' => 'Bandinga ya nkaka', 'redirectedfrom' => '(Balulama tuka $1)', 'lastmodifiedat' => 'Mukânda yayi me sobama na kilumbu $1 na ngûnga $2', 'jumpto' => 'Pamuka na:', 'jumptosearch' => 'nsosa', # All link text and link target definitions of links into project namespace that get used by other message strings, with the exception of user group pages (see grouppage) and the disambiguation template definition (see disambiguations). 'currentevents' => 'Mambu ya mpa', 'currentevents-url' => 'Project:Mambu ya mpa', 'mainpage' => 'Lukaya ya mfumu', 'mainpage-description' => 'Lukaya ya mfumu', 'retrievedfrom' => 'Receptum de "$1"', 'youhavenewmessages' => 'Nge kele na $1 ($2).', 'newmessageslink' => 'bansangu ya yimpa', 'youhavenewmessagesmulti' => 'Nge kele na bansangu ya yimpa kuna $1', 'editsection' => 'soba', 'editold' => 'soba', 'editlink' => 'soba', 'editsectionhint' => 'Soba kibuku: $1', 'red-link-title' => '$1 (mukanda kele ve)', # Short words for each namespace, by default used in the namespace tab in monobook 'nstab-main' => 'Mukanda', 'nstab-mediawiki' => 'Nsangu', 'nstab-category' => 'Kalasi', # Login and logout pages 'yourname' => 'Nkûmbu ya nsoniki:', 'yourpassword' => 'Mpovo ya kuluta:', 'login' => 'Kota', 'userlogin' => 'Kota / sala konti', 'logout' => 'Basika', 'userlogout' => 'Basika', 'nologin' => 'Nge kele na konti ve? $1.', 'nologinlink' => 'Sala konti', 'createaccount' => 'Sala konti', 'gotaccountlink' => 'Kota', 'loginlanguagelabel' => 'Ndinga: $1', # Edit pages 'newarticle' => '(Yimpa)', 'editing' => 'Na kusonika $1', 'editingsection' => 'Na kusonika $1 (kibuku)', # History pages 'history-fieldset-title' => 'Monisa bansoba', 'histfirst' => 'Ya ntete', 'histlast' => 'Ya nsuka', # Diffs 'lineno' => 'Nzila ya $1:', 'editundo' => 'vutula', # Search results 'prevn' => 'biyita {{PLURAL:$1|$1}}', 'nextn' => 'bilandi {{PLURAL:$1|$1}}', 'viewprevnext' => 'Mona ($1 {{int:pipe-separator}} $2) ($3).', 'searchprofile-everything' => 'Nyonso', 'searchprofile-articles-tooltip' => 'Sosa na $1', 'searchprofile-project-tooltip' => 'Sosa na $1', 'search-result-size' => '$1 ({{PLURAL:$2|mpovo 1|bampovo $2}})', 'search-section' => '(kibuku $1)', 'searchall' => 'nyonso', 'powersearch' => 'Sosa', # Preferences page 'mypreferences' => 'Konte ya munu', 'yourlanguage' => 'Ndinga:', # Recent changes 'recentchanges' => 'Bansoba ya yimpa', 'recentchanges-label-minor' => 'Nsoba yayi kele ya fyoti-fyoti', 'recentchanges-label-bot' => 'Nsoba yayi me salama na robo', 'rcshowhideminor' => '$1 bansoba ya fyoti-fyoti', 'rcshowhidemine' => '$1 bansoba na munu', 'diff' => 'nsoba', 'hist' => 'nsoba', 'show' => 'Monisa', 'minoreditletter' => 'f', # File description page 'filehist-datetime' => 'Kilumbu/Ngûnga', 'filehist-user' => 'Nsoniki', # Random page 'randompage' => 'Lukaya na kintulumukini', # Miscellaneous special pages 'ncategories' => '{{PLURAL:$1|kalasi|bakalasi}} $1', 'newpages' => 'Mikanda ya yimpa', # Special:AllPages 'alphaindexline' => '$1 tî $2', # Special:Categories 'categories' => 'Bakalasi', # Contributions 'mycontris' => 'Makabu ya munu', 'month' => 'Katuka ngônda:', 'year' => 'Katuka mvula:', 'sp-contributions-talk' => 'disolo', # What links here 'whatlinkshere' => 'Balukaya ke songa awa', # Move page 'movearticle' => 'Nata lukaya:', 'newtitle' => 'Nkûmbu ya nkaka:', 'movepagebtn' => 'Nata lukaya', 'pagemovedsub' => 'Kunata me nunga', 'movepage-moved' => '\'\'\'"$1" me natama na "$2"\'\'\'', 'articleexists' => 'Lukaya ya nkaka kele na nkûmbu yango, to nkûmbu yango kele ya mbote ve. Sôla nkûmbu ya nkaka.', 'movereason' => 'Samu:', # Tooltip help for the actions 'tooltip-pt-userpage' => 'Mukanda ya munu', 'tooltip-pt-mytalk' => 'Disolo ya munu', 'tooltip-pt-logout' => 'Basika', 'tooltip-search' => 'Sosa na {{SITENAME}}', 'tooltip-undo' => '"Vutula" ke vutula nsoba yayi mpe yawu ke monisa lumoni ya kusoba. Nge lênda sonika kikuma ya mvutula.', # 'all' in various places, this might be different for inflected languages 'namespacesall' => 'nyonso', 'monthsall' => 'nyonso', # Table pager 'table_pager_next' => 'Lukaya ya kulanda', 'table_pager_prev' => 'Lukaya ya kuyita', 'table_pager_first' => 'Lukaya ya ntete', 'table_pager_last' => 'Lukaya ya nsuka', );
AKFourSeven/antoinekougblenou
old/wiki/languages/messages/MessagesKg.php
PHP
mit
8,092
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ /** * MUI CSS/JS main module * @module main */ (function(win) { 'use strict'; // return if library has been loaded already if (win._muiLoadedJS) return; else win._muiLoadedJS = true; // load dependencies var jqLite = require('src/js/lib/jqLite'), dropdown = require('src/js/dropdown'), overlay = require('src/js/overlay'), ripple = require('src/js/ripple'), select = require('src/js/select'), tabs = require('src/js/tabs'), textfield = require('src/js/textfield'); // expose api win.mui = { overlay: overlay, tabs: tabs.api }; // init libraries jqLite.ready(function() { textfield.initListeners(); select.initListeners(); ripple.initListeners(); dropdown.initListeners(); tabs.initListeners(); }); })(window); },{"src/js/dropdown":6,"src/js/lib/jqLite":7,"src/js/overlay":8,"src/js/ripple":9,"src/js/select":10,"src/js/tabs":11,"src/js/textfield":12}],2:[function(require,module,exports){ /** * MUI config module * @module config */ /** Define module API */ module.exports = { /** Use debug mode */ debug: true }; },{}],3:[function(require,module,exports){ /** * MUI CSS/JS form helpers module * @module lib/forms.py */ 'use strict'; var wrapperPadding = 15, // from CSS inputHeight = 32, // from CSS rowHeight = 42, // from CSS menuPadding = 8; // from CSS /** * Menu position/size/scroll helper * @returns {Object} Object with keys 'height', 'top', 'scrollTop' */ function getMenuPositionalCSSFn(wrapperEl, numRows, selectedRow) { var viewHeight = document.documentElement.clientHeight; // determine 'height' var h = numRows * rowHeight + 2 * menuPadding, height = Math.min(h, viewHeight); // determine 'top' var top, initTop, minTop, maxTop; initTop = (menuPadding + rowHeight) - (wrapperPadding + inputHeight); initTop -= selectedRow * rowHeight; minTop = -1 * wrapperEl.getBoundingClientRect().top; maxTop = (viewHeight - height) + minTop; top = Math.min(Math.max(initTop, minTop), maxTop); // determine 'scrollTop' var scrollTop = 0, scrollIdeal, scrollMax; if (h > viewHeight) { scrollIdeal = (menuPadding + (selectedRow + 1) * rowHeight) - (-1 * top + wrapperPadding + inputHeight); scrollMax = numRows * rowHeight + 2 * menuPadding - height; scrollTop = Math.min(scrollIdeal, scrollMax); } return { 'height': height + 'px', 'top': top + 'px', 'scrollTop': scrollTop }; } /** Define module API */ module.exports = { getMenuPositionalCSS: getMenuPositionalCSSFn }; },{}],4:[function(require,module,exports){ /** * MUI CSS/JS jqLite module * @module lib/jqLite */ 'use strict'; /** * Add a class to an element. * @param {Element} element - The DOM element. * @param {string} cssClasses - Space separated list of class names. */ function jqLiteAddClass(element, cssClasses) { if (!cssClasses || !element.setAttribute) return; var existingClasses = _getExistingClasses(element), splitClasses = cssClasses.split(' '), cssClass; for (var i=0; i < splitClasses.length; i++) { cssClass = splitClasses[i].trim(); if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) { existingClasses += cssClass + ' '; } } element.setAttribute('class', existingClasses.trim()); } /** * Get or set CSS properties. * @param {Element} element - The DOM element. * @param {string} [name] - The property name. * @param {string} [value] - The property value. */ function jqLiteCss(element, name, value) { // Return full style object if (name === undefined) { return getComputedStyle(element); } var nameType = jqLiteType(name); // Set multiple values if (nameType === 'object') { for (var key in name) element.style[_camelCase(key)] = name[key]; return; } // Set a single value if (nameType === 'string' && value !== undefined) { element.style[_camelCase(name)] = value; } var styleObj = getComputedStyle(element), isArray = (jqLiteType(name) === 'array'); // Read single value if (!isArray) return _getCurrCssProp(element, name, styleObj); // Read multiple values var outObj = {}, key; for (var i=0; i < name.length; i++) { key = name[i]; outObj[key] = _getCurrCssProp(element, key, styleObj); } return outObj; } /** * Check if element has class. * @param {Element} element - The DOM element. * @param {string} cls - The class name string. */ function jqLiteHasClass(element, cls) { if (!cls || !element.getAttribute) return false; return (_getExistingClasses(element).indexOf(' ' + cls + ' ') > -1); } /** * Return the type of a variable. * @param {} somevar - The JavaScript variable. */ function jqLiteType(somevar) { // handle undefined if (somevar === undefined) return 'undefined'; // handle others (of type [object <Type>]) var typeStr = Object.prototype.toString.call(somevar); if (typeStr.indexOf('[object ') === 0) { return typeStr.slice(8, -1).toLowerCase(); } else { throw new Error("MUI: Could not understand type: " + typeStr); } } /** * Attach an event handler to a DOM element * @param {Element} element - The DOM element. * @param {string} events - Space separated event names. * @param {Function} callback - The callback function. * @param {Boolean} useCapture - Use capture flag. */ function jqLiteOn(element, events, callback, useCapture) { useCapture = (useCapture === undefined) ? false : useCapture; var cache = element._muiEventCache = element._muiEventCache || {}; events.split(' ').map(function(event) { // add to DOM element.addEventListener(event, callback, useCapture); // add to cache cache[event] = cache[event] || []; cache[event].push([callback, useCapture]); }); } /** * Remove an event handler from a DOM element * @param {Element} element - The DOM element. * @param {string} events - Space separated event names. * @param {Function} callback - The callback function. * @param {Boolean} useCapture - Use capture flag. */ function jqLiteOff(element, events, callback, useCapture) { useCapture = (useCapture === undefined) ? false : useCapture; // remove from cache var cache = element._muiEventCache = element._muiEventCache || {}, argsList, args, i; events.split(' ').map(function(event) { argsList = cache[event] || []; i = argsList.length; while (i--) { args = argsList[i]; // remove all events if callback is undefined if (callback === undefined || (args[0] === callback && args[1] === useCapture)) { // remove from cache argsList.splice(i, 1); // remove from DOM element.removeEventListener(event, args[0], args[1]); } } }); } /** * Attach an event hander which will only execute once per element per event * @param {Element} element - The DOM element. * @param {string} events - Space separated event names. * @param {Function} callback - The callback function. * @param {Boolean} useCapture - Use capture flag. */ function jqLiteOne(element, events, callback, useCapture) { events.split(' ').map(function(event) { jqLiteOn(element, event, function onFn(ev) { // execute callback if (callback) callback.apply(this, arguments); // remove wrapper jqLiteOff(element, event, onFn); }, useCapture); }); } /** * Get or set horizontal scroll position * @param {Element} element - The DOM element * @param {number} [value] - The scroll position */ function jqLiteScrollLeft(element, value) { var win = window; // get if (value === undefined) { if (element === win) { var docEl = document.documentElement; return (win.pageXOffset || docEl.scrollLeft) - (docEl.clientLeft || 0); } else { return element.scrollLeft; } } // set if (element === win) win.scrollTo(value, jqLiteScrollTop(win)); else element.scrollLeft = value; } /** * Get or set vertical scroll position * @param {Element} element - The DOM element * @param {number} value - The scroll position */ function jqLiteScrollTop(element, value) { var win = window; // get if (value === undefined) { if (element === win) { var docEl = document.documentElement; return (win.pageYOffset || docEl.scrollTop) - (docEl.clientTop || 0); } else { return element.scrollTop; } } // set if (element === win) win.scrollTo(jqLiteScrollLeft(win), value); else element.scrollTop = value; } /** * Return object representing top/left offset and element height/width. * @param {Element} element - The DOM element. */ function jqLiteOffset(element) { var win = window, rect = element.getBoundingClientRect(), scrollTop = jqLiteScrollTop(win), scrollLeft = jqLiteScrollLeft(win); return { top: rect.top + scrollTop, left: rect.left + scrollLeft, height: rect.height, width: rect.width }; } /** * Attach a callback to the DOM ready event listener * @param {Function} fn - The callback function. */ function jqLiteReady(fn) { var done = false, top = true, doc = document, win = doc.defaultView, root = doc.documentElement, add = doc.addEventListener ? 'addEventListener' : 'attachEvent', rem = doc.addEventListener ? 'removeEventListener' : 'detachEvent', pre = doc.addEventListener ? '' : 'on'; var init = function(e) { if (e.type == 'readystatechange' && doc.readyState != 'complete') { return; } (e.type == 'load' ? win : doc)[rem](pre + e.type, init, false); if (!done && (done = true)) fn.call(win, e.type || e); }; var poll = function() { try { root.doScroll('left'); } catch(e) { setTimeout(poll, 50); return; } init('poll'); }; if (doc.readyState == 'complete') { fn.call(win, 'lazy'); } else { if (doc.createEventObject && root.doScroll) { try { top = !win.frameElement; } catch(e) { } if (top) poll(); } doc[add](pre + 'DOMContentLoaded', init, false); doc[add](pre + 'readystatechange', init, false); win[add](pre + 'load', init, false); } } /** * Remove classes from a DOM element * @param {Element} element - The DOM element. * @param {string} cssClasses - Space separated list of class names. */ function jqLiteRemoveClass(element, cssClasses) { if (!cssClasses || !element.setAttribute) return; var existingClasses = _getExistingClasses(element), splitClasses = cssClasses.split(' '), cssClass; for (var i=0; i < splitClasses.length; i++) { cssClass = splitClasses[i].trim(); while (existingClasses.indexOf(' ' + cssClass + ' ') >= 0) { existingClasses = existingClasses.replace(' ' + cssClass + ' ', ' '); } } element.setAttribute('class', existingClasses.trim()); } // ------------------------------ // Utilities // ------------------------------ var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g, MOZ_HACK_REGEXP = /^moz([A-Z])/, ESCAPE_REGEXP = /([.*+?^=!:${}()|\[\]\/\\])/g; function _getExistingClasses(element) { var classes = (element.getAttribute('class') || '').replace(/[\n\t]/g, ''); return ' ' + classes + ' '; } function _camelCase(name) { return name. replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) { return offset ? letter.toUpperCase() : letter; }). replace(MOZ_HACK_REGEXP, 'Moz$1'); } function _escapeRegExp(string) { return string.replace(ESCAPE_REGEXP, "\\$1"); } function _getCurrCssProp(elem, name, computed) { var ret; // try computed style ret = computed.getPropertyValue(name); // try style attribute (if element is not attached to document) if (ret === '' && !elem.ownerDocument) ret = elem.style[_camelCase(name)]; return ret; } /** * Module API */ module.exports = { /** Add classes */ addClass: jqLiteAddClass, /** Get or set CSS properties */ css: jqLiteCss, /** Check for class */ hasClass: jqLiteHasClass, /** Remove event handlers */ off: jqLiteOff, /** Return offset values */ offset: jqLiteOffset, /** Add event handlers */ on: jqLiteOn, /** Add an execute-once event handler */ one: jqLiteOne, /** DOM ready event handler */ ready: jqLiteReady, /** Remove classes */ removeClass: jqLiteRemoveClass, /** Check JavaScript variable instance type */ type: jqLiteType, /** Get or set horizontal scroll position */ scrollLeft: jqLiteScrollLeft, /** Get or set vertical scroll position */ scrollTop: jqLiteScrollTop }; },{}],5:[function(require,module,exports){ /** * MUI CSS/JS utilities module * @module lib/util */ 'use strict'; var config = require('../config'), jqLite = require('./jqLite'), nodeInsertedCallbacks = [], scrollLock = 0, scrollLockCls = 'mui-body--scroll-lock', scrollLockPos, _supportsPointerEvents; /** * Logging function */ function logFn() { var win = window; if (config.debug && typeof win.console !== "undefined") { try { win.console.log.apply(win.console, arguments); } catch (a) { var e = Array.prototype.slice.call(arguments); win.console.log(e.join("\n")); } } } /** * Load CSS text in new stylesheet * @param {string} cssText - The css text. */ function loadStyleFn(cssText) { var doc = document, head; // copied from jQuery head = doc.head || doc.getElementsByTagName('head')[0] || doc.documentElement; var e = doc.createElement('style'); e.type = 'text/css'; if (e.styleSheet) e.styleSheet.cssText = cssText; else e.appendChild(doc.createTextNode(cssText)); // add to document head.insertBefore(e, head.firstChild); return e; } /** * Raise an error * @param {string} msg - The error message. */ function raiseErrorFn(msg, useConsole) { if (useConsole) { if (typeof console !== 'undefined') console.error('MUI Warning: ' + msg); } else { throw new Error('MUI: ' + msg); } } /** * Register callbacks on muiNodeInserted event * @param {function} callbackFn - The callback function. */ function onNodeInsertedFn(callbackFn) { nodeInsertedCallbacks.push(callbackFn); // initalize listeners if (nodeInsertedCallbacks._initialized === undefined) { var doc = document, events = 'animationstart mozAnimationStart webkitAnimationStart'; jqLite.on(doc, events, animationHandlerFn); nodeInsertedCallbacks._initialized = true; } } /** * Execute muiNodeInserted callbacks * @param {Event} ev - The DOM event. */ function animationHandlerFn(ev) { // check animation name if (ev.animationName !== 'mui-node-inserted') return; var el = ev.target; // iterate through callbacks for (var i=nodeInsertedCallbacks.length - 1; i >= 0; i--) { nodeInsertedCallbacks[i](el); } } /** * Convert Classname object, with class as key and true/false as value, to an * class string. * @param {Object} classes The classes * @return {String} class string */ function classNamesFn(classes) { var cs = ''; for (var i in classes) { cs += (classes[i]) ? i + ' ' : ''; } return cs.trim(); } /** * Check if client supports pointer events. */ function supportsPointerEventsFn() { // check cache if (_supportsPointerEvents !== undefined) return _supportsPointerEvents; var element = document.createElement('x'); element.style.cssText = 'pointer-events:auto'; _supportsPointerEvents = (element.style.pointerEvents === 'auto'); return _supportsPointerEvents; } /** * Create callback closure. * @param {Object} instance - The object instance. * @param {String} funcName - The name of the callback function. */ function callbackFn(instance, funcName) { return function() {instance[funcName].apply(instance, arguments);}; } /** * Dispatch event. * @param {Element} element - The DOM element. * @param {String} eventType - The event type. * @param {Boolean} bubbles=true - If true, event bubbles. * @param {Boolean} cancelable=true = If true, event is cancelable * @param {Object} [data] - Data to add to event object */ function dispatchEventFn(element, eventType, bubbles, cancelable, data) { var ev = document.createEvent('HTMLEvents'), bubbles = (bubbles !== undefined) ? bubbles : true, cancelable = (cancelable !== undefined) ? cancelable : true, k; ev.initEvent(eventType, bubbles, cancelable); // add data to event object if (data) for (k in data) ev[k] = data[k]; // dispatch if (element) element.dispatchEvent(ev); return ev; } /** * Turn on window scroll lock. */ function enableScrollLockFn() { // increment counter scrollLock += 1 // add lock if (scrollLock === 1) { var win = window, doc = document; scrollLockPos = {left: jqLite.scrollLeft(win), top: jqLite.scrollTop(win)}; jqLite.addClass(doc.body, scrollLockCls); win.scrollTo(scrollLockPos.left, scrollLockPos.top); } } /** * Turn off window scroll lock. * @param {Boolean} resetPos - Reset scroll position to original value. */ function disableScrollLockFn(resetPos) { // ignore if (scrollLock === 0) return; // decrement counter scrollLock -= 1 // remove lock if (scrollLock === 0) { var win = window, doc = document; jqLite.removeClass(doc.body, scrollLockCls); if (resetPos) win.scrollTo(scrollLockPos.left, scrollLockPos.top); } } /** * requestAnimationFrame polyfilled * @param {Function} callback - The callback function */ function requestAnimationFrameFn(callback) { var fn = window.requestAnimationFrame; if (fn) fn(callback); else setTimeout(callback, 0); } /** * Define the module API */ module.exports = { /** Create callback closures */ callback: callbackFn, /** Classnames object to string */ classNames: classNamesFn, /** Disable scroll lock */ disableScrollLock: disableScrollLockFn, /** Dispatch event */ dispatchEvent: dispatchEventFn, /** Enable scroll lock */ enableScrollLock: enableScrollLockFn, /** Log messages to the console when debug is turned on */ log: logFn, /** Load CSS text as new stylesheet */ loadStyle: loadStyleFn, /** Register muiNodeInserted handler */ onNodeInserted: onNodeInsertedFn, /** Raise MUI error */ raiseError: raiseErrorFn, /** Request animation frame */ requestAnimationFrame: requestAnimationFrameFn, /** Support Pointer Events check */ supportsPointerEvents: supportsPointerEventsFn }; },{"../config":2,"./jqLite":4}],6:[function(require,module,exports){ /** * MUI CSS/JS dropdown module * @module dropdowns */ 'use strict'; var jqLite = require('./lib/jqLite'), util = require('./lib/util'), attrKey = 'data-mui-toggle', attrSelector = '[data-mui-toggle="dropdown"]', openClass = 'mui--is-open', menuClass = 'mui-dropdown__menu'; /** * Initialize toggle element. * @param {Element} toggleEl - The toggle element. */ function initialize(toggleEl) { // check flag if (toggleEl._muiDropdown === true) return; else toggleEl._muiDropdown = true; // use type "button" to prevent form submission by default if (!toggleEl.hasAttribute('type')) toggleEl.type = 'button'; // attach click handler jqLite.on(toggleEl, 'click', clickHandler); } /** * Handle click events on dropdown toggle element. * @param {Event} ev - The DOM event */ function clickHandler(ev) { // only left clicks if (ev.button !== 0) return; var toggleEl = this; // exit if toggle button is disabled if (toggleEl.getAttribute('disabled') !== null) return; // toggle dropdown toggleDropdown(toggleEl); } /** * Toggle the dropdown. * @param {Element} toggleEl - The dropdown toggle element. */ function toggleDropdown(toggleEl) { var wrapperEl = toggleEl.parentNode, menuEl = toggleEl.nextElementSibling, doc = wrapperEl.ownerDocument; // exit if no menu element if (!menuEl || !jqLite.hasClass(menuEl, menuClass)) { return util.raiseError('Dropdown menu element not found'); } // method to close dropdown function closeDropdownFn() { jqLite.removeClass(menuEl, openClass); // remove event handlers jqLite.off(doc, 'click', closeDropdownFn); } // method to open dropdown function openDropdownFn() { // position menu element below toggle button var wrapperRect = wrapperEl.getBoundingClientRect(), toggleRect = toggleEl.getBoundingClientRect(); var top = toggleRect.top - wrapperRect.top + toggleRect.height; jqLite.css(menuEl, 'top', top + 'px'); // add open class to wrapper jqLite.addClass(menuEl, openClass); // close dropdown when user clicks outside of menu setTimeout(function() {jqLite.on(doc, 'click', closeDropdownFn);}, 0); } // toggle dropdown if (jqLite.hasClass(menuEl, openClass)) closeDropdownFn(); else openDropdownFn(); } /** Define module API */ module.exports = { /** Initialize module listeners */ initListeners: function() { var doc = document; // markup elements available when method is called var elList = doc.querySelectorAll(attrSelector); for (var i=elList.length - 1; i >= 0; i--) initialize(elList[i]); // listen for new elements util.onNodeInserted(function(el) { if (el.getAttribute(attrKey) === 'dropdown') initialize(el); }); } }; },{"./lib/jqLite":4,"./lib/util":5}],7:[function(require,module,exports){ module.exports=require(4) },{}],8:[function(require,module,exports){ /** * MUI CSS/JS overlay module * @module overlay */ 'use strict'; var util = require('./lib/util'), jqLite = require('./lib/jqLite'), overlayId = 'mui-overlay', bodyClass = 'mui--overflow-hidden', iosRegex = /(iPad|iPhone|iPod)/g; /** * Turn overlay on/off. * @param {string} action - Turn overlay "on"/"off". * @param {object} [options] * @config {boolean} [keyboard] - If true, close when escape key is pressed. * @config {boolean} [static] - If false, close when backdrop is clicked. * @config {Function} [onclose] - Callback function to execute on close * @param {Element} [childElement] - Child element to add to overlay. */ function overlayFn(action) { var overlayEl; if (action === 'on') { // extract arguments var arg, options, childElement; // pull options and childElement from arguments for (var i=arguments.length - 1; i > 0; i--) { arg = arguments[i]; if (jqLite.type(arg) === 'object') options = arg; if (arg instanceof Element && arg.nodeType === 1) childElement = arg; } // option defaults options = options || {}; if (options.keyboard === undefined) options.keyboard = true; if (options.static === undefined) options.static = false; // execute method overlayEl = overlayOn(options, childElement); } else if (action === 'off') { overlayEl = overlayOff(); } else { // raise error util.raiseError("Expecting 'on' or 'off'"); } return overlayEl; } /** * Turn on overlay. * @param {object} options - Overlay options. * @param {Element} childElement - The child element. */ function overlayOn(options, childElement) { var bodyEl = document.body, overlayEl = document.getElementById(overlayId); // add overlay util.enableScrollLock(); //jqLite.addClass(bodyEl, bodyClass); if (!overlayEl) { // create overlayEl overlayEl = document.createElement('div'); overlayEl.setAttribute('id', overlayId); // add child element if (childElement) overlayEl.appendChild(childElement); bodyEl.appendChild(overlayEl); } else { // remove existing children while (overlayEl.firstChild) overlayEl.removeChild(overlayEl.firstChild); // add child element if (childElement) overlayEl.appendChild(childElement); } // iOS bugfix if (iosRegex.test(navigator.userAgent)) { jqLite.css(overlayEl, 'cursor', 'pointer'); } // handle options if (options.keyboard) addKeyupHandler(); else removeKeyupHandler(); if (options.static) removeClickHandler(overlayEl); else addClickHandler(overlayEl); // attach options overlayEl.muiOptions = options; return overlayEl; } /** * Turn off overlay. */ function overlayOff() { var overlayEl = document.getElementById(overlayId), callbackFn; if (overlayEl) { // remove children while (overlayEl.firstChild) overlayEl.removeChild(overlayEl.firstChild); // remove overlay element overlayEl.parentNode.removeChild(overlayEl); // callback reference callbackFn = overlayEl.muiOptions.onclose; // remove click handler removeClickHandler(overlayEl); } util.disableScrollLock(); // remove keyup handler removeKeyupHandler(); // execute callback if (callbackFn) callbackFn(); return overlayEl; } /** * Add keyup handler. */ function addKeyupHandler() { jqLite.on(document, 'keyup', onKeyup); } /** * Remove keyup handler. */ function removeKeyupHandler() { jqLite.off(document, 'keyup', onKeyup); } /** * Teardown overlay when escape key is pressed. */ function onKeyup(ev) { if (ev.keyCode === 27) overlayOff(); } /** * Add click handler. */ function addClickHandler(overlayEl) { jqLite.on(overlayEl, 'click', onClick); } /** * Remove click handler. */ function removeClickHandler(overlayEl) { jqLite.off(overlayEl, 'click', onClick); } /** * Teardown overlay when backdrop is clicked. */ function onClick(ev) { if (ev.target.id === overlayId) overlayOff(); } /** Define module API */ module.exports = overlayFn; },{"./lib/jqLite":4,"./lib/util":5}],9:[function(require,module,exports){ /** * MUI CSS/JS ripple module * @module ripple */ 'use strict'; var jqLite = require('./lib/jqLite'), util = require('./lib/util'), btnClass = 'mui-btn', btnFABClass = 'mui-btn--fab', rippleClass = 'mui-ripple-effect', supportsTouch = 'ontouchstart' in document.documentElement, mouseDownEvents = (supportsTouch) ? 'touchstart' : 'mousedown', mouseUpEvents = (supportsTouch) ? 'touchend' : 'mouseup mouseleave', animationDuration = 600; /** * Add ripple effects to button element. * @param {Element} buttonEl - The button element. */ function initialize(buttonEl) { // check flag if (buttonEl._muiRipple === true) return; else buttonEl._muiRipple = true; // exit if element is INPUT (doesn't support absolute positioned children) if (buttonEl.tagName === 'INPUT') return; // attach event handler jqLite.on(buttonEl, mouseDownEvents, mouseDownHandler); } /** * MouseDown Event handler. * @param {Event} ev - The DOM event */ function mouseDownHandler(ev) { // only left clicks if (ev.type === 'mousedown' && ev.button !== 0) return; var buttonEl = this; // exit if button is disabled if (buttonEl.disabled === true) return; // add mouseup event to button once if (!buttonEl.muiMouseUp) { jqLite.on(buttonEl, mouseUpEvents, mouseUpHandler); buttonEl.muiMouseUp = true; } // create ripple element var rippleEl = createRippleEl(ev, buttonEl); buttonEl.appendChild(rippleEl); // animate in util.requestAnimationFrame(function() { jqLite.addClass(rippleEl, 'mui--animate-in mui--active'); }); } /** * MouseUp event handler. * @param {Event} ev - The DOM event */ function mouseUpHandler(ev) { var children = this.children, i = children.length, rippleEls = [], el; // animate out ripples while (i--) { el = children[i]; if (jqLite.hasClass(el, rippleClass)) { jqLite.addClass(el, 'mui--animate-out'); rippleEls.push(el); } } // remove ripples after animation if (rippleEls.length) { setTimeout(function() { var i = rippleEls.length, el, parentNode; // remove elements while (i--) { el = rippleEls[i]; parentNode = el.parentNode; if (parentNode) parentNode.removeChild(el); } }, animationDuration); } } /** * Create ripple element * @param {Element} - buttonEl - The button element. */ function createRippleEl(ev, buttonEl) { // get (x, y) position of click var offset = jqLite.offset(buttonEl), clickEv = (ev.type === 'touchstart') ? ev.touches[0] : ev, xPos = clickEv.pageX - offset.left, yPos = clickEv.pageY - offset.top, diameter, radius, rippleEl; // calculate diameter diameter = Math.sqrt(offset.width * offset.width + offset.height * offset.height) * 2; // create element rippleEl = document.createElement('div'), rippleEl.className = rippleClass; radius = diameter / 2; jqLite.css(rippleEl, { height: diameter + 'px', width: diameter + 'px', top: yPos - radius + 'px', left: xPos - radius + 'px' }); return rippleEl; } /** Define module API */ module.exports = { /** Initialize module listeners */ initListeners: function() { var doc = document; // markup elements available when method is called var elList = doc.getElementsByClassName(btnClass); for (var i=elList.length - 1; i >= 0; i--) initialize(elList[i]); // listen for new elements util.onNodeInserted(function(el) { if (jqLite.hasClass(el, btnClass)) initialize(el); }); } }; },{"./lib/jqLite":4,"./lib/util":5}],10:[function(require,module,exports){ /** * MUI CSS/JS select module * @module forms/select */ 'use strict'; var jqLite = require('./lib/jqLite'), util = require('./lib/util'), formlib = require('./lib/forms'), wrapperClass = 'mui-select', cssSelector = '.mui-select > select', menuClass = 'mui-select__menu', selectedClass = 'mui--is-selected', doc = document, win = window; /** * Initialize select element. * @param {Element} selectEl - The select element. */ function initialize(selectEl) { // check flag if (selectEl._muiSelect === true) return; else selectEl._muiSelect = true; // use default behavior on touch devices if ('ontouchstart' in doc.documentElement) return; // initialize element new Select(selectEl); } /** * Creates a new Select object * @class */ function Select(selectEl) { // instance variables this.selectEl = selectEl; this.wrapperEl = selectEl.parentNode; this.useDefault = false; // currently unused but let's keep just in case // attach event handlers jqLite.on(selectEl, 'mousedown', util.callback(this, 'mousedownHandler')); jqLite.on(selectEl, 'focus', util.callback(this, 'focusHandler')); jqLite.on(selectEl, 'click', util.callback(this, 'clickHandler')); // make wrapper focusable and fix firefox bug this.wrapperEl.tabIndex = -1; var callbackFn = util.callback(this, 'wrapperFocusHandler'); jqLite.on(this.wrapperEl, 'focus', callbackFn); } /** * Disable default dropdown on mousedown. * @param {Event} ev - The DOM event */ Select.prototype.mousedownHandler = function(ev) { if (ev.button !== 0 || this.useDefault === true) return; ev.preventDefault(); } /** * Handle focus event on select element. * @param {Event} ev - The DOM event */ Select.prototype.focusHandler = function(ev) { // check flag if (this.useDefault === true) return; var selectEl = this.selectEl, wrapperEl = this.wrapperEl, tabIndex = selectEl.tabIndex, keydownFn = util.callback(this, 'keydownHandler'); // attach keydown handler jqLite.on(doc, 'keydown', keydownFn); // disable tabfocus once selectEl.tabIndex = -1; jqLite.one(wrapperEl, 'blur', function() { selectEl.tabIndex = tabIndex; jqLite.off(doc, 'keydown', keydownFn); }); // defer focus to parent wrapperEl.focus(); } /** * Handle keydown events on doc **/ Select.prototype.keydownHandler = function(ev) { var keyCode = ev.keyCode; // spacebar, down, up if (keyCode === 32 || keyCode === 38 || keyCode === 40) { // prevent win scroll ev.preventDefault(); if (this.selectEl.disabled !== true) this.renderMenu(); } } /** * Handle focus event on wrapper element. */ Select.prototype.wrapperFocusHandler = function() { // firefox bugfix if (this.selectEl.disabled) return this.wrapperEl.blur(); } /** * Handle click events on select element. * @param {Event} ev - The DOM event */ Select.prototype.clickHandler = function(ev) { // only left clicks if (ev.button !== 0) return; this.renderMenu(); } /** * Render options dropdown. */ Select.prototype.renderMenu = function() { // check and reset flag if (this.useDefault === true) return this.useDefault = false; new Menu(this.wrapperEl, this.selectEl); } /** * Creates a new Menu * @class */ function Menu(wrapperEl, selectEl) { // add scroll lock util.enableScrollLock(); // instance variables this.indexMap = {}; this.origIndex = null; this.currentIndex = null; this.selectEl = selectEl; this.menuEl = this._createMenuEl(wrapperEl, selectEl); this.clickCallbackFn = util.callback(this, 'clickHandler'); this.keydownCallbackFn = util.callback(this, 'keydownHandler'); this.destroyCallbackFn = util.callback(this, 'destroy'); // add to DOM wrapperEl.appendChild(this.menuEl); jqLite.scrollTop(this.menuEl, this.menuEl._muiScrollTop); // blur active element setTimeout(function() { // ie10 bugfix if (doc.activeElement.nodeName.toLowerCase() !== "body") { doc.activeElement.blur(); } }, 0); // attach event handlers jqLite.on(this.menuEl, 'click', this.clickCallbackFn); jqLite.on(doc, 'keydown', this.keydownCallbackFn); jqLite.on(win, 'resize', this.destroyCallbackFn); // attach event handler after current event loop exits var fn = this.destroyCallbackFn; setTimeout(function() {jqLite.on(doc, 'click', fn);}, 0); } /** * Create menu element * @param {Element} selectEl - The select element */ Menu.prototype._createMenuEl = function(wrapperEl, selectEl) { var menuEl = doc.createElement('div'), childEls = selectEl.children, indexNum = 0, indexMap = this.indexMap, selectedRow = 0, loopEl, rowEl, optionEls, inGroup, i, iMax, j, jMax; menuEl.className = menuClass; for (i=0, iMax=childEls.length; i < iMax; i++) { loopEl = childEls[i]; if (loopEl.tagName === 'OPTGROUP') { // add row item to menu rowEl = doc.createElement('div'); rowEl.textContent = loopEl.label; rowEl.className = 'mui-optgroup__label'; menuEl.appendChild(rowEl); inGroup = true; optionEls = loopEl.children; } else { inGroup = false; optionEls = [loopEl]; } // loop through option elements for (j=0, jMax=optionEls.length; j < jMax; j++) { loopEl = optionEls[j]; // add row item to menu rowEl = doc.createElement('div'); rowEl.textContent = loopEl.textContent; rowEl._muiIndex = indexNum; // handle selected options if (loopEl.selected) { rowEl.className = selectedClass; selectedRow = menuEl.children.length; } // handle optgroup options if (inGroup) jqLite.addClass(rowEl, 'mui-optgroup__option'); menuEl.appendChild(rowEl); // add to index map indexMap[indexNum] = rowEl; indexNum += 1; } } // save indices var selectedIndex = selectEl.selectedIndex; this.origIndex = selectedIndex; this.currentIndex = selectedIndex; // set position var props = formlib.getMenuPositionalCSS( wrapperEl, menuEl.children.length, selectedRow ); jqLite.css(menuEl, props); menuEl._muiScrollTop = props.scrollTop; return menuEl; } /** * Handle keydown events on doc element. * @param {Event} ev - The DOM event */ Menu.prototype.keydownHandler = function(ev) { var keyCode = ev.keyCode; // tab if (keyCode === 9) return this.destroy(); // escape | up | down | enter if (keyCode === 27 || keyCode === 40 || keyCode === 38 || keyCode === 13) { ev.preventDefault(); } if (keyCode === 27) { this.destroy(); } else if (keyCode === 40) { this.increment(); } else if (keyCode === 38) { this.decrement(); } else if (keyCode === 13) { this.selectCurrent(); this.destroy(); } } /** * Handle click events on menu element. * @param {Event} ev - The DOM event */ Menu.prototype.clickHandler = function(ev) { // don't allow events to bubble ev.stopPropagation(); var index = ev.target._muiIndex; // ignore clicks on non-items if (index === undefined) return; // select option this.currentIndex = index; this.selectCurrent(); // destroy menu this.destroy(); } /** * Increment selected item */ Menu.prototype.increment = function() { if (this.currentIndex === this.selectEl.length - 1) return; // un-select old row jqLite.removeClass(this.indexMap[this.currentIndex], selectedClass); // select new row this.currentIndex += 1; jqLite.addClass(this.indexMap[this.currentIndex], selectedClass); } /** * Decrement selected item */ Menu.prototype.decrement = function() { if (this.currentIndex === 0) return; // un-select old row jqLite.removeClass(this.indexMap[this.currentIndex], selectedClass); // select new row this.currentIndex -= 1; jqLite.addClass(this.indexMap[this.currentIndex], selectedClass); } /** * Select current item */ Menu.prototype.selectCurrent = function() { if (this.currentIndex !== this.origIndex) { this.selectEl.selectedIndex = this.currentIndex; // trigger change event util.dispatchEvent(this.selectEl, 'change'); } } /** * Destroy menu and detach event handlers */ Menu.prototype.destroy = function() { // remove element and focus element var parentNode = this.menuEl.parentNode; if (parentNode) parentNode.removeChild(this.menuEl); this.selectEl.focus(); // remove scroll lock util.disableScrollLock(true); // remove event handlers jqLite.off(this.menuEl, 'click', this.clickCallbackFn); jqLite.off(doc, 'keydown', this.keydownCallbackFn); jqLite.off(doc, 'click', this.destroyCallbackFn); jqLite.off(win, 'resize', this.destroyCallbackFn); } /** Define module API */ module.exports = { /** Initialize module listeners */ initListeners: function() { // markup elements available when method is called var elList = doc.querySelectorAll(cssSelector); for (var i=elList.length - 1; i >= 0; i--) initialize(elList[i]); // listen for new elements util.onNodeInserted(function(el) { if (el.tagName === 'SELECT' && jqLite.hasClass(el.parentNode, wrapperClass)) { initialize(el); } }); } }; },{"./lib/forms":3,"./lib/jqLite":4,"./lib/util":5}],11:[function(require,module,exports){ /** * MUI CSS/JS tabs module * @module tabs */ 'use strict'; var jqLite = require('./lib/jqLite'), util = require('./lib/util'), attrKey = 'data-mui-toggle', attrSelector = '[' + attrKey + '="tab"]', controlsAttrKey = 'data-mui-controls', activeClass = 'mui--is-active', showstartKey = 'mui.tabs.showstart', showendKey = 'mui.tabs.showend', hidestartKey = 'mui.tabs.hidestart', hideendKey = 'mui.tabs.hideend'; /** * Initialize the toggle element * @param {Element} toggleEl - The toggle element. */ function initialize(toggleEl) { // check flag if (toggleEl._muiTabs === true) return; else toggleEl._muiTabs = true; // attach click handler jqLite.on(toggleEl, 'click', clickHandler); } /** * Handle clicks on the toggle element. * @param {Event} ev - The DOM event. */ function clickHandler(ev) { // only left clicks if (ev.button !== 0) return; var toggleEl = this; // exit if toggle element is disabled if (toggleEl.getAttribute('disabled') !== null) return; activateTab(toggleEl); } /** * Activate the tab controlled by the toggle element. * @param {Element} toggleEl - The toggle element. */ function activateTab(currToggleEl) { var currTabEl = currToggleEl.parentNode, currPaneId = currToggleEl.getAttribute(controlsAttrKey), currPaneEl = document.getElementById(currPaneId), prevTabEl, prevPaneEl, prevPaneId, prevToggleEl, currData, prevData, ev1, ev2, cssSelector; // exit if already active if (jqLite.hasClass(currTabEl, activeClass)) return; // raise error if pane doesn't exist if (!currPaneEl) util.raiseError('Tab pane "' + currPaneId + '" not found'); // get previous pane prevPaneEl = getActiveSibling(currPaneEl); prevPaneId = prevPaneEl.id; // get previous toggle and tab elements cssSelector = '[' + controlsAttrKey + '="' + prevPaneId + '"]'; prevToggleEl = document.querySelectorAll(cssSelector)[0]; prevTabEl = prevToggleEl.parentNode; // define event data currData = {paneId: currPaneId, relatedPaneId: prevPaneId}; prevData = {paneId: prevPaneId, relatedPaneId: currPaneId}; // dispatch 'hidestart', 'showstart' events ev1 = util.dispatchEvent(prevToggleEl, hidestartKey, true, true, prevData); ev2 = util.dispatchEvent(currToggleEl, showstartKey, true, true, currData); // let events bubble setTimeout(function() { // exit if either event was canceled if (ev1.defaultPrevented || ev2.defaultPrevented) return; // de-activate previous if (prevTabEl) jqLite.removeClass(prevTabEl, activeClass); if (prevPaneEl) jqLite.removeClass(prevPaneEl, activeClass); // activate current jqLite.addClass(currTabEl, activeClass); jqLite.addClass(currPaneEl, activeClass); // dispatch 'hideend', 'showend' events util.dispatchEvent(prevToggleEl, hideendKey, true, false, prevData); util.dispatchEvent(currToggleEl, showendKey, true, false, currData); }, 0); } /** * Get previous active sibling. * @param {Element} el - The anchor element. */ function getActiveSibling(el) { var elList = el.parentNode.children, q = elList.length, activeEl = null, tmpEl; while (q-- && !activeEl) { tmpEl = elList[q]; if (tmpEl !== el && jqLite.hasClass(tmpEl, activeClass)) activeEl = tmpEl } return activeEl; } /** Define module API */ module.exports = { /** Initialize module listeners */ initListeners: function() { // markup elements available when method is called var elList = document.querySelectorAll(attrSelector); for (var i=elList.length - 1; i >= 0; i--) initialize(elList[i]); // TODO: listen for new elements util.onNodeInserted(function(el) { if (el.getAttribute(attrKey) === 'tab') initialize(el); }); }, /** External API */ api: { activate: function(paneId) { var cssSelector = '[' + controlsAttrKey + '=' + paneId + ']', toggleEl = document.querySelectorAll(cssSelector); if (!toggleEl.length) { util.raiseError('Tab control for pane "' + paneId + '" not found'); } activateTab(toggleEl[0]); } } }; },{"./lib/jqLite":4,"./lib/util":5}],12:[function(require,module,exports){ /** * MUI CSS/JS form-control module * @module forms/form-control */ 'use strict'; var jqLite = require('./lib/jqLite'), util = require('./lib/util'), cssSelector = '.mui-textfield > input, .mui-textfield > textarea', emptyClass = 'mui--is-empty', notEmptyClass = 'mui--is-not-empty', dirtyClass = 'mui--is-dirty', floatingLabelClass = 'mui-textfield--float-label'; /** * Initialize input element. * @param {Element} inputEl - The input element. */ function initialize(inputEl) { // check flag if (inputEl._muiTextfield === true) return; else inputEl._muiTextfield = true; if (inputEl.value.length) jqLite.addClass(inputEl, notEmptyClass); else jqLite.addClass(inputEl, emptyClass); jqLite.on(inputEl, 'input change', inputHandler); // add dirty class on focus jqLite.on(inputEl, 'focus', function(){jqLite.addClass(this, dirtyClass);}); } /** * Handle input events. */ function inputHandler() { var inputEl = this; if (inputEl.value.length) { jqLite.removeClass(inputEl, emptyClass); jqLite.addClass(inputEl, notEmptyClass); } else { jqLite.removeClass(inputEl, notEmptyClass); jqLite.addClass(inputEl, emptyClass) } jqLite.addClass(inputEl, dirtyClass); } /** Define module API */ module.exports = { /** Initialize input elements */ initialize: initialize, /** Initialize module listeners */ initListeners: function() { var doc = document; // markup elements available when method is called var elList = doc.querySelectorAll(cssSelector); for (var i=elList.length - 1; i >= 0; i--) initialize(elList[i]); // listen for new elements util.onNodeInserted(function(el) { if (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA') initialize(el); }); // add transition css for floating labels setTimeout(function() { var css = '.mui-textfield.mui-textfield--float-label > label {' + [ '-webkit-transition', '-moz-transition', '-o-transition', 'transition', '' ].join(':all .15s ease-out;') + '}'; util.loadStyle(css); }, 150); // pointer-events shim for floating labels if (util.supportsPointerEvents() === false) { jqLite.on(document, 'click', function(ev) { var targetEl = ev.target; if (targetEl.tagName === 'LABEL' && jqLite.hasClass(targetEl.parentNode, floatingLabelClass)) { var inputEl = targetEl.previousElementSibling; if (inputEl) inputEl.focus(); } }); } } }; },{"./lib/jqLite":4,"./lib/util":5}]},{},[1])
joeyparrish/cdnjs
ajax/libs/muicss/0.7.4/js/mui.js
JavaScript
mit
46,197
#!/usr/bin/python # (c) 2017, NetApp, Inc # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' module: sf_account_manager short_description: Manage SolidFire accounts extends_documentation_fragment: - netapp.solidfire version_added: '2.3' author: Sumit Kumar (sumit4@netapp.com) description: - Create, destroy, or update accounts on SolidFire options: state: description: - Whether the specified account should exist or not. required: true choices: ['present', 'absent'] name: description: - Unique username for this account. (May be 1 to 64 characters in length). required: true new_name: description: - New name for the user account. required: false default: None initiator_secret: description: - CHAP secret to use for the initiator. Should be 12-16 characters long and impenetrable. - The CHAP initiator secrets must be unique and cannot be the same as the target CHAP secret. - If not specified, a random secret is created. required: false target_secret: description: - CHAP secret to use for the target (mutual CHAP authentication). - Should be 12-16 characters long and impenetrable. - The CHAP target secrets must be unique and cannot be the same as the initiator CHAP secret. - If not specified, a random secret is created. required: false attributes: description: List of Name/Value pairs in JSON object format. required: false account_id: description: - The ID of the account to manage or update. required: false default: None status: description: - Status of the account. required: false ''' EXAMPLES = """ - name: Create Account sf_account_manager: hostname: "{{ solidfire_hostname }}" username: "{{ solidfire_username }}" password: "{{ solidfire_password }}" state: present name: TenantA - name: Modify Account sf_account_manager: hostname: "{{ solidfire_hostname }}" username: "{{ solidfire_username }}" password: "{{ solidfire_password }}" state: present name: TenantA new_name: TenantA-Renamed - name: Delete Account sf_account_manager: hostname: "{{ solidfire_hostname }}" username: "{{ solidfire_username }}" password: "{{ solidfire_password }}" state: absent name: TenantA-Renamed """ RETURN = """ """ import traceback from ansible.module_utils.basic import AnsibleModule from ansible.module_utils._text import to_native import ansible.module_utils.netapp as netapp_utils HAS_SF_SDK = netapp_utils.has_sf_sdk() class SolidFireAccount(object): def __init__(self): self.argument_spec = netapp_utils.ontap_sf_host_argument_spec() self.argument_spec.update(dict( state=dict(required=True, choices=['present', 'absent']), name=dict(required=True, type='str'), account_id=dict(required=False, type='int', default=None), new_name=dict(required=False, type='str', default=None), initiator_secret=dict(required=False, type='str'), target_secret=dict(required=False, type='str'), attributes=dict(required=False, type='dict'), status=dict(required=False, type='str'), )) self.module = AnsibleModule( argument_spec=self.argument_spec, supports_check_mode=True ) p = self.module.params # set up state variables self.state = p['state'] self.name = p['name'] self.account_id = p['account_id'] self.new_name = p['new_name'] self.initiator_secret = p['initiator_secret'] self.target_secret = p['target_secret'] self.attributes = p['attributes'] self.status = p['status'] if HAS_SF_SDK is False: self.module.fail_json(msg="Unable to import the SolidFire Python SDK") else: self.sfe = netapp_utils.create_sf_connection(module=self.module) def get_account(self): """ Return account object if found :return: Details about the account. None if not found. :rtype: dict """ account_list = self.sfe.list_accounts() for account in account_list.accounts: if account.username == self.name: # Update self.account_id: if self.account_id is not None: if account.account_id == self.account_id: return account else: self.account_id = account.account_id return account return None def create_account(self): try: self.sfe.add_account(username=self.name, initiator_secret=self.initiator_secret, target_secret=self.target_secret, attributes=self.attributes) except Exception as e: self.module.fail_json(msg='Error creating account %s: %s)' % (self.name, to_native(e)), exception=traceback.format_exc()) def delete_account(self): try: self.sfe.remove_account(account_id=self.account_id) except Exception as e: self.module.fail_json(msg='Error deleting account %s: %s' % (self.account_id, to_native(e)), exception=traceback.format_exc()) def update_account(self): try: self.sfe.modify_account(account_id=self.account_id, username=self.new_name, status=self.status, initiator_secret=self.initiator_secret, target_secret=self.target_secret, attributes=self.attributes) except Exception as e: self.module.fail_json(msg='Error updating account %s: %s' % (self.account_id, to_native(e)), exception=traceback.format_exc()) def apply(self): changed = False account_exists = False update_account = False account_detail = self.get_account() if account_detail: account_exists = True if self.state == 'absent': changed = True elif self.state == 'present': # Check if we need to update the account if account_detail.username is not None and self.new_name is not None and \ account_detail.username != self.new_name: update_account = True changed = True elif account_detail.status is not None and self.status is not None \ and account_detail.status != self.status: update_account = True changed = True elif account_detail.initiator_secret is not None and self.initiator_secret is not None \ and account_detail.initiator_secret != self.initiator_secret: update_account = True changed = True elif account_detail.target_secret is not None and self.target_secret is not None \ and account_detail.target_secret != self.target_secret: update_account = True changed = True elif account_detail.attributes is not None and self.attributes is not None \ and account_detail.attributes != self.attributes: update_account = True changed = True else: if self.state == 'present': changed = True if changed: if self.module.check_mode: pass else: if self.state == 'present': if not account_exists: self.create_account() elif update_account: self.update_account() elif self.state == 'absent': self.delete_account() self.module.exit_json(changed=changed) def main(): v = SolidFireAccount() v.apply() if __name__ == '__main__': main()
tsdmgz/ansible
lib/ansible/modules/storage/netapp/sf_account_manager.py
Python
gpl-3.0
8,755
define([ 'INST' /* INST */, 'i18n!submissions', 'jquery' /* $ */, 'str/htmlEscape', 'jquery.ajaxJSON' /* ajaxJSON */, 'jqueryui/dialog', 'jqueryui/progressbar' /* /\.progressbar/ */ ], function(INST, I18n, $, htmlEscape) { INST.downloadSubmissions = function(url) { var cancelled = false; var title = ENV.SUBMISSION_DOWNLOAD_DIALOG_TITLE; title = title || I18n.t('#submissions.download_submissions', 'Download Assignment Submissions'); $("#download_submissions_dialog").dialog({ title: title, close: function() { cancelled = true; } }); $("#download_submissions_dialog .progress").progressbar({value: 0}); var checkForChange = function() { if(cancelled || $("#download_submissions_dialog:visible").length == 0) { return; } $("#download_submissions_dialog .status_loader").css('visibility', 'visible'); var lastProgress = null; $.ajaxJSON(url, 'GET', {}, function(data) { if(data && data.attachment) { var attachment = data.attachment; if(attachment.workflow_state == 'zipped') { $("#download_submissions_dialog .progress").progressbar('value', 100); var message = I18n.t("#submissions.finished_redirecting", "Finished! Redirecting to File..."); var link = "<a href=\"" + htmlEscape(url) + "\"><b> " + htmlEscape(I18n.t("#submissions.click_to_download", "Click here to download %{size_of_file}", {size_of_file: attachment.readable_size})) + "</b></a>" $("#download_submissions_dialog .status").html(htmlEscape(message) + "<br>" + $.raw(link)); $("#download_submissions_dialog .status_loader").css('visibility', 'hidden'); location.href = url; return; } else { var progress = parseInt(attachment.file_state, 10); if(isNaN(progress)) { progress = 0; } progress += 5 $("#download_submissions_dialog .progress").progressbar('value', progress); var message = null; if(progress >= 95){ message = I18n.t("#submissions.creating_zip", "Creating zip file..."); } else { message = I18n.t("#submissions.gathering_files_progress", "Gathering Files (%{progress})...", {progress: I18n.toPercentage(progress)}); } $("#download_submissions_dialog .status").text(message); if(progress <= 5 || progress == lastProgress) { $.ajaxJSON(url + "&compile=1", 'GET', {}, function() {}, function() {}); } lastProgress = progress; } } $("#download_submissions_dialog .status_loader").css('visibility', 'hidden'); setTimeout(checkForChange, 3000); }, function(data) { $("#download_submissions_dialog .status_loader").css('visibility', 'hidden'); setTimeout(checkForChange, 1000); }); } checkForChange(); }; });
dgynn/canvas-lms
public/javascripts/submission_download.js
JavaScript
agpl-3.0
2,986
<?php namespace Thelia\Model; use Propel\Runtime\Connection\ConnectionInterface; use Thelia\Model\Base\ContentI18n as BaseContentI18n; use Thelia\Model\Tools\I18nTimestampableTrait; class ContentI18n extends BaseContentI18n { use I18nTimestampableTrait; public function postInsert(ConnectionInterface $con = null) { $content = $this->getContent(); $content->generateRewrittenUrl($this->getLocale()); } }
amirlionor/mythelia
vendor/thelia/core/lib/Thelia/Model/ContentI18n.php
PHP
lgpl-3.0
440
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package liquibase.util; import java.io.File; /** * Code taken from <a href="http://commons.apache.org/lang">Commons lang utils</a> * <p>Helpers for <code>java.lang.System</code>.</p> * * <p>If a system property cannot be read due to security restrictions, * the corresponding field in this class will be set to <code>null</code> * and a message will be written to <code>System.err</code>.</p> * * @author Apache Software Foundation * @author Based on code from Avalon Excalibur * @author Based on code from Lucene * @author <a href="mailto:sdowney@panix.com">Steve Downey</a> * @author Gary Gregory * @author Michael Becke * @author Tetsuya Kaneuchi * @author Rafal Krupinski * @author Jason Gritman * @since 1.0 * @version $Id: SystemUtils.java 905707 2010-02-02 16:59:59Z niallp $ */ public class SystemUtils { /** * The prefix String for all Windows OS. */ private static final String OS_NAME_WINDOWS_PREFIX = "Windows"; // System property constants //----------------------------------------------------------------------- // These MUST be declared first. Other constants depend on this. /** * The System property key for the user home directory. */ private static final String USER_HOME_KEY = "user.home"; /** * The System property key for the user directory. */ private static final String USER_DIR_KEY = "user.dir"; /** * The System property key for the Java IO temporary directory. */ private static final String JAVA_IO_TMPDIR_KEY = "java.io.tmpdir"; /** * The System property key for the Java home directory. */ private static final String JAVA_HOME_KEY = "java.home"; /** * <p>The <code>awt.toolkit</code> System Property.</p> * <p>Holds a class name, on Windows XP this is <code>sun.awt.windows.WToolkit</code>.</p> * <p><b>On platforms without a GUI, this value is <code>null</code>.</b></p> * * <p>Defaults to <code>null</code> if the runtime does not have * security access to read this property or the property does not exist.</p> * * <p> * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} * or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. * </p> * * @since 2.1 */ public static final String AWT_TOOLKIT = getSystemProperty("awt.toolkit"); /** * <p>The <code>file.encoding</code> System Property.</p> * <p>File encoding, such as <code>Cp1252</code>.</p> * * <p>Defaults to <code>null</code> if the runtime does not have * security access to read this property or the property does not exist.</p> * * <p> * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} * or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. * </p> * * @since 2.0 * @since Java 1.2 */ public static final String FILE_ENCODING = getSystemProperty("file.encoding"); /** * <p>The <code>file.separator</code> System Property. * File separator (<code>&quot;/&quot;</code> on UNIX).</p> * * <p>Defaults to <code>null</code> if the runtime does not have * security access to read this property or the property does not exist.</p> * * <p> * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} * or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. * </p> * * @since Java 1.1 */ public static final String FILE_SEPARATOR = getSystemProperty("file.separator"); /** * <p>The <code>java.awt.fonts</code> System Property.</p> * * <p>Defaults to <code>null</code> if the runtime does not have * security access to read this property or the property does not exist.</p> * * <p> * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} * or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. * </p> * * @since 2.1 */ public static final String JAVA_AWT_FONTS = getSystemProperty("java.awt.fonts"); /** * <p>The <code>java.awt.graphicsenv</code> System Property.</p> * * <p>Defaults to <code>null</code> if the runtime does not have * security access to read this property or the property does not exist.</p> * * <p> * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} * or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. * </p> * * @since 2.1 */ public static final String JAVA_AWT_GRAPHICSENV = getSystemProperty("java.awt.graphicsenv"); /** * <p> * The <code>java.awt.headless</code> System Property. * The value of this property is the String <code>"true"</code> or <code>"false"</code>. * </p> * * <p>Defaults to <code>null</code> if the runtime does not have * security access to read this property or the property does not exist.</p> * * <p> * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} * or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. * </p> * * @see #isJavaAwtHeadless() * @since 2.1 * @since Java 1.4 */ public static final String JAVA_AWT_HEADLESS = getSystemProperty("java.awt.headless"); /** * <p>The <code>java.awt.printerjob</code> System Property.</p> * * <p>Defaults to <code>null</code> if the runtime does not have * security access to read this property or the property does not exist.</p> * * <p> * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} * or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. * </p> * * @since 2.1 */ public static final String JAVA_AWT_PRINTERJOB = getSystemProperty("java.awt.printerjob"); /** * <p>The <code>java.class.path</code> System Property. Java class path.</p> * * <p>Defaults to <code>null</code> if the runtime does not have * security access to read this property or the property does not exist.</p> * * <p> * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} * or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. * </p> * * @since Java 1.1 */ public static final String JAVA_CLASS_PATH = getSystemProperty("java.class.path"); /** * <p>The <code>java.class.version</code> System Property. * Java class format version number.</p> * * <p>Defaults to <code>null</code> if the runtime does not have * security access to read this property or the property does not exist.</p> * * <p> * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} * or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. * </p> * * @since Java 1.1 */ public static final String JAVA_CLASS_VERSION = getSystemProperty("java.class.version"); /** * <p>The <code>java.compiler</code> System Property. Name of JIT compiler to use. * First in JDK version 1.2. Not used in Sun JDKs after 1.2.</p> * * <p>Defaults to <code>null</code> if the runtime does not have * security access to read this property or the property does not exist.</p> * * <p> * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} * or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. * </p> * * @since Java 1.2. Not used in Sun versions after 1.2. */ public static final String JAVA_COMPILER = getSystemProperty("java.compiler"); /** * <p>The <code>java.endorsed.dirs</code> System Property. Path of endorsed directory * or directories.</p> * * <p>Defaults to <code>null</code> if the runtime does not have * security access to read this property or the property does not exist.</p> * * <p> * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} * or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. * </p> * * @since Java 1.4 */ public static final String JAVA_ENDORSED_DIRS = getSystemProperty("java.endorsed.dirs"); /** * <p>The <code>java.ext.dirs</code> System Property. Path of extension directory * or directories.</p> * * <p>Defaults to <code>null</code> if the runtime does not have * security access to read this property or the property does not exist.</p> * * <p> * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} * or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. * </p> * * @since Java 1.3 */ public static final String JAVA_EXT_DIRS = getSystemProperty("java.ext.dirs"); /** * <p>The <code>java.home</code> System Property. Java installation directory.</p> * * <p>Defaults to <code>null</code> if the runtime does not have * security access to read this property or the property does not exist.</p> * * <p> * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} * or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. * </p> * * @since Java 1.1 */ public static final String JAVA_HOME = getSystemProperty(JAVA_HOME_KEY); /** * <p>The <code>java.io.tmpdir</code> System Property. Default temp file path.</p> * * <p>Defaults to <code>null</code> if the runtime does not have * security access to read this property or the property does not exist.</p> * * <p> * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} * or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. * </p> * * @since Java 1.2 */ public static final String JAVA_IO_TMPDIR = getSystemProperty(JAVA_IO_TMPDIR_KEY); /** * <p>The <code>java.library.path</code> System Property. List of paths to search * when loading libraries.</p> * * <p>Defaults to <code>null</code> if the runtime does not have * security access to read this property or the property does not exist.</p> * * <p> * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} * or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. * </p> * * @since Java 1.2 */ public static final String JAVA_LIBRARY_PATH = getSystemProperty("java.library.path"); /** * <p>The <code>java.runtime.name</code> System Property. Java Runtime Environment * name.</p> * * <p>Defaults to <code>null</code> if the runtime does not have * security access to read this property or the property does not exist.</p> * * <p> * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} * or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. * </p> * * @since 2.0 * @since Java 1.3 */ public static final String JAVA_RUNTIME_NAME = getSystemProperty("java.runtime.name"); /** * <p>The <code>java.runtime.version</code> System Property. Java Runtime Environment * version.</p> * * <p>Defaults to <code>null</code> if the runtime does not have * security access to read this property or the property does not exist.</p> * * <p> * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} * or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. * </p> * * @since 2.0 * @since Java 1.3 */ public static final String JAVA_RUNTIME_VERSION = getSystemProperty("java.runtime.version"); /** * <p>The <code>java.specification.name</code> System Property. Java Runtime Environment * specification name.</p> * * <p>Defaults to <code>null</code> if the runtime does not have * security access to read this property or the property does not exist.</p> * * <p> * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} * or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. * </p> * * @since Java 1.2 */ public static final String JAVA_SPECIFICATION_NAME = getSystemProperty("java.specification.name"); /** * <p>The <code>java.specification.vendor</code> System Property. Java Runtime Environment * specification vendor.</p> * * <p>Defaults to <code>null</code> if the runtime does not have * security access to read this property or the property does not exist.</p> * * <p> * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} * or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. * </p> * * @since Java 1.2 */ public static final String JAVA_SPECIFICATION_VENDOR = getSystemProperty("java.specification.vendor"); /** * <p>The <code>java.specification.version</code> System Property. Java Runtime Environment * specification version.</p> * * <p>Defaults to <code>null</code> if the runtime does not have * security access to read this property or the property does not exist.</p> * * <p> * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} * or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. * </p> * * @since Java 1.3 */ public static final String JAVA_SPECIFICATION_VERSION = getSystemProperty("java.specification.version"); /** * <p>The <code>java.util.prefs.PreferencesFactory</code> System Property. A class name.</p> * * <p>Defaults to <code>null</code> if the runtime does not have * security access to read this property or the property does not exist.</p> * * <p> * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} * or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. * </p> * * @since 2.1 * @since Java 1.4 */ public static final String JAVA_UTIL_PREFS_PREFERENCES_FACTORY = getSystemProperty("java.util.prefs.PreferencesFactory"); /** * <p>The <code>java.vendor</code> System Property. Java vendor-specific string.</p> * * <p>Defaults to <code>null</code> if the runtime does not have * security access to read this property or the property does not exist.</p> * * <p> * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} * or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. * </p> * * @since Java 1.1 */ public static final String JAVA_VENDOR = getSystemProperty("java.vendor"); /** * <p>The <code>java.vendor.url</code> System Property. Java vendor URL.</p> * * <p>Defaults to <code>null</code> if the runtime does not have * security access to read this property or the property does not exist.</p> * * <p> * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} * or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. * </p> * * @since Java 1.1 */ public static final String JAVA_VENDOR_URL = getSystemProperty("java.vendor.url"); /** * <p>The <code>java.version</code> System Property. Java version number.</p> * * <p>Defaults to <code>null</code> if the runtime does not have * security access to read this property or the property does not exist.</p> * * <p> * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} * or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. * </p> * * @since Java 1.1 */ public static final String JAVA_VERSION = getSystemProperty("java.version"); /** * <p>The <code>java.vm.info</code> System Property. Java Virtual Machine implementation * info.</p> * * <p>Defaults to <code>null</code> if the runtime does not have * security access to read this property or the property does not exist.</p> * * <p> * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} * or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. * </p> * * @since 2.0 * @since Java 1.2 */ public static final String JAVA_VM_INFO = getSystemProperty("java.vm.info"); /** * <p>The <code>java.vm.name</code> System Property. Java Virtual Machine implementation * name.</p> * * <p>Defaults to <code>null</code> if the runtime does not have * security access to read this property or the property does not exist.</p> * * <p> * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} * or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. * </p> * * @since Java 1.2 */ public static final String JAVA_VM_NAME = getSystemProperty("java.vm.name"); /** * <p>The <code>java.vm.specification.name</code> System Property. Java Virtual Machine * specification name.</p> * * <p>Defaults to <code>null</code> if the runtime does not have * security access to read this property or the property does not exist.</p> * * <p> * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} * or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. * </p> * * @since Java 1.2 */ public static final String JAVA_VM_SPECIFICATION_NAME = getSystemProperty("java.vm.specification.name"); /** * <p>The <code>java.vm.specification.vendor</code> System Property. Java Virtual * Machine specification vendor.</p> * * <p>Defaults to <code>null</code> if the runtime does not have * security access to read this property or the property does not exist.</p> * * <p> * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} * or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. * </p> * * @since Java 1.2 */ public static final String JAVA_VM_SPECIFICATION_VENDOR = getSystemProperty("java.vm.specification.vendor"); /** * <p>The <code>java.vm.specification.version</code> System Property. Java Virtual Machine * specification version.</p> * * <p>Defaults to <code>null</code> if the runtime does not have * security access to read this property or the property does not exist.</p> * * <p> * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} * or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. * </p> * * @since Java 1.2 */ public static final String JAVA_VM_SPECIFICATION_VERSION = getSystemProperty("java.vm.specification.version"); /** * <p>The <code>java.vm.vendor</code> System Property. Java Virtual Machine implementation * vendor.</p> * * <p>Defaults to <code>null</code> if the runtime does not have * security access to read this property or the property does not exist.</p> * * <p> * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} * or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. * </p> * * @since Java 1.2 */ public static final String JAVA_VM_VENDOR = getSystemProperty("java.vm.vendor"); /** * <p>The <code>java.vm.version</code> System Property. Java Virtual Machine * implementation version.</p> * * <p>Defaults to <code>null</code> if the runtime does not have * security access to read this property or the property does not exist.</p> * * <p> * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} * or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. * </p> * * @since Java 1.2 */ public static final String JAVA_VM_VERSION = getSystemProperty("java.vm.version"); /** * <p>The <code>line.separator</code> System Property. Line separator * (<code>&quot;\n&quot;</code> on UNIX).</p> * * <p>Defaults to <code>null</code> if the runtime does not have * security access to read this property or the property does not exist.</p> * * <p> * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} * or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. * </p> * * @since Java 1.1 */ public static final String LINE_SEPARATOR = getSystemProperty("line.separator"); /** * <p>The <code>os.arch</code> System Property. Operating system architecture.</p> * * <p>Defaults to <code>null</code> if the runtime does not have * security access to read this property or the property does not exist.</p> * * <p> * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} * or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. * </p> * * @since Java 1.1 */ public static final String OS_ARCH = getSystemProperty("os.arch"); /** * <p>The <code>os.name</code> System Property. Operating system name.</p> * * <p>Defaults to <code>null</code> if the runtime does not have * security access to read this property or the property does not exist.</p> * * <p> * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} * or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. * </p> * * @since Java 1.1 */ public static final String OS_NAME = getSystemProperty("os.name"); /** * <p>The <code>os.version</code> System Property. Operating system version.</p> * * <p>Defaults to <code>null</code> if the runtime does not have * security access to read this property or the property does not exist.</p> * * <p> * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} * or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. * </p> * * @since Java 1.1 */ public static final String OS_VERSION = getSystemProperty("os.version"); /** * <p>The <code>path.separator</code> System Property. Path separator * (<code>&quot;:&quot;</code> on UNIX).</p> * * <p>Defaults to <code>null</code> if the runtime does not have * security access to read this property or the property does not exist.</p> * * <p> * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} * or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. * </p> * * @since Java 1.1 */ public static final String PATH_SEPARATOR = getSystemProperty("path.separator"); /** * <p>The <code>user.country</code> or <code>user.region</code> System Property. * User's country code, such as <code>GB</code>. First in JDK version 1.2 as * <code>user.region</code>. Renamed to <code>user.country</code> in 1.4</p> * * <p>Defaults to <code>null</code> if the runtime does not have * security access to read this property or the property does not exist.</p> * * <p> * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} * or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. * </p> * * @since 2.0 * @since Java 1.2 */ public static final String USER_COUNTRY = getSystemProperty("user.country") == null ? getSystemProperty("user.region") : getSystemProperty("user.country"); /** * <p>The <code>user.dir</code> System Property. User's current working * directory.</p> * * <p>Defaults to <code>null</code> if the runtime does not have * security access to read this property or the property does not exist.</p> * * <p> * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} * or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. * </p> * * @since Java 1.1 */ public static final String USER_DIR = getSystemProperty(USER_DIR_KEY); /** * <p>The <code>user.home</code> System Property. User's home directory.</p> * * <p>Defaults to <code>null</code> if the runtime does not have * security access to read this property or the property does not exist.</p> * * <p> * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} * or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. * </p> * * @since Java 1.1 */ public static final String USER_HOME = getSystemProperty(USER_HOME_KEY); /** * <p>The <code>user.language</code> System Property. User's language code, * such as <code>"en"</code>.</p> * * <p>Defaults to <code>null</code> if the runtime does not have * security access to read this property or the property does not exist.</p> * * <p> * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} * or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. * </p> * * @since 2.0 * @since Java 1.2 */ public static final String USER_LANGUAGE = getSystemProperty("user.language"); /** * <p>The <code>user.name</code> System Property. User's account name.</p> * * <p>Defaults to <code>null</code> if the runtime does not have * security access to read this property or the property does not exist.</p> * * <p> * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} * or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. * </p> * * @since Java 1.1 */ public static final String USER_NAME = getSystemProperty("user.name"); /** * <p>The <code>user.timezone</code> System Property. * For example: <code>"America/Los_Angeles"</code>.</p> * * <p>Defaults to <code>null</code> if the runtime does not have * security access to read this property or the property does not exist.</p> * * <p> * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} * or {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. * </p> * * @since 2.1 */ public static final String USER_TIMEZONE = getSystemProperty("user.timezone"); // Java version //----------------------------------------------------------------------- // This MUST be declared after those above as it depends on the // values being set up /** * <p>Gets the Java version as a <code>String</code> trimming leading letters.</p> * * <p>The field will return <code>null</code> if {@link #JAVA_VERSION} is <code>null</code>.</p> * * @since 2.1 */ public static final String JAVA_VERSION_TRIMMED = getJavaVersionTrimmed(); // Java version values //----------------------------------------------------------------------- // These MUST be declared after the trim above as they depend on the // value being set up /** * <p>Gets the Java version as a <code>float</code>.</p> * * <p>Example return values:</p> * <ul> * <li><code>1.2f</code> for JDK 1.2 * <li><code>1.31f</code> for JDK 1.3.1 * </ul> * * <p>The field will return zero if {@link #JAVA_VERSION} is <code>null</code>.</p> * * @since 2.0 */ public static final float JAVA_VERSION_FLOAT = getJavaVersionAsFloat(); /** * <p>Gets the Java version as an <code>int</code>.</p> * * <p>Example return values:</p> * <ul> * <li><code>120</code> for JDK 1.2 * <li><code>131</code> for JDK 1.3.1 * </ul> * * <p>The field will return zero if {@link #JAVA_VERSION} is <code>null</code>.</p> * * @since 2.0 */ public static final int JAVA_VERSION_INT = getJavaVersionAsInt(); // Java version checks //----------------------------------------------------------------------- // These MUST be declared after those above as they depend on the // values being set up /** * <p>Is <code>true</code> if this is Java version 1.1 (also 1.1.x versions).</p> * * <p>The field will return <code>false</code> if {@link #JAVA_VERSION} is * <code>null</code>.</p> */ public static final boolean IS_JAVA_1_1 = getJavaVersionMatches("1.1"); /** * <p>Is <code>true</code> if this is Java version 1.2 (also 1.2.x versions).</p> * * <p>The field will return <code>false</code> if {@link #JAVA_VERSION} is * <code>null</code>.</p> */ public static final boolean IS_JAVA_1_2 = getJavaVersionMatches("1.2"); /** * <p>Is <code>true</code> if this is Java version 1.3 (also 1.3.x versions).</p> * * <p>The field will return <code>false</code> if {@link #JAVA_VERSION} is * <code>null</code>.</p> */ public static final boolean IS_JAVA_1_3 = getJavaVersionMatches("1.3"); /** * <p>Is <code>true</code> if this is Java version 1.4 (also 1.4.x versions).</p> * * <p>The field will return <code>false</code> if {@link #JAVA_VERSION} is * <code>null</code>.</p> */ public static final boolean IS_JAVA_1_4 = getJavaVersionMatches("1.4"); /** * <p>Is <code>true</code> if this is Java version 1.5 (also 1.5.x versions).</p> * * <p>The field will return <code>false</code> if {@link #JAVA_VERSION} is * <code>null</code>.</p> */ public static final boolean IS_JAVA_1_5 = getJavaVersionMatches("1.5"); /** * <p>Is <code>true</code> if this is Java version 1.6 (also 1.6.x versions).</p> * * <p>The field will return <code>false</code> if {@link #JAVA_VERSION} is * <code>null</code>.</p> */ public static final boolean IS_JAVA_1_6 = getJavaVersionMatches("1.6"); /** * <p>Is <code>true</code> if this is Java version 1.7 (also 1.7.x versions).</p> * * <p>The field will return <code>false</code> if {@link #JAVA_VERSION} is * <code>null</code>.</p> * * @since 2.5 */ public static final boolean IS_JAVA_1_7 = getJavaVersionMatches("1.7"); // Operating system checks //----------------------------------------------------------------------- // These MUST be declared after those above as they depend on the // values being set up // OS names from http://www.vamphq.com/os.html // Selected ones included - please advise dev@commons.apache.org // if you want another added or a mistake corrected /** * <p>Is <code>true</code> if this is AIX.</p> * * <p>The field will return <code>false</code> if <code>OS_NAME</code> is * <code>null</code>.</p> * * @since 2.0 */ public static final boolean IS_OS_AIX = getOSMatches("AIX"); /** * <p>Is <code>true</code> if this is HP-UX.</p> * * <p>The field will return <code>false</code> if <code>OS_NAME</code> is * <code>null</code>.</p> * * @since 2.0 */ public static final boolean IS_OS_HP_UX = getOSMatches("HP-UX"); /** * <p>Is <code>true</code> if this is Irix.</p> * * <p>The field will return <code>false</code> if <code>OS_NAME</code> is * <code>null</code>.</p> * * @since 2.0 */ public static final boolean IS_OS_IRIX = getOSMatches("Irix"); /** * <p>Is <code>true</code> if this is Linux.</p> * * <p>The field will return <code>false</code> if <code>OS_NAME</code> is * <code>null</code>.</p> * * @since 2.0 */ public static final boolean IS_OS_LINUX = getOSMatches("Linux") || getOSMatches("LINUX"); /** * <p>Is <code>true</code> if this is Mac.</p> * * <p>The field will return <code>false</code> if <code>OS_NAME</code> is * <code>null</code>.</p> * * @since 2.0 */ public static final boolean IS_OS_MAC = getOSMatches("Mac"); /** * <p>Is <code>true</code> if this is Mac.</p> * * <p>The field will return <code>false</code> if <code>OS_NAME</code> is * <code>null</code>.</p> * * @since 2.0 */ public static final boolean IS_OS_MAC_OSX = getOSMatches("Mac OS X"); /** * <p>Is <code>true</code> if this is OS/2.</p> * * <p>The field will return <code>false</code> if <code>OS_NAME</code> is * <code>null</code>.</p> * * @since 2.0 */ public static final boolean IS_OS_OS2 = getOSMatches("OS/2"); /** * <p>Is <code>true</code> if this is Solaris.</p> * * <p>The field will return <code>false</code> if <code>OS_NAME</code> is * <code>null</code>.</p> * * @since 2.0 */ public static final boolean IS_OS_SOLARIS = getOSMatches("Solaris"); /** * <p>Is <code>true</code> if this is SunOS.</p> * * <p>The field will return <code>false</code> if <code>OS_NAME</code> is * <code>null</code>.</p> * * @since 2.0 */ public static final boolean IS_OS_SUN_OS = getOSMatches("SunOS"); /** * <p>Is <code>true</code> if this is a POSIX compilant system, * as in any of AIX, HP-UX, Irix, Linux, MacOSX, Solaris or SUN OS.</p> * * <p>The field will return <code>false</code> if <code>OS_NAME</code> is * <code>null</code>.</p> * * @since 2.1 */ public static final boolean IS_OS_UNIX = IS_OS_AIX || IS_OS_HP_UX || IS_OS_IRIX || IS_OS_LINUX || IS_OS_MAC_OSX || IS_OS_SOLARIS || IS_OS_SUN_OS; /** * <p>Is <code>true</code> if this is Windows.</p> * * <p>The field will return <code>false</code> if <code>OS_NAME</code> is * <code>null</code>.</p> * * @since 2.0 */ public static final boolean IS_OS_WINDOWS = getOSMatches(OS_NAME_WINDOWS_PREFIX); /** * <p>Is <code>true</code> if this is Windows 2000.</p> * * <p>The field will return <code>false</code> if <code>OS_NAME</code> is * <code>null</code>.</p> * * @since 2.0 */ public static final boolean IS_OS_WINDOWS_2000 = getOSMatches(OS_NAME_WINDOWS_PREFIX, "5.0"); /** * <p>Is <code>true</code> if this is Windows 95.</p> * * <p>The field will return <code>false</code> if <code>OS_NAME</code> is * <code>null</code>.</p> * * @since 2.0 */ public static final boolean IS_OS_WINDOWS_95 = getOSMatches(OS_NAME_WINDOWS_PREFIX + " 9", "4.0"); // JDK 1.2 running on Windows98 returns 'Windows 95', hence the above /** * <p>Is <code>true</code> if this is Windows 98.</p> * * <p>The field will return <code>false</code> if <code>OS_NAME</code> is * <code>null</code>.</p> * * @since 2.0 */ public static final boolean IS_OS_WINDOWS_98 = getOSMatches(OS_NAME_WINDOWS_PREFIX + " 9", "4.1"); // JDK 1.2 running on Windows98 returns 'Windows 95', hence the above /** * <p>Is <code>true</code> if this is Windows ME.</p> * * <p>The field will return <code>false</code> if <code>OS_NAME</code> is * <code>null</code>.</p> * * @since 2.0 */ public static final boolean IS_OS_WINDOWS_ME = getOSMatches(OS_NAME_WINDOWS_PREFIX, "4.9"); // JDK 1.2 running on WindowsME may return 'Windows 95', hence the above /** * <p>Is <code>true</code> if this is Windows NT.</p> * * <p>The field will return <code>false</code> if <code>OS_NAME</code> is * <code>null</code>.</p> * * @since 2.0 */ public static final boolean IS_OS_WINDOWS_NT = getOSMatches(OS_NAME_WINDOWS_PREFIX + " NT"); // Windows 2000 returns 'Windows 2000' but may suffer from same JDK1.2 problem /** * <p>Is <code>true</code> if this is Windows XP.</p> * * <p>The field will return <code>false</code> if <code>OS_NAME</code> is * <code>null</code>.</p> * * @since 2.0 */ public static final boolean IS_OS_WINDOWS_XP = getOSMatches(OS_NAME_WINDOWS_PREFIX, "5.1"); //----------------------------------------------------------------------- /** * <p>Is <code>true</code> if this is Windows Vista.</p> * * <p>The field will return <code>false</code> if <code>OS_NAME</code> is * <code>null</code>.</p> * * @since 2.4 */ public static final boolean IS_OS_WINDOWS_VISTA = getOSMatches(OS_NAME_WINDOWS_PREFIX, "6.0"); /** * <p>Is <code>true</code> if this is Windows 7.</p> * * <p>The field will return <code>false</code> if <code>OS_NAME</code> is * <code>null</code>.</p> * * @since 2.5 */ public static final boolean IS_OS_WINDOWS_7 = getOSMatches(OS_NAME_WINDOWS_PREFIX, "6.1"); //----------------------------------------------------------------------- /** * <p>SystemUtils instances should NOT be constructed in standard * programming. Instead, the class should be used as * <code>SystemUtils.FILE_SEPARATOR</code>.</p> * * <p>This constructor is public to permit tools that require a JavaBean * instance to operate.</p> */ public SystemUtils() { super(); } //----------------------------------------------------------------------- /** * <p>Gets the Java version number as a <code>float</code>.</p> * * <p>Example return values:</p> * <ul> * <li><code>1.2f</code> for JDK 1.2 * <li><code>1.31f</code> for JDK 1.3.1 * </ul> * * @return the version, for example 1.31f for JDK 1.3.1 * @deprecated Use {@link #JAVA_VERSION_FLOAT} instead. * Method will be removed in Commons Lang 3.0. */ public static float getJavaVersion() { return JAVA_VERSION_FLOAT; } /** * <p>Gets the Java version number as a <code>float</code>.</p> * * <p>Example return values:</p> * <ul> * <li><code>1.2f</code> for JDK 1.2 * <li><code>1.31f</code> for JDK 1.3.1 * </ul> * * <p>Patch releases are not reported. * Zero is returned if {@link #JAVA_VERSION_TRIMMED} is <code>null</code>.</p> * * @return the version, for example 1.31f for JDK 1.3.1 */ private static float getJavaVersionAsFloat() { if (JAVA_VERSION_TRIMMED == null) { return 0f; } String str = JAVA_VERSION_TRIMMED.substring(0, 3); if (JAVA_VERSION_TRIMMED.length() >= 5) { str = str + JAVA_VERSION_TRIMMED.substring(4, 5); } try { return Float.parseFloat(str); } catch (Exception ex) { return 0; } } /** * <p>Gets the Java version number as an <code>int</code>.</p> * * <p>Example return values:</p> * <ul> * <li><code>120</code> for JDK 1.2 * <li><code>131</code> for JDK 1.3.1 * </ul> * * <p>Patch releases are not reported. * Zero is returned if {@link #JAVA_VERSION_TRIMMED} is <code>null</code>.</p> * * @return the version, for example 131 for JDK 1.3.1 */ private static int getJavaVersionAsInt() { if (JAVA_VERSION_TRIMMED == null) { return 0; } String str = JAVA_VERSION_TRIMMED.substring(0, 1); str = str + JAVA_VERSION_TRIMMED.substring(2, 3); if (JAVA_VERSION_TRIMMED.length() >= 5) { str = str + JAVA_VERSION_TRIMMED.substring(4, 5); } else { str = str + "0"; } try { return Integer.parseInt(str); } catch (Exception ex) { return 0; } } /** * Trims the text of the java version to start with numbers. * * @return the trimmed java version */ private static String getJavaVersionTrimmed() { if (JAVA_VERSION != null) { for (int i = 0; i < JAVA_VERSION.length(); i++) { char ch = JAVA_VERSION.charAt(i); if (ch >= '0' && ch <= '9') { return JAVA_VERSION.substring(i); } } } return null; } /** * <p>Decides if the java version matches.</p> * * @param versionPrefix the prefix for the java version * @return true if matches, or false if not or can't determine */ private static boolean getJavaVersionMatches(String versionPrefix) { if (JAVA_VERSION_TRIMMED == null) { return false; } return JAVA_VERSION_TRIMMED.startsWith(versionPrefix); } /** * <p>Decides if the operating system matches.</p> * * @param osNamePrefix the prefix for the os name * @return true if matches, or false if not or can't determine */ private static boolean getOSMatches(String osNamePrefix) { if (OS_NAME == null) { return false; } return OS_NAME.startsWith(osNamePrefix); } /** * <p>Decides if the operating system matches.</p> * * @param osNamePrefix the prefix for the os name * @param osVersionPrefix the prefix for the version * @return true if matches, or false if not or can't determine */ private static boolean getOSMatches(String osNamePrefix, String osVersionPrefix) { if (OS_NAME == null || OS_VERSION == null) { return false; } return OS_NAME.startsWith(osNamePrefix) && OS_VERSION.startsWith(osVersionPrefix); } //----------------------------------------------------------------------- /** * <p>Gets a System property, defaulting to <code>null</code> if the property * cannot be read.</p> * * <p>If a <code>SecurityException</code> is caught, the return * value is <code>null</code> and a message is written to <code>System.err</code>.</p> * * @param property the system property name * @return the system property value or <code>null</code> if a security problem occurs */ private static String getSystemProperty(String property) { try { return System.getProperty(property); } catch (SecurityException ex) { // we are not allowed to look at this property System.err.println( "Caught a SecurityException reading the system property '" + property + "'; the SystemUtils property value will default to null." ); return null; } } /** * <p>Is the Java version at least the requested version.</p> * * <p>Example input:</p> * <ul> * <li><code>1.2f</code> to test for JDK 1.2</li> * <li><code>1.31f</code> to test for JDK 1.3.1</li> * </ul> * * @param requiredVersion the required version, for example 1.31f * @return <code>true</code> if the actual version is equal or greater * than the required version */ public static boolean isJavaVersionAtLeast(float requiredVersion) { return JAVA_VERSION_FLOAT >= requiredVersion; } /** * <p>Is the Java version at least the requested version.</p> * * <p>Example input:</p> * <ul> * <li><code>120</code> to test for JDK 1.2 or greater</li> * <li><code>131</code> to test for JDK 1.3.1 or greater</li> * </ul> * * @param requiredVersion the required version, for example 131 * @return <code>true</code> if the actual version is equal or greater * than the required version * @since 2.0 */ public static boolean isJavaVersionAtLeast(int requiredVersion) { return JAVA_VERSION_INT >= requiredVersion; } /** * Returns whether the {@link #JAVA_AWT_HEADLESS} value is <code>true</code>. * * @return <code>true</code> if <code>JAVA_AWT_HEADLESS</code> is <code>"true"</code>, * <code>false</code> otherwise. * * @see #JAVA_AWT_HEADLESS * @since 2.1 * @since Java 1.4 */ public static boolean isJavaAwtHeadless() { return JAVA_AWT_HEADLESS != null ? JAVA_AWT_HEADLESS.equals(Boolean.TRUE.toString()) : false; } /** * <p>Gets the Java home directory as a <code>File</code>.</p> * * @return a directory * @throws SecurityException if a security manager exists and its * <code>checkPropertyAccess</code> method doesn't allow * access to the specified system property. * @see System#getProperty(String) * @since 2.1 */ public static File getJavaHome() { return new File(System.getProperty(JAVA_HOME_KEY)); } /** * <p>Gets the Java IO temporary directory as a <code>File</code>.</p> * * @return a directory * @throws SecurityException if a security manager exists and its * <code>checkPropertyAccess</code> method doesn't allow * access to the specified system property. * @see System#getProperty(String) * @since 2.1 */ public static File getJavaIoTmpDir() { return new File(System.getProperty(JAVA_IO_TMPDIR_KEY)); } /** * <p>Gets the user directory as a <code>File</code>.</p> * * @return a directory * @throws SecurityException if a security manager exists and its * <code>checkPropertyAccess</code> method doesn't allow * access to the specified system property. * @see System#getProperty(String) * @since 2.1 */ public static File getUserDir() { return new File(System.getProperty(USER_DIR_KEY)); } /** * <p>Gets the user home directory as a <code>File</code>.</p> * * @return a directory * @throws SecurityException if a security manager exists and its * <code>checkPropertyAccess</code> method doesn't allow * access to the specified system property. * @see System#getProperty(String) * @since 2.1 */ public static File getUserHome() { return new File(System.getProperty(USER_HOME_KEY)); } public static boolean isWindows() { return System.getProperty("os.name").startsWith("Windows "); } }
danielkec/liquibase
liquibase-core/src/main/java/liquibase/util/SystemUtils.java
Java
apache-2.0
52,176
import { ApplicationRef, ComponentFactoryResolver, Injectable, Injector } from '@angular/core'; import { NgElement, WithProperties } from '@angular/elements'; import { PopupComponent } from './popup.component'; @Injectable() export class PopupService { constructor(private injector: Injector, private applicationRef: ApplicationRef, private componentFactoryResolver: ComponentFactoryResolver) {} // Previous dynamic-loading method required you to set up infrastructure // before adding the popup to the DOM. showAsComponent(message: string) { // Create element const popup = document.createElement('popup-component'); // Create the component and wire it up with the element const factory = this.componentFactoryResolver.resolveComponentFactory(PopupComponent); const popupComponentRef = factory.create(this.injector, [], popup); // Attach to the view so that the change detector knows to run this.applicationRef.attachView(popupComponentRef.hostView); // Listen to the close event popupComponentRef.instance.closed.subscribe(() => { document.body.removeChild(popup); this.applicationRef.detachView(popupComponentRef.hostView); }); // Set the message popupComponentRef.instance.message = message; // Add to the DOM document.body.appendChild(popup); } // This uses the new custom-element method to add the popup to the DOM. showAsElement(message: string) { // Create element const popupEl: NgElement & WithProperties<PopupComponent> = document.createElement('popup-element') as any; // Listen to the close event popupEl.addEventListener('closed', () => document.body.removeChild(popupEl)); // Set the message popupEl.message = message; // Add to the DOM document.body.appendChild(popupEl); } }
ocombe/angular
aio/content/examples/elements/src/app/popup.service.ts
TypeScript
mit
1,849
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See the LICENSE file in builder/azure for license information. package arm import ( "crypto/rand" "crypto/rsa" "crypto/x509" "encoding/base64" "encoding/pem" "fmt" "golang.org/x/crypto/ssh" "time" ) const ( KeySize = 2048 ) type OpenSshKeyPair struct { privateKey *rsa.PrivateKey publicKey ssh.PublicKey } func NewOpenSshKeyPair() (*OpenSshKeyPair, error) { return NewOpenSshKeyPairWithSize(KeySize) } func NewOpenSshKeyPairWithSize(keySize int) (*OpenSshKeyPair, error) { privateKey, err := rsa.GenerateKey(rand.Reader, keySize) if err != nil { return nil, err } publicKey, err := ssh.NewPublicKey(&privateKey.PublicKey) if err != nil { return nil, err } return &OpenSshKeyPair{ privateKey: privateKey, publicKey: publicKey, }, nil } func (s *OpenSshKeyPair) AuthorizedKey() string { return fmt.Sprintf("%s %s packer Azure Deployment%s", s.publicKey.Type(), base64.StdEncoding.EncodeToString(s.publicKey.Marshal()), time.Now().Format(time.RFC3339)) } func (s *OpenSshKeyPair) PrivateKey() string { privateKey := string(pem.EncodeToMemory(&pem.Block{ Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(s.privateKey), })) return privateKey }
stardog-union/stardog-graviton
vendor/github.com/mitchellh/packer/builder/azure/arm/openssh_key_pair.go
GO
apache-2.0
1,302
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System; using System.Runtime.InteropServices; internal partial class Interop { internal partial class Kernel32 { [DllImport(Libraries.Kernel32, SetLastError = true)] internal static extern bool SetFileInformationByHandle(SafeFileHandle hFile, FILE_INFO_BY_HANDLE_CLASS FileInformationClass, ref FILE_BASIC_INFO lpFileInformation, uint dwBufferSize); // Default values indicate "no change". Use defaults so that we don't force callsites to be aware of the default values internal static unsafe bool SetFileTime( SafeFileHandle hFile, long creationTime = -1, long lastAccessTime = -1, long lastWriteTime = -1, long changeTime = -1, uint fileAttributes = 0) { FILE_BASIC_INFO basicInfo = new FILE_BASIC_INFO() { CreationTime = creationTime, LastAccessTime = lastAccessTime, LastWriteTime = lastWriteTime, ChangeTime = changeTime, FileAttributes = fileAttributes }; return SetFileInformationByHandle(hFile, FILE_INFO_BY_HANDLE_CLASS.FileBasicInfo, ref basicInfo, (uint)sizeof(FILE_BASIC_INFO)); } internal struct FILE_BASIC_INFO { internal long CreationTime; internal long LastAccessTime; internal long LastWriteTime; internal long ChangeTime; internal uint FileAttributes; } internal enum FILE_INFO_BY_HANDLE_CLASS : uint { FileBasicInfo = 0x0u, FileStandardInfo = 0x1u, FileNameInfo = 0x2u, FileRenameInfo = 0x3u, FileDispositionInfo = 0x4u, FileAllocationInfo = 0x5u, FileEndOfFileInfo = 0x6u, FileStreamInfo = 0x7u, FileCompressionInfo = 0x8u, FileAttributeTagInfo = 0x9u, FileIdBothDirectoryInfo = 0xAu, FileIdBothDirectoryRestartInfo = 0xBu, FileIoPriorityHintInfo = 0xCu, FileRemoteProtocolInfo = 0xDu, FileFullDirectoryInfo = 0xEu, FileFullDirectoryRestartInfo = 0xFu, FileStorageInfo = 0x10u, FileAlignmentInfo = 0x11u, FileIdInfo = 0x12u, FileIdExtdDirectoryInfo = 0x13u, FileIdExtdDirectoryRestartInfo = 0x14u, MaximumFileInfoByHandleClass = 0x15u, } } }
nbarbettini/corefx
src/Common/src/Interop/Windows/kernel32/Interop.SetFileInformationByHandle.cs
C#
mit
2,745
<?php require 'includes/graphs/common.inc.php'; $rrd_filename = rrd_name($device['hostname'], array('app', 'drbd', $app['app_instance'])); $array = array( 'lo' => 'Local I/O', 'pe' => 'Pending', 'ua' => 'UnAcked', 'ap' => 'App Pending', ); $i = 0; if (rrdtool_check_rrd_exists($rrd_filename)) { foreach ($array as $ds => $var) { $rrd_list[$i]['filename'] = $rrd_filename; if (is_array($var)) { $rrd_list[$i]['descr'] = $var['descr']; } else { $rrd_list[$i]['descr'] = $var; } $rrd_list[$i]['ds'] = $ds; $i++; } } else { echo "file missing: $file"; } $colours = 'mixed'; $nototal = 0; $unit_text = ''; require 'includes/graphs/generic_multi_simplex_seperated.inc.php';
xbeaudouin/librenms
html/includes/graphs/application/drbd_queue.inc.php
PHP
gpl-3.0
812
// Generated by CoffeeScript 1.9.3 (function() { var iframe_template, utils; utils = require('./utils'); iframe_template = "<!DOCTYPE html>\n<html>\n<head>\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n <script src=\"{{ sockjs_url }}\"></script>\n <script>\n document.domain = document.domain;\n SockJS.bootstrap_iframe();\n </script>\n</head>\n<body>\n <h2>Don't panic!</h2>\n <p>This is a SockJS hidden iframe. It's used for cross domain magic.</p>\n</body>\n</html>"; exports.app = { iframe: function(req, res) { var content, context, k, quoted_md5; context = { '{{ sockjs_url }}': this.options.sockjs_url }; content = iframe_template; for (k in context) { content = content.replace(k, context[k]); } quoted_md5 = '"' + utils.md5_hex(content) + '"'; if ('if-none-match' in req.headers && req.headers['if-none-match'] === quoted_md5) { res.statusCode = 304; return ''; } res.setHeader('Content-Type', 'text/html; charset=UTF-8'); res.setHeader('ETag', quoted_md5); return content; } }; }).call(this);
Jorginho211/TFG
web/node_modules/sockjs/lib/iframe.js
JavaScript
gpl-3.0
1,235
/** * @param func * @return {Observable<R>} * @method let * @owner Observable */ export function letProto(func) { return func(this); } //# sourceMappingURL=let.js.map
rospilot/rospilot
share/web_assets/nodejs_deps/node_modules/rxjs/_esm2015/operator/let.js
JavaScript
apache-2.0
175
package net.simonvt.menudrawer; import android.os.Build; import android.view.View; final class ViewHelper { private ViewHelper() { } public static int getLeft(View v) { if (MenuDrawer.USE_TRANSLATIONS) { return (int) (v.getLeft() + v.getTranslationX()); } return v.getLeft(); } public static int getTop(View v) { if (MenuDrawer.USE_TRANSLATIONS) { return (int) (v.getTop() + v.getTranslationY()); } return v.getTop(); } public static int getRight(View v) { if (MenuDrawer.USE_TRANSLATIONS) { return (int) (v.getRight() + v.getTranslationX()); } return v.getRight(); } public static int getBottom(View v) { if (MenuDrawer.USE_TRANSLATIONS) { return (int) (v.getBottom() + v.getTranslationY()); } return v.getBottom(); } public static int getLayoutDirection(View v) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { return v.getLayoutDirection(); } return View.LAYOUT_DIRECTION_LTR; } }
W3SS/android-menudrawer
menudrawer/src/net/simonvt/menudrawer/ViewHelper.java
Java
apache-2.0
1,145
/********************************************************************* * * * Configfemtoanalysis.C - configuration macro for the femtoscopic * * analysis, meant as a QA process for two-particle effects * * * * Author: Adam Kisiel (Adam.Kisiel@cern.ch) * * * *********************************************************************/ #if !defined(__CINT__) || defined(__MAKECINT_) #include "AliFemtoManager.h" #include "AliFemtoEventReaderESDChain.h" #include "AliFemtoEventReaderESDChainKine.h" #include "AliFemtoEventReaderAODChain.h" #include "AliFemtoSimpleAnalysis.h" #include "AliFemtoBasicEventCut.h" #include "AliFemtoESDTrackCut.h" #include "AliFemtoCorrFctn.h" #include "AliFemtoCutMonitorParticleYPt.h" #include "AliFemtoCutMonitorParticleVertPos.h" #include "AliFemtoCutMonitorParticleMomRes.h" #include "AliFemtoCutMonitorParticlePID.h" #include "AliFemtoCutMonitorEventMult.h" #include "AliFemtoCutMonitorEventVertex.h" #include "AliFemtoShareQualityTPCEntranceSepPairCut.h" #include "AliFemtoPairCutAntiGamma.h" #include "AliFemtoPairCutRadialDistance.h" #include "AliFemtoQinvCorrFctn.h" #include "AliFemtoCorrFctnNonIdDR.h" #include "AliFemtoShareQualityCorrFctn.h" #include "AliFemtoTPCInnerCorrFctn.h" #include "AliFemtoVertexMultAnalysis.h" #include "AliFemtoCorrFctn3DSpherical.h" #include "AliFemtoChi2CorrFctn.h" #include "AliFemtoCorrFctnTPCNcls.h" #include "AliFemtoBPLCMS3DCorrFctn.h" #include "AliFemtoCorrFctn3DLCMSSym.h" #include "AliFemtoModelBPLCMSCorrFctn.h" #include "AliFemtoModelCorrFctn3DSpherical.h" #include "AliFemtoModelGausLCMSFreezeOutGenerator.h" #include "AliFemtoModelGausRinvFreezeOutGenerator.h" #include "AliFemtoModelManager.h" #include "AliFemtoModelWeightGeneratorBasic.h" #include "AliFemtoModelWeightGeneratorLednicky.h" #include "AliFemtoCorrFctnDirectYlm.h" #include "AliFemtoModelCorrFctnDirectYlm.h" #include "AliFemtoModelCorrFctnSource.h" #include "AliFemtoCutMonitorParticlePtPDG.h" #include "AliFemtoKTPairCut.h" #include "AliFemtoAvgSepCorrFctn.h" #endif //________________________________________________________________________ AliFemtoManager* ConfigFemtoAnalysis() { double PionMass = 0.13956995; double KaonMass = 0.493677; double ProtonMass = 0.938272013; // double psi = TMath::Pi()/2.; // double psid = TMath::Pi()/6.; // int runepvzero[7] = {1, 1, 1, 1, 1, 1, 1}; // double epvzerobins[7] = {-psi, -psi+psid, -psi+2*psid, -psi+3*psid, -psi+4*psid, -psi+5*psid, -psi+6*psid}; double psi = TMath::Pi()/2.; double psid = TMath::Pi()/3.; int runepvzero[4] = {0, 0, 0, 1}; double epvzerobins[4] = {-psi, -psi+psid, -psi+2*psid, -psi+3*psid}; int runmults[10] = {1, 1, 0, 0, 0, 0, 0, 0, 0, 0}; int multbins[11] = {0.001, 50, 100, 200, 300, 400, 500, 600, 700, 800, 900}; int runch[3] = {1, 1, 1}; const char *chrgs[3] = { "PP", "APAP", "PAP" }; int runktdep = 1; double ktrng[3] = {0.01, 1.0, 5.0}; int numOfMultBins = 10; int numOfChTypes = 3; int numOfkTbins = 2; int numOfEPvzero = 4; int runqinv = 1; int runshlcms = 0;// 0:PRF(PAP), 1:LCMS(PP,APAP) int runtype = 2; // Types 0 - global, 1 - ITS only, 2 - TPC Inner int isrealdata = 1; // int gammacut = 1; double shqmax = 1.0; int nbinssh = 100; AliFemtoEventReaderAODChain *Reader = new AliFemtoEventReaderAODChain(); Reader->SetFilterBit(7); Reader->SetCentralityPreSelection(0.001, 310); Reader->SetEPVZERO(kTRUE); AliFemtoManager* Manager = new AliFemtoManager(); Manager->SetEventReader(Reader); AliFemtoVertexMultAnalysis *anetaphitpc[10*3*2]; AliFemtoBasicEventCut *mecetaphitpc[10*3*2]; AliFemtoCutMonitorEventMult *cutPassEvMetaphitpc[50]; AliFemtoCutMonitorEventMult *cutFailEvMetaphitpc[50]; // AliFemtoCutMonitorEventVertex *cutPassEvVetaphitpc[50]; // AliFemtoCutMonitorEventVertex *cutFailEvVetaphitpc[50]; AliFemtoESDTrackCut *dtc1etaphitpc[50]; AliFemtoESDTrackCut *dtc2etaphitpc[50]; AliFemtoCutMonitorParticleYPt *cutPass1YPtetaphitpc[50]; AliFemtoCutMonitorParticleYPt *cutFail1YPtetaphitpc[50]; AliFemtoCutMonitorParticlePID *cutPass1PIDetaphitpc[50]; AliFemtoCutMonitorParticlePID *cutFail1PIDetaphitpc[50]; AliFemtoCutMonitorParticleYPt *cutPass2YPtetaphitpc[50]; AliFemtoCutMonitorParticleYPt *cutFail2YPtetaphitpc[50]; AliFemtoCutMonitorParticlePID *cutPass2PIDetaphitpc[50]; AliFemtoCutMonitorParticlePID *cutFail2PIDetaphitpc[50]; // AliFemtoPairCutAntiGamma *sqpcetaphitpcdiff[10*3]; // AliFemtoShareQualityTPCEntranceSepPairCut *sqpcetaphitpcsame[10*3]; //AliFemtoPairCutAntiGamma *sqpcetaphitpc[10*3]; AliFemtoPairCutRadialDistance *sqpcetaphitpc[50]; // AliFemtoChi2CorrFctn *cchiqinvetaphitpc[20*2]; AliFemtoKTPairCut *ktpcuts[50*2]; AliFemtoCorrFctnDirectYlm *cylmtpc[50]; AliFemtoCorrFctnDirectYlm *cylmkttpc[50*2]; AliFemtoCorrFctnDirectYlm *cylmetaphitpc[10*3]; AliFemtoQinvCorrFctn *cqinvkttpc[50*2]; AliFemtoQinvCorrFctn *cqinvtpc[50]; AliFemtoCorrFctnNonIdDR *ckstartpc[50]; AliFemtoCorrFctnNonIdDR *ckstarkttpc[50*2]; AliFemtoCorrFctnDEtaDPhi *cdedpetaphi[50*2]; AliFemtoAvgSepCorrFctn *cAvgSeptpc[50]; // AliFemtoCorrFctn3DLCMSSym *cq3dlcmskttpc[20*2]; // AliFemtoCorrFctnTPCNcls *cqinvnclstpc[20]; // AliFemtoShareQualityCorrFctn *cqinvsqtpc[20*10]; // AliFemtoChi2CorrFctn *cqinvchi2tpc[20]; AliFemtoTPCInnerCorrFctn *cqinvinnertpc[50]; // *** Third QA task - HBT analysis with all pair cuts off, TPC only *** // *** Begin pion-pion (positive) analysis *** int aniter = 0; for (int imult = 0; imult < numOfMultBins; imult++) { if (runmults[imult]) { for (int ichg = 0; ichg < numOfChTypes; ichg++) { if (runch[ichg]) { for (int iepvzero = 0; iepvzero < numOfEPvzero; iepvzero++) { if (runepvzero[iepvzero]) { aniter = imult * numOfChTypes + ichg * numOfEPvzero + iepvzero; // aniter = ichg * numOfMultBins + imult * numOfEPvzero + iepvzero; // cout << "aniter = " << aniter << endl; // aniter = ichg * numOfMultBins + imult; // if (ichg == 2) // runshlcms = 0; // else // runshlcms = 1; //________________________ anetaphitpc[aniter] = new AliFemtoVertexMultAnalysis(8, -8.0, 8.0, 4, multbins[imult], multbins[imult+1]); anetaphitpc[aniter]->SetNumEventsToMix(10); anetaphitpc[aniter]->SetMinSizePartCollection(1); anetaphitpc[aniter]->SetVerboseMode(kFALSE); mecetaphitpc[aniter] = new AliFemtoBasicEventCut(); mecetaphitpc[aniter]->SetEventMult(0.001,100000); mecetaphitpc[aniter]->SetVertZPos(-8,8); if (iepvzero == 3) mecetaphitpc[aniter]->SetEPVZERO(epvzerobins[0],epvzerobins[3]); else mecetaphitpc[aniter]->SetEPVZERO(epvzerobins[iepvzero],epvzerobins[iepvzero+1]); // if (isrealdata) // mecetaphitpc[aniter]->SetAcceptOnlyPhysics(kTRUE); // cutPassEvMetaphitpc[aniter] = new AliFemtoCutMonitorEventMult(Form("cutPass%stpcM%iPsi%i", chrgs[ichg], imult, iepvzero)); // cutFailEvMetaphitpc[aniter] = new AliFemtoCutMonitorEventMult(Form("cutFail%stpcM%iPsi%i", chrgs[ichg], imult, iepvzero)); // mecetaphitpc[aniter]->AddCutMonitor(cutPassEvMetaphitpc[aniter], cutFailEvMetaphitpc[aniter]); // cutPassEvVetaphitpc[aniter] = new AliFemtoCutMonitorEventVertex(Form("cutPass%stpcM%i", chrgs[ichg], imult)); // cutFailEvVetaphitpc[aniter] = new AliFemtoCutMonitorEventVertex(Form("cutFail%stpcM%i", chrgs[ichg], imult)); // mecetaphitpc[aniter]->AddCutMonitor(cutPassEvVetaphitpc[aniter], cutFailEvVetaphitpc[aniter]); dtc1etaphitpc[aniter] = new AliFemtoESDTrackCut(); dtc2etaphitpc[aniter] = new AliFemtoESDTrackCut(); if (ichg == 0) { dtc1etaphitpc[aniter]->SetCharge(1.0); dtc1etaphitpc[aniter]->SetPt(0.7,4.0); } else if (ichg == 1) { dtc1etaphitpc[aniter]->SetCharge(-1.0); dtc1etaphitpc[aniter]->SetPt(0.7,4.0); } else if (ichg == 2) { dtc1etaphitpc[aniter]->SetCharge(-1.0); dtc2etaphitpc[aniter]->SetCharge(1.0); dtc1etaphitpc[aniter]->SetPt(0.7,4.0); dtc2etaphitpc[aniter]->SetPt(0.7,4.0); } dtc1etaphitpc[aniter]->SetEta(-0.8,0.8); dtc1etaphitpc[aniter]->SetMass(ProtonMass); dtc1etaphitpc[aniter]->SetMostProbableProton(); dtc1etaphitpc[aniter]->SetNsigma(3.0); //dtc1etaphitpc[aniter]->SetNsigma(2.0); dtc1etaphitpc[aniter]->SetNsigmaTPCTOF(kTRUE); //dtc1etaphitpc[aniter]->SetNsigmaTPConly(kTRUE); if (ichg == 2) { dtc2etaphitpc[aniter]->SetEta(-0.8,0.8); dtc2etaphitpc[aniter]->SetMass(ProtonMass); dtc2etaphitpc[aniter]->SetMostProbableProton(); dtc2etaphitpc[aniter]->SetNsigma(3.0); //dtc2etaphitpc[aniter]->SetNsigma(2.0); dtc2etaphitpc[aniter]->SetNsigmaTPCTOF(kTRUE); //dtc2etaphitpc[aniter]->SetNsigmaTPConly(kTRUE); } // Track quality cuts if (runtype == 0) { dtc1etaphitpc[aniter]->SetStatus(AliESDtrack::kTPCrefit|AliESDtrack::kITSrefit); // dtc1etaphitpc[aniter]->SetStatus(AliESDtrack::kTPCrefit); // dtc1etaphitpc[aniter]->SetStatus(AliESDtrack::kITSrefit); dtc1etaphitpc[aniter]->SetminTPCncls(80); dtc1etaphitpc[aniter]->SetRemoveKinks(kTRUE); dtc1etaphitpc[aniter]->SetLabel(kFALSE); // dtc1etaphitpc[aniter]->SetMaxITSChiNdof(6.0); dtc1etaphitpc[aniter]->SetMaxTPCChiNdof(4.0); dtc1etaphitpc[aniter]->SetMaxImpactXY(0.2); // dtc1etaphitpc[aniter]->SetMaxImpactXYPtDep(0.0182, 0.0350, -1.01); dtc1etaphitpc[aniter]->SetMaxImpactZ(0.15); // dtc1etaphitpc[aniter]->SetMaxSigmaToVertex(6.0); } else if (runtype == 1) { // dtc1etaphitpc[aniter]->SetStatus(AliESDtrack::kTPCrefit|AliESDtrack::kITSrefit); // dtc1etaphitpc[aniter]->SetStatus(AliESDtrack::kTPCrefit); // dtc1etaphitpc[aniter]->SetStatus(AliESDtrack::kITSrefit|AliESDtrack::kITSpureSA); // dtc1etaphitpc[aniter]->SetminTPCncls(70); dtc1etaphitpc[aniter]->SetStatus(AliESDtrack::kITSrefit); dtc1etaphitpc[aniter]->SetRemoveKinks(kTRUE); dtc1etaphitpc[aniter]->SetLabel(kFALSE); // dtc1etaphitpc[aniter]->SetMaxITSChiNdof(6.0); // dtc1etaphitpc[aniter]->SetMaxTPCChiNdof(6.0); dtc1etaphitpc[aniter]->SetMaxImpactXY(0.2); dtc1etaphitpc[aniter]->SetMaxImpactZ(0.25); // dtc1etaphitpc[aniter]->SetMaxSigmaToVertex(6.0); } else if (runtype == 2) { //dtc1etaphitpc[aniter]->SetStatus(AliESDtrack::kTPCrefit|AliESDtrack::kITSrefit); dtc1etaphitpc[aniter]->SetStatus(AliESDtrack::kTPCin); dtc1etaphitpc[aniter]->SetminTPCncls(80); dtc1etaphitpc[aniter]->SetRemoveKinks(kTRUE); dtc1etaphitpc[aniter]->SetLabel(kFALSE); dtc1etaphitpc[aniter]->SetMaxTPCChiNdof(4.0); dtc1etaphitpc[aniter]->SetMaxImpactXY(2.4); // 2.4 0.1 // dtc1etaphitpc[aniter]->SetMaxImpactXYPtDep(0.0205, 0.035, -1.1); // DCA xy // dtc1etaphitpc[aniter]->SetMaxImpactXYPtDep(0.018, 0.035, -1.01); // DCA xy dtc1etaphitpc[aniter]->SetMaxImpactZ(3.2); // 2.0 0.1 if (ichg == 2) { //dtc1etaphitpc[aniter]->SetStatus(AliESDtrack::kTPCrefit|AliESDtrack::kITSrefit); dtc2etaphitpc[aniter]->SetStatus(AliESDtrack::kTPCin); dtc2etaphitpc[aniter]->SetminTPCncls(80); dtc2etaphitpc[aniter]->SetRemoveKinks(kTRUE); dtc2etaphitpc[aniter]->SetLabel(kFALSE); dtc2etaphitpc[aniter]->SetMaxTPCChiNdof(4.0); dtc2etaphitpc[aniter]->SetMaxImpactXY(2.4); // 2.4 0.1 // dtc2etaphitpc[aniter]->SetMaxImpactXYPtDep(0.0205, 0.035, -1.1); // DCA xy //dtc2etaphitpc[aniter]->SetMaxImpactXYPtDep(0.018, 0.035, -1.01); // DCA xy dtc2etaphitpc[aniter]->SetMaxImpactZ(3.2); // 2.0 0.1 } } cutPass1YPtetaphitpc[aniter] = new AliFemtoCutMonitorParticleYPt(Form("cutPass1%stpcM%iPsi%i", chrgs[ichg], imult, iepvzero),ProtonMass); cutFail1YPtetaphitpc[aniter] = new AliFemtoCutMonitorParticleYPt(Form("cutFail1%stpcM%iPsi%i", chrgs[ichg], imult, iepvzero),ProtonMass); dtc1etaphitpc[aniter]->AddCutMonitor(cutPass1YPtetaphitpc[aniter], cutFail1YPtetaphitpc[aniter]); cutPass1PIDetaphitpc[aniter] = new AliFemtoCutMonitorParticlePID(Form("cutPass1%stpcM%iPsi%i", chrgs[ichg], imult, iepvzero),2);//0-pion,1-kaon,2-proton cutFail1PIDetaphitpc[aniter] = new AliFemtoCutMonitorParticlePID(Form("cutFail1%stpcM%iPsi%i", chrgs[ichg], imult , iepvzero),2); dtc1etaphitpc[aniter]->AddCutMonitor(cutPass1PIDetaphitpc[aniter], cutFail1PIDetaphitpc[aniter]); // if (ichg == 2){ // cutPass2PIDetaphitpc[aniter] = new AliFemtoCutMonitorParticlePID(Form("cutPass2%stpcM%i", chrgs[ichg], imult),2);//0-pion,1-kaon,2-proton // cutFail2PIDetaphitpc[aniter] = new AliFemtoCutMonitorParticlePID(Form("cutFail2%stpcM%i", chrgs[ichg], imult),2); // dtc2etaphitpc[aniter]->AddCutMonitor(cutPass2PIDetaphitpc[aniter], cutFail2PIDetaphitpc[aniter]); // } // sqpcetaphitpc[aniter] = new AliFemtoPairCutAntiGamma(); sqpcetaphitpc[aniter] = new AliFemtoPairCutRadialDistance(); if (runtype == 0) { sqpcetaphitpc[aniter]->SetShareQualityMax(1.0); sqpcetaphitpc[aniter]->SetShareFractionMax(0.05); sqpcetaphitpc[aniter]->SetRemoveSameLabel(kFALSE); // sqpcetaphitpc[aniter]->SetMaxEEMinv(0.0); // sqpcetaphitpc[aniter]->SetMaxThetaDiff(0.0); // sqpcetaphitpc[aniter]->SetTPCEntranceSepMinimum(1.5); //sqpcetaphitpc[aniter]->SetRadialDistanceMinimum(0.12, 0.03); // sqpcetaphitpc[aniter]->SetEtaDifferenceMinimum(0.02); } else if (runtype == 1) { sqpcetaphitpc[aniter]->SetShareQualityMax(1.0); sqpcetaphitpc[aniter]->SetShareFractionMax(1.05); sqpcetaphitpc[aniter]->SetRemoveSameLabel(kFALSE); // sqpcetaphitpc[aniter]->SetMaxEEMinv(0.002); // sqpcetaphitpc[aniter]->SetMaxThetaDiff(0.008); // sqpcetaphitpc[aniter]->SetTPCEntranceSepMinimum(5.0); //sqpcetaphitpc[aniter]->SetRadialDistanceMinimum(1.2, 0.03); // sqpcetaphitpc[aniter]->SetEtaDifferenceMinimum(0.02); } else if (runtype == 2) { //sqpcetaphitpc[aniter]->SetUseAOD(kTRUE); sqpcetaphitpc[aniter]->SetShareQualityMax(1.0); sqpcetaphitpc[aniter]->SetShareFractionMax(0.05); sqpcetaphitpc[aniter]->SetRemoveSameLabel(kFALSE); // if (gammacut == 0) { //sqpcetaphitpc[aniter]->SetMaxEEMinv(0.0); //sqpcetaphitpc[aniter]->SetMaxThetaDiff(0.0); //} //else if (gammacut == 1) { //sqpcetaphitpc[aniter]->SetMaxEEMinv(0.002); //sqpcetaphitpc[aniter]->SetMaxThetaDiff(0.008); //} // sqpcetaphitpc[aniter]->SetMagneticFieldSign(-1); // field1 -1, field3 +1 // sqpcetaphitpc[aniter]->SetMinimumRadius(0.8); // biggest inefficiency for R=1.1 m (checked on small sample) sqpcetaphitpc[aniter]->SetMinimumRadius(1.2); //0.8 sqpcetaphitpc[aniter]->SetPhiStarMin(kFALSE); sqpcetaphitpc[aniter]->SetPhiStarDifferenceMinimum(0.017); // 0.012 - pions, 0.017 - kaons, 0.018 sqpcetaphitpc[aniter]->SetEtaDifferenceMinimum(0.012); // 0.017 - pions, 0.015 - kaons } anetaphitpc[aniter]->SetEventCut(mecetaphitpc[aniter]); if (ichg == 2) { anetaphitpc[aniter]->SetFirstParticleCut(dtc1etaphitpc[aniter]); anetaphitpc[aniter]->SetSecondParticleCut(dtc2etaphitpc[aniter]); } else { anetaphitpc[aniter]->SetFirstParticleCut(dtc1etaphitpc[aniter]); anetaphitpc[aniter]->SetSecondParticleCut(dtc1etaphitpc[aniter]); } anetaphitpc[aniter]->SetPairCut(sqpcetaphitpc[aniter]); if (ichg == 2) { ckstartpc[aniter] = new AliFemtoCorrFctnNonIdDR(Form("ckstar%stpcM%iPsi%i", chrgs[ichg], imult, iepvzero),nbinssh,0.0,shqmax); anetaphitpc[aniter]->AddCorrFctn(ckstartpc[aniter]); } else { cqinvtpc[aniter] = new AliFemtoQinvCorrFctn(Form("cqinv%stpcM%iPsi%i", chrgs[ichg], imult, iepvzero),2*nbinssh,0.0,2*shqmax); anetaphitpc[aniter]->AddCorrFctn(cqinvtpc[aniter]); } cylmtpc[aniter] = new AliFemtoCorrFctnDirectYlm(Form("cylm%stpcM%i", chrgs[ichg], imult),2,nbinssh, 0.0,shqmax,runshlcms); anetaphitpc[aniter]->AddCorrFctn(cylmtpc[aniter]); // cAvgSeptpc[aniter] = new AliFemtoAvgSepCorrFctn(Form("cAvgSep%stpcM%iPsi%i", chrgs[ichg], imult, iepvzero),4*nbinssh,0.0,200); // anetaphitpc[aniter]->AddCorrFctn(cAvgSeptpc[aniter]); cqinvinnertpc[aniter] = new AliFemtoTPCInnerCorrFctn(Form("cqinvinner%stpcM%d", chrgs[ichg], imult),nbinssh,0.0,shqmax); cqinvinnertpc[aniter]->SetRadius(1.2); anetaphitpc[aniter]->AddCorrFctn(cqinvinnertpc[aniter]); if (runktdep) { int ktm; for (int ikt=0; ikt<numOfkTbins; ikt++) { ktm = aniter * numOfkTbins + ikt; ktpcuts[ktm] = new AliFemtoKTPairCut(ktrng[ikt], ktrng[ikt+1]); cylmkttpc[ktm] = new AliFemtoCorrFctnDirectYlm(Form("cylm%stpcM%ikT%i", chrgs[ichg], imult, ikt),2,nbinssh,0.0,shqmax,runshlcms); cylmkttpc[ktm]->SetPairSelectionCut(ktpcuts[ktm]); anetaphitpc[aniter]->AddCorrFctn(cylmkttpc[ktm]); if (ichg == 2) { ckstarkttpc[ktm] = new AliFemtoCorrFctnNonIdDR(Form("ckstar%stpcM%iPsi%ikT%i", chrgs[ichg], imult, iepvzero, ikt),nbinssh,0.0,shqmax); ckstarkttpc[ktm]->SetPairSelectionCut(ktpcuts[ktm]); anetaphitpc[aniter]->AddCorrFctn(ckstarkttpc[ktm]); } else { cqinvkttpc[ktm] = new AliFemtoQinvCorrFctn(Form("cqinv%stpcM%iPsi%ikT%i", chrgs[ichg], imult, iepvzero, ikt),2*nbinssh,0.0,2*shqmax); cqinvkttpc[ktm]->SetPairSelectionCut(ktpcuts[ktm]); anetaphitpc[aniter]->AddCorrFctn(cqinvkttpc[ktm]); } // cqinvsqtpc[ktm] = new AliFemtoShareQualityCorrFctn(Form("cqinvsq%stpcM%ikT%i", chrgs[ichg], imult, ikt),nbinssh,0.0,shqmax); // cqinvsqtpc[ktm]->SetPairSelectionCut(ktpcuts[ktm]); // anetaphitpc[aniter]->AddCorrFctn(cqinvsqtpc[ktm]); // cqinvinnertpc[ktm] = new AliFemtoTPCInnerCorrFctn(Form("cqinvinner%stpcM%ikT%i", chrgs[ichg], imult, ikt),nbinssh,0.0,shqmax); // cqinvinnertpc[ktm]->SetPairSelectionCut(ktpcuts[ktm]); // cqinvinnertpc[ktm]->SetRadius(1.2); // anetaphitpc[aniter]->AddCorrFctn(cqinvinnertpc[ktm]); // if (run3d) { // cq3dlcmskttpc[ktm] = new AliFemtoCorrFctn3DLCMSSym(Form("cq3d%stpcM%ikT%i", chrgs[ichg], imult, ikt),60,(imult>3)?((imult>6)?((imult>7)?0.6:0.4):0.25):0.15); // cq3dlcmskttpc[ktm]->SetPairSelectionCut(ktpcuts[ktm]); // anetaphitpc[aniter]->AddCorrFctn(cq3dlcmskttpc[ktm]); // } } } // cdedpetaphi[aniter] = new AliFemtoCorrFctnDEtaDPhi(Form("cdedp%stpcM%i", chrgs[ichg], imult),240, 240); // anetaphitpc[aniter]->AddCorrFctn(cdedpetaphi[aniter]); Manager->AddAnalysis(anetaphitpc[aniter]); } } } } } } // *** End pion-pion (positive) analysis return Manager; }
fcolamar/AliPhysics
PWGCF/FEMTOSCOPY/macros/Train/ProtonFemtoscopy/DcaTpcOnlyTTC4/central/ConfigFemtoAnalysis.C
C++
bsd-3-clause
21,741
AT.prototype.atSepHelpers = { sepText: function(){ return T9n.get(AccountsTemplates.texts.sep, markIfMissing=false); }, };
foysalit/SpaceTalk
packages/useraccounts-core/lib/templates_helpers/at_sep.js
JavaScript
mit
138
/* * Date Format 1.2.3 * (c) 2007-2009 Steven Levithan <stevenlevithan.com> * MIT license * * Includes enhancements by Scott Trenda <scott.trenda.net> * and Kris Kowal <cixar.com/~kris.kowal/> * * Accepts a date, a mask, or a date and a mask. * Returns a formatted version of the given date. * The date defaults to the current date/time. * The mask defaults to dateFormat.masks.default. */ var dateFormat = function () { var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g, timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g, timezoneClip = /[^-+\dA-Z]/g, pad = function (val, len) { val = String(val); len = len || 2; while (val.length < len) val = "0" + val; return val; }; // Regexes and supporting functions are cached through closure return function (date, mask, utc) { var dF = dateFormat; // You can't provide utc if you skip other args (use the "UTC:" mask prefix) if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) { mask = date; date = undefined; } // Passing date through Date applies Date.parse, if necessary date = date ? new Date(date) : new Date; if (isNaN(date)) throw SyntaxError("invalid date"); mask = String(dF.masks[mask] || mask || dF.masks["default"]); // Allow setting the utc argument via the mask if (mask.slice(0, 4) == "UTC:") { mask = mask.slice(4); utc = true; } var _ = utc ? "getUTC" : "get", d = date[_ + "Date"](), D = date[_ + "Day"](), m = date[_ + "Month"](), y = date[_ + "FullYear"](), H = date[_ + "Hours"](), M = date[_ + "Minutes"](), s = date[_ + "Seconds"](), L = date[_ + "Milliseconds"](), o = utc ? 0 : date.getTimezoneOffset(), flags = { d: d, dd: pad(d), ddd: dF.i18n.dayNames[D], dddd: dF.i18n.dayNames[D + 7], m: m + 1, mm: pad(m + 1), mmm: dF.i18n.monthNames[m], mmmm: dF.i18n.monthNames[m + 12], yy: String(y).slice(2), yyyy: y, h: H % 12 || 12, hh: pad(H % 12 || 12), H: H, HH: pad(H), M: M, MM: pad(M), s: s, ss: pad(s), l: pad(L, 3), L: pad(L > 99 ? Math.round(L / 10) : L), t: H < 12 ? "a" : "p", tt: H < 12 ? "am" : "pm", T: H < 12 ? "A" : "P", TT: H < 12 ? "AM" : "PM", Z: utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""), o: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4), S: ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10] }; return mask.replace(token, function ($0) { return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1); }); }; }(); // Some common format strings dateFormat.masks = { "default": "ddd mmm dd yyyy HH:MM:ss", shortDate: "m/d/yy", mediumDate: "mmm d, yyyy", longDate: "mmmm d, yyyy", fullDate: "dddd, mmmm d, yyyy", shortTime: "h:MM TT", mediumTime: "h:MM:ss TT", longTime: "h:MM:ss TT Z", isoDate: "yyyy-mm-dd", isoTime: "HH:MM:ss", isoDateTime: "yyyy-mm-dd'T'HH:MM:ss", isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'" }; // Internationalization strings dateFormat.i18n = { dayNames: [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], monthNames: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ] }; // For convenience... Date.prototype.format = function (mask, utc) { return dateFormat(this, mask, utc); };
j-mcnally/teenage_mutant_ninja_graphs
vendor/assets/javascripts/libs/date.format.js
JavaScript
mit
4,117
app.controller("LayersLayergroupSimpleController", [ "$scope", function($scope) { angular.extend($scope, { center: { lat: 39, lng: -100, zoom: 3 }, layers: { baselayers: { xyz: { name: 'OpenStreetMap (XYZ)', url: 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', type: 'xyz' } }, overlays: {} } }); var tileLayer = { name: 'Countries', type: 'xyz', url: 'http://{s}.tiles.mapbox.com/v3/milkator.press_freedom/{z}/{x}/{y}.png', visible: true, layerOptions: { attribution: 'Map data &copy; 2013 Natural Earth | Data &copy; 2013 <a href="http://www.reporter-ohne-grenzen.de/ranglisten/rangliste-2013/">ROG/RSF</a>', maxZoom: 5 } }; var utfGrid = { name: 'UtfGrid', type: 'utfGrid', url: 'http://{s}.tiles.mapbox.com/v3/milkator.press_freedom/{z}/{x}/{y}.grid.json?callback={cb}', visible: true, pluginOptions: { maxZoom: 5, resolution: 4 } }; var group = { name: 'Group Layer', type: 'group', visible: true, layerOptions: { layers: [ tileLayer, utfGrid], maxZoom: 5 } }; $scope.layers['overlays']['Group Layer'] = group; $scope.$on('leafletDirectiveMap.utfgridMouseover', function(event, leafletEvent) { $scope.country = leafletEvent.data.name; }); }]);
ronnpang1/otocopy
www/lib/angular-leaflet-directive-master/examples/js/controllers/LayersLayergroupSimpleController.js
JavaScript
mit
1,967
import React from 'react/addons'; import ContainerListItem from './ContainerListItem.react'; var ContainerList = React.createClass({ componentWillMount: function () { this.start = Date.now(); }, render: function () { var containers = this.props.containers.map(container => { return ( <ContainerListItem key={container.Id} container={container} start={this.start} /> ); }); return ( <ul> {containers} </ul> ); } }); module.exports = ContainerList;
moxiegirl/kitematic
src/components/ContainerList.react.js
JavaScript
apache-2.0
517
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.ui.plaf.beg; import com.intellij.util.ui.UIUtil; import javax.swing.*; import javax.swing.border.AbstractBorder; import javax.swing.border.Border; import javax.swing.border.LineBorder; import javax.swing.plaf.BorderUIResource; import javax.swing.plaf.UIResource; import javax.swing.plaf.basic.BasicBorders; import javax.swing.plaf.metal.MetalLookAndFeel; import javax.swing.text.JTextComponent; import java.awt.*; /** * @author Eugene Belyaev */ public class BegBorders { private static Border ourButtonBorder; private static Border ourTextFieldBorder; private static Border ourScrollPaneBorder; public static Border getButtonBorder() { if (ourButtonBorder == null) { ourButtonBorder = new BorderUIResource.CompoundBorderUIResource( new ButtonBorder(), new BasicBorders.MarginBorder()); } return ourButtonBorder; } public static Border getTextFieldBorder() { if (ourTextFieldBorder == null) { ourTextFieldBorder = new BorderUIResource.CompoundBorderUIResource( new TextFieldBorder(), //new FlatLineBorder(), BorderFactory.createEmptyBorder(2, 2, 2, 2)); } return ourTextFieldBorder; } public static Border getScrollPaneBorder() { if (ourScrollPaneBorder == null) { ourScrollPaneBorder = new BorderUIResource.LineBorderUIResource(MetalLookAndFeel.getControlDarkShadow()); //ourScrollPaneBorder = new FlatLineBorder(); } return ourScrollPaneBorder; } public static class FlatLineBorder extends LineBorder implements UIResource { public FlatLineBorder() { super(new Color(127, 157, 185), 1, true); } } public static class ButtonBorder extends AbstractBorder implements UIResource { protected static Insets borderInsets = new Insets(3, 3, 3, 3); public void paintBorder(Component c, Graphics g, int x, int y, int w, int h) { AbstractButton button = (AbstractButton) c; ButtonModel model = button.getModel(); if (model.isEnabled()) { boolean isPressed = model.isPressed() && model.isArmed(); boolean isDefault = (button instanceof JButton && ((JButton) button).isDefaultButton()); if (isPressed && isDefault) { drawDefaultButtonPressedBorder(g, x, y, w, h); } else if (isPressed) { drawPressed3DBorder(g, x, y, w, h); } else if (isDefault) { drawDefaultButtonBorder(g, x, y, w, h, false); } else { drawButtonBorder(g, x, y, w, h, false); } } else { // disabled state drawDisabledBorder(g, x, y, w - 1, h - 1); } } public Insets getBorderInsets(Component c) { return (Insets)borderInsets.clone(); } public Insets getBorderInsets(Component c, Insets newInsets) { newInsets.top = borderInsets.top; newInsets.left = borderInsets.left; newInsets.bottom = borderInsets.bottom; newInsets.right = borderInsets.right; return newInsets; } } public static class ScrollPaneBorder extends AbstractBorder implements UIResource { private static final Insets insets = new Insets(1, 1, 2, 2); public void paintBorder(Component c, Graphics g, int x, int y, int w, int h) { JScrollPane scroll = (JScrollPane) c; JComponent colHeader = scroll.getColumnHeader(); int colHeaderHeight = 0; if (colHeader != null) colHeaderHeight = colHeader.getHeight(); JComponent rowHeader = scroll.getRowHeader(); int rowHeaderWidth = 0; if (rowHeader != null) rowHeaderWidth = rowHeader.getWidth(); /* g.translate(x, y); g.setColor(MetalLookAndFeel.getControlDarkShadow()); g.drawRect(0, 0, w - 2, h - 2); g.setColor(MetalLookAndFeel.getControlHighlight()); g.drawLine(w - 1, 1, w - 1, h - 1); g.drawLine(1, h - 1, w - 1, h - 1); g.setColor(MetalLookAndFeel.getControl()); if (colHeaderHeight > 0) { g.drawLine(w - 2, 2 + colHeaderHeight, w - 2, 2 + colHeaderHeight); } if (rowHeaderWidth > 0) { g.drawLine(1 + rowHeaderWidth, h - 2, 1 + rowHeaderWidth, h - 2); } g.translate(-x, -y); */ drawLineBorder(g, x, y, w, h); } public Insets getBorderInsets(Component c) { return (Insets)insets.clone(); } } public static class TextFieldBorder /*extends MetalBorders.Flush3DBorder*/ extends LineBorder implements UIResource { public TextFieldBorder() { super(null, 1); } public boolean isBorderOpaque() { return false; } public void paintBorder(Component c, Graphics g, int x, int y, int w, int h) { if (!(c instanceof JTextComponent)) { // special case for non-text components (bug ID 4144840) if (c.isEnabled()) { drawFlush3DBorder(g, x, y, w, h); } else { drawDisabledBorder(g, x, y, w, h); } return; } if (c.isEnabled() && ((JTextComponent) c).isEditable()) { drawLineBorder(g, x, y, w, h); /* g.translate(x, y); g.setColor(MetalLookAndFeel.getControlDarkShadow()); g.drawLine(1, 0, w - 2, 0); g.drawLine(0, 1, 0, h - 2); g.drawLine(w - 1, 1, w - 1, h - 2); g.drawLine(1, h - 1, w - 2, h - 1); g.translate(-x, -y); */ } else { drawDisabledBorder(g, x, y, w, h); } } } static void drawLineBorder(Graphics g, int x, int y, int w, int h) { g.translate(x, y); g.setColor(MetalLookAndFeel.getControlDarkShadow()); g.drawRect(0, 0, w - 1, h - 1); g.translate(-x, -y); } static void drawFlush3DBorder(Graphics g, int x, int y, int w, int h) { g.translate(x, y); g.setColor(MetalLookAndFeel.getControlHighlight()); g.drawRect(1, 1, w - 2, h - 2); g.setColor(MetalLookAndFeel.getControlDarkShadow()); g.drawRect(0, 0, w - 2, h - 2); g.translate(-x, -y); } static void drawDisabledBorder(Graphics g, int x, int y, int w, int h) { g.translate(x, y); g.setColor(MetalLookAndFeel.getControlShadow()); g.drawRect(0, 0, w - 1, h - 1); g.translate(-x, -y); } static void drawDefaultButtonPressedBorder(Graphics g, int x, int y, int w, int h) { drawPressed3DBorder(g, x + 1, y + 1, w - 1, h - 1); g.translate(x, y); g.setColor(MetalLookAndFeel.getControlDarkShadow()); g.drawRect(0, 0, w - 3, h - 3); UIUtil.drawLine(g, w - 2, 0, w - 2, 0); UIUtil.drawLine(g, 0, h - 2, 0, h - 2); g.translate(-x, -y); } static void drawPressed3DBorder(Graphics g, int x, int y, int w, int h) { g.translate(x, y); drawFlush3DBorder(g, 0, 0, w, h); g.setColor(MetalLookAndFeel.getControlShadow()); UIUtil.drawLine(g, 1, 1, 1, h - 1); UIUtil.drawLine(g, 1, 1, w - 1, 1); g.translate(-x, -y); } static void drawDefaultButtonBorder(Graphics g, int x, int y, int w, int h, boolean active) { drawButtonBorder(g, x + 1, y + 1, w - 1, h - 1, active); g.translate(x, y); g.setColor(MetalLookAndFeel.getControlDarkShadow()); g.drawRect(0, 0, w - 3, h - 3); UIUtil.drawLine(g, w - 2, 0, w - 2, 0); UIUtil.drawLine(g, 0, h - 2, 0, h - 2); g.translate(-x, -y); } static void drawButtonBorder(Graphics g, int x, int y, int w, int h, boolean active) { if (active) { drawActiveButtonBorder(g, x, y, w, h); } else { drawFlush3DBorder(g, x, y, w, h); /* drawLineBorder(g, x, y, w - 1, h - 1); g.setColor(MetalLookAndFeel.getControlHighlight()); g.drawLine(x + 1, y + h - 1, x + w - 1, y + h - 1); g.drawLine(x + w - 1, y + 1, x + w - 1, y + h - 1); */ } } static void drawActiveButtonBorder(Graphics g, int x, int y, int w, int h) { drawFlush3DBorder(g, x, y, w, h); g.setColor(MetalLookAndFeel.getPrimaryControl()); UIUtil.drawLine(g, x + 1, y + 1, x + 1, h - 3); UIUtil.drawLine(g, x + 1, y + 1, w - 3, x + 1); g.setColor(MetalLookAndFeel.getPrimaryControlDarkShadow()); UIUtil.drawLine(g, x + 2, h - 2, w - 2, h - 2); UIUtil.drawLine(g, w - 2, y + 2, w - 2, h - 2); } }
ivan-fedorov/intellij-community
platform/platform-impl/src/com/intellij/ui/plaf/beg/BegBorders.java
Java
apache-2.0
8,804
import os import re import subprocess import sys import urlparse from wptrunner.update.sync import LoadManifest from wptrunner.update.tree import get_unique_name from wptrunner.update.base import Step, StepRunner, exit_clean, exit_unclean from .tree import Commit, GitTree, Patch import github from .github import GitHub def rewrite_patch(patch, strip_dir): """Take a Patch and convert to a different repository by stripping a prefix from the file paths. Also rewrite the message to remove the bug number and reviewer, but add a bugzilla link in the summary. :param patch: the Patch to convert :param strip_dir: the path prefix to remove """ if not strip_dir.startswith("/"): strip_dir = "/%s"% strip_dir new_diff = [] line_starts = ["diff ", "+++ ", "--- "] for line in patch.diff.split("\n"): for start in line_starts: if line.startswith(start): new_diff.append(line.replace(strip_dir, "").encode("utf8")) break else: new_diff.append(line) new_diff = "\n".join(new_diff) assert new_diff != patch return Patch(patch.author, patch.email, rewrite_message(patch), new_diff) def rewrite_message(patch): rest = patch.message.body if patch.message.bug is not None: return "\n".join([patch.message.summary, patch.message.body, "", "Upstreamed from https://bugzilla.mozilla.org/show_bug.cgi?id=%s" % patch.message.bug]) return "\n".join([patch.message.full_summary, rest]) class SyncToUpstream(Step): """Sync local changes to upstream""" def create(self, state): if not state.kwargs["upstream"]: return if not isinstance(state.local_tree, GitTree): self.logger.error("Cannot sync with upstream from a non-Git checkout.") return exit_clean try: import requests except ImportError: self.logger.error("Upstream sync requires the requests module to be installed") return exit_clean if not state.sync_tree: os.makedirs(state.sync["path"]) state.sync_tree = GitTree(root=state.sync["path"]) kwargs = state.kwargs with state.push(["local_tree", "sync_tree", "tests_path", "metadata_path", "sync"]): state.token = kwargs["token"] runner = SyncToUpstreamRunner(self.logger, state) runner.run() class CheckoutBranch(Step): """Create a branch in the sync tree pointing at the last upstream sync commit and check it out""" provides = ["branch"] def create(self, state): self.logger.info("Updating sync tree from %s" % state.sync["remote_url"]) state.branch = state.sync_tree.unique_branch_name( "outbound_update_%s" % state.test_manifest.rev) state.sync_tree.update(state.sync["remote_url"], state.sync["branch"], state.branch) state.sync_tree.checkout(state.test_manifest.rev, state.branch, force=True) class GetLastSyncCommit(Step): """Find the gecko commit at which we last performed a sync with upstream.""" provides = ["last_sync_path", "last_sync_commit"] def create(self, state): self.logger.info("Looking for last sync commit") state.last_sync_path = os.path.join(state.metadata_path, "mozilla-sync") with open(state.last_sync_path) as f: last_sync_sha1 = f.read().strip() state.last_sync_commit = Commit(state.local_tree, last_sync_sha1) if not state.local_tree.contains_commit(state.last_sync_commit): self.logger.error("Could not find last sync commit %s" % last_sync_sha1) return exit_clean self.logger.info("Last sync to web-platform-tests happened in %s" % state.last_sync_commit.sha1) class GetBaseCommit(Step): """Find the latest upstream commit on the branch that we are syncing with""" provides = ["base_commit"] def create(self, state): state.base_commit = state.sync_tree.get_remote_sha1(state.sync["remote_url"], state.sync["branch"]) self.logger.debug("New base commit is %s" % state.base_commit.sha1) class LoadCommits(Step): """Get a list of commits in the gecko tree that need to be upstreamed""" provides = ["source_commits"] def create(self, state): state.source_commits = state.local_tree.log(state.last_sync_commit, state.tests_path) update_regexp = re.compile("Bug \d+ - Update web-platform-tests to revision [0-9a-f]{40}") for i, commit in enumerate(state.source_commits[:]): if update_regexp.match(commit.message.text): # This is a previous update commit so ignore it state.source_commits.remove(commit) continue if commit.message.backouts: #TODO: Add support for collapsing backouts raise NotImplementedError("Need to get the Git->Hg commits for backouts and remove the backed out patch") if not commit.message.bug: self.logger.error("Commit %i (%s) doesn't have an associated bug number." % (i + 1, commit.sha1)) return exit_unclean self.logger.debug("Source commits: %s" % state.source_commits) class SelectCommits(Step): """Provide a UI to select which commits to upstream""" def create(self, state): if not state.source_commits: return while True: commits = state.source_commits[:] for i, commit in enumerate(commits): print "%i:\t%s" % (i, commit.message.summary) remove = raw_input("Provide a space-separated list of any commits numbers to remove from the list to upstream:\n").strip() remove_idx = set() invalid = False for item in remove.split(" "): try: item = int(item) except: invalid = True break if item < 0 or item >= len(commits): invalid = True break remove_idx.add(item) if invalid: continue keep_commits = [(i,cmt) for i,cmt in enumerate(commits) if i not in remove_idx] #TODO: consider printed removed commits print "Selected the following commits to keep:" for i, commit in keep_commits: print "%i:\t%s" % (i, commit.message.summary) confirm = raw_input("Keep the above commits? y/n\n").strip().lower() if confirm == "y": state.source_commits = [item[1] for item in keep_commits] break class MovePatches(Step): """Convert gecko commits into patches against upstream and commit these to the sync tree.""" provides = ["commits_loaded"] def create(self, state): state.commits_loaded = 0 strip_path = os.path.relpath(state.tests_path, state.local_tree.root) self.logger.debug("Stripping patch %s" % strip_path) for commit in state.source_commits[state.commits_loaded:]: i = state.commits_loaded + 1 self.logger.info("Moving commit %i: %s" % (i, commit.message.full_summary)) patch = commit.export_patch(state.tests_path) stripped_patch = rewrite_patch(patch, strip_path) try: state.sync_tree.import_patch(stripped_patch) except: print patch.diff raise state.commits_loaded = i class RebaseCommits(Step): """Rebase commits from the current branch on top of the upstream destination branch. This step is particularly likely to fail if the rebase generates merge conflicts. In that case the conflicts can be fixed up locally and the sync process restarted with --continue. """ provides = ["rebased_commits"] def create(self, state): self.logger.info("Rebasing local commits") continue_rebase = False # Check if there's a rebase in progress if (os.path.exists(os.path.join(state.sync_tree.root, ".git", "rebase-merge")) or os.path.exists(os.path.join(state.sync_tree.root, ".git", "rebase-apply"))): continue_rebase = True try: state.sync_tree.rebase(state.base_commit, continue_rebase=continue_rebase) except subprocess.CalledProcessError: self.logger.info("Rebase failed, fix merge and run %s again with --continue" % sys.argv[0]) raise state.rebased_commits = state.sync_tree.log(state.base_commit) self.logger.info("Rebase successful") class CheckRebase(Step): """Check if there are any commits remaining after rebase""" def create(self, state): if not state.rebased_commits: self.logger.info("Nothing to upstream, exiting") return exit_clean class MergeUpstream(Step): """Run steps to push local commits as seperate PRs and merge upstream.""" provides = ["merge_index", "gh_repo"] def create(self, state): gh = GitHub(state.token) if "merge_index" not in state: state.merge_index = 0 org, name = urlparse.urlsplit(state.sync["remote_url"]).path[1:].split("/") if name.endswith(".git"): name = name[:-4] state.gh_repo = gh.repo(org, name) for commit in state.rebased_commits[state.merge_index:]: with state.push(["gh_repo", "sync_tree"]): state.commit = commit pr_merger = PRMergeRunner(self.logger, state) rv = pr_merger.run() if rv is not None: return rv state.merge_index += 1 class UpdateLastSyncCommit(Step): """Update the gecko commit at which we last performed a sync with upstream.""" provides = [] def create(self, state): self.logger.info("Updating last sync commit") with open(state.last_sync_path, "w") as f: f.write(state.local_tree.rev) # This gets added to the patch later on class MergeLocalBranch(Step): """Create a local branch pointing at the commit to upstream""" provides = ["local_branch"] def create(self, state): branch_prefix = "sync_%s" % state.commit.sha1 local_branch = state.sync_tree.unique_branch_name(branch_prefix) state.sync_tree.create_branch(local_branch, state.commit) state.local_branch = local_branch class MergeRemoteBranch(Step): """Get an unused remote branch name to use for the PR""" provides = ["remote_branch"] def create(self, state): remote_branch = "sync_%s" % state.commit.sha1 branches = [ref[len("refs/heads/"):] for sha1, ref in state.sync_tree.list_remote(state.gh_repo.url) if ref.startswith("refs/heads")] state.remote_branch = get_unique_name(branches, remote_branch) class PushUpstream(Step): """Push local branch to remote""" def create(self, state): self.logger.info("Pushing commit upstream") state.sync_tree.push(state.gh_repo.url, state.local_branch, state.remote_branch) class CreatePR(Step): """Create a PR for the remote branch""" provides = ["pr"] def create(self, state): self.logger.info("Creating a PR") commit = state.commit state.pr = state.gh_repo.create_pr(commit.message.full_summary, state.remote_branch, "master", commit.message.body if commit.message.body else "") class PRAddComment(Step): """Add an issue comment indicating that the code has been reviewed already""" def create(self, state): state.pr.issue.add_comment("Code reviewed upstream.") class MergePR(Step): """Merge the PR""" def create(self, state): self.logger.info("Merging PR") state.pr.merge() class PRDeleteBranch(Step): """Delete the remote branch""" def create(self, state): self.logger.info("Deleting remote branch") state.sync_tree.push(state.gh_repo.url, "", state.remote_branch) class SyncToUpstreamRunner(StepRunner): """Runner for syncing local changes to upstream""" steps = [LoadManifest, CheckoutBranch, GetLastSyncCommit, GetBaseCommit, LoadCommits, SelectCommits, MovePatches, RebaseCommits, CheckRebase, MergeUpstream, UpdateLastSyncCommit] class PRMergeRunner(StepRunner): """(Sub)Runner for creating and merging a PR""" steps = [ MergeLocalBranch, MergeRemoteBranch, PushUpstream, CreatePR, PRAddComment, MergePR, PRDeleteBranch, ]
meh/servo
tests/wpt/update/upstream.py
Python
mpl-2.0
13,551
/* * Copyright 2001-2011 Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.time; /** * Defines a partial time that does not support every datetime field, and is * thus a local time. * <p> * A {@code ReadablePartial} supports a subset of those fields on the chronology. * It cannot be compared to a {@code ReadableInstant}, as it does not fully * specify an instant in time. The time it does specify is a local time, and does * not include a time zone. * <p> * A {@code ReadablePartial} can be converted to a {@code ReadableInstant} * using the {@code toDateTime} method. This works by providing a full base * instant that can be used to 'fill in the gaps' and specify a time zone. * <p> * {@code ReadablePartial} is {@code Comparable} from v2.0. * The comparison is based on the fields, compared in order, from largest to smallest. * The first field that is non-equal is used to determine the result. * * @author Stephen Colebourne * @since 1.0 */ public interface ReadablePartial extends Comparable<ReadablePartial> { /** * Gets the number of fields that this partial supports. * * @return the number of fields supported */ int size(); /** * Gets the field type at the specified index. * * @param index the index to retrieve * @return the field at the specified index * @throws IndexOutOfBoundsException if the index is invalid */ DateTimeFieldType getFieldType(int index); /** * Gets the field at the specified index. * * @param index the index to retrieve * @return the field at the specified index * @throws IndexOutOfBoundsException if the index is invalid */ DateTimeField getField(int index); /** * Gets the value at the specified index. * * @param index the index to retrieve * @return the value of the field at the specified index * @throws IndexOutOfBoundsException if the index is invalid */ int getValue(int index); /** * Gets the chronology of the partial which is never null. * <p> * The {@link Chronology} is the calculation engine behind the partial and * provides conversion and validation of the fields in a particular calendar system. * * @return the chronology, never null */ Chronology getChronology(); /** * Gets the value of one of the fields. * <p> * The field type specified must be one of those that is supported by the partial. * * @param field a DateTimeFieldType instance that is supported by this partial * @return the value of that field * @throws IllegalArgumentException if the field is null or not supported */ int get(DateTimeFieldType field); /** * Checks whether the field type specified is supported by this partial. * * @param field the field to check, may be null which returns false * @return true if the field is supported */ boolean isSupported(DateTimeFieldType field); /** * Converts this partial to a full datetime by resolving it against another * datetime. * <p> * This method takes the specified datetime and sets the fields from this * instant on top. The chronology from the base instant is used. * <p> * For example, if this partial represents a time, then the result of this * method will be the datetime from the specified base instant plus the * time from this partial. * * @param baseInstant the instant that provides the missing fields, null means now * @return the combined datetime */ DateTime toDateTime(ReadableInstant baseInstant); //----------------------------------------------------------------------- /** * Compares this partial with the specified object for equality based * on the supported fields, chronology and values. * <p> * Two instances of ReadablePartial are equal if they have the same * chronology, same field types (in same order) and same values. * * @param partial the object to compare to * @return true if equal */ boolean equals(Object partial); /** * Gets a hash code for the partial that is compatible with the * equals method. * <p> * The formula used must be: * <pre> * int total = 157; * for (int i = 0; i < fields.length; i++) { * total = 23 * total + values[i]; * total = 23 * total + fieldTypes[i].hashCode(); * } * total += chronology.hashCode(); * return total; * </pre> * * @return a suitable hash code */ int hashCode(); //----------------------------------------------------------------------- // This is commented out to improve backwards compatibility // /** // * Compares this partial with another returning an integer // * indicating the order. // * <p> // * The fields are compared in order, from largest to smallest. // * The first field that is non-equal is used to determine the result. // * Thus a year-hour partial will first be compared on the year, and then // * on the hour. // * <p> // * The specified object must be a partial instance whose field types // * match those of this partial. If the partial instance has different // * fields then a {@code ClassCastException} is thrown. // * // * @param partial an object to check against // * @return negative if this is less, zero if equal, positive if greater // * @throws ClassCastException if the partial is the wrong class // * or if it has field types that don't match // * @throws NullPointerException if the partial is null // * @since 2.0, previously on {@code AbstractPartial} // */ // int compareTo(ReadablePartial partial); //----------------------------------------------------------------------- /** * Get the value as a String in a recognisable ISO8601 format, only * displaying supported fields. * <p> * The string output is in ISO8601 format to enable the String * constructor to correctly parse it. * * @return the value as an ISO8601 string */ String toString(); }
Guardiola31337/joda-time
src/main/java/org/joda/time/ReadablePartial.java
Java
apache-2.0
6,784
/* Copyright 2016 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. */ // Code generated by protoc-gen-gogo. // source: k8s.io/kubernetes/pkg/util/intstr/generated.proto // DO NOT EDIT! /* Package intstr is a generated protocol buffer package. It is generated from these files: k8s.io/kubernetes/pkg/util/intstr/generated.proto It has these top-level messages: IntOrString */ package intstr import proto "github.com/gogo/protobuf/proto" import fmt "fmt" import math "math" import io "io" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. const _ = proto.GoGoProtoPackageIsVersion1 func (m *IntOrString) Reset() { *m = IntOrString{} } func (*IntOrString) ProtoMessage() {} func (*IntOrString) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{0} } func init() { proto.RegisterType((*IntOrString)(nil), "k8s.io.client-go.1.5.pkg.util.intstr.IntOrString") } func (m *IntOrString) Marshal() (data []byte, err error) { size := m.Size() data = make([]byte, size) n, err := m.MarshalTo(data) if err != nil { return nil, err } return data[:n], nil } func (m *IntOrString) MarshalTo(data []byte) (int, error) { var i int _ = i var l int _ = l data[i] = 0x8 i++ i = encodeVarintGenerated(data, i, uint64(m.Type)) data[i] = 0x10 i++ i = encodeVarintGenerated(data, i, uint64(m.IntVal)) data[i] = 0x1a i++ i = encodeVarintGenerated(data, i, uint64(len(m.StrVal))) i += copy(data[i:], m.StrVal) return i, nil } func encodeFixed64Generated(data []byte, offset int, v uint64) int { data[offset] = uint8(v) data[offset+1] = uint8(v >> 8) data[offset+2] = uint8(v >> 16) data[offset+3] = uint8(v >> 24) data[offset+4] = uint8(v >> 32) data[offset+5] = uint8(v >> 40) data[offset+6] = uint8(v >> 48) data[offset+7] = uint8(v >> 56) return offset + 8 } func encodeFixed32Generated(data []byte, offset int, v uint32) int { data[offset] = uint8(v) data[offset+1] = uint8(v >> 8) data[offset+2] = uint8(v >> 16) data[offset+3] = uint8(v >> 24) return offset + 4 } func encodeVarintGenerated(data []byte, offset int, v uint64) int { for v >= 1<<7 { data[offset] = uint8(v&0x7f | 0x80) v >>= 7 offset++ } data[offset] = uint8(v) return offset + 1 } func (m *IntOrString) Size() (n int) { var l int _ = l n += 1 + sovGenerated(uint64(m.Type)) n += 1 + sovGenerated(uint64(m.IntVal)) l = len(m.StrVal) n += 1 + l + sovGenerated(uint64(l)) return n } func sovGenerated(x uint64) (n int) { for { n++ x >>= 7 if x == 0 { break } } return n } func sozGenerated(x uint64) (n int) { return sovGenerated(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } func (m *IntOrString) Unmarshal(data []byte) error { l := len(data) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := data[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: IntOrString: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: IntOrString: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType) } m.Type = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := data[iNdEx] iNdEx++ m.Type |= (Type(b) & 0x7F) << shift if b < 0x80 { break } } case 2: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field IntVal", wireType) } m.IntVal = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := data[iNdEx] iNdEx++ m.IntVal |= (int32(b) & 0x7F) << shift if b < 0x80 { break } } case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field StrVal", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := data[iNdEx] iNdEx++ stringLen |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + intStringLen if postIndex > l { return io.ErrUnexpectedEOF } m.StrVal = string(data[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(data[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthGenerated } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func skipGenerated(data []byte) (n int, err error) { l := len(data) iNdEx := 0 for iNdEx < l { var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowGenerated } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := data[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } wireType := int(wire & 0x7) switch wireType { case 0: for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowGenerated } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } iNdEx++ if data[iNdEx-1] < 0x80 { break } } return iNdEx, nil case 1: iNdEx += 8 return iNdEx, nil case 2: var length int for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowGenerated } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := data[iNdEx] iNdEx++ length |= (int(b) & 0x7F) << shift if b < 0x80 { break } } iNdEx += length if length < 0 { return 0, ErrInvalidLengthGenerated } return iNdEx, nil case 3: for { var innerWire uint64 var start int = iNdEx for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowGenerated } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := data[iNdEx] iNdEx++ innerWire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } innerWireType := int(innerWire & 0x7) if innerWireType == 4 { break } next, err := skipGenerated(data[start:]) if err != nil { return 0, err } iNdEx = start + next } return iNdEx, nil case 4: return iNdEx, nil case 5: iNdEx += 4 return iNdEx, nil default: return 0, fmt.Errorf("proto: illegal wireType %d", wireType) } } panic("unreachable") } var ( ErrInvalidLengthGenerated = fmt.Errorf("proto: negative length found during unmarshaling") ErrIntOverflowGenerated = fmt.Errorf("proto: integer overflow") ) var fileDescriptorGenerated = []byte{ // 256 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0xe2, 0x32, 0xcc, 0xb6, 0x28, 0xd6, 0xcb, 0xcc, 0xd7, 0xcf, 0x2e, 0x4d, 0x4a, 0x2d, 0xca, 0x4b, 0x2d, 0x49, 0x2d, 0xd6, 0x2f, 0xc8, 0x4e, 0xd7, 0x2f, 0x2d, 0xc9, 0xcc, 0xd1, 0xcf, 0xcc, 0x2b, 0x29, 0x2e, 0x29, 0xd2, 0x4f, 0x4f, 0xcd, 0x4b, 0x2d, 0x4a, 0x2c, 0x49, 0x4d, 0xd1, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x52, 0x84, 0x68, 0xd1, 0x43, 0x68, 0xd1, 0x03, 0x6a, 0xd1, 0x03, 0x69, 0xd1, 0x83, 0x68, 0x91, 0xd2, 0x4d, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0xd5, 0x4f, 0xcf, 0x4f, 0xcf, 0xd7, 0x07, 0xeb, 0x4c, 0x2a, 0x4d, 0x03, 0xf3, 0xc0, 0x1c, 0x30, 0x0b, 0x62, 0xa2, 0xd2, 0x44, 0x46, 0x2e, 0x6e, 0xcf, 0xbc, 0x12, 0xff, 0xa2, 0xe0, 0x92, 0xa2, 0xcc, 0xbc, 0x74, 0x21, 0x0d, 0x2e, 0x96, 0x92, 0xca, 0x82, 0x54, 0x09, 0x46, 0x05, 0x46, 0x0d, 0x66, 0x27, 0x91, 0x13, 0xf7, 0xe4, 0x19, 0x1e, 0xdd, 0x93, 0x67, 0x09, 0x01, 0x8a, 0xfd, 0x82, 0xd2, 0x41, 0x60, 0x15, 0x42, 0x6a, 0x5c, 0x6c, 0x40, 0x2b, 0xc3, 0x12, 0x73, 0x24, 0x98, 0x80, 0x6a, 0x59, 0x9d, 0xf8, 0xa0, 0x6a, 0xd9, 0x3c, 0xc1, 0xa2, 0x41, 0x50, 0x59, 0x90, 0x3a, 0xa0, 0xbb, 0x40, 0xea, 0x98, 0x81, 0xea, 0x38, 0x11, 0xea, 0x82, 0xc1, 0xa2, 0x41, 0x50, 0x59, 0x2b, 0x8e, 0x19, 0x0b, 0xe4, 0x19, 0x1a, 0xee, 0x28, 0x30, 0x38, 0x69, 0x9c, 0x78, 0x28, 0xc7, 0x70, 0x01, 0x88, 0x6f, 0x00, 0x71, 0xc3, 0x23, 0x39, 0xc6, 0x13, 0x40, 0x7c, 0x01, 0x88, 0x1f, 0x00, 0xf1, 0x84, 0xc7, 0x72, 0x0c, 0x51, 0x6c, 0x10, 0xcf, 0x02, 0x02, 0x00, 0x00, 0xff, 0xff, 0x68, 0x57, 0xfb, 0xfa, 0x43, 0x01, 0x00, 0x00, }
jnewland/kops
vendor/k8s.io/kubernetes/staging/src/k8s.io/client-go/1.5/pkg/util/intstr/generated.pb.go
GO
apache-2.0
9,633
/* * Copyright (C) 2011 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "DOMNodeHighlighter.h" #if ENABLE(INSPECTOR) #include "Element.h" #include "Frame.h" #include "FrameView.h" #include "GraphicsContext.h" #include "Page.h" #include "Range.h" #include "RenderInline.h" #include "Settings.h" #include "StyledElement.h" #include "TextRun.h" namespace WebCore { namespace { Path quadToPath(const FloatQuad& quad) { Path quadPath; quadPath.moveTo(quad.p1()); quadPath.addLineTo(quad.p2()); quadPath.addLineTo(quad.p3()); quadPath.addLineTo(quad.p4()); quadPath.closeSubpath(); return quadPath; } void drawOutlinedQuad(GraphicsContext& context, const FloatQuad& quad, const Color& fillColor) { static const int outlineThickness = 2; static const Color outlineColor(62, 86, 180, 228); Path quadPath = quadToPath(quad); // Clip out the quad, then draw with a 2px stroke to get a pixel // of outline (because inflating a quad is hard) { context.save(); context.clipOut(quadPath); context.setStrokeThickness(outlineThickness); context.setStrokeColor(outlineColor, ColorSpaceDeviceRGB); context.strokePath(quadPath); context.restore(); } // Now do the fill context.setFillColor(fillColor, ColorSpaceDeviceRGB); context.fillPath(quadPath); } void drawOutlinedQuadWithClip(GraphicsContext& context, const FloatQuad& quad, const FloatQuad& clipQuad, const Color& fillColor) { context.save(); Path clipQuadPath = quadToPath(clipQuad); context.clipOut(clipQuadPath); drawOutlinedQuad(context, quad, fillColor); context.restore(); } void drawHighlightForBox(GraphicsContext& context, const FloatQuad& contentQuad, const FloatQuad& paddingQuad, const FloatQuad& borderQuad, const FloatQuad& marginQuad, DOMNodeHighlighter::HighlightMode mode) { static const Color contentBoxColor(125, 173, 217, 128); static const Color paddingBoxColor(125, 173, 217, 160); static const Color borderBoxColor(125, 173, 217, 192); static const Color marginBoxColor(125, 173, 217, 228); FloatQuad clipQuad; if (mode == DOMNodeHighlighter::HighlightMargin || (mode == DOMNodeHighlighter::HighlightAll && marginQuad != borderQuad)) { drawOutlinedQuadWithClip(context, marginQuad, borderQuad, marginBoxColor); clipQuad = borderQuad; } if (mode == DOMNodeHighlighter::HighlightBorder || (mode == DOMNodeHighlighter::HighlightAll && borderQuad != paddingQuad)) { drawOutlinedQuadWithClip(context, borderQuad, paddingQuad, borderBoxColor); clipQuad = paddingQuad; } if (mode == DOMNodeHighlighter::HighlightPadding || (mode == DOMNodeHighlighter::HighlightAll && paddingQuad != contentQuad)) { drawOutlinedQuadWithClip(context, paddingQuad, contentQuad, paddingBoxColor); clipQuad = contentQuad; } if (mode == DOMNodeHighlighter::HighlightContent || mode == DOMNodeHighlighter::HighlightAll) drawOutlinedQuad(context, contentQuad, contentBoxColor); else drawOutlinedQuadWithClip(context, clipQuad, clipQuad, contentBoxColor); } void drawHighlightForLineBoxesOrSVGRenderer(GraphicsContext& context, const Vector<FloatQuad>& lineBoxQuads) { static const Color lineBoxColor(125, 173, 217, 128); for (size_t i = 0; i < lineBoxQuads.size(); ++i) drawOutlinedQuad(context, lineBoxQuads[i], lineBoxColor); } inline IntSize frameToMainFrameOffset(Frame* frame) { IntPoint mainFramePoint = frame->page()->mainFrame()->view()->windowToContents(frame->view()->contentsToWindow(IntPoint())); return mainFramePoint - IntPoint(); } void drawElementTitle(GraphicsContext& context, Node* node, const IntRect& boundingBox, const IntRect& anchorBox, const FloatRect& overlayRect, WebCore::Settings* settings) { static const int rectInflatePx = 4; static const int fontHeightPx = 12; static const int borderWidthPx = 1; static const Color tooltipBackgroundColor(255, 255, 194, 255); static const Color tooltipBorderColor(Color::black); static const Color tooltipFontColor(Color::black); Element* element = static_cast<Element*>(node); bool isXHTML = element->document()->isXHTMLDocument(); String nodeTitle = isXHTML ? element->nodeName() : element->nodeName().lower(); const AtomicString& idValue = element->getIdAttribute(); if (!idValue.isNull() && !idValue.isEmpty()) { nodeTitle += "#"; nodeTitle += idValue; } if (element->hasClass() && element->isStyledElement()) { const SpaceSplitString& classNamesString = static_cast<StyledElement*>(element)->classNames(); size_t classNameCount = classNamesString.size(); if (classNameCount) { HashSet<AtomicString> usedClassNames; for (size_t i = 0; i < classNameCount; ++i) { const AtomicString& className = classNamesString[i]; if (usedClassNames.contains(className)) continue; usedClassNames.add(className); nodeTitle += "."; nodeTitle += className; } } } nodeTitle += " ["; nodeTitle += String::number(boundingBox.width()); nodeTitle.append(static_cast<UChar>(0x00D7)); // &times; nodeTitle += String::number(boundingBox.height()); nodeTitle += "]"; FontDescription desc; FontFamily family; family.setFamily(settings->fixedFontFamily()); desc.setFamily(family); desc.setComputedSize(fontHeightPx); Font font = Font(desc, 0, 0); font.update(0); TextRun nodeTitleRun(nodeTitle); IntPoint titleBasePoint = IntPoint(anchorBox.x(), anchorBox.maxY() - 1); titleBasePoint.move(rectInflatePx, rectInflatePx); IntRect titleRect = enclosingIntRect(font.selectionRectForText(nodeTitleRun, titleBasePoint, fontHeightPx)); titleRect.inflate(rectInflatePx); // The initial offsets needed to compensate for a 1px-thick border stroke (which is not a part of the rectangle). int dx = -borderWidthPx; int dy = borderWidthPx; // If the tip sticks beyond the right of overlayRect, right-align the tip with the said boundary. if (titleRect.maxX() > overlayRect.maxX()) dx = overlayRect.maxX() - titleRect.maxX(); // If the tip sticks beyond the left of overlayRect, left-align the tip with the said boundary. if (titleRect.x() + dx < overlayRect.x()) dx = overlayRect.x() - titleRect.x() - borderWidthPx; // If the tip sticks beyond the bottom of overlayRect, show the tip at top of bounding box. if (titleRect.maxY() > overlayRect.maxY()) { dy = anchorBox.y() - titleRect.maxY() - borderWidthPx; // If the tip still sticks beyond the bottom of overlayRect, bottom-align the tip with the said boundary. if (titleRect.maxY() + dy > overlayRect.maxY()) dy = overlayRect.maxY() - titleRect.maxY(); } // If the tip sticks beyond the top of overlayRect, show the tip at top of overlayRect. if (titleRect.y() + dy < overlayRect.y()) dy = overlayRect.y() - titleRect.y() + borderWidthPx; titleRect.move(dx, dy); context.setStrokeColor(tooltipBorderColor, ColorSpaceDeviceRGB); context.setStrokeThickness(borderWidthPx); context.setFillColor(tooltipBackgroundColor, ColorSpaceDeviceRGB); context.drawRect(titleRect); context.setFillColor(tooltipFontColor, ColorSpaceDeviceRGB); context.drawText(font, nodeTitleRun, IntPoint(titleRect.x() + rectInflatePx, titleRect.y() + font.fontMetrics().height())); } } // anonymous namespace namespace DOMNodeHighlighter { void DrawNodeHighlight(GraphicsContext& context, Node* node, HighlightMode mode) { node->document()->updateLayoutIgnorePendingStylesheets(); RenderObject* renderer = node->renderer(); Frame* containingFrame = node->document()->frame(); if (!renderer || !containingFrame) return; IntSize mainFrameOffset = frameToMainFrameOffset(containingFrame); IntRect boundingBox = renderer->absoluteBoundingBoxRect(true); boundingBox.move(mainFrameOffset); IntRect titleAnchorBox = boundingBox; FrameView* view = containingFrame->page()->mainFrame()->view(); FloatRect overlayRect = view->visibleContentRect(); if (!overlayRect.contains(boundingBox) && !boundingBox.contains(enclosingIntRect(overlayRect))) overlayRect = view->visibleContentRect(); context.translate(-overlayRect.x(), -overlayRect.y()); // RenderSVGRoot should be highlighted through the isBox() code path, all other SVG elements should just dump their absoluteQuads(). #if ENABLE(SVG) bool isSVGRenderer = renderer->node() && renderer->node()->isSVGElement() && !renderer->isSVGRoot(); #else bool isSVGRenderer = false; #endif if (renderer->isBox() && !isSVGRenderer) { RenderBox* renderBox = toRenderBox(renderer); // RenderBox returns the "pure" content area box, exclusive of the scrollbars (if present), which also count towards the content area in CSS. IntRect contentBox = renderBox->contentBoxRect(); contentBox.setWidth(contentBox.width() + renderBox->verticalScrollbarWidth()); contentBox.setHeight(contentBox.height() + renderBox->horizontalScrollbarHeight()); IntRect paddingBox(contentBox.x() - renderBox->paddingLeft(), contentBox.y() - renderBox->paddingTop(), contentBox.width() + renderBox->paddingLeft() + renderBox->paddingRight(), contentBox.height() + renderBox->paddingTop() + renderBox->paddingBottom()); IntRect borderBox(paddingBox.x() - renderBox->borderLeft(), paddingBox.y() - renderBox->borderTop(), paddingBox.width() + renderBox->borderLeft() + renderBox->borderRight(), paddingBox.height() + renderBox->borderTop() + renderBox->borderBottom()); IntRect marginBox(borderBox.x() - renderBox->marginLeft(), borderBox.y() - renderBox->marginTop(), borderBox.width() + renderBox->marginLeft() + renderBox->marginRight(), borderBox.height() + renderBox->marginTop() + renderBox->marginBottom()); FloatQuad absContentQuad = renderBox->localToAbsoluteQuad(FloatRect(contentBox)); FloatQuad absPaddingQuad = renderBox->localToAbsoluteQuad(FloatRect(paddingBox)); FloatQuad absBorderQuad = renderBox->localToAbsoluteQuad(FloatRect(borderBox)); FloatQuad absMarginQuad = renderBox->localToAbsoluteQuad(FloatRect(marginBox)); absContentQuad.move(mainFrameOffset); absPaddingQuad.move(mainFrameOffset); absBorderQuad.move(mainFrameOffset); absMarginQuad.move(mainFrameOffset); titleAnchorBox = absMarginQuad.enclosingBoundingBox(); drawHighlightForBox(context, absContentQuad, absPaddingQuad, absBorderQuad, absMarginQuad, mode); } else if (renderer->isRenderInline() || isSVGRenderer) { // FIXME: We should show margins/padding/border for inlines. Vector<FloatQuad> lineBoxQuads; renderer->absoluteQuads(lineBoxQuads); for (unsigned i = 0; i < lineBoxQuads.size(); ++i) lineBoxQuads[i] += mainFrameOffset; drawHighlightForLineBoxesOrSVGRenderer(context, lineBoxQuads); } // Draw node title if necessary. if (!node->isElementNode()) return; WebCore::Settings* settings = containingFrame->settings(); if (mode == DOMNodeHighlighter::HighlightAll) drawElementTitle(context, node, boundingBox, titleAnchorBox, overlayRect, settings); } } // namespace DOMNodeHighlighter } // namespace WebCore #endif // ENABLE(INSPECTOR)
rsadhu/phantomjs
src/qt/src/3rdparty/webkit/Source/WebCore/inspector/DOMNodeHighlighter.cpp
C++
bsd-3-clause
13,206
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v5.0.0-alpha.5 * @link http://www.ag-grid.com/ * @license MIT */ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var csvCreator_1 = require("./csvCreator"); var rowRenderer_1 = require("./rendering/rowRenderer"); var headerRenderer_1 = require("./headerRendering/headerRenderer"); var filterManager_1 = require("./filter/filterManager"); var columnController_1 = require("./columnController/columnController"); var selectionController_1 = require("./selectionController"); var gridOptionsWrapper_1 = require("./gridOptionsWrapper"); var gridPanel_1 = require("./gridPanel/gridPanel"); var valueService_1 = require("./valueService"); var masterSlaveService_1 = require("./masterSlaveService"); var eventService_1 = require("./eventService"); var floatingRowModel_1 = require("./rowControllers/floatingRowModel"); var constants_1 = require("./constants"); var context_1 = require("./context/context"); var gridCore_1 = require("./gridCore"); var sortController_1 = require("./sortController"); var paginationController_1 = require("./rowControllers/paginationController"); var focusedCellController_1 = require("./focusedCellController"); var utils_1 = require("./utils"); var cellRendererFactory_1 = require("./rendering/cellRendererFactory"); var cellEditorFactory_1 = require("./rendering/cellEditorFactory"); var GridApi = (function () { function GridApi() { } GridApi.prototype.init = function () { if (this.rowModel.getType() === constants_1.Constants.ROW_MODEL_TYPE_NORMAL) { this.inMemoryRowModel = this.rowModel; } }; /** Used internally by grid. Not intended to be used by the client. Interface may change between releases. */ GridApi.prototype.__getMasterSlaveService = function () { return this.masterSlaveService; }; GridApi.prototype.getFirstRenderedRow = function () { return this.rowRenderer.getFirstVirtualRenderedRow(); }; GridApi.prototype.getLastRenderedRow = function () { return this.rowRenderer.getLastVirtualRenderedRow(); }; GridApi.prototype.getDataAsCsv = function (params) { return this.csvCreator.getDataAsCsv(params); }; GridApi.prototype.exportDataAsCsv = function (params) { this.csvCreator.exportDataAsCsv(params); }; GridApi.prototype.setDatasource = function (datasource) { if (this.gridOptionsWrapper.isRowModelPagination()) { this.paginationController.setDatasource(datasource); } else if (this.gridOptionsWrapper.isRowModelVirtual()) { this.rowModel.setDatasource(datasource); } else { console.warn("ag-Grid: you can only use a datasource when gridOptions.rowModelType is '" + constants_1.Constants.ROW_MODEL_TYPE_VIRTUAL + "' or '" + constants_1.Constants.ROW_MODEL_TYPE_PAGINATION + "'"); } }; GridApi.prototype.setViewportDatasource = function (viewportDatasource) { if (this.gridOptionsWrapper.isRowModelViewport()) { // this is bad coding, because it's using an interface that's exposed in the enterprise. // really we should create an interface in the core for viewportDatasource and let // the enterprise implement it, rather than casting to 'any' here this.rowModel.setViewportDatasource(viewportDatasource); } else { console.warn("ag-Grid: you can only use a datasource when gridOptions.rowModelType is '" + constants_1.Constants.ROW_MODEL_TYPE_VIEWPORT + "'"); } }; GridApi.prototype.setRowData = function (rowData) { if (this.gridOptionsWrapper.isRowModelDefault()) { this.inMemoryRowModel.setRowData(rowData, true); } else { console.log('cannot call setRowData unless using normal row model'); } }; GridApi.prototype.setFloatingTopRowData = function (rows) { this.floatingRowModel.setFloatingTopRowData(rows); }; GridApi.prototype.setFloatingBottomRowData = function (rows) { this.floatingRowModel.setFloatingBottomRowData(rows); }; GridApi.prototype.setColumnDefs = function (colDefs) { this.columnController.setColumnDefs(colDefs); }; GridApi.prototype.refreshRows = function (rowNodes) { this.rowRenderer.refreshRows(rowNodes); }; GridApi.prototype.refreshCells = function (rowNodes, colIds, animate) { if (animate === void 0) { animate = false; } this.rowRenderer.refreshCells(rowNodes, colIds, animate); }; GridApi.prototype.rowDataChanged = function (rows) { this.rowRenderer.rowDataChanged(rows); }; GridApi.prototype.refreshView = function () { this.rowRenderer.refreshView(); }; GridApi.prototype.softRefreshView = function () { this.rowRenderer.softRefreshView(); }; GridApi.prototype.refreshGroupRows = function () { this.rowRenderer.refreshGroupRows(); }; GridApi.prototype.refreshHeader = function () { // need to review this - the refreshHeader should also refresh all icons in the header this.headerRenderer.refreshHeader(); }; GridApi.prototype.isAnyFilterPresent = function () { return this.filterManager.isAnyFilterPresent(); }; GridApi.prototype.isAdvancedFilterPresent = function () { return this.filterManager.isAdvancedFilterPresent(); }; GridApi.prototype.isQuickFilterPresent = function () { return this.filterManager.isQuickFilterPresent(); }; GridApi.prototype.getModel = function () { return this.rowModel; }; GridApi.prototype.onGroupExpandedOrCollapsed = function (refreshFromIndex) { if (utils_1.Utils.missing(this.inMemoryRowModel)) { console.log('cannot call onGroupExpandedOrCollapsed unless using normal row model'); } this.inMemoryRowModel.refreshModel(constants_1.Constants.STEP_MAP, refreshFromIndex); }; GridApi.prototype.refreshInMemoryRowModel = function () { if (utils_1.Utils.missing(this.inMemoryRowModel)) { console.log('cannot call refreshInMemoryRowModel unless using normal row model'); } this.inMemoryRowModel.refreshModel(constants_1.Constants.STEP_EVERYTHING); }; GridApi.prototype.expandAll = function () { if (utils_1.Utils.missing(this.inMemoryRowModel)) { console.log('cannot call expandAll unless using normal row model'); } this.inMemoryRowModel.expandOrCollapseAll(true); }; GridApi.prototype.collapseAll = function () { if (utils_1.Utils.missing(this.inMemoryRowModel)) { console.log('cannot call collapseAll unless using normal row model'); } this.inMemoryRowModel.expandOrCollapseAll(false); }; GridApi.prototype.addVirtualRowListener = function (eventName, rowIndex, callback) { if (typeof eventName !== 'string') { console.log('ag-Grid: addVirtualRowListener is deprecated, please use addRenderedRowListener.'); } this.addRenderedRowListener(eventName, rowIndex, callback); }; GridApi.prototype.addRenderedRowListener = function (eventName, rowIndex, callback) { if (eventName === 'virtualRowRemoved') { console.log('ag-Grid: event virtualRowRemoved is deprecated, now called renderedRowRemoved'); eventName = '' + ''; } if (eventName === 'virtualRowSelected') { console.log('ag-Grid: event virtualRowSelected is deprecated, to register for individual row ' + 'selection events, add a listener directly to the row node.'); } this.rowRenderer.addRenderedRowListener(eventName, rowIndex, callback); }; GridApi.prototype.setQuickFilter = function (newFilter) { this.filterManager.setQuickFilter(newFilter); }; GridApi.prototype.selectIndex = function (index, tryMulti, suppressEvents) { console.log('ag-Grid: do not use api for selection, call node.setSelected(value) instead'); if (suppressEvents) { console.log('ag-Grid: suppressEvents is no longer supported, stop listening for the event if you no longer want it'); } this.selectionController.selectIndex(index, tryMulti); }; GridApi.prototype.deselectIndex = function (index, suppressEvents) { if (suppressEvents === void 0) { suppressEvents = false; } console.log('ag-Grid: do not use api for selection, call node.setSelected(value) instead'); if (suppressEvents) { console.log('ag-Grid: suppressEvents is no longer supported, stop listening for the event if you no longer want it'); } this.selectionController.deselectIndex(index); }; GridApi.prototype.selectNode = function (node, tryMulti, suppressEvents) { if (tryMulti === void 0) { tryMulti = false; } if (suppressEvents === void 0) { suppressEvents = false; } console.log('ag-Grid: API for selection is deprecated, call node.setSelected(value) instead'); if (suppressEvents) { console.log('ag-Grid: suppressEvents is no longer supported, stop listening for the event if you no longer want it'); } node.setSelectedParams({ newValue: true, clearSelection: !tryMulti }); }; GridApi.prototype.deselectNode = function (node, suppressEvents) { if (suppressEvents === void 0) { suppressEvents = false; } console.log('ag-Grid: API for selection is deprecated, call node.setSelected(value) instead'); if (suppressEvents) { console.log('ag-Grid: suppressEvents is no longer supported, stop listening for the event if you no longer want it'); } node.setSelectedParams({ newValue: false }); }; GridApi.prototype.selectAll = function () { this.selectionController.selectAllRowNodes(); }; GridApi.prototype.deselectAll = function () { this.selectionController.deselectAllRowNodes(); }; GridApi.prototype.recomputeAggregates = function () { if (utils_1.Utils.missing(this.inMemoryRowModel)) { console.log('cannot call recomputeAggregates unless using normal row model'); } this.inMemoryRowModel.refreshModel(constants_1.Constants.STEP_AGGREGATE); }; GridApi.prototype.sizeColumnsToFit = function () { if (this.gridOptionsWrapper.isForPrint()) { console.warn('ag-grid: sizeColumnsToFit does not work when forPrint=true'); return; } this.gridPanel.sizeColumnsToFit(); }; GridApi.prototype.showLoadingOverlay = function () { this.gridPanel.showLoadingOverlay(); }; GridApi.prototype.showNoRowsOverlay = function () { this.gridPanel.showNoRowsOverlay(); }; GridApi.prototype.hideOverlay = function () { this.gridPanel.hideOverlay(); }; GridApi.prototype.isNodeSelected = function (node) { console.log('ag-Grid: no need to call api.isNodeSelected(), just call node.isSelected() instead'); return node.isSelected(); }; GridApi.prototype.getSelectedNodesById = function () { console.error('ag-Grid: since version 3.4, getSelectedNodesById no longer exists, use getSelectedNodes() instead'); return null; }; GridApi.prototype.getSelectedNodes = function () { return this.selectionController.getSelectedNodes(); }; GridApi.prototype.getSelectedRows = function () { return this.selectionController.getSelectedRows(); }; GridApi.prototype.getBestCostNodeSelection = function () { return this.selectionController.getBestCostNodeSelection(); }; GridApi.prototype.getRenderedNodes = function () { return this.rowRenderer.getRenderedNodes(); }; GridApi.prototype.ensureColIndexVisible = function (index) { console.warn('ag-Grid: ensureColIndexVisible(index) no longer supported, use ensureColumnVisible(colKey) instead.'); }; GridApi.prototype.ensureColumnVisible = function (key) { this.gridPanel.ensureColumnVisible(key); }; GridApi.prototype.ensureIndexVisible = function (index) { this.gridPanel.ensureIndexVisible(index); }; GridApi.prototype.ensureNodeVisible = function (comparator) { this.gridCore.ensureNodeVisible(comparator); }; GridApi.prototype.forEachLeafNode = function (callback) { if (utils_1.Utils.missing(this.inMemoryRowModel)) { console.log('cannot call forEachNodeAfterFilter unless using normal row model'); } this.inMemoryRowModel.forEachLeafNode(callback); }; GridApi.prototype.forEachNode = function (callback) { this.rowModel.forEachNode(callback); }; GridApi.prototype.forEachNodeAfterFilter = function (callback) { if (utils_1.Utils.missing(this.inMemoryRowModel)) { console.log('cannot call forEachNodeAfterFilter unless using normal row model'); } this.inMemoryRowModel.forEachNodeAfterFilter(callback); }; GridApi.prototype.forEachNodeAfterFilterAndSort = function (callback) { if (utils_1.Utils.missing(this.inMemoryRowModel)) { console.log('cannot call forEachNodeAfterFilterAndSort unless using normal row model'); } this.inMemoryRowModel.forEachNodeAfterFilterAndSort(callback); }; GridApi.prototype.getFilterApiForColDef = function (colDef) { console.warn('ag-grid API method getFilterApiForColDef deprecated, use getFilterApi instead'); return this.getFilterApi(colDef); }; GridApi.prototype.getFilterApi = function (key) { var column = this.columnController.getPrimaryColumn(key); if (column) { return this.filterManager.getFilterApi(column); } }; GridApi.prototype.destroyFilter = function (key) { var column = this.columnController.getPrimaryColumn(key); if (column) { return this.filterManager.destroyFilter(column); } }; GridApi.prototype.getColumnDef = function (key) { var column = this.columnController.getPrimaryColumn(key); if (column) { return column.getColDef(); } else { return null; } }; GridApi.prototype.onFilterChanged = function () { this.filterManager.onFilterChanged(); }; GridApi.prototype.setSortModel = function (sortModel) { this.sortController.setSortModel(sortModel); }; GridApi.prototype.getSortModel = function () { return this.sortController.getSortModel(); }; GridApi.prototype.setFilterModel = function (model) { this.filterManager.setFilterModel(model); }; GridApi.prototype.getFilterModel = function () { return this.filterManager.getFilterModel(); }; GridApi.prototype.getFocusedCell = function () { return this.focusedCellController.getFocusedCell(); }; GridApi.prototype.setFocusedCell = function (rowIndex, colKey, floating) { this.focusedCellController.setFocusedCell(rowIndex, colKey, floating, true); }; GridApi.prototype.setHeaderHeight = function (headerHeight) { this.gridOptionsWrapper.setHeaderHeight(headerHeight); }; GridApi.prototype.showToolPanel = function (show) { this.gridCore.showToolPanel(show); }; GridApi.prototype.isToolPanelShowing = function () { return this.gridCore.isToolPanelShowing(); }; GridApi.prototype.doLayout = function () { this.gridCore.doLayout(); }; GridApi.prototype.getValue = function (colKey, rowNode) { var column = this.columnController.getPrimaryColumn(colKey); return this.valueService.getValue(column, rowNode); }; GridApi.prototype.addEventListener = function (eventType, listener) { this.eventService.addEventListener(eventType, listener); }; GridApi.prototype.addGlobalListener = function (listener) { this.eventService.addGlobalListener(listener); }; GridApi.prototype.removeEventListener = function (eventType, listener) { this.eventService.removeEventListener(eventType, listener); }; GridApi.prototype.removeGlobalListener = function (listener) { this.eventService.removeGlobalListener(listener); }; GridApi.prototype.dispatchEvent = function (eventType, event) { this.eventService.dispatchEvent(eventType, event); }; GridApi.prototype.destroy = function () { this.context.destroy(); }; GridApi.prototype.resetQuickFilter = function () { this.rowModel.forEachNode(function (node) { return node.quickFilterAggregateText = null; }); }; GridApi.prototype.getRangeSelections = function () { if (this.rangeController) { return this.rangeController.getCellRanges(); } else { console.warn('ag-Grid: cell range selection is only available in ag-Grid Enterprise'); return null; } }; GridApi.prototype.addRangeSelection = function (rangeSelection) { if (!this.rangeController) { console.warn('ag-Grid: cell range selection is only available in ag-Grid Enterprise'); } this.rangeController.addRange(rangeSelection); }; GridApi.prototype.clearRangeSelection = function () { if (!this.rangeController) { console.warn('ag-Grid: cell range selection is only available in ag-Grid Enterprise'); } this.rangeController.clearSelection(); }; GridApi.prototype.copySelectedRowsToClipboard = function () { if (!this.clipboardService) { console.warn('ag-Grid: clipboard is only available in ag-Grid Enterprise'); } this.clipboardService.copySelectedRowsToClipboard(); }; GridApi.prototype.copySelectedRangeToClipboard = function () { if (!this.clipboardService) { console.warn('ag-Grid: clipboard is only available in ag-Grid Enterprise'); } this.clipboardService.copySelectedRangeToClipboard(); }; GridApi.prototype.copySelectedRangeDown = function () { if (!this.clipboardService) { console.warn('ag-Grid: clipboard is only available in ag-Grid Enterprise'); } this.clipboardService.copyRangeDown(); }; GridApi.prototype.showColumnMenuAfterButtonClick = function (colKey, buttonElement) { var column = this.columnController.getPrimaryColumn(colKey); this.menuFactory.showMenuAfterButtonClick(column, buttonElement); }; GridApi.prototype.showColumnMenuAfterMouseClick = function (colKey, mouseEvent) { var column = this.columnController.getPrimaryColumn(colKey); this.menuFactory.showMenuAfterMouseEvent(column, mouseEvent); }; GridApi.prototype.stopEditing = function (cancel) { if (cancel === void 0) { cancel = false; } this.rowRenderer.stopEditing(cancel); }; GridApi.prototype.addAggFunc = function (key, aggFunc) { if (this.aggFuncService) { this.aggFuncService.addAggFunc(key, aggFunc); } }; GridApi.prototype.addAggFuncs = function (aggFuncs) { if (this.aggFuncService) { this.aggFuncService.addAggFuncs(aggFuncs); } }; GridApi.prototype.clearAggFuncs = function () { if (this.aggFuncService) { this.aggFuncService.clear(); } }; __decorate([ context_1.Autowired('csvCreator'), __metadata('design:type', csvCreator_1.CsvCreator) ], GridApi.prototype, "csvCreator", void 0); __decorate([ context_1.Autowired('gridCore'), __metadata('design:type', gridCore_1.GridCore) ], GridApi.prototype, "gridCore", void 0); __decorate([ context_1.Autowired('rowRenderer'), __metadata('design:type', rowRenderer_1.RowRenderer) ], GridApi.prototype, "rowRenderer", void 0); __decorate([ context_1.Autowired('headerRenderer'), __metadata('design:type', headerRenderer_1.HeaderRenderer) ], GridApi.prototype, "headerRenderer", void 0); __decorate([ context_1.Autowired('filterManager'), __metadata('design:type', filterManager_1.FilterManager) ], GridApi.prototype, "filterManager", void 0); __decorate([ context_1.Autowired('columnController'), __metadata('design:type', columnController_1.ColumnController) ], GridApi.prototype, "columnController", void 0); __decorate([ context_1.Autowired('selectionController'), __metadata('design:type', selectionController_1.SelectionController) ], GridApi.prototype, "selectionController", void 0); __decorate([ context_1.Autowired('gridOptionsWrapper'), __metadata('design:type', gridOptionsWrapper_1.GridOptionsWrapper) ], GridApi.prototype, "gridOptionsWrapper", void 0); __decorate([ context_1.Autowired('gridPanel'), __metadata('design:type', gridPanel_1.GridPanel) ], GridApi.prototype, "gridPanel", void 0); __decorate([ context_1.Autowired('valueService'), __metadata('design:type', valueService_1.ValueService) ], GridApi.prototype, "valueService", void 0); __decorate([ context_1.Autowired('masterSlaveService'), __metadata('design:type', masterSlaveService_1.MasterSlaveService) ], GridApi.prototype, "masterSlaveService", void 0); __decorate([ context_1.Autowired('eventService'), __metadata('design:type', eventService_1.EventService) ], GridApi.prototype, "eventService", void 0); __decorate([ context_1.Autowired('floatingRowModel'), __metadata('design:type', floatingRowModel_1.FloatingRowModel) ], GridApi.prototype, "floatingRowModel", void 0); __decorate([ context_1.Autowired('context'), __metadata('design:type', context_1.Context) ], GridApi.prototype, "context", void 0); __decorate([ context_1.Autowired('rowModel'), __metadata('design:type', Object) ], GridApi.prototype, "rowModel", void 0); __decorate([ context_1.Autowired('sortController'), __metadata('design:type', sortController_1.SortController) ], GridApi.prototype, "sortController", void 0); __decorate([ context_1.Autowired('paginationController'), __metadata('design:type', paginationController_1.PaginationController) ], GridApi.prototype, "paginationController", void 0); __decorate([ context_1.Autowired('focusedCellController'), __metadata('design:type', focusedCellController_1.FocusedCellController) ], GridApi.prototype, "focusedCellController", void 0); __decorate([ context_1.Optional('rangeController'), __metadata('design:type', Object) ], GridApi.prototype, "rangeController", void 0); __decorate([ context_1.Optional('clipboardService'), __metadata('design:type', Object) ], GridApi.prototype, "clipboardService", void 0); __decorate([ context_1.Optional('aggFuncService'), __metadata('design:type', Object) ], GridApi.prototype, "aggFuncService", void 0); __decorate([ context_1.Autowired('menuFactory'), __metadata('design:type', Object) ], GridApi.prototype, "menuFactory", void 0); __decorate([ context_1.Autowired('cellRendererFactory'), __metadata('design:type', cellRendererFactory_1.CellRendererFactory) ], GridApi.prototype, "cellRendererFactory", void 0); __decorate([ context_1.Autowired('cellEditorFactory'), __metadata('design:type', cellEditorFactory_1.CellEditorFactory) ], GridApi.prototype, "cellEditorFactory", void 0); __decorate([ context_1.PostConstruct, __metadata('design:type', Function), __metadata('design:paramtypes', []), __metadata('design:returntype', void 0) ], GridApi.prototype, "init", null); GridApi = __decorate([ context_1.Bean('gridApi'), __metadata('design:paramtypes', []) ], GridApi); return GridApi; })(); exports.GridApi = GridApi;
dlueth/cdnjs
ajax/libs/ag-grid/5.0.0-alpha.5/lib/gridApi.js
JavaScript
mit
25,090
/// <reference path="ng-grid.d.ts" /> var options1: ngGrid.IGridOptions = { data: [{ 'Name': 'Bob' }, { 'Name': 'Jane' }] }; var options2: ngGrid.IGridOptions = { afterSelectionChange: () => { }, beforeSelectionChange: () => {return true; }, dataUpdated: () => { } }; var options3: ngGrid.IGridOptions = { columnDefs: [ { field: 'name', displayName: 'Name' }, { field: 'age', displayName: 'Age' } ] }; var options4: ngGrid.IGridOptions = { pagingOptions: { pageSizes: [1, 2, 3, 4], pageSize: 2, totalServerItems: 100, currentPage: 1 } };
balassy/DefinitelyTyped
ng-grid/ng-grid-tests.ts
TypeScript
mit
625
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _pure = require('recompose/pure'); var _pure2 = _interopRequireDefault(_pure); var _SvgIcon = require('../../SvgIcon'); var _SvgIcon2 = _interopRequireDefault(_SvgIcon); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var ContentContentPaste = function ContentContentPaste(props) { return _react2.default.createElement( _SvgIcon2.default, props, _react2.default.createElement('path', { d: 'M19 2h-4.18C14.4.84 13.3 0 12 0c-1.3 0-2.4.84-2.82 2H5c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-7 0c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm7 18H5V4h2v3h10V4h2v16z' }) ); }; ContentContentPaste = (0, _pure2.default)(ContentContentPaste); ContentContentPaste.displayName = 'ContentContentPaste'; ContentContentPaste.muiName = 'SvgIcon'; exports.default = ContentContentPaste;
Jorginho211/TFG
web/node_modules/material-ui/svg-icons/content/content-paste.js
JavaScript
gpl-3.0
1,035
cask "pdfelement-express" do version "1.2.1,1441" sha256 :no_check url "https://download.wondershare.com/cbs_down/mac-pdfelement-express_full4133.dmg" appcast "https://cbs.wondershare.com/go.php?m=upgrade_info&pid=4133" name "PDFelement Express" homepage "https://pdf.wondershare.com/pdfelement-express-mac.html" depends_on macos: ">= :sierra" app "PDFelement Express.app" end
malob/homebrew-cask
Casks/pdfelement-express.rb
Ruby
bsd-2-clause
396
/* -*- Mode: Javascript; indent-tabs-mode:nil; js-indent-level: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /************************************************************* * * MathJax/localization/vi/MathML.js * * Copyright (c) 2009-2015 The MathJax Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ MathJax.Localization.addTranslation("vi","MathML",{ version: "2.5.0", isLoaded: true, strings: { BadMglyph: "mglyph h\u1ECFng: %1", BadMglyphFont: "Ph\u00F4ng ch\u1EEF h\u1ECFng: %1", MathPlayer: "MathJax kh\u00F4ng th\u1EC3 thi\u1EBFt l\u1EADp MathPlayer.\n\nN\u1EBFu MathPlayer ch\u01B0a \u0111\u01B0\u1EE3c c\u00E0i \u0111\u1EB7t, b\u1EA1n c\u1EA7n ph\u1EA3i c\u00E0i \u0111\u1EB7t n\u00F3 tr\u01B0\u1EDBc ti\u00EAn.\nN\u1EBFu kh\u00F4ng, c\u00E1c t\u00F9y ch\u1ECDn b\u1EA3o m\u1EADt c\u1EE7a b\u1EA1n c\u00F3 th\u1EC3 ng\u0103n tr\u1EDF c\u00E1c \u0111i\u1EC1u khi\u1EC3n ActiveX. H\u00E3y ch\u1ECDn T\u00F9y ch\u1ECDn Internet trong tr\u00ECnh \u0111\u01A1n C\u00F4ng c\u1EE5, qua th\u1EBB B\u1EA3o m\u1EADt, v\u00E0 b\u1EA5m n\u00FAt M\u1EE9c t\u00F9y ch\u1EC9nh. Ki\u1EC3m c\u00E1c h\u1ED9p \u201CCh\u1EA1y \u0111i\u1EC1u khi\u1EC3n ActiveX\u201D v\u00E0 \u201CH\u00E0nh vi nh\u1ECB ph\u00E2n v\u00E0 k\u1ECBch b\u1EA3n\u201D.\n\nHi\u1EC7n t\u1EA1i b\u1EA1n s\u1EBD g\u1EB7p c\u00E1c th\u00F4ng b\u00E1o l\u1ED7i thay v\u00EC to\u00E1n h\u1ECDc \u0111\u01B0\u1EE3c k\u1EBFt xu\u1EA5t.", CantCreateXMLParser: "MathJax kh\u00F4ng th\u1EC3 t\u1EA1o ra b\u1ED9 ph\u00E2n t\u00EDch XML cho MathML. H\u00E3y ch\u1ECDn T\u00F9y ch\u1ECDn Internet trong tr\u00ECnh \u0111\u01A1n C\u00F4ng c\u1EE5, qua th\u1EBB B\u1EA3o m\u1EADt, v\u00E0 b\u1EA5m n\u00FAt M\u1EE9c t\u00F9y ch\u1EC9nh. Ki\u1EC3m h\u1ED9p \u201CScript c\u00E1c \u0111i\u1EC1u khi\u1EC3n ActiveX \u0111\u01B0\u1EE3c \u0111\u00E1nh d\u1EA5u l\u00E0 an to\u00E0n\u201D.\n\nMathJax s\u1EBD kh\u00F4ng th\u1EC3 x\u1EED l\u00FD c\u00E1c ph\u01B0\u01A1ng tr\u00ECnh MathML.", UnknownNodeType: "Ki\u1EC3u n\u00FAt kh\u00F4ng r\u00F5: %1", UnexpectedTextNode: "N\u00FAt v\u0103n b\u1EA3n b\u1EA5t ng\u1EEB: %1", ErrorParsingMathML: "L\u1ED7i khi ph\u00E2n t\u00EDch MathML", ParsingError: "L\u1ED7i khi ph\u00E2n t\u00EDch MathML: %1", MathMLSingleElement: "MathML ph\u1EA3i ch\u1EC9 c\u00F3 m\u1ED9t ph\u1EA7n t\u1EED g\u1ED1c", MathMLRootElement: "Ph\u1EA7n t\u1EED g\u1ED1c c\u1EE7a MathML ph\u1EA3i l\u00E0 \u003Cmath\u003E, ch\u1EE9 kh\u00F4ng ph\u1EA3i %1" } }); MathJax.Ajax.loadComplete("[MathJax]/localization/vi/MathML.js");
dongli/mathjax-rails
vendor/mathjax/unpacked/localization/vi/MathML.js
JavaScript
mit
3,166
<?php function mce_put_file( $path, $content ) { if ( function_exists('file_put_contents') ) return @file_put_contents( $path, $content ); $newfile = false; $fp = @fopen( $path, 'wb' ); if ($fp) { $newfile = fwrite( $fp, $content ); fclose($fp); } return $newfile; } // escape text only if it needs translating function mce_escape($text) { global $language; if ( 'en' == $language ) return $text; else return esc_js($text); } $lang = 'tinyMCE.addI18n({' . $language . ':{ common:{ edit_confirm:"' . mce_escape( __('Do you want to use the WYSIWYG mode for this textarea?') ) . '", apply:"' . mce_escape( __('Apply') ) . '", insert:"' . mce_escape( __('Insert') ) . '", update:"' . mce_escape( __('Update') ) . '", cancel:"' . mce_escape( __('Cancel') ) . '", close:"' . mce_escape( __('Close') ) . '", browse:"' . mce_escape( __('Browse') ) . '", class_name:"' . mce_escape( __('Class') ) . '", not_set:"' . mce_escape( __('-- Not set --') ) . '", clipboard_msg:"' . mce_escape( __('Copy/Cut/Paste is not available in Mozilla and Firefox.') ) . '", clipboard_no_support:"' . mce_escape( __('Currently not supported by your browser, use keyboard shortcuts instead.') ) . '", popup_blocked:"' . mce_escape( __('Sorry, but we have noticed that your popup-blocker has disabled a window that provides application functionality. You will need to disable popup blocking on this site in order to fully utilize this tool.') ) . '", invalid_data:"' . mce_escape( __('Error: Invalid values entered, these are marked in red.') ) . '", more_colors:"' . mce_escape( __('More colors') ) . '" }, contextmenu:{ align:"' . mce_escape( __('Alignment') ) . '", left:"' . mce_escape( __('Left') ) . '", center:"' . mce_escape( __('Center') ) . '", right:"' . mce_escape( __('Right') ) . '", full:"' . mce_escape( __('Full') ) . '" }, insertdatetime:{ date_fmt:"' . mce_escape( __('%Y-%m-%d') ) . '", time_fmt:"' . mce_escape( __('%H:%M:%S') ) . '", insertdate_desc:"' . mce_escape( __('Insert date') ) . '", inserttime_desc:"' . mce_escape( __('Insert time') ) . '", months_long:"' . mce_escape( __('January').','.__('February').','.__('March').','.__('April').','.__('May').','.__('June').','.__('July').','.__('August').','.__('September').','.__('October').','.__('November').','.__('December') ) . '", months_short:"' . mce_escape( __('Jan_January_abbreviation').','.__('Feb_February_abbreviation').','.__('Mar_March_abbreviation').','.__('Apr_April_abbreviation').','.__('May_May_abbreviation').','.__('Jun_June_abbreviation').','.__('Jul_July_abbreviation').','.__('Aug_August_abbreviation').','.__('Sep_September_abbreviation').','.__('Oct_October_abbreviation').','.__('Nov_November_abbreviation').','.__('Dec_December_abbreviation') ) . '", day_long:"' . mce_escape( __('Sunday').','.__('Monday').','.__('Tuesday').','.__('Wednesday').','.__('Thursday').','.__('Friday').','.__('Saturday') ) . '", day_short:"' . mce_escape( __('Sun').','.__('Mon').','.__('Tue').','.__('Wed').','.__('Thu').','.__('Fri').','.__('Sat') ) . '" }, print:{ print_desc:"' . mce_escape( __('Print') ) . '" }, preview:{ preview_desc:"' . mce_escape( __('Preview') ) . '" }, directionality:{ ltr_desc:"' . mce_escape( __('Direction left to right') ) . '", rtl_desc:"' . mce_escape( __('Direction right to left') ) . '" }, layer:{ insertlayer_desc:"' . mce_escape( __('Insert new layer') ) . '", forward_desc:"' . mce_escape( __('Move forward') ) . '", backward_desc:"' . mce_escape( __('Move backward') ) . '", absolute_desc:"' . mce_escape( __('Toggle absolute positioning') ) . '", content:"' . mce_escape( __('New layer...') ) . '" }, save:{ save_desc:"' . mce_escape( __('Save') ) . '", cancel_desc:"' . mce_escape( __('Cancel all changes') ) . '" }, nonbreaking:{ nonbreaking_desc:"' . mce_escape( __('Insert non-breaking space character') ) . '" }, iespell:{ iespell_desc:"' . mce_escape( __('Run spell checking') ) . '", download:"' . mce_escape( __('ieSpell not detected. Do you want to install it now?') ) . '" }, advhr:{ advhr_desc:"' . mce_escape( __('Horizontale rule') ) . '" }, emotions:{ emotions_desc:"' . mce_escape( __('Emotions') ) . '" }, searchreplace:{ search_desc:"' . mce_escape( __('Find') ) . '", replace_desc:"' . mce_escape( __('Find/Replace') ) . '" }, advimage:{ image_desc:"' . mce_escape( __('Insert/edit image') ) . '" }, advlink:{ link_desc:"' . mce_escape( __('Insert/edit link') ) . '" }, xhtmlxtras:{ cite_desc:"' . mce_escape( __('Citation') ) . '", abbr_desc:"' . mce_escape( __('Abbreviation') ) . '", acronym_desc:"' . mce_escape( __('Acronym') ) . '", del_desc:"' . mce_escape( __('Deletion') ) . '", ins_desc:"' . mce_escape( __('Insertion') ) . '", attribs_desc:"' . mce_escape( __('Insert/Edit Attributes') ) . '" }, style:{ desc:"' . mce_escape( __('Edit CSS Style') ) . '" }, paste:{ paste_text_desc:"' . mce_escape( __('Paste as Plain Text') ) . '", paste_word_desc:"' . mce_escape( __('Paste from Word') ) . '", selectall_desc:"' . mce_escape( __('Select All') ) . '" }, paste_dlg:{ text_title:"' . mce_escape( __('Use CTRL+V on your keyboard to paste the text into the window.') ) . '", text_linebreaks:"' . mce_escape( __('Keep linebreaks') ) . '", word_title:"' . mce_escape( __('Use CTRL+V on your keyboard to paste the text into the window.') ) . '" }, table:{ desc:"' . mce_escape( __('Inserts a new table') ) . '", row_before_desc:"' . mce_escape( __('Insert row before') ) . '", row_after_desc:"' . mce_escape( __('Insert row after') ) . '", delete_row_desc:"' . mce_escape( __('Delete row') ) . '", col_before_desc:"' . mce_escape( __('Insert column before') ) . '", col_after_desc:"' . mce_escape( __('Insert column after') ) . '", delete_col_desc:"' . mce_escape( __('Remove column') ) . '", split_cells_desc:"' . mce_escape( __('Split merged table cells') ) . '", merge_cells_desc:"' . mce_escape( __('Merge table cells') ) . '", row_desc:"' . mce_escape( __('Table row properties') ) . '", cell_desc:"' . mce_escape( __('Table cell properties') ) . '", props_desc:"' . mce_escape( __('Table properties') ) . '", paste_row_before_desc:"' . mce_escape( __('Paste table row before') ) . '", paste_row_after_desc:"' . mce_escape( __('Paste table row after') ) . '", cut_row_desc:"' . mce_escape( __('Cut table row') ) . '", copy_row_desc:"' . mce_escape( __('Copy table row') ) . '", del:"' . mce_escape( __('Delete table') ) . '", row:"' . mce_escape( __('Row') ) . '", col:"' . mce_escape( __('Column') ) . '", cell:"' . mce_escape( __('Cell') ) . '" }, autosave:{ unload_msg:"' . mce_escape( __('The changes you made will be lost if you navigate away from this page.') ) . '" }, fullscreen:{ desc:"' . mce_escape( __('Toggle fullscreen mode') ) . ' (Alt+Shift+G)" }, media:{ desc:"' . mce_escape( __('Insert / edit embedded media') ) . '", delta_width:"' . /* translators: Extra width for the media popup in pixels */ mce_escape( _x('0', 'media popup width') ) . '", delta_height:"' . /* translators: Extra height for the media popup in pixels */ mce_escape( _x('0', 'media popup height') ) . '", edit:"' . mce_escape( __('Edit embedded media') ) . '" }, fullpage:{ desc:"' . mce_escape( __('Document properties') ) . '" }, template:{ desc:"' . mce_escape( __('Insert predefined template content') ) . '" }, visualchars:{ desc:"' . mce_escape( __('Visual control characters on/off.') ) . '" }, spellchecker:{ desc:"' . mce_escape( __('Toggle spellchecker') ) . ' (Alt+Shift+N)", menu:"' . mce_escape( __('Spellchecker settings') ) . '", ignore_word:"' . mce_escape( __('Ignore word') ) . '", ignore_words:"' . mce_escape( __('Ignore all') ) . '", langs:"' . mce_escape( __('Languages') ) . '", wait:"' . mce_escape( __('Please wait...') ) . '", sug:"' . mce_escape( __('Suggestions') ) . '", no_sug:"' . mce_escape( __('No suggestions') ) . '", no_mpell:"' . mce_escape( __('No misspellings found.') ) . '" }, pagebreak:{ desc:"' . mce_escape( __('Insert page break.') ) . '" }}}); tinyMCE.addI18n("' . $language . '.advanced",{ style_select:"' . mce_escape( /* translators: TinyMCE font styles */ _x('Styles', 'TinyMCE font styles') ) . '", font_size:"' . mce_escape( __('Font size') ) . '", fontdefault:"' . mce_escape( __('Font family') ) . '", block:"' . mce_escape( __('Format') ) . '", paragraph:"' . mce_escape( __('Paragraph') ) . '", div:"' . mce_escape( __('Div') ) . '", address:"' . mce_escape( __('Address') ) . '", pre:"' . mce_escape( __('Preformatted') ) . '", h1:"' . mce_escape( __('Heading 1') ) . '", h2:"' . mce_escape( __('Heading 2') ) . '", h3:"' . mce_escape( __('Heading 3') ) . '", h4:"' . mce_escape( __('Heading 4') ) . '", h5:"' . mce_escape( __('Heading 5') ) . '", h6:"' . mce_escape( __('Heading 6') ) . '", blockquote:"' . mce_escape( __('Blockquote') ) . '", code:"' . mce_escape( __('Code') ) . '", samp:"' . mce_escape( __('Code sample') ) . '", dt:"' . mce_escape( __('Definition term ') ) . '", dd:"' . mce_escape( __('Definition description') ) . '", bold_desc:"' . mce_escape( __('Bold') ) . ' (Ctrl / Alt+Shift + B)", italic_desc:"' . mce_escape( __('Italic') ) . ' (Ctrl / Alt+Shift + I)", underline_desc:"' . mce_escape( __('Underline') ) . '", striketrough_desc:"' . mce_escape( __('Strikethrough') ) . ' (Alt+Shift+D)", justifyleft_desc:"' . mce_escape( __('Align left') ) . ' (Alt+Shift+L)", justifycenter_desc:"' . mce_escape( __('Align center') ) . ' (Alt+Shift+C)", justifyright_desc:"' . mce_escape( __('Align right') ) . ' (Alt+Shift+R)", justifyfull_desc:"' . mce_escape( __('Align full') ) . ' (Alt+Shift+J)", bullist_desc:"' . mce_escape( __('Unordered list') ) . ' (Alt+Shift+U)", numlist_desc:"' . mce_escape( __('Ordered list') ) . ' (Alt+Shift+O)", outdent_desc:"' . mce_escape( __('Outdent') ) . '", indent_desc:"' . mce_escape( __('Indent') ) . '", undo_desc:"' . mce_escape( __('Undo') ) . ' (Ctrl+Z)", redo_desc:"' . mce_escape( __('Redo') ) . ' (Ctrl+Y)", link_desc:"' . mce_escape( __('Insert/edit link') ) . ' (Alt+Shift+A)", link_delta_width:"' . /* translators: Extra width for the link popup in pixels */ mce_escape( _x('0', 'link popup width') ) . '", link_delta_height:"' . /* translators: Extra height for the link popup in pixels */ mce_escape( _x('0', 'link popup height') ) . '", unlink_desc:"' . mce_escape( __('Unlink') ) . ' (Alt+Shift+S)", image_desc:"' . mce_escape( __('Insert/edit image') ) . ' (Alt+Shift+M)", image_delta_width:"' . /* translators: Extra width for the image popup in pixels */ mce_escape( _x('0', 'image popup width') ) . '", image_delta_height:"' . /* translators: Extra height for the image popup in pixels */ mce_escape( _x('0', 'image popup height') ) . '", cleanup_desc:"' . mce_escape( __('Cleanup messy code') ) . '", code_desc:"' . mce_escape( __('Edit HTML Source') ) . '", sub_desc:"' . mce_escape( __('Subscript') ) . '", sup_desc:"' . mce_escape( __('Superscript') ) . '", hr_desc:"' . mce_escape( __('Insert horizontal ruler') ) . '", removeformat_desc:"' . mce_escape( __('Remove formatting') ) . '", forecolor_desc:"' . mce_escape( __('Select text color') ) . '", backcolor_desc:"' . mce_escape( __('Select background color') ) . '", charmap_desc:"' . mce_escape( __('Insert custom character') ) . '", visualaid_desc:"' . mce_escape( __('Toggle guidelines/invisible elements') ) . '", anchor_desc:"' . mce_escape( __('Insert/edit anchor') ) . '", cut_desc:"' . mce_escape( __('Cut') ) . '", copy_desc:"' . mce_escape( __('Copy') ) . '", paste_desc:"' . mce_escape( __('Paste') ) . '", image_props_desc:"' . mce_escape( __('Image properties') ) . '", newdocument_desc:"' . mce_escape( __('New document') ) . '", help_desc:"' . mce_escape( __('Help') ) . '", blockquote_desc:"' . mce_escape( __('Blockquote') ) . ' (Alt+Shift+Q)", clipboard_msg:"' . mce_escape( __('Copy/Cut/Paste is not available in Mozilla and Firefox.') ) . '", path:"' . mce_escape( __('Path') ) . '", newdocument:"' . mce_escape( __('Are you sure you want to clear all contents?') ) . '", toolbar_focus:"' . mce_escape( __('Jump to tool buttons - Alt+Q, Jump to editor - Alt-Z, Jump to element path - Alt-X') ) . '", more_colors:"' . mce_escape( __('More colors') ) . '", colorpicker_delta_width:"' . /* translators: Extra width for the colorpicker popup in pixels */ mce_escape( _x('0', 'colorpicker popup width') ) . '", colorpicker_delta_height:"' . /* translators: Extra height for the colorpicker popup in pixels */ mce_escape( _x('0', 'colorpicker popup height') ) . '" }); tinyMCE.addI18n("' . $language . '.advanced_dlg",{ about_title:"' . mce_escape( __('About TinyMCE') ) . '", about_general:"' . mce_escape( __('About') ) . '", about_help:"' . mce_escape( __('Help') ) . '", about_license:"' . mce_escape( __('License') ) . '", about_plugins:"' . mce_escape( __('Plugins') ) . '", about_plugin:"' . mce_escape( __('Plugin') ) . '", about_author:"' . mce_escape( __('Author') ) . '", about_version:"' . mce_escape( __('Version') ) . '", about_loaded:"' . mce_escape( __('Loaded plugins') ) . '", anchor_title:"' . mce_escape( __('Insert/edit anchor') ) . '", anchor_name:"' . mce_escape( __('Anchor name') ) . '", code_title:"' . mce_escape( __('HTML Source Editor') ) . '", code_wordwrap:"' . mce_escape( __('Word wrap') ) . '", colorpicker_title:"' . mce_escape( __('Select a color') ) . '", colorpicker_picker_tab:"' . mce_escape( __('Picker') ) . '", colorpicker_picker_title:"' . mce_escape( __('Color picker') ) . '", colorpicker_palette_tab:"' . mce_escape( __('Palette') ) . '", colorpicker_palette_title:"' . mce_escape( __('Palette colors') ) . '", colorpicker_named_tab:"' . mce_escape( __('Named') ) . '", colorpicker_named_title:"' . mce_escape( __('Named colors') ) . '", colorpicker_color:"' . mce_escape( __('Color:') ) . '", colorpicker_name:"' . mce_escape( __('Name:') ) . '", charmap_title:"' . mce_escape( __('Select custom character') ) . '", image_title:"' . mce_escape( __('Insert/edit image') ) . '", image_src:"' . mce_escape( __('Image URL') ) . '", image_alt:"' . mce_escape( __('Image description') ) . '", image_list:"' . mce_escape( __('Image list') ) . '", image_border:"' . mce_escape( __('Border') ) . '", image_dimensions:"' . mce_escape( __('Dimensions') ) . '", image_vspace:"' . mce_escape( __('Vertical space') ) . '", image_hspace:"' . mce_escape( __('Horizontal space') ) . '", image_align:"' . mce_escape( __('Alignment') ) . '", image_align_baseline:"' . mce_escape( __('Baseline') ) . '", image_align_top:"' . mce_escape( __('Top') ) . '", image_align_middle:"' . mce_escape( __('Middle') ) . '", image_align_bottom:"' . mce_escape( __('Bottom') ) . '", image_align_texttop:"' . mce_escape( __('Text top') ) . '", image_align_textbottom:"' . mce_escape( __('Text bottom') ) . '", image_align_left:"' . mce_escape( __('Left') ) . '", image_align_right:"' . mce_escape( __('Right') ) . '", link_title:"' . mce_escape( __('Insert/edit link') ) . '", link_url:"' . mce_escape( __('Link URL') ) . '", link_target:"' . mce_escape( __('Target') ) . '", link_target_same:"' . mce_escape( __('Open link in the same window') ) . '", link_target_blank:"' . mce_escape( __('Open link in a new window') ) . '", link_titlefield:"' . mce_escape( __('Title') ) . '", link_is_email:"' . mce_escape( __('The URL you entered seems to be an email address, do you want to add the required mailto: prefix?') ) . '", link_is_external:"' . mce_escape( __('The URL you entered seems to external link, do you want to add the required http:// prefix?') ) . '", link_list:"' . mce_escape( __('Link list') ) . '" }); tinyMCE.addI18n("' . $language . '.media_dlg",{ title:"' . mce_escape( __('Insert / edit embedded media') ) . '", general:"' . mce_escape( __('General') ) . '", advanced:"' . mce_escape( __('Advanced') ) . '", file:"' . mce_escape( __('File/URL') ) . '", list:"' . mce_escape( __('List') ) . '", size:"' . mce_escape( __('Dimensions') ) . '", preview:"' . mce_escape( __('Preview') ) . '", constrain_proportions:"' . mce_escape( __('Constrain proportions') ) . '", type:"' . mce_escape( __('Type') ) . '", id:"' . mce_escape( __('Id') ) . '", name:"' . mce_escape( __('Name') ) . '", class_name:"' . mce_escape( __('Class') ) . '", vspace:"' . mce_escape( __('V-Space') ) . '", hspace:"' . mce_escape( __('H-Space') ) . '", play:"' . mce_escape( __('Auto play') ) . '", loop:"' . mce_escape( __('Loop') ) . '", menu:"' . mce_escape( __('Show menu') ) . '", quality:"' . mce_escape( __('Quality') ) . '", scale:"' . mce_escape( __('Scale') ) . '", align:"' . mce_escape( __('Align') ) . '", salign:"' . mce_escape( __('SAlign') ) . '", wmode:"' . mce_escape( __('WMode') ) . '", bgcolor:"' . mce_escape( __('Background') ) . '", base:"' . mce_escape( __('Base') ) . '", flashvars:"' . mce_escape( __('Flashvars') ) . '", liveconnect:"' . mce_escape( __('SWLiveConnect') ) . '", autohref:"' . mce_escape( __('AutoHREF') ) . '", cache:"' . mce_escape( __('Cache') ) . '", hidden:"' . mce_escape( __('Hidden') ) . '", controller:"' . mce_escape( __('Controller') ) . '", kioskmode:"' . mce_escape( __('Kiosk mode') ) . '", playeveryframe:"' . mce_escape( __('Play every frame') ) . '", targetcache:"' . mce_escape( __('Target cache') ) . '", correction:"' . mce_escape( __('No correction') ) . '", enablejavascript:"' . mce_escape( __('Enable JavaScript') ) . '", starttime:"' . mce_escape( __('Start time') ) . '", endtime:"' . mce_escape( __('End time') ) . '", href:"' . mce_escape( __('Href') ) . '", qtsrcchokespeed:"' . mce_escape( __('Choke speed') ) . '", target:"' . mce_escape( __('Target') ) . '", volume:"' . mce_escape( __('Volume') ) . '", autostart:"' . mce_escape( __('Auto start') ) . '", enabled:"' . mce_escape( __('Enabled') ) . '", fullscreen:"' . mce_escape( __('Fullscreen') ) . '", invokeurls:"' . mce_escape( __('Invoke URLs') ) . '", mute:"' . mce_escape( __('Mute') ) . '", stretchtofit:"' . mce_escape( __('Stretch to fit') ) . '", windowlessvideo:"' . mce_escape( __('Windowless video') ) . '", balance:"' . mce_escape( __('Balance') ) . '", baseurl:"' . mce_escape( __('Base URL') ) . '", captioningid:"' . mce_escape( __('Captioning id') ) . '", currentmarker:"' . mce_escape( __('Current marker') ) . '", currentposition:"' . mce_escape( __('Current position') ) . '", defaultframe:"' . mce_escape( __('Default frame') ) . '", playcount:"' . mce_escape( __('Play count') ) . '", rate:"' . mce_escape( __('Rate') ) . '", uimode:"' . mce_escape( __('UI Mode') ) . '", flash_options:"' . mce_escape( __('Flash options') ) . '", qt_options:"' . mce_escape( __('Quicktime options') ) . '", wmp_options:"' . mce_escape( __('Windows media player options') ) . '", rmp_options:"' . mce_escape( __('Real media player options') ) . '", shockwave_options:"' . mce_escape( __('Shockwave options') ) . '", autogotourl:"' . mce_escape( __('Auto goto URL') ) . '", center:"' . mce_escape( __('Center') ) . '", imagestatus:"' . mce_escape( __('Image status') ) . '", maintainaspect:"' . mce_escape( __('Maintain aspect') ) . '", nojava:"' . mce_escape( __('No java') ) . '", prefetch:"' . mce_escape( __('Prefetch') ) . '", shuffle:"' . mce_escape( __('Shuffle') ) . '", console:"' . mce_escape( __('Console') ) . '", numloop:"' . mce_escape( __('Num loops') ) . '", controls:"' . mce_escape( __('Controls') ) . '", scriptcallbacks:"' . mce_escape( __('Script callbacks') ) . '", swstretchstyle:"' . mce_escape( __('Stretch style') ) . '", swstretchhalign:"' . mce_escape( __('Stretch H-Align') ) . '", swstretchvalign:"' . mce_escape( __('Stretch V-Align') ) . '", sound:"' . mce_escape( __('Sound') ) . '", progress:"' . mce_escape( __('Progress') ) . '", qtsrc:"' . mce_escape( __('QT Src') ) . '", qt_stream_warn:"' . mce_escape( __('Streamed rtsp resources should be added to the QT Src field under the advanced tab.') ) . '", align_top:"' . mce_escape( __('Top') ) . '", align_right:"' . mce_escape( __('Right') ) . '", align_bottom:"' . mce_escape( __('Bottom') ) . '", align_left:"' . mce_escape( __('Left') ) . '", align_center:"' . mce_escape( __('Center') ) . '", align_top_left:"' . mce_escape( __('Top left') ) . '", align_top_right:"' . mce_escape( __('Top right') ) . '", align_bottom_left:"' . mce_escape( __('Bottom left') ) . '", align_bottom_right:"' . mce_escape( __('Bottom right') ) . '", flv_options:"' . mce_escape( __('Flash video options') ) . '", flv_scalemode:"' . mce_escape( __('Scale mode') ) . '", flv_buffer:"' . mce_escape( __('Buffer') ) . '", flv_startimage:"' . mce_escape( __('Start image') ) . '", flv_starttime:"' . mce_escape( __('Start time') ) . '", flv_defaultvolume:"' . mce_escape( __('Default volume') ) . '", flv_hiddengui:"' . mce_escape( __('Hidden GUI') ) . '", flv_autostart:"' . mce_escape( __('Auto start') ) . '", flv_loop:"' . mce_escape( __('Loop') ) . '", flv_showscalemodes:"' . mce_escape( __('Show scale modes') ) . '", flv_smoothvideo:"' . mce_escape( __('Smooth video') ) . '", flv_jscallback:"' . mce_escape( __('JS Callback') ) . '" }); tinyMCE.addI18n("' . $language . '.wordpress",{ wp_adv_desc:"' . mce_escape( __('Show/Hide Kitchen Sink') ) . ' (Alt+Shift+Z)", wp_more_desc:"' . mce_escape( __('Insert More tag') ) . ' (Alt+Shift+T)", wp_page_desc:"' . mce_escape( __('Insert Page break') ) . ' (Alt+Shift+P)", wp_help_desc:"' . mce_escape( __('Help') ) . ' (Alt+Shift+H)", wp_more_alt:"' . mce_escape( __('More...') ) . '", wp_page_alt:"' . mce_escape( __('Next page...') ) . '", add_media:"' . mce_escape( __('Add Media') ) . '", add_image:"' . mce_escape( __('Add an Image') ) . '", add_video:"' . mce_escape( __('Add Video') ) . '", add_audio:"' . mce_escape( __('Add Audio') ) . '", editgallery:"' . mce_escape( __('Edit Gallery') ) . '", delgallery:"' . mce_escape( __('Delete Gallery') ) . '" }); tinyMCE.addI18n("' . $language . '.wpeditimage",{ edit_img:"' . mce_escape( __('Edit Image') ) . '", del_img:"' . mce_escape( __('Delete Image') ) . '", adv_settings:"' . mce_escape( __('Advanced Settings') ) . '", none:"' . mce_escape( __('None') ) . '", size:"' . mce_escape( __('Size') ) . '", thumbnail:"' . mce_escape( __('Thumbnail') ) . '", medium:"' . mce_escape( __('Medium') ) . '", full_size:"' . mce_escape( __('Full Size') ) . '", current_link:"' . mce_escape( __('Current Link') ) . '", link_to_img:"' . mce_escape( __('Link to Image') ) . '", link_help:"' . mce_escape( __('Enter a link URL or click above for presets.') ) . '", adv_img_settings:"' . mce_escape( __('Advanced Image Settings') ) . '", source:"' . mce_escape( __('Source') ) . '", width:"' . mce_escape( __('Width') ) . '", height:"' . mce_escape( __('Height') ) . '", orig_size:"' . mce_escape( __('Original Size') ) . '", css:"' . mce_escape( __('CSS Class') ) . '", adv_link_settings:"' . mce_escape( __('Advanced Link Settings') ) . '", link_rel:"' . mce_escape( __('Link Rel') ) . '", height:"' . mce_escape( __('Height') ) . '", orig_size:"' . mce_escape( __('Original Size') ) . '", css:"' . mce_escape( __('CSS Class') ) . '", s60:"' . mce_escape( __('60%') ) . '", s70:"' . mce_escape( __('70%') ) . '", s80:"' . mce_escape( __('80%') ) . '", s90:"' . mce_escape( __('90%') ) . '", s100:"' . mce_escape( __('100%') ) . '", s110:"' . mce_escape( __('110%') ) . '", s120:"' . mce_escape( __('120%') ) . '", s130:"' . mce_escape( __('130%') ) . '", img_title:"' . mce_escape( __('Edit Image Title') ) . '", caption:"' . mce_escape( __('Edit Image Caption') ) . '", alt:"' . mce_escape( __('Edit Alternate Text') ) . '" }); ';
airhorns/Skylight-Labs
wp-includes/js/tinymce/langs/wp-langs.php
PHP
gpl-2.0
23,380
/*============================================================================= Copyright (c) 2001-2011 Hartmut Kaiser Copyright (c) 2001-2014 Joel de Guzman Copyright (c) 2013 Agustin Berge Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #ifndef BOOST_SPIRIT_X3_ATTR_JUL_23_2008_0956AM #define BOOST_SPIRIT_X3_ATTR_JUL_23_2008_0956AM #include <boost/spirit/home/x3/core/parser.hpp> #include <boost/spirit/home/x3/support/unused.hpp> #include <boost/spirit/home/x3/support/traits/container_traits.hpp> #include <boost/spirit/home/x3/support/traits/move_to.hpp> #include <boost/type_traits/is_same.hpp> #include <boost/type_traits/remove_cv.hpp> #include <boost/type_traits/remove_reference.hpp> #include <algorithm> #include <cstddef> #include <string> #include <utility> namespace boost { namespace spirit { namespace x3 { template <typename Value> struct attr_parser : parser<attr_parser<Value>> { typedef Value attribute_type; static bool const has_attribute = !is_same<unused_type, attribute_type>::value; static bool const handles_container = traits::is_container<attribute_type>::value; attr_parser(Value const& value) : value_(value) {} attr_parser(Value&& value) : value_(std::move(value)) {} template <typename Iterator, typename Context , typename RuleContext, typename Attribute> bool parse(Iterator& /* first */, Iterator const& /* last */ , Context const& /* context */, RuleContext&, Attribute& attr_) const { // $$$ Change to copy_to once we have it $$$ traits::move_to(value_, attr_); return true; } Value value_; private: // silence MSVC warning C4512: assignment operator could not be generated attr_parser& operator= (attr_parser const&); }; template <typename Value, std::size_t N> struct attr_parser<Value[N]> : parser<attr_parser<Value[N]>> { typedef Value attribute_type[N]; static bool const has_attribute = !is_same<unused_type, attribute_type>::value; static bool const handles_container = true; attr_parser(Value const (&value)[N]) { std::copy(value + 0, value + N, value_ + 0); } attr_parser(Value (&&value)[N]) { std::move(value + 0, value + N, value_ + 0); } template <typename Iterator, typename Context , typename RuleContext, typename Attribute> bool parse(Iterator& /* first */, Iterator const& /* last */ , Context const& /* context */, RuleContext&, Attribute& attr_) const { // $$$ Change to copy_to once we have it $$$ traits::move_to(value_ + 0, value_ + N, attr_); return true; } Value value_[N]; private: // silence MSVC warning C4512: assignment operator could not be generated attr_parser& operator= (attr_parser const&); }; template <typename Value> struct get_info<attr_parser<Value>> { typedef std::string result_type; std::string operator()(attr_parser<Value> const& /*p*/) const { return "attr"; } }; struct attr_gen { template <typename Value> attr_parser<typename remove_cv< typename remove_reference<Value>::type>::type> operator()(Value&& value) const { return { std::forward<Value>(value) }; } template <typename Value, std::size_t N> attr_parser<typename remove_cv<Value>::type[N]> operator()(Value (&value)[N]) const { return { value }; } template <typename Value, std::size_t N> attr_parser<typename remove_cv<Value>::type[N]> operator()(Value (&&value)[N]) const { return { value }; } }; auto const attr = attr_gen{}; }}} #endif
zcobell/MetOceanViewer
thirdparty/boost_1_67_0/boost/spirit/home/x3/auxiliary/attr.hpp
C++
gpl-3.0
4,238
<?php class Migrations_Migration314 Extends Shopware\Components\Migrations\AbstractMigration { public function up($modus) { $this->addSql(' ALTER TABLE `s_order_details` ADD `pack_unit` VARCHAR(255) NULL DEFAULT NULL ; '); } }
wlwwt/shopware
update-assets/migrations/314-add-order-detail-pack-unit.php
PHP
agpl-3.0
279
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.Diagnostics { internal abstract partial class CompilerDiagnosticAnalyzer : DiagnosticAnalyzer { private const string Origin = "Origin"; private const string Syntactic = "Syntactic"; private const string Declaration = "Declaration"; private static readonly ImmutableDictionary<string, string> s_syntactic = ImmutableDictionary<string, string>.Empty.Add(Origin, Syntactic); private static readonly ImmutableDictionary<string, string> s_declaration = ImmutableDictionary<string, string>.Empty.Add(Origin, Declaration); /// <summary> /// Per-compilation DiagnosticAnalyzer for compiler's syntax/semantic/compilation diagnostics. /// </summary> private class CompilationAnalyzer { private readonly Compilation _compilation; public CompilationAnalyzer(Compilation compilation) { _compilation = compilation; } public void AnalyzeSyntaxTree(SyntaxTreeAnalysisContext context) { var semanticModel = _compilation.GetSemanticModel(context.Tree); var diagnostics = semanticModel.GetSyntaxDiagnostics(cancellationToken: context.CancellationToken); ReportDiagnostics(diagnostics, context.ReportDiagnostic, IsSourceLocation, s_syntactic); } public static void AnalyzeSemanticModel(SemanticModelAnalysisContext context) { var declDiagnostics = context.SemanticModel.GetDeclarationDiagnostics(cancellationToken: context.CancellationToken); ReportDiagnostics(declDiagnostics, context.ReportDiagnostic, IsSourceLocation, s_declaration); var bodyDiagnostics = context.SemanticModel.GetMethodBodyDiagnostics(cancellationToken: context.CancellationToken); ReportDiagnostics(bodyDiagnostics, context.ReportDiagnostic, IsSourceLocation); } public static void AnalyzeCompilation(CompilationAnalysisContext context) { var diagnostics = context.Compilation.GetDeclarationDiagnostics(cancellationToken: context.CancellationToken); ReportDiagnostics(diagnostics, context.ReportDiagnostic, location => !IsSourceLocation(location), s_declaration); } private static bool IsSourceLocation(Location location) { return location != null && location.Kind == LocationKind.SourceFile; } private static void ReportDiagnostics( ImmutableArray<Diagnostic> diagnostics, Action<Diagnostic> reportDiagnostic, Func<Location, bool> locationFilter, ImmutableDictionary<string, string> properties = null) { foreach (var diagnostic in diagnostics) { if (locationFilter(diagnostic.Location) && diagnostic.Severity != DiagnosticSeverity.Hidden) { var current = properties == null ? diagnostic : new CompilerDiagnostic(diagnostic, properties); reportDiagnostic(current); } } } private class CompilerDiagnostic : Diagnostic { private readonly Diagnostic _original; private readonly ImmutableDictionary<string, string> _properties; public CompilerDiagnostic(Diagnostic original, ImmutableDictionary<string, string> properties) { _original = original; _properties = properties; } #pragma warning disable RS0013 // we are delegating so it is okay here public override DiagnosticDescriptor Descriptor => _original.Descriptor; #pragma warning restore RS0013 public override string Id => _original.Id; public override DiagnosticSeverity Severity => _original.Severity; public override int WarningLevel => _original.WarningLevel; public override Location Location => _original.Location; public override IReadOnlyList<Location> AdditionalLocations => _original.AdditionalLocations; public override ImmutableDictionary<string, string> Properties => _properties; public override string GetMessage(IFormatProvider formatProvider = null) { return _original.GetMessage(formatProvider); } public override bool Equals(object obj) { return _original.Equals(obj); } public override int GetHashCode() { return _original.GetHashCode(); } public override bool Equals(Diagnostic obj) { return _original.Equals(obj); } internal override Diagnostic WithLocation(Location location) { return new CompilerDiagnostic(_original.WithLocation(location), _properties); } internal override Diagnostic WithSeverity(DiagnosticSeverity severity) { return new CompilerDiagnostic(_original.WithSeverity(severity), _properties); } } } } }
droyad/roslyn
src/Compilers/Core/Portable/DiagnosticAnalyzer/CompilerDiagnosticAnalyzer.CompilationAnalyzer.cs
C#
apache-2.0
5,774
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.wm.ex; import com.intellij.openapi.Disposable; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Condition; import com.intellij.openapi.wm.ToolWindowAnchor; import com.intellij.openapi.wm.ToolWindowEP; import com.intellij.openapi.wm.ToolWindowManager; import com.intellij.openapi.wm.impl.DesktopLayout; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.List; public abstract class ToolWindowManagerEx extends ToolWindowManager { public abstract void initToolWindow(@NotNull ToolWindowEP bean); public static ToolWindowManagerEx getInstanceEx(final Project project){ return (ToolWindowManagerEx)getInstance(project); } public abstract void addToolWindowManagerListener(@NotNull ToolWindowManagerListener l); public abstract void addToolWindowManagerListener(@NotNull ToolWindowManagerListener l, @NotNull Disposable parentDisposable); public abstract void removeToolWindowManagerListener(@NotNull ToolWindowManagerListener l); /** * @return <code>ID</code> of tool window that was activated last time. */ @Nullable public abstract String getLastActiveToolWindowId(); /** * @return <code>ID</code> of tool window which was last activated among tool windows satisfying the current condition */ @Nullable public abstract String getLastActiveToolWindowId(@Nullable Condition<JComponent> condition); /** * @return layout of tool windows. */ public abstract DesktopLayout getLayout(); public abstract void setLayoutToRestoreLater(DesktopLayout layout); public abstract DesktopLayout getLayoutToRestoreLater(); /** * Copied <code>layout</code> into internal layout and rearranges tool windows. */ public abstract void setLayout(@NotNull DesktopLayout layout); public abstract void clearSideStack(); public abstract void hideToolWindow(@NotNull String id, boolean hideSide); public abstract List<String> getIdsOn(@NotNull ToolWindowAnchor anchor); }
akosyakov/intellij-community
platform/platform-impl/src/com/intellij/openapi/wm/ex/ToolWindowManagerEx.java
Java
apache-2.0
2,657
<?php /** * Part of the Fuel framework. * * @package Fuel * @version 1.7 * @author Fuel Development Team * @license MIT License * @copyright 2010 - 2015 Fuel Development Team * @link http://fuelphp.com */ namespace Fuel\Core; /** * Fieldset class tests * * @group Core * @group Fieldset */ class Test_Fieldset extends TestCase { public function setUp() { // fake the uri for this request isset($_SERVER['PATH_INFO']) and $this->pathinfo = $_SERVER['PATH_INFO']; $_SERVER['PATH_INFO'] = '/welcome/index'; // set Request::$main $request = \Request::forge('welcome/index'); $rp = new \ReflectionProperty($request, 'main'); $rp->setAccessible(true); $rp->setValue($request, $request); \Request::active($request); } public function tearDown() { // remove the fake uri if (property_exists($this, 'pathinfo')) { $_SERVER['PATH_INFO'] = $this->pathinfo; } else { unset($_SERVER['PATH_INFO']); } // reset Request::$main $request = \Request::forge(); $rp = new \ReflectionProperty($request, 'main'); $rp->setAccessible(true); $rp->setValue($request, false); } /** * Test of "for" attribute in label tag */ public function test_for_in_label() { $form = Fieldset::forge(__METHOD__)->set_config(array( // regular form definitions 'prep_value' => true, 'auto_id' => true, 'auto_id_prefix' => 'form_', 'form_method' => 'post', 'form_template' => "\n\t\t{open}\n\t\t<table>\n{fields}\n\t\t</table>\n\t\t{close}\n", 'fieldset_template' => "\n\t\t<tr><td colspan=\"2\">{open}<table>\n{fields}</table></td></tr>\n\t\t{close}\n", 'field_template' => "\t\t<tr>\n\t\t\t<td class=\"{error_class}\">{label}{required}</td>\n\t\t\t<td class=\"{error_class}\">{field} <span>{description}</span> {error_msg}</td>\n\t\t</tr>\n", 'multi_field_template' => "\t\t<tr>\n\t\t\t<td class=\"{error_class}\">{group_label}{required}</td>\n\t\t\t<td class=\"{error_class}\">{fields}\n\t\t\t\t{field} {label}<br />\n{fields}<span>{description}</span>\t\t\t{error_msg}\n\t\t\t</td>\n\t\t</tr>\n", 'error_template' => '<span>{error_msg}</span>', 'group_label' => '<span>{label}</span>', 'required_mark' => '*', 'inline_errors' => false, 'error_class' => 'validation_error', // tabular form definitions 'tabular_form_template' => "<table>{fields}</table>\n", 'tabular_field_template' => "{field}", 'tabular_row_template' => "<tr>{fields}</tr>\n", 'tabular_row_field_template' => "\t\t\t<td>{label}{required}&nbsp;{field} {icon} {error_msg}</td>\n", 'tabular_delete_label' => "Delete?", )); $ops = array('male', 'female'); $form->add('gender', '', array( 'options' => $ops, 'type' => 'radio', 'value' => 1, )); $output = $form->build(); $output = str_replace(array("\n", "\t"), "", $output); $expected = '<form action="welcome/index" accept-charset="utf-8" method="post"><table><tr><td class=""></td><td class=""><input type="radio" value="0" id="form_gender_0" name="gender" /> <label for="form_gender_0">male</label><br /><input type="radio" value="1" id="form_gender_1" name="gender" checked="checked" /> <label for="form_gender_1">female</label><br /><span></span></td></tr></table></form>'; $this->assertEquals($expected, $output); } }
vano00/todo
fuel/core/tests/fieldset.php
PHP
mit
3,471
import * as _ from "lodash"; declare const sampleSize: typeof _.sampleSize; export default sampleSize;
smrq/DefinitelyTyped
types/lodash-es/sampleSize/index.d.ts
TypeScript
mit
103
/* vtt.js - v0.12.1 (https://github.com/mozilla/vtt.js) built on 21-03-2015 */ /** * Copyright 2013 vtt.js Contributors * * 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. */ (function(root) { var autoKeyword = "auto"; var directionSetting = { "": true, "lr": true, "rl": true }; var alignSetting = { "start": true, "middle": true, "end": true, "left": true, "right": true }; function findDirectionSetting(value) { if (typeof value !== "string") { return false; } var dir = directionSetting[value.toLowerCase()]; return dir ? value.toLowerCase() : false; } function findAlignSetting(value) { if (typeof value !== "string") { return false; } var align = alignSetting[value.toLowerCase()]; return align ? value.toLowerCase() : false; } function extend(obj) { var i = 1; for (; i < arguments.length; i++) { var cobj = arguments[i]; for (var p in cobj) { obj[p] = cobj[p]; } } return obj; } function VTTCue(startTime, endTime, text) { var cue = this; var isIE8 = (/MSIE\s8\.0/).test(navigator.userAgent); var baseObj = {}; if (isIE8) { cue = document.createElement('custom'); } else { baseObj.enumerable = true; } /** * Shim implementation specific properties. These properties are not in * the spec. */ // Lets us know when the VTTCue's data has changed in such a way that we need // to recompute its display state. This lets us compute its display state // lazily. cue.hasBeenReset = false; /** * VTTCue and TextTrackCue properties * http://dev.w3.org/html5/webvtt/#vttcue-interface */ var _id = ""; var _pauseOnExit = false; var _startTime = startTime; var _endTime = endTime; var _text = text; var _region = null; var _vertical = ""; var _snapToLines = true; var _line = "auto"; var _lineAlign = "start"; var _position = 50; var _positionAlign = "middle"; var _size = 50; var _align = "middle"; Object.defineProperty(cue, "id", extend({}, baseObj, { get: function() { return _id; }, set: function(value) { _id = "" + value; } })); Object.defineProperty(cue, "pauseOnExit", extend({}, baseObj, { get: function() { return _pauseOnExit; }, set: function(value) { _pauseOnExit = !!value; } })); Object.defineProperty(cue, "startTime", extend({}, baseObj, { get: function() { return _startTime; }, set: function(value) { if (typeof value !== "number") { throw new TypeError("Start time must be set to a number."); } _startTime = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "endTime", extend({}, baseObj, { get: function() { return _endTime; }, set: function(value) { if (typeof value !== "number") { throw new TypeError("End time must be set to a number."); } _endTime = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "text", extend({}, baseObj, { get: function() { return _text; }, set: function(value) { _text = "" + value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "region", extend({}, baseObj, { get: function() { return _region; }, set: function(value) { _region = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "vertical", extend({}, baseObj, { get: function() { return _vertical; }, set: function(value) { var setting = findDirectionSetting(value); // Have to check for false because the setting an be an empty string. if (setting === false) { throw new SyntaxError("An invalid or illegal string was specified."); } _vertical = setting; this.hasBeenReset = true; } })); Object.defineProperty(cue, "snapToLines", extend({}, baseObj, { get: function() { return _snapToLines; }, set: function(value) { _snapToLines = !!value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "line", extend({}, baseObj, { get: function() { return _line; }, set: function(value) { if (typeof value !== "number" && value !== autoKeyword) { throw new SyntaxError("An invalid number or illegal string was specified."); } _line = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "lineAlign", extend({}, baseObj, { get: function() { return _lineAlign; }, set: function(value) { var setting = findAlignSetting(value); if (!setting) { throw new SyntaxError("An invalid or illegal string was specified."); } _lineAlign = setting; this.hasBeenReset = true; } })); Object.defineProperty(cue, "position", extend({}, baseObj, { get: function() { return _position; }, set: function(value) { if (value < 0 || value > 100) { throw new Error("Position must be between 0 and 100."); } _position = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "positionAlign", extend({}, baseObj, { get: function() { return _positionAlign; }, set: function(value) { var setting = findAlignSetting(value); if (!setting) { throw new SyntaxError("An invalid or illegal string was specified."); } _positionAlign = setting; this.hasBeenReset = true; } })); Object.defineProperty(cue, "size", extend({}, baseObj, { get: function() { return _size; }, set: function(value) { if (value < 0 || value > 100) { throw new Error("Size must be between 0 and 100."); } _size = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "align", extend({}, baseObj, { get: function() { return _align; }, set: function(value) { var setting = findAlignSetting(value); if (!setting) { throw new SyntaxError("An invalid or illegal string was specified."); } _align = setting; this.hasBeenReset = true; } })); /** * Other <track> spec defined properties */ // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state cue.displayState = undefined; if (isIE8) { return cue; } } /** * VTTCue methods */ VTTCue.prototype.getCueAsHTML = function() { // Assume WebVTT.convertCueToDOMTree is on the global. return WebVTT.convertCueToDOMTree(window, this.text); }; root.VTTCue = VTTCue || root.VTTCue; }(this)); /** * Copyright 2013 vtt.js Contributors * * 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. */ (function(root) { var scrollSetting = { "": true, "up": true }; function findScrollSetting(value) { if (typeof value !== "string") { return false; } var scroll = scrollSetting[value.toLowerCase()]; return scroll ? value.toLowerCase() : false; } function isValidPercentValue(value) { return typeof value === "number" && (value >= 0 && value <= 100); } // VTTRegion shim http://dev.w3.org/html5/webvtt/#vttregion-interface function VTTRegion() { var _width = 100; var _lines = 3; var _regionAnchorX = 0; var _regionAnchorY = 100; var _viewportAnchorX = 0; var _viewportAnchorY = 100; var _scroll = ""; Object.defineProperties(this, { "width": { enumerable: true, get: function() { return _width; }, set: function(value) { if (!isValidPercentValue(value)) { throw new Error("Width must be between 0 and 100."); } _width = value; } }, "lines": { enumerable: true, get: function() { return _lines; }, set: function(value) { if (typeof value !== "number") { throw new TypeError("Lines must be set to a number."); } _lines = value; } }, "regionAnchorY": { enumerable: true, get: function() { return _regionAnchorY; }, set: function(value) { if (!isValidPercentValue(value)) { throw new Error("RegionAnchorX must be between 0 and 100."); } _regionAnchorY = value; } }, "regionAnchorX": { enumerable: true, get: function() { return _regionAnchorX; }, set: function(value) { if(!isValidPercentValue(value)) { throw new Error("RegionAnchorY must be between 0 and 100."); } _regionAnchorX = value; } }, "viewportAnchorY": { enumerable: true, get: function() { return _viewportAnchorY; }, set: function(value) { if (!isValidPercentValue(value)) { throw new Error("ViewportAnchorY must be between 0 and 100."); } _viewportAnchorY = value; } }, "viewportAnchorX": { enumerable: true, get: function() { return _viewportAnchorX; }, set: function(value) { if (!isValidPercentValue(value)) { throw new Error("ViewportAnchorX must be between 0 and 100."); } _viewportAnchorX = value; } }, "scroll": { enumerable: true, get: function() { return _scroll; }, set: function(value) { var setting = findScrollSetting(value); // Have to check for false as an empty string is a legal value. if (setting === false) { throw new SyntaxError("An invalid or illegal string was specified."); } _scroll = setting; } } }); } root.VTTRegion = root.VTTRegion || VTTRegion; }(this)); /** * Copyright 2013 vtt.js Contributors * * 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. */ /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */ (function(global) { var _objCreate = Object.create || (function() { function F() {} return function(o) { if (arguments.length !== 1) { throw new Error('Object.create shim only accepts one parameter.'); } F.prototype = o; return new F(); }; })(); // Creates a new ParserError object from an errorData object. The errorData // object should have default code and message properties. The default message // property can be overriden by passing in a message parameter. // See ParsingError.Errors below for acceptable errors. function ParsingError(errorData, message) { this.name = "ParsingError"; this.code = errorData.code; this.message = message || errorData.message; } ParsingError.prototype = _objCreate(Error.prototype); ParsingError.prototype.constructor = ParsingError; // ParsingError metadata for acceptable ParsingErrors. ParsingError.Errors = { BadSignature: { code: 0, message: "Malformed WebVTT signature." }, BadTimeStamp: { code: 1, message: "Malformed time stamp." } }; // Try to parse input as a time stamp. function parseTimeStamp(input) { function computeSeconds(h, m, s, f) { return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + (f | 0) / 1000; } var m = input.match(/^(\d+):(\d{2})(:\d{2})?\.(\d{3})/); if (!m) { return null; } if (m[3]) { // Timestamp takes the form of [hours]:[minutes]:[seconds].[milliseconds] return computeSeconds(m[1], m[2], m[3].replace(":", ""), m[4]); } else if (m[1] > 59) { // Timestamp takes the form of [hours]:[minutes].[milliseconds] // First position is hours as it's over 59. return computeSeconds(m[1], m[2], 0, m[4]); } else { // Timestamp takes the form of [minutes]:[seconds].[milliseconds] return computeSeconds(0, m[1], m[2], m[4]); } } // A settings object holds key/value pairs and will ignore anything but the first // assignment to a specific key. function Settings() { this.values = _objCreate(null); } Settings.prototype = { // Only accept the first assignment to any key. set: function(k, v) { if (!this.get(k) && v !== "") { this.values[k] = v; } }, // Return the value for a key, or a default value. // If 'defaultKey' is passed then 'dflt' is assumed to be an object with // a number of possible default values as properties where 'defaultKey' is // the key of the property that will be chosen; otherwise it's assumed to be // a single value. get: function(k, dflt, defaultKey) { if (defaultKey) { return this.has(k) ? this.values[k] : dflt[defaultKey]; } return this.has(k) ? this.values[k] : dflt; }, // Check whether we have a value for a key. has: function(k) { return k in this.values; }, // Accept a setting if its one of the given alternatives. alt: function(k, v, a) { for (var n = 0; n < a.length; ++n) { if (v === a[n]) { this.set(k, v); break; } } }, // Accept a setting if its a valid (signed) integer. integer: function(k, v) { if (/^-?\d+$/.test(v)) { // integer this.set(k, parseInt(v, 10)); } }, // Accept a setting if its a valid percentage. percent: function(k, v) { var m; if ((m = v.match(/^([\d]{1,3})(\.[\d]*)?%$/))) { v = parseFloat(v); if (v >= 0 && v <= 100) { this.set(k, v); return true; } } return false; } }; // Helper function to parse input into groups separated by 'groupDelim', and // interprete each group as a key/value pair separated by 'keyValueDelim'. function parseOptions(input, callback, keyValueDelim, groupDelim) { var groups = groupDelim ? input.split(groupDelim) : [input]; for (var i in groups) { if (typeof groups[i] !== "string") { continue; } var kv = groups[i].split(keyValueDelim); if (kv.length !== 2) { continue; } var k = kv[0]; var v = kv[1]; callback(k, v); } } function parseCue(input, cue, regionList) { // Remember the original input if we need to throw an error. var oInput = input; // 4.1 WebVTT timestamp function consumeTimeStamp() { var ts = parseTimeStamp(input); if (ts === null) { throw new ParsingError(ParsingError.Errors.BadTimeStamp, "Malformed timestamp: " + oInput); } // Remove time stamp from input. input = input.replace(/^[^\sa-zA-Z-]+/, ""); return ts; } // 4.4.2 WebVTT cue settings function consumeCueSettings(input, cue) { var settings = new Settings(); parseOptions(input, function (k, v) { switch (k) { case "region": // Find the last region we parsed with the same region id. for (var i = regionList.length - 1; i >= 0; i--) { if (regionList[i].id === v) { settings.set(k, regionList[i].region); break; } } break; case "vertical": settings.alt(k, v, ["rl", "lr"]); break; case "line": var vals = v.split(","), vals0 = vals[0]; settings.integer(k, vals0); settings.percent(k, vals0) ? settings.set("snapToLines", false) : null; settings.alt(k, vals0, ["auto"]); if (vals.length === 2) { settings.alt("lineAlign", vals[1], ["start", "middle", "end"]); } break; case "position": vals = v.split(","); settings.percent(k, vals[0]); if (vals.length === 2) { settings.alt("positionAlign", vals[1], ["start", "middle", "end"]); } break; case "size": settings.percent(k, v); break; case "align": settings.alt(k, v, ["start", "middle", "end", "left", "right"]); break; } }, /:/, /\s/); // Apply default values for any missing fields. cue.region = settings.get("region", null); cue.vertical = settings.get("vertical", ""); cue.line = settings.get("line", "auto"); cue.lineAlign = settings.get("lineAlign", "start"); cue.snapToLines = settings.get("snapToLines", true); cue.size = settings.get("size", 100); cue.align = settings.get("align", "middle"); cue.position = settings.get("position", { start: 0, left: 0, middle: 50, end: 100, right: 100 }, cue.align); cue.positionAlign = settings.get("positionAlign", { start: "start", left: "start", middle: "middle", end: "end", right: "end" }, cue.align); } function skipWhitespace() { input = input.replace(/^\s+/, ""); } // 4.1 WebVTT cue timings. skipWhitespace(); cue.startTime = consumeTimeStamp(); // (1) collect cue start time skipWhitespace(); if (input.substr(0, 3) !== "-->") { // (3) next characters must match "-->" throw new ParsingError(ParsingError.Errors.BadTimeStamp, "Malformed time stamp (time stamps must be separated by '-->'): " + oInput); } input = input.substr(3); skipWhitespace(); cue.endTime = consumeTimeStamp(); // (5) collect cue end time // 4.1 WebVTT cue settings list. skipWhitespace(); consumeCueSettings(input, cue); } var ESCAPE = { "&amp;": "&", "&lt;": "<", "&gt;": ">", "&lrm;": "\u200e", "&rlm;": "\u200f", "&nbsp;": "\u00a0" }; var TAG_NAME = { c: "span", i: "i", b: "b", u: "u", ruby: "ruby", rt: "rt", v: "span", lang: "span" }; var TAG_ANNOTATION = { v: "title", lang: "lang" }; var NEEDS_PARENT = { rt: "ruby" }; // Parse content into a document fragment. function parseContent(window, input) { function nextToken() { // Check for end-of-string. if (!input) { return null; } // Consume 'n' characters from the input. function consume(result) { input = input.substr(result.length); return result; } var m = input.match(/^([^<]*)(<[^>]+>?)?/); // If there is some text before the next tag, return it, otherwise return // the tag. return consume(m[1] ? m[1] : m[2]); } // Unescape a string 's'. function unescape1(e) { return ESCAPE[e]; } function unescape(s) { while ((m = s.match(/&(amp|lt|gt|lrm|rlm|nbsp);/))) { s = s.replace(m[0], unescape1); } return s; } function shouldAdd(current, element) { return !NEEDS_PARENT[element.localName] || NEEDS_PARENT[element.localName] === current.localName; } // Create an element for this tag. function createElement(type, annotation) { var tagName = TAG_NAME[type]; if (!tagName) { return null; } var element = window.document.createElement(tagName); element.localName = tagName; var name = TAG_ANNOTATION[type]; if (name && annotation) { element[name] = annotation.trim(); } return element; } var rootDiv = window.document.createElement("div"), current = rootDiv, t, tagStack = []; while ((t = nextToken()) !== null) { if (t[0] === '<') { if (t[1] === "/") { // If the closing tag matches, move back up to the parent node. if (tagStack.length && tagStack[tagStack.length - 1] === t.substr(2).replace(">", "")) { tagStack.pop(); current = current.parentNode; } // Otherwise just ignore the end tag. continue; } var ts = parseTimeStamp(t.substr(1, t.length - 2)); var node; if (ts) { // Timestamps are lead nodes as well. node = window.document.createProcessingInstruction("timestamp", ts); current.appendChild(node); continue; } var m = t.match(/^<([^.\s/0-9>]+)(\.[^\s\\>]+)?([^>\\]+)?(\\?)>?$/); // If we can't parse the tag, skip to the next tag. if (!m) { continue; } // Try to construct an element, and ignore the tag if we couldn't. node = createElement(m[1], m[3]); if (!node) { continue; } // Determine if the tag should be added based on the context of where it // is placed in the cuetext. if (!shouldAdd(current, node)) { continue; } // Set the class list (as a list of classes, separated by space). if (m[2]) { node.className = m[2].substr(1).replace('.', ' '); } // Append the node to the current node, and enter the scope of the new // node. tagStack.push(m[1]); current.appendChild(node); current = node; continue; } // Text nodes are leaf nodes. current.appendChild(window.document.createTextNode(unescape(t))); } return rootDiv; } // This is a list of all the Unicode characters that have a strong // right-to-left category. What this means is that these characters are // written right-to-left for sure. It was generated by pulling all the strong // right-to-left characters out of the Unicode data table. That table can // found at: http://www.unicode.org/Public/UNIDATA/UnicodeData.txt var strongRTLChars = [0x05BE, 0x05C0, 0x05C3, 0x05C6, 0x05D0, 0x05D1, 0x05D2, 0x05D3, 0x05D4, 0x05D5, 0x05D6, 0x05D7, 0x05D8, 0x05D9, 0x05DA, 0x05DB, 0x05DC, 0x05DD, 0x05DE, 0x05DF, 0x05E0, 0x05E1, 0x05E2, 0x05E3, 0x05E4, 0x05E5, 0x05E6, 0x05E7, 0x05E8, 0x05E9, 0x05EA, 0x05F0, 0x05F1, 0x05F2, 0x05F3, 0x05F4, 0x0608, 0x060B, 0x060D, 0x061B, 0x061E, 0x061F, 0x0620, 0x0621, 0x0622, 0x0623, 0x0624, 0x0625, 0x0626, 0x0627, 0x0628, 0x0629, 0x062A, 0x062B, 0x062C, 0x062D, 0x062E, 0x062F, 0x0630, 0x0631, 0x0632, 0x0633, 0x0634, 0x0635, 0x0636, 0x0637, 0x0638, 0x0639, 0x063A, 0x063B, 0x063C, 0x063D, 0x063E, 0x063F, 0x0640, 0x0641, 0x0642, 0x0643, 0x0644, 0x0645, 0x0646, 0x0647, 0x0648, 0x0649, 0x064A, 0x066D, 0x066E, 0x066F, 0x0671, 0x0672, 0x0673, 0x0674, 0x0675, 0x0676, 0x0677, 0x0678, 0x0679, 0x067A, 0x067B, 0x067C, 0x067D, 0x067E, 0x067F, 0x0680, 0x0681, 0x0682, 0x0683, 0x0684, 0x0685, 0x0686, 0x0687, 0x0688, 0x0689, 0x068A, 0x068B, 0x068C, 0x068D, 0x068E, 0x068F, 0x0690, 0x0691, 0x0692, 0x0693, 0x0694, 0x0695, 0x0696, 0x0697, 0x0698, 0x0699, 0x069A, 0x069B, 0x069C, 0x069D, 0x069E, 0x069F, 0x06A0, 0x06A1, 0x06A2, 0x06A3, 0x06A4, 0x06A5, 0x06A6, 0x06A7, 0x06A8, 0x06A9, 0x06AA, 0x06AB, 0x06AC, 0x06AD, 0x06AE, 0x06AF, 0x06B0, 0x06B1, 0x06B2, 0x06B3, 0x06B4, 0x06B5, 0x06B6, 0x06B7, 0x06B8, 0x06B9, 0x06BA, 0x06BB, 0x06BC, 0x06BD, 0x06BE, 0x06BF, 0x06C0, 0x06C1, 0x06C2, 0x06C3, 0x06C4, 0x06C5, 0x06C6, 0x06C7, 0x06C8, 0x06C9, 0x06CA, 0x06CB, 0x06CC, 0x06CD, 0x06CE, 0x06CF, 0x06D0, 0x06D1, 0x06D2, 0x06D3, 0x06D4, 0x06D5, 0x06E5, 0x06E6, 0x06EE, 0x06EF, 0x06FA, 0x06FB, 0x06FC, 0x06FD, 0x06FE, 0x06FF, 0x0700, 0x0701, 0x0702, 0x0703, 0x0704, 0x0705, 0x0706, 0x0707, 0x0708, 0x0709, 0x070A, 0x070B, 0x070C, 0x070D, 0x070F, 0x0710, 0x0712, 0x0713, 0x0714, 0x0715, 0x0716, 0x0717, 0x0718, 0x0719, 0x071A, 0x071B, 0x071C, 0x071D, 0x071E, 0x071F, 0x0720, 0x0721, 0x0722, 0x0723, 0x0724, 0x0725, 0x0726, 0x0727, 0x0728, 0x0729, 0x072A, 0x072B, 0x072C, 0x072D, 0x072E, 0x072F, 0x074D, 0x074E, 0x074F, 0x0750, 0x0751, 0x0752, 0x0753, 0x0754, 0x0755, 0x0756, 0x0757, 0x0758, 0x0759, 0x075A, 0x075B, 0x075C, 0x075D, 0x075E, 0x075F, 0x0760, 0x0761, 0x0762, 0x0763, 0x0764, 0x0765, 0x0766, 0x0767, 0x0768, 0x0769, 0x076A, 0x076B, 0x076C, 0x076D, 0x076E, 0x076F, 0x0770, 0x0771, 0x0772, 0x0773, 0x0774, 0x0775, 0x0776, 0x0777, 0x0778, 0x0779, 0x077A, 0x077B, 0x077C, 0x077D, 0x077E, 0x077F, 0x0780, 0x0781, 0x0782, 0x0783, 0x0784, 0x0785, 0x0786, 0x0787, 0x0788, 0x0789, 0x078A, 0x078B, 0x078C, 0x078D, 0x078E, 0x078F, 0x0790, 0x0791, 0x0792, 0x0793, 0x0794, 0x0795, 0x0796, 0x0797, 0x0798, 0x0799, 0x079A, 0x079B, 0x079C, 0x079D, 0x079E, 0x079F, 0x07A0, 0x07A1, 0x07A2, 0x07A3, 0x07A4, 0x07A5, 0x07B1, 0x07C0, 0x07C1, 0x07C2, 0x07C3, 0x07C4, 0x07C5, 0x07C6, 0x07C7, 0x07C8, 0x07C9, 0x07CA, 0x07CB, 0x07CC, 0x07CD, 0x07CE, 0x07CF, 0x07D0, 0x07D1, 0x07D2, 0x07D3, 0x07D4, 0x07D5, 0x07D6, 0x07D7, 0x07D8, 0x07D9, 0x07DA, 0x07DB, 0x07DC, 0x07DD, 0x07DE, 0x07DF, 0x07E0, 0x07E1, 0x07E2, 0x07E3, 0x07E4, 0x07E5, 0x07E6, 0x07E7, 0x07E8, 0x07E9, 0x07EA, 0x07F4, 0x07F5, 0x07FA, 0x0800, 0x0801, 0x0802, 0x0803, 0x0804, 0x0805, 0x0806, 0x0807, 0x0808, 0x0809, 0x080A, 0x080B, 0x080C, 0x080D, 0x080E, 0x080F, 0x0810, 0x0811, 0x0812, 0x0813, 0x0814, 0x0815, 0x081A, 0x0824, 0x0828, 0x0830, 0x0831, 0x0832, 0x0833, 0x0834, 0x0835, 0x0836, 0x0837, 0x0838, 0x0839, 0x083A, 0x083B, 0x083C, 0x083D, 0x083E, 0x0840, 0x0841, 0x0842, 0x0843, 0x0844, 0x0845, 0x0846, 0x0847, 0x0848, 0x0849, 0x084A, 0x084B, 0x084C, 0x084D, 0x084E, 0x084F, 0x0850, 0x0851, 0x0852, 0x0853, 0x0854, 0x0855, 0x0856, 0x0857, 0x0858, 0x085E, 0x08A0, 0x08A2, 0x08A3, 0x08A4, 0x08A5, 0x08A6, 0x08A7, 0x08A8, 0x08A9, 0x08AA, 0x08AB, 0x08AC, 0x200F, 0xFB1D, 0xFB1F, 0xFB20, 0xFB21, 0xFB22, 0xFB23, 0xFB24, 0xFB25, 0xFB26, 0xFB27, 0xFB28, 0xFB2A, 0xFB2B, 0xFB2C, 0xFB2D, 0xFB2E, 0xFB2F, 0xFB30, 0xFB31, 0xFB32, 0xFB33, 0xFB34, 0xFB35, 0xFB36, 0xFB38, 0xFB39, 0xFB3A, 0xFB3B, 0xFB3C, 0xFB3E, 0xFB40, 0xFB41, 0xFB43, 0xFB44, 0xFB46, 0xFB47, 0xFB48, 0xFB49, 0xFB4A, 0xFB4B, 0xFB4C, 0xFB4D, 0xFB4E, 0xFB4F, 0xFB50, 0xFB51, 0xFB52, 0xFB53, 0xFB54, 0xFB55, 0xFB56, 0xFB57, 0xFB58, 0xFB59, 0xFB5A, 0xFB5B, 0xFB5C, 0xFB5D, 0xFB5E, 0xFB5F, 0xFB60, 0xFB61, 0xFB62, 0xFB63, 0xFB64, 0xFB65, 0xFB66, 0xFB67, 0xFB68, 0xFB69, 0xFB6A, 0xFB6B, 0xFB6C, 0xFB6D, 0xFB6E, 0xFB6F, 0xFB70, 0xFB71, 0xFB72, 0xFB73, 0xFB74, 0xFB75, 0xFB76, 0xFB77, 0xFB78, 0xFB79, 0xFB7A, 0xFB7B, 0xFB7C, 0xFB7D, 0xFB7E, 0xFB7F, 0xFB80, 0xFB81, 0xFB82, 0xFB83, 0xFB84, 0xFB85, 0xFB86, 0xFB87, 0xFB88, 0xFB89, 0xFB8A, 0xFB8B, 0xFB8C, 0xFB8D, 0xFB8E, 0xFB8F, 0xFB90, 0xFB91, 0xFB92, 0xFB93, 0xFB94, 0xFB95, 0xFB96, 0xFB97, 0xFB98, 0xFB99, 0xFB9A, 0xFB9B, 0xFB9C, 0xFB9D, 0xFB9E, 0xFB9F, 0xFBA0, 0xFBA1, 0xFBA2, 0xFBA3, 0xFBA4, 0xFBA5, 0xFBA6, 0xFBA7, 0xFBA8, 0xFBA9, 0xFBAA, 0xFBAB, 0xFBAC, 0xFBAD, 0xFBAE, 0xFBAF, 0xFBB0, 0xFBB1, 0xFBB2, 0xFBB3, 0xFBB4, 0xFBB5, 0xFBB6, 0xFBB7, 0xFBB8, 0xFBB9, 0xFBBA, 0xFBBB, 0xFBBC, 0xFBBD, 0xFBBE, 0xFBBF, 0xFBC0, 0xFBC1, 0xFBD3, 0xFBD4, 0xFBD5, 0xFBD6, 0xFBD7, 0xFBD8, 0xFBD9, 0xFBDA, 0xFBDB, 0xFBDC, 0xFBDD, 0xFBDE, 0xFBDF, 0xFBE0, 0xFBE1, 0xFBE2, 0xFBE3, 0xFBE4, 0xFBE5, 0xFBE6, 0xFBE7, 0xFBE8, 0xFBE9, 0xFBEA, 0xFBEB, 0xFBEC, 0xFBED, 0xFBEE, 0xFBEF, 0xFBF0, 0xFBF1, 0xFBF2, 0xFBF3, 0xFBF4, 0xFBF5, 0xFBF6, 0xFBF7, 0xFBF8, 0xFBF9, 0xFBFA, 0xFBFB, 0xFBFC, 0xFBFD, 0xFBFE, 0xFBFF, 0xFC00, 0xFC01, 0xFC02, 0xFC03, 0xFC04, 0xFC05, 0xFC06, 0xFC07, 0xFC08, 0xFC09, 0xFC0A, 0xFC0B, 0xFC0C, 0xFC0D, 0xFC0E, 0xFC0F, 0xFC10, 0xFC11, 0xFC12, 0xFC13, 0xFC14, 0xFC15, 0xFC16, 0xFC17, 0xFC18, 0xFC19, 0xFC1A, 0xFC1B, 0xFC1C, 0xFC1D, 0xFC1E, 0xFC1F, 0xFC20, 0xFC21, 0xFC22, 0xFC23, 0xFC24, 0xFC25, 0xFC26, 0xFC27, 0xFC28, 0xFC29, 0xFC2A, 0xFC2B, 0xFC2C, 0xFC2D, 0xFC2E, 0xFC2F, 0xFC30, 0xFC31, 0xFC32, 0xFC33, 0xFC34, 0xFC35, 0xFC36, 0xFC37, 0xFC38, 0xFC39, 0xFC3A, 0xFC3B, 0xFC3C, 0xFC3D, 0xFC3E, 0xFC3F, 0xFC40, 0xFC41, 0xFC42, 0xFC43, 0xFC44, 0xFC45, 0xFC46, 0xFC47, 0xFC48, 0xFC49, 0xFC4A, 0xFC4B, 0xFC4C, 0xFC4D, 0xFC4E, 0xFC4F, 0xFC50, 0xFC51, 0xFC52, 0xFC53, 0xFC54, 0xFC55, 0xFC56, 0xFC57, 0xFC58, 0xFC59, 0xFC5A, 0xFC5B, 0xFC5C, 0xFC5D, 0xFC5E, 0xFC5F, 0xFC60, 0xFC61, 0xFC62, 0xFC63, 0xFC64, 0xFC65, 0xFC66, 0xFC67, 0xFC68, 0xFC69, 0xFC6A, 0xFC6B, 0xFC6C, 0xFC6D, 0xFC6E, 0xFC6F, 0xFC70, 0xFC71, 0xFC72, 0xFC73, 0xFC74, 0xFC75, 0xFC76, 0xFC77, 0xFC78, 0xFC79, 0xFC7A, 0xFC7B, 0xFC7C, 0xFC7D, 0xFC7E, 0xFC7F, 0xFC80, 0xFC81, 0xFC82, 0xFC83, 0xFC84, 0xFC85, 0xFC86, 0xFC87, 0xFC88, 0xFC89, 0xFC8A, 0xFC8B, 0xFC8C, 0xFC8D, 0xFC8E, 0xFC8F, 0xFC90, 0xFC91, 0xFC92, 0xFC93, 0xFC94, 0xFC95, 0xFC96, 0xFC97, 0xFC98, 0xFC99, 0xFC9A, 0xFC9B, 0xFC9C, 0xFC9D, 0xFC9E, 0xFC9F, 0xFCA0, 0xFCA1, 0xFCA2, 0xFCA3, 0xFCA4, 0xFCA5, 0xFCA6, 0xFCA7, 0xFCA8, 0xFCA9, 0xFCAA, 0xFCAB, 0xFCAC, 0xFCAD, 0xFCAE, 0xFCAF, 0xFCB0, 0xFCB1, 0xFCB2, 0xFCB3, 0xFCB4, 0xFCB5, 0xFCB6, 0xFCB7, 0xFCB8, 0xFCB9, 0xFCBA, 0xFCBB, 0xFCBC, 0xFCBD, 0xFCBE, 0xFCBF, 0xFCC0, 0xFCC1, 0xFCC2, 0xFCC3, 0xFCC4, 0xFCC5, 0xFCC6, 0xFCC7, 0xFCC8, 0xFCC9, 0xFCCA, 0xFCCB, 0xFCCC, 0xFCCD, 0xFCCE, 0xFCCF, 0xFCD0, 0xFCD1, 0xFCD2, 0xFCD3, 0xFCD4, 0xFCD5, 0xFCD6, 0xFCD7, 0xFCD8, 0xFCD9, 0xFCDA, 0xFCDB, 0xFCDC, 0xFCDD, 0xFCDE, 0xFCDF, 0xFCE0, 0xFCE1, 0xFCE2, 0xFCE3, 0xFCE4, 0xFCE5, 0xFCE6, 0xFCE7, 0xFCE8, 0xFCE9, 0xFCEA, 0xFCEB, 0xFCEC, 0xFCED, 0xFCEE, 0xFCEF, 0xFCF0, 0xFCF1, 0xFCF2, 0xFCF3, 0xFCF4, 0xFCF5, 0xFCF6, 0xFCF7, 0xFCF8, 0xFCF9, 0xFCFA, 0xFCFB, 0xFCFC, 0xFCFD, 0xFCFE, 0xFCFF, 0xFD00, 0xFD01, 0xFD02, 0xFD03, 0xFD04, 0xFD05, 0xFD06, 0xFD07, 0xFD08, 0xFD09, 0xFD0A, 0xFD0B, 0xFD0C, 0xFD0D, 0xFD0E, 0xFD0F, 0xFD10, 0xFD11, 0xFD12, 0xFD13, 0xFD14, 0xFD15, 0xFD16, 0xFD17, 0xFD18, 0xFD19, 0xFD1A, 0xFD1B, 0xFD1C, 0xFD1D, 0xFD1E, 0xFD1F, 0xFD20, 0xFD21, 0xFD22, 0xFD23, 0xFD24, 0xFD25, 0xFD26, 0xFD27, 0xFD28, 0xFD29, 0xFD2A, 0xFD2B, 0xFD2C, 0xFD2D, 0xFD2E, 0xFD2F, 0xFD30, 0xFD31, 0xFD32, 0xFD33, 0xFD34, 0xFD35, 0xFD36, 0xFD37, 0xFD38, 0xFD39, 0xFD3A, 0xFD3B, 0xFD3C, 0xFD3D, 0xFD50, 0xFD51, 0xFD52, 0xFD53, 0xFD54, 0xFD55, 0xFD56, 0xFD57, 0xFD58, 0xFD59, 0xFD5A, 0xFD5B, 0xFD5C, 0xFD5D, 0xFD5E, 0xFD5F, 0xFD60, 0xFD61, 0xFD62, 0xFD63, 0xFD64, 0xFD65, 0xFD66, 0xFD67, 0xFD68, 0xFD69, 0xFD6A, 0xFD6B, 0xFD6C, 0xFD6D, 0xFD6E, 0xFD6F, 0xFD70, 0xFD71, 0xFD72, 0xFD73, 0xFD74, 0xFD75, 0xFD76, 0xFD77, 0xFD78, 0xFD79, 0xFD7A, 0xFD7B, 0xFD7C, 0xFD7D, 0xFD7E, 0xFD7F, 0xFD80, 0xFD81, 0xFD82, 0xFD83, 0xFD84, 0xFD85, 0xFD86, 0xFD87, 0xFD88, 0xFD89, 0xFD8A, 0xFD8B, 0xFD8C, 0xFD8D, 0xFD8E, 0xFD8F, 0xFD92, 0xFD93, 0xFD94, 0xFD95, 0xFD96, 0xFD97, 0xFD98, 0xFD99, 0xFD9A, 0xFD9B, 0xFD9C, 0xFD9D, 0xFD9E, 0xFD9F, 0xFDA0, 0xFDA1, 0xFDA2, 0xFDA3, 0xFDA4, 0xFDA5, 0xFDA6, 0xFDA7, 0xFDA8, 0xFDA9, 0xFDAA, 0xFDAB, 0xFDAC, 0xFDAD, 0xFDAE, 0xFDAF, 0xFDB0, 0xFDB1, 0xFDB2, 0xFDB3, 0xFDB4, 0xFDB5, 0xFDB6, 0xFDB7, 0xFDB8, 0xFDB9, 0xFDBA, 0xFDBB, 0xFDBC, 0xFDBD, 0xFDBE, 0xFDBF, 0xFDC0, 0xFDC1, 0xFDC2, 0xFDC3, 0xFDC4, 0xFDC5, 0xFDC6, 0xFDC7, 0xFDF0, 0xFDF1, 0xFDF2, 0xFDF3, 0xFDF4, 0xFDF5, 0xFDF6, 0xFDF7, 0xFDF8, 0xFDF9, 0xFDFA, 0xFDFB, 0xFDFC, 0xFE70, 0xFE71, 0xFE72, 0xFE73, 0xFE74, 0xFE76, 0xFE77, 0xFE78, 0xFE79, 0xFE7A, 0xFE7B, 0xFE7C, 0xFE7D, 0xFE7E, 0xFE7F, 0xFE80, 0xFE81, 0xFE82, 0xFE83, 0xFE84, 0xFE85, 0xFE86, 0xFE87, 0xFE88, 0xFE89, 0xFE8A, 0xFE8B, 0xFE8C, 0xFE8D, 0xFE8E, 0xFE8F, 0xFE90, 0xFE91, 0xFE92, 0xFE93, 0xFE94, 0xFE95, 0xFE96, 0xFE97, 0xFE98, 0xFE99, 0xFE9A, 0xFE9B, 0xFE9C, 0xFE9D, 0xFE9E, 0xFE9F, 0xFEA0, 0xFEA1, 0xFEA2, 0xFEA3, 0xFEA4, 0xFEA5, 0xFEA6, 0xFEA7, 0xFEA8, 0xFEA9, 0xFEAA, 0xFEAB, 0xFEAC, 0xFEAD, 0xFEAE, 0xFEAF, 0xFEB0, 0xFEB1, 0xFEB2, 0xFEB3, 0xFEB4, 0xFEB5, 0xFEB6, 0xFEB7, 0xFEB8, 0xFEB9, 0xFEBA, 0xFEBB, 0xFEBC, 0xFEBD, 0xFEBE, 0xFEBF, 0xFEC0, 0xFEC1, 0xFEC2, 0xFEC3, 0xFEC4, 0xFEC5, 0xFEC6, 0xFEC7, 0xFEC8, 0xFEC9, 0xFECA, 0xFECB, 0xFECC, 0xFECD, 0xFECE, 0xFECF, 0xFED0, 0xFED1, 0xFED2, 0xFED3, 0xFED4, 0xFED5, 0xFED6, 0xFED7, 0xFED8, 0xFED9, 0xFEDA, 0xFEDB, 0xFEDC, 0xFEDD, 0xFEDE, 0xFEDF, 0xFEE0, 0xFEE1, 0xFEE2, 0xFEE3, 0xFEE4, 0xFEE5, 0xFEE6, 0xFEE7, 0xFEE8, 0xFEE9, 0xFEEA, 0xFEEB, 0xFEEC, 0xFEED, 0xFEEE, 0xFEEF, 0xFEF0, 0xFEF1, 0xFEF2, 0xFEF3, 0xFEF4, 0xFEF5, 0xFEF6, 0xFEF7, 0xFEF8, 0xFEF9, 0xFEFA, 0xFEFB, 0xFEFC, 0x10800, 0x10801, 0x10802, 0x10803, 0x10804, 0x10805, 0x10808, 0x1080A, 0x1080B, 0x1080C, 0x1080D, 0x1080E, 0x1080F, 0x10810, 0x10811, 0x10812, 0x10813, 0x10814, 0x10815, 0x10816, 0x10817, 0x10818, 0x10819, 0x1081A, 0x1081B, 0x1081C, 0x1081D, 0x1081E, 0x1081F, 0x10820, 0x10821, 0x10822, 0x10823, 0x10824, 0x10825, 0x10826, 0x10827, 0x10828, 0x10829, 0x1082A, 0x1082B, 0x1082C, 0x1082D, 0x1082E, 0x1082F, 0x10830, 0x10831, 0x10832, 0x10833, 0x10834, 0x10835, 0x10837, 0x10838, 0x1083C, 0x1083F, 0x10840, 0x10841, 0x10842, 0x10843, 0x10844, 0x10845, 0x10846, 0x10847, 0x10848, 0x10849, 0x1084A, 0x1084B, 0x1084C, 0x1084D, 0x1084E, 0x1084F, 0x10850, 0x10851, 0x10852, 0x10853, 0x10854, 0x10855, 0x10857, 0x10858, 0x10859, 0x1085A, 0x1085B, 0x1085C, 0x1085D, 0x1085E, 0x1085F, 0x10900, 0x10901, 0x10902, 0x10903, 0x10904, 0x10905, 0x10906, 0x10907, 0x10908, 0x10909, 0x1090A, 0x1090B, 0x1090C, 0x1090D, 0x1090E, 0x1090F, 0x10910, 0x10911, 0x10912, 0x10913, 0x10914, 0x10915, 0x10916, 0x10917, 0x10918, 0x10919, 0x1091A, 0x1091B, 0x10920, 0x10921, 0x10922, 0x10923, 0x10924, 0x10925, 0x10926, 0x10927, 0x10928, 0x10929, 0x1092A, 0x1092B, 0x1092C, 0x1092D, 0x1092E, 0x1092F, 0x10930, 0x10931, 0x10932, 0x10933, 0x10934, 0x10935, 0x10936, 0x10937, 0x10938, 0x10939, 0x1093F, 0x10980, 0x10981, 0x10982, 0x10983, 0x10984, 0x10985, 0x10986, 0x10987, 0x10988, 0x10989, 0x1098A, 0x1098B, 0x1098C, 0x1098D, 0x1098E, 0x1098F, 0x10990, 0x10991, 0x10992, 0x10993, 0x10994, 0x10995, 0x10996, 0x10997, 0x10998, 0x10999, 0x1099A, 0x1099B, 0x1099C, 0x1099D, 0x1099E, 0x1099F, 0x109A0, 0x109A1, 0x109A2, 0x109A3, 0x109A4, 0x109A5, 0x109A6, 0x109A7, 0x109A8, 0x109A9, 0x109AA, 0x109AB, 0x109AC, 0x109AD, 0x109AE, 0x109AF, 0x109B0, 0x109B1, 0x109B2, 0x109B3, 0x109B4, 0x109B5, 0x109B6, 0x109B7, 0x109BE, 0x109BF, 0x10A00, 0x10A10, 0x10A11, 0x10A12, 0x10A13, 0x10A15, 0x10A16, 0x10A17, 0x10A19, 0x10A1A, 0x10A1B, 0x10A1C, 0x10A1D, 0x10A1E, 0x10A1F, 0x10A20, 0x10A21, 0x10A22, 0x10A23, 0x10A24, 0x10A25, 0x10A26, 0x10A27, 0x10A28, 0x10A29, 0x10A2A, 0x10A2B, 0x10A2C, 0x10A2D, 0x10A2E, 0x10A2F, 0x10A30, 0x10A31, 0x10A32, 0x10A33, 0x10A40, 0x10A41, 0x10A42, 0x10A43, 0x10A44, 0x10A45, 0x10A46, 0x10A47, 0x10A50, 0x10A51, 0x10A52, 0x10A53, 0x10A54, 0x10A55, 0x10A56, 0x10A57, 0x10A58, 0x10A60, 0x10A61, 0x10A62, 0x10A63, 0x10A64, 0x10A65, 0x10A66, 0x10A67, 0x10A68, 0x10A69, 0x10A6A, 0x10A6B, 0x10A6C, 0x10A6D, 0x10A6E, 0x10A6F, 0x10A70, 0x10A71, 0x10A72, 0x10A73, 0x10A74, 0x10A75, 0x10A76, 0x10A77, 0x10A78, 0x10A79, 0x10A7A, 0x10A7B, 0x10A7C, 0x10A7D, 0x10A7E, 0x10A7F, 0x10B00, 0x10B01, 0x10B02, 0x10B03, 0x10B04, 0x10B05, 0x10B06, 0x10B07, 0x10B08, 0x10B09, 0x10B0A, 0x10B0B, 0x10B0C, 0x10B0D, 0x10B0E, 0x10B0F, 0x10B10, 0x10B11, 0x10B12, 0x10B13, 0x10B14, 0x10B15, 0x10B16, 0x10B17, 0x10B18, 0x10B19, 0x10B1A, 0x10B1B, 0x10B1C, 0x10B1D, 0x10B1E, 0x10B1F, 0x10B20, 0x10B21, 0x10B22, 0x10B23, 0x10B24, 0x10B25, 0x10B26, 0x10B27, 0x10B28, 0x10B29, 0x10B2A, 0x10B2B, 0x10B2C, 0x10B2D, 0x10B2E, 0x10B2F, 0x10B30, 0x10B31, 0x10B32, 0x10B33, 0x10B34, 0x10B35, 0x10B40, 0x10B41, 0x10B42, 0x10B43, 0x10B44, 0x10B45, 0x10B46, 0x10B47, 0x10B48, 0x10B49, 0x10B4A, 0x10B4B, 0x10B4C, 0x10B4D, 0x10B4E, 0x10B4F, 0x10B50, 0x10B51, 0x10B52, 0x10B53, 0x10B54, 0x10B55, 0x10B58, 0x10B59, 0x10B5A, 0x10B5B, 0x10B5C, 0x10B5D, 0x10B5E, 0x10B5F, 0x10B60, 0x10B61, 0x10B62, 0x10B63, 0x10B64, 0x10B65, 0x10B66, 0x10B67, 0x10B68, 0x10B69, 0x10B6A, 0x10B6B, 0x10B6C, 0x10B6D, 0x10B6E, 0x10B6F, 0x10B70, 0x10B71, 0x10B72, 0x10B78, 0x10B79, 0x10B7A, 0x10B7B, 0x10B7C, 0x10B7D, 0x10B7E, 0x10B7F, 0x10C00, 0x10C01, 0x10C02, 0x10C03, 0x10C04, 0x10C05, 0x10C06, 0x10C07, 0x10C08, 0x10C09, 0x10C0A, 0x10C0B, 0x10C0C, 0x10C0D, 0x10C0E, 0x10C0F, 0x10C10, 0x10C11, 0x10C12, 0x10C13, 0x10C14, 0x10C15, 0x10C16, 0x10C17, 0x10C18, 0x10C19, 0x10C1A, 0x10C1B, 0x10C1C, 0x10C1D, 0x10C1E, 0x10C1F, 0x10C20, 0x10C21, 0x10C22, 0x10C23, 0x10C24, 0x10C25, 0x10C26, 0x10C27, 0x10C28, 0x10C29, 0x10C2A, 0x10C2B, 0x10C2C, 0x10C2D, 0x10C2E, 0x10C2F, 0x10C30, 0x10C31, 0x10C32, 0x10C33, 0x10C34, 0x10C35, 0x10C36, 0x10C37, 0x10C38, 0x10C39, 0x10C3A, 0x10C3B, 0x10C3C, 0x10C3D, 0x10C3E, 0x10C3F, 0x10C40, 0x10C41, 0x10C42, 0x10C43, 0x10C44, 0x10C45, 0x10C46, 0x10C47, 0x10C48, 0x1EE00, 0x1EE01, 0x1EE02, 0x1EE03, 0x1EE05, 0x1EE06, 0x1EE07, 0x1EE08, 0x1EE09, 0x1EE0A, 0x1EE0B, 0x1EE0C, 0x1EE0D, 0x1EE0E, 0x1EE0F, 0x1EE10, 0x1EE11, 0x1EE12, 0x1EE13, 0x1EE14, 0x1EE15, 0x1EE16, 0x1EE17, 0x1EE18, 0x1EE19, 0x1EE1A, 0x1EE1B, 0x1EE1C, 0x1EE1D, 0x1EE1E, 0x1EE1F, 0x1EE21, 0x1EE22, 0x1EE24, 0x1EE27, 0x1EE29, 0x1EE2A, 0x1EE2B, 0x1EE2C, 0x1EE2D, 0x1EE2E, 0x1EE2F, 0x1EE30, 0x1EE31, 0x1EE32, 0x1EE34, 0x1EE35, 0x1EE36, 0x1EE37, 0x1EE39, 0x1EE3B, 0x1EE42, 0x1EE47, 0x1EE49, 0x1EE4B, 0x1EE4D, 0x1EE4E, 0x1EE4F, 0x1EE51, 0x1EE52, 0x1EE54, 0x1EE57, 0x1EE59, 0x1EE5B, 0x1EE5D, 0x1EE5F, 0x1EE61, 0x1EE62, 0x1EE64, 0x1EE67, 0x1EE68, 0x1EE69, 0x1EE6A, 0x1EE6C, 0x1EE6D, 0x1EE6E, 0x1EE6F, 0x1EE70, 0x1EE71, 0x1EE72, 0x1EE74, 0x1EE75, 0x1EE76, 0x1EE77, 0x1EE79, 0x1EE7A, 0x1EE7B, 0x1EE7C, 0x1EE7E, 0x1EE80, 0x1EE81, 0x1EE82, 0x1EE83, 0x1EE84, 0x1EE85, 0x1EE86, 0x1EE87, 0x1EE88, 0x1EE89, 0x1EE8B, 0x1EE8C, 0x1EE8D, 0x1EE8E, 0x1EE8F, 0x1EE90, 0x1EE91, 0x1EE92, 0x1EE93, 0x1EE94, 0x1EE95, 0x1EE96, 0x1EE97, 0x1EE98, 0x1EE99, 0x1EE9A, 0x1EE9B, 0x1EEA1, 0x1EEA2, 0x1EEA3, 0x1EEA5, 0x1EEA6, 0x1EEA7, 0x1EEA8, 0x1EEA9, 0x1EEAB, 0x1EEAC, 0x1EEAD, 0x1EEAE, 0x1EEAF, 0x1EEB0, 0x1EEB1, 0x1EEB2, 0x1EEB3, 0x1EEB4, 0x1EEB5, 0x1EEB6, 0x1EEB7, 0x1EEB8, 0x1EEB9, 0x1EEBA, 0x1EEBB, 0x10FFFD]; function determineBidi(cueDiv) { var nodeStack = [], text = "", charCode; if (!cueDiv || !cueDiv.childNodes) { return "ltr"; } function pushNodes(nodeStack, node) { for (var i = node.childNodes.length - 1; i >= 0; i--) { nodeStack.push(node.childNodes[i]); } } function nextTextNode(nodeStack) { if (!nodeStack || !nodeStack.length) { return null; } var node = nodeStack.pop(), text = node.textContent || node.innerText; if (text) { // TODO: This should match all unicode type B characters (paragraph // separator characters). See issue #115. var m = text.match(/^.*(\n|\r)/); if (m) { nodeStack.length = 0; return m[0]; } return text; } if (node.tagName === "ruby") { return nextTextNode(nodeStack); } if (node.childNodes) { pushNodes(nodeStack, node); return nextTextNode(nodeStack); } } pushNodes(nodeStack, cueDiv); while ((text = nextTextNode(nodeStack))) { for (var i = 0; i < text.length; i++) { charCode = text.charCodeAt(i); for (var j = 0; j < strongRTLChars.length; j++) { if (strongRTLChars[j] === charCode) { return "rtl"; } } } } return "ltr"; } function computeLinePos(cue) { if (typeof cue.line === "number" && (cue.snapToLines || (cue.line >= 0 && cue.line <= 100))) { return cue.line; } if (!cue.track || !cue.track.textTrackList || !cue.track.textTrackList.mediaElement) { return -1; } var track = cue.track, trackList = track.textTrackList, count = 0; for (var i = 0; i < trackList.length && trackList[i] !== track; i++) { if (trackList[i].mode === "showing") { count++; } } return ++count * -1; } function StyleBox() { } // Apply styles to a div. If there is no div passed then it defaults to the // div on 'this'. StyleBox.prototype.applyStyles = function(styles, div) { div = div || this.div; for (var prop in styles) { if (styles.hasOwnProperty(prop)) { div.style[prop] = styles[prop]; } } }; StyleBox.prototype.formatStyle = function(val, unit) { return val === 0 ? 0 : val + unit; }; // Constructs the computed display state of the cue (a div). Places the div // into the overlay which should be a block level element (usually a div). function CueStyleBox(window, cue, styleOptions) { var isIE8 = (/MSIE\s8\.0/).test(navigator.userAgent); var color = "rgba(255, 255, 255, 1)"; var backgroundColor = "rgba(0, 0, 0, 0.8)"; if (isIE8) { color = "rgb(255, 255, 255)"; backgroundColor = "rgb(0, 0, 0)"; } StyleBox.call(this); this.cue = cue; // Parse our cue's text into a DOM tree rooted at 'cueDiv'. This div will // have inline positioning and will function as the cue background box. this.cueDiv = parseContent(window, cue.text); var styles = { color: color, backgroundColor: backgroundColor, position: "relative", left: 0, right: 0, top: 0, bottom: 0, display: "inline" }; if (!isIE8) { styles.writingMode = cue.vertical === "" ? "horizontal-tb" : cue.vertical === "lr" ? "vertical-lr" : "vertical-rl"; styles.unicodeBidi = "plaintext"; } this.applyStyles(styles, this.cueDiv); // Create an absolutely positioned div that will be used to position the cue // div. Note, all WebVTT cue-setting alignments are equivalent to the CSS // mirrors of them except "middle" which is "center" in CSS. this.div = window.document.createElement("div"); styles = { textAlign: cue.align === "middle" ? "center" : cue.align, font: styleOptions.font, whiteSpace: "pre-line", position: "absolute" }; if (!isIE8) { styles.direction = determineBidi(this.cueDiv); styles.writingMode = cue.vertical === "" ? "horizontal-tb" : cue.vertical === "lr" ? "vertical-lr" : "vertical-rl". stylesunicodeBidi = "plaintext"; } this.applyStyles(styles); this.div.appendChild(this.cueDiv); // Calculate the distance from the reference edge of the viewport to the text // position of the cue box. The reference edge will be resolved later when // the box orientation styles are applied. var textPos = 0; switch (cue.positionAlign) { case "start": textPos = cue.position; break; case "middle": textPos = cue.position - (cue.size / 2); break; case "end": textPos = cue.position - cue.size; break; } // Horizontal box orientation; textPos is the distance from the left edge of the // area to the left edge of the box and cue.size is the distance extending to // the right from there. if (cue.vertical === "") { this.applyStyles({ left: this.formatStyle(textPos, "%"), width: this.formatStyle(cue.size, "%") }); // Vertical box orientation; textPos is the distance from the top edge of the // area to the top edge of the box and cue.size is the height extending // downwards from there. } else { this.applyStyles({ top: this.formatStyle(textPos, "%"), height: this.formatStyle(cue.size, "%") }); } this.move = function(box) { this.applyStyles({ top: this.formatStyle(box.top, "px"), bottom: this.formatStyle(box.bottom, "px"), left: this.formatStyle(box.left, "px"), right: this.formatStyle(box.right, "px"), height: this.formatStyle(box.height, "px"), width: this.formatStyle(box.width, "px") }); }; } CueStyleBox.prototype = _objCreate(StyleBox.prototype); CueStyleBox.prototype.constructor = CueStyleBox; // Represents the co-ordinates of an Element in a way that we can easily // compute things with such as if it overlaps or intersects with another Element. // Can initialize it with either a StyleBox or another BoxPosition. function BoxPosition(obj) { var isIE8 = (/MSIE\s8\.0/).test(navigator.userAgent); // Either a BoxPosition was passed in and we need to copy it, or a StyleBox // was passed in and we need to copy the results of 'getBoundingClientRect' // as the object returned is readonly. All co-ordinate values are in reference // to the viewport origin (top left). var lh, height, width, top; if (obj.div) { height = obj.div.offsetHeight; width = obj.div.offsetWidth; top = obj.div.offsetTop; var rects = (rects = obj.div.childNodes) && (rects = rects[0]) && rects.getClientRects && rects.getClientRects(); obj = obj.div.getBoundingClientRect(); // In certain cases the outter div will be slightly larger then the sum of // the inner div's lines. This could be due to bold text, etc, on some platforms. // In this case we should get the average line height and use that. This will // result in the desired behaviour. lh = rects ? Math.max((rects[0] && rects[0].height) || 0, obj.height / rects.length) : 0; } this.left = obj.left; this.right = obj.right; this.top = obj.top || top; this.height = obj.height || height; this.bottom = obj.bottom || (top + (obj.height || height)); this.width = obj.width || width; this.lineHeight = lh !== undefined ? lh : obj.lineHeight; if (isIE8 && !this.lineHeight) { this.lineHeight = 13; } } // Move the box along a particular axis. Optionally pass in an amount to move // the box. If no amount is passed then the default is the line height of the // box. BoxPosition.prototype.move = function(axis, toMove) { toMove = toMove !== undefined ? toMove : this.lineHeight; switch (axis) { case "+x": this.left += toMove; this.right += toMove; break; case "-x": this.left -= toMove; this.right -= toMove; break; case "+y": this.top += toMove; this.bottom += toMove; break; case "-y": this.top -= toMove; this.bottom -= toMove; break; } }; // Check if this box overlaps another box, b2. BoxPosition.prototype.overlaps = function(b2) { return this.left < b2.right && this.right > b2.left && this.top < b2.bottom && this.bottom > b2.top; }; // Check if this box overlaps any other boxes in boxes. BoxPosition.prototype.overlapsAny = function(boxes) { for (var i = 0; i < boxes.length; i++) { if (this.overlaps(boxes[i])) { return true; } } return false; }; // Check if this box is within another box. BoxPosition.prototype.within = function(container) { return this.top >= container.top && this.bottom <= container.bottom && this.left >= container.left && this.right <= container.right; }; // Check if this box is entirely within the container or it is overlapping // on the edge opposite of the axis direction passed. For example, if "+x" is // passed and the box is overlapping on the left edge of the container, then // return true. BoxPosition.prototype.overlapsOppositeAxis = function(container, axis) { switch (axis) { case "+x": return this.left < container.left; case "-x": return this.right > container.right; case "+y": return this.top < container.top; case "-y": return this.bottom > container.bottom; } }; // Find the percentage of the area that this box is overlapping with another // box. BoxPosition.prototype.intersectPercentage = function(b2) { var x = Math.max(0, Math.min(this.right, b2.right) - Math.max(this.left, b2.left)), y = Math.max(0, Math.min(this.bottom, b2.bottom) - Math.max(this.top, b2.top)), intersectArea = x * y; return intersectArea / (this.height * this.width); }; // Convert the positions from this box to CSS compatible positions using // the reference container's positions. This has to be done because this // box's positions are in reference to the viewport origin, whereas, CSS // values are in referecne to their respective edges. BoxPosition.prototype.toCSSCompatValues = function(reference) { return { top: this.top - reference.top, bottom: reference.bottom - this.bottom, left: this.left - reference.left, right: reference.right - this.right, height: this.height, width: this.width }; }; // Get an object that represents the box's position without anything extra. // Can pass a StyleBox, HTMLElement, or another BoxPositon. BoxPosition.getSimpleBoxPosition = function(obj) { var height = obj.div ? obj.div.offsetHeight : obj.tagName ? obj.offsetHeight : 0; var width = obj.div ? obj.div.offsetWidth : obj.tagName ? obj.offsetWidth : 0; var top = obj.div ? obj.div.offsetTop : obj.tagName ? obj.offsetTop : 0; obj = obj.div ? obj.div.getBoundingClientRect() : obj.tagName ? obj.getBoundingClientRect() : obj; var ret = { left: obj.left, right: obj.right, top: obj.top || top, height: obj.height || height, bottom: obj.bottom || (top + (obj.height || height)), width: obj.width || width }; return ret; }; // Move a StyleBox to its specified, or next best, position. The containerBox // is the box that contains the StyleBox, such as a div. boxPositions are // a list of other boxes that the styleBox can't overlap with. function moveBoxToLinePosition(window, styleBox, containerBox, boxPositions) { // Find the best position for a cue box, b, on the video. The axis parameter // is a list of axis, the order of which, it will move the box along. For example: // Passing ["+x", "-x"] will move the box first along the x axis in the positive // direction. If it doesn't find a good position for it there it will then move // it along the x axis in the negative direction. function findBestPosition(b, axis) { var bestPosition, specifiedPosition = new BoxPosition(b), percentage = 1; // Highest possible so the first thing we get is better. for (var i = 0; i < axis.length; i++) { while (b.overlapsOppositeAxis(containerBox, axis[i]) || (b.within(containerBox) && b.overlapsAny(boxPositions))) { b.move(axis[i]); } // We found a spot where we aren't overlapping anything. This is our // best position. if (b.within(containerBox)) { return b; } var p = b.intersectPercentage(containerBox); // If we're outside the container box less then we were on our last try // then remember this position as the best position. if (percentage > p) { bestPosition = new BoxPosition(b); percentage = p; } // Reset the box position to the specified position. b = new BoxPosition(specifiedPosition); } return bestPosition || specifiedPosition; } var boxPosition = new BoxPosition(styleBox), cue = styleBox.cue, linePos = computeLinePos(cue), axis = []; // If we have a line number to align the cue to. if (cue.snapToLines) { var size; switch (cue.vertical) { case "": axis = [ "+y", "-y" ]; size = "height"; break; case "rl": axis = [ "+x", "-x" ]; size = "width"; break; case "lr": axis = [ "-x", "+x" ]; size = "width"; break; } var step = boxPosition.lineHeight, position = step * Math.round(linePos), maxPosition = containerBox[size] + step, initialAxis = axis[0]; // If the specified intial position is greater then the max position then // clamp the box to the amount of steps it would take for the box to // reach the max position. if (Math.abs(position) > maxPosition) { position = position < 0 ? -1 : 1; position *= Math.ceil(maxPosition / step) * step; } // If computed line position returns negative then line numbers are // relative to the bottom of the video instead of the top. Therefore, we // need to increase our initial position by the length or width of the // video, depending on the writing direction, and reverse our axis directions. if (linePos < 0) { position += cue.vertical === "" ? containerBox.height : containerBox.width; axis = axis.reverse(); } // Move the box to the specified position. This may not be its best // position. boxPosition.move(initialAxis, position); } else { // If we have a percentage line value for the cue. var calculatedPercentage = (boxPosition.lineHeight / containerBox.height) * 100; switch (cue.lineAlign) { case "middle": linePos -= (calculatedPercentage / 2); break; case "end": linePos -= calculatedPercentage; break; } // Apply initial line position to the cue box. switch (cue.vertical) { case "": styleBox.applyStyles({ top: styleBox.formatStyle(linePos, "%") }); break; case "rl": styleBox.applyStyles({ left: styleBox.formatStyle(linePos, "%") }); break; case "lr": styleBox.applyStyles({ right: styleBox.formatStyle(linePos, "%") }); break; } axis = [ "+y", "-x", "+x", "-y" ]; // Get the box position again after we've applied the specified positioning // to it. boxPosition = new BoxPosition(styleBox); } var bestPosition = findBestPosition(boxPosition, axis); styleBox.move(bestPosition.toCSSCompatValues(containerBox)); } function WebVTT() { // Nothing } // Helper to allow strings to be decoded instead of the default binary utf8 data. WebVTT.StringDecoder = function() { return { decode: function(data) { if (!data) { return ""; } if (typeof data !== "string") { throw new Error("Error - expected string data."); } return decodeURIComponent(encodeURIComponent(data)); } }; }; WebVTT.convertCueToDOMTree = function(window, cuetext) { if (!window || !cuetext) { return null; } return parseContent(window, cuetext); }; var FONT_SIZE_PERCENT = 0.05; var FONT_STYLE = "sans-serif"; var CUE_BACKGROUND_PADDING = "1.5%"; // Runs the processing model over the cues and regions passed to it. // @param overlay A block level element (usually a div) that the computed cues // and regions will be placed into. WebVTT.processCues = function(window, cues, overlay) { if (!window || !cues || !overlay) { return null; } // Remove all previous children. while (overlay.firstChild) { overlay.removeChild(overlay.firstChild); } var paddedOverlay = window.document.createElement("div"); paddedOverlay.style.position = "absolute"; paddedOverlay.style.left = "0"; paddedOverlay.style.right = "0"; paddedOverlay.style.top = "0"; paddedOverlay.style.bottom = "0"; paddedOverlay.style.margin = CUE_BACKGROUND_PADDING; overlay.appendChild(paddedOverlay); // Determine if we need to compute the display states of the cues. This could // be the case if a cue's state has been changed since the last computation or // if it has not been computed yet. function shouldCompute(cues) { for (var i = 0; i < cues.length; i++) { if (cues[i].hasBeenReset || !cues[i].displayState) { return true; } } return false; } // We don't need to recompute the cues' display states. Just reuse them. if (!shouldCompute(cues)) { for (var i = 0; i < cues.length; i++) { paddedOverlay.appendChild(cues[i].displayState); } return; } var boxPositions = [], containerBox = BoxPosition.getSimpleBoxPosition(paddedOverlay), fontSize = Math.round(containerBox.height * FONT_SIZE_PERCENT * 100) / 100; var styleOptions = { font: fontSize + "px " + FONT_STYLE }; (function() { var styleBox, cue; for (var i = 0; i < cues.length; i++) { cue = cues[i]; // Compute the intial position and styles of the cue div. styleBox = new CueStyleBox(window, cue, styleOptions); paddedOverlay.appendChild(styleBox.div); // Move the cue div to it's correct line position. moveBoxToLinePosition(window, styleBox, containerBox, boxPositions); // Remember the computed div so that we don't have to recompute it later // if we don't have too. cue.displayState = styleBox.div; boxPositions.push(BoxPosition.getSimpleBoxPosition(styleBox)); } })(); }; WebVTT.Parser = function(window, decoder) { this.window = window; this.state = "INITIAL"; this.buffer = ""; this.decoder = decoder || new TextDecoder("utf8"); this.regionList = []; }; WebVTT.Parser.prototype = { // If the error is a ParsingError then report it to the consumer if // possible. If it's not a ParsingError then throw it like normal. reportOrThrowError: function(e) { if (e instanceof ParsingError) { this.onparsingerror && this.onparsingerror(e); } else { throw e; } }, parse: function (data) { var self = this; // If there is no data then we won't decode it, but will just try to parse // whatever is in buffer already. This may occur in circumstances, for // example when flush() is called. if (data) { // Try to decode the data that we received. self.buffer += self.decoder.decode(data, {stream: true}); } function collectNextLine() { var buffer = self.buffer; var pos = 0; while (pos < buffer.length && buffer[pos] !== '\r' && buffer[pos] !== '\n') { ++pos; } var line = buffer.substr(0, pos); // Advance the buffer early in case we fail below. if (buffer[pos] === '\r') { ++pos; } if (buffer[pos] === '\n') { ++pos; } self.buffer = buffer.substr(pos); return line; } // 3.4 WebVTT region and WebVTT region settings syntax function parseRegion(input) { var settings = new Settings(); parseOptions(input, function (k, v) { switch (k) { case "id": settings.set(k, v); break; case "width": settings.percent(k, v); break; case "lines": settings.integer(k, v); break; case "regionanchor": case "viewportanchor": var xy = v.split(','); if (xy.length !== 2) { break; } // We have to make sure both x and y parse, so use a temporary // settings object here. var anchor = new Settings(); anchor.percent("x", xy[0]); anchor.percent("y", xy[1]); if (!anchor.has("x") || !anchor.has("y")) { break; } settings.set(k + "X", anchor.get("x")); settings.set(k + "Y", anchor.get("y")); break; case "scroll": settings.alt(k, v, ["up"]); break; } }, /=/, /\s/); // Create the region, using default values for any values that were not // specified. if (settings.has("id")) { var region = new self.window.VTTRegion(); region.width = settings.get("width", 100); region.lines = settings.get("lines", 3); region.regionAnchorX = settings.get("regionanchorX", 0); region.regionAnchorY = settings.get("regionanchorY", 100); region.viewportAnchorX = settings.get("viewportanchorX", 0); region.viewportAnchorY = settings.get("viewportanchorY", 100); region.scroll = settings.get("scroll", ""); // Register the region. self.onregion && self.onregion(region); // Remember the VTTRegion for later in case we parse any VTTCues that // reference it. self.regionList.push({ id: settings.get("id"), region: region }); } } // 3.2 WebVTT metadata header syntax function parseHeader(input) { parseOptions(input, function (k, v) { switch (k) { case "Region": // 3.3 WebVTT region metadata header syntax parseRegion(v); break; } }, /:/); } // 5.1 WebVTT file parsing. try { var line; if (self.state === "INITIAL") { // We can't start parsing until we have the first line. if (!/\r\n|\n/.test(self.buffer)) { return this; } line = collectNextLine(); var m = line.match(/^WEBVTT([ \t].*)?$/); if (!m || !m[0]) { throw new ParsingError(ParsingError.Errors.BadSignature); } self.state = "HEADER"; } var alreadyCollectedLine = false; while (self.buffer) { // We can't parse a line until we have the full line. if (!/\r\n|\n/.test(self.buffer)) { return this; } if (!alreadyCollectedLine) { line = collectNextLine(); } else { alreadyCollectedLine = false; } switch (self.state) { case "HEADER": // 13-18 - Allow a header (metadata) under the WEBVTT line. if (/:/.test(line)) { parseHeader(line); } else if (!line) { // An empty line terminates the header and starts the body (cues). self.state = "ID"; } continue; case "NOTE": // Ignore NOTE blocks. if (!line) { self.state = "ID"; } continue; case "ID": // Check for the start of NOTE blocks. if (/^NOTE($|[ \t])/.test(line)) { self.state = "NOTE"; break; } // 19-29 - Allow any number of line terminators, then initialize new cue values. if (!line) { continue; } self.cue = new self.window.VTTCue(0, 0, ""); self.state = "CUE"; // 30-39 - Check if self line contains an optional identifier or timing data. if (line.indexOf("-->") === -1) { self.cue.id = line; continue; } // Process line as start of a cue. /*falls through*/ case "CUE": // 40 - Collect cue timings and settings. try { parseCue(line, self.cue, self.regionList); } catch (e) { self.reportOrThrowError(e); // In case of an error ignore rest of the cue. self.cue = null; self.state = "BADCUE"; continue; } self.state = "CUETEXT"; continue; case "CUETEXT": var hasSubstring = line.indexOf("-->") !== -1; // 34 - If we have an empty line then report the cue. // 35 - If we have the special substring '-->' then report the cue, // but do not collect the line as we need to process the current // one as a new cue. if (!line || hasSubstring && (alreadyCollectedLine = true)) { // We are done parsing self cue. self.oncue && self.oncue(self.cue); self.cue = null; self.state = "ID"; continue; } if (self.cue.text) { self.cue.text += "\n"; } self.cue.text += line; continue; case "BADCUE": // BADCUE // 54-62 - Collect and discard the remaining cue. if (!line) { self.state = "ID"; } continue; } } } catch (e) { self.reportOrThrowError(e); // If we are currently parsing a cue, report what we have. if (self.state === "CUETEXT" && self.cue && self.oncue) { self.oncue(self.cue); } self.cue = null; // Enter BADWEBVTT state if header was not parsed correctly otherwise // another exception occurred so enter BADCUE state. self.state = self.state === "INITIAL" ? "BADWEBVTT" : "BADCUE"; } return this; }, flush: function () { var self = this; try { // Finish decoding the stream. self.buffer += self.decoder.decode(); // Synthesize the end of the current cue or region. if (self.cue || self.state === "HEADER") { self.buffer += "\n\n"; self.parse(); } // If we've flushed, parsed, and we're still on the INITIAL state then // that means we don't have enough of the stream to parse the first // line. if (self.state === "INITIAL") { throw new ParsingError(ParsingError.Errors.BadSignature); } } catch(e) { self.reportOrThrowError(e); } self.onflush && self.onflush(); return this; } }; global.WebVTT = WebVTT; }(this)); // If we're in node require encoding-indexes and attach it to the global. if (typeof module !== "undefined" && module.exports) { this["encoding-indexes"] = require("./encoding-indexes.js")["encoding-indexes"]; } (function(global) { 'use strict'; // // Utilities // /** * @param {number} a The number to test. * @param {number} min The minimum value in the range, inclusive. * @param {number} max The maximum value in the range, inclusive. * @return {boolean} True if a >= min and a <= max. */ function inRange(a, min, max) { return min <= a && a <= max; } /** * @param {number} n The numerator. * @param {number} d The denominator. * @return {number} The result of the integer division of n by d. */ function div(n, d) { return Math.floor(n / d); } // // Implementation of Encoding specification // http://dvcs.w3.org/hg/encoding/raw-file/tip/Overview.html // // // 3. Terminology // // // 4. Encodings // /** @const */ var EOF_byte = -1; /** @const */ var EOF_code_point = -1; /** * @constructor * @param {Uint8Array} bytes Array of bytes that provide the stream. */ function ByteInputStream(bytes) { /** @type {number} */ var pos = 0; /** * @this {ByteInputStream} * @return {number} Get the next byte from the stream. */ this.get = function() { return (pos >= bytes.length) ? EOF_byte : Number(bytes[pos]); }; /** @param {number} n Number (positive or negative) by which to * offset the byte pointer. */ this.offset = function(n) { pos += n; if (pos < 0) { throw new Error('Seeking past start of the buffer'); } if (pos > bytes.length) { throw new Error('Seeking past EOF'); } }; /** * @param {Array.<number>} test Array of bytes to compare against. * @return {boolean} True if the start of the stream matches the test * bytes. */ this.match = function(test) { if (test.length > pos + bytes.length) { return false; } var i; for (i = 0; i < test.length; i += 1) { if (Number(bytes[pos + i]) !== test[i]) { return false; } } return true; }; } /** * @constructor * @param {Array.<number>} bytes The array to write bytes into. */ function ByteOutputStream(bytes) { /** @type {number} */ var pos = 0; /** * @param {...number} var_args The byte or bytes to emit into the stream. * @return {number} The last byte emitted. */ this.emit = function(var_args) { /** @type {number} */ var last = EOF_byte; var i; for (i = 0; i < arguments.length; ++i) { last = Number(arguments[i]); bytes[pos++] = last; } return last; }; } /** * @constructor * @param {string} string The source of code units for the stream. */ function CodePointInputStream(string) { /** * @param {string} string Input string of UTF-16 code units. * @return {Array.<number>} Code points. */ function stringToCodePoints(string) { /** @type {Array.<number>} */ var cps = []; // Based on http://www.w3.org/TR/WebIDL/#idl-DOMString var i = 0, n = string.length; while (i < string.length) { var c = string.charCodeAt(i); if (!inRange(c, 0xD800, 0xDFFF)) { cps.push(c); } else if (inRange(c, 0xDC00, 0xDFFF)) { cps.push(0xFFFD); } else { // (inRange(cu, 0xD800, 0xDBFF)) if (i === n - 1) { cps.push(0xFFFD); } else { var d = string.charCodeAt(i + 1); if (inRange(d, 0xDC00, 0xDFFF)) { var a = c & 0x3FF; var b = d & 0x3FF; i += 1; cps.push(0x10000 + (a << 10) + b); } else { cps.push(0xFFFD); } } } i += 1; } return cps; } /** @type {number} */ var pos = 0; /** @type {Array.<number>} */ var cps = stringToCodePoints(string); /** @param {number} n The number of bytes (positive or negative) * to advance the code point pointer by.*/ this.offset = function(n) { pos += n; if (pos < 0) { throw new Error('Seeking past start of the buffer'); } if (pos > cps.length) { throw new Error('Seeking past EOF'); } }; /** @return {number} Get the next code point from the stream. */ this.get = function() { if (pos >= cps.length) { return EOF_code_point; } return cps[pos]; }; } /** * @constructor */ function CodePointOutputStream() { /** @type {string} */ var string = ''; /** @return {string} The accumulated string. */ this.string = function() { return string; }; /** @param {number} c The code point to encode into the stream. */ this.emit = function(c) { if (c <= 0xFFFF) { string += String.fromCharCode(c); } else { c -= 0x10000; string += String.fromCharCode(0xD800 + ((c >> 10) & 0x3ff)); string += String.fromCharCode(0xDC00 + (c & 0x3ff)); } }; } /** * @constructor * @param {string} message Description of the error. */ function EncodingError(message) { this.name = 'EncodingError'; this.message = message; this.code = 0; } EncodingError.prototype = Error.prototype; /** * @param {boolean} fatal If true, decoding errors raise an exception. * @param {number=} opt_code_point Override the standard fallback code point. * @return {number} The code point to insert on a decoding error. */ function decoderError(fatal, opt_code_point) { if (fatal) { throw new EncodingError('Decoder error'); } return opt_code_point || 0xFFFD; } /** * @param {number} code_point The code point that could not be encoded. * @return {number} Always throws, no value is actually returned. */ function encoderError(code_point) { throw new EncodingError('The code point ' + code_point + ' could not be encoded.'); } /** * @param {string} label The encoding label. * @return {?{name:string,labels:Array.<string>}} */ function getEncoding(label) { label = String(label).trim().toLowerCase(); if (Object.prototype.hasOwnProperty.call(label_to_encoding, label)) { return label_to_encoding[label]; } return null; } /** @type {Array.<{encodings: Array.<{name:string,labels:Array.<string>}>, * heading: string}>} */ var encodings = [ { "encodings": [ { "labels": [ "unicode-1-1-utf-8", "utf-8", "utf8" ], "name": "utf-8" } ], "heading": "The Encoding" }, { "encodings": [ { "labels": [ "866", "cp866", "csibm866", "ibm866" ], "name": "ibm866" }, { "labels": [ "csisolatin2", "iso-8859-2", "iso-ir-101", "iso8859-2", "iso88592", "iso_8859-2", "iso_8859-2:1987", "l2", "latin2" ], "name": "iso-8859-2" }, { "labels": [ "csisolatin3", "iso-8859-3", "iso-ir-109", "iso8859-3", "iso88593", "iso_8859-3", "iso_8859-3:1988", "l3", "latin3" ], "name": "iso-8859-3" }, { "labels": [ "csisolatin4", "iso-8859-4", "iso-ir-110", "iso8859-4", "iso88594", "iso_8859-4", "iso_8859-4:1988", "l4", "latin4" ], "name": "iso-8859-4" }, { "labels": [ "csisolatincyrillic", "cyrillic", "iso-8859-5", "iso-ir-144", "iso8859-5", "iso88595", "iso_8859-5", "iso_8859-5:1988" ], "name": "iso-8859-5" }, { "labels": [ "arabic", "asmo-708", "csiso88596e", "csiso88596i", "csisolatinarabic", "ecma-114", "iso-8859-6", "iso-8859-6-e", "iso-8859-6-i", "iso-ir-127", "iso8859-6", "iso88596", "iso_8859-6", "iso_8859-6:1987" ], "name": "iso-8859-6" }, { "labels": [ "csisolatingreek", "ecma-118", "elot_928", "greek", "greek8", "iso-8859-7", "iso-ir-126", "iso8859-7", "iso88597", "iso_8859-7", "iso_8859-7:1987", "sun_eu_greek" ], "name": "iso-8859-7" }, { "labels": [ "csiso88598e", "csisolatinhebrew", "hebrew", "iso-8859-8", "iso-8859-8-e", "iso-ir-138", "iso8859-8", "iso88598", "iso_8859-8", "iso_8859-8:1988", "visual" ], "name": "iso-8859-8" }, { "labels": [ "csiso88598i", "iso-8859-8-i", "logical" ], "name": "iso-8859-8-i" }, { "labels": [ "csisolatin6", "iso-8859-10", "iso-ir-157", "iso8859-10", "iso885910", "l6", "latin6" ], "name": "iso-8859-10" }, { "labels": [ "iso-8859-13", "iso8859-13", "iso885913" ], "name": "iso-8859-13" }, { "labels": [ "iso-8859-14", "iso8859-14", "iso885914" ], "name": "iso-8859-14" }, { "labels": [ "csisolatin9", "iso-8859-15", "iso8859-15", "iso885915", "iso_8859-15", "l9" ], "name": "iso-8859-15" }, { "labels": [ "iso-8859-16" ], "name": "iso-8859-16" }, { "labels": [ "cskoi8r", "koi", "koi8", "koi8-r", "koi8_r" ], "name": "koi8-r" }, { "labels": [ "koi8-u" ], "name": "koi8-u" }, { "labels": [ "csmacintosh", "mac", "macintosh", "x-mac-roman" ], "name": "macintosh" }, { "labels": [ "dos-874", "iso-8859-11", "iso8859-11", "iso885911", "tis-620", "windows-874" ], "name": "windows-874" }, { "labels": [ "cp1250", "windows-1250", "x-cp1250" ], "name": "windows-1250" }, { "labels": [ "cp1251", "windows-1251", "x-cp1251" ], "name": "windows-1251" }, { "labels": [ "ansi_x3.4-1968", "ascii", "cp1252", "cp819", "csisolatin1", "ibm819", "iso-8859-1", "iso-ir-100", "iso8859-1", "iso88591", "iso_8859-1", "iso_8859-1:1987", "l1", "latin1", "us-ascii", "windows-1252", "x-cp1252" ], "name": "windows-1252" }, { "labels": [ "cp1253", "windows-1253", "x-cp1253" ], "name": "windows-1253" }, { "labels": [ "cp1254", "csisolatin5", "iso-8859-9", "iso-ir-148", "iso8859-9", "iso88599", "iso_8859-9", "iso_8859-9:1989", "l5", "latin5", "windows-1254", "x-cp1254" ], "name": "windows-1254" }, { "labels": [ "cp1255", "windows-1255", "x-cp1255" ], "name": "windows-1255" }, { "labels": [ "cp1256", "windows-1256", "x-cp1256" ], "name": "windows-1256" }, { "labels": [ "cp1257", "windows-1257", "x-cp1257" ], "name": "windows-1257" }, { "labels": [ "cp1258", "windows-1258", "x-cp1258" ], "name": "windows-1258" }, { "labels": [ "x-mac-cyrillic", "x-mac-ukrainian" ], "name": "x-mac-cyrillic" } ], "heading": "Legacy single-byte encodings" }, { "encodings": [ { "labels": [ "chinese", "csgb2312", "csiso58gb231280", "gb18030", "gb2312", "gb_2312", "gb_2312-80", "gbk", "iso-ir-58", "x-gbk" ], "name": "gb18030" }, { "labels": [ "hz-gb-2312" ], "name": "hz-gb-2312" } ], "heading": "Legacy multi-byte Chinese (simplified) encodings" }, { "encodings": [ { "labels": [ "big5", "big5-hkscs", "cn-big5", "csbig5", "x-x-big5" ], "name": "big5" } ], "heading": "Legacy multi-byte Chinese (traditional) encodings" }, { "encodings": [ { "labels": [ "cseucpkdfmtjapanese", "euc-jp", "x-euc-jp" ], "name": "euc-jp" }, { "labels": [ "csiso2022jp", "iso-2022-jp" ], "name": "iso-2022-jp" }, { "labels": [ "csshiftjis", "ms_kanji", "shift-jis", "shift_jis", "sjis", "windows-31j", "x-sjis" ], "name": "shift_jis" } ], "heading": "Legacy multi-byte Japanese encodings" }, { "encodings": [ { "labels": [ "cseuckr", "csksc56011987", "euc-kr", "iso-ir-149", "korean", "ks_c_5601-1987", "ks_c_5601-1989", "ksc5601", "ksc_5601", "windows-949" ], "name": "euc-kr" } ], "heading": "Legacy multi-byte Korean encodings" }, { "encodings": [ { "labels": [ "csiso2022kr", "iso-2022-cn", "iso-2022-cn-ext", "iso-2022-kr" ], "name": "replacement" }, { "labels": [ "utf-16be" ], "name": "utf-16be" }, { "labels": [ "utf-16", "utf-16le" ], "name": "utf-16le" }, { "labels": [ "x-user-defined" ], "name": "x-user-defined" } ], "heading": "Legacy miscellaneous encodings" } ]; var name_to_encoding = {}; var label_to_encoding = {}; encodings.forEach(function(category) { category['encodings'].forEach(function(encoding) { name_to_encoding[encoding['name']] = encoding; encoding['labels'].forEach(function(label) { label_to_encoding[label] = encoding; }); }); }); // // 5. Indexes // /** * @param {number} pointer The |pointer| to search for. * @param {Array.<?number>|undefined} index The |index| to search within. * @return {?number} The code point corresponding to |pointer| in |index|, * or null if |code point| is not in |index|. */ function indexCodePointFor(pointer, index) { if (!index) return null; return index[pointer] || null; } /** * @param {number} code_point The |code point| to search for. * @param {Array.<?number>} index The |index| to search within. * @return {?number} The first pointer corresponding to |code point| in * |index|, or null if |code point| is not in |index|. */ function indexPointerFor(code_point, index) { var pointer = index.indexOf(code_point); return pointer === -1 ? null : pointer; } /** * @param {string} name Name of the index. * @return {(Array.<number>|Array.<Array.<number>>)} * */ function index(name) { if (!('encoding-indexes' in global)) throw new Error("Indexes missing. Did you forget to include encoding-indexes.js?"); return global['encoding-indexes'][name]; } /** * @param {number} pointer The |pointer| to search for in the gb18030 index. * @return {?number} The code point corresponding to |pointer| in |index|, * or null if |code point| is not in the gb18030 index. */ function indexGB18030CodePointFor(pointer) { if ((pointer > 39419 && pointer < 189000) || (pointer > 1237575)) { return null; } var /** @type {number} */ offset = 0, /** @type {number} */ code_point_offset = 0, /** @type {Array.<Array.<number>>} */ idx = index('gb18030'); var i; for (i = 0; i < idx.length; ++i) { var entry = idx[i]; if (entry[0] <= pointer) { offset = entry[0]; code_point_offset = entry[1]; } else { break; } } return code_point_offset + pointer - offset; } /** * @param {number} code_point The |code point| to locate in the gb18030 index. * @return {number} The first pointer corresponding to |code point| in the * gb18030 index. */ function indexGB18030PointerFor(code_point) { var /** @type {number} */ offset = 0, /** @type {number} */ pointer_offset = 0, /** @type {Array.<Array.<number>>} */ idx = index('gb18030'); var i; for (i = 0; i < idx.length; ++i) { var entry = idx[i]; if (entry[1] <= code_point) { offset = entry[1]; pointer_offset = entry[0]; } else { break; } } return pointer_offset + code_point - offset; } // // 7. API // /** @const */ var DEFAULT_ENCODING = 'utf-8'; // 7.1 Interface TextDecoder /** * @constructor * @param {string=} opt_encoding The label of the encoding; * defaults to 'utf-8'. * @param {{fatal: boolean}=} options */ function TextDecoder(opt_encoding, options) { if (!(this instanceof TextDecoder)) { return new TextDecoder(opt_encoding, options); } opt_encoding = opt_encoding ? String(opt_encoding) : DEFAULT_ENCODING; options = Object(options); /** @private */ this._encoding = getEncoding(opt_encoding); if (this._encoding === null || this._encoding.name === 'replacement') throw new TypeError('Unknown encoding: ' + opt_encoding); if (!this._encoding.getDecoder) throw new Error('Decoder not present. Did you forget to include encoding-indexes.js?'); /** @private @type {boolean} */ this._streaming = false; /** @private @type {boolean} */ this._BOMseen = false; /** @private */ this._decoder = null; /** @private @type {{fatal: boolean}=} */ this._options = { fatal: Boolean(options.fatal) }; if (Object.defineProperty) { Object.defineProperty( this, 'encoding', { get: function() { return this._encoding.name; } }); } else { this.encoding = this._encoding.name; } return this; } // TODO: Issue if input byte stream is offset by decoder // TODO: BOM detection will not work if stream header spans multiple calls // (last N bytes of previous stream may need to be retained?) TextDecoder.prototype = { /** * @param {ArrayBufferView=} opt_view The buffer of bytes to decode. * @param {{stream: boolean}=} options */ decode: function decode(opt_view, options) { if (opt_view && !('buffer' in opt_view && 'byteOffset' in opt_view && 'byteLength' in opt_view)) { throw new TypeError('Expected ArrayBufferView'); } else if (!opt_view) { opt_view = new Uint8Array(0); } options = Object(options); if (!this._streaming) { this._decoder = this._encoding.getDecoder(this._options); this._BOMseen = false; } this._streaming = Boolean(options.stream); var bytes = new Uint8Array(opt_view.buffer, opt_view.byteOffset, opt_view.byteLength); var input_stream = new ByteInputStream(bytes); var output_stream = new CodePointOutputStream(); /** @type {number} */ var code_point; while (input_stream.get() !== EOF_byte) { code_point = this._decoder.decode(input_stream); if (code_point !== null && code_point !== EOF_code_point) { output_stream.emit(code_point); } } if (!this._streaming) { do { code_point = this._decoder.decode(input_stream); if (code_point !== null && code_point !== EOF_code_point) { output_stream.emit(code_point); } } while (code_point !== EOF_code_point && input_stream.get() != EOF_byte); this._decoder = null; } var result = output_stream.string(); if (!this._BOMseen && result.length) { this._BOMseen = true; if (['utf-8', 'utf-16le', 'utf-16be'].indexOf(this.encoding) !== -1 && result.charCodeAt(0) === 0xFEFF) { result = result.substring(1); } } return result; } }; // 7.2 Interface TextEncoder /** * @constructor * @param {string=} opt_encoding The label of the encoding; * defaults to 'utf-8'. * @param {{fatal: boolean}=} options */ function TextEncoder(opt_encoding, options) { if (!(this instanceof TextEncoder)) { return new TextEncoder(opt_encoding, options); } opt_encoding = opt_encoding ? String(opt_encoding) : DEFAULT_ENCODING; options = Object(options); /** @private */ this._encoding = getEncoding(opt_encoding); var allowLegacyEncoding = options.NONSTANDARD_allowLegacyEncoding; var isLegacyEncoding = (this._encoding.name !== 'utf-8' && this._encoding.name !== 'utf-16le' && this._encoding.name !== 'utf-16be'); if (this._encoding === null || (isLegacyEncoding && !allowLegacyEncoding)) throw new TypeError('Unknown encoding: ' + opt_encoding); if (!this._encoding.getEncoder) throw new Error('Encoder not present. Did you forget to include encoding-indexes.js?'); /** @private @type {boolean} */ this._streaming = false; /** @private */ this._encoder = null; /** @private @type {{fatal: boolean}=} */ this._options = { fatal: Boolean(options.fatal) }; if (Object.defineProperty) { Object.defineProperty( this, 'encoding', { get: function() { return this._encoding.name; } }); } else { this.encoding = this._encoding.name; } return this; } TextEncoder.prototype = { /** * @param {string=} opt_string The string to encode. * @param {{stream: boolean}=} options */ encode: function encode(opt_string, options) { opt_string = opt_string ? String(opt_string) : ''; options = Object(options); // TODO: any options? if (!this._streaming) { this._encoder = this._encoding.getEncoder(this._options); } this._streaming = Boolean(options.stream); var bytes = []; var output_stream = new ByteOutputStream(bytes); var input_stream = new CodePointInputStream(opt_string); while (input_stream.get() !== EOF_code_point) { this._encoder.encode(output_stream, input_stream); } if (!this._streaming) { /** @type {number} */ var last_byte; do { last_byte = this._encoder.encode(output_stream, input_stream); } while (last_byte !== EOF_byte); this._encoder = null; } return new Uint8Array(bytes); } }; // // 8. The encoding // // 8.1 utf-8 /** * @constructor * @param {{fatal: boolean}} options */ function UTF8Decoder(options) { var fatal = options.fatal; var /** @type {number} */ utf8_code_point = 0, /** @type {number} */ utf8_bytes_needed = 0, /** @type {number} */ utf8_bytes_seen = 0, /** @type {number} */ utf8_lower_boundary = 0; /** * @param {ByteInputStream} byte_pointer The byte stream to decode. * @return {?number} The next code point decoded, or null if not enough * data exists in the input stream to decode a complete code point. */ this.decode = function(byte_pointer) { var bite = byte_pointer.get(); if (bite === EOF_byte) { if (utf8_bytes_needed !== 0) { return decoderError(fatal); } return EOF_code_point; } byte_pointer.offset(1); if (utf8_bytes_needed === 0) { if (inRange(bite, 0x00, 0x7F)) { return bite; } if (inRange(bite, 0xC2, 0xDF)) { utf8_bytes_needed = 1; utf8_lower_boundary = 0x80; utf8_code_point = bite - 0xC0; } else if (inRange(bite, 0xE0, 0xEF)) { utf8_bytes_needed = 2; utf8_lower_boundary = 0x800; utf8_code_point = bite - 0xE0; } else if (inRange(bite, 0xF0, 0xF4)) { utf8_bytes_needed = 3; utf8_lower_boundary = 0x10000; utf8_code_point = bite - 0xF0; } else { return decoderError(fatal); } utf8_code_point = utf8_code_point * Math.pow(64, utf8_bytes_needed); return null; } if (!inRange(bite, 0x80, 0xBF)) { utf8_code_point = 0; utf8_bytes_needed = 0; utf8_bytes_seen = 0; utf8_lower_boundary = 0; byte_pointer.offset(-1); return decoderError(fatal); } utf8_bytes_seen += 1; utf8_code_point = utf8_code_point + (bite - 0x80) * Math.pow(64, utf8_bytes_needed - utf8_bytes_seen); if (utf8_bytes_seen !== utf8_bytes_needed) { return null; } var code_point = utf8_code_point; var lower_boundary = utf8_lower_boundary; utf8_code_point = 0; utf8_bytes_needed = 0; utf8_bytes_seen = 0; utf8_lower_boundary = 0; if (inRange(code_point, lower_boundary, 0x10FFFF) && !inRange(code_point, 0xD800, 0xDFFF)) { return code_point; } return decoderError(fatal); }; } /** * @constructor * @param {{fatal: boolean}} options */ function UTF8Encoder(options) { var fatal = options.fatal; /** * @param {ByteOutputStream} output_byte_stream Output byte stream. * @param {CodePointInputStream} code_point_pointer Input stream. * @return {number} The last byte emitted. */ this.encode = function(output_byte_stream, code_point_pointer) { /** @type {number} */ var code_point = code_point_pointer.get(); if (code_point === EOF_code_point) { return EOF_byte; } code_point_pointer.offset(1); if (inRange(code_point, 0xD800, 0xDFFF)) { return encoderError(code_point); } if (inRange(code_point, 0x0000, 0x007f)) { return output_byte_stream.emit(code_point); } var count, offset; if (inRange(code_point, 0x0080, 0x07FF)) { count = 1; offset = 0xC0; } else if (inRange(code_point, 0x0800, 0xFFFF)) { count = 2; offset = 0xE0; } else if (inRange(code_point, 0x10000, 0x10FFFF)) { count = 3; offset = 0xF0; } var result = output_byte_stream.emit( div(code_point, Math.pow(64, count)) + offset); while (count > 0) { var temp = div(code_point, Math.pow(64, count - 1)); result = output_byte_stream.emit(0x80 + (temp % 64)); count -= 1; } return result; }; } /** @param {{fatal: boolean}} options */ name_to_encoding['utf-8'].getEncoder = function(options) { return new UTF8Encoder(options); }; /** @param {{fatal: boolean}} options */ name_to_encoding['utf-8'].getDecoder = function(options) { return new UTF8Decoder(options); }; // // 9. Legacy single-byte encodings // /** * @constructor * @param {Array.<number>} index The encoding index. * @param {{fatal: boolean}} options */ function SingleByteDecoder(index, options) { var fatal = options.fatal; /** * @param {ByteInputStream} byte_pointer The byte stream to decode. * @return {?number} The next code point decoded, or null if not enough * data exists in the input stream to decode a complete code point. */ this.decode = function(byte_pointer) { var bite = byte_pointer.get(); if (bite === EOF_byte) { return EOF_code_point; } byte_pointer.offset(1); if (inRange(bite, 0x00, 0x7F)) { return bite; } var code_point = index[bite - 0x80]; if (code_point === null) { return decoderError(fatal); } return code_point; }; } /** * @constructor * @param {Array.<?number>} index The encoding index. * @param {{fatal: boolean}} options */ function SingleByteEncoder(index, options) { var fatal = options.fatal; /** * @param {ByteOutputStream} output_byte_stream Output byte stream. * @param {CodePointInputStream} code_point_pointer Input stream. * @return {number} The last byte emitted. */ this.encode = function(output_byte_stream, code_point_pointer) { var code_point = code_point_pointer.get(); if (code_point === EOF_code_point) { return EOF_byte; } code_point_pointer.offset(1); if (inRange(code_point, 0x0000, 0x007F)) { return output_byte_stream.emit(code_point); } var pointer = indexPointerFor(code_point, index); if (pointer === null) { encoderError(code_point); } return output_byte_stream.emit(pointer + 0x80); }; } (function() { if (!('encoding-indexes' in global)) return; encodings.forEach(function(category) { if (category['heading'] !== 'Legacy single-byte encodings') return; category['encodings'].forEach(function(encoding) { var idx = index(encoding['name']); /** @param {{fatal: boolean}} options */ encoding.getDecoder = function(options) { return new SingleByteDecoder(idx, options); }; /** @param {{fatal: boolean}} options */ encoding.getEncoder = function(options) { return new SingleByteEncoder(idx, options); }; }); }); }()); // // 10. Legacy multi-byte Chinese (simplified) encodings // // 9.1 gb18030 /** * @constructor * @param {{fatal: boolean}} options */ function GB18030Decoder(options) { var fatal = options.fatal; var /** @type {number} */ gb18030_first = 0x00, /** @type {number} */ gb18030_second = 0x00, /** @type {number} */ gb18030_third = 0x00; /** * @param {ByteInputStream} byte_pointer The byte stream to decode. * @return {?number} The next code point decoded, or null if not enough * data exists in the input stream to decode a complete code point. */ this.decode = function(byte_pointer) { var bite = byte_pointer.get(); if (bite === EOF_byte && gb18030_first === 0x00 && gb18030_second === 0x00 && gb18030_third === 0x00) { return EOF_code_point; } if (bite === EOF_byte && (gb18030_first !== 0x00 || gb18030_second !== 0x00 || gb18030_third !== 0x00)) { gb18030_first = 0x00; gb18030_second = 0x00; gb18030_third = 0x00; decoderError(fatal); } byte_pointer.offset(1); var code_point; if (gb18030_third !== 0x00) { code_point = null; if (inRange(bite, 0x30, 0x39)) { code_point = indexGB18030CodePointFor( (((gb18030_first - 0x81) * 10 + (gb18030_second - 0x30)) * 126 + (gb18030_third - 0x81)) * 10 + bite - 0x30); } gb18030_first = 0x00; gb18030_second = 0x00; gb18030_third = 0x00; if (code_point === null) { byte_pointer.offset(-3); return decoderError(fatal); } return code_point; } if (gb18030_second !== 0x00) { if (inRange(bite, 0x81, 0xFE)) { gb18030_third = bite; return null; } byte_pointer.offset(-2); gb18030_first = 0x00; gb18030_second = 0x00; return decoderError(fatal); } if (gb18030_first !== 0x00) { if (inRange(bite, 0x30, 0x39)) { gb18030_second = bite; return null; } var lead = gb18030_first; var pointer = null; gb18030_first = 0x00; var offset = bite < 0x7F ? 0x40 : 0x41; if (inRange(bite, 0x40, 0x7E) || inRange(bite, 0x80, 0xFE)) { pointer = (lead - 0x81) * 190 + (bite - offset); } code_point = pointer === null ? null : indexCodePointFor(pointer, index('gb18030')); if (pointer === null) { byte_pointer.offset(-1); } if (code_point === null) { return decoderError(fatal); } return code_point; } if (inRange(bite, 0x00, 0x7F)) { return bite; } if (bite === 0x80) { return 0x20AC; } if (inRange(bite, 0x81, 0xFE)) { gb18030_first = bite; return null; } return decoderError(fatal); }; } /** * @constructor * @param {{fatal: boolean}} options */ function GB18030Encoder(options) { var fatal = options.fatal; /** * @param {ByteOutputStream} output_byte_stream Output byte stream. * @param {CodePointInputStream} code_point_pointer Input stream. * @return {number} The last byte emitted. */ this.encode = function(output_byte_stream, code_point_pointer) { var code_point = code_point_pointer.get(); if (code_point === EOF_code_point) { return EOF_byte; } code_point_pointer.offset(1); if (inRange(code_point, 0x0000, 0x007F)) { return output_byte_stream.emit(code_point); } var pointer = indexPointerFor(code_point, index('gb18030')); if (pointer !== null) { var lead = div(pointer, 190) + 0x81; var trail = pointer % 190; var offset = trail < 0x3F ? 0x40 : 0x41; return output_byte_stream.emit(lead, trail + offset); } pointer = indexGB18030PointerFor(code_point); var byte1 = div(div(div(pointer, 10), 126), 10); pointer = pointer - byte1 * 10 * 126 * 10; var byte2 = div(div(pointer, 10), 126); pointer = pointer - byte2 * 10 * 126; var byte3 = div(pointer, 10); var byte4 = pointer - byte3 * 10; return output_byte_stream.emit(byte1 + 0x81, byte2 + 0x30, byte3 + 0x81, byte4 + 0x30); }; } /** @param {{fatal: boolean}} options */ name_to_encoding['gb18030'].getEncoder = function(options) { return new GB18030Encoder(options); }; /** @param {{fatal: boolean}} options */ name_to_encoding['gb18030'].getDecoder = function(options) { return new GB18030Decoder(options); }; // 10.2 hz-gb-2312 /** * @constructor * @param {{fatal: boolean}} options */ function HZGB2312Decoder(options) { var fatal = options.fatal; var /** @type {boolean} */ hzgb2312 = false, /** @type {number} */ hzgb2312_lead = 0x00; /** * @param {ByteInputStream} byte_pointer The byte stream to decode. * @return {?number} The next code point decoded, or null if not enough * data exists in the input stream to decode a complete code point. */ this.decode = function(byte_pointer) { var bite = byte_pointer.get(); if (bite === EOF_byte && hzgb2312_lead === 0x00) { return EOF_code_point; } if (bite === EOF_byte && hzgb2312_lead !== 0x00) { hzgb2312_lead = 0x00; return decoderError(fatal); } byte_pointer.offset(1); if (hzgb2312_lead === 0x7E) { hzgb2312_lead = 0x00; if (bite === 0x7B) { hzgb2312 = true; return null; } if (bite === 0x7D) { hzgb2312 = false; return null; } if (bite === 0x7E) { return 0x007E; } if (bite === 0x0A) { return null; } byte_pointer.offset(-1); return decoderError(fatal); } if (hzgb2312_lead !== 0x00) { var lead = hzgb2312_lead; hzgb2312_lead = 0x00; var code_point = null; if (inRange(bite, 0x21, 0x7E)) { code_point = indexCodePointFor((lead - 1) * 190 + (bite + 0x3F), index('gb18030')); } if (bite === 0x0A) { hzgb2312 = false; } if (code_point === null) { return decoderError(fatal); } return code_point; } if (bite === 0x7E) { hzgb2312_lead = 0x7E; return null; } if (hzgb2312) { if (inRange(bite, 0x20, 0x7F)) { hzgb2312_lead = bite; return null; } if (bite === 0x0A) { hzgb2312 = false; } return decoderError(fatal); } if (inRange(bite, 0x00, 0x7F)) { return bite; } return decoderError(fatal); }; } /** * @constructor * @param {{fatal: boolean}} options */ function HZGB2312Encoder(options) { var fatal = options.fatal; /** @type {boolean} */ var hzgb2312 = false; /** * @param {ByteOutputStream} output_byte_stream Output byte stream. * @param {CodePointInputStream} code_point_pointer Input stream. * @return {number} The last byte emitted. */ this.encode = function(output_byte_stream, code_point_pointer) { var code_point = code_point_pointer.get(); if (code_point === EOF_code_point) { return EOF_byte; } code_point_pointer.offset(1); if (inRange(code_point, 0x0000, 0x007F) && hzgb2312) { code_point_pointer.offset(-1); hzgb2312 = false; return output_byte_stream.emit(0x7E, 0x7D); } if (code_point === 0x007E) { return output_byte_stream.emit(0x7E, 0x7E); } if (inRange(code_point, 0x0000, 0x007F)) { return output_byte_stream.emit(code_point); } if (!hzgb2312) { code_point_pointer.offset(-1); hzgb2312 = true; return output_byte_stream.emit(0x7E, 0x7B); } var pointer = indexPointerFor(code_point, index('gb18030')); if (pointer === null) { return encoderError(code_point); } var lead = div(pointer, 190) + 1; var trail = pointer % 190 - 0x3F; if (!inRange(lead, 0x21, 0x7E) || !inRange(trail, 0x21, 0x7E)) { return encoderError(code_point); } return output_byte_stream.emit(lead, trail); }; } /** @param {{fatal: boolean}} options */ name_to_encoding['hz-gb-2312'].getEncoder = function(options) { return new HZGB2312Encoder(options); }; /** @param {{fatal: boolean}} options */ name_to_encoding['hz-gb-2312'].getDecoder = function(options) { return new HZGB2312Decoder(options); }; // // 11. Legacy multi-byte Chinese (traditional) encodings // // 11.1 big5 /** * @constructor * @param {{fatal: boolean}} options */ function Big5Decoder(options) { var fatal = options.fatal; var /** @type {number} */ big5_lead = 0x00, /** @type {?number} */ big5_pending = null; /** * @param {ByteInputStream} byte_pointer The byte steram to decode. * @return {?number} The next code point decoded, or null if not enough * data exists in the input stream to decode a complete code point. */ this.decode = function(byte_pointer) { // NOTE: Hack to support emitting two code points if (big5_pending !== null) { var pending = big5_pending; big5_pending = null; return pending; } var bite = byte_pointer.get(); if (bite === EOF_byte && big5_lead === 0x00) { return EOF_code_point; } if (bite === EOF_byte && big5_lead !== 0x00) { big5_lead = 0x00; return decoderError(fatal); } byte_pointer.offset(1); if (big5_lead !== 0x00) { var lead = big5_lead; var pointer = null; big5_lead = 0x00; var offset = bite < 0x7F ? 0x40 : 0x62; if (inRange(bite, 0x40, 0x7E) || inRange(bite, 0xA1, 0xFE)) { pointer = (lead - 0x81) * 157 + (bite - offset); } if (pointer === 1133) { big5_pending = 0x0304; return 0x00CA; } if (pointer === 1135) { big5_pending = 0x030C; return 0x00CA; } if (pointer === 1164) { big5_pending = 0x0304; return 0x00EA; } if (pointer === 1166) { big5_pending = 0x030C; return 0x00EA; } var code_point = (pointer === null) ? null : indexCodePointFor(pointer, index('big5')); if (pointer === null) { byte_pointer.offset(-1); } if (code_point === null) { return decoderError(fatal); } return code_point; } if (inRange(bite, 0x00, 0x7F)) { return bite; } if (inRange(bite, 0x81, 0xFE)) { big5_lead = bite; return null; } return decoderError(fatal); }; } /** * @constructor * @param {{fatal: boolean}} options */ function Big5Encoder(options) { var fatal = options.fatal; /** * @param {ByteOutputStream} output_byte_stream Output byte stream. * @param {CodePointInputStream} code_point_pointer Input stream. * @return {number} The last byte emitted. */ this.encode = function(output_byte_stream, code_point_pointer) { var code_point = code_point_pointer.get(); if (code_point === EOF_code_point) { return EOF_byte; } code_point_pointer.offset(1); if (inRange(code_point, 0x0000, 0x007F)) { return output_byte_stream.emit(code_point); } var pointer = indexPointerFor(code_point, index('big5')); if (pointer === null) { return encoderError(code_point); } var lead = div(pointer, 157) + 0x81; //if (lead < 0xA1) { // return encoderError(code_point); //} var trail = pointer % 157; var offset = trail < 0x3F ? 0x40 : 0x62; return output_byte_stream.emit(lead, trail + offset); }; } /** @param {{fatal: boolean}} options */ name_to_encoding['big5'].getEncoder = function(options) { return new Big5Encoder(options); }; /** @param {{fatal: boolean}} options */ name_to_encoding['big5'].getDecoder = function(options) { return new Big5Decoder(options); }; // // 12. Legacy multi-byte Japanese encodings // // 12.1 euc.jp /** * @constructor * @param {{fatal: boolean}} options */ function EUCJPDecoder(options) { var fatal = options.fatal; var /** @type {number} */ eucjp_first = 0x00, /** @type {number} */ eucjp_second = 0x00; /** * @param {ByteInputStream} byte_pointer The byte stream to decode. * @return {?number} The next code point decoded, or null if not enough * data exists in the input stream to decode a complete code point. */ this.decode = function(byte_pointer) { var bite = byte_pointer.get(); if (bite === EOF_byte) { if (eucjp_first === 0x00 && eucjp_second === 0x00) { return EOF_code_point; } eucjp_first = 0x00; eucjp_second = 0x00; return decoderError(fatal); } byte_pointer.offset(1); var lead, code_point; if (eucjp_second !== 0x00) { lead = eucjp_second; eucjp_second = 0x00; code_point = null; if (inRange(lead, 0xA1, 0xFE) && inRange(bite, 0xA1, 0xFE)) { code_point = indexCodePointFor((lead - 0xA1) * 94 + bite - 0xA1, index('jis0212')); } if (!inRange(bite, 0xA1, 0xFE)) { byte_pointer.offset(-1); } if (code_point === null) { return decoderError(fatal); } return code_point; } if (eucjp_first === 0x8E && inRange(bite, 0xA1, 0xDF)) { eucjp_first = 0x00; return 0xFF61 + bite - 0xA1; } if (eucjp_first === 0x8F && inRange(bite, 0xA1, 0xFE)) { eucjp_first = 0x00; eucjp_second = bite; return null; } if (eucjp_first !== 0x00) { lead = eucjp_first; eucjp_first = 0x00; code_point = null; if (inRange(lead, 0xA1, 0xFE) && inRange(bite, 0xA1, 0xFE)) { code_point = indexCodePointFor((lead - 0xA1) * 94 + bite - 0xA1, index('jis0208')); } if (!inRange(bite, 0xA1, 0xFE)) { byte_pointer.offset(-1); } if (code_point === null) { return decoderError(fatal); } return code_point; } if (inRange(bite, 0x00, 0x7F)) { return bite; } if (bite === 0x8E || bite === 0x8F || (inRange(bite, 0xA1, 0xFE))) { eucjp_first = bite; return null; } return decoderError(fatal); }; } /** * @constructor * @param {{fatal: boolean}} options */ function EUCJPEncoder(options) { var fatal = options.fatal; /** * @param {ByteOutputStream} output_byte_stream Output byte stream. * @param {CodePointInputStream} code_point_pointer Input stream. * @return {number} The last byte emitted. */ this.encode = function(output_byte_stream, code_point_pointer) { var code_point = code_point_pointer.get(); if (code_point === EOF_code_point) { return EOF_byte; } code_point_pointer.offset(1); if (inRange(code_point, 0x0000, 0x007F)) { return output_byte_stream.emit(code_point); } if (code_point === 0x00A5) { return output_byte_stream.emit(0x5C); } if (code_point === 0x203E) { return output_byte_stream.emit(0x7E); } if (inRange(code_point, 0xFF61, 0xFF9F)) { return output_byte_stream.emit(0x8E, code_point - 0xFF61 + 0xA1); } var pointer = indexPointerFor(code_point, index('jis0208')); if (pointer === null) { return encoderError(code_point); } var lead = div(pointer, 94) + 0xA1; var trail = pointer % 94 + 0xA1; return output_byte_stream.emit(lead, trail); }; } /** @param {{fatal: boolean}} options */ name_to_encoding['euc-jp'].getEncoder = function(options) { return new EUCJPEncoder(options); }; /** @param {{fatal: boolean}} options */ name_to_encoding['euc-jp'].getDecoder = function(options) { return new EUCJPDecoder(options); }; // 12.2 iso-2022-jp /** * @constructor * @param {{fatal: boolean}} options */ function ISO2022JPDecoder(options) { var fatal = options.fatal; /** @enum */ var state = { ASCII: 0, escape_start: 1, escape_middle: 2, escape_final: 3, lead: 4, trail: 5, Katakana: 6 }; var /** @type {number} */ iso2022jp_state = state.ASCII, /** @type {boolean} */ iso2022jp_jis0212 = false, /** @type {number} */ iso2022jp_lead = 0x00; /** * @param {ByteInputStream} byte_pointer The byte stream to decode. * @return {?number} The next code point decoded, or null if not enough * data exists in the input stream to decode a complete code point. */ this.decode = function(byte_pointer) { var bite = byte_pointer.get(); if (bite !== EOF_byte) { byte_pointer.offset(1); } switch (iso2022jp_state) { default: case state.ASCII: if (bite === 0x1B) { iso2022jp_state = state.escape_start; return null; } if (inRange(bite, 0x00, 0x7F)) { return bite; } if (bite === EOF_byte) { return EOF_code_point; } return decoderError(fatal); case state.escape_start: if (bite === 0x24 || bite === 0x28) { iso2022jp_lead = bite; iso2022jp_state = state.escape_middle; return null; } if (bite !== EOF_byte) { byte_pointer.offset(-1); } iso2022jp_state = state.ASCII; return decoderError(fatal); case state.escape_middle: var lead = iso2022jp_lead; iso2022jp_lead = 0x00; if (lead === 0x24 && (bite === 0x40 || bite === 0x42)) { iso2022jp_jis0212 = false; iso2022jp_state = state.lead; return null; } if (lead === 0x24 && bite === 0x28) { iso2022jp_state = state.escape_final; return null; } if (lead === 0x28 && (bite === 0x42 || bite === 0x4A)) { iso2022jp_state = state.ASCII; return null; } if (lead === 0x28 && bite === 0x49) { iso2022jp_state = state.Katakana; return null; } if (bite === EOF_byte) { byte_pointer.offset(-1); } else { byte_pointer.offset(-2); } iso2022jp_state = state.ASCII; return decoderError(fatal); case state.escape_final: if (bite === 0x44) { iso2022jp_jis0212 = true; iso2022jp_state = state.lead; return null; } if (bite === EOF_byte) { byte_pointer.offset(-2); } else { byte_pointer.offset(-3); } iso2022jp_state = state.ASCII; return decoderError(fatal); case state.lead: if (bite === 0x0A) { iso2022jp_state = state.ASCII; return decoderError(fatal, 0x000A); } if (bite === 0x1B) { iso2022jp_state = state.escape_start; return null; } if (bite === EOF_byte) { return EOF_code_point; } iso2022jp_lead = bite; iso2022jp_state = state.trail; return null; case state.trail: iso2022jp_state = state.lead; if (bite === EOF_byte) { return decoderError(fatal); } var code_point = null; var pointer = (iso2022jp_lead - 0x21) * 94 + bite - 0x21; if (inRange(iso2022jp_lead, 0x21, 0x7E) && inRange(bite, 0x21, 0x7E)) { code_point = (iso2022jp_jis0212 === false) ? indexCodePointFor(pointer, index('jis0208')) : indexCodePointFor(pointer, index('jis0212')); } if (code_point === null) { return decoderError(fatal); } return code_point; case state.Katakana: if (bite === 0x1B) { iso2022jp_state = state.escape_start; return null; } if (inRange(bite, 0x21, 0x5F)) { return 0xFF61 + bite - 0x21; } if (bite === EOF_byte) { return EOF_code_point; } return decoderError(fatal); } }; } /** * @constructor * @param {{fatal: boolean}} options */ function ISO2022JPEncoder(options) { var fatal = options.fatal; /** @enum */ var state = { ASCII: 0, lead: 1, Katakana: 2 }; var /** @type {number} */ iso2022jp_state = state.ASCII; /** * @param {ByteOutputStream} output_byte_stream Output byte stream. * @param {CodePointInputStream} code_point_pointer Input stream. * @return {number} The last byte emitted. */ this.encode = function(output_byte_stream, code_point_pointer) { var code_point = code_point_pointer.get(); if (code_point === EOF_code_point) { return EOF_byte; } code_point_pointer.offset(1); if ((inRange(code_point, 0x0000, 0x007F) || code_point === 0x00A5 || code_point === 0x203E) && iso2022jp_state !== state.ASCII) { code_point_pointer.offset(-1); iso2022jp_state = state.ASCII; return output_byte_stream.emit(0x1B, 0x28, 0x42); } if (inRange(code_point, 0x0000, 0x007F)) { return output_byte_stream.emit(code_point); } if (code_point === 0x00A5) { return output_byte_stream.emit(0x5C); } if (code_point === 0x203E) { return output_byte_stream.emit(0x7E); } if (inRange(code_point, 0xFF61, 0xFF9F) && iso2022jp_state !== state.Katakana) { code_point_pointer.offset(-1); iso2022jp_state = state.Katakana; return output_byte_stream.emit(0x1B, 0x28, 0x49); } if (inRange(code_point, 0xFF61, 0xFF9F)) { return output_byte_stream.emit(code_point - 0xFF61 - 0x21); } if (iso2022jp_state !== state.lead) { code_point_pointer.offset(-1); iso2022jp_state = state.lead; return output_byte_stream.emit(0x1B, 0x24, 0x42); } var pointer = indexPointerFor(code_point, index('jis0208')); if (pointer === null) { return encoderError(code_point); } var lead = div(pointer, 94) + 0x21; var trail = pointer % 94 + 0x21; return output_byte_stream.emit(lead, trail); }; } /** @param {{fatal: boolean}} options */ name_to_encoding['iso-2022-jp'].getEncoder = function(options) { return new ISO2022JPEncoder(options); }; /** @param {{fatal: boolean}} options */ name_to_encoding['iso-2022-jp'].getDecoder = function(options) { return new ISO2022JPDecoder(options); }; // 12.3 shift_jis /** * @constructor * @param {{fatal: boolean}} options */ function ShiftJISDecoder(options) { var fatal = options.fatal; var /** @type {number} */ shiftjis_lead = 0x00; /** * @param {ByteInputStream} byte_pointer The byte stream to decode. * @return {?number} The next code point decoded, or null if not enough * data exists in the input stream to decode a complete code point. */ this.decode = function(byte_pointer) { var bite = byte_pointer.get(); if (bite === EOF_byte && shiftjis_lead === 0x00) { return EOF_code_point; } if (bite === EOF_byte && shiftjis_lead !== 0x00) { shiftjis_lead = 0x00; return decoderError(fatal); } byte_pointer.offset(1); if (shiftjis_lead !== 0x00) { var lead = shiftjis_lead; shiftjis_lead = 0x00; if (inRange(bite, 0x40, 0x7E) || inRange(bite, 0x80, 0xFC)) { var offset = (bite < 0x7F) ? 0x40 : 0x41; var lead_offset = (lead < 0xA0) ? 0x81 : 0xC1; var code_point = indexCodePointFor((lead - lead_offset) * 188 + bite - offset, index('jis0208')); if (code_point === null) { return decoderError(fatal); } return code_point; } byte_pointer.offset(-1); return decoderError(fatal); } if (inRange(bite, 0x00, 0x80)) { return bite; } if (inRange(bite, 0xA1, 0xDF)) { return 0xFF61 + bite - 0xA1; } if (inRange(bite, 0x81, 0x9F) || inRange(bite, 0xE0, 0xFC)) { shiftjis_lead = bite; return null; } return decoderError(fatal); }; } /** * @constructor * @param {{fatal: boolean}} options */ function ShiftJISEncoder(options) { var fatal = options.fatal; /** * @param {ByteOutputStream} output_byte_stream Output byte stream. * @param {CodePointInputStream} code_point_pointer Input stream. * @return {number} The last byte emitted. */ this.encode = function(output_byte_stream, code_point_pointer) { var code_point = code_point_pointer.get(); if (code_point === EOF_code_point) { return EOF_byte; } code_point_pointer.offset(1); if (inRange(code_point, 0x0000, 0x0080)) { return output_byte_stream.emit(code_point); } if (code_point === 0x00A5) { return output_byte_stream.emit(0x5C); } if (code_point === 0x203E) { return output_byte_stream.emit(0x7E); } if (inRange(code_point, 0xFF61, 0xFF9F)) { return output_byte_stream.emit(code_point - 0xFF61 + 0xA1); } var pointer = indexPointerFor(code_point, index('jis0208')); if (pointer === null) { return encoderError(code_point); } var lead = div(pointer, 188); var lead_offset = lead < 0x1F ? 0x81 : 0xC1; var trail = pointer % 188; var offset = trail < 0x3F ? 0x40 : 0x41; return output_byte_stream.emit(lead + lead_offset, trail + offset); }; } /** @param {{fatal: boolean}} options */ name_to_encoding['shift_jis'].getEncoder = function(options) { return new ShiftJISEncoder(options); }; /** @param {{fatal: boolean}} options */ name_to_encoding['shift_jis'].getDecoder = function(options) { return new ShiftJISDecoder(options); }; // // 13. Legacy multi-byte Korean encodings // // 13.1 euc-kr /** * @constructor * @param {{fatal: boolean}} options */ function EUCKRDecoder(options) { var fatal = options.fatal; var /** @type {number} */ euckr_lead = 0x00; /** * @param {ByteInputStream} byte_pointer The byte stream to decode. * @return {?number} The next code point decoded, or null if not enough * data exists in the input stream to decode a complete code point. */ this.decode = function(byte_pointer) { var bite = byte_pointer.get(); if (bite === EOF_byte && euckr_lead === 0) { return EOF_code_point; } if (bite === EOF_byte && euckr_lead !== 0) { euckr_lead = 0x00; return decoderError(fatal); } byte_pointer.offset(1); if (euckr_lead !== 0x00) { var lead = euckr_lead; var pointer = null; euckr_lead = 0x00; if (inRange(lead, 0x81, 0xC6)) { var temp = (26 + 26 + 126) * (lead - 0x81); if (inRange(bite, 0x41, 0x5A)) { pointer = temp + bite - 0x41; } else if (inRange(bite, 0x61, 0x7A)) { pointer = temp + 26 + bite - 0x61; } else if (inRange(bite, 0x81, 0xFE)) { pointer = temp + 26 + 26 + bite - 0x81; } } if (inRange(lead, 0xC7, 0xFD) && inRange(bite, 0xA1, 0xFE)) { pointer = (26 + 26 + 126) * (0xC7 - 0x81) + (lead - 0xC7) * 94 + (bite - 0xA1); } var code_point = (pointer === null) ? null : indexCodePointFor(pointer, index('euc-kr')); if (pointer === null) { byte_pointer.offset(-1); } if (code_point === null) { return decoderError(fatal); } return code_point; } if (inRange(bite, 0x00, 0x7F)) { return bite; } if (inRange(bite, 0x81, 0xFD)) { euckr_lead = bite; return null; } return decoderError(fatal); }; } /** * @constructor * @param {{fatal: boolean}} options */ function EUCKREncoder(options) { var fatal = options.fatal; /** * @param {ByteOutputStream} output_byte_stream Output byte stream. * @param {CodePointInputStream} code_point_pointer Input stream. * @return {number} The last byte emitted. */ this.encode = function(output_byte_stream, code_point_pointer) { var code_point = code_point_pointer.get(); if (code_point === EOF_code_point) { return EOF_byte; } code_point_pointer.offset(1); if (inRange(code_point, 0x0000, 0x007F)) { return output_byte_stream.emit(code_point); } var pointer = indexPointerFor(code_point, index('euc-kr')); if (pointer === null) { return encoderError(code_point); } var lead, trail; if (pointer < ((26 + 26 + 126) * (0xC7 - 0x81))) { lead = div(pointer, (26 + 26 + 126)) + 0x81; trail = pointer % (26 + 26 + 126); var offset = trail < 26 ? 0x41 : trail < 26 + 26 ? 0x47 : 0x4D; return output_byte_stream.emit(lead, trail + offset); } pointer = pointer - (26 + 26 + 126) * (0xC7 - 0x81); lead = div(pointer, 94) + 0xC7; trail = pointer % 94 + 0xA1; return output_byte_stream.emit(lead, trail); }; } /** @param {{fatal: boolean}} options */ name_to_encoding['euc-kr'].getEncoder = function(options) { return new EUCKREncoder(options); }; /** @param {{fatal: boolean}} options */ name_to_encoding['euc-kr'].getDecoder = function(options) { return new EUCKRDecoder(options); }; // // 14. Legacy miscellaneous encodings // // 14.1 replacement // Not needed - API throws TypeError // 14.2 utf-16 /** * @constructor * @param {boolean} utf16_be True if big-endian, false if little-endian. * @param {{fatal: boolean}} options */ function UTF16Decoder(utf16_be, options) { var fatal = options.fatal; var /** @type {?number} */ utf16_lead_byte = null, /** @type {?number} */ utf16_lead_surrogate = null; /** * @param {ByteInputStream} byte_pointer The byte stream to decode. * @return {?number} The next code point decoded, or null if not enough * data exists in the input stream to decode a complete code point. */ this.decode = function(byte_pointer) { var bite = byte_pointer.get(); if (bite === EOF_byte && utf16_lead_byte === null && utf16_lead_surrogate === null) { return EOF_code_point; } if (bite === EOF_byte && (utf16_lead_byte !== null || utf16_lead_surrogate !== null)) { return decoderError(fatal); } byte_pointer.offset(1); if (utf16_lead_byte === null) { utf16_lead_byte = bite; return null; } var code_point; if (utf16_be) { code_point = (utf16_lead_byte << 8) + bite; } else { code_point = (bite << 8) + utf16_lead_byte; } utf16_lead_byte = null; if (utf16_lead_surrogate !== null) { var lead_surrogate = utf16_lead_surrogate; utf16_lead_surrogate = null; if (inRange(code_point, 0xDC00, 0xDFFF)) { return 0x10000 + (lead_surrogate - 0xD800) * 0x400 + (code_point - 0xDC00); } byte_pointer.offset(-2); return decoderError(fatal); } if (inRange(code_point, 0xD800, 0xDBFF)) { utf16_lead_surrogate = code_point; return null; } if (inRange(code_point, 0xDC00, 0xDFFF)) { return decoderError(fatal); } return code_point; }; } /** * @constructor * @param {boolean} utf16_be True if big-endian, false if little-endian. * @param {{fatal: boolean}} options */ function UTF16Encoder(utf16_be, options) { var fatal = options.fatal; /** * @param {ByteOutputStream} output_byte_stream Output byte stream. * @param {CodePointInputStream} code_point_pointer Input stream. * @return {number} The last byte emitted. */ this.encode = function(output_byte_stream, code_point_pointer) { /** * @param {number} code_unit * @return {number} last byte emitted */ function convert_to_bytes(code_unit) { var byte1 = code_unit >> 8; var byte2 = code_unit & 0x00FF; if (utf16_be) { return output_byte_stream.emit(byte1, byte2); } return output_byte_stream.emit(byte2, byte1); } var code_point = code_point_pointer.get(); if (code_point === EOF_code_point) { return EOF_byte; } code_point_pointer.offset(1); if (inRange(code_point, 0xD800, 0xDFFF)) { encoderError(code_point); } if (code_point <= 0xFFFF) { return convert_to_bytes(code_point); } var lead = div((code_point - 0x10000), 0x400) + 0xD800; var trail = ((code_point - 0x10000) % 0x400) + 0xDC00; convert_to_bytes(lead); return convert_to_bytes(trail); }; } // 14.3 utf-16be /** @param {{fatal: boolean}} options */ name_to_encoding['utf-16be'].getEncoder = function(options) { return new UTF16Encoder(true, options); }; /** @param {{fatal: boolean}} options */ name_to_encoding['utf-16be'].getDecoder = function(options) { return new UTF16Decoder(true, options); }; // 14.4 utf-16le /** @param {{fatal: boolean}} options */ name_to_encoding['utf-16le'].getEncoder = function(options) { return new UTF16Encoder(false, options); }; /** @param {{fatal: boolean}} options */ name_to_encoding['utf-16le'].getDecoder = function(options) { return new UTF16Decoder(false, options); }; // 14.5 x-user-defined /** * @constructor * @param {{fatal: boolean}} options */ function XUserDefinedDecoder(options) { var fatal = options.fatal; /** * @param {ByteInputStream} byte_pointer The byte stream to decode. * @return {?number} The next code point decoded, or null if not enough * data exists in the input stream to decode a complete code point. */ this.decode = function(byte_pointer) { var bite = byte_pointer.get(); if (bite === EOF_byte) { return EOF_code_point; } byte_pointer.offset(1); if (inRange(bite, 0x00, 0x7F)) { return bite; } return 0xF780 + bite - 0x80; }; } /** * @constructor * @param {{fatal: boolean}} options */ function XUserDefinedEncoder(index, options) { var fatal = options.fatal; /** * @param {ByteOutputStream} output_byte_stream Output byte stream. * @param {CodePointInputStream} code_point_pointer Input stream. * @return {number} The last byte emitted. */ this.encode = function(output_byte_stream, code_point_pointer) { var code_point = code_point_pointer.get(); if (code_point === EOF_code_point) { return EOF_byte; } code_point_pointer.offset(1); if (inRange(code_point, 0x0000, 0x007F)) { return output_byte_stream.emit(code_point); } if (inRange(code_point, 0xF780, 0xF7FF)) { return output_byte_stream.emit(code_point - 0xF780 + 0x80); } encoderError(code_point); }; } /** @param {{fatal: boolean}} options */ name_to_encoding['x-user-defined'].getEncoder = function(options) { return new XUserDefinedEncoder(false, options); }; /** @param {{fatal: boolean}} options */ name_to_encoding['x-user-defined'].getDecoder = function(options) { return new XUserDefinedDecoder(false, options); }; // NOTE: currently unused /** * @param {string} label The encoding label. * @param {ByteInputStream} input_stream The byte stream to test. */ function detectEncoding(label, input_stream) { if (input_stream.match([0xFF, 0xFE])) { input_stream.offset(2); return 'utf-16le'; } if (input_stream.match([0xFE, 0xFF])) { input_stream.offset(2); return 'utf-16be'; } if (input_stream.match([0xEF, 0xBB, 0xBF])) { input_stream.offset(3); return 'utf-8'; } return label; } if (!('TextEncoder' in global)) global['TextEncoder'] = TextEncoder; if (!('TextDecoder' in global)) global['TextDecoder'] = TextDecoder; }(this));
RickEyre/vtt.js-dist
vtt.js
JavaScript
mpl-2.0
138,701
/** * Shopware 5 * Copyright (c) shopware AG * * According to our dual licensing model, this program can be used either * under the terms of the GNU Affero General Public License, version 3, * or under a proprietary license. * * The texts of the GNU Affero General Public License with an additional * permission and of our proprietary license can be found at and * in the LICENSE file you have received along with this program. * * 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 Affero General Public License for more details. * * "Shopware" is a registered trademark of shopware AG. * The licensing of the program under the AGPLv3 does not imply a * trademark license. Therefore any rights, title and interest in * our trademarks remain entirely with us. * * @category Shopware * @package CanceledOrder * @subpackage Store * @version $Id$ * @author shopware AG */ /** * Shopware Store - canceled baskets' articles */ //{block name="backend/canceled_order/store/articles"} Ext.define('Shopware.apps.CanceledOrder.store.Articles', { extend: 'Ext.data.Store', // Do not load data, when not explicitly requested autoLoad: false, model : 'Shopware.apps.CanceledOrder.model.Articles', remoteFilter: true, remoteSort: true, /** * Configure the data communication * @object */ proxy: { type: 'ajax', /** * Configure the url mapping * @object */ api: { read: '{url controller=CanceledOrder action="getArticle"}' }, /** * Configure the data reader * @object */ reader: { type: 'json', root: 'data', totalProperty:'total' } } }); //{/block}
ShopwareHackathon/shopware_search_optimization
themes/Backend/ExtJs/backend/canceled_order/store/articles.js
JavaScript
agpl-3.0
1,931
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace spec\Sylius\Bundle\ResourceBundle\DependencyInjection\Driver; use PhpSpec\ObjectBehavior; use Sylius\Bundle\ResourceBundle\SyliusResourceBundle; use Symfony\Component\DependencyInjection\ContainerBuilder; /** * @author Arnaud Langlade <aRn0D.dev@gmail.com> */ class DatabaseDriverFactorySpec extends ObjectBehavior { function it_is_initializable() { $this->shouldHaveType('Sylius\Bundle\ResourceBundle\DependencyInjection\Driver\DatabaseDriverFactory'); } function it_should_create_a_orm_driver_by_default(ContainerBuilder $container) { $this::get($container, 'prefix', 'resource', 'default') ->shouldhaveType('Sylius\Bundle\ResourceBundle\DependencyInjection\Driver\DoctrineORMDriver'); } function it_should_create_a_odm_driver(ContainerBuilder $container) { $this::get($container, 'prefix', 'resource', 'default', SyliusResourceBundle::DRIVER_DOCTRINE_MONGODB_ODM) ->shouldhaveType('Sylius\Bundle\ResourceBundle\DependencyInjection\Driver\DoctrineODMDriver'); } function it_should_create_a_phpcr_driver(ContainerBuilder $container) { $this::get($container, 'prefix', 'resource', 'default', SyliusResourceBundle::DRIVER_DOCTRINE_PHPCR_ODM) ->shouldhaveType('Sylius\Bundle\ResourceBundle\DependencyInjection\Driver\DoctrinePHPCRDriver'); } }
witalikkowal/Store
vendor/sylius/resource-bundle/spec/DependencyInjection/Driver/DatabaseDriverFactorySpec.php
PHP
mit
1,595
export = function tsd(gulp, plugins) { return plugins.shell.task([ 'tsd reinstall --clean', 'tsd link', 'tsd rebundle' ]); };
ravi-mone/angular2-lab
tools/tasks/tsd.ts
TypeScript
mit
142
FactoryGirl.define do factory :user do sequence :name do |n| "User #{ n }" end sequence :email do |n| "user#{ n }@user.com" end end end
idify/directory-service
vendor/mailboxer/spec/factories/user.rb
Ruby
mit
168
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ /** * Expose `Emitter`. */ module.exports = Emitter; /** * Initialize a new `Emitter`. * * @api public */ function Emitter(obj) { if (obj) return mixin(obj); }; /** * Mixin the emitter properties. * * @param {Object} obj * @return {Object} * @api private */ function mixin(obj) { for (var key in Emitter.prototype) { obj[key] = Emitter.prototype[key]; } return obj; } /** * Listen on the given `event` with `fn`. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.on = Emitter.prototype.addEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; (this._callbacks['$' + event] = this._callbacks['$' + event] || []) .push(fn); return this; }; /** * Adds an `event` listener that will be invoked a single * time then automatically removed. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.once = function(event, fn){ function on() { this.off(event, on); fn.apply(this, arguments); } on.fn = fn; this.on(event, on); return this; }; /** * Remove the given callback for `event` or all * registered callbacks. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; if (0 == arguments.length) { this._callbacks = {}; return this; } var callbacks = this._callbacks['$' + event]; if (!callbacks) return this; if (1 == arguments.length) { delete this._callbacks['$' + event]; return this; } var cb; for (var i = 0; i < callbacks.length; i++) { cb = callbacks[i]; if (cb === fn || cb.fn === fn) { callbacks.splice(i, 1); break; } } return this; }; /** * Emit `event` with the given args. * * @param {String} event * @param {Mixed} ... * @return {Emitter} */ Emitter.prototype.emit = function(event){ this._callbacks = this._callbacks || {}; var args = [].slice.call(arguments, 1) , callbacks = this._callbacks['$' + event]; if (callbacks) { callbacks = callbacks.slice(0); for (var i = 0, len = callbacks.length; i < len; ++i) { callbacks[i].apply(this, args); } } return this; }; /** * Return array of callbacks for `event`. * * @param {String} event * @return {Array} * @api public */ Emitter.prototype.listeners = function(event){ this._callbacks = this._callbacks || {}; return this._callbacks['$' + event] || []; }; /** * Check if this emitter has `event` handlers. * * @param {String} event * @return {Boolean} * @api public */ Emitter.prototype.hasListeners = function(event){ return !! this.listeners(event).length; }; },{}],2:[function(require,module,exports){ /*! * domready (c) Dustin Diaz 2012 - License MIT */ !function (name, definition) { if (typeof module != 'undefined') module.exports = definition() else if (typeof define == 'function' && typeof define.amd == 'object') {} else this[name] = definition() }('domready', function (ready) { var fns = [], fn, f = false , doc = document , testEl = doc.documentElement , hack = testEl.doScroll , domContentLoaded = 'DOMContentLoaded' , addEventListener = 'addEventListener' , onreadystatechange = 'onreadystatechange' , readyState = 'readyState' , loadedRgx = hack ? /^loaded|^c/ : /^loaded|c/ , loaded = loadedRgx.test(doc[readyState]) function flush(f) { loaded = 1 while (f = fns.shift()) f() } doc[addEventListener] && doc[addEventListener](domContentLoaded, fn = function () { doc.removeEventListener(domContentLoaded, fn, f) flush() }, f) hack && doc.attachEvent(onreadystatechange, fn = function () { if (/^c/.test(doc[readyState])) { doc.detachEvent(onreadystatechange, fn) flush() } }) return (ready = hack ? function (fn) { self != top ? loaded ? fn() : fns.push(fn) : function () { try { testEl.doScroll('left') } catch (e) { return setTimeout(function() { ready(fn) }, 50) } fn() }() } : function (fn) { loaded ? fn() : fns.push(fn) }) }) },{}],3:[function(require,module,exports){ (function (global){ /*! JSON v3.3.2 | http://bestiejs.github.io/json3 | Copyright 2012-2014, Kit Cambridge | http://kit.mit-license.org */ ;(function () { var isLoader = typeof define === "function" && define.amd; var objectTypes = { "function": true, "object": true }; var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports; var root = objectTypes[typeof window] && window || this, freeGlobal = freeExports && objectTypes[typeof module] && module && !module.nodeType && typeof global == "object" && global; if (freeGlobal && (freeGlobal["global"] === freeGlobal || freeGlobal["window"] === freeGlobal || freeGlobal["self"] === freeGlobal)) { root = freeGlobal; } function runInContext(context, exports) { context || (context = root["Object"]()); exports || (exports = root["Object"]()); var Number = context["Number"] || root["Number"], String = context["String"] || root["String"], Object = context["Object"] || root["Object"], Date = context["Date"] || root["Date"], SyntaxError = context["SyntaxError"] || root["SyntaxError"], TypeError = context["TypeError"] || root["TypeError"], Math = context["Math"] || root["Math"], nativeJSON = context["JSON"] || root["JSON"]; if (typeof nativeJSON == "object" && nativeJSON) { exports.stringify = nativeJSON.stringify; exports.parse = nativeJSON.parse; } var objectProto = Object.prototype, getClass = objectProto.toString, isProperty, forEach, undef; var isExtended = new Date(-3509827334573292); try { isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 && isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708; } catch (exception) {} function has(name) { if (has[name] !== undef) { return has[name]; } var isSupported; if (name == "bug-string-char-index") { isSupported = "a"[0] != "a"; } else if (name == "json") { isSupported = has("json-stringify") && has("json-parse"); } else { var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}'; if (name == "json-stringify") { var stringify = exports.stringify, stringifySupported = typeof stringify == "function" && isExtended; if (stringifySupported) { (value = function () { return 1; }).toJSON = value; try { stringifySupported = stringify(0) === "0" && stringify(new Number()) === "0" && stringify(new String()) == '""' && stringify(getClass) === undef && stringify(undef) === undef && stringify() === undef && stringify(value) === "1" && stringify([value]) == "[1]" && stringify([undef]) == "[null]" && stringify(null) == "null" && stringify([undef, getClass, null]) == "[null,null,null]" && stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized && stringify(null, value) === "1" && stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" && stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' && stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' && stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' && stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"'; } catch (exception) { stringifySupported = false; } } isSupported = stringifySupported; } if (name == "json-parse") { var parse = exports.parse; if (typeof parse == "function") { try { if (parse("0") === 0 && !parse(false)) { value = parse(serialized); var parseSupported = value["a"].length == 5 && value["a"][0] === 1; if (parseSupported) { try { parseSupported = !parse('"\t"'); } catch (exception) {} if (parseSupported) { try { parseSupported = parse("01") !== 1; } catch (exception) {} } if (parseSupported) { try { parseSupported = parse("1.") !== 1; } catch (exception) {} } } } } catch (exception) { parseSupported = false; } } isSupported = parseSupported; } } return has[name] = !!isSupported; } if (!has("json")) { var functionClass = "[object Function]", dateClass = "[object Date]", numberClass = "[object Number]", stringClass = "[object String]", arrayClass = "[object Array]", booleanClass = "[object Boolean]"; var charIndexBuggy = has("bug-string-char-index"); if (!isExtended) { var floor = Math.floor; var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]; var getDay = function (year, month) { return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400); }; } if (!(isProperty = objectProto.hasOwnProperty)) { isProperty = function (property) { var members = {}, constructor; if ((members.__proto__ = null, members.__proto__ = { "toString": 1 }, members).toString != getClass) { isProperty = function (property) { var original = this.__proto__, result = property in (this.__proto__ = null, this); this.__proto__ = original; return result; }; } else { constructor = members.constructor; isProperty = function (property) { var parent = (this.constructor || constructor).prototype; return property in this && !(property in parent && this[property] === parent[property]); }; } members = null; return isProperty.call(this, property); }; } forEach = function (object, callback) { var size = 0, Properties, members, property; (Properties = function () { this.valueOf = 0; }).prototype.valueOf = 0; members = new Properties(); for (property in members) { if (isProperty.call(members, property)) { size++; } } Properties = members = null; if (!size) { members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"]; forEach = function (object, callback) { var isFunction = getClass.call(object) == functionClass, property, length; var hasProperty = !isFunction && typeof object.constructor != "function" && objectTypes[typeof object.hasOwnProperty] && object.hasOwnProperty || isProperty; for (property in object) { if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) { callback(property); } } for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property)); }; } else if (size == 2) { forEach = function (object, callback) { var members = {}, isFunction = getClass.call(object) == functionClass, property; for (property in object) { if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) { callback(property); } } }; } else { forEach = function (object, callback) { var isFunction = getClass.call(object) == functionClass, property, isConstructor; for (property in object) { if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) { callback(property); } } if (isConstructor || isProperty.call(object, (property = "constructor"))) { callback(property); } }; } return forEach(object, callback); }; if (!has("json-stringify")) { var Escapes = { 92: "\\\\", 34: '\\"', 8: "\\b", 12: "\\f", 10: "\\n", 13: "\\r", 9: "\\t" }; var leadingZeroes = "000000"; var toPaddedString = function (width, value) { return (leadingZeroes + (value || 0)).slice(-width); }; var unicodePrefix = "\\u00"; var quote = function (value) { var result = '"', index = 0, length = value.length, useCharIndex = !charIndexBuggy || length > 10; var symbols = useCharIndex && (charIndexBuggy ? value.split("") : value); for (; index < length; index++) { var charCode = value.charCodeAt(index); switch (charCode) { case 8: case 9: case 10: case 12: case 13: case 34: case 92: result += Escapes[charCode]; break; default: if (charCode < 32) { result += unicodePrefix + toPaddedString(2, charCode.toString(16)); break; } result += useCharIndex ? symbols[index] : value.charAt(index); } } return result + '"'; }; var serialize = function (property, object, callback, properties, whitespace, indentation, stack) { var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result; try { value = object[property]; } catch (exception) {} if (typeof value == "object" && value) { className = getClass.call(value); if (className == dateClass && !isProperty.call(value, "toJSON")) { if (value > -1 / 0 && value < 1 / 0) { if (getDay) { date = floor(value / 864e5); for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++); for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++); date = 1 + date - getDay(year, month); time = (value % 864e5 + 864e5) % 864e5; hours = floor(time / 36e5) % 24; minutes = floor(time / 6e4) % 60; seconds = floor(time / 1e3) % 60; milliseconds = time % 1e3; } else { year = value.getUTCFullYear(); month = value.getUTCMonth(); date = value.getUTCDate(); hours = value.getUTCHours(); minutes = value.getUTCMinutes(); seconds = value.getUTCSeconds(); milliseconds = value.getUTCMilliseconds(); } value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) + "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) + "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) + "." + toPaddedString(3, milliseconds) + "Z"; } else { value = null; } } else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) { value = value.toJSON(property); } } if (callback) { value = callback.call(object, property, value); } if (value === null) { return "null"; } className = getClass.call(value); if (className == booleanClass) { return "" + value; } else if (className == numberClass) { return value > -1 / 0 && value < 1 / 0 ? "" + value : "null"; } else if (className == stringClass) { return quote("" + value); } if (typeof value == "object") { for (length = stack.length; length--;) { if (stack[length] === value) { throw TypeError(); } } stack.push(value); results = []; prefix = indentation; indentation += whitespace; if (className == arrayClass) { for (index = 0, length = value.length; index < length; index++) { element = serialize(index, value, callback, properties, whitespace, indentation, stack); results.push(element === undef ? "null" : element); } result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]"; } else { forEach(properties || value, function (property) { var element = serialize(property, value, callback, properties, whitespace, indentation, stack); if (element !== undef) { results.push(quote(property) + ":" + (whitespace ? " " : "") + element); } }); result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}"; } stack.pop(); return result; } }; exports.stringify = function (source, filter, width) { var whitespace, callback, properties, className; if (objectTypes[typeof filter] && filter) { if ((className = getClass.call(filter)) == functionClass) { callback = filter; } else if (className == arrayClass) { properties = {}; for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1)); } } if (width) { if ((className = getClass.call(width)) == numberClass) { if ((width -= width % 1) > 0) { for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " "); } } else if (className == stringClass) { whitespace = width.length <= 10 ? width : width.slice(0, 10); } } return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []); }; } if (!has("json-parse")) { var fromCharCode = String.fromCharCode; var Unescapes = { 92: "\\", 34: '"', 47: "/", 98: "\b", 116: "\t", 110: "\n", 102: "\f", 114: "\r" }; var Index, Source; var abort = function () { Index = Source = null; throw SyntaxError(); }; var lex = function () { var source = Source, length = source.length, value, begin, position, isSigned, charCode; while (Index < length) { charCode = source.charCodeAt(Index); switch (charCode) { case 9: case 10: case 13: case 32: Index++; break; case 123: case 125: case 91: case 93: case 58: case 44: value = charIndexBuggy ? source.charAt(Index) : source[Index]; Index++; return value; case 34: for (value = "@", Index++; Index < length;) { charCode = source.charCodeAt(Index); if (charCode < 32) { abort(); } else if (charCode == 92) { charCode = source.charCodeAt(++Index); switch (charCode) { case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114: value += Unescapes[charCode]; Index++; break; case 117: begin = ++Index; for (position = Index + 4; Index < position; Index++) { charCode = source.charCodeAt(Index); if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) { abort(); } } value += fromCharCode("0x" + source.slice(begin, Index)); break; default: abort(); } } else { if (charCode == 34) { break; } charCode = source.charCodeAt(Index); begin = Index; while (charCode >= 32 && charCode != 92 && charCode != 34) { charCode = source.charCodeAt(++Index); } value += source.slice(begin, Index); } } if (source.charCodeAt(Index) == 34) { Index++; return value; } abort(); default: begin = Index; if (charCode == 45) { isSigned = true; charCode = source.charCodeAt(++Index); } if (charCode >= 48 && charCode <= 57) { if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) { abort(); } isSigned = false; for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++); if (source.charCodeAt(Index) == 46) { position = ++Index; for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++); if (position == Index) { abort(); } Index = position; } charCode = source.charCodeAt(Index); if (charCode == 101 || charCode == 69) { charCode = source.charCodeAt(++Index); if (charCode == 43 || charCode == 45) { Index++; } for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++); if (position == Index) { abort(); } Index = position; } return +source.slice(begin, Index); } if (isSigned) { abort(); } if (source.slice(Index, Index + 4) == "true") { Index += 4; return true; } else if (source.slice(Index, Index + 5) == "false") { Index += 5; return false; } else if (source.slice(Index, Index + 4) == "null") { Index += 4; return null; } abort(); } } return "$"; }; var get = function (value) { var results, hasMembers; if (value == "$") { abort(); } if (typeof value == "string") { if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") { return value.slice(1); } if (value == "[") { results = []; for (;; hasMembers || (hasMembers = true)) { value = lex(); if (value == "]") { break; } if (hasMembers) { if (value == ",") { value = lex(); if (value == "]") { abort(); } } else { abort(); } } if (value == ",") { abort(); } results.push(get(value)); } return results; } else if (value == "{") { results = {}; for (;; hasMembers || (hasMembers = true)) { value = lex(); if (value == "}") { break; } if (hasMembers) { if (value == ",") { value = lex(); if (value == "}") { abort(); } } else { abort(); } } if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") { abort(); } results[value.slice(1)] = get(lex()); } return results; } abort(); } return value; }; var update = function (source, property, callback) { var element = walk(source, property, callback); if (element === undef) { delete source[property]; } else { source[property] = element; } }; var walk = function (source, property, callback) { var value = source[property], length; if (typeof value == "object" && value) { if (getClass.call(value) == arrayClass) { for (length = value.length; length--;) { update(value, length, callback); } } else { forEach(value, function (property) { update(value, property, callback); }); } } return callback.call(source, property, value); }; exports.parse = function (source, callback) { var result, value; Index = 0; Source = "" + source; result = get(lex()); if (lex() != "$") { abort(); } Index = Source = null; return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result; }; } } exports["runInContext"] = runInContext; return exports; } if (freeExports && !isLoader) { runInContext(root, freeExports); } else { var nativeJSON = root.JSON, previousJSON = root["JSON3"], isRestored = false; var JSON3 = runInContext(root, (root["JSON3"] = { "noConflict": function () { if (!isRestored) { isRestored = true; root.JSON = nativeJSON; root["JSON3"] = previousJSON; nativeJSON = previousJSON = null; } return JSON3; } })); root.JSON = { "parse": JSON3.parse, "stringify": JSON3.stringify }; } if (false) { (function(){ return JSON3; }); } }).call(this); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],4:[function(require,module,exports){ /** * Reduce `arr` with `fn`. * * @param {Array} arr * @param {Function} fn * @param {Mixed} initial * * TODO: combatible error handling? */ module.exports = function(arr, fn, initial){ var idx = 0; var len = arr.length; var curr = arguments.length == 3 ? initial : arr[idx++]; while (idx < len) { curr = fn.call(null, curr, arr[idx], ++idx, arr); } return curr; }; },{}],5:[function(require,module,exports){ /** * Copyright (c) 2011-2014 Felix Gnass * Licensed under the MIT license * http://spin.js.org/ * * Example: var opts = { lines: 12 , length: 7 , width: 5 , radius: 10 , scale: 1.0 , corners: 1 , color: '#000' , opacity: 1/4 , rotate: 0 , direction: 1 , speed: 1 , trail: 100 , fps: 20 , zIndex: 2e9 , className: 'spinner' , top: '50%' , left: '50%' , shadow: false , hwaccel: false , position: 'absolute' } var target = document.getElementById('foo') var spinner = new Spinner(opts).spin(target) */ ;(function (root, factory) { /* CommonJS */ if (typeof module == 'object' && module.exports) module.exports = factory() /* AMD module */ else if (typeof define == 'function' && define.amd) {} /* Browser global */ else root.Spinner = factory() }(this, function () { "use strict" var prefixes = ['webkit', 'Moz', 'ms', 'O'] /* Vendor prefixes */ , animations = {} /* Animation rules keyed by their name */ , useCssAnimations /* Whether to use CSS animations or setTimeout */ , sheet /* A stylesheet to hold the @keyframe or VML rules. */ /** * Utility function to create elements. If no tag name is given, * a DIV is created. Optionally properties can be passed. */ function createEl (tag, prop) { var el = document.createElement(tag || 'div') , n for (n in prop) el[n] = prop[n] return el } /** * Appends children and returns the parent. */ function ins (parent /* child1, child2, ...*/) { for (var i = 1, n = arguments.length; i < n; i++) { parent.appendChild(arguments[i]) } return parent } /** * Creates an opacity keyframe animation rule and returns its name. * Since most mobile Webkits have timing issues with animation-delay, * we create separate rules for each line/segment. */ function addAnimation (alpha, trail, i, lines) { var name = ['opacity', trail, ~~(alpha * 100), i, lines].join('-') , start = 0.01 + i/lines * 100 , z = Math.max(1 - (1-alpha) / trail * (100-start), alpha) , prefix = useCssAnimations.substring(0, useCssAnimations.indexOf('Animation')).toLowerCase() , pre = prefix && '-' + prefix + '-' || '' if (!animations[name]) { sheet.insertRule( '@' + pre + 'keyframes ' + name + '{' + '0%{opacity:' + z + '}' + start + '%{opacity:' + alpha + '}' + (start+0.01) + '%{opacity:1}' + (start+trail) % 100 + '%{opacity:' + alpha + '}' + '100%{opacity:' + z + '}' + '}', sheet.cssRules.length) animations[name] = 1 } return name } /** * Tries various vendor prefixes and returns the first supported property. */ function vendor (el, prop) { var s = el.style , pp , i prop = prop.charAt(0).toUpperCase() + prop.slice(1) if (s[prop] !== undefined) return prop for (i = 0; i < prefixes.length; i++) { pp = prefixes[i]+prop if (s[pp] !== undefined) return pp } } /** * Sets multiple style properties at once. */ function css (el, prop) { for (var n in prop) { el.style[vendor(el, n) || n] = prop[n] } return el } /** * Fills in default values. */ function merge (obj) { for (var i = 1; i < arguments.length; i++) { var def = arguments[i] for (var n in def) { if (obj[n] === undefined) obj[n] = def[n] } } return obj } /** * Returns the line color from the given string or array. */ function getColor (color, idx) { return typeof color == 'string' ? color : color[idx % color.length] } var defaults = { lines: 12 , length: 7 , width: 5 , radius: 10 , scale: 1.0 , corners: 1 , color: '#000' , opacity: 1/4 , rotate: 0 , direction: 1 , speed: 1 , trail: 100 , fps: 20 , zIndex: 2e9 , className: 'spinner' , top: '50%' , left: '50%' , shadow: false , hwaccel: false , position: 'absolute' } /** The constructor */ function Spinner (o) { this.opts = merge(o || {}, Spinner.defaults, defaults) } Spinner.defaults = {} merge(Spinner.prototype, { /** * Adds the spinner to the given target element. If this instance is already * spinning, it is automatically removed from its previous target b calling * stop() internally. */ spin: function (target) { this.stop() var self = this , o = self.opts , el = self.el = createEl(null, {className: o.className}) css(el, { position: o.position , width: 0 , zIndex: o.zIndex , left: o.left , top: o.top }) if (target) { target.insertBefore(el, target.firstChild || null) } el.setAttribute('role', 'progressbar') self.lines(el, self.opts) if (!useCssAnimations) { var i = 0 , start = (o.lines - 1) * (1 - o.direction) / 2 , alpha , fps = o.fps , f = fps / o.speed , ostep = (1 - o.opacity) / (f * o.trail / 100) , astep = f / o.lines ;(function anim () { i++ for (var j = 0; j < o.lines; j++) { alpha = Math.max(1 - (i + (o.lines - j) * astep) % f * ostep, o.opacity) self.opacity(el, j * o.direction + start, alpha, o) } self.timeout = self.el && setTimeout(anim, ~~(1000 / fps)) })() } return self } /** * Stops and removes the Spinner. */ , stop: function () { var el = this.el if (el) { clearTimeout(this.timeout) if (el.parentNode) el.parentNode.removeChild(el) this.el = undefined } return this } /** * Internal method that draws the individual lines. Will be overwritten * in VML fallback mode below. */ , lines: function (el, o) { var i = 0 , start = (o.lines - 1) * (1 - o.direction) / 2 , seg function fill (color, shadow) { return css(createEl(), { position: 'absolute' , width: o.scale * (o.length + o.width) + 'px' , height: o.scale * o.width + 'px' , background: color , boxShadow: shadow , transformOrigin: 'left' , transform: 'rotate(' + ~~(360/o.lines*i + o.rotate) + 'deg) translate(' + o.scale*o.radius + 'px' + ',0)' , borderRadius: (o.corners * o.scale * o.width >> 1) + 'px' }) } for (; i < o.lines; i++) { seg = css(createEl(), { position: 'absolute' , top: 1 + ~(o.scale * o.width / 2) + 'px' , transform: o.hwaccel ? 'translate3d(0,0,0)' : '' , opacity: o.opacity , animation: useCssAnimations && addAnimation(o.opacity, o.trail, start + i * o.direction, o.lines) + ' ' + 1 / o.speed + 's linear infinite' }) if (o.shadow) ins(seg, css(fill('#000', '0 0 4px #000'), {top: '2px'})) ins(el, ins(seg, fill(getColor(o.color, i), '0 0 1px rgba(0,0,0,.1)'))) } return el } /** * Internal method that adjusts the opacity of a single line. * Will be overwritten in VML fallback mode below. */ , opacity: function (el, i, val) { if (i < el.childNodes.length) el.childNodes[i].style.opacity = val } }) function initVML () { /* Utility function to create a VML tag */ function vml (tag, attr) { return createEl('<' + tag + ' xmlns="urn:schemas-microsoft.com:vml" class="spin-vml">', attr) } sheet.addRule('.spin-vml', 'behavior:url(#default#VML)') Spinner.prototype.lines = function (el, o) { var r = o.scale * (o.length + o.width) , s = o.scale * 2 * r function grp () { return css( vml('group', { coordsize: s + ' ' + s , coordorigin: -r + ' ' + -r }) , { width: s, height: s } ) } var margin = -(o.width + o.length) * o.scale * 2 + 'px' , g = css(grp(), {position: 'absolute', top: margin, left: margin}) , i function seg (i, dx, filter) { ins( g , ins( css(grp(), {rotation: 360 / o.lines * i + 'deg', left: ~~dx}) , ins( css( vml('roundrect', {arcsize: o.corners}) , { width: r , height: o.scale * o.width , left: o.scale * o.radius , top: -o.scale * o.width >> 1 , filter: filter } ) , vml('fill', {color: getColor(o.color, i), opacity: o.opacity}) , vml('stroke', {opacity: 0}) ) ) ) } if (o.shadow) for (i = 1; i <= o.lines; i++) { seg(i, -2, 'progid:DXImageTransform.Microsoft.Blur(pixelradius=2,makeshadow=1,shadowopacity=.3)') } for (i = 1; i <= o.lines; i++) seg(i) return ins(el, g) } Spinner.prototype.opacity = function (el, i, val, o) { var c = el.firstChild o = o.shadow && o.lines || 0 if (c && i + o < c.childNodes.length) { c = c.childNodes[i + o]; c = c && c.firstChild; c = c && c.firstChild if (c) c.opacity = val } } } if (typeof document !== 'undefined') { sheet = (function () { var el = createEl('style', {type : 'text/css'}) ins(document.getElementsByTagName('head')[0], el) return el.sheet || el.styleSheet }()) var probe = css(createEl('group'), {behavior: 'url(#default#VML)'}) if (!vendor(probe, 'transform') && probe.adj) initVML() else useCssAnimations = vendor(probe, 'animation') } return Spinner })); },{}],6:[function(require,module,exports){ /** * Module dependencies. */ var Emitter = require('emitter'); var reduce = require('reduce'); var requestBase = require('./request-base'); var isObject = require('./is-object'); /** * Root reference for iframes. */ var root; if (typeof window !== 'undefined') { root = window; } else if (typeof self !== 'undefined') { root = self; } else { root = this; } /** * Noop. */ function noop(){}; /** * Check if `obj` is a host object, * we don't want to serialize these :) * * TODO: future proof, move to compoent land * * @param {Object} obj * @return {Boolean} * @api private */ function isHost(obj) { var str = {}.toString.call(obj); switch (str) { case '[object File]': case '[object Blob]': case '[object FormData]': return true; default: return false; } } /** * Expose `request`. */ var request = module.exports = require('./request').bind(null, Request); /** * Determine XHR. */ request.getXHR = function () { if (root.XMLHttpRequest && (!root.location || 'file:' != root.location.protocol || !root.ActiveXObject)) { return new XMLHttpRequest; } else { try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) {} try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {} try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {} try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) {} } return false; }; /** * Removes leading and trailing whitespace, added to support IE. * * @param {String} s * @return {String} * @api private */ var trim = ''.trim ? function(s) { return s.trim(); } : function(s) { return s.replace(/(^\s*|\s*$)/g, ''); }; /** * Serialize the given `obj`. * * @param {Object} obj * @return {String} * @api private */ function serialize(obj) { if (!isObject(obj)) return obj; var pairs = []; for (var key in obj) { if (null != obj[key]) { pushEncodedKeyValuePair(pairs, key, obj[key]); } } return pairs.join('&'); } /** * Helps 'serialize' with serializing arrays. * Mutates the pairs array. * * @param {Array} pairs * @param {String} key * @param {Mixed} val */ function pushEncodedKeyValuePair(pairs, key, val) { if (Array.isArray(val)) { return val.forEach(function(v) { pushEncodedKeyValuePair(pairs, key, v); }); } pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(val)); } /** * Expose serialization method. */ request.serializeObject = serialize; /** * Parse the given x-www-form-urlencoded `str`. * * @param {String} str * @return {Object} * @api private */ function parseString(str) { var obj = {}; var pairs = str.split('&'); var parts; var pair; for (var i = 0, len = pairs.length; i < len; ++i) { pair = pairs[i]; parts = pair.split('='); obj[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]); } return obj; } /** * Expose parser. */ request.parseString = parseString; /** * Default MIME type map. * * superagent.types.xml = 'application/xml'; * */ request.types = { html: 'text/html', json: 'application/json', xml: 'application/xml', urlencoded: 'application/x-www-form-urlencoded', 'form': 'application/x-www-form-urlencoded', 'form-data': 'application/x-www-form-urlencoded' }; /** * Default serialization map. * * superagent.serialize['application/xml'] = function(obj){ * return 'generated xml here'; * }; * */ request.serialize = { 'application/x-www-form-urlencoded': serialize, 'application/json': JSON.stringify }; /** * Default parsers. * * superagent.parse['application/xml'] = function(str){ * return { object parsed from str }; * }; * */ request.parse = { 'application/x-www-form-urlencoded': parseString, 'application/json': JSON.parse }; /** * Parse the given header `str` into * an object containing the mapped fields. * * @param {String} str * @return {Object} * @api private */ function parseHeader(str) { var lines = str.split(/\r?\n/); var fields = {}; var index; var line; var field; var val; lines.pop(); for (var i = 0, len = lines.length; i < len; ++i) { line = lines[i]; index = line.indexOf(':'); field = line.slice(0, index).toLowerCase(); val = trim(line.slice(index + 1)); fields[field] = val; } return fields; } /** * Check if `mime` is json or has +json structured syntax suffix. * * @param {String} mime * @return {Boolean} * @api private */ function isJSON(mime) { return /[\/+]json\b/.test(mime); } /** * Return the mime type for the given `str`. * * @param {String} str * @return {String} * @api private */ function type(str){ return str.split(/ *; */).shift(); }; /** * Return header field parameters. * * @param {String} str * @return {Object} * @api private */ function params(str){ return reduce(str.split(/ *; */), function(obj, str){ var parts = str.split(/ *= */) , key = parts.shift() , val = parts.shift(); if (key && val) obj[key] = val; return obj; }, {}); }; /** * Initialize a new `Response` with the given `xhr`. * * - set flags (.ok, .error, etc) * - parse header * * Examples: * * Aliasing `superagent` as `request` is nice: * * request = superagent; * * We can use the promise-like API, or pass callbacks: * * request.get('/').end(function(res){}); * request.get('/', function(res){}); * * Sending data can be chained: * * request * .post('/user') * .send({ name: 'tj' }) * .end(function(res){}); * * Or passed to `.send()`: * * request * .post('/user') * .send({ name: 'tj' }, function(res){}); * * Or passed to `.post()`: * * request * .post('/user', { name: 'tj' }) * .end(function(res){}); * * Or further reduced to a single call for simple cases: * * request * .post('/user', { name: 'tj' }, function(res){}); * * @param {XMLHTTPRequest} xhr * @param {Object} options * @api private */ function Response(req, options) { options = options || {}; this.req = req; this.xhr = this.req.xhr; this.text = ((this.req.method !='HEAD' && (this.xhr.responseType === '' || this.xhr.responseType === 'text')) || typeof this.xhr.responseType === 'undefined') ? this.xhr.responseText : null; this.statusText = this.req.xhr.statusText; this.setStatusProperties(this.xhr.status); this.header = this.headers = parseHeader(this.xhr.getAllResponseHeaders()); this.header['content-type'] = this.xhr.getResponseHeader('content-type'); this.setHeaderProperties(this.header); this.body = this.req.method != 'HEAD' ? this.parseBody(this.text ? this.text : this.xhr.response) : null; } /** * Get case-insensitive `field` value. * * @param {String} field * @return {String} * @api public */ Response.prototype.get = function(field){ return this.header[field.toLowerCase()]; }; /** * Set header related properties: * * - `.type` the content type without params * * A response of "Content-Type: text/plain; charset=utf-8" * will provide you with a `.type` of "text/plain". * * @param {Object} header * @api private */ Response.prototype.setHeaderProperties = function(header){ var ct = this.header['content-type'] || ''; this.type = type(ct); var obj = params(ct); for (var key in obj) this[key] = obj[key]; }; /** * Parse the given body `str`. * * Used for auto-parsing of bodies. Parsers * are defined on the `superagent.parse` object. * * @param {String} str * @return {Mixed} * @api private */ Response.prototype.parseBody = function(str){ var parse = request.parse[this.type]; if (!parse && isJSON(this.type)) { parse = request.parse['application/json']; } return parse && str && (str.length || str instanceof Object) ? parse(str) : null; }; /** * Set flags such as `.ok` based on `status`. * * For example a 2xx response will give you a `.ok` of __true__ * whereas 5xx will be __false__ and `.error` will be __true__. The * `.clientError` and `.serverError` are also available to be more * specific, and `.statusType` is the class of error ranging from 1..5 * sometimes useful for mapping respond colors etc. * * "sugar" properties are also defined for common cases. Currently providing: * * - .noContent * - .badRequest * - .unauthorized * - .notAcceptable * - .notFound * * @param {Number} status * @api private */ Response.prototype.setStatusProperties = function(status){ if (status === 1223) { status = 204; } var type = status / 100 | 0; this.status = this.statusCode = status; this.statusType = type; this.info = 1 == type; this.ok = 2 == type; this.clientError = 4 == type; this.serverError = 5 == type; this.error = (4 == type || 5 == type) ? this.toError() : false; this.accepted = 202 == status; this.noContent = 204 == status; this.badRequest = 400 == status; this.unauthorized = 401 == status; this.notAcceptable = 406 == status; this.notFound = 404 == status; this.forbidden = 403 == status; }; /** * Return an `Error` representative of this response. * * @return {Error} * @api public */ Response.prototype.toError = function(){ var req = this.req; var method = req.method; var url = req.url; var msg = 'cannot ' + method + ' ' + url + ' (' + this.status + ')'; var err = new Error(msg); err.status = this.status; err.method = method; err.url = url; return err; }; /** * Expose `Response`. */ request.Response = Response; /** * Initialize a new `Request` with the given `method` and `url`. * * @param {String} method * @param {String} url * @api public */ function Request(method, url) { var self = this; this._query = this._query || []; this.method = method; this.url = url; this.header = {}; this._header = {}; this.on('end', function(){ var err = null; var res = null; try { res = new Response(self); } catch(e) { err = new Error('Parser is unable to parse the response'); err.parse = true; err.original = e; err.rawResponse = self.xhr && self.xhr.responseText ? self.xhr.responseText : null; err.statusCode = self.xhr && self.xhr.status ? self.xhr.status : null; return self.callback(err); } self.emit('response', res); if (err) { return self.callback(err, res); } if (res.status >= 200 && res.status < 300) { return self.callback(err, res); } var new_err = new Error(res.statusText || 'Unsuccessful HTTP response'); new_err.original = err; new_err.response = res; new_err.status = res.status; self.callback(new_err, res); }); } /** * Mixin `Emitter` and `requestBase`. */ Emitter(Request.prototype); for (var key in requestBase) { Request.prototype[key] = requestBase[key]; } /** * Abort the request, and clear potential timeout. * * @return {Request} * @api public */ Request.prototype.abort = function(){ if (this.aborted) return; this.aborted = true; this.xhr.abort(); this.clearTimeout(); this.emit('abort'); return this; }; /** * Set Content-Type to `type`, mapping values from `request.types`. * * Examples: * * superagent.types.xml = 'application/xml'; * * request.post('/') * .type('xml') * .send(xmlstring) * .end(callback); * * request.post('/') * .type('application/xml') * .send(xmlstring) * .end(callback); * * @param {String} type * @return {Request} for chaining * @api public */ Request.prototype.type = function(type){ this.set('Content-Type', request.types[type] || type); return this; }; /** * Set responseType to `val`. Presently valid responseTypes are 'blob' and * 'arraybuffer'. * * Examples: * * req.get('/') * .responseType('blob') * .end(callback); * * @param {String} val * @return {Request} for chaining * @api public */ Request.prototype.responseType = function(val){ this._responseType = val; return this; }; /** * Set Accept to `type`, mapping values from `request.types`. * * Examples: * * superagent.types.json = 'application/json'; * * request.get('/agent') * .accept('json') * .end(callback); * * request.get('/agent') * .accept('application/json') * .end(callback); * * @param {String} accept * @return {Request} for chaining * @api public */ Request.prototype.accept = function(type){ this.set('Accept', request.types[type] || type); return this; }; /** * Set Authorization field value with `user` and `pass`. * * @param {String} user * @param {String} pass * @param {Object} options with 'type' property 'auto' or 'basic' (default 'basic') * @return {Request} for chaining * @api public */ Request.prototype.auth = function(user, pass, options){ if (!options) { options = { type: 'basic' } } switch (options.type) { case 'basic': var str = btoa(user + ':' + pass); this.set('Authorization', 'Basic ' + str); break; case 'auto': this.username = user; this.password = pass; break; } return this; }; /** * Add query-string `val`. * * Examples: * * request.get('/shoes') * .query('size=10') * .query({ color: 'blue' }) * * @param {Object|String} val * @return {Request} for chaining * @api public */ Request.prototype.query = function(val){ if ('string' != typeof val) val = serialize(val); if (val) this._query.push(val); return this; }; /** * Queue the given `file` as an attachment to the specified `field`, * with optional `filename`. * * ``` js * request.post('/upload') * .attach(new Blob(['<a id="a"><b id="b">hey!</b></a>'], { type: "text/html"})) * .end(callback); * ``` * * @param {String} field * @param {Blob|File} file * @param {String} filename * @return {Request} for chaining * @api public */ Request.prototype.attach = function(field, file, filename){ this._getFormData().append(field, file, filename || file.name); return this; }; Request.prototype._getFormData = function(){ if (!this._formData) { this._formData = new root.FormData(); } return this._formData; }; /** * Send `data` as the request body, defaulting the `.type()` to "json" when * an object is given. * * Examples: * * * request.post('/user') * .type('json') * .send('{"name":"tj"}') * .end(callback) * * * request.post('/user') * .send({ name: 'tj' }) * .end(callback) * * * request.post('/user') * .type('form') * .send('name=tj') * .end(callback) * * * request.post('/user') * .type('form') * .send({ name: 'tj' }) * .end(callback) * * * request.post('/user') * .send('name=tobi') * .send('species=ferret') * .end(callback) * * @param {String|Object} data * @return {Request} for chaining * @api public */ Request.prototype.send = function(data){ var obj = isObject(data); var type = this._header['content-type']; if (obj && isObject(this._data)) { for (var key in data) { this._data[key] = data[key]; } } else if ('string' == typeof data) { if (!type) this.type('form'); type = this._header['content-type']; if ('application/x-www-form-urlencoded' == type) { this._data = this._data ? this._data + '&' + data : data; } else { this._data = (this._data || '') + data; } } else { this._data = data; } if (!obj || isHost(data)) return this; if (!type) this.type('json'); return this; }; /** * @deprecated */ Response.prototype.parse = function serialize(fn){ if (root.console) { console.warn("Client-side parse() method has been renamed to serialize(). This method is not compatible with superagent v2.0"); } this.serialize(fn); return this; }; Response.prototype.serialize = function serialize(fn){ this._parser = fn; return this; }; /** * Invoke the callback with `err` and `res` * and handle arity check. * * @param {Error} err * @param {Response} res * @api private */ Request.prototype.callback = function(err, res){ var fn = this._callback; this.clearTimeout(); fn(err, res); }; /** * Invoke callback with x-domain error. * * @api private */ Request.prototype.crossDomainError = function(){ var err = new Error('Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.'); err.crossDomain = true; err.status = this.status; err.method = this.method; err.url = this.url; this.callback(err); }; /** * Invoke callback with timeout error. * * @api private */ Request.prototype.timeoutError = function(){ var timeout = this._timeout; var err = new Error('timeout of ' + timeout + 'ms exceeded'); err.timeout = timeout; this.callback(err); }; /** * Enable transmission of cookies with x-domain requests. * * Note that for this to work the origin must not be * using "Access-Control-Allow-Origin" with a wildcard, * and also must set "Access-Control-Allow-Credentials" * to "true". * * @api public */ Request.prototype.withCredentials = function(){ this._withCredentials = true; return this; }; /** * Initiate request, invoking callback `fn(res)` * with an instanceof `Response`. * * @param {Function} fn * @return {Request} for chaining * @api public */ Request.prototype.end = function(fn){ var self = this; var xhr = this.xhr = request.getXHR(); var query = this._query.join('&'); var timeout = this._timeout; var data = this._formData || this._data; this._callback = fn || noop; xhr.onreadystatechange = function(){ if (4 != xhr.readyState) return; var status; try { status = xhr.status } catch(e) { status = 0; } if (0 == status) { if (self.timedout) return self.timeoutError(); if (self.aborted) return; return self.crossDomainError(); } self.emit('end'); }; var handleProgress = function(e){ if (e.total > 0) { e.percent = e.loaded / e.total * 100; } e.direction = 'download'; self.emit('progress', e); }; if (this.hasListeners('progress')) { xhr.onprogress = handleProgress; } try { if (xhr.upload && this.hasListeners('progress')) { xhr.upload.onprogress = handleProgress; } } catch(e) { } if (timeout && !this._timer) { this._timer = setTimeout(function(){ self.timedout = true; self.abort(); }, timeout); } if (query) { query = request.serializeObject(query); this.url += ~this.url.indexOf('?') ? '&' + query : '?' + query; } if (this.username && this.password) { xhr.open(this.method, this.url, true, this.username, this.password); } else { xhr.open(this.method, this.url, true); } if (this._withCredentials) xhr.withCredentials = true; if ('GET' != this.method && 'HEAD' != this.method && 'string' != typeof data && !isHost(data)) { var contentType = this._header['content-type']; var serialize = this._parser || request.serialize[contentType ? contentType.split(';')[0] : '']; if (!serialize && isJSON(contentType)) serialize = request.serialize['application/json']; if (serialize) data = serialize(data); } for (var field in this.header) { if (null == this.header[field]) continue; xhr.setRequestHeader(field, this.header[field]); } if (this._responseType) { xhr.responseType = this._responseType; } this.emit('request', this); xhr.send(typeof data !== 'undefined' ? data : null); return this; }; /** * Expose `Request`. */ request.Request = Request; /** * GET `url` with optional callback `fn(res)`. * * @param {String} url * @param {Mixed|Function} data or fn * @param {Function} fn * @return {Request} * @api public */ request.get = function(url, data, fn){ var req = request('GET', url); if ('function' == typeof data) fn = data, data = null; if (data) req.query(data); if (fn) req.end(fn); return req; }; /** * HEAD `url` with optional callback `fn(res)`. * * @param {String} url * @param {Mixed|Function} data or fn * @param {Function} fn * @return {Request} * @api public */ request.head = function(url, data, fn){ var req = request('HEAD', url); if ('function' == typeof data) fn = data, data = null; if (data) req.send(data); if (fn) req.end(fn); return req; }; /** * DELETE `url` with optional callback `fn(res)`. * * @param {String} url * @param {Function} fn * @return {Request} * @api public */ function del(url, fn){ var req = request('DELETE', url); if (fn) req.end(fn); return req; }; request['del'] = del; request['delete'] = del; /** * PATCH `url` with optional `data` and callback `fn(res)`. * * @param {String} url * @param {Mixed} data * @param {Function} fn * @return {Request} * @api public */ request.patch = function(url, data, fn){ var req = request('PATCH', url); if ('function' == typeof data) fn = data, data = null; if (data) req.send(data); if (fn) req.end(fn); return req; }; /** * POST `url` with optional `data` and callback `fn(res)`. * * @param {String} url * @param {Mixed} data * @param {Function} fn * @return {Request} * @api public */ request.post = function(url, data, fn){ var req = request('POST', url); if ('function' == typeof data) fn = data, data = null; if (data) req.send(data); if (fn) req.end(fn); return req; }; /** * PUT `url` with optional `data` and callback `fn(res)`. * * @param {String} url * @param {Mixed|Function} data or fn * @param {Function} fn * @return {Request} * @api public */ request.put = function(url, data, fn){ var req = request('PUT', url); if ('function' == typeof data) fn = data, data = null; if (data) req.send(data); if (fn) req.end(fn); return req; }; },{"./is-object":7,"./request":9,"./request-base":8,"emitter":1,"reduce":4}],7:[function(require,module,exports){ /** * Check if `obj` is an object. * * @param {Object} obj * @return {Boolean} * @api private */ function isObject(obj) { return null != obj && 'object' == typeof obj; } module.exports = isObject; },{}],8:[function(require,module,exports){ /** * Module of mixed-in functions shared between node and client code */ var isObject = require('./is-object'); /** * Clear previous timeout. * * @return {Request} for chaining * @api public */ exports.clearTimeout = function _clearTimeout(){ this._timeout = 0; clearTimeout(this._timer); return this; }; /** * Force given parser * * Sets the body parser no matter type. * * @param {Function} * @api public */ exports.parse = function parse(fn){ this._parser = fn; return this; }; /** * Set timeout to `ms`. * * @param {Number} ms * @return {Request} for chaining * @api public */ exports.timeout = function timeout(ms){ this._timeout = ms; return this; }; /** * Faux promise support * * @param {Function} fulfill * @param {Function} reject * @return {Request} */ exports.then = function then(fulfill, reject) { return this.end(function(err, res) { err ? reject(err) : fulfill(res); }); } /** * Allow for extension */ exports.use = function use(fn) { fn(this); return this; } /** * Get request header `field`. * Case-insensitive. * * @param {String} field * @return {String} * @api public */ exports.get = function(field){ return this._header[field.toLowerCase()]; }; /** * Get case-insensitive header `field` value. * This is a deprecated internal API. Use `.get(field)` instead. * * (getHeader is no longer used internally by the superagent code base) * * @param {String} field * @return {String} * @api private * @deprecated */ exports.getHeader = exports.get; /** * Set header `field` to `val`, or multiple fields with one object. * Case-insensitive. * * Examples: * * req.get('/') * .set('Accept', 'application/json') * .set('X-API-Key', 'foobar') * .end(callback); * * req.get('/') * .set({ Accept: 'application/json', 'X-API-Key': 'foobar' }) * .end(callback); * * @param {String|Object} field * @param {String} val * @return {Request} for chaining * @api public */ exports.set = function(field, val){ if (isObject(field)) { for (var key in field) { this.set(key, field[key]); } return this; } this._header[field.toLowerCase()] = val; this.header[field] = val; return this; }; /** * Remove header `field`. * Case-insensitive. * * Example: * * req.get('/') * .unset('User-Agent') * .end(callback); * * @param {String} field */ exports.unset = function(field){ delete this._header[field.toLowerCase()]; delete this.header[field]; return this; }; /** * Write the field `name` and `val` for "multipart/form-data" * request bodies. * * ``` js * request.post('/upload') * .field('foo', 'bar') * .end(callback); * ``` * * @param {String} name * @param {String|Blob|File|Buffer|fs.ReadStream} val * @return {Request} for chaining * @api public */ exports.field = function(name, val) { this._getFormData().append(name, val); return this; }; },{"./is-object":7}],9:[function(require,module,exports){ /** * Issue a request: * * Examples: * * request('GET', '/users').end(callback) * request('/users').end(callback) * request('/users', callback) * * @param {String} method * @param {String|Function} url or callback * @return {Request} * @api public */ function request(RequestConstructor, method, url) { if ('function' == typeof url) { return new RequestConstructor('GET', method).end(url); } if (2 == arguments.length) { return new RequestConstructor('GET', method); } return new RequestConstructor(method, url); } module.exports = request; },{}],10:[function(require,module,exports){ var Keen = require("./index"), each = require("./utils/each"); module.exports = function(){ var loaded = window['Keen'] || null, cached = window['_' + 'Keen'] || null, clients, ready; if (loaded && cached) { clients = cached['clients'] || {}, ready = cached['ready'] || []; each(clients, function(client, id){ each(Keen.prototype, function(method, key){ loaded.prototype[key] = method; }); each(["Query", "Request", "Dataset", "Dataviz"], function(name){ loaded[name] = (Keen[name]) ? Keen[name] : function(){}; }); if (client._config) { client.configure.call(client, client._config); } if (client._setGlobalProperties) { each(client._setGlobalProperties, function(fn){ client.setGlobalProperties.apply(client, fn); }); } if (client._addEvent) { each(client._addEvent, function(obj){ client.addEvent.apply(client, obj); }); } var callback = client._on || []; if (client._on) { each(client._on, function(obj){ client.on.apply(client, obj); }); client.trigger('ready'); } each(["_config", "_setGlobalProperties", "_addEvent", "_on"], function(name){ if (client[name]) { client[name] = undefined; try{ delete client[name]; } catch(e){} } }); }); each(ready, function(cb, i){ Keen.once("ready", cb); }); } window['_' + 'Keen'] = undefined; try { delete window['_' + 'Keen'] } catch(e) {} }; },{"./index":18,"./utils/each":31}],11:[function(require,module,exports){ module.exports = function(){ return "undefined" == typeof window ? "server" : "browser"; }; },{}],12:[function(require,module,exports){ var each = require('../utils/each'), json = require('../utils/json-shim'); module.exports = function(params){ var query = []; each(params, function(value, key){ if ('string' !== typeof value) { value = json.stringify(value); } query.push(key + '=' + encodeURIComponent(value)); }); return '?' + query.join('&'); }; },{"../utils/each":31,"../utils/json-shim":34}],13:[function(require,module,exports){ module.exports = function(){ return new Date().getTimezoneOffset() * -60; }; },{}],14:[function(require,module,exports){ module.exports = function(){ if ("undefined" !== typeof window) { if (navigator.userAgent.indexOf('MSIE') !== -1 || navigator.appVersion.indexOf('Trident/') > 0) { return 2000; } } return 16000; }; },{}],15:[function(require,module,exports){ module.exports = function() { var root = "undefined" == typeof window ? this : window; if (root.XMLHttpRequest && ("file:" != root.location.protocol || !root.ActiveXObject)) { return new XMLHttpRequest; } else { try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch(e) {} try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch(e) {} try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {} } return false; }; },{}],16:[function(require,module,exports){ module.exports = function(err, res, callback) { var cb = callback || function() {}; if (res && !res.ok) { var is_err = res.body && res.body.error_code; err = new Error(is_err ? res.body.message : 'Unknown error occurred'); err.code = is_err ? res.body.error_code : 'UnknownError'; } if (err) { cb(err, null); } else { cb(null, res.body); } return; }; },{}],17:[function(require,module,exports){ var superagent = require('superagent'); var each = require('../utils/each'), getXHR = require('./get-xhr-object'); module.exports = function(type, opts){ return function(request) { var __super__ = request.constructor.prototype.end; if ( typeof window === 'undefined' ) return; request.requestType = request.requestType || {}; request.requestType['type'] = type; request.requestType['options'] = request.requestType['options'] || { async: true, success: { responseText: '{ "created": true }', status: 201 }, error: { responseText: '{ "error_code": "ERROR", "message": "Request failed" }', status: 404 } }; if (opts) { if ( typeof opts.async === 'boolean' ) { request.requestType['options'].async = opts.async; } if ( opts.success ) { extend(request.requestType['options'].success, opts.success); } if ( opts.error ) { extend(request.requestType['options'].error, opts.error); } } request.end = function(fn){ var self = this, reqType = (this.requestType) ? this.requestType['type'] : 'xhr', query, timeout; if ( ('GET' !== self['method'] || reqType === 'xhr' ) && self.requestType['options'].async ) { __super__.call(self, fn); return; } query = self._query.join('&'); timeout = self._timeout; self._callback = fn || noop; if (timeout && !self._timer) { self._timer = setTimeout(function(){ abortRequest.call(self); }, timeout); } if (query) { query = superagent.serializeObject(query); self.url += ~self.url.indexOf('?') ? '&' + query : '?' + query; } self.emit('request', self); if ( !self.requestType['options'].async ) { sendXhrSync.call(self); } else if ( reqType === 'jsonp' ) { sendJsonp.call(self); } else if ( reqType === 'beacon' ) { sendBeacon.call(self); } return self; }; return request; }; }; function sendXhrSync(){ var xhr = getXHR(); if (xhr) { xhr.open('GET', this.url, false); xhr.send(null); } return this; } function sendJsonp(){ var self = this, timestamp = new Date().getTime(), script = document.createElement('script'), parent = document.getElementsByTagName('head')[0], callbackName = 'keenJSONPCallback', loaded = false; callbackName += timestamp; while (callbackName in window) { callbackName += 'a'; } window[callbackName] = function(response) { if (loaded === true) return; loaded = true; handleSuccess.call(self, response); cleanup(); }; script.src = self.url + '&jsonp=' + callbackName; parent.appendChild(script); script.onreadystatechange = function() { if (loaded === false && self.readyState === 'loaded') { loaded = true; handleError.call(self); cleanup(); } }; script.onerror = function() { if (loaded === false) { loaded = true; handleError.call(self); cleanup(); } }; function cleanup(){ window[callbackName] = undefined; try { delete window[callbackName]; } catch(e){} parent.removeChild(script); } } function sendBeacon(){ var self = this, img = document.createElement('img'), loaded = false; img.onload = function() { loaded = true; if ('naturalHeight' in this) { if (this.naturalHeight + this.naturalWidth === 0) { this.onerror(); return; } } else if (this.width + this.height === 0) { this.onerror(); return; } handleSuccess.call(self); }; img.onerror = function() { loaded = true; handleError.call(self); }; img.src = self.url + '&c=clv1'; } function handleSuccess(res){ var opts = this.requestType['options']['success'], response = ''; xhrShim.call(this, opts); if (res) { try { response = JSON.stringify(res); } catch(e) {} } else { response = opts['responseText']; } this.xhr.responseText = response; this.xhr.status = opts['status']; this.emit('end'); } function handleError(){ var opts = this.requestType['options']['error']; xhrShim.call(this, opts); this.xhr.responseText = opts['responseText']; this.xhr.status = opts['status']; this.emit('end'); } function abortRequest(){ this.aborted = true; this.clearTimeout(); this.emit('abort'); } function xhrShim(opts){ this.xhr = { getAllResponseHeaders: function(){ return ''; }, getResponseHeader: function(){ return 'application/json'; }, responseText: opts['responseText'], status: opts['status'] }; return this; } },{"../utils/each":31,"./get-xhr-object":15,"superagent":6}],18:[function(require,module,exports){ var root = 'undefined' !== typeof window ? window : this; var previous_Keen = root.Keen; var Emitter = require('./utils/emitter-shim'); function Keen(config) { this.configure(config || {}); Keen.trigger('client', this); } Keen.debug = false; Keen.enabled = true; Keen.loaded = true; Keen.version = '3.4.1'; Emitter(Keen); Emitter(Keen.prototype); Keen.prototype.configure = function(cfg){ var config = cfg || {}; if (config['host']) { config['host'].replace(/.*?:\/\//g, ''); } if (config.protocol && config.protocol === 'auto') { config['protocol'] = location.protocol.replace(/:/g, ''); } this.config = { projectId : config.projectId, writeKey : config.writeKey, readKey : config.readKey, masterKey : config.masterKey, requestType : config.requestType || 'jsonp', host : config['host'] || 'api.keen.io/3.0', protocol : config['protocol'] || 'https', globalProperties: null }; if (Keen.debug) { this.on('error', Keen.log); } this.trigger('ready'); }; Keen.prototype.projectId = function(str){ if (!arguments.length) return this.config.projectId; this.config.projectId = (str ? String(str) : null); return this; }; Keen.prototype.masterKey = function(str){ if (!arguments.length) return this.config.masterKey; this.config.masterKey = (str ? String(str) : null); return this; }; Keen.prototype.readKey = function(str){ if (!arguments.length) return this.config.readKey; this.config.readKey = (str ? String(str) : null); return this; }; Keen.prototype.writeKey = function(str){ if (!arguments.length) return this.config.writeKey; this.config.writeKey = (str ? String(str) : null); return this; }; Keen.prototype.url = function(path){ if (!this.projectId()) { this.trigger('error', 'Client is missing projectId property'); return; } return this.config.protocol + '://' + this.config.host + '/projects/' + this.projectId() + path; }; Keen.log = function(message) { if (Keen.debug && typeof console == 'object') { console.log('[Keen IO]', message); } }; Keen.noConflict = function(){ root.Keen = previous_Keen; return Keen; }; Keen.ready = function(fn){ if (Keen.loaded) { fn(); } else { Keen.once('ready', fn); } }; module.exports = Keen; },{"./utils/emitter-shim":32}],19:[function(require,module,exports){ var json = require('../utils/json-shim'); var request = require('superagent'); var Keen = require('../index'); var base64 = require('../utils/base64'), each = require('../utils/each'), getContext = require('../helpers/get-context'), getQueryString = require('../helpers/get-query-string'), getUrlMaxLength = require('../helpers/get-url-max-length'), getXHR = require('../helpers/get-xhr-object'), requestTypes = require('../helpers/superagent-request-types'), responseHandler = require('../helpers/superagent-handle-response'); module.exports = function(collection, payload, callback, async) { var self = this, urlBase = this.url('/events/' + encodeURIComponent(collection)), reqType = this.config.requestType, data = {}, cb = callback, isAsync, getUrl; isAsync = ('boolean' === typeof async) ? async : true; if (!Keen.enabled) { handleValidationError.call(self, 'Keen.enabled = false'); return; } if (!self.projectId()) { handleValidationError.call(self, 'Missing projectId property'); return; } if (!self.writeKey()) { handleValidationError.call(self, 'Missing writeKey property'); return; } if (!collection || typeof collection !== 'string') { handleValidationError.call(self, 'Collection name must be a string'); return; } if (self.config.globalProperties) { data = self.config.globalProperties(collection); } each(payload, function(value, key){ data[key] = value; }); if ( !getXHR() && 'xhr' === reqType ) { reqType = 'jsonp'; } if ( 'xhr' !== reqType || !isAsync ) { getUrl = prepareGetRequest.call(self, urlBase, data); } if ( getUrl && getContext() === 'browser' ) { request .get(getUrl) .use(requestTypes(reqType, { async: isAsync })) .end(handleResponse); } else if ( getXHR() || getContext() === 'server' ) { request .post(urlBase) .set('Content-Type', 'application/json') .set('Authorization', self.writeKey()) .send(data) .end(handleResponse); } else { self.trigger('error', 'Request not sent: URL length exceeds current browser limit, and XHR (POST) is not supported.'); } function handleResponse(err, res){ responseHandler(err, res, cb); cb = callback = null; } function handleValidationError(msg){ var err = 'Event not recorded: ' + msg; self.trigger('error', err); if (cb) { cb.call(self, err, null); cb = callback = null; } } return; }; function prepareGetRequest(url, data){ url += getQueryString({ api_key : this.writeKey(), data : base64.encode( json.stringify(data) ), modified : new Date().getTime() }); return ( url.length < getUrlMaxLength() ) ? url : false; } },{"../helpers/get-context":11,"../helpers/get-query-string":12,"../helpers/get-url-max-length":14,"../helpers/get-xhr-object":15,"../helpers/superagent-handle-response":16,"../helpers/superagent-request-types":17,"../index":18,"../utils/base64":29,"../utils/each":31,"../utils/json-shim":34,"superagent":6}],20:[function(require,module,exports){ var Keen = require('../index'); var request = require('superagent'); var each = require('../utils/each'), getContext = require('../helpers/get-context'), getXHR = require('../helpers/get-xhr-object'), requestTypes = require('../helpers/superagent-request-types'), responseHandler = require('../helpers/superagent-handle-response'); module.exports = function(payload, callback) { var self = this, urlBase = this.url('/events'), data = {}, cb = callback; if (!Keen.enabled) { handleValidationError.call(self, 'Keen.enabled = false'); return; } if (!self.projectId()) { handleValidationError.call(self, 'Missing projectId property'); return; } if (!self.writeKey()) { handleValidationError.call(self, 'Missing writeKey property'); return; } if (arguments.length > 2) { handleValidationError.call(self, 'Incorrect arguments provided to #addEvents method'); return; } if (typeof payload !== 'object' || payload instanceof Array) { handleValidationError.call(self, 'Request payload must be an object'); return; } if (self.config.globalProperties) { each(payload, function(events, collection){ each(events, function(body, index){ var base = self.config.globalProperties(collection); each(body, function(value, key){ base[key] = value; }); data[collection].push(base); }); }); } else { data = payload; } if ( getXHR() || getContext() === 'server' ) { request .post(urlBase) .set('Content-Type', 'application/json') .set('Authorization', self.writeKey()) .send(data) .end(function(err, res){ responseHandler(err, res, cb); cb = callback = null; }); } else { self.trigger('error', 'Events not recorded: XHR support is required for batch upload'); } function handleValidationError(msg){ var err = 'Events not recorded: ' + msg; self.trigger('error', err); if (cb) { cb.call(self, err, null); cb = callback = null; } } return; }; },{"../helpers/get-context":11,"../helpers/get-xhr-object":15,"../helpers/superagent-handle-response":16,"../helpers/superagent-request-types":17,"../index":18,"../utils/each":31,"superagent":6}],21:[function(require,module,exports){ var request = require('superagent'); var getQueryString = require('../helpers/get-query-string'), handleResponse = require('../helpers/superagent-handle-response'), requestTypes = require('../helpers/superagent-request-types'); module.exports = function(url, params, api_key, callback){ var reqType = this.config.requestType, data = params || {}; if (reqType === 'beacon') { reqType = 'jsonp'; } data['api_key'] = data['api_key'] || api_key; request .get(url+getQueryString(data)) .use(requestTypes(reqType)) .end(function(err, res){ handleResponse(err, res, callback); callback = null; }); }; },{"../helpers/get-query-string":12,"../helpers/superagent-handle-response":16,"../helpers/superagent-request-types":17,"superagent":6}],22:[function(require,module,exports){ var request = require('superagent'); var handleResponse = require('../helpers/superagent-handle-response'); module.exports = function(url, data, api_key, callback){ request .post(url) .set('Content-Type', 'application/json') .set('Authorization', api_key) .send(data || {}) .end(function(err, res) { handleResponse(err, res, callback); callback = null; }); }; },{"../helpers/superagent-handle-response":16,"superagent":6}],23:[function(require,module,exports){ var Request = require("../request"); module.exports = function(query, callback) { var queries = [], cb = callback, request; if (!this.config.projectId || !this.config.projectId.length) { handleConfigError.call(this, 'Missing projectId property'); } if (!this.config.readKey || !this.config.readKey.length) { handleConfigError.call(this, 'Missing readKey property'); } function handleConfigError(msg){ var err = 'Query not sent: ' + msg; this.trigger('error', err); if (cb) { cb.call(this, err, null); cb = callback = null; } } if (query instanceof Array) { queries = query; } else { queries.push(query); } request = new Request(this, queries, cb).refresh(); cb = callback = null; return request; }; },{"../request":27}],24:[function(require,module,exports){ module.exports = function(newGlobalProperties) { if (newGlobalProperties && typeof(newGlobalProperties) == "function") { this.config.globalProperties = newGlobalProperties; } else { this.trigger("error", "Invalid value for global properties: " + newGlobalProperties); } }; },{}],25:[function(require,module,exports){ var addEvent = require("./addEvent"); module.exports = function(jsEvent, eventCollection, payload, timeout, timeoutCallback){ var evt = jsEvent, target = (evt.currentTarget) ? evt.currentTarget : (evt.srcElement || evt.target), timer = timeout || 500, triggered = false, targetAttr = "", callback, win; if (target.getAttribute !== void 0) { targetAttr = target.getAttribute("target"); } else if (target.target) { targetAttr = target.target; } if ((targetAttr == "_blank" || targetAttr == "blank") && !evt.metaKey) { win = window.open("about:blank"); win.document.location = target.href; } if (target.nodeName === "A") { callback = function(){ if(!triggered && !evt.metaKey && (targetAttr !== "_blank" && targetAttr !== "blank")){ triggered = true; window.location = target.href; } }; } else if (target.nodeName === "FORM") { callback = function(){ if(!triggered){ triggered = true; target.submit(); } }; } else { this.trigger("error", "#trackExternalLink method not attached to an <a> or <form> DOM element"); } if (timeoutCallback) { callback = function(){ if(!triggered){ triggered = true; timeoutCallback(); } }; } addEvent.call(this, eventCollection, payload, callback); setTimeout(callback, timer); if (!evt.metaKey) { return false; } }; },{"./addEvent":19}],26:[function(require,module,exports){ var each = require("./utils/each"), extend = require("./utils/extend"), getTimezoneOffset = require("./helpers/get-timezone-offset"), getQueryString = require("./helpers/get-query-string"); var Emitter = require('./utils/emitter-shim'); function Query(){ this.configure.apply(this, arguments); }; Emitter(Query.prototype); Query.prototype.configure = function(analysisType, params) { this.analysis = analysisType; this.params = this.params || {}; this.set(params); if (this.params.timezone === void 0) { this.params.timezone = getTimezoneOffset(); } return this; }; Query.prototype.set = function(attributes) { var self = this; each(attributes, function(v, k){ var key = k, value = v; if (k.match(new RegExp("[A-Z]"))) { key = k.replace(/([A-Z])/g, function($1) { return "_"+$1.toLowerCase(); }); } self.params[key] = value; if (value instanceof Array) { each(value, function(dv, index){ if (dv instanceof Array == false && typeof dv === "object") { each(dv, function(deepValue, deepKey){ if (deepKey.match(new RegExp("[A-Z]"))) { var _deepKey = deepKey.replace(/([A-Z])/g, function($1) { return "_"+$1.toLowerCase(); }); delete self.params[key][index][deepKey]; self.params[key][index][_deepKey] = deepValue; } }); } }); } }); return self; }; Query.prototype.get = function(attribute) { var key = attribute; if (key.match(new RegExp("[A-Z]"))) { key = key.replace(/([A-Z])/g, function($1) { return "_"+$1.toLowerCase(); }); } if (this.params) { return this.params[key] || null; } }; Query.prototype.addFilter = function(property, operator, value) { this.params.filters = this.params.filters || []; this.params.filters.push({ "property_name": property, "operator": operator, "property_value": value }); return this; }; module.exports = Query; },{"./helpers/get-query-string":12,"./helpers/get-timezone-offset":13,"./utils/each":31,"./utils/emitter-shim":32,"./utils/extend":33}],27:[function(require,module,exports){ var each = require('./utils/each'), extend = require('./utils/extend'), sendQuery = require('./utils/sendQuery'), sendSavedQuery = require('./utils/sendSavedQuery'); var Emitter = require('./utils/emitter-shim'); var Keen = require('./'); var Query = require('./query'); function Request(client, queries, callback){ var cb = callback; this.config = { timeout: 300 * 1000 }; this.configure(client, queries, cb); cb = callback = null; }; Emitter(Request.prototype); Request.prototype.configure = function(client, queries, callback){ var cb = callback; extend(this, { 'client' : client, 'queries' : queries, 'data' : {}, 'callback' : cb }); cb = callback = null; return this; }; Request.prototype.timeout = function(ms){ if (!arguments.length) return this.config.timeout; this.config.timeout = (!isNaN(parseInt(ms)) ? parseInt(ms) : null); return this; }; Request.prototype.refresh = function(){ var self = this, completions = 0, response = [], errored = false; var handleResponse = function(err, res, index){ if (errored) { return; } if (err) { self.trigger('error', err); if (self.callback) { self.callback(err, null); } errored = true; return; } response[index] = res; completions++; if (completions == self.queries.length && !errored) { self.data = (self.queries.length == 1) ? response[0] : response; self.trigger('complete', null, self.data); if (self.callback) { self.callback(null, self.data); } } }; each(self.queries, function(query, index){ var cbSequencer = function(err, res){ handleResponse(err, res, index); }; var path = '/queries'; if (typeof query === 'string') { path += '/saved/' + query + '/result'; sendSavedQuery.call(self, path, {}, cbSequencer); } else if (query instanceof Query) { path += '/' + query.analysis; if (query.analysis === 'saved') { path += '/' + query.params.query_name + '/result'; sendSavedQuery.call(self, path, {}, cbSequencer); } else { sendQuery.call(self, path, query.params, cbSequencer); } } else { var res = { statusText: 'Bad Request', responseText: { message: 'Error: Query ' + (+index+1) + ' of ' + self.queries.length + ' for project ' + self.client.projectId() + ' is not a valid request' } }; self.trigger('error', res.responseText.message); if (self.callback) { self.callback(res.responseText.message, null); } } }); return this; }; module.exports = Request; },{"./":18,"./query":26,"./utils/each":31,"./utils/emitter-shim":32,"./utils/extend":33,"./utils/sendQuery":36,"./utils/sendSavedQuery":37}],28:[function(require,module,exports){ var request = require('superagent'); var responseHandler = require('./helpers/superagent-handle-response'); function savedQueries() { var _this = this; this.all = function(callback) { var url = _this.url('/queries/saved'); request .get(url) .set('Content-Type', 'application/json') .set('Authorization', _this.masterKey()) .end(handleResponse); function handleResponse(err, res){ responseHandler(err, res, callback); callback = null; } }; this.get = function(queryName, callback) { var url = _this.url('/queries/saved/' + queryName); request .get(url) .set('Content-Type', 'application/json') .set('Authorization', _this.masterKey()) .end(handleResponse); function handleResponse(err, res){ responseHandler(err, res, callback); callback = null; } }; this.update = function(queryName, body, callback) { var url = _this.url('/queries/saved/' + queryName); request .put(url) .set('Content-Type', 'application/json') .set('Authorization', _this.masterKey()) .send(body || {}) .end(handleResponse); function handleResponse(err, res){ responseHandler(err, res, callback); callback = null; } }; this.create = this.update; this.destroy = function(queryName, callback) { var url = _this.url('/queries/saved/' + queryName); request .del(url) .set('Content-Type', 'application/json') .set('Authorization', _this.masterKey()) .end(handleResponse); function handleResponse(err, res){ responseHandler(err, res, callback); callback = null; } }; return this; } module.exports = savedQueries; },{"./helpers/superagent-handle-response":16,"superagent":6}],29:[function(require,module,exports){ module.exports = { map: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", encode: function (n) { "use strict"; var o = "", i = 0, m = this.map, i1, i2, i3, e1, e2, e3, e4; n = this.utf8.encode(n); while (i < n.length) { i1 = n.charCodeAt(i++); i2 = n.charCodeAt(i++); i3 = n.charCodeAt(i++); e1 = (i1 >> 2); e2 = (((i1 & 3) << 4) | (i2 >> 4)); e3 = (isNaN(i2) ? 64 : ((i2 & 15) << 2) | (i3 >> 6)); e4 = (isNaN(i2) || isNaN(i3)) ? 64 : i3 & 63; o = o + m.charAt(e1) + m.charAt(e2) + m.charAt(e3) + m.charAt(e4); } return o; }, decode: function (n) { "use strict"; var o = "", i = 0, m = this.map, cc = String.fromCharCode, e1, e2, e3, e4, c1, c2, c3; n = n.replace(/[^A-Za-z0-9\+\/\=]/g, ""); while (i < n.length) { e1 = m.indexOf(n.charAt(i++)); e2 = m.indexOf(n.charAt(i++)); e3 = m.indexOf(n.charAt(i++)); e4 = m.indexOf(n.charAt(i++)); c1 = (e1 << 2) | (e2 >> 4); c2 = ((e2 & 15) << 4) | (e3 >> 2); c3 = ((e3 & 3) << 6) | e4; o = o + (cc(c1) + ((e3 != 64) ? cc(c2) : "")) + (((e4 != 64) ? cc(c3) : "")); } return this.utf8.decode(o); }, utf8: { encode: function (n) { "use strict"; var o = "", i = 0, cc = String.fromCharCode, c; while (i < n.length) { c = n.charCodeAt(i++); o = o + ((c < 128) ? cc(c) : ((c > 127) && (c < 2048)) ? (cc((c >> 6) | 192) + cc((c & 63) | 128)) : (cc((c >> 12) | 224) + cc(((c >> 6) & 63) | 128) + cc((c & 63) | 128))); } return o; }, decode: function (n) { "use strict"; var o = "", i = 0, cc = String.fromCharCode, c2, c; while (i < n.length) { c = n.charCodeAt(i); o = o + ((c < 128) ? [cc(c), i++][0] : ((c > 191) && (c < 224)) ? [cc(((c & 31) << 6) | ((c2 = n.charCodeAt(i + 1)) & 63)), (i += 2)][0] : [cc(((c & 15) << 12) | (((c2 = n.charCodeAt(i + 1)) & 63) << 6) | ((c3 = n.charCodeAt(i + 2)) & 63)), (i += 3)][0]); } return o; } } }; },{}],30:[function(require,module,exports){ var json = require('./json-shim'); module.exports = function(target) { return json.parse( json.stringify( target ) ); }; },{"./json-shim":34}],31:[function(require,module,exports){ module.exports = function(o, cb, s){ var n; if (!o){ return 0; } s = !s ? o : s; if (o instanceof Array){ for (n=0; n<o.length; n++) { if (cb.call(s, o[n], n, o) === false){ return 0; } } } else { for (n in o){ if (o.hasOwnProperty(n)) { if (cb.call(s, o[n], n, o) === false){ return 0; } } } } return 1; }; },{}],32:[function(require,module,exports){ var Emitter = require('component-emitter'); Emitter.prototype.trigger = Emitter.prototype.emit; module.exports = Emitter; },{"component-emitter":1}],33:[function(require,module,exports){ module.exports = function(target){ for (var i = 1; i < arguments.length; i++) { for (var prop in arguments[i]){ target[prop] = arguments[i][prop]; } } return target; }; },{}],34:[function(require,module,exports){ module.exports = ('undefined' !== typeof window && window.JSON) ? window.JSON : require("json3"); },{"json3":3}],35:[function(require,module,exports){ function parseParams(str){ var urlParams = {}, match, pl = /\+/g, search = /([^&=]+)=?([^&]*)/g, decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); }, query = str.split("?")[1]; while (!!(match=search.exec(query))) { urlParams[decode(match[1])] = decode(match[2]); } return urlParams; }; module.exports = parseParams; },{}],36:[function(require,module,exports){ var request = require('superagent'); var getContext = require('../helpers/get-context'), getXHR = require('../helpers/get-xhr-object'), responseHandler = require('../helpers/superagent-handle-response'); module.exports = function(path, params, callback){ var url = this.client.url(path); if (!this.client.projectId()) { this.client.trigger('error', 'Query not sent: Missing projectId property'); return; } if (!this.client.readKey()) { this.client.trigger('error', 'Query not sent: Missing readKey property'); return; } if (getContext() === 'server' || getXHR()) { request .post(url) .set('Content-Type', 'application/json') .set('Authorization', this.client.readKey()) .timeout(this.timeout()) .send(params || {}) .end(handleResponse); } function handleResponse(err, res){ responseHandler(err, res, callback); callback = null; } return; } },{"../helpers/get-context":11,"../helpers/get-xhr-object":15,"../helpers/superagent-handle-response":16,"superagent":6}],37:[function(require,module,exports){ var request = require('superagent'); var responseHandler = require('../helpers/superagent-handle-response'); module.exports = function(path, params, callback){ var key; if (this.client.readKey()) { key = this.client.readKey(); } else if (this.client.masterKey()) { key = this.client.masterKey(); } request .get(this.client.url(path)) .set('Content-Type', 'application/json') .set('Authorization', key) .timeout(this.timeout()) .send() .end(function(err, res) { responseHandler(err, res, callback); callback = null; }); return; } },{"../helpers/superagent-handle-response":16,"superagent":6}],38:[function(require,module,exports){ var clone = require("../core/utils/clone"), each = require("../core/utils/each"), flatten = require("./utils/flatten"), parse = require("./utils/parse"); var Emitter = require('../core/utils/emitter-shim'); function Dataset(){ this.data = { input: {}, output: [['Index']] }; this.meta = { schema: {}, method: undefined }; this.parser = undefined; if (arguments.length > 0) { this.parse.apply(this, arguments); } } Dataset.defaults = { delimeter: " -> " }; Emitter(Dataset); Emitter(Dataset.prototype); Dataset.parser = require('./utils/parsers')(Dataset); Dataset.prototype.input = function(obj){ if (!arguments.length) return this["data"]["input"]; this["data"]["input"] = (obj ? clone(obj) : null); return this; }; Dataset.prototype.output = function(arr){ if (!arguments.length) return this["data"].output; this["data"].output = (arr instanceof Array ? arr : null); return this; } Dataset.prototype.method = function(str){ if (!arguments.length) return this.meta["method"]; this.meta["method"] = (str ? String(str) : null); return this; }; Dataset.prototype.schema = function(obj){ if (!arguments.length) return this.meta.schema; this.meta.schema = (obj ? obj : null); return this; }; Dataset.prototype.parse = function(raw, schema){ var options; if (raw) this.input(raw); if (schema) this.schema(schema); this.output([[]]); if (this.meta.schema.select) { this.method("select"); options = extend({ records: "", select: true }, this.schema()); _select.call(this, _optHash(options)); } else if (this.meta.schema.unpack) { this.method("unpack"); options = extend({ records: "", unpack: { index: false, value: false, label: false } }, this.schema()); _unpack.call(this, _optHash(options)); } return this; }; function _select(cfg){ var self = this, options = cfg || {}, target_set = [], unique_keys = []; var root, records_target; if (options.records === "" || !options.records) { root = [self.input()]; } else { records_target = options.records.split(Dataset.defaults.delimeter); root = parse.apply(self, [self.input()].concat(records_target))[0]; } each(options.select, function(prop){ target_set.push(prop.path.split(Dataset.defaults.delimeter)); }); if (target_set.length == 0) { each(root, function(record, interval){ var flat = flatten(record); for (var key in flat) { if (flat.hasOwnProperty(key) && unique_keys.indexOf(key) == -1) { unique_keys.push(key); target_set.push([key]); } } }); } var test = [[]]; each(target_set, function(props, i){ if (target_set.length == 1) { test[0].push('label', 'value'); } else { test[0].push(props.join(".")); } }); each(root, function(record, i){ var flat = flatten(record); if (target_set.length == 1) { test.push([target_set.join("."), flat[target_set.join(".")]]); } else { test.push([]); each(target_set, function(t, j){ var target = t.join("."); test[i+1].push(flat[target]); }); } }); self.output(test); self.format(options.select); return self; } function _unpack(options){ var self = this, discovered_labels = []; var value_set = (options.unpack.value) ? options.unpack.value.path.split(Dataset.defaults.delimeter) : false, label_set = (options.unpack.label) ? options.unpack.label.path.split(Dataset.defaults.delimeter) : false, index_set = (options.unpack.index) ? options.unpack.index.path.split(Dataset.defaults.delimeter) : false; var value_desc = (value_set[value_set.length-1] !== "") ? value_set[value_set.length-1] : "Value", label_desc = (label_set[label_set.length-1] !== "") ? label_set[label_set.length-1] : "Label", index_desc = (index_set[index_set.length-1] !== "") ? index_set[index_set.length-1] : "Index"; var root = (function(){ var root; if (options.records == "") { root = [self.input()]; } else { root = parse.apply(self, [self.input()].concat(options.records.split(Dataset.defaults.delimeter))); } return root[0]; })(); if (root instanceof Array == false) { root = [root]; } each(root, function(record, interval){ var labels = (label_set) ? parse.apply(self, [record].concat(label_set)) : []; if (labels) { discovered_labels = labels; } }); each(root, function(record, interval){ var plucked_value = (value_set) ? parse.apply(self, [record].concat(value_set)) : false, plucked_index = (index_set) ? parse.apply(self, [record].concat(index_set)) : false; if (plucked_index) { each(plucked_index, function(){ self.data.output.push([]); }); } else { self.data.output.push([]); } if (plucked_index) { if (interval == 0) { self.data.output[0].push(index_desc); if (discovered_labels.length > 0) { each(discovered_labels, function(value, i){ self.data.output[0].push(value); }); } else { self.data.output[0].push(value_desc); } } if (root.length < self.data.output.length-1) { if (interval == 0) { each(self.data.output, function(row, i){ if (i > 0) { self.data.output[i].push(plucked_index[i-1]); } }); } } else { self.data.output[interval+1].push(plucked_index[0]); } } if (!plucked_index && discovered_labels.length > 0) { if (interval == 0) { self.data.output[0].push(label_desc); self.data.output[0].push(value_desc); } self.data.output[interval+1].push(discovered_labels[0]); } if (!plucked_index && discovered_labels.length == 0) { self.data.output[0].push(''); } if (plucked_value) { if (root.length < self.data.output.length-1) { if (interval == 0) { each(self.data.output, function(row, i){ if (i > 0) { self.data.output[i].push(plucked_value[i-1]); } }); } } else { each(plucked_value, function(value){ self.data.output[interval+1].push(value); }); } } else { each(self.data.output[0], function(cell, i){ var offset = (plucked_index) ? 0 : -1; if (i > offset) { self.data.output[interval+1].push(null); } }) } }); self.format(options.unpack); return this; } function _optHash(options){ each(options.unpack, function(value, key, object){ if (value && is(value, 'string')) { options.unpack[key] = { path: options.unpack[key] }; } }); return options; } function is(o, t){ o = typeof(o); if (!t){ return o != 'undefined'; } return o == t; } function extend(o, e){ each(e, function(v, n){ if (is(o[n], 'object') && is(v, 'object')){ o[n] = extend(o[n], v); } else if (v !== null) { o[n] = v; } }); return o; } module.exports = Dataset; },{"../core/utils/clone":30,"../core/utils/each":31,"../core/utils/emitter-shim":32,"./utils/flatten":51,"./utils/parse":52,"./utils/parsers":53}],39:[function(require,module,exports){ var extend = require("../core/utils/extend"), Dataset = require("./dataset"); extend(Dataset.prototype, require("./lib/append")); extend(Dataset.prototype, require("./lib/delete")); extend(Dataset.prototype, require("./lib/filter")); extend(Dataset.prototype, require("./lib/insert")); extend(Dataset.prototype, require("./lib/select")); extend(Dataset.prototype, require("./lib/set")); extend(Dataset.prototype, require("./lib/sort")); extend(Dataset.prototype, require("./lib/update")); extend(Dataset.prototype, require("./lib/analyses")); extend(Dataset.prototype, { "format": require("./lib/format") }); module.exports = Dataset; },{"../core/utils/extend":33,"./dataset":38,"./lib/analyses":40,"./lib/append":41,"./lib/delete":42,"./lib/filter":43,"./lib/format":44,"./lib/insert":45,"./lib/select":46,"./lib/set":47,"./lib/sort":48,"./lib/update":49}],40:[function(require,module,exports){ var each = require("../../core/utils/each"), arr = ["Average", "Maximum", "Minimum", "Sum"], output = {}; output["average"] = function(arr, start, end){ var set = arr.slice(start||0, (end ? end+1 : arr.length)), sum = 0, avg = null; each(set, function(val, i){ if (typeof val === "number" && !isNaN(parseFloat(val))) { sum += parseFloat(val); } }); return sum / set.length; }; output["maximum"] = function(arr, start, end){ var set = arr.slice(start||0, (end ? end+1 : arr.length)), nums = []; each(set, function(val, i){ if (typeof val === "number" && !isNaN(parseFloat(val))) { nums.push(parseFloat(val)); } }); return Math.max.apply(Math, nums); }; output["minimum"] = function(arr, start, end){ var set = arr.slice(start||0, (end ? end+1 : arr.length)), nums = []; each(set, function(val, i){ if (typeof val === "number" && !isNaN(parseFloat(val))) { nums.push(parseFloat(val)); } }); return Math.min.apply(Math, nums); }; output["sum"] = function(arr, start, end){ var set = arr.slice(start||0, (end ? end+1 : arr.length)), sum = 0; each(set, function(val, i){ if (typeof val === "number" && !isNaN(parseFloat(val))) { sum += parseFloat(val); } }); return sum; }; each(arr, function(v,i){ output["getColumn"+v] = output["getRow"+v] = function(arr){ return this[v.toLowerCase()](arr, 1); }; }); output["getColumnLabel"] = output["getRowIndex"] = function(arr){ return arr[0]; }; module.exports = output; },{"../../core/utils/each":31}],41:[function(require,module,exports){ var each = require("../../core/utils/each"); var createNullList = require('../utils/create-null-list'); module.exports = { "appendColumn": appendColumn, "appendRow": appendRow }; function appendColumn(str, input){ var self = this, args = Array.prototype.slice.call(arguments, 2), label = (str !== undefined) ? str : null; if (typeof input === "function") { self.data.output[0].push(label); each(self.output(), function(row, i){ var cell; if (i > 0) { cell = input.call(self, row, i); if (typeof cell === "undefined") { cell = null; } self.data.output[i].push(cell); } }); } else if (!input || input instanceof Array) { input = input || []; if (input.length <= self.output().length - 1) { input = input.concat( createNullList(self.output().length - 1 - input.length) ); } else { each(input, function(value, i){ if (self.data.output.length -1 < input.length) { appendRow.call(self, String( self.data.output.length )); } }); } self.data.output[0].push(label); each(input, function(value, i){ self.data.output[i+1][self.data.output[0].length-1] = value; }); } return self; } function appendRow(str, input){ var self = this, args = Array.prototype.slice.call(arguments, 2), label = (str !== undefined) ? str : null, newRow = []; newRow.push(label); if (typeof input === "function") { each(self.data.output[0], function(label, i){ var col, cell; if (i > 0) { col = self.selectColumn(i); cell = input.call(self, col, i); if (typeof cell === "undefined") { cell = null; } newRow.push(cell); } }); self.data.output.push(newRow); } else if (!input || input instanceof Array) { input = input || []; if (input.length <= self.data.output[0].length - 1) { input = input.concat( createNullList( self.data.output[0].length - 1 - input.length ) ); } else { each(input, function(value, i){ if (self.data.output[0].length -1 < input.length) { appendColumn.call(self, String( self.data.output[0].length )); } }); } self.data.output.push( newRow.concat(input) ); } return self; } },{"../../core/utils/each":31,"../utils/create-null-list":50}],42:[function(require,module,exports){ var each = require("../../core/utils/each"); module.exports = { "deleteColumn": deleteColumn, "deleteRow": deleteRow }; function deleteColumn(q){ var self = this, index = (typeof q === 'number') ? q : this.data.output[0].indexOf(q); if (index > -1) { each(self.data.output, function(row, i){ self.data.output[i].splice(index, 1); }); } return self; } function deleteRow(q){ var index = (typeof q === 'number') ? q : this.selectColumn(0).indexOf(q); if (index > -1) { this.data.output.splice(index, 1); } return this; } },{"../../core/utils/each":31}],43:[function(require,module,exports){ var each = require("../../core/utils/each"); module.exports = { "filterColumns": filterColumns, "filterRows": filterRows }; function filterColumns(fn){ var self = this, clone = new Array(); each(self.data.output, function(row, i){ clone.push([]); }); each(self.data.output[0], function(col, i){ var selectedColumn = self.selectColumn(i); if (i == 0 || fn.call(self, selectedColumn, i)) { each(selectedColumn, function(cell, ri){ clone[ri].push(cell); }); } }); self.output(clone); return self; } function filterRows(fn){ var self = this, clone = []; each(self.output(), function(row, i){ if (i == 0 || fn.call(self, row, i)) { clone.push(row); } }); self.output(clone); return self; } },{"../../core/utils/each":31}],44:[function(require,module,exports){ var each = require("../../core/utils/each"); module.exports = function(options){ var self = this; if (this.method() === 'select') { each(self.output(), function(row, i){ if (i == 0) { each(row, function(cell, j){ if (options[j] && options[j].label) { self.data.output[i][j] = options[j].label; } }); } else { each(row, function(cell, j){ self.data.output[i][j] = _applyFormat(self.data.output[i][j], options[j]); }); } }); } if (this.method() === 'unpack') { if (options.index) { each(self.output(), function(row, i){ if (i == 0) { if (options.index.label) { self.data.output[i][0] = options.index.label; } } else { self.data.output[i][0] = _applyFormat(self.data.output[i][0], options.index); } }); } if (options.label) { if (options.index) { each(self.output(), function(row, i){ each(row, function(cell, j){ if (i == 0 && j > 0) { self.data.output[i][j] = _applyFormat(self.data.output[i][j], options.label); } }); }); } else { each(self.output(), function(row, i){ if (i > 0) { self.data.output[i][0] = _applyFormat(self.data.output[i][0], options.label); } }); } } if (options.value) { if (options.index) { each(self.output(), function(row, i){ each(row, function(cell, j){ if (i > 0 && j > 0) { self.data.output[i][j] = _applyFormat(self.data.output[i][j], options.value); } }); }); } else { each(self.output(), function(row, i){ each(row, function(cell, j){ if (i > 0) { self.data.output[i][j] = _applyFormat(self.data.output[i][j], options.value); } }); }); } } } return self; }; function _applyFormat(value, opts){ var output = value, options = opts || {}; if (options.replace) { each(options.replace, function(val, key){ if (output == key || String(output) == String(key) || parseFloat(output) == parseFloat(key)) { output = val; } }); } if (options.type && options.type == 'date') { if (options.format && moment && moment(value).isValid()) { output = moment(output).format(options.format); } else { output = new Date(output); } } if (options.type && options.type == 'string') { output = String(output); } if (options.type && options.type == 'number' && !isNaN(parseFloat(output))) { output = parseFloat(output); } return output; } },{"../../core/utils/each":31}],45:[function(require,module,exports){ var each = require("../../core/utils/each"); var createNullList = require('../utils/create-null-list'); var append = require('./append'); var appendRow = append.appendRow, appendColumn = append.appendColumn; module.exports = { "insertColumn": insertColumn, "insertRow": insertRow }; function insertColumn(index, str, input){ var self = this, label; label = (str !== undefined) ? str : null; if (typeof input === "function") { self.data.output[0].splice(index, 0, label); each(self.output(), function(row, i){ var cell; if (i > 0) { cell = input.call(self, row, i); if (typeof cell === "undefined") { cell = null; } self.data.output[i].splice(index, 0, cell); } }); } else if (!input || input instanceof Array) { input = input || []; if (input.length <= self.output().length - 1) { input = input.concat( createNullList(self.output().length - 1 - input.length) ); } else { each(input, function(value, i){ if (self.data.output.length -1 < input.length) { appendRow.call(self, String( self.data.output.length )); } }); } self.data.output[0].splice(index, 0, label); each(input, function(value, i){ self.data.output[i+1].splice(index, 0, value); }); } return self; } function insertRow(index, str, input){ var self = this, label, newRow = []; label = (str !== undefined) ? str : null; newRow.push(label); if (typeof input === "function") { each(self.output()[0], function(label, i){ var col, cell; if (i > 0) { col = self.selectColumn(i); cell = input.call(self, col, i); if (typeof cell === "undefined") { cell = null; } newRow.push(cell); } }); self.data.output.splice(index, 0, newRow); } else if (!input || input instanceof Array) { input = input || []; if (input.length <= self.data.output[0].length - 1) { input = input.concat( createNullList( self.data.output[0].length - 1 - input.length ) ); } else { each(input, function(value, i){ if (self.data.output[0].length -1 < input.length) { appendColumn.call(self, String( self.data.output[0].length )); } }); } self.data.output.splice(index, 0, newRow.concat(input) ); } return self; } },{"../../core/utils/each":31,"../utils/create-null-list":50,"./append":41}],46:[function(require,module,exports){ var each = require("../../core/utils/each"); module.exports = { "selectColumn": selectColumn, "selectRow": selectRow }; function selectColumn(q){ var result = new Array(), index = (typeof q === 'number') ? q : this.data.output[0].indexOf(q); if (index > -1 && 'undefined' !== typeof this.data.output[0][index]) { each(this.data.output, function(row, i){ result.push(row[index]); }); } return result; } function selectRow(q){ var result = new Array(), index = (typeof q === 'number') ? q : this.selectColumn(0).indexOf(q); if (index > -1 && 'undefined' !== typeof this.data.output[index]) { result = this.data.output[index]; } return result; } },{"../../core/utils/each":31}],47:[function(require,module,exports){ var each = require("../../core/utils/each"); var append = require('./append'); var select = require('./select'); module.exports = { "set": set }; function set(coords, value){ if (arguments.length < 2 || coords.length < 2) { throw Error('Incorrect arguments provided for #set method'); } var colIndex = 'number' === typeof coords[0] ? coords[0] : this.data.output[0].indexOf(coords[0]), rowIndex = 'number' === typeof coords[1] ? coords[1] : select.selectColumn.call(this, 0).indexOf(coords[1]); var colResult = select.selectColumn.call(this, coords[0]), rowResult = select.selectRow.call(this, coords[1]); if (colResult.length < 1) { append.appendColumn.call(this, coords[0]); colIndex = this.data.output[0].length-1; } if (rowResult.length < 1) { append.appendRow.call(this, coords[1]); rowIndex = this.data.output.length-1; } this.data.output[ rowIndex ][ colIndex ] = value; return this; } },{"../../core/utils/each":31,"./append":41,"./select":46}],48:[function(require,module,exports){ var each = require("../../core/utils/each"); module.exports = { "sortColumns": sortColumns, "sortRows": sortRows }; function sortColumns(str, comp){ var self = this, head = this.output()[0].slice(1), cols = [], clone = [], fn = comp || this.getColumnLabel; each(head, function(cell, i){ cols.push(self.selectColumn(i+1).slice(0)); }); cols.sort(function(a,b){ var op = fn.call(self, a) > fn.call(self, b); if (op) { return (str === "asc" ? 1 : -1); } else if (!op) { return (str === "asc" ? -1 : 1); } else { return 0; } }); each(cols, function(col, i){ self .deleteColumn(i+1) .insertColumn(i+1, col[0], col.slice(1)); }); return self; } function sortRows(str, comp){ var self = this, head = this.output().slice(0,1), body = this.output().slice(1), fn = comp || this.getRowIndex; body.sort(function(a, b){ var op = fn.call(self, a) > fn.call(self, b); if (op) { return (str === "asc" ? 1 : -1); } else if (!op) { return (str === "asc" ? -1 : 1); } else { return 0; } }); self.output(head.concat(body)); return self; } },{"../../core/utils/each":31}],49:[function(require,module,exports){ var each = require("../../core/utils/each"); var createNullList = require('../utils/create-null-list'); var append = require('./append'); var appendRow = append.appendRow, appendColumn = append.appendColumn; module.exports = { "updateColumn": updateColumn, "updateRow": updateRow }; function updateColumn(q, input){ var self = this, index = (typeof q === 'number') ? q : this.data.output[0].indexOf(q); if (index > -1) { if (typeof input === "function") { each(self.output(), function(row, i){ var cell; if (i > 0) { cell = input.call(self, row[index], i, row); if (typeof cell !== "undefined") { self.data.output[i][index] = cell; } } }); } else if (!input || input instanceof Array) { input = input || []; if (input.length <= self.output().length - 1) { input = input.concat( createNullList(self.output().length - 1 - input.length) ); } else { each(input, function(value, i){ if (self.data.output.length -1 < input.length) { appendRow.call(self, String( self.data.output.length )); } }); } each(input, function(value, i){ self.data.output[i+1][index] = value; }); } } return self; } function updateRow(q, input){ var self = this, index = (typeof q === 'number') ? q : this.selectColumn(0).indexOf(q); if (index > -1) { if (typeof input === "function") { each(self.output()[index], function(value, i){ var col = self.selectColumn(i), cell = input.call(self, value, i, col); if (typeof cell !== "undefined") { self.data.output[index][i] = cell; } }); } else if (!input || input instanceof Array) { input = input || []; if (input.length <= self.data.output[0].length - 1) { input = input.concat( createNullList( self.data.output[0].length - 1 - input.length ) ); } else { each(input, function(value, i){ if (self.data.output[0].length -1 < input.length) { appendColumn.call(self, String( self.data.output[0].length )); } }); } each(input, function(value, i){ self.data.output[index][i+1] = value; }); } } return self; } },{"../../core/utils/each":31,"../utils/create-null-list":50,"./append":41}],50:[function(require,module,exports){ module.exports = function(len){ var list = new Array(); for (i = 0; i < len; i++) { list.push(null); } return list; }; },{}],51:[function(require,module,exports){ module.exports = flatten; function flatten(ob) { var toReturn = {}; for (var i in ob) { if (!ob.hasOwnProperty(i)) continue; if ((typeof ob[i]) == 'object' && ob[i] !== null) { var flatObject = flatten(ob[i]); for (var x in flatObject) { if (!flatObject.hasOwnProperty(x)) continue; toReturn[i + '.' + x] = flatObject[x]; } } else { toReturn[i] = ob[i]; } } return toReturn; } },{}],52:[function(require,module,exports){ var each = require("../../core/utils/each"); module.exports = function() { var result = []; var loop = function() { var root = arguments[0]; var args = Array.prototype.slice.call(arguments, 1); var target = args.pop(); if (args.length === 0) { if (root instanceof Array) { args = root; } else if (typeof root === 'object') { args.push(root); } } each(args, function(el){ if (target == "") { if (typeof el == "number" || el == null) { return result.push(el); } } if (el[target] || el[target] === 0 || el[target] !== void 0) { if (el[target] === null) { return result.push(null); } else { return result.push(el[target]); } } else if (root[el]){ if (root[el] instanceof Array) { each(root[el], function(n, i) { var splinter = [root[el]].concat(root[el][i]).concat(args.slice(1)).concat(target); return loop.apply(this, splinter); }); } else { if (root[el][target]) { return result.push(root[el][target]); } else { return loop.apply(this, [root[el]].concat(args.splice(1)).concat(target)); } } } else if (typeof root === 'object' && root instanceof Array === false && !root[target]) { throw new Error("Target property does not exist", target); } else { return loop.apply(this, [el].concat(args.splice(1)).concat(target)); } return; }); if (result.length > 0) { return result; } }; return loop.apply(this, arguments); } },{"../../core/utils/each":31}],53:[function(require,module,exports){ var Dataset; /* injected */ var each = require('../../core/utils/each'), flatten = require('./flatten'); var parsers = { 'metric': parseMetric, 'interval': parseInterval, 'grouped-metric': parseGroupedMetric, 'grouped-interval': parseGroupedInterval, 'double-grouped-metric': parseDoubleGroupedMetric, 'double-grouped-interval': parseDoubleGroupedInterval, 'funnel': parseFunnel, 'list': parseList, 'extraction': parseExtraction }; module.exports = initialize; function initialize(lib){ Dataset = lib; return function(name){ var options = Array.prototype.slice.call(arguments, 1); if (!parsers[name]) { throw 'Requested parser does not exist'; } else { return parsers[name].apply(this, options); } }; } function parseMetric(){ return function(res){ var dataset = new Dataset(); dataset.data.input = res; dataset.parser = { name: 'metric' }; return dataset.set(['Value', 'Result'], res.result); } } function parseInterval(){ var options = Array.prototype.slice.call(arguments); return function(res){ var dataset = new Dataset(); each(res.result, function(record, i){ var index = options[0] && options[0] === 'timeframe.end' ? record.timeframe.end : record.timeframe.start; dataset.set(['Result', index], record.value); }); dataset.data.input = res; dataset.parser = 'interval'; dataset.parser = { name: 'interval', options: options }; return dataset; } } function parseGroupedMetric(){ return function(res){ var dataset = new Dataset(); each(res.result, function(record, i){ var label; each(record, function(value, key){ if (key !== 'result') { label = key; } }); dataset.set(['Result', String(record[label])], record.result); }); dataset.data.input = res; dataset.parser = { name: 'grouped-metric' }; return dataset; } } function parseGroupedInterval(){ var options = Array.prototype.slice.call(arguments); return function(res){ var dataset = new Dataset(); each(res.result, function(record, i){ var index = options[0] && options[0] === 'timeframe.end' ? record.timeframe.end : record.timeframe.start; if (record.value.length) { each(record.value, function(group, j){ var label; each(group, function(value, key){ if (key !== 'result') { label = key; } }); dataset.set([ String(group[label]) || '', index ], group.result); }); } else { dataset.appendRow(index); } }); dataset.data.input = res; dataset.parser = { name: 'grouped-interval', options: options }; return dataset; } } function parseDoubleGroupedMetric(){ var options = Array.prototype.slice.call(arguments); if (!options[0]) throw 'Requested parser requires a sequential list (array) of properties to target as a second argument'; return function(res){ var dataset = new Dataset(); each(res.result, function(record, i){ dataset.set([ 'Result', record[options[0][0]] + ' ' + record[options[0][1]] ], record.result); }); dataset.data.input = res; dataset.parser = { name: 'double-grouped-metric', options: options }; return dataset; } } function parseDoubleGroupedInterval(){ var options = Array.prototype.slice.call(arguments); if (!options[0]) throw 'Requested parser requires a sequential list (array) of properties to target as a second argument'; return function(res){ var dataset = new Dataset(); each(res.result, function(record, i){ var index = options[1] && options[1] === 'timeframe.end' ? record.timeframe.end : record.timeframe.start; each(record['value'], function(value, j){ var label = String(value[options[0][0]]) + ' ' + String(value[options[0][1]]); dataset.set([ label, index ], value.result); }); }); dataset.data.input = res; dataset.parser = { name: 'double-grouped-interval', options: options }; return dataset; } } function parseFunnel(){ return function(res){ var dataset = new Dataset(); dataset.appendColumn('Step Value'); each(res.result, function(value, i){ dataset.appendRow(res.steps[i].event_collection, [ value ]); }); dataset.data.input = res; dataset.parser = { name: 'funnel' }; return dataset; } } function parseList(){ return function(res){ var dataset = new Dataset(); each(res.result, function(value, i){ dataset.set( [ 'Value', i+1 ], value ); }); dataset.data.input = res; dataset.parser = { name: 'list' }; return dataset; } } function parseExtraction(){ return function(res){ var dataset = new Dataset(); each(res.result, function(record, i){ each(flatten(record), function(value, key){ dataset.set([key, i+1], value); }); }); dataset.deleteColumn(0); dataset.data.input = res; dataset.parser = { name: 'extraction' }; return dataset; } } },{"../../core/utils/each":31,"./flatten":51}],54:[function(require,module,exports){ /*! * ---------------------- * C3.js Adapter * ---------------------- */ var Dataviz = require('../dataviz'), each = require('../../core/utils/each'), extend = require('../../core/utils/extend'); getSetupTemplate = require('./c3/get-setup-template') module.exports = function(){ var dataTypes = { 'singular' : ['gauge'], 'categorical' : ['donut', 'pie'], 'cat-interval' : ['area-step', 'step', 'bar', 'area', 'area-spline', 'spline', 'line'], 'cat-ordinal' : ['bar', 'area', 'area-spline', 'spline', 'line', 'step', 'area-step'], 'chronological' : ['area', 'area-spline', 'spline', 'line', 'bar', 'step', 'area-step'], 'cat-chronological' : ['line', 'spline', 'area', 'area-spline', 'bar', 'step', 'area-step'] }; var charts = {}; each(['gauge', 'donut', 'pie', 'bar', 'area', 'area-spline', 'spline', 'line', 'step', 'area-step'], function(type, index){ charts[type] = { render: function(){ if (this.data()[0].length === 1 || this.data().length === 1) { this.error('No data to display'); return; } this.view._artifacts['c3'] = c3.generate(getSetupTemplate.call(this, type)); this.update(); }, update: function(){ var self = this, cols = []; if (type === 'gauge') { self.view._artifacts['c3'].load({ columns: [ [self.title(), self.data()[1][1]] ] }) } else if (type === 'pie' || type === 'donut') { self.view._artifacts['c3'].load({ columns: self.dataset.data.output.slice(1) }); } else { if (this.dataType().indexOf('chron') > -1) { cols.push(self.dataset.selectColumn(0)); cols[0][0] = 'x'; } each(self.data()[0], function(c, i){ if (i > 0) { cols.push(self.dataset.selectColumn(i)); } }); if (self.stacked()) { self.view._artifacts['c3'].groups([self.labels()]); } self.view._artifacts['c3'].load({ columns: cols }); } }, destroy: function(){ _selfDestruct.call(this); } }; }); function _selfDestruct(){ if (this.view._artifacts['c3']) { this.view._artifacts['c3'].destroy(); this.view._artifacts['c3'] = null; } } Dataviz.register('c3', charts, { capabilities: dataTypes }); }; },{"../../core/utils/each":31,"../../core/utils/extend":33,"../dataviz":59,"./c3/get-setup-template":55}],55:[function(require,module,exports){ var extend = require('../../../core/utils/extend'); var clone = require('../../../core/utils/clone'); module.exports = function (type) { var chartOptions = clone(this.chartOptions()); var setup = extend({ axis: {}, color: {}, data: {}, size: {} }, chartOptions); setup.bindto = this.el(); setup.color.pattern = this.colors(); setup.data.columns = []; setup.size.height = this.height(); setup.size.width = this.width(); setup['data']['type'] = type; if (type === 'gauge') {} else if (type === 'pie' || type === 'donut') { setup[type] = { title: this.title() }; } else { if (this.dataType().indexOf('chron') > -1) { setup['data']['x'] = 'x'; setup['axis']['x'] = setup['axis']['x'] || {}; setup['axis']['x']['type'] = 'timeseries'; setup['axis']['x']['tick'] = setup['axis']['x']['tick'] || { format: this.dateFormat() || getDateFormatDefault(this.data()[1][0], this.data()[2][0]) }; } else { if (this.dataType() === 'cat-ordinal') { setup['axis']['x'] = setup['axis']['x'] || {}; setup['axis']['x']['type'] = 'category'; setup['axis']['x']['categories'] = setup['axis']['x']['categories'] || this.labels() } } if (this.title()) { setup['axis']['y'] = { label: this.title() }; } } return setup; } function getDateFormatDefault(a, b){ var d = Math.abs(new Date(a).getTime() - new Date(b).getTime()); var months = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec' ]; if (d >= 2419200000) { return function(ms){ var date = new Date(ms); return months[date.getMonth()] + ' ' + date.getFullYear(); }; } else if (d >= 86400000) { return function(ms){ var date = new Date(ms); return months[date.getMonth()] + ' ' + date.getDate(); }; } else if (d >= 3600000) { return '%I:%M %p'; } else { return '%I:%M:%S %p'; } } },{"../../../core/utils/clone":30,"../../../core/utils/extend":33}],56:[function(require,module,exports){ /*! * ---------------------- * Chart.js Adapter * ---------------------- */ var Dataviz = require("../dataviz"), each = require("../../core/utils/each"), extend = require("../../core/utils/extend"); module.exports = function(){ if (typeof Chart !== "undefined") { Chart.defaults.global.responsive = true; } var dataTypes = { "categorical" : ["doughnut", "pie", "polar-area", "radar"], "cat-interval" : ["bar", "line"], "cat-ordinal" : ["bar", "line"], "chronological" : ["line", "bar"], "cat-chronological" : ["line", "bar"] }; var ChartNameMap = { "radar": "Radar", "polar-area": "PolarArea", "pie": "Pie", "doughnut": "Doughnut", "line": "Line", "bar": "Bar" }; var dataTransformers = { 'doughnut': getCategoricalData, 'pie': getCategoricalData, 'polar-area': getCategoricalData, 'radar': getSeriesData, 'line': getSeriesData, 'bar': getSeriesData }; function getCategoricalData(){ var self = this, result = []; each(self.dataset.selectColumn(0).slice(1), function(label, i){ result.push({ value: self.dataset.selectColumn(1).slice(1)[i], color: self.colors()[+i], hightlight: self.colors()[+i+9], label: label }); }); return result; } function getSeriesData(){ var self = this, labels, result = { labels: [], datasets: [] }; labels = this.dataset.selectColumn(0).slice(1); each(labels, function(l,i){ if (l instanceof Date) { result.labels.push((l.getMonth()+1) + "-" + l.getDate() + "-" + l.getFullYear()); } else { result.labels.push(l); } }) each(self.dataset.selectRow(0).slice(1), function(label, i){ var hex = { r: hexToR(self.colors()[i]), g: hexToG(self.colors()[i]), b: hexToB(self.colors()[i]) }; result.datasets.push({ label: label, fillColor : "rgba(" + hex.r + "," + hex.g + "," + hex.b + ",0.2)", strokeColor : "rgba(" + hex.r + "," + hex.g + "," + hex.b + ",1)", pointColor : "rgba(" + hex.r + "," + hex.g + "," + hex.b + ",1)", pointStrokeColor: "#fff", pointHighlightFill: "#fff", pointHighlightStroke: "rgba(" + hex.r + "," + hex.g + "," + hex.b + ",1)", data: self.dataset.selectColumn(+i+1).slice(1) }); }); return result; } var charts = {}; each(["doughnut", "pie", "polar-area", "radar", "bar", "line"], function(type, index){ charts[type] = { initialize: function(){ if (this.data()[0].length === 1 || this.data().length === 1) { this.error('No data to display'); return; } if (this.el().nodeName.toLowerCase() !== "canvas") { var canvas = document.createElement('canvas'); this.el().innerHTML = ""; this.el().appendChild(canvas); this.view._artifacts["ctx"] = canvas.getContext("2d"); } else { this.view._artifacts["ctx"] = this.el().getContext("2d"); } if (this.height()) { this.view._artifacts["ctx"].canvas.height = this.height(); this.view._artifacts["ctx"].canvas.style.height = String(this.height() + "px"); } if (this.width()) { this.view._artifacts["ctx"].canvas.width = this.width(); this.view._artifacts["ctx"].canvas.style.width = String(this.width() + "px"); } return this; }, render: function(){ if(_isEmptyOutput(this.dataset)) { this.error("No data to display"); return; } var method = ChartNameMap[type], opts = extend({}, this.chartOptions()), data = dataTransformers[type].call(this); if (this.view._artifacts["chartjs"]) { this.view._artifacts["chartjs"].destroy(); } this.view._artifacts["chartjs"] = new Chart(this.view._artifacts["ctx"])[method](data, opts); return this; }, destroy: function(){ _selfDestruct.call(this); } }; }); function _selfDestruct(){ if (this.view._artifacts["chartjs"]) { this.view._artifacts["chartjs"].destroy(); this.view._artifacts["chartjs"] = null; } } function _isEmptyOutput(dataset) { var flattened = dataset.output().reduce(function(a, b) { return a.concat(b) }); return flattened.length === 0 } function hexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)} function hexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)} function hexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)} function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h} Dataviz.register("chartjs", charts, { capabilities: dataTypes }); }; },{"../../core/utils/each":31,"../../core/utils/extend":33,"../dataviz":59}],57:[function(require,module,exports){ /*! * ---------------------- * Google Charts Adapter * ---------------------- */ /* TODO: [ ] Build a more robust DataTable transformer [ ] ^Expose date parser for google charts tooltips (#70) [ ] ^Allow custom tooltips (#147) */ var Dataviz = require("../dataviz"), each = require("../../core/utils/each"), extend = require("../../core/utils/extend"), Keen = require("../../core"); module.exports = function(){ Keen.loaded = false; var errorMapping = { "Data column(s) for axis #0 cannot be of type string": "No results to visualize" }; var chartTypes = ['AreaChart', 'BarChart', 'ColumnChart', 'LineChart', 'PieChart', 'Table']; var chartMap = {}; var dataTypes = { 'categorical': ['piechart', 'barchart', 'columnchart', 'table'], 'cat-interval': ['columnchart', 'barchart', 'table'], 'cat-ordinal': ['barchart', 'columnchart', 'areachart', 'linechart', 'table'], 'chronological': ['areachart', 'linechart', 'table'], 'cat-chronological': ['linechart', 'columnchart', 'barchart', 'areachart'], 'nominal': ['table'], 'extraction': ['table'] }; each(chartTypes, function (type) { var name = type.toLowerCase(); chartMap[name] = { initialize: function(){ }, render: function(){ if(typeof google === "undefined") { this.error("The Google Charts library could not be loaded."); return; } var self = this; if (self.view._artifacts['googlechart']) { this.destroy(); } self.view._artifacts['googlechart'] = self.view._artifacts['googlechart'] || new google.visualization[type](self.el()); google.visualization.events.addListener(self.view._artifacts['googlechart'], 'error', function(stack){ _handleErrors.call(self, stack); }); this.update(); }, update: function(){ var options = _getDefaultAttributes.call(this, type); extend(options, this.chartOptions(), this.attributes()); options['isStacked'] = (this.stacked() || options['isStacked']); this.view._artifacts['datatable'] = google.visualization.arrayToDataTable(this.data()); if (options.dateFormat) { if (typeof options.dateFormat === 'function') { options.dateFormat(this.view._artifacts['datatable']); } else if (typeof options.dateFormat === 'string') { new google.visualization.DateFormat({ pattern: options.dateFormat }).format(this.view._artifacts['datatable'], 0); } } if (this.view._artifacts['googlechart']) { this.view._artifacts['googlechart'].draw(this.view._artifacts['datatable'], options); } }, destroy: function(){ if (this.view._artifacts['googlechart']) { google.visualization.events.removeAllListeners(this.view._artifacts['googlechart']); this.view._artifacts['googlechart'].clearChart(); this.view._artifacts['googlechart'] = null; this.view._artifacts['datatable'] = null; } } }; }); Dataviz.register('google', chartMap, { capabilities: dataTypes, dependencies: [{ type: 'script', url: 'https://www.google.com/jsapi', cb: function(done) { if (typeof google === 'undefined'){ this.trigger("error", "Problem loading Google Charts library. Please contact us!"); done(); } else { google.load('visualization', '1.1', { packages: ['corechart', 'table'], callback: function(){ done(); } }); } } }] }); function _handleErrors(stack){ var message = errorMapping[stack['message']] || stack['message'] || 'An error occurred'; this.error(message); } function _getDefaultAttributes(type){ var output = {}; switch (type.toLowerCase()) { case "areachart": output.lineWidth = 2; output.hAxis = { baselineColor: 'transparent', gridlines: { color: 'transparent' } }; output.vAxis = { viewWindow: { min: 0 } }; if (this.dataType() === "chronological" || this.dataType() === "cat-ordinal") { output.legend = "none"; output.chartArea = { width: "85%" }; } if (this.dateFormat() && typeof this.dateFormat() === 'string') { output.hAxis.format = this.dateFormat(); } break; case "barchart": output.hAxis = { viewWindow: { min: 0 } }; output.vAxis = { baselineColor: 'transparent', gridlines: { color: 'transparent' } }; if (this.dataType() === "chronological" || this.dataType() === "cat-ordinal") { output.legend = "none"; } if (this.dateFormat() && typeof this.dateFormat() === 'string') { output.vAxis.format = this.dateFormat(); } break; case "columnchart": output.hAxis = { baselineColor: 'transparent', gridlines: { color: 'transparent' } }; output.vAxis = { viewWindow: { min: 0 } }; if (this.dataType() === "chronological" || this.dataType() === "cat-ordinal") { output.legend = "none"; output.chartArea = { width: "85%" }; } if (this.dateFormat() && typeof this.dateFormat() === 'string') { output.hAxis.format = this.dateFormat(); } break; case "linechart": output.lineWidth = 2; output.hAxis = { baselineColor: 'transparent', gridlines: { color: 'transparent' } }; output.vAxis = { viewWindow: { min: 0 } }; if (this.dataType() === "chronological" || this.dataType() === "cat-ordinal") { output.legend = "none"; output.chartArea = { width: "85%" }; } if (this.dateFormat() && typeof this.dateFormat() === 'string') { output.hAxis.format = this.dateFormat(); } break; case "piechart": output.sliceVisibilityThreshold = 0.01; break; case "table": break; } return output; } }; },{"../../core":18,"../../core/utils/each":31,"../../core/utils/extend":33,"../dataviz":59}],58:[function(require,module,exports){ /*! * ---------------------- * Keen IO Adapter * ---------------------- */ var Keen = require("../../core"), Dataviz = require("../dataviz"); var clone = require("../../core/utils/clone"), each = require("../../core/utils/each"), extend = require("../../core/utils/extend"), prettyNumber = require("../utils/prettyNumber"); module.exports = function(){ var Metric, Error, Spinner; Keen.Error = { defaults: { backgroundColor : "", borderRadius : "4px", color : "#ccc", display : "block", fontFamily : "Helvetica Neue, Helvetica, Arial, sans-serif", fontSize : "21px", fontWeight : "light", textAlign : "center" } }; Keen.Spinner.defaults = { height: 138, lines: 10, length: 8, width: 3, radius: 10, corners: 1, rotate: 0, direction: 1, color: '#4d4d4d', speed: 1.67, trail: 60, shadow: false, hwaccel: false, className: 'keen-spinner', zIndex: 2e9, top: '50%', left: '50%' }; var dataTypes = { 'singular': ['metric'] }; Metric = { initialize: function(){ var css = document.createElement("style"), bgDefault = "#49c5b1"; css.id = "keen-widgets"; css.type = "text/css"; css.innerHTML = "\ .keen-metric { \n background: " + bgDefault + "; \n border-radius: 4px; \n color: #fff; \n font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; \n padding: 10px 0; \n text-align: center; \n} \ .keen-metric-value { \n display: block; \n font-size: 84px; \n font-weight: 700; \n line-height: 84px; \n} \ .keen-metric-title { \n display: block; \n font-size: 24px; \n font-weight: 200; \n}"; if (!document.getElementById(css.id)) { document.body.appendChild(css); } }, render: function(){ var bgColor = (this.colors().length == 1) ? this.colors()[0] : "#49c5b1", title = this.title() || "Result", value = (this.data()[1] && this.data()[1][1]) ? this.data()[1][1] : 0, width = this.width(), opts = this.chartOptions() || {}, prefix = "", suffix = ""; var styles = { 'width': (width) ? width + 'px' : 'auto' }; var formattedNum = value; if ( typeof opts.prettyNumber === 'undefined' || opts.prettyNumber == true ) { if ( !isNaN(parseInt(value)) ) { formattedNum = prettyNumber(value); } } if (opts['prefix']) { prefix = '<span class="keen-metric-prefix">' + opts['prefix'] + '</span>'; } if (opts['suffix']) { suffix = '<span class="keen-metric-suffix">' + opts['suffix'] + '</span>'; } this.el().innerHTML = '' + '<div class="keen-widget keen-metric" style="background-color: ' + bgColor + '; width:' + styles.width + ';" title="' + value + '">' + '<span class="keen-metric-value">' + prefix + formattedNum + suffix + '</span>' + '<span class="keen-metric-title">' + title + '</span>' + '</div>'; } }; Error = { initialize: function(){}, render: function(text, style){ var err, msg; var defaultStyle = clone(Keen.Error.defaults); var currentStyle = extend(defaultStyle, style); err = document.createElement("div"); err.className = "keen-error"; each(currentStyle, function(value, key){ err.style[key] = value; }); err.style.height = String(this.height() + "px"); err.style.paddingTop = (this.height() / 2 - 15) + "px"; err.style.width = String(this.width() + "px"); msg = document.createElement("span"); msg.innerHTML = text || "Yikes! An error occurred!"; err.appendChild(msg); this.el().innerHTML = ""; this.el().appendChild(err); }, destroy: function(){ this.el().innerHTML = ""; } }; Spinner = { initialize: function(){}, render: function(){ var spinner = document.createElement("div"); var height = this.height() || Keen.Spinner.defaults.height; spinner.className = "keen-loading"; spinner.style.height = String(height + "px"); spinner.style.position = "relative"; spinner.style.width = String(this.width() + "px"); this.el().innerHTML = ""; this.el().appendChild(spinner); this.view._artifacts.spinner = new Keen.Spinner(Keen.Spinner.defaults).spin(spinner); }, destroy: function(){ this.view._artifacts.spinner.stop(); this.view._artifacts.spinner = null; } }; Keen.Dataviz.register('keen-io', { 'metric': Metric, 'error': Error, 'spinner': Spinner }, { capabilities: dataTypes }); }; },{"../../core":18,"../../core/utils/clone":30,"../../core/utils/each":31,"../../core/utils/extend":33,"../dataviz":59,"../utils/prettyNumber":98}],59:[function(require,module,exports){ var clone = require('../core/utils/clone'), each = require('../core/utils/each'), extend = require('../core/utils/extend'), loadScript = require('./utils/loadScript'), loadStyle = require('./utils/loadStyle'); var Keen = require('../core'); var Emitter = require('../core/utils/emitter-shim'); var Dataset = require('../dataset'); function Dataviz(){ this.dataset = new Dataset(); this.view = { _prepared: false, _initialized: false, _rendered: false, _artifacts: { /* state bin */ }, adapter: { library: undefined, chartOptions: {}, chartType: undefined, defaultChartType: undefined, dataType: undefined }, attributes: clone(Dataviz.defaults), defaults: clone(Dataviz.defaults), el: undefined, loader: { library: 'keen-io', chartType: 'spinner' } }; Dataviz.visuals.push(this); }; extend(Dataviz, { dataTypeMap: { 'singular': { library: 'keen-io', chartType: 'metric' }, 'categorical': { library: 'google', chartType: 'piechart' }, 'cat-interval': { library: 'google', chartType: 'columnchart' }, 'cat-ordinal': { library: 'google', chartType: 'barchart' }, 'chronological': { library: 'google', chartType: 'areachart' }, 'cat-chronological': { library: 'google', chartType: 'linechart' }, 'extraction': { library: 'google', chartType: 'table' }, 'nominal': { library: 'google', chartType: 'table' } }, defaults: { colors: [ /* teal red yellow purple orange mint blue green lavender */ '#00bbde', '#fe6672', '#eeb058', '#8a8ad6', '#ff855c', '#00cfbb', '#5a9eed', '#73d483', '#c879bb', '#0099b6', '#d74d58', '#cb9141', '#6b6bb6', '#d86945', '#00aa99', '#4281c9', '#57b566', '#ac5c9e', '#27cceb', '#ff818b', '#f6bf71', '#9b9be1', '#ff9b79', '#26dfcd', '#73aff4', '#87e096', '#d88bcb' ], indexBy: 'timeframe.start', stacked: false }, dependencies: { loading: 0, loaded: 0, urls: {} }, libraries: {}, visuals: [] }); Emitter(Dataviz); Emitter(Dataviz.prototype); Dataviz.register = function(name, methods, config){ var self = this; var loadHandler = function(st) { st.loaded++; if(st.loaded === st.loading) { Keen.loaded = true; Keen.trigger('ready'); } }; Dataviz.libraries[name] = Dataviz.libraries[name] || {}; each(methods, function(method, key){ Dataviz.libraries[name][key] = method; }); if (config && config.capabilities) { Dataviz.libraries[name]._defaults = Dataviz.libraries[name]._defaults || {}; each(config.capabilities, function(typeSet, key){ Dataviz.libraries[name]._defaults[key] = typeSet; }); } if (config && config.dependencies) { each(config.dependencies, function (dependency, index, collection) { var status = Dataviz.dependencies; if(!status.urls[dependency.url]) { status.urls[dependency.url] = true; status.loading++; var method = dependency.type === 'script' ? loadScript : loadStyle; method(dependency.url, function() { if(dependency.cb) { dependency.cb.call(self, function() { loadHandler(status); }); } else { loadHandler(status); } }); } }); } }; Dataviz.find = function(target){ if (!arguments.length) return Dataviz.visuals; var el = target.nodeName ? target : document.querySelector(target), match; each(Dataviz.visuals, function(visual){ if (el == visual.el()){ match = visual; return false; } }); if (match) return match; }; module.exports = Dataviz; },{"../core":18,"../core/utils/clone":30,"../core/utils/each":31,"../core/utils/emitter-shim":32,"../core/utils/extend":33,"../dataset":39,"./utils/loadScript":96,"./utils/loadStyle":97}],60:[function(require,module,exports){ var clone = require("../../core/utils/clone"), extend = require("../../core/utils/extend"), Dataviz = require("../dataviz"), Request = require("../../core/request"); module.exports = function(query, el, cfg) { var DEFAULTS = clone(Dataviz.defaults), visual = new Dataviz(), request = new Request(this, [query]), config = cfg || {}; visual .attributes(extend(DEFAULTS, config)) .el(el) .prepare(); request.refresh(); request.on("complete", function(){ visual .parseRequest(this) .call(function(){ if (config.labels) { this.labels(config.labels); } }) .render(); }); request.on("error", function(res){ visual.error(res.message); }); return visual; }; },{"../../core/request":27,"../../core/utils/clone":30,"../../core/utils/extend":33,"../dataviz":59}],61:[function(require,module,exports){ var Dataviz = require("../dataviz"), extend = require("../../core/utils/extend") module.exports = function(){ var map = extend({}, Dataviz.dataTypeMap), dataType = this.dataType(), library = this.library(), chartType = this.chartType() || this.defaultChartType(); if (!library && map[dataType]) { library = map[dataType].library; } if (library && !chartType && dataType) { chartType = Dataviz.libraries[library]._defaults[dataType][0]; } if (library && !chartType && map[dataType]) { chartType = map[dataType].chartType; } if (library && chartType && Dataviz.libraries[library][chartType]) { return Dataviz.libraries[library][chartType]; } else { return {}; } }; },{"../../core/utils/extend":33,"../dataviz":59}],62:[function(require,module,exports){ module.exports = function(req){ var analysis = req.queries[0].analysis.replace("_", " "), collection = req.queries[0].get('event_collection'), output; output = analysis.replace( /\b./g, function(a){ return a.toUpperCase(); }); if (collection) { output += ' - ' + collection; } return output; }; },{}],63:[function(require,module,exports){ module.exports = function(query){ var isInterval = typeof query.params.interval === "string", isGroupBy = typeof query.params.group_by === "string", is2xGroupBy = query.params.group_by instanceof Array, dataType; if (!isGroupBy && !isInterval) { dataType = 'singular'; } if (isGroupBy && !isInterval) { dataType = 'categorical'; } if (isInterval && !isGroupBy) { dataType = 'chronological'; } if (isInterval && isGroupBy) { dataType = 'cat-chronological'; } if (!isInterval && is2xGroupBy) { dataType = 'categorical'; } if (isInterval && is2xGroupBy) { dataType = 'cat-chronological'; } if (query.analysis === "funnel") { dataType = 'cat-ordinal'; } if (query.analysis === "extraction") { dataType = 'extraction'; } if (query.analysis === "select_unique") { dataType = 'nominal'; } return dataType; }; },{}],64:[function(require,module,exports){ var extend = require('../core/utils/extend'), Dataviz = require('./dataviz'); extend(Dataviz.prototype, { 'adapter' : require('./lib/adapter'), 'attributes' : require('./lib/attributes'), 'call' : require('./lib/call'), 'chartOptions' : require('./lib/chartOptions'), 'chartType' : require('./lib/chartType'), 'colorMapping' : require('./lib/colorMapping'), 'colors' : require('./lib/colors'), 'data' : require('./lib/data'), 'dataType' : require('./lib/dataType'), 'dateFormat' : require('./lib/dateFormat'), 'defaultChartType' : require('./lib/defaultChartType'), 'el' : require('./lib/el'), 'height' : require('./lib/height'), 'indexBy' : require('./lib/indexBy'), 'labelMapping' : require('./lib/labelMapping'), 'labels' : require('./lib/labels'), 'library' : require('./lib/library'), 'parseRawData' : require('./lib/parseRawData'), 'parseRequest' : require('./lib/parseRequest'), 'prepare' : require('./lib/prepare'), 'sortGroups' : require('./lib/sortGroups'), 'sortIntervals' : require('./lib/sortIntervals'), 'stacked' : require('./lib/stacked'), 'title' : require('./lib/title'), 'width' : require('./lib/width') }); extend(Dataviz.prototype, { 'destroy' : require('./lib/actions/destroy'), 'error' : require('./lib/actions/error'), 'initialize' : require('./lib/actions/initialize'), 'render' : require('./lib/actions/render'), 'update' : require('./lib/actions/update') }); module.exports = Dataviz; },{"../core/utils/extend":33,"./dataviz":59,"./lib/actions/destroy":65,"./lib/actions/error":66,"./lib/actions/initialize":67,"./lib/actions/render":68,"./lib/actions/update":69,"./lib/adapter":70,"./lib/attributes":71,"./lib/call":72,"./lib/chartOptions":73,"./lib/chartType":74,"./lib/colorMapping":75,"./lib/colors":76,"./lib/data":77,"./lib/dataType":78,"./lib/dateFormat":79,"./lib/defaultChartType":80,"./lib/el":81,"./lib/height":82,"./lib/indexBy":83,"./lib/labelMapping":84,"./lib/labels":85,"./lib/library":86,"./lib/parseRawData":87,"./lib/parseRequest":88,"./lib/prepare":89,"./lib/sortGroups":90,"./lib/sortIntervals":91,"./lib/stacked":92,"./lib/title":93,"./lib/width":94}],65:[function(require,module,exports){ var getAdapterActions = require("../../helpers/getAdapterActions"); module.exports = function(){ var actions = getAdapterActions.call(this); if (actions.destroy) { actions.destroy.apply(this, arguments); } if (this.el()) { this.el().innerHTML = ""; } this.view._prepared = false; this.view._initialized = false; this.view._rendered = false; this.view._artifacts = {}; return this; }; },{"../../helpers/getAdapterActions":61}],66:[function(require,module,exports){ var getAdapterActions = require("../../helpers/getAdapterActions"), Dataviz = require("../../dataviz"); module.exports = function(){ var actions = getAdapterActions.call(this); if (this.el()) { if (actions['error']) { actions['error'].apply(this, arguments); } else { Dataviz.libraries['keen-io']['error'].render.apply(this, arguments); } } else { this.emit('error', 'No DOM element provided'); } return this; }; },{"../../dataviz":59,"../../helpers/getAdapterActions":61}],67:[function(require,module,exports){ var getAdapterActions = require("../../helpers/getAdapterActions"), Dataviz = require("../../dataviz"); module.exports = function(){ var actions = getAdapterActions.call(this); var loader = Dataviz.libraries[this.view.loader.library][this.view.loader.chartType]; if (this.view._prepared) { if (loader.destroy) loader.destroy.apply(this, arguments); } else { if (this.el()) this.el().innerHTML = ""; } if (actions.initialize) { actions.initialize.apply(this, arguments); } else { this.error('Incorrect chartType'); this.emit('error', 'Incorrect chartType'); } this.view._initialized = true; return this; }; },{"../../dataviz":59,"../../helpers/getAdapterActions":61}],68:[function(require,module,exports){ var getAdapterActions = require("../../helpers/getAdapterActions"), applyTransforms = require("../../utils/applyTransforms"); module.exports = function(){ var actions = getAdapterActions.call(this); applyTransforms.call(this); if (!this.view._initialized) { this.initialize(); } if (this.el() && actions.render) { actions.render.apply(this, arguments); this.view._rendered = true; } return this; }; },{"../../helpers/getAdapterActions":61,"../../utils/applyTransforms":95}],69:[function(require,module,exports){ var getAdapterActions = require("../../helpers/getAdapterActions"), applyTransforms = require("../../utils/applyTransforms"); module.exports = function(){ var actions = getAdapterActions.call(this); applyTransforms.call(this); if (actions.update) { actions.update.apply(this, arguments); } else if (actions.render) { this.render(); } return this; }; },{"../../helpers/getAdapterActions":61,"../../utils/applyTransforms":95}],70:[function(require,module,exports){ var each = require("../../core/utils/each"); module.exports = function(obj){ if (!arguments.length) return this.view.adapter; var self = this; each(obj, function(prop, key){ self.view.adapter[key] = (prop ? prop : null); }); return this; }; },{"../../core/utils/each":31}],71:[function(require,module,exports){ var each = require("../../core/utils/each"); var chartOptions = require("./chartOptions") chartType = require("./chartType"), library = require("./library"); module.exports = function(obj){ if (!arguments.length) return this.view["attributes"]; var self = this; each(obj, function(prop, key){ if (key === "library") { library.call(self, prop); } else if (key === "chartType") { chartType.call(self, prop); } else if (key === "chartOptions") { chartOptions.call(self, prop); } else { self.view["attributes"][key] = prop; } }); return this; }; },{"../../core/utils/each":31,"./chartOptions":73,"./chartType":74,"./library":86}],72:[function(require,module,exports){ module.exports = function(fn){ fn.call(this); return this; }; },{}],73:[function(require,module,exports){ var extend = require('../../core/utils/extend'); module.exports = function(obj){ if (!arguments.length) return this.view.adapter.chartOptions; if (typeof obj === 'object' && obj !== null) { extend(this.view.adapter.chartOptions, obj); } else { this.view.adapter.chartOptions = {}; } return this; }; },{"../../core/utils/extend":33}],74:[function(require,module,exports){ module.exports = function(str){ if (!arguments.length) return this.view.adapter.chartType; this.view.adapter.chartType = (str ? String(str) : null); return this; }; },{}],75:[function(require,module,exports){ var each = require("../../core/utils/each"); module.exports = function(obj){ if (!arguments.length) return this.view["attributes"].colorMapping; this.view["attributes"].colorMapping = (obj ? obj : null); colorMapping.call(this); return this; }; function colorMapping(){ var self = this, schema = this.dataset.schema, data = this.dataset.output(), colorSet = this.view.defaults.colors.slice(), colorMap = this.colorMapping(), dt = this.dataType() || ""; if (colorMap) { if (dt.indexOf("chronological") > -1 || (schema.unpack && data[0].length > 2)) { each(data[0].slice(1), function(label, i){ var color = colorMap[label]; if (color && colorSet[i] !== color) { colorSet.splice(i, 0, color); } }); } else { each(self.dataset.selectColumn(0).slice(1), function(label, i){ var color = colorMap[label]; if (color && colorSet[i] !== color) { colorSet.splice(i, 0, color); } }); } self.view.attributes.colors = colorSet; } } },{"../../core/utils/each":31}],76:[function(require,module,exports){ module.exports = function(arr){ if (!arguments.length) return this.view["attributes"].colors; this.view["attributes"].colors = (arr instanceof Array ? arr : null); this.view.defaults.colors = (arr instanceof Array ? arr : null); return this; }; },{}],77:[function(require,module,exports){ var Dataset = require("../../dataset"), Request = require("../../core/request"); module.exports = function(data){ if (!arguments.length) return this.dataset.output(); if (data instanceof Dataset) { this.dataset = data; } else if (data instanceof Request) { this.parseRequest(data); } else { this.parseRawData(data); } return this; }; },{"../../core/request":27,"../../dataset":39}],78:[function(require,module,exports){ module.exports = function(str){ if (!arguments.length) return this.view.adapter.dataType; this.view.adapter.dataType = (str ? String(str) : null); return this; }; },{}],79:[function(require,module,exports){ module.exports = function(val){ if (!arguments.length) return this.view.attributes.dateFormat; if (typeof val === 'string' || typeof val === 'function') { this.view.attributes.dateFormat = val; } else { this.view.attributes.dateFormat = undefined; } return this; }; },{}],80:[function(require,module,exports){ module.exports = function(str){ if (!arguments.length) return this.view.adapter.defaultChartType; this.view.adapter.defaultChartType = (str ? String(str) : null); return this; }; },{}],81:[function(require,module,exports){ module.exports = function(el){ if (!arguments.length) return this.view.el; this.view.el = el; return this; }; },{}],82:[function(require,module,exports){ module.exports = function(num){ if (!arguments.length) return this.view["attributes"]["height"]; this.view["attributes"]["height"] = (!isNaN(parseInt(num)) ? parseInt(num) : null); return this; }; },{}],83:[function(require,module,exports){ var Dataset = require('../../dataset'), Dataviz = require('../dataviz'), each = require('../../core/utils/each'); module.exports = function(str){ if (!arguments.length) return this.view['attributes'].indexBy; this.view['attributes'].indexBy = (str ? String(str) : Dataviz.defaults.indexBy); indexBy.call(this); return this; }; function indexBy(){ var parser, options; if (this.dataset.output().length > 1 && !isNaN(new Date(this.dataset.output()[1][0]).getTime())) { if (this.dataset.parser && this.dataset.parser.name && this.dataset.parser.options) { if (this.dataset.parser.options.length === 1) { parser = Dataset.parser(this.dataset.parser.name, this.indexBy()); this.dataset.parser.options[0] = this.indexBy(); } else { parser = Dataset.parser(this.dataset.parser.name, this.dataset.parser.options[0], this.indexBy()); this.dataset.parser.options[1] = this.indexBy(); } } else if (this.dataset.output()[0].length === 2) { parser = Dataset.parser('interval', this.indexBy()); this.dataset.parser = { name: 'interval', options: [this.indexBy()] }; } else { parser = Dataset.parser('grouped-interval', this.indexBy()); this.dataset.parser = { name: 'grouped-interval', options: [this.indexBy()] }; } this.dataset = parser(this.dataset.input()); this.dataset.updateColumn(0, function(value){ return (typeof value === 'string') ? new Date(value) : value; }); } } },{"../../core/utils/each":31,"../../dataset":39,"../dataviz":59}],84:[function(require,module,exports){ var each = require("../../core/utils/each"); module.exports = function(obj){ if (!arguments.length) return this.view["attributes"].labelMapping; this.view["attributes"].labelMapping = (obj ? obj : null); applyLabelMapping.call(this); return this; }; function applyLabelMapping(){ var self = this, labelMap = this.labelMapping(), dt = this.dataType() || ""; if (labelMap) { if (dt.indexOf("chronological") > -1 || (self.dataset.output()[0].length > 2)) { each(self.dataset.output()[0], function(c, i){ if (i > 0) { self.dataset.data.output[0][i] = labelMap[c] || c; } }); } else if (self.dataset.output()[0].length === 2) { self.dataset.updateColumn(0, function(c, i){ return labelMap[c] || c; }); } } } },{"../../core/utils/each":31}],85:[function(require,module,exports){ var each = require('../../core/utils/each'); module.exports = function(arr){ if (!arguments.length) { if (!this.view['attributes'].labels || !this.view['attributes'].labels.length) { return getLabels.call(this); } else { return this.view['attributes'].labels; } } else { this.view['attributes'].labels = (arr instanceof Array ? arr : null); setLabels.call(this); return this; } }; function setLabels(){ var self = this, labelSet = this.labels() || null, data = this.dataset.output(), dt = this.dataType() || ''; if (labelSet) { if (dt.indexOf('chronological') > -1 || (data[0].length > 2)) { each(data[0], function(cell,i){ if (i > 0 && labelSet[i-1]) { self.dataset.data.output[0][i] = labelSet[i-1]; } }); } else { each(data, function(row,i){ if (i > 0 && labelSet[i-1]) { self.dataset.data.output[i][0] = labelSet[i-1]; } }); } } } function getLabels(){ var data = this.dataset.output(), dt = this.dataType() || '', labels; if (dt.indexOf('chron') > -1 || (data[0].length > 2)) { labels = this.dataset.selectRow(0).slice(1); } else { labels = this.dataset.selectColumn(0).slice(1); } return labels; } },{"../../core/utils/each":31}],86:[function(require,module,exports){ module.exports = function(str){ if (!arguments.length) return this.view.adapter.library; this.view.adapter.library = (str ? String(str) : null); return this; }; },{}],87:[function(require,module,exports){ var Dataset = require('../../dataset'); var extend = require('../../core/utils/extend'); module.exports = function(response){ var dataType, indexBy = this.indexBy() ? this.indexBy() : 'timestamp.start', parser, parserArgs = [], query = (typeof response.query !== 'undefined') ? response.query : {}; query = extend({ analysis_type: null, event_collection: null, filters: [], group_by: null, interval: null, timeframe: null, timezone: null }, query); if (query.analysis_type === 'funnel') { dataType = 'cat-ordinal'; parser = 'funnel'; } else if (query.analysis_type === 'extraction'){ dataType = 'extraction'; parser = 'extraction'; } else if (query.analysis_type === 'select_unique') { if (!query.group_by && !query.interval) { dataType = 'nominal'; parser = 'list'; } } else if (query.analysis_type) { if (!query.group_by && !query.interval) { dataType = 'singular'; parser = 'metric'; } else if (query.group_by && !query.interval) { if (query.group_by instanceof Array && query.group_by.length > 1) { dataType = 'categorical'; parser = 'double-grouped-metric'; parserArgs.push(query.group_by); } else { dataType = 'categorical'; parser = 'grouped-metric'; } } else if (query.interval && !query.group_by) { dataType = 'chronological'; parser = 'interval'; parserArgs.push(indexBy); } else if (query.group_by && query.interval) { if (query.group_by instanceof Array && query.group_by.length > 1) { dataType = 'cat-chronological'; parser = 'double-grouped-interval'; parserArgs.push(query.group_by); parserArgs.push(indexBy); } else { dataType = 'cat-chronological'; parser = 'grouped-interval'; parserArgs.push(indexBy); } } } if (!parser) { if (typeof response.result === 'number'){ dataType = 'singular'; parser = 'metric'; } if (response.result instanceof Array && response.result.length > 0){ if (response.result[0].timeframe && (typeof response.result[0].value == 'number' || response.result[0].value == null)) { dataType = 'chronological'; parser = 'interval'; parserArgs.push(indexBy) } if (typeof response.result[0].result == 'number'){ dataType = 'categorical'; parser = 'grouped-metric'; } if (response.result[0].value instanceof Array){ dataType = 'cat-chronological'; parser = 'grouped-interval'; parserArgs.push(indexBy) } if (typeof response.result[0] == 'number' && typeof response.steps !== "undefined"){ dataType = 'cat-ordinal'; parser = 'funnel'; } if ((typeof response.result[0] == 'string' || typeof response.result[0] == 'number') && typeof response.steps === "undefined"){ dataType = 'nominal'; parser = 'list'; } if (dataType === void 0) { dataType = 'extraction'; parser = 'extraction'; } } } if (dataType) { this.dataType(dataType); } this.dataset = Dataset.parser.apply(this, [parser].concat(parserArgs))(response); if (parser.indexOf('interval') > -1) { this.dataset.updateColumn(0, function(value, i){ return new Date(value); }); } return this; }; },{"../../core/utils/extend":33,"../../dataset":39}],88:[function(require,module,exports){ var Query = require('../../core/query'); var dataType = require('./dataType'), extend = require('../../core/utils/extend'), getDefaultTitle = require('../helpers/getDefaultTitle'), getQueryDataType = require('../helpers/getQueryDataType'), parseRawData = require('./parseRawData'), title = require('./title'); module.exports = function(req){ var response = req.data instanceof Array ? req.data[0] : req.data; if (req.queries[0] instanceof Query) { response.query = extend({ analysis_type: req.queries[0].analysis }, req.queries[0].params); dataType.call(this, getQueryDataType(req.queries[0])); this.view.defaults.title = getDefaultTitle.call(this, req); if (!title.call(this)) { title.call(this, this.view.defaults.title); } } parseRawData.call(this, response); return this; }; },{"../../core/query":26,"../../core/utils/extend":33,"../helpers/getDefaultTitle":62,"../helpers/getQueryDataType":63,"./dataType":78,"./parseRawData":87,"./title":93}],89:[function(require,module,exports){ var Dataviz = require("../dataviz"); module.exports = function(){ var loader; if (this.view._rendered) { this.destroy(); } if (this.el()) { this.el().innerHTML = ""; loader = Dataviz.libraries[this.view.loader.library][this.view.loader.chartType]; if (loader.initialize) { loader.initialize.apply(this, arguments); } if (loader.render) { loader.render.apply(this, arguments); } this.view._prepared = true; } return this; }; },{"../dataviz":59}],90:[function(require,module,exports){ module.exports = function(str){ if (!arguments.length) return this.view["attributes"].sortGroups; this.view["attributes"].sortGroups = (str ? String(str) : null); runSortGroups.call(this); return this; }; function runSortGroups(){ var dt = this.dataType(); if (!this.sortGroups()) return; if ((dt && dt.indexOf("chronological") > -1) || this.data()[0].length > 2) { this.dataset.sortColumns(this.sortGroups(), this.dataset.getColumnSum); } else if (dt && (dt.indexOf("cat-") > -1 || dt.indexOf("categorical") > -1)) { this.dataset.sortRows(this.sortGroups(), this.dataset.getRowSum); } return; } },{}],91:[function(require,module,exports){ module.exports = function(str){ if (!arguments.length) return this.view["attributes"].sortIntervals; this.view["attributes"].sortIntervals = (str ? String(str) : null); runSortIntervals.call(this); return this; }; function runSortIntervals(){ if (!this.sortIntervals()) return; this.dataset.sortRows(this.sortIntervals()); return; } },{}],92:[function(require,module,exports){ module.exports = function(bool){ if (!arguments.length) return this.view['attributes']['stacked']; this.view['attributes']['stacked'] = bool ? true : false; return this; }; },{}],93:[function(require,module,exports){ module.exports = function(str){ if (!arguments.length) return this.view["attributes"]["title"]; this.view["attributes"]["title"] = (str ? String(str) : null); return this; }; },{}],94:[function(require,module,exports){ module.exports = function(num){ if (!arguments.length) return this.view["attributes"]["width"]; this.view["attributes"]["width"] = (!isNaN(parseInt(num)) ? parseInt(num) : null); return this; }; },{}],95:[function(require,module,exports){ module.exports = function(){ if (this.labelMapping()) { this.labelMapping(this.labelMapping()); } if (this.colorMapping()) { this.colorMapping(this.colorMapping()); } if (this.sortGroups()) { this.sortGroups(this.sortGroups()); } if (this.sortIntervals()) { this.sortIntervals(this.sortIntervals()); } }; },{}],96:[function(require,module,exports){ module.exports = function(url, cb) { var doc = document; var handler; var head = doc.head || doc.getElementsByTagName("head"); setTimeout(function () { if ('item' in head) { if (!head[0]) { setTimeout(arguments.callee, 25); return; } head = head[0]; } var script = doc.createElement("script"), scriptdone = false; script.onload = script.onreadystatechange = function () { if ((script.readyState && script.readyState !== "complete" && script.readyState !== "loaded") || scriptdone) { return false; } script.onload = script.onreadystatechange = null; scriptdone = true; cb(); }; script.src = url; head.insertBefore(script, head.firstChild); }, 0); if (doc.readyState === null && doc.addEventListener) { doc.readyState = "loading"; doc.addEventListener("DOMContentLoaded", handler = function () { doc.removeEventListener("DOMContentLoaded", handler, false); doc.readyState = "complete"; }, false); } }; },{}],97:[function(require,module,exports){ module.exports = function(url, cb) { var link = document.createElement('link'); link.setAttribute('rel', 'stylesheet'); link.type = 'text/css'; link.href = url; cb(); document.head.appendChild(link); }; },{}],98:[function(require,module,exports){ module.exports = function(_input) { var input = Number(_input), sciNo = input.toPrecision(3), prefix = "", suffixes = ["", "k", "M", "B", "T"]; if (Number(sciNo) == input && String(input).length <= 4) { return String(input); } if(input >= 1 || input <= -1) { if(input < 0){ input = -input; prefix = "-"; } return prefix + recurse(input, 0); } else { return input.toPrecision(3); } function recurse(input, iteration) { var input = String(input); var split = input.split("."); if(split.length > 1) { input = split[0]; var rhs = split[1]; if (input.length == 2 && rhs.length > 0) { if (rhs.length > 0) { input = input + "." + rhs.charAt(0); } else { input += "0"; } } else if (input.length == 1 && rhs.length > 0) { input = input + "." + rhs.charAt(0); if(rhs.length > 1) { input += rhs.charAt(1); } else { input += "0"; } } } var numNumerals = input.length; if (input.split(".").length > 1) { numNumerals--; } if(numNumerals <= 3) { return String(input) + suffixes[iteration]; } else { return recurse(Number(input) / 1000, iteration + 1); } } }; },{}],99:[function(require,module,exports){ (function (global){ ;(function (f) { if (typeof define === "function" && define.amd) { define("keen", [], function(){ return f(); }); } if (typeof exports === "object" && typeof module !== "undefined") { module.exports = f(); } var g = null; if (typeof window !== "undefined") { g = window; } else if (typeof global !== "undefined") { g = global; } else if (typeof self !== "undefined") { g = self; } if (g) { g.Keen = f(); } })(function() { "use strict"; var Keen = require("./core"), extend = require("./core/utils/extend"); extend(Keen.prototype, { "addEvent" : require("./core/lib/addEvent"), "addEvents" : require("./core/lib/addEvents"), "setGlobalProperties" : require("./core/lib/setGlobalProperties"), "trackExternalLink" : require("./core/lib/trackExternalLink"), "get" : require("./core/lib/get"), "post" : require("./core/lib/post"), "put" : require("./core/lib/post"), "run" : require("./core/lib/run"), "savedQueries" : require("./core/saved-queries"), "draw" : require("./dataviz/extensions/draw") }); Keen.Query = require("./core/query"); Keen.Request = require("./core/request"); Keen.Dataset = require("./dataset"); Keen.Dataviz = require("./dataviz"); Keen.Base64 = require("./core/utils/base64"); Keen.Spinner = require("spin.js"); Keen.utils = { "domready" : require("domready"), "each" : require("./core/utils/each"), "extend" : extend, "parseParams" : require("./core/utils/parseParams"), "prettyNumber" : require("./dataviz/utils/prettyNumber") }; require("./dataviz/adapters/keen-io")(); require("./dataviz/adapters/google")(); require("./dataviz/adapters/c3")(); require("./dataviz/adapters/chartjs")(); if (Keen.loaded) { setTimeout(function(){ Keen.utils.domready(function(){ Keen.emit("ready"); }); }, 0); } require("./core/async")(); module.exports = Keen; return Keen; }); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./core":18,"./core/async":10,"./core/lib/addEvent":19,"./core/lib/addEvents":20,"./core/lib/get":21,"./core/lib/post":22,"./core/lib/run":23,"./core/lib/setGlobalProperties":24,"./core/lib/trackExternalLink":25,"./core/query":26,"./core/request":27,"./core/saved-queries":28,"./core/utils/base64":29,"./core/utils/each":31,"./core/utils/extend":33,"./core/utils/parseParams":35,"./dataset":39,"./dataviz":64,"./dataviz/adapters/c3":54,"./dataviz/adapters/chartjs":56,"./dataviz/adapters/google":57,"./dataviz/adapters/keen-io":58,"./dataviz/extensions/draw":60,"./dataviz/utils/prettyNumber":98,"domready":2,"spin.js":5}]},{},[99]);
keicheng/cdnjs
ajax/libs/keen-js/3.4.1/keen.js
JavaScript
mit
186,623
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * @fileOverview Defines the {@link CKEDITOR.lang} object, for the * Latvian language. */ /**#@+ @type String @example */ /** * Constains the dictionary of language entries. * @namespace */ CKEDITOR.lang['lv'] = { /** * The language reading direction. Possible values are "rtl" for * Right-To-Left languages (like Arabic) and "ltr" for Left-To-Right * languages (like English). * @default 'ltr' */ dir : 'ltr', /* * Screenreader titles. Please note that screenreaders are not always capable * of reading non-English words. So be careful while translating it. */ editorTitle : 'Rich text editor, %1, press ALT 0 for help.', // MISSING // ARIA descriptions. toolbars : 'Editor toolbars', // MISSING editor : 'Rich Text Editor', // MISSING // Toolbar buttons without dialogs. source : 'HTML kods', newPage : 'Jauna lapa', save : 'Saglabāt', preview : 'Pārskatīt', cut : 'Izgriezt', copy : 'Kopēt', paste : 'Ievietot', print : 'Drukāt', underline : 'Apakšsvītra', bold : 'Treknu šriftu', italic : 'Slīprakstā', selectAll : 'Iezīmēt visu', removeFormat : 'Noņemt stilus', strike : 'Pārsvītrots', subscript : 'Zemrakstā', superscript : 'Augšrakstā', horizontalrule : 'Ievietot horizontālu Atdalītājsvītru', pagebreak : 'Ievietot lapas pārtraukumu', pagebreakAlt : 'Page Break', // MISSING unlink : 'Noņemt hipersaiti', undo : 'Atcelt', redo : 'Atkārtot', // Common messages and labels. common : { browseServer : 'Skatīt servera saturu', url : 'URL', protocol : 'Protokols', upload : 'Augšupielādēt', uploadSubmit : 'Nosūtīt serverim', image : 'Attēls', flash : 'Flash', form : 'Forma', checkbox : 'Atzīmēšanas kastīte', radio : 'Izvēles poga', textField : 'Teksta rinda', textarea : 'Teksta laukums', hiddenField : 'Paslēpta teksta rinda', button : 'Poga', select : 'Iezīmēšanas lauks', imageButton : 'Attēlpoga', notSet : '<nav iestatīts>', id : 'Id', name : 'Nosaukums', langDir : 'Valodas lasīšanas virziens', langDirLtr : 'No kreisās uz labo (LTR)', langDirRtl : 'No labās uz kreiso (RTL)', langCode : 'Valodas kods', longDescr : 'Gara apraksta Hipersaite', cssClass : 'Stilu saraksta klases', advisoryTitle : 'Konsultatīvs virsraksts', cssStyle : 'Stils', ok : 'Darīts!', cancel : 'Atcelt', close : 'Close', // MISSING preview : 'Preview', // MISSING generalTab : 'General', // MISSING advancedTab : 'Izvērstais', validateNumberFailed : 'This value is not a number.', // MISSING confirmNewPage : 'Any unsaved changes to this content will be lost. Are you sure you want to load new page?', // MISSING confirmCancel : 'Some of the options have been changed. Are you sure to close the dialog?', // MISSING options : 'Options', // MISSING target : 'Target', // MISSING targetNew : 'New Window (_blank)', // MISSING targetTop : 'Topmost Window (_top)', // MISSING targetSelf : 'Same Window (_self)', // MISSING targetParent : 'Parent Window (_parent)', // MISSING langDirLTR : 'Left to Right (LTR)', // MISSING langDirRTL : 'Right to Left (RTL)', // MISSING styles : 'Style', // MISSING cssClasses : 'Stylesheet Classes', // MISSING width : 'Platums', height : 'Augstums', align : 'Nolīdzināt', alignLeft : 'Pa kreisi', alignRight : 'Pa labi', alignCenter : 'Centrēti', alignTop : 'Augšā', alignMiddle : 'Vertikāli centrēts', alignBottom : 'Apakšā', invalidHeight : 'Height must be a number.', // MISSING invalidWidth : 'Width must be a number.', // MISSING invalidCssLength : 'Value specified for the "%1" field must be a positive number with or without a valid CSS measurement unit (px, %, in, cm, mm, em, ex, pt, or pc).', // MISSING invalidHtmlLength : 'Value specified for the "%1" field must be a positive number with or without a valid HTML measurement unit (px or %).', // MISSING // Put the voice-only part of the label in the span. unavailable : '%1<span class="cke_accessibility">, unavailable</span>' // MISSING }, contextmenu : { options : 'Context Menu Options' // MISSING }, // Special char dialog. specialChar : { toolbar : 'Ievietot speciālo simbolu', title : 'Ievietot īpašu simbolu', options : 'Special Character Options' // MISSING }, // Link dialog. link : { toolbar : 'Ievietot/Labot hipersaiti', other : '<cits>', menu : 'Labot hipersaiti', title : 'Hipersaite', info : 'Hipersaites informācija', target : 'Mērķis', upload : 'Augšupielādēt', advanced : 'Izvērstais', type : 'Hipersaites tips', toUrl : 'URL', // MISSING toAnchor : 'Iezīme šajā lapā', toEmail : 'E-pasts', targetFrame : '<ietvars>', targetPopup : '<uznirstošā logā>', targetFrameName : 'Mērķa ietvara nosaukums', targetPopupName : 'Uznirstošā loga nosaukums', popupFeatures : 'Uznirstošā loga nosaukums īpašības', popupResizable : 'Resizable', // MISSING popupStatusBar : 'Statusa josla', popupLocationBar: 'Atrašanās vietas josla', popupToolbar : 'Rīku josla', popupMenuBar : 'Izvēlnes josla', popupFullScreen : 'Pilnā ekrānā (IE)', popupScrollBars : 'Ritjoslas', popupDependent : 'Atkarīgs (Netscape)', popupLeft : 'Kreisā koordināte', popupTop : 'Augšējā koordināte', id : 'Id', // MISSING langDir : 'Valodas lasīšanas virziens', langDirLTR : 'No kreisās uz labo (LTR)', langDirRTL : 'No labās uz kreiso (RTL)', acccessKey : 'Pieejas kods', name : 'Nosaukums', langCode : 'Valodas lasīšanas virziens', tabIndex : 'Ciļņu indekss', advisoryTitle : 'Konsultatīvs virsraksts', advisoryContentType : 'Konsultatīvs satura tips', cssClasses : 'Stilu saraksta klases', charset : 'Pievienotā resursa kodu tabula', styles : 'Stils', rel : 'Relationship', // MISSING selectAnchor : 'Izvēlēties iezīmi', anchorName : 'Pēc iezīmes nosaukuma', anchorId : 'Pēc elementa ID', emailAddress : 'E-pasta adrese', emailSubject : 'Ziņas tēma', emailBody : 'Ziņas saturs', noAnchors : '(Šajā dokumentā nav iezīmju)', noUrl : 'Lūdzu norādi hipersaiti', noEmail : 'Lūdzu norādi e-pasta adresi' }, // Anchor dialog anchor : { toolbar : 'Ievietot/Labot iezīmi', menu : 'Iezīmes īpašības', title : 'Iezīmes īpašības', name : 'Iezīmes nosaukums', errorName : 'Lūdzu norādiet iezīmes nosaukumu', remove : 'Remove Anchor' // MISSING }, // List style dialog list: { numberedTitle : 'Numbered List Properties', // MISSING bulletedTitle : 'Bulleted List Properties', // MISSING type : 'Type', // MISSING start : 'Start', // MISSING validateStartNumber :'List start number must be a whole number.', // MISSING circle : 'Circle', // MISSING disc : 'Disc', // MISSING square : 'Square', // MISSING none : 'None', // MISSING notset : '<not set>', // MISSING armenian : 'Armenian numbering', // MISSING georgian : 'Georgian numbering (an, ban, gan, etc.)', // MISSING lowerRoman : 'Lower Roman (i, ii, iii, iv, v, etc.)', // MISSING upperRoman : 'Upper Roman (I, II, III, IV, V, etc.)', // MISSING lowerAlpha : 'Lower Alpha (a, b, c, d, e, etc.)', // MISSING upperAlpha : 'Upper Alpha (A, B, C, D, E, etc.)', // MISSING lowerGreek : 'Lower Greek (alpha, beta, gamma, etc.)', // MISSING decimal : 'Decimal (1, 2, 3, etc.)', // MISSING decimalLeadingZero : 'Decimal leading zero (01, 02, 03, etc.)' // MISSING }, // Find And Replace Dialog findAndReplace : { title : 'Find and Replace', // MISSING find : 'Meklēt', replace : 'Nomainīt', findWhat : 'Meklēt:', replaceWith : 'Nomainīt uz:', notFoundMsg : 'Norādītā frāze netika atrasta.', matchCase : 'Reģistrjūtīgs', matchWord : 'Jāsakrīt pilnībā', matchCyclic : 'Match cyclic', // MISSING replaceAll : 'Aizvietot visu', replaceSuccessMsg : '%1 occurrence(s) replaced.' // MISSING }, // Table Dialog table : { toolbar : 'Tabula', title : 'Tabulas īpašības', menu : 'Tabulas īpašības', deleteTable : 'Dzēst tabulu', rows : 'Rindas', columns : 'Kolonnas', border : 'Rāmja izmērs', widthPx : 'pikseļos', widthPc : 'procentuāli', widthUnit : 'width unit', // MISSING cellSpace : 'Rūtiņu atstatums', cellPad : 'Rūtiņu nobīde', caption : 'Leģenda', summary : 'Anotācija', headers : 'Headers', // MISSING headersNone : 'None', // MISSING headersColumn : 'First column', // MISSING headersRow : 'First Row', // MISSING headersBoth : 'Both', // MISSING invalidRows : 'Number of rows must be a number greater than 0.', // MISSING invalidCols : 'Number of columns must be a number greater than 0.', // MISSING invalidBorder : 'Border size must be a number.', // MISSING invalidWidth : 'Table width must be a number.', // MISSING invalidHeight : 'Table height must be a number.', // MISSING invalidCellSpacing : 'Cell spacing must be a positive number.', // MISSING invalidCellPadding : 'Cell padding must be a positive number.', // MISSING cell : { menu : 'Šūna', insertBefore : 'Insert Cell Before', // MISSING insertAfter : 'Insert Cell After', // MISSING deleteCell : 'Dzēst rūtiņas', merge : 'Apvienot rūtiņas', mergeRight : 'Merge Right', // MISSING mergeDown : 'Merge Down', // MISSING splitHorizontal : 'Split Cell Horizontally', // MISSING splitVertical : 'Split Cell Vertically', // MISSING title : 'Cell Properties', // MISSING cellType : 'Cell Type', // MISSING rowSpan : 'Rows Span', // MISSING colSpan : 'Columns Span', // MISSING wordWrap : 'Word Wrap', // MISSING hAlign : 'Horizontal Alignment', // MISSING vAlign : 'Vertical Alignment', // MISSING alignBaseline : 'Baseline', // MISSING bgColor : 'Background Color', // MISSING borderColor : 'Border Color', // MISSING data : 'Data', // MISSING header : 'Header', // MISSING yes : 'Yes', // MISSING no : 'No', // MISSING invalidWidth : 'Cell width must be a number.', // MISSING invalidHeight : 'Cell height must be a number.', // MISSING invalidRowSpan : 'Rows span must be a whole number.', // MISSING invalidColSpan : 'Columns span must be a whole number.', // MISSING chooseColor : 'Choose' // MISSING }, row : { menu : 'Rinda', insertBefore : 'Insert Row Before', // MISSING insertAfter : 'Insert Row After', // MISSING deleteRow : 'Dzēst rindas' }, column : { menu : 'Kolonna', insertBefore : 'Insert Column Before', // MISSING insertAfter : 'Insert Column After', // MISSING deleteColumn : 'Dzēst kolonnas' } }, // Button Dialog. button : { title : 'Pogas īpašības', text : 'Teksts (vērtība)', type : 'Tips', typeBtn : 'Button', // MISSING typeSbm : 'Submit', // MISSING typeRst : 'Reset' // MISSING }, // Checkbox and Radio Button Dialogs. checkboxAndRadio : { checkboxTitle : 'Atzīmēšanas kastītes īpašības', radioTitle : 'Izvēles poga īpašības', value : 'Vērtība', selected : 'Iezīmēts' }, // Form Dialog. form : { title : 'Formas īpašības', menu : 'Formas īpašības', action : 'Darbība', method : 'Metode', encoding : 'Encoding' // MISSING }, // Select Field Dialog. select : { title : 'Iezīmēšanas lauka īpašības', selectInfo : 'Informācija', opAvail : 'Pieejamās iespējas', value : 'Vērtība', size : 'Izmērs', lines : 'rindas', chkMulti : 'Atļaut vairākus iezīmējumus', opText : 'Teksts', opValue : 'Vērtība', btnAdd : 'Pievienot', btnModify : 'Veikt izmaiņas', btnUp : 'Augšup', btnDown : 'Lejup', btnSetValue : 'Noteikt kā iezīmēto vērtību', btnDelete : 'Dzēst' }, // Textarea Dialog. textarea : { title : 'Teksta laukuma īpašības', cols : 'Kolonnas', rows : 'Rindas' }, // Text Field Dialog. textfield : { title : 'Teksta rindas īpašības', name : 'Nosaukums', value : 'Vērtība', charWidth : 'Simbolu platums', maxChars : 'Simbolu maksimālais daudzums', type : 'Tips', typeText : 'Teksts', typePass : 'Parole' }, // Hidden Field Dialog. hidden : { title : 'Paslēptās teksta rindas īpašības', name : 'Nosaukums', value : 'Vērtība' }, // Image Dialog. image : { title : 'Attēla īpašības', titleButton : 'Attēlpogas īpašības', menu : 'Attēla īpašības', infoTab : 'Informācija par attēlu', btnUpload : 'Nosūtīt serverim', upload : 'Augšupielādēt', alt : 'Alternatīvais teksts', lockRatio : 'Nemainīga Augstuma/Platuma attiecība', resetSize : 'Atjaunot sākotnējo izmēru', border : 'Rāmis', hSpace : 'Horizontālā telpa', vSpace : 'Vertikālā telpa', alertUrl : 'Lūdzu norādīt attēla hipersaiti', linkTab : 'Hipersaite', button2Img : 'Do you want to transform the selected image button on a simple image?', // MISSING img2Button : 'Do you want to transform the selected image on a image button?', // MISSING urlMissing : 'Image source URL is missing.', // MISSING validateBorder : 'Border must be a whole number.', // MISSING validateHSpace : 'HSpace must be a whole number.', // MISSING validateVSpace : 'VSpace must be a whole number.' // MISSING }, // Flash Dialog flash : { properties : 'Flash īpašības', propertiesTab : 'Properties', // MISSING title : 'Flash īpašības', chkPlay : 'Automātiska atskaņošana', chkLoop : 'Nepārtraukti', chkMenu : 'Atļaut Flash izvēlni', chkFull : 'Allow Fullscreen', // MISSING scale : 'Mainīt izmēru', scaleAll : 'Rādīt visu', scaleNoBorder : 'Bez rāmja', scaleFit : 'Precīzs izmērs', access : 'Script Access', // MISSING accessAlways : 'Always', // MISSING accessSameDomain: 'Same domain', // MISSING accessNever : 'Never', // MISSING alignAbsBottom : 'Absolūti apakšā', alignAbsMiddle : 'Absolūti vertikāli centrēts', alignBaseline : 'Pamatrindā', alignTextTop : 'Teksta augšā', quality : 'Quality', // MISSING qualityBest : 'Best', // MISSING qualityHigh : 'High', // MISSING qualityAutoHigh : 'Auto High', // MISSING qualityMedium : 'Medium', // MISSING qualityAutoLow : 'Auto Low', // MISSING qualityLow : 'Low', // MISSING windowModeWindow: 'Window', // MISSING windowModeOpaque: 'Opaque', // MISSING windowModeTransparent : 'Transparent', // MISSING windowMode : 'Window mode', // MISSING flashvars : 'Variables for Flash', // MISSING bgcolor : 'Fona krāsa', hSpace : 'Horizontālā telpa', vSpace : 'Vertikālā telpa', validateSrc : 'Lūdzu norādi hipersaiti', validateHSpace : 'HSpace must be a number.', // MISSING validateVSpace : 'VSpace must be a number.' // MISSING }, // Speller Pages Dialog spellCheck : { toolbar : 'Pareizrakstības pārbaude', title : 'Spell Check', // MISSING notAvailable : 'Sorry, but service is unavailable now.', // MISSING errorLoading : 'Error loading application service host: %s.', // MISSING notInDic : 'Netika atrasts vārdnīcā', changeTo : 'Nomainīt uz', btnIgnore : 'Ignorēt', btnIgnoreAll : 'Ignorēt visu', btnReplace : 'Aizvietot', btnReplaceAll : 'Aizvietot visu', btnUndo : 'Atcelt', noSuggestions : '- Nav ieteikumu -', progress : 'Notiek pareizrakstības pārbaude...', noMispell : 'Pareizrakstības pārbaude pabeigta: kļūdas netika atrastas', noChanges : 'Pareizrakstības pārbaude pabeigta: nekas netika labots', oneChange : 'Pareizrakstības pārbaude pabeigta: 1 vārds izmainīts', manyChanges : 'Pareizrakstības pārbaude pabeigta: %1 vārdi tika mainīti', ieSpellDownload : 'Pareizrakstības pārbaudītājs nav pievienots. Vai vēlaties to lejupielādēt tagad?' }, smiley : { toolbar : 'Smaidiņi', title : 'Ievietot smaidiņu', options : 'Smiley Options' // MISSING }, elementsPath : { eleLabel : 'Elements path', // MISSING eleTitle : '%1 element' // MISSING }, numberedlist : 'Numurēts saraksts', bulletedlist : 'Izcelts saraksts', indent : 'Palielināt atkāpi', outdent : 'Samazināt atkāpi', justify : { left : 'Izlīdzināt pa kreisi', center : 'Izlīdzināt pret centru', right : 'Izlīdzināt pa labi', block : 'Izlīdzināt malas' }, blockquote : 'Block Quote', // MISSING clipboard : { title : 'Ievietot', cutError : 'Jūsu pārlūkprogrammas drošības iestatījumi nepieļauj editoram automātiski veikt izgriešanas darbību. Lūdzu, izmantojiet (Ctrl/Cmd+X, lai veiktu šo darbību.', copyError : 'Jūsu pārlūkprogrammas drošības iestatījumi nepieļauj editoram automātiski veikt kopēšanas darbību. Lūdzu, izmantojiet (Ctrl/Cmd+C), lai veiktu šo darbību.', pasteMsg : 'Lūdzu, ievietojiet tekstu šajā laukumā, izmantojot klaviatūru (<STRONG>Ctrl/Cmd+V</STRONG>) un apstipriniet ar <STRONG>Darīts!</STRONG>.', securityMsg : 'Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.', // MISSING pasteArea : 'Paste Area' // MISSING }, pastefromword : { confirmCleanup : 'The text you want to paste seems to be copied from Word. Do you want to clean it before pasting?', // MISSING toolbar : 'Ievietot no Worda', title : 'Ievietot no Worda', error : 'It was not possible to clean up the pasted data due to an internal error' // MISSING }, pasteText : { button : 'Ievietot kā vienkāršu tekstu', title : 'Ievietot kā vienkāršu tekstu' }, templates : { button : 'Sagataves', title : 'Satura sagataves', options : 'Template Options', // MISSING insertOption : 'Replace actual contents', // MISSING selectPromptMsg : 'Lūdzu, norādiet sagatavi, ko atvērt editorā<br>(patreizējie dati tiks zaudēti):', emptyListMsg : '(Nav norādītas sagataves)' }, showBlocks : 'Show Blocks', // MISSING stylesCombo : { label : 'Stils', panelTitle : 'Formatting Styles', // MISSING panelTitle1 : 'Block Styles', // MISSING panelTitle2 : 'Inline Styles', // MISSING panelTitle3 : 'Object Styles' // MISSING }, format : { label : 'Formāts', panelTitle : 'Formāts', tag_p : 'Normāls teksts', tag_pre : 'Formatēts teksts', tag_address : 'Adrese', tag_h1 : 'Virsraksts 1', tag_h2 : 'Virsraksts 2', tag_h3 : 'Virsraksts 3', tag_h4 : 'Virsraksts 4', tag_h5 : 'Virsraksts 5', tag_h6 : 'Virsraksts 6', tag_div : 'Rindkopa (DIV)' }, div : { title : 'Create Div Container', // MISSING toolbar : 'Create Div Container', // MISSING cssClassInputLabel : 'Stylesheet Classes', // MISSING styleSelectLabel : 'Style', // MISSING IdInputLabel : 'Id', // MISSING languageCodeInputLabel : ' Language Code', // MISSING inlineStyleInputLabel : 'Inline Style', // MISSING advisoryTitleInputLabel : 'Advisory Title', // MISSING langDirLabel : 'Language Direction', // MISSING langDirLTRLabel : 'Left to Right (LTR)', // MISSING langDirRTLLabel : 'Right to Left (RTL)', // MISSING edit : 'Edit Div', // MISSING remove : 'Remove Div' // MISSING }, iframe : { title : 'IFrame Properties', // MISSING toolbar : 'IFrame', // MISSING noUrl : 'Please type the iframe URL', // MISSING scrolling : 'Enable scrollbars', // MISSING border : 'Show frame border' // MISSING }, font : { label : 'Šrifts', voiceLabel : 'Font', // MISSING panelTitle : 'Šrifts' }, fontSize : { label : 'Izmērs', voiceLabel : 'Font Size', // MISSING panelTitle : 'Izmērs' }, colorButton : { textColorTitle : 'Teksta krāsa', bgColorTitle : 'Fona krāsa', panelTitle : 'Colors', // MISSING auto : 'Automātiska', more : 'Plašāka palete...' }, colors : { '000' : 'Black', // MISSING '800000' : 'Maroon', // MISSING '8B4513' : 'Saddle Brown', // MISSING '2F4F4F' : 'Dark Slate Gray', // MISSING '008080' : 'Teal', // MISSING '000080' : 'Navy', // MISSING '4B0082' : 'Indigo', // MISSING '696969' : 'Dark Gray', // MISSING 'B22222' : 'Fire Brick', // MISSING 'A52A2A' : 'Brown', // MISSING 'DAA520' : 'Golden Rod', // MISSING '006400' : 'Dark Green', // MISSING '40E0D0' : 'Turquoise', // MISSING '0000CD' : 'Medium Blue', // MISSING '800080' : 'Purple', // MISSING '808080' : 'Gray', // MISSING 'F00' : 'Red', // MISSING 'FF8C00' : 'Dark Orange', // MISSING 'FFD700' : 'Gold', // MISSING '008000' : 'Green', // MISSING '0FF' : 'Cyan', // MISSING '00F' : 'Blue', // MISSING 'EE82EE' : 'Violet', // MISSING 'A9A9A9' : 'Dim Gray', // MISSING 'FFA07A' : 'Light Salmon', // MISSING 'FFA500' : 'Orange', // MISSING 'FFFF00' : 'Yellow', // MISSING '00FF00' : 'Lime', // MISSING 'AFEEEE' : 'Pale Turquoise', // MISSING 'ADD8E6' : 'Light Blue', // MISSING 'DDA0DD' : 'Plum', // MISSING 'D3D3D3' : 'Light Grey', // MISSING 'FFF0F5' : 'Lavender Blush', // MISSING 'FAEBD7' : 'Antique White', // MISSING 'FFFFE0' : 'Light Yellow', // MISSING 'F0FFF0' : 'Honeydew', // MISSING 'F0FFFF' : 'Azure', // MISSING 'F0F8FF' : 'Alice Blue', // MISSING 'E6E6FA' : 'Lavender', // MISSING 'FFF' : 'White' // MISSING }, scayt : { title : 'Spell Check As You Type', // MISSING opera_title : 'Not supported by Opera', // MISSING enable : 'Enable SCAYT', // MISSING disable : 'Disable SCAYT', // MISSING about : 'About SCAYT', // MISSING toggle : 'Toggle SCAYT', // MISSING options : 'Options', // MISSING langs : 'Languages', // MISSING moreSuggestions : 'More suggestions', // MISSING ignore : 'Ignore', // MISSING ignoreAll : 'Ignore All', // MISSING addWord : 'Add Word', // MISSING emptyDic : 'Dictionary name should not be empty.', // MISSING optionsTab : 'Options', // MISSING allCaps : 'Ignore All-Caps Words', // MISSING ignoreDomainNames : 'Ignore Domain Names', // MISSING mixedCase : 'Ignore Words with Mixed Case', // MISSING mixedWithDigits : 'Ignore Words with Numbers', // MISSING languagesTab : 'Languages', // MISSING dictionariesTab : 'Dictionaries', // MISSING dic_field_name : 'Dictionary name', // MISSING dic_create : 'Create', // MISSING dic_restore : 'Restore', // MISSING dic_delete : 'Delete', // MISSING dic_rename : 'Rename', // MISSING dic_info : 'Initially the User Dictionary is stored in a Cookie. However, Cookies are limited in size. When the User Dictionary grows to a point where it cannot be stored in a Cookie, then the dictionary may be stored on our server. To store your personal dictionary on our server you should specify a name for your dictionary. If you already have a stored dictionary, please type its name and click the Restore button.', // MISSING aboutTab : 'About' // MISSING }, about : { title : 'About CKEditor', // MISSING dlgTitle : 'About CKEditor', // MISSING help : 'Check $1 for help.', // MISSING userGuide : 'CKEditor User\'s Guide', // MISSING moreInfo : 'For licensing information please visit our web site:', // MISSING copy : 'Copyright &copy; $1. All rights reserved.' // MISSING }, maximize : 'Maximize', // MISSING minimize : 'Minimize', // MISSING fakeobjects : { anchor : 'Anchor', // MISSING flash : 'Flash Animation', // MISSING iframe : 'IFrame', // MISSING hiddenfield : 'Hidden Field', // MISSING unknown : 'Unknown Object' // MISSING }, resize : 'Drag to resize', // MISSING colordialog : { title : 'Select color', // MISSING options : 'Color Options', // MISSING highlight : 'Highlight', // MISSING selected : 'Selected Color', // MISSING clear : 'Clear' // MISSING }, toolbarCollapse : 'Collapse Toolbar', // MISSING toolbarExpand : 'Expand Toolbar', // MISSING toolbarGroups : { document : 'Document', // MISSING clipboard : 'Clipboard/Undo', // MISSING editing : 'Editing', // MISSING forms : 'Forms', // MISSING basicstyles : 'Basic Styles', // MISSING paragraph : 'Paragraph', // MISSING links : 'Links', // MISSING insert : 'Insert', // MISSING styles : 'Styles', // MISSING colors : 'Colors', // MISSING tools : 'Tools' // MISSING }, bidi : { ltr : 'Text direction from left to right', // MISSING rtl : 'Text direction from right to left' // MISSING }, docprops : { label : 'Dokumenta īpašības', title : 'Dokumenta īpašības', design : 'Design', // MISSING meta : 'META dati', chooseColor : 'Choose', // MISSING other : '<cits>', docTitle : 'Dokumenta virsraksts <Title>', charset : 'Simbolu kodējums', charsetOther : 'Cits simbolu kodējums', charsetASCII : 'ASCII', // MISSING charsetCE : 'Central European', // MISSING charsetCT : 'Chinese Traditional (Big5)', // MISSING charsetCR : 'Cyrillic', // MISSING charsetGR : 'Greek', // MISSING charsetJP : 'Japanese', // MISSING charsetKR : 'Korean', // MISSING charsetTR : 'Turkish', // MISSING charsetUN : 'Unicode (UTF-8)', // MISSING charsetWE : 'Western European', // MISSING docType : 'Dokumenta tips', docTypeOther : 'Cits dokumenta tips', xhtmlDec : 'Ietvert XHTML deklarācijas', bgColor : 'Fona krāsa', bgImage : 'Fona attēla hipersaite', bgFixed : 'Fona attēls ir fiksēts', txtColor : 'Teksta krāsa', margin : 'Lapas robežas', marginTop : 'Augšā', marginLeft : 'Pa kreisi', marginRight : 'Pa labi', marginBottom : 'Apakšā', metaKeywords : 'Dokumentu aprakstoši atslēgvārdi (atdalīti ar komatu)', metaDescription : 'Dokumenta apraksts', metaAuthor : 'Autors', metaCopyright : 'Autortiesības', previewHtml : '<p>This is some <strong>sample text</strong>. You are using <a href="javascript:void(0)">CKEditor</a>.</p>' // MISSING } };
monkeythecoder/wp_lisder
wp-content/plugins/wp-online-store/admin/ckeditor/_source/lang/lv.js
JavaScript
gpl-2.0
27,055
<?php namespace Drupal\Core\Template; use Drupal\Component\Utility\Html; /** * A class that defines a type of Attribute that can be added to as an array. * * To use with Attribute, the array must be specified. * Correct: * @code * $attributes = new Attribute(); * $attributes['class'] = array(); * $attributes['class'][] = 'cat'; * @endcode * Incorrect: * @code * $attributes = new Attribute(); * $attributes['class'][] = 'cat'; * @endcode * * @see \Drupal\Core\Template\Attribute */ class AttributeArray extends AttributeValueBase implements \ArrayAccess, \IteratorAggregate { /** * Ensures empty array as a result of array_filter will not print '$name=""'. * * @see \Drupal\Core\Template\AttributeArray::__toString() * @see \Drupal\Core\Template\AttributeValueBase::render() */ const RENDER_EMPTY_ATTRIBUTE = FALSE; /** * {@inheritdoc} */ public function offsetGet($offset) { return $this->value[$offset]; } /** * {@inheritdoc} */ public function offsetSet($offset, $value) { if (isset($offset)) { $this->value[$offset] = $value; } else { $this->value[] = $value; } } /** * {@inheritdoc} */ public function offsetUnset($offset) { unset($this->value[$offset]); } /** * {@inheritdoc} */ public function offsetExists($offset) { return isset($this->value[$offset]); } /** * Implements the magic __toString() method. */ public function __toString() { // Filter out any empty values before printing. $this->value = array_unique(array_filter($this->value)); return Html::escape(implode(' ', $this->value)); } /** * {@inheritdoc} */ public function getIterator() { return new \ArrayIterator($this->value); } /** * Exchange the array for another one. * * @see ArrayObject::exchangeArray * * @param array $input * The array input to replace the internal value. * * @return array * The old array value. */ public function exchangeArray($input) { $old = $this->value; $this->value = $input; return $old; } }
JeramyK/training
web/core/lib/Drupal/Core/Template/AttributeArray.php
PHP
gpl-2.0
2,131
// Boost.Geometry (aka GGL, Generic Geometry Library) // Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands. // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_OVERLAY_ENRICH_HPP #define BOOST_GEOMETRY_ALGORITHMS_DETAIL_OVERLAY_ENRICH_HPP #include <cstddef> #include <algorithm> #include <map> #include <set> #include <vector> #ifdef BOOST_GEOMETRY_DEBUG_ENRICH # include <iostream> # include <boost/geometry/algorithms/detail/overlay/debug_turn_info.hpp> # include <boost/geometry/io/wkt/wkt.hpp> # define BOOST_GEOMETRY_DEBUG_IDENTIFIER #endif #include <boost/range.hpp> #include <boost/geometry/iterators/ever_circling_iterator.hpp> #include <boost/geometry/algorithms/detail/ring_identifier.hpp> #include <boost/geometry/algorithms/detail/overlay/copy_segment_point.hpp> #include <boost/geometry/algorithms/detail/overlay/handle_colocations.hpp> #include <boost/geometry/algorithms/detail/overlay/less_by_segment_ratio.hpp> #include <boost/geometry/algorithms/detail/overlay/overlay_type.hpp> #include <boost/geometry/algorithms/detail/overlay/sort_by_side.hpp> #include <boost/geometry/policies/robustness/robust_type.hpp> #include <boost/geometry/strategies/side.hpp> #ifdef BOOST_GEOMETRY_DEBUG_ENRICH # include <boost/geometry/algorithms/detail/overlay/check_enrich.hpp> #endif namespace boost { namespace geometry { #ifndef DOXYGEN_NO_DETAIL namespace detail { namespace overlay { // Sorts IP-s of this ring on segment-identifier, and if on same segment, // on distance. // Then assigns for each IP which is the next IP on this segment, // plus the vertex-index to travel to, plus the next IP // (might be on another segment) template < bool Reverse1, bool Reverse2, typename Operations, typename Turns, typename Geometry1, typename Geometry2, typename RobustPolicy, typename Strategy > inline void enrich_sort(Operations& operations, Turns const& turns, operation_type for_operation, Geometry1 const& geometry1, Geometry2 const& geometry2, RobustPolicy const& robust_policy, Strategy const& /*strategy*/) { std::sort(boost::begin(operations), boost::end(operations), less_by_segment_ratio < Turns, typename boost::range_value<Operations>::type, Geometry1, Geometry2, RobustPolicy, Reverse1, Reverse2 >(turns, for_operation, geometry1, geometry2, robust_policy)); } template <typename Operations, typename Turns> inline void enrich_assign(Operations& operations, Turns& turns) { typedef typename boost::range_value<Turns>::type turn_type; typedef typename turn_type::turn_operation_type op_type; typedef typename boost::range_iterator<Operations>::type iterator_type; if (operations.size() > 0) { // Assign travel-to-vertex/ip index for each turning point. // Iterator "next" is circular geometry::ever_circling_range_iterator<Operations const> next(operations); ++next; for (iterator_type it = boost::begin(operations); it != boost::end(operations); ++it) { turn_type& turn = turns[it->turn_index]; op_type& op = turn.operations[it->operation_index]; // Normal behaviour: next should point at next turn: if (it->turn_index == next->turn_index) { ++next; } // Cluster behaviour: next should point after cluster, unless // their seg_ids are not the same while (turn.cluster_id != -1 && it->turn_index != next->turn_index && turn.cluster_id == turns[next->turn_index].cluster_id && op.seg_id == turns[next->turn_index].operations[next->operation_index].seg_id) { ++next; } turn_type const& next_turn = turns[next->turn_index]; op_type const& next_op = next_turn.operations[next->operation_index]; op.enriched.travels_to_ip_index = static_cast<signed_size_type>(next->turn_index); op.enriched.travels_to_vertex_index = next->subject->seg_id.segment_index; if (op.seg_id.segment_index == next_op.seg_id.segment_index && op.fraction < next_op.fraction) { // Next turn is located further on same segment // assign next_ip_index // (this is one not circular therefore fraction is considered) op.enriched.next_ip_index = static_cast<signed_size_type>(next->turn_index); } } } // DEBUG #ifdef BOOST_GEOMETRY_DEBUG_ENRICH { for (iterator_type it = boost::begin(operations); it != boost::end(operations); ++it) { op_type& op = turns[it->turn_index] .operations[it->operation_index]; std::cout << it->turn_index << " cl=" << turns[it->turn_index].cluster_id << " meth=" << method_char(turns[it->turn_index].method) << " seg=" << op.seg_id << " dst=" << op.fraction // needs define << " op=" << operation_char(turns[it->turn_index].operations[0].operation) << operation_char(turns[it->turn_index].operations[1].operation) << " (" << operation_char(op.operation) << ")" << " nxt=" << op.enriched.next_ip_index << " / " << op.enriched.travels_to_ip_index << " [vx " << op.enriched.travels_to_vertex_index << "]" << std::boolalpha << turns[it->turn_index].discarded << std::endl; ; } } #endif // END DEBUG } template <typename Turns, typename MappedVector> inline void create_map(Turns const& turns, detail::overlay::operation_type for_operation, MappedVector& mapped_vector) { typedef typename boost::range_value<Turns>::type turn_type; typedef typename turn_type::container_type container_type; typedef typename MappedVector::mapped_type mapped_type; typedef typename boost::range_value<mapped_type>::type indexed_type; std::size_t index = 0; for (typename boost::range_iterator<Turns const>::type it = boost::begin(turns); it != boost::end(turns); ++it, ++index) { // Add all (non discarded) operations on this ring // Blocked operations or uu on clusters (for intersection) // should be included, to block potential paths in clusters turn_type const& turn = *it; if (turn.discarded) { continue; } if (for_operation == operation_intersection && turn.cluster_id == -1 && turn.both(operation_union)) { // Only include uu turns if part of cluster (to block potential paths), // otherwise they can block possibly viable paths continue; } std::size_t op_index = 0; for (typename boost::range_iterator<container_type const>::type op_it = boost::begin(turn.operations); op_it != boost::end(turn.operations); ++op_it, ++op_index) { ring_identifier const ring_id ( op_it->seg_id.source_index, op_it->seg_id.multi_index, op_it->seg_id.ring_index ); mapped_vector[ring_id].push_back ( indexed_type(index, op_index, *op_it, it->operations[1 - op_index].seg_id) ); } } } }} // namespace detail::overlay #endif //DOXYGEN_NO_DETAIL /*! \brief All intersection points are enriched with successor information \ingroup overlay \tparam Turns type of intersection container (e.g. vector of "intersection/turn point"'s) \tparam Clusters type of cluster container \tparam Geometry1 \tparam_geometry \tparam Geometry2 \tparam_geometry \tparam Strategy side strategy type \param turns container containing intersection points \param clusters container containing clusters \param geometry1 \param_geometry \param geometry2 \param_geometry \param robust_policy policy to handle robustness issues \param strategy strategy */ template < bool Reverse1, bool Reverse2, overlay_type OverlayType, typename Turns, typename Clusters, typename Geometry1, typename Geometry2, typename RobustPolicy, typename Strategy > inline void enrich_intersection_points(Turns& turns, Clusters& clusters, Geometry1 const& geometry1, Geometry2 const& geometry2, RobustPolicy const& robust_policy, Strategy const& strategy) { static const detail::overlay::operation_type for_operation = detail::overlay::operation_from_overlay<OverlayType>::value; typedef typename boost::range_value<Turns>::type turn_type; typedef typename turn_type::turn_operation_type op_type; typedef detail::overlay::indexed_turn_operation < op_type > indexed_turn_operation; typedef std::map < ring_identifier, std::vector<indexed_turn_operation> > mapped_vector_type; bool const has_colocations = detail::overlay::handle_colocations<Reverse1, Reverse2>(turns, clusters, geometry1, geometry2); // Discard none turns, if any for (typename boost::range_iterator<Turns>::type it = boost::begin(turns); it != boost::end(turns); ++it) { if (it->both(detail::overlay::operation_none)) { it->discarded = true; } } // Create a map of vectors of indexed operation-types to be able // to sort intersection points PER RING mapped_vector_type mapped_vector; detail::overlay::create_map(turns, for_operation, mapped_vector); // No const-iterator; contents of mapped copy is temporary, // and changed by enrich for (typename mapped_vector_type::iterator mit = mapped_vector.begin(); mit != mapped_vector.end(); ++mit) { #ifdef BOOST_GEOMETRY_DEBUG_ENRICH std::cout << "ENRICH-sort Ring " << mit->first << std::endl; #endif detail::overlay::enrich_sort<Reverse1, Reverse2>( mit->second, turns, for_operation, geometry1, geometry2, robust_policy, strategy); } for (typename mapped_vector_type::iterator mit = mapped_vector.begin(); mit != mapped_vector.end(); ++mit) { #ifdef BOOST_GEOMETRY_DEBUG_ENRICH std::cout << "ENRICH-assign Ring " << mit->first << std::endl; #endif detail::overlay::enrich_assign(mit->second, turns); } if (has_colocations) { detail::overlay::gather_cluster_properties<Reverse1, Reverse2>( clusters, turns, for_operation, geometry1, geometry2); } #ifdef BOOST_GEOMETRY_DEBUG_ENRICH //detail::overlay::check_graph(turns, for_operation); #endif } }} // namespace boost::geometry #endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_OVERLAY_ENRICH_HPP
vovkasm/react-native-web-image
tests/TestApp/Pods/boost-for-react-native/boost/geometry/algorithms/detail/overlay/enrich_intersection_points.hpp
C++
mit
11,595
<?php /** * Smarty Internal Plugin Compile Include * Compiles the {include} tag * * @package Smarty * @subpackage Compiler * @author Uwe Tews */ /** * Smarty Internal Plugin Compile Include Class * * @package Smarty * @subpackage Compiler */ class Smarty_Internal_Compile_Include extends Smarty_Internal_CompileBase { /** * caching mode to create nocache code but no cache file */ const CACHING_NOCACHE_CODE = 9999; /** * Attribute definition: Overwrites base class. * * @var array * @see Smarty_Internal_CompileBase */ public $required_attributes = array('file'); /** * Attribute definition: Overwrites base class. * * @var array * @see Smarty_Internal_CompileBase */ public $shorttag_order = array('file'); /** * Attribute definition: Overwrites base class. * * @var array * @see Smarty_Internal_CompileBase */ public $option_flags = array('nocache', 'inline', 'caching'); /** * Attribute definition: Overwrites base class. * * @var array * @see Smarty_Internal_CompileBase */ public $optional_attributes = array('_any'); /** * Valid scope names * * @var array */ public $valid_scopes = array('parent' => Smarty::SCOPE_PARENT, 'root' => Smarty::SCOPE_ROOT, 'global' => Smarty::SCOPE_GLOBAL, 'tpl_root' => Smarty::SCOPE_TPL_ROOT, 'smarty' => Smarty::SCOPE_SMARTY); /** * Compiles code for the {include} tag * * @param array $args array with attributes from parser * @param Smarty_Internal_SmartyTemplateCompiler $compiler compiler object * @param array $parameter array with compilation parameter * * @throws SmartyCompilerException * @return string compiled code */ public function compile($args, Smarty_Internal_SmartyTemplateCompiler $compiler, $parameter) { $uid = $t_hash = null; // check and get attributes $_attr = $this->getAttributes($compiler, $args); $fullResourceName = $source_resource = $_attr[ 'file' ]; $variable_template = false; $cache_tpl = false; // parse resource_name if (preg_match('/^([\'"])(([A-Za-z0-9_\-]{2,})[:])?(([^$()]+)|(.+))\1$/', $source_resource, $match)) { $type = !empty($match[ 3 ]) ? $match[ 3 ] : $compiler->template->smarty->default_resource_type; $name = !empty($match[ 5 ]) ? $match[ 5 ] : $match[ 6 ]; $handler = Smarty_Resource::load($compiler->smarty, $type); if ($handler->recompiled || $handler->uncompiled) { $variable_template = true; } if (!$variable_template) { if ($type != 'string') { $fullResourceName = "{$type}:{$name}"; $compiled = $compiler->parent_compiler->template->compiled; if (isset($compiled->includes[ $fullResourceName ])) { $compiled->includes[ $fullResourceName ] ++; $cache_tpl = true; } else { if ("{$compiler->template->source->type}:{$compiler->template->source->name}" == $fullResourceName ) { // recursive call of current template $compiled->includes[ $fullResourceName ] = 2; $cache_tpl = true; } else { $compiled->includes[ $fullResourceName ] = 1; } } $fullResourceName = '"' . $fullResourceName . '"'; } } if (empty($match[ 5 ])) { $variable_template = true; } } else { $variable_template = true; } // scope setup $_scope = $compiler->convertScope($_attr, $this->valid_scopes); // set flag to cache subtemplate object when called within loop or template name is variable. if ($cache_tpl || $variable_template || $compiler->loopNesting > 0) { $_cache_tpl = 'true'; } else { $_cache_tpl = 'false'; } // assume caching is off $_caching = Smarty::CACHING_OFF; $call_nocache = $compiler->tag_nocache || $compiler->nocache; // caching was on and {include} is not in nocache mode if ($compiler->template->caching && !$compiler->nocache && !$compiler->tag_nocache) { $_caching = self::CACHING_NOCACHE_CODE; } // flag if included template code should be merged into caller $merge_compiled_includes = ($compiler->smarty->merge_compiled_includes || $_attr[ 'inline' ] === true) && !$compiler->template->source->handler->recompiled; if ($merge_compiled_includes) { // variable template name ? if ($variable_template) { $merge_compiled_includes = false; } // variable compile_id? if (isset($_attr[ 'compile_id' ]) && $compiler->isVariable($_attr[ 'compile_id' ])) { $merge_compiled_includes = false; } } /* * if the {include} tag provides individual parameter for caching or compile_id * the subtemplate must not be included into the common cache file and is treated like * a call in nocache mode. * */ if ($_attr[ 'nocache' ] !== true && $_attr[ 'caching' ]) { $_caching = $_new_caching = (int) $_attr[ 'caching' ]; $call_nocache = true; } else { $_new_caching = Smarty::CACHING_LIFETIME_CURRENT; } if (isset($_attr[ 'cache_lifetime' ])) { $_cache_lifetime = $_attr[ 'cache_lifetime' ]; $call_nocache = true; $_caching = $_new_caching; } else { $_cache_lifetime = '$_smarty_tpl->cache_lifetime'; } if (isset($_attr[ 'cache_id' ])) { $_cache_id = $_attr[ 'cache_id' ]; $call_nocache = true; $_caching = $_new_caching; } else { $_cache_id = '$_smarty_tpl->cache_id'; } if (isset($_attr[ 'compile_id' ])) { $_compile_id = $_attr[ 'compile_id' ]; } else { $_compile_id = '$_smarty_tpl->compile_id'; } // if subtemplate will be called in nocache mode do not merge if ($compiler->template->caching && $call_nocache) { $merge_compiled_includes = false; } // assign attribute if (isset($_attr[ 'assign' ])) { // output will be stored in a smarty variable instead of being displayed if ($_assign = $compiler->getId($_attr[ 'assign' ])) { $_assign = "'{$_assign}'"; if ($compiler->tag_nocache || $compiler->nocache || $call_nocache) { // create nocache var to make it know for further compiling $compiler->setNocacheInVariable($_attr[ 'assign' ]); } } else { $_assign = $_attr[ 'assign' ]; } } $has_compiled_template = false; if ($merge_compiled_includes) { $c_id = isset($_attr[ 'compile_id' ]) ? $_attr[ 'compile_id' ] : $compiler->template->compile_id; // we must observe different compile_id and caching $t_hash = sha1($c_id . ($_caching ? '--caching' : '--nocaching')); $compiler->smarty->allow_ambiguous_resources = true; /* @var Smarty_Internal_Template $tpl */ $tpl = new $compiler->smarty->template_class (trim($fullResourceName, '"\''), $compiler->smarty, $compiler->template, $compiler->template->cache_id, $c_id, $_caching); $uid = $tpl->source->type . $tpl->source->uid; if (!isset($compiler->parent_compiler->mergedSubTemplatesData[ $uid ][ $t_hash ])) { $has_compiled_template = $this->compileInlineTemplate($compiler, $tpl, $t_hash); } else { $has_compiled_template = true; } unset($tpl); } // delete {include} standard attributes unset($_attr[ 'file' ], $_attr[ 'assign' ], $_attr[ 'cache_id' ], $_attr[ 'compile_id' ], $_attr[ 'cache_lifetime' ], $_attr[ 'nocache' ], $_attr[ 'caching' ], $_attr[ 'scope' ], $_attr[ 'inline' ]); // remaining attributes must be assigned as smarty variable $_vars = 'array()'; if (!empty($_attr)) { $_pairs = array(); // create variables foreach ($_attr as $key => $value) { $_pairs[] = "'$key'=>$value"; } $_vars = 'array(' . join(',', $_pairs) . ')'; } $update_compile_id = $compiler->template->caching && !$compiler->tag_nocache && !$compiler->nocache && $_compile_id != '$_smarty_tpl->compile_id'; if ($has_compiled_template && !$call_nocache) { $_output = "<?php\n"; if ($update_compile_id) { $_output .= $compiler->makeNocacheCode("\$_compile_id_save[] = \$_smarty_tpl->compile_id;\n\$_smarty_tpl->compile_id = {$_compile_id};\n"); } if (!empty($_attr) && $_caching == 9999 && $compiler->template->caching) { $_vars_nc = "foreach ($_vars as \$ik => \$iv) {\n"; $_vars_nc .= "\$_smarty_tpl->tpl_vars[\$ik] = new Smarty_Variable(\$iv);\n"; $_vars_nc .= "}\n"; $_output .= substr($compiler->processNocacheCode('<?php ' . $_vars_nc . "?>\n", true), 6, - 3); } if (isset($_assign)) { $_output .= "ob_start();\n"; } $_output .= "\$_smarty_tpl->_subTemplateRender({$fullResourceName}, {$_cache_id}, {$_compile_id}, {$_caching}, {$_cache_lifetime}, {$_vars}, {$_scope}, {$_cache_tpl}, '{$compiler->parent_compiler->mergedSubTemplatesData[$uid][$t_hash]['uid']}', '{$compiler->parent_compiler->mergedSubTemplatesData[$uid][$t_hash]['func']}');\n"; if (isset($_assign)) { $_output .= "\$_smarty_tpl->assign({$_assign}, ob_get_clean());\n"; } if ($update_compile_id) { $_output .= $compiler->makeNocacheCode("\$_smarty_tpl->compile_id = array_pop(\$_compile_id_save);\n"); } $_output .= "?>\n"; return $_output; } if ($call_nocache) { $compiler->tag_nocache = true; } $_output = "<?php "; if ($update_compile_id) { $_output .= "\$_compile_id_save[] = \$_smarty_tpl->compile_id;\n\$_smarty_tpl->compile_id = {$_compile_id};\n"; } // was there an assign attribute if (isset($_assign)) { $_output .= "ob_start();\n"; } $_output .= "\$_smarty_tpl->_subTemplateRender({$fullResourceName}, $_cache_id, $_compile_id, $_caching, $_cache_lifetime, $_vars, $_scope, {$_cache_tpl});\n"; if (isset($_assign)) { $_output .= "\$_smarty_tpl->assign({$_assign}, ob_get_clean());\n"; } if ($update_compile_id) { $_output .= "\$_smarty_tpl->compile_id = array_pop(\$_compile_id_save);\n"; } $_output .= "?>\n"; return $_output; } /** * Compile inline sub template * * @param \Smarty_Internal_SmartyTemplateCompiler $compiler * @param \Smarty_Internal_Template $tpl * @param string $t_hash * * @return bool */ public function compileInlineTemplate(Smarty_Internal_SmartyTemplateCompiler $compiler, Smarty_Internal_Template $tpl, $t_hash) { $uid = $tpl->source->type . $tpl->source->uid; if (!($tpl->source->handler->uncompiled) && $tpl->source->exists) { $compiler->parent_compiler->mergedSubTemplatesData[ $uid ][ $t_hash ][ 'uid' ] = $tpl->source->uid; if (isset($compiler->template->inheritance)) { $tpl->inheritance = clone $compiler->template->inheritance; } $tpl->compiled = new Smarty_Template_Compiled(); $tpl->compiled->nocache_hash = $compiler->parent_compiler->template->compiled->nocache_hash; $tpl->loadCompiler(); // save unique function name $compiler->parent_compiler->mergedSubTemplatesData[ $uid ][ $t_hash ][ 'func' ] = $tpl->compiled->unifunc = 'content_' . str_replace(array('.', ','), '_', uniqid('', true)); // make sure whole chain gets compiled $tpl->mustCompile = true; $compiler->parent_compiler->mergedSubTemplatesData[ $uid ][ $t_hash ][ 'nocache_hash' ] = $tpl->compiled->nocache_hash; if ($compiler->template->source->type == 'file') { $sourceInfo = $compiler->template->source->filepath; } else { $basename = $compiler->template->source->handler->getBasename($compiler->template->source); $sourceInfo = $compiler->template->source->type . ':' . ($basename ? $basename : $compiler->template->source->name); } // get compiled code $compiled_code = "<?php\n\n"; $compiled_code .= "/* Start inline template \"{$sourceInfo}\" =============================*/\n"; $compiled_code .= "function {$tpl->compiled->unifunc} (\$_smarty_tpl) {\n"; $compiled_code .= "?>\n" . $tpl->compiler->compileTemplateSource($tpl, null, $compiler->parent_compiler); $compiled_code .= "<?php\n"; $compiled_code .= "}\n?>\n"; $compiled_code .= $tpl->compiler->postFilter($tpl->compiler->blockOrFunctionCode); $compiled_code .= "<?php\n\n"; $compiled_code .= "/* End inline template \"{$sourceInfo}\" =============================*/\n"; $compiled_code .= "?>"; unset($tpl->compiler); if ($tpl->compiled->has_nocache_code) { // replace nocache_hash $compiled_code = str_replace("{$tpl->compiled->nocache_hash}", $compiler->template->compiled->nocache_hash, $compiled_code); $compiler->template->compiled->has_nocache_code = true; } $compiler->parent_compiler->mergedSubTemplatesCode[ $tpl->compiled->unifunc ] = $compiled_code; return true; } else { return false; } } }
fangwChina/yaf_framework
yaframework/application/library/Smarty/sysplugins/smarty_internal_compile_include.php
PHP
mit
15,106
VectorCanvas.prototype.createPath = function (config) { var node; if (this.mode === 'svg') { node = this.createSvgNode('path'); node.setAttribute('d', config.path); if (this.params.borderColor !== null) { node.setAttribute('stroke', this.params.borderColor); } if (this.params.borderWidth > 0) { node.setAttribute('stroke-width', this.params.borderWidth); node.setAttribute('stroke-linecap', 'round'); node.setAttribute('stroke-linejoin', 'round'); } if (this.params.borderOpacity > 0) { node.setAttribute('stroke-opacity', this.params.borderOpacity); } node.setFill = function (color) { this.setAttribute('fill', color); if (this.getAttribute('original') === null) { this.setAttribute('original', color); } }; node.getFill = function () { return this.getAttribute('fill'); }; node.getOriginalFill = function () { return this.getAttribute('original'); }; node.setOpacity = function (opacity) { this.setAttribute('fill-opacity', opacity); }; } else { node = this.createVmlNode('shape'); node.coordorigin = '0 0'; node.coordsize = this.width + ' ' + this.height; node.style.width = this.width + 'px'; node.style.height = this.height + 'px'; node.fillcolor = JQVMap.defaultFillColor; node.stroked = false; node.path = VectorCanvas.pathSvgToVml(config.path); var scale = this.createVmlNode('skew'); scale.on = true; scale.matrix = '0.01,0,0,0.01,0,0'; scale.offset = '0,0'; node.appendChild(scale); var fill = this.createVmlNode('fill'); node.appendChild(fill); node.setFill = function (color) { this.getElementsByTagName('fill')[0].color = color; if (this.getAttribute('original') === null) { this.setAttribute('original', color); } }; node.getFill = function () { return this.getElementsByTagName('fill')[0].color; }; node.getOriginalFill = function () { return this.getAttribute('original'); }; node.setOpacity = function (opacity) { this.getElementsByTagName('fill')[0].opacity = parseInt(opacity * 100, 10) + '%'; }; } return node; };
krasnyuk/e-liquid-MS
wwwroot/assets/js/jqvmap/src/VectorCanvas/createPath.js
JavaScript
mit
2,230
/** * jQuery plugin wrapper for TinySort * Does not use the first argument in tinysort.js since that is handled internally by the jQuery selector. * Sub-selections (option.selector) do not use the jQuery selector syntax but regular CSS3 selector syntax. * @summary jQuery plugin wrapper for TinySort * @version 2.2.2 * @requires tinysort * @license MIT/GPL * @author Ron Valstar (http://www.sjeiti.com/) * @copyright Ron Valstar <ron@ronvalstar.nl> */ !function(a){"use strict";"function"==typeof define&&define.amd?define(["jquery","tinysort"],a):jQuery&&!jQuery.fn.tsort&&a(jQuery,tinysort)}(function(a,b){"use strict";a.tinysort={defaults:b.defaults},a.fn.extend({tinysort:function(){var a,c,d=Array.prototype.slice.call(arguments);d.unshift(this),a=b.apply(null,d),c=a.length;for(var e=0,f=this.length;f>e;e++)c>e?this[e]=a[e]:delete this[e];return this.length=c,this}}),a.fn.tsort=a.fn.tinysort});
sajochiu/cdnjs
ajax/libs/tinysort/2.2.2/jquery.tinysort.min.js
JavaScript
mit
912
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/invalidation/invalidation_notifier.h" #include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" #include "components/invalidation/fake_invalidation_handler.h" #include "components/invalidation/fake_invalidation_state_tracker.h" #include "components/invalidation/invalidation_state_tracker.h" #include "components/invalidation/invalidator_test_template.h" #include "components/invalidation/push_client_channel.h" #include "jingle/notifier/base/fake_base_task.h" #include "jingle/notifier/base/notifier_options.h" #include "jingle/notifier/listener/fake_push_client.h" #include "net/url_request/url_request_test_util.h" #include "testing/gtest/include/gtest/gtest.h" namespace syncer { namespace { class InvalidationNotifierTestDelegate { public: InvalidationNotifierTestDelegate() {} ~InvalidationNotifierTestDelegate() { DestroyInvalidator(); } void CreateInvalidator( const std::string& invalidator_client_id, const std::string& initial_state, const base::WeakPtr<InvalidationStateTracker>& invalidation_state_tracker) { DCHECK(!invalidator_.get()); scoped_ptr<notifier::PushClient> push_client( new notifier::FakePushClient()); scoped_ptr<SyncNetworkChannel> network_channel( new PushClientChannel(push_client.Pass())); invalidator_.reset( new InvalidationNotifier(network_channel.Pass(), invalidator_client_id, UnackedInvalidationsMap(), initial_state, invalidation_state_tracker, base::MessageLoopProxy::current(), "fake_client_info")); } Invalidator* GetInvalidator() { return invalidator_.get(); } void DestroyInvalidator() { // Stopping the invalidation notifier stops its scheduler, which deletes // any pending tasks without running them. Some tasks "run and delete" // another task, so they must be run in order to avoid leaking the inner // task. Stopping does not schedule any tasks, so it's both necessary and // sufficient to drain the task queue before stopping the notifier. message_loop_.RunUntilIdle(); invalidator_.reset(); } void WaitForInvalidator() { message_loop_.RunUntilIdle(); } void TriggerOnInvalidatorStateChange(InvalidatorState state) { invalidator_->OnInvalidatorStateChange(state); } void TriggerOnIncomingInvalidation( const ObjectIdInvalidationMap& invalidation_map) { invalidator_->OnInvalidate(invalidation_map); } private: base::MessageLoop message_loop_; scoped_ptr<InvalidationNotifier> invalidator_; }; INSTANTIATE_TYPED_TEST_CASE_P( InvalidationNotifierTest, InvalidatorTest, InvalidationNotifierTestDelegate); } // namespace } // namespace syncer
s20121035/rk3288_android5.1_repo
external/chromium_org/components/invalidation/invalidation_notifier_unittest.cc
C++
gpl-3.0
3,082
from django.db import models, DEFAULT_DB_ALIAS, connection from django.contrib.auth.models import User from django.conf import settings class Animal(models.Model): name = models.CharField(max_length=150) latin_name = models.CharField(max_length=150) count = models.IntegerField() weight = models.FloatField() # use a non-default name for the default manager specimens = models.Manager() def __unicode__(self): return self.name class Plant(models.Model): name = models.CharField(max_length=150) class Meta: # For testing when upper case letter in app name; regression for #4057 db_table = "Fixtures_regress_plant" class Stuff(models.Model): name = models.CharField(max_length=20, null=True) owner = models.ForeignKey(User, null=True) def __unicode__(self): return unicode(self.name) + u' is owned by ' + unicode(self.owner) class Absolute(models.Model): name = models.CharField(max_length=40) load_count = 0 def __init__(self, *args, **kwargs): super(Absolute, self).__init__(*args, **kwargs) Absolute.load_count += 1 class Parent(models.Model): name = models.CharField(max_length=10) class Meta: ordering = ('id',) class Child(Parent): data = models.CharField(max_length=10) # Models to regression test #7572 class Channel(models.Model): name = models.CharField(max_length=255) class Article(models.Model): title = models.CharField(max_length=255) channels = models.ManyToManyField(Channel) class Meta: ordering = ('id',) # Models to regression test #11428 class Widget(models.Model): name = models.CharField(max_length=255) class Meta: ordering = ('name',) def __unicode__(self): return self.name class WidgetProxy(Widget): class Meta: proxy = True # Check for forward references in FKs and M2Ms with natural keys class TestManager(models.Manager): def get_by_natural_key(self, key): return self.get(name=key) class Store(models.Model): objects = TestManager() name = models.CharField(max_length=255) class Meta: ordering = ('name',) def __unicode__(self): return self.name def natural_key(self): return (self.name,) class Person(models.Model): objects = TestManager() name = models.CharField(max_length=255) class Meta: ordering = ('name',) def __unicode__(self): return self.name # Person doesn't actually have a dependency on store, but we need to define # one to test the behaviour of the dependency resolution algorithm. def natural_key(self): return (self.name,) natural_key.dependencies = ['fixtures_regress.store'] class Book(models.Model): name = models.CharField(max_length=255) author = models.ForeignKey(Person) stores = models.ManyToManyField(Store) class Meta: ordering = ('name',) def __unicode__(self): return u'%s by %s (available at %s)' % ( self.name, self.author.name, ', '.join(s.name for s in self.stores.all()) ) class NKManager(models.Manager): def get_by_natural_key(self, data): return self.get(data=data) class NKChild(Parent): data = models.CharField(max_length=10, unique=True) objects = NKManager() def natural_key(self): return self.data def __unicode__(self): return u'NKChild %s:%s' % (self.name, self.data) class RefToNKChild(models.Model): text = models.CharField(max_length=10) nk_fk = models.ForeignKey(NKChild, related_name='ref_fks') nk_m2m = models.ManyToManyField(NKChild, related_name='ref_m2ms') def __unicode__(self): return u'%s: Reference to %s [%s]' % ( self.text, self.nk_fk, ', '.join(str(o) for o in self.nk_m2m.all()) ) # ome models with pathological circular dependencies class Circle1(models.Model): name = models.CharField(max_length=255) def natural_key(self): return self.name natural_key.dependencies = ['fixtures_regress.circle2'] class Circle2(models.Model): name = models.CharField(max_length=255) def natural_key(self): return self.name natural_key.dependencies = ['fixtures_regress.circle1'] class Circle3(models.Model): name = models.CharField(max_length=255) def natural_key(self): return self.name natural_key.dependencies = ['fixtures_regress.circle3'] class Circle4(models.Model): name = models.CharField(max_length=255) def natural_key(self): return self.name natural_key.dependencies = ['fixtures_regress.circle5'] class Circle5(models.Model): name = models.CharField(max_length=255) def natural_key(self): return self.name natural_key.dependencies = ['fixtures_regress.circle6'] class Circle6(models.Model): name = models.CharField(max_length=255) def natural_key(self): return self.name natural_key.dependencies = ['fixtures_regress.circle4'] class ExternalDependency(models.Model): name = models.CharField(max_length=255) def natural_key(self): return self.name natural_key.dependencies = ['fixtures_regress.book'] # Model for regression test of #11101 class Thingy(models.Model): name = models.CharField(max_length=255)
mzdaniel/oh-mainline
vendor/packages/Django/tests/regressiontests/fixtures_regress/models.py
Python
agpl-3.0
5,411
//// [inheritedConstructorWithRestParams2.ts] class IBaseBase<T, U> { constructor(x: U) { } } interface IBase<T, U> extends IBaseBase<T, U> { } class BaseBase2 { constructor(x: number) { } } declare class BaseBase<T, U> extends BaseBase2 implements IBase<T, U> { constructor(x: T, ...y: U[]); constructor(x1: T, x2: T, ...y: U[]); constructor(x1: T, x2: U, y: T); } class Base extends BaseBase<string, number> { } class Derived extends Base { } // Ok new Derived("", ""); new Derived("", 3); new Derived("", 3, 3); new Derived("", 3, 3, 3); new Derived("", 3, ""); new Derived("", "", 3); new Derived("", "", 3, 3); // Errors new Derived(3); new Derived("", 3, "", 3); new Derived("", 3, "", ""); //// [inheritedConstructorWithRestParams2.js] var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var IBaseBase = (function () { function IBaseBase(x) { } return IBaseBase; })(); var BaseBase2 = (function () { function BaseBase2(x) { } return BaseBase2; })(); var Base = (function (_super) { __extends(Base, _super); function Base() { _super.apply(this, arguments); } return Base; })(BaseBase); var Derived = (function (_super) { __extends(Derived, _super); function Derived() { _super.apply(this, arguments); } return Derived; })(Base); // Ok new Derived("", ""); new Derived("", 3); new Derived("", 3, 3); new Derived("", 3, 3, 3); new Derived("", 3, ""); new Derived("", "", 3); new Derived("", "", 3, 3); // Errors new Derived(3); new Derived("", 3, "", 3); new Derived("", 3, "", "");
sassson/TypeScript
tests/baselines/reference/inheritedConstructorWithRestParams2.js
JavaScript
apache-2.0
1,838
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "mojo/public/cpp/environment/async_waiter.h" namespace mojo { AsyncWaiter::AsyncWaiter(Handle handle, MojoHandleSignals signals, const Callback& callback) : waiter_(Environment::GetDefaultAsyncWaiter()), id_(0), callback_(callback) { id_ = waiter_->AsyncWait(handle.value(), signals, MOJO_DEADLINE_INDEFINITE, &AsyncWaiter::WaitComplete, this); } AsyncWaiter::~AsyncWaiter() { if (id_) waiter_->CancelWait(id_); } // static void AsyncWaiter::WaitComplete(void* waiter, MojoResult result) { static_cast<AsyncWaiter*>(waiter)->WaitCompleteInternal(result); } void AsyncWaiter::WaitCompleteInternal(MojoResult result) { id_ = 0; callback_.Run(result); } } // namespace mojo
guorendong/iridium-browser-ubuntu
third_party/mojo/src/mojo/public/cpp/environment/lib/async_waiter.cc
C++
bsd-3-clause
960
/* Copyright 2016 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 watch import ( "time" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/meta" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/util/wait" ) // ConditionFunc returns true if the condition has been reached, false if it has not been reached yet, // or an error if the condition cannot be checked and should terminate. In general, it is better to define // level driven conditions over edge driven conditions (pod has ready=true, vs pod modified and ready changed // from false to true). type ConditionFunc func(event Event) (bool, error) // Until reads items from the watch until each provided condition succeeds, and then returns the last watch // encountered. The first condition that returns an error terminates the watch (and the event is also returned). // If no event has been received, the returned event will be nil. // Conditions are satisfied sequentially so as to provide a useful primitive for higher level composition. // A zero timeout means to wait forever. func Until(timeout time.Duration, watcher Interface, conditions ...ConditionFunc) (*Event, error) { ch := watcher.ResultChan() defer watcher.Stop() var after <-chan time.Time if timeout > 0 { after = time.After(timeout) } else { ch := make(chan time.Time) defer close(ch) after = ch } var lastEvent *Event for _, condition := range conditions { // check the next condition against the previous event and short circuit waiting for the next watch if lastEvent != nil { done, err := condition(*lastEvent) if err != nil { return lastEvent, err } if done { continue } } ConditionSucceeded: for { select { case event, ok := <-ch: if !ok { return lastEvent, wait.ErrWaitTimeout } lastEvent = &event // TODO: check for watch expired error and retry watch from latest point? done, err := condition(event) if err != nil { return lastEvent, err } if done { break ConditionSucceeded } case <-after: return lastEvent, wait.ErrWaitTimeout } } } return lastEvent, nil } // ListerWatcher is any object that knows how to perform an initial list and start a watch on a resource. type ListerWatcher interface { // List should return a list type object; the Items field will be extracted, and the // ResourceVersion field will be used to start the watch in the right place. List(options api.ListOptions) (runtime.Object, error) // Watch should begin a watch at the specified version. Watch(options api.ListOptions) (Interface, error) } // TODO: check for watch expired error and retry watch from latest point? Same issue exists for Until. func ListWatchUntil(timeout time.Duration, lw ListerWatcher, conditions ...ConditionFunc) (*Event, error) { if len(conditions) == 0 { return nil, nil } list, err := lw.List(api.ListOptions{}) if err != nil { return nil, err } initialItems, err := meta.ExtractList(list) if err != nil { return nil, err } // use the initial items as simulated "adds" var lastEvent *Event currIndex := 0 passedConditions := 0 for _, condition := range conditions { // check the next condition against the previous event and short circuit waiting for the next watch if lastEvent != nil { done, err := condition(*lastEvent) if err != nil { return lastEvent, err } if done { passedConditions = passedConditions + 1 continue } } ConditionSucceeded: for currIndex < len(initialItems) { lastEvent = &Event{Type: Added, Object: initialItems[currIndex]} currIndex++ done, err := condition(*lastEvent) if err != nil { return lastEvent, err } if done { passedConditions = passedConditions + 1 break ConditionSucceeded } } } if passedConditions == len(conditions) { return lastEvent, nil } remainingConditions := conditions[passedConditions:] metaObj, err := meta.ListAccessor(list) if err != nil { return nil, err } currResourceVersion := metaObj.GetResourceVersion() watch, err := lw.Watch(api.ListOptions{ResourceVersion: currResourceVersion}) if err != nil { return nil, err } return Until(timeout, watch, remainingConditions...) }
gwmoura/tsuru
vendor/k8s.io/kubernetes/pkg/watch/until.go
GO
bsd-3-clause
4,738
// to indexed object, toObject with fallback for non-array-like ES3 strings var IObject = require('./_iobject') , defined = require('./_defined'); module.exports = function(it){ return IObject(defined(it)); };
migua1204/jikexueyuan
极客学院/nodeBaidu/node_modules/core-js/modules/_to-iobject.js
JavaScript
apache-2.0
213
<?php /** * Drupal_Sniffs_Files_TxtFileLineLengthSniff. * * PHP version 5 * * @category PHP * @package PHP_CodeSniffer * @author Klaus Purer * @link http://pear.php.net/package/PHP_CodeSniffer */ /** * Drupal_Sniffs_Files_TxtFileLineLengthSniff. * * Checks all lines in a *.txt or *.md file and throws warnings if they are over 80 * characters in length. * * @category PHP * @package PHP_CodeSniffer * @author Klaus Purer * @link http://pear.php.net/package/PHP_CodeSniffer */ class Drupal_Sniffs_Files_TxtFileLineLengthSniff implements PHP_CodeSniffer_Sniff { /** * Returns an array of tokens this test wants to listen for. * * @return array */ public function register() { return array(T_INLINE_HTML); }//end register() /** * Processes this test, when one of its tokens is encountered. * * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. * @param int $stackPtr The position of the current token in the * stack passed in $tokens. * * @return void */ public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr) { $fileExtension = strtolower(substr($phpcsFile->getFilename(), -3)); if ($fileExtension === 'txt' || $fileExtension === '.md') { $tokens = $phpcsFile->getTokens(); $content = rtrim($tokens[$stackPtr]['content']); $lineLength = mb_strlen($content, 'UTF-8'); if ($lineLength > 80) { $data = array( 80, $lineLength, ); $warning = 'Line exceeds %s characters; contains %s characters'; $phpcsFile->addWarning($warning, $stackPtr, 'TooLong', $data); } } }//end process() }//end class ?>
RobLoach/PHP_CodeSniffer_Drupal
src/Drupal/Sniffs/Files/TxtFileLineLengthSniff.php
PHP
gpl-2.0
1,923
<?php ///////////////////////////////////////////////////////////////////////////// // // // NOTICE OF COPYRIGHT // // // // Moodle - Calendar extension // // // // Copyright (C) 2003-2004 Greek School Network www.sch.gr // // // // Designed by: // // Avgoustos Tsinakos (tsinakos@teikav.edu.gr) // // Jon Papaioannou (pj@moodle.org) // // // // Programming and development: // // Jon Papaioannou (pj@moodle.org) // // // // For bugs, suggestions, etc contact: // // Jon Papaioannou (pj@moodle.org) // // // // The current module was developed at the University of Macedonia // // (www.uom.gr) under the funding of the Greek School Network (www.sch.gr) // // The aim of this project is to provide additional and improved // // functionality to the Asynchronous Distance Education service that the // // Greek School Network deploys. // // // // 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: // // // // http://www.gnu.org/copyleft/gpl.html // // // ///////////////////////////////////////////////////////////////////////////// /** * This file is part of the User section Moodle * * @copyright 2003-2004 Jon Papaioannou (pj@moodle.org) * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v2 or later * @package calendar */ require_once('../config.php'); require_once($CFG->dirroot.'/course/lib.php'); require_once($CFG->dirroot.'/calendar/lib.php'); if (empty($CFG->enablecalendarexport)) { die('no export'); } $courseid = optional_param('course', SITEID, PARAM_INT); $action = optional_param('action', '', PARAM_ALPHA); $day = optional_param('cal_d', 0, PARAM_INT); $mon = optional_param('cal_m', 0, PARAM_INT); $year = optional_param('cal_y', 0, PARAM_INT); $time = optional_param('time', 0, PARAM_INT); $generateurl = optional_param('generateurl', 0, PARAM_BOOL); // If a day, month and year were passed then convert it to a timestamp. If these were passed // then we can assume the day, month and year are passed as Gregorian, as no where in core // should we be passing these values rather than the time. This is done for BC. if (!empty($day) && !empty($mon) && !empty($year)) { if (checkdate($mon, $day, $year)) { $time = make_timestamp($year, $mon, $day); } else { $time = time(); } } else if (empty($time)) { $time = time(); } if ($courseid != SITEID && !empty($courseid)) { // Course ID must be valid and existing. $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST); $courses = array($course->id => $course); $issite = false; } else { $course = get_site(); $courses = calendar_get_default_courses(); $issite = true; } require_login($course, false); $url = new moodle_url('/calendar/export.php', array('time' => $time)); if ($action !== '') { $url->param('action', $action); } if ($course !== NULL) { $url->param('course', $course->id); } $PAGE->set_url($url); $calendar = new calendar_information(0, 0, 0, $time); $calendar->set_sources($course, $courses); $pagetitle = get_string('export', 'calendar'); // Print title and header if ($issite) { $PAGE->navbar->add($course->shortname, new moodle_url('/course/view.php', array('id'=>$course->id))); } $link = new moodle_url(CALENDAR_URL.'view.php', array('view'=>'upcoming', 'course'=>$calendar->courseid)); $PAGE->navbar->add(get_string('calendar', 'calendar'), calendar_get_link_href($link, 0, 0, 0, $time)); $PAGE->navbar->add($pagetitle); $PAGE->set_title($course->shortname.': '.get_string('calendar', 'calendar').': '.$pagetitle); $PAGE->set_heading($course->fullname); $PAGE->set_pagelayout('standard'); $renderer = $PAGE->get_renderer('core_calendar'); $calendar->add_sidecalendar_blocks($renderer); // Get the calendar type we are using. $calendartype = \core_calendar\type_factory::get_calendar_instance(); $now = $calendartype->timestamp_to_date_array($time); $weekend = CALENDAR_DEFAULT_WEEKEND; if (isset($CFG->calendar_weekend)) { $weekend = intval($CFG->calendar_weekend); } $numberofdaysinweek = $calendartype->get_num_weekdays(); $formdata = array( // Let's populate some vars to let "common tasks" be somewhat smart... // If today it's weekend, give the "next week" option. 'allownextweek' => $weekend & (1 << $now['wday']), // If it's the last week of the month, give the "next month" option. 'allownextmonth' => calendar_days_in_month($now['mon'], $now['year']) - $now['mday'] < $numberofdaysinweek, // If today it's weekend but tomorrow it isn't, do NOT give the "this week" option. 'allowthisweek' => !(($weekend & (1 << $now['wday'])) && !($weekend & (1 << (($now['wday'] + 1) % $numberofdaysinweek)))) ); $exportform = new core_calendar_export_form(null, $formdata); $calendarurl = ''; if ($data = $exportform->get_data()) { $password = $DB->get_record('user', array('id' => $USER->id), 'password'); $params = array(); $params['userid'] = $USER->id; $params['authtoken'] = sha1($USER->id . (isset($password->password) ? $password->password : '') . $CFG->calendar_exportsalt); $params['preset_what'] = $data->events['exportevents']; $params['preset_time'] = $data->period['timeperiod']; $link = new moodle_url('/calendar/export_execute.php', $params); if (!empty($data->generateurl)) { $urlclasses = array('class' => 'generalbox calendarurl'); $calendarurl = html_writer::tag( 'div', get_string('calendarurl', 'calendar', $link->out()), $urlclasses); } if (!empty($data->export)) { redirect($link); } } echo $OUTPUT->header(); echo $renderer->start_layout(); echo $OUTPUT->heading(get_string('exportcalendar', 'calendar')); if ($action != 'advanced') { $exportform->display(); } echo $calendarurl; echo $renderer->complete_layout(); echo $OUTPUT->footer();
merrill-oakland/moodle
calendar/export.php
PHP
gpl-3.0
7,652
/** * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.bitcoin.core; import static com.google.common.base.Preconditions.checkArgument; /** * <p>Represents the "inv" P2P network message. An inv contains a list of hashes of either blocks or transactions. It's * a bandwidth optimization - on receiving some data, a (fully validating) peer sends every connected peer an inv * containing the hash of what it saw. It'll only transmit the full thing if a peer asks for it with a * {@link GetDataMessage}.</p> */ public class InventoryMessage extends ListMessage { private static final long serialVersionUID = -7050246551646107066L; public InventoryMessage(NetworkParameters params, byte[] bytes) throws ProtocolException { super(params, bytes); } /** * Deserializes an 'inv' message. * @param params NetworkParameters object. * @param msg Bitcoin protocol formatted byte array containing message content. * @param parseLazy Whether to perform a full parse immediately or delay until a read is requested. * @param parseRetain Whether to retain the backing byte array for quick reserialization. * If true and the backing byte array is invalidated due to modification of a field then * the cached bytes may be repopulated and retained if the message is serialized again in the future. * @param length The length of message if known. Usually this is provided when deserializing of the wire * as the length will be provided as part of the header. If unknown then set to Message.UNKNOWN_LENGTH * @throws ProtocolException */ public InventoryMessage(NetworkParameters params, byte[] msg, boolean parseLazy, boolean parseRetain, int length) throws ProtocolException { super(params, msg, parseLazy, parseRetain, length); } public InventoryMessage(NetworkParameters params) { super(params); } public void addBlock(Block block) { addItem(new InventoryItem(InventoryItem.Type.Block, block.getHash())); } public void addTransaction(Transaction tx) { addItem(new InventoryItem(InventoryItem.Type.Transaction, tx.getHash())); } /** Creates a new inv message for the given transactions. */ public static InventoryMessage with(Transaction... txns) { checkArgument(txns.length > 0); InventoryMessage result = new InventoryMessage(txns[0].getParams()); for (Transaction tx : txns) result.addTransaction(tx); return result; } }
hardbitcn/HardbitSafetyCheck
src/com/google/bitcoin/core/InventoryMessage.java
Java
apache-2.0
3,091
#region License, Terms and Author(s) // // ELMAH - Error Logging Modules and Handlers for ASP.NET // Copyright (c) 2004-9 Atif Aziz. All rights reserved. // // Author(s): // // Atif Aziz, http://www.raboof.com // // 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. // #endregion namespace Elmah { #region Imports using System; using System.Data; using System.Reflection; #endregion /// <summary> /// Extension methods for <see cref="IDbCommand"/> objects. /// </summary> static class DbCommandExtensions { /// <remarks> /// Use <see cref="Missing.Value"/> for parameter value to avoid /// having it set by the returned function. /// </remarks> public static Func<string, DbType?, object, IDbDataParameter> ParameterAdder(this IDbCommand command) { return ParameterAdder(command, cmd => cmd.CreateParameter()); } /// <remarks> /// Use <see cref="Missing.Value"/> for parameter value to avoid /// having it set by the returned function. /// </remarks> public static Func<string, DbType?, object, TParameter> ParameterAdder<TCommand, TParameter>(this TCommand command, Func<TCommand, TParameter> parameterCreator) where TCommand : IDbCommand where TParameter : IDataParameter { // ReSharper disable CompareNonConstrainedGenericWithNull if (command == null) throw new ArgumentNullException("command"); // ReSharper restore CompareNonConstrainedGenericWithNull if (parameterCreator == null) throw new ArgumentNullException("parameterCreator"); return (name, dbType, value) => { var parameter = parameterCreator(command); parameter.ParameterName = name; if (dbType != null) parameter.DbType = dbType.Value; if (Missing.Value != value) parameter.Value = value; command.Parameters.Add(parameter); return parameter; }; } } }
clearwavebuild/elmah
src/Elmah/DbCommandExtensions.cs
C#
apache-2.0
2,716
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Navigation * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ /** * Zend_Navigation_Container * * Container class for Zend_Navigation_Page classes. * * @category Zend * @package Zend_Navigation * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ abstract class Zend_Navigation_Container implements RecursiveIterator, Countable { /** * Contains sub pages * * @var array */ protected $_pages = array(); /** * An index that contains the order in which to iterate pages * * @var array */ protected $_index = array(); /** * Whether index is dirty and needs to be re-arranged * * @var bool */ protected $_dirtyIndex = false; // Internal methods: /** * Sorts the page index according to page order * * @return void */ protected function _sort() { if ($this->_dirtyIndex) { $newIndex = array(); $index = 0; foreach ($this->_pages as $hash => $page) { $order = $page->getOrder(); if ($order === null) { $newIndex[$hash] = $index; $index++; } else { $newIndex[$hash] = $order; } } asort($newIndex); $this->_index = $newIndex; $this->_dirtyIndex = false; } } // Public methods: /** * Notifies container that the order of pages are updated * * @return void */ public function notifyOrderUpdated() { $this->_dirtyIndex = true; } /** * Adds a page to the container * * This method will inject the container as the given page's parent by * calling {@link Zend_Navigation_Page::setParent()}. * * @param Zend_Navigation_Page|array|Zend_Config $page page to add * @return Zend_Navigation_Container fluent interface, * returns self * @throws Zend_Navigation_Exception if page is invalid */ public function addPage($page) { if ($page === $this) { require_once 'Zend/Navigation/Exception.php'; throw new Zend_Navigation_Exception( 'A page cannot have itself as a parent'); } if (is_array($page) || $page instanceof Zend_Config) { require_once 'Zend/Navigation/Page.php'; $page = Zend_Navigation_Page::factory($page); } elseif (!$page instanceof Zend_Navigation_Page) { require_once 'Zend/Navigation/Exception.php'; throw new Zend_Navigation_Exception( 'Invalid argument: $page must be an instance of ' . 'Zend_Navigation_Page or Zend_Config, or an array'); } $hash = $page->hashCode(); if (array_key_exists($hash, $this->_index)) { // page is already in container return $this; } // adds page to container and sets dirty flag $this->_pages[$hash] = $page; $this->_index[$hash] = $page->getOrder(); $this->_dirtyIndex = true; // inject self as page parent $page->setParent($this); return $this; } /** * Adds several pages at once * * @param array|Zend_Config|Zend_Navigation_Container $pages pages to add * @return Zend_Navigation_Container fluent interface, * returns self * @throws Zend_Navigation_Exception if $pages is not * array, Zend_Config or * Zend_Navigation_Container */ public function addPages($pages) { if ($pages instanceof Zend_Config) { $pages = $pages->toArray(); } if ($pages instanceof Zend_Navigation_Container) { $pages = iterator_to_array($pages); } if (!is_array($pages)) { require_once 'Zend/Navigation/Exception.php'; throw new Zend_Navigation_Exception( 'Invalid argument: $pages must be an array, an ' . 'instance of Zend_Config or an instance of ' . 'Zend_Navigation_Container'); } foreach ($pages as $page) { $this->addPage($page); } return $this; } /** * Sets pages this container should have, removing existing pages * * @param array $pages pages to set * @return Zend_Navigation_Container fluent interface, returns self */ public function setPages(array $pages) { $this->removePages(); return $this->addPages($pages); } /** * Returns pages in the container * * @return array array of Zend_Navigation_Page instances */ public function getPages() { return $this->_pages; } /** * Removes the given page from the container * * @param Zend_Navigation_Page|int $page page to remove, either a page * instance or a specific page order * @return bool whether the removal was * successful */ public function removePage($page) { if ($page instanceof Zend_Navigation_Page) { $hash = $page->hashCode(); } elseif (is_int($page)) { $this->_sort(); if (!$hash = array_search($page, $this->_index)) { return false; } } else { return false; } if (isset($this->_pages[$hash])) { unset($this->_pages[$hash]); unset($this->_index[$hash]); $this->_dirtyIndex = true; return true; } return false; } /** * Removes all pages in container * * @return Zend_Navigation_Container fluent interface, returns self */ public function removePages() { $this->_pages = array(); $this->_index = array(); return $this; } /** * Checks if the container has the given page * * @param Zend_Navigation_Page $page page to look for * @param bool $recursive [optional] whether to search * recursively. Default is false. * @return bool whether page is in container */ public function hasPage(Zend_Navigation_Page $page, $recursive = false) { if (array_key_exists($page->hashCode(), $this->_index)) { return true; } elseif ($recursive) { foreach ($this->_pages as $childPage) { if ($childPage->hasPage($page, true)) { return true; } } } return false; } /** * Returns true if container contains any pages * * @return bool whether container has any pages */ public function hasPages() { return count($this->_index) > 0; } /** * Returns a child page matching $property == $value or * preg_match($value, $property), or null if not found * * @param string $property name of property to match against * @param mixed $value value to match property against * @param bool $useRegex [optional] if true PHP's preg_match * is used. Default is false. * @return Zend_Navigation_Page|null matching page or null */ public function findOneBy($property, $value, $useRegex = false) { $iterator = new RecursiveIteratorIterator( $this, RecursiveIteratorIterator::SELF_FIRST ); foreach ($iterator as $page) { $pageProperty = $page->get($property); // Rel and rev if (is_array($pageProperty)) { foreach ($pageProperty as $item) { if (is_array($item)) { // Use regex? if (true === $useRegex) { foreach ($item as $item2) { if (0 !== preg_match($value, $item2)) { return $page; } } } else { if (in_array($value, $item)) { return $page; } } } else { // Use regex? if (true === $useRegex) { if (0 !== preg_match($value, $item)) { return $page; } } else { if ($item == $value) { return $page; } } } } continue; } // Use regex? if (true === $useRegex) { if (preg_match($value, $pageProperty)) { return $page; } } else { if ($pageProperty == $value) { return $page; } } } return null; } /** * Returns all child pages matching $property == $value or * preg_match($value, $property), or an empty array if no pages are found * * @param string $property name of property to match against * @param mixed $value value to match property against * @param bool $useRegex [optional] if true PHP's preg_match is used. * Default is false. * @return array array containing only Zend_Navigation_Page * instances */ public function findAllBy($property, $value, $useRegex = false) { $found = array(); $iterator = new RecursiveIteratorIterator( $this, RecursiveIteratorIterator::SELF_FIRST ); foreach ($iterator as $page) { $pageProperty = $page->get($property); // Rel and rev if (is_array($pageProperty)) { foreach ($pageProperty as $item) { if (is_array($item)) { // Use regex? if (true === $useRegex) { foreach ($item as $item2) { if (0 !== preg_match($value, $item2)) { $found[] = $page; } } } else { if (in_array($value, $item)) { $found[] = $page; } } } else { // Use regex? if (true === $useRegex) { if (0 !== preg_match($value, $item)) { $found[] = $page; } } else { if ($item == $value) { $found[] = $page; } } } } continue; } // Use regex? if (true === $useRegex) { if (0 !== preg_match($value, $pageProperty)) { $found[] = $page; } } else { if ($pageProperty == $value) { $found[] = $page; } } } return $found; } /** * Returns page(s) matching $property == $value or * preg_match($value, $property) * * @param string $property name of property to match against * @param mixed $value value to match property against * @param bool $all [optional] whether an array of all matching * pages should be returned, or only the first. * If true, an array will be returned, even if not * matching pages are found. If false, null will * be returned if no matching page is found. * Default is false. * @param bool $useRegex [optional] if true PHP's preg_match is used. * Default is false. * @return Zend_Navigation_Page|null matching page or null */ public function findBy($property, $value, $all = false, $useRegex = false) { if ($all) { return $this->findAllBy($property, $value, $useRegex); } else { return $this->findOneBy($property, $value, $useRegex); } } /** * Magic overload: Proxy calls to finder methods * * Examples of finder calls: * <code> * // METHOD // SAME AS * $nav->findByLabel('foo'); // $nav->findOneBy('label', 'foo'); * $nav->findByLabel('/foo/', true); // $nav->findBy('label', '/foo/', true); * $nav->findOneByLabel('foo'); // $nav->findOneBy('label', 'foo'); * $nav->findAllByClass('foo'); // $nav->findAllBy('class', 'foo'); * </code> * * @param string $method method name * @param array $arguments method arguments * @return mixed Zend_Navigation|array|null matching page, array of pages * or null * @throws Zend_Navigation_Exception if method does not exist */ public function __call($method, $arguments) { if (@preg_match('/(find(?:One|All)?By)(.+)/', $method, $match)) { return $this->{$match[1]}($match[2], $arguments[0], !empty($arguments[1])); } require_once 'Zend/Navigation/Exception.php'; throw new Zend_Navigation_Exception( sprintf( 'Bad method call: Unknown method %s::%s', get_class($this), $method ) ); } /** * Returns an array representation of all pages in container * * @return array */ public function toArray() { $pages = array(); $this->_dirtyIndex = true; $this->_sort(); $indexes = array_keys($this->_index); foreach ($indexes as $hash) { $pages[] = $this->_pages[$hash]->toArray(); } return $pages; } // RecursiveIterator interface: /** * Returns current page * * Implements RecursiveIterator interface. * * @return Zend_Navigation_Page current page or null * @throws Zend_Navigation_Exception if the index is invalid */ public function current() { $this->_sort(); current($this->_index); $hash = key($this->_index); if (isset($this->_pages[$hash])) { return $this->_pages[$hash]; } else { require_once 'Zend/Navigation/Exception.php'; throw new Zend_Navigation_Exception( 'Corruption detected in container; ' . 'invalid key found in internal iterator'); } } /** * Returns hash code of current page * * Implements RecursiveIterator interface. * * @return string hash code of current page */ public function key() { $this->_sort(); return key($this->_index); } /** * Moves index pointer to next page in the container * * Implements RecursiveIterator interface. * * @return void */ public function next() { $this->_sort(); next($this->_index); } /** * Sets index pointer to first page in the container * * Implements RecursiveIterator interface. * * @return void */ public function rewind() { $this->_sort(); reset($this->_index); } /** * Checks if container index is valid * * Implements RecursiveIterator interface. * * @return bool */ public function valid() { $this->_sort(); return current($this->_index) !== false; } /** * Proxy to hasPages() * * Implements RecursiveIterator interface. * * @return bool whether container has any pages */ public function hasChildren() { return $this->hasPages(); } /** * Returns the child container. * * Implements RecursiveIterator interface. * * @return Zend_Navigation_Page|null */ public function getChildren() { $hash = key($this->_index); if (isset($this->_pages[$hash])) { return $this->_pages[$hash]; } return null; } // Countable interface: /** * Returns number of pages in container * * Implements Countable interface. * * @return int number of pages in the container */ public function count() { return count($this->_index); } }
svn2github/zend_framework
library/Zend/Navigation/Container.php
PHP
bsd-3-clause
18,577
<?php /** * CodeIgniter * * An open source application development framework for PHP 5.2.4 or newer * * This content is released under the MIT License (MIT) * * Copyright (c) 2014, British Columbia Institute of Technology * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @package CodeIgniter * @author EllisLab Dev Team * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) * @copyright Copyright (c) 2014, British Columbia Institute of Technology (http://bcit.ca/) * @license http://opensource.org/licenses/MIT MIT License * @link http://codeigniter.com * @since Version 2.1.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); /** * PDO Database Adapter Class * * Note: _DB is an extender class that the app controller * creates dynamically based on whether the query builder * class is being used or not. * * @package CodeIgniter * @subpackage Drivers * @category Database * @author EllisLab Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_pdo_driver extends CI_DB { /** * Database driver * * @var string */ public $dbdriver = 'pdo'; /** * PDO Options * * @var array */ public $options = array(); // -------------------------------------------------------------------- /** * Class constructor * * Validates the DSN string and/or detects the subdriver. * * @param array $params * @return void */ public function __construct($params) { parent::__construct($params); if (preg_match('/([^:]+):/', $this->dsn, $match) && count($match) === 2) { // If there is a minimum valid dsn string pattern found, we're done // This is for general PDO users, who tend to have a full DSN string. $this->subdriver = $match[1]; return; } // Legacy support for DSN specified in the hostname field elseif (preg_match('/([^:]+):/', $this->hostname, $match) && count($match) === 2) { $this->dsn = $this->hostname; $this->hostname = NULL; $this->subdriver = $match[1]; return; } elseif (in_array($this->subdriver, array('mssql', 'sybase'), TRUE)) { $this->subdriver = 'dblib'; } elseif ($this->subdriver === '4D') { $this->subdriver = '4d'; } elseif ( ! in_array($this->subdriver, array('4d', 'cubrid', 'dblib', 'firebird', 'ibm', 'informix', 'mysql', 'oci', 'odbc', 'pgsql', 'sqlite', 'sqlsrv'), TRUE)) { log_message('error', 'PDO: Invalid or non-existent subdriver'); if ($this->db_debug) { show_error('Invalid or non-existent PDO subdriver'); } } $this->dsn = NULL; } // -------------------------------------------------------------------- /** * Database connection * * @param bool $persistent * @return object */ public function db_connect($persistent = FALSE) { $this->options[PDO::ATTR_PERSISTENT] = $persistent; try { return new PDO($this->dsn, $this->username, $this->password, $this->options); } catch (PDOException $e) { if ($this->db_debug && empty($this->failover)) { $this->display_error($e->getMessage(), '', TRUE); } return FALSE; } } // -------------------------------------------------------------------- /** * Database version number * * @return string */ public function version() { if (isset($this->data_cache['version'])) { return $this->data_cache['version']; } elseif ( ! $this->conn_id) { $this->initialize(); } // Not all subdrivers support the getAttribute() method try { return $this->data_cache['version'] = $this->conn_id->getAttribute(PDO::ATTR_SERVER_VERSION); } catch (PDOException $e) { return parent::version(); } } // -------------------------------------------------------------------- /** * Execute the query * * @param string $sql SQL query * @return mixed */ protected function _execute($sql) { return $this->conn_id->query($sql); } // -------------------------------------------------------------------- /** * Begin Transaction * * @param bool $test_mode * @return bool */ public function trans_begin($test_mode = FALSE) { // When transactions are nested we only begin/commit/rollback the outermost ones if ( ! $this->trans_enabled OR $this->_trans_depth > 0) { return TRUE; } // Reset the transaction failure flag. // If the $test_mode flag is set to TRUE transactions will be rolled back // even if the queries produce a successful result. $this->_trans_failure = ($test_mode === TRUE); return $this->conn_id->beginTransaction(); } // -------------------------------------------------------------------- /** * Commit Transaction * * @return bool */ public function trans_commit() { // When transactions are nested we only begin/commit/rollback the outermost ones if ( ! $this->trans_enabled OR $this->_trans_depth > 0) { return TRUE; } return $this->conn_id->commit(); } // -------------------------------------------------------------------- /** * Rollback Transaction * * @return bool */ public function trans_rollback() { // When transactions are nested we only begin/commit/rollback the outermost ones if ( ! $this->trans_enabled OR $this->_trans_depth > 0) { return TRUE; } return $this->conn_id->rollBack(); } // -------------------------------------------------------------------- /** * Platform-dependant string escape * * @param string * @return string */ protected function _escape_str($str) { // Escape the string $str = $this->conn_id->quote($str); // If there are duplicated quotes, trim them away return ($str[0] === "'") ? substr($str, 1, -1) : $str; } // -------------------------------------------------------------------- /** * Affected Rows * * @return int */ public function affected_rows() { return is_object($this->result_id) ? $this->result_id->rowCount() : 0; } // -------------------------------------------------------------------- /** * Insert ID * * @param string $name * @return int */ public function insert_id($name = NULL) { return $this->conn_id->lastInsertId($name); } // -------------------------------------------------------------------- /** * Field data query * * Generates a platform-specific query so that the column data can be retrieved * * @param string $table * @return string */ protected function _field_data($table) { return 'SELECT TOP 1 * FROM '.$this->protect_identifiers($table); } // -------------------------------------------------------------------- /** * Error * * Returns an array containing code and message of the last * database error that has occured. * * @return array */ public function error() { $error = array('code' => '00000', 'message' => ''); $pdo_error = $this->conn_id->errorInfo(); if (empty($pdo_error[0])) { return $error; } $error['code'] = isset($pdo_error[1]) ? $pdo_error[0].'/'.$pdo_error[1] : $pdo_error[0]; if (isset($pdo_error[2])) { $error['message'] = $pdo_error[2]; } return $error; } // -------------------------------------------------------------------- /** * Update_Batch statement * * Generates a platform-specific batch update string from the supplied data * * @param string $table Table name * @param array $values Update data * @param string $index WHERE key * @return string */ protected function _update_batch($table, $values, $index) { $ids = array(); foreach ($values as $key => $val) { $ids[] = $val[$index]; foreach (array_keys($val) as $field) { if ($field !== $index) { $final[$field][] = 'WHEN '.$index.' = '.$val[$index].' THEN '.$val[$field]; } } } $cases = ''; foreach ($final as $k => $v) { $cases .= $k.' = CASE '."\n"; foreach ($v as $row) { $cases .= $row."\n"; } $cases .= 'ELSE '.$k.' END, '; } $this->where($index.' IN('.implode(',', $ids).')', NULL, FALSE); return 'UPDATE '.$table.' SET '.substr($cases, 0, -2).$this->_compile_wh('qb_where'); } // -------------------------------------------------------------------- /** * Truncate statement * * Generates a platform-specific truncate string from the supplied data * * If the database does not support the TRUNCATE statement, * then this method maps to 'DELETE FROM table' * * @param string $table * @return string */ protected function _truncate($table) { return 'TRUNCATE TABLE '.$table; } } /* End of file pdo_driver.php */ /* Location: ./system/database/drivers/pdo/pdo_driver.php */
J2TeaM/CodeIgniter
system/database/drivers/pdo/pdo_driver.php
PHP
mit
9,638
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.itest.springboot; import org.apache.camel.itest.springboot.util.ArquillianPackager; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.Archive; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(Arquillian.class) public class CamelUnivocityParsersTest extends AbstractSpringBootTestSupport { @Deployment public static Archive<?> createSpringBootPackage() throws Exception { return ArquillianPackager.springBootPackage(createTestConfig()); } public static ITestConfig createTestConfig() { return new ITestConfigBuilder() .module(inferModuleName(CamelUnivocityParsersTest.class)) .build(); } @Test public void componentTests() throws Exception { this.runDataformatTest(config, "univocity-csv"); this.runDataformatTest(config, "univocity-fixed"); this.runDataformatTest(config, "univocity-tsv"); this.runModuleUnitTestsIfEnabled(config); } }
punkhorn/camel-upstream
tests/camel-itest-spring-boot/src/test/java/org/apache/camel/itest/springboot/CamelUnivocityParsersTest.java
Java
apache-2.0
1,889
package com.marshalchen.ultimaterecyclerview.demo; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.ActionMode; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdSize; import com.google.android.gms.ads.AdView; import com.marshalchen.ultimaterecyclerview.AdmobAdapter; import com.marshalchen.ultimaterecyclerview.URLogs; import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView; import com.marshalchen.ultimaterecyclerview.demo.modules.FastBinding; import com.marshalchen.ultimaterecyclerview.demo.modules.SampleDataboxset; import com.marshalchen.ultimaterecyclerview.demo.modules.admobdfpadapter; import java.util.ArrayList; import java.util.List; /** * Created by hesk on 20/5/15. */ public class TestAdMob extends AppCompatActivity { UltimateRecyclerView ultimateRecyclerView; admobdfpadapter simpleRecyclerViewAdapter = null; LinearLayoutManager linearLayoutManager; int moreNum = 2; private ActionMode actionMode; Toolbar toolbar; boolean isDrag = true; private boolean admob_test_mode = false; private AdView createadmob() { AdView mAdView = new AdView(this); mAdView.setAdSize(AdSize.MEDIUM_RECTANGLE); mAdView.setAdUnitId("/1015938/Hypebeast_App_320x50"); mAdView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); // Create an ad request. AdRequest.Builder adRequestBuilder = new AdRequest.Builder(); if (admob_test_mode) // Optionally populate the ad request builder. adRequestBuilder.addTestDevice(AdRequest.DEVICE_ID_EMULATOR); // Start loading the ad. mAdView.loadAd(adRequestBuilder.build()); return mAdView; } private void enableSwipe() { } private void enableRefreshAndLoadMore() { ultimateRecyclerView.setDefaultOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { new Handler().postDelayed(new Runnable() { @Override public void run() { simpleRecyclerViewAdapter.insert(moreNum++ + " Refresh things"); ultimateRecyclerView.setRefreshing(false); // ultimateRecyclerView.scrollBy(0, -50); linearLayoutManager.scrollToPosition(0); // ultimateRecyclerView.setAdapter(simpleRecyclerViewAdapter); // simpleRecyclerViewAdapter.notifyDataSetChanged(); } }, 1000); } }); ultimateRecyclerView.setOnLoadMoreListener(new UltimateRecyclerView.OnLoadMoreListener() { @Override public void loadMore(int itemsCount, final int maxLastVisiblePosition) { Handler handler = new Handler(); handler.postDelayed(new Runnable() { public void run() { Log.d("loadmore", maxLastVisiblePosition + " position"); SampleDataboxset.insertMore(simpleRecyclerViewAdapter, 1); // linearLayoutManager.scrollToPosition(linearLayoutManager.getChildCount() - 1); } }, 5000); } }); simpleRecyclerViewAdapter.setCustomLoadMoreView(LayoutInflater.from(this).inflate(R.layout.custom_bottom_progressbar, null)); ultimateRecyclerView.enableLoadmore(); } private void enableClick() { } private void impleAddDrop() { findViewById(R.id.add).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SampleDataboxset.insertMore(simpleRecyclerViewAdapter, 1); } }); findViewById(R.id.del).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { simpleRecyclerViewAdapter.remove(3); } }); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar = (Toolbar) findViewById(R.id.tool_bar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayShowTitleEnabled(false); ultimateRecyclerView = (UltimateRecyclerView) findViewById(R.id.ultimate_recycler_view); ultimateRecyclerView.setHasFixedSize(false); /** * wokring example 1 implementation of Admob banner with static Adview */ // simpleRecyclerViewAdapter = new admobdfpadapter(createadmob(), 5, stringList); /** * working example 2 with multiple called Adviews */ simpleRecyclerViewAdapter = new admobdfpadapter(createadmob(), 3, SampleDataboxset.newListFromGen(), new AdmobAdapter.AdviewListener() { @Override public AdView onGenerateAdview() { return createadmob(); } }); linearLayoutManager = new LinearLayoutManager(this); ultimateRecyclerView.setLayoutManager(linearLayoutManager); ultimateRecyclerView.setAdapter(simpleRecyclerViewAdapter); ultimateRecyclerView.setRecylerViewBackgroundColor(Color.parseColor("#ffffff")); enableRefreshAndLoadMore(); enableClick(); impleAddDrop(); } private void toggleSelection(int position) { simpleRecyclerViewAdapter.toggleSelection(position); actionMode.setTitle("Selected " + "1"); } @Override protected void onDestroy() { super.onDestroy(); } public int getScreenHeight() { return findViewById(android.R.id.content).getHeight(); } // @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { FastBinding.startactivity(this, item.getItemId()); return super.onOptionsItemSelected(item); } }
bunnyblue/UltimateRecyclerView
UltimateRecyclerView/app/src/main/java/com/marshalchen/ultimaterecyclerview/demo/TestAdMob.java
Java
apache-2.0
6,829
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_InfoCard * @subpackage Zend_InfoCard_Xml * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ /** * Zend_InfoCard_Xml_Element */ require_once 'Zend/InfoCard/Xml/Element.php'; /** * Represents a SecurityTokenReference XML block * * @category Zend * @package Zend_InfoCard * @subpackage Zend_InfoCard_Xml * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_InfoCard_Xml_SecurityTokenReference extends Zend_InfoCard_Xml_Element { /** * Base64 Binary Encoding URI */ const ENCODING_BASE64BIN = 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary'; /** * Return an instance of the object based on the input XML * * @param string $xmlData The SecurityTokenReference XML Block * @return Zend_InfoCard_Xml_SecurityTokenReference * @throws Zend_InfoCard_Xml_Exception */ static public function getInstance($xmlData) { if($xmlData instanceof Zend_InfoCard_Xml_Element) { $strXmlData = $xmlData->asXML(); } else if (is_string($xmlData)) { $strXmlData = $xmlData; } else { throw new Zend_InfoCard_Xml_Exception("Invalid Data provided to create instance"); } $sxe = simplexml_load_string($strXmlData); if($sxe->getName() != "SecurityTokenReference") { throw new Zend_InfoCard_Xml_Exception("Invalid XML Block provided for SecurityTokenReference"); } return simplexml_load_string($strXmlData, "Zend_InfoCard_Xml_SecurityTokenReference"); } /** * Return the Key Identifier XML Object * * @return Zend_InfoCard_Xml_Element * @throws Zend_InfoCard_Xml_Exception */ protected function _getKeyIdentifier() { $this->registerXPathNamespace('o', 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd'); list($keyident) = $this->xpath('//o:KeyIdentifier'); if(!($keyident instanceof Zend_InfoCard_Xml_Element)) { throw new Zend_InfoCard_Xml_Exception("Failed to retrieve Key Identifier"); } return $keyident; } /** * Return the Key URI identifying the thumbprint type used * * @return string The thumbprint type URI * @throws Zend_InfoCard_Xml_Exception */ public function getKeyThumbprintType() { $keyident = $this->_getKeyIdentifier(); $dom = self::convertToDOM($keyident); if(!$dom->hasAttribute('ValueType')) { throw new Zend_InfoCard_Xml_Exception("Key Identifier did not provide a type for the value"); } return $dom->getAttribute('ValueType'); } /** * Return the thumbprint encoding type used as a URI * * @return string the URI of the thumbprint encoding used * @throws Zend_InfoCard_Xml_Exception */ public function getKeyThumbprintEncodingType() { $keyident = $this->_getKeyIdentifier(); $dom = self::convertToDOM($keyident); if(!$dom->hasAttribute('EncodingType')) { throw new Zend_InfoCard_Xml_Exception("Unable to determine the encoding type for the key identifier"); } return $dom->getAttribute('EncodingType'); } /** * Get the key reference data used to identify the public key * * @param bool $decode if true, will return a decoded version of the key * @return string the key reference thumbprint, either in binary or encoded form * @throws Zend_InfoCard_Xml_Exception */ public function getKeyReference($decode = true) { $keyIdentifier = $this->_getKeyIdentifier(); $dom = self::convertToDOM($keyIdentifier); $encoded = $dom->nodeValue; if(empty($encoded)) { throw new Zend_InfoCard_Xml_Exception("Could not find the Key Reference Encoded Value"); } if($decode) { $decoded = ""; switch($this->getKeyThumbprintEncodingType()) { case self::ENCODING_BASE64BIN: if(version_compare(PHP_VERSION, "5.2.0", ">=")) { $decoded = base64_decode($encoded, true); } else { $decoded = base64_decode($encoded); } break; default: throw new Zend_InfoCard_Xml_Exception("Unknown Key Reference Encoding Type: {$this->getKeyThumbprintEncodingType()}"); } if(!$decoded || empty($decoded)) { throw new Zend_InfoCard_Xml_Exception("Failed to decode key reference"); } return $decoded; } return $encoded; } }
ajgarlag/zf1
library/Zend/InfoCard/Xml/SecurityTokenReference.php
PHP
bsd-3-clause
5,507
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Db * @subpackage Profiler * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ /** * @see Zend_Db_Exception */ require_once 'Zend/Db/Exception.php'; /** * @category Zend * @package Zend_Db * @subpackage Profiler * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Db_Profiler_Exception extends Zend_Db_Exception { }
svn2github/zend_framework
library/Zend/Db/Profiler/Exception.php
PHP
bsd-3-clause
1,099
MessageFormat.locale.es = function ( n ) { if ( n === 1 ) { return "one"; } return "other"; };
Ergosign/grunt-swagger-docs-onepage
test/fixtures/libs/messageformat/locale/es.js
JavaScript
mit
105
def func(a1): """ Parameters: a1 (:class:`MyClass`): used to call :def:`my_function` and access :attr:`my_attr` Raises: :class:`MyException`: thrown in case of any error """
asedunov/intellij-community
python/testData/docstrings/typeReferences.py
Python
apache-2.0
206
'use strict'; exports.__esModule = true; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _warnOnce = require('./warn-once'); var _warnOnce2 = _interopRequireDefault(_warnOnce); var _node = require('./node'); var _node2 = _interopRequireDefault(_node); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Declaration = function (_Node) { _inherits(Declaration, _Node); function Declaration(defaults) { _classCallCheck(this, Declaration); var _this = _possibleConstructorReturn(this, _Node.call(this, defaults)); _this.type = 'decl'; return _this; } /* istanbul ignore next */ _createClass(Declaration, [{ key: '_value', get: function get() { (0, _warnOnce2.default)('Node#_value was deprecated. Use Node#raws.value'); return this.raws.value; } /* istanbul ignore next */ , set: function set(val) { (0, _warnOnce2.default)('Node#_value was deprecated. Use Node#raws.value'); this.raws.value = val; } /* istanbul ignore next */ }, { key: '_important', get: function get() { (0, _warnOnce2.default)('Node#_important was deprecated. Use Node#raws.important'); return this.raws.important; } /* istanbul ignore next */ , set: function set(val) { (0, _warnOnce2.default)('Node#_important was deprecated. Use Node#raws.important'); this.raws.important = val; } }]); return Declaration; }(_node2.default); exports.default = Declaration; module.exports = exports['default'];
jgcopple/GarySchwantz
wp-content/themes/square-child/foundation/node_modules/gulp-autoprefixer/node_modules/postcss/lib/declaration.js
JavaScript
gpl-2.0
3,125
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\PropertyInfo\DependencyInjection; use Symfony\Component\DependencyInjection\Argument\IteratorArgument; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\Compiler\PriorityTaggedServiceTrait; use Symfony\Component\DependencyInjection\ContainerBuilder; /** * Adds extractors to the property_info service. * * @author Kévin Dunglas <dunglas@gmail.com> */ class PropertyInfoPass implements CompilerPassInterface { use PriorityTaggedServiceTrait; private $propertyInfoService; private $listExtractorTag; private $typeExtractorTag; private $descriptionExtractorTag; private $accessExtractorTag; private $initializableExtractorTag; public function __construct(string $propertyInfoService = 'property_info', string $listExtractorTag = 'property_info.list_extractor', string $typeExtractorTag = 'property_info.type_extractor', string $descriptionExtractorTag = 'property_info.description_extractor', string $accessExtractorTag = 'property_info.access_extractor', string $initializableExtractorTag = 'property_info.initializable_extractor') { $this->propertyInfoService = $propertyInfoService; $this->listExtractorTag = $listExtractorTag; $this->typeExtractorTag = $typeExtractorTag; $this->descriptionExtractorTag = $descriptionExtractorTag; $this->accessExtractorTag = $accessExtractorTag; $this->initializableExtractorTag = $initializableExtractorTag; } /** * {@inheritdoc} */ public function process(ContainerBuilder $container) { if (!$container->hasDefinition($this->propertyInfoService)) { return; } $definition = $container->getDefinition($this->propertyInfoService); $listExtractors = $this->findAndSortTaggedServices($this->listExtractorTag, $container); $definition->replaceArgument(0, new IteratorArgument($listExtractors)); $typeExtractors = $this->findAndSortTaggedServices($this->typeExtractorTag, $container); $definition->replaceArgument(1, new IteratorArgument($typeExtractors)); $descriptionExtractors = $this->findAndSortTaggedServices($this->descriptionExtractorTag, $container); $definition->replaceArgument(2, new IteratorArgument($descriptionExtractors)); $accessExtractors = $this->findAndSortTaggedServices($this->accessExtractorTag, $container); $definition->replaceArgument(3, new IteratorArgument($accessExtractors)); $initializableExtractors = $this->findAndSortTaggedServices($this->initializableExtractorTag, $container); $definition->setArgument(4, new IteratorArgument($initializableExtractors)); } }
Simperfit/symfony
src/Symfony/Component/PropertyInfo/DependencyInjection/PropertyInfoPass.php
PHP
mit
3,002
"""Tests for parabolic cylinder functions. """ import numpy as np from numpy.testing import assert_allclose, assert_equal import scipy.special as sc def test_pbwa_segfault(): # Regression test for https://github.com/scipy/scipy/issues/6208. # # Data generated by mpmath. # w = 1.02276567211316867161 wp = -0.48887053372346189882 assert_allclose(sc.pbwa(0, 0), (w, wp), rtol=1e-13, atol=0) def test_pbwa_nan(): # Check that NaN's are returned outside of the range in which the # implementation is accurate. pts = [(-6, -6), (-6, 6), (6, -6), (6, 6)] for p in pts: assert_equal(sc.pbwa(*p), (np.nan, np.nan))
mbayon/TFG-MachineLearning
venv/lib/python3.6/site-packages/scipy/special/tests/test_pcf.py
Python
mit
664
/** * Require unassigned functions to be named inline * * Types: `Boolean` or `Object` * * Values: * - `true` * - `Object`: * - `allExcept`: array of quoted identifiers * * #### Example * * ```js * "requireNamedUnassignedFunctions": { "allExcept": ["describe", "it"] } * ``` * * ##### Valid * * ```js * [].forEach(function x() {}); * var y = function() {}; * function z() {} * it(function () {}); * ``` * * ##### Invalid * * ```js * [].forEach(function () {}); * before(function () {}); * ``` */ var assert = require('assert'); var pathval = require('pathval'); function getNodeName(node) { if (node.type === 'Identifier') { return node.name; } else { return node.value; } } module.exports = function() {}; module.exports.prototype = { configure: function(options) { assert( options === true || typeof options === 'object', this.getOptionName() + ' option requires true value ' + 'or an object with String[] `allExcept` property' ); // verify first item in `allExcept` property in object (if it's an object) assert( typeof options !== 'object' || Array.isArray(options.allExcept) && typeof options.allExcept[0] === 'string', 'Property `allExcept` in ' + this.getOptionName() + ' should be an array of strings' ); if (options.allExcept) { this._allExceptItems = options.allExcept.map(function(item) { var parts = pathval.parse(item).map(function extractPart(part) { return part.i !== undefined ? part.i : part.p; }); return JSON.stringify(parts); }); } }, getOptionName: function() { return 'requireNamedUnassignedFunctions'; }, check: function(file, errors) { var _this = this; file.iterateNodesByType('FunctionExpression', function(node) { var parentElement = node.parentElement; // If the function has been named via left hand assignment, skip it // e.g. `var hello = function() {`, `foo.bar = function() {` if (parentElement.type.match(/VariableDeclarator|Property|AssignmentExpression/)) { return; } // If the function has been named, skip it // e.g. `[].forEach(function hello() {` if (node.id !== null) { return; } // If we have exceptions and the function is being invoked, detect whether we excepted it if (_this._allExceptItems && parentElement.type === 'CallExpression') { // Determine the path that resolves to our call expression // We must cover both direct calls (e.g. `it(function() {`) and // member expressions (e.g. `foo.bar(function() {`) var memberNode = parentElement.callee; var canBeRepresented = true; var fullpathParts = []; while (memberNode) { if (memberNode.type.match(/Identifier|Literal/)) { fullpathParts.unshift(getNodeName(memberNode)); } else if (memberNode.type === 'MemberExpression') { fullpathParts.unshift(getNodeName(memberNode.property)); } else { canBeRepresented = false; break; } memberNode = memberNode.object; } // If the path is not-dynamic (i.e. can be represented by static parts), // then check it against our exceptions if (canBeRepresented) { var fullpath = JSON.stringify(fullpathParts); for (var i = 0, l = _this._allExceptItems.length; i < l; i++) { if (fullpath === _this._allExceptItems[i]) { return; } } } } // Complain that this function must be named errors.add('Inline functions need to be named', node); }); } };
oavasquez/ingeneria_software
web-project/node_modules/jscs/lib/rules/require-named-unassigned-functions.js
JavaScript
mit
4,284
<?php if (!defined('_JEXEC')) die('Direct Access to ' . basename(__FILE__) . ' is not allowed.'); /** * IsAuthorized.class.php */ /** * * * @author Avalara * @copyright � 2004 - 2011 Avalara, Inc. All rights reserved. * @package Batch */ class IsAuthorized { private $Operations; // string public function setOperations($value){$this->Operations=$value;} // string public function getOperations(){return $this->Operations;} // string } ?>
jburnim/example-virtuemart-store-heroku
virtuemart/plugins/vmcalculation/avalara/classes/BatchSvc/IsAuthorized.class.php
PHP
gpl-2.0
467
<?php // displays the settings tab in Polylang settings $content_with_no_languages = $this->model->get_objects_with_no_lang() && $this->options['default_lang']; $page_on_front = 'page' == get_option('show_on_front') ? get_option('page_on_front') : 0; ?> <form id="options-lang" method="post" action="admin.php?page=mlang&amp;tab=settings&amp;noheader=true" class="validate"> <?php wp_nonce_field('options-lang', '_wpnonce_options-lang');?> <input type="hidden" name="pll_action" value="options" /> <table class="form-table"> <tr> <th <?php echo $content_with_no_languages ? 'rowspan=2' : ''; ?>> <label for='default_lang'><?php _e('Default language', 'polylang');?></label> </th> <td><?php $dropdown = new PLL_Walker_Dropdown; echo $dropdown->walk($listlanguages, array('name' => 'default_lang', 'selected' => $this->options['default_lang']));?> </td> </tr><?php // posts or terms without language set if ($content_with_no_languages) {?> <tr> <td> <label style="color: red"><?php printf( '<input name="fill_languages" type="checkbox" value="1" /> %s', __('There are posts, pages, categories or tags without language set. Do you want to set them all to default language ?', 'polylang') );?> </label> </td> </tr><?php }?> <tr> <th rowspan = <?php echo ($page_on_front ? 3 : 2) + $this->links_model->using_permalinks; ?>><?php _e('URL modifications', 'polylang') ?></th> <td><fieldset id='pll-force-lang'> <label><?php printf( '<input name="force_lang" type="radio" value="0" %s /> %s', $this->options['force_lang'] ? '' : 'checked="checked"', __('The language is set from content', 'polylang') );?> </label> <p class="description"><?php _e('Posts, pages, categories and tags urls are not modified.', 'polylang');?></p> <label><?php printf( '<input name="force_lang" type="radio" value="1" %s/> %s', 1 == $this->options['force_lang'] ? 'checked="checked"' : '', $this->links_model->using_permalinks ? __('The language is set from the directory name in pretty permalinks', 'polylang') : __('The language is set from the code in the URL', 'polylang') );?> </label> <p class="description"><?php echo __('Example:', 'polylang') . ' <code>'.esc_html(home_url($this->links_model->using_permalinks ? 'en/my-post/' : '?lang=en&p=1')).'</code>';?></p> <label><?php printf( '<input name="force_lang" type="radio" value="2" %s %s/> %s', $this->links_model->using_permalinks ? '' : 'disabled="disabled"', 2 == $this->options['force_lang'] ? 'checked="checked"' : '', __('The language is set from the subdomain name in pretty permalinks', 'polylang') );?> </label> <p class="description"><?php echo __('Example:', 'polylang') . ' <code>'.esc_html(str_replace(array('://', 'www.'), array('://en.', ''), home_url('my-post/'))).'</code>';?></p> <label><?php printf( '<input name="force_lang" type="radio" value="3" %s %s/> %s', $this->links_model->using_permalinks ? '' : 'disabled="disabled"', 3 == $this->options['force_lang'] ? 'checked="checked"' : '', __('The language is set from different domains', 'polylang') );?> </label> <table id="pll-domains-table" <?php echo 3 == $this->options['force_lang'] ? '' : 'style="display: none;"'; ?>><?php foreach ($listlanguages as $lg) { printf( '<tr><td><label for="pll-domain[%1$s]">%2$s</label></td>' . '<td><input name="domains[%1$s]" id="pll-domain[%1$s]" type="text" value="%3$s" size="40" aria-required="true" /></td></tr>', esc_attr($lg->slug), esc_attr($lg->name), esc_url(isset($this->options['domains'][$lg->slug]) ? $this->options['domains'][$lg->slug] : ($lg->slug == $this->options['default_lang'] ? $this->links_model->home : '')) ); }?> </table> </fieldset></td> </tr> <tr> <td id="pll-hide-default" <?php echo 3 > $this->options['force_lang'] ? '' : 'style="display: none;"'; ?>><fieldset> <label><?php printf( '<input name="hide_default" type="checkbox" value="1" %s /> %s', $this->options['hide_default'] ? 'checked="checked"' :'', __('Hide URL language information for default language', 'polylang') );?> </label> </fieldset></td> </tr><?php if ($this->links_model->using_permalinks) { ?> <tr> <td id="pll-rewrite" <?php echo 2 > $this->options['force_lang'] ? '' : 'style="display: none;"'; ?>><fieldset> <label><?php printf( '<input name="rewrite" type="radio" value="1" %s %s/> %s', $this->links_model->using_permalinks ? '' : 'disabled="disabled"', $this->options['rewrite'] ? 'checked="checked"' : '', __('Remove /language/ in pretty permalinks', 'polylang') );?> </label> <p class="description"><?php echo __('Example:', 'polylang') . ' <code>'.esc_html(home_url('en/')).'</code>';?></p> <label><?php printf( '<input name="rewrite" type="radio" value="0" %s %s/> %s', $this->links_model->using_permalinks ? '' : 'disabled="disabled"', $this->options['rewrite'] ? '' : 'checked="checked"', __('Keep /language/ in pretty permalinks', 'polylang') );?> </label> <p class="description"><?php echo __('Example:', 'polylang') . ' <code>'.esc_html(home_url('language/en/')).'</code>';?></p> </fieldset></td> </tr><?php } if ($page_on_front) { ?> <tr> <td><fieldset> <label><?php printf( '<input name="redirect_lang" type="checkbox" value="1" %s/> %s', $this->options['redirect_lang'] ? 'checked="checked"' :'', __('The front page url contains the language code instead of the page name or page id', 'polylang') );?> </label> <p class="description"><?php // that's nice to display the right home urls but don't forget that the page on front may have no language yet $lang = $this->model->get_post_language($page_on_front); $lang = $lang ? $lang : $this->model->get_language($this->options['default_lang']); printf( __('Example: %s instead of %s', 'polylang'), '<code>' . esc_html($this->links_model->home_url($lang)) . '</code>', '<code>' . esc_html(_get_page_link($page_on_front)) . '</code>' ); ?> </p> </fieldset></td> </tr><?php } ?> <tr id="pll-detect-browser" <?php echo 3 > $this->options['force_lang'] ? '' : 'style="display: none;"'; ?>> <th><?php _e('Detect browser language', 'polylang');?></th> <td> <label><?php printf( '<input name="browser" type="checkbox" value="1" %s /> %s', $this->options['browser'] ? 'checked="checked"' :'', __('When the front page is visited, set the language according to the browser preference', 'polylang') );?> </label> </td> </tr> <tr> <th scope="row"><?php _e('Media', 'polylang') ?></th> <td> <label><?php printf( '<input name="media_support" type="checkbox" value="1" %s /> %s', $this->options['media_support'] ? 'checked="checked"' :'', __('Activate languages and translations for media', 'polylang') );?> </label> </td> </tr><?php if (!empty($post_types)) {?> <tr> <th scope="row"><?php _e('Custom post types', 'polylang') ?></th> <td> <ul class="pll_inline_block"><?php foreach ($post_types as $post_type) { $pt = get_post_type_object($post_type); printf( '<li><label><input name="post_types[%s]" type="checkbox" value="1" %s /> %s</label></li>', esc_attr($post_type), in_array($post_type, $this->options['post_types']) ? 'checked="checked"' :'', esc_html($pt->labels->name) ); }?> </ul> <p class="description"><?php _e('Activate languages and translations for custom post types.', 'polylang');?></p> </td> </tr><?php } if (!empty($taxonomies)) {?> <tr> <th scope="row"><?php _e('Custom taxonomies', 'polylang') ?></th> <td> <ul class="pll_inline_block"><?php foreach ($taxonomies as $taxonomy) { $tax = get_taxonomy($taxonomy); printf( '<li><label><input name="taxonomies[%s]" type="checkbox" value="1" %s /> %s</label></li>', esc_attr($taxonomy), in_array($taxonomy, $this->options['taxonomies']) ? 'checked="checked"' :'', esc_html($tax->labels->name) ); }?> </ul> <p class="description"><?php _e('Activate languages and translations for custom taxonomies.', 'polylang');?></p> </td> </tr><?php }?> <tr> <th scope="row"><?php _e('Synchronization', 'polylang') ?></th> <td> <ul class="pll_inline_block"><?php foreach (self::list_metas_to_sync() as $key => $str) printf( '<li><label><input name="sync[%s]" type="checkbox" value="1" %s /> %s</label></li>', esc_attr($key), in_array($key, $this->options['sync']) ? 'checked="checked"' :'', esc_html($str) );?> </ul> <p class="description"><?php _e('The synchronization options allow to maintain exact same values (or translations in the case of taxonomies and page parent) of meta content between the translations of a post or page.', 'polylang');?></p> </td> </tr> </table> <?php submit_button(); // since WP 3.1 ?> </form>
akashprabhakar/finance-house
wp-content/plugins/polylang/admin/view-tab-settings.php
PHP
gpl-2.0
9,177
<?php if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point'); /********************************************************************************* * SugarCRM Community Edition is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc. * SuiteCRM is an extension to SugarCRM Community Edition developed by Salesagility Ltd. * Copyright (C) 2011 - 2014 Salesagility Ltd. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not * reasonably feasible for technical reasons, the Appropriate Legal Notices must * display the words "Powered by SugarCRM" and "Supercharged by SuiteCRM". ********************************************************************************/ function additionalDetailsCampaign($fields) { static $mod_strings; if(empty($mod_strings)) { global $current_language; $mod_strings = return_module_language($current_language, 'Campaigns'); } $overlib_string = ''; if(!empty($fields['START_DATE'])) $overlib_string .= '<b>'. $mod_strings['LBL_CAMPAIGN_START_DATE'] . '</b> ' . $fields['START_DATE'] . '<br>'; if(!empty($fields['TRACKER_TEXT'])) $overlib_string .= '<b>'. $mod_strings['LBL_TRACKER_TEXT'] . '</b> ' . $fields['TRACKER_TEXT'] . '<br>'; if(!empty($fields['REFER_URL'])) $overlib_string .= '<a target=_blank href='. $fields['REFER_URL'] . '>' . $fields['REFER_URL'] . '</a><br>'; if(!empty($fields['OBJECTIVE'])) { $overlib_string .= '<b>'. $mod_strings['LBL_CAMPAIGN_OBJECTIVE'] . '</b> ' . substr($fields['OBJECTIVE'], 0, 300); if(strlen($fields['OBJECTIVE']) > 300) $overlib_string .= '...'; $overlib_string .= '<br>'; } if(!empty($fields['CONTENT'])) { $overlib_string .= '<b>'. $mod_strings['LBL_CAMPAIGN_CONTENT'] . '</b> ' . substr($fields['CONTENT'], 0, 300); if(strlen($fields['CONTENT']) > 300) $overlib_string .= '...'; } return array('fieldToAddTo' => 'NAME', 'string' => $overlib_string, 'editLink' => "index.php?action=EditView&module=Campaigns&return_module=Campaigns&record={$fields['ID']}", 'viewLink' => "index.php?action=DetailView&module=Campaigns&return_module=Campaigns&record={$fields['ID']}"); } ?>
sgaved/SuiteCRM
modules/Campaigns/metadata/additionalDetails.php
PHP
agpl-3.0
3,753
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ // Usage: convert_computation <txt2bin|bin2txt> serialized_computation_proto // // bin2txt spits out the result to stdout. txt2bin modifies the file in place. #include <stdio.h> #include <unistd.h> #include <string> #include "tensorflow/compiler/xla/service/hlo.pb.h" #include "tensorflow/compiler/xla/statusor.h" #include "tensorflow/compiler/xla/types.h" #include "tensorflow/core/platform/env.h" #include "tensorflow/core/platform/init_main.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/protobuf.h" namespace xla { namespace tools { void RealMain(const string& mode, const string& path) { HloSnapshot module; tensorflow::Env* env = tensorflow::Env::Default(); if (mode == "txt2bin") { TF_CHECK_OK(tensorflow::ReadTextProto(env, path, &module)); TF_CHECK_OK(tensorflow::WriteBinaryProto(env, path, module)); } else if (mode == "bin2txt") { TF_CHECK_OK(tensorflow::ReadBinaryProto(env, path, &module)); string out; tensorflow::protobuf::TextFormat::PrintToString(module, &out); fprintf(stdout, "%s", out.c_str()); } else { LOG(QFATAL) << "unknown mode for computation conversion: " << mode; } } } // namespace tools } // namespace xla int main(int argc, char** argv) { tensorflow::port::InitMain(argv[0], &argc, &argv); QCHECK_EQ(argc, 3) << "usage: " << argv[0] << " <txt2bin|bin2txt> <path>"; xla::tools::RealMain(argv[1], argv[2]); return 0; }
adit-chandra/tensorflow
tensorflow/compiler/xla/tools/convert_computation.cc
C++
apache-2.0
2,113
/** * Copyright 1999-2014 dangdang.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.common.serialize.support.fst; import com.alibaba.dubbo.common.serialize.ObjectOutput; import de.ruedigermoeller.serialization.FSTObjectOutput; import java.io.IOException; import java.io.OutputStream; /** * @author lishen */ public class FstObjectOutput implements ObjectOutput { private FSTObjectOutput output; public FstObjectOutput(OutputStream outputStream) { output = FstFactory.getDefaultFactory().getObjectOutput(outputStream); } public void writeBool(boolean v) throws IOException { output.writeBoolean(v); } public void writeByte(byte v) throws IOException { output.writeByte(v); } public void writeShort(short v) throws IOException { output.writeShort(v); } public void writeInt(int v) throws IOException { output.writeInt(v); } public void writeLong(long v) throws IOException { output.writeLong(v); } public void writeFloat(float v) throws IOException { output.writeFloat(v); } public void writeDouble(double v) throws IOException { output.writeDouble(v); } public void writeBytes(byte[] v) throws IOException { if (v == null) { output.writeInt(-1); } else { writeBytes(v, 0, v.length); } } public void writeBytes(byte[] v, int off, int len) throws IOException { if (v == null) { output.writeInt(-1); } else { output.writeInt(len); output.write(v, off, len); } } public void writeUTF(String v) throws IOException { output.writeUTF(v); } public void writeObject(Object v) throws IOException { output.writeObject(v); } public void flushBuffer() throws IOException { output.flush(); } }
shuvigoss/dubbox
dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/fst/FstObjectOutput.java
Java
apache-2.0
2,448
import * as React from 'react'; import { CSSModule } from '../index'; export type FormTextProps<T = {}> = React.HTMLAttributes<HTMLElement> & { inline?: boolean; tag?: React.ReactType; color?: string; className?: string; cssModule?: CSSModule; } & T; declare class FormText<T = {[key: string]: any}> extends React.Component<FormTextProps<T>> {} export default FormText;
borisyankov/DefinitelyTyped
types/reactstrap/v7/lib/FormText.d.ts
TypeScript
mit
382
package digitalocean import ( "fmt" "log" "strings" "time" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/helper/schema" "github.com/pearkes/digitalocean" ) func resourceDigitalOceanDroplet() *schema.Resource { return &schema.Resource{ Create: resourceDigitalOceanDropletCreate, Read: resourceDigitalOceanDropletRead, Update: resourceDigitalOceanDropletUpdate, Delete: resourceDigitalOceanDropletDelete, Schema: map[string]*schema.Schema{ "image": &schema.Schema{ Type: schema.TypeString, Required: true, ForceNew: true, }, "name": &schema.Schema{ Type: schema.TypeString, Required: true, }, "region": &schema.Schema{ Type: schema.TypeString, Required: true, ForceNew: true, }, "size": &schema.Schema{ Type: schema.TypeString, Required: true, }, "status": &schema.Schema{ Type: schema.TypeString, Computed: true, }, "locked": &schema.Schema{ Type: schema.TypeString, Computed: true, }, "backups": &schema.Schema{ Type: schema.TypeBool, Optional: true, }, "ipv6": &schema.Schema{ Type: schema.TypeBool, Optional: true, }, "ipv6_address": &schema.Schema{ Type: schema.TypeString, Computed: true, }, "ipv6_address_private": &schema.Schema{ Type: schema.TypeString, Computed: true, }, "private_networking": &schema.Schema{ Type: schema.TypeBool, Optional: true, }, "ipv4_address": &schema.Schema{ Type: schema.TypeString, Computed: true, }, "ipv4_address_private": &schema.Schema{ Type: schema.TypeString, Computed: true, }, "ssh_keys": &schema.Schema{ Type: schema.TypeList, Optional: true, Elem: &schema.Schema{Type: schema.TypeString}, }, "user_data": &schema.Schema{ Type: schema.TypeString, Optional: true, }, }, } } func resourceDigitalOceanDropletCreate(d *schema.ResourceData, meta interface{}) error { client := meta.(*digitalocean.Client) // Build up our creation options opts := &digitalocean.CreateDroplet{ Image: d.Get("image").(string), Name: d.Get("name").(string), Region: d.Get("region").(string), Size: d.Get("size").(string), } if attr, ok := d.GetOk("backups"); ok { opts.Backups = attr.(bool) } if attr, ok := d.GetOk("ipv6"); ok { opts.IPV6 = attr.(bool) } if attr, ok := d.GetOk("private_networking"); ok { opts.PrivateNetworking = attr.(bool) } if attr, ok := d.GetOk("user_data"); ok { opts.UserData = attr.(string) } // Get configured ssh_keys ssh_keys := d.Get("ssh_keys.#").(int) if ssh_keys > 0 { opts.SSHKeys = make([]string, 0, ssh_keys) for i := 0; i < ssh_keys; i++ { key := fmt.Sprintf("ssh_keys.%d", i) opts.SSHKeys = append(opts.SSHKeys, d.Get(key).(string)) } } log.Printf("[DEBUG] Droplet create configuration: %#v", opts) id, err := client.CreateDroplet(opts) if err != nil { return fmt.Errorf("Error creating droplet: %s", err) } // Assign the droplets id d.SetId(id) log.Printf("[INFO] Droplet ID: %s", d.Id()) _, err = WaitForDropletAttribute(d, "active", []string{"new"}, "status", meta) if err != nil { return fmt.Errorf( "Error waiting for droplet (%s) to become ready: %s", d.Id(), err) } return resourceDigitalOceanDropletRead(d, meta) } func resourceDigitalOceanDropletRead(d *schema.ResourceData, meta interface{}) error { client := meta.(*digitalocean.Client) // Retrieve the droplet properties for updating the state droplet, err := client.RetrieveDroplet(d.Id()) if err != nil { // check if the droplet no longer exists. if err.Error() == "Error retrieving droplet: API Error: 404 Not Found" { d.SetId("") return nil } return fmt.Errorf("Error retrieving droplet: %s", err) } if droplet.ImageSlug() != "" { d.Set("image", droplet.ImageSlug()) } else { d.Set("image", droplet.ImageId()) } d.Set("name", droplet.Name) d.Set("region", droplet.RegionSlug()) d.Set("size", droplet.SizeSlug) d.Set("status", droplet.Status) d.Set("locked", droplet.IsLocked()) if droplet.IPV6Address("public") != "" { d.Set("ipv6", true) d.Set("ipv6_address", droplet.IPV6Address("public")) d.Set("ipv6_address_private", droplet.IPV6Address("private")) } d.Set("ipv4_address", droplet.IPV4Address("public")) if droplet.NetworkingType() == "private" { d.Set("private_networking", true) d.Set("ipv4_address_private", droplet.IPV4Address("private")) } // Initialize the connection info d.SetConnInfo(map[string]string{ "type": "ssh", "host": droplet.IPV4Address("public"), }) return nil } func resourceDigitalOceanDropletUpdate(d *schema.ResourceData, meta interface{}) error { client := meta.(*digitalocean.Client) if d.HasChange("size") { oldSize, newSize := d.GetChange("size") err := client.PowerOff(d.Id()) if err != nil && !strings.Contains(err.Error(), "Droplet is already powered off") { return fmt.Errorf( "Error powering off droplet (%s): %s", d.Id(), err) } // Wait for power off _, err = WaitForDropletAttribute(d, "off", []string{"active"}, "status", client) if err != nil { return fmt.Errorf( "Error waiting for droplet (%s) to become powered off: %s", d.Id(), err) } // Resize the droplet err = client.Resize(d.Id(), newSize.(string)) if err != nil { newErr := powerOnAndWait(d, meta) if newErr != nil { return fmt.Errorf( "Error powering on droplet (%s) after failed resize: %s", d.Id(), err) } return fmt.Errorf( "Error resizing droplet (%s): %s", d.Id(), err) } // Wait for the size to change _, err = WaitForDropletAttribute( d, newSize.(string), []string{"", oldSize.(string)}, "size", meta) if err != nil { newErr := powerOnAndWait(d, meta) if newErr != nil { return fmt.Errorf( "Error powering on droplet (%s) after waiting for resize to finish: %s", d.Id(), err) } return fmt.Errorf( "Error waiting for resize droplet (%s) to finish: %s", d.Id(), err) } err = client.PowerOn(d.Id()) if err != nil { return fmt.Errorf( "Error powering on droplet (%s) after resize: %s", d.Id(), err) } // Wait for power off _, err = WaitForDropletAttribute(d, "active", []string{"off"}, "status", meta) if err != nil { return err } } if d.HasChange("name") { oldName, newName := d.GetChange("name") // Rename the droplet err := client.Rename(d.Id(), newName.(string)) if err != nil { return fmt.Errorf( "Error renaming droplet (%s): %s", d.Id(), err) } // Wait for the name to change _, err = WaitForDropletAttribute( d, newName.(string), []string{"", oldName.(string)}, "name", meta) if err != nil { return fmt.Errorf( "Error waiting for rename droplet (%s) to finish: %s", d.Id(), err) } } // As there is no way to disable private networking, // we only check if it needs to be enabled if d.HasChange("private_networking") && d.Get("private_networking").(bool) { err := client.EnablePrivateNetworking(d.Id()) if err != nil { return fmt.Errorf( "Error enabling private networking for droplet (%s): %s", d.Id(), err) } // Wait for the private_networking to turn on _, err = WaitForDropletAttribute( d, "true", []string{"", "false"}, "private_networking", meta) return fmt.Errorf( "Error waiting for private networking to be enabled on for droplet (%s): %s", d.Id(), err) } // As there is no way to disable IPv6, we only check if it needs to be enabled if d.HasChange("ipv6") && d.Get("ipv6").(bool) { err := client.EnableIPV6s(d.Id()) if err != nil { return fmt.Errorf( "Error turning on ipv6 for droplet (%s): %s", d.Id(), err) } // Wait for ipv6 to turn on _, err = WaitForDropletAttribute( d, "true", []string{"", "false"}, "ipv6", meta) if err != nil { return fmt.Errorf( "Error waiting for ipv6 to be turned on for droplet (%s): %s", d.Id(), err) } } return resourceDigitalOceanDropletRead(d, meta) } func resourceDigitalOceanDropletDelete(d *schema.ResourceData, meta interface{}) error { client := meta.(*digitalocean.Client) _, err := WaitForDropletAttribute( d, "false", []string{"", "true"}, "locked", meta) if err != nil { return fmt.Errorf( "Error waiting for droplet to be unlocked for destroy (%s): %s", d.Id(), err) } log.Printf("[INFO] Deleting droplet: %s", d.Id()) // Destroy the droplet err = client.DestroyDroplet(d.Id()) // Handle remotely destroyed droplets if err != nil && strings.Contains(err.Error(), "404 Not Found") { return nil } if err != nil { return fmt.Errorf("Error deleting droplet: %s", err) } return nil } func WaitForDropletAttribute( d *schema.ResourceData, target string, pending []string, attribute string, meta interface{}) (interface{}, error) { // Wait for the droplet so we can get the networking attributes // that show up after a while log.Printf( "[INFO] Waiting for droplet (%s) to have %s of %s", d.Id(), attribute, target) stateConf := &resource.StateChangeConf{ Pending: pending, Target: target, Refresh: newDropletStateRefreshFunc(d, attribute, meta), Timeout: 60 * time.Minute, Delay: 10 * time.Second, MinTimeout: 3 * time.Second, // This is a hack around DO API strangeness. // https://github.com/hashicorp/terraform/issues/481 // NotFoundChecks: 60, } return stateConf.WaitForState() } // TODO This function still needs a little more refactoring to make it // cleaner and more efficient func newDropletStateRefreshFunc( d *schema.ResourceData, attribute string, meta interface{}) resource.StateRefreshFunc { client := meta.(*digitalocean.Client) return func() (interface{}, string, error) { err := resourceDigitalOceanDropletRead(d, meta) if err != nil { return nil, "", err } // If the droplet is locked, continue waiting. We can // only perform actions on unlocked droplets, so it's // pointless to look at that status if d.Get("locked").(string) == "true" { log.Println("[DEBUG] Droplet is locked, skipping status check and retrying") return nil, "", nil } // See if we can access our attribute if attr, ok := d.GetOk(attribute); ok { // Retrieve the droplet properties droplet, err := client.RetrieveDroplet(d.Id()) if err != nil { return nil, "", fmt.Errorf("Error retrieving droplet: %s", err) } return &droplet, attr.(string), nil } return nil, "", nil } } // Powers on the droplet and waits for it to be active func powerOnAndWait(d *schema.ResourceData, meta interface{}) error { client := meta.(*digitalocean.Client) err := client.PowerOn(d.Id()) if err != nil { return err } // Wait for power on _, err = WaitForDropletAttribute(d, "active", []string{"off"}, "status", client) if err != nil { return err } return nil }
printedheart/terraform
builtin/providers/digitalocean/resource_digitalocean_droplet.go
GO
mpl-2.0
10,934
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.operator.aggregation; import com.facebook.presto.operator.aggregation.state.RegressionState; import com.facebook.presto.spi.block.BlockBuilder; import com.facebook.presto.spi.type.StandardTypes; import com.facebook.presto.type.SqlType; import static com.facebook.presto.operator.aggregation.AggregationUtils.mergeRegressionState; import static com.facebook.presto.operator.aggregation.AggregationUtils.updateRegressionState; import static com.facebook.presto.spi.type.DoubleType.DOUBLE; @AggregationFunction("") // Names are on output methods public class RegressionAggregation { private RegressionAggregation() {} @InputFunction public static void input(RegressionState state, @SqlType(StandardTypes.DOUBLE) double dependentValue, @SqlType(StandardTypes.DOUBLE) double independentValue) { updateRegressionState(state, independentValue, dependentValue); } @CombineFunction public static void combine(RegressionState state, RegressionState otherState) { mergeRegressionState(state, otherState); } @AggregationFunction("regr_slope") @OutputFunction(StandardTypes.DOUBLE) public static void regrSlope(RegressionState state, BlockBuilder out) { // Math comes from ISO9075-2:2011(E) 10.9 General Rules 7 c xii double dividend = state.getCount() * state.getSumXY() - state.getSumX() * state.getSumY(); double divisor = state.getCount() * state.getSumXSquare() - state.getSumX() * state.getSumX(); // divisor deliberately not checked for zero because the result can be Infty or NaN even if it is not zero double result = dividend / divisor; if (Double.isFinite(result)) { DOUBLE.writeDouble(out, result); } else { out.appendNull(); } } @AggregationFunction("regr_intercept") @OutputFunction(StandardTypes.DOUBLE) public static void regrIntercept(RegressionState state, BlockBuilder out) { // Math comes from ISO9075-2:2011(E) 10.9 General Rules 7 c xiii double dividend = state.getSumY() * state.getSumXSquare() - state.getSumX() * state.getSumXY(); double divisor = state.getCount() * state.getSumXSquare() - state.getSumX() * state.getSumX(); // divisor deliberately not checked for zero because the result can be Infty or NaN even if it is not zero double result = dividend / divisor; if (Double.isFinite(result)) { DOUBLE.writeDouble(out, result); } else { out.appendNull(); } } }
kuzemchik/presto
presto-main/src/main/java/com/facebook/presto/operator/aggregation/RegressionAggregation.java
Java
apache-2.0
3,161
// (C) Copyright 2008 CodeRage, LLC (turkanis at coderage dot com) // (C) Copyright 2003-2007 Jonathan Turkanis // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt.) // See http://www.boost.org/libs/iostreams for documentation. #ifndef BOOST_IOSTREAMS_STREAM_HPP_INCLUDED #define BOOST_IOSTREAMS_STREAM_HPP_INCLUDED #if defined(_MSC_VER) # pragma once #endif #include <boost/iostreams/constants.hpp> #include <boost/iostreams/detail/char_traits.hpp> #include <boost/iostreams/detail/config/overload_resolution.hpp> #include <boost/iostreams/detail/forward.hpp> #include <boost/iostreams/detail/iostream.hpp> // standard streams. #include <boost/iostreams/detail/select.hpp> #include <boost/iostreams/stream_buffer.hpp> #include <boost/mpl/and.hpp> #include <boost/type_traits/is_convertible.hpp> #include <boost/utility/base_from_member.hpp> namespace boost { namespace iostreams { namespace detail { template<typename Device, typename Tr> struct stream_traits { typedef typename char_type_of<Device>::type char_type; typedef Tr traits_type; typedef typename category_of<Device>::type mode; typedef typename iostreams::select< // Disambiguation required for Tru64. mpl::and_< is_convertible<mode, input>, is_convertible<mode, output> >, BOOST_IOSTREAMS_BASIC_IOSTREAM(char_type, traits_type), is_convertible<mode, input>, BOOST_IOSTREAMS_BASIC_ISTREAM(char_type, traits_type), else_, BOOST_IOSTREAMS_BASIC_OSTREAM(char_type, traits_type) >::type stream_type; typedef typename iostreams::select< // Disambiguation required for Tru64. mpl::and_< is_convertible<mode, input>, is_convertible<mode, output> >, iostream_tag, is_convertible<mode, input>, istream_tag, else_, ostream_tag >::type stream_tag; }; #if defined(BOOST_MSVC) && (BOOST_MSVC == 1700) # pragma warning(push) // https://connect.microsoft.com/VisualStudio/feedback/details/733720/ # pragma warning(disable: 4250) #endif // By encapsulating initialization in a base, we can define the macro // BOOST_IOSTREAMS_DEFINE_FORWARDING_FUNCTIONS to generate constructors // without base member initializer lists. template< typename Device, typename Tr = BOOST_IOSTREAMS_CHAR_TRAITS( BOOST_DEDUCED_TYPENAME char_type_of<Device>::type ), typename Alloc = std::allocator< BOOST_DEDUCED_TYPENAME char_type_of<Device>::type >, typename Base = // VC6 Workaround. BOOST_DEDUCED_TYPENAME detail::stream_traits<Device, Tr>::stream_type > class stream_base : protected base_from_member< stream_buffer<Device, Tr, Alloc> >, public Base { private: typedef base_from_member< stream_buffer<Device, Tr, Alloc> > pbase_type; typedef typename stream_traits<Device, Tr>::stream_type stream_type; protected: using pbase_type::member; // Avoid warning about 'this' in initializer list. public: stream_base() : pbase_type(), stream_type(&member) { } }; #if defined(BOOST_MSVC) && (BOOST_MSVC == 1700) # pragma warning(pop) #endif } } } // End namespaces detail, iostreams, boost. #ifdef BOOST_IOSTREAMS_BROKEN_OVERLOAD_RESOLUTION # include <boost/iostreams/detail/broken_overload_resolution/stream.hpp> #else namespace boost { namespace iostreams { #if defined(BOOST_MSVC) && (BOOST_MSVC == 1700) # pragma warning(push) // https://connect.microsoft.com/VisualStudio/feedback/details/733720/ # pragma warning(disable: 4250) #endif // // Template name: stream. // Description: A iostream which reads from and writes to an instance of a // designated device type. // Template parameters: // Device - A device type. // Alloc - The allocator type. // template< typename Device, typename Tr = BOOST_IOSTREAMS_CHAR_TRAITS( BOOST_DEDUCED_TYPENAME char_type_of<Device>::type ), typename Alloc = std::allocator< BOOST_DEDUCED_TYPENAME char_type_of<Device>::type > > struct stream : detail::stream_base<Device, Tr, Alloc> { public: typedef typename char_type_of<Device>::type char_type; struct category : mode_of<Device>::type, closable_tag, detail::stream_traits<Device, Tr>::stream_tag { }; BOOST_IOSTREAMS_STREAMBUF_TYPEDEFS(Tr) private: typedef typename detail::stream_traits< Device, Tr >::stream_type stream_type; public: stream() { } BOOST_IOSTREAMS_FORWARD( stream, open_impl, Device, BOOST_IOSTREAMS_PUSH_PARAMS, BOOST_IOSTREAMS_PUSH_ARGS ) bool is_open() const { return this->member.is_open(); } void close() { this->member.close(); } bool auto_close() const { return this->member.auto_close(); } void set_auto_close(bool close) { this->member.set_auto_close(close); } bool strict_sync() { return this->member.strict_sync(); } Device& operator*() { return *this->member; } Device* operator->() { return &*this->member; } Device* component() { return this->member.component(); } private: void open_impl(const Device& dev BOOST_IOSTREAMS_PUSH_PARAMS()) // For forwarding. { this->clear(); this->member.open(dev BOOST_IOSTREAMS_PUSH_ARGS()); } }; #if defined(BOOST_MSVC) && (BOOST_MSVC == 1700) # pragma warning(pop) #endif } } // End namespaces iostreams, boost. #endif // #ifdef BOOST_IOSTREAMS_BROKEN_OVERLOAD_RESOLUTION #endif // #ifndef BOOST_IOSTREAMS_stream_HPP_INCLUDED
zcobell/MetOceanViewer
thirdparty/boost_1_67_0/boost/iostreams/stream.hpp
C++
gpl-3.0
6,133
require 'rails_helper' RSpec.describe Comment, type: :model do pending "add some examples to (or delete) #{__FILE__}" end
sommda/photogram
web/spec/models/comment_spec.rb
Ruby
apache-2.0
125
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Routing\Generator\Dumper; /** * PhpGeneratorDumper creates a PHP class able to generate URLs for a given set of routes. * * @author Fabien Potencier <fabien@symfony.com> * @author Tobias Schultze <http://tobion.de> * * @api */ class PhpGeneratorDumper extends GeneratorDumper { /** * Dumps a set of routes to a PHP class. * * Available options: * * * class: The class name * * base_class: The base class name * * @param array $options An array of options * * @return string A PHP class representing the generator class * * @api */ public function dump(array $options = array()) { $options = array_merge(array( 'class' => 'ProjectUrlGenerator', 'base_class' => 'Symfony\\Component\\Routing\\Generator\\UrlGenerator', ), $options); return <<<EOF <?php use Symfony\Component\Routing\RequestContext; use Symfony\Component\Routing\Exception\RouteNotFoundException; use Psr\Log\LoggerInterface; /** * {$options['class']} * * This class has been auto-generated * by the Symfony Routing Component. */ class {$options['class']} extends {$options['base_class']} { private static \$declaredRoutes = {$this->generateDeclaredRoutes()}; /** * Constructor. */ public function __construct(RequestContext \$context, LoggerInterface \$logger = null) { \$this->context = \$context; \$this->logger = \$logger; } {$this->generateGenerateMethod()} } EOF; } /** * Generates PHP code representing an array of defined routes * together with the routes properties (e.g. requirements). * * @return string PHP code */ private function generateDeclaredRoutes() { $routes = "array(\n"; foreach ($this->getRoutes()->all() as $name => $route) { $compiledRoute = $route->compile(); $properties = array(); $properties[] = $compiledRoute->getVariables(); $properties[] = $route->getDefaults(); $properties[] = $route->getRequirements(); $properties[] = $compiledRoute->getTokens(); $properties[] = $compiledRoute->getHostTokens(); $routes .= sprintf(" '%s' => %s,\n", $name, str_replace("\n", '', var_export($properties, true))); } $routes .= ' )'; return $routes; } /** * Generates PHP code representing the `generate` method that implements the UrlGeneratorInterface. * * @return string PHP code */ private function generateGenerateMethod() { return <<<EOF public function generate(\$name, \$parameters = array(), \$referenceType = self::ABSOLUTE_PATH) { if (!isset(self::\$declaredRoutes[\$name])) { throw new RouteNotFoundException(sprintf('Unable to generate a URL for the named route "%s" as such route does not exist.', \$name)); } list(\$variables, \$defaults, \$requirements, \$tokens, \$hostTokens) = self::\$declaredRoutes[\$name]; return \$this->doGenerate(\$variables, \$defaults, \$requirements, \$tokens, \$parameters, \$name, \$referenceType, \$hostTokens); } EOF; } }
smeagonline-developers/OnlineEducationPlatform---SMEAGonline
vendor2/symfony/symfony/src/Symfony/Component/Routing/Generator/Dumper/PhpGeneratorDumper.php
PHP
mit
3,511
function X2JS(_1){ "use strict"; var _2="1.1.2"; _1=_1||{}; _3(); function _3(){ if(_1.escapeMode===undefined){ _1.escapeMode=true; } if(_1.attributePrefix===undefined){ _1.attributePrefix="_"; } if(_1.arrayAccessForm===undefined){ _1.arrayAccessForm="none"; } if(_1.emptyNodeForm===undefined){ _1.emptyNodeForm="text"; } }; var _4={ELEMENT_NODE:1,TEXT_NODE:3,CDATA_SECTION_NODE:4,DOCUMENT_NODE:9}; function _5(_6){ var _7=_6.localName; if(_7==null){ _7=_6.baseName; } if(_7==null||_7==""){ _7=_6.nodeName; } return _7; }; function _8(_9){ return _9.prefix; }; function _a(_b){ if(typeof (_b)=="string"){ return _b.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#x27;").replace(/\//g,"&#x2F;"); }else{ return _b; } }; function _c(_d){ return _d.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,"\"").replace(/&#x27;/g,"'").replace(/&#x2F;/g,"/"); }; function _e(_f,_10){ switch(_1.arrayAccessForm){ case "property": if(!(_f[_10] instanceof Array)){ _f[_10+"_asArray"]=[_f[_10]]; }else{ _f[_10+"_asArray"]=_f[_10]; } break; } }; function _11(_12){ if(_12.nodeType==_4.DOCUMENT_NODE){ var _13=new Object; var _14=_12.firstChild; var _15=_5(_14); _13[_15]=_11(_14); return _13; }else{ if(_12.nodeType==_4.ELEMENT_NODE){ var _13=new Object; _13.__cnt=0; var _16=_12.childNodes; for(var _17=0;_17<_16.length;_17++){ var _14=_16.item(_17); var _15=_5(_14); _13.__cnt++; if(_13[_15]==null){ _13[_15]=_11(_14); _e(_13,_15); }else{ if(_13[_15]!=null){ if(!(_13[_15] instanceof Array)){ _13[_15]=[_13[_15]]; _e(_13,_15); } } var _18=0; while(_13[_15][_18]!=null){ _18++; } (_13[_15])[_18]=_11(_14); } } for(var _19=0;_19<_12.attributes.length;_19++){ var _1a=_12.attributes.item(_19); _13.__cnt++; _13[_1.attributePrefix+_1a.name]=_1a.value; } var _1b=_8(_12); if(_1b!=null&&_1b!=""){ _13.__cnt++; _13.__prefix=_1b; } if(_13["#text"]!=null){ _13.__text=_13["#text"]; if(_13.__text instanceof Array){ _13.__text=_13.__text.join("\n"); } if(_1.escapeMode){ _13.__text=_c(_13.__text); } delete _13["#text"]; if(_1.arrayAccessForm=="property"){ delete _13["#text_asArray"]; } } if(_13["#cdata-section"]!=null){ _13.__cdata=_13["#cdata-section"]; delete _13["#cdata-section"]; if(_1.arrayAccessForm=="property"){ delete _13["#cdata-section_asArray"]; } } if(_13.__cnt==1&&_13.__text!=null){ _13=_13.__text; }else{ if(_13.__cnt==0&&_1.emptyNodeForm=="text"){ _13=""; } } delete _13.__cnt; if(_13.__text!=null||_13.__cdata!=null){ _13.toString=function(){ return (this.__text!=null?this.__text:"")+(this.__cdata!=null?this.__cdata:""); }; } return _13; }else{ if(_12.nodeType==_4.TEXT_NODE||_12.nodeType==_4.CDATA_SECTION_NODE){ return _12.nodeValue; } } } }; function _1c(_1d,_1e,_1f,_20){ var _21="<"+((_1d!=null&&_1d.__prefix!=null)?(_1d.__prefix+":"):"")+_1e; if(_1f!=null){ for(var _22=0;_22<_1f.length;_22++){ var _23=_1f[_22]; var _24=_1d[_23]; _21+=" "+_23.substr(_1.attributePrefix.length)+"='"+_24+"'"; } } if(!_20){ _21+=">"; }else{ _21+="/>"; } return _21; }; function _25(_26,_27){ return "</"+(_26.__prefix!=null?(_26.__prefix+":"):"")+_27+">"; }; function _28(str,_29){ return str.indexOf(_29,str.length-_29.length)!==-1; }; function _2a(_2b,_2c){ if((_1.arrayAccessForm=="property"&&_28(_2c.toString(),("_asArray")))||_2c.toString().indexOf(_1.attributePrefix)==0||_2c.toString().indexOf("__")==0||(_2b[_2c] instanceof Function)){ return true; }else{ return false; } }; function _2d(_2e){ var _2f=0; if(_2e instanceof Object){ for(var it in _2e){ if(_2a(_2e,it)){ continue; } _2f++; } } return _2f; }; function _30(_31){ var _32=[]; if(_31 instanceof Object){ for(var ait in _31){ if(ait.toString().indexOf("__")==-1&&ait.toString().indexOf(_1.attributePrefix)==0){ _32.push(ait); } } } return _32; }; function _33(_34){ var _35=""; if(_34.__cdata!=null){ _35+="<![CDATA["+_34.__cdata+"]]>"; } if(_34.__text!=null){ if(_1.escapeMode){ _35+=_a(_34.__text); }else{ _35+=_34.__text; } } return _35; }; function _36(_37){ var _38=""; if(_37 instanceof Object){ _38+=_33(_37); }else{ if(_37!=null){ if(_1.escapeMode){ _38+=_a(_37); }else{ _38+=_37; } } } return _38; }; function _39(_3a,_3b,_3c){ var _3d=""; if(_3a.length==0){ _3d+=_1c(_3a,_3b,_3c,true); }else{ for(var _3e=0;_3e<_3a.length;_3e++){ _3d+=_1c(_3a[_3e],_3b,_30(_3a[_3e]),false); _3d+=_3f(_3a[_3e]); _3d+=_25(_3a[_3e],_3b); } } return _3d; }; function _3f(_40){ var _41=""; var _42=_2d(_40); if(_42>0){ for(var it in _40){ if(_2a(_40,it)){ continue; } var _43=_40[it]; var _44=_30(_43); if(_43==null||_43==undefined){ _41+=_1c(_43,it,_44,true); }else{ if(_43 instanceof Object){ if(_43 instanceof Array){ _41+=_39(_43,it,_44); }else{ var _45=_2d(_43); if(_45>0||_43.__text!=null||_43.__cdata!=null){ _41+=_1c(_43,it,_44,false); _41+=_3f(_43); _41+=_25(_43,it); }else{ _41+=_1c(_43,it,_44,true); } } }else{ _41+=_1c(_43,it,_44,false); _41+=_36(_43); _41+=_25(_43,it); } } } } _41+=_36(_40); return _41; }; this.parseXmlString=function(_46){ if(_46===undefined){ return null; } var _47; if(window.DOMParser){ var _48=new window.DOMParser(); _47=_48.parseFromString(_46,"text/xml"); }else{ if(_46.indexOf("<?")==0){ _46=_46.substr(_46.indexOf("?>")+2); } _47=new ActiveXObject("Microsoft.XMLDOM"); _47.async="false"; _47.loadXML(_46); } return _47; }; this.asArray=function(_49){ if(_49 instanceof Array){ return _49; }else{ return [_49]; } }; this.xml2json=function(_4a){ return _11(_4a); }; this.xml_str2json=function(_4b){ var _4c=this.parseXmlString(_4b); return this.xml2json(_4c); }; this.json2xml_str=function(_4d){ return _3f(_4d); }; this.json2xml=function(_4e){ var _4f=this.json2xml_str(_4e); return this.parseXmlString(_4f); }; this.getVersion=function(){ return _2; }; };
retrobot/zurbebay
zips/x2js-v1.1.2/xml2json.min.js
JavaScript
mit
5,729
import * as React from 'react'; import { IconBaseProps } from 'react-icon-base'; declare class IoIosRefresh extends React.Component<IconBaseProps> { } export = IoIosRefresh;
zuzusik/DefinitelyTyped
types/react-icons/lib/io/ios-refresh.d.ts
TypeScript
mit
174