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 |
|---|---|---|---|---|---|
#!/usr/bin/python
#
# 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.
#
import os, sys, subprocess, socket, fcntl, struct
from socket import gethostname
from xml.dom.minidom import parseString
from xmlrpclib import ServerProxy, Error
def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
def is_it_up(host, port):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(1)
s.connect((host, port))
s.close()
except:
print "host: %s:%s DOWN" % (host, port)
return False
print "host: %s:%s UP" % (host, port)
return True
# hmm master actions don't apply to a slave
master = "192.168.1.161"
port = 8899
user = "oracle"
password = "*******"
auth = "%s:%s" % (user, password)
server = ServerProxy("http://%s:%s" % ("localhost", port))
mserver = ServerProxy("http://%s@%s:%s" % (auth, master, port))
poolNode = True
interface = "c0a80100"
role = 'xen,utility'
hostname = gethostname()
ip = get_ip_address(interface)
poolMembers = []
xserver = server
print "setting up password"
server.update_agent_password(user, password)
if (is_it_up(master, port)):
print "master seems to be up, slaving"
xserver = mserver
else:
print "no master yet, will become master"
# other mechanism must be used to make interfaces equal...
try:
# pooling related same as primary storage!
poolalias = "Pool 0"
poolid = "0004fb0000020000ba9aaf00ae5e2d73"
poolfsnfsbaseuuid = "7718562d-872f-47a7-b454-8f9cac4ffa3a"
pooluuid = poolid
poolfsuuid = poolid
clusterid = "ba9aaf00ae5e2d72"
mgr = "d1a749d4295041fb99854f52ea4dea97"
poolmvip = master
poolfsnfsbaseuuid = "6824e646-5908-48c9-ba44-bb1a8a778084"
repoid = "6824e646590848c9ba44bb1a8a778084"
poolid = repoid
repo = "/OVS/Repositories/%s" % (repoid)
repomount = "cs-mgmt:/volumes/cs-data/secondary"
# primary
primuuid = "7718562d872f47a7b4548f9cac4ffa3a"
ssuuid = "7718562d-872f-47a7-b454-8f9cac4ffa3a"
fshost = "cs-mgmt"
fstarget = "/volumes/cs-data/primary"
fstype = "nfs"
fsname = "Primary storage"
fsmntpoint = "%s:%s" % (fshost, fstarget)
fsmnt = "/nfsmnt/%s" % (ssuuid)
fsplugin = "oracle.generic.NFSPlugin.GenericNFSPlugin"
# set the basics we require to "operate"
print server.take_ownership(mgr, '')
print server.update_server_roles(role,)
# if we're pooling pool...
if (poolNode == True):
poolCount = 0
pooled = False
# check pooling
try:
poolDom = parseString(xserver.discover_server_pool())
print xserver.discover_server_pool()
for node in poolDom.getElementsByTagName('Server_Pool'):
id = node.getElementsByTagName('Unique_Id')[0].firstChild.nodeValue
alias = node.getElementsByTagName('Pool_Alias')[0].firstChild.nodeValue
mvip = node.getElementsByTagName('Master_Virtual_Ip')[0].firstChild.nodeValue
print "pool: %s, %s, %s" % (id, mvip, alias)
members = node.getElementsByTagName('Member')
for member in members:
poolCount = poolCount + 1
mip = member.getElementsByTagName('Registered_IP')[0].firstChild.nodeValue
print "member: %s" % (mip)
if mip == ip:
pooled = True
else:
poolMembers.append(mip)
except Error, v:
print "no master will become master, %s" % v
if (pooled == False):
# setup the repository
print "setup repo"
print server.mount_repository_fs(repomount, repo)
try:
print "adding repo"
print server.add_repository(repomount, repo)
except Error, v:
print "will create the repo, as it's not there", v
print server.create_repository(repomount, repo, repoid, "repo")
print "not pooled!"
if (poolCount == 0):
print "no pool yet, create it"
# check if a pool exists already if not create
# pool if so add us to the pool
print "create pool fs"
print server.create_pool_filesystem(
fstype,
"%s/VirtualMachines/" % repomount,
clusterid,
poolfsuuid,
poolfsnfsbaseuuid,
mgr,
pooluuid
)
print "create pool"
print server.create_server_pool(poolalias,
pooluuid,
poolmvip,
poolCount,
hostname,
ip,
role
)
else:
print "join the pool"
print server.join_server_pool(poolalias,
pooluuid,
poolmvip,
poolCount,
hostname,
ip,
role
)
# add member to ip list ?
poolMembers.append(ip)
print "mambers for pool: %s" % poolMembers
print xserver.set_pool_member_ip_list(poolMembers)
print server.discover_server_pool()
except Error, v:
print "ERROR", v
| MissionCriticalCloud/cosmic-plugin-hypervisor-ovm3 | src/test/resources/scripts/repo_pool.py | Python | apache-2.0 | 6,325 |
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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 io.undertow.protocols.ssl;
import org.xnio.ChannelListener;
import org.xnio.ChannelListeners;
import org.xnio.Option;
import org.xnio.Options;
import io.undertow.connector.ByteBufferPool;
import org.xnio.SslClientAuthMode;
import org.xnio.StreamConnection;
import org.xnio.ssl.SslConnection;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLSession;
import java.io.IOException;
import java.net.SocketAddress;
import java.util.Set;
import java.util.concurrent.Executor;
/**
* @author Stuart Douglas
*/
class UndertowSslConnection extends SslConnection {
private static final Set<Option<?>> SUPPORTED_OPTIONS = Option.setBuilder().add(Options.SECURE, Options.SSL_CLIENT_AUTH_MODE).create();
private final StreamConnection delegate;
private final SslConduit sslConduit;
private final ChannelListener.SimpleSetter<SslConnection> handshakeSetter = new ChannelListener.SimpleSetter<>();
private final SSLEngine engine;
/**
* Construct a new instance.
*
* @param delegate the underlying connection
*/
UndertowSslConnection(StreamConnection delegate, SSLEngine engine, ByteBufferPool bufferPool, Executor delegatedTaskExecutor) {
super(delegate.getIoThread());
this.delegate = delegate;
this.engine = engine;
sslConduit = new SslConduit(this, delegate, engine, delegatedTaskExecutor, bufferPool, new HandshakeCallback());
setSourceConduit(sslConduit);
setSinkConduit(sslConduit);
}
@Override
public void startHandshake() throws IOException {
sslConduit.startHandshake();
}
@Override
public SSLSession getSslSession() {
return sslConduit.getSslSession();
}
@Override
public ChannelListener.Setter<? extends SslConnection> getHandshakeSetter() {
return handshakeSetter;
}
@Override
protected void notifyWriteClosed() {
sslConduit.notifyWriteClosed();
}
@Override
protected void notifyReadClosed() {
sslConduit.notifyReadClosed();
}
@Override
public SocketAddress getPeerAddress() {
return delegate.getPeerAddress();
}
@Override
public SocketAddress getLocalAddress() {
return delegate.getLocalAddress();
}
public SSLEngine getSSLEngine() {
return sslConduit.getSSLEngine();
}
SslConduit getSslConduit() {
return sslConduit;
}
/** {@inheritDoc} */
@Override
public <T> T setOption(final Option<T> option, final T value) throws IllegalArgumentException, IOException {
if (option == Options.SSL_CLIENT_AUTH_MODE) {
try {
return option.cast(engine.getNeedClientAuth() ? SslClientAuthMode.REQUIRED : engine.getWantClientAuth() ? SslClientAuthMode.REQUESTED : SslClientAuthMode.NOT_REQUESTED);
} finally {
engine.setWantClientAuth(false);
engine.setNeedClientAuth(false);
if (value == SslClientAuthMode.REQUESTED) {
engine.setWantClientAuth(true);
} else if (value == SslClientAuthMode.REQUIRED) {
engine.setNeedClientAuth(true);
}
}
} else if (option == Options.SECURE) {
throw new IllegalArgumentException();
} else {
return delegate.setOption(option, value);
}
}
/** {@inheritDoc} */
@Override
public <T> T getOption(final Option<T> option) throws IOException {
if (option == Options.SSL_CLIENT_AUTH_MODE) {
return option.cast(engine.getNeedClientAuth() ? SslClientAuthMode.REQUIRED : engine.getWantClientAuth() ? SslClientAuthMode.REQUESTED : SslClientAuthMode.NOT_REQUESTED);
} else {
return option == Options.SECURE ? (T)Boolean.TRUE : delegate.getOption(option);
}
}
/** {@inheritDoc} */
@Override
public boolean supportsOption(final Option<?> option) {
return SUPPORTED_OPTIONS.contains(option) || delegate.supportsOption(option);
}
@Override
protected boolean readClosed() {
return super.readClosed();
}
@Override
protected boolean writeClosed() {
return super.writeClosed();
}
protected void closeAction() {
sslConduit.close();
}
private final class HandshakeCallback implements Runnable {
@Override
public void run() {
final ChannelListener<? super SslConnection> listener = handshakeSetter.get();
if (listener == null) {
return;
}
ChannelListeners.<SslConnection>invokeChannelListener(UndertowSslConnection.this, listener);
}
}
}
| rhusar/undertow | core/src/main/java/io/undertow/protocols/ssl/UndertowSslConnection.java | Java | apache-2.0 | 5,435 |
<?php
if(!defined('IN_CB'))die('You are not allowed to access to this page.');
/**
* ean13.php
*--------------------------------------------------------------------
*
* Sub-Class - EAN-13
*
* You can provide a ISBN code (without dash), the code will transform
* it into a EAN13 format.
* EAN-13 contains
* - 2 system digits (1 not displayed but coded with parity)
* - 5 manufacturer code digits
* - 5 product digits
* - 1 checksum digit
*
*--------------------------------------------------------------------
* Revision History
* V1.00 17 jun 2004 Jean-Sebastien Goupil
*--------------------------------------------------------------------
* Copyright (C) Jean-Sebastien Goupil
* http://other.lookstrike.com/barcode/
*/
class ean13 extends BarCode {
protected $keys = array(), $code = array(), $codeParity = array();
private $text;
private $textfont;
private $book;
/**
* Constructor
*
* @param int $maxHeight
* @param FColor $color1
* @param FColor $color2
* @param int $res
* @param string $text
* @param int $textfont
* @param bool $book
*/
public function __construct($maxHeight,FColor $color1,FColor $color2,$res,$text,$textfont,$book=false) {
BarCode::__construct($maxHeight,$color1,$color2,$res);
$this->keys = array('0','1','2','3','4','5','6','7','8','9');
// Left-Hand Odd Parity starting with a space
// Left-Hand Even Parity is the inverse (0=0012) starting with a space
// Right-Hand is the same of Left-Hand starting with a bar
$this->code = array(
'2100', /* 0 */
'1110', /* 1 */
'1011', /* 2 */
'0300', /* 3 */
'0021', /* 4 */
'0120', /* 5 */
'0003', /* 6 */
'0201', /* 7 */
'0102', /* 8 */
'2001' /* 9 */
);
// Parity, 0=Odd, 1=Even for manufacturer code. Depending on 1st System Digit
$this->codeParity = array(
array(0,0,0,0,0), /* 0 */
array(0,1,0,1,1), /* 1 */
array(0,1,1,0,1), /* 2 */
array(0,1,1,1,0), /* 3 */
array(1,0,0,1,1), /* 4 */
array(1,1,0,0,1), /* 5 */
array(1,1,1,0,0), /* 6 */
array(1,0,1,0,1), /* 7 */
array(1,0,1,1,0), /* 8 */
array(1,1,0,1,0) /* 9 */
);
$this->setText($text);
$this->textfont = $textfont;
$this->book = $book;
}
/**
* Saves Text
*
* @param string $text
*/
public function setText($text){
$this->text = $text;
}
private function inverse($text,$inverse=1) {
if($inverse == 1)
$text = strrev($text);
return $text;
}
/**
* Draws the barcode
*
* @param ressource $im
*/
public function draw($im) {
$error_stop = false;
// Checking if all chars are allowed
for($i=0;$i<strlen($this->text);$i++) {
if(!is_int(array_search($this->text[$i],$this->keys))) {
$this->DrawError($im,'Char \''.$this->text[$i].'\' not allowed.');
$error_stop = true;
}
}
if($error_stop == false) {
if($this->book == true && strlen($this->text) != 10) {
$this->DrawError($im,'Must contains 10 chars if ISBN is true.');
$error_stop = true;
}
// If it's a book, we change the code to the right one
if($this->book==true && strlen($this->text)==10)
$this->text = '978'.substr($this->text,0,strlen($this->text)-1);
// Must contains 12 chars
if(strlen($this->text) != 12) {
$this->DrawError($im,'Must contains 12 chars, the 13th digit is automatically added.');
$error_stop = true;
}
if($error_stop == false) {
// Calculating Checksum
// Consider the right-most digit of the message to be in an "odd" position,
// and assign odd/even to each character moving from right to left
// Odd Position = 3, Even Position = 1
// Multiply it by the number
// Add all of that and do 10-(?mod10)
$odd = true;
$checksum=0;
for($i=strlen($this->text);$i>0;$i--) {
if($odd==true) {
$multiplier=3;
$odd=false;
}
else {
$multiplier=1;
$odd=true;
}
$checksum += $this->keys[$this->text[$i - 1]] * $multiplier;
}
$checksum = 10 - $checksum % 10;
$checksum = ($checksum == 10)?0:$checksum;
$this->text .= $this->keys[$checksum];
// If we have to write text, we move the barcode to the right to have space to put system digit
$this->positionX = ($this->textfont == 0)?0:10;
// Starting Code
$this->DrawChar($im,'000',1);
// Draw Second Code
$this->DrawChar($im,$this->findCode($this->text[1]),2);
// Draw Manufacturer Code
for($i=0;$i<5;$i++)
$this->DrawChar($im,$this->inverse($this->findCode($this->text[$i + 2]),$this->codeParity[$this->text[0]][$i]),2);
// Draw Center Guard Bar
$this->DrawChar($im,'00000',2);
// Draw Product Code
for($i=7;$i<13;$i++){
$this->DrawChar($im,$this->findCode($this->text[$i]),1);
}
// Draw Right Guard Bar
$this->DrawChar($im,'000',1);
$this->lastX = $this->positionX;
$this->lastY = $this->maxHeight;
$this->DrawText($im);
}
}
}
/**
* Overloaded method for drawing special label
*
* @param ressource $im
*/
protected function DrawText($im) {
if($this->textfont != 0) {
$bar_color = (is_null($this->color1))?NULL:$this->color1->allocate($im);
if(!is_null($bar_color)) {
$rememberX = $this->positionX;
$rememberH = $this->maxHeight;
// We increase the bars
$this->maxHeight = $this->maxHeight + 9;
$this->positionX = 10;
$this->DrawSingleBar($im,$this->color1);
$this->positionX += $this->res*2;
$this->DrawSingleBar($im,$this->color1);
// Center Guard Bar
$this->positionX += $this->res*44;
$this->DrawSingleBar($im,$this->color1);
$this->positionX += $this->res*2;
$this->DrawSingleBar($im,$this->color1);
// Last Bars
$this->positionX += $this->res*44;
$this->DrawSingleBar($im,$this->color1);
$this->positionX += $this->res*2;
$this->DrawSingleBar($im,$this->color1);
$this->positionX = $rememberX;
$this->maxHeight = $rememberH;
imagechar($im,$this->textfont,1,$this->maxHeight-(imagefontheight($this->textfont)/2),$this->text[0],$bar_color);
imagestring($im,$this->textfont,10+(3*$this->res+48*$this->res)/2-imagefontwidth($this->textfont)*(6/2),$this->maxHeight+1,substr($this->text,1,6),$bar_color);
imagestring($im,$this->textfont,10+46*$this->res+(3*$this->res+46*$this->res)/2-imagefontwidth($this->textfont)*(6/2),$this->maxHeight+1,substr($this->text,7,6),$bar_color);
}
$this->lastY = $this->maxHeight + imagefontheight($this->textfont);
}
}
};
?> | blondprod/veganet | public/barcode/class/ean13.barcode.php | PHP | apache-2.0 | 6,651 |
#!/usr/bin/env python
# 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.
# pylint: skip-file
import sys
sys.path.insert(0, "../../python/")
import mxnet as mx
kv = mx.kv.create('dist_async')
my_rank = kv.rank
nworker = kv.num_workers
def test_gluon_trainer_type():
def check_trainer_kv_update(weight_stype, update_on_kv):
x = mx.gluon.Parameter('x', shape=(10,1), lr_mult=1.0, stype=weight_stype)
x.initialize(ctx=[mx.cpu(0), mx.cpu(1)], init='zeros')
try:
trainer = mx.gluon.Trainer([x], 'sgd', {'learning_rate': 0.1},
kvstore=kv, update_on_kvstore=update_on_kv)
trainer._init_kvstore()
assert trainer._kv_initialized
assert trainer._update_on_kvstore is True
except ValueError:
assert update_on_kv is False
check_trainer_kv_update('default', False)
check_trainer_kv_update('default', True)
check_trainer_kv_update('default', None)
check_trainer_kv_update('row_sparse', False)
check_trainer_kv_update('row_sparse', True)
check_trainer_kv_update('row_sparse', None)
print('worker ' + str(my_rank) + ' passed test_gluon_trainer_type')
if __name__ == "__main__":
test_gluon_trainer_type()
| szha/mxnet | tests/nightly/dist_async_kvstore.py | Python | apache-2.0 | 1,994 |
/*
* Copyright 2015 JBoss, by Red Hat, 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 org.uberfire.ext.wires.bpmn.client.commands.impl;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;
import org.uberfire.commons.validation.PortablePreconditions;
import org.uberfire.ext.wires.bpmn.client.commands.Command;
import org.uberfire.ext.wires.bpmn.client.commands.ResultType;
import org.uberfire.ext.wires.bpmn.client.commands.Results;
import org.uberfire.ext.wires.bpmn.client.rules.RuleManager;
/**
* A batch of Commands to be executed as an atomic unit
*/
public class BatchCommand implements Command {
private List<Command> commands;
public BatchCommand( final List<Command> commands ) {
this.commands = PortablePreconditions.checkNotNull( "commands",
commands );
}
public BatchCommand( final Command... commands ) {
this.commands = Arrays.asList( PortablePreconditions.checkNotNull( "commands",
commands ) );
}
@Override
public Results apply( final RuleManager ruleManager ) {
final Results results = new DefaultResultsImpl();
final Stack<Command> appliedCommands = new Stack<Command>();
for ( Command command : commands ) {
results.getMessages().addAll( command.apply( ruleManager ).getMessages() );
if ( results.contains( ResultType.ERROR ) ) {
for ( Command undo : appliedCommands ) {
undo.undo( ruleManager );
}
return results;
} else {
appliedCommands.add( command );
}
}
return results;
}
@Override
public Results undo( final RuleManager ruleManager ) {
final Results results = new DefaultResultsImpl();
final Stack<Command> appliedCommands = new Stack<Command>();
for ( Command command : commands ) {
results.getMessages().addAll( command.undo( ruleManager ).getMessages() );
if ( results.contains( ResultType.ERROR ) ) {
for ( Command cmd : appliedCommands ) {
cmd.apply( ruleManager );
}
return results;
} else {
appliedCommands.add( command );
}
}
return results;
}
}
| dgutierr/uberfire-extensions | uberfire-wires/uberfire-wires-bpmn/uberfire-wires-bpmn-client/src/main/java/org/uberfire/ext/wires/bpmn/client/commands/impl/BatchCommand.java | Java | apache-2.0 | 2,980 |
/*
* Copyright 2010 Henry Coles
*
* 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.pitest.mutationtest;
public class MutableIncrement {
public static int increment() {
int i = 42;
i++;
return i;
}
}
| jacksonpradolima/pitest | pitest/src/test/java/org/pitest/mutationtest/MutableIncrement.java | Java | apache-2.0 | 735 |
// Copyright 2016 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.android.desugar.testdata;
import com.google.common.collect.ImmutableList;
import java.util.List;
import java.util.stream.Collectors;
public interface InterfaceWithLambda {
String ZERO = String.valueOf(0);
List<String> DIGITS =
ImmutableList.of(0, 1)
.stream()
.map(i -> i == 0 ? ZERO : String.valueOf(i))
.collect(Collectors.toList());
}
| aehlig/bazel | src/test/java/com/google/devtools/build/android/desugar/testdata/InterfaceWithLambda.java | Java | apache-2.0 | 1,029 |
/* Copyright 2016 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.
==============================================================================*/
#include "tensorflow/core/kernels/cwise_ops_common.h"
namespace tensorflow {
REGISTER5(UnaryOp, CPU, "Round", functor::round, Eigen::half, float, double,
int32, int64_t);
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
#if !defined(MLIR_GENERATED_GPU_KERNELS_ENABLED)
REGISTER5(UnaryOp, GPU, "Round", functor::round, Eigen::half, float, double,
int32, int64);
#endif
#endif
} // namespace tensorflow
| frreiss/tensorflow-fred | tensorflow/core/kernels/cwise_op_round.cc | C++ | apache-2.0 | 1,086 |
# Copyright 2007 Google, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.
"""Abstract Base Classes (ABCs) for collections, according to PEP 3119.
DON'T USE THIS MODULE DIRECTLY! The classes here should be imported
via collections; they are defined here only to alleviate certain
bootstrapping issues. Unit tests are in test_collections.
"""
from abc import ABCMeta, abstractmethod
import sys
__all__ = ["Hashable", "Iterable", "Iterator",
"Sized", "Container", "Callable",
"Set", "MutableSet",
"Mapping", "MutableMapping",
"MappingView", "KeysView", "ItemsView", "ValuesView",
"Sequence", "MutableSequence",
]
### ONE-TRICK PONIES ###
class Hashable:
__metaclass__ = ABCMeta
@abstractmethod
def __hash__(self):
return 0
@classmethod
def __subclasshook__(cls, C):
if cls is Hashable:
for B in C.__mro__:
if "__hash__" in B.__dict__:
if B.__dict__["__hash__"]:
return True
break
return NotImplemented
class Iterable:
__metaclass__ = ABCMeta
@abstractmethod
def __iter__(self):
while False:
yield None
@classmethod
def __subclasshook__(cls, C):
if cls is Iterable:
if any("__iter__" in B.__dict__ for B in C.__mro__):
return True
return NotImplemented
Iterable.register(str)
class Iterator(Iterable):
@abstractmethod
def __next__(self):
raise StopIteration
def __iter__(self):
return self
@classmethod
def __subclasshook__(cls, C):
if cls is Iterator:
if any("next" in B.__dict__ for B in C.__mro__):
return True
return NotImplemented
class Sized:
__metaclass__ = ABCMeta
@abstractmethod
def __len__(self):
return 0
@classmethod
def __subclasshook__(cls, C):
if cls is Sized:
if any("__len__" in B.__dict__ for B in C.__mro__):
return True
return NotImplemented
class Container:
__metaclass__ = ABCMeta
@abstractmethod
def __contains__(self, x):
return False
@classmethod
def __subclasshook__(cls, C):
if cls is Container:
if any("__contains__" in B.__dict__ for B in C.__mro__):
return True
return NotImplemented
class Callable:
__metaclass__ = ABCMeta
@abstractmethod
def __call__(self, *args, **kwds):
return False
@classmethod
def __subclasshook__(cls, C):
if cls is Callable:
if any("__call__" in B.__dict__ for B in C.__mro__):
return True
return NotImplemented
### SETS ###
class Set(Sized, Iterable, Container):
"""A set is a finite, iterable container.
This class provides concrete generic implementations of all
methods except for __contains__, __iter__ and __len__.
To override the comparisons (presumably for speed, as the
semantics are fixed), all you have to do is redefine __le__ and
then the other operations will automatically follow suit.
"""
def __le__(self, other):
if not isinstance(other, Set):
return NotImplemented
if len(self) > len(other):
return False
for elem in self:
if elem not in other:
return False
return True
def __lt__(self, other):
if not isinstance(other, Set):
return NotImplemented
return len(self) < len(other) and self.__le__(other)
def __gt__(self, other):
if not isinstance(other, Set):
return NotImplemented
return other < self
def __ge__(self, other):
if not isinstance(other, Set):
return NotImplemented
return other <= self
def __eq__(self, other):
if not isinstance(other, Set):
return NotImplemented
return len(self) == len(other) and self.__le__(other)
def __ne__(self, other):
return not (self == other)
@classmethod
def _from_iterable(cls, it):
'''Construct an instance of the class from any iterable input.
Must override this method if the class constructor signature
does not accept an iterable for an input.
'''
return cls(it)
def __and__(self, other):
if not isinstance(other, Iterable):
return NotImplemented
return self._from_iterable(value for value in other if value in self)
def isdisjoint(self, other):
for value in other:
if value in self:
return False
return True
def __or__(self, other):
if not isinstance(other, Iterable):
return NotImplemented
chain = (e for s in (self, other) for e in s)
return self._from_iterable(chain)
def __sub__(self, other):
if not isinstance(other, Set):
if not isinstance(other, Iterable):
return NotImplemented
other = self._from_iterable(other)
return self._from_iterable(value for value in self
if value not in other)
def __xor__(self, other):
if not isinstance(other, Set):
if not isinstance(other, Iterable):
return NotImplemented
other = self._from_iterable(other)
return (self - other) | (other - self)
# Sets are not hashable by default, but subclasses can change this
__hash__ = None
def _hash(self):
"""Compute the hash value of a set.
Note that we don't define __hash__: not all sets are hashable.
But if you define a hashable set type, its __hash__ should
call this function.
This must be compatible __eq__.
All sets ought to compare equal if they contain the same
elements, regardless of how they are implemented, and
regardless of the order of the elements; so there's not much
freedom for __eq__ or __hash__. We match the algorithm used
by the built-in frozenset type.
"""
MAX = sys.maxint
MASK = 2 * MAX + 1
n = len(self)
h = 1927868237 * (n + 1)
h &= MASK
for x in self:
hx = hash(x)
h ^= (hx ^ (hx << 16) ^ 89869747) * 3644798167
h &= MASK
h = h * 69069 + 907133923
h &= MASK
if h > MAX:
h -= MASK + 1
if h == -1:
h = 590923713
return h
Set.register(frozenset)
class MutableSet(Set):
@abstractmethod
def add(self, value):
"""Return True if it was added, False if already there."""
raise NotImplementedError
@abstractmethod
def discard(self, value):
"""Return True if it was deleted, False if not there."""
raise NotImplementedError
def remove(self, value):
"""Remove an element. If not a member, raise a KeyError."""
if value not in self:
raise KeyError(value)
self.discard(value)
def pop(self):
"""Return the popped value. Raise KeyError if empty."""
it = iter(self)
try:
value = it.__next__()
except StopIteration:
raise KeyError
self.discard(value)
return value
def clear(self):
"""This is slow (creates N new iterators!) but effective."""
try:
while True:
self.pop()
except KeyError:
pass
def __ior__(self, it):
for value in it:
self.add(value)
return self
def __iand__(self, c):
for value in self:
if value not in c:
self.discard(value)
return self
def __ixor__(self, it):
if not isinstance(it, Set):
it = self._from_iterable(it)
for value in it:
if value in self:
self.discard(value)
else:
self.add(value)
return self
def __isub__(self, it):
for value in it:
self.discard(value)
return self
MutableSet.register(set)
### MAPPINGS ###
class Mapping(Sized, Iterable, Container):
@abstractmethod
def __getitem__(self, key):
raise KeyError
def get(self, key, default=None):
try:
return self[key]
except KeyError:
return default
def __contains__(self, key):
try:
self[key]
except KeyError:
return False
else:
return True
def iterkeys(self):
return iter(self)
def itervalues(self):
for key in self:
yield self[key]
def iteritems(self):
for key in self:
yield (key, self[key])
def keys(self):
return list(self)
def items(self):
return [(key, self[key]) for key in self]
def values(self):
return [self[key] for key in self]
# Mappings are not hashable by default, but subclasses can change this
__hash__ = None
def __eq__(self, other):
return isinstance(other, Mapping) and \
dict(self.items()) == dict(other.items())
def __ne__(self, other):
return not (self == other)
class MappingView(Sized):
def __init__(self, mapping):
self._mapping = mapping
def __len__(self):
return len(self._mapping)
class KeysView(MappingView, Set):
def __contains__(self, key):
return key in self._mapping
def __iter__(self):
for key in self._mapping:
yield key
class ItemsView(MappingView, Set):
def __contains__(self, item):
key, value = item
try:
v = self._mapping[key]
except KeyError:
return False
else:
return v == value
def __iter__(self):
for key in self._mapping:
yield (key, self._mapping[key])
class ValuesView(MappingView):
def __contains__(self, value):
for key in self._mapping:
if value == self._mapping[key]:
return True
return False
def __iter__(self):
for key in self._mapping:
yield self._mapping[key]
class MutableMapping(Mapping):
@abstractmethod
def __setitem__(self, key, value):
raise KeyError
@abstractmethod
def __delitem__(self, key):
raise KeyError
__marker = object()
def pop(self, key, default=__marker):
try:
value = self[key]
except KeyError:
if default is self.__marker:
raise
return default
else:
del self[key]
return value
def popitem(self):
try:
key = next(iter(self))
except StopIteration:
raise KeyError
value = self[key]
del self[key]
return key, value
def clear(self):
try:
while True:
self.popitem()
except KeyError:
pass
def update(self, other=(), **kwds):
if isinstance(other, Mapping):
for key in other:
self[key] = other[key]
elif hasattr(other, "keys"):
for key in other.keys():
self[key] = other[key]
else:
for key, value in other:
self[key] = value
for key, value in kwds.items():
self[key] = value
def setdefault(self, key, default=None):
try:
return self[key]
except KeyError:
self[key] = default
return default
MutableMapping.register(dict)
### SEQUENCES ###
class Sequence(Sized, Iterable, Container):
"""All the operations on a read-only sequence.
Concrete subclasses must override __new__ or __init__,
__getitem__, and __len__.
"""
@abstractmethod
def __getitem__(self, index):
raise IndexError
def __iter__(self):
i = 0
try:
while True:
v = self[i]
yield v
i += 1
except IndexError:
return
def __contains__(self, value):
for v in self:
if v == value:
return True
return False
def __reversed__(self):
for i in reversed(range(len(self))):
yield self[i]
def index(self, value):
for i, v in enumerate(self):
if v == value:
return i
raise ValueError
def count(self, value):
return sum(1 for v in self if v == value)
Sequence.register(tuple)
Sequence.register(basestring)
Sequence.register(buffer)
class MutableSequence(Sequence):
@abstractmethod
def __setitem__(self, index, value):
raise IndexError
@abstractmethod
def __delitem__(self, index):
raise IndexError
@abstractmethod
def insert(self, index, value):
raise IndexError
def append(self, value):
self.insert(len(self), value)
def reverse(self):
n = len(self)
for i in range(n//2):
self[i], self[n-i-1] = self[n-i-1], self[i]
def extend(self, values):
for v in values:
self.append(v)
def pop(self, index=-1):
v = self[index]
del self[index]
return v
def remove(self, value):
del self[self.index(value)]
def __iadd__(self, values):
self.extend(values)
MutableSequence.register(list)
| tempbottle/restcommander | play-1.2.4/python/Lib/_abcoll.py | Python | apache-2.0 | 13,666 |
/*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.wire;
/**
* Class to represent {@link FileSystemCommand} options.
*/
public final class FileSystemCommandOptions {
private PersistCommandOptions mPersistCommandOptions;
/**
* Creates a new instance of {@link FileSystemCommandOptions}.
*/
public FileSystemCommandOptions() {}
/**
* @return the persist options
*/
public PersistCommandOptions getPersistOptions() {
return mPersistCommandOptions;
}
/**
* Set the persist options.
*
* @param persistCommandOptions the persist options
*/
public void setPersistOptions(PersistCommandOptions persistCommandOptions) {
mPersistCommandOptions = persistCommandOptions;
}
}
| wwjiang007/alluxio | core/common/src/main/java/alluxio/wire/FileSystemCommandOptions.java | Java | apache-2.0 | 1,198 |
/*
* Copyright 2015-present Facebook, 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.facebook.buck.cxx;
import com.facebook.buck.rules.Tool;
import com.google.common.collect.ImmutableList;
import java.util.Optional;
public class ClangCompiler extends DefaultCompiler {
public ClangCompiler(Tool tool) {
super(tool);
}
@Override
public Optional<ImmutableList<String>> debugCompilationDirFlags(String debugCompilationDir) {
return Optional.of(
ImmutableList.of("-Xclang", "-fdebug-compilation-dir", "-Xclang", debugCompilationDir));
}
@Override
public Optional<ImmutableList<String>> getFlagsForColorDiagnostics() {
return Optional.of(ImmutableList.of("-fcolor-diagnostics"));
}
@Override
public boolean isArgFileSupported() {
return true;
}
}
| sdwilsh/buck | src/com/facebook/buck/cxx/ClangCompiler.java | Java | apache-2.0 | 1,330 |
/*
Copyright 2013-2014, JUMA Technology
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.bcsphere.bluetooth;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.util.Log;
import org.bcsphere.bluetooth.tools.BluetoothDetection;
import org.bcsphere.bluetooth.tools.Tools;
public class BCBluetooth extends CordovaPlugin {
public Context myContext = null;
private SharedPreferences sp;
private boolean isSetContext = true;
private IBluetooth bluetoothAPI = null;
private String versionOfAPI;
private CallbackContext newadvpacketContext;
private CallbackContext disconnectContext;
private BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
private static final String TAG = "BCBluetooth";
//classical interface relative data structure
public HashMap<String, BluetoothSerialService> classicalServices = new HashMap<String, BluetoothSerialService>();
//when the accept services construct a connection , the service will remove from this map & append into classicalServices map for read/write interface call
public HashMap<String, BluetoothSerialService> acceptServices = new HashMap<String, BluetoothSerialService>();
public BCBluetooth() {
}
@Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
myContext = this.webView.getContext();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
myContext.registerReceiver(receiver, intentFilter);
sp = myContext.getSharedPreferences("VERSION_OF_API", 1);
BluetoothDetection.detectionBluetoothAPI(myContext);
try {
if ((versionOfAPI = sp.getString("API", "no_google"))
.equals("google")) {
bluetoothAPI = (IBluetooth) Class.forName(
"org.bcsphere.bluetooth.BluetoothG43plus")
.newInstance();
} else if ((versionOfAPI = sp.getString("API", "no_samsung"))
.equals("samsung")) {
bluetoothAPI = (IBluetooth) Class.forName(
"org.bcsphere.bluetooth.BluetoothSam42").newInstance();
} else if ((versionOfAPI = sp.getString("API", "no_htc"))
.equals("htc")) {
bluetoothAPI = (IBluetooth) Class.forName(
"org.bcsphere.bluetooth.BluetoothHTC41").newInstance();
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public boolean execute(final String action, final JSONArray json,
final CallbackContext callbackContext) throws JSONException {
try {
if(bluetoothAPI != null){
if (isSetContext) {
bluetoothAPI.setContext(myContext);
isSetContext = false;
}
if (action.equals("getCharacteristics")) {
bluetoothAPI.getCharacteristics(json, callbackContext);
} else if (action.equals("getDescriptors")) {
bluetoothAPI.getDescriptors(json, callbackContext);
} else if (action.equals("removeServices")) {
bluetoothAPI.removeServices(json, callbackContext);
}
if (action.equals("stopScan")) {
bluetoothAPI.stopScan(json, callbackContext);
} else if (action.equals("getConnectedDevices")) {
bluetoothAPI.getConnectedDevices(json, callbackContext);
}
cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
if (action.equals("startScan")) {
bluetoothAPI.startScan(json, callbackContext);
} else if (action.equals("connect")) {
bluetoothAPI.connect(json, callbackContext);
} else if (action.equals("disconnect")) {
bluetoothAPI.disconnect(json, callbackContext);
} else if (action.equals("getServices")) {
bluetoothAPI.getServices(json, callbackContext);
} else if (action.equals("writeValue")) {
bluetoothAPI.writeValue(json, callbackContext);
} else if (action.equals("readValue")) {
bluetoothAPI.readValue(json, callbackContext);
} else if (action.equals("setNotification")) {
bluetoothAPI.setNotification(json, callbackContext);
} else if (action.equals("getDeviceAllData")) {
bluetoothAPI.getDeviceAllData(json, callbackContext);
} else if (action.equals("addServices")) {
bluetoothAPI.addServices(json, callbackContext);
} else if (action.equals("getRSSI")) {
bluetoothAPI.getRSSI(json, callbackContext);
}
}
});
}
if (action.equals("addEventListener")) {
String eventName = Tools.getData(json, Tools.EVENT_NAME);
if (eventName.equals("newadvpacket") ) {
newadvpacketContext = callbackContext;
}else if(eventName.equals("disconnect")){
disconnectContext = callbackContext;
}
if(bluetoothAPI != null){
bluetoothAPI.addEventListener(json, callbackContext);
}
return true;
}
if (action.equals("getEnvironment")) {
JSONObject jo = new JSONObject();
Tools.addProperty(jo, "appID", "com.test.yourappid");
Tools.addProperty(jo, "deviceAddress", "N/A");
Tools.addProperty(jo, "api", versionOfAPI);
callbackContext.success(jo);
return true;
}
if (action.equals("openBluetooth")) {
if(!bluetoothAdapter.isEnabled()){
bluetoothAdapter.enable();
}
Tools.sendSuccessMsg(callbackContext);
return true;
}
if (action.equals("closeBluetooth")) {
if(bluetoothAdapter.isEnabled()){
bluetoothAdapter.disable();
}
Tools.sendSuccessMsg(callbackContext);
return true;
}
if (action.equals("getBluetoothState")) {
Log.i(TAG, "getBluetoothState");
JSONObject obj = new JSONObject();
if (bluetoothAdapter.isEnabled()) {
Tools.addProperty(obj, Tools.BLUETOOTH_STATE, Tools.IS_TRUE);
callbackContext.success(obj);
}else {
Tools.addProperty(obj, Tools.BLUETOOTH_STATE, Tools.IS_FALSE);
callbackContext.success(obj);
}
return true;
}
if(action.equals("startClassicalScan")){
Log.i(TAG,"startClassicalScan");
if(bluetoothAdapter.isEnabled()){
if(bluetoothAdapter.startDiscovery()){
callbackContext.success();
}else{
callbackContext.error("start classical scan error!");
}
}else{
callbackContext.error("your bluetooth is not open!");
}
}
if(action.equals("stopClassicalScan")){
Log.i(TAG,"stopClassicalScan");
if(bluetoothAdapter.isEnabled()){
if(bluetoothAdapter.cancelDiscovery()){
callbackContext.success();
}else{
callbackContext.error("stop classical scan error!");
}
}else{
callbackContext.error("your bluetooth is not open!");
}
}
if(action.equals("rfcommConnect")){
String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS);
String securestr = Tools.getData(json, Tools.SECURE);
String uuidstr = Tools.getData(json, Tools.UUID);
boolean secure = false;
if(securestr != null && securestr.equals("true")){
secure = true;
}
Log.i(TAG,"connect to "+deviceAddress);
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
BluetoothSerialService classicalService = classicalServices.get(deviceAddress);
if(device != null && classicalService == null){
classicalService = new BluetoothSerialService();
classicalService.disconnectCallback = disconnectContext;
classicalServices.put(deviceAddress, classicalService);
}
if (device != null) {
classicalService.connectCallback = callbackContext;
classicalService.connect(device,uuidstr,secure);
} else {
callbackContext.error("Could not connect to " + deviceAddress);
}
}
if (action.equals("rfcommDisconnect")) {
String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS);
BluetoothSerialService service = classicalServices.get(deviceAddress);
if(service != null){
service.connectCallback = null;
service.stop();
classicalServices.remove(deviceAddress);
callbackContext.success();
}else{
callbackContext.error("Could not disconnect to " + deviceAddress);
}
}
if(action.equals("rfcommListen")){
String name = Tools.getData(json, Tools.NAME);
String uuidstr = Tools.getData(json, Tools.UUID);
String securestr = Tools.getData(json, Tools.SECURE);
boolean secure = false;
if(securestr.equals("true")){
secure = true;
}
BluetoothSerialService service = new BluetoothSerialService();
service.listen(name, uuidstr, secure, this);
acceptServices.put(name+uuidstr, service);
}
if(action.equals("rfcommUnListen")){
String name = Tools.getData(json, Tools.NAME);
String uuidstr = Tools.getData(json, Tools.UUID);
BluetoothSerialService service = acceptServices.get(name+uuidstr);
if(service != null){
service.stop();
}
}
if(action.equals("rfcommWrite")){
String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS);
BluetoothSerialService service = classicalServices.get(deviceAddress);
if(service != null){
String data = Tools.getData(json, Tools.WRITE_VALUE);
service.write(Tools.decodeBase64(data));
callbackContext.success();
}else{
callbackContext.error("there is no connection on device:" + deviceAddress);
}
}
if(action.equals("rfcommRead")){
String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS);
BluetoothSerialService service = classicalServices.get(deviceAddress);
if(service != null){
byte[] data = new byte[2048];
byte[] predata = service.buffer.array();
for(int i = 0;i < service.bufferSize;i++){
data[i] = predata[i];
}
JSONObject obj = new JSONObject();
//Tools.addProperty(obj, Tools.DEVICE_ADDRESS, deviceAddress);
Tools.addProperty(obj, Tools.VALUE, Tools.encodeBase64(data));
Tools.addProperty(obj, Tools.DATE, Tools.getDateString());
callbackContext.success(obj);
service.bufferSize = 0;
service.buffer.clear();
}else{
callbackContext.error("there is no connection on device:" + deviceAddress);
}
}
if(action.equals("rfcommSubscribe")){
String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS);
BluetoothSerialService service = classicalServices.get(deviceAddress);
if(service != null){
service.dataAvailableCallback = callbackContext;
}else{
callbackContext.error("there is no connection on device:" + deviceAddress);
}
}
if (action.equals("rfcommUnsubscribe")) {
String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS);
BluetoothSerialService service = classicalServices.get(deviceAddress);
if(service != null){
service.dataAvailableCallback = null;
}else{
callbackContext.error("there is no connection on device:" + deviceAddress);
}
}
if (action.equals("getPairedDevices")) {
try {
Log.i(TAG, "getPairedDevices");
JSONArray ary = new JSONArray();
Set<BluetoothDevice> devices = bluetoothAdapter.getBondedDevices();
Iterator<BluetoothDevice> it = devices.iterator();
while (it.hasNext()) {
BluetoothDevice device = (BluetoothDevice) it.next();
JSONObject obj = new JSONObject();
Tools.addProperty(obj, Tools.DEVICE_ADDRESS, device.getAddress());
Tools.addProperty(obj, Tools.DEVICE_NAME, device.getName());
ary.put(obj);
}
callbackContext.success(ary);
} catch (Exception e) {
Tools.sendErrorMsg(callbackContext);
} catch (java.lang.Error e) {
Tools.sendErrorMsg(callbackContext);
}
} else if (action.equals("createPair")) {
Log.i(TAG, "createPair");
String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS);
JSONObject obj = new JSONObject();
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
if (Tools.creatBond(device.getClass(), device)) {
Tools.addProperty(obj, Tools.DEVICE_ADDRESS, device.getAddress());
callbackContext.success(obj);
}else {
Tools.addProperty(obj, Tools.DEVICE_ADDRESS, device.getAddress());
callbackContext.error(obj);
}
} else if (action.equals("removePair")) {
Log.i(TAG, "removePair");
String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS);
JSONObject obj = new JSONObject();
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
if (Tools.removeBond(device.getClass(), device)) {
Tools.addProperty(obj, Tools.DEVICE_ADDRESS, device.getAddress());
callbackContext.success(obj);
}else {
Tools.addProperty(obj, Tools.DEVICE_ADDRESS, device.getAddress());
callbackContext.error(obj);
}
}
} catch (Exception e) {
Tools.sendErrorMsg(callbackContext);
} catch(Error e){
Tools.sendErrorMsg(callbackContext);
}
return true;
}
public BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getIntExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, -1) == 11) {
JSONObject joOpen = new JSONObject();
try {
joOpen.put("state", "open");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
webView.sendJavascript("cordova.fireDocumentEvent('bluetoothopen')");
} else if (intent.getIntExtra(
BluetoothAdapter.EXTRA_PREVIOUS_STATE, -1) == 13) {
JSONObject joClose = new JSONObject();
try {
joClose.put("state", "close");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
webView.sendJavascript("cordova.fireDocumentEvent('bluetoothclose')");
}else if(BluetoothDevice.ACTION_FOUND.equals(intent.getAction())) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
System.out.println("new classical bluetooth device found!"+device.getAddress());
// Add the name and address to an array adapter to show in a ListView
JSONObject obj = new JSONObject();
Tools.addProperty(obj, Tools.DEVICE_ADDRESS, device.getAddress());
Tools.addProperty(obj, Tools.DEVICE_NAME, device.getName());
Tools.addProperty(obj, Tools.IS_CONNECTED, Tools.IS_FALSE);
Tools.addProperty(obj, Tools.TYPE, "Classical");
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK , obj);
pluginResult.setKeepCallback(true);
newadvpacketContext.sendPluginResult(pluginResult);
}
}
};
}
| bcsphere/bcexplorer | plugins/org/src/android/org/bcsphere/bluetooth/BCBluetooth.java | Java | apache-2.0 | 15,604 |
class AddSolutionToLevels < ActiveRecord::Migration
def change
add_column :levels, :solution_level_source_id, :integer
end
end
| giroto/teste | db/migrate/20140205192227_add_solution_to_levels.rb | Ruby | apache-2.0 | 135 |
#!/usr/bin/env python
# example setselection.py
import pygtk
pygtk.require('2.0')
import gtk
import time
class SetSelectionExample:
# Callback when the user toggles the selection
def selection_toggled(self, widget, window):
if widget.get_active():
self.have_selection = window.selection_owner_set("PRIMARY")
# if claiming the selection failed, we return the button to
# the out state
if not self.have_selection:
widget.set_active(False)
else:
if self.have_selection:
# Not possible to release the selection in PyGTK
# just mark that we don't have it
self.have_selection = False
return
# Called when another application claims the selection
def selection_clear(self, widget, event):
self.have_selection = False
widget.set_active(False)
return True
# Supplies the current time as the selection.
def selection_handle(self, widget, selection_data, info, time_stamp):
current_time = time.time()
timestr = time.asctime(time.localtime(current_time))
# When we return a single string, it should not be null terminated.
# That will be done for us
selection_data.set_text(timestr, len(timestr))
return
def __init__(self):
self.have_selection = False
# Create the toplevel window
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.set_title("Set Selection")
window.set_border_width(10)
window.connect("destroy", lambda w: gtk.main_quit())
self.window = window
# Create an eventbox to hold the button since it no longer has
# a GdkWindow
eventbox = gtk.EventBox()
eventbox.show()
window.add(eventbox)
# Create a toggle button to act as the selection
selection_button = gtk.ToggleButton("Claim Selection")
eventbox.add(selection_button)
selection_button.connect("toggled", self.selection_toggled, eventbox)
eventbox.connect_object("selection_clear_event", self.selection_clear,
selection_button)
eventbox.selection_add_target("PRIMARY", "STRING", 1)
eventbox.selection_add_target("PRIMARY", "COMPOUND_TEXT", 1)
eventbox.connect("selection_get", self.selection_handle)
selection_button.show()
window.show()
def main():
gtk.main()
return 0
if __name__ == "__main__":
SetSelectionExample()
main()
| certik/pyjamas | pygtkweb/demos/065-setselection.py | Python | apache-2.0 | 2,570 |
/*
* Copyright 2005 JBoss 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 org.drools.modelcompiler;
import java.util.ArrayList;
import java.util.List;
import org.assertj.core.api.Assertions;
import org.drools.modelcompiler.domain.Address;
import org.drools.modelcompiler.domain.Employee;
import org.drools.modelcompiler.domain.Person;
import org.junit.Test;
import org.kie.api.builder.Results;
import org.kie.api.runtime.KieSession;
import static org.drools.modelcompiler.domain.Employee.createEmployee;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class OrTest extends BaseModelTest {
public OrTest( RUN_TYPE testRunType ) {
super( testRunType );
}
@Test
public void testOr() {
String str =
"import " + Person.class.getCanonicalName() + ";" +
"rule R when\n" +
" $p : Person(name == \"Mark\") or\n" +
" ( $mark : Person(name == \"Mark\")\n" +
" and\n" +
" $p : Person(age > $mark.age) )\n" +
" $s: String(this == $p.name)\n" +
"then\n" +
" System.out.println(\"Found: \" + $s);\n" +
"end";
KieSession ksession = getKieSession( str );
ksession.insert( "Mario" );
ksession.insert( new Person( "Mark", 37 ) );
ksession.insert( new Person( "Edson", 35 ) );
ksession.insert( new Person( "Mario", 40 ) );
assertEquals(1, ksession.fireAllRules());
}
@Test
public void testOrWhenStringFirst() {
String str =
"import " + Person.class.getCanonicalName() + ";" +
"import " + Address.class.getCanonicalName() + ";" +
"rule R when\n" +
" $s : String(this == \"Go\")\n" +
" ( Person(name == \"Mark\") or \n" +
" (\n" +
" Person(name == \"Mario\") and\n" +
" Address(city == \"London\") ) )\n" +
"then\n" +
" System.out.println(\"Found: \" + $s.getClass());\n" +
"end";
KieSession ksession = getKieSession( str );
ksession.insert( "Go" );
ksession.insert( new Person( "Mark", 37 ) );
ksession.insert( new Person( "Mario", 100 ) );
ksession.insert( new Address( "London" ) );
assertEquals(2, ksession.fireAllRules());
}
@Test
public void testOrWithBetaIndex() {
String str =
"import " + Person.class.getCanonicalName() + ";" +
"rule R when\n" +
" $p : Person(name == \"Mark\") or\n" +
" ( $mark : Person(name == \"Mark\")\n" +
" and\n" +
" $p : Person(age == $mark.age) )\n" +
" $s: String(this == $p.name)\n" +
"then\n" +
" System.out.println(\"Found: \" + $s);\n" +
"end";
KieSession ksession = getKieSession(str);
ksession.insert("Mario");
ksession.insert(new Person("Mark", 37));
ksession.insert(new Person("Edson", 35));
ksession.insert(new Person("Mario", 37));
assertEquals(1, ksession.fireAllRules());
}
@Test
public void testOrWithBetaIndexOffset() {
String str =
"import " + Person.class.getCanonicalName() + ";" +
"rule R when\n" +
" $e : Person(name == \"Edson\")\n" +
" $p : Person(name == \"Mark\") or\n" +
" ( $mark : Person(name == \"Mark\")\n" +
" and\n" +
" $p : Person(age == $mark.age) )\n" +
" $s: String(this == $p.name)\n" +
"then\n" +
" System.out.println(\"Found: \" + $s);\n" +
"end";
KieSession ksession = getKieSession(str);
ksession.insert("Mario");
ksession.insert(new Person("Mark", 37));
ksession.insert(new Person("Edson", 35));
ksession.insert(new Person("Mario", 37));
assertEquals(1, ksession.fireAllRules());
}
@Test
public void testOrConditional() {
final String drl =
"import " + Employee.class.getCanonicalName() + ";" +
"import " + Address.class.getCanonicalName() + ";" +
"global java.util.List list\n" +
"\n" +
"rule R when\n" +
" Employee( $address: address, address.city == 'Big City' )\n" +
" or " +
" Employee( $address: address, address.city == 'Small City' )\n" +
"then\n" +
" list.add( $address.getCity() );\n" +
"end\n";
KieSession kieSession = getKieSession(drl);
List<String> results = new ArrayList<>();
kieSession.setGlobal("list", results);
final Employee bruno = createEmployee("Bruno", new Address("Elm", 10, "Small City"));
kieSession.insert(bruno);
final Employee alice = createEmployee("Alice", new Address("Elm", 10, "Big City"));
kieSession.insert(alice);
kieSession.fireAllRules();
Assertions.assertThat(results).containsExactlyInAnyOrder("Big City", "Small City");
}
@Test
public void testOrConstraint() {
final String drl =
"import " + Employee.class.getCanonicalName() + ";" +
"import " + Address.class.getCanonicalName() + ";" +
"global java.util.List list\n" +
"\n" +
"rule R when\n" +
" Employee( $address: address, ( address.city == 'Big City' || address.city == 'Small City' ) )\n" +
"then\n" +
" list.add( $address.getCity() );\n" +
"end\n";
KieSession kieSession = getKieSession(drl);
List<String> results = new ArrayList<>();
kieSession.setGlobal("list", results);
final Employee bruno = createEmployee("Bruno", new Address("Elm", 10, "Small City"));
kieSession.insert(bruno);
final Employee alice = createEmployee("Alice", new Address("Elm", 10, "Big City"));
kieSession.insert(alice);
kieSession.fireAllRules();
Assertions.assertThat(results).containsExactlyInAnyOrder("Big City", "Small City");
}
@Test
public void testOrWithDuplicatedVariables() {
String str =
"import " + Person.class.getCanonicalName() + ";" +
"global java.util.List list\n" +
"\n" +
"rule R1 when\n" +
" Person( $name: name == \"Mark\", $age: age ) or\n" +
" Person( $name: name == \"Mario\", $age : age )\n" +
"then\n" +
" list.add( $name + \" is \" + $age);\n" +
"end\n" +
"rule R2 when\n" +
" $p: Person( name == \"Mark\", $age: age ) or\n" +
" $p: Person( name == \"Mario\", $age : age )\n" +
"then\n" +
" list.add( $p + \" has \" + $age + \" years\");\n" +
"end\n";
KieSession ksession = getKieSession( str );
List<String> results = new ArrayList<>();
ksession.setGlobal("list", results);
ksession.insert( new Person( "Mark", 37 ) );
ksession.insert( new Person( "Edson", 35 ) );
ksession.insert( new Person( "Mario", 40 ) );
ksession.fireAllRules();
assertEquals(4, results.size());
assertTrue(results.contains("Mark is 37"));
assertTrue(results.contains("Mark has 37 years"));
assertTrue(results.contains("Mario is 40"));
assertTrue(results.contains("Mario has 40 years"));
}
@Test
public void generateErrorForEveryFieldInRHSNotDefinedInLHS() {
// JBRULES-3390
final String drl1 = "package org.drools.compiler.integrationtests.operators; \n" +
"declare B\n" +
" field : int\n" +
"end\n" +
"declare C\n" +
" field : int\n" +
"end\n" +
"rule R when\n" +
"( " +
" ( B( $bField : field ) or C( $cField : field ) ) " +
")\n" +
"then\n" +
" System.out.println($bField);\n" +
"end\n";
Results results = getCompilationResults(drl1);
assertFalse(results.getMessages().isEmpty());
}
private Results getCompilationResults( String drl ) {
return createKieBuilder( drl ).getResults();
}
}
| jomarko/drools | drools-model/drools-model-compiler/src/test/java/org/drools/modelcompiler/OrTest.java | Java | apache-2.0 | 9,484 |
/*
* Copyright 2000-2013 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 org.jetbrains.idea.maven.importing;
import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.roots.*;
import com.intellij.openapi.roots.libraries.Library;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.pom.java.LanguageLevel;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.maven.model.MavenArtifact;
import org.jetbrains.idea.maven.project.MavenProject;
import org.jetbrains.idea.maven.utils.Path;
import org.jetbrains.jps.model.JpsElement;
import org.jetbrains.jps.model.java.JavaSourceRootType;
import org.jetbrains.jps.model.module.JpsModuleSourceRootType;
import java.io.File;
public class MavenRootModelAdapter implements MavenRootModelAdapterInterface {
private final MavenRootModelAdapterInterface myDelegate;
public MavenRootModelAdapter(MavenRootModelAdapterInterface delegate) {myDelegate = delegate;}
@Override
public void init(boolean isNewlyCreatedModule) {
myDelegate.init(isNewlyCreatedModule);
}
@Override
public ModifiableRootModel getRootModel() {
return myDelegate.getRootModel();
}
@Override
public String @NotNull [] getSourceRootUrls(boolean includingTests) {
return myDelegate.getSourceRootUrls(includingTests);
}
@Override
public Module getModule() {
return myDelegate.getModule();
}
@Override
public void clearSourceFolders() {
myDelegate.clearSourceFolders();
}
@Override
public <P extends JpsElement> void addSourceFolder(String path,
JpsModuleSourceRootType<P> rootType) {
myDelegate.addSourceFolder(path, rootType);
}
@Override
public void addGeneratedJavaSourceFolder(String path, JavaSourceRootType rootType, boolean ifNotEmpty) {
myDelegate.addGeneratedJavaSourceFolder(path, rootType, ifNotEmpty);
}
@Override
public void addGeneratedJavaSourceFolder(String path, JavaSourceRootType rootType) {
myDelegate.addGeneratedJavaSourceFolder(path, rootType);
}
@Override
public boolean hasRegisteredSourceSubfolder(@NotNull File f) {
return myDelegate.hasRegisteredSourceSubfolder(f);
}
@Override
@Nullable
public SourceFolder getSourceFolder(File folder) {
return myDelegate.getSourceFolder(folder);
}
@Override
public boolean isAlreadyExcluded(File f) {
return myDelegate.isAlreadyExcluded(f);
}
@Override
public void addExcludedFolder(String path) {
myDelegate.addExcludedFolder(path);
}
@Override
public void unregisterAll(String path, boolean under, boolean unregisterSources) {
myDelegate.unregisterAll(path, under, unregisterSources);
}
@Override
public boolean hasCollision(String sourceRootPath) {
return myDelegate.hasCollision(sourceRootPath);
}
@Override
public void useModuleOutput(String production, String test) {
myDelegate.useModuleOutput(production, test);
}
@Override
public Path toPath(String path) {
return myDelegate.toPath(path);
}
@Override
public void addModuleDependency(@NotNull String moduleName, @NotNull DependencyScope scope, boolean testJar) {
myDelegate.addModuleDependency(moduleName, scope, testJar);
}
@Override
@Nullable
public Module findModuleByName(String moduleName) {
return myDelegate.findModuleByName(moduleName);
}
@Override
public void addSystemDependency(MavenArtifact artifact, DependencyScope scope) {
myDelegate.addSystemDependency(artifact, scope);
}
@Override
public LibraryOrderEntry addLibraryDependency(MavenArtifact artifact,
DependencyScope scope,
IdeModifiableModelsProvider provider,
MavenProject project) {
return myDelegate.addLibraryDependency(artifact, scope, provider, project);
}
@Override
public Library findLibrary(@NotNull MavenArtifact artifact) {
return myDelegate.findLibrary(artifact);
}
@Override
public void setLanguageLevel(LanguageLevel level) {
myDelegate.setLanguageLevel(level);
}
static boolean isChangedByUser(Library library) {
String[] classRoots = library.getUrls(
OrderRootType.CLASSES);
if (classRoots.length != 1) return true;
String classes = classRoots[0];
if (!classes.endsWith("!/")) return true;
int dotPos = classes.lastIndexOf("/", classes.length() - 2 /* trim ending !/ */);
if (dotPos == -1) return true;
String pathToJar = classes.substring(0, dotPos);
if (MavenRootModelAdapter
.hasUserPaths(OrderRootType.SOURCES, library, pathToJar)) {
return true;
}
if (MavenRootModelAdapter
.hasUserPaths(
JavadocOrderRootType
.getInstance(), library, pathToJar)) {
return true;
}
return false;
}
private static boolean hasUserPaths(OrderRootType rootType, Library library, String pathToJar) {
String[] sources = library.getUrls(rootType);
for (String each : sources) {
if (!FileUtil.startsWith(each, pathToJar)) return true;
}
return false;
}
public static boolean isMavenLibrary(@Nullable Library library) {
return library != null && MavenArtifact.isMavenLibrary(library.getName());
}
public static ProjectModelExternalSource getMavenExternalSource() {
return ExternalProjectSystemRegistry.getInstance().getSourceById(ExternalProjectSystemRegistry.MAVEN_EXTERNAL_SOURCE_ID);
}
@Nullable
public static OrderEntry findLibraryEntry(@NotNull Module m, @NotNull MavenArtifact artifact) {
String name = artifact.getLibraryName();
for (OrderEntry each : ModuleRootManager.getInstance(m).getOrderEntries()) {
if (each instanceof LibraryOrderEntry && name.equals(((LibraryOrderEntry)each).getLibraryName())) {
return each;
}
}
return null;
}
@Nullable
public static MavenArtifact findArtifact(@NotNull MavenProject project, @Nullable Library library) {
if (library == null) return null;
String name = library.getName();
if (!MavenArtifact.isMavenLibrary(name)) return null;
for (MavenArtifact each : project.getDependencies()) {
if (each.getLibraryName().equals(name)) return each;
}
return null;
}
}
| GunoH/intellij-community | plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenRootModelAdapter.java | Java | apache-2.0 | 6,985 |
#region License
/*
* Copyright © 2002-2011 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.
*/
#endregion
using System;
using System.Text;
using Spring.Util;
namespace Spring.Objects.Factory.Parsing
{
public class Problem
{
private string _message;
private Location _location;
private Exception _rootCause;
/// <summary>
/// Initializes a new instance of the <see cref="Problem"/> class.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="location">The location.</param>
public Problem(string message, Location location)
: this(message, location, null)
{
}
/// <summary>
/// Initializes a new instance of the Problem class.
/// </summary>
/// <param name="message"></param>
/// <param name="location"></param>
/// <param name="rootCause"></param>
public Problem(string message, Location location, Exception rootCause)
{
AssertUtils.ArgumentNotNull(message, "message");
AssertUtils.ArgumentNotNull(location, "resource");
_message = message;
_location = location;
_rootCause = rootCause;
}
public string Message
{
get
{
return _message;
}
}
public Location Location
{
get
{
return _location;
}
}
public string ResourceDescription
{
get { return _location.Resource != null ? _location.Resource.Description : string.Empty; }
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("Configuration problem: ");
sb.Append(Message);
sb.Append("\nOffending resource: ").Append(ResourceDescription);
return sb.ToString();
}
}
}
| spring-projects/spring-net | src/Spring/Spring.Core/Objects/Factory/Parsing/Problem.cs | C# | apache-2.0 | 2,660 |
"use strict";
var _Object$defineProperty = require("@babel/runtime-corejs3/core-js-stable/object/define-property");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var noteRole = {
abstract: false,
accessibleNameRequired: false,
baseConcepts: [],
childrenPresentational: false,
nameFrom: ['author'],
prohibitedProps: [],
props: {},
relatedConcepts: [],
requireContextRole: [],
requiredContextRole: [],
requiredOwnedElements: [],
requiredProps: {},
superClass: [['roletype', 'structure', 'section']]
};
var _default = noteRole;
exports.default = _default; | GoogleCloudPlatform/prometheus-engine | third_party/prometheus_ui/base/web/ui/react-app/node_modules/aria-query/lib/etc/roles/literal/noteRole.js | JavaScript | apache-2.0 | 627 |
/*
* 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.psi.formatter.java;
import com.intellij.formatting.*;
import com.intellij.formatting.alignment.AlignmentStrategy;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.psi.codeStyle.CommonCodeStyleSettings;
import com.intellij.psi.codeStyle.JavaCodeStyleSettings;
import com.intellij.psi.formatter.FormatterUtil;
import com.intellij.psi.formatter.common.AbstractBlock;
import com.intellij.psi.formatter.java.wrap.JavaWrapManager;
import com.intellij.psi.formatter.java.wrap.ReservedWrapsProvider;
import com.intellij.psi.impl.source.SourceTreeToPsiMap;
import com.intellij.psi.impl.source.codeStyle.ShiftIndentInsideHelper;
import com.intellij.psi.impl.source.tree.*;
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil;
import com.intellij.psi.impl.source.tree.java.ClassElement;
import com.intellij.psi.jsp.JspElementType;
import com.intellij.psi.tree.IElementType;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.text.CharArrayUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static com.intellij.psi.formatter.java.JavaFormatterUtil.getWrapType;
import static com.intellij.psi.formatter.java.MultipleFieldDeclarationHelper.findLastFieldInGroup;
public abstract class AbstractJavaBlock extends AbstractBlock implements JavaBlock, ReservedWrapsProvider {
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.formatter.java.AbstractJavaBlock");
@NotNull protected final CommonCodeStyleSettings mySettings;
@NotNull protected final JavaCodeStyleSettings myJavaSettings;
protected final CommonCodeStyleSettings.IndentOptions myIndentSettings;
private final Indent myIndent;
protected Indent myChildIndent;
protected Alignment myChildAlignment;
protected boolean myUseChildAttributes = false;
@NotNull protected final AlignmentStrategy myAlignmentStrategy;
private boolean myIsAfterClassKeyword = false;
protected Alignment myReservedAlignment;
protected Alignment myReservedAlignment2;
private final JavaWrapManager myWrapManager;
private Map<IElementType, Wrap> myPreferredWraps;
private AbstractJavaBlock myParentBlock;
protected AbstractJavaBlock(@NotNull final ASTNode node,
final Wrap wrap,
final Alignment alignment,
final Indent indent,
@NotNull final CommonCodeStyleSettings settings,
@NotNull JavaCodeStyleSettings javaSettings)
{
this(node, wrap, indent, settings, javaSettings, JavaWrapManager.INSTANCE, AlignmentStrategy.wrap(alignment));
}
protected AbstractJavaBlock(@NotNull final ASTNode node,
final Wrap wrap,
@NotNull final AlignmentStrategy alignmentStrategy,
final Indent indent,
@NotNull final CommonCodeStyleSettings settings,
@NotNull JavaCodeStyleSettings javaSettings)
{
this(node, wrap, indent, settings, javaSettings, JavaWrapManager.INSTANCE, alignmentStrategy);
}
private AbstractJavaBlock(@NotNull ASTNode ignored,
@NotNull CommonCodeStyleSettings commonSettings,
@NotNull JavaCodeStyleSettings javaSettings) {
super(ignored, null, null);
mySettings = commonSettings;
myJavaSettings = javaSettings;
myIndentSettings = commonSettings.getIndentOptions();
myIndent = null;
myWrapManager = JavaWrapManager.INSTANCE;
myAlignmentStrategy = AlignmentStrategy.getNullStrategy();
}
protected AbstractJavaBlock(@NotNull final ASTNode node,
final Wrap wrap,
final Indent indent,
@NotNull final CommonCodeStyleSettings settings,
@NotNull JavaCodeStyleSettings javaSettings,
final JavaWrapManager wrapManager,
@NotNull final AlignmentStrategy alignmentStrategy) {
super(node, wrap, createBlockAlignment(alignmentStrategy, node));
mySettings = settings;
myJavaSettings = javaSettings;
myIndentSettings = settings.getIndentOptions();
myIndent = indent;
myWrapManager = wrapManager;
myAlignmentStrategy = alignmentStrategy;
}
@Nullable
private static Alignment createBlockAlignment(@NotNull AlignmentStrategy strategy, @NotNull ASTNode node) {
// There is a possible case that 'implements' section is incomplete (e.g. ends with comma). We may want to align lbrace
// to the first implemented interface reference then.
if (node.getElementType() == JavaElementType.IMPLEMENTS_LIST) {
return null;
}
return strategy.getAlignment(node.getElementType());
}
@NotNull
public Block createJavaBlock(@NotNull ASTNode child,
@NotNull CommonCodeStyleSettings settings,
@NotNull JavaCodeStyleSettings javaSettings,
@Nullable Indent indent,
@Nullable Wrap wrap,
Alignment alignment) {
return createJavaBlock(child, settings, javaSettings,indent, wrap, AlignmentStrategy.wrap(alignment));
}
@NotNull
public Block createJavaBlock(@NotNull ASTNode child,
@NotNull CommonCodeStyleSettings settings,
@NotNull JavaCodeStyleSettings javaSettings,
final Indent indent,
@Nullable Wrap wrap,
@NotNull AlignmentStrategy alignmentStrategy) {
return createJavaBlock(child, settings, javaSettings, indent, wrap, alignmentStrategy, -1);
}
@NotNull
private Block createJavaBlock(@NotNull ASTNode child,
@NotNull CommonCodeStyleSettings settings,
@NotNull JavaCodeStyleSettings javaSettings,
@Nullable Indent indent,
Wrap wrap,
@NotNull AlignmentStrategy alignmentStrategy,
int startOffset) {
Indent actualIndent = indent == null ? getDefaultSubtreeIndent(child, getJavaIndentOptions(settings)) : indent;
final IElementType elementType = child.getElementType();
Alignment alignment = alignmentStrategy.getAlignment(elementType);
if (child.getPsi() instanceof PsiWhiteSpace) {
String text = child.getText();
int start = CharArrayUtil.shiftForward(text, 0, " \t\n");
int end = CharArrayUtil.shiftBackward(text, text.length() - 1, " \t\n") + 1;
LOG.assertTrue(start < end);
return new PartialWhitespaceBlock(child, new TextRange(start + child.getStartOffset(), end + child.getStartOffset()),
wrap, alignment, actualIndent, settings, javaSettings);
}
if (child.getPsi() instanceof PsiClass) {
return new CodeBlockBlock(child, wrap, alignment, actualIndent, settings, javaSettings);
}
if (isBlockType(elementType)) {
return new BlockContainingJavaBlock(child, wrap, alignment, actualIndent, settings, javaSettings);
}
if (isStatement(child, child.getTreeParent())) {
return new CodeBlockBlock(child, wrap, alignment, actualIndent, settings, javaSettings);
}
if (isBuildInjectedBlocks() &&
child instanceof PsiComment &&
child instanceof PsiLanguageInjectionHost &&
InjectedLanguageUtil.hasInjections((PsiLanguageInjectionHost)child)) {
return new CommentWithInjectionBlock(child, wrap, alignment, indent, settings, javaSettings);
}
if (child instanceof LeafElement) {
final LeafBlock block = new LeafBlock(child, wrap, alignment, actualIndent);
block.setStartOffset(startOffset);
return block;
}
else if (isLikeExtendsList(elementType)) {
return new ExtendsListBlock(child, wrap, alignmentStrategy, settings, javaSettings);
}
else if (elementType == JavaElementType.CODE_BLOCK) {
return new CodeBlockBlock(child, wrap, alignment, actualIndent, settings, javaSettings);
}
else if (elementType == JavaElementType.LABELED_STATEMENT) {
return new LabeledJavaBlock(child, wrap, alignment, actualIndent, settings, javaSettings);
}
else if (elementType == JavaDocElementType.DOC_COMMENT) {
return new DocCommentBlock(child, wrap, alignment, actualIndent, settings, javaSettings);
}
else {
final SimpleJavaBlock simpleJavaBlock = new SimpleJavaBlock(child, wrap, alignmentStrategy, actualIndent, settings, javaSettings);
simpleJavaBlock.setStartOffset(startOffset);
return simpleJavaBlock;
}
}
@NotNull
public static Block newJavaBlock(@NotNull ASTNode child,
@NotNull CommonCodeStyleSettings settings,
@NotNull JavaCodeStyleSettings javaSettings) {
final Indent indent = getDefaultSubtreeIndent(child, getJavaIndentOptions(settings));
return newJavaBlock(child, settings, javaSettings, indent, null, AlignmentStrategy.getNullStrategy());
}
@NotNull
public static Block newJavaBlock(@NotNull ASTNode child,
@NotNull CommonCodeStyleSettings settings,
@NotNull JavaCodeStyleSettings javaSettings,
@Nullable Indent indent,
@Nullable Wrap wrap,
@NotNull AlignmentStrategy strategy) {
return new AbstractJavaBlock(child, settings, javaSettings) {
@Override
protected List<Block> buildChildren() {
return null;
}
}.createJavaBlock(child, settings, javaSettings, indent, wrap, strategy);
}
@NotNull
private static CommonCodeStyleSettings.IndentOptions getJavaIndentOptions(CommonCodeStyleSettings settings) {
CommonCodeStyleSettings.IndentOptions indentOptions = settings.getIndentOptions();
assert indentOptions != null : "Java indent options are not initialized";
return indentOptions;
}
private static boolean isLikeExtendsList(final IElementType elementType) {
return elementType == JavaElementType.EXTENDS_LIST
|| elementType == JavaElementType.IMPLEMENTS_LIST
|| elementType == JavaElementType.THROWS_LIST;
}
private static boolean isBlockType(final IElementType elementType) {
return elementType == JavaElementType.SWITCH_STATEMENT
|| elementType == JavaElementType.FOR_STATEMENT
|| elementType == JavaElementType.WHILE_STATEMENT
|| elementType == JavaElementType.DO_WHILE_STATEMENT
|| elementType == JavaElementType.TRY_STATEMENT
|| elementType == JavaElementType.CATCH_SECTION
|| elementType == JavaElementType.IF_STATEMENT
|| elementType == JavaElementType.METHOD
|| elementType == JavaElementType.ARRAY_INITIALIZER_EXPRESSION
|| elementType == JavaElementType.ANNOTATION_ARRAY_INITIALIZER
|| elementType == JavaElementType.CLASS_INITIALIZER
|| elementType == JavaElementType.SYNCHRONIZED_STATEMENT
|| elementType == JavaElementType.FOREACH_STATEMENT;
}
@Nullable
private static Indent getDefaultSubtreeIndent(@NotNull ASTNode child, @NotNull CommonCodeStyleSettings.IndentOptions indentOptions) {
final ASTNode parent = child.getTreeParent();
final IElementType childNodeType = child.getElementType();
if (childNodeType == JavaElementType.ANNOTATION) {
if (parent.getPsi() instanceof PsiArrayInitializerMemberValue) {
return Indent.getNormalIndent();
}
return Indent.getNoneIndent();
}
final ASTNode prevElement = FormatterUtil.getPreviousNonWhitespaceSibling(child);
if (prevElement != null && prevElement.getElementType() == JavaElementType.MODIFIER_LIST) {
return Indent.getNoneIndent();
}
if (childNodeType == JavaDocElementType.DOC_TAG) return Indent.getNoneIndent();
if (childNodeType == JavaDocTokenType.DOC_COMMENT_LEADING_ASTERISKS) return Indent.getSpaceIndent(1);
if (child.getPsi() instanceof PsiFile) return Indent.getNoneIndent();
if (parent != null) {
final Indent defaultChildIndent = getChildIndent(parent, indentOptions);
if (defaultChildIndent != null) return defaultChildIndent;
}
if (child.getTreeParent() instanceof PsiLambdaExpression && child instanceof PsiCodeBlock) {
return Indent.getNoneIndent();
}
return null;
}
@Nullable
private static Indent getChildIndent(@NotNull ASTNode parent, @NotNull CommonCodeStyleSettings.IndentOptions indentOptions) {
final IElementType parentType = parent.getElementType();
if (parentType == JavaElementType.MODIFIER_LIST) return Indent.getNoneIndent();
if (parentType == JspElementType.JSP_CODE_BLOCK) return Indent.getNormalIndent();
if (parentType == JspElementType.JSP_CLASS_LEVEL_DECLARATION_STATEMENT) return Indent.getNormalIndent();
if (parentType == TokenType.DUMMY_HOLDER) return Indent.getNoneIndent();
if (parentType == JavaElementType.CLASS) return Indent.getNoneIndent();
if (parentType == JavaElementType.IF_STATEMENT) return Indent.getNoneIndent();
if (parentType == JavaElementType.TRY_STATEMENT) return Indent.getNoneIndent();
if (parentType == JavaElementType.CATCH_SECTION) return Indent.getNoneIndent();
if (parentType == JavaElementType.FOR_STATEMENT) return Indent.getNoneIndent();
if (parentType == JavaElementType.FOREACH_STATEMENT) return Indent.getNoneIndent();
if (parentType == JavaElementType.BLOCK_STATEMENT) return Indent.getNoneIndent();
if (parentType == JavaElementType.DO_WHILE_STATEMENT) return Indent.getNoneIndent();
if (parentType == JavaElementType.WHILE_STATEMENT) return Indent.getNoneIndent();
if (parentType == JavaElementType.SWITCH_STATEMENT) return Indent.getNoneIndent();
if (parentType == JavaElementType.METHOD) return Indent.getNoneIndent();
if (parentType == JavaDocElementType.DOC_COMMENT) return Indent.getNoneIndent();
if (parentType == JavaDocElementType.DOC_TAG) return Indent.getNoneIndent();
if (parentType == JavaDocElementType.DOC_INLINE_TAG) return Indent.getNoneIndent();
if (parentType == JavaElementType.IMPORT_LIST) return Indent.getNoneIndent();
if (parentType == JavaElementType.FIELD) return Indent.getContinuationWithoutFirstIndent(indentOptions.USE_RELATIVE_INDENTS);
if (parentType == JavaElementType.EXPRESSION_STATEMENT) return Indent.getNoneIndent();
if (SourceTreeToPsiMap.treeElementToPsi(parent) instanceof PsiFile) {
return Indent.getNoneIndent();
}
return null;
}
protected static boolean isRBrace(@NotNull final ASTNode child) {
return child.getElementType() == JavaTokenType.RBRACE;
}
@Nullable
@Override
public Spacing getSpacing(Block child1, @NotNull Block child2) {
return JavaSpacePropertyProcessor.getSpacing(getTreeNode(child2), mySettings, myJavaSettings);
}
@Override
public ASTNode getFirstTreeNode() {
return myNode;
}
@Override
public Indent getIndent() {
return myIndent;
}
protected static boolean isStatement(final ASTNode child, @Nullable final ASTNode parentNode) {
if (parentNode != null) {
final IElementType parentType = parentNode.getElementType();
if (parentType == JavaElementType.CODE_BLOCK) return false;
final int role = ((CompositeElement)parentNode).getChildRole(child);
if (parentType == JavaElementType.IF_STATEMENT) return role == ChildRole.THEN_BRANCH || role == ChildRole.ELSE_BRANCH;
if (parentType == JavaElementType.FOR_STATEMENT) return role == ChildRole.LOOP_BODY;
if (parentType == JavaElementType.WHILE_STATEMENT) return role == ChildRole.LOOP_BODY;
if (parentType == JavaElementType.DO_WHILE_STATEMENT) return role == ChildRole.LOOP_BODY;
if (parentType == JavaElementType.FOREACH_STATEMENT) return role == ChildRole.LOOP_BODY;
}
return false;
}
@Nullable
protected Wrap createChildWrap() {
return myWrapManager.createChildBlockWrap(this, getSettings(), this);
}
@Nullable
protected Alignment createChildAlignment() {
IElementType nodeType = myNode.getElementType();
if (nodeType == JavaElementType.POLYADIC_EXPRESSION) nodeType = JavaElementType.BINARY_EXPRESSION;
if (nodeType == JavaElementType.ASSIGNMENT_EXPRESSION) {
if (myNode.getTreeParent() != null
&& myNode.getTreeParent().getElementType() == JavaElementType.ASSIGNMENT_EXPRESSION
&& myAlignment != null) {
return myAlignment;
}
return createAlignment(mySettings.ALIGN_MULTILINE_ASSIGNMENT, null);
}
if (nodeType == JavaElementType.PARENTH_EXPRESSION) {
return createAlignment(mySettings.ALIGN_MULTILINE_PARENTHESIZED_EXPRESSION, null);
}
if (nodeType == JavaElementType.CONDITIONAL_EXPRESSION) {
return createAlignment(mySettings.ALIGN_MULTILINE_TERNARY_OPERATION, null);
}
if (nodeType == JavaElementType.FOR_STATEMENT) {
return createAlignment(mySettings.ALIGN_MULTILINE_FOR, null);
}
if (nodeType == JavaElementType.EXTENDS_LIST || nodeType == JavaElementType.IMPLEMENTS_LIST) {
return createAlignment(mySettings.ALIGN_MULTILINE_EXTENDS_LIST, null);
}
if (nodeType == JavaElementType.THROWS_LIST) {
return createAlignment(mySettings.ALIGN_MULTILINE_THROWS_LIST, null);
}
if (nodeType == JavaElementType.PARAMETER_LIST) {
return createAlignment(mySettings.ALIGN_MULTILINE_PARAMETERS, null);
}
if (nodeType == JavaElementType.RESOURCE_LIST) {
return createAlignment(mySettings.ALIGN_MULTILINE_RESOURCES, null);
}
if (nodeType == JavaElementType.BINARY_EXPRESSION) {
Alignment defaultAlignment = null;
if (shouldInheritAlignment()) {
defaultAlignment = myAlignment;
}
return createAlignment(mySettings.ALIGN_MULTILINE_BINARY_OPERATION, defaultAlignment);
}
if (nodeType == JavaElementType.CLASS || nodeType == JavaElementType.METHOD) {
return null;
}
return null;
}
@Nullable
protected Alignment chooseAlignment(@Nullable Alignment alignment, @Nullable Alignment alignment2, @NotNull ASTNode child) {
if (isTernaryOperatorToken(child)) {
return alignment2;
}
return alignment;
}
private boolean isTernaryOperatorToken(@NotNull final ASTNode child) {
final IElementType nodeType = myNode.getElementType();
if (nodeType == JavaElementType.CONDITIONAL_EXPRESSION) {
IElementType childType = child.getElementType();
return childType == JavaTokenType.QUEST || childType ==JavaTokenType.COLON;
}
else {
return false;
}
}
private boolean shouldInheritAlignment() {
if (myNode instanceof PsiPolyadicExpression) {
final ASTNode treeParent = myNode.getTreeParent();
if (treeParent instanceof PsiPolyadicExpression) {
return JavaFormatterUtil.areSamePriorityBinaryExpressions(myNode, treeParent);
}
}
return false;
}
@Nullable
protected ASTNode processChild(@NotNull final List<Block> result,
@NotNull ASTNode child,
Alignment defaultAlignment,
final Wrap defaultWrap,
final Indent childIndent) {
return processChild(result, child, AlignmentStrategy.wrap(defaultAlignment), defaultWrap, childIndent, -1);
}
@Nullable
protected ASTNode processChild(@NotNull final List<Block> result,
@NotNull ASTNode child,
@NotNull AlignmentStrategy alignmentStrategy,
@Nullable final Wrap defaultWrap,
final Indent childIndent) {
return processChild(result, child, alignmentStrategy, defaultWrap, childIndent, -1);
}
@Nullable
protected ASTNode processChild(@NotNull final List<Block> result,
@NotNull ASTNode child,
@NotNull AlignmentStrategy alignmentStrategy,
final Wrap defaultWrap,
final Indent childIndent,
int childOffset) {
final IElementType childType = child.getElementType();
if (childType == JavaTokenType.CLASS_KEYWORD || childType == JavaTokenType.INTERFACE_KEYWORD) {
myIsAfterClassKeyword = true;
}
if (childType == JavaElementType.METHOD_CALL_EXPRESSION) {
Alignment alignment = shouldAlignChild(child) ? alignmentStrategy.getAlignment(childType) : null;
result.add(createMethodCallExpressionBlock(child, arrangeChildWrap(child, defaultWrap), alignment, childIndent));
}
else {
IElementType nodeType = myNode.getElementType();
if (nodeType == JavaElementType.POLYADIC_EXPRESSION) nodeType = JavaElementType.BINARY_EXPRESSION;
if (childType == JavaTokenType.LBRACE && nodeType == JavaElementType.ARRAY_INITIALIZER_EXPRESSION) {
final Wrap wrap = Wrap.createWrap(getWrapType(mySettings.ARRAY_INITIALIZER_WRAP), false);
child = processParenthesisBlock(JavaTokenType.LBRACE, JavaTokenType.RBRACE,
result,
child,
WrappingStrategy.createDoNotWrapCommaStrategy(wrap),
mySettings.ALIGN_MULTILINE_ARRAY_INITIALIZER_EXPRESSION);
}
else if (childType == JavaTokenType.LBRACE && nodeType == JavaElementType.ANNOTATION_ARRAY_INITIALIZER) {
final Wrap wrap = Wrap.createWrap(getWrapType(mySettings.ARRAY_INITIALIZER_WRAP), false);
child = processParenthesisBlock(JavaTokenType.LBRACE, JavaTokenType.RBRACE,
result,
child,
WrappingStrategy.createDoNotWrapCommaStrategy(wrap),
mySettings.ALIGN_MULTILINE_ARRAY_INITIALIZER_EXPRESSION);
}
else if (childType == JavaTokenType.LPARENTH && nodeType == JavaElementType.EXPRESSION_LIST) {
final Wrap wrap = Wrap.createWrap(getWrapType(mySettings.CALL_PARAMETERS_WRAP), false);
if (mySettings.PREFER_PARAMETERS_WRAP && !isInsideMethodCall(myNode.getPsi())) {
wrap.ignoreParentWraps();
}
child = processParenthesisBlock(result, child,
WrappingStrategy.createDoNotWrapCommaStrategy(wrap),
mySettings.ALIGN_MULTILINE_PARAMETERS_IN_CALLS);
}
else if (childType == JavaTokenType.LPARENTH && nodeType == JavaElementType.PARAMETER_LIST) {
ASTNode parent = myNode.getTreeParent();
boolean isLambdaParameterList = parent != null && parent.getElementType() == JavaElementType.LAMBDA_EXPRESSION;
Wrap wrapToUse = isLambdaParameterList ? null : getMethodParametersWrap();
WrappingStrategy wrapStrategy = WrappingStrategy.createDoNotWrapCommaStrategy(wrapToUse);
child = processParenthesisBlock(result, child, wrapStrategy, mySettings.ALIGN_MULTILINE_PARAMETERS);
}
else if (childType == JavaTokenType.LPARENTH && nodeType == JavaElementType.RESOURCE_LIST) {
Wrap wrap = Wrap.createWrap(getWrapType(mySettings.RESOURCE_LIST_WRAP), false);
child = processParenthesisBlock(result, child,
WrappingStrategy.createDoNotWrapCommaStrategy(wrap),
mySettings.ALIGN_MULTILINE_RESOURCES);
}
else if (childType == JavaTokenType.LPARENTH && nodeType == JavaElementType.ANNOTATION_PARAMETER_LIST) {
Wrap wrap = Wrap.createWrap(getWrapType(myJavaSettings.ANNOTATION_PARAMETER_WRAP), false);
child = processParenthesisBlock(result, child,
WrappingStrategy.createDoNotWrapCommaStrategy(wrap),
myJavaSettings.ALIGN_MULTILINE_ANNOTATION_PARAMETERS);
}
else if (childType == JavaTokenType.LPARENTH && nodeType == JavaElementType.PARENTH_EXPRESSION) {
child = processParenthesisBlock(result, child,
WrappingStrategy.DO_NOT_WRAP,
mySettings.ALIGN_MULTILINE_PARENTHESIZED_EXPRESSION);
}
else if (childType == JavaElementType.ENUM_CONSTANT && myNode instanceof ClassElement) {
child = processEnumBlock(result, child, ((ClassElement)myNode).findEnumConstantListDelimiterPlace());
}
else if (mySettings.TERNARY_OPERATION_SIGNS_ON_NEXT_LINE && isTernaryOperationSign(child)) {
child = processTernaryOperationRange(result, child, defaultWrap, childIndent);
}
else if (childType == JavaElementType.FIELD) {
child = processField(result, child, alignmentStrategy, defaultWrap, childIndent);
}
else if (childType == JavaElementType.LOCAL_VARIABLE
|| childType == JavaElementType.DECLARATION_STATEMENT
&& (nodeType == JavaElementType.METHOD || nodeType == JavaElementType.CODE_BLOCK))
{
result.add(new SimpleJavaBlock(child, defaultWrap, alignmentStrategy, childIndent, mySettings, myJavaSettings));
}
else {
Alignment alignment = alignmentStrategy.getAlignment(childType);
AlignmentStrategy alignmentStrategyToUse = shouldAlignChild(child)
? AlignmentStrategy.wrap(alignment)
: AlignmentStrategy.getNullStrategy();
if (myAlignmentStrategy.getAlignment(nodeType, childType) != null &&
(nodeType == JavaElementType.IMPLEMENTS_LIST || nodeType == JavaElementType.CLASS)) {
alignmentStrategyToUse = myAlignmentStrategy;
}
Wrap wrap = arrangeChildWrap(child, defaultWrap);
Block block = createJavaBlock(child, mySettings, myJavaSettings, childIndent, wrap, alignmentStrategyToUse, childOffset);
if (block instanceof AbstractJavaBlock) {
final AbstractJavaBlock javaBlock = (AbstractJavaBlock)block;
if (nodeType == JavaElementType.METHOD_CALL_EXPRESSION && childType == JavaElementType.REFERENCE_EXPRESSION ||
nodeType == JavaElementType.REFERENCE_EXPRESSION && childType == JavaElementType.METHOD_CALL_EXPRESSION) {
javaBlock.setReservedWrap(getReservedWrap(nodeType), nodeType);
javaBlock.setReservedWrap(getReservedWrap(childType), childType);
}
else if (nodeType == JavaElementType.BINARY_EXPRESSION) {
javaBlock.setReservedWrap(defaultWrap, nodeType);
}
}
result.add(block);
}
}
return child;
}
private boolean isInsideMethodCall(@NotNull PsiElement element) {
PsiElement e = element.getParent();
int parentsVisited = 0;
while (e != null && !(e instanceof PsiStatement) && parentsVisited < 5) {
if (e instanceof PsiExpressionList) {
return true;
}
e = e.getParent();
parentsVisited++;
}
return false;
}
@NotNull
private Wrap getMethodParametersWrap() {
Wrap preferredWrap = getModifierListWrap();
if (preferredWrap == null) {
return Wrap.createWrap(getWrapType(mySettings.METHOD_PARAMETERS_WRAP), false);
} else {
return Wrap.createChildWrap(preferredWrap, getWrapType(mySettings.METHOD_PARAMETERS_WRAP), false);
}
}
@Nullable
private Wrap getModifierListWrap() {
AbstractJavaBlock parentBlock = getParentBlock();
if (parentBlock != null) {
return parentBlock.getReservedWrap(JavaElementType.MODIFIER_LIST);
}
return null;
}
private ASTNode processField(@NotNull final List<Block> result,
ASTNode child,
@NotNull final AlignmentStrategy alignmentStrategy,
final Wrap defaultWrap,
final Indent childIndent) {
ASTNode lastFieldInGroup = findLastFieldInGroup(child);
if (lastFieldInGroup == child) {
result.add(createJavaBlock(child, getSettings(), myJavaSettings, childIndent, arrangeChildWrap(child, defaultWrap), alignmentStrategy));
return child;
}
else {
final ArrayList<Block> localResult = new ArrayList<Block>();
while (child != null) {
if (!FormatterUtil.containsWhiteSpacesOnly(child)) {
localResult.add(createJavaBlock(
child, getSettings(), myJavaSettings,
Indent.getContinuationWithoutFirstIndent(myIndentSettings.USE_RELATIVE_INDENTS),
arrangeChildWrap(child, defaultWrap),
alignmentStrategy
)
);
}
if (child == lastFieldInGroup) break;
child = child.getTreeNext();
}
if (!localResult.isEmpty()) {
result.add(new SyntheticCodeBlock(localResult, null, getSettings(), myJavaSettings, childIndent, null));
}
return lastFieldInGroup;
}
}
@Nullable
private ASTNode processTernaryOperationRange(@NotNull final List<Block> result,
@NotNull final ASTNode child,
final Wrap defaultWrap,
final Indent childIndent) {
final ArrayList<Block> localResult = new ArrayList<Block>();
final Wrap wrap = arrangeChildWrap(child, defaultWrap);
final Alignment alignment = myReservedAlignment;
final Alignment alignment2 = myReservedAlignment2;
localResult.add(new LeafBlock(child, wrap, chooseAlignment(alignment, alignment2, child), childIndent));
ASTNode current = child.getTreeNext();
while (current != null) {
if (!FormatterUtil.containsWhiteSpacesOnly(current) && current.getTextLength() > 0) {
if (isTernaryOperationSign(current)) break;
current = processChild(localResult, current, chooseAlignment(alignment, alignment2, current), defaultWrap, childIndent);
}
if (current != null) {
current = current.getTreeNext();
}
}
result.add(new SyntheticCodeBlock(localResult, chooseAlignment(alignment, alignment2, child), getSettings(), myJavaSettings, null, wrap));
if (current == null) {
return null;
}
return current.getTreePrev();
}
private boolean isTernaryOperationSign(@NotNull final ASTNode child) {
if (myNode.getElementType() != JavaElementType.CONDITIONAL_EXPRESSION) return false;
final int role = ((CompositeElement)child.getTreeParent()).getChildRole(child);
return role == ChildRole.OPERATION_SIGN || role == ChildRole.COLON;
}
@NotNull
private Block createMethodCallExpressionBlock(@NotNull ASTNode node, Wrap blockWrap, Alignment alignment, Indent indent) {
final ArrayList<ASTNode> nodes = new ArrayList<ASTNode>();
collectNodes(nodes, node);
return new ChainMethodCallsBlockBuilder(alignment, blockWrap, indent, mySettings, myJavaSettings).build(nodes);
}
private static void collectNodes(@NotNull List<ASTNode> nodes, @NotNull ASTNode node) {
ASTNode child = node.getFirstChildNode();
while (child != null) {
if (!FormatterUtil.containsWhiteSpacesOnly(child)) {
if (child.getElementType() == JavaElementType.METHOD_CALL_EXPRESSION || child.getElementType() ==
JavaElementType
.REFERENCE_EXPRESSION) {
collectNodes(nodes, child);
}
else {
nodes.add(child);
}
}
child = child.getTreeNext();
}
}
private boolean shouldAlignChild(@NotNull final ASTNode child) {
int role = getChildRole(child);
final IElementType nodeType = myNode.getElementType();
if (nodeType == JavaElementType.FOR_STATEMENT) {
if (role == ChildRole.FOR_INITIALIZATION || role == ChildRole.CONDITION || role == ChildRole.FOR_UPDATE) {
return true;
}
return false;
}
else if (nodeType == JavaElementType.EXTENDS_LIST || nodeType == JavaElementType.IMPLEMENTS_LIST) {
if (role == ChildRole.REFERENCE_IN_LIST || role == ChildRole.IMPLEMENTS_KEYWORD) {
return true;
}
return false;
}
else if (nodeType == JavaElementType.THROWS_LIST) {
if (role == ChildRole.REFERENCE_IN_LIST) {
return true;
}
return false;
}
else if (nodeType == JavaElementType.CLASS) {
if (role == ChildRole.CLASS_OR_INTERFACE_KEYWORD) return true;
if (myIsAfterClassKeyword) return false;
if (role == ChildRole.MODIFIER_LIST) return true;
return false;
}
else if (JavaElementType.FIELD == nodeType) {
return shouldAlignFieldInColumns(child);
}
else if (nodeType == JavaElementType.METHOD) {
if (role == ChildRole.MODIFIER_LIST) return true;
if (role == ChildRole.TYPE_PARAMETER_LIST) return true;
if (role == ChildRole.TYPE) return true;
if (role == ChildRole.NAME) return true;
if (role == ChildRole.THROWS_LIST && mySettings.ALIGN_THROWS_KEYWORD) return true;
return false;
}
else if (nodeType == JavaElementType.ASSIGNMENT_EXPRESSION) {
if (role == ChildRole.LOPERAND) return true;
if (role == ChildRole.ROPERAND && child.getElementType() == JavaElementType.ASSIGNMENT_EXPRESSION) {
return true;
}
return false;
}
else if (child.getElementType() == JavaTokenType.END_OF_LINE_COMMENT) {
ASTNode previous = child.getTreePrev();
// There is a special case - comment block that is located at the very start of the line. We don't reformat such a blocks,
// hence, no alignment should be applied to them in order to avoid subsequent blocks aligned with the same alignment to
// be located at the left editor edge as well.
CharSequence prevChars;
if (previous != null && previous.getElementType() == TokenType.WHITE_SPACE && (prevChars = previous.getChars()).length() > 0
&& prevChars.charAt(prevChars.length() - 1) == '\n') {
return false;
}
return true;
}
else if (nodeType == JavaElementType.MODIFIER_LIST) {
// There is a possible case that modifier list contains from more than one elements, e.g. 'private final'. It's also possible
// that the list is aligned. We want to apply alignment rule only to the first element then.
ASTNode previous = child.getTreePrev();
if (previous == null || previous.getTreeParent() != myNode) {
return true;
}
return false;
}
else {
return true;
}
}
private static int getChildRole(@NotNull ASTNode child) {
return ((CompositeElement)child.getTreeParent()).getChildRole(child);
}
/**
* Encapsulates alignment retrieval logic for variable declaration use-case assuming that given node is a child node
* of basic variable declaration node.
*
* @param child variable declaration child node which alignment is to be defined
* @return alignment to use for the given node
* @see CodeStyleSettings#ALIGN_GROUP_FIELD_DECLARATIONS
*/
@Nullable
private boolean shouldAlignFieldInColumns(@NotNull ASTNode child) {
// The whole idea of variable declarations alignment is that complete declaration blocks which children are to be aligned hold
// reference to the same AlignmentStrategy object, hence, reuse the same Alignment objects. So, there is no point in checking
// if it's necessary to align sub-blocks if shared strategy is not defined.
if (!mySettings.ALIGN_GROUP_FIELD_DECLARATIONS) {
return false;
}
IElementType childType = child.getElementType();
// We don't want to align subsequent identifiers in single-line declarations like 'int i1, i2, i3'. I.e. only 'i1'
// should be aligned then.
ASTNode previousNode = FormatterUtil.getPreviousNonWhitespaceSibling(child);
if (childType == JavaTokenType.IDENTIFIER && (previousNode == null || previousNode.getElementType() == JavaTokenType.COMMA)) {
return false;
}
return true;
}
@Nullable
public static Alignment createAlignment(final boolean alignOption, @Nullable final Alignment defaultAlignment) {
return alignOption ? createAlignmentOrDefault(null, defaultAlignment) : defaultAlignment;
}
@Nullable
public static Alignment createAlignment(Alignment base, final boolean alignOption, @Nullable final Alignment defaultAlignment) {
return alignOption ? createAlignmentOrDefault(base, defaultAlignment) : defaultAlignment;
}
@Nullable
protected Wrap arrangeChildWrap(final ASTNode child, Wrap defaultWrap) {
return myWrapManager.arrangeChildWrap(child, myNode, mySettings, myJavaSettings, defaultWrap, this);
}
@NotNull
private ASTNode processParenthesisBlock(@NotNull List<Block> result,
@NotNull ASTNode child,
@NotNull WrappingStrategy wrappingStrategy,
final boolean doAlign) {
myUseChildAttributes = true;
final IElementType from = JavaTokenType.LPARENTH;
final IElementType to = JavaTokenType.RPARENTH;
return processParenthesisBlock(from, to, result, child, wrappingStrategy, doAlign);
}
@NotNull
private ASTNode processParenthesisBlock(@NotNull IElementType from,
@Nullable final IElementType to,
@NotNull final List<Block> result,
@NotNull ASTNode child,
@NotNull final WrappingStrategy wrappingStrategy,
final boolean doAlign) {
final Indent externalIndent = Indent.getNoneIndent();
final Indent internalIndent = Indent.getContinuationWithoutFirstIndent(myIndentSettings.USE_RELATIVE_INDENTS);
final Indent internalIndentEnforcedToChildren = Indent.getIndent(Indent.Type.CONTINUATION, myIndentSettings.USE_RELATIVE_INDENTS, true);
AlignmentStrategy alignmentStrategy = AlignmentStrategy.wrap(createAlignment(doAlign, null), JavaTokenType.COMMA);
setChildIndent(internalIndent);
setChildAlignment(alignmentStrategy.getAlignment(null));
boolean methodParametersBlock = true;
ASTNode lBracketParent = child.getTreeParent();
if (lBracketParent != null) {
ASTNode methodCandidate = lBracketParent.getTreeParent();
methodParametersBlock = methodCandidate != null && (methodCandidate.getElementType() == JavaElementType.METHOD
|| methodCandidate.getElementType() == JavaElementType.METHOD_CALL_EXPRESSION);
}
Alignment bracketAlignment = methodParametersBlock && mySettings.ALIGN_MULTILINE_METHOD_BRACKETS ? Alignment.createAlignment() : null;
AlignmentStrategy anonymousClassStrategy = doAlign ? alignmentStrategy
: AlignmentStrategy.wrap(Alignment.createAlignment(),
false,
JavaTokenType.NEW_KEYWORD,
JavaElementType.NEW_EXPRESSION,
JavaTokenType.RBRACE);
setChildIndent(internalIndent);
setChildAlignment(alignmentStrategy.getAlignment(null));
boolean isAfterIncomplete = false;
ASTNode prev = child;
boolean afterAnonymousClass = false;
final boolean enforceIndent = shouldEnforceIndentToChildren();
while (child != null) {
isAfterIncomplete = isAfterIncomplete || child.getElementType() == TokenType.ERROR_ELEMENT ||
child.getElementType() == JavaElementType.EMPTY_EXPRESSION;
if (!FormatterUtil.containsWhiteSpacesOnly(child) && child.getTextLength() > 0) {
if (child.getElementType() == from) {
result.add(createJavaBlock(child, mySettings, myJavaSettings, externalIndent, null, bracketAlignment));
}
else if (child.getElementType() == to) {
result.add(createJavaBlock(child, mySettings, myJavaSettings,
isAfterIncomplete && !afterAnonymousClass ? internalIndent : externalIndent,
null,
isAfterIncomplete ? alignmentStrategy.getAlignment(null) : bracketAlignment)
);
return child;
}
else {
final IElementType elementType = child.getElementType();
Indent indentToUse = enforceIndent ? internalIndentEnforcedToChildren : internalIndent;
AlignmentStrategy alignmentStrategyToUse = canUseAnonymousClassAlignment(child) ? anonymousClassStrategy : alignmentStrategy;
processChild(result, child, alignmentStrategyToUse.getAlignment(elementType), wrappingStrategy.getWrap(elementType), indentToUse);
if (to == null) {//process only one statement
return child;
}
}
isAfterIncomplete = false;
if (child.getElementType() != JavaTokenType.COMMA) {
afterAnonymousClass = isAnonymousClass(child);
}
}
prev = child;
child = child.getTreeNext();
}
return prev;
}
private static boolean canUseAnonymousClassAlignment(@NotNull ASTNode child) {
// The general idea is to handle situations like below:
// test(new Runnable() {
// public void run() {
// }
// }, new Runnable() {
// public void run() {
// }
// }
// );
// I.e. we want to align subsequent anonymous class argument to the previous one if it's not preceded by another argument
// at the same line, e.g.:
// test("this is a long argument", new Runnable() {
// public void run() {
// }
// }, new Runnable() {
// public void run() {
// }
// }
// );
if (!isAnonymousClass(child)) {
return false;
}
for (ASTNode node = child.getTreePrev(); node != null; node = node.getTreePrev()) {
if (node.getElementType() == TokenType.WHITE_SPACE) {
if (StringUtil.countNewLines(node.getChars()) > 0) {
return false;
}
}
else if (node.getElementType() == JavaTokenType.LPARENTH) {
// First method call argument.
return true;
}
else if (node.getElementType() != JavaTokenType.COMMA && !isAnonymousClass(node)) {
return false;
}
}
return true;
}
private boolean shouldEnforceIndentToChildren() {
if (myNode.getElementType() != JavaElementType.EXPRESSION_LIST) {
return false;
}
ASTNode parent = myNode.getTreeParent();
if (parent == null || parent.getElementType() != JavaElementType.METHOD_CALL_EXPRESSION) {
return false;
}
PsiExpression[] arguments = ((PsiExpressionList)myNode.getPsi()).getExpressions();
return JavaFormatterUtil.hasMultilineArguments(arguments) && JavaFormatterUtil.isMultilineExceptArguments(arguments);
}
private static boolean isAnonymousClass(@Nullable ASTNode node) {
if (node == null || node.getElementType() != JavaElementType.NEW_EXPRESSION) {
return false;
}
ASTNode lastChild = node.getLastChildNode();
return lastChild != null && lastChild.getElementType() == JavaElementType.ANONYMOUS_CLASS;
}
@Nullable
private ASTNode processEnumBlock(@NotNull List<Block> result,
@Nullable ASTNode child,
ASTNode last)
{
final WrappingStrategy wrappingStrategy = WrappingStrategy.createDoNotWrapCommaStrategy(Wrap
.createWrap(getWrapType(mySettings.ENUM_CONSTANTS_WRAP), true));
while (child != null) {
if (!FormatterUtil.containsWhiteSpacesOnly(child) && child.getTextLength() > 0) {
result.add(createJavaBlock(child, mySettings, myJavaSettings, Indent.getNormalIndent(),
wrappingStrategy.getWrap(child.getElementType()), AlignmentStrategy.getNullStrategy()));
if (child == last) return child;
}
child = child.getTreeNext();
}
return null;
}
private void setChildAlignment(final Alignment alignment) {
myChildAlignment = alignment;
}
private void setChildIndent(final Indent internalIndent) {
myChildIndent = internalIndent;
}
@Nullable
private static Alignment createAlignmentOrDefault(@Nullable Alignment base, @Nullable final Alignment defaultAlignment) {
if (defaultAlignment == null) {
return base == null ? Alignment.createAlignment() : Alignment.createChildAlignment(base);
}
return defaultAlignment;
}
private int getBraceStyle() {
final PsiElement psiNode = SourceTreeToPsiMap.treeElementToPsi(myNode);
if (psiNode instanceof PsiClass) {
return mySettings.CLASS_BRACE_STYLE;
}
if (psiNode instanceof PsiMethod
|| psiNode instanceof PsiCodeBlock && psiNode.getParent() != null && psiNode.getParent() instanceof PsiMethod) {
return mySettings.METHOD_BRACE_STYLE;
}
return mySettings.BRACE_STYLE;
}
protected Indent getCodeBlockInternalIndent(final int baseChildrenIndent) {
return getCodeBlockInternalIndent(baseChildrenIndent, false);
}
protected Indent getCodeBlockInternalIndent(final int baseChildrenIndent, boolean enforceParentIndent) {
if (isTopLevelClass() && mySettings.DO_NOT_INDENT_TOP_LEVEL_CLASS_MEMBERS) {
return Indent.getNoneIndent();
}
final int braceStyle = getBraceStyle();
return braceStyle == CommonCodeStyleSettings.NEXT_LINE_SHIFTED ?
createNormalIndent(baseChildrenIndent - 1, enforceParentIndent)
: createNormalIndent(baseChildrenIndent, enforceParentIndent);
}
protected static Indent createNormalIndent(final int baseChildrenIndent) {
return createNormalIndent(baseChildrenIndent, false);
}
protected static Indent createNormalIndent(final int baseChildrenIndent, boolean enforceIndentToChildren) {
if (baseChildrenIndent == 1) {
return Indent.getIndent(Indent.Type.NORMAL, false, enforceIndentToChildren);
}
else if (baseChildrenIndent <= 0) {
return Indent.getNoneIndent();
}
else {
LOG.assertTrue(false);
return Indent.getIndent(Indent.Type.NORMAL, false, enforceIndentToChildren);
}
}
private boolean isTopLevelClass() {
return myNode.getElementType() == JavaElementType.CLASS &&
SourceTreeToPsiMap.treeElementToPsi(myNode.getTreeParent()) instanceof PsiFile;
}
protected Indent getCodeBlockExternalIndent() {
final int braceStyle = getBraceStyle();
if (braceStyle == CommonCodeStyleSettings.END_OF_LINE || braceStyle == CommonCodeStyleSettings.NEXT_LINE ||
braceStyle == CommonCodeStyleSettings.NEXT_LINE_IF_WRAPPED) {
return Indent.getNoneIndent();
}
return Indent.getNormalIndent();
}
protected Indent getCodeBlockChildExternalIndent(final int newChildIndex) {
final int braceStyle = getBraceStyle();
if (!isAfterCodeBlock(newChildIndex)) {
return Indent.getNormalIndent();
}
if (braceStyle == CommonCodeStyleSettings.NEXT_LINE ||
braceStyle == CommonCodeStyleSettings.NEXT_LINE_IF_WRAPPED ||
braceStyle == CommonCodeStyleSettings.END_OF_LINE) {
return Indent.getNoneIndent();
}
return Indent.getNormalIndent();
}
private boolean isAfterCodeBlock(final int newChildIndex) {
if (newChildIndex == 0) return false;
Block blockBefore = getSubBlocks().get(newChildIndex - 1);
return blockBefore instanceof CodeBlockBlock;
}
/**
* <b>Note:</b> this method is considered to be a legacy heritage and is assumed to be removed as soon as formatting processing
* is refactored
*
* @param elementType target element type
* @return <code>null</code> all the time
*/
@Nullable
@Override
public Wrap getReservedWrap(IElementType elementType) {
return myPreferredWraps != null ? myPreferredWraps.get(elementType) : null;
}
/**
* Defines contract for associating operation type and particular wrap instance. I.e. given wrap object <b>may</b> be returned
* from subsequent {@link #getReservedWrap(IElementType)} call if given operation type is used as an argument there.
* <p/>
* Default implementation ({@link AbstractJavaBlock#setReservedWrap(Wrap, IElementType)}) does nothing.
* <p/>
* <b>Note:</b> this method is considered to be a legacy heritage and is assumed to be removed as soon as formatting processing
* is refactored
*
* @param reservedWrap reserved wrap instance
* @param operationType target operation type to associate with the given wrap instance
*/
public void setReservedWrap(final Wrap reservedWrap, final IElementType operationType) {
if (myPreferredWraps == null) {
myPreferredWraps = ContainerUtil.newHashMap();
}
myPreferredWraps.put(operationType, reservedWrap);
}
@Nullable
protected static ASTNode getTreeNode(final Block child2) {
if (child2 instanceof JavaBlock) {
return ((JavaBlock)child2).getFirstTreeNode();
}
if (child2 instanceof LeafBlock) {
return ((LeafBlock)child2).getTreeNode();
}
return null;
}
@Override
@NotNull
public ChildAttributes getChildAttributes(final int newChildIndex) {
if (myUseChildAttributes) {
return new ChildAttributes(myChildIndent, myChildAlignment);
}
if (isAfter(newChildIndex, new IElementType[]{JavaDocElementType.DOC_COMMENT})) {
return new ChildAttributes(Indent.getNoneIndent(), myChildAlignment);
}
return super.getChildAttributes(newChildIndex);
}
@Override
@Nullable
protected Indent getChildIndent() {
return getChildIndent(myNode, myIndentSettings);
}
@NotNull
public CommonCodeStyleSettings getSettings() {
return mySettings;
}
protected boolean isAfter(final int newChildIndex, @NotNull final IElementType[] elementTypes) {
if (newChildIndex == 0) return false;
final Block previousBlock = getSubBlocks().get(newChildIndex - 1);
if (!(previousBlock instanceof AbstractBlock)) return false;
final IElementType previousElementType = ((AbstractBlock)previousBlock).getNode().getElementType();
for (IElementType elementType : elementTypes) {
if (previousElementType == elementType) return true;
}
return false;
}
@Nullable
protected Alignment getUsedAlignment(final int newChildIndex) {
final List<Block> subBlocks = getSubBlocks();
for (int i = 0; i < newChildIndex; i++) {
if (i >= subBlocks.size()) return null;
final Block block = subBlocks.get(i);
final Alignment alignment = block.getAlignment();
if (alignment != null) return alignment;
}
return null;
}
@Override
public boolean isLeaf() {
return ShiftIndentInsideHelper.mayShiftIndentInside(myNode);
}
@Nullable
protected ASTNode composeCodeBlock(@NotNull final List<Block> result,
ASTNode child,
final Indent indent,
final int childrenIndent,
@Nullable final Wrap childWrap) {
final ArrayList<Block> localResult = new ArrayList<Block>();
processChild(localResult, child, AlignmentStrategy.getNullStrategy(), null, Indent.getNoneIndent());
child = child.getTreeNext();
ChildAlignmentStrategyProvider alignmentStrategyProvider = getStrategyProvider();
while (child != null) {
if (FormatterUtil.containsWhiteSpacesOnly(child)) {
child = child.getTreeNext();
continue;
}
Indent childIndent = getIndentForCodeBlock(child, childrenIndent);
AlignmentStrategy alignmentStrategyToUse = alignmentStrategyProvider.getNextChildStrategy(child);
final boolean isRBrace = isRBrace(child);
child = processChild(localResult, child, alignmentStrategyToUse, childWrap, childIndent);
if (isRBrace) {
result.add(createCodeBlockBlock(localResult, indent, childrenIndent));
return child;
}
if (child != null) {
child = child.getTreeNext();
}
}
result.add(createCodeBlockBlock(localResult, indent, childrenIndent));
return null;
}
private ChildAlignmentStrategyProvider getStrategyProvider() {
if (mySettings.ALIGN_GROUP_FIELD_DECLARATIONS && myNode.getElementType() == JavaElementType.CLASS) {
return new SubsequentFieldAligner(mySettings);
}
ASTNode parent = myNode.getTreeParent();
IElementType parentType = parent != null ? parent.getElementType() : null;
if (mySettings.ALIGN_CONSECUTIVE_VARIABLE_DECLARATIONS && parentType == JavaElementType.METHOD) {
return new SubsequentVariablesAligner();
}
return ChildAlignmentStrategyProvider.NULL_STRATEGY_PROVIDER;
}
private Indent getIndentForCodeBlock(ASTNode child, int childrenIndent) {
if (child.getElementType() == JavaElementType.CODE_BLOCK
&& (getBraceStyle() == CommonCodeStyleSettings.NEXT_LINE_SHIFTED
|| getBraceStyle() == CommonCodeStyleSettings.NEXT_LINE_SHIFTED2))
{
return Indent.getNormalIndent();
}
return isRBrace(child) ? Indent.getNoneIndent() : getCodeBlockInternalIndent(childrenIndent, false);
}
public AbstractJavaBlock getParentBlock() {
return myParentBlock;
}
public void setParentBlock(@NotNull AbstractJavaBlock parentBlock) {
myParentBlock = parentBlock;
}
@NotNull
public SyntheticCodeBlock createCodeBlockBlock(final List<Block> localResult, final Indent indent, final int childrenIndent) {
final SyntheticCodeBlock result = new SyntheticCodeBlock(localResult, null, getSettings(), myJavaSettings, indent, null);
result.setChildAttributes(new ChildAttributes(getCodeBlockInternalIndent(childrenIndent), null));
return result;
}
}
| robovm/robovm-studio | java/java-impl/src/com/intellij/psi/formatter/java/AbstractJavaBlock.java | Java | apache-2.0 | 55,736 |
/*
* 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.sql.relational;
import com.facebook.presto.Session;
import com.facebook.presto.metadata.FunctionKind;
import com.facebook.presto.metadata.FunctionRegistry;
import com.facebook.presto.metadata.Signature;
import com.facebook.presto.spi.type.DecimalParseResult;
import com.facebook.presto.spi.type.Decimals;
import com.facebook.presto.spi.type.TimeZoneKey;
import com.facebook.presto.spi.type.Type;
import com.facebook.presto.spi.type.TypeManager;
import com.facebook.presto.spi.type.TypeSignature;
import com.facebook.presto.sql.relational.optimizer.ExpressionOptimizer;
import com.facebook.presto.sql.tree.ArithmeticBinaryExpression;
import com.facebook.presto.sql.tree.ArithmeticUnaryExpression;
import com.facebook.presto.sql.tree.ArrayConstructor;
import com.facebook.presto.sql.tree.AstVisitor;
import com.facebook.presto.sql.tree.BetweenPredicate;
import com.facebook.presto.sql.tree.BinaryLiteral;
import com.facebook.presto.sql.tree.BooleanLiteral;
import com.facebook.presto.sql.tree.Cast;
import com.facebook.presto.sql.tree.CharLiteral;
import com.facebook.presto.sql.tree.CoalesceExpression;
import com.facebook.presto.sql.tree.ComparisonExpression;
import com.facebook.presto.sql.tree.DecimalLiteral;
import com.facebook.presto.sql.tree.DereferenceExpression;
import com.facebook.presto.sql.tree.DoubleLiteral;
import com.facebook.presto.sql.tree.Expression;
import com.facebook.presto.sql.tree.FieldReference;
import com.facebook.presto.sql.tree.FunctionCall;
import com.facebook.presto.sql.tree.GenericLiteral;
import com.facebook.presto.sql.tree.IfExpression;
import com.facebook.presto.sql.tree.InListExpression;
import com.facebook.presto.sql.tree.InPredicate;
import com.facebook.presto.sql.tree.IntervalLiteral;
import com.facebook.presto.sql.tree.IsNotNullPredicate;
import com.facebook.presto.sql.tree.IsNullPredicate;
import com.facebook.presto.sql.tree.LambdaArgumentDeclaration;
import com.facebook.presto.sql.tree.LambdaExpression;
import com.facebook.presto.sql.tree.LikePredicate;
import com.facebook.presto.sql.tree.LogicalBinaryExpression;
import com.facebook.presto.sql.tree.LongLiteral;
import com.facebook.presto.sql.tree.NotExpression;
import com.facebook.presto.sql.tree.NullIfExpression;
import com.facebook.presto.sql.tree.NullLiteral;
import com.facebook.presto.sql.tree.Row;
import com.facebook.presto.sql.tree.SearchedCaseExpression;
import com.facebook.presto.sql.tree.SimpleCaseExpression;
import com.facebook.presto.sql.tree.StringLiteral;
import com.facebook.presto.sql.tree.SubscriptExpression;
import com.facebook.presto.sql.tree.SymbolReference;
import com.facebook.presto.sql.tree.TimeLiteral;
import com.facebook.presto.sql.tree.TimestampLiteral;
import com.facebook.presto.sql.tree.TryExpression;
import com.facebook.presto.sql.tree.WhenClause;
import com.facebook.presto.type.RowType;
import com.facebook.presto.type.RowType.RowField;
import com.facebook.presto.type.UnknownType;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import java.util.IdentityHashMap;
import java.util.List;
import static com.facebook.presto.metadata.FunctionKind.SCALAR;
import static com.facebook.presto.spi.type.BigintType.BIGINT;
import static com.facebook.presto.spi.type.BooleanType.BOOLEAN;
import static com.facebook.presto.spi.type.CharType.createCharType;
import static com.facebook.presto.spi.type.DoubleType.DOUBLE;
import static com.facebook.presto.spi.type.IntegerType.INTEGER;
import static com.facebook.presto.spi.type.TimeWithTimeZoneType.TIME_WITH_TIME_ZONE;
import static com.facebook.presto.spi.type.TimestampWithTimeZoneType.TIMESTAMP_WITH_TIME_ZONE;
import static com.facebook.presto.spi.type.TypeSignature.parseTypeSignature;
import static com.facebook.presto.spi.type.VarbinaryType.VARBINARY;
import static com.facebook.presto.spi.type.VarcharType.VARCHAR;
import static com.facebook.presto.spi.type.VarcharType.createVarcharType;
import static com.facebook.presto.sql.relational.Expressions.call;
import static com.facebook.presto.sql.relational.Expressions.constant;
import static com.facebook.presto.sql.relational.Expressions.constantNull;
import static com.facebook.presto.sql.relational.Expressions.field;
import static com.facebook.presto.sql.relational.Signatures.arithmeticExpressionSignature;
import static com.facebook.presto.sql.relational.Signatures.arithmeticNegationSignature;
import static com.facebook.presto.sql.relational.Signatures.arrayConstructorSignature;
import static com.facebook.presto.sql.relational.Signatures.betweenSignature;
import static com.facebook.presto.sql.relational.Signatures.castSignature;
import static com.facebook.presto.sql.relational.Signatures.coalesceSignature;
import static com.facebook.presto.sql.relational.Signatures.comparisonExpressionSignature;
import static com.facebook.presto.sql.relational.Signatures.dereferenceSignature;
import static com.facebook.presto.sql.relational.Signatures.likePatternSignature;
import static com.facebook.presto.sql.relational.Signatures.likeSignature;
import static com.facebook.presto.sql.relational.Signatures.logicalExpressionSignature;
import static com.facebook.presto.sql.relational.Signatures.nullIfSignature;
import static com.facebook.presto.sql.relational.Signatures.rowConstructorSignature;
import static com.facebook.presto.sql.relational.Signatures.subscriptSignature;
import static com.facebook.presto.sql.relational.Signatures.switchSignature;
import static com.facebook.presto.sql.relational.Signatures.tryCastSignature;
import static com.facebook.presto.sql.relational.Signatures.whenSignature;
import static com.facebook.presto.type.JsonType.JSON;
import static com.facebook.presto.type.LikePatternType.LIKE_PATTERN;
import static com.facebook.presto.util.DateTimeUtils.parseDayTimeInterval;
import static com.facebook.presto.util.DateTimeUtils.parseTimeWithTimeZone;
import static com.facebook.presto.util.DateTimeUtils.parseTimeWithoutTimeZone;
import static com.facebook.presto.util.DateTimeUtils.parseTimestampWithTimeZone;
import static com.facebook.presto.util.DateTimeUtils.parseTimestampWithoutTimeZone;
import static com.facebook.presto.util.DateTimeUtils.parseYearMonthInterval;
import static com.facebook.presto.util.ImmutableCollectors.toImmutableList;
import static com.facebook.presto.util.Types.checkType;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static io.airlift.slice.SliceUtf8.countCodePoints;
import static io.airlift.slice.Slices.utf8Slice;
import static java.util.Objects.requireNonNull;
public final class SqlToRowExpressionTranslator
{
private SqlToRowExpressionTranslator() {}
public static RowExpression translate(
Expression expression,
FunctionKind functionKind,
IdentityHashMap<Expression, Type> types,
FunctionRegistry functionRegistry,
TypeManager typeManager,
Session session,
boolean optimize)
{
RowExpression result = new Visitor(functionKind, types, typeManager, session.getTimeZoneKey()).process(expression, null);
requireNonNull(result, "translated expression is null");
if (optimize) {
ExpressionOptimizer optimizer = new ExpressionOptimizer(functionRegistry, typeManager, session);
return optimizer.optimize(result);
}
return result;
}
private static class Visitor
extends AstVisitor<RowExpression, Void>
{
private final FunctionKind functionKind;
private final IdentityHashMap<Expression, Type> types;
private final TypeManager typeManager;
private final TimeZoneKey timeZoneKey;
private Visitor(FunctionKind functionKind, IdentityHashMap<Expression, Type> types, TypeManager typeManager, TimeZoneKey timeZoneKey)
{
this.functionKind = functionKind;
this.types = types;
this.typeManager = typeManager;
this.timeZoneKey = timeZoneKey;
}
@Override
protected RowExpression visitExpression(Expression node, Void context)
{
throw new UnsupportedOperationException("not yet implemented: expression translator for " + node.getClass().getName());
}
@Override
protected RowExpression visitFieldReference(FieldReference node, Void context)
{
return field(node.getFieldIndex(), types.get(node));
}
@Override
protected RowExpression visitNullLiteral(NullLiteral node, Void context)
{
return constantNull(UnknownType.UNKNOWN);
}
@Override
protected RowExpression visitBooleanLiteral(BooleanLiteral node, Void context)
{
return constant(node.getValue(), BOOLEAN);
}
@Override
protected RowExpression visitLongLiteral(LongLiteral node, Void context)
{
if (node.getValue() >= Integer.MIN_VALUE && node.getValue() <= Integer.MAX_VALUE) {
return constant(node.getValue(), INTEGER);
}
return constant(node.getValue(), BIGINT);
}
@Override
protected RowExpression visitDoubleLiteral(DoubleLiteral node, Void context)
{
return constant(node.getValue(), DOUBLE);
}
@Override
protected RowExpression visitDecimalLiteral(DecimalLiteral node, Void context)
{
DecimalParseResult parseResult = Decimals.parse(node.getValue());
return constant(parseResult.getObject(), parseResult.getType());
}
@Override
protected RowExpression visitStringLiteral(StringLiteral node, Void context)
{
return constant(node.getSlice(), createVarcharType(countCodePoints(node.getSlice())));
}
@Override
protected RowExpression visitCharLiteral(CharLiteral node, Void context)
{
return constant(node.getSlice(), createCharType(node.getValue().length()));
}
@Override
protected RowExpression visitBinaryLiteral(BinaryLiteral node, Void context)
{
return constant(node.getValue(), VARBINARY);
}
@Override
protected RowExpression visitGenericLiteral(GenericLiteral node, Void context)
{
Type type = typeManager.getType(parseTypeSignature(node.getType()));
if (type == null) {
throw new IllegalArgumentException("Unsupported type: " + node.getType());
}
if (JSON.equals(type)) {
return call(
new Signature("json_parse", SCALAR, types.get(node).getTypeSignature(), VARCHAR.getTypeSignature()),
types.get(node),
constant(utf8Slice(node.getValue()), VARCHAR));
}
return call(
castSignature(types.get(node), VARCHAR),
types.get(node),
constant(utf8Slice(node.getValue()), VARCHAR));
}
@Override
protected RowExpression visitTimeLiteral(TimeLiteral node, Void context)
{
long value;
if (types.get(node).equals(TIME_WITH_TIME_ZONE)) {
value = parseTimeWithTimeZone(node.getValue());
}
else {
// parse in time zone of client
value = parseTimeWithoutTimeZone(timeZoneKey, node.getValue());
}
return constant(value, types.get(node));
}
@Override
protected RowExpression visitTimestampLiteral(TimestampLiteral node, Void context)
{
long value;
if (types.get(node).equals(TIMESTAMP_WITH_TIME_ZONE)) {
value = parseTimestampWithTimeZone(timeZoneKey, node.getValue());
}
else {
// parse in time zone of client
value = parseTimestampWithoutTimeZone(timeZoneKey, node.getValue());
}
return constant(value, types.get(node));
}
@Override
protected RowExpression visitIntervalLiteral(IntervalLiteral node, Void context)
{
long value;
if (node.isYearToMonth()) {
value = node.getSign().multiplier() * parseYearMonthInterval(node.getValue(), node.getStartField(), node.getEndField());
}
else {
value = node.getSign().multiplier() * parseDayTimeInterval(node.getValue(), node.getStartField(), node.getEndField());
}
return constant(value, types.get(node));
}
@Override
protected RowExpression visitComparisonExpression(ComparisonExpression node, Void context)
{
RowExpression left = process(node.getLeft(), context);
RowExpression right = process(node.getRight(), context);
return call(
comparisonExpressionSignature(node.getType(), left.getType(), right.getType()),
BOOLEAN,
left,
right);
}
@Override
protected RowExpression visitFunctionCall(FunctionCall node, Void context)
{
List<RowExpression> arguments = node.getArguments().stream()
.map(value -> process(value, context))
.collect(toImmutableList());
List<TypeSignature> argumentTypes = arguments.stream()
.map(RowExpression::getType)
.map(Type::getTypeSignature)
.collect(toImmutableList());
Signature signature = new Signature(node.getName().getSuffix(), functionKind, types.get(node).getTypeSignature(), argumentTypes);
return call(signature, types.get(node), arguments);
}
@Override
protected RowExpression visitSymbolReference(SymbolReference node, Void context)
{
return new VariableReferenceExpression(node.getName(), types.get(node));
}
@Override
protected RowExpression visitLambdaExpression(LambdaExpression node, Void context)
{
RowExpression body = process(node.getBody(), context);
Type type = types.get(node);
List<Type> typeParameters = type.getTypeParameters();
List<Type> argumentTypes = typeParameters.subList(0, typeParameters.size() - 1);
List<String> argumentNames = node.getArguments().stream()
.map(LambdaArgumentDeclaration::getName)
.collect(toImmutableList());
return new LambdaDefinitionExpression(argumentTypes, argumentNames, body);
}
@Override
protected RowExpression visitArithmeticBinary(ArithmeticBinaryExpression node, Void context)
{
RowExpression left = process(node.getLeft(), context);
RowExpression right = process(node.getRight(), context);
return call(
arithmeticExpressionSignature(node.getType(), types.get(node), left.getType(), right.getType()),
types.get(node),
left,
right);
}
@Override
protected RowExpression visitArithmeticUnary(ArithmeticUnaryExpression node, Void context)
{
RowExpression expression = process(node.getValue(), context);
switch (node.getSign()) {
case PLUS:
return expression;
case MINUS:
return call(
arithmeticNegationSignature(types.get(node), expression.getType()),
types.get(node),
expression);
}
throw new UnsupportedOperationException("Unsupported unary operator: " + node.getSign());
}
@Override
protected RowExpression visitLogicalBinaryExpression(LogicalBinaryExpression node, Void context)
{
return call(
logicalExpressionSignature(node.getType()),
BOOLEAN,
process(node.getLeft(), context),
process(node.getRight(), context));
}
@Override
protected RowExpression visitCast(Cast node, Void context)
{
RowExpression value = process(node.getExpression(), context);
if (node.isTypeOnly()) {
return changeType(value, types.get(node));
}
if (node.isSafe()) {
return call(tryCastSignature(types.get(node), value.getType()), types.get(node), value);
}
return call(castSignature(types.get(node), value.getType()), types.get(node), value);
}
private static RowExpression changeType(RowExpression value, Type targetType)
{
ChangeTypeVisitor visitor = new ChangeTypeVisitor(targetType);
return value.accept(visitor, null);
}
private static class ChangeTypeVisitor
implements RowExpressionVisitor<Void, RowExpression>
{
private final Type targetType;
private ChangeTypeVisitor(Type targetType)
{
this.targetType = targetType;
}
@Override
public RowExpression visitCall(CallExpression call, Void context)
{
return new CallExpression(call.getSignature(), targetType, call.getArguments());
}
@Override
public RowExpression visitInputReference(InputReferenceExpression reference, Void context)
{
return new InputReferenceExpression(reference.getField(), targetType);
}
@Override
public RowExpression visitConstant(ConstantExpression literal, Void context)
{
return new ConstantExpression(literal.getValue(), targetType);
}
@Override
public RowExpression visitLambda(LambdaDefinitionExpression lambda, Void context)
{
throw new UnsupportedOperationException();
}
@Override
public RowExpression visitVariableReference(VariableReferenceExpression reference, Void context)
{
return new VariableReferenceExpression(reference.getName(), targetType);
}
}
@Override
protected RowExpression visitCoalesceExpression(CoalesceExpression node, Void context)
{
List<RowExpression> arguments = node.getOperands().stream()
.map(value -> process(value, context))
.collect(toImmutableList());
List<Type> argumentTypes = arguments.stream().map(RowExpression::getType).collect(toImmutableList());
return call(coalesceSignature(types.get(node), argumentTypes), types.get(node), arguments);
}
@Override
protected RowExpression visitSimpleCaseExpression(SimpleCaseExpression node, Void context)
{
ImmutableList.Builder<RowExpression> arguments = ImmutableList.builder();
arguments.add(process(node.getOperand(), context));
for (WhenClause clause : node.getWhenClauses()) {
arguments.add(call(whenSignature(types.get(clause)),
types.get(clause),
process(clause.getOperand(), context),
process(clause.getResult(), context)));
}
Type returnType = types.get(node);
arguments.add(node.getDefaultValue()
.map((value) -> process(value, context))
.orElse(constantNull(returnType)));
return call(switchSignature(returnType), returnType, arguments.build());
}
@Override
protected RowExpression visitSearchedCaseExpression(SearchedCaseExpression node, Void context)
{
/*
Translates an expression like:
case when cond1 then value1
when cond2 then value2
when cond3 then value3
else value4
end
To:
IF(cond1,
value1,
IF(cond2,
value2,
If(cond3,
value3,
value4)))
*/
RowExpression expression = node.getDefaultValue()
.map((value) -> process(value, context))
.orElse(constantNull(types.get(node)));
for (WhenClause clause : Lists.reverse(node.getWhenClauses())) {
expression = call(
Signatures.ifSignature(types.get(node)),
types.get(node),
process(clause.getOperand(), context),
process(clause.getResult(), context),
expression);
}
return expression;
}
@Override
protected RowExpression visitDereferenceExpression(DereferenceExpression node, Void context)
{
RowType rowType = checkType(types.get(node.getBase()), RowType.class, "type");
List<RowField> fields = rowType.getFields();
int index = -1;
for (int i = 0; i < fields.size(); i++) {
RowField field = fields.get(i);
if (field.getName().isPresent() && field.getName().get().equalsIgnoreCase(node.getFieldName())) {
checkArgument(index < 0, "Ambiguous field %s in type %s", field, rowType.getDisplayName());
index = i;
}
}
checkState(index >= 0, "could not find field name: %s", node.getFieldName());
Type returnType = types.get(node);
return call(dereferenceSignature(returnType, rowType), returnType, process(node.getBase(), context), constant(index, INTEGER));
}
@Override
protected RowExpression visitIfExpression(IfExpression node, Void context)
{
ImmutableList.Builder<RowExpression> arguments = ImmutableList.builder();
arguments.add(process(node.getCondition(), context))
.add(process(node.getTrueValue(), context));
if (node.getFalseValue().isPresent()) {
arguments.add(process(node.getFalseValue().get(), context));
}
else {
arguments.add(constantNull(types.get(node)));
}
return call(Signatures.ifSignature(types.get(node)), types.get(node), arguments.build());
}
@Override
protected RowExpression visitTryExpression(TryExpression node, Void context)
{
return call(Signatures.trySignature(types.get(node)), types.get(node), process(node.getInnerExpression(), context));
}
@Override
protected RowExpression visitInPredicate(InPredicate node, Void context)
{
ImmutableList.Builder<RowExpression> arguments = ImmutableList.builder();
arguments.add(process(node.getValue(), context));
InListExpression values = (InListExpression) node.getValueList();
for (Expression value : values.getValues()) {
arguments.add(process(value, context));
}
return call(Signatures.inSignature(), BOOLEAN, arguments.build());
}
@Override
protected RowExpression visitIsNotNullPredicate(IsNotNullPredicate node, Void context)
{
RowExpression expression = process(node.getValue(), context);
return call(
Signatures.notSignature(),
BOOLEAN,
call(Signatures.isNullSignature(expression.getType()), BOOLEAN, ImmutableList.of(expression)));
}
@Override
protected RowExpression visitIsNullPredicate(IsNullPredicate node, Void context)
{
RowExpression expression = process(node.getValue(), context);
return call(Signatures.isNullSignature(expression.getType()), BOOLEAN, expression);
}
@Override
protected RowExpression visitNotExpression(NotExpression node, Void context)
{
return call(Signatures.notSignature(), BOOLEAN, process(node.getValue(), context));
}
@Override
protected RowExpression visitNullIfExpression(NullIfExpression node, Void context)
{
RowExpression first = process(node.getFirst(), context);
RowExpression second = process(node.getSecond(), context);
return call(
nullIfSignature(types.get(node), first.getType(), second.getType()),
types.get(node),
first,
second);
}
@Override
protected RowExpression visitBetweenPredicate(BetweenPredicate node, Void context)
{
RowExpression value = process(node.getValue(), context);
RowExpression min = process(node.getMin(), context);
RowExpression max = process(node.getMax(), context);
return call(
betweenSignature(value.getType(), min.getType(), max.getType()),
BOOLEAN,
value,
min,
max);
}
@Override
protected RowExpression visitLikePredicate(LikePredicate node, Void context)
{
RowExpression value = process(node.getValue(), context);
RowExpression pattern = process(node.getPattern(), context);
if (node.getEscape() != null) {
RowExpression escape = process(node.getEscape(), context);
return call(likeSignature(), BOOLEAN, value, call(likePatternSignature(), LIKE_PATTERN, pattern, escape));
}
return call(likeSignature(), BOOLEAN, value, call(castSignature(LIKE_PATTERN, VARCHAR), LIKE_PATTERN, pattern));
}
@Override
protected RowExpression visitSubscriptExpression(SubscriptExpression node, Void context)
{
RowExpression base = process(node.getBase(), context);
RowExpression index = process(node.getIndex(), context);
return call(
subscriptSignature(types.get(node), base.getType(), index.getType()),
types.get(node),
base,
index);
}
@Override
protected RowExpression visitArrayConstructor(ArrayConstructor node, Void context)
{
List<RowExpression> arguments = node.getValues().stream()
.map(value -> process(value, context))
.collect(toImmutableList());
List<Type> argumentTypes = arguments.stream()
.map(RowExpression::getType)
.collect(toImmutableList());
return call(arrayConstructorSignature(types.get(node), argumentTypes), types.get(node), arguments);
}
@Override
protected RowExpression visitRow(Row node, Void context)
{
List<RowExpression> arguments = node.getItems().stream()
.map(value -> process(value, context))
.collect(toImmutableList());
Type returnType = types.get(node);
List<Type> argumentTypes = node.getItems().stream()
.map(value -> types.get(value))
.collect(toImmutableList());
return call(rowConstructorSignature(returnType, argumentTypes), returnType, arguments);
}
}
}
| marsorp/blog | presto166/presto-main/src/main/java/com/facebook/presto/sql/relational/SqlToRowExpressionTranslator.java | Java | apache-2.0 | 28,699 |
/* Copyright (c) 2012 Stanford University
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "RPC/OpaqueServerRPC.h"
#include "RPC/Server.h"
#include "RPC/ServerRPC.h"
#include "RPC/ThreadDispatchService.h"
namespace LogCabin {
namespace RPC {
////////// Server::RPCHandler //////////
Server::RPCHandler::RPCHandler(Server& server)
: server(server)
{
}
Server::RPCHandler::~RPCHandler()
{
}
void
Server::RPCHandler::handleRPC(OpaqueServerRPC opaqueRPC)
{
ServerRPC rpc(std::move(opaqueRPC));
if (!rpc.needsReply()) {
// The RPC may have had an invalid header, in which case it needs no
// further action.
return;
}
std::shared_ptr<Service> service;
{
std::lock_guard<std::mutex> lockGuard(server.mutex);
auto it = server.services.find(rpc.getService());
if (it != server.services.end())
service = it->second;
}
if (service)
service->handleRPC(std::move(rpc));
else
rpc.rejectInvalidService();
}
////////// Server //////////
Server::Server(Event::Loop& eventLoop, uint32_t maxMessageLength)
: mutex()
, services()
, rpcHandler(*this)
, opaqueServer(rpcHandler, eventLoop, maxMessageLength)
{
}
Server::~Server()
{
}
std::string
Server::bind(const Address& listenAddress)
{
return opaqueServer.bind(listenAddress);
}
void
Server::registerService(uint16_t serviceId,
std::shared_ptr<Service> service,
uint32_t maxThreads)
{
std::lock_guard<std::mutex> lockGuard(mutex);
services[serviceId] =
std::make_shared<ThreadDispatchService>(service, 0, maxThreads);
}
} // namespace LogCabin::RPC
} // namespace LogCabin
| Ghatage/peloton | third_party/logcabin/RPC/Server.cc | C++ | apache-2.0 | 2,408 |
#region License
/*
* Copyright 2002-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.
*/
#endregion
using System;
using Spring.Core.TypeResolution;
using Spring.Objects.Factory;
using Spring.Objects.Factory.Config;
using Spring.Util;
using TIBCO.EMS;
using Common.Logging;
namespace Spring.Messaging.Ems.Jndi
{
public class JndiLookupFactoryObject : JndiObjectLocator, IConfigurableFactoryObject
{
static JndiLookupFactoryObject()
{
TypeRegistry.RegisterType("LookupContext", typeof(LookupContext));
TypeRegistry.RegisterType("JndiContextType", typeof(JndiContextType));
}
private object defaultObject;
private Object jndiObject;
private IObjectDefinition productTemplate;
public JndiLookupFactoryObject()
{
this.logger = LogManager.GetLogger(GetType());
}
/// <summary>
/// Sets the default object to fall back to if the JNDI lookup fails.
/// Default is none.
/// </summary>
/// <remarks>
/// <para>This can be an arbitrary bean reference or literal value.
/// It is typically used for literal values in scenarios where the JNDI environment
/// might define specific config settings but those are not required to be present.
/// </para>
/// </remarks>
/// <value>The default object to use when lookup fails.</value>
public object DefaultObject
{
set { defaultObject = value; }
}
#region Implementation of IFactoryObject
/// <summary>
/// Return the Jndi object
/// </summary>
/// <returns>The Jndi object</returns>
public object GetObject()
{
return this.jndiObject;
}
/// <summary>
/// Return type of object retrieved from Jndi or the expected type if the Jndi retrieval
/// did not succeed.
/// </summary>
/// <value>Return value of retrieved object</value>
public Type ObjectType
{
get
{
if (this.jndiObject != null)
{
return this.jndiObject.GetType();
}
return ExpectedType;
}
}
/// <summary>
/// Returns true
/// </summary>
public bool IsSingleton
{
get { return true; }
}
#endregion
public override void AfterPropertiesSet()
{
base.AfterPropertiesSet();
TypeRegistry.RegisterType("LookupContext", typeof(LookupContext));
if (this.defaultObject != null && ExpectedType != null &&
!ObjectUtils.IsAssignable(ExpectedType, this.defaultObject))
{
throw new ArgumentException("Default object [" + this.defaultObject +
"] of type [" + this.defaultObject.GetType().Name +
"] is not of expected type [" + ExpectedType.Name + "]");
}
// Locate specified JNDI object.
this.jndiObject = LookupWithFallback();
}
protected virtual object LookupWithFallback()
{
try
{
return Lookup();
}
catch (TypeMismatchNamingException)
{
// Always let TypeMismatchNamingException through -
// we don't want to fall back to the defaultObject in this case.
throw;
}
catch (NamingException ex)
{
if (this.defaultObject != null)
{
if (logger.IsDebugEnabled)
{
logger.Debug("JNDI lookup failed - returning specified default object instead", ex);
}
else if (logger.IsInfoEnabled)
{
logger.Info("JNDI lookup failed - returning specified default object instead: " + ex);
}
return this.defaultObject;
}
throw;
}
}
/// <summary>
/// Gets the template object definition that should be used
/// to configure the instance of the object managed by this factory.
/// </summary>
/// <value></value>
public IObjectDefinition ProductTemplate
{
get { return productTemplate; }
set { productTemplate = value; }
}
}
} | dreamofei/spring-net | src/Spring/Spring.Messaging.Ems/Messaging/Ems/Jndi/JndiLookupFactoryObject.cs | C# | apache-2.0 | 5,343 |
# typed: false
# frozen_string_literal: true
require "rubocops/bottle"
describe RuboCop::Cop::FormulaAudit::BottleTagIndentation do
subject(:cop) { described_class.new }
it "reports no offenses for `bottle :uneeded`" do
expect_no_offenses(<<~RUBY)
class Foo < Formula
url "https://brew.sh/foo-1.0.tgz"
bottle :unneeded
end
RUBY
end
it "reports no offenses for `bottle` blocks without cellars" do
expect_no_offenses(<<~RUBY)
class Foo < Formula
url "https://brew.sh/foo-1.0.tgz"
bottle do
rebuild 4
sha256 arm64_big_sur: "aaaaaaaa"
sha256 big_sur: "faceb00c"
sha256 catalina: "deadbeef"
end
end
RUBY
expect_no_offenses(<<~RUBY)
class Foo < Formula
url "https://brew.sh/foo-1.0.tgz"
bottle do
sha256 big_sur: "faceb00c"
end
end
RUBY
end
it "reports no offenses for properly aligned tags in `bottle` blocks with cellars" do
expect_no_offenses(<<~RUBY)
class Foo < Formula
url "https://brew.sh/foo-1.0.tgz"
bottle do
rebuild 4
sha256 cellar: :any, arm64_big_sur: "aaaaaaaa"
sha256 cellar: "/usr/local/Cellar", big_sur: "faceb00c"
sha256 catalina: "deadbeef"
end
end
RUBY
expect_no_offenses(<<~RUBY)
class Foo < Formula
url "https://brew.sh/foo-1.0.tgz"
bottle do
sha256 cellar: :any, arm64_big_sur: "aaaaaaaa"
end
end
RUBY
end
it "reports and corrects misaligned tags in `bottle` block with cellars" do
expect_offense(<<~RUBY)
class Foo < Formula
url "https://brew.sh/foo-1.0.tgz"
bottle do
rebuild 4
sha256 cellar: :any, arm64_big_sur: "aaaaaaaa"
^^^^^^^^^^^^^^^^^^^^^^^^^ Align bottle tags
sha256 cellar: "/usr/local/Cellar", big_sur: "faceb00c"
sha256 catalina: "deadbeef"
^^^^^^^^^^^^^^^^^^^^ Align bottle tags
end
end
RUBY
expect_correction(<<~RUBY)
class Foo < Formula
url "https://brew.sh/foo-1.0.tgz"
bottle do
rebuild 4
sha256 cellar: :any, arm64_big_sur: "aaaaaaaa"
sha256 cellar: "/usr/local/Cellar", big_sur: "faceb00c"
sha256 catalina: "deadbeef"
end
end
RUBY
end
end
| EricFromCanada/brew | Library/Homebrew/test/rubocops/bottle/bottle_tag_indentation_spec.rb | Ruby | bsd-2-clause | 2,538 |
<?php
class Kwc_Shop_Cart_Checkout_Payment_Abstract_OrderTable_Component extends Kwc_Abstract
{
public static function getSettings()
{
$ret = parent::getSettings();
$ret['viewCache'] = false;
return $ret;
}
public function getTemplateVars()
{
$ret = parent::getTemplateVars();
$ret['order'] = $this->_getOrder();
$ret['items'] = $ret['order']->getProductsData();
$items = $ret['order']->getChildRows('Products');
$ret['items'] = array();
$ret['additionalOrderDataHeaders'] = array();
foreach ($items as $i) {
$addComponent = Kwf_Component_Data_Root::getInstance()
->getComponentByDbId($i->add_component_id);
$additionalOrderData = $addComponent->getComponent()->getAdditionalOrderData($i);
foreach ($additionalOrderData as $d) {
if (!isset($ret['additionalOrderDataHeaders'][$d['name']])) {
$ret['additionalOrderDataHeaders'][$d['name']] = array(
'class' => $d['class'],
'text' => $d['name']
);
}
}
$ret['items'][] = (object)array(
'product' => $addComponent->parent,
'row' => $i,
'additionalOrderData' => $additionalOrderData,
'price' => $i->getProductPrice(),
'text' => $i->getProductText(),
);
}
$ret['sumRows'] = $this->_getSumRows($this->_getOrder());
$ret['tableFooterText'] = '';
$ret['footerText'] = '';
return $ret;
}
protected function _getOrder()
{
return Kwf_Model_Abstract::getInstance(Kwc_Abstract::getSetting($this->getData()->getParentByClass('Kwc_Shop_Cart_Component')->componentClass, 'childModel'))
->getReferencedModel('Order')->getCartOrder();
}
protected function _getSumRows($order)
{
return $this->getData()->parent->parent->getComponent()->getSumRows($order);
}
}
| yacon/koala-framework | Kwc/Shop/Cart/Checkout/Payment/Abstract/OrderTable/Component.php | PHP | bsd-2-clause | 2,091 |
package org.motechproject.mds.builder.impl;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtField;
import javassist.NotFoundException;
import org.apache.commons.lang.reflect.FieldUtils;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.motechproject.mds.annotations.internal.samples.AnotherSample;
import org.motechproject.mds.builder.EntityMetadataBuilder;
import org.motechproject.mds.builder.Sample;
import org.motechproject.mds.builder.SampleWithIncrementStrategy;
import org.motechproject.mds.domain.ClassData;
import org.motechproject.mds.domain.EntityType;
import org.motechproject.mds.domain.OneToManyRelationship;
import org.motechproject.mds.domain.OneToOneRelationship;
import org.motechproject.mds.dto.EntityDto;
import org.motechproject.mds.dto.FieldBasicDto;
import org.motechproject.mds.dto.FieldDto;
import org.motechproject.mds.dto.LookupDto;
import org.motechproject.mds.dto.LookupFieldDto;
import org.motechproject.mds.dto.LookupFieldType;
import org.motechproject.mds.dto.MetadataDto;
import org.motechproject.mds.dto.SchemaHolder;
import org.motechproject.mds.dto.TypeDto;
import org.motechproject.mds.javassist.MotechClassPool;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceModifier;
import javax.jdo.metadata.ClassMetadata;
import javax.jdo.metadata.ClassPersistenceModifier;
import javax.jdo.metadata.CollectionMetadata;
import javax.jdo.metadata.FieldMetadata;
import javax.jdo.metadata.ForeignKeyMetadata;
import javax.jdo.metadata.IndexMetadata;
import javax.jdo.metadata.InheritanceMetadata;
import javax.jdo.metadata.JDOMetadata;
import javax.jdo.metadata.PackageMetadata;
import javax.jdo.metadata.UniqueMetadata;
import java.util.ArrayList;
import java.util.List;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
import static org.motechproject.mds.testutil.FieldTestHelper.fieldDto;
import static org.motechproject.mds.util.Constants.MetadataKeys.RELATED_CLASS;
import static org.motechproject.mds.util.Constants.MetadataKeys.RELATED_FIELD;
import static org.motechproject.mds.util.Constants.Util.CREATION_DATE_DISPLAY_FIELD_NAME;
import static org.motechproject.mds.util.Constants.Util.CREATION_DATE_FIELD_NAME;
import static org.motechproject.mds.util.Constants.Util.CREATOR_DISPLAY_FIELD_NAME;
import static org.motechproject.mds.util.Constants.Util.CREATOR_FIELD_NAME;
import static org.motechproject.mds.util.Constants.Util.DATANUCLEUS;
import static org.motechproject.mds.util.Constants.Util.MODIFICATION_DATE_DISPLAY_FIELD_NAME;
import static org.motechproject.mds.util.Constants.Util.MODIFICATION_DATE_FIELD_NAME;
import static org.motechproject.mds.util.Constants.Util.MODIFIED_BY_DISPLAY_FIELD_NAME;
import static org.motechproject.mds.util.Constants.Util.MODIFIED_BY_FIELD_NAME;
import static org.motechproject.mds.util.Constants.Util.OWNER_DISPLAY_FIELD_NAME;
import static org.motechproject.mds.util.Constants.Util.OWNER_FIELD_NAME;
import static org.motechproject.mds.util.Constants.Util.VALUE_GENERATOR;
@RunWith(PowerMockRunner.class)
@PrepareForTest({MotechClassPool.class, FieldUtils.class})
public class EntityMetadataBuilderTest {
private static final String PACKAGE = "org.motechproject.mds.entity";
private static final String ENTITY_NAME = "Sample";
private static final String MODULE = "MrS";
private static final String NAMESPACE = "arrio";
private static final String TABLE_NAME = "";
private static final String CLASS_NAME = String.format("%s.%s", PACKAGE, ENTITY_NAME);
private static final String TABLE_NAME_1 = String.format("MDS_%s", ENTITY_NAME).toUpperCase();
private static final String TABLE_NAME_2 = String.format("%s_%s", MODULE, ENTITY_NAME).toUpperCase();
private static final String TABLE_NAME_3 = String.format("%s_%s_%s", MODULE, NAMESPACE, ENTITY_NAME).toUpperCase();
private EntityMetadataBuilder entityMetadataBuilder = new EntityMetadataBuilderImpl();
@Mock
private EntityDto entity;
@Mock
private FieldDto idField;
@Mock
private JDOMetadata jdoMetadata;
@Mock
private PackageMetadata packageMetadata;
@Mock
private ClassMetadata classMetadata;
@Mock
private FieldMetadata idMetadata;
@Mock
private InheritanceMetadata inheritanceMetadata;
@Mock
private IndexMetadata indexMetadata;
@Mock
private SchemaHolder schemaHolder;
@Before
public void setUp() {
initMocks(this);
when(entity.getClassName()).thenReturn(CLASS_NAME);
when(classMetadata.newFieldMetadata("id")).thenReturn(idMetadata);
when(idMetadata.getName()).thenReturn("id");
when(classMetadata.newInheritanceMetadata()).thenReturn(inheritanceMetadata);
when(schemaHolder.getFieldByName(entity, "id")).thenReturn(idField);
when(entity.isBaseEntity()).thenReturn(true);
}
@Test
public void shouldAddEntityMetadata() throws Exception {
when(entity.getName()).thenReturn(ENTITY_NAME);
when(entity.getModule()).thenReturn(MODULE);
when(entity.getNamespace()).thenReturn(NAMESPACE);
when(entity.getTableName()).thenReturn(TABLE_NAME);
when(jdoMetadata.newPackageMetadata(PACKAGE)).thenReturn(packageMetadata);
when(packageMetadata.newClassMetadata(ENTITY_NAME)).thenReturn(classMetadata);
entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, Sample.class, schemaHolder);
verify(jdoMetadata).newPackageMetadata(PACKAGE);
verify(packageMetadata).newClassMetadata(ENTITY_NAME);
verify(classMetadata).setTable(TABLE_NAME_3);
verifyCommonClassMetadata();
}
@Test
public void shouldAddToAnExistingPackage() {
when(entity.getName()).thenReturn(ENTITY_NAME);
when(entity.getTableName()).thenReturn(TABLE_NAME);
when(jdoMetadata.getPackages()).thenReturn(new PackageMetadata[]{packageMetadata});
when(packageMetadata.getName()).thenReturn(PACKAGE);
when(packageMetadata.newClassMetadata(ENTITY_NAME)).thenReturn(classMetadata);
entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, Sample.class, schemaHolder);
verify(jdoMetadata, never()).newPackageMetadata(PACKAGE);
verify(jdoMetadata).getPackages();
verify(packageMetadata).newClassMetadata(ENTITY_NAME);
verify(classMetadata).setTable(TABLE_NAME_1);
verifyCommonClassMetadata();
}
@Test
public void shouldSetAppropriateTableName() throws Exception {
when(entity.getName()).thenReturn(ENTITY_NAME);
when(entity.getTableName()).thenReturn(TABLE_NAME);
when(jdoMetadata.newPackageMetadata(anyString())).thenReturn(packageMetadata);
when(packageMetadata.newClassMetadata(anyString())).thenReturn(classMetadata);
entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, Sample.class, schemaHolder);
verify(classMetadata).setTable(TABLE_NAME_1);
when(entity.getModule()).thenReturn(MODULE);
entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, Sample.class, schemaHolder);
verify(classMetadata).setTable(TABLE_NAME_2);
when(entity.getNamespace()).thenReturn(NAMESPACE);
entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, Sample.class, schemaHolder);
verify(classMetadata).setTable(TABLE_NAME_3);
}
@Test
public void shouldAddBaseEntityMetadata() throws Exception {
CtField ctField = mock(CtField.class);
CtClass ctClass = mock(CtClass.class);
CtClass superClass = mock(CtClass.class);
ClassData classData = mock(ClassData.class);
ClassPool pool = mock(ClassPool.class);
PowerMockito.mockStatic(MotechClassPool.class);
PowerMockito.when(MotechClassPool.getDefault()).thenReturn(pool);
when(classData.getClassName()).thenReturn(CLASS_NAME);
when(classData.getModule()).thenReturn(MODULE);
when(classData.getNamespace()).thenReturn(NAMESPACE);
when(entity.getTableName()).thenReturn(TABLE_NAME);
when(pool.getOrNull(CLASS_NAME)).thenReturn(ctClass);
when(ctClass.getField("id")).thenReturn(ctField);
when(ctClass.getSuperclass()).thenReturn(superClass);
when(superClass.getName()).thenReturn(Object.class.getName());
when(jdoMetadata.newPackageMetadata(PACKAGE)).thenReturn(packageMetadata);
when(packageMetadata.newClassMetadata(ENTITY_NAME)).thenReturn(classMetadata);
entityMetadataBuilder.addBaseMetadata(jdoMetadata, classData, EntityType.STANDARD, Sample.class);
verify(jdoMetadata).newPackageMetadata(PACKAGE);
verify(packageMetadata).newClassMetadata(ENTITY_NAME);
verify(classMetadata).setTable(TABLE_NAME_3);
verifyCommonClassMetadata();
}
@Test
public void shouldAddOneToManyRelationshipMetadata() {
FieldDto oneToManyField = fieldDto("oneToManyName", OneToManyRelationship.class);
oneToManyField.addMetadata(new MetadataDto(RELATED_CLASS, "org.motechproject.test.MyClass"));
FieldMetadata fmd = mock(FieldMetadata.class);
CollectionMetadata collMd = mock(CollectionMetadata.class);
when(entity.getName()).thenReturn(ENTITY_NAME);
when(entity.getId()).thenReturn(2L);
when(schemaHolder.getFields(entity)).thenReturn(singletonList(oneToManyField));
when(entity.getTableName()).thenReturn(TABLE_NAME);
when(jdoMetadata.newPackageMetadata(PACKAGE)).thenReturn(packageMetadata);
when(packageMetadata.newClassMetadata(ENTITY_NAME)).thenReturn(classMetadata);
when(classMetadata.newFieldMetadata("oneToManyName")).thenReturn(fmd);
when(fmd.getCollectionMetadata()).thenReturn(collMd);
when(fmd.getName()).thenReturn("oneToManyName");
entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, Sample.class, schemaHolder);
verifyCommonClassMetadata();
verify(fmd).setDefaultFetchGroup(true);
verify(collMd).setEmbeddedElement(false);
verify(collMd).setSerializedElement(false);
verify(collMd).setElementType("org.motechproject.test.MyClass");
}
@Test
public void shouldAddOneToOneRelationshipMetadata() throws NotFoundException, CannotCompileException {
final String relClassName = "org.motechproject.test.MyClass";
final String relFieldName = "myField";
FieldDto oneToOneField = fieldDto("oneToOneName", OneToOneRelationship.class);
oneToOneField.addMetadata(new MetadataDto(RELATED_CLASS, relClassName));
oneToOneField.addMetadata(new MetadataDto(RELATED_FIELD, relFieldName));
FieldMetadata fmd = mock(FieldMetadata.class);
when(fmd.getName()).thenReturn("oneToOneName");
ForeignKeyMetadata fkmd = mock(ForeignKeyMetadata.class);
when(entity.getName()).thenReturn(ENTITY_NAME);
when(entity.getId()).thenReturn(3L);
when(schemaHolder.getFields(entity)).thenReturn(singletonList(oneToOneField));
when(entity.getTableName()).thenReturn(TABLE_NAME);
when(jdoMetadata.newPackageMetadata(PACKAGE)).thenReturn(packageMetadata);
when(packageMetadata.newClassMetadata(ENTITY_NAME)).thenReturn(classMetadata);
when(classMetadata.newFieldMetadata("oneToOneName")).thenReturn(fmd);
when(fmd.newForeignKeyMetadata()).thenReturn(fkmd);
/* We simulate configuration for the bi-directional relationship (the related class has got
a field that links back to the main class) */
CtClass myClass = mock(CtClass.class);
CtClass relatedClass = mock(CtClass.class);
CtField myField = mock(CtField.class);
CtField relatedField = mock(CtField.class);
when(myClass.getName()).thenReturn(relClassName);
when(myClass.getDeclaredFields()).thenReturn(new CtField[]{myField});
when(myField.getType()).thenReturn(relatedClass);
when(myField.getName()).thenReturn(relFieldName);
when(relatedClass.getDeclaredFields()).thenReturn(new CtField[]{relatedField});
when(relatedClass.getName()).thenReturn(CLASS_NAME);
entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, Sample.class, schemaHolder);
verifyCommonClassMetadata();
verify(fmd).setDefaultFetchGroup(true);
verify(fmd).setPersistenceModifier(PersistenceModifier.PERSISTENT);
verify(fkmd).setName("fk_Sample_oneToOneName_3");
}
@Test
public void shouldSetIndexOnMetadataLookupField() throws Exception {
FieldDto lookupField = fieldDto("lookupField", String.class);
LookupDto lookup = new LookupDto();
lookup.setLookupName("A lookup");
lookup.setLookupFields(singletonList(new LookupFieldDto("lookupField", LookupFieldType.VALUE)));
lookup.setIndexRequired(true);
lookupField.setLookups(singletonList(lookup));
FieldMetadata fmd = mock(FieldMetadata.class);
when(entity.getName()).thenReturn(ENTITY_NAME);
when(entity.getId()).thenReturn(14L);
when(schemaHolder.getFields(entity)).thenReturn(singletonList(lookupField));
when(entity.getTableName()).thenReturn(TABLE_NAME);
when(jdoMetadata.newPackageMetadata(PACKAGE)).thenReturn(packageMetadata);
when(packageMetadata.newClassMetadata(ENTITY_NAME)).thenReturn(classMetadata);
when(classMetadata.newFieldMetadata("lookupField")).thenReturn(fmd);
when(fmd.newIndexMetadata()).thenReturn(indexMetadata);
PowerMockito.mockStatic(FieldUtils.class);
when(FieldUtils.getDeclaredField(eq(Sample.class), anyString(), eq(true))).thenReturn(Sample.class.getDeclaredField("notInDefFg"));
entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, Sample.class, schemaHolder);
verifyCommonClassMetadata();
verify(fmd).newIndexMetadata();
verify(indexMetadata).setName("lkp_idx_" + ENTITY_NAME + "_lookupField_14");
}
@Test
public void shouldAddObjectValueGeneratorToAppropriateFields() throws Exception {
when(entity.getName()).thenReturn(ENTITY_NAME);
when(entity.getTableName()).thenReturn(TABLE_NAME);
when(jdoMetadata.newPackageMetadata(anyString())).thenReturn(packageMetadata);
when(packageMetadata.newClassMetadata(anyString())).thenReturn(classMetadata);
List<FieldDto> fields = new ArrayList<>();
// for these fields the appropriate generator should be added
fields.add(fieldDto(1L, CREATOR_FIELD_NAME, String.class.getName(), CREATOR_DISPLAY_FIELD_NAME, null));
fields.add(fieldDto(2L, OWNER_FIELD_NAME, String.class.getName(), OWNER_DISPLAY_FIELD_NAME, null));
fields.add(fieldDto(3L, CREATION_DATE_FIELD_NAME, DateTime.class.getName(), CREATION_DATE_DISPLAY_FIELD_NAME, null));
fields.add(fieldDto(4L, MODIFIED_BY_FIELD_NAME, String.class.getName(), MODIFIED_BY_DISPLAY_FIELD_NAME, null));
fields.add(fieldDto(5L, MODIFICATION_DATE_FIELD_NAME, DateTime.class.getName(), MODIFICATION_DATE_DISPLAY_FIELD_NAME, null));
doReturn(fields).when(schemaHolder).getFields(CLASS_NAME);
final List<FieldMetadata> list = new ArrayList<>();
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
// we create a mock ...
FieldMetadata metadata = mock(FieldMetadata.class);
// ... and it should return correct name
doReturn(invocation.getArguments()[0]).when(metadata).getName();
// Because we want to check that appropriate methods was executed
// we added metadata to list and later we will verify conditions
list.add(metadata);
// in the end we have to return the mock
return metadata;
}
}).when(classMetadata).newFieldMetadata(anyString());
PowerMockito.mockStatic(FieldUtils.class);
when(FieldUtils.getDeclaredField(eq(Sample.class), anyString(), eq(true))).thenReturn(Sample.class.getDeclaredField("notInDefFg"));
entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, Sample.class, schemaHolder);
for (FieldMetadata metadata : list) {
String name = metadata.getName();
// the id field should not have set object value generator metadata
int invocations = "id".equalsIgnoreCase(name) ? 0 : 1;
verify(classMetadata).newFieldMetadata(name);
verify(metadata, times(invocations)).setPersistenceModifier(PersistenceModifier.PERSISTENT);
verify(metadata, times(invocations)).setDefaultFetchGroup(true);
verify(metadata, times(invocations)).newExtensionMetadata(DATANUCLEUS, VALUE_GENERATOR, "ovg." + name);
}
}
@Test
public void shouldNotSetDefaultInheritanceStrategyIfUserDefinedOwn() {
when(entity.getName()).thenReturn(ENTITY_NAME);
when(entity.getTableName()).thenReturn(TABLE_NAME);
when(jdoMetadata.newPackageMetadata(anyString())).thenReturn(packageMetadata);
when(packageMetadata.newClassMetadata(anyString())).thenReturn(classMetadata);
entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, AnotherSample.class, schemaHolder);
verifyZeroInteractions(inheritanceMetadata);
}
@Test
public void shouldNotSetDefaultFetchGroupIfSpecified() {
when(entity.getName()).thenReturn(ENTITY_NAME);
when(entity.getTableName()).thenReturn(TABLE_NAME);
when(jdoMetadata.newPackageMetadata(anyString())).thenReturn(packageMetadata);
when(packageMetadata.newClassMetadata(anyString())).thenReturn(classMetadata);
FieldDto field = fieldDto("notInDefFg", OneToOneRelationship.class);
when(schemaHolder.getFields(CLASS_NAME)).thenReturn(singletonList(field));
FieldMetadata fmd = mock(FieldMetadata.class);
when(fmd.getName()).thenReturn("notInDefFg");
when(classMetadata.newFieldMetadata("notInDefFg")).thenReturn(fmd);
entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, Sample.class, schemaHolder);
verify(fmd, never()).setDefaultFetchGroup(anyBoolean());
}
@Test
public void shouldMarkEudeFieldsAsUnique() {
when(entity.getName()).thenReturn(ENTITY_NAME);
when(jdoMetadata.newPackageMetadata(anyString())).thenReturn(packageMetadata);
when(packageMetadata.newClassMetadata(anyString())).thenReturn(classMetadata);
FieldDto eudeField = mock(FieldDto.class);
FieldBasicDto eudeBasic = mock(FieldBasicDto.class);
when(eudeField.getBasic()).thenReturn(eudeBasic);
when(eudeBasic.getName()).thenReturn("uniqueField");
when(eudeField.isReadOnly()).thenReturn(false);
when(eudeBasic.isUnique()).thenReturn(true);
when(eudeField.getType()).thenReturn(TypeDto.STRING);
FieldDto ddeField = mock(FieldDto.class);
FieldBasicDto ddeBasic = mock(FieldBasicDto.class);
when(ddeField.getBasic()).thenReturn(ddeBasic);
when(ddeBasic.getName()).thenReturn("uniqueField2");
when(ddeField.isReadOnly()).thenReturn(true);
when(ddeBasic.isUnique()).thenReturn(true);
when(ddeField.getType()).thenReturn(TypeDto.STRING);
when(schemaHolder.getFields(entity)).thenReturn(asList(ddeField, eudeField));
FieldMetadata fmdEude = mock(FieldMetadata.class);
when(fmdEude.getName()).thenReturn("uniqueField");
when(classMetadata.newFieldMetadata("uniqueField")).thenReturn(fmdEude);
FieldMetadata fmdDde = mock(FieldMetadata.class);
when(fmdDde.getName()).thenReturn("uniqueField2");
when(classMetadata.newFieldMetadata("uniqueField2")).thenReturn(fmdDde);
UniqueMetadata umd = mock(UniqueMetadata.class);
when(fmdEude.newUniqueMetadata()).thenReturn(umd);
entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, Sample.class, schemaHolder);
verify(fmdDde, never()).newUniqueMetadata();
verify(fmdDde, never()).setUnique(anyBoolean());
verify(fmdEude).newUniqueMetadata();
verify(umd).setName("unq_Sample_uniqueField");
}
@Test
public void shouldSetIncrementStrategy() {
when(entity.getName()).thenReturn(ENTITY_NAME);
when(entity.getModule()).thenReturn(MODULE);
when(entity.getNamespace()).thenReturn(NAMESPACE);
when(entity.getTableName()).thenReturn(TABLE_NAME);
when(jdoMetadata.newPackageMetadata(PACKAGE)).thenReturn(packageMetadata);
when(packageMetadata.newClassMetadata(ENTITY_NAME)).thenReturn(classMetadata);
entityMetadataBuilder.addEntityMetadata(jdoMetadata, entity, SampleWithIncrementStrategy.class, schemaHolder);
verify(jdoMetadata).newPackageMetadata(PACKAGE);
verify(packageMetadata).newClassMetadata(ENTITY_NAME);
verify(classMetadata).setTable(TABLE_NAME_3);
verifyCommonClassMetadata(IdGeneratorStrategy.INCREMENT);
}
private void verifyCommonClassMetadata() {
verifyCommonClassMetadata(IdGeneratorStrategy.NATIVE);
}
private void verifyCommonClassMetadata(IdGeneratorStrategy expextedStrategy) {
verify(classMetadata).setDetachable(true);
verify(classMetadata).setIdentityType(IdentityType.APPLICATION);
verify(classMetadata).setPersistenceModifier(ClassPersistenceModifier.PERSISTENCE_CAPABLE);
verify(idMetadata).setPrimaryKey(true);
verify(idMetadata).setValueStrategy(expextedStrategy);
verify(inheritanceMetadata).setCustomStrategy("complete-table");
}
}
| sebbrudzinski/motech | platform/mds/mds/src/test/java/org/motechproject/mds/builder/impl/EntityMetadataBuilderTest.java | Java | bsd-3-clause | 22,796 |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Variable = void 0;
const VariableBase_1 = require("./VariableBase");
/**
* A Variable represents a locally scoped identifier. These include arguments to functions.
*/
class Variable extends VariableBase_1.VariableBase {
/**
* `true` if the variable is valid in a type context, false otherwise
* @public
*/
get isTypeVariable() {
if (this.defs.length === 0) {
// we don't statically know whether this is a type or a value
return true;
}
return this.defs.some(def => def.isTypeDefinition);
}
/**
* `true` if the variable is valid in a value context, false otherwise
* @public
*/
get isValueVariable() {
if (this.defs.length === 0) {
// we don't statically know whether this is a type or a value
return true;
}
return this.defs.some(def => def.isVariableDefinition);
}
}
exports.Variable = Variable;
//# sourceMappingURL=Variable.js.map | ChromeDevTools/devtools-frontend | node_modules/@typescript-eslint/scope-manager/dist/variable/Variable.js | JavaScript | bsd-3-clause | 1,070 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Orchard.Forms")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Orchard")]
[assembly: AssemblyCopyright("Copyright © Outercurve Foundation 2009")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("7d9d33f6-ee65-4d41-b4c3-edbadaf0a658")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.7")]
[assembly: AssemblyFileVersion("1.7")]
| cryogen/orchard | src/Orchard.Web/Modules/Orchard.Forms/Properties/AssemblyInfo.cs | C# | bsd-3-clause | 1,391 |
//
// Copyright 2015 The ANGLE 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 "test_utils/ANGLETest.h"
using namespace angle;
class MaxTextureSizeTest : public ANGLETest
{
protected:
MaxTextureSizeTest()
{
setWindowWidth(512);
setWindowHeight(512);
setConfigRedBits(8);
setConfigGreenBits(8);
setConfigBlueBits(8);
setConfigAlphaBits(8);
}
virtual void SetUp()
{
ANGLETest::SetUp();
const std::string vsSource = SHADER_SOURCE
(
precision highp float;
attribute vec4 position;
varying vec2 texcoord;
void main()
{
gl_Position = position;
texcoord = (position.xy * 0.5) + 0.5;
}
);
const std::string textureFSSource = SHADER_SOURCE
(
precision highp float;
uniform sampler2D tex;
varying vec2 texcoord;
void main()
{
gl_FragColor = texture2D(tex, texcoord);
}
);
const std::string blueFSSource = SHADER_SOURCE
(
precision highp float;
void main()
{
gl_FragColor = vec4(0.0, 0.0, 1.0, 1.0);
}
);
mTextureProgram = CompileProgram(vsSource, textureFSSource);
mBlueProgram = CompileProgram(vsSource, blueFSSource);
if (mTextureProgram == 0 || mBlueProgram == 0)
{
FAIL() << "shader compilation failed.";
}
mTextureUniformLocation = glGetUniformLocation(mTextureProgram, "tex");
glGetIntegerv(GL_MAX_TEXTURE_SIZE, &mMaxTexture2DSize);
glGetIntegerv(GL_MAX_CUBE_MAP_TEXTURE_SIZE, &mMaxTextureCubeSize);
glGetIntegerv(GL_MAX_RENDERBUFFER_SIZE, &mMaxRenderbufferSize);
ASSERT_GL_NO_ERROR();
}
virtual void TearDown()
{
glDeleteProgram(mTextureProgram);
glDeleteProgram(mBlueProgram);
ANGLETest::TearDown();
}
GLuint mTextureProgram;
GLint mTextureUniformLocation;
GLuint mBlueProgram;
GLint mMaxTexture2DSize;
GLint mMaxTextureCubeSize;
GLint mMaxRenderbufferSize;
};
TEST_P(MaxTextureSizeTest, SpecificationTexImage)
{
GLuint tex;
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
GLsizei textureWidth = mMaxTexture2DSize;
GLsizei textureHeight = 64;
std::vector<GLubyte> data(textureWidth * textureHeight * 4);
for (int y = 0; y < textureHeight; y++)
{
for (int x = 0; x < textureWidth; x++)
{
GLubyte* pixel = &data[0] + ((y * textureWidth + x) * 4);
// Draw a gradient, red in direction, green in y direction
pixel[0] = static_cast<GLubyte>((float(x) / textureWidth) * 255);
pixel[1] = static_cast<GLubyte>((float(y) / textureHeight) * 255);
pixel[2] = 0;
pixel[3] = 255;
}
}
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, textureWidth, textureHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, &data[0]);
EXPECT_GL_NO_ERROR();
glUseProgram(mTextureProgram);
glUniform1i(mTextureUniformLocation, 0);
drawQuad(mTextureProgram, "position", 0.5f);
std::vector<GLubyte> pixels(getWindowWidth() * getWindowHeight() * 4);
glReadPixels(0, 0, getWindowWidth(), getWindowHeight(), GL_RGBA, GL_UNSIGNED_BYTE, &pixels[0]);
for (int y = 1; y < getWindowHeight(); y++)
{
for (int x = 1; x < getWindowWidth(); x++)
{
const GLubyte* prevPixel = &pixels[0] + (((y - 1) * getWindowWidth() + (x - 1)) * 4);
const GLubyte* curPixel = &pixels[0] + ((y * getWindowWidth() + x) * 4);
EXPECT_GE(curPixel[0], prevPixel[0]);
EXPECT_GE(curPixel[1], prevPixel[1]);
EXPECT_EQ(curPixel[2], prevPixel[2]);
EXPECT_EQ(curPixel[3], prevPixel[3]);
}
}
}
TEST_P(MaxTextureSizeTest, SpecificationTexStorage)
{
if (getClientVersion() < 3 && (!extensionEnabled("GL_EXT_texture_storage") || !extensionEnabled("GL_OES_rgb8_rgba8")))
{
return;
}
GLuint tex;
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
GLsizei textureWidth = 64;
GLsizei textureHeight = mMaxTexture2DSize;
std::vector<GLubyte> data(textureWidth * textureHeight * 4);
for (int y = 0; y < textureHeight; y++)
{
for (int x = 0; x < textureWidth; x++)
{
GLubyte* pixel = &data[0] + ((y * textureWidth + x) * 4);
// Draw a gradient, red in direction, green in y direction
pixel[0] = static_cast<GLubyte>((float(x) / textureWidth) * 255);
pixel[1] = static_cast<GLubyte>((float(y) / textureHeight) * 255);
pixel[2] = 0;
pixel[3] = 255;
}
}
if (getClientVersion() < 3)
{
glTexStorage2DEXT(GL_TEXTURE_2D, 1, GL_RGBA8_OES, textureWidth, textureHeight);
}
else
{
glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA8_OES, textureWidth, textureHeight);
}
EXPECT_GL_NO_ERROR();
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, textureWidth, textureHeight, GL_RGBA, GL_UNSIGNED_BYTE, &data[0]);
EXPECT_GL_NO_ERROR();
glUseProgram(mTextureProgram);
glUniform1i(mTextureUniformLocation, 0);
drawQuad(mTextureProgram, "position", 0.5f);
std::vector<GLubyte> pixels(getWindowWidth() * getWindowHeight() * 4);
glReadPixels(0, 0, getWindowWidth(), getWindowHeight(), GL_RGBA, GL_UNSIGNED_BYTE, &pixels[0]);
for (int y = 1; y < getWindowHeight(); y++)
{
for (int x = 1; x < getWindowWidth(); x++)
{
const GLubyte* prevPixel = &pixels[0] + (((y - 1) * getWindowWidth() + (x - 1)) * 4);
const GLubyte* curPixel = &pixels[0] + ((y * getWindowWidth() + x) * 4);
EXPECT_GE(curPixel[0], prevPixel[0]);
EXPECT_GE(curPixel[1], prevPixel[1]);
EXPECT_EQ(curPixel[2], prevPixel[2]);
EXPECT_EQ(curPixel[3], prevPixel[3]);
}
}
}
TEST_P(MaxTextureSizeTest, RenderToTexture)
{
if (getClientVersion() < 3 && (!extensionEnabled("GL_ANGLE_framebuffer_blit")))
{
std::cout << "Test skipped due to missing glBlitFramebuffer[ANGLE] support." << std::endl;
return;
}
GLuint fbo = 0;
GLuint textureId = 0;
// create a 1-level texture at maximum size
glGenTextures(1, &textureId);
glBindTexture(GL_TEXTURE_2D, textureId);
GLsizei textureWidth = 64;
GLsizei textureHeight = mMaxTexture2DSize;
// texture setup code
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_BGRA_EXT, textureWidth, textureHeight, 0, GL_BGRA_EXT, GL_UNSIGNED_BYTE, NULL);
EXPECT_GL_NO_ERROR();
// create an FBO and attach the texture
glGenFramebuffers(1, &fbo);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textureId, 0);
EXPECT_GL_NO_ERROR();
EXPECT_GLENUM_EQ(GL_FRAMEBUFFER_COMPLETE, glCheckFramebufferStatus(GL_FRAMEBUFFER));
const int frameCount = 64;
for (int i = 0; i < frameCount; i++)
{
// clear the screen
glBindFramebuffer(GL_FRAMEBUFFER, 0);
GLubyte clearRed = static_cast<GLubyte>((float(i) / frameCount) * 255);
GLubyte clearGreen = 255 - clearRed;
GLubyte clearBlue = 0;
glClearColor(clearRed / 255.0f, clearGreen / 255.0f, clearBlue / 255.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
// render blue into the texture
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
drawQuad(mBlueProgram, "position", 0.5f);
// copy corner of texture to LL corner of window
glBindFramebuffer(GL_DRAW_FRAMEBUFFER_ANGLE, 0);
glBindFramebuffer(GL_READ_FRAMEBUFFER_ANGLE, fbo);
glBlitFramebufferANGLE(0, 0, textureWidth - 1, getWindowHeight() - 1,
0, 0, textureWidth - 1, getWindowHeight() - 1,
GL_COLOR_BUFFER_BIT, GL_NEAREST);
glBindFramebuffer(GL_READ_FRAMEBUFFER_ANGLE, 0);
EXPECT_GL_NO_ERROR();
EXPECT_PIXEL_EQ(textureWidth / 2, getWindowHeight() / 2, 0, 0, 255, 255);
EXPECT_PIXEL_EQ(textureWidth + 10, getWindowHeight() / 2, clearRed, clearGreen, clearBlue, 255);
swapBuffers();
}
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glBindTexture(GL_TEXTURE_2D, 0);
glDeleteFramebuffers(1, &fbo);
glDeleteTextures(1, &textureId);
}
// Use this to select which configurations (e.g. which renderer, which GLES major version) these tests should be run against.
ANGLE_INSTANTIATE_TEST(MaxTextureSizeTest, ES2_D3D9(), ES2_D3D11(), ES2_D3D11_FL9_3());
| crezefire/angle | src/tests/gl_tests/MaxTextureSizeTest.cpp | C++ | bsd-3-clause | 9,742 |
# class generated by DeVIDE::createDeVIDEModuleFromVTKObject
from module_kits.vtk_kit.mixins import SimpleVTKClassModuleBase
import vtk
class vtkRuledSurfaceFilter(SimpleVTKClassModuleBase):
def __init__(self, module_manager):
SimpleVTKClassModuleBase.__init__(
self, module_manager,
vtk.vtkRuledSurfaceFilter(), 'Processing.',
('vtkPolyData',), ('vtkPolyData',),
replaceDoc=True,
inputFunctions=None, outputFunctions=None)
| nagyistoce/devide | modules/vtk_basic/vtkRuledSurfaceFilter.py | Python | bsd-3-clause | 497 |
# Copyright 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.
from telemetry.internal.app import possible_app
class PossibleBrowser(possible_app.PossibleApp):
"""A browser that can be controlled.
Call Create() to launch the browser and begin manipulating it..
"""
def __init__(self, browser_type, target_os, supports_tab_control):
super(PossibleBrowser, self).__init__(app_type=browser_type,
target_os=target_os)
self._supports_tab_control = supports_tab_control
self._credentials_path = None
def __repr__(self):
return 'PossibleBrowser(app_type=%s)' % self.app_type
@property
def browser_type(self):
return self.app_type
@property
def supports_tab_control(self):
return self._supports_tab_control
def _InitPlatformIfNeeded(self):
raise NotImplementedError()
def Create(self, finder_options):
raise NotImplementedError()
def SupportsOptions(self, browser_options):
"""Tests for extension support."""
raise NotImplementedError()
def IsRemote(self):
return False
def RunRemote(self):
pass
def UpdateExecutableIfNeeded(self):
pass
def last_modification_time(self):
return -1
def SetCredentialsPath(self, credentials_path):
self._credentials_path = credentials_path
| catapult-project/catapult-csm | telemetry/telemetry/internal/browser/possible_browser.py | Python | bsd-3-clause | 1,414 |
#!/usr/bin/env python
# Copyright 2015 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.
"""Implements a standard mechanism for Chrome Infra Python environment setup.
This library provides a central location to define Chrome Infra environment
setup. It also provides several faculties to install this environment.
Within a cooperating script, the environment can be setup by importing this
module and running its 'Install' method:
# Install Chrome-Infra environment (replaces 'sys.path').
sys.path.insert(0,
os.path.join(os.path.dirname(__file__), os.pardir, ...))
# (/path/to/build/scripts)
import common.env
common.env.Install()
When attempting to export the Chrome Infra path to external scripts, this
script can be invoked as an executable with various subcommands to emit a valid
PYTHONPATH clause.
In addition, this module has several functions to construct the path.
The goal is to deploy this module universally among Chrome-Infra scripts,
BuildBot configurations, tool invocations, and tests to ensure that they all
execute with the same centrally-defined environment.
"""
import argparse
import collections
import contextlib
import imp
import itertools
import os
import sys
import traceback
# Export for bootstrapping.
__all__ = [
'Install',
'PythonPath',
]
# Name of enviornment extension file to seek.
ENV_EXTENSION_NAME = 'environment.cfg.py'
# Standard directories (based on this file's location in the <build> tree).
def path_if(*args):
if not all(args):
return None
path = os.path.abspath(os.path.join(*args))
return (path) if os.path.exists(path) else (None)
# The path to the <build> directory in which this script resides.
Build = path_if(os.path.dirname(__file__), os.pardir, os.pardir)
# The path to the <build_internal> directory.
BuildInternal = path_if(Build, os.pardir, 'build_internal')
def SetPythonPathEnv(value):
"""Sets the system's PYTHONPATH environemnt variable.
Args:
value (str): The value to use. If this is empty/None, the system's
PYTHONPATH will be cleared.
"""
# Since we can't assign None to the environment "dictionary", we have to
# either set or delete the key depending on the original value.
if value is not None:
os.environ['PYTHONPATH'] = str(value)
else:
os.environ.pop('PYTHONPATH', None)
def Install(**kwargs):
"""Replaces the current 'sys.path' with a hermetic Chrome-Infra path.
Args:
kwargs (dict): See GetInfraPythonPath arguments.
Returns (PythonPath): The PythonPath object that was installed.
"""
infra_python_path = GetInfraPythonPath(**kwargs)
infra_python_path.Install()
return infra_python_path
def SplitPath(path):
"""Returns (list): A list of path elements.
Splits a path into path elements. For example (assuming '/' is the local
system path separator):
>>> print SplitPath('/a/b/c/d')
['/', 'a', 'b', 'c', 'd']
>>> print SplitPath('a/b/c')
['a', 'b,' 'c']
"""
parts = []
while True:
path, component = os.path.split(path)
if not component:
if path:
parts.append(path)
break
parts.append(component)
parts.reverse()
return parts
def ExtendPath(base, root_dir):
"""Returns (PythonPath): The extended python path.
This method looks for the ENV_EXTENSION_NAME file within "root_dir". If
present, it will be loaded as a Python module and have its "Extend" method
called.
If no extension is found, the base PythonPath will be returned.
Args:
base (PythonPath): The base python path.
root_dir (str): The path to check for an extension.
"""
extension_path = os.path.join(root_dir, ENV_EXTENSION_NAME)
if not os.path.isfile(extension_path):
return base
with open(extension_path, 'r') as fd:
extension = fd.read()
extension_module = imp.new_module('env-extension')
# Execute the enviornment extension.
try:
exec extension in extension_module.__dict__
extend_func = getattr(extension_module, 'Extend', None)
assert extend_func, (
"The environment extension module is missing the 'Extend()' method.")
base = extend_func(base, root_dir)
if not isinstance(base, PythonPath):
raise TypeError("Extension module returned non-PythonPath object (%s)" % (
type(base).__name__,))
except Exception:
# Re-raise the exception, but include the configuration file name.
tb = traceback.format_exc()
raise RuntimeError("Environment extension [%s] raised exception: %s" % (
extension_path, tb))
return base
def IsSystemPythonPath(path):
"""Returns (bool): If a python path is user-installed.
Paths that are known to be user-installed paths can be ignored when setting
up a hermetic Python path environment to avoid user libraries that would not
be present in other environments falsely affecting code.
This function can be updated as-needed to exclude other non-system paths
encountered on bots and in the wild.
"""
components = SplitPath(path)
for component in components:
if component in ('dist-packages', 'site-packages'):
return False
return True
class PythonPath(collections.Sequence):
"""An immutable set of Python path elements.
All paths represented in this structure are absolute. If a relative path
is passed into this structure, it will be converted to absolute based on
the current working directory (via os.path.abspath).
"""
def __init__(self, components=None):
"""Initializes a new PythonPath instance.
Args:
components (list): A list of path component strings.
"""
seen = set()
self._components = []
for component in (components or ()):
component = os.path.abspath(component)
assert isinstance(component, basestring), (
"Path component '%s' is not a string (%s)" % (
component, type(component).__name__))
if component in seen:
continue
seen.add(component)
self._components.append(component)
def __getitem__(self, value):
return self._components[value]
def __len__(self):
return len(self._components)
def __iadd__(self, other):
return self.Append(other)
def __repr__(self):
return self.pathstr
def __eq__(self, other):
assert isinstance(other, type(self))
return self._components == other._components
@classmethod
def Flatten(cls, *paths):
"""Returns (list): A single-level list containing flattened path elements.
>>> print PythonPath.Flatten('a', ['b', ['c', 'd']])
['a', 'b', 'c', 'd']
"""
result = []
for path in paths:
if not isinstance(path, basestring):
# Assume it's an iterable of paths.
result += cls.Flatten(*path)
else:
result.append(path)
return result
@classmethod
def FromPaths(cls, *paths):
"""Returns (PythonPath): A PythonPath instantiated from path elements.
Args:
paths (tuple): A tuple of path elements or iterables containing path
elements (e.g., PythonPath instances).
"""
return cls(cls.Flatten(*paths))
@classmethod
def FromPathStr(cls, pathstr):
"""Returns (PythonPath): A PythonPath instantiated from the path string.
Args:
pathstr (str): An os.pathsep()-delimited path string.
"""
return cls(pathstr.split(os.pathsep))
@property
def pathstr(self):
"""Returns (str): A path string for the instance's path elements."""
return os.pathsep.join(self)
def IsHermetic(self):
"""Returns (bool): True if this instance contains only system paths."""
return all(IsSystemPythonPath(p) for p in self)
def GetHermetic(self):
"""Returns (PythonPath): derivative PythonPath containing only system paths.
"""
return type(self).FromPaths(*(p for p in self if IsSystemPythonPath(p)))
def Append(self, *paths):
"""Returns (PythonPath): derivative PythonPath with paths added to the end.
Args:
paths (tuple): A tuple of path elements to append to the current instance.
"""
return type(self)(itertools.chain(self, self.FromPaths(*paths)))
def Override(self, *paths):
"""Returns (PythonPath): derivative PythonPath with paths prepended.
Args:
paths (tuple): A tuple of path elements to prepend to the current
instance.
"""
return self.FromPaths(*paths).Append(self)
def Install(self):
"""Overwrites Python runtime variables based on the current instance.
Performs the following operations:
- Replaces sys.path with the current instance's path.
- Replaces os.environ['PYTHONPATH'] with the current instance's path
string.
"""
sys.path = list(self)
SetPythonPathEnv(self.pathstr)
@contextlib.contextmanager
def Enter(self):
"""Context manager wrapper for Install.
On exit, the context manager will restore the original environment.
"""
orig_sys_path = sys.path[:]
orig_pythonpath = os.environ.get('PYTHONPATH')
try:
self.Install()
yield
finally:
sys.path = orig_sys_path
SetPythonPathEnv(orig_pythonpath)
def GetSysPythonPath(hermetic=True):
"""Returns (PythonPath): A path based on 'sys.path'.
Args:
hermetic (bool): If True, prune any non-system path.
"""
path = PythonPath.FromPaths(*sys.path)
if hermetic:
path = path.GetHermetic()
return path
def GetEnvPythonPath():
"""Returns (PythonPath): A path based on the PYTHONPATH environment variable.
"""
pythonpath = os.environ.get('PYTHONPATH')
if not pythonpath:
return PythonPath.FromPaths()
return PythonPath.FromPathStr(pythonpath)
def GetMasterPythonPath(master_dir):
"""Returns (PythonPath): A path including a BuildBot master's directory.
Args:
master_dir (str): The BuildBot master root directory.
"""
return PythonPath.FromPaths(master_dir)
def GetBuildPythonPath():
"""Returns (PythonPath): The Chrome Infra build path."""
build_path = PythonPath.FromPaths()
for extension_dir in (
Build,
BuildInternal,
):
if extension_dir:
build_path = ExtendPath(build_path, extension_dir)
return build_path
def GetInfraPythonPath(hermetic=True, master_dir=None):
"""Returns (PythonPath): The full working Chrome Infra utility path.
This path is consistent for master, slave, and tool usage. It includes (in
this order):
- Any environment PYTHONPATH overrides.
- If 'master_dir' is supplied, the master's python path component.
- The Chrome Infra build path.
- The system python path.
Args:
hermetic (bool): True, prune any non-system path from the system path.
master_dir (str): If not None, include a master path component.
"""
path = GetEnvPythonPath()
if master_dir:
path += GetMasterPythonPath(master_dir)
path += GetBuildPythonPath()
path += GetSysPythonPath(hermetic=hermetic)
return path
def _InfraPathFromArgs(args):
"""Returns (PythonPath): A PythonPath populated from command-line arguments.
Args:
args (argparse.Namespace): The command-line arguments constructed by 'main'.
"""
return GetInfraPythonPath(
master_dir=args.master_dir,
)
def _Command_Echo(args, path):
"""Returns (int): Return code.
Command function for the 'echo' subcommand. Outputs the path string for
'path'.
Args:
args (argparse.Namespace): The command-line arguments constructed by 'main'.
path (PythonPath): The python path to use.
"""
args.output.write(path.pathstr)
return 0
def _Command_Print(args, path):
"""Returns (int): Return code.
Command function for the 'print' subcommand. Outputs each path component in
path on a separate line.
Args:
args (argparse.Namespace): The command-line arguments constructed by 'main'.
path (PythonPath): The python path to use.
"""
for component in path:
print >>args.output, component
return 0
def main():
"""Main execution function."""
parser = argparse.ArgumentParser()
parser.add_argument('-M', '--master_dir',
help="Augment the path with the master's directory.")
parser.add_argument('-o', '--output', metavar='PATH',
type=argparse.FileType('w'), default='-',
help="File to output to (use '-' for STDOUT).")
subparsers = parser.add_subparsers()
# 'echo'
subparser = subparsers.add_parser('echo')
subparser.set_defaults(func=_Command_Echo)
# 'print'
subparser = subparsers.add_parser('print')
subparser.set_defaults(func=_Command_Print)
# Parse
args = parser.parse_args()
# Execute our subcommand function, which will return the exit code.
path = _InfraPathFromArgs(args)
return args.func(args, path)
if __name__ == '__main__':
sys.exit(main())
| hgl888/chromium-crosswalk | infra/scripts/legacy/scripts/common/env.py | Python | bsd-3-clause | 12,777 |
// Copyright 2017 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 "third_party/blink/renderer/modules/presentation/presentation_availability_state.h"
#include "third_party/blink/renderer/modules/presentation/presentation_availability_observer.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
namespace blink {
PresentationAvailabilityState::PresentationAvailabilityState(
mojom::blink::PresentationService* presentation_service)
: presentation_service_(presentation_service) {}
PresentationAvailabilityState::~PresentationAvailabilityState() = default;
void PresentationAvailabilityState::RequestAvailability(
const Vector<KURL>& urls,
PresentationAvailabilityCallbacks* callback) {
auto screen_availability = GetScreenAvailability(urls);
// Reject Promise if screen availability is unsupported for all URLs.
if (screen_availability == mojom::blink::ScreenAvailability::DISABLED) {
Thread::Current()->GetTaskRunner()->PostTask(
FROM_HERE,
WTF::Bind(
&PresentationAvailabilityCallbacks::RejectAvailabilityNotSupported,
WrapPersistent(callback)));
// Do not listen to urls if we reject the promise.
return;
}
auto* listener = GetAvailabilityListener(urls);
if (!listener) {
listener = MakeGarbageCollected<AvailabilityListener>(urls);
availability_listeners_.emplace_back(listener);
}
if (screen_availability != mojom::blink::ScreenAvailability::UNKNOWN) {
Thread::Current()->GetTaskRunner()->PostTask(
FROM_HERE, WTF::Bind(&PresentationAvailabilityCallbacks::Resolve,
WrapPersistent(callback),
screen_availability ==
mojom::blink::ScreenAvailability::AVAILABLE));
} else {
listener->availability_callbacks.push_back(callback);
}
for (const auto& availability_url : urls)
StartListeningToURL(availability_url);
}
void PresentationAvailabilityState::AddObserver(
PresentationAvailabilityObserver* observer) {
const auto& urls = observer->Urls();
auto* listener = GetAvailabilityListener(urls);
if (!listener) {
listener = MakeGarbageCollected<AvailabilityListener>(urls);
availability_listeners_.emplace_back(listener);
}
if (listener->availability_observers.Contains(observer))
return;
listener->availability_observers.push_back(observer);
for (const auto& availability_url : urls)
StartListeningToURL(availability_url);
}
void PresentationAvailabilityState::RemoveObserver(
PresentationAvailabilityObserver* observer) {
const auto& urls = observer->Urls();
auto* listener = GetAvailabilityListener(urls);
if (!listener) {
DLOG(WARNING) << "Stop listening for availability for unknown URLs.";
return;
}
wtf_size_t slot = listener->availability_observers.Find(observer);
if (slot != kNotFound) {
listener->availability_observers.EraseAt(slot);
}
for (const auto& availability_url : urls)
MaybeStopListeningToURL(availability_url);
TryRemoveAvailabilityListener(listener);
}
void PresentationAvailabilityState::UpdateAvailability(
const KURL& url,
mojom::blink::ScreenAvailability availability) {
auto* listening_status = GetListeningStatus(url);
if (!listening_status)
return;
if (listening_status->listening_state == ListeningState::kWaiting)
listening_status->listening_state = ListeningState::kActive;
if (listening_status->last_known_availability == availability)
return;
listening_status->last_known_availability = availability;
HeapVector<Member<AvailabilityListener>> listeners = availability_listeners_;
for (auto& listener : listeners) {
if (!listener->urls.Contains<KURL>(url))
continue;
auto screen_availability = GetScreenAvailability(listener->urls);
DCHECK(screen_availability != mojom::blink::ScreenAvailability::UNKNOWN);
HeapVector<Member<PresentationAvailabilityObserver>> observers =
listener->availability_observers;
for (auto& observer : observers) {
observer->AvailabilityChanged(screen_availability);
}
if (screen_availability == mojom::blink::ScreenAvailability::DISABLED) {
for (auto& callback_ptr : listener->availability_callbacks) {
callback_ptr->RejectAvailabilityNotSupported();
}
} else {
for (auto& callback_ptr : listener->availability_callbacks) {
callback_ptr->Resolve(screen_availability ==
mojom::blink::ScreenAvailability::AVAILABLE);
}
}
listener->availability_callbacks.clear();
for (const auto& availability_url : listener->urls)
MaybeStopListeningToURL(availability_url);
TryRemoveAvailabilityListener(listener);
}
}
void PresentationAvailabilityState::Trace(Visitor* visitor) const {
visitor->Trace(availability_listeners_);
}
void PresentationAvailabilityState::StartListeningToURL(const KURL& url) {
auto* listening_status = GetListeningStatus(url);
if (!listening_status) {
listening_status = new ListeningStatus(url);
availability_listening_status_.emplace_back(listening_status);
}
// Already listening.
if (listening_status->listening_state != ListeningState::kInactive)
return;
listening_status->listening_state = ListeningState::kWaiting;
presentation_service_->ListenForScreenAvailability(url);
}
void PresentationAvailabilityState::MaybeStopListeningToURL(const KURL& url) {
for (const auto& listener : availability_listeners_) {
if (!listener->urls.Contains(url))
continue;
// URL is still observed by some availability object.
if (!listener->availability_callbacks.IsEmpty() ||
!listener->availability_observers.IsEmpty()) {
return;
}
}
auto* listening_status = GetListeningStatus(url);
if (!listening_status) {
LOG(WARNING) << "Stop listening to unknown url: " << url.GetString();
return;
}
if (listening_status->listening_state == ListeningState::kInactive)
return;
listening_status->listening_state = ListeningState::kInactive;
presentation_service_->StopListeningForScreenAvailability(url);
}
mojom::blink::ScreenAvailability
PresentationAvailabilityState::GetScreenAvailability(
const Vector<KURL>& urls) const {
bool has_disabled = false;
bool has_source_not_supported = false;
bool has_unavailable = false;
for (const auto& url : urls) {
auto* status = GetListeningStatus(url);
auto screen_availability = status
? status->last_known_availability
: mojom::blink::ScreenAvailability::UNKNOWN;
switch (screen_availability) {
case mojom::blink::ScreenAvailability::AVAILABLE:
return mojom::blink::ScreenAvailability::AVAILABLE;
case mojom::blink::ScreenAvailability::DISABLED:
has_disabled = true;
break;
case mojom::blink::ScreenAvailability::SOURCE_NOT_SUPPORTED:
has_source_not_supported = true;
break;
case mojom::blink::ScreenAvailability::UNAVAILABLE:
has_unavailable = true;
break;
case mojom::blink::ScreenAvailability::UNKNOWN:
break;
}
}
if (has_disabled)
return mojom::blink::ScreenAvailability::DISABLED;
if (has_source_not_supported)
return mojom::blink::ScreenAvailability::SOURCE_NOT_SUPPORTED;
if (has_unavailable)
return mojom::blink::ScreenAvailability::UNAVAILABLE;
return mojom::blink::ScreenAvailability::UNKNOWN;
}
PresentationAvailabilityState::AvailabilityListener*
PresentationAvailabilityState::GetAvailabilityListener(
const Vector<KURL>& urls) {
auto* listener_it = std::find_if(
availability_listeners_.begin(), availability_listeners_.end(),
[&urls](const auto& listener) { return listener->urls == urls; });
return listener_it == availability_listeners_.end() ? nullptr : *listener_it;
}
void PresentationAvailabilityState::TryRemoveAvailabilityListener(
AvailabilityListener* listener) {
// URL is still observed by some availability object.
if (!listener->availability_callbacks.IsEmpty() ||
!listener->availability_observers.IsEmpty()) {
return;
}
wtf_size_t slot = availability_listeners_.Find(listener);
if (slot != kNotFound) {
availability_listeners_.EraseAt(slot);
}
}
PresentationAvailabilityState::ListeningStatus*
PresentationAvailabilityState::GetListeningStatus(const KURL& url) const {
auto* status_it =
std::find_if(availability_listening_status_.begin(),
availability_listening_status_.end(),
[&url](const std::unique_ptr<ListeningStatus>& status) {
return status->url == url;
});
return status_it == availability_listening_status_.end() ? nullptr
: status_it->get();
}
PresentationAvailabilityState::AvailabilityListener::AvailabilityListener(
const Vector<KURL>& availability_urls)
: urls(availability_urls) {}
PresentationAvailabilityState::AvailabilityListener::~AvailabilityListener() =
default;
void PresentationAvailabilityState::AvailabilityListener::Trace(
blink::Visitor* visitor) const {
visitor->Trace(availability_callbacks);
visitor->Trace(availability_observers);
}
PresentationAvailabilityState::ListeningStatus::ListeningStatus(
const KURL& availability_url)
: url(availability_url),
last_known_availability(mojom::blink::ScreenAvailability::UNKNOWN),
listening_state(ListeningState::kInactive) {}
PresentationAvailabilityState::ListeningStatus::~ListeningStatus() = default;
} // namespace blink
| chromium/chromium | third_party/blink/renderer/modules/presentation/presentation_availability_state.cc | C++ | bsd-3-clause | 9,801 |
// Copyright (c) 2011 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 "chrome_frame/http_negotiate.h"
#include <atlbase.h>
#include <atlcom.h>
#include <htiframe.h>
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/string_util.h"
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "chrome_frame/bho.h"
#include "chrome_frame/exception_barrier.h"
#include "chrome_frame/html_utils.h"
#include "chrome_frame/urlmon_moniker.h"
#include "chrome_frame/urlmon_url_request.h"
#include "chrome_frame/utils.h"
#include "chrome_frame/vtable_patch_manager.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_util.h"
bool HttpNegotiatePatch::modify_user_agent_ = true;
const char kUACompatibleHttpHeader[] = "x-ua-compatible";
const char kLowerCaseUserAgent[] = "user-agent";
// From the latest urlmon.h. Symbol name prepended with LOCAL_ to
// avoid conflict (and therefore build errors) for those building with
// a newer Windows SDK.
// TODO(robertshield): Remove this once we update our SDK version.
const int LOCAL_BINDSTATUS_SERVER_MIMETYPEAVAILABLE = 54;
static const int kHttpNegotiateBeginningTransactionIndex = 3;
BEGIN_VTABLE_PATCHES(IHttpNegotiate)
VTABLE_PATCH_ENTRY(kHttpNegotiateBeginningTransactionIndex,
HttpNegotiatePatch::BeginningTransaction)
END_VTABLE_PATCHES()
namespace {
class SimpleBindStatusCallback : public CComObjectRootEx<CComSingleThreadModel>,
public IBindStatusCallback {
public:
BEGIN_COM_MAP(SimpleBindStatusCallback)
COM_INTERFACE_ENTRY(IBindStatusCallback)
END_COM_MAP()
// IBindStatusCallback implementation
STDMETHOD(OnStartBinding)(DWORD reserved, IBinding* binding) {
return E_NOTIMPL;
}
STDMETHOD(GetPriority)(LONG* priority) {
return E_NOTIMPL;
}
STDMETHOD(OnLowResource)(DWORD reserved) {
return E_NOTIMPL;
}
STDMETHOD(OnProgress)(ULONG progress, ULONG max_progress,
ULONG status_code, LPCWSTR status_text) {
return E_NOTIMPL;
}
STDMETHOD(OnStopBinding)(HRESULT result, LPCWSTR error) {
return E_NOTIMPL;
}
STDMETHOD(GetBindInfo)(DWORD* bind_flags, BINDINFO* bind_info) {
return E_NOTIMPL;
}
STDMETHOD(OnDataAvailable)(DWORD flags, DWORD size, FORMATETC* formatetc,
STGMEDIUM* storage) {
return E_NOTIMPL;
}
STDMETHOD(OnObjectAvailable)(REFIID iid, IUnknown* object) {
return E_NOTIMPL;
}
};
} // end namespace
std::string AppendCFUserAgentString(LPCWSTR headers,
LPCWSTR additional_headers) {
using net::HttpUtil;
std::string ascii_headers;
if (additional_headers) {
ascii_headers = WideToASCII(additional_headers);
}
// Extract "User-Agent" from |additional_headers| or |headers|.
HttpUtil::HeadersIterator headers_iterator(ascii_headers.begin(),
ascii_headers.end(), "\r\n");
std::string user_agent_value;
if (headers_iterator.AdvanceTo(kLowerCaseUserAgent)) {
user_agent_value = headers_iterator.values();
} else if (headers != NULL) {
// See if there's a user-agent header specified in the original headers.
std::string original_headers(WideToASCII(headers));
HttpUtil::HeadersIterator original_it(original_headers.begin(),
original_headers.end(), "\r\n");
if (original_it.AdvanceTo(kLowerCaseUserAgent))
user_agent_value = original_it.values();
}
// Use the default "User-Agent" if none was provided.
if (user_agent_value.empty())
user_agent_value = http_utils::GetDefaultUserAgent();
// Now add chromeframe to it.
user_agent_value = http_utils::AddChromeFrameToUserAgentValue(
user_agent_value);
// Build new headers, skip the existing user agent value from
// existing headers.
std::string new_headers;
headers_iterator.Reset();
while (headers_iterator.GetNext()) {
std::string name(headers_iterator.name());
if (!LowerCaseEqualsASCII(name, kLowerCaseUserAgent)) {
new_headers += name + ": " + headers_iterator.values() + "\r\n";
}
}
new_headers += "User-Agent: " + user_agent_value;
new_headers += "\r\n";
return new_headers;
}
std::string ReplaceOrAddUserAgent(LPCWSTR headers,
const std::string& user_agent_value) {
using net::HttpUtil;
std::string new_headers;
if (headers) {
std::string ascii_headers(WideToASCII(headers));
// Extract "User-Agent" from the headers.
HttpUtil::HeadersIterator headers_iterator(ascii_headers.begin(),
ascii_headers.end(), "\r\n");
// Build new headers, skip the existing user agent value from
// existing headers.
while (headers_iterator.GetNext()) {
std::string name(headers_iterator.name());
if (!LowerCaseEqualsASCII(name, kLowerCaseUserAgent)) {
new_headers += name + ": " + headers_iterator.values() + "\r\n";
}
}
}
new_headers += "User-Agent: " + user_agent_value;
new_headers += "\r\n";
return new_headers;
}
HttpNegotiatePatch::HttpNegotiatePatch() {
}
HttpNegotiatePatch::~HttpNegotiatePatch() {
}
// static
bool HttpNegotiatePatch::Initialize() {
if (IS_PATCHED(IHttpNegotiate)) {
DLOG(WARNING) << __FUNCTION__ << " called more than once.";
return true;
}
// Use our SimpleBindStatusCallback class as we need a temporary object that
// implements IBindStatusCallback.
CComObjectStackEx<SimpleBindStatusCallback> request;
base::win::ScopedComPtr<IBindCtx> bind_ctx;
HRESULT hr = CreateAsyncBindCtx(0, &request, NULL, bind_ctx.Receive());
DCHECK(SUCCEEDED(hr)) << "CreateAsyncBindCtx";
if (bind_ctx) {
base::win::ScopedComPtr<IUnknown> bscb_holder;
bind_ctx->GetObjectParam(L"_BSCB_Holder_", bscb_holder.Receive());
if (bscb_holder) {
hr = PatchHttpNegotiate(bscb_holder);
} else {
NOTREACHED() << "Failed to get _BSCB_Holder_";
hr = E_UNEXPECTED;
}
bind_ctx.Release();
}
return SUCCEEDED(hr);
}
// static
void HttpNegotiatePatch::Uninitialize() {
vtable_patch::UnpatchInterfaceMethods(IHttpNegotiate_PatchInfo);
}
// static
HRESULT HttpNegotiatePatch::PatchHttpNegotiate(IUnknown* to_patch) {
DCHECK(to_patch);
DCHECK_IS_NOT_PATCHED(IHttpNegotiate);
base::win::ScopedComPtr<IHttpNegotiate> http;
HRESULT hr = http.QueryFrom(to_patch);
if (FAILED(hr)) {
hr = DoQueryService(IID_IHttpNegotiate, to_patch, http.Receive());
}
if (http) {
hr = vtable_patch::PatchInterfaceMethods(http, IHttpNegotiate_PatchInfo);
DLOG_IF(ERROR, FAILED(hr))
<< base::StringPrintf("HttpNegotiate patch failed 0x%08X", hr);
} else {
DLOG(WARNING)
<< base::StringPrintf("IHttpNegotiate not supported 0x%08X", hr);
}
return hr;
}
// static
HRESULT HttpNegotiatePatch::BeginningTransaction(
IHttpNegotiate_BeginningTransaction_Fn original, IHttpNegotiate* me,
LPCWSTR url, LPCWSTR headers, DWORD reserved, LPWSTR* additional_headers) {
DVLOG(1) << __FUNCTION__ << " " << url << " headers:\n" << headers;
HRESULT hr = original(me, url, headers, reserved, additional_headers);
if (FAILED(hr)) {
DLOG(WARNING) << __FUNCTION__ << " Delegate returned an error";
return hr;
}
if (modify_user_agent_) {
std::string updated_headers;
if (IsGcfDefaultRenderer() &&
RendererTypeForUrl(url) == RENDERER_TYPE_CHROME_DEFAULT_RENDERER) {
// Replace the user-agent header with Chrome's.
updated_headers = ReplaceOrAddUserAgent(*additional_headers,
http_utils::GetChromeUserAgent());
} else {
updated_headers = AppendCFUserAgentString(headers, *additional_headers);
}
*additional_headers = reinterpret_cast<wchar_t*>(::CoTaskMemRealloc(
*additional_headers,
(updated_headers.length() + 1) * sizeof(wchar_t)));
lstrcpyW(*additional_headers, ASCIIToWide(updated_headers).c_str());
} else {
// TODO(erikwright): Remove the user agent if it is present (i.e., because
// of PostPlatform setting in the registry).
}
return S_OK;
}
| aYukiSekiguchi/ACCESS-Chromium | chrome_frame/http_negotiate.cc | C++ | bsd-3-clause | 8,266 |
/*
* Copyright (C) 2013 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "flutter/sky/engine/wtf/PartitionAlloc.h"
#include <string.h>
#ifndef NDEBUG
#include <stdio.h>
#endif
// Two partition pages are used as guard / metadata page so make sure the super
// page size is bigger.
COMPILE_ASSERT(WTF::kPartitionPageSize * 4 <= WTF::kSuperPageSize, ok_super_page_size);
COMPILE_ASSERT(!(WTF::kSuperPageSize % WTF::kPartitionPageSize), ok_super_page_multiple);
// Four system pages gives us room to hack out a still-guard-paged piece
// of metadata in the middle of a guard partition page.
COMPILE_ASSERT(WTF::kSystemPageSize * 4 <= WTF::kPartitionPageSize, ok_partition_page_size);
COMPILE_ASSERT(!(WTF::kPartitionPageSize % WTF::kSystemPageSize), ok_partition_page_multiple);
COMPILE_ASSERT(sizeof(WTF::PartitionPage) <= WTF::kPageMetadataSize, PartitionPage_not_too_big);
COMPILE_ASSERT(sizeof(WTF::PartitionBucket) <= WTF::kPageMetadataSize, PartitionBucket_not_too_big);
COMPILE_ASSERT(sizeof(WTF::PartitionSuperPageExtentEntry) <= WTF::kPageMetadataSize, PartitionSuperPageExtentEntry_not_too_big);
COMPILE_ASSERT(WTF::kPageMetadataSize * WTF::kNumPartitionPagesPerSuperPage <= WTF::kSystemPageSize, page_metadata_fits_in_hole);
// Check that some of our zanier calculations worked out as expected.
COMPILE_ASSERT(WTF::kGenericSmallestBucket == 8, generic_smallest_bucket);
COMPILE_ASSERT(WTF::kGenericMaxBucketed == 983040, generic_max_bucketed);
namespace WTF {
int PartitionRootBase::gInitializedLock = 0;
bool PartitionRootBase::gInitialized = false;
PartitionPage PartitionRootBase::gSeedPage;
PartitionBucket PartitionRootBase::gPagedBucket;
static size_t partitionBucketNumSystemPages(size_t size)
{
// This works out reasonably for the current bucket sizes of the generic
// allocator, and the current values of partition page size and constants.
// Specifically, we have enough room to always pack the slots perfectly into
// some number of system pages. The only waste is the waste associated with
// unfaulted pages (i.e. wasted address space).
// TODO: we end up using a lot of system pages for very small sizes. For
// example, we'll use 12 system pages for slot size 24. The slot size is
// so small that the waste would be tiny with just 4, or 1, system pages.
// Later, we can investigate whether there are anti-fragmentation benefits
// to using fewer system pages.
double bestWasteRatio = 1.0f;
size_t bestPages = 0;
if (size > kMaxSystemPagesPerSlotSpan * kSystemPageSize) {
ASSERT(!(size % kSystemPageSize));
return size / kSystemPageSize;
}
ASSERT(size <= kMaxSystemPagesPerSlotSpan * kSystemPageSize);
for (size_t i = kNumSystemPagesPerPartitionPage - 1; i <= kMaxSystemPagesPerSlotSpan; ++i) {
size_t pageSize = kSystemPageSize * i;
size_t numSlots = pageSize / size;
size_t waste = pageSize - (numSlots * size);
// Leaving a page unfaulted is not free; the page will occupy an empty page table entry.
// Make a simple attempt to account for that.
size_t numRemainderPages = i & (kNumSystemPagesPerPartitionPage - 1);
size_t numUnfaultedPages = numRemainderPages ? (kNumSystemPagesPerPartitionPage - numRemainderPages) : 0;
waste += sizeof(void*) * numUnfaultedPages;
double wasteRatio = (double) waste / (double) pageSize;
if (wasteRatio < bestWasteRatio) {
bestWasteRatio = wasteRatio;
bestPages = i;
}
}
ASSERT(bestPages > 0);
return bestPages;
}
static void parititonAllocBaseInit(PartitionRootBase* root)
{
ASSERT(!root->initialized);
spinLockLock(&PartitionRootBase::gInitializedLock);
if (!PartitionRootBase::gInitialized) {
PartitionRootBase::gInitialized = true;
// We mark the seed page as free to make sure it is skipped by our
// logic to find a new active page.
PartitionRootBase::gPagedBucket.activePagesHead = &PartitionRootGeneric::gSeedPage;
}
spinLockUnlock(&PartitionRootBase::gInitializedLock);
root->initialized = true;
root->totalSizeOfCommittedPages = 0;
root->totalSizeOfSuperPages = 0;
root->nextSuperPage = 0;
root->nextPartitionPage = 0;
root->nextPartitionPageEnd = 0;
root->firstExtent = 0;
root->currentExtent = 0;
memset(&root->globalEmptyPageRing, '\0', sizeof(root->globalEmptyPageRing));
root->globalEmptyPageRingIndex = 0;
// This is a "magic" value so we can test if a root pointer is valid.
root->invertedSelf = ~reinterpret_cast<uintptr_t>(root);
}
static void partitionBucketInitBase(PartitionBucket* bucket, PartitionRootBase* root)
{
bucket->activePagesHead = &PartitionRootGeneric::gSeedPage;
bucket->freePagesHead = 0;
bucket->numFullPages = 0;
bucket->numSystemPagesPerSlotSpan = partitionBucketNumSystemPages(bucket->slotSize);
}
void partitionAllocInit(PartitionRoot* root, size_t numBuckets, size_t maxAllocation)
{
parititonAllocBaseInit(root);
root->numBuckets = numBuckets;
root->maxAllocation = maxAllocation;
size_t i;
for (i = 0; i < root->numBuckets; ++i) {
PartitionBucket* bucket = &root->buckets()[i];
if (!i)
bucket->slotSize = kAllocationGranularity;
else
bucket->slotSize = i << kBucketShift;
partitionBucketInitBase(bucket, root);
}
}
void partitionAllocGenericInit(PartitionRootGeneric* root)
{
parititonAllocBaseInit(root);
root->lock = 0;
// Precalculate some shift and mask constants used in the hot path.
// Example: malloc(41) == 101001 binary.
// Order is 6 (1 << 6-1)==32 is highest bit set.
// orderIndex is the next three MSB == 010 == 2.
// subOrderIndexMask is a mask for the remaining bits == 11 (masking to 01 for the subOrderIndex).
size_t order;
for (order = 0; order <= kBitsPerSizet; ++order) {
size_t orderIndexShift;
if (order < kGenericNumBucketsPerOrderBits + 1)
orderIndexShift = 0;
else
orderIndexShift = order - (kGenericNumBucketsPerOrderBits + 1);
root->orderIndexShifts[order] = orderIndexShift;
size_t subOrderIndexMask;
if (order == kBitsPerSizet) {
// This avoids invoking undefined behavior for an excessive shift.
subOrderIndexMask = static_cast<size_t>(-1) >> (kGenericNumBucketsPerOrderBits + 1);
} else {
subOrderIndexMask = ((1 << order) - 1) >> (kGenericNumBucketsPerOrderBits + 1);
}
root->orderSubIndexMasks[order] = subOrderIndexMask;
}
// Set up the actual usable buckets first.
// Note that typical values (i.e. min allocation size of 8) will result in
// invalid buckets (size==9 etc. or more generally, size is not a multiple
// of the smallest allocation granularity).
// We avoid them in the bucket lookup map, but we tolerate them to keep the
// code simpler and the structures more generic.
size_t i, j;
size_t currentSize = kGenericSmallestBucket;
size_t currentIncrement = kGenericSmallestBucket >> kGenericNumBucketsPerOrderBits;
PartitionBucket* bucket = &root->buckets[0];
for (i = 0; i < kGenericNumBucketedOrders; ++i) {
for (j = 0; j < kGenericNumBucketsPerOrder; ++j) {
bucket->slotSize = currentSize;
partitionBucketInitBase(bucket, root);
// Disable invalid buckets so that touching them faults.
if (currentSize % kGenericSmallestBucket)
bucket->activePagesHead = 0;
currentSize += currentIncrement;
++bucket;
}
currentIncrement <<= 1;
}
ASSERT(currentSize == 1 << kGenericMaxBucketedOrder);
ASSERT(bucket == &root->buckets[0] + (kGenericNumBucketedOrders * kGenericNumBucketsPerOrder));
// Then set up the fast size -> bucket lookup table.
bucket = &root->buckets[0];
PartitionBucket** bucketPtr = &root->bucketLookups[0];
for (order = 0; order <= kBitsPerSizet; ++order) {
for (j = 0; j < kGenericNumBucketsPerOrder; ++j) {
if (order < kGenericMinBucketedOrder) {
// Use the bucket of finest granularity for malloc(0) etc.
*bucketPtr++ = &root->buckets[0];
} else if (order > kGenericMaxBucketedOrder) {
*bucketPtr++ = &PartitionRootGeneric::gPagedBucket;
} else {
PartitionBucket* validBucket = bucket;
// Skip over invalid buckets.
while (validBucket->slotSize % kGenericSmallestBucket)
validBucket++;
*bucketPtr++ = validBucket;
bucket++;
}
}
}
ASSERT(bucket == &root->buckets[0] + (kGenericNumBucketedOrders * kGenericNumBucketsPerOrder));
ASSERT(bucketPtr == &root->bucketLookups[0] + ((kBitsPerSizet + 1) * kGenericNumBucketsPerOrder));
// And there's one last bucket lookup that will be hit for e.g. malloc(-1),
// which tries to overflow to a non-existant order.
*bucketPtr = &PartitionRootGeneric::gPagedBucket;
}
static bool partitionAllocShutdownBucket(PartitionBucket* bucket)
{
// Failure here indicates a memory leak.
bool noLeaks = !bucket->numFullPages;
PartitionPage* page = bucket->activePagesHead;
while (page) {
if (page->numAllocatedSlots)
noLeaks = false;
page = page->nextPage;
}
return noLeaks;
}
static void partitionAllocBaseShutdown(PartitionRootBase* root)
{
ASSERT(root->initialized);
root->initialized = false;
// Now that we've examined all partition pages in all buckets, it's safe
// to free all our super pages. We first collect the super page pointers
// on the stack because some of them are themselves store in super pages.
char* superPages[kMaxPartitionSize / kSuperPageSize];
size_t numSuperPages = 0;
PartitionSuperPageExtentEntry* entry = root->firstExtent;
while (entry) {
char* superPage = entry->superPageBase;
while (superPage != entry->superPagesEnd) {
superPages[numSuperPages] = superPage;
numSuperPages++;
superPage += kSuperPageSize;
}
entry = entry->next;
}
ASSERT(numSuperPages == root->totalSizeOfSuperPages / kSuperPageSize);
for (size_t i = 0; i < numSuperPages; ++i)
freePages(superPages[i], kSuperPageSize);
}
bool partitionAllocShutdown(PartitionRoot* root)
{
bool noLeaks = true;
size_t i;
for (i = 0; i < root->numBuckets; ++i) {
PartitionBucket* bucket = &root->buckets()[i];
if (!partitionAllocShutdownBucket(bucket))
noLeaks = false;
}
partitionAllocBaseShutdown(root);
return noLeaks;
}
bool partitionAllocGenericShutdown(PartitionRootGeneric* root)
{
bool noLeaks = true;
size_t i;
for (i = 0; i < kGenericNumBucketedOrders * kGenericNumBucketsPerOrder; ++i) {
PartitionBucket* bucket = &root->buckets[i];
if (!partitionAllocShutdownBucket(bucket))
noLeaks = false;
}
partitionAllocBaseShutdown(root);
return noLeaks;
}
static NEVER_INLINE void partitionOutOfMemory()
{
IMMEDIATE_CRASH();
}
static NEVER_INLINE void partitionFull()
{
IMMEDIATE_CRASH();
}
static ALWAYS_INLINE void partitionDecommitSystemPages(PartitionRootBase* root, void* addr, size_t len)
{
decommitSystemPages(addr, len);
ASSERT(root->totalSizeOfCommittedPages > len);
root->totalSizeOfCommittedPages -= len;
}
static ALWAYS_INLINE void partitionRecommitSystemPages(PartitionRootBase* root, void* addr, size_t len)
{
recommitSystemPages(addr, len);
root->totalSizeOfCommittedPages += len;
}
static ALWAYS_INLINE void* partitionAllocPartitionPages(PartitionRootBase* root, int flags, size_t numPartitionPages)
{
ASSERT(!(reinterpret_cast<uintptr_t>(root->nextPartitionPage) % kPartitionPageSize));
ASSERT(!(reinterpret_cast<uintptr_t>(root->nextPartitionPageEnd) % kPartitionPageSize));
RELEASE_ASSERT(numPartitionPages <= kNumPartitionPagesPerSuperPage);
size_t totalSize = kPartitionPageSize * numPartitionPages;
root->totalSizeOfCommittedPages += totalSize;
size_t numPartitionPagesLeft = (root->nextPartitionPageEnd - root->nextPartitionPage) >> kPartitionPageShift;
if (LIKELY(numPartitionPagesLeft >= numPartitionPages)) {
// In this case, we can still hand out pages from the current super page
// allocation.
char* ret = root->nextPartitionPage;
root->nextPartitionPage += totalSize;
return ret;
}
// Need a new super page.
root->totalSizeOfSuperPages += kSuperPageSize;
if (root->totalSizeOfSuperPages > kMaxPartitionSize)
partitionFull();
char* requestedAddress = root->nextSuperPage;
char* superPage = reinterpret_cast<char*>(allocPages(requestedAddress, kSuperPageSize, kSuperPageSize));
if (UNLIKELY(!superPage)) {
if (flags & PartitionAllocReturnNull)
return 0;
partitionOutOfMemory();
}
root->nextSuperPage = superPage + kSuperPageSize;
char* ret = superPage + kPartitionPageSize;
root->nextPartitionPage = ret + totalSize;
root->nextPartitionPageEnd = root->nextSuperPage - kPartitionPageSize;
// Make the first partition page in the super page a guard page, but leave a
// hole in the middle.
// This is where we put page metadata and also a tiny amount of extent
// metadata.
setSystemPagesInaccessible(superPage, kSystemPageSize);
setSystemPagesInaccessible(superPage + (kSystemPageSize * 2), kPartitionPageSize - (kSystemPageSize * 2));
// Also make the last partition page a guard page.
setSystemPagesInaccessible(superPage + (kSuperPageSize - kPartitionPageSize), kPartitionPageSize);
// If we were after a specific address, but didn't get it, assume that
// the system chose a lousy address and re-randomize the next
// allocation.
if (requestedAddress && requestedAddress != superPage)
root->nextSuperPage = 0;
// We allocated a new super page so update super page metadata.
// First check if this is a new extent or not.
PartitionSuperPageExtentEntry* latestExtent = reinterpret_cast<PartitionSuperPageExtentEntry*>(partitionSuperPageToMetadataArea(superPage));
PartitionSuperPageExtentEntry* currentExtent = root->currentExtent;
bool isNewExtent = (superPage != requestedAddress);
if (UNLIKELY(isNewExtent)) {
latestExtent->next = 0;
if (UNLIKELY(!currentExtent)) {
root->firstExtent = latestExtent;
} else {
ASSERT(currentExtent->superPageBase);
currentExtent->next = latestExtent;
}
root->currentExtent = latestExtent;
currentExtent = latestExtent;
currentExtent->superPageBase = superPage;
currentExtent->superPagesEnd = superPage + kSuperPageSize;
} else {
// We allocated next to an existing extent so just nudge the size up a little.
currentExtent->superPagesEnd += kSuperPageSize;
ASSERT(ret >= currentExtent->superPageBase && ret < currentExtent->superPagesEnd);
}
// By storing the root in every extent metadata object, we have a fast way
// to go from a pointer within the partition to the root object.
latestExtent->root = root;
return ret;
}
static ALWAYS_INLINE void partitionUnusePage(PartitionRootBase* root, PartitionPage* page)
{
ASSERT(page->bucket->numSystemPagesPerSlotSpan);
void* addr = partitionPageToPointer(page);
partitionDecommitSystemPages(root, addr, page->bucket->numSystemPagesPerSlotSpan * kSystemPageSize);
}
static ALWAYS_INLINE size_t partitionBucketSlots(const PartitionBucket* bucket)
{
return (bucket->numSystemPagesPerSlotSpan * kSystemPageSize) / bucket->slotSize;
}
static ALWAYS_INLINE size_t partitionBucketPartitionPages(const PartitionBucket* bucket)
{
return (bucket->numSystemPagesPerSlotSpan + (kNumSystemPagesPerPartitionPage - 1)) / kNumSystemPagesPerPartitionPage;
}
static ALWAYS_INLINE void partitionPageReset(PartitionPage* page, PartitionBucket* bucket)
{
ASSERT(page != &PartitionRootGeneric::gSeedPage);
page->numAllocatedSlots = 0;
page->numUnprovisionedSlots = partitionBucketSlots(bucket);
ASSERT(page->numUnprovisionedSlots);
page->bucket = bucket;
page->nextPage = 0;
// NULLing the freelist is not strictly necessary but it makes an ASSERT in partitionPageFillFreelist simpler.
page->freelistHead = 0;
page->pageOffset = 0;
page->freeCacheIndex = -1;
size_t numPartitionPages = partitionBucketPartitionPages(bucket);
size_t i;
char* pageCharPtr = reinterpret_cast<char*>(page);
for (i = 1; i < numPartitionPages; ++i) {
pageCharPtr += kPageMetadataSize;
PartitionPage* secondaryPage = reinterpret_cast<PartitionPage*>(pageCharPtr);
secondaryPage->pageOffset = i;
}
}
static ALWAYS_INLINE char* partitionPageAllocAndFillFreelist(PartitionPage* page)
{
ASSERT(page != &PartitionRootGeneric::gSeedPage);
size_t numSlots = page->numUnprovisionedSlots;
ASSERT(numSlots);
PartitionBucket* bucket = page->bucket;
// We should only get here when _every_ slot is either used or unprovisioned.
// (The third state is "on the freelist". If we have a non-empty freelist, we should not get here.)
ASSERT(numSlots + page->numAllocatedSlots == partitionBucketSlots(bucket));
// Similarly, make explicitly sure that the freelist is empty.
ASSERT(!page->freelistHead);
ASSERT(page->numAllocatedSlots >= 0);
size_t size = bucket->slotSize;
char* base = reinterpret_cast<char*>(partitionPageToPointer(page));
char* returnObject = base + (size * page->numAllocatedSlots);
char* firstFreelistPointer = returnObject + size;
char* firstFreelistPointerExtent = firstFreelistPointer + sizeof(PartitionFreelistEntry*);
// Our goal is to fault as few system pages as possible. We calculate the
// page containing the "end" of the returned slot, and then allow freelist
// pointers to be written up to the end of that page.
char* subPageLimit = reinterpret_cast<char*>((reinterpret_cast<uintptr_t>(firstFreelistPointer) + kSystemPageOffsetMask) & kSystemPageBaseMask);
char* slotsLimit = returnObject + (size * page->numUnprovisionedSlots);
char* freelistLimit = subPageLimit;
if (UNLIKELY(slotsLimit < freelistLimit))
freelistLimit = slotsLimit;
size_t numNewFreelistEntries = 0;
if (LIKELY(firstFreelistPointerExtent <= freelistLimit)) {
// Only consider used space in the slot span. If we consider wasted
// space, we may get an off-by-one when a freelist pointer fits in the
// wasted space, but a slot does not.
// We know we can fit at least one freelist pointer.
numNewFreelistEntries = 1;
// Any further entries require space for the whole slot span.
numNewFreelistEntries += (freelistLimit - firstFreelistPointerExtent) / size;
}
// We always return an object slot -- that's the +1 below.
// We do not neccessarily create any new freelist entries, because we cross sub page boundaries frequently for large bucket sizes.
ASSERT(numNewFreelistEntries + 1 <= numSlots);
numSlots -= (numNewFreelistEntries + 1);
page->numUnprovisionedSlots = numSlots;
page->numAllocatedSlots++;
if (LIKELY(numNewFreelistEntries)) {
char* freelistPointer = firstFreelistPointer;
PartitionFreelistEntry* entry = reinterpret_cast<PartitionFreelistEntry*>(freelistPointer);
page->freelistHead = entry;
while (--numNewFreelistEntries) {
freelistPointer += size;
PartitionFreelistEntry* nextEntry = reinterpret_cast<PartitionFreelistEntry*>(freelistPointer);
entry->next = partitionFreelistMask(nextEntry);
entry = nextEntry;
}
entry->next = partitionFreelistMask(0);
} else {
page->freelistHead = 0;
}
return returnObject;
}
// This helper function scans the active page list for a suitable new active
// page, starting at the passed in page.
// When it finds a suitable new active page (one that has free slots), it is
// set as the new active page and true is returned. If there is no suitable new
// active page, false is returned and the current active page is set to null.
// As potential pages are scanned, they are tidied up according to their state.
// Freed pages are swept on to the free page list and full pages are unlinked
// from any list.
static ALWAYS_INLINE bool partitionSetNewActivePage(PartitionPage* page)
{
if (page == &PartitionRootBase::gSeedPage) {
ASSERT(!page->nextPage);
return false;
}
PartitionPage* nextPage = 0;
PartitionBucket* bucket = page->bucket;
for (; page; page = nextPage) {
nextPage = page->nextPage;
ASSERT(page->bucket == bucket);
ASSERT(page != bucket->freePagesHead);
ASSERT(!bucket->freePagesHead || page != bucket->freePagesHead->nextPage);
// Page is usable if it has something on the freelist, or unprovisioned
// slots that can be turned into a freelist.
if (LIKELY(page->freelistHead != 0) || LIKELY(page->numUnprovisionedSlots)) {
bucket->activePagesHead = page;
return true;
}
ASSERT(page->numAllocatedSlots >= 0);
if (LIKELY(page->numAllocatedSlots == 0)) {
ASSERT(page->freeCacheIndex == -1);
// We hit a free page, so shepherd it on to the free page list.
page->nextPage = bucket->freePagesHead;
bucket->freePagesHead = page;
} else {
// If we get here, we found a full page. Skip over it too, and also
// tag it as full (via a negative value). We need it tagged so that
// free'ing can tell, and move it back into the active page list.
ASSERT(page->numAllocatedSlots == static_cast<int>(partitionBucketSlots(bucket)));
page->numAllocatedSlots = -page->numAllocatedSlots;
++bucket->numFullPages;
// numFullPages is a uint16_t for efficient packing so guard against
// overflow to be safe.
RELEASE_ASSERT(bucket->numFullPages);
// Not necessary but might help stop accidents.
page->nextPage = 0;
}
}
bucket->activePagesHead = 0;
return false;
}
struct PartitionDirectMapExtent {
size_t mapSize; // Mapped size, not including guard pages and meta-data.
};
static ALWAYS_INLINE PartitionDirectMapExtent* partitionPageToDirectMapExtent(PartitionPage* page)
{
ASSERT(partitionBucketIsDirectMapped(page->bucket));
return reinterpret_cast<PartitionDirectMapExtent*>(reinterpret_cast<char*>(page) + 2 * kPageMetadataSize);
}
static ALWAYS_INLINE void* partitionDirectMap(PartitionRootBase* root, int flags, size_t size)
{
size = partitionDirectMapSize(size);
// Because we need to fake looking like a super page, We need to allocate
// a bunch of system pages more than "size":
// - The first few system pages are the partition page in which the super
// page metadata is stored. We fault just one system page out of a partition
// page sized clump.
// - We add a trailing guard page.
size_t mapSize = size + kPartitionPageSize + kSystemPageSize;
// Round up to the allocation granularity.
mapSize += kPageAllocationGranularityOffsetMask;
mapSize &= kPageAllocationGranularityBaseMask;
// TODO: we may want to let the operating system place these allocations
// where it pleases. On 32-bit, this might limit address space
// fragmentation and on 64-bit, this might have useful savings for TLB
// and page table overhead.
// TODO: if upsizing realloc()s are common on large sizes, we could
// consider over-allocating address space on 64-bit, "just in case".
// TODO: consider pre-populating page tables (e.g. MAP_POPULATE on Linux,
// MADV_WILLNEED on POSIX).
// TODO: these pages will be zero-filled. Consider internalizing an
// allocZeroed() API so we can avoid a memset() entirely in this case.
char* ptr = reinterpret_cast<char*>(allocPages(0, mapSize, kSuperPageSize));
if (!ptr) {
if (flags & PartitionAllocReturnNull)
return 0;
partitionOutOfMemory();
}
char* ret = ptr + kPartitionPageSize;
// TODO: due to all the guard paging, this arrangement creates 4 mappings.
// We could get it down to three by using read-only for the metadata page,
// or perhaps two by leaving out the trailing guard page on 64-bit.
setSystemPagesInaccessible(ptr, kSystemPageSize);
setSystemPagesInaccessible(ptr + (kSystemPageSize * 2), kPartitionPageSize - (kSystemPageSize * 2));
setSystemPagesInaccessible(ret + size, kSystemPageSize);
PartitionSuperPageExtentEntry* extent = reinterpret_cast<PartitionSuperPageExtentEntry*>(partitionSuperPageToMetadataArea(ptr));
extent->root = root;
PartitionPage* page = partitionPointerToPageNoAlignmentCheck(ret);
PartitionBucket* bucket = reinterpret_cast<PartitionBucket*>(reinterpret_cast<char*>(page) + kPageMetadataSize);
page->freelistHead = 0;
page->nextPage = 0;
page->bucket = bucket;
page->numAllocatedSlots = 1;
page->numUnprovisionedSlots = 0;
page->pageOffset = 0;
page->freeCacheIndex = 0;
bucket->activePagesHead = 0;
bucket->freePagesHead = 0;
bucket->slotSize = size;
bucket->numSystemPagesPerSlotSpan = 0;
bucket->numFullPages = 0;
PartitionDirectMapExtent* mapExtent = partitionPageToDirectMapExtent(page);
mapExtent->mapSize = mapSize - kPartitionPageSize - kSystemPageSize;
return ret;
}
static ALWAYS_INLINE void partitionDirectUnmap(PartitionPage* page)
{
size_t unmapSize = partitionPageToDirectMapExtent(page)->mapSize;
// Add on the size of the trailing guard page and preceeding partition
// page.
unmapSize += kPartitionPageSize + kSystemPageSize;
ASSERT(!(unmapSize & kPageAllocationGranularityOffsetMask));
char* ptr = reinterpret_cast<char*>(partitionPageToPointer(page));
// Account for the mapping starting a partition page before the actual
// allocation address.
ptr -= kPartitionPageSize;
freePages(ptr, unmapSize);
}
void* partitionAllocSlowPath(PartitionRootBase* root, int flags, size_t size, PartitionBucket* bucket)
{
// The slow path is called when the freelist is empty.
ASSERT(!bucket->activePagesHead->freelistHead);
// For the partitionAllocGeneric API, we have a bunch of buckets marked
// as special cases. We bounce them through to the slow path so that we
// can still have a blazing fast hot path due to lack of corner-case
// branches.
bool returnNull = flags & PartitionAllocReturnNull;
if (UNLIKELY(partitionBucketIsDirectMapped(bucket))) {
ASSERT(size > kGenericMaxBucketed);
ASSERT(bucket == &PartitionRootBase::gPagedBucket);
if (size > kGenericMaxDirectMapped) {
if (returnNull)
return 0;
RELEASE_ASSERT(false);
}
return partitionDirectMap(root, flags, size);
}
// First, look for a usable page in the existing active pages list.
// Change active page, accepting the current page as a candidate.
if (LIKELY(partitionSetNewActivePage(bucket->activePagesHead))) {
PartitionPage* newPage = bucket->activePagesHead;
if (LIKELY(newPage->freelistHead != 0)) {
PartitionFreelistEntry* ret = newPage->freelistHead;
newPage->freelistHead = partitionFreelistMask(ret->next);
newPage->numAllocatedSlots++;
return ret;
}
ASSERT(newPage->numUnprovisionedSlots);
return partitionPageAllocAndFillFreelist(newPage);
}
// Second, look in our list of freed but reserved pages.
PartitionPage* newPage = bucket->freePagesHead;
if (LIKELY(newPage != 0)) {
ASSERT(newPage != &PartitionRootGeneric::gSeedPage);
ASSERT(!newPage->freelistHead);
ASSERT(!newPage->numAllocatedSlots);
ASSERT(!newPage->numUnprovisionedSlots);
ASSERT(newPage->freeCacheIndex == -1);
bucket->freePagesHead = newPage->nextPage;
void* addr = partitionPageToPointer(newPage);
partitionRecommitSystemPages(root, addr, newPage->bucket->numSystemPagesPerSlotSpan * kSystemPageSize);
} else {
// Third. If we get here, we need a brand new page.
size_t numPartitionPages = partitionBucketPartitionPages(bucket);
void* rawNewPage = partitionAllocPartitionPages(root, flags, numPartitionPages);
if (UNLIKELY(!rawNewPage)) {
ASSERT(returnNull);
return 0;
}
// Skip the alignment check because it depends on page->bucket, which is not yet set.
newPage = partitionPointerToPageNoAlignmentCheck(rawNewPage);
}
partitionPageReset(newPage, bucket);
bucket->activePagesHead = newPage;
return partitionPageAllocAndFillFreelist(newPage);
}
static ALWAYS_INLINE void partitionFreePage(PartitionRootBase* root, PartitionPage* page)
{
ASSERT(page->freelistHead);
ASSERT(!page->numAllocatedSlots);
partitionUnusePage(root, page);
// We actually leave the freed page in the active list. We'll sweep it on
// to the free page list when we next walk the active page list. Pulling
// this trick enables us to use a singly-linked page list for all cases,
// which is critical in keeping the page metadata structure down to 32
// bytes in size.
page->freelistHead = 0;
page->numUnprovisionedSlots = 0;
}
static ALWAYS_INLINE void partitionRegisterEmptyPage(PartitionPage* page)
{
PartitionRootBase* root = partitionPageToRoot(page);
// If the page is already registered as empty, give it another life.
if (page->freeCacheIndex != -1) {
ASSERT(page->freeCacheIndex >= 0);
ASSERT(static_cast<unsigned>(page->freeCacheIndex) < kMaxFreeableSpans);
ASSERT(root->globalEmptyPageRing[page->freeCacheIndex] == page);
root->globalEmptyPageRing[page->freeCacheIndex] = 0;
}
size_t currentIndex = root->globalEmptyPageRingIndex;
PartitionPage* pageToFree = root->globalEmptyPageRing[currentIndex];
// The page might well have been re-activated, filled up, etc. before we get
// around to looking at it here.
if (pageToFree) {
ASSERT(pageToFree != &PartitionRootBase::gSeedPage);
ASSERT(pageToFree->freeCacheIndex >= 0);
ASSERT(static_cast<unsigned>(pageToFree->freeCacheIndex) < kMaxFreeableSpans);
ASSERT(pageToFree == root->globalEmptyPageRing[pageToFree->freeCacheIndex]);
if (!pageToFree->numAllocatedSlots && pageToFree->freelistHead) {
// The page is still empty, and not freed, so _really_ free it.
partitionFreePage(root, pageToFree);
}
pageToFree->freeCacheIndex = -1;
}
// We put the empty slot span on our global list of "pages that were once
// empty". thus providing it a bit of breathing room to get re-used before
// we really free it. This improves performance, particularly on Mac OS X
// which has subpar memory management performance.
root->globalEmptyPageRing[currentIndex] = page;
page->freeCacheIndex = currentIndex;
++currentIndex;
if (currentIndex == kMaxFreeableSpans)
currentIndex = 0;
root->globalEmptyPageRingIndex = currentIndex;
}
void partitionFreeSlowPath(PartitionPage* page)
{
PartitionBucket* bucket = page->bucket;
ASSERT(page != &PartitionRootGeneric::gSeedPage);
ASSERT(bucket->activePagesHead != &PartitionRootGeneric::gSeedPage);
if (LIKELY(page->numAllocatedSlots == 0)) {
// Page became fully unused.
if (UNLIKELY(partitionBucketIsDirectMapped(bucket))) {
partitionDirectUnmap(page);
return;
}
// If it's the current active page, attempt to change it. We'd prefer to leave
// the page empty as a gentle force towards defragmentation.
if (LIKELY(page == bucket->activePagesHead) && page->nextPage) {
if (partitionSetNewActivePage(page->nextPage)) {
ASSERT(bucket->activePagesHead != page);
// Link the empty page back in after the new current page, to
// avoid losing a reference to it.
// TODO: consider walking the list to link the empty page after
// all non-empty pages?
PartitionPage* currentPage = bucket->activePagesHead;
page->nextPage = currentPage->nextPage;
currentPage->nextPage = page;
} else {
bucket->activePagesHead = page;
page->nextPage = 0;
}
}
partitionRegisterEmptyPage(page);
} else {
// Ensure that the page is full. That's the only valid case if we
// arrive here.
ASSERT(page->numAllocatedSlots < 0);
// A transition of numAllocatedSlots from 0 to -1 is not legal, and
// likely indicates a double-free.
RELEASE_ASSERT(page->numAllocatedSlots != -1);
page->numAllocatedSlots = -page->numAllocatedSlots - 2;
ASSERT(page->numAllocatedSlots == static_cast<int>(partitionBucketSlots(bucket) - 1));
// Fully used page became partially used. It must be put back on the
// non-full page list. Also make it the current page to increase the
// chances of it being filled up again. The old current page will be
// the next page.
page->nextPage = bucket->activePagesHead;
bucket->activePagesHead = page;
--bucket->numFullPages;
// Special case: for a partition page with just a single slot, it may
// now be empty and we want to run it through the empty logic.
if (UNLIKELY(page->numAllocatedSlots == 0))
partitionFreeSlowPath(page);
}
}
bool partitionReallocDirectMappedInPlace(PartitionRootGeneric* root, PartitionPage* page, size_t newSize)
{
ASSERT(partitionBucketIsDirectMapped(page->bucket));
newSize = partitionCookieSizeAdjustAdd(newSize);
// Note that the new size might be a bucketed size; this function is called
// whenever we're reallocating a direct mapped allocation.
newSize = partitionDirectMapSize(newSize);
if (newSize < kGenericMinDirectMappedDownsize)
return false;
// bucket->slotSize is the current size of the allocation.
size_t currentSize = page->bucket->slotSize;
if (newSize == currentSize)
return true;
char* charPtr = static_cast<char*>(partitionPageToPointer(page));
if (newSize < currentSize) {
size_t mapSize = partitionPageToDirectMapExtent(page)->mapSize;
// Don't reallocate in-place if new size is less than 80 % of the full
// map size, to avoid holding on to too much unused address space.
if ((newSize / kSystemPageSize) * 5 < (mapSize / kSystemPageSize) * 4)
return false;
// Shrink by decommitting unneeded pages and making them inaccessible.
size_t decommitSize = currentSize - newSize;
partitionDecommitSystemPages(root, charPtr + newSize, decommitSize);
setSystemPagesInaccessible(charPtr + newSize, decommitSize);
} else if (newSize <= partitionPageToDirectMapExtent(page)->mapSize) {
// Grow within the actually allocated memory. Just need to make the
// pages accessible again.
size_t recommitSize = newSize - currentSize;
setSystemPagesAccessible(charPtr + currentSize, recommitSize);
partitionRecommitSystemPages(root, charPtr + currentSize, recommitSize);
#if ENABLE(ASSERT)
memset(charPtr + currentSize, kUninitializedByte, recommitSize);
#endif
} else {
// We can't perform the realloc in-place.
// TODO: support this too when possible.
return false;
}
#if ENABLE(ASSERT)
// Write a new trailing cookie.
partitionCookieWriteValue(charPtr + newSize - kCookieSize);
#endif
page->bucket->slotSize = newSize;
return true;
}
void* partitionReallocGeneric(PartitionRootGeneric* root, void* ptr, size_t newSize)
{
#if defined(MEMORY_TOOL_REPLACES_ALLOCATOR)
return realloc(ptr, newSize);
#else
if (UNLIKELY(!ptr))
return partitionAllocGeneric(root, newSize);
if (UNLIKELY(!newSize)) {
partitionFreeGeneric(root, ptr);
return 0;
}
RELEASE_ASSERT(newSize <= kGenericMaxDirectMapped);
ASSERT(partitionPointerIsValid(partitionCookieFreePointerAdjust(ptr)));
PartitionPage* page = partitionPointerToPage(partitionCookieFreePointerAdjust(ptr));
if (UNLIKELY(partitionBucketIsDirectMapped(page->bucket))) {
// We may be able to perform the realloc in place by changing the
// accessibility of memory pages and, if reducing the size, decommitting
// them.
if (partitionReallocDirectMappedInPlace(root, page, newSize))
return ptr;
}
size_t actualNewSize = partitionAllocActualSize(root, newSize);
size_t actualOldSize = partitionAllocGetSize(ptr);
// TODO: note that tcmalloc will "ignore" a downsizing realloc() unless the
// new size is a significant percentage smaller. We could do the same if we
// determine it is a win.
if (actualNewSize == actualOldSize) {
// Trying to allocate a block of size newSize would give us a block of
// the same size as the one we've already got, so no point in doing
// anything here.
return ptr;
}
// This realloc cannot be resized in-place. Sadness.
void* ret = partitionAllocGeneric(root, newSize);
size_t copySize = actualOldSize;
if (newSize < copySize)
copySize = newSize;
memcpy(ret, ptr, copySize);
partitionFreeGeneric(root, ptr);
return ret;
#endif
}
#ifndef NDEBUG
void partitionDumpStats(const PartitionRoot& root)
{
size_t i;
size_t totalLive = 0;
size_t totalResident = 0;
size_t totalFreeable = 0;
for (i = 0; i < root.numBuckets; ++i) {
const PartitionBucket& bucket = root.buckets()[i];
if (bucket.activePagesHead == &PartitionRootGeneric::gSeedPage && !bucket.freePagesHead && !bucket.numFullPages) {
// Empty bucket with no freelist or full pages. Skip reporting it.
continue;
}
size_t numFreePages = 0;
PartitionPage* freePages = bucket.freePagesHead;
while (freePages) {
++numFreePages;
freePages = freePages->nextPage;
}
size_t bucketSlotSize = bucket.slotSize;
size_t bucketNumSlots = partitionBucketSlots(&bucket);
size_t bucketUsefulStorage = bucketSlotSize * bucketNumSlots;
size_t bucketPageSize = bucket.numSystemPagesPerSlotSpan * kSystemPageSize;
size_t bucketWaste = bucketPageSize - bucketUsefulStorage;
size_t numActiveBytes = bucket.numFullPages * bucketUsefulStorage;
size_t numResidentBytes = bucket.numFullPages * bucketPageSize;
size_t numFreeableBytes = 0;
size_t numActivePages = 0;
const PartitionPage* page = bucket.activePagesHead;
while (page) {
ASSERT(page != &PartitionRootGeneric::gSeedPage);
// A page may be on the active list but freed and not yet swept.
if (!page->freelistHead && !page->numUnprovisionedSlots && !page->numAllocatedSlots) {
++numFreePages;
} else {
++numActivePages;
numActiveBytes += (page->numAllocatedSlots * bucketSlotSize);
size_t pageBytesResident = (bucketNumSlots - page->numUnprovisionedSlots) * bucketSlotSize;
// Round up to system page size.
pageBytesResident = (pageBytesResident + kSystemPageOffsetMask) & kSystemPageBaseMask;
numResidentBytes += pageBytesResident;
if (!page->numAllocatedSlots)
numFreeableBytes += pageBytesResident;
}
page = page->nextPage;
}
totalLive += numActiveBytes;
totalResident += numResidentBytes;
totalFreeable += numFreeableBytes;
printf("bucket size %zu (pageSize %zu waste %zu): %zu alloc/%zu commit/%zu freeable bytes, %zu/%zu/%zu full/active/free pages\n", bucketSlotSize, bucketPageSize, bucketWaste, numActiveBytes, numResidentBytes, numFreeableBytes, static_cast<size_t>(bucket.numFullPages), numActivePages, numFreePages);
}
printf("total live: %zu bytes\n", totalLive);
printf("total resident: %zu bytes\n", totalResident);
printf("total freeable: %zu bytes\n", totalFreeable);
fflush(stdout);
}
#endif // !NDEBUG
} // namespace WTF
| mpcomplete/flutter_engine | sky/engine/wtf/PartitionAlloc.cpp | C++ | bsd-3-clause | 42,604 |
// Copyright 2018 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.
function waitUntilIdle() {
return new Promise(resolve=>{
window.requestIdleCallback(()=>resolve());
});
}
(async function() {
TestRunner.addResult(`Tests V8 code cache for javascript resources\n`);
await TestRunner.loadLegacyModule('timeline'); await TestRunner.loadTestModule('performance_test_runner');
await TestRunner.showPanel('timeline');
// Clear browser cache to avoid any existing entries for the fetched
// scripts in the cache.
SDK.multitargetNetworkManager.clearBrowserCache();
// There are two scripts:
// [A] http://127.0.0.1:8000/devtools/resources/v8-cache-script.cgi
// [B] http://localhost:8000/devtools/resources/v8-cache-script.cgi
// An iframe that loads [A].
// The script is executed as a parser-inserted script,
// to keep the ScriptResource on the MemoryCache.
// ScriptResources for dynamically-inserted <script>s can be
// garbage-collected and thus removed from MemoryCache after its execution.
const scope = 'resources/same-origin-script.html';
// An iframe that loads [B].
const scopeCrossOrigin = 'resources/cross-origin-script.html';
TestRunner.addResult('--- Trace events related to code caches ------');
await PerformanceTestRunner.startTimeline();
async function stopAndPrintTimeline() {
await PerformanceTestRunner.stopTimeline();
await PerformanceTestRunner.printTimelineRecordsWithDetails(
TimelineModel.TimelineModel.RecordType.CompileScript,
TimelineModel.TimelineModel.RecordType.CacheScript);
}
async function expectationComment(msg) {
await stopAndPrintTimeline();
TestRunner.addResult(msg);
await PerformanceTestRunner.startTimeline();
}
// Load [A] thrice. With the current V8 heuristics (defined in
// third_party/blink/renderer/bindings/core/v8/v8_code_cache.cc) we produce
// cache on second fetch and consume it in the third fetch. This tests these
// heuristics.
// Note that addIframe() waits for iframe's load event, which waits for the
// <script> loading.
await expectationComment('Load [A] 1st time. Produce timestamp. -->');
await TestRunner.addIframe(scope);
await expectationComment('Load [A] 2nd time. Produce code cache. -->');
await TestRunner.addIframe(scope);
await waitUntilIdle();
await expectationComment('Load [A] 3rd time. Consume code cache. -->');
await TestRunner.addIframe(scope);
await expectationComment('Load [B]. Should not use the cached code. -->');
await TestRunner.addIframe(scopeCrossOrigin);
await expectationComment('Load [A] again from MemoryCache. ' +
'Should use the cached code. -->');
await TestRunner.addIframe(scope);
await expectationComment('Clear [A] from MemoryCache. -->');
// Blink evicts previous Resource when a new request to the same URL but with
// different resource type is started. We fetch() to the URL of [A], and thus
// evicts the previous ScriptResource of [A].
await TestRunner.evaluateInPageAsync(
`fetch('/devtools/resources/v8-cache-script.cgi')`);
await expectationComment('Load [A] from Disk Cache. -->');
// As we cleared [A] from MemoryCache, this doesn't hit MemoryCache, but still
// hits Disk Cache.
await TestRunner.addIframe(scope);
await stopAndPrintTimeline();
TestRunner.addResult('-----------------------------------------------');
TestRunner.completeTest();
})();
| chromium/chromium | third_party/blink/web_tests/http/tests/devtools/isolated-code-cache/same-origin-test.js | JavaScript | bsd-3-clause | 3,533 |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
namespace WebsitePanel.Providers.HostedSolution
{
public class BaseStatistics
{
public string TopResellerName { get; set; }
public string ResellerName { get; set; }
public string CustomerName { get; set; }
public DateTime CustomerCreated { get; set; }
public string HostingSpace { get; set; }
public string OrganizationName { get; set; }
public DateTime OrganizationCreated { get; set; }
public string OrganizationID { get; set; }
public DateTime HostingSpaceCreated
{
get;
set;
}
}
}
| simonegli8/Websitepanel | WebsitePanel/Sources/WebsitePanel.Providers.Base/HostedSolution/BaseStatistics.cs | C# | bsd-3-clause | 2,325 |
<?php
/**
* PEAR_Command_Auth (login, logout commands)
*
* PHP versions 4 and 5
*
* @category pear
* @package PEAR
* @author Stig Bakken <ssb@php.net>
* @author Greg Beaver <cellog@php.net>
* @copyright 1997-2009 The Authors
* @license http://opensource.org/licenses/bsd-license.php New BSD License
* @version CVS: $Id: Auth.php,v 1.36 2009/02/24 23:39:29 dufuz Exp $
* @link http://pear.php.net/package/PEAR
* @since File available since Release 0.1
* @deprecated since 1.8.0alpha1
*/
/**
* base class
*/
require_once 'PEAR/Command/Channels.php';
/**
* PEAR commands for login/logout
*
* @category pear
* @package PEAR
* @author Stig Bakken <ssb@php.net>
* @author Greg Beaver <cellog@php.net>
* @copyright 1997-2009 The Authors
* @license http://opensource.org/licenses/bsd-license.php New BSD License
* @version Release: 1.8.1
* @link http://pear.php.net/package/PEAR
* @since Class available since Release 0.1
* @deprecated since 1.8.0alpha1
*/
class PEAR_Command_Auth extends PEAR_Command_Channels
{
var $commands = array(
'login' => array(
'summary' => 'Connects and authenticates to remote server [Deprecated in favor of channel-login]',
'shortcut' => 'li',
'function' => 'doLogin',
'options' => array(),
'doc' => '<channel name>
WARNING: This function is deprecated in favor of using channel-login
Log in to a remote channel server. If <channel name> is not supplied,
the default channel is used. To use remote functions in the installer
that require any kind of privileges, you need to log in first. The
username and password you enter here will be stored in your per-user
PEAR configuration (~/.pearrc on Unix-like systems). After logging
in, your username and password will be sent along in subsequent
operations on the remote server.',
),
'logout' => array(
'summary' => 'Logs out from the remote server [Deprecated in favor of channel-logout]',
'shortcut' => 'lo',
'function' => 'doLogout',
'options' => array(),
'doc' => '
WARNING: This function is deprecated in favor of using channel-logout
Logs out from the remote server. This command does not actually
connect to the remote server, it only deletes the stored username and
password from your user configuration.',
)
);
/**
* PEAR_Command_Auth constructor.
*
* @access public
*/
function PEAR_Command_Auth(&$ui, &$config)
{
parent::PEAR_Command_Channels($ui, $config);
}
} | PatidarWeb/pimcore | pimcore/lib/PEAR/Command/Auth.php | PHP | bsd-3-clause | 2,657 |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.Azure.ServiceBus.Amqp
{
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Azure.Amqp;
using Azure.Amqp.Encoding;
using Core;
using Framing;
using Primitives;
internal sealed class AmqpSubscriptionClient : IInnerSubscriptionClient
{
int prefetchCount;
readonly object syncLock;
MessageReceiver innerReceiver;
static AmqpSubscriptionClient()
{
AmqpCodec.RegisterKnownTypes(AmqpTrueFilterCodec.Name, AmqpTrueFilterCodec.Code, () => new AmqpTrueFilterCodec());
AmqpCodec.RegisterKnownTypes(AmqpFalseFilterCodec.Name, AmqpFalseFilterCodec.Code, () => new AmqpFalseFilterCodec());
AmqpCodec.RegisterKnownTypes(AmqpCorrelationFilterCodec.Name, AmqpCorrelationFilterCodec.Code, () => new AmqpCorrelationFilterCodec());
AmqpCodec.RegisterKnownTypes(AmqpSqlFilterCodec.Name, AmqpSqlFilterCodec.Code, () => new AmqpSqlFilterCodec());
AmqpCodec.RegisterKnownTypes(AmqpEmptyRuleActionCodec.Name, AmqpEmptyRuleActionCodec.Code, () => new AmqpEmptyRuleActionCodec());
AmqpCodec.RegisterKnownTypes(AmqpSqlRuleActionCodec.Name, AmqpSqlRuleActionCodec.Code, () => new AmqpSqlRuleActionCodec());
AmqpCodec.RegisterKnownTypes(AmqpRuleDescriptionCodec.Name, AmqpRuleDescriptionCodec.Code, () => new AmqpRuleDescriptionCodec());
}
public AmqpSubscriptionClient(
string path,
ServiceBusConnection servicebusConnection,
RetryPolicy retryPolicy,
ICbsTokenProvider cbsTokenProvider,
int prefetchCount = 0,
ReceiveMode mode = ReceiveMode.ReceiveAndDelete)
{
this.syncLock = new object();
this.Path = path;
this.ServiceBusConnection = servicebusConnection;
this.RetryPolicy = retryPolicy;
this.CbsTokenProvider = cbsTokenProvider;
this.PrefetchCount = prefetchCount;
this.ReceiveMode = mode;
}
public MessageReceiver InnerReceiver
{
get
{
if (this.innerReceiver == null)
{
lock (this.syncLock)
{
if (this.innerReceiver == null)
{
this.innerReceiver = new MessageReceiver(
this.Path,
MessagingEntityType.Subscriber,
this.ReceiveMode,
this.ServiceBusConnection,
this.CbsTokenProvider,
this.RetryPolicy,
this.PrefetchCount);
}
}
}
return this.innerReceiver;
}
}
/// <summary>
/// Gets or sets the number of messages that the subscription client can simultaneously request.
/// </summary>
/// <value>The number of messages that the subscription client can simultaneously request.</value>
public int PrefetchCount
{
get => this.prefetchCount;
set
{
if (value < 0)
{
throw Fx.Exception.ArgumentOutOfRange(nameof(this.PrefetchCount), value, "Value cannot be less than 0.");
}
this.prefetchCount = value;
if (this.innerReceiver != null)
{
this.innerReceiver.PrefetchCount = value;
}
}
}
ServiceBusConnection ServiceBusConnection { get; }
RetryPolicy RetryPolicy { get; }
ICbsTokenProvider CbsTokenProvider { get; }
ReceiveMode ReceiveMode { get; }
string Path { get; }
public Task CloseAsync()
{
return this.innerReceiver?.CloseAsync();
}
public async Task OnAddRuleAsync(RuleDescription description)
{
try
{
var amqpRequestMessage = AmqpRequestMessage.CreateRequest(
ManagementConstants.Operations.AddRuleOperation,
this.ServiceBusConnection.OperationTimeout,
null);
amqpRequestMessage.Map[ManagementConstants.Properties.RuleName] = description.Name;
amqpRequestMessage.Map[ManagementConstants.Properties.RuleDescription] =
AmqpMessageConverter.GetRuleDescriptionMap(description);
var response = await this.InnerReceiver.ExecuteRequestResponseAsync(amqpRequestMessage).ConfigureAwait(false);
if (response.StatusCode != AmqpResponseStatusCode.OK)
{
throw response.ToMessagingContractException();
}
}
catch (Exception exception)
{
throw AmqpExceptionHelper.GetClientException(exception);
}
}
public async Task OnRemoveRuleAsync(string ruleName)
{
try
{
var amqpRequestMessage =
AmqpRequestMessage.CreateRequest(
ManagementConstants.Operations.RemoveRuleOperation,
this.ServiceBusConnection.OperationTimeout,
null);
amqpRequestMessage.Map[ManagementConstants.Properties.RuleName] = ruleName;
var response = await this.InnerReceiver.ExecuteRequestResponseAsync(amqpRequestMessage).ConfigureAwait(false);
if (response.StatusCode != AmqpResponseStatusCode.OK)
{
throw response.ToMessagingContractException();
}
}
catch (Exception exception)
{
throw AmqpExceptionHelper.GetClientException(exception);
}
}
public async Task<IList<RuleDescription>> OnGetRulesAsync(int top, int skip)
{
try
{
var amqpRequestMessage =
AmqpRequestMessage.CreateRequest(
ManagementConstants.Operations.EnumerateRulesOperation,
this.ServiceBusConnection.OperationTimeout,
null);
amqpRequestMessage.Map[ManagementConstants.Properties.Top] = top;
amqpRequestMessage.Map[ManagementConstants.Properties.Skip] = skip;
var response = await this.InnerReceiver.ExecuteRequestResponseAsync(amqpRequestMessage).ConfigureAwait(false);
var ruleDescriptions = new List<RuleDescription>();
if (response.StatusCode == AmqpResponseStatusCode.OK)
{
var ruleList = response.GetListValue<AmqpMap>(ManagementConstants.Properties.Rules);
foreach (var entry in ruleList)
{
var amqpRule = (AmqpRuleDescriptionCodec)entry[ManagementConstants.Properties.RuleDescription];
var ruleDescription = AmqpMessageConverter.GetRuleDescription(amqpRule);
ruleDescriptions.Add(ruleDescription);
}
}
else if (response.StatusCode == AmqpResponseStatusCode.NoContent)
{
// Do nothing. Return empty list;
}
else
{
throw response.ToMessagingContractException();
}
return ruleDescriptions;
}
catch (Exception exception)
{
throw AmqpExceptionHelper.GetClientException(exception);
}
}
}
} | jamestao/azure-sdk-for-net | src/SDKs/ServiceBus/data-plane/src/Microsoft.Azure.ServiceBus/Amqp/AmqpSubscriptionClient.cs | C# | mit | 8,085 |
require 'support/doubled_classes'
module RSpec
module Mocks
RSpec.describe 'An instance double with the doubled class loaded' do
include_context "with isolated configuration"
before do
RSpec::Mocks.configuration.verify_doubled_constant_names = true
end
it 'only allows instance methods that exist to be stubbed' do
o = instance_double('LoadedClass', :defined_instance_method => 1)
expect(o.defined_instance_method).to eq(1)
prevents(/does not implement the instance method/) { allow(o).to receive(:undefined_instance_method) }
prevents(/does not implement the instance method/) { allow(o).to receive(:defined_class_method) }
end
it 'only allows instance methods that exist to be expected' do
o = instance_double('LoadedClass')
expect(o).to receive(:defined_instance_method)
o.defined_instance_method
prevents { expect(o).to receive(:undefined_instance_method) }
prevents { expect(o).to receive(:defined_class_method) }
prevents { expect(o).to receive(:undefined_instance_method) }
prevents { expect(o).to receive(:defined_class_method) }
end
USE_CLASS_DOUBLE_MSG = "Perhaps you meant to use `class_double`"
it "suggests using `class_double` when a class method is stubbed" do
o = instance_double("LoadedClass")
prevents(a_string_including(USE_CLASS_DOUBLE_MSG)) { allow(o).to receive(:defined_class_method) }
end
it "doesn't suggest `class_double` when a non-class method is stubbed" do
o = instance_double("LoadedClass")
prevents(a_string_excluding(USE_CLASS_DOUBLE_MSG)) { allow(o).to receive(:undefined_class_method) }
end
it 'allows `send` to be stubbed if it is defined on the class' do
o = instance_double('LoadedClass')
allow(o).to receive(:send).and_return("received")
expect(o.send(:msg)).to eq("received")
end
it 'gives a descriptive error message for NoMethodError' do
o = instance_double("LoadedClass")
expect {
o.defined_private_method
}.to raise_error(NoMethodError,
a_string_including("InstanceDouble(LoadedClass)"))
end
it 'does not allow dynamic methods to be expected' do
# This isn't possible at the moment since an instance of the class
# would be required for the verification, and we only have the
# class itself.
#
# This spec exists as "negative" documentation of the absence of a
# feature, to highlight the asymmetry from class doubles (that do
# support this behaviour).
prevents {
instance_double('LoadedClass', :dynamic_instance_method => 1)
}
end
it 'checks the arity of stubbed methods' do
o = instance_double('LoadedClass')
prevents {
expect(o).to receive(:defined_instance_method).with(:a)
}
reset o
end
it 'checks that stubbed methods are invoked with the correct arity' do
o = instance_double('LoadedClass', :defined_instance_method => 25)
expect {
o.defined_instance_method(:a)
}.to raise_error(ArgumentError,
"Wrong number of arguments. Expected 0, got 1.")
end
if required_kw_args_supported?
it 'allows keyword arguments' do
o = instance_double('LoadedClass', :kw_args_method => true)
expect(o.kw_args_method(1, :required_arg => 'something')).to eq(true)
end
context 'for a method that only accepts keyword args' do
it 'allows hash matchers like `hash_including` to be used in place of the keywords arg hash' do
o = instance_double('LoadedClass')
expect(o).to receive(:kw_args_method).
with(1, hash_including(:required_arg => 1))
o.kw_args_method(1, :required_arg => 1)
end
it 'allows anything matcher to be used in place of the keywords arg hash' do
o = instance_double('LoadedClass')
expect(o).to receive(:kw_args_method).with(1, anything)
o.kw_args_method(1, :required_arg => 1)
end
it 'still checks positional arguments when matchers used for keyword args' do
o = instance_double('LoadedClass')
prevents(/Expected 1, got 3/) {
expect(o).to receive(:kw_args_method).
with(1, 2, 3, hash_including(:required_arg => 1))
}
reset o
end
it 'does not allow matchers to be used in an actual method call' do
o = instance_double('LoadedClass')
matcher = hash_including(:required_arg => 1)
allow(o).to receive(:kw_args_method).with(1, matcher)
expect {
o.kw_args_method(1, matcher)
}.to raise_error(ArgumentError)
end
end
context 'for a method that accepts a mix of optional keyword and positional args' do
it 'allows hash matchers like `hash_including` to be used in place of the keywords arg hash' do
o = instance_double('LoadedClass')
expect(o).to receive(:mixed_args_method).with(1, 2, hash_including(:optional_arg_1 => 1))
o.mixed_args_method(1, 2, :optional_arg_1 => 1)
end
end
it 'checks that stubbed methods with required keyword args are ' +
'invoked with the required arguments' do
o = instance_double('LoadedClass', :kw_args_method => true)
expect {
o.kw_args_method(:optional_arg => 'something')
}.to raise_error(ArgumentError)
end
end
it 'validates `with` args against the method signature when stubbing a method' do
dbl = instance_double(LoadedClass)
prevents(/Wrong number of arguments. Expected 2, got 3./) {
allow(dbl).to receive(:instance_method_with_two_args).with(3, :foo, :args)
}
end
it 'allows class to be specified by constant' do
o = instance_double(LoadedClass, :defined_instance_method => 1)
expect(o.defined_instance_method).to eq(1)
end
context "when the class const has been previously stubbed" do
before { class_double(LoadedClass).as_stubbed_const }
it "uses the original class to verify against for `instance_double('LoadedClass')`" do
o = instance_double("LoadedClass")
allow(o).to receive(:defined_instance_method)
prevents { allow(o).to receive(:undefined_method) }
end
it "uses the original class to verify against for `instance_double(LoadedClass)`" do
o = instance_double(LoadedClass)
allow(o).to receive(:defined_instance_method)
prevents { allow(o).to receive(:undefined_method) }
end
end
context "when given a class that has an overriden `#name` method" do
it "properly verifies" do
o = instance_double(LoadedClassWithOverridenName)
allow(o).to receive(:defined_instance_method)
prevents { allow(o).to receive(:undefined_method) }
end
end
context 'for null objects' do
let(:obj) { instance_double('LoadedClass').as_null_object }
it 'only allows defined methods' do
expect(obj.defined_instance_method).to eq(obj)
prevents { obj.undefined_method }
prevents { obj.send(:undefined_method) }
prevents { obj.__send__(:undefined_method) }
end
it 'verifies arguments' do
expect {
obj.defined_instance_method(:too, :many, :args)
}.to raise_error(ArgumentError, "Wrong number of arguments. Expected 0, got 3.")
end
it "includes the double's name in a private method error" do
expect {
obj.rand
}.to raise_error(NoMethodError, a_string_including("private", "InstanceDouble(LoadedClass)"))
end
it 'reports what public messages it responds to accurately' do
expect(obj.respond_to?(:defined_instance_method)).to be true
expect(obj.respond_to?(:defined_instance_method, true)).to be true
expect(obj.respond_to?(:defined_instance_method, false)).to be true
expect(obj.respond_to?(:undefined_method)).to be false
expect(obj.respond_to?(:undefined_method, true)).to be false
expect(obj.respond_to?(:undefined_method, false)).to be false
end
it 'reports that it responds to defined private methods when the appropriate arg is passed' do
expect(obj.respond_to?(:defined_private_method)).to be false
expect(obj.respond_to?(:defined_private_method, true)).to be true
expect(obj.respond_to?(:defined_private_method, false)).to be false
end
if RUBY_VERSION.to_f < 2.0 # respond_to?(:protected_method) changed behavior in Ruby 2.0.
it 'reports that it responds to protected methods' do
expect(obj.respond_to?(:defined_protected_method)).to be true
expect(obj.respond_to?(:defined_protected_method, true)).to be true
expect(obj.respond_to?(:defined_protected_method, false)).to be true
end
else
it 'reports that it responds to protected methods when the appropriate arg is passed' do
expect(obj.respond_to?(:defined_protected_method)).to be false
expect(obj.respond_to?(:defined_protected_method, true)).to be true
expect(obj.respond_to?(:defined_protected_method, false)).to be false
end
end
end
end
end
end
| ducthanh/rspec-mocks | spec/rspec/mocks/verifying_doubles/instance_double_with_class_loaded_spec.rb | Ruby | mit | 9,728 |
######################## BEGIN LICENSE BLOCK ########################
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1998
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Mark Pilgrim - port to Python
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
######################### END LICENSE BLOCK #########################
from .mbcharsetprober import MultiByteCharSetProber
from .codingstatemachine import CodingStateMachine
from .chardistribution import EUCTWDistributionAnalysis
from .mbcssm import EUCTW_SM_MODEL
class EUCTWProber(MultiByteCharSetProber):
def __init__(self):
super(EUCTWProber, self).__init__()
self.coding_sm = CodingStateMachine(EUCTW_SM_MODEL)
self.distribution_analyzer = EUCTWDistributionAnalysis()
self.reset()
@property
def charset_name(self):
return "EUC-TW"
@property
def language(self):
return "Taiwan"
| ncos/lisa | src/lisa_drive/scripts/venv/lib/python3.5/site-packages/pip-10.0.1-py3.5.egg/pip/_vendor/chardet/euctwprober.py | Python | mit | 1,793 |
// This is not the set of all possible signals.
//
// It IS, however, the set of all signals that trigger
// an exit on either Linux or BSD systems. Linux is a
// superset of the signal names supported on BSD, and
// the unknown signals just fail to register, so we can
// catch that easily enough.
//
// Don't bother with SIGKILL. It's uncatchable, which
// means that we can't fire any callbacks anyway.
//
// If a user does happen to register a handler on a non-
// fatal signal like SIGWINCH or something, and then
// exit, it'll end up firing `process.emit('exit')`, so
// the handler will be fired anyway.
//
// SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised
// artificially, inherently leave the process in a
// state from which it is not safe to try and enter JS
// listeners.
module.exports = [
'SIGABRT',
'SIGALRM',
'SIGHUP',
'SIGINT',
'SIGTERM'
]
if (process.platform !== 'win32') {
module.exports.push(
'SIGVTALRM',
'SIGXCPU',
'SIGXFSZ',
'SIGUSR2',
'SIGTRAP',
'SIGSYS',
'SIGQUIT',
'SIGIOT'
// should detect profiler and enable/disable accordingly.
// see #21
// 'SIGPROF'
)
}
if (process.platform === 'linux') {
module.exports.push(
'SIGIO',
'SIGPOLL',
'SIGPWR',
'SIGSTKFLT',
'SIGUNUSED'
)
}
| Moccine/global-service-plus.com | web/libariries/bootstrap/node_modules/signal-exit/signals.js | JavaScript | mit | 1,348 |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace BlueYonderDemo
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
PanelToggle.Click += PanelToggle_Click;
}
private void PanelToggle_Click(object sender, RoutedEventArgs e)
{
if (MenuSplitView.IsPaneOpen)
{
MenuSplitView.IsPaneOpen = false;
if (MenuSplitView.DisplayMode == SplitViewDisplayMode.Inline)
{
MenuSplitView.DisplayMode = SplitViewDisplayMode.CompactInline;
}
}
else
{
MenuSplitView.IsPaneOpen = true;
}
}
}
}
| tiagocostapt/WinDevWorkshop | Presentations/01. Introduction to UWP/Demos/AdaptiveUI/BlueYonderDemo/MainPage.xaml.cs | C# | mit | 1,383 |
import { css, StyleSheet } from 'aphrodite/no-important';
import React, { PropTypes } from 'react';
import octicons from './octicons';
import colors from './colors';
import sizes from './sizes';
import styles from './styles';
const classes = StyleSheet.create(styles);
// FIXME static octicon classes leaning on Elemental to avoid duplicate
// font and CSS; inflating the project size
function Glyph ({
aphroditeStyles,
className,
color,
component: Component,
name,
size,
style,
...props
}) {
const colorIsValidType = Object.keys(colors).includes(color);
props.className = css(
classes.glyph,
colorIsValidType && classes['color__' + color],
classes['size__' + size],
aphroditeStyles
) + ` ${octicons[name]}`;
if (className) {
props.className += (' ' + className);
}
// support random color strings
props.style = {
color: !colorIsValidType ? color : null,
...style,
};
return <Component {...props} />;
};
Glyph.propTypes = {
aphroditeStyles: PropTypes.shape({
_definition: PropTypes.object,
_name: PropTypes.string,
}),
color: PropTypes.oneOfType([
PropTypes.oneOf(Object.keys(colors)),
PropTypes.string, // support random color strings
]),
name: PropTypes.oneOf(Object.keys(octicons)).isRequired,
size: PropTypes.oneOf(Object.keys(sizes)),
};
Glyph.defaultProps = {
component: 'i',
color: 'inherit',
size: 'small',
};
module.exports = Glyph;
| linhanyang/keystone | admin/client/App/elemental/Glyph/index.js | JavaScript | mit | 1,398 |
"""The tests for the heat control thermostat."""
import unittest
from homeassistant.bootstrap import _setup_component
from homeassistant.const import (
ATTR_UNIT_OF_MEASUREMENT,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
STATE_ON,
STATE_OFF,
TEMP_CELSIUS,
)
from homeassistant.components import thermostat
from tests.common import get_test_home_assistant
ENTITY = 'thermostat.test'
ENT_SENSOR = 'sensor.test'
ENT_SWITCH = 'switch.test'
MIN_TEMP = 3.0
MAX_TEMP = 65.0
TARGET_TEMP = 42.0
class TestSetupThermostatHeatControl(unittest.TestCase):
"""Test the Heat Control thermostat with custom config."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
self.hass = get_test_home_assistant()
def tearDown(self): # pylint: disable=invalid-name
"""Stop down everything that was started."""
self.hass.stop()
def test_setup_missing_conf(self):
"""Test set up heat_control with missing config values."""
config = {
'name': 'test',
'target_sensor': ENT_SENSOR
}
self.assertFalse(_setup_component(self.hass, 'thermostat', {
'thermostat': config}))
def test_valid_conf(self):
"""Test set up heat_control with valid config values."""
self.assertTrue(_setup_component(self.hass, 'thermostat',
{'thermostat': {
'platform': 'heat_control',
'name': 'test',
'heater': ENT_SWITCH,
'target_sensor': ENT_SENSOR}}))
def test_setup_with_sensor(self):
"""Test set up heat_control with sensor to trigger update at init."""
self.hass.states.set(ENT_SENSOR, 22.0, {
ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS
})
thermostat.setup(self.hass, {'thermostat': {
'platform': 'heat_control',
'name': 'test',
'heater': ENT_SWITCH,
'target_sensor': ENT_SENSOR
}})
state = self.hass.states.get(ENTITY)
self.assertEqual(
TEMP_CELSIUS, state.attributes.get('unit_of_measurement'))
self.assertEqual(22.0, state.attributes.get('current_temperature'))
class TestThermostatHeatControl(unittest.TestCase):
"""Test the Heat Control thermostat."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.hass.config.temperature_unit = TEMP_CELSIUS
thermostat.setup(self.hass, {'thermostat': {
'platform': 'heat_control',
'name': 'test',
'heater': ENT_SWITCH,
'target_sensor': ENT_SENSOR
}})
def tearDown(self): # pylint: disable=invalid-name
"""Stop down everything that was started."""
self.hass.stop()
def test_setup_defaults_to_unknown(self):
"""Test the setting of defaults to unknown."""
self.assertEqual('unknown', self.hass.states.get(ENTITY).state)
def test_default_setup_params(self):
"""Test the setup with default parameters."""
state = self.hass.states.get(ENTITY)
self.assertEqual(7, state.attributes.get('min_temp'))
self.assertEqual(35, state.attributes.get('max_temp'))
self.assertEqual(None, state.attributes.get('temperature'))
def test_custom_setup_params(self):
"""Test the setup with custom parameters."""
thermostat.setup(self.hass, {'thermostat': {
'platform': 'heat_control',
'name': 'test',
'heater': ENT_SWITCH,
'target_sensor': ENT_SENSOR,
'min_temp': MIN_TEMP,
'max_temp': MAX_TEMP,
'target_temp': TARGET_TEMP
}})
state = self.hass.states.get(ENTITY)
self.assertEqual(MIN_TEMP, state.attributes.get('min_temp'))
self.assertEqual(MAX_TEMP, state.attributes.get('max_temp'))
self.assertEqual(TARGET_TEMP, state.attributes.get('temperature'))
self.assertEqual(str(TARGET_TEMP), self.hass.states.get(ENTITY).state)
def test_set_target_temp(self):
"""Test the setting of the target temperature."""
thermostat.set_temperature(self.hass, 30)
self.hass.pool.block_till_done()
self.assertEqual('30.0', self.hass.states.get(ENTITY).state)
def test_sensor_bad_unit(self):
"""Test sensor that have bad unit."""
self._setup_sensor(22.0, unit='bad_unit')
self.hass.pool.block_till_done()
state = self.hass.states.get(ENTITY)
self.assertEqual(None, state.attributes.get('unit_of_measurement'))
self.assertEqual(None, state.attributes.get('current_temperature'))
def test_sensor_bad_value(self):
"""Test sensor that have None as state."""
self._setup_sensor(None)
self.hass.pool.block_till_done()
state = self.hass.states.get(ENTITY)
self.assertEqual(None, state.attributes.get('unit_of_measurement'))
self.assertEqual(None, state.attributes.get('current_temperature'))
def test_set_target_temp_heater_on(self):
"""Test if target temperature turn heater on."""
self._setup_switch(False)
self._setup_sensor(25)
self.hass.pool.block_till_done()
thermostat.set_temperature(self.hass, 30)
self.hass.pool.block_till_done()
self.assertEqual(1, len(self.calls))
call = self.calls[0]
self.assertEqual('switch', call.domain)
self.assertEqual(SERVICE_TURN_ON, call.service)
self.assertEqual(ENT_SWITCH, call.data['entity_id'])
def test_set_target_temp_heater_off(self):
"""Test if target temperature turn heater off."""
self._setup_switch(True)
self._setup_sensor(30)
self.hass.pool.block_till_done()
thermostat.set_temperature(self.hass, 25)
self.hass.pool.block_till_done()
self.assertEqual(1, len(self.calls))
call = self.calls[0]
self.assertEqual('switch', call.domain)
self.assertEqual(SERVICE_TURN_OFF, call.service)
self.assertEqual(ENT_SWITCH, call.data['entity_id'])
def test_set_temp_change_heater_on(self):
"""Test if temperature change turn heater on."""
self._setup_switch(False)
thermostat.set_temperature(self.hass, 30)
self.hass.pool.block_till_done()
self._setup_sensor(25)
self.hass.pool.block_till_done()
self.assertEqual(1, len(self.calls))
call = self.calls[0]
self.assertEqual('switch', call.domain)
self.assertEqual(SERVICE_TURN_ON, call.service)
self.assertEqual(ENT_SWITCH, call.data['entity_id'])
def test_temp_change_heater_off(self):
"""Test if temperature change turn heater off."""
self._setup_switch(True)
thermostat.set_temperature(self.hass, 25)
self.hass.pool.block_till_done()
self._setup_sensor(30)
self.hass.pool.block_till_done()
self.assertEqual(1, len(self.calls))
call = self.calls[0]
self.assertEqual('switch', call.domain)
self.assertEqual(SERVICE_TURN_OFF, call.service)
self.assertEqual(ENT_SWITCH, call.data['entity_id'])
def _setup_sensor(self, temp, unit=TEMP_CELSIUS):
"""Setup the test sensor."""
self.hass.states.set(ENT_SENSOR, temp, {
ATTR_UNIT_OF_MEASUREMENT: unit
})
def _setup_switch(self, is_on):
"""Setup the test switch."""
self.hass.states.set(ENT_SWITCH, STATE_ON if is_on else STATE_OFF)
self.calls = []
def log_call(call):
"""Log service calls."""
self.calls.append(call)
self.hass.services.register('switch', SERVICE_TURN_ON, log_call)
self.hass.services.register('switch', SERVICE_TURN_OFF, log_call)
| deisi/home-assistant | tests/components/thermostat/test_heat_control.py | Python | mit | 7,976 |
# $Id$
#
# Author:: Francis Cianfrocca (gmail: blackhedd)
# Homepage:: http://rubyeventmachine.com
# Date:: 8 April 2006
#
# See EventMachine and EventMachine::Connection for documentation and
# usage examples.
#
#----------------------------------------------------------------------------
#
# Copyright (C) 2006-07 by Francis Cianfrocca. All Rights Reserved.
# Gmail: blackhedd
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of either: 1) 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; or 2) Ruby's License.
#
# See the file COPYING for complete licensing information.
#
#---------------------------------------------------------------------------
#
#
#
$:.unshift "../lib"
require 'eventmachine'
require 'socket'
require 'test/unit'
class TestServers < Test::Unit::TestCase
Host = "127.0.0.1"
Port = 9555
module NetstatHelper
GlobalUdp4Rexp = /udp.*\s+(?:\*|(?:0\.){3}0)[:.](\d+)\s/i
GlobalTcp4Rexp = /tcp.*\s+(?:\*|(?:0\.){3}0)[:.](\d+)\s/i
LocalUdpRexp = /udp.*\s+(?:127\.0\.0\.1|::1)[:.](\d+)\s/i
LocalTcpRexp = /tcp.*\s+(?:127\.0\.0\.1|::1)[:.](\d+)\s/i
def grep_netstat(pattern)
`netstat -an`.scan(/^.*$/).grep(pattern)
end
end
include NetstatHelper
class TestStopServer < EM::Connection
def initialize *args
super
end
def post_init
# TODO,sucks that this isn't OOPy enough.
EM.stop_server @server_instance
end
end
def run_test_stop_server
EM.run {
sig = EM.start_server(Host, Port)
assert(grep_netstat(LocalTcpRexp).grep(%r(#{Port})).size >= 1, "Server didn't start")
EM.stop_server sig
# Give the server some time to shutdown.
EM.add_timer(0.1) {
assert(grep_netstat(LocalTcpRexp).grep(%r(#{Port})).empty?, "Servers didn't stop")
EM.stop
}
}
end
def test_stop_server
assert(grep_netstat(LocalTcpRexp).grep(Port).empty?, "Port already in use")
5.times {run_test_stop_server}
assert(grep_netstat(LocalTcpRexp).grep(%r(#{Port})).empty?, "Servers didn't stop")
end
end
| mattgraham/play-graham | vendor/gems/ruby/1.8/gems/eventmachine-0.12.10/tests/test_servers.rb | Ruby | mit | 2,198 |
angular.module('merchello.plugins.braintree').controller('Merchello.Plugins.GatewayProviders.Dialogs.PaymentMethodAddEditController',
['$scope', 'braintreeProviderSettingsBuilder',
function($scope, braintreeProviderSettingsBuilder) {
$scope.providerSettings = {};
function init() {
var json = JSON.parse($scope.dialogData.provider.extendedData.getValue('braintreeProviderSettings'));
$scope.providerSettings = braintreeProviderSettingsBuilder.transform(json);
$scope.$watch(function () {
return $scope.providerSettings;
}, function (newValue, oldValue) {
$scope.dialogData.provider.extendedData.setValue('braintreeProviderSettings', angular.toJson(newValue));
}, true);
}
// initialize the controller
init();
}]); | bjarnef/Merchello | src/Merchello.Web.UI/App_Plugins/Merchello.Braintree/payment.braintree.providersettings.controller.js | JavaScript | mit | 922 |
// (C) Copyright 1996-2006 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
// DESCRIPTION:
//
// Source file for the ObjectARX application command "BRBBLOCK".
#include "brsample_pch.h" //precompiled header
//This is been defined for future use. all headers should be under this guard.
// include here
void
dumpBblock()
{
AcBr::ErrorStatus returnValue = AcBr::eOk;
// Select the entity by type
AcBrEntity* pEnt = NULL;
AcDb::SubentType subType = AcDb::kNullSubentType;
returnValue = selectEntityByType(pEnt, subType);
if (returnValue != AcBr::eOk) {
acutPrintf(ACRX_T("\n Error in selectEntityByType:"));
errorReport(returnValue);
delete pEnt;
return;
}
AcGeBoundBlock3d bblock;
returnValue = pEnt->getBoundBlock(bblock);
if (returnValue != AcBr::eOk) {
acutPrintf(ACRX_T("\n Error in AcBrEntity::getBoundBlock:"));
errorReport(returnValue);
delete pEnt;
return;
}
delete pEnt;
AcGePoint3d min, max;
bblock.getMinMaxPoints(min, max);
bblockReport(min, max);
return;
}
| kevinzhwl/ObjectARXCore | 2013/utils/brep/samples/brepsamp/brbblock.cpp | C++ | mit | 1,979 |
using ArmyOfCreatures.Logic.Creatures;
namespace ArmyOfCreatures.Logic
{
public interface ICreaturesFactory
{
Creature CreateCreature(string name);
}
}
| shopOFF/TelerikAcademyCourses | Unit-Testing/Unit-Testing/Topics/04. Workshop (Trainers)/ArmyOfCreatures-Evening-livedemo/ArmyOfCreatures-All/Solution/ArmyOfCreatures/Logic/ICreaturesFactory.cs | C# | mit | 176 |
# Configure Rails Envinronment
ENV["RAILS_ENV"] = "test"
require File.expand_path("../../config/environment.rb", __FILE__)
require "rails/test_help"
Rails.backtrace_cleaner.remove_silencers!
| DouglasAllen/site-camping | vendor/gems/ruby/2.2.0/gems/mab-0.0.3/test/rails/test/helper.rb | Ruby | mit | 193 |
using namespace System;
using namespace NETGeographicLib;
int main(array<System::String ^> ^/*args*/)
{
try {
Geodesic^ geod = gcnew Geodesic(); // WGS84
const double lat0 = 48 + 50/60.0, lon0 = 2 + 20/60.0; // Paris
Gnomonic^ proj = gcnew Gnomonic(geod);
{
// Sample forward calculation
double lat = 50.9, lon = 1.8; // Calais
double x, y;
proj->Forward(lat0, lon0, lat, lon, x, y);
Console::WriteLine(String::Format("X: {0} Y: {1}", x, y));
}
{
// Sample reverse calculation
double x = -38e3, y = 230e3;
double lat, lon;
proj->Reverse(lat0, lon0, x, y, lat, lon);
Console::WriteLine(String::Format("Latitude: {0} Longitude: {1}", lat, lon));
}
}
catch (GeographicErr^ e) {
Console::WriteLine(String::Format("Caught exception: {0}", e->Message));
return -1;
}
return 0;
}
| JanEicken/MA | libs/GeographicLib-1.43/dotnet/examples/ManagedCPP/example-Gnomonic.cpp | C++ | mit | 986 |
(function () {
'use strict';
function ContentEditController($rootScope, $scope, $routeParams, $q, $timeout, $window, $location, appState, contentResource, entityResource, navigationService, notificationsService, angularHelper, serverValidationManager, contentEditingHelper, treeService, fileManager, formHelper, umbRequestHelper, keyboardService, umbModelMapper, editorState, $http, eventsService, relationResource) {
var evts = [];
//setup scope vars
$scope.defaultButton = null;
$scope.subButtons = [];
$scope.page = {};
$scope.page.loading = false;
$scope.page.menu = {};
$scope.page.menu.currentNode = null;
$scope.page.menu.currentSection = appState.getSectionState("currentSection");
$scope.page.listViewPath = null;
$scope.page.isNew = $scope.isNew ? true : false;
$scope.page.buttonGroupState = "init";
$scope.allowOpen = true;
function init(content) {
createButtons(content);
editorState.set($scope.content);
//We fetch all ancestors of the node to generate the footer breadcrumb navigation
if (!$scope.page.isNew) {
if (content.parentId && content.parentId !== -1) {
entityResource.getAncestors(content.id, "document")
.then(function (anc) {
$scope.ancestors = anc;
});
}
}
evts.push(eventsService.on("editors.content.changePublishDate", function (event, args) {
createButtons(args.node);
}));
evts.push(eventsService.on("editors.content.changeUnpublishDate", function (event, args) {
createButtons(args.node);
}));
// We don't get the info tab from the server from version 7.8 so we need to manually add it
contentEditingHelper.addInfoTab($scope.content.tabs);
}
function getNode() {
$scope.page.loading = true;
//we are editing so get the content item from the server
$scope.getMethod()($scope.contentId)
.then(function (data) {
$scope.content = data;
if (data.isChildOfListView && data.trashed === false) {
$scope.page.listViewPath = ($routeParams.page) ?
"/content/content/edit/" + data.parentId + "?page=" + $routeParams.page :
"/content/content/edit/" + data.parentId;
}
init($scope.content);
//in one particular special case, after we've created a new item we redirect back to the edit
// route but there might be server validation errors in the collection which we need to display
// after the redirect, so we will bind all subscriptions which will show the server validation errors
// if there are any and then clear them so the collection no longer persists them.
serverValidationManager.executeAndClearAllSubscriptions();
syncTreeNode($scope.content, data.path, true);
resetLastListPageNumber($scope.content);
eventsService.emit("content.loaded", { content: $scope.content });
$scope.page.loading = false;
});
}
function createButtons(content) {
$scope.page.buttonGroupState = "init";
var buttons = contentEditingHelper.configureContentEditorButtons({
create: $scope.page.isNew,
content: content,
methods: {
saveAndPublish: $scope.saveAndPublish,
sendToPublish: $scope.sendToPublish,
save: $scope.save,
unPublish: $scope.unPublish
}
});
$scope.defaultButton = buttons.defaultButton;
$scope.subButtons = buttons.subButtons;
}
/** Syncs the content item to it's tree node - this occurs on first load and after saving */
function syncTreeNode(content, path, initialLoad) {
if (!$scope.content.isChildOfListView) {
navigationService.syncTree({ tree: $scope.treeAlias, path: path.split(","), forceReload: initialLoad !== true }).then(function (syncArgs) {
$scope.page.menu.currentNode = syncArgs.node;
});
}
else if (initialLoad === true) {
//it's a child item, just sync the ui node to the parent
navigationService.syncTree({ tree: $scope.treeAlias, path: path.substring(0, path.lastIndexOf(",")).split(","), forceReload: initialLoad !== true });
//if this is a child of a list view and it's the initial load of the editor, we need to get the tree node
// from the server so that we can load in the actions menu.
umbRequestHelper.resourcePromise(
$http.get(content.treeNodeUrl),
'Failed to retrieve data for child node ' + content.id).then(function (node) {
$scope.page.menu.currentNode = node;
});
}
}
// This is a helper method to reduce the amount of code repitition for actions: Save, Publish, SendToPublish
function performSave(args) {
var deferred = $q.defer();
$scope.page.buttonGroupState = "busy";
eventsService.emit("content.saving", { content: $scope.content, action: args.action });
contentEditingHelper.contentEditorPerformSave({
statusMessage: args.statusMessage,
saveMethod: args.saveMethod,
scope: $scope,
content: $scope.content,
action: args.action
}).then(function (data) {
//success
init($scope.content);
syncTreeNode($scope.content, data.path);
$scope.page.buttonGroupState = "success";
deferred.resolve(data);
eventsService.emit("content.saved", { content: $scope.content, action: args.action });
}, function (err) {
//error
if (err) {
editorState.set($scope.content);
}
$scope.page.buttonGroupState = "error";
deferred.reject(err);
});
return deferred.promise;
}
function resetLastListPageNumber(content) {
// We're using rootScope to store the page number for list views, so if returning to the list
// we can restore the page. If we've moved on to edit a piece of content that's not the list or it's children
// we should remove this so as not to confuse if navigating to a different list
if (!content.isChildOfListView && !content.isContainer) {
$rootScope.lastListViewPageViewed = null;
}
}
if ($scope.page.isNew) {
$scope.page.loading = true;
//we are creating so get an empty content item
$scope.getScaffoldMethod()()
.then(function (data) {
$scope.content = data;
init($scope.content);
resetLastListPageNumber($scope.content);
$scope.page.loading = false;
eventsService.emit("content.newReady", { content: $scope.content });
});
}
else {
getNode();
}
$scope.unPublish = function () {
// raising the event triggers the confirmation dialog
if (!notificationsService.hasView()) {
notificationsService.add({ view: "confirmunpublish" });
}
$scope.page.buttonGroupState = "busy";
// actioning the dialog raises the confirmUnpublish event, act on it here
var actioned = $rootScope.$on("content.confirmUnpublish", function(event, confirmed) {
if (confirmed && formHelper.submitForm({ scope: $scope, statusMessage: "Unpublishing...", skipValidation: true })) {
eventsService.emit("content.unpublishing", { content: $scope.content });
contentResource.unPublish($scope.content.id)
.then(function (data) {
formHelper.resetForm({ scope: $scope, notifications: data.notifications });
contentEditingHelper.handleSuccessfulSave({
scope: $scope,
savedContent: data,
rebindCallback: contentEditingHelper.reBindChangedProperties($scope.content, data)
});
init($scope.content);
syncTreeNode($scope.content, data.path);
$scope.page.buttonGroupState = "success";
eventsService.emit("content.unpublished", { content: $scope.content });
}, function(err) {
formHelper.showNotifications(err.data);
$scope.page.buttonGroupState = 'error';
});
} else {
$scope.page.buttonGroupState = "init";
}
// unsubscribe to avoid queueing notifications
// listener is re-bound when the unpublish button is clicked so it is created just-in-time
actioned();
});
};
$scope.sendToPublish = function () {
return performSave({ saveMethod: contentResource.sendToPublish, statusMessage: "Sending...", action: "sendToPublish" });
};
$scope.saveAndPublish = function () {
return performSave({ saveMethod: contentResource.publish, statusMessage: "Publishing...", action: "publish" });
};
$scope.save = function () {
return performSave({ saveMethod: $scope.saveMethod(), statusMessage: "Saving...", action: "save" });
};
$scope.preview = function (content) {
if (!$scope.busy) {
// Chromes popup blocker will kick in if a window is opened
// without the initial scoped request. This trick will fix that.
//
var previewWindow = $window.open('preview/?init=true&id=' + content.id, 'umbpreview');
// Build the correct path so both /#/ and #/ work.
var redirect = Umbraco.Sys.ServerVariables.umbracoSettings.umbracoPath + '/preview/?id=' + content.id;
//The user cannot save if they don't have access to do that, in which case we just want to preview
//and that's it otherwise they'll get an unauthorized access message
if (!_.contains(content.allowedActions, "A")) {
previewWindow.location.href = redirect;
}
else {
$scope.save().then(function (data) {
previewWindow.location.href = redirect;
});
}
}
};
$scope.restore = function (content) {
$scope.page.buttonRestore = "busy";
relationResource.getByChildId(content.id, "relateParentDocumentOnDelete").then(function (data) {
var relation = null;
var target = null;
var error = { headline: "Cannot automatically restore this item", content: "Use the Move menu item to move it manually"};
if (data.length == 0) {
notificationsService.error(error.headline, "There is no 'restore' relation found for this node. Use the Move menu item to move it manually.");
$scope.page.buttonRestore = "error";
return;
}
relation = data[0];
if (relation.parentId == -1) {
target = { id: -1, name: "Root" };
moveNode(content, target);
} else {
contentResource.getById(relation.parentId).then(function (data) {
target = data;
// make sure the target item isn't in the recycle bin
if(target.path.indexOf("-20") !== -1) {
notificationsService.error(error.headline, "The item you want to restore it under (" + target.name + ") is in the recycle bin. Use the Move menu item to move the item manually.");
$scope.page.buttonRestore = "error";
return;
}
moveNode(content, target);
}, function (err) {
$scope.page.buttonRestore = "error";
notificationsService.error(error.headline, error.content);
});
}
}, function (err) {
$scope.page.buttonRestore = "error";
notificationsService.error(error.headline, error.content);
});
};
function moveNode(node, target) {
contentResource.move({ "parentId": target.id, "id": node.id })
.then(function (path) {
// remove the node that we're working on
if($scope.page.menu.currentNode) {
treeService.removeNode($scope.page.menu.currentNode);
}
// sync the destination node
navigationService.syncTree({ tree: "content", path: path, forceReload: true, activate: false });
$scope.page.buttonRestore = "success";
notificationsService.success("Successfully restored " + node.name + " to " + target.name);
// reload the node
getNode();
}, function (err) {
$scope.page.buttonRestore = "error";
notificationsService.error("Cannot automatically restore this item", err);
});
}
//ensure to unregister from all events!
$scope.$on('$destroy', function () {
for (var e in evts) {
eventsService.unsubscribe(evts[e]);
}
});
}
function createDirective() {
var directive = {
restrict: 'E',
replace: true,
templateUrl: 'views/components/content/edit.html',
controller: 'Umbraco.Editors.Content.EditorDirectiveController',
scope: {
contentId: "=",
isNew: "=?",
treeAlias: "@",
page: "=?",
saveMethod: "&",
getMethod: "&",
getScaffoldMethod: "&?"
}
};
return directive;
}
angular.module('umbraco.directives').controller('Umbraco.Editors.Content.EditorDirectiveController', ContentEditController);
angular.module('umbraco.directives').directive('contentEditor', createDirective);
})();
| abryukhov/Umbraco-CMS | src/Umbraco.Web.UI.Client/src/common/directives/components/content/edit.controller.js | JavaScript | mit | 13,245 |
<?php
defined('C5_EXECUTE') or die("Access Denied.");
Loader::controller('/profile/edit');
Loader::model('user_private_message');
class ProfileMessagesController extends ProfileEditController {
public function __construct() {
parent::__construct();
}
public function on_start() {
parent::on_start();
$this->error = Loader::helper('validation/error');
$this->set('vt', Loader::helper('validation/token'));
$this->set('text', Loader::helper('text'));
}
public function view() {
$u = new User();
$ui = UserInfo::getByID($u->getUserID());
$inbox = UserPrivateMessageMailbox::get($ui, UserPrivateMessageMailbox::MBTYPE_INBOX);
$sent = UserPrivateMessageMailbox::get($ui, UserPrivateMessageMailbox::MBTYPE_SENT);
$this->set('inbox', $inbox);
$this->set('sent', $sent);
}
protected function validateUser($uID) {
if ($uID > 0) {
$ui = UserInfo::getByID($uID);
if ((is_object($ui)) && ($ui->getAttribute('profile_private_messages_enabled') == 1)) {
$this->set('recipient', $ui);
return true;
}
}
$this->redirect('/profile');
}
protected function getMessageMailboxID($box) {
$msgMailboxID = 0;
switch($box) {
case 'inbox':
$msgMailboxID = UserPrivateMessageMailbox::MBTYPE_INBOX;
break;
case 'sent':
$msgMailboxID = UserPrivateMessageMailbox::MBTYPE_SENT;
break;
default:
$msgMailboxID = $box;
break;
}
return $msgMailboxID;
}
public function view_mailbox($box) {
$msgMailboxID = $this->getMessageMailboxID($box);
$u = new User();
$ui = UserInfo::getByID($u->getUserID());
$mailbox = UserPrivateMessageMailbox::get($ui, $msgMailboxID);
if (is_object($mailbox)) {
$messageList = $mailbox->getMessageList();
$messages = $messageList->getPage();
$this->set('messages', $messages);
$this->set('messageList', $messageList);
}
// also, we have to mark all messages in this mailbox as no longer "new"
$mailbox->removeNewStatus();
$this->set('mailbox', $box);
}
public function view_message($box, $msgID) {
$msgMailboxID = $this->getMessageMailboxID($box);
$u = new User();
$ui = UserInfo::getByID($u->getUserID());
$mailbox = UserPrivateMessageMailbox::get($ui, $msgMailboxID);
$msg = UserPrivateMessage::getByID($msgID, $mailbox);
if ($ui->canReadPrivateMessage($msg)) {
$msg->markAsRead();
$this->set('subject', $msg->getFormattedMessageSubject());
$this->set('msgContent', $msg->getMessageBody());
$this->set('dateAdded', $msg->getMessageDateAdded('user', t('F d, Y \a\t g:i A')));
$this->set('author', $msg->getMessageAuthorObject());
$this->set('msg', $msg);
$this->set('box', $box);
$this->set('backURL', View::url('/profile/messages', 'view_mailbox', $box));
$valt = Loader::helper('validation/token');
$token = $valt->generate('delete_message_' . $msgID);
$this->set('deleteURL', View::url('/profile/messages', 'delete_message', $box, $msgID, $token));
}
}
public function delete_message($box, $msgID, $token) {
$valt = Loader::helper('validation/token');
if (!$valt->validate('delete_message_' . $msgID, $token)) {
$this->error->add($valt->getErrorMessage());
}
$msgMailboxID = $this->getMessageMailboxID($box);
$u = new User();
$ui = UserInfo::getByID($u->getUserID());
$mailbox = UserPrivateMessageMailbox::get($ui, $msgMailboxID);
$msg = UserPrivateMessage::getByID($msgID, $mailbox);
if ($ui->canReadPrivateMessage($msg) && (!$this->error->has())) {
$msg->delete();
$this->redirect('/profile/messages', 'view_mailbox', $box);
}
print $this->view();
}
public function write($uID) {
$this->validateUser($uID);
$this->set('backURL', View::url('/profile', 'view', $uID));
}
public function reply($boxID, $msgID) {
$msg = UserPrivateMessage::getByID($msgID);
$uID = $msg->getMessageRelevantUserID();
$this->validateUser($uID);
$this->set('backURL', View::url('/profile/messages', 'view_message', $boxID, $msgID));
$this->set('msgID', $msgID);
$this->set('box', $boxID);
$this->set('msg', $msg);
$this->set('msgSubject', $msg->getFormattedMessageSubject());
$body = "\n\n\n" . $msg->getMessageDelimiter() . "\n";
$body .= t("From: %s\nDate Sent: %s\nSubject: %s", $msg->getMessageAuthorName(), $msg->getMessageDateAdded('user', t('F d, Y \a\t g:i A')), $msg->getFormattedMessageSubject());
$body .= "\n\n" . $msg->getMessageBody();
$this->set('msgBody', $body);
}
public function send() {
$uID = $this->post('uID');
if ($this->post('msgID') > 0) {
$msgID = $this->post('msgID');
$box = $this->post('box');
$this->reply($box, $msgID);
} else {
$this->write($uID);
}
$vf = Loader::helper('validation/form');
$vf->setData($this->post());
$vf->addRequired('msgBody', t("You haven't written a message!"));
$vf->addRequiredToken("validate_send_message");
if ($vf->test()) {
$u = new User();
$sender = UserInfo::getByID($u->getUserID());
$r = $sender->sendPrivateMessage($this->get('recipient'), $this->post('msgSubject'), $this->post('msgBody'), $this->get('msg'));
if ($r instanceof ValidationErrorHelper) {
$this->error = $r;
} else {
if ($this->post('msgID') > 0) {
$this->redirect('/profile/messages', 'reply_complete', $box, $msgID);
} else {
$this->redirect('/profile/messages', 'send_complete', $uID);
}
}
} else {
$this->error = $vf->getError();
}
}
public function send_complete($uID) {
$this->validateUser($uID);
}
public function reply_complete($box, $msgID) {
$this->reply($box, $msgID);
}
public function on_before_render() {
$this->set('error', $this->error);
}
} | clejer/concrete_ | concrete/controllers/profile/messages.php | PHP | mit | 5,679 |
var tns = (function (){
// keys
if (!Object.keys) {
Object.keys = function (object) {
var keys = [];
for (var name in object) {
if (Object.prototype.hasOwnProperty.call(object, name)) {
keys.push(name);
}
}
return keys;
};
}
// ChildNode.remove
(function () {
"use strict";
if(!("remove" in Element.prototype)){
Element.prototype.remove = function(){
if(this.parentNode) {
this.parentNode.removeChild(this);
}
};
}
})();
var win = window;
var raf = win.requestAnimationFrame
|| win.webkitRequestAnimationFrame
|| win.mozRequestAnimationFrame
|| win.msRequestAnimationFrame
|| function(cb) { return setTimeout(cb, 16); };
var win$1 = window;
var caf = win$1.cancelAnimationFrame
|| win$1.mozCancelAnimationFrame
|| function(id){ clearTimeout(id); };
function extend() {
var obj, name, copy,
target = arguments[0] || {},
i = 1,
length = arguments.length;
for (; i < length; i++) {
if ((obj = arguments[i]) !== null) {
for (name in obj) {
copy = obj[name];
if (target === copy) {
continue;
} else if (copy !== undefined) {
target[name] = copy;
}
}
}
}
return target;
}
function checkStorageValue (value) {
return ['true', 'false'].indexOf(value) >= 0 ? JSON.parse(value) : value;
}
function setLocalStorage(key, value) {
localStorage.setItem(key, value);
return value;
}
function getSlideId() {
var id = window.tnsId;
window.tnsId = !id ? 1 : id + 1;
return 'tns' + window.tnsId;
}
function getBody () {
var doc = document,
body = doc.body;
if (!body) {
body = doc.createElement('body');
body.fake = true;
}
return body;
}
var docElement = document.documentElement;
function setFakeBody (body) {
var docOverflow = '';
if (body.fake) {
docOverflow = docElement.style.overflow;
//avoid crashing IE8, if background image is used
body.style.background = '';
//Safari 5.13/5.1.4 OSX stops loading if ::-webkit-scrollbar is used and scrollbars are visible
body.style.overflow = docElement.style.overflow = 'hidden';
docElement.appendChild(body);
}
return docOverflow;
}
function resetFakeBody (body, docOverflow) {
if (body.fake) {
body.remove();
docElement.style.overflow = docOverflow;
// Trigger layout so kinetic scrolling isn't disabled in iOS6+
// eslint-disable-next-line
docElement.offsetHeight;
}
}
// get css-calc
function calc() {
var doc = document,
body = getBody(),
docOverflow = setFakeBody(body),
div = doc.createElement('div'),
result = false;
body.appendChild(div);
try {
var vals = ['calc(10px)', '-moz-calc(10px)', '-webkit-calc(10px)'], val;
for (var i = 0; i < 3; i++) {
val = vals[i];
div.style.width = val;
if (div.offsetWidth === 10) {
result = val.replace('(10px)', '');
break;
}
}
} catch (e) {}
body.fake ? resetFakeBody(body, docOverflow) : div.remove();
return result;
}
// get subpixel support value
function subpixelLayout() {
var doc = document,
body = getBody(),
docOverflow = setFakeBody(body),
parent = doc.createElement('div'),
child1 = doc.createElement('div'),
child2,
supported;
parent.style.cssText = 'width: 10px';
child1.style.cssText = 'float: left; width: 5.5px; height: 10px;';
child2 = child1.cloneNode(true);
parent.appendChild(child1);
parent.appendChild(child2);
body.appendChild(parent);
supported = child1.offsetTop !== child2.offsetTop;
body.fake ? resetFakeBody(body, docOverflow) : parent.remove();
return supported;
}
function mediaquerySupport () {
var doc = document,
body = getBody(),
docOverflow = setFakeBody(body),
div = doc.createElement('div'),
style = doc.createElement('style'),
rule = '@media all and (min-width:1px){.tns-mq-test{position:absolute}}',
position;
style.type = 'text/css';
div.className = 'tns-mq-test';
body.appendChild(style);
body.appendChild(div);
if (style.styleSheet) {
style.styleSheet.cssText = rule;
} else {
style.appendChild(doc.createTextNode(rule));
}
position = window.getComputedStyle ? window.getComputedStyle(div).position : div.currentStyle['position'];
body.fake ? resetFakeBody(body, docOverflow) : div.remove();
return position === "absolute";
}
// create and append style sheet
function createStyleSheet (media) {
// Create the <style> tag
var style = document.createElement("style");
// style.setAttribute("type", "text/css");
// Add a media (and/or media query) here if you'd like!
// style.setAttribute("media", "screen")
// style.setAttribute("media", "only screen and (max-width : 1024px)")
if (media) { style.setAttribute("media", media); }
// WebKit hack :(
// style.appendChild(document.createTextNode(""));
// Add the <style> element to the page
document.querySelector('head').appendChild(style);
return style.sheet ? style.sheet : style.styleSheet;
}
// cross browsers addRule method
function addCSSRule(sheet, selector, rules, index) {
// return raf(function() {
'insertRule' in sheet ?
sheet.insertRule(selector + '{' + rules + '}', index) :
sheet.addRule(selector, rules, index);
// });
}
function getCssRulesLength(sheet) {
var rule = ('insertRule' in sheet) ? sheet.cssRules : sheet.rules;
return rule.length;
}
function toDegree (y, x) {
return Math.atan2(y, x) * (180 / Math.PI);
}
function getTouchDirection(angle, range) {
var direction = false,
gap = Math.abs(90 - Math.abs(angle));
if (gap >= 90 - range) {
direction = 'horizontal';
} else if (gap <= range) {
direction = 'vertical';
}
return direction;
}
// https://toddmotto.com/ditch-the-array-foreach-call-nodelist-hack/
function forEachNodeList (arr, callback, scope) {
for (var i = 0, l = arr.length; i < l; i++) {
callback.call(scope, arr[i], i);
}
}
var classListSupport = 'classList' in document.createElement('_');
var hasClass = classListSupport ?
function (el, str) { return el.classList.contains(str); } :
function (el, str) { return el.className.indexOf(str) >= 0; };
var addClass = classListSupport ?
function (el, str) {
if (!hasClass(el, str)) { el.classList.add(str); }
} :
function (el, str) {
if (!hasClass(el, str)) { el.className += ' ' + str; }
};
var removeClass = classListSupport ?
function (el, str) {
if (hasClass(el, str)) { el.classList.remove(str); }
} :
function (el, str) {
if (hasClass(el, str)) { el.className = el.className.replace(str, ''); }
};
function hasAttr(el, attr) {
return el.hasAttribute(attr);
}
function getAttr(el, attr) {
return el.getAttribute(attr);
}
function isNodeList(el) {
// Only NodeList has the "item()" function
return typeof el.item !== "undefined";
}
function setAttrs(els, attrs) {
els = (isNodeList(els) || els instanceof Array) ? els : [els];
if (Object.prototype.toString.call(attrs) !== '[object Object]') { return; }
for (var i = els.length; i--;) {
for(var key in attrs) {
els[i].setAttribute(key, attrs[key]);
}
}
}
function removeAttrs(els, attrs) {
els = (isNodeList(els) || els instanceof Array) ? els : [els];
attrs = (attrs instanceof Array) ? attrs : [attrs];
var attrLength = attrs.length;
for (var i = els.length; i--;) {
for (var j = attrLength; j--;) {
els[i].removeAttribute(attrs[j]);
}
}
}
function removeElementStyles(el) {
el.style.cssText = '';
}
function arrayFromNodeList (nl) {
var arr = [];
for (var i = 0, l = nl.length; i < l; i++) {
arr.push(nl[i]);
}
return arr;
}
function hideElement(el) {
if (!hasAttr(el, 'hidden')) {
setAttrs(el, {'hidden': ''});
}
}
function showElement(el) {
if (hasAttr(el, 'hidden')) {
removeAttrs(el, 'hidden');
}
}
function isVisible(el) {
return el.offsetWidth > 0 && el.offsetHeight > 0;
}
function whichProperty(props){
if (typeof props === 'string') {
var arr = [props],
Props = props.charAt(0).toUpperCase() + props.substr(1),
prefixes = ['Webkit', 'Moz', 'ms', 'O'];
prefixes.forEach(function(prefix) {
if (prefix !== 'ms' || props === 'transform') {
arr.push(prefix + Props);
}
});
props = arr;
}
var el = document.createElement('fakeelement'),
len = props.length;
for(var i = 0; i < props.length; i++){
var prop = props[i];
if( el.style[prop] !== undefined ){ return prop; }
}
return false; // explicit for ie9-
}
function has3D(tf){
if (!window.getComputedStyle) { return false; }
var doc = document,
body = getBody(),
docOverflow = setFakeBody(body),
el = doc.createElement('p'),
has3d,
cssTF = tf.length > 9 ? '-' + tf.slice(0, -9).toLowerCase() + '-' : '';
cssTF += 'transform';
// Add it to the body to get the computed style
body.insertBefore(el, null);
el.style[tf] = 'translate3d(1px,1px,1px)';
has3d = window.getComputedStyle(el).getPropertyValue(cssTF);
body.fake ? resetFakeBody(body, docOverflow) : el.remove();
return (has3d !== undefined && has3d.length > 0 && has3d !== "none");
}
// get transitionend, animationend based on transitionDuration
// @propin: string
// @propOut: string, first-letter uppercase
// Usage: getEndProperty('WebkitTransitionDuration', 'Transition') => webkitTransitionEnd
function getEndProperty(propIn, propOut) {
var endProp = false;
if (/^Webkit/.test(propIn)) {
endProp = 'webkit' + propOut + 'End';
} else if (/^O/.test(propIn)) {
endProp = 'o' + propOut + 'End';
} else if (propIn) {
endProp = propOut.toLowerCase() + 'end';
}
return endProp;
}
// Test via a getter in the options object to see if the passive property is accessed
var supportsPassive = false;
try {
var opts = Object.defineProperty({}, 'passive', {
get: function() {
supportsPassive = true;
}
});
window.addEventListener("test", null, opts);
} catch (e) {}
var passiveOption = supportsPassive ? { passive: true } : false;
function addEvents(el, obj) {
for (var prop in obj) {
var option = (prop === 'touchstart' || prop === 'touchmove') ? passiveOption : false;
el.addEventListener(prop, obj[prop], option);
}
}
function removeEvents(el, obj) {
for (var prop in obj) {
var option = ['touchstart', 'touchmove'].indexOf(prop) >= 0 ? passiveOption : false;
el.removeEventListener(prop, obj[prop], option);
}
}
function Events() {
return {
topics: {},
on: function (eventName, fn) {
this.topics[eventName] = this.topics[eventName] || [];
this.topics[eventName].push(fn);
},
off: function(eventName, fn) {
if (this.topics[eventName]) {
for (var i = 0; i < this.topics[eventName].length; i++) {
if (this.topics[eventName][i] === fn) {
this.topics[eventName].splice(i, 1);
break;
}
}
}
},
emit: function (eventName, data) {
if (this.topics[eventName]) {
this.topics[eventName].forEach(function(fn) {
fn(data);
});
}
}
};
}
function jsTransform(element, attr, prefix, postfix, to, duration, callback) {
var tick = Math.min(duration, 10),
unit = (to.indexOf('%') >= 0) ? '%' : 'px',
to = to.replace(unit, ''),
from = Number(element.style[attr].replace(prefix, '').replace(postfix, '').replace(unit, '')),
positionTick = (to - from) / duration * tick,
running;
setTimeout(moveElement, tick);
function moveElement() {
duration -= tick;
from += positionTick;
element.style[attr] = prefix + from + unit + postfix;
if (duration > 0) {
setTimeout(moveElement, tick);
} else {
callback();
}
}
}
// Format: IIFE
var tns = function(options) {
options = extend({
container: '.slider',
mode: 'carousel',
axis: 'horizontal',
items: 1,
gutter: 0,
edgePadding: 0,
fixedWidth: false,
fixedWidthViewportWidth: false,
slideBy: 1,
controls: true,
controlsText: ['prev', 'next'],
controlsContainer: false,
prevButton: false,
nextButton: false,
nav: true,
navContainer: false,
navAsThumbnails: false,
arrowKeys: false,
speed: 300,
autoplay: false,
autoplayTimeout: 5000,
autoplayDirection: 'forward',
autoplayText: ['start', 'stop'],
autoplayHoverPause: false,
autoplayButton: false,
autoplayButtonOutput: true,
autoplayResetOnVisibility: true,
// animateIn: 'tns-fadeIn',
// animateOut: 'tns-fadeOut',
// animateNormal: 'tns-normal',
// animateDelay: false,
loop: true,
rewind: false,
autoHeight: false,
responsive: false,
lazyload: false,
touch: true,
mouseDrag: false,
swipeAngle: 15,
nested: false,
freezable: true,
// startIndex: 0,
onInit: false,
useLocalStorage: true
}, options || {});
var doc = document,
win = window,
KEYS = {
ENTER: 13,
SPACE: 32,
PAGEUP: 33,
PAGEDOWN: 34,
END: 35,
HOME: 36,
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40
},
CALC,
SUBPIXEL,
CSSMQ,
TRANSFORM,
HAS3D,
TRANSITIONDURATION,
TRANSITIONDELAY,
ANIMATIONDURATION,
ANIMATIONDELAY,
TRANSITIONEND,
ANIMATIONEND,
localStorageAccess = true;
if (options.useLocalStorage) {
// check browser version and local storage
// if browser upgraded,
// 1. delete browser ralated data from local storage and
// 2. recheck these options and save them to local storage
var browserInfo = navigator.userAgent,
tnsStorage = {};
// tC => calc
// tSP => subpixel
// tMQ => mediaquery
// tTf => transform
// tTDu => transitionDuration
// tTDe => transitionDelay
// tADu => animationDuration
// tADe => animationDelay
// tTE => transitionEnd
// tAE => animationEnd
try {
tnsStorage = localStorage;
// remove storage when browser version changes
if (tnsStorage['tnsApp'] && tnsStorage['tnsApp'] !== browserInfo) {
['tC', 'tSP', 'tMQ', 'tTf', 't3D', 'tTDu', 'tTDe', 'tADu', 'tADe', 'tTE', 'tAE'].forEach(function(item) { tnsStorage.removeItem(item); });
}
// update browserInfo
tnsStorage['tnsApp'] = browserInfo;
} catch(e) {
localStorageAccess = false;
}
// reset tnsStorage when localStorage is null (on some versions of Chrome Mobile #134)
// https://stackoverflow.com/questions/8701015/html-localstorage-is-null-on-android-when-using-webview
if (!localStorage) {
tnsStorage = {};
localStorageAccess = false;
}
// get browser related data from local storage if they exist
// otherwise, run the functions again and save these data to local storage
// checkStorageValue() convert non-string value to its original value: 'true' > true
if (localStorageAccess) {
if (tnsStorage['tC']) {
CALC = checkStorageValue(tnsStorage['tC']);
SUBPIXEL = checkStorageValue(tnsStorage['tSP']);
CSSMQ = checkStorageValue(tnsStorage['tMQ']);
TRANSFORM = checkStorageValue(tnsStorage['tTf']);
HAS3D = checkStorageValue(tnsStorage['t3D']);
TRANSITIONDURATION = checkStorageValue(tnsStorage['tTDu']);
TRANSITIONDELAY = checkStorageValue(tnsStorage['tTDe']);
ANIMATIONDURATION = checkStorageValue(tnsStorage['tADu']);
ANIMATIONDELAY = checkStorageValue(tnsStorage['tADe']);
TRANSITIONEND = checkStorageValue(tnsStorage['tTE']);
ANIMATIONEND = checkStorageValue(tnsStorage['tAE']);
} else {
CALC = setLocalStorage('tC', calc());
SUBPIXEL = setLocalStorage('tSP', subpixelLayout());
CSSMQ = setLocalStorage('tMQ', mediaquerySupport());
TRANSFORM = setLocalStorage('tTf', whichProperty('transform'));
HAS3D = setLocalStorage('t3D', has3D(TRANSFORM));
TRANSITIONDURATION = setLocalStorage('tTDu', whichProperty('transitionDuration'));
TRANSITIONDELAY = setLocalStorage('tTDe', whichProperty('transitionDelay'));
ANIMATIONDURATION = setLocalStorage('tADu', whichProperty('animationDuration'));
ANIMATIONDELAY = setLocalStorage('tADe', whichProperty('animationDelay'));
TRANSITIONEND = setLocalStorage('tTE', getEndProperty(TRANSITIONDURATION, 'Transition'));
ANIMATIONEND = setLocalStorage('tAE', getEndProperty(ANIMATIONDURATION, 'Animation'));
}
}
} else {
localStorageAccess = false;
}
if (!localStorageAccess) {
CALC = calc();
SUBPIXEL = subpixelLayout();
CSSMQ = mediaquerySupport();
TRANSFORM = whichProperty('transform');
HAS3D = has3D(TRANSFORM);
TRANSITIONDURATION = whichProperty('transitionDuration');
TRANSITIONDELAY = whichProperty('transitionDelay');
ANIMATIONDURATION = whichProperty('animationDuration');
ANIMATIONDELAY = whichProperty('animationDelay');
TRANSITIONEND = getEndProperty(TRANSITIONDURATION, 'Transition');
ANIMATIONEND = getEndProperty(ANIMATIONDURATION, 'Animation');
}
// reset SUBPIXEL for IE8
if (!CSSMQ) { SUBPIXEL = false; }
// get element nodes from selectors
var supportConsoleWarn = win.console && typeof win.console.warn === "function";
var list = ['container', 'controlsContainer', 'prevButton', 'nextButton', 'navContainer', 'autoplayButton'];
for (var i = list.length; i--;) {
var item = list[i];
if (typeof options[item] === 'string') {
var el = doc.querySelector(options[item]);
if (el && el.nodeName) {
options[item] = el;
} else {
if (supportConsoleWarn) { console.warn('Can\'t find', options[item]); }
return;
}
}
}
// make sure at least 1 slide
if (options.container.children && options.container.children.length < 1) {
if (supportConsoleWarn) { console.warn('No slides found in', options.container); }
return;
}
// update responsive
// from: {
// 300: 2,
// 800: {
// loop: false
// }
// }
// to: {
// 300: {
// items: 2
// },
// 800: {
// loop: false
// }
// }
if (options.responsive) {
var resTem = {}, res = options.responsive;
for(var key in res) {
var val = res[key];
resTem[key] = typeof val === 'number' ? {items: val} : val;
}
options.responsive = resTem;
resTem = null;
// apply responsive[0] to options and remove it
if (0 in options.responsive) {
options = extend(options, options.responsive[0]);
delete options.responsive[0];
}
}
// === define and set variables ===
var carousel = options.mode === 'carousel' ? true : false;
if (!carousel) {
options.axis = 'horizontal';
// options.rewind = false;
// options.loop = true;
options.edgePadding = false;
var animateIn = 'tns-fadeIn',
animateOut = 'tns-fadeOut',
animateDelay = false,
animateNormal = options.animateNormal || 'tns-normal';
if (TRANSITIONEND && ANIMATIONEND) {
animateIn = options.animateIn || animateIn;
animateOut = options.animateOut || animateOut;
animateDelay = options.animateDelay || animateDelay;
}
}
var horizontal = options.axis === 'horizontal' ? true : false,
outerWrapper = doc.createElement('div'),
innerWrapper = doc.createElement('div'),
container = options.container,
containerParent = container.parentNode,
slideItems = container.children,
slideCount = slideItems.length,
vpInner,
responsive = options.responsive,
responsiveItems = [],
breakpoints = false,
breakpointZone = 0,
windowWidth = getWindowWidth(),
isOn;
if (options.fixedWidth) { var vpOuter = getViewportWidth(containerParent); }
if (responsive) {
breakpoints = Object.keys(responsive)
.map(function (x) { return parseInt(x); })
.sort(function (a, b) { return a - b; });
// get all responsive items
breakpoints.forEach(function(bp) {
responsiveItems = responsiveItems.concat(Object.keys(responsive[bp]));
});
// remove duplicated items
var arr = [];
responsiveItems.forEach(function (item) { if (arr.indexOf(item) < 0) { arr.push(item); } });
responsiveItems = arr;
setBreakpointZone();
}
var items = getOption('items'),
slideBy = getOption('slideBy') === 'page' ? items : getOption('slideBy'),
nested = options.nested,
gutter = getOption('gutter'),
edgePadding = getOption('edgePadding'),
fixedWidth = getOption('fixedWidth'),
fixedWidthViewportWidth = options.fixedWidthViewportWidth,
arrowKeys = getOption('arrowKeys'),
speed = getOption('speed'),
rewind = options.rewind,
loop = rewind ? false : options.loop,
autoHeight = getOption('autoHeight'),
sheet = createStyleSheet(),
lazyload = options.lazyload,
slideOffsetTops, // collection of slide offset tops
slideItemsOut = [],
hasEdgePadding = checkOption('edgePadding'),
cloneCount = loop ? getCloneCountForLoop() : 0,
slideCountNew = !carousel ? slideCount + cloneCount : slideCount + cloneCount * 2,
hasRightDeadZone = fixedWidth && !loop && !edgePadding ? true : false,
updateIndexBeforeTransform = (!carousel || !loop) ? true : false,
// transform
transformAttr = horizontal ? 'left' : 'top',
transformPrefix = '',
transformPostfix = '',
// index
startIndex = getOption('startIndex'),
index = startIndex ? updateStartIndex(startIndex) : !carousel ? 0 : cloneCount,
indexCached = index,
indexMin = 0,
indexMax = getIndexMax(),
// resize
resizeTimer,
swipeAngle = options.swipeAngle,
moveDirectionExpected = swipeAngle ? '?' : true,
running = false,
onInit = options.onInit,
events = new Events(),
// id, class
containerIdCached = container.id,
classContainer = ' tns-slider tns-' + options.mode,
slideId = container.id || getSlideId(),
disable = getOption('disable'),
freezable = options.freezable,
freeze = disable ? true : freezable ? slideCount <= items : false,
frozen,
importantStr = nested === 'inner' ? ' !important' : '',
controlsEvents = {
'click': onControlsClick,
'keydown': onControlsKeydown
},
navEvents = {
'click': onNavClick,
'keydown': onNavKeydown
},
hoverEvents = {
'mouseover': mouseoverPause,
'mouseout': mouseoutRestart
},
visibilityEvent = {'visibilitychange': onVisibilityChange},
docmentKeydownEvent = {'keydown': onDocumentKeydown},
touchEvents = {
'touchstart': onPanStart,
'touchmove': onPanMove,
'touchend': onPanEnd,
'touchcancel': onPanEnd
}, dragEvents = {
'mousedown': onPanStart,
'mousemove': onPanMove,
'mouseup': onPanEnd,
'mouseleave': onPanEnd
},
hasControls = checkOption('controls'),
hasNav = checkOption('nav'),
navAsThumbnails = options.navAsThumbnails,
hasAutoplay = checkOption('autoplay'),
hasTouch = checkOption('touch'),
hasMouseDrag = checkOption('mouseDrag'),
slideActiveClass = 'tns-slide-active',
imgCompleteClass = 'tns-complete',
imgEvents = {
'load': imgLoadedOrError,
'error': imgLoadedOrError
},
imgsComplete;
// controls
if (hasControls) {
var controls = getOption('controls'),
controlsText = getOption('controlsText'),
controlsContainer = options.controlsContainer,
prevButton = options.prevButton,
nextButton = options.nextButton,
prevIsButton,
nextIsButton;
}
// nav
if (hasNav) {
var nav = getOption('nav'),
navContainer = options.navContainer,
navItems,
visibleNavIndexes = [],
visibleNavIndexesCached = visibleNavIndexes,
navClicked = -1,
navCurrentIndex = getAbsIndex(),
navCurrentIndexCached = navCurrentIndex,
navActiveClass = 'tns-nav-active';
}
// autoplay
if (hasAutoplay) {
var autoplay = getOption('autoplay'),
autoplayTimeout = getOption('autoplayTimeout'),
autoplayDirection = options.autoplayDirection === 'forward' ? 1 : -1,
autoplayText = getOption('autoplayText'),
autoplayHoverPause = getOption('autoplayHoverPause'),
autoplayButton = options.autoplayButton,
autoplayResetOnVisibility = getOption('autoplayResetOnVisibility'),
autoplayHtmlStrings = ['<span class=\'tns-visually-hidden\'>', ' animation</span>'],
autoplayTimer,
animating,
autoplayHoverPaused,
autoplayUserPaused,
autoplayVisibilityPaused;
}
if (hasTouch || hasMouseDrag) {
var initPosition = {},
lastPosition = {},
translateInit,
disX,
disY,
panStart = false,
rafIndex = 0,
getDist = horizontal ?
function(a, b) { return a.x - b.x; } :
function(a, b) { return a.y - b.y; };
}
// touch
if (hasTouch) {
var touch = getOption('touch');
}
// mouse drag
if (hasMouseDrag) {
var mouseDrag = getOption('mouseDrag');
}
// disable slider when slidecount <= items
if (freeze) {
controls = nav = touch = mouseDrag = arrowKeys = autoplay = autoplayHoverPause = autoplayResetOnVisibility = false;
}
if (TRANSFORM) {
transformAttr = TRANSFORM;
transformPrefix = 'translate';
if (HAS3D) {
transformPrefix += horizontal ? '3d(' : '3d(0px, ';
transformPostfix = horizontal ? ', 0px, 0px)' : ', 0px)';
} else {
transformPrefix += horizontal ? 'X(' : 'Y(';
transformPostfix = ')';
}
}
// === COMMON FUNCTIONS === //
function getIndexMax () {
return carousel || loop ? Math.max(0, slideCountNew - items) : slideCountNew - 1;
}
function updateStartIndex (indexTem) {
indexTem = indexTem%slideCount;
if (indexTem < 0) { indexTem += slideCount; }
indexTem = Math.min(indexTem, slideCountNew - items);
return indexTem;
}
function getAbsIndex (i) {
if (i === undefined) { i = index; }
if (carousel) {
while (i < cloneCount) { i += slideCount; }
i -= cloneCount;
}
return i ? i%slideCount : i;
}
function getItemsMax () {
if (fixedWidth && !fixedWidthViewportWidth) {
return slideCount - 1;
} else {
var str = fixedWidth ? 'fixedWidth' : 'items',
arr = [];
if (fixedWidth || options[str] < slideCount) { arr.push(options[str]); }
if (breakpoints && responsiveItems.indexOf(str) >= 0) {
breakpoints.forEach(function(bp) {
var tem = responsive[bp][str];
if (tem && (fixedWidth || tem < slideCount)) { arr.push(tem); }
});
}
if (!arr.length) { arr.push(0); }
return fixedWidth ? Math.ceil(fixedWidthViewportWidth / Math.min.apply(null, arr)) :
Math.max.apply(null, arr);
}
}
function getCloneCountForLoop () {
var itemsMax = getItemsMax(),
result = carousel ? Math.ceil((itemsMax * 5 - slideCount)/2) : (itemsMax * 4 - slideCount);
result = Math.max(itemsMax, result);
return hasEdgePadding ? result + 1 : result;
}
function getWindowWidth () {
return win.innerWidth || doc.documentElement.clientWidth || doc.body.clientWidth;
}
function getViewportWidth (el) {
return el.clientWidth || getViewportWidth(el.parentNode);
}
function checkOption (item) {
var result = options[item];
if (!result && breakpoints && responsiveItems.indexOf(item) >= 0) {
breakpoints.forEach(function (bp) {
if (responsive[bp][item]) { result = true; }
});
}
return result;
}
function getOption (item, viewport) {
viewport = viewport ? viewport : windowWidth;
var obj = {
slideBy: 'page',
edgePadding: false
},
result;
if (!carousel && item in obj) {
result = obj[item];
} else {
if (item === 'items' && getOption('fixedWidth')) {
result = Math.floor(vpOuter / (getOption('fixedWidth') + getOption('gutter')));
} else if (item === 'autoHeight' && nested === 'outer') {
result = true;
} else {
result = options[item];
if (breakpoints && responsiveItems.indexOf(item) >= 0) {
for (var i = 0, len = breakpoints.length; i < len; i++) {
var bp = breakpoints[i];
if (viewport >= bp) {
if (item in responsive[bp]) { result = responsive[bp][item]; }
} else { break; }
}
}
}
}
if (item === 'slideBy' && result === 'page') { result = getOption('items'); }
return result;
}
function getSlideMarginLeft (i) {
var str = CALC ?
CALC + '(' + i * 100 + '% / ' + slideCountNew + ')' :
i * 100 / slideCountNew + '%';
return str;
}
function getInnerWrapperStyles (edgePaddingTem, gutterTem, fixedWidthTem, speedTem) {
var str = '';
if (edgePaddingTem) {
var gap = edgePaddingTem;
if (gutterTem) { gap += gutterTem; }
if (fixedWidthTem) {
str = 'margin: 0px ' + (vpOuter%(fixedWidthTem + gutterTem) + gutterTem) / 2 + 'px;';
} else {
str = horizontal ?
'margin: 0 ' + edgePaddingTem + 'px 0 ' + gap + 'px;' :
'padding: ' + gap + 'px 0 ' + edgePaddingTem + 'px 0;';
}
} else if (gutterTem && !fixedWidthTem) {
var gutterTemUnit = '-' + gutterTem + 'px',
dir = horizontal ? gutterTemUnit + ' 0 0' : '0 ' + gutterTemUnit + ' 0';
str = 'margin: 0 ' + dir + ';';
}
if (TRANSITIONDURATION && speedTem) { str += getTrsnsitionDurationStyle(speedTem); }
return str;
}
function getContainerWidth (fixedWidthTem, gutterTem, itemsTem) {
var str;
if (fixedWidthTem) {
str = (fixedWidthTem + gutterTem) * slideCountNew + 'px';
} else {
str = CALC ?
CALC + '(' + slideCountNew * 100 + '% / ' + itemsTem + ')' :
slideCountNew * 100 / itemsTem + '%';
}
return str;
}
function getSlideWidthStyle (fixedWidthTem, gutterTem, itemsTem) {
var str = '';
if (horizontal) {
str = 'width:';
if (fixedWidthTem) {
str += (fixedWidthTem + gutterTem) + 'px';
} else {
var dividend = carousel ? slideCountNew : itemsTem;
str += CALC ?
CALC + '(100% / ' + dividend + ')' :
100 / dividend + '%';
}
str += importantStr + ';';
}
return str;
}
function getSlideGutterStyle (gutterTem) {
var str = '';
// gutter maybe interger || 0
// so can't use 'if (gutter)'
if (gutterTem !== false) {
var prop = horizontal ? 'padding-' : 'margin-',
dir = horizontal ? 'right' : 'bottom';
str = prop + dir + ': ' + gutterTem + 'px;';
}
return str;
}
function getCSSPrefix (name, num) {
var prefix = name.substring(0, name.length - num).toLowerCase();
if (prefix) { prefix = '-' + prefix + '-'; }
return prefix;
}
function getTrsnsitionDurationStyle (speed) {
return getCSSPrefix(TRANSITIONDURATION, 18) + 'transition-duration:' + speed / 1000 + 's;';
}
function getAnimationDurationStyle (speed) {
return getCSSPrefix(ANIMATIONDURATION, 17) + 'animation-duration:' + speed / 1000 + 's;';
}
(function sliderInit () {
// First thing first, wrap container with 'outerWrapper > innerWrapper',
// to get the correct view width
outerWrapper.appendChild(innerWrapper);
containerParent.insertBefore(outerWrapper, container);
innerWrapper.appendChild(container);
vpInner = getViewportWidth(innerWrapper);
var classOuter = 'tns-outer',
classInner = 'tns-inner',
hasGutter = checkOption('gutter');
if (carousel) {
if (horizontal) {
if (checkOption('edgePadding') || hasGutter && !options.fixedWidth) {
classOuter += ' tns-ovh';
} else {
classInner += ' tns-ovh';
}
} else {
classInner += ' tns-ovh';
}
} else if (hasGutter) {
classOuter += ' tns-ovh';
}
outerWrapper.className = classOuter;
innerWrapper.className = classInner;
innerWrapper.id = slideId + '-iw';
if (autoHeight) { innerWrapper.className += ' tns-ah'; }
// set container properties
if (container.id === '') { container.id = slideId; }
classContainer += SUBPIXEL ? ' tns-subpixel' : ' tns-no-subpixel';
classContainer += CALC ? ' tns-calc' : ' tns-no-calc';
if (carousel) { classContainer += ' tns-' + options.axis; }
container.className += classContainer;
// add event
if (carousel && TRANSITIONEND) {
var eve = {};
eve[TRANSITIONEND] = onTransitionEnd;
addEvents(container, eve);
}
// delete datas after init
classOuter = classInner = null;
// add id, class, aria attributes
// before clone slides
for (var x = 0; x < slideCount; x++) {
var item = slideItems[x];
if (!item.id) { item.id = slideId + '-item' + x; }
addClass(item, 'tns-item');
if (!carousel && animateNormal) { addClass(item, animateNormal); }
setAttrs(item, {
'aria-hidden': 'true',
'tabindex': '-1'
});
}
// clone slides
if (loop || edgePadding) {
var fragmentBefore = doc.createDocumentFragment(),
fragmentAfter = doc.createDocumentFragment();
for (var j = cloneCount; j--;) {
var num = j%slideCount,
cloneFirst = slideItems[num].cloneNode(true);
removeAttrs(cloneFirst, 'id');
fragmentAfter.insertBefore(cloneFirst, fragmentAfter.firstChild);
if (carousel) {
var cloneLast = slideItems[slideCount - 1 - num].cloneNode(true);
removeAttrs(cloneLast, 'id');
fragmentBefore.appendChild(cloneLast);
}
}
container.insertBefore(fragmentBefore, container.firstChild);
container.appendChild(fragmentAfter);
slideItems = container.children;
}
// add image events
if (checkOption('autoHeight') || !carousel) {
var imgs = container.querySelectorAll('img');
// check all image complete status
// add complete class if true
forEachNodeList(imgs, function(img) {
addEvents(img, imgEvents);
var src = img.src;
img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
img.src = src;
});
// set imgsComplete to true
// when all images are compulete (loaded or error)
raf(function(){ checkImagesLoaded(arrayFromNodeList(imgs), function() {
imgsComplete = true;
}); });
}
// activate visible slides
// add aria attrs
// set animation classes and left value for gallery slider
// use slide count when slides are fewer than items
for (var i = index, l = index + Math.min(slideCount, items); i < l; i++) {
var item = slideItems[i];
setAttrs(item, {'aria-hidden': 'false'});
removeAttrs(item, ['tabindex']);
addClass(item, slideActiveClass);
if (!carousel) {
item.style.left = (i - index) * 100 / items + '%';
addClass(item, animateIn);
removeClass(item, animateNormal);
}
}
if (carousel && horizontal) {
// set font-size rules
// for modern browsers
if (SUBPIXEL) {
// set slides font-size first
addCSSRule(sheet, '#' + slideId + ' > .tns-item', 'font-size:' + win.getComputedStyle(slideItems[0]).fontSize + ';', getCssRulesLength(sheet));
addCSSRule(sheet, '#' + slideId, 'font-size:0;', getCssRulesLength(sheet));
// slide left margin
// for IE8 & webkit browsers (no subpixel)
} else {
forEachNodeList(slideItems, function (slide, i) {
slide.style.marginLeft = getSlideMarginLeft(i);
});
}
}
// all browsers which support CSS transitions support CSS media queries
if (CSSMQ) {
// inner wrapper styles
var str = getInnerWrapperStyles(options.edgePadding, options.gutter, options.fixedWidth, options.speed);
addCSSRule(sheet, '#' + slideId + '-iw', str, getCssRulesLength(sheet));
// container styles
if (carousel) {
str = horizontal ? 'width:' + getContainerWidth(options.fixedWidth, options.gutter, options.items) + ';' : '';
if (TRANSITIONDURATION) { str += getTrsnsitionDurationStyle(speed); }
addCSSRule(sheet, '#' + slideId, str, getCssRulesLength(sheet));
}
// slide styles
if (horizontal || options.gutter) {
str = getSlideWidthStyle(options.fixedWidth, options.gutter, options.items) +
getSlideGutterStyle(options.gutter);
// set gallery items transition-duration
if (!carousel) {
if (TRANSITIONDURATION) { str += getTrsnsitionDurationStyle(speed); }
if (ANIMATIONDURATION) { str += getAnimationDurationStyle(speed); }
}
addCSSRule(sheet, '#' + slideId + ' > .tns-item', str, getCssRulesLength(sheet));
}
// non CSS mediaqueries: IE8
// ## update inner wrapper, container, slides if needed
// set inline styles for inner wrapper & container
// insert stylesheet (one line) for slides only (since slides are many)
} else {
// inner wrapper styles
innerWrapper.style.cssText = getInnerWrapperStyles(edgePadding, gutter, fixedWidth);
// container styles
if (carousel && horizontal) {
container.style.width = getContainerWidth(fixedWidth, gutter, items);
}
// slide styles
if (horizontal || gutter) {
var str = getSlideWidthStyle(fixedWidth, gutter, items) +
getSlideGutterStyle(gutter);
// append to the last line
addCSSRule(sheet, '#' + slideId + ' > .tns-item', str, getCssRulesLength(sheet));
}
}
if (!horizontal && !disable) {
getSlideOffsetTops();
updateContentWrapperHeight();
}
// media queries
if (responsive && CSSMQ) {
breakpoints.forEach(function(bp) {
var opts = responsive[bp],
str = '',
innerWrapperStr = '',
containerStr = '',
slideStr = '',
itemsBP = getOption('items', bp),
fixedWidthBP = getOption('fixedWidth', bp),
speedBP = getOption('speed', bp),
edgePaddingBP = getOption('edgePadding', bp),
gutterBP = getOption('gutter', bp);
// inner wrapper string
if ('edgePadding' in opts || 'gutter' in opts) {
innerWrapperStr = '#' + slideId + '-iw{' + getInnerWrapperStyles(edgePaddingBP, gutterBP, fixedWidthBP, speedBP) + '}';
}
// container string
if (carousel && horizontal && ('fixedWidth' in opts || 'gutter' in opts || 'items' in opts)) {
containerStr = 'width:' + getContainerWidth(fixedWidthBP, gutterBP, itemsBP) + ';';
}
if (TRANSITIONDURATION && 'speed' in opts) {
containerStr += getTrsnsitionDurationStyle(speedBP);
}
if (containerStr) {
containerStr = '#' + slideId + '{' + containerStr + '}';
}
// slide string
if ('fixedWidth' in opts || checkOption('fixedWidth') && 'gutter' in opts || !carousel && 'items' in opts) {
slideStr += getSlideWidthStyle(fixedWidthBP, gutterBP, itemsBP);
}
if ('gutter' in opts) {
slideStr += getSlideGutterStyle(gutterBP);
}
// set gallery items transition-duration
if (!carousel && 'speed' in opts) {
if (TRANSITIONDURATION) { slideStr += getTrsnsitionDurationStyle(speedBP); }
if (ANIMATIONDURATION) { slideStr += getAnimationDurationStyle(speedBP); }
}
if (slideStr) { slideStr = '#' + slideId + ' > .tns-item{' + slideStr + '}'; }
// add up
str = innerWrapperStr + containerStr + slideStr;
if (str) {
sheet.insertRule('@media (min-width: ' + bp / 16 + 'em) {' + str + '}', sheet.cssRules.length);
}
});
}
// set container transform property
if (carousel && !disable) {
doContainerTransformSilent();
}
// == msInit ==
// for IE10
if (navigator.msMaxTouchPoints) {
addClass(container, 'ms-touch');
addEvents(container, {'scroll': ie10Scroll});
setSnapInterval();
}
// == navInit ==
if (hasNav) {
var initIndex = !carousel ? 0 : cloneCount;
// customized nav
// will not hide the navs in case they're thumbnails
if (navContainer) {
setAttrs(navContainer, {'aria-label': 'Carousel Pagination'});
navItems = navContainer.children;
forEachNodeList(navItems, function (item, i) {
setAttrs(item, {
'data-nav': i,
'tabindex': '-1',
'aria-selected': 'false',
'aria-controls': slideItems[initIndex + i].id,
});
});
// generated nav
} else {
var navHtml = '',
hiddenStr = navAsThumbnails ? '' : 'hidden';
for (var i = 0; i < slideCount; i++) {
// hide nav items by default
navHtml += '<button data-nav="' + i +'" tabindex="-1" aria-selected="false" aria-controls="' + slideItems[initIndex + i].id + '" ' + hiddenStr + ' type="button"></button>';
}
navHtml = '<div class="tns-nav" aria-label="Carousel Pagination">' + navHtml + '</div>';
outerWrapper.insertAdjacentHTML('afterbegin', navHtml);
navContainer = outerWrapper.querySelector('.tns-nav');
navItems = navContainer.children;
}
updateNavVisibility();
// add transition
if (TRANSITIONDURATION) {
var prefix = TRANSITIONDURATION.substring(0, TRANSITIONDURATION.length - 18).toLowerCase(),
str = 'transition: all ' + speed / 1000 + 's';
if (prefix) {
str = '-' + prefix + '-' + str;
}
addCSSRule(sheet, '[aria-controls^=' + slideId + '-item]', str, getCssRulesLength(sheet));
}
setAttrs(navItems[navCurrentIndex], {'tabindex': '0', 'aria-selected': 'true'});
addClass(navItems[navCurrentIndex], navActiveClass);
// add events
addEvents(navContainer, navEvents);
if (!nav) { hideElement(navContainer); }
}
// == autoplayInit ==
if (hasAutoplay) {
var txt = autoplay ? 'stop' : 'start';
if (autoplayButton) {
setAttrs(autoplayButton, {'data-action': txt});
} else if (options.autoplayButtonOutput) {
innerWrapper.insertAdjacentHTML('beforebegin', '<button data-action="' + txt + '" type="button">' + autoplayHtmlStrings[0] + txt + autoplayHtmlStrings[1] + autoplayText[0] + '</button>');
autoplayButton = outerWrapper.querySelector('[data-action]');
}
// add event
if (autoplayButton) {
addEvents(autoplayButton, {'click': toggleAutoplay});
}
if (!autoplay) {
if (autoplayButton) {
hideElement(autoplayButton);
}
} else {
startAutoplay();
if (autoplayHoverPause) { addEvents(container, hoverEvents); }
if (autoplayResetOnVisibility) { addEvents(container, visibilityEvent); }
}
}
// == controlsInit ==
if (hasControls) {
if (controlsContainer || (prevButton && nextButton)) {
if (controlsContainer) {
prevButton = controlsContainer.children[0];
nextButton = controlsContainer.children[1];
setAttrs(controlsContainer, {
'aria-label': 'Carousel Navigation',
'tabindex': '0'
});
setAttrs(controlsContainer.children, {
'aria-controls': slideId,
'tabindex': '-1',
});
}
setAttrs(prevButton, {'data-controls' : 'prev'});
setAttrs(nextButton, {'data-controls' : 'next'});
} else {
outerWrapper.insertAdjacentHTML('afterbegin', '<div class="tns-controls" aria-label="Carousel Navigation" tabindex="0"><button data-controls="prev" tabindex="-1" aria-controls="' + slideId +'" type="button">' + controlsText[0] + '</button><button data-controls="next" tabindex="-1" aria-controls="' + slideId +'" type="button">' + controlsText[1] + '</button></div>');
controlsContainer = outerWrapper.querySelector('.tns-controls');
prevButton = controlsContainer.children[0];
nextButton = controlsContainer.children[1];
}
prevIsButton = isButton(prevButton);
nextIsButton = isButton(nextButton);
updateControlsStatus();
// add events
if (controlsContainer) {
addEvents(controlsContainer, controlsEvents);
} else {
addEvents(prevButton, controlsEvents);
addEvents(nextButton, controlsEvents);
}
if (!controls) { hideElement(controlsContainer); }
}
// if (!navigator.msMaxTouchPoints) {
if (carousel) {
if (touch) { addEvents(container, touchEvents); }
if (mouseDrag) { addEvents(container, dragEvents); }
}
// }
if (arrowKeys) { addEvents(doc, docmentKeydownEvent); }
if (nested === 'inner') {
events.on('outerResized', function () {
resizeTasks();
events.emit('innerLoaded', info());
});
} else {
addEvents(win, {'resize': onResize});
}
if (nested === 'outer') {
events.on('innerLoaded', runAutoHeight);
} else if ((autoHeight || !carousel) && !disable) {
runAutoHeight();
}
lazyLoad();
toggleSlideDisplayAndEdgePadding();
updateFixedWidthInnerWrapperStyle();
events.on('indexChanged', additionalUpdates);
if (typeof onInit === 'function') { onInit(info()); }
if (nested === 'inner') { events.emit('innerLoaded', info()); }
if (disable) { disableSlider(true); }
isOn = true;
})();
// === ON RESIZE ===
function onResize (e) {
raf(function(){ resizeTasks(getEvent(e)); });
}
function resizeTasks (e) {
if (!isOn) { return; }
windowWidth = getWindowWidth();
if (nested === 'outer') { events.emit('outerResized', info(e)); }
var breakpointZoneTem = breakpointZone,
indexTem = index,
itemsTem = items,
freezeTem = freeze,
needContainerTransform = false;
if (fixedWidth) { vpOuter = getViewportWidth(outerWrapper); }
vpInner = getViewportWidth(innerWrapper);
if (breakpoints) { setBreakpointZone(); }
// things do when breakpoint zone change
if (breakpointZoneTem !== breakpointZone || fixedWidth) {
var slideByTem = slideBy,
arrowKeysTem = arrowKeys,
autoHeightTem = autoHeight,
fixedWidthTem = fixedWidth,
edgePaddingTem = edgePadding,
gutterTem = gutter,
disableTem = disable;
// update variables
items = getOption('items');
slideBy = getOption('slideBy');
disable = getOption('disable');
freeze = disable ? true : freezable ? slideCount <= items : false;
if (items !== itemsTem) {
indexMax = getIndexMax();
// check index before transform in case
// slider reach the right edge then items become bigger
updateIndex();
}
if (disable !== disableTem) {
disableSlider(disable);
}
if (freeze !== freezeTem) {
// reset index to initial status
if (freeze) { index = !carousel ? 0 : cloneCount; }
toggleSlideDisplayAndEdgePadding();
}
if (breakpointZoneTem !== breakpointZone) {
speed = getOption('speed');
edgePadding = getOption('edgePadding');
gutter = getOption('gutter');
fixedWidth = getOption('fixedWidth');
if (!disable && fixedWidth !== fixedWidthTem) {
needContainerTransform = true;
}
autoHeight = getOption('autoHeight');
if (autoHeight !== autoHeightTem) {
if (!autoHeight) { innerWrapper.style.height = ''; }
}
}
arrowKeys = freeze ? false : getOption('arrowKeys');
if (arrowKeys !== arrowKeysTem) {
arrowKeys ?
addEvents(doc, docmentKeydownEvent) :
removeEvents(doc, docmentKeydownEvent);
}
if (hasControls) {
var controlsTem = controls,
controlsTextTem = controlsText;
controls = freeze ? false : getOption('controls');
controlsText = getOption('controlsText');
if (controls !== controlsTem) {
controls ?
showElement(controlsContainer) :
hideElement(controlsContainer);
}
if (controlsText !== controlsTextTem) {
prevButton.innerHTML = controlsText[0];
nextButton.innerHTML = controlsText[1];
}
}
if (hasNav) {
var navTem = nav;
nav = freeze ? false : getOption('nav');
if (nav !== navTem) {
if (nav) {
showElement(navContainer);
updateNavVisibility();
} else {
hideElement(navContainer);
}
}
}
if (hasTouch) {
var touchTem = touch;
touch = freeze ? false : getOption('touch');
if (touch !== touchTem && carousel) {
touch ?
addEvents(container, touchEvents) :
removeEvents(container, touchEvents);
}
}
if (hasMouseDrag) {
var mouseDragTem = mouseDrag;
mouseDrag = freeze ? false : getOption('mouseDrag');
if (mouseDrag !== mouseDragTem && carousel) {
mouseDrag ?
addEvents(container, dragEvents) :
removeEvents(container, dragEvents);
}
}
if (hasAutoplay) {
var autoplayTem = autoplay,
autoplayHoverPauseTem = autoplayHoverPause,
autoplayResetOnVisibilityTem = autoplayResetOnVisibility,
autoplayTextTem = autoplayText;
if (freeze) {
autoplay = autoplayHoverPause = autoplayResetOnVisibility = false;
} else {
autoplay = getOption('autoplay');
if (autoplay) {
autoplayHoverPause = getOption('autoplayHoverPause');
autoplayResetOnVisibility = getOption('autoplayResetOnVisibility');
} else {
autoplayHoverPause = autoplayResetOnVisibility = false;
}
}
autoplayText = getOption('autoplayText');
autoplayTimeout = getOption('autoplayTimeout');
if (autoplay !== autoplayTem) {
if (autoplay) {
if (autoplayButton) { showElement(autoplayButton); }
if (!animating && !autoplayUserPaused) { startAutoplay(); }
} else {
if (autoplayButton) { hideElement(autoplayButton); }
if (animating) { stopAutoplay(); }
}
}
if (autoplayHoverPause !== autoplayHoverPauseTem) {
autoplayHoverPause ?
addEvents(container, hoverEvents) :
removeEvents(container, hoverEvents);
}
if (autoplayResetOnVisibility !== autoplayResetOnVisibilityTem) {
autoplayResetOnVisibility ?
addEvents(doc, visibilityEvent) :
removeEvents(doc, visibilityEvent);
}
if (autoplayButton && autoplayText !== autoplayTextTem) {
var i = autoplay ? 1 : 0,
html = autoplayButton.innerHTML,
len = html.length - autoplayTextTem[i].length;
if (html.substring(len) === autoplayTextTem[i]) {
autoplayButton.innerHTML = html.substring(0, len) + autoplayText[i];
}
}
}
// IE8
// ## update inner wrapper, container, slides if needed
// set inline styles for inner wrapper & container
// insert stylesheet (one line) for slides only (since slides are many)
if (!CSSMQ) {
// inner wrapper styles
if (!freeze && (edgePadding !== edgePaddingTem || gutter !== gutterTem)) {
innerWrapper.style.cssText = getInnerWrapperStyles(edgePadding, gutter, fixedWidth);
}
// container styles
if (carousel && horizontal && (fixedWidth !== fixedWidthTem || gutter !== gutterTem || items !== itemsTem)) {
container.style.width = getContainerWidth(fixedWidth, gutter, items);
}
// slide styles
if (horizontal && (items !== itemsTem || gutter !== gutterTem || fixedWidth != fixedWidthTem)) {
var str = getSlideWidthStyle(fixedWidth, gutter, items) +
getSlideGutterStyle(gutter);
// remove the last line and
// add new styles
sheet.removeRule(getCssRulesLength(sheet) - 1);
addCSSRule(sheet, '#' + slideId + ' > .tns-item', str, getCssRulesLength(sheet));
}
if (!fixedWidth) { needContainerTransform = true; }
}
if (index !== indexTem) {
events.emit('indexChanged', info());
needContainerTransform = true;
}
if (items !== itemsTem) {
additionalUpdates();
updateSlidePosition();
if (navigator.msMaxTouchPoints) { setSnapInterval(); }
}
}
// things always do regardless of breakpoint zone changing
if (!horizontal && !disable) {
getSlideOffsetTops();
updateContentWrapperHeight();
needContainerTransform = true;
}
if (needContainerTransform) {
doContainerTransformSilent();
indexCached = index;
}
updateFixedWidthInnerWrapperStyle(true);
// auto height
if ((autoHeight || !carousel) && !disable) { runAutoHeight(); }
}
// === INITIALIZATION FUNCTIONS === //
function setBreakpointZone () {
breakpointZone = 0;
breakpoints.forEach(function(bp, i) {
if (windowWidth >= bp) { breakpointZone = i + 1; }
});
}
function loopNumber (num, min, max) {
return index >= indexMin && index <= indexMax ? index : index > indexMax ? index - slideCount : index + slideCount;
}
function cutindexber (index, min, indexMax) {
return index >= indexMin && index <= indexMax ? index : index > indexMax ? indexMax : indexMin;
}
// (slideBy, indexMin, indexMax) => index
var updateIndex = (function () {
return loop ?
carousel ?
// loop + carousel
function () {
var leftEdge = indexMin,
rightEdge = indexMax;
leftEdge += slideBy;
rightEdge -= slideBy;
// adjust edges when edge padding is true
// or fixed-width slider with extra space on the right side
if (edgePadding) {
leftEdge += 1;
rightEdge -= 1;
} else if (fixedWidth) {
var gt = gutter ? gutter : 0;
if (vpOuter%(fixedWidth + gt) > gt) { rightEdge -= 1; }
}
if (cloneCount) {
if (index > rightEdge) {
index -= slideCount;
} else if (index < leftEdge) {
index += slideCount;
}
}
} :
// loop + gallery
function() {
if (index > indexMax) {
while (index >= indexMin + slideCount) { index -= slideCount; }
} else if (index < indexMin) {
while (index <= indexMax - slideCount) { index += slideCount; }
}
} :
// non-loop
function() {
index = (index >= indexMin && index <= indexMax) ? index :
index > indexMax ? indexMax : indexMin;
};
})();
function toggleSlideDisplayAndEdgePadding () {
// if (cloneCount) {
// if (fixedWidth && cloneCount) {
var str = 'tns-transparent';
if (freeze) {
if (!frozen) {
// remove edge padding from inner wrapper
if (edgePadding) { innerWrapper.style.margin = '0px'; }
// add class tns-transparent to cloned slides
if (cloneCount) {
for (var i = cloneCount; i--;) {
if (carousel) { addClass(slideItems[i], str); }
addClass(slideItems[slideCountNew - i - 1], str);
}
}
frozen = true;
}
} else if (frozen) {
// restore edge padding for inner wrapper
// for mordern browsers
if (edgePadding && !fixedWidth && CSSMQ) { innerWrapper.style.margin = ''; }
// remove class tns-transparent to cloned slides
if (cloneCount) {
for (var i = cloneCount; i--;) {
if (carousel) { removeClass(slideItems[i], str); }
removeClass(slideItems[slideCountNew - i - 1], str);
}
}
frozen = false;
}
// }
}
function updateFixedWidthInnerWrapperStyle (resize) {
if (fixedWidth && edgePadding) {
// remove edge padding when freeze or viewport narrower than one slide
if (freeze || vpOuter <= (fixedWidth + gutter)) {
if (innerWrapper.style.margin !== '0px') { innerWrapper.style.margin = '0px'; }
// update edge padding on resize
} else if (resize) {
innerWrapper.style.cssText = getInnerWrapperStyles(edgePadding, gutter, fixedWidth);
}
}
}
function disableSlider (disable) {
var len = slideItems.length;
if (disable) {
sheet.disabled = true;
container.className = container.className.replace(classContainer.substring(1), '');
removeElementStyles(container);
if (loop) {
for (var j = cloneCount; j--;) {
if (carousel) { hideElement(slideItems[j]); }
hideElement(slideItems[len - j - 1]);
}
}
// vertical slider
if (!horizontal || !carousel) { removeElementStyles(innerWrapper); }
// gallery
if (!carousel) {
for (var i = index, l = index + slideCount; i < l; i++) {
var item = slideItems[i];
removeElementStyles(item);
removeClass(item, animateIn);
removeClass(item, animateNormal);
}
}
} else {
sheet.disabled = false;
container.className += classContainer;
// vertical slider: get offsetTops before container transform
if (!horizontal) { getSlideOffsetTops(); }
doContainerTransformSilent();
if (loop) {
for (var j = cloneCount; j--;) {
if (carousel) { showElement(slideItems[j]); }
showElement(slideItems[len - j - 1]);
}
}
// gallery
if (!carousel) {
for (var i = index, l = index + slideCount; i < l; i++) {
var item = slideItems[i],
classN = i < index + items ? animateIn : animateNormal;
item.style.left = (i - index) * 100 / items + '%';
addClass(item, classN);
}
}
}
}
// lazyload
function lazyLoad () {
if (lazyload && !disable) {
var i = index,
len = index + items;
if (edgePadding) {
i -=1;
len +=1;
}
i = Math.max(i, 0);
len = Math.min(len, slideCountNew);
for(; i < len; i++) {
forEachNodeList(slideItems[i].querySelectorAll('.tns-lazy-img'), function (img) {
// stop propagationl transitionend event to container
var eve = {};
eve[TRANSITIONEND] = function (e) { e.stopPropagation(); };
addEvents(img, eve);
if (!hasClass(img, 'loaded')) {
img.src = getAttr(img, 'data-src');
addClass(img, 'loaded');
}
});
}
}
}
function imgLoadedOrError (e) {
var img = getTarget(e);
addClass(img, imgCompleteClass);
removeEvents(img, imgEvents);
}
function getImageArray (slideStart, slideRange) {
var imgs = [];
for (var i = slideStart, l = slideStart + slideRange; i < l; i++) {
forEachNodeList(slideItems[i].querySelectorAll('img'), function (img) {
imgs.push(img);
});
}
return imgs;
}
// check if all visible images are loaded
// and update container height if it's done
function runAutoHeight () {
var imgs = autoHeight ?
getImageArray(index, items) :
getImageArray(cloneCount, slideCount);
raf(function(){ checkImagesLoaded(imgs, updateInnerWrapperHeight); });
}
function checkImagesLoaded (imgs, cb) {
// directly execute callback function if all images are complete
if (imgsComplete) { return cb(); }
// check selected image classes otherwise
imgs.forEach(function (img, index) {
if (hasClass(img, imgCompleteClass)) { imgs.splice(index, 1); }
});
// execute callback function if selected images are all complete
if (!imgs.length) { return cb(); }
// otherwise execute this functiona again
raf(function(){ checkImagesLoaded(imgs, cb); });
}
function additionalUpdates () {
lazyLoad();
updateSlideStatus();
updateControlsStatus();
updateNavVisibility();
updateNavStatus();
}
function getMaxSlideHeight (slideStart, slideRange) {
var heights = [];
for (var i = slideStart, l = slideStart + slideRange; i < l; i++) {
heights.push(slideItems[i].offsetHeight);
}
return Math.max.apply(null, heights);
}
// update inner wrapper height
// 1. get the max-height of the visible slides
// 2. set transitionDuration to speed
// 3. update inner wrapper height to max-height
// 4. set transitionDuration to 0s after transition done
function updateInnerWrapperHeight () {
var maxHeight = autoHeight ?
getMaxSlideHeight(index, items) :
getMaxSlideHeight(cloneCount, slideCount);
if (innerWrapper.style.height !== maxHeight) { innerWrapper.style.height = maxHeight + 'px'; }
}
// get the distance from the top edge of the first slide to each slide
// (init) => slideOffsetTops
function getSlideOffsetTops () {
slideOffsetTops = [0];
var topFirst = slideItems[0].getBoundingClientRect().top, attr;
for (var i = 1; i < slideCountNew; i++) {
attr = slideItems[i].getBoundingClientRect().top;
slideOffsetTops.push(attr - topFirst);
}
}
// set snapInterval (for IE10)
function setSnapInterval () {
outerWrapper.style.msScrollSnapPointsX = 'snapInterval(0%, ' + (100 / items) + '%)';
}
// update slide
function updateSlideStatus () {
var l = index + Math.min(slideCount, items);
for (var i = slideCountNew; i--;) {
var item = slideItems[i];
// visible slides
if (i >= index && i < l) {
if (hasAttr(item, 'tabindex')) {
setAttrs(item, {'aria-hidden': 'false'});
removeAttrs(item, ['tabindex']);
addClass(item, slideActiveClass);
}
// hidden slides
} else {
if (!hasAttr(item, 'tabindex')) {
setAttrs(item, {
'aria-hidden': 'true',
'tabindex': '-1'
});
}
if (hasClass(item, slideActiveClass)) {
removeClass(item, slideActiveClass);
}
}
}
}
// gallery: update slide position
function updateSlidePosition () {
if (!carousel) {
var l = index + Math.min(slideCount, items);
for (var i = slideCountNew; i--;) {
var item = slideItems[i];
if (i >= index && i < l) {
// add transitions to visible slides when adjusting their positions
addClass(item, 'tns-moving');
item.style.left = (i - index) * 100 / items + '%';
addClass(item, animateIn);
removeClass(item, animateNormal);
} else if (item.style.left) {
item.style.left = '';
addClass(item, animateNormal);
removeClass(item, animateIn);
}
// remove outlet animation
removeClass(item, animateOut);
}
// removing '.tns-moving'
setTimeout(function() {
forEachNodeList(slideItems, function(el) {
removeClass(el, 'tns-moving');
});
}, 300);
}
}
// set tabindex & aria-selected on Nav
function updateNavStatus () {
// get current nav
if (nav) {
navCurrentIndex = navClicked !== -1 ? navClicked : getAbsIndex();
navClicked = -1;
if (navCurrentIndex !== navCurrentIndexCached) {
var navPrev = navItems[navCurrentIndexCached],
navCurrent = navItems[navCurrentIndex];
setAttrs(navPrev, {
'tabindex': '-1',
'aria-selected': 'false'
});
setAttrs(navCurrent, {
'tabindex': '0',
'aria-selected': 'true'
});
removeClass(navPrev, navActiveClass);
addClass(navCurrent, navActiveClass);
}
}
}
function getLowerCaseNodeName (el) {
return el.nodeName.toLowerCase();
}
function isButton (el) {
return getLowerCaseNodeName(el) === 'button';
}
function isAriaDisabled (el) {
return el.getAttribute('aria-disabled') === 'true';
}
function disEnableElement (isButton, el, val) {
if (isButton) {
el.disabled = val;
} else {
el.setAttribute('aria-disabled', val.toString());
}
}
// set 'disabled' to true on controls when reach the edges
function updateControlsStatus () {
if (!controls || rewind || loop) { return; }
var prevDisabled = (prevIsButton) ? prevButton.disabled : isAriaDisabled(prevButton),
nextDisabled = (nextIsButton) ? nextButton.disabled : isAriaDisabled(nextButton),
disablePrev = (index === indexMin) ? true : false,
disableNext = (!rewind && index === indexMax) ? true : false;
if (disablePrev && !prevDisabled) {
disEnableElement(prevIsButton, prevButton, true);
}
if (!disablePrev && prevDisabled) {
disEnableElement(prevIsButton, prevButton, false);
}
if (disableNext && !nextDisabled) {
disEnableElement(nextIsButton, nextButton, true);
}
if (!disableNext && nextDisabled) {
disEnableElement(nextIsButton, nextButton, false);
}
}
// set duration
function resetDuration (el, str) {
if (TRANSITIONDURATION) { el.style[TRANSITIONDURATION] = str; }
}
function getContainerTransformValue () {
var val;
if (horizontal) {
if (fixedWidth) {
val = - (fixedWidth + gutter) * index + 'px';
} else {
var denominator = TRANSFORM ? slideCountNew : items;
val = - index * 100 / denominator + '%';
}
} else {
val = - slideOffsetTops[index] + 'px';
}
return val;
}
function doContainerTransformSilent (val) {
resetDuration(container, '0s');
doContainerTransform(val);
setTimeout(function() { resetDuration(container, ''); }, 0);
}
function doContainerTransform (val, test) {
if (!val) { val = getContainerTransformValue(); }
container.style[transformAttr] = transformPrefix + val + transformPostfix;
}
function animateSlide (number, classOut, classIn, isOut) {
var l = number + items;
if (!loop) { l = Math.min(l, slideCountNew); }
for (var i = number; i < l; i++) {
var item = slideItems[i];
// set item positions
if (!isOut) { item.style.left = (i - index) * 100 / items + '%'; }
if (animateDelay && TRANSITIONDELAY) {
item.style[TRANSITIONDELAY] = item.style[ANIMATIONDELAY] = animateDelay * (i - number) / 1000 + 's';
}
removeClass(item, classOut);
addClass(item, classIn);
if (isOut) { slideItemsOut.push(item); }
}
}
// make transfer after click/drag:
// 1. change 'transform' property for mordern browsers
// 2. change 'left' property for legacy browsers
var transformCore = (function () {
return carousel ?
function (duration, distance) {
if (!distance) { distance = getContainerTransformValue(); }
// constrain the distance when non-loop no-edgePadding fixedWidth reaches the right edge
if (hasRightDeadZone && index === indexMax) {
distance = - ((fixedWidth + gutter) * slideCountNew - vpInner) + 'px';
}
if (TRANSITIONDURATION || !duration) {
// for morden browsers with non-zero duration or
// zero duration for all browsers
doContainerTransform(distance);
// run fallback function manually
// when duration is 0 / container is hidden
if (!duration || !isVisible(container)) { onTransitionEnd(); }
} else {
// for old browser with non-zero duration
jsTransform(container, transformAttr, transformPrefix, transformPostfix, distance, speed, onTransitionEnd);
}
if (!horizontal) { updateContentWrapperHeight(); }
} :
function (duration) {
slideItemsOut = [];
var eve = {};
eve[TRANSITIONEND] = eve[ANIMATIONEND] = onTransitionEnd;
removeEvents(slideItems[indexCached], eve);
addEvents(slideItems[index], eve);
animateSlide(indexCached, animateIn, animateOut, true);
animateSlide(index, animateNormal, animateIn);
// run fallback function manually
// when transition or animation not supported / duration is 0
if (!TRANSITIONEND || !ANIMATIONEND || !duration) { onTransitionEnd(); }
};
})();
function doTransform (duration, distance) {
// check duration is defined and is a number
if (isNaN(duration)) { duration = speed; }
// if container is hidden, set duration to 0
// to fix an issue where browser doesn't fire ontransitionend on hidden element
if (animating && !isVisible(container)) { duration = 0; }
transformCore(duration, distance);
}
function render (e, sliderMoved) {
if (updateIndexBeforeTransform) { updateIndex(); }
// render when slider was moved (touch or drag) even though index may not change
if (index !== indexCached || sliderMoved) {
// events
events.emit('indexChanged', info());
events.emit('transitionStart', info());
// pause autoplay when click or keydown from user
if (animating && e && ['click', 'keydown'].indexOf(e.type) >= 0) { stopAutoplay(); }
running = true;
doTransform();
}
}
/*
* Transfer prefixed properties to the same format
* CSS: -Webkit-Transform => webkittransform
* JS: WebkitTransform => webkittransform
* @param {string} str - property
*
*/
function strTrans (str) {
return str.toLowerCase().replace(/-/g, '');
}
// AFTER TRANSFORM
// Things need to be done after a transfer:
// 1. check index
// 2. add classes to visible slide
// 3. disable controls buttons when reach the first/last slide in non-loop slider
// 4. update nav status
// 5. lazyload images
// 6. update container height
function onTransitionEnd (event) {
// check running on gallery mode
// make sure trantionend/animationend events run only once
if (carousel || running) {
events.emit('transitionEnd', info(event));
if (!carousel && slideItemsOut.length > 0) {
for (var i = 0; i < slideItemsOut.length; i++) {
var item = slideItemsOut[i];
// set item positions
item.style.left = '';
if (ANIMATIONDELAY && TRANSITIONDELAY) {
item.style[ANIMATIONDELAY] = '';
item.style[TRANSITIONDELAY] = '';
}
removeClass(item, animateOut);
addClass(item, animateNormal);
}
}
/* update slides, nav, controls after checking ...
* => legacy browsers who don't support 'event'
* have to check event first, otherwise event.target will cause an error
* => or 'gallery' mode:
* + event target is slide item
* => or 'carousel' mode:
* + event target is container,
* + event.property is the same with transform attribute
*/
if (!event ||
!carousel && event.target.parentNode === container ||
event.target === container && strTrans(event.propertyName) === strTrans(transformAttr)) {
if (!updateIndexBeforeTransform) {
var indexTem = index;
updateIndex();
if (index !== indexTem) {
events.emit('indexChanged', info());
doContainerTransformSilent();
}
}
if (autoHeight) { runAutoHeight(); }
if (nested === 'inner') { events.emit('innerLoaded', info()); }
running = false;
navCurrentIndexCached = navCurrentIndex;
indexCached = index;
}
}
}
// # ACTIONS
function goTo (targetIndex, e) {
if (freeze) { return; }
// prev slideBy
if (targetIndex === 'prev') {
onControlsClick(e, -1);
// next slideBy
} else if (targetIndex === 'next') {
onControlsClick(e, 1);
// go to exact slide
} else {
if (running) { onTransitionEnd(); }
// } else if (!running) {
var absIndex = getAbsIndex(),
indexGap = 0;
if (absIndex < 0) { absIndex += slideCount; }
if (targetIndex === 'first') {
indexGap = - absIndex;
} else if (targetIndex === 'last') {
indexGap = carousel ? slideCount - items - absIndex : slideCount - 1 - absIndex;
} else {
if (typeof targetIndex !== 'number') { targetIndex = parseInt(targetIndex); }
if (!isNaN(targetIndex)) {
var absTargetIndex = getAbsIndex(targetIndex);
if (absTargetIndex < 0) { absTargetIndex += slideCount; }
indexGap = absTargetIndex - absIndex;
}
}
index += indexGap;
// if index is changed, start rendering
if (getAbsIndex(index) !== getAbsIndex(indexCached)) {
render(e);
}
}
}
// on controls click
function onControlsClick (e, dir) {
// if (!running) {
if (running) { onTransitionEnd(); }
var passEventObject;
if (!dir) {
e = getEvent(e);
var target = e.target || e.srcElement;
while (target !== controlsContainer && [prevButton, nextButton].indexOf(target) < 0) { target = target.parentNode; }
var targetIn = [prevButton, nextButton].indexOf(target);
if (targetIn >= 0) {
passEventObject = true;
dir = targetIn === 0 ? -1 : 1;
}
}
if (rewind) {
if (index === indexMin && dir === -1) {
goTo('last', e);
return;
} else if (index === indexMax && dir === 1) {
goTo(0, e);
return;
}
}
if (dir) {
index += slideBy * dir;
// pass e when click control buttons or keydown
render((passEventObject || (e && e.type === 'keydown')) ? e : null);
}
// }
}
// on nav click
function onNavClick (e) {
// if (!running) {
if (running) { onTransitionEnd(); }
e = getEvent(e);
var target = e.target || e.srcElement,
navIndex;
// find the clicked nav item
while (target !== navContainer && !hasAttr(target, 'data-nav')) { target = target.parentNode; }
if (hasAttr(target, 'data-nav')) {
navIndex = navClicked = [].indexOf.call(navItems, target);
goTo(navIndex + cloneCount, e);
}
// }
}
// autoplay functions
function setAutoplayTimer () {
autoplayTimer = setInterval(function () {
onControlsClick(null, autoplayDirection);
}, autoplayTimeout);
animating = true;
}
function stopAutoplayTimer () {
clearInterval(autoplayTimer);
animating = false;
}
function updateAutoplayButton (action, txt) {
setAttrs(autoplayButton, {'data-action': action});
autoplayButton.innerHTML = autoplayHtmlStrings[0] + action + autoplayHtmlStrings[1] + txt;
}
function startAutoplay () {
setAutoplayTimer();
if (autoplayButton) { updateAutoplayButton('stop', autoplayText[1]); }
}
function stopAutoplay () {
stopAutoplayTimer();
if (autoplayButton) { updateAutoplayButton('start', autoplayText[0]); }
}
// programaitcally play/pause the slider
function play () {
if (autoplay && !animating) {
startAutoplay();
autoplayUserPaused = false;
}
}
function pause () {
if (animating) {
stopAutoplay();
autoplayUserPaused = true;
}
}
function toggleAutoplay () {
if (animating) {
stopAutoplay();
autoplayUserPaused = true;
} else {
startAutoplay();
autoplayUserPaused = false;
}
}
function onVisibilityChange () {
if (doc.hidden) {
if (animating) {
stopAutoplayTimer();
autoplayVisibilityPaused = true;
}
} else if (autoplayVisibilityPaused) {
setAutoplayTimer();
autoplayVisibilityPaused = false;
}
}
function mouseoverPause () {
if (animating) {
stopAutoplayTimer();
autoplayHoverPaused = true;
}
}
function mouseoutRestart () {
if (autoplayHoverPaused) {
setAutoplayTimer();
autoplayHoverPaused = false;
}
}
// keydown events on document
function onDocumentKeydown (e) {
e = getEvent(e);
switch(e.keyCode) {
case KEYS.LEFT:
onControlsClick(e, -1);
break;
case KEYS.RIGHT:
onControlsClick(e, 1);
}
}
// on key control
function onControlsKeydown (e) {
e = getEvent(e);
var code = e.keyCode;
switch (code) {
case KEYS.LEFT:
case KEYS.UP:
case KEYS.PAGEUP:
if (!prevButton.disabled) {
onControlsClick(e, -1);
}
break;
case KEYS.RIGHT:
case KEYS.DOWN:
case KEYS.PAGEDOWN:
if (!nextButton.disabled) {
onControlsClick(e, 1);
}
break;
case KEYS.HOME:
goTo(0, e);
break;
case KEYS.END:
goTo(slideCount - 1, e);
break;
}
}
// set focus
function setFocus (focus) {
focus.focus();
}
// on key nav
function onNavKeydown (e) {
var curElement = doc.activeElement;
if (!hasAttr(curElement, 'data-nav')) { return; }
e = getEvent(e);
var code = e.keyCode,
navIndex = [].indexOf.call(navItems, curElement),
len = visibleNavIndexes.length,
current = visibleNavIndexes.indexOf(navIndex);
if (options.navContainer) {
len = slideCount;
current = navIndex;
}
function getNavIndex (num) {
return options.navContainer ? num : visibleNavIndexes[num];
}
switch(code) {
case KEYS.LEFT:
case KEYS.PAGEUP:
if (current > 0) { setFocus(navItems[getNavIndex(current - 1)]); }
break;
case KEYS.UP:
case KEYS.HOME:
if (current > 0) { setFocus(navItems[getNavIndex(0)]); }
break;
case KEYS.RIGHT:
case KEYS.PAGEDOWN:
if (current < len - 1) { setFocus(navItems[getNavIndex(current + 1)]); }
break;
case KEYS.DOWN:
case KEYS.END:
if (current < len - 1) { setFocus(navItems[getNavIndex(len - 1)]); }
break;
// Can't use onNavClick here,
// Because onNavClick require event.target as nav items
case KEYS.ENTER:
case KEYS.SPACE:
navClicked = navIndex;
goTo(navIndex + cloneCount, e);
break;
}
}
// IE10 scroll function
function ie10Scroll () {
transformCore(0, container.scrollLeft);
indexCached = index;
}
function getEvent (e) {
e = e || win.event;
return isTouchEvent(e) ? e.changedTouches[0] : e;
}
function getTarget (e) {
return e.target || win.event.srcElement;
}
function isTouchEvent (e) {
return e.type.indexOf('touch') >= 0;
}
function preventDefaultBehavior (e) {
e.preventDefault ? e.preventDefault() : e.returnValue = false;
}
function onPanStart (e) {
if (running) { onTransitionEnd(); }
panStart = true;
caf(rafIndex);
rafIndex = raf(function(){ panUpdate(e); });
var $ = getEvent(e);
events.emit(isTouchEvent(e) ? 'touchStart' : 'dragStart', info(e));
if (!isTouchEvent(e) && ['img', 'a'].indexOf(getLowerCaseNodeName(getTarget(e))) >= 0) {
preventDefaultBehavior(e);
}
lastPosition.x = initPosition.x = parseInt($.clientX);
lastPosition.y = initPosition.y = parseInt($.clientY);
translateInit = parseFloat(container.style[transformAttr].replace(transformPrefix, '').replace(transformPostfix, ''));
resetDuration(container, '0s');
}
function onPanMove (e) {
if (panStart) {
var $ = getEvent(e);
lastPosition.x = parseInt($.clientX);
lastPosition.y = parseInt($.clientY);
}
}
function panUpdate (e) {
if (!moveDirectionExpected) {
panStart = false;
return;
}
caf(rafIndex);
if (panStart) { rafIndex = raf(function(){ panUpdate(e); }); }
if (
moveDirectionExpected === '?' &&
lastPosition.x !== initPosition.x &&
lastPosition.y !== initPosition.y) {
moveDirectionExpected = getTouchDirection(toDegree(lastPosition.y - initPosition.y, lastPosition.x - initPosition.x), swipeAngle) === options.axis;
}
if (moveDirectionExpected) {
events.emit(isTouchEvent(e) ? 'touchMove' : 'dragMove', info(e));
var x = translateInit,
dist = getDist(lastPosition, initPosition);
if (!horizontal || fixedWidth) {
x += dist;
x += 'px';
} else {
var percentageX = TRANSFORM ? dist * items * 100 / (vpInner * slideCountNew): dist * 100 / vpInner;
x += percentageX;
x += '%';
}
container.style[transformAttr] = transformPrefix + x + transformPostfix;
}
}
function onPanEnd (e) {
if (swipeAngle) { moveDirectionExpected = '?'; } // reset
if (panStart) {
caf(rafIndex);
resetDuration(container, '');
panStart = false;
var $ = getEvent(e);
lastPosition.x = parseInt($.clientX);
lastPosition.y = parseInt($.clientY);
var dist = getDist(lastPosition, initPosition);
// initPosition = {x:0, y:0}; // reset positions
// lastPosition = {x:0, y:0}; // reset positions
if (Math.abs(dist) >= 5) {
// drag vs click
if (!isTouchEvent(e)) {
// prevent "click"
var target = getTarget(e);
addEvents(target, {'click': function preventClick (e) {
preventDefaultBehavior(e);
removeEvents(target, {'click': preventClick});
}});
}
rafIndex = raf(function() {
events.emit(isTouchEvent(e) ? 'touchEnd' : 'dragEnd', info(e));
if (horizontal) {
var indexMoved = - dist * items / vpInner;
indexMoved = dist > 0 ? Math.floor(indexMoved) : Math.ceil(indexMoved);
index += indexMoved;
} else {
var moved = - (translateInit + dist);
if (moved <= 0) {
index = indexMin;
} else if (moved >= slideOffsetTops[slideOffsetTops.length - 1]) {
index = indexMax;
} else {
var i = 0;
do {
i++;
index = dist < 0 ? i + 1 : i;
} while (i < slideCountNew && moved >= slideOffsetTops[i + 1]);
}
}
render(e, dist);
});
}
}
}
// === RESIZE FUNCTIONS === //
// (slideOffsetTops, index, items) => vertical_conentWrapper.height
function updateContentWrapperHeight () {
innerWrapper.style.height = slideOffsetTops[index + items] - slideOffsetTops[index] + 'px';
}
/*
* get nav item indexes per items
* add 1 more if the nav items cann't cover all slides
* [0, 1, 2, 3, 4] / 3 => [0, 3]
*/
function getVisibleNavIndex () {
// reset visibleNavIndexes
visibleNavIndexes = [];
var absIndexMin = getAbsIndex()%items;
while (absIndexMin < slideCount) {
if (carousel && !loop && absIndexMin + items > slideCount) { absIndexMin = slideCount - items; }
visibleNavIndexes.push(absIndexMin);
absIndexMin += items;
}
// nav count * items < slide count means
// some slides can not be displayed only by nav clicking
if (loop && visibleNavIndexes.length * items < slideCount ||
!loop && visibleNavIndexes[0] > 0) {
visibleNavIndexes.unshift(0);
}
}
/*
* 1. update visible nav items list
* 2. add "hidden" attributes to previous visible nav items
* 3. remove "hidden" attrubutes to new visible nav items
*/
function updateNavVisibility () {
if (!nav || navAsThumbnails) { return; }
getVisibleNavIndex();
if (visibleNavIndexes !== visibleNavIndexesCached) {
forEachNodeList(navItems, function(el, i) {
if (visibleNavIndexes.indexOf(i) < 0) {
hideElement(el);
} else {
showElement(el);
}
});
// cache visible nav indexes
visibleNavIndexesCached = visibleNavIndexes;
}
}
function info (e) {
return {
container: container,
slideItems: slideItems,
navContainer: navContainer,
navItems: navItems,
controlsContainer: controlsContainer,
hasControls: hasControls,
prevButton: prevButton,
nextButton: nextButton,
items: items,
slideBy: slideBy,
cloneCount: cloneCount,
slideCount: slideCount,
slideCountNew: slideCountNew,
index: index,
indexCached: indexCached,
navCurrentIndex: navCurrentIndex,
navCurrentIndexCached: navCurrentIndexCached,
visibleNavIndexes: visibleNavIndexes,
visibleNavIndexesCached: visibleNavIndexesCached,
sheet: sheet,
event: e || {},
};
}
return {
getInfo: info,
events: events,
goTo: goTo,
play: play,
pause: pause,
isOn: isOn,
updateSliderHeight: updateInnerWrapperHeight,
rebuild: function() {
return tns(options);
},
destroy: function () {
// remove win event listeners
removeEvents(win, {'resize': onResize});
// remove arrowKeys eventlistener
removeEvents(doc, docmentKeydownEvent);
// sheet
sheet.disabled = true;
// cloned items
if (loop) {
for (var j = cloneCount; j--;) {
if (carousel) { slideItems[0].remove(); }
slideItems[slideItems.length - 1].remove();
}
}
// Slide Items
var slideClasses = ['tns-item', slideActiveClass];
if (!carousel) { slideClasses = slideClasses.concat('tns-normal', animateIn); }
for (var i = slideCount; i--;) {
var slide = slideItems[i];
if (slide.id.indexOf(slideId + '-item') >= 0) { slide.id = ''; }
slideClasses.forEach(function(cl) { removeClass(slide, cl); });
}
removeAttrs(slideItems, ['style', 'aria-hidden', 'tabindex']);
slideItems = slideId = slideCount = slideCountNew = cloneCount = null;
// controls
if (controls) {
removeEvents(controlsContainer, controlsEvents);
if (options.controlsContainer) {
removeAttrs(controlsContainer, ['aria-label', 'tabindex']);
removeAttrs(controlsContainer.children, ['aria-controls', 'aria-disabled', 'tabindex']);
}
controlsContainer = prevButton = nextButton = null;
}
// nav
if (nav) {
removeEvents(navContainer, navEvents);
if (options.navContainer) {
removeAttrs(navContainer, ['aria-label']);
removeAttrs(navItems, ['aria-selected', 'aria-controls', 'tabindex']);
}
navContainer = navItems = null;
}
// auto
if (autoplay) {
clearInterval(autoplayTimer);
if (autoplayButton) {
removeEvents(autoplayButton, {'click': toggleAutoplay});
}
removeEvents(container, hoverEvents);
removeEvents(container, visibilityEvent);
if (options.autoplayButton) {
removeAttrs(autoplayButton, ['data-action']);
}
}
// container
container.id = containerIdCached || '';
container.className = container.className.replace(classContainer, '');
removeElementStyles(container);
if (carousel && TRANSITIONEND) {
var eve = {};
eve[TRANSITIONEND] = onTransitionEnd;
removeEvents(container, eve);
}
removeEvents(container, touchEvents);
removeEvents(container, dragEvents);
// outerWrapper
containerParent.insertBefore(container, outerWrapper);
outerWrapper.remove();
outerWrapper = innerWrapper = container =
index = indexCached = items = slideBy = navCurrentIndex = navCurrentIndexCached = hasControls = visibleNavIndexes = visibleNavIndexesCached =
this.getInfo = this.events = this.goTo = this.play = this.pause = this.destroy = null;
this.isOn = isOn = false;
}
};
};
return tns;
})(); | jonobr1/cdnjs | ajax/libs/tiny-slider/2.7.3/tiny-slider.js | JavaScript | mit | 89,288 |
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Package\Archiver;
use Symfony\Component\Finder;
/**
* @author Nils Adermann <naderman@naderman.de>
*/
abstract class BaseExcludeFilter
{
/**
* @var string
*/
protected $sourcePath;
/**
* @var array
*/
protected $excludePatterns;
/**
* @param string $sourcePath Directory containing sources to be filtered
*/
public function __construct($sourcePath)
{
$this->sourcePath = $sourcePath;
$this->excludePatterns = array();
}
/**
* Checks the given path against all exclude patterns in this filter
*
* Negated patterns overwrite exclude decisions of previous filters.
*
* @param string $relativePath The file's path relative to the sourcePath
* @param bool $exclude Whether a previous filter wants to exclude this file
*
* @return bool Whether the file should be excluded
*/
public function filter($relativePath, $exclude)
{
foreach ($this->excludePatterns as $patternData) {
list($pattern, $negate, $stripLeadingSlash) = $patternData;
if ($stripLeadingSlash) {
$path = substr($relativePath, 1);
} else {
$path = $relativePath;
}
if (preg_match($pattern, $path)) {
$exclude = !$negate;
}
}
return $exclude;
}
/**
* Processes a file containing exclude rules of different formats per line
*
* @param array $lines A set of lines to be parsed
* @param callback $lineParser The parser to be used on each line
*
* @return array Exclude patterns to be used in filter()
*/
protected function parseLines(array $lines, $lineParser)
{
return array_filter(
array_map(
function ($line) use ($lineParser) {
$line = trim($line);
$commentHash = strpos($line, '#');
if ($commentHash !== false) {
$line = substr($line, 0, $commentHash);
}
if ($line) {
return call_user_func($lineParser, $line);
}
return null;
}, $lines),
function ($pattern) {
return $pattern !== null;
}
);
}
/**
* Generates a set of exclude patterns for filter() from gitignore rules
*
* @param array $rules A list of exclude rules in gitignore syntax
*
* @return array Exclude patterns
*/
protected function generatePatterns($rules)
{
$patterns = array();
foreach ($rules as $rule) {
$patterns[] = $this->generatePattern($rule);
}
return $patterns;
}
/**
* Generates an exclude pattern for filter() from a gitignore rule
*
* @param string $rule An exclude rule in gitignore syntax
*
* @return array An exclude pattern
*/
protected function generatePattern($rule)
{
$negate = false;
$pattern = '#';
if (strlen($rule) && $rule[0] === '!') {
$negate = true;
$rule = substr($rule, 1);
}
if (strlen($rule) && $rule[0] === '/') {
$pattern .= '^/';
$rule = substr($rule, 1);
} elseif (false === strpos($rule, '/') || strlen($rule) - 1 === strpos($rule, '/')) {
$pattern .= '/';
}
$pattern .= substr(Finder\Glob::toRegex($rule), 2, -2);
return array($pattern . '#', $negate, false);
}
}
| minhnguyen-balance/oro_platform | vendor/composer/composer/src/Composer/Package/Archiver/BaseExcludeFilter.php | PHP | mit | 3,939 |
function dec(target, name, descriptor) {
assert(target);
assert.equal(typeof name, "string");
assert.equal(typeof descriptor, "object");
target.decoratedProps = (target.decoratedProps || []).concat([name]);
let value = descriptor.value;
Object.assign(descriptor, {
enumerable: name.indexOf("enum") !== -1,
configurable: name.indexOf("conf") !== -1,
writable: name.indexOf("write") !== -1,
value: function(...args) {
return "__" + value.apply(this, args) + "__";
},
});
}
const inst = {
@dec
enumconfwrite(){
return 1;
},
@dec
enumconf(){
return 2;
},
@dec
enumwrite(){
return 3;
},
@dec
enum(){
return 4;
},
@dec
confwrite(){
return 5;
},
@dec
conf(){
return 6;
},
@dec
write(){
return 7;
},
@dec
_(){
return 8;
},
}
assert(inst.hasOwnProperty('decoratedProps'));
assert.deepEqual(inst.decoratedProps, [
"enumconfwrite",
"enumconf",
"enumwrite",
"enum",
"confwrite",
"conf",
"write",
"_",
]);
const descs = Object.getOwnPropertyDescriptors(inst);
assert(descs.enumconfwrite.enumerable);
assert(descs.enumconfwrite.writable);
assert(descs.enumconfwrite.configurable);
assert.equal(inst.enumconfwrite(), "__1__");
assert(descs.enumconf.enumerable);
assert.equal(descs.enumconf.writable, false);
assert(descs.enumconf.configurable);
assert.equal(inst.enumconf(), "__2__");
assert(descs.enumwrite.enumerable);
assert(descs.enumwrite.writable);
assert.equal(descs.enumwrite.configurable, false);
assert.equal(inst.enumwrite(), "__3__");
assert(descs.enum.enumerable);
assert.equal(descs.enum.writable, false);
assert.equal(descs.enum.configurable, false);
assert.equal(inst.enum(), "__4__");
assert.equal(descs.confwrite.enumerable, false);
assert(descs.confwrite.writable);
assert(descs.confwrite.configurable);
assert.equal(inst.confwrite(), "__5__");
assert.equal(descs.conf.enumerable, false);
assert.equal(descs.conf.writable, false);
assert(descs.conf.configurable);
assert.equal(inst.conf(), "__6__");
assert.equal(descs.write.enumerable, false);
assert(descs.write.writable);
assert.equal(descs.write.configurable, false);
assert.equal(inst.write(), "__7__");
assert.equal(descs._.enumerable, false);
assert.equal(descs._.writable, false);
assert.equal(descs._.configurable, false);
assert.equal(inst._(), "__8__");
| ccschneidr/babel | packages/babel-plugin-transform-decorators/test/fixtures/object-methods/mutate-descriptor/exec.js | JavaScript | mit | 2,375 |
import chainer
from chainer import backend
from chainer import utils
def sign(x):
"""Elementwise sign function.
For a given input :math:`x`, this function returns :math:`sgn(x)`
defined as
.. math::
sgn(x) = \\left \\{ \\begin{array}{cc}
-1 & {\\rm if~x < 0} \\\\
0 & {\\rm if~x = 0} \\\\
1 & {\\rm if~x > 0} \\\\
\\end{array} \\right.
.. note::
The gradient of this function is ``None`` everywhere and therefore
unchains the computational graph.
Args:
x (:class:`~chainer.Variable` or :ref:`ndarray`):
Input variable for which the sign is computed.
Returns:
~chainer.Variable: Output variable.
"""
if isinstance(x, chainer.variable.Variable):
x = x.array
xp = backend.get_array_module(x)
return chainer.as_variable(utils.force_array(xp.sign(x)))
| okuta/chainer | chainer/functions/math/sign.py | Python | mit | 893 |
require "acts-as-taggable-on"
require "calagator/tag_model_extensions"
ActsAsTaggableOn::Tag.send :include, Calagator::TagModelExtensions
| kerrizor/calagator | config/initializers/load_tag_model_extensions.rb | Ruby | mit | 138 |
/*
Language: Lisp
Description: Generic lisp syntax
Author: Vasily Polovnyov <vast@whiteants.net>
Category: lisp
*/
function lisp(hljs) {
var LISP_IDENT_RE = '[a-zA-Z_\\-+\\*\\/<=>&#][a-zA-Z0-9_\\-+*\\/<=>&#!]*';
var MEC_RE = '\\|[^]*?\\|';
var LISP_SIMPLE_NUMBER_RE = '(-|\\+)?\\d+(\\.\\d+|\\/\\d+)?((d|e|f|l|s|D|E|F|L|S)(\\+|-)?\\d+)?';
var LITERAL = {
className: 'literal',
begin: '\\b(t{1}|nil)\\b'
};
var NUMBER = {
className: 'number',
variants: [
{begin: LISP_SIMPLE_NUMBER_RE, relevance: 0},
{begin: '#(b|B)[0-1]+(/[0-1]+)?'},
{begin: '#(o|O)[0-7]+(/[0-7]+)?'},
{begin: '#(x|X)[0-9a-fA-F]+(/[0-9a-fA-F]+)?'},
{begin: '#(c|C)\\(' + LISP_SIMPLE_NUMBER_RE + ' +' + LISP_SIMPLE_NUMBER_RE, end: '\\)'}
]
};
var STRING = hljs.inherit(hljs.QUOTE_STRING_MODE, {illegal: null});
var COMMENT = hljs.COMMENT(
';', '$',
{
relevance: 0
}
);
var VARIABLE = {
begin: '\\*', end: '\\*'
};
var KEYWORD = {
className: 'symbol',
begin: '[:&]' + LISP_IDENT_RE
};
var IDENT = {
begin: LISP_IDENT_RE,
relevance: 0
};
var MEC = {
begin: MEC_RE
};
var QUOTED_LIST = {
begin: '\\(', end: '\\)',
contains: ['self', LITERAL, STRING, NUMBER, IDENT]
};
var QUOTED = {
contains: [NUMBER, STRING, VARIABLE, KEYWORD, QUOTED_LIST, IDENT],
variants: [
{
begin: '[\'`]\\(', end: '\\)'
},
{
begin: '\\(quote ', end: '\\)',
keywords: {name: 'quote'}
},
{
begin: '\'' + MEC_RE
}
]
};
var QUOTED_ATOM = {
variants: [
{begin: '\'' + LISP_IDENT_RE},
{begin: '#\'' + LISP_IDENT_RE + '(::' + LISP_IDENT_RE + ')*'}
]
};
var LIST = {
begin: '\\(\\s*', end: '\\)'
};
var BODY = {
endsWithParent: true,
relevance: 0
};
LIST.contains = [
{
className: 'name',
variants: [
{
begin: LISP_IDENT_RE,
relevance: 0,
},
{begin: MEC_RE}
]
},
BODY
];
BODY.contains = [QUOTED, QUOTED_ATOM, LIST, LITERAL, NUMBER, STRING, COMMENT, VARIABLE, KEYWORD, MEC, IDENT];
return {
name: 'Lisp',
illegal: /\S/,
contains: [
NUMBER,
hljs.SHEBANG(),
LITERAL,
STRING,
COMMENT,
QUOTED,
QUOTED_ATOM,
LIST,
IDENT
]
};
}
module.exports = lisp;
| ealbertos/dotfiles | vscode.symlink/extensions/bierner.markdown-preview-github-styles-0.2.0/node_modules/highlight.js/lib/languages/lisp.js | JavaScript | mit | 2,398 |
define(
//begin v1.x content
{
"field-quarter-short-relative+0": "detta kv.",
"field-quarter-short-relative+1": "nästa kv.",
"field-tue-relative+-1": "tisdag förra veckan",
"field-year": "år",
"field-wed-relative+0": "onsdag denna vecka",
"field-wed-relative+1": "onsdag nästa vecka",
"field-minute": "minut",
"field-month-narrow-relative+-1": "förra mån.",
"field-tue-narrow-relative+0": "denna tis.",
"field-tue-narrow-relative+1": "nästa tis.",
"field-thu-short-relative+0": "tors. denna vecka",
"field-day-short-relative+-1": "i går",
"field-thu-short-relative+1": "tors. nästa vecka",
"field-day-relative+0": "i dag",
"field-day-short-relative+-2": "i förrgår",
"field-day-relative+1": "i morgon",
"field-week-narrow-relative+0": "denna v.",
"field-day-relative+2": "i övermorgon",
"field-week-narrow-relative+1": "nästa v.",
"field-wed-narrow-relative+-1": "förra ons.",
"field-year-narrow": "år",
"field-era-short": "era",
"field-year-narrow-relative+0": "i år",
"field-tue-relative+0": "tisdag denna vecka",
"field-year-narrow-relative+1": "nästa år",
"field-tue-relative+1": "tisdag nästa vecka",
"field-weekdayOfMonth": "veckodag i månad",
"field-second-short": "sek",
"field-weekdayOfMonth-narrow": "veckodag i mån.",
"field-week-relative+0": "denna vecka",
"field-month-relative+0": "denna månad",
"field-week-relative+1": "nästa vecka",
"field-month-relative+1": "nästa månad",
"field-sun-narrow-relative+0": "denna sön.",
"field-mon-short-relative+0": "mån. denna vecka",
"field-sun-narrow-relative+1": "nästa sön.",
"field-mon-short-relative+1": "mån. nästa vecka",
"field-second-relative+0": "nu",
"field-weekOfMonth": "vecka i månaden",
"field-month-short": "m",
"field-day": "dag",
"field-dayOfYear-short": "dag under året",
"field-year-relative+-1": "i fjol",
"field-sat-short-relative+-1": "lör. förra veckan",
"field-hour-relative+0": "denna timme",
"field-second-short-relative+0": "nu",
"field-wed-relative+-1": "onsdag förra veckan",
"field-sat-narrow-relative+-1": "förra lör.",
"field-second": "sekund",
"field-hour-short-relative+0": "denna timme",
"field-quarter": "kvartal",
"field-week-short": "v",
"field-day-narrow-relative+0": "idag",
"field-day-narrow-relative+1": "imorgon",
"field-day-narrow-relative+2": "i övermorgon",
"field-tue-short-relative+0": "tis. denna vecka",
"field-tue-short-relative+1": "tis. nästa vecka",
"field-month-short-relative+-1": "förra mån.",
"field-mon-relative+-1": "måndag förra veckan",
"field-month": "månad",
"field-day-narrow": "dag",
"field-minute-short": "min",
"field-dayperiod": "fm/em",
"field-sat-short-relative+0": "lör. denna vecka",
"field-sat-short-relative+1": "lör. nästa vecka",
"field-second-narrow": "s",
"field-mon-relative+0": "måndag denna vecka",
"field-mon-relative+1": "måndag nästa vecka",
"field-day-narrow-relative+-1": "igår",
"field-year-short": "år",
"field-day-narrow-relative+-2": "i förrgår",
"field-quarter-relative+-1": "förra kvartalet",
"field-dayperiod-narrow": "fm/em",
"field-week-narrow-relative+-1": "förra v.",
"field-dayOfYear": "dag under året",
"field-sat-relative+-1": "lördag förra veckan",
"field-hour": "timme",
"field-minute-narrow-relative+0": "denna minut",
"field-month-relative+-1": "förra månaden",
"field-quarter-short": "kv.",
"field-sat-narrow-relative+0": "denna lör.",
"field-fri-relative+0": "fredag denna vecka",
"field-sat-narrow-relative+1": "nästa lör.",
"field-fri-relative+1": "fredag nästa vecka",
"field-month-narrow-relative+0": "denna mån.",
"field-month-narrow-relative+1": "nästa mån.",
"field-sun-short-relative+0": "sön. denna vecka",
"field-sun-short-relative+1": "sön. nästa vecka",
"field-week-relative+-1": "förra veckan",
"field-quarter-short-relative+-1": "förra kv.",
"field-minute-short-relative+0": "denna minut",
"field-quarter-relative+0": "detta kvartal",
"field-minute-relative+0": "denna minut",
"field-quarter-relative+1": "nästa kvartal",
"field-wed-short-relative+-1": "ons. förra veckan",
"field-thu-short-relative+-1": "tors. förra veckan",
"field-year-narrow-relative+-1": "i fjol",
"field-thu-narrow-relative+-1": "förra tors.",
"field-tue-narrow-relative+-1": "förra tis.",
"field-weekOfMonth-short": "vk. i mån.",
"field-wed-short-relative+0": "ons. denna vecka",
"field-wed-short-relative+1": "ons. nästa vecka",
"field-sun-relative+-1": "söndag förra veckan",
"field-second-narrow-relative+0": "nu",
"field-weekday": "veckodag",
"field-day-short-relative+0": "i dag",
"field-quarter-narrow-relative+0": "detta kv.",
"field-sat-relative+0": "lördag denna vecka",
"field-day-short-relative+1": "i morgon",
"field-quarter-narrow-relative+1": "nästa kv.",
"field-sat-relative+1": "lördag nästa vecka",
"field-day-short-relative+2": "i övermorgon",
"field-week-short-relative+0": "denna v.",
"field-week-short-relative+1": "nästa v.",
"field-dayOfYear-narrow": "dag under året",
"field-month-short-relative+0": "denna mån.",
"field-month-short-relative+1": "nästa mån.",
"field-weekdayOfMonth-short": "veckodag i mån.",
"field-zone-narrow": "tidszon",
"field-thu-narrow-relative+0": "denna tors.",
"field-thu-narrow-relative+1": "nästa tors.",
"field-sun-narrow-relative+-1": "förra sön.",
"field-mon-short-relative+-1": "mån. förra veckan",
"field-thu-relative+0": "torsdag denna vecka",
"field-thu-relative+1": "torsdag nästa vecka",
"field-fri-short-relative+-1": "fre. förra veckan",
"field-thu-relative+-1": "torsdag förra veckan",
"field-week": "vecka",
"field-wed-narrow-relative+0": "denna ons.",
"field-wed-narrow-relative+1": "nästa ons.",
"field-quarter-narrow-relative+-1": "förra kv.",
"field-year-short-relative+0": "i år",
"field-dayperiod-short": "fm/em",
"field-year-short-relative+1": "nästa år",
"field-fri-short-relative+0": "fre. denna vecka",
"field-fri-short-relative+1": "fre. nästa vecka",
"field-week-short-relative+-1": "förra v.",
"field-hour-narrow-relative+0": "denna timme",
"field-hour-short": "tim",
"field-zone-short": "tidszon",
"field-month-narrow": "mån",
"field-hour-narrow": "h",
"field-fri-narrow-relative+-1": "förra fre.",
"field-year-relative+0": "i år",
"field-year-relative+1": "nästa år",
"field-era-narrow": "era",
"field-fri-relative+-1": "fredag förra veckan",
"field-tue-short-relative+-1": "tis. förra veckan",
"field-minute-narrow": "m",
"field-year-short-relative+-1": "i fjol",
"field-zone": "tidszon",
"field-weekOfMonth-narrow": "vk.i mån.",
"field-weekday-narrow": "veckodag",
"field-quarter-narrow": "kv.",
"field-sun-short-relative+-1": "sön. förra veckan",
"field-day-relative+-1": "i går",
"field-day-relative+-2": "i förrgår",
"field-weekday-short": "veckodag",
"field-sun-relative+0": "söndag denna vecka",
"field-sun-relative+1": "söndag nästa vecka",
"field-day-short": "dag",
"field-week-narrow": "v",
"field-era": "era",
"field-fri-narrow-relative+0": "denna fre.",
"field-fri-narrow-relative+1": "nästa fre."
}
//end v1.x content
); | cdnjs/cdnjs | ajax/libs/dojo/1.17.1/cldr/nls/sv/dangi.js | JavaScript | mit | 7,152 |
/**
* Copyright (c) 2010-2019 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.dsmr.internal.device;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.eclipse.smarthome.io.transport.serial.SerialPortManager;
import org.openhab.binding.dsmr.internal.device.connector.DSMRConnectorErrorEvent;
import org.openhab.binding.dsmr.internal.device.connector.DSMRSerialConnector;
import org.openhab.binding.dsmr.internal.device.connector.DSMRSerialSettings;
import org.openhab.binding.dsmr.internal.device.p1telegram.P1Telegram;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* DSMR Serial device that auto discovers the serial port speed.
*
* @author M. Volaart - Initial contribution
* @author Hilbrand Bouwkamp - New class. Simplified states and contains code specific to discover the serial port
* settings automatically.
*/
@NonNullByDefault
public class DSMRSerialAutoDevice implements DSMRDevice, DSMREventListener {
/**
* Enum to keep track of the internal state of {@link DSMRSerialAutoDevice}.
*/
enum DeviceState {
/**
* Discovers the settings of the serial port.
*/
DISCOVER_SETTINGS,
/**
* Device is receiving telegram data from the serial port.
*/
NORMAL,
/**
* Communication with serial port isn't working.
*/
ERROR
}
/**
* When switching baudrate ignore any errors received with the given time frame. Switching baudrate causes errors
* and should not be interpreted as reading errors.
*/
private static final long SWITCHING_BAUDRATE_TIMEOUT_NANOS = TimeUnit.SECONDS.toNanos(5);
/**
* This factor is multiplied with the {@link #baudrateSwitchTimeoutSeconds} and used as the duration the discovery
* of the baudrate may take.
*/
private static final int DISCOVER_TIMEOUT_FACTOR = 4;
/*
* Februari 2017
* Due to the Dutch Smart Meter program where every residence is provided
* a smart for free and the smart meters are DSMR V4 or higher
* we assume the majority of meters communicate with HIGH_SPEED_SETTINGS
* For older meters this means initializing is taking probably 1 minute
*/
private static final DSMRSerialSettings DEFAULT_PORT_SETTINGS = DSMRSerialSettings.HIGH_SPEED_SETTINGS;
private final Logger logger = LoggerFactory.getLogger(DSMRSerialAutoDevice.class);
/**
* DSMR Connector to the serial port
*/
private final DSMRSerialConnector dsmrConnector;
private final ScheduledExecutorService scheduler;
private final DSMRTelegramListener telegramListener;
/**
* Time in seconds in which period valid data is expected during discovery. If exceeded without success the baudrate
* is switched
*/
private final int baudrateSwitchTimeoutSeconds;
/**
* Serial port connection settings
*/
private DSMRSerialSettings portSettings = DEFAULT_PORT_SETTINGS;
/**
* Keeps track of the state this instance is in.
*/
private DeviceState state = DeviceState.NORMAL;
/**
* Timer for handling discovery of a single setting.
*/
private @Nullable ScheduledFuture<?> halfTimeTimer;
/**
* Timer for handling end of discovery.
*/
private @Nullable ScheduledFuture<?> endTimeTimer;
/**
* The listener of the class handling the connector events
*/
private DSMREventListener parentListener;
/**
* Time in nanos the last time the baudrate was switched. This is used during discovery ignore errors retrieved
* after switching baudrate for the period set in {@link #SWITCHING_BAUDRATE_TIMEOUT_NANOS}.
*/
private long lastSwitchedBaudrateNanos;
/**
* Creates a new {@link DSMRSerialAutoDevice}
*
* @param serialPortManager the manager to get a new serial port connecting from
* @param serialPortName the port name (e.g. /dev/ttyUSB0 or COM1)
* @param listener the parent {@link DSMREventListener}
* @param scheduler the scheduler to use with the baudrate switching timers
* @param baudrateSwitchTimeoutSeconds timeout period for when to try other baudrate settings and end the discovery
* of the baudrate
*/
public DSMRSerialAutoDevice(SerialPortManager serialPortManager, String serialPortName, DSMREventListener listener,
ScheduledExecutorService scheduler, int baudrateSwitchTimeoutSeconds) {
this.parentListener = listener;
this.scheduler = scheduler;
this.baudrateSwitchTimeoutSeconds = baudrateSwitchTimeoutSeconds;
telegramListener = new DSMRTelegramListener(listener);
dsmrConnector = new DSMRSerialConnector(serialPortManager, serialPortName, telegramListener);
logger.debug("Initialized port '{}'", serialPortName);
}
@Override
public void start() {
stopDiscover(DeviceState.DISCOVER_SETTINGS);
portSettings = DEFAULT_PORT_SETTINGS;
telegramListener.setDsmrEventListener(this);
dsmrConnector.open(portSettings);
restartHalfTimer();
endTimeTimer = scheduler.schedule(this::endTimeScheduledCall,
baudrateSwitchTimeoutSeconds * DISCOVER_TIMEOUT_FACTOR, TimeUnit.SECONDS);
}
@Override
public void restart() {
if (state == DeviceState.ERROR) {
stop();
start();
} else if (state == DeviceState.NORMAL) {
dsmrConnector.restart(portSettings);
}
}
@Override
public synchronized void stop() {
dsmrConnector.close();
stopDiscover(state);
logger.trace("stopped with state:{}", state);
}
/**
* Handle if telegrams are received.
*
* @param telegram the details of the received telegram
*/
@Override
public void handleTelegramReceived(P1Telegram telegram) {
if (!telegram.getCosemObjects().isEmpty()) {
stopDiscover(DeviceState.NORMAL);
parentListener.handleTelegramReceived(telegram);
logger.info("Start receiving telegrams on port {} with settings: {}", dsmrConnector.getPortName(),
portSettings);
}
}
/**
* Event handler for DSMR Port events.
*
* @param portEvent {@link DSMRConnectorErrorEvent} to handle
*/
@Override
public void handleErrorEvent(DSMRConnectorErrorEvent portEvent) {
logger.trace("Received portEvent {}", portEvent.getEventDetails());
if (portEvent == DSMRConnectorErrorEvent.READ_ERROR) {
switchBaudrate();
} else {
logger.debug("Error during discovery of port settings: {}, current state:{}.", portEvent.getEventDetails(),
state);
stopDiscover(DeviceState.ERROR);
parentListener.handleErrorEvent(portEvent);
}
}
/**
* @param lenientMode the lenientMode to set
*/
@Override
public void setLenientMode(boolean lenientMode) {
telegramListener.setLenientMode(lenientMode);
}
/**
* @return Returns the state of the instance. Used for testing only.
*/
DeviceState getState() {
return state;
}
/**
* Switches the baudrate on the serial port.
*/
private void switchBaudrate() {
if (lastSwitchedBaudrateNanos + SWITCHING_BAUDRATE_TIMEOUT_NANOS > System.nanoTime()) {
// Ignore switching baudrate if this is called within the timeout after a previous switch.
return;
}
lastSwitchedBaudrateNanos = System.nanoTime();
if (state == DeviceState.DISCOVER_SETTINGS) {
restartHalfTimer();
logger.debug(
"Discover port settings is running for half time now and still nothing discovered, switching baudrate and retrying");
portSettings = portSettings == DSMRSerialSettings.HIGH_SPEED_SETTINGS
? DSMRSerialSettings.LOW_SPEED_SETTINGS
: DSMRSerialSettings.HIGH_SPEED_SETTINGS;
dsmrConnector.setSerialPortParams(portSettings);
}
}
/**
* Stops the discovery process as triggered by the end timer. It will only act if the discovery process was still
* running.
*/
private void endTimeScheduledCall() {
if (state == DeviceState.DISCOVER_SETTINGS) {
stopDiscover(DeviceState.ERROR);
parentListener.handleErrorEvent(DSMRConnectorErrorEvent.DONT_EXISTS);
}
}
/**
* Stops the discovery of port speed process and sets the state with which it should be stopped.
*
* @param state the state with which the process was stopped.
*/
private void stopDiscover(DeviceState state) {
telegramListener.setDsmrEventListener(parentListener);
logger.debug("Stop discovery of port settings.");
if (halfTimeTimer != null) {
halfTimeTimer.cancel(true);
halfTimeTimer = null;
}
if (endTimeTimer != null) {
endTimeTimer.cancel(true);
endTimeTimer = null;
}
this.state = state;
}
/**
* Method to (re)start the switching baudrate timer.
*/
private void restartHalfTimer() {
if (halfTimeTimer != null) {
halfTimeTimer.cancel(true);
}
halfTimeTimer = scheduler.schedule(this::switchBaudrate, baudrateSwitchTimeoutSeconds, TimeUnit.SECONDS);
}
}
| afuechsel/openhab2 | addons/binding/org.openhab.binding.dsmr/src/main/java/org/openhab/binding/dsmr/internal/device/DSMRSerialAutoDevice.java | Java | epl-1.0 | 9,975 |
/**
* Copyright (c) 2010-2018 by the respective copyright holders.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.yamahareceiver.internal.state;
import static org.openhab.binding.yamahareceiver.YamahaReceiverBindingConstants.VALUE_EMPTY;
/**
* The state of a specific zone of a Yamaha receiver.
*
* @author David Graeff <david.graeff@web.de>
*
*/
public class ZoneControlState {
public boolean power = false;
// User visible name of the input channel for the current zone
public String inputName = VALUE_EMPTY;
// The ID of the input channel that is used as xml tags (for example NET_RADIO, HDMI_1).
// This may differ from what the AVR returns in Input/Input_Sel ("NET RADIO", "HDMI1")
public String inputID = VALUE_EMPTY;
public String surroundProgram = VALUE_EMPTY;
public float volumeDB = 0.0f; // volume in dB
public boolean mute = false;
public int dialogueLevel = 0;
}
| johannrichard/openhab2-addons | addons/binding/org.openhab.binding.yamahareceiver/src/main/java/org/openhab/binding/yamahareceiver/internal/state/ZoneControlState.java | Java | epl-1.0 | 1,158 |
/**
* Copyright (c) 2010-2018 by the respective copyright holders.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.nikohomecontrol.internal.protocol;
/**
* Class {@link NhcMessageBase} used as base class for output from gson for cmd or event feedback from Niko Home
* Control. This class only contains the common base fields required for the deserializer
* {@link NikoHomeControlMessageDeserializer} to select the specific formats implemented in {@link NhcMessageMap},
* {@link NhcMessageListMap}, {@link NhcMessageCmd}.
* <p>
*
* @author Mark Herwege - Initial Contribution
*/
abstract class NhcMessageBase {
private String cmd;
private String event;
String getCmd() {
return this.cmd;
}
void setCmd(String cmd) {
this.cmd = cmd;
}
String getEvent() {
return this.event;
}
void setEvent(String event) {
this.event = event;
}
}
| aogorek/openhab2-addons | addons/binding/org.openhab.binding.nikohomecontrol/src/main/java/org/openhab/binding/nikohomecontrol/internal/protocol/NhcMessageBase.java | Java | epl-1.0 | 1,148 |
/*
* Copyright (C) 2012-2013 JadeCore <http://www.pandashan.com/>
* Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "GameObjectAI.h"
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "heart_of_fear.h"
// Zorlok - 62980
class boss_unsok : public CreatureScript
{
public:
boss_unsok() : CreatureScript("boss_unsok") { }
struct boss_unsokAI : public BossAI
{
boss_unsokAI(Creature* creature) : BossAI(creature, DATA_UNSOK)
{
pInstance = creature->GetInstanceScript();
}
InstanceScript* pInstance;
EventMap events;
};
CreatureAI* GetAI(Creature* creature) const
{
return new boss_unsokAI(creature);
}
};
void AddSC_boss_unsok()
{
new boss_unsok();
}
| DeActiveDev/Core | src/server/scripts/Pandaria/HeartOfFear/boss_unsok.cpp | C++ | gpl-2.0 | 1,576 |
// Copyright 2015 Dolphin Emulator Project
// Licensed under GPLv2+
// Refer to the license.txt file included.
#include "Core/HW/SI/SI_DeviceKeyboard.h"
#include <cstring>
#include "Common/ChunkFile.h"
#include "Common/CommonTypes.h"
#include "Common/Logging/Log.h"
#include "Common/Swap.h"
#include "Core/HW/GCKeyboard.h"
#include "InputCommon/KeyboardStatus.h"
namespace SerialInterface
{
// --- GameCube keyboard ---
CSIDevice_Keyboard::CSIDevice_Keyboard(SIDevices device, int device_number)
: ISIDevice(device, device_number)
{
}
int CSIDevice_Keyboard::RunBuffer(u8* buffer, int request_length)
{
// For debug logging only
ISIDevice::RunBuffer(buffer, request_length);
// Read the command
const auto command = static_cast<EBufferCommands>(buffer[0]);
// Handle it
switch (command)
{
case CMD_RESET:
case CMD_ID:
{
u32 id = Common::swap32(SI_GC_KEYBOARD);
std::memcpy(buffer, &id, sizeof(id));
return sizeof(id);
}
case CMD_DIRECT:
{
INFO_LOG_FMT(SERIALINTERFACE, "Keyboard - Direct (Request Length: {})", request_length);
u32 high, low;
GetData(high, low);
for (int i = 0; i < 4; i++)
{
buffer[i + 0] = (high >> (24 - (i * 8))) & 0xff;
buffer[i + 4] = (low >> (24 - (i * 8))) & 0xff;
}
return sizeof(high) + sizeof(low);
}
default:
{
ERROR_LOG_FMT(SERIALINTERFACE, "Unknown SI command ({:#x})", command);
}
break;
}
return 0;
}
KeyboardStatus CSIDevice_Keyboard::GetKeyboardStatus() const
{
return Keyboard::GetStatus(m_device_number);
}
bool CSIDevice_Keyboard::GetData(u32& hi, u32& low)
{
KeyboardStatus key_status = GetKeyboardStatus();
u8 key[3] = {0x00, 0x00, 0x00};
MapKeys(key_status, key);
u8 checksum = key[0] ^ key[1] ^ key[2] ^ m_counter;
hi = m_counter << 24;
low = key[0] << 24 | key[1] << 16 | key[2] << 8 | checksum;
return true;
}
void CSIDevice_Keyboard::SendCommand(u32 command, u8 poll)
{
UCommand keyboard_command(command);
switch (keyboard_command.command)
{
case 0x00:
break;
case CMD_POLL:
{
m_counter++;
m_counter &= 15;
}
break;
default:
{
ERROR_LOG_FMT(SERIALINTERFACE, "Unknown direct command ({:#x})", command);
}
break;
}
}
void CSIDevice_Keyboard::DoState(PointerWrap& p)
{
p.Do(m_counter);
}
void CSIDevice_Keyboard::MapKeys(const KeyboardStatus& key_status, u8* key)
{
u8 keys_held = 0;
const u8 MAX_KEYS_HELD = 3;
if (key_status.key0x & KEYMASK_HOME)
{
key[keys_held++] = KEY_HOME;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key0x & KEYMASK_END)
{
key[keys_held++] = KEY_END;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key0x & KEYMASK_PGUP)
{
key[keys_held++] = KEY_PGUP;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key0x & KEYMASK_PGDN)
{
key[keys_held++] = KEY_PGDN;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key0x & KEYMASK_SCROLLLOCK)
{
key[keys_held++] = KEY_SCROLLLOCK;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key0x & KEYMASK_A)
{
key[keys_held++] = KEY_A;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key0x & KEYMASK_B)
{
key[keys_held++] = KEY_B;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key0x & KEYMASK_C)
{
key[keys_held++] = KEY_C;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key0x & KEYMASK_D)
{
key[keys_held++] = KEY_D;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key0x & KEYMASK_E)
{
key[keys_held++] = KEY_E;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key0x & KEYMASK_F)
{
key[keys_held++] = KEY_F;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key0x & KEYMASK_G)
{
key[keys_held++] = KEY_G;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key0x & KEYMASK_H)
{
key[keys_held++] = KEY_H;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key0x & KEYMASK_I)
{
key[keys_held++] = KEY_I;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key0x & KEYMASK_J)
{
key[keys_held++] = KEY_J;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key0x & KEYMASK_K)
{
key[keys_held++] = KEY_K;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key1x & KEYMASK_L)
{
key[keys_held++] = KEY_L;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key1x & KEYMASK_M)
{
key[keys_held++] = KEY_M;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key1x & KEYMASK_N)
{
key[keys_held++] = KEY_N;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key1x & KEYMASK_O)
{
key[keys_held++] = KEY_O;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key1x & KEYMASK_P)
{
key[keys_held++] = KEY_P;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key1x & KEYMASK_Q)
{
key[keys_held++] = KEY_Q;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key1x & KEYMASK_R)
{
key[keys_held++] = KEY_R;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key1x & KEYMASK_S)
{
key[keys_held++] = KEY_S;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key1x & KEYMASK_T)
{
key[keys_held++] = KEY_T;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key1x & KEYMASK_U)
{
key[keys_held++] = KEY_U;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key1x & KEYMASK_V)
{
key[keys_held++] = KEY_V;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key1x & KEYMASK_W)
{
key[keys_held++] = KEY_W;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key1x & KEYMASK_X)
{
key[keys_held++] = KEY_X;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key1x & KEYMASK_Y)
{
key[keys_held++] = KEY_Y;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key1x & KEYMASK_Z)
{
key[keys_held++] = KEY_Z;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key1x & KEYMASK_1)
{
key[keys_held++] = KEY_1;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key2x & KEYMASK_2)
{
key[keys_held++] = KEY_2;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key2x & KEYMASK_3)
{
key[keys_held++] = KEY_3;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key2x & KEYMASK_4)
{
key[keys_held++] = KEY_4;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key2x & KEYMASK_5)
{
key[keys_held++] = KEY_5;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key2x & KEYMASK_6)
{
key[keys_held++] = KEY_6;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key2x & KEYMASK_7)
{
key[keys_held++] = KEY_7;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key2x & KEYMASK_8)
{
key[keys_held++] = KEY_8;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key2x & KEYMASK_9)
{
key[keys_held++] = KEY_9;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key2x & KEYMASK_0)
{
key[keys_held++] = KEY_0;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key2x & KEYMASK_MINUS)
{
key[keys_held++] = KEY_MINUS;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key2x & KEYMASK_PLUS)
{
key[keys_held++] = KEY_PLUS;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key2x & KEYMASK_PRINTSCR)
{
key[keys_held++] = KEY_PRINTSCR;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key2x & KEYMASK_BRACE_OPEN)
{
key[keys_held++] = KEY_BRACE_OPEN;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key2x & KEYMASK_BRACE_CLOSE)
{
key[keys_held++] = KEY_BRACE_CLOSE;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key2x & KEYMASK_COLON)
{
key[keys_held++] = KEY_COLON;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key2x & KEYMASK_QUOTE)
{
key[keys_held++] = KEY_QUOTE;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key3x & KEYMASK_HASH)
{
key[keys_held++] = KEY_HASH;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key3x & KEYMASK_COMMA)
{
key[keys_held++] = KEY_COMMA;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key3x & KEYMASK_PERIOD)
{
key[keys_held++] = KEY_PERIOD;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key3x & KEYMASK_QUESTIONMARK)
{
key[keys_held++] = KEY_QUESTIONMARK;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key3x & KEYMASK_INTERNATIONAL1)
{
key[keys_held++] = KEY_INTERNATIONAL1;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key3x & KEYMASK_F1)
{
key[keys_held++] = KEY_F1;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key3x & KEYMASK_F2)
{
key[keys_held++] = KEY_F2;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key3x & KEYMASK_F3)
{
key[keys_held++] = KEY_F3;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key3x & KEYMASK_F4)
{
key[keys_held++] = KEY_F4;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key3x & KEYMASK_F5)
{
key[keys_held++] = KEY_F5;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key3x & KEYMASK_F6)
{
key[keys_held++] = KEY_F6;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key3x & KEYMASK_F7)
{
key[keys_held++] = KEY_F7;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key3x & KEYMASK_F8)
{
key[keys_held++] = KEY_F8;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key3x & KEYMASK_F9)
{
key[keys_held++] = KEY_F9;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key3x & KEYMASK_F10)
{
key[keys_held++] = KEY_F10;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key3x & KEYMASK_F11)
{
key[keys_held++] = KEY_F11;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key4x & KEYMASK_F12)
{
key[keys_held++] = KEY_F12;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key4x & KEYMASK_ESC)
{
key[keys_held++] = KEY_ESC;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key4x & KEYMASK_INSERT)
{
key[keys_held++] = KEY_INSERT;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key4x & KEYMASK_DELETE)
{
key[keys_held++] = KEY_DELETE;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key4x & KEYMASK_TILDE)
{
key[keys_held++] = KEY_TILDE;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key4x & KEYMASK_BACKSPACE)
{
key[keys_held++] = KEY_BACKSPACE;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key4x & KEYMASK_TAB)
{
key[keys_held++] = KEY_TAB;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key4x & KEYMASK_CAPSLOCK)
{
key[keys_held++] = KEY_CAPSLOCK;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key4x & KEYMASK_LEFTSHIFT)
{
key[keys_held++] = KEY_LEFTSHIFT;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key4x & KEYMASK_RIGHTSHIFT)
{
key[keys_held++] = KEY_RIGHTSHIFT;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key4x & KEYMASK_LEFTCONTROL)
{
key[keys_held++] = KEY_LEFTCONTROL;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key4x & KEYMASK_RIGHTALT)
{
key[keys_held++] = KEY_RIGHTALT;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key4x & KEYMASK_LEFTWINDOWS)
{
key[keys_held++] = KEY_LEFTWINDOWS;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key4x & KEYMASK_SPACE)
{
key[keys_held++] = KEY_SPACE;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key4x & KEYMASK_RIGHTWINDOWS)
{
key[keys_held++] = KEY_RIGHTWINDOWS;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key4x & KEYMASK_MENU)
{
key[keys_held++] = KEY_MENU;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key5x & KEYMASK_LEFTARROW)
{
key[keys_held++] = KEY_LEFTARROW;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key5x & KEYMASK_DOWNARROW)
{
key[keys_held++] = KEY_DOWNARROW;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key5x & KEYMASK_UPARROW)
{
key[keys_held++] = KEY_UPARROW;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key5x & KEYMASK_RIGHTARROW)
{
key[keys_held++] = KEY_RIGHTARROW;
if (keys_held >= MAX_KEYS_HELD)
return;
}
if (key_status.key5x & KEYMASK_ENTER)
{
key[keys_held++] = KEY_ENTER;
if (keys_held >= MAX_KEYS_HELD)
return;
}
}
} // namespace SerialInterface
| TwitchPlaysPokemon/dolphinWatch | Source/Core/Core/HW/SI/SI_DeviceKeyboard.cpp | C++ | gpl-2.0 | 13,504 |
<?php
if (!get_option('users_can_register')) return;
add_action('login_enqueue_scripts','sfc_register_enqueue_scripts');
function sfc_register_enqueue_scripts() {
wp_enqueue_script('jquery');
}
add_action('sfc_login_new_fb_user', 'sfc_register_redirect');
function sfc_register_redirect() {
wp_redirect(site_url('wp-login.php?action=register', 'login'));
exit;
}
remove_action('login_form','sfc_login_add_login_button');
add_action('login_form','sfc_register_add_login_button');
function sfc_register_add_login_button() {
global $action;
if ($action == 'login') echo '<p><fb:login-button v="2" registration-url="'.site_url('wp-login.php?action=register', 'login').'" scope="email,user_website" onlogin="window.location.reload();" /></p><br />';
}
add_action('register_form','sfc_register_form');
function sfc_register_form() {
add_action('sfc_async_init', 'sfc_register_form_script');
$fields = json_encode( apply_filters('sfc_register_fields',array(
array('name'=>'name', 'view'=>'prefilled'),
array('name'=>'username', 'description'=>__('Choose a username','sfc'), 'type'=>'text'),
array('name'=>'email'),
array('name'=>'captcha'),
)
) );
?>
<fb:registration
fields='<?php echo $fields; ?>'
redirect-uri="<?php echo apply_filters('sfc_register_redirect', site_url('wp-login.php?action=register', 'login') ); ?>"
width="262"
>
</fb:registration>
<?php
}
function sfc_register_form_script() {
?>
jQuery('#registerform p').hide();
jQuery('#reg_passmail').show();
<?php
}
add_action('register_form','sfc_add_base_js',20);
// catch the signed request
add_action('login_form_register','sfc_register_handle_signed_request');
function sfc_register_handle_signed_request() {
global $wpdb;
$options = get_option('sfc_options');
if (!empty($_POST['signed_request'])) {
list($encoded_sig, $payload) = explode('.', $_POST['signed_request'], 2);
// decode the data
$sig = sfc_base64_url_decode($encoded_sig);
$data = json_decode(sfc_base64_url_decode($payload), true);
if (!isset($data['algorithm']) || strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
return;
}
// check sig
$expected_sig = hash_hmac('sha256', $payload, $options['app_secret'], true);
if ($sig !== $expected_sig) {
return;
}
if (isset($data['registration'])) {
$info = $data['registration'];
if (isset($info['username']) && isset($info['email'])) {
// first check to see if this user already exists in the db
$user_id = $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->users WHERE user_email = %s", $info['email']) );
if ($user_id) {
$fbuid = $data['user_id'];
update_usermeta($user_id, 'fbuid', $fbuid); // connect the account so we don't have to query this again
// redirect to admin and exit
wp_redirect( add_query_arg( array('updated' => 'true'), self_admin_url( 'profile.php' ) ) );
exit;
} else {
// new user, set the registration info
$_POST['user_login'] = $info['username'];
$_POST['user_email'] = $info['email'];
do_action('sfc_register_request',$info);
}
}
}
}
} | tahitinuiarena/site | wp-content/plugins/simple-facebook-connect/sfc-register.php | PHP | gpl-2.0 | 3,192 |
<?php
namespace Illuminate\Queue\Console;
use Exception;
use RuntimeException;
use Illuminate\Queue\IronQueue;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
/**
* @deprecated since version 5.1
*/
class SubscribeCommand extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'queue:subscribe';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Subscribe a URL to an Iron.io push queue';
/**
* The queue meta information from Iron.io.
*
* @var object
*/
protected $meta;
/**
* Execute the console command.
*
* @return void
*
* @throws \RuntimeException
*/
public function fire()
{
$iron = $this->laravel['queue']->connection();
if (!$iron instanceof IronQueue) {
throw new RuntimeException('Iron.io based queue must be default.');
}
$iron->getIron()->updateQueue($this->argument('queue'), $this->getQueueOptions());
$this->line('<info>Queue subscriber added:</info> <comment>'.$this->argument('url').'</comment>');
}
/**
* Get the queue options.
*
* @return array
*/
protected function getQueueOptions()
{
return [
'push_type' => $this->getPushType(), 'subscribers' => $this->getSubscriberList(),
];
}
/**
* Get the push type for the queue.
*
* @return string
*/
protected function getPushType()
{
if ($this->option('type')) {
return $this->option('type');
}
try {
return $this->getQueue()->push_type;
} catch (Exception $e) {
return 'multicast';
}
}
/**
* Get the current subscribers for the queue.
*
* @return array
*/
protected function getSubscriberList()
{
$subscribers = $this->getCurrentSubscribers();
$url = $this->argument('url');
if (!starts_with($url, ['http://', 'https://'])) {
$url = $this->laravel['url']->to($url);
}
$subscribers[] = ['url' => $url];
return $subscribers;
}
/**
* Get the current subscriber list.
*
* @return array
*/
protected function getCurrentSubscribers()
{
try {
return $this->getQueue()->subscribers;
} catch (Exception $e) {
return [];
}
}
/**
* Get the queue information from Iron.io.
*
* @return object
*/
protected function getQueue()
{
if (isset($this->meta)) {
return $this->meta;
}
return $this->meta = $this->laravel['queue']->getIron()->getQueue($this->argument('queue'));
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return [
['queue', InputArgument::REQUIRED, 'The name of Iron.io queue.'],
['url', InputArgument::REQUIRED, 'The URL to be subscribed.'],
];
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return [
['type', null, InputOption::VALUE_OPTIONAL, 'The push type for the queue.'],
];
}
}
| SalocinDotTEN/FindRecycler-AHKL15 | vendor/laravel/framework/src/Illuminate/Queue/Console/SubscribeCommand.php | PHP | gpl-2.0 | 3,476 |
<?php
$lang = array(
#Texts
'text_puke' => "Puke",
'text_nfofor' => "NFO for ",
'text_forbest' => "For best visual result, install the ",
'text_linedraw' => "MS Linedraw",
'text_font' => " font",
'text_stdhead' => "View Nfo"
);
?>
| TTsWeb/U-232-V4 | lang/2/lang_viewnfo.php | PHP | gpl-2.0 | 237 |
/*
* Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
// MAIN.CPP - Entry point for the Architecture Description Language Compiler
#include "adlc.hpp"
//------------------------------Prototypes-------------------------------------
static void usage(ArchDesc& AD); // Print usage message and exit
static char *strip_ext(char *fname); // Strip off name extension
static char *base_plus_suffix(const char* base, const char *suffix);// New concatenated string
static int get_legal_text(FileBuff &fbuf, char **legal_text); // Get pointer to legal text
ArchDesc* globalAD = NULL; // global reference to Architecture Description object
const char* get_basename(const char* filename) {
const char *basename = filename;
const char *cp;
for (cp = basename; *cp; cp++) {
if (*cp == '/') {
basename = cp+1;
}
}
return basename;
}
//------------------------------main-------------------------------------------
int main(int argc, char *argv[])
{
ArchDesc AD; // Architecture Description object
globalAD = &AD;
// ResourceMark mark;
ADLParser *ADL_Parse; // ADL Parser object to parse AD file
// Check for proper arguments
if( argc == 1 ) usage(AD); // No arguments? Then print usage
// Read command line arguments and file names
for( int i = 1; i < argc; i++ ) { // For all arguments
register char *s = argv[i]; // Get option/filename
if( *s++ == '-' ) { // It's a flag? (not a filename)
if( !*s ) { // Stand-alone `-' means stdin
//********** INSERT CODE HERE **********
} else while (*s != '\0') { // While have flags on option
switch (*s++) { // Handle flag
case 'd': // Debug flag
AD._dfa_debug += 1; // Set Debug Flag
break;
case 'g': // Debug ad location flag
AD._adlocation_debug += 1; // Set Debug ad location Flag
break;
case 'o': // No Output Flag
AD._no_output ^= 1; // Toggle no_output flag
break;
case 'q': // Quiet Mode Flag
AD._quiet_mode ^= 1; // Toggle quiet_mode flag
break;
case 'w': // Disable Warnings Flag
AD._disable_warnings ^= 1; // Toggle disable_warnings flag
break;
case 'T': // Option to make DFA as many subroutine calls.
AD._dfa_small += 1; // Set Mode Flag
break;
case 'c': { // Set C++ Output file name
AD._CPP_file._name = s;
const char *base = strip_ext(strdup(s));
AD._CPP_CLONE_file._name = base_plus_suffix(base,"_clone.cpp");
AD._CPP_EXPAND_file._name = base_plus_suffix(base,"_expand.cpp");
AD._CPP_FORMAT_file._name = base_plus_suffix(base,"_format.cpp");
AD._CPP_GEN_file._name = base_plus_suffix(base,"_gen.cpp");
AD._CPP_MISC_file._name = base_plus_suffix(base,"_misc.cpp");
AD._CPP_PEEPHOLE_file._name = base_plus_suffix(base,"_peephole.cpp");
AD._CPP_PIPELINE_file._name = base_plus_suffix(base,"_pipeline.cpp");
s += strlen(s);
break;
}
case 'h': // Set C++ Output file name
AD._HPP_file._name = s; s += strlen(s);
break;
case 'v': // Set C++ Output file name
AD._VM_file._name = s; s += strlen(s);
break;
case 'a': // Set C++ Output file name
AD._DFA_file._name = s;
AD._bug_file._name = s;
s += strlen(s);
break;
case '#': // Special internal debug flag
AD._adl_debug++; // Increment internal debug level
break;
case 's': // Output which instructions are cisc-spillable
AD._cisc_spill_debug = true;
break;
case 'D': // Flag Definition
{
char* flag = s;
s += strlen(s);
char* def = strchr(flag, '=');
if (def == NULL) def = (char*)"1";
else *def++ = '\0';
AD.set_preproc_def(flag, def);
}
break;
case 'U': // Flag Un-Definition
{
char* flag = s;
s += strlen(s);
AD.set_preproc_def(flag, NULL);
}
break;
default: // Unknown option
usage(AD); // So print usage and exit
} // End of switch on options...
} // End of while have options...
} else { // Not an option; must be a filename
AD._ADL_file._name = argv[i]; // Set the input filename
// // Files for storage, based on input file name
const char *base = strip_ext(strdup(argv[i]));
char *temp = base_plus_suffix("dfa_",base);
AD._DFA_file._name = base_plus_suffix(temp,".cpp");
delete temp;
temp = base_plus_suffix("ad_",base);
AD._CPP_file._name = base_plus_suffix(temp,".cpp");
AD._CPP_CLONE_file._name = base_plus_suffix(temp,"_clone.cpp");
AD._CPP_EXPAND_file._name = base_plus_suffix(temp,"_expand.cpp");
AD._CPP_FORMAT_file._name = base_plus_suffix(temp,"_format.cpp");
AD._CPP_GEN_file._name = base_plus_suffix(temp,"_gen.cpp");
AD._CPP_MISC_file._name = base_plus_suffix(temp,"_misc.cpp");
AD._CPP_PEEPHOLE_file._name = base_plus_suffix(temp,"_peephole.cpp");
AD._CPP_PIPELINE_file._name = base_plus_suffix(temp,"_pipeline.cpp");
AD._HPP_file._name = base_plus_suffix(temp,".hpp");
delete temp;
temp = base_plus_suffix("adGlobals_",base);
AD._VM_file._name = base_plus_suffix(temp,".hpp");
delete temp;
temp = base_plus_suffix("bugs_",base);
AD._bug_file._name = base_plus_suffix(temp,".out");
delete temp;
} // End of files vs options...
} // End of while have command line arguments
// Open files used to store the matcher and its components
if (AD.open_files() == 0) return 1; // Open all input/output files
// Build the File Buffer, Parse the input, & Generate Code
FileBuff ADL_Buf(&AD._ADL_file, AD); // Create a file buffer for input file
// Get pointer to legal text at the beginning of AD file.
// It will be used in generated ad files.
char* legal_text;
int legal_sz = get_legal_text(ADL_Buf, &legal_text);
ADL_Parse = new ADLParser(ADL_Buf, AD); // Create a parser to parse the buffer
ADL_Parse->parse(); // Parse buffer & build description lists
if( AD._dfa_debug >= 1 ) { // For higher debug settings, print dump
AD.dump();
}
delete ADL_Parse; // Delete parser
// Verify that the results of the parse are consistent
AD.verify();
// Prepare to generate the result files:
AD.generateMatchLists();
AD.identify_unique_operands();
AD.identify_cisc_spill_instructions();
AD.identify_short_branches();
// Make sure every file starts with a copyright:
AD.addSunCopyright(legal_text, legal_sz, AD._HPP_file._fp); // .hpp
AD.addSunCopyright(legal_text, legal_sz, AD._CPP_file._fp); // .cpp
AD.addSunCopyright(legal_text, legal_sz, AD._CPP_CLONE_file._fp); // .cpp
AD.addSunCopyright(legal_text, legal_sz, AD._CPP_EXPAND_file._fp); // .cpp
AD.addSunCopyright(legal_text, legal_sz, AD._CPP_FORMAT_file._fp); // .cpp
AD.addSunCopyright(legal_text, legal_sz, AD._CPP_GEN_file._fp); // .cpp
AD.addSunCopyright(legal_text, legal_sz, AD._CPP_MISC_file._fp); // .cpp
AD.addSunCopyright(legal_text, legal_sz, AD._CPP_PEEPHOLE_file._fp); // .cpp
AD.addSunCopyright(legal_text, legal_sz, AD._CPP_PIPELINE_file._fp); // .cpp
AD.addSunCopyright(legal_text, legal_sz, AD._VM_file._fp); // .hpp
AD.addSunCopyright(legal_text, legal_sz, AD._DFA_file._fp); // .cpp
// Add include guards for all .hpp files
AD.addIncludeGuardStart(AD._HPP_file, "GENERATED_ADFILES_AD_HPP"); // .hpp
AD.addIncludeGuardStart(AD._VM_file, "GENERATED_ADFILES_ADGLOBALS_HPP"); // .hpp
// Add includes
AD.addInclude(AD._CPP_file, "precompiled.hpp");
AD.addInclude(AD._CPP_file, "adfiles", get_basename(AD._VM_file._name));
AD.addInclude(AD._CPP_file, "adfiles", get_basename(AD._HPP_file._name));
AD.addInclude(AD._CPP_file, "memory/allocation.inline.hpp");
AD.addInclude(AD._CPP_file, "asm/macroAssembler.inline.hpp");
AD.addInclude(AD._CPP_file, "code/compiledIC.hpp");
AD.addInclude(AD._CPP_file, "code/nativeInst.hpp");
AD.addInclude(AD._CPP_file, "code/vmreg.inline.hpp");
AD.addInclude(AD._CPP_file, "gc/shared/collectedHeap.inline.hpp");
AD.addInclude(AD._CPP_file, "oops/compiledICHolder.hpp");
AD.addInclude(AD._CPP_file, "oops/markOop.hpp");
AD.addInclude(AD._CPP_file, "oops/method.hpp");
AD.addInclude(AD._CPP_file, "oops/oop.inline.hpp");
AD.addInclude(AD._CPP_file, "opto/cfgnode.hpp");
AD.addInclude(AD._CPP_file, "opto/intrinsicnode.hpp");
AD.addInclude(AD._CPP_file, "opto/locknode.hpp");
AD.addInclude(AD._CPP_file, "opto/opcodes.hpp");
AD.addInclude(AD._CPP_file, "opto/regalloc.hpp");
AD.addInclude(AD._CPP_file, "opto/regmask.hpp");
AD.addInclude(AD._CPP_file, "opto/runtime.hpp");
AD.addInclude(AD._CPP_file, "runtime/biasedLocking.hpp");
AD.addInclude(AD._CPP_file, "runtime/sharedRuntime.hpp");
AD.addInclude(AD._CPP_file, "runtime/stubRoutines.hpp");
AD.addInclude(AD._CPP_file, "utilities/growableArray.hpp");
AD.addInclude(AD._HPP_file, "memory/allocation.hpp");
AD.addInclude(AD._HPP_file, "code/nativeInst.hpp");
AD.addInclude(AD._HPP_file, "opto/machnode.hpp");
AD.addInclude(AD._HPP_file, "opto/node.hpp");
AD.addInclude(AD._HPP_file, "opto/regalloc.hpp");
AD.addInclude(AD._HPP_file, "opto/subnode.hpp");
AD.addInclude(AD._HPP_file, "opto/vectornode.hpp");
AD.addInclude(AD._CPP_CLONE_file, "precompiled.hpp");
AD.addInclude(AD._CPP_CLONE_file, "adfiles", get_basename(AD._HPP_file._name));
AD.addInclude(AD._CPP_EXPAND_file, "precompiled.hpp");
AD.addInclude(AD._CPP_EXPAND_file, "adfiles", get_basename(AD._HPP_file._name));
AD.addInclude(AD._CPP_FORMAT_file, "precompiled.hpp");
AD.addInclude(AD._CPP_FORMAT_file, "adfiles", get_basename(AD._HPP_file._name));
AD.addInclude(AD._CPP_GEN_file, "precompiled.hpp");
AD.addInclude(AD._CPP_GEN_file, "adfiles", get_basename(AD._HPP_file._name));
AD.addInclude(AD._CPP_GEN_file, "opto/cfgnode.hpp");
AD.addInclude(AD._CPP_GEN_file, "opto/locknode.hpp");
AD.addInclude(AD._CPP_MISC_file, "precompiled.hpp");
AD.addInclude(AD._CPP_MISC_file, "adfiles", get_basename(AD._HPP_file._name));
AD.addInclude(AD._CPP_PEEPHOLE_file, "precompiled.hpp");
AD.addInclude(AD._CPP_PEEPHOLE_file, "adfiles", get_basename(AD._HPP_file._name));
AD.addInclude(AD._CPP_PIPELINE_file, "precompiled.hpp");
AD.addInclude(AD._CPP_PIPELINE_file, "adfiles", get_basename(AD._HPP_file._name));
AD.addInclude(AD._DFA_file, "precompiled.hpp");
AD.addInclude(AD._DFA_file, "adfiles", get_basename(AD._HPP_file._name));
AD.addInclude(AD._DFA_file, "opto/cfgnode.hpp"); // Use PROB_MAX in predicate.
AD.addInclude(AD._DFA_file, "opto/intrinsicnode.hpp");
AD.addInclude(AD._DFA_file, "opto/matcher.hpp");
AD.addInclude(AD._DFA_file, "opto/narrowptrnode.hpp");
AD.addInclude(AD._DFA_file, "opto/opcodes.hpp");
AD.addInclude(AD._DFA_file, "opto/convertnode.hpp");
// Make sure each .cpp file starts with include lines:
// files declaring and defining generators for Mach* Objects (hpp,cpp)
// Generate the result files:
// enumerations, class definitions, object generators, and the DFA
// file containing enumeration of machine operands & instructions (hpp)
AD.addPreHeaderBlocks(AD._HPP_file._fp); // .hpp
AD.buildMachOperEnum(AD._HPP_file._fp); // .hpp
AD.buildMachOpcodesEnum(AD._HPP_file._fp); // .hpp
AD.buildMachRegisterNumbers(AD._VM_file._fp); // VM file
AD.buildMachRegisterEncodes(AD._HPP_file._fp); // .hpp file
AD.declareRegSizes(AD._HPP_file._fp); // .hpp
AD.build_pipeline_enums(AD._HPP_file._fp); // .hpp
// output definition of class "State"
AD.defineStateClass(AD._HPP_file._fp); // .hpp
// file declaring the Mach* classes derived from MachOper and MachNode
AD.declareClasses(AD._HPP_file._fp);
// declare and define maps: in the .hpp and .cpp files respectively
AD.addSourceBlocks(AD._CPP_file._fp); // .cpp
AD.addHeaderBlocks(AD._HPP_file._fp); // .hpp
AD.buildReduceMaps(AD._HPP_file._fp, AD._CPP_file._fp);
AD.buildMustCloneMap(AD._HPP_file._fp, AD._CPP_file._fp);
// build CISC_spilling oracle and MachNode::cisc_spill() methods
AD.build_cisc_spill_instructions(AD._HPP_file._fp, AD._CPP_file._fp);
// define methods for machine dependent State, MachOper, and MachNode classes
AD.defineClasses(AD._CPP_file._fp);
AD.buildMachOperGenerator(AD._CPP_GEN_file._fp);// .cpp
AD.buildMachNodeGenerator(AD._CPP_GEN_file._fp);// .cpp
// define methods for machine dependent instruction matching
AD.buildInstructMatchCheck(AD._CPP_file._fp); // .cpp
// define methods for machine dependent frame management
AD.buildFrameMethods(AD._CPP_file._fp); // .cpp
AD.generate_needs_clone_jvms(AD._CPP_file._fp);
// do this last:
AD.addPreprocessorChecks(AD._CPP_file._fp); // .cpp
AD.addPreprocessorChecks(AD._CPP_CLONE_file._fp); // .cpp
AD.addPreprocessorChecks(AD._CPP_EXPAND_file._fp); // .cpp
AD.addPreprocessorChecks(AD._CPP_FORMAT_file._fp); // .cpp
AD.addPreprocessorChecks(AD._CPP_GEN_file._fp); // .cpp
AD.addPreprocessorChecks(AD._CPP_MISC_file._fp); // .cpp
AD.addPreprocessorChecks(AD._CPP_PEEPHOLE_file._fp); // .cpp
AD.addPreprocessorChecks(AD._CPP_PIPELINE_file._fp); // .cpp
// define the finite automata that selects lowest cost production
AD.buildDFA(AD._DFA_file._fp);
// Add include guards for all .hpp files
AD.addIncludeGuardEnd(AD._HPP_file, "GENERATED_ADFILES_AD_HPP"); // .hpp
AD.addIncludeGuardEnd(AD._VM_file, "GENERATED_ADFILES_ADGLOBALS_HPP"); // .hpp
AD.close_files(0); // Close all input/output files
// Final printout and statistics
// cout << program;
if( AD._dfa_debug & 2 ) { // For higher debug settings, print timing info
// Timer t_stop;
// Timer t_total = t_stop - t_start; // Total running time
// cerr << "\n---Architecture Description Totals---\n";
// cerr << ", Total lines: " << TotalLines;
// float l = TotalLines;
// cerr << "\nTotal Compilation Time: " << t_total << "\n";
// float ft = (float)t_total;
// if( ft > 0.0 ) fprintf(stderr,"Lines/sec: %#5.2f\n", l/ft);
}
return (AD._syntax_errs + AD._semantic_errs + AD._internal_errs); // Bye Bye!!
}
//------------------------------usage------------------------------------------
static void usage(ArchDesc& AD)
{
printf("Architecture Description Language Compiler\n\n");
printf("Usage: adlc [-doqwTs] [-#]* [-D<FLAG>[=<DEF>]] [-U<FLAG>] [-c<CPP_FILE_NAME>] [-h<HPP_FILE_NAME>] [-a<DFA_FILE_NAME>] [-v<GLOBALS_FILE_NAME>] <ADL_FILE_NAME>\n");
printf(" d produce DFA debugging info\n");
printf(" o no output produced, syntax and semantic checking only\n");
printf(" q quiet mode, supresses all non-essential messages\n");
printf(" w suppress warning messages\n");
printf(" T make DFA as many subroutine calls\n");
printf(" s output which instructions are cisc-spillable\n");
printf(" D define preprocessor symbol\n");
printf(" U undefine preprocessor symbol\n");
printf(" c specify CPP file name (default: %s)\n", AD._CPP_file._name);
printf(" h specify HPP file name (default: %s)\n", AD._HPP_file._name);
printf(" a specify DFA output file name\n");
printf(" v specify adGlobals output file name\n");
printf(" # increment ADL debug level\n");
printf("\n");
}
//------------------------------open_file------------------------------------
int ArchDesc::open_file(bool required, ADLFILE & ADF, const char *action)
{
if (required &&
(ADF._fp = fopen(ADF._name, action)) == NULL) {
printf("ERROR: Cannot open file for %s: %s\n", action, ADF._name);
close_files(1);
return 0;
}
return 1;
}
//------------------------------open_files-------------------------------------
int ArchDesc::open_files(void)
{
if (_ADL_file._name == NULL)
{ printf("ERROR: No ADL input file specified\n"); return 0; }
if (!open_file(true , _ADL_file, "r")) { return 0; }
if (!open_file(!_no_output, _DFA_file, "w")) { return 0; }
if (!open_file(!_no_output, _HPP_file, "w")) { return 0; }
if (!open_file(!_no_output, _CPP_file, "w")) { return 0; }
if (!open_file(!_no_output, _CPP_CLONE_file, "w")) { return 0; }
if (!open_file(!_no_output, _CPP_EXPAND_file, "w")) { return 0; }
if (!open_file(!_no_output, _CPP_FORMAT_file, "w")) { return 0; }
if (!open_file(!_no_output, _CPP_GEN_file, "w")) { return 0; }
if (!open_file(!_no_output, _CPP_MISC_file, "w")) { return 0; }
if (!open_file(!_no_output, _CPP_PEEPHOLE_file, "w")) { return 0; }
if (!open_file(!_no_output, _CPP_PIPELINE_file, "w")) { return 0; }
if (!open_file(!_no_output, _VM_file , "w")) { return 0; }
if (!open_file(_dfa_debug != 0, _bug_file, "w")) { return 0; }
return 1;
}
//------------------------------close_file------------------------------------
void ArchDesc::close_file(int delete_out, ADLFILE& ADF)
{
if (ADF._fp) {
fclose(ADF._fp);
if (delete_out) remove(ADF._name);
}
}
//------------------------------close_files------------------------------------
void ArchDesc::close_files(int delete_out)
{
if (_ADL_file._fp) fclose(_ADL_file._fp);
close_file(delete_out, _CPP_file);
close_file(delete_out, _CPP_CLONE_file);
close_file(delete_out, _CPP_EXPAND_file);
close_file(delete_out, _CPP_FORMAT_file);
close_file(delete_out, _CPP_GEN_file);
close_file(delete_out, _CPP_MISC_file);
close_file(delete_out, _CPP_PEEPHOLE_file);
close_file(delete_out, _CPP_PIPELINE_file);
close_file(delete_out, _HPP_file);
close_file(delete_out, _DFA_file);
close_file(delete_out, _bug_file);
if (!_quiet_mode) {
printf("\n");
if (_no_output || delete_out) {
if (_ADL_file._name) printf("%s: ", _ADL_file._name);
printf("No output produced");
}
else {
if (_ADL_file._name) printf("%s --> ", _ADL_file._name);
printf("%s, %s, %s, %s, %s, %s, %s, %s, %s, %s",
_CPP_file._name,
_CPP_CLONE_file._name,
_CPP_EXPAND_file._name,
_CPP_FORMAT_file._name,
_CPP_GEN_file._name,
_CPP_MISC_file._name,
_CPP_PEEPHOLE_file._name,
_CPP_PIPELINE_file._name,
_HPP_file._name,
_DFA_file._name);
}
printf("\n");
}
}
//------------------------------strip_ext--------------------------------------
static char *strip_ext(char *fname)
{
char *ep;
if (fname) {
ep = fname + strlen(fname) - 1; // start at last character and look for '.'
while (ep >= fname && *ep != '.') --ep;
if (*ep == '.') *ep = '\0'; // truncate string at '.'
}
return fname;
}
//------------------------------base_plus_suffix-------------------------------
// New concatenated string
static char *base_plus_suffix(const char* base, const char *suffix)
{
int len = (int)strlen(base) + (int)strlen(suffix) + 1;
char* fname = new char[len];
sprintf(fname,"%s%s",base,suffix);
return fname;
}
//------------------------------get_legal_text---------------------------------
// Get pointer to legal text at the beginning of AD file.
// This code assumes that a legal text starts at the beginning of .ad files,
// is commented by "//" at each line and ends with empty line.
//
int get_legal_text(FileBuff &fbuf, char **legal_text)
{
char* legal_start = fbuf.get_line();
assert(legal_start[0] == '/' && legal_start[1] == '/', "Incorrect header of AD file");
char* legal_end = fbuf.get_line();
assert(strncmp(legal_end, "// Copyright", 12) == 0, "Incorrect header of AD file");
while(legal_end[0] == '/' && legal_end[1] == '/') {
legal_end = fbuf.get_line();
}
*legal_text = legal_start;
return (int) (legal_end - legal_start);
}
// VS2005 has its own definition, identical to this one.
#if !defined(_WIN32) || defined(_WIN64) || _MSC_VER < 1400
void *operator new( size_t size, int, const char *, int ) throw() {
return ::operator new( size );
}
#endif
| YouDiSN/OpenJDK-Research | jdk9/hotspot/src/share/vm/adlc/main.cpp | C++ | gpl-2.0 | 21,875 |
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8163346
* @summary Test hashing of extended characters in Serviceability Agent.
* @library /test/lib
* @library /lib/testlibrary
* @compile -encoding utf8 HeapDumpTest.java
* @run main/timeout=240 HeapDumpTest
*/
import static jdk.testlibrary.Asserts.assertTrue;
import java.io.IOException;
import java.io.File;
import java.util.List;
import java.util.Arrays;
import jdk.testlibrary.JDKToolLauncher;
import jdk.testlibrary.OutputAnalyzer;
import jdk.testlibrary.ProcessTools;
import jdk.test.lib.apps.LingeredApp;
import jdk.test.lib.Platform;
public class HeapDumpTest {
private static LingeredAppWithExtendedChars theApp = null;
/**
*
* @param vmArgs - tool arguments to launch jhsdb
* @return exit code of tool
*/
public static void launch(String expectedMessage, List<String> toolArgs)
throws IOException {
System.out.println("Starting LingeredApp");
try {
theApp = new LingeredAppWithExtendedChars();
LingeredApp.startApp(Arrays.asList("-Xmx256m"), theApp);
System.out.println(theApp.\u00CB);
System.out.println("Starting " + toolArgs.get(0) + " against " + theApp.getPid());
JDKToolLauncher launcher = JDKToolLauncher.createUsingTestJDK("jhsdb");
for (String cmd : toolArgs) {
launcher.addToolArg(cmd);
}
launcher.addToolArg("--pid=" + Long.toString(theApp.getPid()));
ProcessBuilder processBuilder = new ProcessBuilder(launcher.getCommand());
processBuilder.redirectError(ProcessBuilder.Redirect.INHERIT);
OutputAnalyzer output = ProcessTools.executeProcess(processBuilder);
System.out.println("stdout:");
System.out.println(output.getStdout());
System.out.println("stderr:");
System.out.println(output.getStderr());
output.shouldContain(expectedMessage);
output.shouldHaveExitValue(0);
} catch (Exception ex) {
throw new RuntimeException("Test ERROR " + ex, ex);
} finally {
LingeredApp.stopApp(theApp);
}
}
public static void launch(String expectedMessage, String... toolArgs)
throws IOException {
launch(expectedMessage, Arrays.asList(toolArgs));
}
public static void testHeapDump() throws IOException {
File dump = new File("jhsdb.jmap.heap." +
System.currentTimeMillis() + ".hprof");
if (dump.exists()) {
dump.delete();
}
launch("heap written to", "jmap",
"--binaryheap", "--dumpfile=" + dump.getAbsolutePath());
assertTrue(dump.exists() && dump.isFile(),
"Could not create dump file " + dump.getAbsolutePath());
dump.delete();
}
public static void main(String[] args) throws Exception {
if (!Platform.shouldSAAttach()) {
// Silently skip the test if we don't have enough permissions to attach
System.err.println("Error! Insufficient permissions to attach - test skipped.");
return;
}
testHeapDump();
// The test throws RuntimeException on error.
// IOException is thrown if LingeredApp can't start because of some bad
// environment condition
System.out.println("Test PASSED");
}
}
| YouDiSN/OpenJDK-Research | jdk9/jdk/test/sun/tools/jhsdb/HeapDumpTest.java | Java | gpl-2.0 | 4,479 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Manager of RPC calls from plugins.
"""
from golismero.api.config import Config
__license__ = """
GoLismero 2.0 - The web knife - Copyright (C) 2011-2014
Golismero project site: https://github.com/golismero
Golismero project mail: contact@golismero-project.com
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
__all__ = ["RPCManager"]
from ..common import pickle
from ..messaging.codes import MessageCode, MSG_RPC_CODES
from ..messaging.manager import MessageManager
from functools import partial
from threading import Thread
import sys
import traceback
#------------------------------------------------------------------------------
# Decorators to automatically register RPC implementors at import time.
# Global map of RPC codes to implementors.
# dict( int -> tuple(callable, bool) )
rpcMap = {}
def implementor(rpc_code, blocking=False):
"""
RPC implementation function.
"""
return partial(_add_implementor, rpc_code, blocking)
def _add_implementor(rpc_code, blocking, fn):
# Validate the argument types.
if type(rpc_code) is not int:
raise TypeError("Expected int, got %r instead" % type(rpc_code))
if type(blocking) is not bool:
raise TypeError("Expected bool, got %r instead" % type(blocking))
if not callable(fn):
raise TypeError("Expected callable, got %r instead" % type(fn))
# Validate the RPC code.
if rpc_code in rpcMap:
try:
msg = "Duplicated RPC implementors for code %d: %s and %s"
msg %= (rpc_code, rpcMap[rpc_code][0].__name__, fn.__name__)
except Exception:
msg = "Duplicated RPC implementors for code: %d" % rpc_code
raise SyntaxError(msg)
# TODO: use introspection to validate the function signature
# Register the implementor.
rpcMap[rpc_code] = (fn, blocking)
# Return the implementor. No wrapping is needed! :)
return fn
#------------------------------------------------------------------------------
# Implementor for the special MSG_RPC_BULK code for bulk RPC calls.
@implementor(MessageCode.MSG_RPC_BULK)
def rpc_bulk(orchestrator, audit_name, rpc_code, *arguments):
# Get the implementor for the RPC code.
# Raise NotImplementedError if it's not defined.
try:
method, blocking = rpcMap[rpc_code]
except KeyError:
raise NotImplementedError("RPC code not implemented: %r" % rpc_code)
# This can't be done with blocking implementors!
if blocking:
raise NotImplementedError(
"Cannot run blocking RPC calls in bulk. Code: %r" % rpc_code)
# Prepare a partial function call to the implementor.
caller = partial(method, orchestrator, audit_name)
# Use the built-in map() function to issue all the calls.
# This ensures we support the exact same interface and functionality.
return map(caller, *arguments)
#------------------------------------------------------------------------------
# Ensures the message is received by the Orchestrator.
@implementor(MessageCode.MSG_RPC_SEND_MESSAGE)
def rpc_send_message(orchestrator, audit_name, message):
# Enqueue the ACK message.
orchestrator.enqueue_msg(message)
#------------------------------------------------------------------------------
class RPCManager (object):
"""
Executes remote procedure calls from plugins.
"""
#--------------------------------------------------------------------------
def __init__(self, orchestrator):
"""
:param orchestrator: Orchestrator instance.
:type orchestrator: Orchestrator
"""
# Keep a reference to the Orchestrator.
self.__orchestrator = orchestrator
# Keep a reference to the global RPC map (it's faster this way).
self.__rpcMap = rpcMap
# Check all RPC messages have been mapped at this point.
missing = MSG_RPC_CODES.difference(self.__rpcMap.keys())
if missing:
msg = "Missing RPC implementors for codes: %s"
msg %= ", ".join(str(x) for x in sorted(missing))
raise SyntaxError(msg)
#--------------------------------------------------------------------------
@property
def orchestrator(self):
"""
:returns: Orchestrator instance.
:rtype: Orchestrator
"""
return self.__orchestrator
#--------------------------------------------------------------------------
def execute_rpc(self, audit_name, rpc_code, response_queue, args, kwargs):
"""
Honor a remote procedure call request from a plugin.
:param audit_name: Name of the audit requesting the call.
:type audit_name: str
:param rpc_code: RPC code.
:type rpc_code: int
:param response_queue: Response queue identity.
:type response_queue: str
:param args: Positional arguments to the call.
:type args: tuple
:param kwargs: Keyword arguments to the call.
:type kwargs: dict
"""
try:
# Get the implementor for the RPC code.
# Raise NotImplementedError if it's not defined.
try:
target, blocking = self.__rpcMap[rpc_code]
except KeyError:
raise NotImplementedError(
"RPC code not implemented: %r" % rpc_code)
# If it's a blocking call...
if blocking:
# Run the implementor in a new thread.
thread = Thread(
target = self._execute_rpc_implementor_background,
args = (
Config._context,
audit_name,
target,
response_queue,
args, kwargs),
)
thread.daemon = True
thread.start()
# If it's a non-blocking call...
else:
# Call the implementor directly.
self.execute_rpc_implementor(
audit_name, target, response_queue, args, kwargs)
# Catch exceptions and send them back.
except Exception:
if response_queue:
error = self.prepare_exception(*sys.exc_info())
try:
self.orchestrator.messageManager.send(
response_queue, (False, error))
except IOError:
import warnings
warnings.warn("RPC caller died!")
pass
#--------------------------------------------------------------------------
def _execute_rpc_implementor_background(self, context, audit_name, target,
response_queue, args, kwargs):
"""
Honor a remote procedure call request from a plugin,
from a background thread. Must only be used as the entry
point for said background thread!
:param context: Plugin execution context.
:type context: PluginContext
:param audit_name: Name of the audit requesting the call.
:type audit_name: str
:param target: RPC implementor function.
:type target: callable
:param response_queue: Response queue identity.
:type response_queue: str
:param args: Positional arguments to the call.
:type args: tuple
:param kwargs: Keyword arguments to the call.
:type kwargs: dict
"""
Config._context = context
self.execute_rpc_implementor(
audit_name, target, response_queue, args, kwargs)
#--------------------------------------------------------------------------
def execute_rpc_implementor(self, audit_name, target, response_queue,
args, kwargs):
"""
Honor a remote procedure call request from a plugin.
:param audit_name: Name of the audit requesting the call.
:type audit_name: str
:param target: RPC implementor function.
:type target: callable
:param response_queue: Response queue identity.
:type response_queue: str
:param args: Positional arguments to the call.
:type args: tuple
:param kwargs: Keyword arguments to the call.
:type kwargs: dict
"""
try:
# Call the implementor and get the response.
response = target(self.orchestrator, audit_name, *args, **kwargs)
success = True
# Catch exceptions and prepare them for sending.
except Exception:
if response_queue:
response = self.prepare_exception(*sys.exc_info())
success = False
# If the call was synchronous,
# send the response/error back to the plugin.
if response_queue:
self.orchestrator.messageManager.send(
response_queue, (success, response))
#--------------------------------------------------------------------------
@staticmethod
def prepare_exception(exc_type, exc_value, exc_traceback):
"""
Prepare an exception for sending back to the plugins.
:param exc_type: Exception type.
:type exc_type: class
:param exc_value: Exception value.
:type exc_value:
:returns: Exception type, exception value
and formatted traceback. The exception value may be formatted too
and the exception type replaced by Exception if it's not possible
to serialize it for sending.
:rtype: tuple(class, object, str)
"""
exc_type, exc_value, exc_traceback = sys.exc_info()
try:
pickle.dumps(exc_value, -1)
except Exception:
exc_value = traceback.format_exception_only(exc_type, exc_value)
try:
pickle.dumps(exc_type, -1)
except Exception:
exc_type = Exception
exc_traceback = traceback.extract_tb(exc_traceback)
return exc_type, exc_value, exc_traceback
| golismero/golismero | golismero/managers/rpcmanager.py | Python | gpl-2.0 | 10,792 |
using System;
namespace Server.Items
{
[Flipable( 0xC12, 0xC13 )]
public class BrokenArmoireComponent : AddonComponent
{
public override int LabelNumber { get { return 1076262; } } // Broken Armoire
public BrokenArmoireComponent() : base( 0xC12 )
{
}
public BrokenArmoireComponent( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.WriteEncodedInt( 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadEncodedInt();
}
}
public class BrokenArmoireAddon : BaseAddon
{
public override BaseAddonDeed Deed { get { return new BrokenArmoireDeed(); } }
[Constructable]
public BrokenArmoireAddon() : base()
{
AddComponent( new BrokenArmoireComponent(), 0, 0, 0 );
}
public BrokenArmoireAddon( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.WriteEncodedInt( 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadEncodedInt();
}
}
public class BrokenArmoireDeed : BaseAddonDeed
{
public override BaseAddon Addon { get { return new BrokenArmoireAddon(); } }
public override int LabelNumber { get { return 1076262; } } // Broken Armoire
[Constructable]
public BrokenArmoireDeed() : base()
{
LootType = LootType.Blessed;
}
public BrokenArmoireDeed( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.WriteEncodedInt( 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadEncodedInt();
}
}
}
| jackuoll/Pre-AOS-RunUO | Scripts/Items/Special/Broken Furniture Collection/BrokenArmoire.cs | C# | gpl-2.0 | 1,896 |
/**********************************************************************
Audacity: A Digital Audio Editor
ExpandingToolBar.cpp
Dominic Mazzoni
*******************************************************************//**
\class ExpandingToolBar
\brief A smart ToolBar class that has a "MainPanel" which is always
displayed, and an "ExtraPanel" that can be hidden to save space.
Can be docked into a ToolBarArea or floated in an ToolBarFrame;
If auto-expanding is off, behavior is very simple: clicking the
toggle button expands, clicking it again collapses.
If auto-expanding is on, behavior is a little more complicated.
When the mouse movers over a toolbar and it is collapsed, it gets
auto-expanded, and it gets auto-collapsed as soon as the mouse
leaves. However, if they manually toggle it collapsed
while it was auto-expanded, it will stay collapsed until you move
the mouse completely away and then back again later. If you
manually expand it, it will stay manually expanded until you
manually collapse it.
*//****************************************************************//**
\class ExpandingToolBarEvtHandler
\brief A custom event handler for ExpandingToolBar.
*//****************************************************************//**
\class ToolBarGrabber
\brief Draws the grabber for an ExpandingToolBar.
*//****************************************************************//**
\class ToolBarDialog
\brief A dialog based container for ExpandingToolBars providing modal
based operations.
*//****************************************************************//**
\class ToolBarFrame
\brief A miniframe based container for ExpandingToolBars providing
modeless presentation.
*//****************************************************************//**
\class ToolBarArea
\brief An alterantive to ToolBarFrame which can contain an
ExpandingToolBar. ToolBarArea is used for a 'docked' ToolBar,
ToolBarFrame for a floating one.
*//****************************************************************//**
\class ToolBarArrangement
\brief Small class that holds some layout information for an
ExpandingToolBar.
*//*******************************************************************/
#include "../Theme.h"
// For compilers that support precompilation, includes "wx/wx.h".
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/window.h>
#endif
#include <wx/wx.h>
#include <wx/dcmemory.h>
#include <wx/log.h>
#include <wx/dragimag.h>
#include <wx/arrimpl.cpp>
#include <wx/dialog.h>
#include "ExpandingToolBar.h"
#include "AButton.h"
#include "../AllThemeResources.h"
#include "../Experimental.h"
const int kToggleButtonHeight = 8;
const int kTimerInterval = 50; // every 50 ms -> ~20 updates per second
const wxRect kDummyRect = wxRect(-9999, -9999, 0, 0);
enum {
kToggleButtonID = 5000,
kTimerID
};
WX_DEFINE_OBJARRAY(wxArrayRect);
class ToolBarArrangement
{
public:
ExpandingToolBarArray childArray;
wxArrayRect rectArray;
wxArrayInt rowArray;
};
//
// ExpandingToolBar
//
BEGIN_EVENT_TABLE(ExpandingToolBar, wxPanel)
EVT_SIZE(ExpandingToolBar::OnSize)
EVT_TIMER(kTimerID, ExpandingToolBar::OnTimer)
EVT_BUTTON(kToggleButtonID, ExpandingToolBar::OnToggle)
END_EVENT_TABLE()
IMPLEMENT_CLASS(ExpandingToolBar, wxPanel)
//static
int ExpandingToolBar::msNoAutoExpandStack = 0;
ExpandingToolBar::ExpandingToolBar(wxWindow* parent,
wxWindowID id,
const wxPoint& pos,
const wxSize& size):
wxPanel(parent, id, pos, size),
mIsAutoExpanded(false),
mIsManualExpanded(false),
mIsExpanded(false),
mAutoExpand(true),
mFirstTime(true),
mFrameParent(NULL),
mDialogParent(NULL),
mAreaParent(NULL),
mSavedArrangement(NULL),
mDragImage(NULL),
mTopLevelParent(NULL)
{
mMainPanel = new wxPanel(this, -1,
wxDefaultPosition, wxSize(1, 1));
mExtraPanel = new wxPanel(this, -1,
wxDefaultPosition, wxSize(1, 1));
mGrabber = NULL;
ToolBarArea *toolBarParent =
dynamic_cast<ToolBarArea *>(GetParent());
if (toolBarParent)
mGrabber = new ToolBarGrabber(this, -1, this);
/// \todo check whether this is a memory leak (and check similar code)
wxImage hbar = theTheme.Image(bmpToolBarToggle);
wxColour magicColor = wxColour(0, 255, 255);
ImageArray fourStates = ImageRoll::SplitV(hbar, magicColor);
mToggleButton = new AButton(this, kToggleButtonID,
wxDefaultPosition, wxDefaultSize,
ImageRoll(ImageRoll::HorizontalRoll,
fourStates[0], magicColor),
ImageRoll(ImageRoll::HorizontalRoll,
fourStates[1], magicColor),
ImageRoll(ImageRoll::HorizontalRoll,
fourStates[2], magicColor),
ImageRoll(ImageRoll::HorizontalRoll,
fourStates[3], magicColor),
true);
mToggleButton->UseDisabledAsDownHiliteImage(true);
SetAutoLayout(true);
mTimer.SetOwner(this, kTimerID);
}
ExpandingToolBar::~ExpandingToolBar()
{
}
void ExpandingToolBar::OnSize(wxSizeEvent & WXUNUSED(event))
{
if (mFrameParent || mDialogParent || mAreaParent)
return;
// At the time of construction, it wasn't "safe" to tell
// our parent that we've just joined the window, so we check
// for it during our first OnSize event.
if (!mFrameParent) {
ToolBarFrame *toolBarParent =
dynamic_cast<ToolBarFrame *>(GetParent());
if (toolBarParent) {
// We were placed into a floating window
mFrameParent = toolBarParent;
toolBarParent->SetChild(this);
}
}
if (!mDialogParent) {
ToolBarDialog *toolBarParent =
dynamic_cast<ToolBarDialog *>(GetParent());
if (toolBarParent) {
// We were placed into a dialog
mDialogParent = toolBarParent;
toolBarParent->SetChild(this);
}
}
if (!mAreaParent) {
ToolBarArea *toolBarParent =
dynamic_cast<ToolBarArea *>(GetParent());
if (toolBarParent) {
// We were placed into an area full of other toolbars
mAreaParent = toolBarParent;
toolBarParent->AddChild(this);
}
}
}
void ExpandingToolBar::OnToggle(wxCommandEvent & WXUNUSED(event))
{
if (mIsExpanded)
Collapse();
else
Expand();
}
void ExpandingToolBar::Expand()
{
// We set both mIsManualExpanded and mIsAutoExpanded to true;
// that way if the user manually collapses the toolbar we set
// mIsManualExpanded to false but keep mIsAutoExpanded to true
// to prevent it from being auto-expanded again until the user
// actually moves the mouse completely away and back again later.
mToggleButton->PushDown();
mIsManualExpanded = true;
mIsAutoExpanded = true;
Fit();
}
void ExpandingToolBar::Collapse(bool now /* = false */)
{
// After being manually collapsed, we set mIsAutoExpanded back to
// true, which prevents it from being immediately auto-expanded
// again until after the mouse actually moves away and then
// back again later.
mToggleButton->PopUp();
mIsManualExpanded = false;
mIsAutoExpanded = false;
Fit();
mIsAutoExpanded = true;
if (now) {
mCurrentDrawerSize = mTargetDrawerSize;
MoveDrawer(wxSize(0, 0));
}
}
void ExpandingToolBar::TryAutoExpand()
{
if (mAutoExpand && msNoAutoExpandStack==0 &&
mIsManualExpanded == false && mIsAutoExpanded == false) {
mToggleButton->PushDown();
mIsAutoExpanded = true;
Fit();
}
}
void ExpandingToolBar::TryAutoCollapse()
{
#ifdef EXPERIMENTAL_ROLL_UP_DIALOG
if (mIsAutoExpanded == true && mIsManualExpanded == false) {
mToggleButton->PopUp();
mIsAutoExpanded = false;
Fit();
}
#endif
}
class ExpandingToolBarEvtHandler : public wxEvtHandler
{
public:
ExpandingToolBarEvtHandler(ExpandingToolBar *toolbar,
wxEvtHandler *inheritedEvtHandler)
{
mToolBar = toolbar;
mInheritedEvtHandler = inheritedEvtHandler;
}
virtual bool ProcessEvent(wxEvent& evt)
{
if (mToolBar->IsCursorInWindow())
mToolBar->TryAutoExpand();
else
mToolBar->TryAutoExpand();
return mInheritedEvtHandler->ProcessEvent(evt);
}
protected:
ExpandingToolBar *mToolBar;
wxEvtHandler *mInheritedEvtHandler;
DECLARE_NO_COPY_CLASS(ExpandingToolBarEvtHandler);
};
void ExpandingToolBar::RecursivelyPushEventHandlers(wxWindow *win)
{
if (!mWindowHash[win]) {
ExpandingToolBarEvtHandler *evtHandler =
new ExpandingToolBarEvtHandler(this, win->GetEventHandler());
win->PushEventHandler(evtHandler);
mWindowHash[win] = 1;
}
wxWindowList children = win->GetChildren();
typedef wxWindowList::compatibility_iterator Node;
for(Node node = children.GetFirst(); node; node = node->GetNext()) {
wxWindow *child = node->GetData();
RecursivelyPushEventHandlers(child);
}
}
bool ExpandingToolBar::Layout()
{
mMainSize = mMainPanel->GetBestSize();
mExtraSize = mExtraPanel->GetBestSize();
mButtonSize = wxSize(wxMax(mMainSize.x, mExtraSize.x),
kToggleButtonHeight);
int left = 0;
if (mGrabber) {
mGrabberSize = mGrabber->GetMinSize();
left += mGrabberSize.x;
}
else
mGrabberSize = wxSize(0, 0);
mMainPanel->SetSize(left, 0, mMainSize.x, mMainSize.y);
mToggleButton->SetSize(left, mMainSize.y, mButtonSize.x, mButtonSize.y);
mExtraPanel->SetSize(left, mMainSize.y + mButtonSize.y,
mExtraSize.x, mExtraSize.y);
if (mGrabber)
mGrabber->SetSize(0, 0, left, mMainSize.y + mButtonSize.y);
// Add event handlers to all children
//RecursivelyPushEventHandlers(this);
return true;
}
void ExpandingToolBar::Fit()
{
#ifdef EXPERIMENTAL_ROLL_UP_DIALOG
mIsExpanded = (mIsAutoExpanded || mIsManualExpanded);
#else
mIsExpanded = true;// JKC - Wedge it open at all times.
#endif
int width = mButtonSize.x + mGrabberSize.x;
wxSize baseWindowSize = wxSize(width,
mMainSize.y + mButtonSize.y);
mTargetDrawerSize = wxSize(mButtonSize.x, 0);
if (mIsExpanded)
mTargetDrawerSize.y += mExtraSize.y;
mCurrentDrawerSize.x = mTargetDrawerSize.x;
// The first time, we always update the size. Otherwise, we set
// a target size, and the actual size changes during a timer
// event.
if (mFirstTime) {
mFirstTime = false;
mCurrentDrawerSize = wxSize(mExtraSize.x, 0);
mCurrentTotalSize = baseWindowSize;
SetSizeHints(mCurrentTotalSize, mCurrentTotalSize);
SetSize(mCurrentTotalSize);
}
// wxTimers seem to be a little unreliable - sometimes they stop for
// no good reason, so this "primes" it every now and then...
mTimer.Stop();
mTimer.Start(kTimerInterval);
}
bool ExpandingToolBar::IsCursorInWindow()
{
wxPoint globalMouse = ::wxGetMousePosition();
wxPoint localMouse = ScreenToClient(globalMouse);
bool result = (localMouse.x >= 0 && localMouse.y >= 0 &&
localMouse.x < mCurrentTotalSize.x &&
localMouse.y < mCurrentTotalSize.y);
// The grabber doesn't count!
if (mGrabber && mGrabber->GetRect().Contains(localMouse))
result = false;
return result;
}
void ExpandingToolBar::ReparentExtraPanel()
{
// This is how we make sure the extra panel, which slides out
// like a drawer, appears on top of everything else in the window...
wxPoint pos;
pos.x = mGrabberSize.x;
pos.y = mMainSize.y + mButtonSize.y;
wxWindow *frame = this;
while(!frame->IsTopLevel()) {
pos += frame->GetPosition();
frame = frame->GetParent();
}
mExtraPanel->Reparent(frame);
mExtraPanel->SetPosition(pos);
}
void ExpandingToolBar::MoveDrawer(wxSize prevSize)
{
mCurrentTotalSize = wxSize(mButtonSize.x,
mMainSize.y +
mButtonSize.y +
mCurrentDrawerSize.y);
if (mFrameParent) {
// If we're in a tool window
SetSizeHints(mCurrentTotalSize, mCurrentTotalSize);
SetSize(mCurrentTotalSize);
GetParent()->Fit();
}
if (mDialogParent) {
// If we're in a dialog
SetSizeHints(mCurrentTotalSize, mCurrentTotalSize);
SetSize(mCurrentTotalSize);
GetParent()->Fit();
}
if (mAreaParent) {
// If we're in a tool area
if (mCurrentDrawerSize.y > 0 && prevSize.y == 0) {
ReparentExtraPanel();
mExtraPanel->Show();
}
mExtraPanel->SetSizeHints(mCurrentDrawerSize, mCurrentDrawerSize);
mExtraPanel->SetSize(mCurrentDrawerSize);
if (mCurrentDrawerSize.y == 0)
mExtraPanel->Hide();
}
}
void ExpandingToolBar::OnTimer(wxTimerEvent & WXUNUSED(event))
{
if (mAutoExpand && msNoAutoExpandStack==0 &&
IsCursorInWindow())
TryAutoExpand();
else if (!IsCursorInWindow())
TryAutoCollapse();
if (mCurrentDrawerSize == mTargetDrawerSize)
return;
// This accelerates the current size towards the target size;
// it's a neat way for the window to roll open, but in such a
// way that it
wxSize prevSize = mCurrentDrawerSize;
mCurrentDrawerSize = (mCurrentDrawerSize*2 + mTargetDrawerSize) / 3;
if (abs((mCurrentDrawerSize-mTargetDrawerSize).x)<2 &&
abs((mCurrentDrawerSize-mTargetDrawerSize).y)<2)
mCurrentDrawerSize = mTargetDrawerSize;
MoveDrawer(prevSize);
}
wxBitmap ExpandingToolBar::GetToolbarBitmap()
{
wxSize size = GetClientSize();
wxBitmap bitmap(size.x, size.y);
wxClientDC winDC(this);
wxMemoryDC memDC;
memDC.SelectObject(bitmap);
memDC.Blit(0, 0, size.x, size.y,
&winDC, 0, 0);
return bitmap;
}
void ExpandingToolBar::StartMoving()
{
if (!mAreaParent)
return;
int j;
mAreaParent->CollapseAll(true);
mTimer.Stop();
// This gives time for wx to finish redrawing the window that way.
// HACK: why do we need to do it so many times???
for(j=0; j<500; j++)
::wxSafeYield();
wxBitmap toolbarBitmap = GetToolbarBitmap();
msNoAutoExpandStack++;
mSavedArrangement = mAreaParent->SaveArrangement();
mAreaParent->RemoveChild(this);
mAreaParent->Refresh(true);
mTopLevelParent = this;
while(!mTopLevelParent->IsTopLevel())
mTopLevelParent = mTopLevelParent->GetParent();
wxPoint hotSpot = ScreenToClient(wxGetMousePosition());
hotSpot -= (ClientToScreen(wxPoint(0, 0)) -
mAreaParent->ClientToScreen(wxPoint(0, 0)));
mDropTargets = mAreaParent->GetDropTargets();
mDropTarget = kDummyRect;
wxColour magicColor = wxColour(0, 255, 255);
wxImage tgtImage = theTheme.Image(bmpToolBarTarget);
ImageRoll tgtImageRoll = ImageRoll(ImageRoll::VerticalRoll,
tgtImage,
magicColor);
mTargetPanel = new ImageRollPanel(mAreaParent, -1, tgtImageRoll,
wxDefaultPosition,
wxDefaultSize,
wxTRANSPARENT_WINDOW);
mTargetPanel->SetLogicalFunction(wxXOR);
mTargetPanel->SetSize(mDropTarget);
// This gives time for wx to finish redrawing the window that way.
// HACK: why do we need to do it several times???
for(j=0; j<500; j++)
::wxSafeYield();
mAreaParent->SetCapturedChild(this);
mDragImage = new wxDragImage(toolbarBitmap);
mDragImage->BeginDrag(hotSpot, mAreaParent, mTopLevelParent);
mDragImage->Show();
mDragImage->Move(ScreenToClient(wxGetMousePosition()));
}
void ExpandingToolBar::UpdateMoving()
{
if (!mAreaParent || !mSavedArrangement || !mDragImage)
return;
wxPoint cursorPos = mAreaParent->ScreenToClient(wxGetMousePosition());
wxRect prevTarget = mDropTarget;
int best_dist_sq = 99999;
int i;
for(i=0; i<(int)mDropTargets.GetCount(); i++) {
int x = (mDropTargets[i].x + (mDropTargets[i].width/2))-cursorPos.x;
int y = (mDropTargets[i].y + (mDropTargets[i].height/2))-cursorPos.y;
int dist_sq = (x*x) + (y*y);
if (dist_sq < best_dist_sq) {
best_dist_sq = dist_sq;
mDropTarget = mDropTargets[i];
}
}
if (!mAreaParent->GetRect().Contains(cursorPos))
mDropTarget = kDummyRect;
if (mDropTarget != prevTarget) {
mDragImage->Hide();
wxRect r = mDropTarget;
r.Inflate(4, 4);
mTargetPanel->SetSize(r);
#if 0
wxClientDC dc(mAreaParent);
dc.DestroyClippingRegion();
dc.SetLogicalFunction(wxINVERT);
wxRect r = prevTarget;
r.Inflate(4, 4);
dc.DrawRectangle(r);
r = mDropTarget;
r.Inflate(4, 4);
dc.DrawRectangle(r);
#endif
// This gives time for wx to finish redrawing the window that way.
// HACK: why do we need to do it so many times???
for(i=0; i<500; i++)
::wxSafeYield();
mDragImage->Show();
mDragImage->Move(ScreenToClient(wxGetMousePosition()));
}
else
mDragImage->Move(ScreenToClient(wxGetMousePosition()));
}
void ExpandingToolBar::FinishMoving()
{
if (!mAreaParent || !mSavedArrangement)
return;
delete mTargetPanel;
mAreaParent->SetCapturedChild(NULL);
mDragImage->Hide();
mDragImage->EndDrag();
msNoAutoExpandStack--;
if (mDropTarget == kDummyRect) {
mAreaParent->RestoreArrangement(mSavedArrangement);
mSavedArrangement = NULL;
}
else {
delete mSavedArrangement;
mSavedArrangement = NULL;
mAreaParent->MoveChild(this, mDropTarget);
}
// Keep all drawers closed until the user moves specifically to a
// different window
mAreaParent->CollapseAll();
mTopLevelParent->Refresh(true);
mTimer.Start(kTimerInterval);
}
//
// ToolBarGrabber
//
BEGIN_EVENT_TABLE(ToolBarGrabber, wxPanel)
EVT_PAINT(ToolBarGrabber::OnPaint)
EVT_SIZE(ToolBarGrabber::OnSize)
EVT_MOUSE_EVENTS(ToolBarGrabber::OnMouse)
END_EVENT_TABLE()
IMPLEMENT_CLASS(ToolBarGrabber, wxPanel)
ToolBarGrabber::ToolBarGrabber(wxWindow *parent,
wxWindowID id,
ExpandingToolBar *ownerToolbar,
const wxPoint& pos,
const wxSize& size):
wxPanel(parent, id, pos, size),
mOwnerToolBar(ownerToolbar)
{
wxImage grabberImages = theTheme.Image(bmpToolBarGrabber);
wxColour magicColor = wxColour(0, 255, 255);
ImageArray images = ImageRoll::SplitH(grabberImages, magicColor);
mImageRoll[0] = ImageRoll(ImageRoll::VerticalRoll,
images[0],
magicColor);
mImageRoll[1] = ImageRoll(ImageRoll::VerticalRoll,
images[1],
magicColor);
SetSizeHints(mImageRoll[0].GetMinSize(),
mImageRoll[1].GetMaxSize());
mState = 0;
}
void ToolBarGrabber::OnMouse(wxMouseEvent &event)
{
int prevState = mState;
// Handle hilighting the image if the mouse is over it
if (event.Entering())
mState = 1;
else if (event.Leaving())
mState = 0;
else {
wxSize clientSize = GetClientSize();
if (event.m_x >= 0 && event.m_y >= 0 &&
event.m_x < clientSize.x && event.m_y < clientSize.y)
mState = 1;
else
mState = 0;
}
if (event.ButtonDown())
mOwnerToolBar->StartMoving();
if (mState != prevState)
Refresh(false);
}
void ToolBarGrabber::OnPaint(wxPaintEvent & WXUNUSED(event))
{
wxPaintDC dc(this);
mImageRoll[mState].Draw(dc, GetClientRect());
}
void ToolBarGrabber::OnSize(wxSizeEvent & WXUNUSED(event))
{
Refresh(false);
}
//
// ToolBarDialog
//
BEGIN_EVENT_TABLE(ToolBarDialog, wxDialog)
END_EVENT_TABLE()
IMPLEMENT_CLASS(ToolBarDialog, wxDialog)
ToolBarDialog::ToolBarDialog(wxWindow* parent,
wxWindowID id,
const wxString& name,
const wxPoint& pos):
wxDialog(parent, id, name, pos, wxSize(1, 1),
// Workaround for bug in __WXMSW__. No close box on a wxDialog unless wxSYSTEM_MENU is used.
#ifdef __WXMSW__
wxSYSTEM_MENU |
#endif
wxCAPTION|wxCLOSE_BOX),
mChild(NULL)
{
}
ToolBarDialog::~ToolBarDialog()
{
}
void ToolBarDialog::SetChild(ExpandingToolBar *child)
{
mChild = child;
if (mChild && mChild->GetParent() != this)
mChild->Reparent(this);
Fit();
}
void ToolBarDialog::Fit()
{
if (mChild) {
wxSize childSize = mChild->GetBestSize();
// Take into account the difference between the content
// size and the frame size
wxSize curContentSize = GetClientSize();
wxSize curFrameSize = GetSize();
wxSize newFrameSize = childSize + (curFrameSize - curContentSize);
SetSizeHints(newFrameSize, newFrameSize);
SetSize(newFrameSize);
}
}
//
// ToolBarFrame
//
BEGIN_EVENT_TABLE(ToolBarFrame, wxMiniFrame)
END_EVENT_TABLE()
IMPLEMENT_CLASS(ToolBarFrame, wxMiniFrame)
ToolBarFrame::ToolBarFrame(wxWindow* parent,
wxWindowID id,
const wxString& name,
const wxPoint& pos):
wxMiniFrame(parent, id, name, pos, wxSize(1, 1),
// Workaround for bug in __WXMSW__. No close box on a miniframe unless wxSYSTEM_MENU is used.
#ifdef __WXMSW__
wxSYSTEM_MENU |
#endif
wxCAPTION|wxCLOSE_BOX),
mChild(NULL)
{
}
ToolBarFrame::~ToolBarFrame()
{
}
void ToolBarFrame::SetChild(ExpandingToolBar *child)
{
mChild = child;
if (mChild && mChild->GetParent() != this)
mChild->Reparent(this);
Fit();
}
void ToolBarFrame::Fit()
{
if (mChild) {
wxSize childSize = mChild->GetBestSize();
// Take into account the difference between the content
// size and the frame size
wxSize curContentSize = GetClientSize();
wxSize curFrameSize = GetSize();
wxSize newFrameSize = childSize + (curFrameSize - curContentSize);
SetSizeHints(newFrameSize, newFrameSize);
SetSize(newFrameSize);
}
}
//
// ToolBarArea
//
BEGIN_EVENT_TABLE(ToolBarArea, wxPanel)
EVT_SIZE(ToolBarArea::OnSize)
EVT_MOUSE_EVENTS(ToolBarArea::OnMouse)
END_EVENT_TABLE()
IMPLEMENT_CLASS(ToolBarArea, wxPanel)
ToolBarArea::ToolBarArea(wxWindow* parent,
wxWindowID id,
const wxPoint& pos,
const wxSize& size):
wxPanel(parent, id, pos, size),
mInOnSize(false),
mCapturedChild(NULL)
{
}
ToolBarArea::~ToolBarArea()
{
}
void ToolBarArea::ContractRow(int rowIndex)
{
// Contract all of the toolbars in a given row to their
// minimum size. This is an intermediate step in layout.
int i;
int x = 0;
for(i=0; i<(int)mChildArray.GetCount(); i++)
if (mRowArray[i] == rowIndex) {
wxPoint childPos = mChildArray[i]->GetPosition();
wxSize childMin = mChildArray[i]->GetMinSize();
mChildArray[i]->SetSize(x, childPos.y,
childMin.x, childMin.y);
x += childMin.x;
}
}
bool ToolBarArea::ExpandRow(int rowIndex)
{
// Expand all of the toolbars in a given row so that the
// whole width is filled, if possible. This is the last
// step after laying out as many toolbars as possible in
// that row. Returns false if it's not possible to fit
// all of these toolbars in one row anymore.
wxSize area = GetClientSize();
int i, j, x;
int minWidth = 0;
int leftoverSpace = 0;
int expandableCount = 0;
int toolbarCount = 0;
for(i=0; i<(int)mChildArray.GetCount(); i++)
if (mRowArray[i] == rowIndex) {
ExpandingToolBar *child = mChildArray[i];
wxSize childMin = child->GetMinSize();
wxSize childMax = child->GetMaxSize();
minWidth += childMin.x;
toolbarCount++;
if (childMax.x > childMin.x)
expandableCount++;
}
leftoverSpace = area.x - minWidth;
if (leftoverSpace <= 0) {
if (toolbarCount > 1)
return false; // not possible to fit all in one row
else
return true; // there's only one, so it doesn't matter
}
j = 0;
x = 0;
for(i=0; i<(int)mChildArray.GetCount(); i++)
if (mRowArray[i] == rowIndex) {
ExpandingToolBar *child = mChildArray[i];
wxPoint childPos = child->GetPosition();
wxSize childMin = child->GetMinSize();
wxSize childMax = child->GetMaxSize();
int width = childMin.x;
if (childMax.x > childMin.x)
width +=
(leftoverSpace * (j+1) / expandableCount) -
(leftoverSpace * (j) / expandableCount);
mChildArray[i]->SetSize(x, childPos.y,
width, childMin.y);
x += width;
j++;
}
return true; // success
}
void ToolBarArea::LayoutOne(int childIndex)
{
wxSize area = GetClientSize();
ExpandingToolBar *child = mChildArray[childIndex];
wxSize childMin = child->GetMinSize();
if (childIndex == 0) {
mRowArray[childIndex] = 0;
mChildArray[childIndex]->SetSize(0, 0, childMin.x, childMin.y);
ExpandRow(0);
#if 0
wxPoint p = mChildArray[childIndex]->GetPosition();
wxSize s = mChildArray[childIndex]->GetSize();
printf("ToolBar %d moved to row %d at (%d, %d), size (%d x %d)\n",
childIndex, mRowArray[childIndex],
p.x, p.y, s.x, s.y);
#endif
mLastLayoutSize = area;
return;
}
int prevRow = mRowArray[childIndex-1];
ContractRow(prevRow);
wxPoint prevPos = mChildArray[childIndex-1]->GetPosition();
wxSize prevSize = mChildArray[childIndex-1]->GetSize();
int prevX = prevPos.x + prevSize.x;
int availableWidth = area.x - prevX;
if (childMin.x <= availableWidth) {
// It fits into the same row
mRowArray[childIndex] = prevRow;
mChildArray[childIndex]->SetSize(prevX, prevPos.y,
childMin.x, childMin.y);
ExpandRow(prevRow);
}
else {
// Go to the next row
ExpandRow(prevRow);
mRowArray[childIndex] = prevRow + 1;
int i;
int maxRowHeight = 0;
for(i=0; i<childIndex; i++)
if (mRowArray[i] == prevRow &&
mChildArray[i]->GetSize().y > maxRowHeight)
maxRowHeight = mChildArray[i]->GetSize().y;
mChildArray[childIndex]->SetSize(0, prevPos.y + maxRowHeight,
childMin.x, childMin.y);
ExpandRow(prevRow+1);
}
// Save the size of the window the last time we moved one of the
// toolbars around. If the user does a minor resize, we try to
// preserve the layout. If the user does a major resize, we're
// allowed to redo the layout.
mLastLayoutSize = area;
#if 0
wxPoint p = mChildArray[childIndex]->GetPosition();
wxSize s = mChildArray[childIndex]->GetSize();
printf("ToolBar %d moved to row %d at (%d, %d), size (%d x %d)\n",
childIndex, mRowArray[childIndex],
p.x, p.y, s.x, s.y);
#endif
}
bool ToolBarArea::Layout()
{
// Redo the layout from scratch, preserving only the order of
// the children
int i;
for(i=0; i<(int)mChildArray.GetCount(); i++)
mRowArray[i] = -1;
for(i=0; i<(int)mChildArray.GetCount(); i++)
LayoutOne(i);
Refresh(true);
return true;
}
void ToolBarArea::AdjustLayout()
{
// Try to modify the layout as little as possible - but if that's
// impossible, redo the layout as necessary.
int row = -1;
int i, j;
for(i=0; i<(int)mChildArray.GetCount(); i++) {
if (mRowArray[i] > row) {
row = mRowArray[i];
bool success = ExpandRow(row);
if (!success) {
// Re-layout all toolbars from this row on
for(j=i; j<(int)mChildArray.GetCount(); j++)
LayoutOne(j);
return;
}
}
}
}
void ToolBarArea::Fit()
{
Fit(true, true);
}
void ToolBarArea::Fit(bool horizontal, bool vertical)
{
wxSize clientSize = GetClientSize();
wxSize minSize;
wxSize maxSize;
wxSize actualSize;
int i;
minSize.x = 0;
minSize.y = 0;
maxSize.x = 9999;
maxSize.y = 0;
for(i=0; i<(int)mChildArray.GetCount(); i++) {
wxPoint childPos = mChildArray[i]->GetPosition();
wxSize childSize = mChildArray[i]->GetSize();
if (childPos.x + childSize.x > actualSize.x) {
actualSize.x = childPos.x + childSize.x;
}
if (childSize.x > minSize.x) {
minSize.x = childSize.x;
}
if (childPos.y + childSize.y > maxSize.y) {
maxSize.y = childPos.y + childSize.y;
minSize.y = maxSize.y;
actualSize.y = maxSize.y;
}
}
if (!horizontal && actualSize.x < clientSize.x)
actualSize.x = clientSize.x;
if (!vertical && actualSize.y < clientSize.y)
actualSize.y = clientSize.y;
if (minSize != mMinSize ||
maxSize != mMaxSize) {
mMinSize = minSize;
mMaxSize = maxSize;
SetSizeHints(mMinSize, mMaxSize);
}
if (actualSize != mActualSize) {
mActualSize = actualSize;
SetSize(mActualSize);
}
}
void ToolBarArea::OnSize(wxSizeEvent & WXUNUSED(event))
{
if (mInOnSize)
return;
mInOnSize = true;
wxSize currentSize = GetClientSize();
if (abs(currentSize.x - mLastLayoutSize.x >= 100)) {
// If they resize by more than 100 pixels (horizontally),
// we totally redo the layout, preserving the order of the
// toolbars but not the exact position.
Layout();
}
else {
// If it was a minor resize, we try to preserve the positions of
// the toolbars. If this is impossible, we still redo the layout,
// of course.
AdjustLayout();
}
Fit(false, true);
mInOnSize = false;
}
void ToolBarArea::OnMouse(wxMouseEvent &evt)
{
if (mCapturedChild) {
if (evt.ButtonUp())
mCapturedChild->FinishMoving();
else if (evt.Moving() || evt.Dragging())
mCapturedChild->UpdateMoving();
}
else {
evt.Skip();
}
}
void ToolBarArea::CollapseAll(bool now)
{
int i;
for(i=0; i<(int)mChildArray.GetCount(); i++)
mChildArray[i]->Collapse(now);
}
void ToolBarArea::AddChild(ExpandingToolBar *child)
{
mChildArray.Add(child);
mRowArray.Add(-1); // unknown row
LayoutOne(mChildArray.GetCount()-1);
Fit(false, true);
}
void ToolBarArea::RemoveChild(ExpandingToolBar *child)
{
int i, j;
for(i=0; i<(int)mChildArray.GetCount(); i++) {
if (mChildArray[i] == child) {
child->Hide();
mChildArray.RemoveAt(i);
mRowArray.RemoveAt(i);
for(j=i; j<(int)mChildArray.GetCount(); j++)
mRowArray[j] = -1;
for(j=i; j<(int)mChildArray.GetCount(); j++)
LayoutOne(j);
Fit(false, true);
}
}
}
ToolBarArrangement *ToolBarArea::SaveArrangement()
{
ToolBarArrangement *arrangement = new ToolBarArrangement();
int i;
arrangement->childArray = mChildArray;
arrangement->rowArray = mRowArray;
for(i=0; i<(int)mChildArray.GetCount(); i++)
arrangement->rectArray.Add(mChildArray[i]->GetRect());
return arrangement;
}
void ToolBarArea::RestoreArrangement(ToolBarArrangement *arrangement)
{
int i;
mChildArray = arrangement->childArray;
mRowArray = arrangement->rowArray;
for(i=0; i<(int)mChildArray.GetCount(); i++) {
mChildArray[i]->SetSize(arrangement->rectArray[i]);
mChildArray[i]->Show();
}
Fit(false, true);
delete arrangement;
}
wxArrayRect ToolBarArea::GetDropTargets()
{
mDropTargets.Clear();
mDropTargetIndices.Clear();
mDropTargetRows.Clear();
int numChildren = (int)mChildArray.GetCount();
int i;
int row = -1;
if (numChildren == 0)
return mDropTargets;
for(i=0; i<numChildren; i++) {
int childRow = mRowArray[i];
wxRect childRect = mChildArray[i]->GetRect();
if (childRow != row) {
// Add a target before this child (at beginning of row only)
row = childRow;
mDropTargetIndices.Add(i);
mDropTargetRows.Add(row);
mDropTargets.Add(wxRect(childRect.x, childRect.y,
0, childRect.height));
}
// Add a target after this child (always)
mDropTargetIndices.Add(i+1);
mDropTargetRows.Add(row);
mDropTargets.Add(wxRect(childRect.x+childRect.width, childRect.y,
0, childRect.height));
}
return mDropTargets;
}
void ToolBarArea::MoveChild(ExpandingToolBar *toolBar, wxRect dropTarget)
{
int i, j;
for(i=0; i<(int)mDropTargets.GetCount(); i++) {
if (dropTarget == mDropTargets[i]) {
int newIndex = mDropTargetIndices[i];
int newRow = mDropTargetRows[i];
mChildArray.Insert(toolBar, newIndex);
mRowArray.Insert(newRow, newIndex);
for(j=newIndex+1; j<(int)mChildArray.GetCount(); j++)
mRowArray[j] = -1;
ContractRow(newRow);
mChildArray[newIndex]->Show();
for(j=newIndex; j<(int)mChildArray.GetCount(); j++)
LayoutOne(j);
Fit(false, true);
return;
}
}
}
void ToolBarArea::SetCapturedChild(ExpandingToolBar *child)
{
mCapturedChild = child;
}
| oneminot/audacity | src/widgets/ExpandingToolBar.cpp | C++ | gpl-2.0 | 33,841 |
<?php
/**
* TestLink Open Source Project - http://testlink.sourceforge.net/
* This script is distributed under the GNU General Public License 2 or later.
*
* Filename $RCSfile: reqExport.php,v $
*
* @version $Revision: 1.10 $
* @modified $Date: 2010/03/21 19:28:34 $ by $Author: franciscom $
*
* Allows users to export requirements.
*
* 20100321 - franciscom - manage export of :
* req. spec => full tree or branch (new to 1.9)
* child (direct children) requirements inside a req. spec
**/
require_once("../../config.inc.php");
require_once("csv.inc.php");
require_once("xml.inc.php");
require_once("common.php");
require_once("requirements.inc.php");
testlinkInitPage($db,false,false,"checkRights");
$templateCfg = templateConfiguration();
$req_spec_mgr = new requirement_spec_mgr($db);
$args = init_args();
$gui = initializeGui($args,$req_spec_mgr);
switch($args->doAction)
{
case 'export':
$smarty = new TLSmarty();
$smarty->assign('gui', $gui);
$smarty->display($templateCfg->template_dir . $templateCfg->default_template);
break;
case 'doExport':
doExport($args,$req_spec_mgr);
break;
}
/**
* checkRights
*
*/
function checkRights(&$db,&$user)
{
return $user->hasRight($db,'mgt_view_req');
}
/**
* init_args
*
*/
function init_args()
{
$_REQUEST = strings_stripSlashes($_REQUEST);
$args = new stdClass();
$args->doAction = isset($_REQUEST['doAction']) ? $_REQUEST['doAction'] : 'export';
$args->exportType = isset($_REQUEST['exportType']) ? $_REQUEST['exportType'] : null;
$args->req_spec_id = isset($_REQUEST['req_spec_id']) ? $_REQUEST['req_spec_id'] : null;
$args->export_filename = isset($_REQUEST['export_filename']) ? $_REQUEST['export_filename'] : "";
$args->tproject_id = isset($_REQUEST['tproject_id']) ? $_REQUEST['tproject_id'] : 0;
if( $args->tproject_id == 0 )
{
$args->tproject_id = isset($_SESSION['testprojectID']) ? $_SESSION['testprojectID'] : 0;
}
$args->scope = isset($_REQUEST['scope']) ? $_REQUEST['scope'] : 'items';
return $args;
}
/**
* initializeGui
*
*/
function initializeGui(&$argsObj,&$req_spec_mgr)
{
$gui = new stdClass();
$gui->exportTypes = $req_spec_mgr->get_export_file_types();
$gui->exportType = $argsObj->exportType;
$gui->scope = $argsObj->scope;
$gui->tproject_id = $argsObj->tproject_id;
switch($argsObj->scope)
{
case 'tree':
$gui->req_spec['title'] = lang_get('all_reqspecs_in_tproject');
$gui->req_spec_id = 0;
$exportFileName = 'all-req.xml';
break;
case 'branch':
$gui->req_spec = $req_spec_mgr->get_by_id($argsObj->req_spec_id);
$gui->req_spec_id = $argsObj->req_spec_id;
$exportFileName = $gui->req_spec['title'] . '-req-spec.xml';
break;
case 'items':
$gui->req_spec = $req_spec_mgr->get_by_id($argsObj->req_spec_id);
$gui->req_spec_id = $argsObj->req_spec_id;
$exportFileName = $gui->req_spec['title'] . '-child_req.xml';
break;
}
$gui->export_filename = trim($argsObj->export_filename);
if($gui->export_filename == "")
{
$gui->export_filename = $exportFileName;
}
return $gui;
}
/**
* doExport
*
*/
function doExport(&$argsObj,&$req_spec_mgr)
{
$pfn = null;
switch($argsObj->exportType)
{
case 'csv':
$requirements_map = $req_spec_mgr->get_requirements($argsObj->req_spec_id);
$pfn = "exportReqDataToCSV";
$fileName = 'reqs.csv';
$content = $pfn($requirements_map);
break;
case 'XML':
$pfn = "exportReqSpecToXML";
$fileName = 'reqs.xml';
$content = TL_XMLEXPORT_HEADER;
$optionsForExport['RECURSIVE'] = $argsObj->scope == 'items' ? false : true;
$openTag = $argsObj->scope == 'items' ? "requirements>" : 'requirement-specification>';
switch($argsObj->scope)
{
case 'tree':
$reqSpecSet = $req_spec_mgr->getFirstLevelInTestProject($argsObj->tproject_id);
$reqSpecSet = array_keys($reqSpecSet);
break;
case 'branch':
case 'items':
$reqSpecSet = array($argsObj->req_spec_id);
break;
}
$content .= "<" . $openTag . "\n";
if(!is_null($reqSpecSet))
{
foreach($reqSpecSet as $reqSpecID)
{
$content .= $req_spec_mgr->$pfn($reqSpecID,$argsObj->tproject_id,$optionsForExport);
}
}
$content .= "</" . $openTag . "\n";
break;
}
if ($pfn)
{
$fileName = is_null($argsObj->export_filename) ? $fileName : $argsObj->export_filename;
downloadContentsToFile($content,$fileName);
exit();
}
}
?> | qasourceinc/TestLink_1.9.5_QASourceContribution | lib/requirements/reqExport.php | PHP | gpl-2.0 | 4,583 |
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.util.List;
import java.util.Properties;
import org.compiere.util.DB;
/**
* Shipment Material Allocation
*
* @author Jorg Janke
* @version $Id: MInOutLineMA.java,v 1.3 2006/07/30 00:51:02 jjanke Exp $
*/
public class MInOutLineMA extends X_M_InOutLineMA
{
/**
*
*/
private static final long serialVersionUID = -3229418883339488380L;
/**
* Get Material Allocations for Line
* @param ctx context
* @param M_InOutLine_ID line
* @param trxName trx
* @return allocations
*/
public static MInOutLineMA[] get (Properties ctx, int M_InOutLine_ID, String trxName)
{
Query query = MTable.get(ctx, MInOutLineMA.Table_Name)
.createQuery(I_M_InOutLineMA.COLUMNNAME_M_InOutLine_ID+"=?", trxName);
query.setParameters(M_InOutLine_ID);
List<MInOutLineMA> list = query.list();
MInOutLineMA[] retValue = new MInOutLineMA[list.size ()];
list.toArray (retValue);
return retValue;
} // get
/**
* Delete all Material Allocation for InOut
* @param M_InOut_ID shipment
* @param trxName transaction
* @return number of rows deleted or -1 for error
*/
public static int deleteInOutMA (int M_InOut_ID, String trxName)
{
String sql = "DELETE FROM M_InOutLineMA ma WHERE EXISTS "
+ "(SELECT * FROM M_InOutLine l WHERE l.M_InOutLine_ID=ma.M_InOutLine_ID"
+ " AND M_InOut_ID=" + M_InOut_ID + ")";
return DB.executeUpdate(sql, trxName);
} // deleteInOutMA
/**
* Delete all Material Allocation for InOutLine
* @param M_InOutLine_ID Shipment Line
* @param trxName transaction
* @return number of rows deleted or -1 for error
*/
public static int deleteInOutLineMA (int M_InOutLine_ID, String trxName)
{
String sql = "DELETE FROM M_InOutLineMA ma WHERE ma.M_InOutLine_ID=?";
return DB.executeUpdate(sql, M_InOutLine_ID, trxName);
} // deleteInOutLineMA
// /** Logger */
// private static CLogger s_log = CLogger.getCLogger (MInOutLineMA.class);
/**************************************************************************
* Standard Constructor
* @param ctx context
* @param M_InOutLineMA_ID ignored
* @param trxName trx
*/
public MInOutLineMA (Properties ctx, int M_InOutLineMA_ID, String trxName)
{
super (ctx, M_InOutLineMA_ID, trxName);
if (M_InOutLineMA_ID != 0)
throw new IllegalArgumentException("Multi-Key");
} // MInOutLineMA
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName trx
*/
public MInOutLineMA (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
} // MInOutLineMA
/**
* Parent Constructor
* @param parent parent
* @param M_AttributeSetInstance_ID asi
* @param MovementQty qty
*/
public MInOutLineMA (MInOutLine parent, int M_AttributeSetInstance_ID, BigDecimal MovementQty)
{
this (parent.getCtx(), 0, parent.get_TrxName());
setClientOrg(parent);
setM_InOutLine_ID(parent.getM_InOutLine_ID());
//
setM_AttributeSetInstance_ID(M_AttributeSetInstance_ID);
setMovementQty(MovementQty);
} // MInOutLineMA
/**
* String Representation
* @return info
*/
public String toString ()
{
StringBuffer sb = new StringBuffer ("MInOutLineMA[");
sb.append("M_InOutLine_ID=").append(getM_InOutLine_ID())
.append(",M_AttributeSetInstance_ID=").append(getM_AttributeSetInstance_ID())
.append(", Qty=").append(getMovementQty())
.append ("]");
return sb.toString ();
} // toString
} // MInOutLineMA
| erpcya/adempierePOS | base/src/org/compiere/model/MInOutLineMA.java | Java | gpl-2.0 | 4,940 |
<?php
/**
* base class to choose the language
*
* @since 1.2
*/
abstract class PLL_Choose_Lang {
public $links_model, $model, $options;
public $curlang;
/**
* constructor
*
* @since 1.2
*
* @param object $polylang
*/
public function __construct( &$polylang ) {
$this->links_model = &$polylang->links_model;
$this->model = &$polylang->model;
$this->options = &$polylang->options;
$this->curlang = &$polylang->curlang;
}
/**
* sets the language for ajax requests
* and setup actions
* any child class must call this method if it overrides it
*
* @since 1.8
*/
public function init() {
if ( PLL_AJAX_ON_FRONT || false === stripos( $_SERVER['SCRIPT_FILENAME'], 'index.php' ) ) {
$this->set_language( empty( $_REQUEST['lang'] ) ? $this->get_preferred_language() : $this->model->get_language( $_REQUEST['lang'] ) );
}
add_action( 'pre_comment_on_post', array( &$this, 'pre_comment_on_post' ) ); // sets the language of comment
add_action( 'parse_query', array( &$this, 'parse_main_query' ), 2 ); // sets the language in special cases
}
/**
* writes language cookie
* loads user defined translations
* fires the action 'pll_language_defined'
*
* @since 1.2
*
* @param object $curlang current language
*/
protected function set_language( $curlang ) {
// don't set the language a second time
if ( isset( $this->curlang ) ) {
return;
}
// final check in case $curlang has an unexpected value
// see https://wordpress.org/support/topic/detect-browser-language-sometimes-setting-null-language
$this->curlang = ( $curlang instanceof PLL_Language ) ? $curlang : $this->model->get_language( $this->options['default_lang'] );
$this->maybe_setcookie();
$GLOBALS['text_direction'] = $this->curlang->is_rtl ? 'rtl' : 'ltr';
/**
* Fires when the current language is defined
*
* @since 0.9.5
*
* @param string $slug current language code
* @param object $curlang current language object
*/
do_action( 'pll_language_defined', $this->curlang->slug, $this->curlang );
}
/**
* set a cookie to remember the language.
* possibility to set PLL_COOKIE to false will disable cookie although it will break some functionalities
*
* @since 1.5
*/
protected function maybe_setcookie() {
// check headers have not been sent to avoid ugly error
// cookie domain must be set to false for localhost ( default value for COOKIE_DOMAIN ) thanks to Stephen Harris.
if ( ! headers_sent() && PLL_COOKIE !== false && ( ! isset( $_COOKIE[ PLL_COOKIE ] ) || $_COOKIE[ PLL_COOKIE ] != $this->curlang->slug ) ) {
/**
* Filter the Polylang cookie duration
*
* @since 1.8
*
* @param int $duration cookie duration in seconds
*/
$expiration = apply_filters( 'pll_cookie_expiration', YEAR_IN_SECONDS );
setcookie(
PLL_COOKIE,
$this->curlang->slug,
time() + $expiration,
COOKIEPATH,
2 == $this->options['force_lang'] ? parse_url( $this->links_model->home, PHP_URL_HOST ) : COOKIE_DOMAIN
);
}
}
/**
* get the preferred language according to the browser preferences
* code adapted from http://www.thefutureoftheweb.com/blog/use-accept-language-header
*
* @since 1.8
*
* @return string|bool the preferred language slug or false
*/
public function get_preferred_browser_language() {
$accept_langs = array();
if ( isset( $_SERVER['HTTP_ACCEPT_LANGUAGE'] ) ) {
// break up string into pieces ( languages and q factors )
preg_match_all( '/([a-z]{1,8}(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*( 1|0\.[0-9]+))?/i', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $lang_parse );
$k = $lang_parse[1];
$v = $lang_parse[4];
if ( $n = count( $k ) ) {
// set default to 1 for any without q factor
foreach ( $v as $key => $val ) {
if ( '' === $val ) {
$v[ $key ] = 1;
}
}
// bubble sort ( need a stable sort for Android, so can't use a PHP sort function )
if ( $n > 1 ) {
for ( $i = 2; $i <= $n; $i++ ) {
for ( $j = 0; $j <= $n - 2; $j++ ) {
if ( $v[ $j ] < $v[ $j + 1 ] ) {
// swap values
$temp = $v[ $j ];
$v[ $j ] = $v[ $j + 1 ];
$v[ $j + 1 ] = $temp;
//swap keys
$temp = $k[ $j ];
$k[ $j ] = $k[ $j + 1 ];
$k[ $j + 1 ] = $temp;
}
}
}
}
$accept_langs = array_combine( $k,$v );
}
}
// looks through sorted list and use first one that matches our language list
$listlanguages = $this->model->get_languages_list( array( 'hide_empty' => true ) ); // hides languages with no post
foreach ( array_keys( $accept_langs ) as $accept_lang ) {
// first loop to match the exact locale
foreach ( $listlanguages as $language ) {
if ( 0 === strcasecmp( $accept_lang, $language->get_locale( 'display' ) ) ) {
return $language->slug;
}
}
// second loop to match the language set
foreach ( $listlanguages as $language ) {
if ( 0 === stripos( $accept_lang, $language->slug ) || 0 === stripos( $language->get_locale( 'display' ), $accept_lang ) ) {
return $language->slug;
}
}
}
return false;
}
/**
* returns the language according to browser preference or the default language
*
* @since 0.1
*
* @return object browser preferred language or default language
*/
public function get_preferred_language() {
// check first if the user was already browsing this site
if ( isset( $_COOKIE[ PLL_COOKIE ] ) ) {
return $this->model->get_language( $_COOKIE[ PLL_COOKIE ] );
}
/**
* Filter the visitor's preferred language (normally set first by cookie
* if this is not the first visit, then by the browser preferences).
* If no preferred language has been found or set by this filter,
* Polylang fallbacks to the default language
*
* @since 1.0
*
* @param string $language preferred language code
*/
$slug = apply_filters( 'pll_preferred_language', $this->options['browser'] ? $this->get_preferred_browser_language() : false );
// return default if there is no preferences in the browser or preferences does not match our languages or it is requested not to use the browser preference
return ( $lang = $this->model->get_language( $slug ) ) ? $lang : $this->model->get_language( $this->options['default_lang'] );
}
/**
* sets the language when home page is resquested
*
* @since 1.2
*/
protected function home_language() {
// test referer in case PLL_COOKIE is set to false
// thanks to Ov3rfly http://wordpress.org/support/topic/enhance-feature-when-front-page-is-visited-set-language-according-to-browser
$language = $this->options['hide_default'] && ( ( isset( $_SERVER['HTTP_REFERER'] ) && in_array( parse_url( $_SERVER['HTTP_REFERER'], PHP_URL_HOST ), $this->links_model->get_hosts() ) ) || ! $this->options['browser'] ) ?
$this->model->get_language( $this->options['default_lang'] ) :
$this->get_preferred_language(); // sets the language according to browser preference or default language
$this->set_language( $language );
}
/**
* to call when the home page has been requested
* make sure to call this after 'setup_theme' has been fired as we need $wp_query
* performs a redirection to the home page in the current language if needed
*
* @since 0.9
*/
public function home_requested() {
// we are already on the right page
if ( $this->options['default_lang'] == $this->curlang->slug && $this->options['hide_default'] ) {
$this->set_lang_query_var( $GLOBALS['wp_query'], $this->curlang );
/**
* Fires when the site root page is requested
*
* @since 1.8
*/
do_action( 'pll_home_requested' );
}
// redirect to the home page in the right language
// test to avoid crash if get_home_url returns something wrong
// FIXME why this happens? http://wordpress.org/support/topic/polylang-crashes-1
// don't redirect if $_POST is not empty as it could break other plugins
// don't forget the query string which may be added by plugins
elseif ( is_string( $redirect = $this->curlang->home_url ) && empty( $_POST ) ) {
$redirect = empty( $_SERVER['QUERY_STRING'] ) ? $redirect : $redirect . ( $this->links_model->using_permalinks ? '?' : '&' ) . $_SERVER['QUERY_STRING'];
/**
* When a visitor reaches the site home, Polylang redirects to the home page in the correct language.
* This filter allows plugins to modify the redirected url or prevent this redirection
*
* @since 1.1.1
*
* @param string $redirect the url the visitor will be redirected to
*/
if ( $redirect = apply_filters( 'pll_redirect_home', $redirect ) ) {
wp_redirect( $redirect );
exit;
}
}
}
/**
* set the language when posting a comment
*
* @since 0.8.4
*
* @param int $post_id the post beeing commented
*/
public function pre_comment_on_post( $post_id ) {
$this->set_language( $this->model->post->get_language( $post_id ) );
}
/**
* modifies some main query vars for home page and page for posts
* to enable one home page ( and one page for posts ) per language
*
* @since 1.2
*
* @param object $query instance of WP_Query
*/
public function parse_main_query( $query ) {
if ( ! $query->is_main_query() ) {
return;
}
/**
* This filter allows to set the language based on information contained in the main query
*
* @since 1.8
*
* @param bool|object $lang false or language object
* @param object $query WP_Query object
*/
if ( $lang = apply_filters( 'pll_set_language_from_query', false, $query ) ) {
$this->set_language( $lang );
$this->set_lang_query_var( $query, $this->curlang );
}
// sets is_home on translated home page when it displays posts
// is_home must be true on page 2, 3... too
// as well as when searching an empty string: http://wordpress.org/support/topic/plugin-polylang-polylang-breaks-search-in-spun-theme
if ( 'posts' == get_option( 'show_on_front' ) && ( count( $query->query ) == 1 || ( is_paged() && count( $query->query ) == 2 ) || ( isset( $query->query['s'] ) && ! $query->query['s'] ) ) && $lang = get_query_var( 'lang' ) ) {
$lang = $this->model->get_language( $lang );
$this->set_language( $lang ); // sets the language now otherwise it will be too late to filter sticky posts !
$query->is_home = true;
$query->is_archive = $query->is_tax = false;
}
}
/**
* sets the language in query
* optimized for ( needs ) WP 3.5+
*
* @since 1.3
*/
public function set_lang_query_var( &$query, $lang ) {
// defining directly the tax_query ( rather than setting 'lang' avoids transforming the query by WP )
$query->query_vars['tax_query'][] = array(
'taxonomy' => 'language',
'field' => 'term_taxonomy_id', // since WP 3.5
'terms' => $lang->term_taxonomy_id,
'operator' => 'IN',
);
}
}
| petersondrs/interage-consultoria | wp-content/plugins/polylang/frontend/choose-lang.php | PHP | gpl-2.0 | 10,845 |
// -*- C++ -*-
// Copyright (C) 2005-2017 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library 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, or (at your option) any later
// version.
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
// Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL.
// Permission to use, copy, modify, sell, and distribute this software
// is hereby granted without fee, provided that the above copyright
// notice appears in all copies, and that both that copyright notice
// and this permission notice appear in supporting documentation. None
// of the above authors, nor IBM Haifa Research Laboratories, make any
// representation about the suitability of this software for any
// purpose. It is provided "as is" without express or implied
// warranty.
/**
* @file native_tree_tag.hpp
* Contains a tag for native tree-based containers
*/
#ifndef PB_DS_NATIVE_TREE_DS_TAG_HPP
#define PB_DS_NATIVE_TREE_DS_TAG_HPP
namespace __gnu_pbds
{
namespace test
{
struct native_tree_tag
{ };
} // namespace test
} // namespace __gnu_pbds
#endif
| mickael-guene/gcc | libstdc++-v3/testsuite/util/native_type/native_tree_tag.hpp | C++ | gpl-2.0 | 1,637 |
// license:BSD-3-Clause
// copyright-holders:Bryan McPhail
/***************************************************************************
Desert Assault Video emulation - Bryan McPhail, mish@tendril.co.uk
I'm not sure if one of the alpha blending effects is correct (mode 0x8000,
the usual mode 0x4000 should be correct). It may be some kind of orthogonal
priority effect where it should cut a hole in other higher priority sprites
to reveal a non-alpha'd hole, or alpha against a further back tilemap.
(is this the helicopter shadow at the end of lv.1 ?)
Also, some priorities are still a little questionable.
****************************************************************************/
#include "emu.h"
#include "includes/dassault.h"
/******************************************************************************/
void dassault_state::video_start()
{
m_sprgen1->alloc_sprite_bitmap();
m_sprgen2->alloc_sprite_bitmap();
}
void dassault_state::mixdassaultlayer(bitmap_rgb32 &bitmap, bitmap_ind16* sprite_bitmap, const rectangle &cliprect, UINT16 pri, UINT16 primask, UINT16 penbase, UINT8 alpha)
{
int y, x;
const pen_t *paldata = &m_palette->pen(0);
UINT16* srcline;
UINT32* dstline;
for (y=cliprect.min_y;y<=cliprect.max_y;y++)
{
srcline=&sprite_bitmap->pix16(y,0);
dstline=&bitmap.pix32(y,0);
for (x=cliprect.min_x;x<=cliprect.max_x;x++)
{
UINT16 pix = srcline[x];
if ((pix & primask) != pri)
continue;
if (pix&0xf)
{
UINT16 pen = pix&0x1ff;
if (pix & 0x800) pen += 0x200;
if (alpha!=0xff)
{
if (pix&0x600)
{
UINT32 base = dstline[x];
dstline[x] = alpha_blend_r32(base, paldata[pen+penbase], alpha);
}
else
{
dstline[x] = paldata[pen+penbase];
}
}
else
{
dstline[x] = paldata[pen+penbase];
}
}
}
}
}
/* are the priorities 100% correct? they're the same as they were before conversion to DECO52 sprite device, but if (for example) you walk to the side of the crates in the first part of the game you appear over them... */
UINT32 dassault_state::screen_update_dassault(screen_device &screen, bitmap_rgb32 &bitmap, const rectangle &cliprect)
{
address_space &space = machine().driver_data()->generic_space();
UINT16 flip = m_deco_tilegen1->pf_control_r(space, 0, 0xffff);
UINT16 priority = m_decocomn->priority_r(space, 0, 0xffff);
m_sprgen2->draw_sprites(bitmap, cliprect, m_spriteram2->buffer(), 0x400, false);
m_sprgen1->draw_sprites(bitmap, cliprect, m_spriteram->buffer(), 0x400, false);
bitmap_ind16* sprite_bitmap1 = &m_sprgen1->get_sprite_temp_bitmap();
bitmap_ind16* sprite_bitmap2 = &m_sprgen2->get_sprite_temp_bitmap();
/* Update tilemaps */
flip_screen_set(BIT(flip, 7));
m_deco_tilegen1->pf_update(nullptr, m_pf2_rowscroll);
m_deco_tilegen2->pf_update(nullptr, m_pf4_rowscroll);
/* Draw playfields/update priority bitmap */
screen.priority().fill(0, cliprect);
bitmap.fill(m_palette->pen(3072), cliprect);
m_deco_tilegen2->tilemap_2_draw(screen, bitmap, cliprect, TILEMAP_DRAW_OPAQUE, 0);
/* The middle playfields can be swapped priority-wise */
if ((priority & 3) == 0)
{
mixdassaultlayer(bitmap, sprite_bitmap1, cliprect, 0x0600, 0x0600, 0x400, 0xff); // 1
m_deco_tilegen1->tilemap_2_draw(screen, bitmap, cliprect, 0, 2); // 2
mixdassaultlayer(bitmap, sprite_bitmap1, cliprect, 0x0400, 0x0600, 0x400, 0xff); // 8
m_deco_tilegen2->tilemap_1_draw(screen, bitmap, cliprect, 0, 16); // 16
mixdassaultlayer(bitmap, sprite_bitmap1, cliprect, 0x0200, 0x0600, 0x400, 0xff); // 32
mixdassaultlayer(bitmap, sprite_bitmap2, cliprect, 0x0000, 0x0000, 0x800, 0x80); // 64?
mixdassaultlayer(bitmap, sprite_bitmap1, cliprect, 0x0000, 0x0600, 0x400, 0xff); // 128
}
else if ((priority & 3) == 1)
{
mixdassaultlayer(bitmap, sprite_bitmap1, cliprect, 0x0600, 0x0600, 0x400, 0xff); // 1
m_deco_tilegen2->tilemap_1_draw(screen, bitmap, cliprect, 0, 2); // 2
mixdassaultlayer(bitmap, sprite_bitmap1, cliprect, 0x0400, 0x0600, 0x400, 0xff); // 8
mixdassaultlayer(bitmap, sprite_bitmap2, cliprect, 0x0000, 0x0000, 0x800, 0x80); // 16?
mixdassaultlayer(bitmap, sprite_bitmap1, cliprect, 0x0200, 0x0600, 0x400, 0xff); // 32
m_deco_tilegen1->tilemap_2_draw(screen, bitmap, cliprect, 0, 64); // 64
mixdassaultlayer(bitmap, sprite_bitmap1, cliprect, 0x0000, 0x0600, 0x400, 0xff); // 128
}
else if ((priority & 3) == 3)
{
mixdassaultlayer(bitmap, sprite_bitmap1, cliprect, 0x0600, 0x0600, 0x400, 0xff); // 1
m_deco_tilegen2->tilemap_1_draw(screen, bitmap, cliprect, 0, 2); // 2
mixdassaultlayer(bitmap, sprite_bitmap1, cliprect, 0x0400, 0x0600, 0x400, 0xff); // 8
m_deco_tilegen1->tilemap_2_draw(screen, bitmap, cliprect, 0, 16); // 16
mixdassaultlayer(bitmap, sprite_bitmap1, cliprect, 0x0200, 0x0600, 0x400, 0xff); // 32
mixdassaultlayer(bitmap, sprite_bitmap2, cliprect, 0x0000, 0x0000, 0x800, 0x80); // 64?
mixdassaultlayer(bitmap, sprite_bitmap1, cliprect, 0x0000, 0x0600, 0x400, 0xff); // 128
}
else
{
/* Unused */
}
m_deco_tilegen1->tilemap_1_draw(screen, bitmap, cliprect, 0, 0);
return 0;
}
| GiuseppeGorgoglione/mame | src/mame/video/dassault.cpp | C++ | gpl-2.0 | 5,152 |
/***************************************************************************
tag: Peter Soetens Wed Apr 17 16:01:31 CEST 2002 TimerThread.cpp
TimerThread.cpp - description
-------------------
begin : Wed April 17 2002
copyright : (C) 2002 Peter Soetens
email : peter.soetens@mech.kuleuven.ac.be
***************************************************************************
* This library 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; *
* version 2 of the License. *
* *
* As a special exception, you may use this file as part of a free *
* software library without restriction. Specifically, if other files *
* instantiate templates or use macros or inline functions from this *
* file, or you compile this file and link it with other files to *
* produce an executable, this file does not by itself cause the *
* resulting executable to be covered by the GNU General Public *
* License. This exception does not however invalidate any other *
* reasons why the executable file might be covered by the GNU General *
* Public License. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307 USA *
* *
***************************************************************************/
#include "TimerThread.hpp"
#include "PeriodicActivity.hpp"
#include "rtt-config.h"
#include "../Time.hpp"
#include "../Logger.hpp"
#include <algorithm>
#include "../os/MutexLock.hpp"
namespace RTT {
using namespace extras;
using namespace base;
using os::MutexLock;
using namespace std;
TimerThread::TimerThreadList TimerThread::TimerThreads;
TimerThreadPtr TimerThread::Instance(int pri, double per)
{
return Instance(ORO_SCHED_RT, pri, per);
}
TimerThreadPtr TimerThread::Instance(int scheduler, int pri, double per)
{
return Instance(scheduler, pri, per, ~0);
}
TimerThreadPtr TimerThread::Instance(int scheduler, int pri, double per, unsigned cpu_affinity)
{
// Since the period is stored as nsecs, we convert per to NS in order
// to get a match.
os::CheckPriority(scheduler, pri);
TimerThreadList::iterator it = TimerThreads.begin();
while ( it != TimerThreads.end() ) {
TimerThreadPtr tptr = it->lock();
// detect old pointer.
if ( !tptr ) {
TimerThreads.erase(it);
it = TimerThreads.begin();
continue;
}
if ( tptr->getScheduler() == scheduler && tptr->getPriority() == pri && tptr->getPeriodNS() == Seconds_to_nsecs(per) ) {
return tptr;
}
++it;
}
TimerThreadPtr ret( new TimerThread(scheduler, pri, "TimerThreadInstance", per, cpu_affinity) );
TimerThreads.push_back( ret );
return ret;
}
TimerThread::TimerThread(int priority, const std::string& name, double periodicity, unsigned cpu_affinity)
: Thread( ORO_SCHED_RT, priority, periodicity, cpu_affinity, name), cleanup(false)
{
tasks.reserve(MAX_ACTIVITIES);
}
TimerThread::TimerThread(int scheduler, int priority, const std::string& name, double periodicity, unsigned cpu_affinity)
: Thread(scheduler, priority, periodicity, cpu_affinity, name), cleanup(false)
{
tasks.reserve(MAX_ACTIVITIES);
}
TimerThread::~TimerThread()
{
// make sure the thread does not run when we start deleting clocks...
this->stop();
}
bool TimerThread::addActivity( PeriodicActivity* t ) {
MutexLock lock(mutex);
if ( tasks.size() == MAX_ACTIVITIES ) {
// Logger::log() << Logger:: << "TimerThread : tasks queue full, failed to add Activity : "<< t << Logger::endl;
return false;
}
tasks.push_back( t );
// Logger::log() << Logger::Debug << "TimerThread : successfully started Activity : "<< t << Logger::endl;
return true;
}
bool TimerThread::removeActivity( PeriodicActivity* t ) {
MutexLock lock(mutex);
ActivityList::iterator it = find(tasks.begin(), tasks.end(), t);
if ( it != tasks.end() ) {
*it = 0; // clear task away
cleanup = true;
return true;
}
// Logger::log() << Logger::Debug << "TimerThread : failed to stop Activity : "<< t->getPeriod() << Logger::endl;
return false;
}
bool TimerThread::initialize() {
return true;
}
void TimerThread::finalize() {
MutexLock lock(mutex);
for( ActivityList::iterator t_iter = tasks.begin(); t_iter != tasks.end(); ++t_iter)
if ( *t_iter )
(*t_iter)->stop(); // stop() calls us back to removeActivity (recursive mutex).
if ( cleanup )
this->reorderList();
}
void TimerThread::step() {
MutexLock lock(mutex);
// The size of the tasks vector does not change during add/remove, thus
// t_iter is never invalidated.
for( ActivityList::iterator t_iter = tasks.begin(); t_iter != tasks.end(); ++t_iter)
if ( *t_iter )
(*t_iter)->step();
if ( cleanup )
this->reorderList();
}
void TimerThread::reorderList() {
// reorder the list to remove clear'ed tasks
ActivityList::iterator begin = tasks.begin();
// first zero :
PeriodicActivity* nullActivity = 0;
ActivityList::iterator it = tasks.begin();
it = find( tasks.begin(), tasks.end(), nullActivity); // First zero
begin = it+1;
while ( it != tasks.end() ) {
// Look for first non-zero after 'it' :
while ( begin != tasks.end() && *begin == 0 )
++begin;
if ( begin == tasks.end() ) { // if no task found after zero :
// Logger::log() << Logger::Error << "beginBefore resize :"<< tasks.size() << Logger::endl;
tasks.resize( it - tasks.begin() ); // cut out the items after 'it'
// Logger::log() << Logger::Error << "beginAfter resize :"<< tasks.size() << Logger::endl;
break; // This is our exit condition !
}
// first zero after begin :
ActivityList::iterator end = find ( begin, tasks.end(), nullActivity);
// if end == tasks.end() ==> next while will copy all
// if end != tasks.end() ==> next while will copy first zero's
while ( begin != end ) {
*it = *begin; // copy operation
++begin;
++it; // go to next slot to inspect.
}
}
cleanup = false;
}
}
| shyamalschandra/rtt | rtt/extras/TimerThread.cpp | C++ | gpl-2.0 | 7,933 |
/*
* #%L
* Bio-Formats Plugins for ImageJ: a collection of ImageJ plugins including the
* Bio-Formats Importer, Bio-Formats Exporter, Bio-Formats Macro Extensions,
* Data Browser and Stack Slicer.
* %%
* Copyright (C) 2006 - 2015 Open Microscopy Environment:
* - Board of Regents of the University of Wisconsin-Madison
* - Glencoe Software, Inc.
* - University of Dundee
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
package loci.plugins.util;
import ij.IJ;
import ij.ImageJ;
import ij.gui.GenericDialog;
import java.awt.BorderLayout;
import java.awt.Checkbox;
import java.awt.Choice;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Panel;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.ScrollPane;
import java.awt.TextField;
import java.awt.Toolkit;
import java.awt.Window;
import java.util.List;
import java.util.StringTokenizer;
import loci.common.DebugTools;
import loci.plugins.BF;
/**
* Utility methods for managing ImageJ dialogs and windows.
*/
public final class WindowTools {
// -- Constructor --
private WindowTools() { }
// -- Utility methods --
/** Adds AWT scroll bars to the given container. */
public static void addScrollBars(Container pane) {
GridBagLayout layout = (GridBagLayout) pane.getLayout();
// extract components
int count = pane.getComponentCount();
Component[] c = new Component[count];
GridBagConstraints[] gbc = new GridBagConstraints[count];
for (int i=0; i<count; i++) {
c[i] = pane.getComponent(i);
gbc[i] = layout.getConstraints(c[i]);
}
// clear components
pane.removeAll();
layout.invalidateLayout(pane);
// create new container panel
Panel newPane = new Panel();
GridBagLayout newLayout = new GridBagLayout();
newPane.setLayout(newLayout);
for (int i=0; i<count; i++) {
newLayout.setConstraints(c[i], gbc[i]);
newPane.add(c[i]);
}
// HACK - get preferred size for container panel
// NB: don't know a better way:
// - newPane.getPreferredSize() doesn't work
// - newLayout.preferredLayoutSize(newPane) doesn't work
Frame f = new Frame();
f.setLayout(new BorderLayout());
f.add(newPane, BorderLayout.CENTER);
f.pack();
final Dimension size = newPane.getSize();
f.remove(newPane);
f.dispose();
// compute best size for scrollable viewport
size.width += 25;
size.height += 15;
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
int maxWidth = 7 * screen.width / 8;
int maxHeight = 3 * screen.height / 4;
if (size.width > maxWidth) size.width = maxWidth;
if (size.height > maxHeight) size.height = maxHeight;
// create scroll pane
ScrollPane scroll = new ScrollPane() {
@Override
public Dimension getPreferredSize() {
return size;
}
};
scroll.add(newPane);
// add scroll pane to original container
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridwidth = GridBagConstraints.REMAINDER;
constraints.fill = GridBagConstraints.BOTH;
constraints.weightx = 1.0;
constraints.weighty = 1.0;
layout.setConstraints(scroll, constraints);
pane.add(scroll);
}
/**
* Places the given window at a nice location on screen, either centered
* below the ImageJ window if there is one, or else centered on screen.
*/
public static void placeWindow(Window w) {
Dimension size = w.getSize();
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
ImageJ ij = IJ.getInstance();
Point p = new Point();
if (ij == null) {
// center config window on screen
p.x = (screen.width - size.width) / 2;
p.y = (screen.height - size.height) / 2;
}
else {
// place config window below ImageJ window
Rectangle ijBounds = ij.getBounds();
p.x = ijBounds.x + (ijBounds.width - size.width) / 2;
p.y = ijBounds.y + ijBounds.height + 5;
}
// nudge config window away from screen edges
final int pad = 10;
if (p.x < pad) p.x = pad;
else if (p.x + size.width + pad > screen.width) {
p.x = screen.width - size.width - pad;
}
if (p.y < pad) p.y = pad;
else if (p.y + size.height + pad > screen.height) {
p.y = screen.height - size.height - pad;
}
w.setLocation(p);
}
/** Reports the given exception with stack trace in an ImageJ error dialog. */
public static void reportException(Throwable t) {
reportException(t, false, null);
}
/** Reports the given exception with stack trace in an ImageJ error dialog. */
public static void reportException(Throwable t, boolean quiet) {
reportException(t, quiet, null);
}
/** Reports the given exception with stack trace in an ImageJ error dialog. */
public static void reportException(Throwable t, boolean quiet, String msg) {
if (quiet) return;
BF.status(quiet, "");
if (t != null) {
String s = DebugTools.getStackTrace(t);
StringTokenizer st = new StringTokenizer(s, "\n\r");
while (st.hasMoreTokens()) IJ.log(st.nextToken());
}
if (msg != null) IJ.error("Bio-Formats Importer", msg);
}
@SuppressWarnings("unchecked")
public static List<TextField> getNumericFields(GenericDialog gd) {
return gd.getNumericFields();
}
@SuppressWarnings("unchecked")
public static List<Checkbox> getCheckboxes(GenericDialog gd) {
return gd.getCheckboxes();
}
@SuppressWarnings("unchecked")
public static List<Choice> getChoices(GenericDialog gd) {
return gd.getChoices();
}
}
| dgault/bioformats | components/bio-formats-plugins/src/loci/plugins/util/WindowTools.java | Java | gpl-2.0 | 6,353 |
<?php
/**
* @package Joomla.Administrator
* @subpackage Template.hathor
*
* @copyright (C) 2010 Open Source Matters, Inc. <https://www.joomla.org>
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
$listOrder = $this->escape($this->state->get('list.ordering'));
$listDirn = $this->escape($this->state->get('list.direction'));
?>
<form action="<?php echo JRoute::_('index.php?option=com_cache'); ?>" method="post" name="adminForm" id="adminForm">
<?php if (!empty( $this->sidebar)) : ?>
<div id="j-sidebar-container" class="span2">
<?php echo $this->sidebar; ?>
</div>
<div id="j-main-container" class="span10">
<?php else : ?>
<div id="j-main-container">
<?php endif;?>
<fieldset id="filter-bar">
<legend class="element-invisible"><?php echo JText::_('JSEARCH_FILTER_LABEL'); ?></legend>
<div class="filter-select fltrt">
<label class="selectlabel" for="client_id">
<?php echo JText::_('COM_CACHE_SELECT_CLIENT'); ?>
</label>
<select name="client_id" id="client_id">
<?php echo JHtml::_('select.options', CacheHelper::getClientOptions(), 'value', 'text', $this->state->get('client_id'));?>
</select>
<button type="submit" id="filter-go">
<?php echo JText::_('JSUBMIT'); ?></button>
</div>
</fieldset>
<div class="clr"> </div>
<table class="adminlist">
<thead>
<tr>
<th class="checkmark-col">
<input type="checkbox" name="checkall-toggle" value="" title="<?php echo JText::_('JGLOBAL_CHECK_ALL'); ?>" onclick="Joomla.checkAll(this)" />
</th>
<th class="title nowrap">
<?php echo JHtml::_('grid.sort', 'COM_CACHE_GROUP', 'group', $listDirn, $listOrder); ?>
</th>
<th class="width-5 center nowrap">
<?php echo JHtml::_('grid.sort', 'COM_CACHE_NUMBER_OF_FILES', 'count', $listDirn, $listOrder); ?>
</th>
<th class="width-10 center">
<?php echo JHtml::_('grid.sort', 'COM_CACHE_SIZE', 'size', $listDirn, $listOrder); ?>
</th>
</tr>
</thead>
<tbody>
<?php
$i = 0;
foreach ($this->data as $folder => $item) : ?>
<tr class="row<?php echo $i % 2; ?>">
<td>
<input type="checkbox" id="cb<?php echo $i;?>" name="cid[]" value="<?php echo $item->group; ?>" onclick="Joomla.isChecked(this.checked);" />
</td>
<td>
<span class="bold">
<?php echo $item->group; ?>
</span>
</td>
<td class="center">
<?php echo $item->count; ?>
</td>
<td class="center">
<?php echo JHtml::_('number.bytes', $item->size*1024); ?>
</td>
</tr>
<?php $i++; endforeach; ?>
</tbody>
</table>
<?php echo $this->pagination->getListFooter(); ?>
<input type="hidden" name="task" value="" />
<input type="hidden" name="boxchecked" value="0" />
<input type="hidden" name="client" value="<?php echo $this->client->id;?>" />
<input type="hidden" name="filter_order" value="<?php echo $listOrder; ?>" />
<input type="hidden" name="filter_order_Dir" value="<?php echo $listDirn; ?>" />
<?php echo JHtml::_('form.token'); ?>
</div>
</form>
| zero-24/joomla-cms | administrator/templates/hathor/html/com_cache/cache/default.php | PHP | gpl-2.0 | 3,019 |
jQuery.fn.nextInArray = function(element) {
var nextId = 0;
for(var i = 0; i < this.length; i++) {
if(this[i] == element) {
nextId = i + 1;
break;
}
}
if(nextId > this.length-1)
nextId = 0;
return this[nextId];
};
jQuery.fn.clearForm = function() {
return this.each(function() {
var type = this.type, tag = this.tagName.toLowerCase();
if (tag == 'form')
return jQuery(':input', this).clearForm();
if (type == 'text' || type == 'password' || tag == 'textarea')
this.value = '';
else if (type == 'checkbox' || type == 'radio')
this.checked = false;
else if (tag == 'select')
this.selectedIndex = -1;
});
};
jQuery.fn.tagName = function() {
return this.get(0).tagName;
};
jQuery.fn.exists = function(){
return (jQuery(this).size() > 0 ? true : false);
};
function isNumber(val) {
return /^\d+/.test(val);
}
jQuery.fn.serializeAnything = function(addData) {
var toReturn = [];
var els = jQuery(this).find(':input').get();
jQuery.each(els, function() {
if (this.name && !this.disabled && (this.checked || /select|textarea/i.test(this.nodeName) || /text|hidden|password/i.test(this.type))) {
var val = jQuery(this).val();
toReturn.push( encodeURIComponent(this.name) + "=" + encodeURIComponent( val ) );
}
});
if(typeof(addData) != 'undefined') {
for(var key in addData)
toReturn.push(key + "=" + addData[key]);
}
return toReturn.join("&").replace(/%20/g, "+");
};
jQuery.fn.hasScrollBarH = function() {
return this.get(0).scrollHeight > this.height();
};
jQuery.fn.hasScrollBarV = function() {
console.log(this.get(0).scrollWidth, this.width(), this.get(0).scrollHeight, this.height());
return this.get(0).scrollWidth > this.width();
};
function str_replace(haystack, needle, replacement) {
var temp = haystack.split(needle);
return temp.join(replacement);
}
/**
* @see php html::nameToClassId($name) method
**/
function nameToClassId(name) {
return str_replace(
str_replace(name, ']', ''),
'[', ''
);
}
function strpos( haystack, needle, offset){
var i = haystack.indexOf( needle, offset ); // returns -1
return i >= 0 ? i : false;
}
function extend(Child, Parent) {
var F = function() { };
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
Child.superclass = Parent.prototype;
}
function toeRedirect(url) {
document.location.href = url;
}
function toeReload() {
document.location.reload();
}
jQuery.fn.toeRebuildSelect = function(data, useIdAsValue, val) {
if(jQuery(this).tagName() == 'SELECT' && typeof(data) == 'object') {
if(jQuery(data).size() > 0) {
if(typeof(val) == 'undefined')
val = false;
if(jQuery(this).children('option').length) {
jQuery(this).children('option').remove();
}
if(typeof(useIdAsValue) == 'undefined')
useIdAsValue = false;
var selected = '';
for(var id in data) {
selected = '';
if(val && ((useIdAsValue && id == val) || (data[id] == val)))
selected = 'selected';
jQuery(this).append('<option value="'+ (useIdAsValue ? id : data[id])+ '" '+ selected+ '>'+ data[id]+ '</option>');
}
}
}
}
/**
* We will not use just jQUery.inArray because it is work incorrect for objects
* @return mixed - key that was found element or -1 if not
*/
function toeInArray(needle, haystack) {
if(typeof(haystack) == 'object') {
for(var k in haystack) {
if(haystack[ k ] == needle)
return k;
}
} else if(typeof(haystack) == 'array') {
return jQuery.inArray(needle, haystack);
}
return -1;
}
jQuery.fn.setReadonly = function() {
jQuery(this).addClass('toeReadonly').attr('readonly', 'readonly');
}
jQuery.fn.unsetReadonly = function() {
jQuery(this).removeClass('toeReadonly').removeAttr('readonly', 'readonly');
}
jQuery.fn.getClassId = function(pref, test) {
var classId = jQuery(this).attr('class');
classId = classId.substr( strpos(classId, pref+ '_') );
if(strpos(classId, ' '))
classId = classId.substr( 0, strpos(classId, ' ') );
classId = classId.split('_');
classId = classId[1];
return classId;
}
function toeTextIncDec(textFieldId, inc) {
var value = parseInt(jQuery('#'+ textFieldId).val());
if(isNaN(value))
value = 0;
if(!(inc < 0 && value < 1)) {
value += inc;
}
jQuery('#'+ textFieldId).val(value);
}
/**
* Make first letter of string in upper case
* @param str string - string to convert
* @return string converted string - first letter in upper case
*/
function toeStrFirstUp(str) {
str += '';
var f = str.charAt(0).toUpperCase();
return f + str.substr(1);
}
function parseStr (str, array) {
// http://kevin.vanzonneveld.net
// + original by: Cagri Ekin
// + improved by: Michael White (http://getsprink.com)
// + tweaked by: Jack
// + bugfixed by: Onno Marsman
// + reimplemented by: stag019
// + bugfixed by: Brett Zamir (http://brett-zamir.me)
// + bugfixed by: stag019
// + input by: Dreamer
// + bugfixed by: Brett Zamir (http://brett-zamir.me)
// + bugfixed by: MIO_KODUKI (http://mio-koduki.blogspot.com/)
// + input by: Zaide (http://zaidesthings.com/)
// + input by: David Pesta (http://davidpesta.com/)
// + input by: jeicquest
// + improved by: Brett Zamir (http://brett-zamir.me)
// % note 1: When no argument is specified, will put variables in global scope.
// % note 1: When a particular argument has been passed, and the returned value is different parse_str of PHP. For example, a=b=c&d====c
// * example 1: var arr = {};
// * example 1: parse_str('first=foo&second=bar', arr);
// * results 1: arr == { first: 'foo', second: 'bar' }
// * example 2: var arr = {};
// * example 2: parse_str('str_a=Jack+and+Jill+didn%27t+see+the+well.', arr);
// * results 2: arr == { str_a: "Jack and Jill didn't see the well." }
// * example 3: var abc = {3:'a'};
// * example 3: parse_str('abc[a][b]["c"]=def&abc[q]=t+5');
// * results 3: JSON.stringify(abc) === '{"3":"a","a":{"b":{"c":"def"}},"q":"t 5"}';
var strArr = String(str).replace(/^&/, '').replace(/&$/, '').split('&'),
sal = strArr.length,
i, j, ct, p, lastObj, obj, lastIter, undef, chr, tmp, key, value,
postLeftBracketPos, keys, keysLen,
fixStr = function (str) {
return decodeURIComponent(str.replace(/\+/g, '%20'));
};
// Comented by Alexey Bolotov
/*
if (!array) {
array = this.window;
}*/
if (!array) {
array = {};
}
for (i = 0; i < sal; i++) {
tmp = strArr[i].split('=');
key = fixStr(tmp[0]);
value = (tmp.length < 2) ? '' : fixStr(tmp[1]);
while (key.charAt(0) === ' ') {
key = key.slice(1);
}
if (key.indexOf('\x00') > -1) {
key = key.slice(0, key.indexOf('\x00'));
}
if (key && key.charAt(0) !== '[') {
keys = [];
postLeftBracketPos = 0;
for (j = 0; j < key.length; j++) {
if (key.charAt(j) === '[' && !postLeftBracketPos) {
postLeftBracketPos = j + 1;
} else if (key.charAt(j) === ']') {
if (postLeftBracketPos) {
if (!keys.length) {
keys.push(key.slice(0, postLeftBracketPos - 1));
}
keys.push(key.substr(postLeftBracketPos, j - postLeftBracketPos));
postLeftBracketPos = 0;
if (key.charAt(j + 1) !== '[') {
break;
}
}
}
}
if (!keys.length) {
keys = [key];
}
for (j = 0; j < keys[0].length; j++) {
chr = keys[0].charAt(j);
if (chr === ' ' || chr === '.' || chr === '[') {
keys[0] = keys[0].substr(0, j) + '_' + keys[0].substr(j + 1);
}
if (chr === '[') {
break;
}
}
obj = array;
for (j = 0, keysLen = keys.length; j < keysLen; j++) {
key = keys[j].replace(/^['"]/, '').replace(/['"]$/, '');
lastIter = j !== keys.length - 1;
lastObj = obj;
if ((key !== '' && key !== ' ') || j === 0) {
if (obj[key] === undef) {
obj[key] = {};
}
obj = obj[key];
} else { // To insert new dimension
ct = -1;
for (p in obj) {
if (obj.hasOwnProperty(p)) {
if (+p > ct && p.match(/^\d+$/g)) {
ct = +p;
}
}
}
key = ct + 1;
}
}
lastObj[key] = value;
}
}
return array;
}
function toeListable(params) {
this.params = jQuery.extend({}, params);
this.table = jQuery(this.params.table);
this.paging = jQuery(this.params.paging);
this.perPage = this.params.perPage;
this.list = this.params.list;
this.count = this.params.count;
this.page = this.params.page;
this.pagingCallback = this.params.pagingCallback;
var self = this;
this.draw = function(list, count) {
this.table.find('tr').not('.gmpExample, .gmpTblHeader').remove();
var exampleRow = this.table.find('.gmpExample');
for(var i in list) {
var newRow = exampleRow.clone();
for(var key in list[i]) {
var element = newRow.find('.'+ key);
if(element.size()) {
var valueTo = element.attr('valueTo');
if(valueTo) {
var newValue = list[i][key];
var prevValue = element.attr(valueTo);
if(prevValue)
newValue = prevValue+ ' '+ newValue;
element.attr(valueTo, newValue);
} else
element.html(list[i][key]);
}
}
newRow.removeClass('gmpExample').show();
this.table.append(newRow);
}
if(this.paging) {
this.paging.html('');
if(count && count > list.length && this.perPage) {
for(var i = 1; i <= Math.ceil(count/this.perPage); i++) {
var newPageId = i-1
, newElement = (newPageId == this.page) ? jQuery('<b/>') : jQuery('<a/>');
if(newPageId != this.page) {
newElement.attr('href', '#'+ newPageId)
.click(function(){
if(self.pagingCallback && typeof(self.pagingCallback) == 'function') {
self.pagingCallback(parseInt(jQuery(this).attr('href').replace('#', '')));
return false;
}
});
}
newElement.addClass('toePagingElement').html(i);
this.paging.append(newElement);
}
}
}
}
if(this.list)
this.draw(this.list, this.count);
}
function setCookieGmp(c_name, value, exdays) {
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
function getCookieGmp(name) {
var parts = document.cookie.split(name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
return null;
}
function getImgSize(url, callback) {
jQuery('<img/>').attr('src', url).load(function(){
callback({w: this.width, h: this.height});
});
}
function callUserFuncArray(cb, parameters) {
// http://kevin.vanzonneveld.net
// + original by: Thiago Mata (http://thiagomata.blog.com)
// + revised by: Jon Hohle
// + improved by: Brett Zamir (http://brett-zamir.me)
// + improved by: Diplom@t (http://difane.com/)
// + improved by: Brett Zamir (http://brett-zamir.me)
// * example 1: call_user_func_array('isNaN', ['a']);
// * returns 1: true
// * example 2: call_user_func_array('isNaN', [1]);
// * returns 2: false
var func;
if (typeof cb === 'string') {
func = (typeof this[cb] === 'function') ? this[cb] : func = (new Function(null, 'return ' + cb))();
}
else if (Object.prototype.toString.call(cb) === '[object Array]') {
func = (typeof cb[0] == 'string') ? eval(cb[0] + "['" + cb[1] + "']") : func = cb[0][cb[1]];
}
else if (typeof cb === 'function') {
func = cb;
}
if (typeof func !== 'function') {
throw new Error(func + ' is not a valid function');
}
return (typeof cb[0] === 'string') ? func.apply(eval(cb[0]), parameters) : (typeof cb[0] !== 'object') ? func.apply(null, parameters) : func.apply(cb[0], parameters);
}
| nikakoss/arsenal-media.net | wp-content/plugins/google-maps-ready/js/common.js | JavaScript | gpl-2.0 | 12,013 |
<?php
/**
* Joomla! Content Management System
*
* @copyright (C) 2011 Open Source Matters, Inc. <https://www.joomla.org>
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
namespace Joomla\CMS\Http;
defined('JPATH_PLATFORM') or die;
use Joomla\Registry\Registry;
use Joomla\CMS\Uri\Uri;
/**
* HTTP transport class interface.
*
* @since 1.7.3
*/
interface TransportInterface
{
/**
* Constructor.
*
* @param Registry $options Client options object.
*
* @since 1.7.3
*/
public function __construct(Registry $options);
/**
* Send a request to the server and return a HttpResponse object with the response.
*
* @param string $method The HTTP method for sending the request.
* @param Uri $uri The URI to the resource to request.
* @param mixed $data Either an associative array or a string to be sent with the request.
* @param array $headers An array of request headers to send with the request.
* @param integer $timeout Read timeout in seconds.
* @param string $userAgent The optional user agent string to send with the request.
*
* @return Response
*
* @since 1.7.3
*/
public function request($method, Uri $uri, $data = null, array $headers = null, $timeout = null, $userAgent = null);
/**
* Method to check if HTTP transport is available for use
*
* @return boolean True if available else false
*
* @since 3.0.0
*/
public static function isSupported();
}
| zero-24/joomla-cms | libraries/src/Http/TransportInterface.php | PHP | gpl-2.0 | 1,521 |
// Copyright (C) 2014 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library 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, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
#include <regex>
#include <testsuite_performance.h>
using namespace __gnu_test;
int main()
{
time_counter time;
resource_counter resource;
start_counters(time, resource);
// this should get compiled to just L"[abcd]"
auto re = std::wregex(L'[' + std::wstring(300, L'a') + L"bc"
+ std::wstring(1000, 'a') + L"d]");
bool ok = true;
for (int i = 0; i < 100000; ++i)
ok = ok && (std::regex_match(L"b", re) && std::regex_match(L"d", re));
stop_counters(time, resource);
report_performance(__FILE__, "", time, resource);
return ok ? 0 : 1;
}
| xinchoubiology/gcc | libstdc++-v3/testsuite/performance/28_regex/range.cc | C++ | gpl-2.0 | 1,349 |
<?php
/**
* This code was generated by
* \ / _ _ _| _ _
* | (_)\/(_)(_|\/| |(/_ v1.0.0
* / /
*/
namespace Twilio\Rest\Preview;
use Twilio\Domain;
use Twilio\Exceptions\TwilioException;
use Twilio\Rest\Preview\HostedNumbers\HostedNumberOrderList;
use Twilio\Version;
/**
* @property \Twilio\Rest\Preview\HostedNumbers\HostedNumberOrderList hostedNumberOrders
* @method \Twilio\Rest\Preview\HostedNumbers\HostedNumberOrderContext hostedNumberOrders(string $sid)
*/
class HostedNumbers extends Version {
protected $_hostedNumberOrders = null;
/**
* Construct the HostedNumbers version of Preview
*
* @param \Twilio\Domain $domain Domain that contains the version
* @return \Twilio\Rest\Preview\HostedNumbers HostedNumbers version of Preview
*/
public function __construct(Domain $domain) {
parent::__construct($domain);
$this->version = 'HostedNumbers';
}
/**
* @return \Twilio\Rest\Preview\HostedNumbers\HostedNumberOrderList
*/
protected function getHostedNumberOrders() {
if (!$this->_hostedNumberOrders) {
$this->_hostedNumberOrders = new HostedNumberOrderList($this);
}
return $this->_hostedNumberOrders;
}
/**
* Magic getter to lazy load root resources
*
* @param string $name Resource to return
* @return \Twilio\ListResource The requested resource
* @throws \Twilio\Exceptions\TwilioException For unknown resource
*/
public function __get($name) {
$method = 'get' . ucfirst($name);
if (method_exists($this, $method)) {
return $this->$method();
}
throw new TwilioException('Unknown resource ' . $name);
}
/**
* Magic caller to get resource contexts
*
* @param string $name Resource to return
* @param array $arguments Context parameters
* @return \Twilio\InstanceContext The requested resource context
* @throws \Twilio\Exceptions\TwilioException For unknown resource
*/
public function __call($name, $arguments) {
$property = $this->$name;
if (method_exists($property, 'getContext')) {
return call_user_func_array(array($property, 'getContext'), $arguments);
}
throw new TwilioException('Resource does not have a context');
}
/**
* Provide a friendly representation
*
* @return string Machine friendly representation
*/
public function __toString() {
return '[Twilio.Preview.HostedNumbers]';
}
} | Haynie-Research-and-Development/jarvis | web/webapi/sms/vendor/twilio/sdk/Twilio/Rest/Preview/HostedNumbers.php | PHP | gpl-2.0 | 2,570 |
<?php
/* pluginbuddy_ui class
*
* Handles typical user interface items used in WordPress development.
*
* @author Dustin Bolton
* @version 1.0.0
*/
class pb_backupbuddy_ui {
private $_tab_interface_tag = '';
/* pluginbuddy_ui->start_metabox()
*
* Starts a metabox. Use with end_metabox().
* @see pluginbuddy_ui->end_metabox
*
* @param string $title Title to display for the metabox.
* @param boolean $echo Echos if true; else returns.
* @param boolean/string $small_or_css true: size is limited smaller. false: size is limited larger. If a string then interpreted as CSS.
* @return null/string Returns null if $echo is true; else returns string with HTML.
*/
public function start_metabox( $title, $echo = true, $small_or_css = false ) {
if ( $small_or_css === false ) { // Large size.
$css = 'width: 70%; min-width: 720px;';
} elseif ( $small_or_css === true ) { // Small size.
$css = 'width: 20%; min-width: 250px;';
} else { // String so interpret as CSS.
$css = $small_or_css;
}
$css .= ' padding-top: 0; margin-top: 10px; cursor: auto;';
$response = '<div class="metabox-holder postbox" style="' . $css . '">
<h3 class="hndle" style="cursor: auto;"><span>' . $title . '</span></h3>
<div class="inside">';
if ( $echo === true ) {
echo $response;
} else {
return $response;
}
} // End start_metabox().
/* pluginbuddy_ui->end_metabox()
*
* Ends a metabox. Use with start_metabox().
* @see pluginbuddy_ui->start_metabox
*
* @param boolean $echo Echos if true; else returns.
* @return null/string Returns null if $echo is true; else returns string with HTML.
*/
public function end_metabox( $echo = true ) {
$response = ' </div>
</div>';
if ( $echo === true ) {
echo $response;
} else {
return $response;
}
} // End end_metabox().
/* pluginbuddy_ui->title()
*
* Displays a styled, properly formatted title for pages.
*
* @param string $title Title to display.
* @param boolean $echo Whether or not to echo the string or return.
* @return null/string Returns null if $echo is true; else returns string with HTML.
*/
public function title( $title, $echo = true ) {
$return = '<h2><img src="' . pb_backupbuddy::plugin_url() . '/images/icon_32x32.png" style="vertical-align: -7px;"> ' . $title . '</h2><br />';
if ( $echo === true ) {
echo $return;
} else {
return $return;
}
} // End title().
/* pluginbuddy_ui->button()
*
* Displays a nice pretty styled button. How nice. Always returns.
*
* @param string $url URL (href) for the button to link to.
* @param string $text Text to display in the button.
* @param string $title Optional title text to display on hover in the title tag.
* @param boolean $primary (optional) Whether or not this is a primary button. Primary buttons are blue and strong where default non-primary is grey and gentle.
* @param string $additional_class (optional) Additional CSS class to apply to button. Useful for thickbox or other JS stuff.
* @param string $id (optional) HTML ID to apply. Useful for JS.
* @return string HTML string for the button.
*/
public function button( $url, $text, $title = '', $primary = false, $additional_class = '', $id = '' ) {
if ( $primary === false ) {
return '<a class="button secondary-button ' . $additional_class . '" style="margin-top: 3px;" id="' . $id . '" title="' . $title . '" href="' . $url . '">' . $text . '</a>';
} else {
return '<a class="button button-primary ' . $additional_class . '" style="margin-top: 3px;" id="' . $id . '" title="' . $title . '" href="' . $url . '">' . $text . '</a>';
}
} // End button().
/* pluginbuddy_ui->note()
*
* Display text in a subtle way.
*
* @param string $text Text of note.
* @param boolean $echo Whether or not to echo the string or return.
* @return null/string Returns null if $echo is true; else returns string with HTML.
*/
public static function note( $text, $echo = true ) {
$return = '<span class="description"><i>' . $text . '</i></span>';
if ( $echo === true ) {
echo $return;
} else {
return $return;
}
} // End note().
/* pluginbuddy_ui->list_table()
*
* Displays a nice table with multiple columns, rows, bulk actions, hover actions, etc similar to WordPress posts table.
* Currently only supports echo of output.
*
* @param array $items Array of rows to display. Each row array contains an array with the columns. Typically set in controller.
* Ex: array( array( 'blue', 'red' ), array( 'brown', 'green' ) ).
* If the value for an item is an array then the first value will be assigned to the rel tag of any hover actions. If not
* an array then the value itself will be put in the rel tag. If an array the second value will be the one displayed in the column.
* BackupBuddy needed the displayed item in the column to be a link (for downloading backups) but the backup file as the rel.
* @param array $settings Array of all the various settings. Merged with defaults prior to usage. Typically set in view.
* See $default_settings at beginning of function for available settings.
* Ex: $settings = array(
* 'action' => pb_backupbuddy::plugin_url(),
* 'columns' => array( 'Group Name', 'Images', 'Shortcode' ),
* 'hover_actions' => array( 'edit' => 'Edit Group Settings' ), // Slug can be a URL. In this case the value of the hovered row will be appended to the end of the URL. TODO: Make the first hover action be the link for the first listed item.
* 'bulk_actions' => array( 'delete_images' => 'Delete' ),
* );
* @return null
*/
public static function list_table( $items, $settings ) {
$default_settings = array(
'columns' => array(),
'hover_actions' => array(),
'bulk_actions' => array(),
'hover_action_column_key' => '', // int of column to set value= in URL and rel tag= for using in JS.
'action' => '',
'reorder' => '',
'after_bulk' => '',
'css' => '',
);
// Merge defaults.
$settings = array_merge( $default_settings, $settings );
// Function to iterate through bulk actions. Top and bottom set are the same.
if ( !function_exists( 'bulk_actions' ) ) {
function bulk_actions( $settings, $hover_note = false ) {
if ( count( $settings['bulk_actions'] ) > 0 ) {
echo '<div style="padding-bottom: 3px; padding-top: 3px;">';
if ( count( $settings['bulk_actions'] ) == 1 ) {
foreach( $settings['bulk_actions'] as $action_slug => $action_title ) {
echo '<input type="hidden" name="bulk_action" value="' . $action_slug . '">';
echo '<input type="submit" name="do_bulk_action" value="' . $action_title . '" class="button secondary-button">';
}
} else {
echo '<select name="bulk_action" class="actions">';
foreach ( $settings['bulk_actions'] as $action_slug => $action_title ) {
echo '<option>Bulk Actions</option>';
echo '<option value="' . $action_slug . '">' . $action_title . '</option>';
}
echo '</select> ';
//echo self::button( '#', 'Apply' );
echo '<input type="submit" name="do_bulk_action" value="Apply" class="button secondary-button">';
}
echo ' ';
echo $settings['after_bulk'];
echo '<div class="alignright actions">';
if ( $hover_note === true ) {
echo pb_backupbuddy::$ui->note( 'Hover over items above for additional options.' );
}
if ( $settings['reorder'] != '' ) {
echo ' <input type="submit" name="save_order" id="save_order" value="Save Order" class="button-secondary" />';
}
echo '</div>';
echo '</div>';
}
} // End subfunction bulk_actions().
} // End if function does not exist.
if ( $settings['action'] != '' ) {
echo '<form method="post" action="' . $settings['action'] . '">';
pb_backupbuddy::nonce();
if ( $settings['reorder'] != '' ) {
echo '<input type="hidden" name="order" value="" id="pb_order">';
}
}
echo '<div style="width: 70%; min-width: 720px; ' . $settings['css'] . '">';
// Display bulk actions (top).
bulk_actions( $settings );
echo '<table class="widefat"';
echo ' id="test">';
echo ' <thead>
<tr class="thead">';
if ( count( $settings['bulk_actions'] ) > 0 ) {
echo' <th scope="col" class="check-column"><input type="checkbox" class="check-all-entries" /></th>';
}
foreach ( $settings['columns'] as $column ) {
echo '<th>' . $column . '</th>';
}
echo ' </tr>
</thead>
<tfoot>
<tr class="thead">';
if ( count( $settings['bulk_actions'] ) > 0 ) {
echo' <th scope="col" class="check-column"><input type="checkbox" class="check-all-entries" /></th>';
}
foreach ( $settings['columns'] as $column ) {
echo '<th>' . $column . '</th>';
}
echo ' </tr>
</tfoot>
<tbody';
if ( $settings['reorder'] != '' ) {
echo ' class="pb_reorder"';
}
echo '>';
// LOOP THROUGH EACH ROW.
foreach ( (array)$items as $item_id => $item ) {
echo ' <tr class="entry-row alternate" id="pb_rowitem-' . $item_id . '">';
if ( count( $settings['bulk_actions'] ) > 0 ) {
echo' <th scope="row" class="check-column"><input type="checkbox" name="items[]" class="entries" value="' . $item_id . '"></th>';
}
echo ' <td>';
if ( is_array( $item['0'] ) ) {
if ( $item['0'][1] == '' ) {
echo ' ';
} else {
echo $item['0'][1];
}
} else {
if ( $item['0'] == '' ) {
echo ' ';
} else {
echo $item['0'];
}
}
echo ' <div class="row-actions">'; // style="margin:0; padding:0;"
$i = 0;
foreach ( $settings['hover_actions'] as $action_slug => $action_title ) { // Display all hover actions.
$i++;
if ( $settings['hover_action_column_key'] != '' ) {
if ( is_array( $item[$settings['hover_action_column_key']] ) ) {
$hover_action_column_value = $item[$settings['hover_action_column_key']][0];
} else {
$hover_action_column_value = $item[$settings['hover_action_column_key']];
}
} else {
$hover_action_column_value = '';
}
if ( strstr( $action_slug, 'http' ) === false ) { // Word hover action slug.
$hover_link= pb_backupbuddy::page_url() . '&' . $action_slug . '=' . $item_id . '&value=' . $hover_action_column_value;
} else { // URL hover action slug so just append value to URL.
$hover_link = $action_slug . $hover_action_column_value;
}
echo '<a href="' . $hover_link . '" class="pb_' . pb_backupbuddy::settings( 'slug' ) . '_hoveraction_' . $action_slug . '" rel="' . $hover_action_column_value . '">' . $action_title . '</a>';
if ( $i < count( $settings['hover_actions'] ) ) {
echo ' | ';
}
}
echo ' </div>
</td>';
if ( $settings['reorder'] != '' ) {
$count = count( $item ) + 1; // Extra row for reordering.
} else {
$count = count( $item );
}
// LOOP THROUGH COLUMNS FOR THIS ROW.
for ( $i = 1; $i < $count; $i++ ) {
echo '<td';
if ( $settings['reorder'] != '' ) {
if ( $i == $settings['reorder'] ) {
echo ' class="pb_draghandle" align="center"';
}
}
echo '>';
if ( ( $settings['reorder'] != '' ) && ( $i == ( $settings['reorder'] ) ) ) {
echo '<img src="' . pb_backupbuddy::plugin_url() . '/pluginbuddy/images/draghandle.png" alt="Click and drag to reorder">';
} else {
if ( $item[$i] == '' ) {
echo ' ';
} else {
echo $item[$i];
}
}
echo '</td>';
}
echo ' </tr>';
}
echo ' </tbody>';
echo '</table>';
// Display bulk actions (bottom).
bulk_actions( $settings, true );
echo '</div>';
if ( $settings['action'] != '' ) {
echo '</form>';
}
} // End list_table().
/**
* pb_backupbuddy::get_feed()
*
* Gets an RSS or other feed and inserts it as a list of links...
*
* @param string $feed URL to the feed.
* @param int $limit Number of items to retrieve.
* @param string $append HTML to include in the list. Should usually be <li> items including the <li> code.
* @param string $replace String to replace in every title returned. ie twitter includes your own username at the beginning of each line.
* @return string
*/
public function get_feed( $feed, $limit, $append = '', $replace = '' ) {
$return = '';
$feed_html = get_transient( md5( $feed ) );
if ( false === $feed_html ) {
$feed_html = '';
require_once(ABSPATH.WPINC.'/feed.php');
$rss = fetch_feed( $feed );
if ( is_wp_error( $rss ) ) {
$return .= '{Temporarily unable to load feed.}';
return $return;
}
$maxitems = $rss->get_item_quantity( $limit ); // Limit
$rss_items = $rss->get_items(0, $maxitems);
}
$return .= '<ul class="pluginbuddy-nodecor" style="margin-left: 10px;">';
if ( $feed_html == '' ) {
foreach ( (array) $rss_items as $item ) {
$feed_html .= '<li style="list-style-type: none;"><a href="' . $item->get_permalink() . '" target="_new">';
$title = $item->get_title(); //, ENT_NOQUOTES, 'UTF-8');
if ( $replace != '' ) {
$title = str_replace( $replace, '', $title );
}
if ( strlen( $title ) < 30 ) {
$feed_html .= $title;
} else {
$feed_html .= substr( $title, 0, 32 ) . ' ...';
}
$feed_html .= '</a></li>';
}
set_transient( md5( $feed ), $feed_html, 300 ); // expires in 300secs aka 5min
} else {
//echo 'CACHED';
}
$return .= $feed_html;
$return .= $append;
$return .= '</ul>';
return $return;
} // End get_feed().
/**
* pb_backupbuddy::tip()
*
* Displays a message to the user when they hover over the question mark. Gracefully falls back to normal tooltip.
* HTML is supposed within tooltips.
*
* @param string $message Actual message to show to user.
* @param string $title Title of message to show to user. This is displayed at top of tip in bigger letters. Default is blank. (optional)
* @param boolean $echo_tip Whether to echo the tip (default; true), or return the tip (false). (optional)
* @return string/null If not echoing tip then the string will be returned. When echoing there is no return.
*/
public function tip( $message, $title = '', $echo_tip = true ) {
$tip = ' <a class="pluginbuddy_tip" title="' . $title . ' - ' . $message . '"><img src="' . pb_backupbuddy::plugin_url() . '/pluginbuddy/images/pluginbuddy_tip.png" alt="(?)" /></a>';
if ( $echo_tip === true ) {
echo $tip;
} else {
return $tip;
}
} // End tip().
/**
* pb_backupbuddy::alert()
*
* Displays a message to the user at the top of the page when in the dashboard.
*
* @param string $message Message you want to display to the user.
* @param boolean $error OPTIONAL! true indicates this alert is an error and displays as red. Default: false
* @param int $error_code OPTIONAL! Error code number to use in linking in the wiki for easy reference.
* @return null
*/
public function alert( $message, $error = false, $error_code = '', $rel_tag = '' ) {
$log_error = false;
echo '<div id="message" style="padding: 9px;" rel="' . $rel_tag . '" class="pb_backupbuddy_alert ';
if ( $error === false ) {
echo 'updated fade';
} else {
echo 'error';
$log_error = true;
}
if ( $error_code != '' ) {
$message .= ' <a href="http://ithemes.com/codex/page/' . pb_backupbuddy::settings( 'name' ) . ':_Error_Codes#' . $error_code . '" target="_new"><i>' . pb_backupbuddy::settings( 'name' ) . ' Error Code ' . $error_code . ' - Click for more details.</i></a>';
$log_error = true;
}
if ( $log_error === true ) {
pb_backupbuddy::log( $message . ' Error Code: ' . $error_code, 'error' );
}
echo '" >' . $message . '</div>';
} // End alert().
/**
* pb_backupbuddy::disalert()
*
* Displays a DISMISSABLE message to the user at the top of the page when in the dashboard.
*
* @param string $message Message you want to display to the user.
* @param boolean $error OPTIONAL! true indicates this alert is an error and displays as red. Default: false
* @param int $error_code OPTIONAL! Error code number to use in linking in the wiki for easy reference.
* @return null
*/
public function disalert( $unique_id, $message, $error = false ) {
if ( ! isset( pb_backupbuddy::$options['disalerts'][$unique_id] ) ) {
$message = '<a style="float: right;" class="pb_backupbuddy_disalert" href="#" title="' . __( 'Dismiss this alert. Unhide dismissed alerts on the Getting Started page.', 'it-l10n-backupbuddy' ) . '" alt="' . pb_backupbuddy::ajax_url( 'disalert' ) . '">' . __( 'Dismiss', 'it-l10n-backupbuddy' ) . '</a><div style="margin-right: 60px;">' . $message . '</div>';
$this->alert( $message, $error, '', $unique_id );
} else {
echo '<!-- Previously Dismissed Alert: `' . htmlentities( $message ) . '` -->';
}
return;
} // End alert().
/**
* pb_backupbuddy::video()
*
* Displays a YouTube video to the user when they hover over the question video mark.
* HTML is supposed within tooltips.
*
* @param string $video_key YouTube video key from the URL ?v=VIDEO_KEY_HERE -- To jump to a certain timestamp add #SECONDS to the end of the key, where SECONDS is the number of seconds into the video to start at. Example to start 65 seconds into a video: 9ZHWGjBr84s#65. This must be in seconds format.
* @param string $title Title of message to show to user. This is displayed at top of tip in bigger letters. Default is blank. (optional)
* @param boolean $echo_tip Whether to echo the tip (default; true), or return the tip (false). (optional)
* @return string/null If not echoing tip then the string will be returned. When echoing there is no return.
*/
public function video( $video_key, $title = '', $echo_tip = true ) {
if ( !defined( 'PB_IMPORTBUDDY' ) ) {
global $wp_scripts;
if ( is_object( $wp_scripts ) ) {
if ( !in_array( 'thickbox', $wp_scripts->done ) ) {
wp_enqueue_script( 'thickbox' );
wp_print_scripts( 'thickbox' );
wp_print_styles( 'thickbox' );
}
}
}
if ( strstr( $video_key, '#' ) ) {
$video = explode( '#', $video_key );
$video[1] = '&start=' . $video[1];
} else {
$video[0] = $video_key;
$video[1] = '';
}
$tip = '<a target="_new" href="http://www.youtube.com/embed/' . urlencode( $video[0] ) . '?autoplay=1' . $video[1] . '&TB_iframe=1&width=600&height=400" class="thickbox pluginbuddy_tip" title="Video Tutorial - ' . $title . '"><img src="' . pb_backupbuddy::plugin_url() . '/pluginbuddy/images/pluginbuddy_play.png" alt="(video)" /></a>';
if ( $echo_tip === true ) {
echo $tip;
} else {
return $tip;
}
} // End video().
/*
public function media_library( $save_point, $default_options_point ) {
require_once( pb_backupbuddy::plugin_path() . '/pluginbuddy/lib/media_library/media_library.php' );
$media_library = new pluginbuddy_medialibrary( $save_point, $default_options_point );
$media_library->display();
}
*/
/* start_tabs()
*
* Starts a tabbed interface.
* @see end_tabs().
*
* @param string $interface_tag Tag/slug for this entire tabbed interface. Should be unique.
* @param array $tabs Array containing an array of settings for this tabbed interface. Ex: array( array( 'title'> 'my title', 'slug' => 'mytabs' ) );
* Optional setting with key `ajax_url` may define a URL for AJAX loading.
* @param string $css Additional CSS to apply to main outer div. (optional)
* @param boolean $echo Echo output instead of returning. (optional)
* @param int $active_tab_index Tab to start as active/selected.
* @return null/string null if $echo = false, all data otherwise.
*/
public function start_tabs( $interface_tag, $tabs, $css = '', $echo = true, $active_tab_index = 0 ) {
$this->_tab_interface_tag = $interface_tag;
pb_backupbuddy::load_script( 'jquery-ui-tabs' );
$prefix = 'pb_' . pb_backupbuddy::settings( 'slug' ) . '_'; // pb_PLUGINSLUG_
$return = '';
$return .= '<script type="text/javascript">';
$return .= ' jQuery(document).ready(function() {';
$return .= ' jQuery("#' . $prefix . $this->_tab_interface_tag . '_tabs").tabs({ active: ' . $active_tab_index . ' });';
$return .= ' });';
$return .= '</script>';
$return .= '<div id="' . $prefix . $this->_tab_interface_tag . '_tabs" style="' . $css . '">';
$return .= '<ul>';
foreach( $tabs as $tab ) {
if ( ! isset( $tab['css'] ) ) {
$tab['css'] = '';
}
if ( isset( $tab['ajax'] ) && ( $tab['ajax_url'] != '' ) ) { // AJAX tab.
$return .= '<li><a href="' . $tab['ajax_url'] . '"><span>' . $tab['title'] . '</span></a></li>';
} else { // Standard; NO AJAX.
$return .= '<li style="' . $tab['css'] . '"><a href="#' . $prefix . $this->_tab_interface_tag . '_tab_' . $tab['slug'] . '"><span>' . $tab['title'] . '</span></a></li>';
}
}
$return .= '</ul>';
$return .= '<br>';
$return .= '<div class="tabs-borderwrap">';
if ( $echo === true ) {
echo $return;
} else {
return $return;
}
} // End start_tabs().
/* end_tabs()
*
* Closes off a tabbed interface.
* @see start_tabs().
*
* @param boolean $echo Echo output instead of returning. (optional)
* @return null/string null if $echo = false, all data otherwise.
*/
public function end_tabs( $echo = true ) {
$return = '';
$return .= ' </div>';
$return .= '</div>';
$this->_tab_interface_tag = '';
if ( $echo === true ) {
echo $return;
} else {
return $return;
}
} // End end_tabs().
/* start_tab()
*
* Opens the start of an individual page to be loaded by a tab.
* @see end_tab().
*
* @param string $tab_tag Unique tag for this tab section. Must match the tag defined when creating the tab interface.
* @param boolean $echo Echo output instead of returning. (optional)
* @return null/string null if $echo = false, all data otherwise.
*/
public function start_tab( $tab_tag, $echo = true ) {
$prefix = 'pb_' . pb_backupbuddy::settings( 'slug' ) . '_'; // pb_PLUGINSLUG_
$return = '';
$return .= '<div id="' . $prefix . $this->_tab_interface_tag . '_tab_' . $tab_tag . '">';
if ( $echo === true ) {
echo $return;
} else {
return $return;
}
} // End start_tab().
/* end_tab()
*
* Closes this tab section.
* @see start_tab().
*
* @param string $tab_tag Unique tag for this tab section. Must match the tag defined when creating the tab interface.
* @param boolean $echo Echo output instead of returning. (optional)
* @return null/string null if $echo = false, all data otherwise.
*/
public function end_tab( $echo = true ) {
$return = '</div>';
if ( $echo === true ) {
echo $return;
} else {
return $return;
}
} // End end_tab().
/* ajax_header()
*
* Output HTML headers when using AJAX.
*
* @param boolean $js Whether or not to load javascript. Default false.
* @param bool $padding Whether or not to padd wrapper div. Default has padding.
* @return
*/
function ajax_header( $js = true, $padding = true ) {
echo '<head>';
echo '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
echo '<title>PluginBuddy</title>';
wp_print_styles( 'global' );
wp_print_styles( 'wp-admin' );
wp_print_styles( 'colors-fresh' );
wp_print_styles( 'colors-fresh' );
if ( $js === true ) {
wp_enqueue_script( 'jquery' );
wp_print_scripts( 'jquery' );
}
//echo '<link rel="stylesheet" href="' . pb_backupbuddy::plugin_url(); . '/css/admin.css" type="text/css" media="all" />';
pb_backupbuddy::load_script( 'admin.js', true );
pb_backupbuddy::load_style( 'admin.css', true );
pb_backupbuddy::load_script( 'tooltip.js', true );
echo '<body class="wp-core-ui">';
if ( $padding === true ) {
echo '<div style="padding: 8px; padding-left: 12px; padding-right: 12px;">';
} else {
echo '<div>';
}
} // End ajax_header().
function ajax_footer() {
echo '</body>';
echo '</div>';
echo '</head>';
echo '</html>';
} // End ajax_footer().
} // End class pluginbuddy_ui.
?> | ghostego/viscom-new | wp-content/plugins/backupbuddy/pluginbuddy/classes/ui.php | PHP | gpl-2.0 | 24,642 |
""" Encoding Aliases Support
This module is used by the encodings package search function to
map encodings names to module names.
Note that the search function converts the encoding names to lower
case and replaces hyphens with underscores *before* performing the
lookup.
"""
aliases = {
# Latin-1
'latin': 'latin_1',
'latin1': 'latin_1',
# UTF-7
'utf7': 'utf_7',
'u7': 'utf_7',
# UTF-8
'utf': 'utf_8',
'utf8': 'utf_8',
'u8': 'utf_8',
'utf8@ucs2': 'utf_8',
'utf8@ucs4': 'utf_8',
# UTF-16
'utf16': 'utf_16',
'u16': 'utf_16',
'utf_16be': 'utf_16_be',
'utf_16le': 'utf_16_le',
'unicodebigunmarked': 'utf_16_be',
'unicodelittleunmarked': 'utf_16_le',
# ASCII
'us_ascii': 'ascii',
'ansi_x3.4_1968': 'ascii', # used on Linux
'ansi_x3_4_1968': 'ascii', # used on BSD?
'646': 'ascii', # used on Solaris
# EBCDIC
'ebcdic_cp_us': 'cp037',
'ibm039': 'cp037',
'ibm1140': 'cp1140',
# ISO
'8859': 'latin_1',
'iso8859': 'latin_1',
'iso8859_1': 'latin_1',
'iso_8859_1': 'latin_1',
'iso_8859_10': 'iso8859_10',
'iso_8859_13': 'iso8859_13',
'iso_8859_14': 'iso8859_14',
'iso_8859_15': 'iso8859_15',
'iso_8859_2': 'iso8859_2',
'iso_8859_3': 'iso8859_3',
'iso_8859_4': 'iso8859_4',
'iso_8859_5': 'iso8859_5',
'iso_8859_6': 'iso8859_6',
'iso_8859_7': 'iso8859_7',
'iso_8859_8': 'iso8859_8',
'iso_8859_9': 'iso8859_9',
# Mac
'maclatin2': 'mac_latin2',
'maccentraleurope': 'mac_latin2',
'maccyrillic': 'mac_cyrillic',
'macgreek': 'mac_greek',
'maciceland': 'mac_iceland',
'macroman': 'mac_roman',
'macturkish': 'mac_turkish',
# Windows
'windows_1251': 'cp1251',
'windows_1252': 'cp1252',
'windows_1254': 'cp1254',
'windows_1255': 'cp1255',
'windows_1256': 'cp1256',
'windows_1257': 'cp1257',
'windows_1258': 'cp1258',
# MBCS
'dbcs': 'mbcs',
# Code pages
'437': 'cp437',
# CJK
#
# The codecs for these encodings are not distributed with the
# Python core, but are included here for reference, since the
# locale module relies on having these aliases available.
#
'jis_7': 'jis_7',
'iso_2022_jp': 'jis_7',
'ujis': 'euc_jp',
'ajec': 'euc_jp',
'eucjp': 'euc_jp',
'tis260': 'tactis',
'sjis': 'shift_jis',
# Content transfer/compression encodings
'rot13': 'rot_13',
'base64': 'base64_codec',
'base_64': 'base64_codec',
'zlib': 'zlib_codec',
'zip': 'zlib_codec',
'hex': 'hex_codec',
'uu': 'uu_codec',
'quopri': 'quopri_codec',
'quotedprintable': 'quopri_codec',
'quoted_printable': 'quopri_codec',
}
| remybaranx/qtaste | tools/jython/lib/Lib/encodings/aliases.py | Python | gpl-3.0 | 2,790 |
<?php
require_once "$CFG->dirroot/lib/formslib.php";
require_once "$CFG->dirroot/mod/facetoface/lib.php";
class mod_facetoface_sitenotice_form extends moodleform {
function definition()
{
$mform =& $this->_form;
$mform->addElement('header', 'general', get_string('general', 'form'));
$mform->addElement('hidden', 'id', $this->_customdata['id']);
$mform->addElement('text', 'name', get_string('name'), 'maxlength="255" size="50"');
$mform->addRule('name', null, 'required', null, 'client');
$mform->setType('name', PARAM_MULTILANG);
$mform->addElement('htmleditor', 'text', get_string('noticetext', 'facetoface'), array('rows' => 10, 'cols' => 64));
$mform->setType('text', PARAM_RAW);
$mform->addRule('text', null, 'required', null, 'client');
$mform->addElement('header', 'conditions', get_string('conditions', 'facetoface'));
$mform->addElement('html', get_string('conditionsexplanation', 'facetoface'));
// Show all custom fields
$customfields = $this->_customdata['customfields'];
facetoface_add_customfields_to_form($mform, $customfields, true);
$this->add_action_buttons();
}
}
| mynameisdongyoung/Face-to-Face2.0 | sitenotice_form.php | PHP | gpl-3.0 | 1,228 |
/*******************************************************************************
* You may amend and distribute as you like, but don't remove this header!
*
* EPPlus provides server-side generation of Excel 2007/2010 spreadsheets.
* See http://www.codeplex.com/EPPlus for details.
*
* Copyright (C) 2011 Jan Källman
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* The GNU Lesser General Public License can be viewed at http://www.opensource.org/licenses/lgpl-license.php
* If you unfamiliar with this license or have questions about it, here is an http://www.gnu.org/licenses/gpl-faq.html
*
* All code and executables are provided "as is" with no warranty either express or implied.
* The author accepts no liability for any damage or loss of business that this product may cause.
*
* Code change notes:
*
* Author Change Date
* ******************************************************************************
* Eyal Seagull Added 2012-04-03
*******************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Xml;
using OfficeOpenXml.ConditionalFormatting.Contracts;
namespace OfficeOpenXml.ConditionalFormatting
{
/// <summary>
/// ExcelConditionalFormattingTop
/// </summary>
public class ExcelConditionalFormattingTop
: ExcelConditionalFormattingRule,
IExcelConditionalFormattingTopBottomGroup
{
/****************************************************************************************/
#region Constructors
/// <summary>
///
/// </summary>
/// <param name="priority"></param>
/// <param name="address"></param>
/// <param name="worksheet"></param>
/// <param name="itemElementNode"></param>
/// <param name="namespaceManager"></param>
internal ExcelConditionalFormattingTop(
ExcelAddress address,
int priority,
ExcelWorksheet worksheet,
XmlNode itemElementNode,
XmlNamespaceManager namespaceManager)
: base(
eExcelConditionalFormattingRuleType.Top,
address,
priority,
worksheet,
itemElementNode,
(namespaceManager == null) ? worksheet.NameSpaceManager : namespaceManager)
{
if (itemElementNode==null) //Set default values and create attributes if needed
{
Bottom = false;
Percent = false;
Rank = 10; // First 10 values
}
}
/// <summary>
///
/// </summary>
/// <param name="priority"></param>
/// <param name="address"></param>
/// <param name="worksheet"></param>
/// <param name="itemElementNode"></param>
internal ExcelConditionalFormattingTop(
ExcelAddress address,
int priority,
ExcelWorksheet worksheet,
XmlNode itemElementNode)
: this(
address,
priority,
worksheet,
itemElementNode,
null)
{
}
/// <summary>
///
/// </summary>
/// <param name="priority"></param>
/// <param name="address"></param>
/// <param name="worksheet"></param>
internal ExcelConditionalFormattingTop(
ExcelAddress address,
int priority,
ExcelWorksheet worksheet)
: this(
address,
priority,
worksheet,
null,
null)
{
}
#endregion Constructors
/****************************************************************************************/
}
} | wtsi-swat/eq_exporter | epplus_90cfd9a3a979/EPPlus/ConditionalFormatting/Rules/ExcelConditionalFormattingTop.cs | C# | gpl-3.0 | 4,023 |
<?php
//============================================================+
// File name : example_052.php
// Begin : 2009-05-07
// Last Update : 2009-09-30
//
// Description : Example 052 for TCPDF class
// Certification Signature (experimental)
//
// Author: Nicola Asuni
//
// (c) Copyright:
// Nicola Asuni
// Tecnick.com s.r.l.
// Via Della Pace, 11
// 09044 Quartucciu (CA)
// ITALY
// www.tecnick.com
// info@tecnick.com
//============================================================+
/**
* Creates an example PDF TEST document using TCPDF
* @package com.tecnick.tcpdf
* @abstract TCPDF - Example: Certification Signature (experimental)
* @author Nicola Asuni
* @copyright 2004-2009 Nicola Asuni - Tecnick.com S.r.l (www.tecnick.com) Via Della Pace, 11 - 09044 - Quartucciu (CA) - ITALY - www.tecnick.com - info@tecnick.com
* @link http://tcpdf.org
* @license http://www.gnu.org/copyleft/lesser.html LGPL
* @since 2009-05-07
*/
require_once('../config/lang/eng.php');
require_once('../tcpdf.php');
// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Nicola Asuni');
$pdf->SetTitle('TCPDF Example 052');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE, PDF_HEADER_STRING);
// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
//set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
//set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
//set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
//set some language-dependent strings
$pdf->setLanguageArray($l);
// ---------------------------------------------------------
// set certificate file
$certificate = 'file://../tcpdf.crt';
// set additional information
$info = array(
'Name' => 'TCPDF',
'Location' => 'Office',
'Reason' => 'Testing TCPDF',
'ContactInfo' => 'http://www.tcpdf.org',
);
// set document signature
$pdf->setSignature($certificate, $certificate, 'tcpdfdemo', '', 2, $info);
// set font
$pdf->SetFont('helvetica', '', 10);
// add a page
$pdf->AddPage();
// print a line of text
$text = 'This is a <b color="#FF0000">digitally signed document</b> using the default (example) <b>tcpdf.crt</b> certificate.<br />To validate this signature you have to load the <b>tcpdf.fdf</b> on the Arobat Reader to add the certificate to List of Trusted Identities.<br /><br />For more information check the source code of this example and the source code documentation for the <i>setSignature()</i> method.<br /><br /><a href="http://www.tcpdf.org">www.tcpdf.org</a>.';
$pdf->writeHTML($text, true, 0, true, 0);
// ---------------------------------------------------------
//Close and output PDF document
$pdf->Output('example_052.pdf', 'I');
//============================================================+
// END OF FILE
//============================================================+
?>
| mfandrade/siac | vendors/tcpdf/examples/example_052.php | PHP | gpl-3.0 | 3,586 |
// RUN: %clang_cc1 -fsyntax-only -verify %s
// RUN: %clang_cc1 -fsyntax-only -Wno-signed-unsigned-wchar -verify=allow-signed -DSKIP_ERROR_TESTS %s
// allow-signed-no-diagnostics
wchar_t x;
void f(wchar_t p) {
wchar_t x;
unsigned wchar_t y; // expected-error {{'wchar_t' cannot be signed or unsigned}}
signed wchar_t z; // expected-error {{'wchar_t' cannot be signed or unsigned}}
++x;
}
// PR4502
wchar_t const c = L'c';
int a[c == L'c' ? 1 : -1];
// PR5917
template<typename _CharT>
struct basic_string {
};
template<typename _CharT>
basic_string<_CharT> operator+ (const basic_string<_CharT>&, _CharT);
int t(void) {
basic_string<wchar_t>() + L'-';
return (0);
}
// rdar://8040728
wchar_t in[] = L"\x434" "\x434"; // No warning
#ifndef SKIP_ERROR_TESTS
// Verify that we do not crash when assigning wchar_t* to another pointer type.
void assignment(wchar_t *x) {
char *y;
y = x; // expected-error {{incompatible pointer types assigning to 'char *' from 'wchar_t *'}}
}
#endif
| sabel83/metashell | 3rd/templight/clang/test/SemaCXX/wchar_t.cpp | C++ | gpl-3.0 | 1,004 |
var Deferred = require('./')
var assert = require('assert')
var d = new Deferred()
var t = require('tap')
t.match(d, {
resolve: Function,
reject: Function,
promise: Object
})
| gerrytucker78/emse_capstone_project | services/node_modules/nodeunit/node_modules/tap/node_modules/trivial-deferred/test.js | JavaScript | gpl-3.0 | 181 |
<?php
/**
* The template for displaying product widget entries.
*
* This template can be overridden by copying it to yourtheme/woocommerce/content-widget-reviews.php
*
* HOWEVER, on occasion WooCommerce will need to update template files and you
* (the theme developer) will need to copy the new files to your theme to
* maintain compatibility. We try to do this as little as possible, but it does
* happen. When this occurs the version of the template file will be bumped and
* the readme will list any important changes.
*
* @see https://docs.woocommerce.com/document/template-structure/
* @package WooCommerce\Templates
* @version 3.4.0
*/
defined( 'ABSPATH' ) || exit;
?>
<li>
<?php do_action( 'woocommerce_widget_product_review_item_start', $args ); ?>
<a href="<?php echo esc_url( get_comment_link( $comment->comment_ID ) ); ?>">
<?php echo $product->get_image(); ?>
<span class="product-title"><?php echo $product->get_name(); ?></span>
</a>
<?php echo wc_get_rating_html( intval( get_comment_meta( $comment->comment_ID, 'rating', true ) ) ); ?>
<span class="reviewer"><?php echo sprintf( esc_html__( 'by %s', 'woocommerce' ), get_comment_author( $comment->comment_ID ) ); ?></span>
<?php do_action( 'woocommerce_widget_product_review_item_end', $args ); ?>
</li>
| Ninos/woocommerce | templates/content-widget-reviews.php | PHP | gpl-3.0 | 1,305 |
/**
* Aptana Studio
* Copyright (c) 2005-2011 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the GNU Public License (GPL) v3 (with exceptions).
* Please see the license.html included with this distribution for details.
* Any modifications to this file must keep this entire header intact.
*/
package com.aptana.core.internal.resources;
import org.eclipse.osgi.util.NLS;
/**
*
* @author Ingo Muschenetz
*
*/
public final class Messages extends NLS
{
private static final String BUNDLE_NAME = "com.aptana.core.internal.resources.messages"; //$NON-NLS-1$
private Messages()
{
}
static
{
// initialize resource bundle
NLS.initializeMessages(BUNDLE_NAME, Messages.class);
}
/**
* MarkerManager_MarkerIDIsDefined
*/
public static String MarkerManager_MarkerIDIsDefined;
/**
* UniformResourceMarker_UniformResourceMarketInfoNull
*/
public static String UniformResourceMarker_UniformResourceMarketInfoNull;
}
| HossainKhademian/Studio3 | plugins/com.aptana.core/src/com/aptana/core/internal/resources/Messages.java | Java | gpl-3.0 | 969 |
/*
* Pixel Dungeon
* Copyright (C) 2012-2014 Oleg Dolya
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.shatteredpixel.shatteredpixeldungeon.scenes;
import com.shatteredpixel.shatteredpixeldungeon.Assets;
import com.shatteredpixel.shatteredpixeldungeon.Dungeon;
import com.shatteredpixel.shatteredpixeldungeon.Statistics;
import com.shatteredpixel.shatteredpixeldungeon.actors.Actor;
import com.shatteredpixel.shatteredpixeldungeon.items.Generator;
import com.shatteredpixel.shatteredpixeldungeon.levels.Level;
import com.shatteredpixel.shatteredpixeldungeon.windows.WndError;
import com.shatteredpixel.shatteredpixeldungeon.windows.WndStory;
import com.watabou.noosa.BitmapText;
import com.watabou.noosa.Camera;
import com.watabou.noosa.Game;
import com.watabou.noosa.audio.Music;
import com.watabou.noosa.audio.Sample;
import java.io.FileNotFoundException;
import java.io.IOException;
public class InterlevelScene extends PixelScene {
private static final float TIME_TO_FADE = 0.3f;
private static final String TXT_DESCENDING = "Descending...";
private static final String TXT_ASCENDING = "Ascending...";
private static final String TXT_LOADING = "Loading...";
private static final String TXT_RESURRECTING= "Resurrecting...";
private static final String TXT_RETURNING = "Returning...";
private static final String TXT_FALLING = "Falling...";
private static final String ERR_FILE_NOT_FOUND = "Save file not found. If this error persists after restarting, " +
"it may mean this save game is corrupted. Sorry about that.";
private static final String ERR_IO = "Cannot read save file. If this error persists after restarting, " +
"it may mean this save game is corrupted. Sorry about that.";
public static enum Mode {
DESCEND, ASCEND, CONTINUE, RESURRECT, RETURN, FALL
};
public static Mode mode;
public static int returnDepth;
public static int returnPos;
public static boolean noStory = false;
public static boolean fallIntoPit;
private enum Phase {
FADE_IN, STATIC, FADE_OUT
};
private Phase phase;
private float timeLeft;
private BitmapText message;
private Thread thread;
private Exception error = null;
@Override
public void create() {
super.create();
String text = "";
switch (mode) {
case DESCEND:
text = TXT_DESCENDING;
break;
case ASCEND:
text = TXT_ASCENDING;
break;
case CONTINUE:
text = TXT_LOADING;
break;
case RESURRECT:
text = TXT_RESURRECTING;
break;
case RETURN:
text = TXT_RETURNING;
break;
case FALL:
text = TXT_FALLING;
break;
}
message = PixelScene.createText( text, 9 );
message.measure();
message.x = (Camera.main.width - message.width()) / 2;
message.y = (Camera.main.height - message.height()) / 2;
add( message );
phase = Phase.FADE_IN;
timeLeft = TIME_TO_FADE;
thread = new Thread() {
@Override
public void run() {
try {
Generator.reset();
switch (mode) {
case DESCEND:
descend();
break;
case ASCEND:
ascend();
break;
case CONTINUE:
restore();
break;
case RESURRECT:
resurrect();
break;
case RETURN:
returnTo();
break;
case FALL:
fall();
break;
}
if ((Dungeon.depth % 5) == 0) {
Sample.INSTANCE.load( Assets.SND_BOSS );
}
} catch (Exception e) {
error = e;
}
if (phase == Phase.STATIC && error == null) {
phase = Phase.FADE_OUT;
timeLeft = TIME_TO_FADE;
}
}
};
thread.start();
}
@Override
public void update() {
super.update();
float p = timeLeft / TIME_TO_FADE;
switch (phase) {
case FADE_IN:
message.alpha( 1 - p );
if ((timeLeft -= Game.elapsed) <= 0) {
if (!thread.isAlive() && error == null) {
phase = Phase.FADE_OUT;
timeLeft = TIME_TO_FADE;
} else {
phase = Phase.STATIC;
}
}
break;
case FADE_OUT:
message.alpha( p );
if (mode == Mode.CONTINUE || (mode == Mode.DESCEND && Dungeon.depth == 1)) {
Music.INSTANCE.volume( p );
}
if ((timeLeft -= Game.elapsed) <= 0) {
Game.switchScene( GameScene.class );
}
break;
case STATIC:
if (error != null) {
String errorMsg;
if (error instanceof FileNotFoundException) errorMsg = ERR_FILE_NOT_FOUND;
else if (error instanceof IOException) errorMsg = ERR_IO;
else throw new RuntimeException("fatal error occured while moving between floors", error);
add( new WndError( errorMsg ) {
public void onBackPressed() {
super.onBackPressed();
Game.switchScene( StartScene.class );
};
} );
error = null;
}
break;
}
}
private void descend() throws IOException {
Actor.fixTime();
if (Dungeon.hero == null) {
Dungeon.init();
if (noStory) {
Dungeon.chapters.add( WndStory.ID_SEWERS );
noStory = false;
}
} else {
Dungeon.saveLevel();
}
Level level;
if (Dungeon.depth >= Statistics.deepestFloor) {
level = Dungeon.newLevel();
} else {
Dungeon.depth++;
level = Dungeon.loadLevel( Dungeon.hero.heroClass );
}
Dungeon.switchLevel( level, level.entrance );
}
private void fall() throws IOException {
Actor.fixTime();
Dungeon.saveLevel();
Level level;
if (Dungeon.depth >= Statistics.deepestFloor) {
level = Dungeon.newLevel();
} else {
Dungeon.depth++;
level = Dungeon.loadLevel( Dungeon.hero.heroClass );
}
Dungeon.switchLevel( level, fallIntoPit ? level.pitCell() : level.randomRespawnCell() );
}
private void ascend() throws IOException {
Actor.fixTime();
Dungeon.saveLevel();
Dungeon.depth--;
Level level = Dungeon.loadLevel( Dungeon.hero.heroClass );
Dungeon.switchLevel( level, level.exit );
}
private void returnTo() throws IOException {
Actor.fixTime();
Dungeon.saveLevel();
Dungeon.depth = returnDepth;
Level level = Dungeon.loadLevel( Dungeon.hero.heroClass );
Dungeon.switchLevel( level, Level.resizingNeeded ? level.adjustPos( returnPos ) : returnPos );
}
private void restore() throws IOException {
Actor.fixTime();
Dungeon.loadGame( StartScene.curClass );
if (Dungeon.depth == -1) {
Dungeon.depth = Statistics.deepestFloor;
Dungeon.switchLevel( Dungeon.loadLevel( StartScene.curClass ), -1 );
} else {
Level level = Dungeon.loadLevel( StartScene.curClass );
Dungeon.switchLevel( level, Level.resizingNeeded ? level.adjustPos( Dungeon.hero.pos ) : Dungeon.hero.pos );
}
}
private void resurrect() throws IOException {
Actor.fixTime();
if (Dungeon.level.locked) {
Dungeon.hero.resurrect( Dungeon.depth );
Dungeon.depth--;
Level level = Dungeon.newLevel();
Dungeon.switchLevel( level, level.entrance );
} else {
Dungeon.hero.resurrect( -1 );
Dungeon.resetLevel();
}
}
@Override
protected void onBackPressed() {
//Do nothing
}
}
| Lobz/reforged-pixel-dungeon | src/com/shatteredpixel/shatteredpixeldungeon/scenes/InterlevelScene.java | Java | gpl-3.0 | 7,657 |
# Copyright 2013 The Servo Project Developers. See the COPYRIGHT
# file at the top-level directory of this distribution.
#
# Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
# http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
# <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
# option. This file may not be copied, modified, or distributed
# except according to those terms.
from __future__ import absolute_import, print_function, unicode_literals
import base64
import json
import os
import os.path as path
import re
import shutil
import sys
import urllib2
from mach.decorators import (
CommandArgument,
CommandProvider,
Command,
)
import servo.bootstrap as bootstrap
from servo.command_base import CommandBase, BIN_SUFFIX
from servo.util import download_bytes, download_file, extract, host_triple
@CommandProvider
class MachCommands(CommandBase):
@Command('env',
description='Print environment setup commands',
category='bootstrap')
def env(self):
env = self.build_env()
print("export PATH=%s" % env["PATH"])
if sys.platform == "darwin":
print("export DYLD_LIBRARY_PATH=%s" % env["DYLD_LIBRARY_PATH"])
else:
print("export LD_LIBRARY_PATH=%s" % env["LD_LIBRARY_PATH"])
@Command('bootstrap',
description='Install required packages for building.',
category='bootstrap')
@CommandArgument('--force', '-f',
action='store_true',
help='Boostrap without confirmation')
def bootstrap(self, force=False):
return bootstrap.bootstrap(self.context, force=force)
@Command('bootstrap-rust',
description='Download the Rust compiler',
category='bootstrap')
@CommandArgument('--force', '-f',
action='store_true',
help='Force download even if a copy already exists')
@CommandArgument('--target',
action='append',
default=[],
help='Download rust stdlib for specified target')
@CommandArgument('--stable',
action='store_true',
help='Use stable rustc version')
def bootstrap_rustc(self, force=False, target=[], stable=False):
self.set_use_stable_rust(stable)
version = self.rust_version()
rust_path = self.rust_path()
rust_dir = path.join(self.context.sharedir, "rust", rust_path)
install_dir = path.join(self.context.sharedir, "rust", version)
if not self.config["build"]["llvm-assertions"]:
install_dir += "-alt"
if not force and path.exists(path.join(rust_dir, "rustc", "bin", "rustc" + BIN_SUFFIX)):
print("Rust compiler already downloaded.", end=" ")
print("Use |bootstrap-rust --force| to download again.")
else:
if path.isdir(rust_dir):
shutil.rmtree(rust_dir)
os.makedirs(rust_dir)
# The nightly Rust compiler is hosted on the nightly server under the date with a name
# rustc-nightly-HOST-TRIPLE.tar.gz, whereas the stable compiler is named
# rustc-VERSION-HOST-TRIPLE.tar.gz. We just need to pull down and extract it,
# giving a directory name that will be the same as the tarball name (rustc is
# in that directory).
if stable:
tarball = "rustc-%s-%s.tar.gz" % (version, host_triple())
rustc_url = "https://static-rust-lang-org.s3.amazonaws.com/dist/" + tarball
else:
tarball = "%s/rustc-nightly-%s.tar.gz" % (version, host_triple())
base_url = "https://s3.amazonaws.com/rust-lang-ci/rustc-builds"
if not self.config["build"]["llvm-assertions"]:
base_url += "-alt"
rustc_url = base_url + "/" + tarball
tgz_file = rust_dir + '-rustc.tar.gz'
download_file("Rust compiler", rustc_url, tgz_file)
print("Extracting Rust compiler...")
extract(tgz_file, install_dir)
print("Rust compiler ready.")
# Each Rust stdlib has a name of the form `rust-std-nightly-TRIPLE.tar.gz` for the nightly
# releases, or rust-std-VERSION-TRIPLE.tar.gz for stable releases, with
# a directory of the name `rust-std-TRIPLE` inside and then a `lib` directory.
# This `lib` directory needs to be extracted and merged with the `rustc/lib`
# directory from the host compiler above.
nightly_suffix = "" if stable else "-nightly"
stable_version = "-{}".format(version) if stable else ""
lib_dir = path.join(install_dir,
"rustc{}{}-{}".format(nightly_suffix, stable_version, host_triple()),
"rustc", "lib", "rustlib")
# ensure that the libs for the host's target is downloaded
host_target = host_triple()
if host_target not in target:
target.append(host_target)
for target_triple in target:
target_lib_dir = path.join(lib_dir, target_triple)
if path.exists(target_lib_dir):
# No need to check for force. If --force the directory is already deleted
print("Rust lib for target {} already downloaded.".format(target_triple), end=" ")
print("Use |bootstrap-rust --force| to download again.")
continue
if self.use_stable_rust():
std_url = ("https://static-rust-lang-org.s3.amazonaws.com/dist/rust-std-%s-%s.tar.gz"
% (version, target_triple))
tgz_file = install_dir + ('rust-std-%s-%s.tar.gz' % (version, target_triple))
else:
std_url = ("https://s3.amazonaws.com/rust-lang-ci/rustc-builds/%s/rust-std-nightly-%s.tar.gz"
% (version, target_triple))
tgz_file = install_dir + ('rust-std-nightly-%s.tar.gz' % target_triple)
download_file("Host rust library for target %s" % target_triple, std_url, tgz_file)
print("Extracting Rust stdlib for target %s..." % target_triple)
extract(tgz_file, install_dir)
shutil.copytree(path.join(install_dir,
"rust-std%s%s-%s" % (nightly_suffix, stable_version, target_triple),
"rust-std-%s" % target_triple, "lib", "rustlib", target_triple),
path.join(install_dir,
"rustc%s%s-%s" % (nightly_suffix, stable_version, host_triple()),
"rustc", "lib", "rustlib", target_triple))
shutil.rmtree(path.join(install_dir,
"rust-std%s%s-%s" % (nightly_suffix, stable_version, target_triple)))
print("Rust {} libs ready.".format(target_triple))
@Command('bootstrap-rust-docs',
description='Download the Rust documentation',
category='bootstrap')
@CommandArgument('--force', '-f',
action='store_true',
help='Force download even if docs already exist')
def bootstrap_rustc_docs(self, force=False):
self.ensure_bootstrapped()
rust_root = self.config["tools"]["rust-root"]
docs_dir = path.join(rust_root, "doc")
if not force and path.exists(docs_dir):
print("Rust docs already downloaded.", end=" ")
print("Use |bootstrap-rust-docs --force| to download again.")
return
if path.isdir(docs_dir):
shutil.rmtree(docs_dir)
docs_name = self.rust_path().replace("rustc-", "rust-docs-")
docs_url = ("https://static-rust-lang-org.s3.amazonaws.com/dist/rust-docs-nightly-%s.tar.gz"
% host_triple())
tgz_file = path.join(rust_root, 'doc.tar.gz')
download_file("Rust docs", docs_url, tgz_file)
print("Extracting Rust docs...")
temp_dir = path.join(rust_root, "temp_docs")
if path.isdir(temp_dir):
shutil.rmtree(temp_dir)
extract(tgz_file, temp_dir)
shutil.move(path.join(temp_dir, docs_name.split("/")[1],
"rust-docs", "share", "doc", "rust", "html"),
docs_dir)
shutil.rmtree(temp_dir)
print("Rust docs ready.")
@Command('bootstrap-cargo',
description='Download the Cargo build tool',
category='bootstrap')
@CommandArgument('--force', '-f',
action='store_true',
help='Force download even if cargo already exists')
def bootstrap_cargo(self, force=False):
cargo_dir = path.join(self.context.sharedir, "cargo",
self.cargo_build_id())
if not force and path.exists(path.join(cargo_dir, "cargo", "bin", "cargo" + BIN_SUFFIX)):
print("Cargo already downloaded.", end=" ")
print("Use |bootstrap-cargo --force| to download again.")
return
if path.isdir(cargo_dir):
shutil.rmtree(cargo_dir)
os.makedirs(cargo_dir)
tgz_file = "cargo-nightly-%s.tar.gz" % host_triple()
nightly_url = "https://s3.amazonaws.com/rust-lang-ci/cargo-builds/%s/%s" % \
(self.cargo_build_id(), tgz_file)
download_file("Cargo nightly", nightly_url, tgz_file)
print("Extracting Cargo nightly...")
nightly_dir = path.join(cargo_dir,
path.basename(tgz_file).replace(".tar.gz", ""))
extract(tgz_file, cargo_dir, movedir=nightly_dir)
print("Cargo ready.")
@Command('update-hsts-preload',
description='Download the HSTS preload list',
category='bootstrap')
def bootstrap_hsts_preload(self, force=False):
preload_filename = "hsts_preload.json"
preload_path = path.join(self.context.topdir, "resources")
chromium_hsts_url = "https://chromium.googlesource.com/chromium/src" + \
"/net/+/master/http/transport_security_state_static.json?format=TEXT"
try:
content_base64 = download_bytes("Chromium HSTS preload list", chromium_hsts_url)
except urllib2.URLError:
print("Unable to download chromium HSTS preload list; are you connected to the internet?")
sys.exit(1)
content_decoded = base64.b64decode(content_base64)
# The chromium "json" has single line comments in it which, of course,
# are non-standard/non-valid json. Simply strip them out before parsing
content_json = re.sub(r'(^|\s+)//.*$', '', content_decoded, flags=re.MULTILINE)
try:
pins_and_static_preloads = json.loads(content_json)
entries = {
"entries": [
{
"host": e["name"],
"include_subdomains": e.get("include_subdomains", False)
}
for e in pins_and_static_preloads["entries"]
]
}
with open(path.join(preload_path, preload_filename), 'w') as fd:
json.dump(entries, fd, indent=4)
except ValueError, e:
print("Unable to parse chromium HSTS preload list, has the format changed?")
sys.exit(1)
@Command('update-pub-domains',
description='Download the public domains list and update resources/public_domains.txt',
category='bootstrap')
def bootstrap_pub_suffix(self, force=False):
list_url = "https://publicsuffix.org/list/public_suffix_list.dat"
dst_filename = path.join(self.context.topdir, "resources", "public_domains.txt")
not_implemented_case = re.compile(r'^[^*]+\*')
try:
content = download_bytes("Public suffix list", list_url)
except urllib2.URLError:
print("Unable to download the public suffix list; are you connected to the internet?")
sys.exit(1)
lines = [l.strip() for l in content.decode("utf8").split("\n")]
suffixes = [l for l in lines if not l.startswith("//") and not l == ""]
with open(dst_filename, "wb") as fo:
for suffix in suffixes:
if not_implemented_case.match(suffix):
print("Warning: the new list contains a case that servo can't handle: %s" % suffix)
fo.write(suffix.encode("idna") + "\n")
@Command('clean-nightlies',
description='Clean unused nightly builds of Rust and Cargo',
category='bootstrap')
@CommandArgument('--force', '-f',
action='store_true',
help='Actually remove stuff')
def clean_nightlies(self, force=False):
rust_current = self.rust_path().split('/')[0]
cargo_current = self.cargo_build_id()
print("Current Rust version: " + rust_current)
print("Current Cargo version: " + cargo_current)
removing_anything = False
for current, base in [(rust_current, "rust"), (cargo_current, "cargo")]:
base = path.join(self.context.sharedir, base)
for name in os.listdir(base):
if name != current:
removing_anything = True
name = path.join(base, name)
if force:
print("Removing " + name)
if os.path.isdir(name):
shutil.rmtree(name)
else:
os.remove(name)
else:
print("Would remove " + name)
if not removing_anything:
print("Nothing to remove.")
elif not force:
print("Nothing done. "
"Run `./mach clean-nightlies -f` to actually remove.")
| ddrmanxbxfr/servo | python/servo/bootstrap_commands.py | Python | mpl-2.0 | 14,058 |
/* TL.Point
Inspired by Leaflet
TL.Point represents a point with x and y coordinates.
================================================== */
TL.Point = function (/*Number*/ x, /*Number*/ y, /*Boolean*/ round) {
this.x = (round ? Math.round(x) : x);
this.y = (round ? Math.round(y) : y);
};
TL.Point.prototype = {
add: function (point) {
return this.clone()._add(point);
},
_add: function (point) {
this.x += point.x;
this.y += point.y;
return this;
},
subtract: function (point) {
return this.clone()._subtract(point);
},
// destructive subtract (faster)
_subtract: function (point) {
this.x -= point.x;
this.y -= point.y;
return this;
},
divideBy: function (num, round) {
return new TL.Point(this.x / num, this.y / num, round);
},
multiplyBy: function (num) {
return new TL.Point(this.x * num, this.y * num);
},
distanceTo: function (point) {
var x = point.x - this.x,
y = point.y - this.y;
return Math.sqrt(x * x + y * y);
},
round: function () {
return this.clone()._round();
},
// destructive round
_round: function () {
this.x = Math.round(this.x);
this.y = Math.round(this.y);
return this;
},
clone: function () {
return new TL.Point(this.x, this.y);
},
toString: function () {
return 'Point(' +
TL.Util.formatNum(this.x) + ', ' +
TL.Util.formatNum(this.y) + ')';
}
}; | tkandala/TimelineJS3 | source/js/dom/TL.Point.js | JavaScript | mpl-2.0 | 1,360 |
// Copyright 2014 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package model_test
import (
"errors"
gc "gopkg.in/check.v1"
"gopkg.in/juju/names.v2"
"github.com/juju/juju/api"
jujucloud "github.com/juju/juju/cloud"
"github.com/juju/juju/environs/config"
"github.com/juju/juju/testing"
)
// ModelConfig related fake environment for testing.
type fakeEnvSuite struct {
testing.FakeJujuXDGDataHomeSuite
fake *fakeEnvAPI
}
func (s *fakeEnvSuite) SetUpTest(c *gc.C) {
s.FakeJujuXDGDataHomeSuite.SetUpTest(c)
s.fake = &fakeEnvAPI{
values: map[string]interface{}{
"name": "test-model",
"special": "special value",
"running": true,
},
defaults: config.ConfigValues{
"attr": {Value: "foo", Source: "default"},
"attr2": {Value: "bar", Source: "controller"},
"attr3": {Value: "baz", Source: "region"},
},
}
}
type fakeEnvAPI struct {
values map[string]interface{}
cloud, region string
defaults config.ConfigValues
err error
keys []string
resetKeys []string
}
func (f *fakeEnvAPI) Close() error {
return nil
}
func (f *fakeEnvAPI) ModelGet() (map[string]interface{}, error) {
return f.values, nil
}
func (f *fakeEnvAPI) ModelGetWithMetadata() (config.ConfigValues, error) {
result := make(config.ConfigValues)
for name, val := range f.values {
result[name] = config.ConfigValue{Value: val, Source: "model"}
}
return result, nil
}
func (f *fakeEnvAPI) ModelSet(config map[string]interface{}) error {
f.values = config
return f.err
}
func (f *fakeEnvAPI) ModelUnset(keys ...string) error {
f.resetKeys = keys
return f.err
}
// ModelDefaults related fake environment for testing.
type fakeModelDefaultEnvSuite struct {
testing.FakeJujuXDGDataHomeSuite
fakeAPIRoot *fakeAPIConnection
fakeDefaultsAPI *fakeModelDefaultsAPI
fakeCloudAPI *fakeCloudAPI
}
func (s *fakeModelDefaultEnvSuite) SetUpTest(c *gc.C) {
s.FakeJujuXDGDataHomeSuite.SetUpTest(c)
s.fakeAPIRoot = &fakeAPIConnection{}
s.fakeDefaultsAPI = &fakeModelDefaultsAPI{
values: map[string]interface{}{
"name": "test-model",
"special": "special value",
"running": true,
},
defaults: config.ModelDefaultAttributes{
"attr": {Default: "foo"},
"attr2": {
Controller: "bar",
Regions: []config.RegionDefaultValue{{
"dummy-region",
"dummy-value",
}, {
"another-region",
"another-value",
}}},
},
}
s.fakeCloudAPI = &fakeCloudAPI{
clouds: map[string]jujucloud.Cloud{
"cloud-dummy": {
Type: "dummy-cloud",
Regions: []jujucloud.Region{
{Name: "dummy-region"},
{Name: "another-region"},
},
},
},
}
}
type fakeAPIConnection struct {
api.Connection
}
func (*fakeAPIConnection) Close() error {
return nil
}
type fakeModelDefaultsAPI struct {
values map[string]interface{}
cloud, region string
defaults config.ModelDefaultAttributes
err error
keys []string
}
func (f *fakeModelDefaultsAPI) Close() error {
return nil
}
func (f *fakeModelDefaultsAPI) ModelGet() (map[string]interface{}, error) {
return f.values, nil
}
func (f *fakeModelDefaultsAPI) ModelDefaults() (config.ModelDefaultAttributes, error) {
return f.defaults, nil
}
func (f *fakeModelDefaultsAPI) SetModelDefaults(cloud, region string, cfg map[string]interface{}) error {
if f.err != nil {
return f.err
}
f.cloud = cloud
f.region = region
for name, val := range cfg {
f.defaults[name] = config.AttributeDefaultValues{Controller: val}
}
return nil
}
func (f *fakeModelDefaultsAPI) UnsetModelDefaults(cloud, region string, keys ...string) error {
if f.err != nil {
return f.err
}
f.cloud = cloud
f.region = region
for _, key := range keys {
delete(f.defaults, key)
}
return nil
}
func (f *fakeModelDefaultsAPI) ModelSet(config map[string]interface{}) error {
f.values = config
return f.err
}
func (f *fakeModelDefaultsAPI) ModelUnset(keys ...string) error {
f.keys = keys
return f.err
}
type fakeCloudAPI struct {
clouds map[string]jujucloud.Cloud
}
func (f *fakeCloudAPI) Close() error { return nil }
func (f *fakeCloudAPI) DefaultCloud() (names.CloudTag, error) {
return names.NewCloudTag("dummy"), nil
}
func (f *fakeCloudAPI) Cloud(name names.CloudTag) (jujucloud.Cloud, error) {
var (
c jujucloud.Cloud
ok bool
)
if c, ok = f.clouds[name.String()]; !ok {
return jujucloud.Cloud{}, errors.New("Unknown cloud")
}
return c, nil
}
| gabriel-samfira/juju | cmd/juju/model/fakeenv_test.go | GO | agpl-3.0 | 4,463 |
<?php return array(
'field workspace description' => '説明',
'workspace description' => 'ワークスペースの説明',
'add new workspace' => '新しいワークスペースを追加',
'add your first workspace' => '最初のワークスペースを追加',
'you have no workspaces yet' => 'まだワークスペースがありません',
'filter by workspaces' => 'ワークスペースで絞り込み',
'filter by tags' => 'タグで絞り込み',
); ?>
| md11235/fengoffice | plugins/workspaces/language/ja_jp/lang.php | PHP | agpl-3.0 | 468 |
/*
* The Kuali Financial System, a comprehensive financial management system for higher education.
*
* Copyright 2005-2014 The Kuali Foundation
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU 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/>.
*/
package org.kuali.kfs.module.cg.service.impl;
import java.util.ArrayList;
import java.util.List;
import org.kuali.kfs.module.cg.CGPropertyConstants;
import org.kuali.kfs.module.cg.service.ContractsAndGrantsBillingService;
/**
* Service with methods related to the Contracts & Grants Billing (CGB) enhancement.
*/
public class ContractsAndGrantsBillingServiceImpl implements ContractsAndGrantsBillingService {
@Override
public List<String> getAgencyContractsGrantsBillingSectionIds() {
List<String> contractsGrantsSectionIds = new ArrayList<String>();
contractsGrantsSectionIds.add(CGPropertyConstants.SectionId.AGENCY_ADDRESS_SECTION_ID);
contractsGrantsSectionIds.add(CGPropertyConstants.SectionId.AGENCY_ADDRESSES_SECTION_ID);
contractsGrantsSectionIds.add(CGPropertyConstants.SectionId.AGENCY_COLLECTIONS_MAINTENANCE_SECTION_ID);
contractsGrantsSectionIds.add(CGPropertyConstants.SectionId.AGENCY_CONTRACTS_AND_GRANTS_SECTION_ID);
contractsGrantsSectionIds.add(CGPropertyConstants.SectionId.AGENCY_CUSTOMER_SECTION_ID);
return contractsGrantsSectionIds;
}
@Override
public List<String> getAwardContractsGrantsBillingSectionIds() {
List<String> contractsGrantsSectionIds = new ArrayList<String>();
contractsGrantsSectionIds.add(CGPropertyConstants.SectionId.AWARD_FUND_MANAGERS_SECTION_ID);
contractsGrantsSectionIds.add(CGPropertyConstants.SectionId.AWARD_INVOICING_SECTION_ID);
contractsGrantsSectionIds.add(CGPropertyConstants.SectionId.AWARD_MILESTONE_SCHEDULE_SECTION_ID);
contractsGrantsSectionIds.add(CGPropertyConstants.SectionId.AWARD_PREDETERMINED_BILLING_SCHEDULE_SECTION_ID);
return contractsGrantsSectionIds;
}
}
| bhutchinson/kfs | kfs-cg/src/main/java/org/kuali/kfs/module/cg/service/impl/ContractsAndGrantsBillingServiceImpl.java | Java | agpl-3.0 | 2,589 |
namespace N2.Configuration
{
public enum ErrorAction
{
None,
Email
}
}
| DejanMilicic/n2cms | src/Framework/N2/Configuration/ErrorAction.cs | C# | lgpl-2.1 | 99 |