code
stringlengths 4
1.01M
| language
stringclasses 2
values |
---|---|
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.felix.karaf.tooling.features;
import org.apache.maven.artifact.Artifact;
import org.easymock.EasyMock;
import static org.easymock.EasyMock.*;
import junit.framework.TestCase;
/**
* Test cases for {@link GenerateFeaturesXmlMojo}
*/
public class GenerateFeaturesXmlMojoTest extends TestCase {
public void testToString() throws Exception {
Artifact artifact = EasyMock.createMock(Artifact.class);
expect(artifact.getGroupId()).andReturn("org.apache.felix.karaf.test");
expect(artifact.getArtifactId()).andReturn("test-artifact");
expect(artifact.getVersion()).andReturn("1.2.3");
replay(artifact);
assertEquals("org.apache.felix.karaf.test/test-artifact/1.2.3", GenerateFeaturesXmlMojo.toString(artifact));
}
}
| Java |
How to access Feedly RSS feed from the command line on Linux
================================================================================
In case you didn't know, [Feedly][1] is one of the most popular online news aggregation services. It offers seamlessly unified news reading experience across desktops, Android and iOS devices via browser extensions and mobile apps. Feedly took on the demise of Google Reader in 2013, quickly gaining a lot of then Google Reader users. I was one of them, and Feedly has remained my default RSS reader since then.
While I appreciate the sleek interface of Feedly's browser extensions and mobile apps, there is yet another way to access Feedly: Linux command-line. That's right. You can access Feedly's news feed from the command line. Sounds geeky? Well, at least for system admins who live on headless servers, this can be pretty useful.
Enter [Feednix][2]. This open-source software is a Feedly's unofficial command-line client written in C++. It allows you to browse Feedly's news feed in ncurses-based terminal interface. By default, Feednix is linked with a console-based browser called w3m to allow you to read articles within a terminal environment. You can choose to read from your favorite web browser though.
In this tutorial, I am going to demonstrate how to install and configure Feednix to access Feedly from the command line.
### Install Feednix on Linux ###
You can build Feednix from the source using the following instructions. At the moment, the "Ubuntu-stable" branch of the official Github repository has the most up-to-date code. So let's use this branch to build it.
As prerequisites, you will need to install a couple of development libraries, as well as w3m browser.
#### Debian, Ubuntu or Linux Mint ####
$ sudo apt-get install git automake g++ make libncursesw5-dev libjsoncpp-dev libcurl4-gnutls-dev w3m
$ git clone -b Ubuntu-stable https://github.com/Jarkore/Feednix.git
$ cd Feednix
$ ./autogen.sh
$ ./configure
$ make
$ sudo make install
#### Fedora ####
$ sudo yum groupinstall "C Development Tools and Libraries"
$ sudo yum install gcc-c++ git automake make ncurses-devel jsoncpp-devel libcurl-devel w3m
$ git clone -b Ubuntu-stable https://github.com/Jarkore/Feednix.git
$ cd Feednix
$ ./autogen.sh
$ ./configure
$ make
$ sudo make install
Arch Linux
On Arch Linux, you can easily install Feednix from [AUR][3].
### Configure Feednix for the First Time ###
After installing it, launch Feednix as follows.
$ feednix
The first time you run Feednix, it will pop up a web browser window, where you need to sign up to create a Feedly's user ID and its corresponding developer access token. If you are running Feednix in a desktop-less environment, open a web browser on another computer, and go to https://feedly.com/v3/auth/dev.

Once you sign in, you will see your Feedly user ID generated.

To retrieve an access token, you need to follow the token link sent to your email address in your browser. Only then will you see the window showing your user ID, access token, and its expiration date. Be aware that access token is quite long (more than 200 characters). The token appears in a horizontally scrollable text box, so make sure to copy the whole access token string.

Paste your user ID and access token into the Feednix' command-line prompt.
[Enter User ID] >> XXXXXX
[Enter token] >> YYYYY
After successful authentication, you will see an initial Feednix screen with two panes. The left-side "Categories" pane shows a list of news categories, while the right-side "Posts" pane displays a list of news articles in the current category.

### Read News in Feednix ###
Here I am going to briefly describe how to access Feedly via Feednix.
#### Navigate Feednix ####
As I mentioned, the top screen of Feednix consists of two panes. To switch focus between the two panes, use TAB key. To move up and down the list within a pane, use 'j' and 'k' keys, respectively. These keyboard shorcuts are obviously inspired by Vim text editor.
#### Read an Article ####
To read a particular article, press 'o' key at the current article. It will invoke w2m browser, and load the article inside the browser. Once you are done reading, press 'q' to quit the browser, and come back to Feednix. If your environment can open a web browser, you can press 'O' to load an article on your default web browser such as Firefox.

#### Subscribe to a News Feed ####
You can add any arbitrary RSS news feed to your Feedly account from Feednix interface. To do so, simply press 'a' key. This will show "[ENTER FEED]:" prompt at the bottom of the screen. After typing the RSS feed, go ahead and fill in the name of the feed and its preferred category.

#### Summary ####
As you can see, Feednix is a quite convenient and easy-to-use command-line RSS reader. If you are a command-line junkie as well as a regular Feedly user, Feednix is definitely worth trying. I have been communicating with the creator of Feednix, Jarkore, to troubleshoot some issue. As far as I can tell, he is very active in responding to bug reports and fixing bugs. I encourage you to try out Feednix and let him know your feedback.
--------------------------------------------------------------------------------
via: http://xmodulo.com/feedly-rss-feed-command-line-linux.html
作者:[Dan Nanni][a]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创翻译,[Linux中国](http://linux.cn/) 荣誉推出
[a]:http://xmodulo.com/author/nanni
[1]:https://feedly.com/
[2]:https://github.com/Jarkore/Feednix
[3]:https://aur.archlinux.org/packages/feednix/ | Java |
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<!-- template designed by Marco Von Ballmoos -->
<title></title>
<link rel="stylesheet" href="media/stylesheet.css" />
</head>
<body>
<a name="top"></a>
<h2>[log4php] element index</h2>
<a href="elementindex.html">All elements</a>
<br />
<div class="index-letter-menu">
<a class="index-letter" href="elementindex_log4php.html#a">a</a>
<a class="index-letter" href="elementindex_log4php.html#c">c</a>
<a class="index-letter" href="elementindex_log4php.html#d">d</a>
<a class="index-letter" href="elementindex_log4php.html#e">e</a>
<a class="index-letter" href="elementindex_log4php.html#f">f</a>
<a class="index-letter" href="elementindex_log4php.html#g">g</a>
<a class="index-letter" href="elementindex_log4php.html#h">h</a>
<a class="index-letter" href="elementindex_log4php.html#i">i</a>
<a class="index-letter" href="elementindex_log4php.html#l">l</a>
<a class="index-letter" href="elementindex_log4php.html#m">m</a>
<a class="index-letter" href="elementindex_log4php.html#n">n</a>
<a class="index-letter" href="elementindex_log4php.html#o">o</a>
<a class="index-letter" href="elementindex_log4php.html#p">p</a>
<a class="index-letter" href="elementindex_log4php.html#r">r</a>
<a class="index-letter" href="elementindex_log4php.html#s">s</a>
<a class="index-letter" href="elementindex_log4php.html#t">t</a>
<a class="index-letter" href="elementindex_log4php.html#u">u</a>
<a class="index-letter" href="elementindex_log4php.html#w">w</a>
<a class="index-letter" href="elementindex_log4php.html#x">x</a>
<a class="index-letter" href="elementindex_log4php.html#_">_</a>
</div>
<a name="_"></a>
<div class="index-letter-section">
<div style="float: left" class="index-letter-title">_</div>
<div style="float: right"><a href="#top">top</a></div>
<div style="clear: both"></div>
</div>
<dl>
<dt class="field">
<span class="method-title">__construct</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerReflectionUtils.html#method__construct">LoggerReflectionUtils::__construct()</a> in LoggerReflectionUtils.php</div>
<div class="index-item-description">Create a new LoggerReflectionUtils for the specified Object.</div>
</dd>
<dt class="field">
<span class="method-title">__construct</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerRoot.html#method__construct">LoggerRoot::__construct()</a> in LoggerRoot.php</div>
<div class="index-item-description">Constructor</div>
</dd>
<dt class="field">
<span class="method-title">__construct</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLoggingEvent.html#method__construct">LoggerLoggingEvent::__construct()</a> in LoggerLoggingEvent.php</div>
<div class="index-item-description">Instantiate a LoggingEvent from the supplied parameters.</div>
</dd>
<dt class="field">
<span class="method-title">__construct</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLocationInfo.html#method__construct">LoggerLocationInfo::__construct()</a> in LoggerLocationInfo.php</div>
<div class="index-item-description">Instantiate location information based on a <a href="http://www.php.net/debug_backtrace">http://www.php.net/debug_backtrace</a>.</div>
</dd>
<dt class="field">
<span class="method-title">__construct</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerHierarchy.html#method__construct">LoggerHierarchy::__construct()</a> in LoggerHierarchy.php</div>
<div class="index-item-description">Create a new logger hierarchy.</div>
</dd>
<dt class="field">
<span class="method-title">__construct</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/Logger.html#method__construct">Logger::__construct()</a> in Logger.php</div>
<div class="index-item-description">Constructor.</div>
</dd>
<dt class="field">
<span class="method-title">__construct</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerAppender.html#method__construct">LoggerAppender::__construct()</a> in LoggerAppender.php</div>
<div class="index-item-description">Constructor</div>
</dd>
<dt class="field">
<span class="method-title">__sleep</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLoggingEvent.html#method__sleep">LoggerLoggingEvent::__sleep()</a> in LoggerLoggingEvent.php</div>
<div class="index-item-description">Avoid serialization of the $logger object</div>
</dd>
<dt class="field">
<span class="method-title">__construct</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderAdodb.html#method__construct">LoggerAppenderAdodb::__construct()</a> in LoggerAppenderAdodb.php</div>
<div class="index-item-description">Constructor.</div>
</dd>
<dt class="field">
<span class="method-title">__construct</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderPDO.html#method__construct">LoggerAppenderPDO::__construct()</a> in LoggerAppenderPDO.php</div>
<div class="index-item-description">Constructor.</div>
</dd>
<dt class="field">
<span class="method-title">__construct</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderPhp.html#method__construct">LoggerAppenderPhp::__construct()</a> in LoggerAppenderPhp.php</div>
</dd>
<dt class="field">
<span class="method-title">__construct</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderSyslog.html#method__construct">LoggerAppenderSyslog::__construct()</a> in LoggerAppenderSyslog.php</div>
</dd>
<dt class="field">
<span class="method-title">__construct</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderMail.html#method__construct">LoggerAppenderMail::__construct()</a> in LoggerAppenderMail.php</div>
<div class="index-item-description">Constructor.</div>
</dd>
<dt class="field">
<span class="method-title">__construct</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderMailEvent.html#method__construct">LoggerAppenderMailEvent::__construct()</a> in LoggerAppenderMailEvent.php</div>
<div class="index-item-description">Constructor.</div>
</dd>
<dt class="field">
<span class="method-title">__construct</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderFile.html#method__construct">LoggerAppenderFile::__construct()</a> in LoggerAppenderFile.php</div>
</dd>
<dt class="field">
<span class="method-title">__construct</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderEcho.html#method__construct">LoggerAppenderEcho::__construct()</a> in LoggerAppenderEcho.php</div>
</dd>
<dt class="field">
<span class="method-title">__destruct</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderRollingFile.html#method__destruct">LoggerAppenderRollingFile::__destruct()</a> in LoggerAppenderRollingFile.php</div>
</dd>
<dt class="field">
<span class="method-title">__destruct</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderPhp.html#method__destruct">LoggerAppenderPhp::__destruct()</a> in LoggerAppenderPhp.php</div>
</dd>
<dt class="field">
<span class="method-title">__destruct</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderSocket.html#method__destruct">LoggerAppenderSocket::__destruct()</a> in LoggerAppenderSocket.php</div>
</dd>
<dt class="field">
<span class="method-title">__destruct</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderConsole.html#method__destruct">LoggerAppenderConsole::__destruct()</a> in LoggerAppenderConsole.php</div>
</dd>
<dt class="field">
<span class="method-title">__destruct</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderSyslog.html#method__destruct">LoggerAppenderSyslog::__destruct()</a> in LoggerAppenderSyslog.php</div>
</dd>
<dt class="field">
<span class="method-title">__destruct</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderDailyFile.html#method__destruct">LoggerAppenderDailyFile::__destruct()</a> in LoggerAppenderDailyFile.php</div>
</dd>
<dt class="field">
<span class="method-title">__destruct</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderPDO.html#method__destruct">LoggerAppenderPDO::__destruct()</a> in LoggerAppenderPDO.php</div>
</dd>
<dt class="field">
<span class="method-title">__destruct</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderEcho.html#method__destruct">LoggerAppenderEcho::__destruct()</a> in LoggerAppenderEcho.php</div>
</dd>
<dt class="field">
<span class="method-title">__destruct</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderMailEvent.html#method__destruct">LoggerAppenderMailEvent::__destruct()</a> in LoggerAppenderMailEvent.php</div>
</dd>
<dt class="field">
<span class="method-title">__destruct</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderNull.html#method__destruct">LoggerAppenderNull::__destruct()</a> in LoggerAppenderNull.php</div>
</dd>
<dt class="field">
<span class="method-title">__destruct</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderFile.html#method__destruct">LoggerAppenderFile::__destruct()</a> in LoggerAppenderFile.php</div>
</dd>
<dt class="field">
<span class="method-title">__destruct</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderMail.html#method__destruct">LoggerAppenderMail::__destruct()</a> in LoggerAppenderMail.php</div>
</dd>
<dt class="field">
<span class="method-title">__construct</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/configurators/LoggerConfiguratorXml.html#method__construct">LoggerConfiguratorXml::__construct()</a> in LoggerConfiguratorXml.php</div>
<div class="index-item-description">Constructor</div>
</dd>
<dt class="field">
<span class="method-title">__construct</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/configurators/LoggerConfiguratorIni.html#method__construct">LoggerConfiguratorIni::__construct()</a> in LoggerConfiguratorIni.php</div>
<div class="index-item-description">Constructor</div>
</dd>
<dt class="field">
<span class="method-title">__construct</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerMDCPatternConverter.html#method__construct">LoggerMDCPatternConverter::__construct()</a> in LoggerMDCPatternConverter.php</div>
<div class="index-item-description">Constructor</div>
</dd>
<dt class="field">
<span class="method-title">__construct</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerNamedPatternConverter.html#method__construct">LoggerNamedPatternConverter::__construct()</a> in LoggerNamedPatternConverter.php</div>
<div class="index-item-description">Constructor</div>
</dd>
<dt class="field">
<span class="method-title">__construct</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerPatternConverter.html#method__construct">LoggerPatternConverter::__construct()</a> in LoggerPatternConverter.php</div>
<div class="index-item-description">Constructor</div>
</dd>
<dt class="field">
<span class="method-title">__construct</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerPatternParser.html#method__construct">LoggerPatternParser::__construct()</a> in LoggerPatternParser.php</div>
<div class="index-item-description">Constructor</div>
</dd>
<dt class="field">
<span class="method-title">__construct</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerLocationPatternConverter.html#method__construct">LoggerLocationPatternConverter::__construct()</a> in LoggerLocationPatternConverter.php</div>
<div class="index-item-description">Constructor</div>
</dd>
<dt class="field">
<span class="method-title">__construct</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerLiteralPatternConverter.html#method__construct">LoggerLiteralPatternConverter::__construct()</a> in LoggerLiteralPatternConverter.php</div>
<div class="index-item-description">Constructor</div>
</dd>
<dt class="field">
<span class="method-title">__construct</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerCategoryPatternConverter.html#method__construct">LoggerCategoryPatternConverter::__construct()</a> in LoggerCategoryPatternConverter.php</div>
<div class="index-item-description">Constructor</div>
</dd>
<dt class="field">
<span class="method-title">__construct</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerClassNamePatternConverter.html#method__construct">LoggerClassNamePatternConverter::__construct()</a> in LoggerClassNamePatternConverter.php</div>
<div class="index-item-description">Constructor</div>
</dd>
<dt class="field">
<span class="method-title">__construct</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerDatePatternConverter.html#method__construct">LoggerDatePatternConverter::__construct()</a> in LoggerDatePatternConverter.php</div>
<div class="index-item-description">Constructor</div>
</dd>
<dt class="field">
<span class="method-title">__construct</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerFormattingInfo.html#method__construct">LoggerFormattingInfo::__construct()</a> in LoggerFormattingInfo.php</div>
<div class="index-item-description">Constructor</div>
</dd>
<dt class="field">
<span class="method-title">__construct</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerBasicPatternConverter.html#method__construct">LoggerBasicPatternConverter::__construct()</a> in LoggerBasicPatternConverter.php</div>
<div class="index-item-description">Constructor</div>
</dd>
<dt class="field">
<span class="method-title">__construct</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutTTCC.html#method__construct">LoggerLayoutTTCC::__construct()</a> in LoggerLayoutTTCC.php</div>
<div class="index-item-description">Constructor</div>
</dd>
<dt class="field">
<span class="method-title">__construct</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutSimple.html#method__construct">LoggerLayoutSimple::__construct()</a> in LoggerLayoutSimple.php</div>
<div class="index-item-description">Constructor</div>
</dd>
<dt class="field">
<span class="method-title">__construct</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutPattern.html#method__construct">LoggerLayoutPattern::__construct()</a> in LoggerLayoutPattern.php</div>
<div class="index-item-description">Constructs a PatternLayout using the DEFAULT_LAYOUT_PATTERN.</div>
</dd>
<dt class="field">
<span class="method-title">__construct</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutHtml.html#method__construct">LoggerLayoutHtml::__construct()</a> in LoggerLayoutHtml.php</div>
<div class="index-item-description">Constructor</div>
</dd>
<dt class="field">
<span class="method-title">__construct</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/renderers/LoggerRendererMap.html#method__construct">LoggerRendererMap::__construct()</a> in LoggerRendererMap.php</div>
<div class="index-item-description">Constructor</div>
</dd>
</dl>
<a name="a"></a>
<div class="index-letter-section">
<div style="float: left" class="index-letter-title">a</div>
<div style="float: right"><a href="#top">top</a></div>
<div style="clear: both"></div>
</div>
<dl>
<dt class="field">
<span class="var-title">$appenderPool</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerAppenderPool.html#var$appenderPool">LoggerAppenderPool::$appenderPool</a> in LoggerAppenderPool.php</div>
</dd>
<dt class="field">
ACCEPT
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerFilter.html#constACCEPT">LoggerFilter::ACCEPT</a> in LoggerFilter.php</div>
<div class="index-item-description">The log event must be logged immediately without consulting with the remaining filters, if any, in the chain.</div>
</dd>
<dt class="field">
<span class="method-title">activate</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerReflectionUtils.html#methodactivate">LoggerReflectionUtils::activate()</a> in LoggerReflectionUtils.php</div>
</dd>
<dt class="field">
<span class="method-title">activateOptions</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerFilter.html#methodactivateOptions">LoggerFilter::activateOptions()</a> in LoggerFilter.php</div>
<div class="index-item-description">Usually filters options become active when set. We provide a default do-nothing implementation for convenience.</div>
</dd>
<dt class="field">
<span class="method-title">activateOptions</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerAppender.html#methodactivateOptions">LoggerAppender::activateOptions()</a> in LoggerAppender.php</div>
<div class="index-item-description">Derived appenders should override this method if option structure requires it.</div>
</dd>
<dt class="field">
<span class="method-title">activateOptions</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLayout.html#methodactivateOptions">LoggerLayout::activateOptions()</a> in LoggerLayout.php</div>
<div class="index-item-description">Activates options for this layout.</div>
</dd>
<dt class="field">
<span class="method-title">addAppender</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/Logger.html#methodaddAppender">Logger::addAppender()</a> in Logger.php</div>
<div class="index-item-description">Add a new Appender to the list of appenders of this Category instance.</div>
</dd>
<dt class="field">
<span class="method-title">addFilter</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerAppender.html#methodaddFilter">LoggerAppender::addFilter()</a> in LoggerAppender.php</div>
<div class="index-item-description">Add a filter to the end of the filter list.</div>
</dd>
<dt class="field">
<span class="method-title">addNext</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerFilter.html#methodaddNext">LoggerFilter::addNext()</a> in LoggerFilter.php</div>
<div class="index-item-description">Adds a new filter to the filter chain this filter is a part of.</div>
</dd>
<dt class="field">
ALL
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLevel.html#constALL">LoggerLevel::ALL</a> in LoggerLevel.php</div>
</dd>
<dt class="field">
<span class="method-title">append</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerAppender.html#methodappend">LoggerAppender::append()</a> in LoggerAppender.php</div>
<div class="index-item-description">Subclasses of <a href="log4php/LoggerAppender.html">LoggerAppender</a> should implement this method to perform actual logging.</div>
</dd>
<dt class="field">
<span class="method-title">assertLog</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/Logger.html#methodassertLog">Logger::assertLog()</a> in Logger.php</div>
<div class="index-item-description">If assertion parameter is false, then logs msg as an error statement.</div>
</dd>
<dt class="field">
<span class="method-title">autoload</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/Logger.html#methodautoload">Logger::autoload()</a> in Logger.php</div>
<div class="index-item-description">Class autoloader This method is provided to be invoked within an __autoload() magic method.</div>
</dd>
<dt class="field">
<span class="method-title">activateOptions</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderMailEvent.html#methodactivateOptions">LoggerAppenderMailEvent::activateOptions()</a> in LoggerAppenderMailEvent.php</div>
</dd>
<dt class="field">
<span class="method-title">activateOptions</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderMail.html#methodactivateOptions">LoggerAppenderMail::activateOptions()</a> in LoggerAppenderMail.php</div>
</dd>
<dt class="field">
<span class="method-title">activateOptions</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderAdodb.html#methodactivateOptions">LoggerAppenderAdodb::activateOptions()</a> in LoggerAppenderAdodb.php</div>
<div class="index-item-description">Setup db connection.</div>
</dd>
<dt class="field">
<span class="method-title">activateOptions</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderNull.html#methodactivateOptions">LoggerAppenderNull::activateOptions()</a> in LoggerAppenderNull.php</div>
</dd>
<dt class="field">
<span class="method-title">activateOptions</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderPDO.html#methodactivateOptions">LoggerAppenderPDO::activateOptions()</a> in LoggerAppenderPDO.php</div>
<div class="index-item-description">Setup db connection.</div>
</dd>
<dt class="field">
<span class="method-title">activateOptions</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderPhp.html#methodactivateOptions">LoggerAppenderPhp::activateOptions()</a> in LoggerAppenderPhp.php</div>
</dd>
<dt class="field">
<span class="method-title">activateOptions</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderSocket.html#methodactivateOptions">LoggerAppenderSocket::activateOptions()</a> in LoggerAppenderSocket.php</div>
<div class="index-item-description">Create a socket connection using defined parameters</div>
</dd>
<dt class="field">
<span class="method-title">activateOptions</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderSyslog.html#methodactivateOptions">LoggerAppenderSyslog::activateOptions()</a> in LoggerAppenderSyslog.php</div>
</dd>
<dt class="field">
<span class="method-title">activateOptions</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderConsole.html#methodactivateOptions">LoggerAppenderConsole::activateOptions()</a> in LoggerAppenderConsole.php</div>
</dd>
<dt class="field">
<span class="method-title">activateOptions</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderFile.html#methodactivateOptions">LoggerAppenderFile::activateOptions()</a> in LoggerAppenderFile.php</div>
</dd>
<dt class="field">
<span class="method-title">activateOptions</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderEcho.html#methodactivateOptions">LoggerAppenderEcho::activateOptions()</a> in LoggerAppenderEcho.php</div>
</dd>
<dt class="field">
<span class="method-title">append</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderSyslog.html#methodappend">LoggerAppenderSyslog::append()</a> in LoggerAppenderSyslog.php</div>
</dd>
<dt class="field">
<span class="method-title">append</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderPhp.html#methodappend">LoggerAppenderPhp::append()</a> in LoggerAppenderPhp.php</div>
</dd>
<dt class="field">
<span class="method-title">append</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderSocket.html#methodappend">LoggerAppenderSocket::append()</a> in LoggerAppenderSocket.php</div>
</dd>
<dt class="field">
<span class="method-title">append</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderRollingFile.html#methodappend">LoggerAppenderRollingFile::append()</a> in LoggerAppenderRollingFile.php</div>
</dd>
<dt class="field">
<span class="method-title">append</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderMailEvent.html#methodappend">LoggerAppenderMailEvent::append()</a> in LoggerAppenderMailEvent.php</div>
</dd>
<dt class="field">
<span class="method-title">append</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderConsole.html#methodappend">LoggerAppenderConsole::append()</a> in LoggerAppenderConsole.php</div>
</dd>
<dt class="field">
<span class="method-title">append</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderAdodb.html#methodappend">LoggerAppenderAdodb::append()</a> in LoggerAppenderAdodb.php</div>
</dd>
<dt class="field">
<span class="method-title">append</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderEcho.html#methodappend">LoggerAppenderEcho::append()</a> in LoggerAppenderEcho.php</div>
</dd>
<dt class="field">
<span class="method-title">append</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderFile.html#methodappend">LoggerAppenderFile::append()</a> in LoggerAppenderFile.php</div>
</dd>
<dt class="field">
<span class="method-title">append</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderNull.html#methodappend">LoggerAppenderNull::append()</a> in LoggerAppenderNull.php</div>
<div class="index-item-description">Do nothing.</div>
</dd>
<dt class="field">
<span class="method-title">append</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderMail.html#methodappend">LoggerAppenderMail::append()</a> in LoggerAppenderMail.php</div>
</dd>
<dt class="field">
<span class="method-title">append</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderPDO.html#methodappend">LoggerAppenderPDO::append()</a> in LoggerAppenderPDO.php</div>
<div class="index-item-description">Appends a new event to the database.</div>
</dd>
<dt class="field">
ADDITIVITY_PREFIX
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/configurators/LoggerConfiguratorIni.html#constADDITIVITY_PREFIX">LoggerConfiguratorIni::ADDITIVITY_PREFIX</a> in LoggerConfiguratorIni.php</div>
</dd>
<dt class="field">
APPENDER_PREFIX
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/configurators/LoggerConfiguratorIni.html#constAPPENDER_PREFIX">LoggerConfiguratorIni::APPENDER_PREFIX</a> in LoggerConfiguratorIni.php</div>
</dd>
<dt class="field">
APPENDER_STATE
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/configurators/LoggerConfiguratorXml.html#constAPPENDER_STATE">LoggerConfiguratorXml::APPENDER_STATE</a> in LoggerConfiguratorXml.php</div>
</dd>
<dt class="field">
<span class="method-title">addConverter</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerPatternParser.html#methodaddConverter">LoggerPatternParser::addConverter()</a> in LoggerPatternParser.php</div>
</dd>
<dt class="field">
<span class="method-title">addToList</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerPatternParser.html#methodaddToList">LoggerPatternParser::addToList()</a> in LoggerPatternParser.php</div>
</dd>
<dt class="field">
<span class="method-title">activateOptions</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutXml.html#methodactivateOptions">LoggerLayoutXml::activateOptions()</a> in LoggerLayoutXml.php</div>
<div class="index-item-description">No options to activate.</div>
</dd>
<dt class="field">
<span class="method-title">addRenderer</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/renderers/LoggerRendererMap.html#methodaddRenderer">LoggerRendererMap::addRenderer()</a> in LoggerRendererMap.php</div>
<div class="index-item-description">Add a renderer to a hierarchy passed as parameter.</div>
</dd>
</dl>
<a name="c"></a>
<div class="index-letter-section">
<div style="float: left" class="index-letter-title">c</div>
<div style="float: right"><a href="#top">top</a></div>
<div style="clear: both"></div>
</div>
<dl>
<dt class="field">
<span class="var-title">$className</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLocationInfo.html#var$className">LoggerLocationInfo::$className</a> in LoggerLocationInfo.php</div>
</dd>
<dt class="field">
<span class="var-title">$closed</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerAppender.html#var$closed">LoggerAppender::$closed</a> in LoggerAppender.php</div>
</dd>
<dt class="field">
<span class="method-title">callAppenders</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/Logger.html#methodcallAppenders">Logger::callAppenders()</a> in Logger.php</div>
<div class="index-item-description">Call the appenders in the hierarchy starting at this.</div>
</dd>
<dt class="field">
<span class="method-title">clear</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/Logger.html#methodclear">Logger::clear()</a> in Logger.php</div>
<div class="index-item-description">Clears all logger definitions</div>
</dd>
<dt class="field">
<span class="method-title">clear</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerHierarchy.html#methodclear">LoggerHierarchy::clear()</a> in LoggerHierarchy.php</div>
<div class="index-item-description">This call will clear all logger definitions from the internal hashtable.</div>
</dd>
<dt class="field">
<span class="method-title">clear</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerNDC.html#methodclear">LoggerNDC::clear()</a> in LoggerNDC.php</div>
<div class="index-item-description">Clear any nested diagnostic information if any. This method is useful in cases where the same thread can be potentially used over and over in different unrelated contexts.</div>
</dd>
<dt class="field">
<span class="method-title">clearFilters</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerAppender.html#methodclearFilters">LoggerAppender::clearFilters()</a> in LoggerAppender.php</div>
<div class="index-item-description">Clear the list of filters by removing all the filters in it.</div>
</dd>
<dt class="field">
<span class="method-title">close</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerAppender.html#methodclose">LoggerAppender::close()</a> in LoggerAppender.php</div>
<div class="index-item-description">Release any resources allocated.</div>
</dd>
<dt class="field">
CONFIGURATOR_INHERITED
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerConfigurator.html#constCONFIGURATOR_INHERITED">LoggerConfigurator::CONFIGURATOR_INHERITED</a> in LoggerConfigurator.php</div>
<div class="index-item-description">Special level value signifying inherited behaviour. The current value of this string constant is <strong>inherited</strong>.</div>
</dd>
<dt class="field">
CONFIGURATOR_NULL
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerConfigurator.html#constCONFIGURATOR_NULL">LoggerConfigurator::CONFIGURATOR_NULL</a> in LoggerConfigurator.php</div>
<div class="index-item-description">Special level signifying inherited behaviour, same as CONFIGURATOR_INHERITED.</div>
</dd>
<dt class="field">
<span class="method-title">configure</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerConfigurator.html#methodconfigure">LoggerConfigurator::configure()</a> in LoggerConfigurator.php</div>
<div class="index-item-description">Interpret a resource pointed by a <var>url</var> and configure accordingly.</div>
</dd>
<dt class="field">
<span class="method-title">configure</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/Logger.html#methodconfigure">Logger::configure()</a> in Logger.php</div>
<div class="index-item-description">Configures Log4PHP.</div>
</dd>
<dt class="field">
<span class="method-title">createObject</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerReflectionUtils.html#methodcreateObject">LoggerReflectionUtils::createObject()</a> in LoggerReflectionUtils.php</div>
<div class="index-item-description">Creates an instances from the given class name.</div>
</dd>
<dt class="field">
<span class="var-title">$createTable</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderAdodb.html#var$createTable">LoggerAppenderAdodb::$createTable</a> in LoggerAppenderAdodb.php</div>
<div class="index-item-description">Create the log table if it does not exists (optional).</div>
</dd>
<dt class="field">
<span class="method-title">close</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderPDO.html#methodclose">LoggerAppenderPDO::close()</a> in LoggerAppenderPDO.php</div>
<div class="index-item-description">Closes the connection to the logging database</div>
</dd>
<dt class="field">
<span class="method-title">close</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderPhp.html#methodclose">LoggerAppenderPhp::close()</a> in LoggerAppenderPhp.php</div>
</dd>
<dt class="field">
<span class="method-title">close</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderSocket.html#methodclose">LoggerAppenderSocket::close()</a> in LoggerAppenderSocket.php</div>
</dd>
<dt class="field">
<span class="method-title">close</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderSyslog.html#methodclose">LoggerAppenderSyslog::close()</a> in LoggerAppenderSyslog.php</div>
</dd>
<dt class="field">
<span class="method-title">close</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderNull.html#methodclose">LoggerAppenderNull::close()</a> in LoggerAppenderNull.php</div>
</dd>
<dt class="field">
<span class="method-title">close</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderMail.html#methodclose">LoggerAppenderMail::close()</a> in LoggerAppenderMail.php</div>
</dd>
<dt class="field">
<span class="method-title">close</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderAdodb.html#methodclose">LoggerAppenderAdodb::close()</a> in LoggerAppenderAdodb.php</div>
</dd>
<dt class="field">
<span class="method-title">close</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderConsole.html#methodclose">LoggerAppenderConsole::close()</a> in LoggerAppenderConsole.php</div>
</dd>
<dt class="field">
<span class="method-title">close</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderEcho.html#methodclose">LoggerAppenderEcho::close()</a> in LoggerAppenderEcho.php</div>
</dd>
<dt class="field">
<span class="method-title">close</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderFile.html#methodclose">LoggerAppenderFile::close()</a> in LoggerAppenderFile.php</div>
</dd>
<dt class="field">
<span class="method-title">close</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderMailEvent.html#methodclose">LoggerAppenderMailEvent::close()</a> in LoggerAppenderMailEvent.php</div>
</dd>
<dt class="field">
CATEGORY_PREFIX
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/configurators/LoggerConfiguratorIni.html#constCATEGORY_PREFIX">LoggerConfiguratorIni::CATEGORY_PREFIX</a> in LoggerConfiguratorIni.php</div>
</dd>
<dt class="field">
<span class="method-title">configure</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/configurators/LoggerConfiguratorXml.html#methodconfigure">LoggerConfiguratorXml::configure()</a> in LoggerConfiguratorXml.php</div>
<div class="index-item-description">Configure the default repository using the resource pointed by <strong>url</strong>.</div>
</dd>
<dt class="field">
<span class="method-title">configure</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/configurators/LoggerConfiguratorPhp.html#methodconfigure">LoggerConfiguratorPhp::configure()</a> in LoggerConfiguratorPhp.php</div>
</dd>
<dt class="field">
<span class="method-title">configure</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/configurators/LoggerConfiguratorIni.html#methodconfigure">LoggerConfiguratorIni::configure()</a> in LoggerConfiguratorIni.php</div>
<div class="index-item-description">Read configuration from a file.</div>
</dd>
<dt class="field">
<span class="method-title">configure</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/configurators/LoggerConfiguratorBasic.html#methodconfigure">LoggerConfiguratorBasic::configure()</a> in LoggerConfiguratorBasic.php</div>
<div class="index-item-description">Add a <a href="log4php/appenders/LoggerAppenderConsole.html">LoggerAppenderConsole</a> that uses the <a href="log4php/layouts/LoggerLayoutTTCC.html">LoggerLayoutTTCC</a> to the root category.</div>
</dd>
<dt class="field">
CLASS_LOCATION_CONVERTER
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerPatternParser.html#constCLASS_LOCATION_CONVERTER">LoggerPatternParser::CLASS_LOCATION_CONVERTER</a> in LoggerPatternParser.php</div>
</dd>
<dt class="field">
<span class="method-title">convert</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerNamedPatternConverter.html#methodconvert">LoggerNamedPatternConverter::convert()</a> in LoggerNamedPatternConverter.php</div>
</dd>
<dt class="field">
<span class="method-title">convert</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerPatternConverter.html#methodconvert">LoggerPatternConverter::convert()</a> in LoggerPatternConverter.php</div>
<div class="index-item-description">Derived pattern converters must override this method in order to convert conversion specifiers in the correct way.</div>
</dd>
<dt class="field">
<span class="method-title">convert</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerBasicPatternConverter.html#methodconvert">LoggerBasicPatternConverter::convert()</a> in LoggerBasicPatternConverter.php</div>
</dd>
<dt class="field">
<span class="method-title">convert</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerMDCPatternConverter.html#methodconvert">LoggerMDCPatternConverter::convert()</a> in LoggerMDCPatternConverter.php</div>
</dd>
<dt class="field">
<span class="method-title">convert</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerDatePatternConverter.html#methodconvert">LoggerDatePatternConverter::convert()</a> in LoggerDatePatternConverter.php</div>
</dd>
<dt class="field">
<span class="method-title">convert</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerLiteralPatternConverter.html#methodconvert">LoggerLiteralPatternConverter::convert()</a> in LoggerLiteralPatternConverter.php</div>
</dd>
<dt class="field">
<span class="method-title">convert</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerLocationPatternConverter.html#methodconvert">LoggerLocationPatternConverter::convert()</a> in LoggerLocationPatternConverter.php</div>
</dd>
<dt class="field">
CONVERTER_STATE
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerPatternParser.html#constCONVERTER_STATE">LoggerPatternParser::CONVERTER_STATE</a> in LoggerPatternParser.php</div>
</dd>
<dt class="field">
<span class="var-title">$categoryPrefixing</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutTTCC.html#var$categoryPrefixing">LoggerLayoutTTCC::$categoryPrefixing</a> in LoggerLayoutTTCC.php</div>
</dd>
<dt class="field">
<span class="var-title">$contextPrinting</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutTTCC.html#var$contextPrinting">LoggerLayoutTTCC::$contextPrinting</a> in LoggerLayoutTTCC.php</div>
</dd>
<dt class="field">
CDATA_EMBEDDED_END
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutXml.html#constCDATA_EMBEDDED_END">LoggerLayoutXml::CDATA_EMBEDDED_END</a> in LoggerLayoutXml.php</div>
</dd>
<dt class="field">
CDATA_END
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutXml.html#constCDATA_END">LoggerLayoutXml::CDATA_END</a> in LoggerLayoutXml.php</div>
</dd>
<dt class="field">
CDATA_PSEUDO_END
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutXml.html#constCDATA_PSEUDO_END">LoggerLayoutXml::CDATA_PSEUDO_END</a> in LoggerLayoutXml.php</div>
</dd>
<dt class="field">
CDATA_START
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutXml.html#constCDATA_START">LoggerLayoutXml::CDATA_START</a> in LoggerLayoutXml.php</div>
</dd>
<dt class="field">
<span class="method-title">clear</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/renderers/LoggerRendererMap.html#methodclear">LoggerRendererMap::clear()</a> in LoggerRendererMap.php</div>
</dd>
</dl>
<a name="d"></a>
<div class="index-letter-section">
<div style="float: left" class="index-letter-title">d</div>
<div style="float: right"><a href="#top">top</a></div>
<div style="clear: both"></div>
</div>
<dl>
<dt class="field">
<span class="var-title">$defaultFactory</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerHierarchy.html#var$defaultFactory">LoggerHierarchy::$defaultFactory</a> in LoggerHierarchy.php</div>
<div class="index-item-description">Default Factory</div>
</dd>
<dt class="field">
<span class="method-title">debug</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/Logger.html#methoddebug">Logger::debug()</a> in Logger.php</div>
<div class="index-item-description">Log a message object with the DEBUG level including the caller.</div>
</dd>
<dt class="field">
DEBUG
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLevel.html#constDEBUG">LoggerLevel::DEBUG</a> in LoggerLevel.php</div>
</dd>
<dt class="field">
<span class="method-title">decide</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerFilter.html#methoddecide">LoggerFilter::decide()</a> in LoggerFilter.php</div>
<div class="index-item-description">Decide what to do.</div>
</dd>
<dt class="field">
DENY
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerFilter.html#constDENY">LoggerFilter::DENY</a> in LoggerFilter.php</div>
<div class="index-item-description">The log event must be dropped immediately without consulting with the remaining filters, if any, in the chain.</div>
</dd>
<dt class="field">
<span class="method-title">doAppend</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerAppender.html#methoddoAppend">LoggerAppender::doAppend()</a> in LoggerAppender.php</div>
<div class="index-item-description">This method performs threshold checks and invokes filters before delegating actual logging to the subclasses specific <em>append()</em> method.</div>
</dd>
<dt class="field">
<span class="var-title">$database</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderAdodb.html#var$database">LoggerAppenderAdodb::$database</a> in LoggerAppenderAdodb.php</div>
<div class="index-item-description">Name of the database to connect to</div>
</dd>
<dt class="field">
<span class="var-title">$datePattern</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderDailyFile.html#var$datePattern">LoggerAppenderDailyFile::$datePattern</a> in LoggerAppenderDailyFile.php</div>
<div class="index-item-description">Format date.</div>
</dd>
<dt class="field">
DEFAULT_CONFIGURATION
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/configurators/LoggerConfiguratorXml.html#constDEFAULT_CONFIGURATION">LoggerConfiguratorXml::DEFAULT_CONFIGURATION</a> in LoggerConfiguratorXml.php</div>
</dd>
<dt class="field">
DEFAULT_FILENAME
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/configurators/LoggerConfiguratorXml.html#constDEFAULT_FILENAME">LoggerConfiguratorXml::DEFAULT_FILENAME</a> in LoggerConfiguratorXml.php</div>
</dd>
<dt class="field">
<span class="method-title">decide</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/filters/LoggerFilterStringMatch.html#methoddecide">LoggerFilterStringMatch::decide()</a> in LoggerFilterStringMatch.php</div>
</dd>
<dt class="field">
<span class="method-title">decide</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/filters/LoggerFilterLevelRange.html#methoddecide">LoggerFilterLevelRange::decide()</a> in LoggerFilterLevelRange.php</div>
<div class="index-item-description">Return the decision of this filter.</div>
</dd>
<dt class="field">
<span class="method-title">decide</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/filters/LoggerFilterLevelMatch.html#methoddecide">LoggerFilterLevelMatch::decide()</a> in LoggerFilterLevelMatch.php</div>
<div class="index-item-description">Return the decision of this filter.</div>
</dd>
<dt class="field">
<span class="method-title">decide</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/filters/LoggerFilterDenyAll.html#methoddecide">LoggerFilterDenyAll::decide()</a> in LoggerFilterDenyAll.php</div>
<div class="index-item-description">Always returns the integer constant <a href="log4php/LoggerFilter.html#constDENY">LoggerFilter::DENY</a> regardless of the <a href="log4php/LoggerLoggingEvent.html">LoggerLoggingEvent</a> parameter.</div>
</dd>
<dt class="field">
DATE_FORMAT_ABSOLUTE
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerPatternParser.html#constDATE_FORMAT_ABSOLUTE">LoggerPatternParser::DATE_FORMAT_ABSOLUTE</a> in LoggerPatternParser.php</div>
</dd>
<dt class="field">
DATE_FORMAT_DATE
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerPatternParser.html#constDATE_FORMAT_DATE">LoggerPatternParser::DATE_FORMAT_DATE</a> in LoggerPatternParser.php</div>
</dd>
<dt class="field">
DATE_FORMAT_ISO8601
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerPatternParser.html#constDATE_FORMAT_ISO8601">LoggerPatternParser::DATE_FORMAT_ISO8601</a> in LoggerPatternParser.php</div>
</dd>
<dt class="field">
DELIM_START
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerOptionConverter.html#constDELIM_START">LoggerOptionConverter::DELIM_START</a> in LoggerOptionConverter.php</div>
</dd>
<dt class="field">
DELIM_START_LEN
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerOptionConverter.html#constDELIM_START_LEN">LoggerOptionConverter::DELIM_START_LEN</a> in LoggerOptionConverter.php</div>
</dd>
<dt class="field">
DELIM_STOP
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerOptionConverter.html#constDELIM_STOP">LoggerOptionConverter::DELIM_STOP</a> in LoggerOptionConverter.php</div>
</dd>
<dt class="field">
DELIM_STOP_LEN
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerOptionConverter.html#constDELIM_STOP_LEN">LoggerOptionConverter::DELIM_STOP_LEN</a> in LoggerOptionConverter.php</div>
</dd>
<dt class="field">
DOT_STATE
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerPatternParser.html#constDOT_STATE">LoggerPatternParser::DOT_STATE</a> in LoggerPatternParser.php</div>
</dd>
<dt class="field">
<span class="method-title">dump</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerFormattingInfo.html#methoddump">LoggerFormattingInfo::dump()</a> in LoggerFormattingInfo.php</div>
</dd>
<dt class="field">
<span class="var-title">$dateFormat</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutTTCC.html#var$dateFormat">LoggerLayoutTTCC::$dateFormat</a> in LoggerLayoutTTCC.php</div>
</dd>
<dt class="field">
DEFAULT_CONVERSION_PATTERN
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutPattern.html#constDEFAULT_CONVERSION_PATTERN">LoggerLayoutPattern::DEFAULT_CONVERSION_PATTERN</a> in LoggerLayoutPattern.php</div>
<div class="index-item-description">Default conversion Pattern</div>
</dd>
</dl>
<a name="e"></a>
<div class="index-letter-section">
<div style="float: left" class="index-letter-title">e</div>
<div style="float: right"><a href="#top">top</a></div>
<div style="clear: both"></div>
</div>
<dl>
<dt class="field">
<span class="method-title">equals</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLevel.html#methodequals">LoggerLevel::equals()</a> in LoggerLevel.php</div>
<div class="index-item-description">Two priorities are equal if their level fields are equal.</div>
</dd>
<dt class="field">
<span class="method-title">error</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/Logger.html#methoderror">Logger::error()</a> in Logger.php</div>
<div class="index-item-description">Log a message object with the ERROR level including the caller.</div>
</dd>
<dt class="field">
ERROR
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLevel.html#constERROR">LoggerLevel::ERROR</a> in LoggerLevel.php</div>
</dd>
<dt class="field">
<span class="method-title">exists</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerHierarchy.html#methodexists">LoggerHierarchy::exists()</a> in LoggerHierarchy.php</div>
<div class="index-item-description">Check if the named logger exists in the hierarchy.</div>
</dd>
<dt class="field">
<span class="method-title">exists</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/Logger.html#methodexists">Logger::exists()</a> in Logger.php</div>
<div class="index-item-description">check if a given logger exists.</div>
</dd>
<dt class="field">
ESCAPE_CHAR
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerPatternParser.html#constESCAPE_CHAR">LoggerPatternParser::ESCAPE_CHAR</a> in LoggerPatternParser.php</div>
</dd>
<dt class="field">
<span class="method-title">extractOption</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerPatternParser.html#methodextractOption">LoggerPatternParser::extractOption()</a> in LoggerPatternParser.php</div>
</dd>
<dt class="field">
<span class="method-title">extractPrecisionOption</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerPatternParser.html#methodextractPrecisionOption">LoggerPatternParser::extractPrecisionOption()</a> in LoggerPatternParser.php</div>
<div class="index-item-description">The option is expected to be in decimal and positive. In case of error, zero is returned.</div>
</dd>
</dl>
<a name="f"></a>
<div class="index-letter-section">
<div style="float: left" class="index-letter-title">f</div>
<div style="float: right"><a href="#top">top</a></div>
<div style="clear: both"></div>
</div>
<dl>
<dt class="field">
<span class="var-title">$fileName</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLocationInfo.html#var$fileName">LoggerLocationInfo::$fileName</a> in LoggerLocationInfo.php</div>
</dd>
<dt class="field">
<span class="var-title">$filter</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerAppender.html#var$filter">LoggerAppender::$filter</a> in LoggerAppender.php</div>
<div class="index-item-description">The first filter in the filter chain</div>
</dd>
<dt class="field">
<span class="var-title">$fullInfo</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLocationInfo.html#var$fullInfo">LoggerLocationInfo::$fullInfo</a> in LoggerLocationInfo.php</div>
</dd>
<dt class="field">
FATAL
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLevel.html#constFATAL">LoggerLevel::FATAL</a> in LoggerLevel.php</div>
</dd>
<dt class="field">
<span class="method-title">fatal</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/Logger.html#methodfatal">Logger::fatal()</a> in Logger.php</div>
<div class="index-item-description">Log a message object with the FATAL level including the caller.</div>
</dd>
<dt class="field">
<span class="method-title">forcedLog</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/Logger.html#methodforcedLog">Logger::forcedLog()</a> in Logger.php</div>
<div class="index-item-description">This method creates a new logging event and logs the event without further checks.</div>
</dd>
<dt class="field">
<span class="method-title">format</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLayout.html#methodformat">LoggerLayout::format()</a> in LoggerLayout.php</div>
<div class="index-item-description">Override this method to create your own layout format.</div>
</dd>
<dt class="field">
<span class="var-title">$fileName</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderFile.html#var$fileName">LoggerAppenderFile::$fileName</a> in LoggerAppenderFile.php</div>
</dd>
<dt class="field">
<span class="var-title">$fp</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderFile.html#var$fp">LoggerAppenderFile::$fp</a> in LoggerAppenderFile.php</div>
</dd>
<dt class="field">
<span class="var-title">$fp</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderConsole.html#var$fp">LoggerAppenderConsole::$fp</a> in LoggerAppenderConsole.php</div>
</dd>
<dt class="field">
FACTORY_PREFIX
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/configurators/LoggerConfiguratorIni.html#constFACTORY_PREFIX">LoggerConfiguratorIni::FACTORY_PREFIX</a> in LoggerConfiguratorIni.php</div>
</dd>
<dt class="field">
FILTER_STATE
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/configurators/LoggerConfiguratorXml.html#constFILTER_STATE">LoggerConfiguratorXml::FILTER_STATE</a> in LoggerConfiguratorXml.php</div>
</dd>
<dt class="field">
FILE_LOCATION_CONVERTER
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerPatternParser.html#constFILE_LOCATION_CONVERTER">LoggerPatternParser::FILE_LOCATION_CONVERTER</a> in LoggerPatternParser.php</div>
</dd>
<dt class="field">
<span class="method-title">finalizeConverter</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerPatternParser.html#methodfinalizeConverter">LoggerPatternParser::finalizeConverter()</a> in LoggerPatternParser.php</div>
</dd>
<dt class="field">
<span class="method-title">findAndSubst</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerOptionConverter.html#methodfindAndSubst">LoggerOptionConverter::findAndSubst()</a> in LoggerOptionConverter.php</div>
<div class="index-item-description">Find the value corresponding to <var>$key</var> in <var>$props</var>. Then perform variable substitution on the found value.</div>
</dd>
<dt class="field">
<span class="method-title">format</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerPatternConverter.html#methodformat">LoggerPatternConverter::format()</a> in LoggerPatternConverter.php</div>
<div class="index-item-description">A template method for formatting in a converter specific way.</div>
</dd>
<dt class="field">
<span class="method-title">format</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerLiteralPatternConverter.html#methodformat">LoggerLiteralPatternConverter::format()</a> in LoggerLiteralPatternConverter.php</div>
</dd>
<dt class="field">
FULL_LOCATION_CONVERTER
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerPatternParser.html#constFULL_LOCATION_CONVERTER">LoggerPatternParser::FULL_LOCATION_CONVERTER</a> in LoggerPatternParser.php</div>
</dd>
<dt class="field">
<span class="method-title">format</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutTTCC.html#methodformat">LoggerLayoutTTCC::format()</a> in LoggerLayoutTTCC.php</div>
<div class="index-item-description">In addition to the level of the statement and message, the returned string includes time, thread, category.</div>
</dd>
<dt class="field">
<span class="method-title">format</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutSimple.html#methodformat">LoggerLayoutSimple::format()</a> in LoggerLayoutSimple.php</div>
<div class="index-item-description">Returns the log statement in a format consisting of the</div>
</dd>
<dt class="field">
<span class="method-title">format</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutHtml.html#methodformat">LoggerLayoutHtml::format()</a> in LoggerLayoutHtml.php</div>
</dd>
<dt class="field">
<span class="method-title">format</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutPattern.html#methodformat">LoggerLayoutPattern::format()</a> in LoggerLayoutPattern.php</div>
<div class="index-item-description">Produces a formatted string as specified by the conversion pattern.</div>
</dd>
<dt class="field">
<span class="method-title">format</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutXml.html#methodformat">LoggerLayoutXml::format()</a> in LoggerLayoutXml.php</div>
<div class="index-item-description">Formats a <a href="log4php/LoggerLoggingEvent.html">LoggerLoggingEvent</a> in conformance with the log4php.dtd.</div>
</dd>
<dt class="field">
<span class="method-title">formatToArray</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutPattern.html#methodformatToArray">LoggerLayoutPattern::formatToArray()</a> in LoggerLayoutPattern.php</div>
<div class="index-item-description">Returns an array with the formatted elements.</div>
</dd>
<dt class="field">
<span class="method-title">findAndRender</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/renderers/LoggerRendererMap.html#methodfindAndRender">LoggerRendererMap::findAndRender()</a> in LoggerRendererMap.php</div>
<div class="index-item-description">Find the appropriate renderer for the class type of the <var>o</var> parameter.</div>
</dd>
</dl>
<a name="g"></a>
<div class="index-letter-section">
<div style="float: left" class="index-letter-title">g</div>
<div style="float: right"><a href="#top">top</a></div>
<div style="clear: both"></div>
</div>
<dl>
<dt class="field">
<span class="method-title">get</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerNDC.html#methodget">LoggerNDC::get()</a> in LoggerNDC.php</div>
<div class="index-item-description">Never use this method directly, use the <a href="log4php/LoggerLoggingEvent.html#methodgetNDC">LoggerLoggingEvent::getNDC()</a> method instead.</div>
</dd>
<dt class="field">
<span class="method-title">get</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerMDC.html#methodget">LoggerMDC::get()</a> in LoggerMDC.php</div>
<div class="index-item-description">Get the context identified by the key parameter.</div>
</dd>
<dt class="field">
<span class="method-title">getAdditivity</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/Logger.html#methodgetAdditivity">Logger::getAdditivity()</a> in Logger.php</div>
<div class="index-item-description">Get the additivity flag for this Category instance.</div>
</dd>
<dt class="field">
<span class="method-title">getAllAppenders</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/Logger.html#methodgetAllAppenders">Logger::getAllAppenders()</a> in Logger.php</div>
<div class="index-item-description">Get the appenders contained in this category as an array.</div>
</dd>
<dt class="field">
<span class="method-title">getAppender</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/Logger.html#methodgetAppender">Logger::getAppender()</a> in Logger.php</div>
<div class="index-item-description">Look for the appender named as name.</div>
</dd>
<dt class="field">
<span class="method-title">getAppenderFromPool</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerAppenderPool.html#methodgetAppenderFromPool">LoggerAppenderPool::getAppenderFromPool()</a> in LoggerAppenderPool.php</div>
</dd>
<dt class="field">
<span class="method-title">getChainedLevel</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerRoot.html#methodgetChainedLevel">LoggerRoot::getChainedLevel()</a> in LoggerRoot.php</div>
</dd>
<dt class="field">
<span class="method-title">getClassName</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLocationInfo.html#methodgetClassName">LoggerLocationInfo::getClassName()</a> in LoggerLocationInfo.php</div>
</dd>
<dt class="field">
<span class="method-title">getConfigurationClass</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/Logger.html#methodgetConfigurationClass">Logger::getConfigurationClass()</a> in Logger.php</div>
<div class="index-item-description">Returns the current configurator</div>
</dd>
<dt class="field">
<span class="method-title">getConfigurationFile</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/Logger.html#methodgetConfigurationFile">Logger::getConfigurationFile()</a> in Logger.php</div>
<div class="index-item-description">Returns the current configuration file</div>
</dd>
<dt class="field">
<span class="method-title">getContentType</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLayout.html#methodgetContentType">LoggerLayout::getContentType()</a> in LoggerLayout.php</div>
<div class="index-item-description">Returns the content type output by this layout.</div>
</dd>
<dt class="field">
<span class="method-title">getCurrentLoggers</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerHierarchy.html#methodgetCurrentLoggers">LoggerHierarchy::getCurrentLoggers()</a> in LoggerHierarchy.php</div>
<div class="index-item-description">Returns all the currently defined categories in this hierarchy as an array.</div>
</dd>
<dt class="field">
<span class="method-title">getCurrentLoggers</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/Logger.html#methodgetCurrentLoggers">Logger::getCurrentLoggers()</a> in Logger.php</div>
<div class="index-item-description">Returns an array this whole Logger instances.</div>
</dd>
<dt class="field">
<span class="method-title">getDepth</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerNDC.html#methodgetDepth">LoggerNDC::getDepth()</a> in LoggerNDC.php</div>
<div class="index-item-description">Get the current nesting depth of this diagnostic context.</div>
</dd>
<dt class="field">
<span class="method-title">getEffectiveLevel</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/Logger.html#methodgetEffectiveLevel">Logger::getEffectiveLevel()</a> in Logger.php</div>
<div class="index-item-description">Starting from this category, search the category hierarchy for a non-null level and return it.</div>
</dd>
<dt class="field">
<span class="method-title">getFileName</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLocationInfo.html#methodgetFileName">LoggerLocationInfo::getFileName()</a> in LoggerLocationInfo.php</div>
<div class="index-item-description">Return the file name of the caller.</div>
</dd>
<dt class="field">
<span class="method-title">getFilter</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerAppender.html#methodgetFilter">LoggerAppender::getFilter()</a> in LoggerAppender.php</div>
<div class="index-item-description">Return the first filter in the filter chain for this Appender.</div>
</dd>
<dt class="field">
<span class="method-title">getFirstFilter</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerAppender.html#methodgetFirstFilter">LoggerAppender::getFirstFilter()</a> in LoggerAppender.php</div>
<div class="index-item-description">Return the first filter in the filter chain for this Appender.</div>
</dd>
<dt class="field">
<span class="method-title">getFooter</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLayout.html#methodgetFooter">LoggerLayout::getFooter()</a> in LoggerLayout.php</div>
<div class="index-item-description">Returns the footer for the layout format.</div>
</dd>
<dt class="field">
<span class="method-title">getFullInfo</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLocationInfo.html#methodgetFullInfo">LoggerLocationInfo::getFullInfo()</a> in LoggerLocationInfo.php</div>
<div class="index-item-description">Returns the full information of the caller.</div>
</dd>
<dt class="field">
<span class="method-title">getHeader</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLayout.html#methodgetHeader">LoggerLayout::getHeader()</a> in LoggerLayout.php</div>
<div class="index-item-description">Returns the header for the layout format.</div>
</dd>
<dt class="field">
<span class="method-title">getHierarchy</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/Logger.html#methodgetHierarchy">Logger::getHierarchy()</a> in Logger.php</div>
<div class="index-item-description">Returns the hierarchy used by this Logger.</div>
</dd>
<dt class="field">
<span class="method-title">getLayout</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerAppender.html#methodgetLayout">LoggerAppender::getLayout()</a> in LoggerAppender.php</div>
<div class="index-item-description">Returns this appender layout.</div>
</dd>
<dt class="field">
<span class="method-title">getLevel</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/Logger.html#methodgetLevel">Logger::getLevel()</a> in Logger.php</div>
<div class="index-item-description">Returns the assigned Level, if any, for this Category.</div>
</dd>
<dt class="field">
<span class="method-title">getLevel</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLoggingEvent.html#methodgetLevel">LoggerLoggingEvent::getLevel()</a> in LoggerLoggingEvent.php</div>
<div class="index-item-description">Return the level of this event. Use this form instead of directly accessing the $level field.</div>
</dd>
<dt class="field">
<span class="method-title">getLevelAll</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLevel.html#methodgetLevelAll">LoggerLevel::getLevelAll()</a> in LoggerLevel.php</div>
<div class="index-item-description">Returns an All Level</div>
</dd>
<dt class="field">
<span class="method-title">getLevelDebug</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLevel.html#methodgetLevelDebug">LoggerLevel::getLevelDebug()</a> in LoggerLevel.php</div>
<div class="index-item-description">Returns a Debug Level</div>
</dd>
<dt class="field">
<span class="method-title">getLevelError</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLevel.html#methodgetLevelError">LoggerLevel::getLevelError()</a> in LoggerLevel.php</div>
<div class="index-item-description">Returns an Error Level</div>
</dd>
<dt class="field">
<span class="method-title">getLevelFatal</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLevel.html#methodgetLevelFatal">LoggerLevel::getLevelFatal()</a> in LoggerLevel.php</div>
<div class="index-item-description">Returns a Fatal Level</div>
</dd>
<dt class="field">
<span class="method-title">getLevelInfo</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLevel.html#methodgetLevelInfo">LoggerLevel::getLevelInfo()</a> in LoggerLevel.php</div>
<div class="index-item-description">Returns an Info Level</div>
</dd>
<dt class="field">
<span class="method-title">getLevelOff</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLevel.html#methodgetLevelOff">LoggerLevel::getLevelOff()</a> in LoggerLevel.php</div>
<div class="index-item-description">Returns an Off Level</div>
</dd>
<dt class="field">
<span class="method-title">getLevelWarn</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLevel.html#methodgetLevelWarn">LoggerLevel::getLevelWarn()</a> in LoggerLevel.php</div>
<div class="index-item-description">Returns a Warn Level</div>
</dd>
<dt class="field">
<span class="method-title">getLineNumber</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLocationInfo.html#methodgetLineNumber">LoggerLocationInfo::getLineNumber()</a> in LoggerLocationInfo.php</div>
<div class="index-item-description">Returns the line number of the caller.</div>
</dd>
<dt class="field">
<span class="method-title">getLocationInformation</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLoggingEvent.html#methodgetLocationInformation">LoggerLoggingEvent::getLocationInformation()</a> in LoggerLoggingEvent.php</div>
<div class="index-item-description">Set the location information for this logging event. The collected information is cached for future use.</div>
</dd>
<dt class="field">
<span class="method-title">getLogger</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerHierarchy.html#methodgetLogger">LoggerHierarchy::getLogger()</a> in LoggerHierarchy.php</div>
<div class="index-item-description">Return a new logger instance named as the first parameter using the default factory.</div>
</dd>
<dt class="field">
<span class="method-title">getLogger</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/Logger.html#methodgetLogger">Logger::getLogger()</a> in Logger.php</div>
<div class="index-item-description">Get a Logger by name (Delegate to <a href="log4php/Logger.html">Logger</a>)</div>
</dd>
<dt class="field">
<span class="method-title">getLoggerName</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLoggingEvent.html#methodgetLoggerName">LoggerLoggingEvent::getLoggerName()</a> in LoggerLoggingEvent.php</div>
<div class="index-item-description">Return the name of the logger. Use this form instead of directly accessing the $categoryName field.</div>
</dd>
<dt class="field">
<span class="method-title">getMDC</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLoggingEvent.html#methodgetMDC">LoggerLoggingEvent::getMDC()</a> in LoggerLoggingEvent.php</div>
<div class="index-item-description">Returns the the context corresponding to the <div class="src-code"><ol><li><div class="src-line"><a href="http://www.php.net/key">key</a></div></li>
</ol></div> parameter.</div>
</dd>
<dt class="field">
<span class="method-title">getMessage</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLoggingEvent.html#methodgetMessage">LoggerLoggingEvent::getMessage()</a> in LoggerLoggingEvent.php</div>
<div class="index-item-description">Return the message for this logging event.</div>
</dd>
<dt class="field">
<span class="method-title">getMethodName</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLocationInfo.html#methodgetMethodName">LoggerLocationInfo::getMethodName()</a> in LoggerLocationInfo.php</div>
<div class="index-item-description">Returns the method name of the caller.</div>
</dd>
<dt class="field">
<span class="method-title">getName</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/Logger.html#methodgetName">Logger::getName()</a> in Logger.php</div>
<div class="index-item-description">Return the category name.</div>
</dd>
<dt class="field">
<span class="method-title">getName</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerAppender.html#methodgetName">LoggerAppender::getName()</a> in LoggerAppender.php</div>
<div class="index-item-description">Get the name of this appender.</div>
</dd>
<dt class="field">
<span class="method-title">getNDC</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLoggingEvent.html#methodgetNDC">LoggerLoggingEvent::getNDC()</a> in LoggerLoggingEvent.php</div>
<div class="index-item-description">This method returns the NDC for this event. It will return the correct content even if the event was generated in a different thread or even on a different machine. The <a href="log4php/LoggerNDC.html#methodget">LoggerNDC::get()</a> method should <strong>never</strong> be called directly.</div>
</dd>
<dt class="field">
<span class="method-title">getNext</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerFilter.html#methodgetNext">LoggerFilter::getNext()</a> in LoggerFilter.php</div>
<div class="index-item-description">Returns the next filter in this chain</div>
</dd>
<dt class="field">
<span class="method-title">getParent</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/Logger.html#methodgetParent">Logger::getParent()</a> in Logger.php</div>
<div class="index-item-description">Returns the parent of this category.</div>
</dd>
<dt class="field">
<span class="method-title">getRenderedMessage</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLoggingEvent.html#methodgetRenderedMessage">LoggerLoggingEvent::getRenderedMessage()</a> in LoggerLoggingEvent.php</div>
<div class="index-item-description">Render message.</div>
</dd>
<dt class="field">
<span class="method-title">getRendererMap</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerHierarchy.html#methodgetRendererMap">LoggerHierarchy::getRendererMap()</a> in LoggerHierarchy.php</div>
</dd>
<dt class="field">
<span class="method-title">getRootLogger</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/Logger.html#methodgetRootLogger">Logger::getRootLogger()</a> in Logger.php</div>
<div class="index-item-description">get the Root Logger (Delegate to <a href="log4php/Logger.html">Logger</a>)</div>
</dd>
<dt class="field">
<span class="method-title">getRootLogger</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerHierarchy.html#methodgetRootLogger">LoggerHierarchy::getRootLogger()</a> in LoggerHierarchy.php</div>
</dd>
<dt class="field">
<span class="method-title">getStartTime</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLoggingEvent.html#methodgetStartTime">LoggerLoggingEvent::getStartTime()</a> in LoggerLoggingEvent.php</div>
<div class="index-item-description">Returns the time when the application started, in seconds elapsed since 01.01.1970 plus microseconds if available.</div>
</dd>
<dt class="field">
<span class="method-title">getSyslogEquivalent</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLevel.html#methodgetSyslogEquivalent">LoggerLevel::getSyslogEquivalent()</a> in LoggerLevel.php</div>
<div class="index-item-description">Return the syslog equivalent of this priority as an integer.</div>
</dd>
<dt class="field">
<span class="method-title">getThreadName</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLoggingEvent.html#methodgetThreadName">LoggerLoggingEvent::getThreadName()</a> in LoggerLoggingEvent.php</div>
</dd>
<dt class="field">
<span class="method-title">getThreshold</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerAppender.html#methodgetThreshold">LoggerAppender::getThreshold()</a> in LoggerAppender.php</div>
<div class="index-item-description">Returns this appenders threshold level.</div>
</dd>
<dt class="field">
<span class="method-title">getThreshold</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerHierarchy.html#methodgetThreshold">LoggerHierarchy::getThreshold()</a> in LoggerHierarchy.php</div>
</dd>
<dt class="field">
<span class="method-title">getThrowableInformation</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLoggingEvent.html#methodgetThrowableInformation">LoggerLoggingEvent::getThrowableInformation()</a> in LoggerLoggingEvent.php</div>
</dd>
<dt class="field">
<span class="method-title">getTime</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLoggingEvent.html#methodgetTime">LoggerLoggingEvent::getTime()</a> in LoggerLoggingEvent.php</div>
<div class="index-item-description">Calculates the time of this event.</div>
</dd>
<dt class="field">
<span class="method-title">getTimeStamp</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLoggingEvent.html#methodgetTimeStamp">LoggerLoggingEvent::getTimeStamp()</a> in LoggerLoggingEvent.php</div>
</dd>
<dt class="field">
<span class="method-title">getAppend</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderFile.html#methodgetAppend">LoggerAppenderFile::getAppend()</a> in LoggerAppenderFile.php</div>
</dd>
<dt class="field">
<span class="method-title">getCreateTable</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderAdodb.html#methodgetCreateTable">LoggerAppenderAdodb::getCreateTable()</a> in LoggerAppenderAdodb.php</div>
</dd>
<dt class="field">
<span class="method-title">getDatabase</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderAdodb.html#methodgetDatabase">LoggerAppenderAdodb::getDatabase()</a> in LoggerAppenderAdodb.php</div>
</dd>
<dt class="field">
<span class="method-title">getDatabaseHandle</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderPDO.html#methodgetDatabaseHandle">LoggerAppenderPDO::getDatabaseHandle()</a> in LoggerAppenderPDO.php</div>
<div class="index-item-description">Sometimes databases allow only one connection to themselves in one thread.</div>
</dd>
<dt class="field">
<span class="method-title">getDatePattern</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderDailyFile.html#methodgetDatePattern">LoggerAppenderDailyFile::getDatePattern()</a> in LoggerAppenderDailyFile.php</div>
</dd>
<dt class="field">
<span class="method-title">getFile</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderFile.html#methodgetFile">LoggerAppenderFile::getFile()</a> in LoggerAppenderFile.php</div>
</dd>
<dt class="field">
<span class="method-title">getFileName</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderFile.html#methodgetFileName">LoggerAppenderFile::getFileName()</a> in LoggerAppenderFile.php</div>
</dd>
<dt class="field">
<span class="method-title">getHost</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderAdodb.html#methodgetHost">LoggerAppenderAdodb::getHost()</a> in LoggerAppenderAdodb.php</div>
</dd>
<dt class="field">
<span class="method-title">getHostname</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderSocket.html#methodgetHostname">LoggerAppenderSocket::getHostname()</a> in LoggerAppenderSocket.php</div>
</dd>
<dt class="field">
<span class="method-title">getLocationInfo</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderSocket.html#methodgetLocationInfo">LoggerAppenderSocket::getLocationInfo()</a> in LoggerAppenderSocket.php</div>
</dd>
<dt class="field">
<span class="method-title">getLog4jNamespace</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderSocket.html#methodgetLog4jNamespace">LoggerAppenderSocket::getLog4jNamespace()</a> in LoggerAppenderSocket.php</div>
</dd>
<dt class="field">
<span class="method-title">getPassword</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderAdodb.html#methodgetPassword">LoggerAppenderAdodb::getPassword()</a> in LoggerAppenderAdodb.php</div>
</dd>
<dt class="field">
<span class="method-title">getPort</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderSocket.html#methodgetPort">LoggerAppenderSocket::getPort()</a> in LoggerAppenderSocket.php</div>
</dd>
<dt class="field">
<span class="method-title">getRemoteHost</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderSocket.html#methodgetRemoteHost">LoggerAppenderSocket::getRemoteHost()</a> in LoggerAppenderSocket.php</div>
</dd>
<dt class="field">
<span class="method-title">getSql</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderAdodb.html#methodgetSql">LoggerAppenderAdodb::getSql()</a> in LoggerAppenderAdodb.php</div>
</dd>
<dt class="field">
<span class="method-title">getTable</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderAdodb.html#methodgetTable">LoggerAppenderAdodb::getTable()</a> in LoggerAppenderAdodb.php</div>
</dd>
<dt class="field">
<span class="method-title">getTimeout</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderSocket.html#methodgetTimeout">LoggerAppenderSocket::getTimeout()</a> in LoggerAppenderSocket.php</div>
</dd>
<dt class="field">
<span class="method-title">getType</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderAdodb.html#methodgetType">LoggerAppenderAdodb::getType()</a> in LoggerAppenderAdodb.php</div>
</dd>
<dt class="field">
<span class="method-title">getUser</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderAdodb.html#methodgetUser">LoggerAppenderAdodb::getUser()</a> in LoggerAppenderAdodb.php</div>
</dd>
<dt class="field">
<span class="method-title">getUseXml</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderSocket.html#methodgetUseXml">LoggerAppenderSocket::getUseXml()</a> in LoggerAppenderSocket.php</div>
</dd>
<dt class="field">
<span class="method-title">getFullyQualifiedName</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerNamedPatternConverter.html#methodgetFullyQualifiedName">LoggerNamedPatternConverter::getFullyQualifiedName()</a> in LoggerNamedPatternConverter.php</div>
</dd>
<dt class="field">
<span class="method-title">getFullyQualifiedName</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerClassNamePatternConverter.html#methodgetFullyQualifiedName">LoggerClassNamePatternConverter::getFullyQualifiedName()</a> in LoggerClassNamePatternConverter.php</div>
</dd>
<dt class="field">
<span class="method-title">getFullyQualifiedName</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerCategoryPatternConverter.html#methodgetFullyQualifiedName">LoggerCategoryPatternConverter::getFullyQualifiedName()</a> in LoggerCategoryPatternConverter.php</div>
</dd>
<dt class="field">
<span class="method-title">getSystemProperty</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerOptionConverter.html#methodgetSystemProperty">LoggerOptionConverter::getSystemProperty()</a> in LoggerOptionConverter.php</div>
<div class="index-item-description">Read a predefined var.</div>
</dd>
<dt class="field">
<span class="method-title">getCategoryPrefixing</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutTTCC.html#methodgetCategoryPrefixing">LoggerLayoutTTCC::getCategoryPrefixing()</a> in LoggerLayoutTTCC.php</div>
</dd>
<dt class="field">
<span class="method-title">getContentType</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutHtml.html#methodgetContentType">LoggerLayoutHtml::getContentType()</a> in LoggerLayoutHtml.php</div>
</dd>
<dt class="field">
<span class="method-title">getContextPrinting</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutTTCC.html#methodgetContextPrinting">LoggerLayoutTTCC::getContextPrinting()</a> in LoggerLayoutTTCC.php</div>
</dd>
<dt class="field">
<span class="method-title">getDateFormat</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutTTCC.html#methodgetDateFormat">LoggerLayoutTTCC::getDateFormat()</a> in LoggerLayoutTTCC.php</div>
</dd>
<dt class="field">
<span class="method-title">getFooter</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutXml.html#methodgetFooter">LoggerLayoutXml::getFooter()</a> in LoggerLayoutXml.php</div>
</dd>
<dt class="field">
<span class="method-title">getFooter</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutHtml.html#methodgetFooter">LoggerLayoutHtml::getFooter()</a> in LoggerLayoutHtml.php</div>
</dd>
<dt class="field">
<span class="method-title">getHeader</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutXml.html#methodgetHeader">LoggerLayoutXml::getHeader()</a> in LoggerLayoutXml.php</div>
</dd>
<dt class="field">
<span class="method-title">getHeader</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutHtml.html#methodgetHeader">LoggerLayoutHtml::getHeader()</a> in LoggerLayoutHtml.php</div>
</dd>
<dt class="field">
<span class="method-title">getLocationInfo</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutXml.html#methodgetLocationInfo">LoggerLayoutXml::getLocationInfo()</a> in LoggerLayoutXml.php</div>
<div class="index-item-description">Whether or not file name and line number will be included in the output.</div>
</dd>
<dt class="field">
<span class="method-title">getLocationInfo</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutHtml.html#methodgetLocationInfo">LoggerLayoutHtml::getLocationInfo()</a> in LoggerLayoutHtml.php</div>
<div class="index-item-description">Returns the current value of the <strong>LocationInfo</strong> option.</div>
</dd>
<dt class="field">
<span class="method-title">getLog4jNamespace</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutXml.html#methodgetLog4jNamespace">LoggerLayoutXml::getLog4jNamespace()</a> in LoggerLayoutXml.php</div>
</dd>
<dt class="field">
<span class="method-title">getMicroSecondsPrinting</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutTTCC.html#methodgetMicroSecondsPrinting">LoggerLayoutTTCC::getMicroSecondsPrinting()</a> in LoggerLayoutTTCC.php</div>
</dd>
<dt class="field">
<span class="method-title">getThreadPrinting</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutTTCC.html#methodgetThreadPrinting">LoggerLayoutTTCC::getThreadPrinting()</a> in LoggerLayoutTTCC.php</div>
</dd>
<dt class="field">
<span class="method-title">getTitle</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutHtml.html#methodgetTitle">LoggerLayoutHtml::getTitle()</a> in LoggerLayoutHtml.php</div>
</dd>
<dt class="field">
<span class="method-title">getByClassName</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/renderers/LoggerRendererMap.html#methodgetByClassName">LoggerRendererMap::getByClassName()</a> in LoggerRendererMap.php</div>
<div class="index-item-description">Search the parents of <var>clazz</var> for a renderer.</div>
</dd>
<dt class="field">
<span class="method-title">getByObject</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/renderers/LoggerRendererMap.html#methodgetByObject">LoggerRendererMap::getByObject()</a> in LoggerRendererMap.php</div>
<div class="index-item-description">Syntactic sugar method that calls <a href="http://www.php.net/get_class">http://www.php.net/get_class</a> with the class of the object parameter.</div>
</dd>
</dl>
<a name="h"></a>
<div class="index-letter-section">
<div style="float: left" class="index-letter-title">h</div>
<div style="float: right"><a href="#top">top</a></div>
<div style="clear: both"></div>
</div>
<dl>
<dt class="field">
<span class="var-title">$ht</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerHierarchy.html#var$ht">LoggerHierarchy::$ht</a> in LoggerHierarchy.php</div>
<div class="index-item-description">array hierarchy tree. saves here all loggers</div>
</dd>
<dt class="field">
HT_SIZE
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerNDC.html#constHT_SIZE">LoggerNDC::HT_SIZE</a> in LoggerNDC.php</div>
</dd>
<dt class="field">
<span class="var-title">$host</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderAdodb.html#var$host">LoggerAppenderAdodb::$host</a> in LoggerAppenderAdodb.php</div>
<div class="index-item-description">Database host to connect to</div>
</dd>
</dl>
<a name="i"></a>
<div class="index-letter-section">
<div style="float: left" class="index-letter-title">i</div>
<div style="float: right"><a href="#top">top</a></div>
<div style="clear: both"></div>
</div>
<dl>
<dt class="field">
<span class="method-title">info</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/Logger.html#methodinfo">Logger::info()</a> in Logger.php</div>
<div class="index-item-description">Log a message object with the INFO Level.</div>
</dd>
<dt class="field">
INFO
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLevel.html#constINFO">LoggerLevel::INFO</a> in LoggerLevel.php</div>
</dd>
<dt class="field">
<span class="method-title">initialize</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/Logger.html#methodinitialize">Logger::initialize()</a> in Logger.php</div>
<div class="index-item-description">Initializes the log4php framework.</div>
</dd>
<dt class="field">
<span class="method-title">isAsSevereAsThreshold</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerAppender.html#methodisAsSevereAsThreshold">LoggerAppender::isAsSevereAsThreshold()</a> in LoggerAppender.php</div>
<div class="index-item-description">Check whether the message level is below the appender's threshold.</div>
</dd>
<dt class="field">
<span class="method-title">isAttached</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/Logger.html#methodisAttached">Logger::isAttached()</a> in Logger.php</div>
<div class="index-item-description">Is the appender passed as parameter attached to this category?</div>
</dd>
<dt class="field">
<span class="method-title">isDebugEnabled</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/Logger.html#methodisDebugEnabled">Logger::isDebugEnabled()</a> in Logger.php</div>
<div class="index-item-description">Check whether this category is enabled for the DEBUG Level.</div>
</dd>
<dt class="field">
<span class="method-title">isDisabled</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerHierarchy.html#methodisDisabled">LoggerHierarchy::isDisabled()</a> in LoggerHierarchy.php</div>
<div class="index-item-description">This method will return true if this repository is disabled for level object passed as parameter and false otherwise.</div>
</dd>
<dt class="field">
<span class="method-title">isEnabledFor</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/Logger.html#methodisEnabledFor">Logger::isEnabledFor()</a> in Logger.php</div>
<div class="index-item-description">Check whether this category is enabled for a given Level passed as parameter.</div>
</dd>
<dt class="field">
<span class="method-title">isGreaterOrEqual</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLevel.html#methodisGreaterOrEqual">LoggerLevel::isGreaterOrEqual()</a> in LoggerLevel.php</div>
<div class="index-item-description">Returns <em>true</em> if this level has a higher or equal level than the level passed as argument, <em>false</em> otherwise.</div>
</dd>
<dt class="field">
<span class="method-title">isInfoEnabled</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/Logger.html#methodisInfoEnabled">Logger::isInfoEnabled()</a> in Logger.php</div>
<div class="index-item-description">Check whether this category is enabled for the info Level.</div>
</dd>
<dt class="field">
INTERNAL_ROOT_NAME
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/configurators/LoggerConfiguratorIni.html#constINTERNAL_ROOT_NAME">LoggerConfiguratorIni::INTERNAL_ROOT_NAME</a> in LoggerConfiguratorIni.php</div>
</dd>
<dt class="field">
<span class="method-title">ignoresThrowable</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutTTCC.html#methodignoresThrowable">LoggerLayoutTTCC::ignoresThrowable()</a> in LoggerLayoutTTCC.php</div>
</dd>
</dl>
<a name="l"></a>
<div class="index-letter-section">
<div style="float: left" class="index-letter-title">l</div>
<div style="float: right"><a href="#top">top</a></div>
<div style="clear: both"></div>
</div>
<dl>
<dt class="field">
<span class="var-title">$layout</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerAppender.html#var$layout">LoggerAppender::$layout</a> in LoggerAppender.php</div>
<div class="index-item-description">LoggerLayout for this appender. It can be null if appender has its own layout</div>
</dd>
<dt class="field">
<span class="var-title">$level</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLoggingEvent.html#var$level">LoggerLoggingEvent::$level</a> in LoggerLoggingEvent.php</div>
<div class="index-item-description">Level of logging event.</div>
</dd>
<dt class="field">
<span class="var-title">$lineNumber</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLocationInfo.html#var$lineNumber">LoggerLocationInfo::$lineNumber</a> in LoggerLocationInfo.php</div>
</dd>
<dt class="field">
<span class="include-title">LoggerAppenderAdodb.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_appenders---LoggerAppenderAdodb.php.html">LoggerAppenderAdodb.php</a> in LoggerAppenderAdodb.php</div>
</dd>
<dt class="field">
<span class="include-title">LoggerAppenderConsole.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_appenders---LoggerAppenderConsole.php.html">LoggerAppenderConsole.php</a> in LoggerAppenderConsole.php</div>
</dd>
<dt class="field">
<span class="include-title">LoggerAppenderDailyFile.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_appenders---LoggerAppenderDailyFile.php.html">LoggerAppenderDailyFile.php</a> in LoggerAppenderDailyFile.php</div>
</dd>
<dt class="field">
<span class="include-title">LoggerAppenderEcho.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_appenders---LoggerAppenderEcho.php.html">LoggerAppenderEcho.php</a> in LoggerAppenderEcho.php</div>
</dd>
<dt class="field">
<span class="include-title">LoggerAppenderFile.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_appenders---LoggerAppenderFile.php.html">LoggerAppenderFile.php</a> in LoggerAppenderFile.php</div>
</dd>
<dt class="field">
<span class="include-title">LoggerAppenderMail.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_appenders---LoggerAppenderMail.php.html">LoggerAppenderMail.php</a> in LoggerAppenderMail.php</div>
</dd>
<dt class="field">
<span class="include-title">LoggerAppenderMailEvent.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_appenders---LoggerAppenderMailEvent.php.html">LoggerAppenderMailEvent.php</a> in LoggerAppenderMailEvent.php</div>
</dd>
<dt class="field">
<span class="include-title">LoggerAppenderNull.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_appenders---LoggerAppenderNull.php.html">LoggerAppenderNull.php</a> in LoggerAppenderNull.php</div>
</dd>
<dt class="field">
<span class="include-title">LoggerAppenderPDO.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_appenders---LoggerAppenderPDO.php.html">LoggerAppenderPDO.php</a> in LoggerAppenderPDO.php</div>
</dd>
<dt class="field">
<span class="include-title">LoggerAppenderPhp.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_appenders---LoggerAppenderPhp.php.html">LoggerAppenderPhp.php</a> in LoggerAppenderPhp.php</div>
</dd>
<dt class="field">
<span class="include-title">LoggerAppenderRollingFile.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_appenders---LoggerAppenderRollingFile.php.html">LoggerAppenderRollingFile.php</a> in LoggerAppenderRollingFile.php</div>
</dd>
<dt class="field">
<span class="include-title">LoggerAppenderSocket.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_appenders---LoggerAppenderSocket.php.html">LoggerAppenderSocket.php</a> in LoggerAppenderSocket.php</div>
</dd>
<dt class="field">
<span class="include-title">LoggerAppenderSyslog.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_appenders---LoggerAppenderSyslog.php.html">LoggerAppenderSyslog.php</a> in LoggerAppenderSyslog.php</div>
</dd>
<dt class="field">
<span class="include-title">LoggerConfiguratorBasic.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_configurators---LoggerConfiguratorBasic.php.html">LoggerConfiguratorBasic.php</a> in LoggerConfiguratorBasic.php</div>
</dd>
<dt class="field">
<span class="include-title">LoggerConfiguratorIni.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_configurators---LoggerConfiguratorIni.php.html">LoggerConfiguratorIni.php</a> in LoggerConfiguratorIni.php</div>
</dd>
<dt class="field">
<span class="include-title">LoggerConfiguratorPhp.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_configurators---LoggerConfiguratorPhp.php.html">LoggerConfiguratorPhp.php</a> in LoggerConfiguratorPhp.php</div>
</dd>
<dt class="field">
<span class="include-title">LoggerConfiguratorXml.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_configurators---LoggerConfiguratorXml.php.html">LoggerConfiguratorXml.php</a> in LoggerConfiguratorXml.php</div>
</dd>
<dt class="field">
<span class="include-title">LoggerFilterDenyAll.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_filters---LoggerFilterDenyAll.php.html">LoggerFilterDenyAll.php</a> in LoggerFilterDenyAll.php</div>
</dd>
<dt class="field">
<span class="include-title">LoggerFilterLevelMatch.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_filters---LoggerFilterLevelMatch.php.html">LoggerFilterLevelMatch.php</a> in LoggerFilterLevelMatch.php</div>
</dd>
<dt class="field">
<span class="include-title">LoggerFilterLevelRange.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_filters---LoggerFilterLevelRange.php.html">LoggerFilterLevelRange.php</a> in LoggerFilterLevelRange.php</div>
</dd>
<dt class="field">
<span class="include-title">LoggerFilterStringMatch.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_filters---LoggerFilterStringMatch.php.html">LoggerFilterStringMatch.php</a> in LoggerFilterStringMatch.php</div>
</dd>
<dt class="field">
<span class="include-title">LoggerBasicPatternConverter.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_helpers---LoggerBasicPatternConverter.php.html">LoggerBasicPatternConverter.php</a> in LoggerBasicPatternConverter.php</div>
</dd>
<dt class="field">
<span class="include-title">LoggerCategoryPatternConverter.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_helpers---LoggerCategoryPatternConverter.php.html">LoggerCategoryPatternConverter.php</a> in LoggerCategoryPatternConverter.php</div>
</dd>
<dt class="field">
<span class="include-title">LoggerClassNamePatternConverter.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_helpers---LoggerClassNamePatternConverter.php.html">LoggerClassNamePatternConverter.php</a> in LoggerClassNamePatternConverter.php</div>
</dd>
<dt class="field">
<span class="include-title">LoggerDatePatternConverter.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_helpers---LoggerDatePatternConverter.php.html">LoggerDatePatternConverter.php</a> in LoggerDatePatternConverter.php</div>
</dd>
<dt class="field">
<span class="include-title">LoggerFormattingInfo.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_helpers---LoggerFormattingInfo.php.html">LoggerFormattingInfo.php</a> in LoggerFormattingInfo.php</div>
</dd>
<dt class="field">
<span class="include-title">LoggerLiteralPatternConverter.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_helpers---LoggerLiteralPatternConverter.php.html">LoggerLiteralPatternConverter.php</a> in LoggerLiteralPatternConverter.php</div>
</dd>
<dt class="field">
<span class="include-title">LoggerLocationPatternConverter.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_helpers---LoggerLocationPatternConverter.php.html">LoggerLocationPatternConverter.php</a> in LoggerLocationPatternConverter.php</div>
</dd>
<dt class="field">
<span class="include-title">LoggerMDCPatternConverter.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_helpers---LoggerMDCPatternConverter.php.html">LoggerMDCPatternConverter.php</a> in LoggerMDCPatternConverter.php</div>
</dd>
<dt class="field">
<span class="include-title">LoggerNamedPatternConverter.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_helpers---LoggerNamedPatternConverter.php.html">LoggerNamedPatternConverter.php</a> in LoggerNamedPatternConverter.php</div>
</dd>
<dt class="field">
<span class="include-title">LoggerOptionConverter.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_helpers---LoggerOptionConverter.php.html">LoggerOptionConverter.php</a> in LoggerOptionConverter.php</div>
</dd>
<dt class="field">
<span class="include-title">LoggerPatternConverter.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_helpers---LoggerPatternConverter.php.html">LoggerPatternConverter.php</a> in LoggerPatternConverter.php</div>
</dd>
<dt class="field">
<span class="include-title">LoggerPatternParser.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_helpers---LoggerPatternParser.php.html">LoggerPatternParser.php</a> in LoggerPatternParser.php</div>
</dd>
<dt class="field">
<span class="include-title">LoggerLayoutHtml.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_layouts---LoggerLayoutHtml.php.html">LoggerLayoutHtml.php</a> in LoggerLayoutHtml.php</div>
</dd>
<dt class="field">
<span class="include-title">LoggerLayoutPattern.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_layouts---LoggerLayoutPattern.php.html">LoggerLayoutPattern.php</a> in LoggerLayoutPattern.php</div>
</dd>
<dt class="field">
<span class="include-title">LoggerLayoutSimple.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_layouts---LoggerLayoutSimple.php.html">LoggerLayoutSimple.php</a> in LoggerLayoutSimple.php</div>
</dd>
<dt class="field">
<span class="include-title">LoggerLayoutTTCC.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_layouts---LoggerLayoutTTCC.php.html">LoggerLayoutTTCC.php</a> in LoggerLayoutTTCC.php</div>
</dd>
<dt class="field">
<span class="include-title">LoggerLayoutXml.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_layouts---LoggerLayoutXml.php.html">LoggerLayoutXml.php</a> in LoggerLayoutXml.php</div>
</dd>
<dt class="field">
LOCATION_INFO_NA
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLocationInfo.html#constLOCATION_INFO_NA">LoggerLocationInfo::LOCATION_INFO_NA</a> in LoggerLocationInfo.php</div>
<div class="index-item-description">When location information is not available the constant <em>NA</em> is returned. Current value of this string constant is <strong>?</strong>.</div>
</dd>
<dt class="field">
<span class="method-title">log</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/Logger.html#methodlog">Logger::log()</a> in Logger.php</div>
<div class="index-item-description">This generic form is intended to be used by wrappers.</div>
</dd>
<dt class="field">
<span class="const-title">LOG4PHP_DIR</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_Logger.php.html#defineLOG4PHP_DIR">LOG4PHP_DIR</a> in Logger.php</div>
<div class="index-item-description">LOG4PHP_DIR points to the log4php root directory.</div>
</dd>
<dt class="field">
Logger
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/Logger.html">Logger</a> in Logger.php</div>
<div class="index-item-description">This is the central class in the log4j package. Most logging operations, except configuration, are done through this class.</div>
</dd>
<dt class="field">
<span class="include-title">Logger.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_Logger.php.html">Logger.php</a> in Logger.php</div>
</dd>
<dt class="field">
LoggerAppender
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerAppender.html">LoggerAppender</a> in LoggerAppender.php</div>
<div class="index-item-description">Abstract class that defines output logs strategies.</div>
</dd>
<dt class="field">
<span class="include-title">LoggerAppender.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_LoggerAppender.php.html">LoggerAppender.php</a> in LoggerAppender.php</div>
</dd>
<dt class="field">
LoggerAppenderPool
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerAppenderPool.html">LoggerAppenderPool</a> in LoggerAppenderPool.php</div>
<div class="index-item-description">Pool implmentation for LoggerAppender instances</div>
</dd>
<dt class="field">
<span class="include-title">LoggerAppenderPool.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_LoggerAppenderPool.php.html">LoggerAppenderPool.php</a> in LoggerAppenderPool.php</div>
</dd>
<dt class="field">
LoggerConfigurator
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerConfigurator.html">LoggerConfigurator</a> in LoggerConfigurator.php</div>
<div class="index-item-description">Implemented by classes capable of configuring log4php using a URL.</div>
</dd>
<dt class="field">
<span class="include-title">LoggerConfigurator.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_LoggerConfigurator.php.html">LoggerConfigurator.php</a> in LoggerConfigurator.php</div>
</dd>
<dt class="field">
LoggerException
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerException.html">LoggerException</a> in LoggerException.php</div>
<div class="index-item-description">LoggerException class</div>
</dd>
<dt class="field">
<span class="include-title">LoggerException.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_LoggerException.php.html">LoggerException.php</a> in LoggerException.php</div>
</dd>
<dt class="field">
LoggerFilter
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerFilter.html">LoggerFilter</a> in LoggerFilter.php</div>
<div class="index-item-description">Users should extend this class to implement customized logging</div>
</dd>
<dt class="field">
<span class="include-title">LoggerFilter.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_LoggerFilter.php.html">LoggerFilter.php</a> in LoggerFilter.php</div>
</dd>
<dt class="field">
LoggerHierarchy
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerHierarchy.html">LoggerHierarchy</a> in LoggerHierarchy.php</div>
<div class="index-item-description">This class is specialized in retrieving loggers by name and also maintaining the logger hierarchy. The logger hierarchy is dealing with the several Log-Levels Logger can have. From log4j website:</div>
</dd>
<dt class="field">
<span class="include-title">LoggerHierarchy.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_LoggerHierarchy.php.html">LoggerHierarchy.php</a> in LoggerHierarchy.php</div>
</dd>
<dt class="field">
LoggerLayout
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLayout.html">LoggerLayout</a> in LoggerLayout.php</div>
<div class="index-item-description">Extend this abstract class to create your own log layout format.</div>
</dd>
<dt class="field">
<span class="include-title">LoggerLayout.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_LoggerLayout.php.html">LoggerLayout.php</a> in LoggerLayout.php</div>
</dd>
<dt class="field">
LoggerLevel
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLevel.html">LoggerLevel</a> in LoggerLevel.php</div>
<div class="index-item-description">Defines the minimum set of levels recognized by the system, that is <em>OFF</em>, <em>FATAL</em>, <em>ERROR</em>, <em>WARN</em>, <em>INFO</em>, <em>DEBUG</em> and <em>ALL</em>.</div>
</dd>
<dt class="field">
<span class="include-title">LoggerLevel.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_LoggerLevel.php.html">LoggerLevel.php</a> in LoggerLevel.php</div>
</dd>
<dt class="field">
LoggerLocationInfo
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLocationInfo.html">LoggerLocationInfo</a> in LoggerLocationInfo.php</div>
<div class="index-item-description">The internal representation of caller location information.</div>
</dd>
<dt class="field">
<span class="include-title">LoggerLocationInfo.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_LoggerLocationInfo.php.html">LoggerLocationInfo.php</a> in LoggerLocationInfo.php</div>
</dd>
<dt class="field">
LoggerLoggingEvent
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLoggingEvent.html">LoggerLoggingEvent</a> in LoggerLoggingEvent.php</div>
<div class="index-item-description">The internal representation of logging event.</div>
</dd>
<dt class="field">
<span class="include-title">LoggerLoggingEvent.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_LoggerLoggingEvent.php.html">LoggerLoggingEvent.php</a> in LoggerLoggingEvent.php</div>
</dd>
<dt class="field">
LoggerMDC
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerMDC.html">LoggerMDC</a> in LoggerMDC.php</div>
<div class="index-item-description">The LoggerMDC class provides <em>mapped diagnostic contexts</em>.</div>
</dd>
<dt class="field">
<span class="include-title">LoggerMDC.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_LoggerMDC.php.html">LoggerMDC.php</a> in LoggerMDC.php</div>
</dd>
<dt class="field">
LoggerNDC
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerNDC.html">LoggerNDC</a> in LoggerNDC.php</div>
<div class="index-item-description">The NDC class implements <em>nested diagnostic contexts</em>.</div>
</dd>
<dt class="field">
<span class="include-title">LoggerNDC.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_LoggerNDC.php.html">LoggerNDC.php</a> in LoggerNDC.php</div>
</dd>
<dt class="field">
LoggerReflectionUtils
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerReflectionUtils.html">LoggerReflectionUtils</a> in LoggerReflectionUtils.php</div>
<div class="index-item-description">Provides methods for reflective use on php objects</div>
</dd>
<dt class="field">
<span class="include-title">LoggerReflectionUtils.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_LoggerReflectionUtils.php.html">LoggerReflectionUtils.php</a> in LoggerReflectionUtils.php</div>
</dd>
<dt class="field">
LoggerRoot
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerRoot.html">LoggerRoot</a> in LoggerRoot.php</div>
<div class="index-item-description">The root logger.</div>
</dd>
<dt class="field">
<span class="include-title">LoggerRoot.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_LoggerRoot.php.html">LoggerRoot.php</a> in LoggerRoot.php</div>
</dd>
<dt class="field">
<span class="include-title">LoggerRendererDefault.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_renderers---LoggerRendererDefault.php.html">LoggerRendererDefault.php</a> in LoggerRendererDefault.php</div>
</dd>
<dt class="field">
<span class="include-title">LoggerRendererMap.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_renderers---LoggerRendererMap.php.html">LoggerRendererMap.php</a> in LoggerRendererMap.php</div>
</dd>
<dt class="field">
<span class="include-title">LoggerRendererObject.php</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/_renderers---LoggerRendererObject.php.html">LoggerRendererObject.php</a> in LoggerRendererObject.php</div>
</dd>
<dt class="field">
LoggerAppenderAdodb
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderAdodb.html">LoggerAppenderAdodb</a> in LoggerAppenderAdodb.php</div>
<div class="index-item-description">Appends log events to a db table using adodb class.</div>
</dd>
<dt class="field">
LoggerAppenderConsole
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderConsole.html">LoggerAppenderConsole</a> in LoggerAppenderConsole.php</div>
<div class="index-item-description">ConsoleAppender appends log events to STDOUT or STDERR.</div>
</dd>
<dt class="field">
LoggerAppenderDailyFile
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderDailyFile.html">LoggerAppenderDailyFile</a> in LoggerAppenderDailyFile.php</div>
<div class="index-item-description">An Appender that automatically creates a new logfile each day.</div>
</dd>
<dt class="field">
LoggerAppenderEcho
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderEcho.html">LoggerAppenderEcho</a> in LoggerAppenderEcho.php</div>
<div class="index-item-description">LoggerAppenderEcho uses <a href="http://www.php.net/echo">echo</a> function to output events.</div>
</dd>
<dt class="field">
LoggerAppenderFile
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderFile.html">LoggerAppenderFile</a> in LoggerAppenderFile.php</div>
<div class="index-item-description">FileAppender appends log events to a file.</div>
</dd>
<dt class="field">
LoggerAppenderMail
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderMail.html">LoggerAppenderMail</a> in LoggerAppenderMail.php</div>
<div class="index-item-description">Appends log events to mail using php function <a href="http://www.php.net/mail">http://www.php.net/mail</a>.</div>
</dd>
<dt class="field">
LoggerAppenderMailEvent
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderMailEvent.html">LoggerAppenderMailEvent</a> in LoggerAppenderMailEvent.php</div>
<div class="index-item-description">Log every events as a separate email.</div>
</dd>
<dt class="field">
LoggerAppenderNull
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderNull.html">LoggerAppenderNull</a> in LoggerAppenderNull.php</div>
<div class="index-item-description">A NullAppender merely exists, it never outputs a message to any device.</div>
</dd>
<dt class="field">
LoggerAppenderPDO
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderPDO.html">LoggerAppenderPDO</a> in LoggerAppenderPDO.php</div>
<div class="index-item-description">Appends log events to a db table using PDO.</div>
</dd>
<dt class="field">
LoggerAppenderPhp
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderPhp.html">LoggerAppenderPhp</a> in LoggerAppenderPhp.php</div>
<div class="index-item-description">Log events using php <a href="http://www.php.net/trigger_error">http://www.php.net/trigger_error</a> function and a <a href="log4php/layouts/LoggerLayoutTTCC.html">LoggerLayoutTTCC</a> default layout.</div>
</dd>
<dt class="field">
LoggerAppenderRollingFile
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderRollingFile.html">LoggerAppenderRollingFile</a> in LoggerAppenderRollingFile.php</div>
<div class="index-item-description">LoggerAppenderRollingFile extends LoggerAppenderFile to backup the log files when they reach a certain size.</div>
</dd>
<dt class="field">
LoggerAppenderSocket
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderSocket.html">LoggerAppenderSocket</a> in LoggerAppenderSocket.php</div>
<div class="index-item-description">Serialize events and send them to a network socket.</div>
</dd>
<dt class="field">
LoggerAppenderSyslog
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderSyslog.html">LoggerAppenderSyslog</a> in LoggerAppenderSyslog.php</div>
<div class="index-item-description">Log events using php <a href="http://www.php.net/syslog">http://www.php.net/syslog</a> function.</div>
</dd>
<dt class="field">
LAYOUT_STATE
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/configurators/LoggerConfiguratorXml.html#constLAYOUT_STATE">LoggerConfiguratorXml::LAYOUT_STATE</a> in LoggerConfiguratorXml.php</div>
</dd>
<dt class="field">
LoggerConfiguratorBasic
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/configurators/LoggerConfiguratorBasic.html">LoggerConfiguratorBasic</a> in LoggerConfiguratorBasic.php</div>
<div class="index-item-description">Use this class to quickly configure the package.</div>
</dd>
<dt class="field">
LoggerConfiguratorIni
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/configurators/LoggerConfiguratorIni.html">LoggerConfiguratorIni</a> in LoggerConfiguratorIni.php</div>
<div class="index-item-description">Allows the configuration of log4php from an external file.</div>
</dd>
<dt class="field">
LoggerConfiguratorPhp
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/configurators/LoggerConfiguratorPhp.html">LoggerConfiguratorPhp</a> in LoggerConfiguratorPhp.php</div>
<div class="index-item-description">LoggerConfiguratorPhp class</div>
</dd>
<dt class="field">
LoggerConfiguratorXml
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/configurators/LoggerConfiguratorXml.html">LoggerConfiguratorXml</a> in LoggerConfiguratorXml.php</div>
<div class="index-item-description">Use this class to initialize the log4php environment using XML files.</div>
</dd>
<dt class="field">
LOGGER_DEBUG_KEY
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/configurators/LoggerConfiguratorIni.html#constLOGGER_DEBUG_KEY">LoggerConfiguratorIni::LOGGER_DEBUG_KEY</a> in LoggerConfiguratorIni.php</div>
</dd>
<dt class="field">
LOGGER_FACTORY_KEY
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/configurators/LoggerConfiguratorIni.html#constLOGGER_FACTORY_KEY">LoggerConfiguratorIni::LOGGER_FACTORY_KEY</a> in LoggerConfiguratorIni.php</div>
<div class="index-item-description">Key for specifying the LoggerFactory.</div>
</dd>
<dt class="field">
LOGGER_PREFIX
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/configurators/LoggerConfiguratorIni.html#constLOGGER_PREFIX">LoggerConfiguratorIni::LOGGER_PREFIX</a> in LoggerConfiguratorIni.php</div>
</dd>
<dt class="field">
LOGGER_STATE
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/configurators/LoggerConfiguratorXml.html#constLOGGER_STATE">LoggerConfiguratorXml::LOGGER_STATE</a> in LoggerConfiguratorXml.php</div>
</dd>
<dt class="field">
LoggerFilterDenyAll
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/filters/LoggerFilterDenyAll.html">LoggerFilterDenyAll</a> in LoggerFilterDenyAll.php</div>
<div class="index-item-description">This filter drops all logging events.</div>
</dd>
<dt class="field">
LoggerFilterLevelMatch
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/filters/LoggerFilterLevelMatch.html">LoggerFilterLevelMatch</a> in LoggerFilterLevelMatch.php</div>
<div class="index-item-description">This is a very simple filter based on level matching.</div>
</dd>
<dt class="field">
LoggerFilterLevelRange
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/filters/LoggerFilterLevelRange.html">LoggerFilterLevelRange</a> in LoggerFilterLevelRange.php</div>
<div class="index-item-description">This is a very simple filter based on level matching, which can be used to reject messages with priorities outside a certain range.</div>
</dd>
<dt class="field">
LoggerFilterStringMatch
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/filters/LoggerFilterStringMatch.html">LoggerFilterStringMatch</a> in LoggerFilterStringMatch.php</div>
<div class="index-item-description">This is a very simple filter based on string matching.</div>
</dd>
<dt class="field">
<span class="var-title">$leftAlign</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerPatternConverter.html#var$leftAlign">LoggerPatternConverter::$leftAlign</a> in LoggerPatternConverter.php</div>
</dd>
<dt class="field">
<span class="var-title">$leftAlign</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerFormattingInfo.html#var$leftAlign">LoggerFormattingInfo::$leftAlign</a> in LoggerFormattingInfo.php</div>
</dd>
<dt class="field">
LEVEL_CONVERTER
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerPatternParser.html#constLEVEL_CONVERTER">LoggerPatternParser::LEVEL_CONVERTER</a> in LoggerPatternParser.php</div>
</dd>
<dt class="field">
LINE_LOCATION_CONVERTER
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerPatternParser.html#constLINE_LOCATION_CONVERTER">LoggerPatternParser::LINE_LOCATION_CONVERTER</a> in LoggerPatternParser.php</div>
</dd>
<dt class="field">
LITERAL_STATE
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerPatternParser.html#constLITERAL_STATE">LoggerPatternParser::LITERAL_STATE</a> in LoggerPatternParser.php</div>
</dd>
<dt class="field">
LoggerBasicPatternConverter
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerBasicPatternConverter.html">LoggerBasicPatternConverter</a> in LoggerBasicPatternConverter.php</div>
</dd>
<dt class="field">
LoggerCategoryPatternConverter
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerCategoryPatternConverter.html">LoggerCategoryPatternConverter</a> in LoggerCategoryPatternConverter.php</div>
</dd>
<dt class="field">
LoggerClassNamePatternConverter
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerClassNamePatternConverter.html">LoggerClassNamePatternConverter</a> in LoggerClassNamePatternConverter.php</div>
</dd>
<dt class="field">
LoggerDatePatternConverter
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerDatePatternConverter.html">LoggerDatePatternConverter</a> in LoggerDatePatternConverter.php</div>
</dd>
<dt class="field">
LoggerFormattingInfo
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerFormattingInfo.html">LoggerFormattingInfo</a> in LoggerFormattingInfo.php</div>
<div class="index-item-description">This class encapsulates the information obtained when parsing formatting modifiers in conversion modifiers.</div>
</dd>
<dt class="field">
LoggerLiteralPatternConverter
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerLiteralPatternConverter.html">LoggerLiteralPatternConverter</a> in LoggerLiteralPatternConverter.php</div>
</dd>
<dt class="field">
LoggerLocationPatternConverter
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerLocationPatternConverter.html">LoggerLocationPatternConverter</a> in LoggerLocationPatternConverter.php</div>
</dd>
<dt class="field">
LoggerMDCPatternConverter
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerMDCPatternConverter.html">LoggerMDCPatternConverter</a> in LoggerMDCPatternConverter.php</div>
</dd>
<dt class="field">
LoggerNamedPatternConverter
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerNamedPatternConverter.html">LoggerNamedPatternConverter</a> in LoggerNamedPatternConverter.php</div>
</dd>
<dt class="field">
LoggerOptionConverter
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerOptionConverter.html">LoggerOptionConverter</a> in LoggerOptionConverter.php</div>
<div class="index-item-description">A convenience class to convert property values to specific types.</div>
</dd>
<dt class="field">
LoggerPatternConverter
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerPatternConverter.html">LoggerPatternConverter</a> in LoggerPatternConverter.php</div>
<div class="index-item-description">LoggerPatternConverter is an abstract class that provides the formatting functionality that derived classes need.</div>
</dd>
<dt class="field">
LoggerPatternParser
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerPatternParser.html">LoggerPatternParser</a> in LoggerPatternParser.php</div>
<div class="index-item-description">Most of the work of the LoggerPatternLayout class is delegated to the <a href="log4php/helpers/LoggerPatternParser.html">LoggerPatternParser</a> class.</div>
</dd>
<dt class="field">
LOG4J_NS
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutXml.html#constLOG4J_NS">LoggerLayoutXml::LOG4J_NS</a> in LoggerLayoutXml.php</div>
</dd>
<dt class="field">
LOG4J_NS_PREFIX
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutXml.html#constLOG4J_NS_PREFIX">LoggerLayoutXml::LOG4J_NS_PREFIX</a> in LoggerLayoutXml.php</div>
</dd>
<dt class="field">
LOG4PHP_LOGGER_LAYOUT_NULL_DATE_FORMAT
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutTTCC.html#constLOG4PHP_LOGGER_LAYOUT_NULL_DATE_FORMAT">LoggerLayoutTTCC::LOG4PHP_LOGGER_LAYOUT_NULL_DATE_FORMAT</a> in LoggerLayoutTTCC.php</div>
<div class="index-item-description">String constant designating no time information. Current value of this constant is <strong>NULL</strong>.</div>
</dd>
<dt class="field">
LOG4PHP_LOGGER_LAYOUT_RELATIVE_TIME_DATE_FORMAT
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutTTCC.html#constLOG4PHP_LOGGER_LAYOUT_RELATIVE_TIME_DATE_FORMAT">LoggerLayoutTTCC::LOG4PHP_LOGGER_LAYOUT_RELATIVE_TIME_DATE_FORMAT</a> in LoggerLayoutTTCC.php</div>
<div class="index-item-description">String constant designating relative time. Current value of this constant is <strong>RELATIVE</strong>.</div>
</dd>
<dt class="field">
LOG4PHP_NS
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutXml.html#constLOG4PHP_NS">LoggerLayoutXml::LOG4PHP_NS</a> in LoggerLayoutXml.php</div>
</dd>
<dt class="field">
LOG4PHP_NS_PREFIX
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutXml.html#constLOG4PHP_NS_PREFIX">LoggerLayoutXml::LOG4PHP_NS_PREFIX</a> in LoggerLayoutXml.php</div>
</dd>
<dt class="field">
LoggerLayoutHtml
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutHtml.html">LoggerLayoutHtml</a> in LoggerLayoutHtml.php</div>
<div class="index-item-description">This layout outputs events in a HTML table.</div>
</dd>
<dt class="field">
LoggerLayoutPattern
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutPattern.html">LoggerLayoutPattern</a> in LoggerLayoutPattern.php</div>
<div class="index-item-description">A flexible layout configurable with pattern string.</div>
</dd>
<dt class="field">
LoggerLayoutSimple
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutSimple.html">LoggerLayoutSimple</a> in LoggerLayoutSimple.php</div>
<div class="index-item-description">A simple layout.</div>
</dd>
<dt class="field">
LoggerLayoutTTCC
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutTTCC.html">LoggerLayoutTTCC</a> in LoggerLayoutTTCC.php</div>
<div class="index-item-description">TTCC layout format consists of <strong>t</strong>ime, <strong>t</strong>hread, <strong>c</strong>ategory and nested diagnostic <strong>c</strong>ontext information, hence the name.</div>
</dd>
<dt class="field">
LoggerLayoutXml
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutXml.html">LoggerLayoutXml</a> in LoggerLayoutXml.php</div>
<div class="index-item-description">The output of the LoggerXmlLayout consists of a series of log4php:event elements.</div>
</dd>
<dt class="field">
LoggerRendererDefault
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/renderers/LoggerRendererDefault.html">LoggerRendererDefault</a> in LoggerRendererDefault.php</div>
<div class="index-item-description">The default Renderer renders objects by type casting.</div>
</dd>
<dt class="field">
LoggerRendererMap
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/renderers/LoggerRendererMap.html">LoggerRendererMap</a> in LoggerRendererMap.php</div>
<div class="index-item-description">Log objects using customized renderers that implement <a href="log4php/renderers/LoggerRendererObject.html">LoggerRendererObject</a>.</div>
</dd>
<dt class="field">
LoggerRendererObject
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/renderers/LoggerRendererObject.html">LoggerRendererObject</a> in LoggerRendererObject.php</div>
<div class="index-item-description">Implement this interface in order to render objects as strings using <a href="log4php/renderers/LoggerRendererMap.html">LoggerRendererMap</a>.</div>
</dd>
</dl>
<a name="m"></a>
<div class="index-letter-section">
<div style="float: left" class="index-letter-title">m</div>
<div style="float: right"><a href="#top">top</a></div>
<div style="clear: both"></div>
</div>
<dl>
<dt class="field">
<span class="var-title">$methodName</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLocationInfo.html#var$methodName">LoggerLocationInfo::$methodName</a> in LoggerLocationInfo.php</div>
</dd>
<dt class="field">
<span class="var-title">$max</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerPatternConverter.html#var$max">LoggerPatternConverter::$max</a> in LoggerPatternConverter.php</div>
</dd>
<dt class="field">
<span class="var-title">$max</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerFormattingInfo.html#var$max">LoggerFormattingInfo::$max</a> in LoggerFormattingInfo.php</div>
</dd>
<dt class="field">
<span class="var-title">$min</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerPatternConverter.html#var$min">LoggerPatternConverter::$min</a> in LoggerPatternConverter.php</div>
</dd>
<dt class="field">
<span class="var-title">$min</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerFormattingInfo.html#var$min">LoggerFormattingInfo::$min</a> in LoggerFormattingInfo.php</div>
</dd>
<dt class="field">
MAX_STATE
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerPatternParser.html#constMAX_STATE">LoggerPatternParser::MAX_STATE</a> in LoggerPatternParser.php</div>
</dd>
<dt class="field">
MESSAGE_CONVERTER
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerPatternParser.html#constMESSAGE_CONVERTER">LoggerPatternParser::MESSAGE_CONVERTER</a> in LoggerPatternParser.php</div>
</dd>
<dt class="field">
METHOD_LOCATION_CONVERTER
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerPatternParser.html#constMETHOD_LOCATION_CONVERTER">LoggerPatternParser::METHOD_LOCATION_CONVERTER</a> in LoggerPatternParser.php</div>
</dd>
<dt class="field">
MINUS_STATE
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerPatternParser.html#constMINUS_STATE">LoggerPatternParser::MINUS_STATE</a> in LoggerPatternParser.php</div>
</dd>
<dt class="field">
MIN_STATE
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerPatternParser.html#constMIN_STATE">LoggerPatternParser::MIN_STATE</a> in LoggerPatternParser.php</div>
</dd>
<dt class="field">
<span class="var-title">$microSecondsPrinting</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutTTCC.html#var$microSecondsPrinting">LoggerLayoutTTCC::$microSecondsPrinting</a> in LoggerLayoutTTCC.php</div>
</dd>
</dl>
<a name="n"></a>
<div class="index-letter-section">
<div style="float: left" class="index-letter-title">n</div>
<div style="float: right"><a href="#top">top</a></div>
<div style="clear: both"></div>
</div>
<dl>
<dt class="field">
<span class="var-title">$name</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerAppender.html#var$name">LoggerAppender::$name</a> in LoggerAppender.php</div>
</dd>
<dt class="field">
<span class="var-title">$next</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerFilter.html#var$next">LoggerFilter::$next</a> in LoggerFilter.php</div>
</dd>
<dt class="field">
NEUTRAL
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerFilter.html#constNEUTRAL">LoggerFilter::NEUTRAL</a> in LoggerFilter.php</div>
<div class="index-item-description">This filter is neutral with respect to the log event. The remaining filters, if any, should be consulted for a final decision.</div>
</dd>
<dt class="field">
<span class="var-title">$next</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerPatternConverter.html#var$next">LoggerPatternConverter::$next</a> in LoggerPatternConverter.php</div>
</dd>
<dt class="field">
NDC_CONVERTER
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerPatternParser.html#constNDC_CONVERTER">LoggerPatternParser::NDC_CONVERTER</a> in LoggerPatternParser.php</div>
</dd>
</dl>
<a name="o"></a>
<div class="index-letter-section">
<div style="float: left" class="index-letter-title">o</div>
<div style="float: right"><a href="#top">top</a></div>
<div style="clear: both"></div>
</div>
<dl>
<dt class="field">
OFF
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLevel.html#constOFF">LoggerLevel::OFF</a> in LoggerLevel.php</div>
</dd>
</dl>
<a name="p"></a>
<div class="index-letter-section">
<div style="float: left" class="index-letter-title">p</div>
<div style="float: right"><a href="#top">top</a></div>
<div style="clear: both"></div>
</div>
<dl>
<dt class="field">
<span class="method-title">peek</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerNDC.html#methodpeek">LoggerNDC::peek()</a> in LoggerNDC.php</div>
<div class="index-item-description">Looks at the last diagnostic context at the top of this NDC without removing it.</div>
</dd>
<dt class="field">
<span class="method-title">pop</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerNDC.html#methodpop">LoggerNDC::pop()</a> in LoggerNDC.php</div>
<div class="index-item-description">Clients should call this method before leaving a diagnostic context.</div>
</dd>
<dt class="field">
<span class="method-title">push</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerNDC.html#methodpush">LoggerNDC::push()</a> in LoggerNDC.php</div>
<div class="index-item-description">Push new diagnostic context information for the current thread.</div>
</dd>
<dt class="field">
<span class="method-title">put</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerMDC.html#methodput">LoggerMDC::put()</a> in LoggerMDC.php</div>
<div class="index-item-description">Put a context value as identified with the key parameter into the current thread's context map.</div>
</dd>
<dt class="field">
<span class="var-title">$password</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderAdodb.html#var$password">LoggerAppenderAdodb::$password</a> in LoggerAppenderAdodb.php</div>
<div class="index-item-description">Database password</div>
</dd>
<dt class="field">
<span class="method-title">parse</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerPatternParser.html#methodparse">LoggerPatternParser::parse()</a> in LoggerPatternParser.php</div>
<div class="index-item-description">Parser.</div>
</dd>
</dl>
<a name="r"></a>
<div class="index-letter-section">
<div style="float: left" class="index-letter-title">r</div>
<div style="float: right"><a href="#top">top</a></div>
<div style="clear: both"></div>
</div>
<dl>
<dt class="field">
<span class="var-title">$rendererMap</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerHierarchy.html#var$rendererMap">LoggerHierarchy::$rendererMap</a> in LoggerHierarchy.php</div>
<div class="index-item-description">LoggerRendererMap</div>
</dd>
<dt class="field">
<span class="var-title">$requiresLayout</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerAppender.html#var$requiresLayout">LoggerAppender::$requiresLayout</a> in LoggerAppender.php</div>
</dd>
<dt class="field">
<span class="var-title">$root</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerHierarchy.html#var$root">LoggerHierarchy::$root</a> in LoggerHierarchy.php</div>
<div class="index-item-description">The root Logger</div>
</dd>
<dt class="field">
<span class="method-title">remove</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerNDC.html#methodremove">LoggerNDC::remove()</a> in LoggerNDC.php</div>
<div class="index-item-description">Remove the diagnostic context for this thread.</div>
</dd>
<dt class="field">
<span class="method-title">remove</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerMDC.html#methodremove">LoggerMDC::remove()</a> in LoggerMDC.php</div>
<div class="index-item-description">Remove the the context identified by the key parameter.</div>
</dd>
<dt class="field">
<span class="method-title">removeAllAppenders</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/Logger.html#methodremoveAllAppenders">Logger::removeAllAppenders()</a> in Logger.php</div>
<div class="index-item-description">Remove all previously added appenders from this Category instance.</div>
</dd>
<dt class="field">
<span class="method-title">removeAppender</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/Logger.html#methodremoveAppender">Logger::removeAppender()</a> in Logger.php</div>
<div class="index-item-description">Remove the appender passed as parameter form the list of appenders.</div>
</dd>
<dt class="field">
<span class="method-title">requiresLayout</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerAppender.html#methodrequiresLayout">LoggerAppender::requiresLayout()</a> in LoggerAppender.php</div>
<div class="index-item-description">Configurators call this method to determine if the appender requires a layout.</div>
</dd>
<dt class="field">
<span class="method-title">resetConfiguration</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/Logger.html#methodresetConfiguration">Logger::resetConfiguration()</a> in Logger.php</div>
<div class="index-item-description">Destroy configurations for logger definitions</div>
</dd>
<dt class="field">
<span class="method-title">resetConfiguration</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerHierarchy.html#methodresetConfiguration">LoggerHierarchy::resetConfiguration()</a> in LoggerHierarchy.php</div>
<div class="index-item-description">Reset all values contained in this hierarchy instance to their default.</div>
</dd>
<dt class="field">
<span class="var-title">$requiresLayout</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderNull.html#var$requiresLayout">LoggerAppenderNull::$requiresLayout</a> in LoggerAppenderNull.php</div>
</dd>
<dt class="field">
<span class="var-title">$requiresLayout</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderMailEvent.html#var$requiresLayout">LoggerAppenderMailEvent::$requiresLayout</a> in LoggerAppenderMailEvent.php</div>
</dd>
<dt class="field">
<span class="var-title">$requiresLayout</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderConsole.html#var$requiresLayout">LoggerAppenderConsole::$requiresLayout</a> in LoggerAppenderConsole.php</div>
</dd>
<dt class="field">
<span class="method-title">reset</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderSocket.html#methodreset">LoggerAppenderSocket::reset()</a> in LoggerAppenderSocket.php</div>
</dd>
<dt class="field">
RENDERER_PREFIX
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/configurators/LoggerConfiguratorIni.html#constRENDERER_PREFIX">LoggerConfiguratorIni::RENDERER_PREFIX</a> in LoggerConfiguratorIni.php</div>
</dd>
<dt class="field">
ROOT_CATEGORY_PREFIX
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/configurators/LoggerConfiguratorIni.html#constROOT_CATEGORY_PREFIX">LoggerConfiguratorIni::ROOT_CATEGORY_PREFIX</a> in LoggerConfiguratorIni.php</div>
</dd>
<dt class="field">
ROOT_LOGGER_PREFIX
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/configurators/LoggerConfiguratorIni.html#constROOT_LOGGER_PREFIX">LoggerConfiguratorIni::ROOT_LOGGER_PREFIX</a> in LoggerConfiguratorIni.php</div>
</dd>
<dt class="field">
ROOT_STATE
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/configurators/LoggerConfiguratorXml.html#constROOT_STATE">LoggerConfiguratorXml::ROOT_STATE</a> in LoggerConfiguratorXml.php</div>
</dd>
<dt class="field">
RELATIVE_TIME_CONVERTER
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerPatternParser.html#constRELATIVE_TIME_CONVERTER">LoggerPatternParser::RELATIVE_TIME_CONVERTER</a> in LoggerPatternParser.php</div>
</dd>
<dt class="field">
<span class="method-title">reset</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerFormattingInfo.html#methodreset">LoggerFormattingInfo::reset()</a> in LoggerFormattingInfo.php</div>
</dd>
<dt class="field">
<span class="method-title">render</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/renderers/LoggerRendererObject.html#methodrender">LoggerRendererObject::render()</a> in LoggerRendererObject.php</div>
<div class="index-item-description">Render the entity passed as parameter as a String.</div>
</dd>
<dt class="field">
<span class="method-title">render</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/renderers/LoggerRendererDefault.html#methodrender">LoggerRendererDefault::render()</a> in LoggerRendererDefault.php</div>
<div class="index-item-description">Render objects by type casting</div>
</dd>
</dl>
<a name="s"></a>
<div class="index-letter-section">
<div style="float: left" class="index-letter-title">s</div>
<div style="float: right"><a href="#top">top</a></div>
<div style="clear: both"></div>
</div>
<dl>
<dt class="field">
<span class="method-title">setAdditivity</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/Logger.html#methodsetAdditivity">Logger::setAdditivity()</a> in Logger.php</div>
<div class="index-item-description">Set the additivity flag for this Category instance.</div>
</dd>
<dt class="field">
<span class="method-title">setLayout</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerAppender.html#methodsetLayout">LoggerAppender::setLayout()</a> in LoggerAppender.php</div>
<div class="index-item-description">Set the Layout for this appender.</div>
</dd>
<dt class="field">
<span class="method-title">setLevel</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/Logger.html#methodsetLevel">Logger::setLevel()</a> in Logger.php</div>
<div class="index-item-description">Set the level of this Category.</div>
</dd>
<dt class="field">
<span class="method-title">setLevel</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerRoot.html#methodsetLevel">LoggerRoot::setLevel()</a> in LoggerRoot.php</div>
<div class="index-item-description">Setting a null value to the level of the root category may have catastrophic results.</div>
</dd>
<dt class="field">
<span class="method-title">setMaxDepth</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerNDC.html#methodsetMaxDepth">LoggerNDC::setMaxDepth()</a> in LoggerNDC.php</div>
<div class="index-item-description">Set maximum depth of this diagnostic context. If the current depth is smaller or equal to <var>maxDepth</var>, then no action is taken.</div>
</dd>
<dt class="field">
<span class="method-title">setName</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerAppender.html#methodsetName">LoggerAppender::setName()</a> in LoggerAppender.php</div>
<div class="index-item-description">Set the name of this appender.</div>
</dd>
<dt class="field">
<span class="method-title">setParent</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/Logger.html#methodsetParent">Logger::setParent()</a> in Logger.php</div>
<div class="index-item-description">Sets the parent logger of this logger</div>
</dd>
<dt class="field">
<span class="method-title">setParent</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerRoot.html#methodsetParent">LoggerRoot::setParent()</a> in LoggerRoot.php</div>
<div class="index-item-description">Always returns false.</div>
</dd>
<dt class="field">
<span class="method-title">setProperties</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerReflectionUtils.html#methodsetProperties">LoggerReflectionUtils::setProperties()</a> in LoggerReflectionUtils.php</div>
<div class="index-item-description">Set the properites for the object that match the <div class="src-code"><ol><li><div class="src-line"><span class="src-id">prefix</span></div></li>
</ol></div> passed as parameter.</div>
</dd>
<dt class="field">
<span class="method-title">setPropertiesByObject</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerReflectionUtils.html#methodsetPropertiesByObject">LoggerReflectionUtils::setPropertiesByObject()</a> in LoggerReflectionUtils.php</div>
<div class="index-item-description">Set the properties of an object passed as a parameter in one go. The <div class="src-code"><ol><li><div class="src-line"><span class="src-id">properties</span></div></li>
</ol></div> are parsed relative to a <div class="src-code"><ol><li><div class="src-line"><span class="src-id">prefix</span></div></li>
</ol></div>.</div>
</dd>
<dt class="field">
<span class="method-title">setProperty</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerReflectionUtils.html#methodsetProperty">LoggerReflectionUtils::setProperty()</a> in LoggerReflectionUtils.php</div>
<div class="index-item-description">Set a property on this PropertySetter's Object. If successful, this</div>
</dd>
<dt class="field">
<span class="method-title">setter</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerReflectionUtils.html#methodsetter">LoggerReflectionUtils::setter()</a> in LoggerReflectionUtils.php</div>
</dd>
<dt class="field">
<span class="method-title">setThreshold</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerHierarchy.html#methodsetThreshold">LoggerHierarchy::setThreshold()</a> in LoggerHierarchy.php</div>
<div class="index-item-description">set a new threshold level</div>
</dd>
<dt class="field">
<span class="method-title">setThreshold</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerAppender.html#methodsetThreshold">LoggerAppender::setThreshold()</a> in LoggerAppender.php</div>
<div class="index-item-description">Set the threshold level of this appender.</div>
</dd>
<dt class="field">
<span class="method-title">shutdown</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/Logger.html#methodshutdown">Logger::shutdown()</a> in Logger.php</div>
<div class="index-item-description">Safely close all appenders.</div>
</dd>
<dt class="field">
<span class="method-title">shutdown</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerHierarchy.html#methodshutdown">LoggerHierarchy::shutdown()</a> in LoggerHierarchy.php</div>
<div class="index-item-description">Shutting down a hierarchy will <em>safely</em> close and remove all appenders in all categories including the root logger.</div>
</dd>
<dt class="field">
<span class="var-title">$sql</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderAdodb.html#var$sql">LoggerAppenderAdodb::$sql</a> in LoggerAppenderAdodb.php</div>
<div class="index-item-description">A LoggerPatternLayout string used to format a valid insert query (mandatory).</div>
</dd>
<dt class="field">
<span class="method-title">setAppend</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderFile.html#methodsetAppend">LoggerAppenderFile::setAppend()</a> in LoggerAppenderFile.php</div>
</dd>
<dt class="field">
<span class="method-title">setCreateTable</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderPDO.html#methodsetCreateTable">LoggerAppenderPDO::setCreateTable()</a> in LoggerAppenderPDO.php</div>
<div class="index-item-description">Indicator if the logging table should be created on startup, if its not existing.</div>
</dd>
<dt class="field">
<span class="method-title">setCreateTable</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderAdodb.html#methodsetCreateTable">LoggerAppenderAdodb::setCreateTable()</a> in LoggerAppenderAdodb.php</div>
</dd>
<dt class="field">
<span class="method-title">setDatabase</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderAdodb.html#methodsetDatabase">LoggerAppenderAdodb::setDatabase()</a> in LoggerAppenderAdodb.php</div>
</dd>
<dt class="field">
<span class="method-title">setDatePattern</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderDailyFile.html#methodsetDatePattern">LoggerAppenderDailyFile::setDatePattern()</a> in LoggerAppenderDailyFile.php</div>
<div class="index-item-description">Sets date format for the file name.</div>
</dd>
<dt class="field">
<span class="method-title">setDry</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderMailEvent.html#methodsetDry">LoggerAppenderMailEvent::setDry()</a> in LoggerAppenderMailEvent.php</div>
</dd>
<dt class="field">
<span class="method-title">setDry</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderSyslog.html#methodsetDry">LoggerAppenderSyslog::setDry()</a> in LoggerAppenderSyslog.php</div>
</dd>
<dt class="field">
<span class="method-title">setDry</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderMail.html#methodsetDry">LoggerAppenderMail::setDry()</a> in LoggerAppenderMail.php</div>
</dd>
<dt class="field">
<span class="method-title">setDry</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderSocket.html#methodsetDry">LoggerAppenderSocket::setDry()</a> in LoggerAppenderSocket.php</div>
</dd>
<dt class="field">
<span class="method-title">setDSN</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderPDO.html#methodsetDSN">LoggerAppenderPDO::setDSN()</a> in LoggerAppenderPDO.php</div>
<div class="index-item-description">Sets the DSN string for this connection. In case of</div>
</dd>
<dt class="field">
<span class="method-title">setFacility</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderSyslog.html#methodsetFacility">LoggerAppenderSyslog::setFacility()</a> in LoggerAppenderSyslog.php</div>
<div class="index-item-description">Set the facility value for the syslog message.</div>
</dd>
<dt class="field">
<span class="method-title">setFile</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderDailyFile.html#methodsetFile">LoggerAppenderDailyFile::setFile()</a> in LoggerAppenderDailyFile.php</div>
<div class="index-item-description">The File property takes a string value which should be the name of the file to append to.</div>
</dd>
<dt class="field">
<span class="method-title">setFile</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderFile.html#methodsetFile">LoggerAppenderFile::setFile()</a> in LoggerAppenderFile.php</div>
<div class="index-item-description">Sets and opens the file where the log output will go.</div>
</dd>
<dt class="field">
<span class="method-title">setFileName</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderFile.html#methodsetFileName">LoggerAppenderFile::setFileName()</a> in LoggerAppenderFile.php</div>
</dd>
<dt class="field">
<span class="method-title">setFileName</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderRollingFile.html#methodsetFileName">LoggerAppenderRollingFile::setFileName()</a> in LoggerAppenderRollingFile.php</div>
</dd>
<dt class="field">
<span class="method-title">setFrom</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderMailEvent.html#methodsetFrom">LoggerAppenderMailEvent::setFrom()</a> in LoggerAppenderMailEvent.php</div>
</dd>
<dt class="field">
<span class="method-title">setFrom</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderMail.html#methodsetFrom">LoggerAppenderMail::setFrom()</a> in LoggerAppenderMail.php</div>
</dd>
<dt class="field">
<span class="method-title">setHost</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderAdodb.html#methodsetHost">LoggerAppenderAdodb::setHost()</a> in LoggerAppenderAdodb.php</div>
</dd>
<dt class="field">
<span class="method-title">setIdent</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderSyslog.html#methodsetIdent">LoggerAppenderSyslog::setIdent()</a> in LoggerAppenderSyslog.php</div>
<div class="index-item-description">Set the ident of the syslog message.</div>
</dd>
<dt class="field">
<span class="method-title">setInsertPattern</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderPDO.html#methodsetInsertPattern">LoggerAppenderPDO::setInsertPattern()</a> in LoggerAppenderPDO.php</div>
<div class="index-item-description">Sets the <a href="log4php/layouts/LoggerLayoutPattern.html">LoggerLayoutPattern</a> format strings for $insertSql.</div>
</dd>
<dt class="field">
<span class="method-title">setInsertSql</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderPDO.html#methodsetInsertSql">LoggerAppenderPDO::setInsertSql()</a> in LoggerAppenderPDO.php</div>
<div class="index-item-description">Sets the SQL INSERT string to use with $insertPattern.</div>
</dd>
<dt class="field">
<span class="method-title">setLocationInfo</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderSocket.html#methodsetLocationInfo">LoggerAppenderSocket::setLocationInfo()</a> in LoggerAppenderSocket.php</div>
</dd>
<dt class="field">
<span class="method-title">setLog4jNamespace</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderSocket.html#methodsetLog4jNamespace">LoggerAppenderSocket::setLog4jNamespace()</a> in LoggerAppenderSocket.php</div>
</dd>
<dt class="field">
<span class="method-title">setMaxBackupIndex</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderRollingFile.html#methodsetMaxBackupIndex">LoggerAppenderRollingFile::setMaxBackupIndex()</a> in LoggerAppenderRollingFile.php</div>
<div class="index-item-description">Set the maximum number of backup files to keep around.</div>
</dd>
<dt class="field">
<span class="method-title">setMaxFileSize</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderRollingFile.html#methodsetMaxFileSize">LoggerAppenderRollingFile::setMaxFileSize()</a> in LoggerAppenderRollingFile.php</div>
<div class="index-item-description">Set the maximum size that the output file is allowed to reach before being rolled over to backup files.</div>
</dd>
<dt class="field">
<span class="method-title">setMaximumFileSize</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderRollingFile.html#methodsetMaximumFileSize">LoggerAppenderRollingFile::setMaximumFileSize()</a> in LoggerAppenderRollingFile.php</div>
<div class="index-item-description">Set the maximum size that the output file is allowed to reach before being rolled over to backup files.</div>
</dd>
<dt class="field">
<span class="method-title">setOption</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderSyslog.html#methodsetOption">LoggerAppenderSyslog::setOption()</a> in LoggerAppenderSyslog.php</div>
<div class="index-item-description">Set the option value for the syslog message.</div>
</dd>
<dt class="field">
<span class="method-title">setOverridePriority</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderSyslog.html#methodsetOverridePriority">LoggerAppenderSyslog::setOverridePriority()</a> in LoggerAppenderSyslog.php</div>
<div class="index-item-description">If the priority of the message to be sent can be defined by a value in the properties-file, set parameter value to "true".</div>
</dd>
<dt class="field">
<span class="method-title">setPassword</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderAdodb.html#methodsetPassword">LoggerAppenderAdodb::setPassword()</a> in LoggerAppenderAdodb.php</div>
</dd>
<dt class="field">
<span class="method-title">setPassword</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderPDO.html#methodsetPassword">LoggerAppenderPDO::setPassword()</a> in LoggerAppenderPDO.php</div>
<div class="index-item-description">Sets the password for this connection.</div>
</dd>
<dt class="field">
<span class="method-title">setPort</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderSocket.html#methodsetPort">LoggerAppenderSocket::setPort()</a> in LoggerAppenderSocket.php</div>
</dd>
<dt class="field">
<span class="method-title">setPort</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderMailEvent.html#methodsetPort">LoggerAppenderMailEvent::setPort()</a> in LoggerAppenderMailEvent.php</div>
</dd>
<dt class="field">
<span class="method-title">setPriority</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderSyslog.html#methodsetPriority">LoggerAppenderSyslog::setPriority()</a> in LoggerAppenderSyslog.php</div>
<div class="index-item-description">Set the priority value for the syslog message.</div>
</dd>
<dt class="field">
<span class="method-title">setRemoteHost</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderSocket.html#methodsetRemoteHost">LoggerAppenderSocket::setRemoteHost()</a> in LoggerAppenderSocket.php</div>
</dd>
<dt class="field">
<span class="method-title">setSmtpHost</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderMailEvent.html#methodsetSmtpHost">LoggerAppenderMailEvent::setSmtpHost()</a> in LoggerAppenderMailEvent.php</div>
</dd>
<dt class="field">
<span class="method-title">setSql</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderAdodb.html#methodsetSql">LoggerAppenderAdodb::setSql()</a> in LoggerAppenderAdodb.php</div>
</dd>
<dt class="field">
<span class="method-title">setSql</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderPDO.html#methodsetSql">LoggerAppenderPDO::setSql()</a> in LoggerAppenderPDO.php</div>
<div class="index-item-description">Sets the SQL string into which the event should be transformed.</div>
</dd>
<dt class="field">
<span class="method-title">setSubject</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderMailEvent.html#methodsetSubject">LoggerAppenderMailEvent::setSubject()</a> in LoggerAppenderMailEvent.php</div>
</dd>
<dt class="field">
<span class="method-title">setSubject</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderMail.html#methodsetSubject">LoggerAppenderMail::setSubject()</a> in LoggerAppenderMail.php</div>
</dd>
<dt class="field">
<span class="method-title">setTable</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderPDO.html#methodsetTable">LoggerAppenderPDO::setTable()</a> in LoggerAppenderPDO.php</div>
<div class="index-item-description">Sets the tablename to which this appender should log.</div>
</dd>
<dt class="field">
<span class="method-title">setTable</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderAdodb.html#methodsetTable">LoggerAppenderAdodb::setTable()</a> in LoggerAppenderAdodb.php</div>
</dd>
<dt class="field">
<span class="method-title">setTarget</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderConsole.html#methodsetTarget">LoggerAppenderConsole::setTarget()</a> in LoggerAppenderConsole.php</div>
<div class="index-item-description">Set console target.</div>
</dd>
<dt class="field">
<span class="method-title">setTimeout</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderSocket.html#methodsetTimeout">LoggerAppenderSocket::setTimeout()</a> in LoggerAppenderSocket.php</div>
</dd>
<dt class="field">
<span class="method-title">setTo</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderMailEvent.html#methodsetTo">LoggerAppenderMailEvent::setTo()</a> in LoggerAppenderMailEvent.php</div>
</dd>
<dt class="field">
<span class="method-title">setTo</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderMail.html#methodsetTo">LoggerAppenderMail::setTo()</a> in LoggerAppenderMail.php</div>
</dd>
<dt class="field">
<span class="method-title">setType</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderAdodb.html#methodsetType">LoggerAppenderAdodb::setType()</a> in LoggerAppenderAdodb.php</div>
</dd>
<dt class="field">
<span class="method-title">setUser</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderPDO.html#methodsetUser">LoggerAppenderPDO::setUser()</a> in LoggerAppenderPDO.php</div>
<div class="index-item-description">Sets the username for this connection.</div>
</dd>
<dt class="field">
<span class="method-title">setUser</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderAdodb.html#methodsetUser">LoggerAppenderAdodb::setUser()</a> in LoggerAppenderAdodb.php</div>
</dd>
<dt class="field">
<span class="method-title">setUseXml</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderSocket.html#methodsetUseXml">LoggerAppenderSocket::setUseXml()</a> in LoggerAppenderSocket.php</div>
</dd>
<dt class="field">
STDERR
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderConsole.html#constSTDERR">LoggerAppenderConsole::STDERR</a> in LoggerAppenderConsole.php</div>
</dd>
<dt class="field">
STDOUT
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderConsole.html#constSTDOUT">LoggerAppenderConsole::STDOUT</a> in LoggerAppenderConsole.php</div>
</dd>
<dt class="field">
<span class="method-title">setAcceptOnMatch</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/filters/LoggerFilterLevelRange.html#methodsetAcceptOnMatch">LoggerFilterLevelRange::setAcceptOnMatch()</a> in LoggerFilterLevelRange.php</div>
</dd>
<dt class="field">
<span class="method-title">setAcceptOnMatch</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/filters/LoggerFilterStringMatch.html#methodsetAcceptOnMatch">LoggerFilterStringMatch::setAcceptOnMatch()</a> in LoggerFilterStringMatch.php</div>
</dd>
<dt class="field">
<span class="method-title">setAcceptOnMatch</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/filters/LoggerFilterLevelMatch.html#methodsetAcceptOnMatch">LoggerFilterLevelMatch::setAcceptOnMatch()</a> in LoggerFilterLevelMatch.php</div>
</dd>
<dt class="field">
<span class="method-title">setLevelMax</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/filters/LoggerFilterLevelRange.html#methodsetLevelMax">LoggerFilterLevelRange::setLevelMax()</a> in LoggerFilterLevelRange.php</div>
</dd>
<dt class="field">
<span class="method-title">setLevelMin</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/filters/LoggerFilterLevelRange.html#methodsetLevelMin">LoggerFilterLevelRange::setLevelMin()</a> in LoggerFilterLevelRange.php</div>
</dd>
<dt class="field">
<span class="method-title">setLevelToMatch</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/filters/LoggerFilterLevelMatch.html#methodsetLevelToMatch">LoggerFilterLevelMatch::setLevelToMatch()</a> in LoggerFilterLevelMatch.php</div>
</dd>
<dt class="field">
<span class="method-title">setStringToMatch</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/filters/LoggerFilterStringMatch.html#methodsetStringToMatch">LoggerFilterStringMatch::setStringToMatch()</a> in LoggerFilterStringMatch.php</div>
</dd>
<dt class="field">
<span class="method-title">spacePad</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerPatternConverter.html#methodspacePad">LoggerPatternConverter::spacePad()</a> in LoggerPatternConverter.php</div>
<div class="index-item-description">Fast space padding method.</div>
</dd>
<dt class="field">
<span class="method-title">substVars</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerOptionConverter.html#methodsubstVars">LoggerOptionConverter::substVars()</a> in LoggerOptionConverter.php</div>
<div class="index-item-description">Perform variable substitution in string <var>$val</var> from the values of keys found with the getSystemProperty() method.</div>
</dd>
<dt class="field">
<span class="method-title">setCategoryPrefixing</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutTTCC.html#methodsetCategoryPrefixing">LoggerLayoutTTCC::setCategoryPrefixing()</a> in LoggerLayoutTTCC.php</div>
<div class="index-item-description">The <strong>CategoryPrefixing</strong> option specifies whether Category name is part of log output or not. This is true by default.</div>
</dd>
<dt class="field">
<span class="method-title">setContextPrinting</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutTTCC.html#methodsetContextPrinting">LoggerLayoutTTCC::setContextPrinting()</a> in LoggerLayoutTTCC.php</div>
<div class="index-item-description">The <strong>ContextPrinting</strong> option specifies log output will include the nested context information belonging to the current thread.</div>
</dd>
<dt class="field">
<span class="method-title">setConversionPattern</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutPattern.html#methodsetConversionPattern">LoggerLayoutPattern::setConversionPattern()</a> in LoggerLayoutPattern.php</div>
<div class="index-item-description">Set the <strong>ConversionPattern</strong> option. This is the string which controls formatting and consists of a mix of literal content and conversion specifiers.</div>
</dd>
<dt class="field">
<span class="method-title">setDateFormat</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutTTCC.html#methodsetDateFormat">LoggerLayoutTTCC::setDateFormat()</a> in LoggerLayoutTTCC.php</div>
</dd>
<dt class="field">
<span class="method-title">setLocationInfo</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutXml.html#methodsetLocationInfo">LoggerLayoutXml::setLocationInfo()</a> in LoggerLayoutXml.php</div>
<div class="index-item-description">The $locationInfo option takes a boolean value. By default,</div>
</dd>
<dt class="field">
<span class="method-title">setLocationInfo</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutHtml.html#methodsetLocationInfo">LoggerLayoutHtml::setLocationInfo()</a> in LoggerLayoutHtml.php</div>
<div class="index-item-description">The <strong>LocationInfo</strong> option takes a boolean value. By</div>
</dd>
<dt class="field">
<span class="method-title">setLog4jNamespace</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutXml.html#methodsetLog4jNamespace">LoggerLayoutXml::setLog4jNamespace()</a> in LoggerLayoutXml.php</div>
</dd>
<dt class="field">
<span class="method-title">setMicroSecondsPrinting</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutTTCC.html#methodsetMicroSecondsPrinting">LoggerLayoutTTCC::setMicroSecondsPrinting()</a> in LoggerLayoutTTCC.php</div>
<div class="index-item-description">The <strong>MicroSecondsPrinting</strong> option specifies if microseconds infos should be printed at the end of timestamp.</div>
</dd>
<dt class="field">
<span class="method-title">setThreadPrinting</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutTTCC.html#methodsetThreadPrinting">LoggerLayoutTTCC::setThreadPrinting()</a> in LoggerLayoutTTCC.php</div>
<div class="index-item-description">The <strong>ThreadPrinting</strong> option specifies whether the name of the current thread is part of log output or not. This is true by default.</div>
</dd>
<dt class="field">
<span class="method-title">setTitle</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutHtml.html#methodsetTitle">LoggerLayoutHtml::setTitle()</a> in LoggerLayoutHtml.php</div>
<div class="index-item-description">The <strong>Title</strong> option takes a String value. This option sets the document title of the generated HTML document.</div>
</dd>
</dl>
<a name="t"></a>
<div class="index-letter-section">
<div style="float: left" class="index-letter-title">t</div>
<div style="float: right"><a href="#top">top</a></div>
<div style="clear: both"></div>
</div>
<dl>
<dt class="field">
<span class="var-title">$threshold</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerAppender.html#var$threshold">LoggerAppender::$threshold</a> in LoggerAppender.php</div>
</dd>
<dt class="field">
<span class="var-title">$threshold</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerHierarchy.html#var$threshold">LoggerHierarchy::$threshold</a> in LoggerHierarchy.php</div>
<div class="index-item-description">LoggerLevel main level threshold</div>
</dd>
<dt class="field">
<span class="var-title">$timeStamp</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLoggingEvent.html#var$timeStamp">LoggerLoggingEvent::$timeStamp</a> in LoggerLoggingEvent.php</div>
<div class="index-item-description">The number of seconds elapsed from 1/1/1970 until logging event was created plus microseconds if available.</div>
</dd>
<dt class="field">
<span class="method-title">toInt</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLevel.html#methodtoInt">LoggerLevel::toInt()</a> in LoggerLevel.php</div>
<div class="index-item-description">Returns the integer representation of this level.</div>
</dd>
<dt class="field">
<span class="method-title">toLevel</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLevel.html#methodtoLevel">LoggerLevel::toLevel()</a> in LoggerLevel.php</div>
<div class="index-item-description">Convert the string passed as argument to a level. If the conversion fails, then this method returns a DEBUG Level.</div>
</dd>
<dt class="field">
<span class="method-title">toString</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLoggingEvent.html#methodtoString">LoggerLoggingEvent::toString()</a> in LoggerLoggingEvent.php</div>
<div class="index-item-description">Serialize this object</div>
</dd>
<dt class="field">
<span class="method-title">toString</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLevel.html#methodtoString">LoggerLevel::toString()</a> in LoggerLevel.php</div>
<div class="index-item-description">Returns the string representation of this priority.</div>
</dd>
<dt class="field">
<span class="var-title">$table</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderAdodb.html#var$table">LoggerAppenderAdodb::$table</a> in LoggerAppenderAdodb.php</div>
<div class="index-item-description">Table name to write events. Used only if $createTable is true.</div>
</dd>
<dt class="field">
<span class="var-title">$type</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderAdodb.html#var$type">LoggerAppenderAdodb::$type</a> in LoggerAppenderAdodb.php</div>
<div class="index-item-description">The type of database to connect to</div>
</dd>
<dt class="field">
THRESHOLD_PREFIX
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/configurators/LoggerConfiguratorIni.html#constTHRESHOLD_PREFIX">LoggerConfiguratorIni::THRESHOLD_PREFIX</a> in LoggerConfiguratorIni.php</div>
</dd>
<dt class="field">
THREAD_CONVERTER
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerPatternParser.html#constTHREAD_CONVERTER">LoggerPatternParser::THREAD_CONVERTER</a> in LoggerPatternParser.php</div>
</dd>
<dt class="field">
<span class="method-title">toBoolean</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerOptionConverter.html#methodtoBoolean">LoggerOptionConverter::toBoolean()</a> in LoggerOptionConverter.php</div>
<div class="index-item-description">If <var>$value</var> is <em>true</em>, then <em>true</em> is returned. If <var>$value</var> is <em>false</em>, then <em>true</em> is returned. Otherwise, <var>$default</var> is returned.</div>
</dd>
<dt class="field">
<span class="method-title">toFileSize</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerOptionConverter.html#methodtoFileSize">LoggerOptionConverter::toFileSize()</a> in LoggerOptionConverter.php</div>
</dd>
<dt class="field">
<span class="method-title">toInt</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerOptionConverter.html#methodtoInt">LoggerOptionConverter::toInt()</a> in LoggerOptionConverter.php</div>
</dd>
<dt class="field">
<span class="method-title">toLevel</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/helpers/LoggerOptionConverter.html#methodtoLevel">LoggerOptionConverter::toLevel()</a> in LoggerOptionConverter.php</div>
<div class="index-item-description">Converts a standard or custom priority level to a Level object.</div>
</dd>
<dt class="field">
<span class="var-title">$threadPrinting</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutTTCC.html#var$threadPrinting">LoggerLayoutTTCC::$threadPrinting</a> in LoggerLayoutTTCC.php</div>
</dd>
<dt class="field">
TTCC_CONVERSION_PATTERN
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/layouts/LoggerLayoutPattern.html#constTTCC_CONVERSION_PATTERN">LoggerLayoutPattern::TTCC_CONVERSION_PATTERN</a> in LoggerLayoutPattern.php</div>
<div class="index-item-description">Default conversion TTCC Pattern</div>
</dd>
</dl>
<a name="u"></a>
<div class="index-letter-section">
<div style="float: left" class="index-letter-title">u</div>
<div style="float: right"><a href="#top">top</a></div>
<div style="clear: both"></div>
</div>
<dl>
<dt class="field">
<span class="var-title">$user</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/appenders/LoggerAppenderAdodb.html#var$user">LoggerAppenderAdodb::$user</a> in LoggerAppenderAdodb.php</div>
<div class="index-item-description">Database user name</div>
</dd>
</dl>
<a name="w"></a>
<div class="index-letter-section">
<div style="float: left" class="index-letter-title">w</div>
<div style="float: right"><a href="#top">top</a></div>
<div style="clear: both"></div>
</div>
<dl>
<dt class="field">
WARN
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/LoggerLevel.html#constWARN">LoggerLevel::WARN</a> in LoggerLevel.php</div>
</dd>
<dt class="field">
<span class="method-title">warn</span>
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/Logger.html#methodwarn">Logger::warn()</a> in Logger.php</div>
<div class="index-item-description">Log a message with the WARN level.</div>
</dd>
</dl>
<a name="x"></a>
<div class="index-letter-section">
<div style="float: left" class="index-letter-title">x</div>
<div style="float: right"><a href="#top">top</a></div>
<div style="clear: both"></div>
</div>
<dl>
<dt class="field">
XMLNS
</dt>
<dd class="index-item-body">
<div class="index-item-details"><a href="log4php/configurators/LoggerConfiguratorXml.html#constXMLNS">LoggerConfiguratorXml::XMLNS</a> in LoggerConfiguratorXml.php</div>
</dd>
</dl>
<div class="index-letter-menu">
<a class="index-letter" href="elementindex_log4php.html#a">a</a>
<a class="index-letter" href="elementindex_log4php.html#c">c</a>
<a class="index-letter" href="elementindex_log4php.html#d">d</a>
<a class="index-letter" href="elementindex_log4php.html#e">e</a>
<a class="index-letter" href="elementindex_log4php.html#f">f</a>
<a class="index-letter" href="elementindex_log4php.html#g">g</a>
<a class="index-letter" href="elementindex_log4php.html#h">h</a>
<a class="index-letter" href="elementindex_log4php.html#i">i</a>
<a class="index-letter" href="elementindex_log4php.html#l">l</a>
<a class="index-letter" href="elementindex_log4php.html#m">m</a>
<a class="index-letter" href="elementindex_log4php.html#n">n</a>
<a class="index-letter" href="elementindex_log4php.html#o">o</a>
<a class="index-letter" href="elementindex_log4php.html#p">p</a>
<a class="index-letter" href="elementindex_log4php.html#r">r</a>
<a class="index-letter" href="elementindex_log4php.html#s">s</a>
<a class="index-letter" href="elementindex_log4php.html#t">t</a>
<a class="index-letter" href="elementindex_log4php.html#u">u</a>
<a class="index-letter" href="elementindex_log4php.html#w">w</a>
<a class="index-letter" href="elementindex_log4php.html#x">x</a>
<a class="index-letter" href="elementindex_log4php.html#_">_</a>
</div> </body>
</html> | Java |
/**
* Copyright 2015 IBM Corp.
*
* 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.ibmcloud.contest.phonebook;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
/**
* Throw a 400 status code
*/
public class BadRequestException extends WebApplicationException {
private static final long serialVersionUID = 1L;
public BadRequestException() {
super(Response.status(Status.BAD_REQUEST).build());
}
}
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_111) on Thu Aug 18 01:51:14 UTC 2016 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>org.apache.hadoop.registry.client.impl (Apache Hadoop Main 2.7.3 API)</title>
<meta name="date" content="2016-08-18">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
</head>
<body>
<h1 class="bar"><a href="../../../../../../org/apache/hadoop/registry/client/impl/package-summary.html" target="classFrame">org.apache.hadoop.registry.client.impl</a></h1>
<div class="indexContainer">
<h2 title="Classes">Classes</h2>
<ul title="Classes">
<li><a href="RegistryOperationsClient.html" title="class in org.apache.hadoop.registry.client.impl" target="classFrame">RegistryOperationsClient</a></li>
</ul>
</div>
</body>
</html>
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" >
<title>Silicon Valley 2013
- Proposal</title>
<meta name="author" content="Andrew Hay" >
<link rel="alternate" type="application/rss+xml" title="devopsdays RSS Feed" href="http://www.devopsdays.org/feed/" >
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('jquery', '1.3.2');
</script>
<!---This is a combined jAmpersand, jqwindont , jPullquote -->
<script type="text/javascript" src="/js/devops.js"></script>
<!--- Blueprint CSS Framework Screen + Fancytype-Screen + jedi.css -->
<link rel="stylesheet" href="/css/devops.min.css" type="text/css" media="screen, projection">
<link rel="stylesheet" href="/css/blueprint/print.css" type="text/css" media="print">
<!--[if IE]>
<link rel="stylesheet" href="/css/blueprint/ie.css" type="text/css" media="screen, projection">
<![endif]-->
</head>
<body onload="initialize()">
<div class="container ">
<div class="span-24 last" id="header">
<div class="span-16 first">
<img src="/images/devopsdays-banner.png" title="devopsdays banner" width="801" height="115" alt="devopdays banner" ><br>
</div>
<div class="span-8 last">
</div>
</div>
<div class="span-24 last">
<div class="span-15 first">
<div id="headermenu">
<table >
<tr>
<td>
<a href="/"><img alt="home" title="home" src="/images/home.png"></a>
<a href="/">Home</a>
</td>
<td>
<a href="/contact/"><img alt="contact" title="contact" src="/images/contact.png"></a>
<a href="/contact/">Contact</a>
</td>
<td>
<a href="/events/"><img alt="events" title="events" src="/images/events.png"></a>
<a href="/events/">Events</a>
</td>
<td>
<a href="/presentations/"><img alt="presentations" title="presentations" src="/images/presentations.png"></a>
<a href="/presentations/">Presentations</a>
</td>
<td>
<a href="/blog/"><img alt="blog" title="blog" src="/images/blog.png"></a>
<a href="/blog/">Blog</a>
</td>
</tr>
</table>
</div>
</div>
<div class="span-8 last">
</div>
<div class="span-24 last" id="title">
<div class="span-15 first">
<h1>Silicon Valley 2013
- Proposal </h1>
</div>
<div class="span-8 last">
</div>
<h1>Gold sponsors</h1>
</div>
<div class="span-15 ">
<div class="span-15 last ">
<div class="submenu">
<h3>
<a href="/events/2013-mountainview/">welcome</a>
<a href="/events/2013-mountainview/propose">propose</a>
<a href="/events/2013-mountainview/program">program</a>
<a href="/events/2013-mountainview/location">location</a>
<a href="/events/2013-mountainview/registration">register</a>
<a href="/events/2013-mountainview/sponsor">sponsor</a>
<a href="/events/2013-mountainview/contact">contact</a>
</h3>
</div>
Back to <a href='..'>proposals overview</a> - <a href='../../program'>program</a>
<hr>
<h3>DevOps for Security: Automation is your only hope to protect Cloud IaaS</h3>
<p><strong>Abstract:</strong></p>
<p>Enterprises today are adopting the cloud in all shapes and sizes:
public, private, hybrid, even (cloud)washed. For some security teams
this is a nightmare, but that won’t stop the business from moving
ahead because on-demand computing simply helps improve business
agility too much.</p>
<p>There is hope though. Whether you are building applications in public
CSPs (Amazon EC2/VPC, Rackspace Cloud, etc), private
infrastructure-as-a-service (OpenStack, CloudStack, VMware even) the
security controls you care about are the same, but they way they need
to be deployed and run is very very different.</p>
<p>DevOps teams have fallen in love with automation tools like Chef,
Puppet, and others, but how can security teams leverage automation to
improve their life? How do we let the business realize the promise of
fully automated self-service provisioning of resources by end users,
while keeping our necessary controls in place and ensuring continuous
compliance?</p>
<p>In this session, Rand Wacker (VP of Product for CloudPassage) will
share experience learned from some of the largest and most advanced
organizations in the world as they have pioneered the cloud security
automation trail.</p>
<p>Please join us to learn and discuss:
· Why the DevOps, Marketing, and BU teams love cloud, and where adoption is going
· How security must re-think their approach to enable the business to get the most out of IaaS, in both public and private environments
· Who is responsible for cloud security, both in your org as well as with your providers
· What it takes to maintain security visibility and compliance in a self-service world
· When you can expect your org to be using cloud resources that aren’t adequately secured (spoiler alert: its probably already happening)</p>
<p><strong>Speaker:</strong></p>
<p>Andrew Hay Director of Applied Security Research CloudPassage Inc.</p>
</div>
<div class="span-15 first last">
<script type="text/javascript">
// var disqus_developer = 1;
</script>
<div id="disqus_thread"></div>
<script type="text/javascript">
var disqus_shortname = 'devopsdays';
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
<a href="http://disqus.com" class="dsq-brlink">blog comments powered by <span class="logo-disqus">Disqus</span></a>
<hr>
</div>
</div>
<div class="span-8 last">
<div class="span-8 last">
<a href='http://www.urbancode.com/'><img border=0 alt='Urbancode' title='Urbancode' width=100px height=100px src='/events/2013-mountainview/logos/urbancode.png'></a>
<a href='http://www.zeroturnaround.com/'><img border=0 alt='Zeroturnaround' title='Zeroturnaround' width=100px height=100px src='/events/2013-mountainview/logos/zeroturnaround.png'></a>
<a href='http://opscode.com/'><img border=0 alt='Opscode' title='Opscode' width=100px height=100px src='/events/2013-mountainview/logos/opscode.png'></a>
<a href='http://www.bmc.com/'><img border=0 alt='BMC' title='BMC' width=100px height=100px src='/events/2013-mountainview/logos/bmc.png'></a>
<a href='http://www8.hp.com/us/en/software-solutions/software.html?compURI=1234839&jumpid=reg_r1002_usen_c-001_title_r0001'><img border=0 alt='HP' title='HP' width=100px height=100px src='/events/2013-mountainview/logos/hp.png'></a>
<a href='http://www.puppetlabs.com/'><img border=0 alt='Puppetlabs' title='Puppetlabs' width=100px height=100px src='/events/2013-mountainview/logos/puppetlabs.png'></a>
<a href='http://www.collabnet.com/'><img border=0 alt='Collabnet' title='Collabnet' width=100px height=100px src='/events/2013-mountainview/logos/collabnet.png'></a>
<a href='http://www.datadoghq.com/'><img border=0 alt='Datadog HQ' title='Datadog HQ' width=100px height=100px src='/events/2013-mountainview/logos/datadog.png'></a>
<a href='http://www.uc4.com/ara'><img border=0 alt='UC4' title='UC4' width=100px height=100px src='/events/2013-mountainview/logos/uc4.png'></a>
<h1>Special sponsors</h1>
<a href='http://www.pagerduty.com/'><img border=0 alt='Pagerduty' title='Pagerduty' width=100px height=100px src='/events/2013-mountainview/logos/pagerduty.png'></a>
<a href='http://www.citrix.com/'><img border=0 alt='Citrix' title='Citrix' width=100px height=100px src='/events/2013-mountainview/logos/citrix.png'></a>
<a href='http://www.itsmacademy.com/'><img border=0 alt='Itsmacademy' title='Itsmacademy' width=100px height=100px src='/events/2013-mountainview/logos/itsmacademy.png'></a>
<h1>Gold sponsors</h1>
<a href='http://www.boundary.com/'><img border=0 alt='Boundary' title='Boundary' width=100px height=100px src='/events/2013-mountainview/logos/boundary.png'></a>
<a href='http://www.librato.com/'><img border=0 alt='Librato' title='Librato' width=100px height=100px src='/events/2013-mountainview/logos/librato.png'></a>
<a href='http://www.sumologic.com/'><img border=0 alt='Sumologic' title='Sumologic' width=100px height=100px src='/events/2013-mountainview/logos/sumologic.png'></a>
<a href='http://www.stackdriver.com/'><img border=0 alt='Stackdriver' title='Stackdriver' width=100px height=100px src='/events/2013-mountainview/logos/stackdriver.png'></a>
<a href='http://www.stormpath.com/'><img border=0 alt='Stormpath' title='Stormpath' width=100px height=100px src='/events/2013-mountainview/logos/stormpath.png'></a>
<a href='http://www.activestate.com/'><img border=0 alt='Activestate' title='Activestate' width=100px height=100px src='/events/2013-mountainview/logos/activestate.png'></a>
<a href='http://www.cloudmunch.com/'><img border=0 alt='CloudMunch' title='CloudMunch' width=100px height=100px src='/events/2013-mountainview/logos/cloudmunch.png'></a>
<a href='http://ca.com/lisa'><img border=0 alt='Ca Technologies' title='Ca Technologies' width=100px height=100px src='/events/2013-mountainview/logos/ca.png'></a>
<a href='http://www.riverbed.com/'><img border=0 alt='Riverbed' title='Riverbed' width=100px height=100px src='/events/2013-mountainview/logos/riverbed.png'></a>
<a href='http://www.logicmonitor.com/'><img border=0 alt='Logicmonitor' title='Logicmonitor' width=100px height=100px src='/events/2013-mountainview/logos/logicmonitor.png'></a>
<a href='http://www.saltstack.com/'><img border=0 alt='Saltstack' title='Saltstack' width=100px height=100px src='/events/2013-mountainview/logos/saltstack.png'></a>
<a href='http://www.vmware.com/'><img border=0 alt='Vmware' title='Vmware' width=100px height=100px src='/events/2013-mountainview/logos/vmware.png'></a>
<a href='http://cumulusnetworks.com/'><img border=0 alt='Cumulus Networks' title='Cumulus Networks' width=100px height=100px src='/events/2013-mountainview/logos/cumulusnetworks.png'></a>
<h1>Silver sponsors</h1>
<a href='http://www.serena.com/'><img border=0 alt='Serena Software' title='Serena Software' width=100px height=100px src='/events/2013-mountainview/logos/serena.png'></a>
<a href='http://www.salesforce.com/'><img border=0 alt='Salesforce' title='Salesforce' width=100px height=100px src='/events/2013-mountainview/logos/salesforce.png'></a>
<a href='http://www.ansibleworks.com/'><img border=0 alt='AnsibleWorks' title='AnsibleWorks' width=100px height=100px src='/events/2013-mountainview/logos/ansibleworks.png'></a>
<a href='http://www.dyn.com/'><img border=0 alt='Dyn' title='Dyn' width=100px height=100px src='/events/2013-mountainview/logos/dyn.png'></a>
<a href='http://www.newrelic.com/'><img border=0 alt='New Relic' title='New Relic' width=100px height=100px src='/events/2013-mountainview/logos/newrelic.png'></a>
<a href='http://www.electric-cloud.com/'><img border=0 alt='Electric-Cloud' title='Electric-Cloud' width=100px height=100px src='/events/2013-mountainview/logos/electriccloud.png'></a>
<a href='http://www.enstratius.com/'><img border=0 alt='Enstratius' title='Enstratius' width=100px height=100px src='/events/2013-mountainview/logos/enstratius.png'></a>
<a href='http://www.xebialabs.com/'><img border=0 alt='Xebialabs' title='Xebialabs' width=100px height=100px src='/events/2013-mountainview/logos/xebialabs.png'></a>
<a href='http://www.10gen.com/'><img border=0 alt='10gen' title='10gen' width=100px height=100px src='/events/2013-mountainview/logos/10gen.png'></a>
<a href='http://www.mozilla.com/'><img border=0 alt='Mozilla' title='Mozilla' width=100px height=100px src='/events/2013-mountainview/logos/mozilla.png'></a>
<h1>Media sponsors</h1>
<a href='http://www.oreilly.com/'><img border=0 alt='Oreilly' title='Oreilly' width=100px height=100px src='/events/2013-mountainview/logos/oreilly.png'></a>
<a href='http://www.usenix.org/conference/fcw13'><img border=0 alt='Usenix' title='Usenix' width=100px height=100px src='/events/2013-mountainview/logos/usenix.png'></a>
<a href='http://lopsa.org'><img border=0 alt='Lopsa' title='Lopsa' width=100px height=100px src='/events/2013-mountainview/logos/lopsa.png'></a>
</div>
<div class="span-8 last">
</div>
</div>
</div>
</div>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-9713393-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</body>
</html>
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<!--
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.
$Id: package.html 1187701 2011-10-22 12:21:54Z bommel $
-->
</head>
<body bgcolor="white">
A collection of classes to support EL integration.
</body>
</html> | Java |
//
// Account.h
// CardFlightLibrary
//
// Created by Tim Saunders on 9/20/13.
// Copyright (c) 2013 Filip Andrei. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface CFTAccount : NSObject
@property (nonatomic, strong) NSString *apiToken;
@property (nonatomic, strong) NSString *accountToken;
/**
* Create the account object with the api token and account token
* @param apiToken The API Token associated with this developer account
* @param accountToken The Merchant Account Token associated with this developer account
*/
-(id) initWithApiToken:(NSString *)apiToken andAccountToken:(NSString *)accountToken;
@end
| Java |
<?php
namespace ctala\transaccion\classes;
/**
* Description of Helper
*
* @author ctala
*/
class Helper {
/**
* Esta función permite la redirección para los pagos.
*
* @param type $url
* @param type $variables
*/
public static function redirect($url, $variables) {
foreach ($variables as $key => $value) {
$args_array[] = '<input type="hidden" name="' . $key . '" value="' . $value . '" />';
}
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body style="background-image:url('https://webpay3g.transbank.cl/webpayserver/imagenes/background.gif')">
<form name="WS1" id="WS1" action="<?= $url ?>" method="POST" onl>
<?php
foreach ($args_array as $arg) {
echo $arg;
}
?>
<input type="submit" id="submit_webpayplus_payment_form" style="visibility: hidden;">
</form>
<script>
$(document).ready(function () {
$("#WS1").submit();
});
</script>
</body>
</html>
<?php
}
}
| Java |
package org.zstack.sdk.zwatch.monitorgroup.api;
import org.zstack.sdk.zwatch.monitorgroup.entity.MonitorTemplateInventory;
public class CreateMonitorTemplateResult {
public MonitorTemplateInventory inventory;
public void setInventory(MonitorTemplateInventory inventory) {
this.inventory = inventory;
}
public MonitorTemplateInventory getInventory() {
return this.inventory;
}
}
| Java |
/*-
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Modifications:
* -Changed package name
* -Removed Android dependencies
* -Removed/replaced Java SE dependencies
* -Removed/replaced annotations
*/
package com.google.authenticator.blackberry;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.ByteArrayOutputStream;
import java.util.Vector;
/**
* Immutable URI reference. A URI reference includes a URI and a fragment, the
* component of the URI following a '#'. Builds and parses URI references
* which conform to
* <a href="http://www.faqs.org/rfcs/rfc2396.html">RFC 2396</a>.
*
* <p>In the interest of performance, this class performs little to no
* validation. Behavior is undefined for invalid input. This class is very
* forgiving--in the face of invalid input, it will return garbage
* rather than throw an exception unless otherwise specified.
*/
public abstract class Uri {
/*
This class aims to do as little up front work as possible. To accomplish
that, we vary the implementation dependending on what the user passes in.
For example, we have one implementation if the user passes in a
URI string (StringUri) and another if the user passes in the
individual components (OpaqueUri).
*Concurrency notes*: Like any truly immutable object, this class is safe
for concurrent use. This class uses a caching pattern in some places where
it doesn't use volatile or synchronized. This is safe to do with ints
because getting or setting an int is atomic. It's safe to do with a String
because the internal fields are final and the memory model guarantees other
threads won't see a partially initialized instance. We are not guaranteed
that some threads will immediately see changes from other threads on
certain platforms, but we don't mind if those threads reconstruct the
cached result. As a result, we get thread safe caching with no concurrency
overhead, which means the most common case, access from a single thread,
is as fast as possible.
From the Java Language spec.:
"17.5 Final Field Semantics
... when the object is seen by another thread, that thread will always
see the correctly constructed version of that object's final fields.
It will also see versions of any object or array referenced by
those final fields that are at least as up-to-date as the final fields
are."
In that same vein, all non-transient fields within Uri
implementations should be final and immutable so as to ensure true
immutability for clients even when they don't use proper concurrency
control.
For reference, from RFC 2396:
"4.3. Parsing a URI Reference
A URI reference is typically parsed according to the four main
components and fragment identifier in order to determine what
components are present and whether the reference is relative or
absolute. The individual components are then parsed for their
subparts and, if not opaque, to verify their validity.
Although the BNF defines what is allowed in each component, it is
ambiguous in terms of differentiating between an authority component
and a path component that begins with two slash characters. The
greedy algorithm is used for disambiguation: the left-most matching
rule soaks up as much of the URI reference string as it is capable of
matching. In other words, the authority component wins."
The "four main components" of a hierarchical URI consist of
<scheme>://<authority><path>?<query>
*/
/**
* NOTE: EMPTY accesses this field during its own initialization, so this
* field *must* be initialized first, or else EMPTY will see a null value!
*
* Placeholder for strings which haven't been cached. This enables us
* to cache null. We intentionally create a new String instance so we can
* compare its identity and there is no chance we will confuse it with
* user data.
*/
private static final String NOT_CACHED = new String("NOT CACHED");
/**
* The empty URI, equivalent to "".
*/
public static final Uri EMPTY = new HierarchicalUri(null, Part.NULL,
PathPart.EMPTY, Part.NULL, Part.NULL);
/**
* Prevents external subclassing.
*/
private Uri() {}
/**
* Returns true if this URI is hierarchical like "http://google.com".
* Absolute URIs are hierarchical if the scheme-specific part starts with
* a '/'. Relative URIs are always hierarchical.
*/
public abstract boolean isHierarchical();
/**
* Returns true if this URI is opaque like "mailto:[email protected]". The
* scheme-specific part of an opaque URI cannot start with a '/'.
*/
public boolean isOpaque() {
return !isHierarchical();
}
/**
* Returns true if this URI is relative, i.e. if it doesn't contain an
* explicit scheme.
*
* @return true if this URI is relative, false if it's absolute
*/
public abstract boolean isRelative();
/**
* Returns true if this URI is absolute, i.e. if it contains an
* explicit scheme.
*
* @return true if this URI is absolute, false if it's relative
*/
public boolean isAbsolute() {
return !isRelative();
}
/**
* Gets the scheme of this URI. Example: "http"
*
* @return the scheme or null if this is a relative URI
*/
public abstract String getScheme();
/**
* Gets the scheme-specific part of this URI, i.e. everything between the
* scheme separator ':' and the fragment separator '#'. If this is a
* relative URI, this method returns the entire URI. Decodes escaped octets.
*
* <p>Example: "//www.google.com/search?q=android"
*
* @return the decoded scheme-specific-part
*/
public abstract String getSchemeSpecificPart();
/**
* Gets the scheme-specific part of this URI, i.e. everything between the
* scheme separator ':' and the fragment separator '#'. If this is a
* relative URI, this method returns the entire URI. Leaves escaped octets
* intact.
*
* <p>Example: "//www.google.com/search?q=android"
*
* @return the decoded scheme-specific-part
*/
public abstract String getEncodedSchemeSpecificPart();
/**
* Gets the decoded authority part of this URI. For
* server addresses, the authority is structured as follows:
* {@code [ userinfo '@' ] host [ ':' port ]}
*
* <p>Examples: "google.com", "[email protected]:80"
*
* @return the authority for this URI or null if not present
*/
public abstract String getAuthority();
/**
* Gets the encoded authority part of this URI. For
* server addresses, the authority is structured as follows:
* {@code [ userinfo '@' ] host [ ':' port ]}
*
* <p>Examples: "google.com", "[email protected]:80"
*
* @return the authority for this URI or null if not present
*/
public abstract String getEncodedAuthority();
/**
* Gets the decoded user information from the authority.
* For example, if the authority is "[email protected]", this method will
* return "nobody".
*
* @return the user info for this URI or null if not present
*/
public abstract String getUserInfo();
/**
* Gets the encoded user information from the authority.
* For example, if the authority is "[email protected]", this method will
* return "nobody".
*
* @return the user info for this URI or null if not present
*/
public abstract String getEncodedUserInfo();
/**
* Gets the encoded host from the authority for this URI. For example,
* if the authority is "[email protected]", this method will return
* "google.com".
*
* @return the host for this URI or null if not present
*/
public abstract String getHost();
/**
* Gets the port from the authority for this URI. For example,
* if the authority is "google.com:80", this method will return 80.
*
* @return the port for this URI or -1 if invalid or not present
*/
public abstract int getPort();
/**
* Gets the decoded path.
*
* @return the decoded path, or null if this is not a hierarchical URI
* (like "mailto:[email protected]") or the URI is invalid
*/
public abstract String getPath();
/**
* Gets the encoded path.
*
* @return the encoded path, or null if this is not a hierarchical URI
* (like "mailto:[email protected]") or the URI is invalid
*/
public abstract String getEncodedPath();
/**
* Gets the decoded query component from this URI. The query comes after
* the query separator ('?') and before the fragment separator ('#'). This
* method would return "q=android" for
* "http://www.google.com/search?q=android".
*
* @return the decoded query or null if there isn't one
*/
public abstract String getQuery();
/**
* Gets the encoded query component from this URI. The query comes after
* the query separator ('?') and before the fragment separator ('#'). This
* method would return "q=android" for
* "http://www.google.com/search?q=android".
*
* @return the encoded query or null if there isn't one
*/
public abstract String getEncodedQuery();
/**
* Gets the decoded fragment part of this URI, everything after the '#'.
*
* @return the decoded fragment or null if there isn't one
*/
public abstract String getFragment();
/**
* Gets the encoded fragment part of this URI, everything after the '#'.
*
* @return the encoded fragment or null if there isn't one
*/
public abstract String getEncodedFragment();
/**
* Gets the decoded path segments.
*
* @return decoded path segments, each without a leading or trailing '/'
*/
public abstract String[] getPathSegments();
/**
* Gets the decoded last segment in the path.
*
* @return the decoded last segment or null if the path is empty
*/
public abstract String getLastPathSegment();
/**
* Compares this Uri to another object for equality. Returns true if the
* encoded string representations of this Uri and the given Uri are
* equal. Case counts. Paths are not normalized. If one Uri specifies a
* default port explicitly and the other leaves it implicit, they will not
* be considered equal.
*/
public boolean equals(Object o) {
if (!(o instanceof Uri)) {
return false;
}
Uri other = (Uri) o;
return toString().equals(other.toString());
}
/**
* Hashes the encoded string represention of this Uri consistently with
* {@link #equals(Object)}.
*/
public int hashCode() {
return toString().hashCode();
}
/**
* Compares the string representation of this Uri with that of
* another.
*/
public int compareTo(Uri other) {
return toString().compareTo(other.toString());
}
/**
* Returns the encoded string representation of this URI.
* Example: "http://google.com/"
*/
public abstract String toString();
/**
* Constructs a new builder, copying the attributes from this Uri.
*/
public abstract Builder buildUpon();
/** Index of a component which was not found. */
private final static int NOT_FOUND = -1;
/** Placeholder value for an index which hasn't been calculated yet. */
private final static int NOT_CALCULATED = -2;
/**
* Error message presented when a user tries to treat an opaque URI as
* hierarchical.
*/
private static final String NOT_HIERARCHICAL
= "This isn't a hierarchical URI.";
/** Default encoding. */
private static final String DEFAULT_ENCODING = "UTF-8";
/**
* Creates a Uri which parses the given encoded URI string.
*
* @param uriString an RFC 2396-compliant, encoded URI
* @throws NullPointerException if uriString is null
* @return Uri for this given uri string
*/
public static Uri parse(String uriString) {
return new StringUri(uriString);
}
/**
* An implementation which wraps a String URI. This URI can be opaque or
* hierarchical, but we extend AbstractHierarchicalUri in case we need
* the hierarchical functionality.
*/
private static class StringUri extends AbstractHierarchicalUri {
/** Used in parcelling. */
static final int TYPE_ID = 1;
/** URI string representation. */
private final String uriString;
private StringUri(String uriString) {
if (uriString == null) {
throw new NullPointerException("uriString");
}
this.uriString = uriString;
}
/** Cached scheme separator index. */
private volatile int cachedSsi = NOT_CALCULATED;
/** Finds the first ':'. Returns -1 if none found. */
private int findSchemeSeparator() {
return cachedSsi == NOT_CALCULATED
? cachedSsi = uriString.indexOf(':')
: cachedSsi;
}
/** Cached fragment separator index. */
private volatile int cachedFsi = NOT_CALCULATED;
/** Finds the first '#'. Returns -1 if none found. */
private int findFragmentSeparator() {
return cachedFsi == NOT_CALCULATED
? cachedFsi = uriString.indexOf('#', findSchemeSeparator())
: cachedFsi;
}
public boolean isHierarchical() {
int ssi = findSchemeSeparator();
if (ssi == NOT_FOUND) {
// All relative URIs are hierarchical.
return true;
}
if (uriString.length() == ssi + 1) {
// No ssp.
return false;
}
// If the ssp starts with a '/', this is hierarchical.
return uriString.charAt(ssi + 1) == '/';
}
public boolean isRelative() {
// Note: We return true if the index is 0
return findSchemeSeparator() == NOT_FOUND;
}
private volatile String scheme = NOT_CACHED;
public String getScheme() {
boolean cached = (scheme != NOT_CACHED);
return cached ? scheme : (scheme = parseScheme());
}
private String parseScheme() {
int ssi = findSchemeSeparator();
return ssi == NOT_FOUND ? null : uriString.substring(0, ssi);
}
private Part ssp;
private Part getSsp() {
return ssp == null ? ssp = Part.fromEncoded(parseSsp()) : ssp;
}
public String getEncodedSchemeSpecificPart() {
return getSsp().getEncoded();
}
public String getSchemeSpecificPart() {
return getSsp().getDecoded();
}
private String parseSsp() {
int ssi = findSchemeSeparator();
int fsi = findFragmentSeparator();
// Return everything between ssi and fsi.
return fsi == NOT_FOUND
? uriString.substring(ssi + 1)
: uriString.substring(ssi + 1, fsi);
}
private Part authority;
private Part getAuthorityPart() {
if (authority == null) {
String encodedAuthority
= parseAuthority(this.uriString, findSchemeSeparator());
return authority = Part.fromEncoded(encodedAuthority);
}
return authority;
}
public String getEncodedAuthority() {
return getAuthorityPart().getEncoded();
}
public String getAuthority() {
return getAuthorityPart().getDecoded();
}
private PathPart path;
private PathPart getPathPart() {
return path == null
? path = PathPart.fromEncoded(parsePath())
: path;
}
public String getPath() {
return getPathPart().getDecoded();
}
public String getEncodedPath() {
return getPathPart().getEncoded();
}
public String[] getPathSegments() {
return getPathPart().getPathSegments().segments;
}
private String parsePath() {
String uriString = this.uriString;
int ssi = findSchemeSeparator();
// If the URI is absolute.
if (ssi > -1) {
// Is there anything after the ':'?
boolean schemeOnly = ssi + 1 == uriString.length();
if (schemeOnly) {
// Opaque URI.
return null;
}
// A '/' after the ':' means this is hierarchical.
if (uriString.charAt(ssi + 1) != '/') {
// Opaque URI.
return null;
}
} else {
// All relative URIs are hierarchical.
}
return parsePath(uriString, ssi);
}
private Part query;
private Part getQueryPart() {
return query == null
? query = Part.fromEncoded(parseQuery()) : query;
}
public String getEncodedQuery() {
return getQueryPart().getEncoded();
}
private String parseQuery() {
// It doesn't make sense to cache this index. We only ever
// calculate it once.
int qsi = uriString.indexOf('?', findSchemeSeparator());
if (qsi == NOT_FOUND) {
return null;
}
int fsi = findFragmentSeparator();
if (fsi == NOT_FOUND) {
return uriString.substring(qsi + 1);
}
if (fsi < qsi) {
// Invalid.
return null;
}
return uriString.substring(qsi + 1, fsi);
}
public String getQuery() {
return getQueryPart().getDecoded();
}
private Part fragment;
private Part getFragmentPart() {
return fragment == null
? fragment = Part.fromEncoded(parseFragment()) : fragment;
}
public String getEncodedFragment() {
return getFragmentPart().getEncoded();
}
private String parseFragment() {
int fsi = findFragmentSeparator();
return fsi == NOT_FOUND ? null : uriString.substring(fsi + 1);
}
public String getFragment() {
return getFragmentPart().getDecoded();
}
public String toString() {
return uriString;
}
/**
* Parses an authority out of the given URI string.
*
* @param uriString URI string
* @param ssi scheme separator index, -1 for a relative URI
*
* @return the authority or null if none is found
*/
static String parseAuthority(String uriString, int ssi) {
int length = uriString.length();
// If "//" follows the scheme separator, we have an authority.
if (length > ssi + 2
&& uriString.charAt(ssi + 1) == '/'
&& uriString.charAt(ssi + 2) == '/') {
// We have an authority.
// Look for the start of the path, query, or fragment, or the
// end of the string.
int end = ssi + 3;
LOOP: while (end < length) {
switch (uriString.charAt(end)) {
case '/': // Start of path
case '?': // Start of query
case '#': // Start of fragment
break LOOP;
}
end++;
}
return uriString.substring(ssi + 3, end);
} else {
return null;
}
}
/**
* Parses a path out of this given URI string.
*
* @param uriString URI string
* @param ssi scheme separator index, -1 for a relative URI
*
* @return the path
*/
static String parsePath(String uriString, int ssi) {
int length = uriString.length();
// Find start of path.
int pathStart;
if (length > ssi + 2
&& uriString.charAt(ssi + 1) == '/'
&& uriString.charAt(ssi + 2) == '/') {
// Skip over authority to path.
pathStart = ssi + 3;
LOOP: while (pathStart < length) {
switch (uriString.charAt(pathStart)) {
case '?': // Start of query
case '#': // Start of fragment
return ""; // Empty path.
case '/': // Start of path!
break LOOP;
}
pathStart++;
}
} else {
// Path starts immediately after scheme separator.
pathStart = ssi + 1;
}
// Find end of path.
int pathEnd = pathStart;
LOOP: while (pathEnd < length) {
switch (uriString.charAt(pathEnd)) {
case '?': // Start of query
case '#': // Start of fragment
break LOOP;
}
pathEnd++;
}
return uriString.substring(pathStart, pathEnd);
}
public Builder buildUpon() {
if (isHierarchical()) {
return new Builder()
.scheme(getScheme())
.authority(getAuthorityPart())
.path(getPathPart())
.query(getQueryPart())
.fragment(getFragmentPart());
} else {
return new Builder()
.scheme(getScheme())
.opaquePart(getSsp())
.fragment(getFragmentPart());
}
}
}
/**
* Creates an opaque Uri from the given components. Encodes the ssp
* which means this method cannot be used to create hierarchical URIs.
*
* @param scheme of the URI
* @param ssp scheme-specific-part, everything between the
* scheme separator (':') and the fragment separator ('#'), which will
* get encoded
* @param fragment fragment, everything after the '#', null if undefined,
* will get encoded
*
* @throws NullPointerException if scheme or ssp is null
* @return Uri composed of the given scheme, ssp, and fragment
*
* @see Builder if you don't want the ssp and fragment to be encoded
*/
public static Uri fromParts(String scheme, String ssp,
String fragment) {
if (scheme == null) {
throw new NullPointerException("scheme");
}
if (ssp == null) {
throw new NullPointerException("ssp");
}
return new OpaqueUri(scheme, Part.fromDecoded(ssp),
Part.fromDecoded(fragment));
}
/**
* Opaque URI.
*/
private static class OpaqueUri extends Uri {
/** Used in parcelling. */
static final int TYPE_ID = 2;
private final String scheme;
private final Part ssp;
private final Part fragment;
private OpaqueUri(String scheme, Part ssp, Part fragment) {
this.scheme = scheme;
this.ssp = ssp;
this.fragment = fragment == null ? Part.NULL : fragment;
}
public boolean isHierarchical() {
return false;
}
public boolean isRelative() {
return scheme == null;
}
public String getScheme() {
return this.scheme;
}
public String getEncodedSchemeSpecificPart() {
return ssp.getEncoded();
}
public String getSchemeSpecificPart() {
return ssp.getDecoded();
}
public String getAuthority() {
return null;
}
public String getEncodedAuthority() {
return null;
}
public String getPath() {
return null;
}
public String getEncodedPath() {
return null;
}
public String getQuery() {
return null;
}
public String getEncodedQuery() {
return null;
}
public String getFragment() {
return fragment.getDecoded();
}
public String getEncodedFragment() {
return fragment.getEncoded();
}
public String[] getPathSegments() {
return new String[0];
}
public String getLastPathSegment() {
return null;
}
public String getUserInfo() {
return null;
}
public String getEncodedUserInfo() {
return null;
}
public String getHost() {
return null;
}
public int getPort() {
return -1;
}
private volatile String cachedString = NOT_CACHED;
public String toString() {
boolean cached = cachedString != NOT_CACHED;
if (cached) {
return cachedString;
}
StringBuffer sb = new StringBuffer();
sb.append(scheme).append(':');
sb.append(getEncodedSchemeSpecificPart());
if (!fragment.isEmpty()) {
sb.append('#').append(fragment.getEncoded());
}
return cachedString = sb.toString();
}
public Builder buildUpon() {
return new Builder()
.scheme(this.scheme)
.opaquePart(this.ssp)
.fragment(this.fragment);
}
}
/**
* Wrapper for path segment array.
*/
static class PathSegments {
static final PathSegments EMPTY = new PathSegments(null, 0);
final String[] segments;
final int size;
PathSegments(String[] segments, int size) {
this.segments = segments;
this.size = size;
}
public String get(int index) {
if (index >= size) {
throw new IndexOutOfBoundsException();
}
return segments[index];
}
public int size() {
return this.size;
}
}
/**
* Builds PathSegments.
*/
static class PathSegmentsBuilder {
String[] segments;
int size = 0;
void add(String segment) {
if (segments == null) {
segments = new String[4];
} else if (size + 1 == segments.length) {
String[] expanded = new String[segments.length * 2];
System.arraycopy(segments, 0, expanded, 0, segments.length);
segments = expanded;
}
segments[size++] = segment;
}
PathSegments build() {
if (segments == null) {
return PathSegments.EMPTY;
}
try {
return new PathSegments(segments, size);
} finally {
// Makes sure this doesn't get reused.
segments = null;
}
}
}
/**
* Support for hierarchical URIs.
*/
private abstract static class AbstractHierarchicalUri extends Uri {
public String getLastPathSegment() {
// TODO: If we haven't parsed all of the segments already, just
// grab the last one directly so we only allocate one string.
String[] segments = getPathSegments();
int size = segments.length;
if (size == 0) {
return null;
}
return segments[size - 1];
}
private Part userInfo;
private Part getUserInfoPart() {
return userInfo == null
? userInfo = Part.fromEncoded(parseUserInfo()) : userInfo;
}
public final String getEncodedUserInfo() {
return getUserInfoPart().getEncoded();
}
private String parseUserInfo() {
String authority = getEncodedAuthority();
if (authority == null) {
return null;
}
int end = authority.indexOf('@');
return end == NOT_FOUND ? null : authority.substring(0, end);
}
public String getUserInfo() {
return getUserInfoPart().getDecoded();
}
private volatile String host = NOT_CACHED;
public String getHost() {
boolean cached = (host != NOT_CACHED);
return cached ? host
: (host = parseHost());
}
private String parseHost() {
String authority = getEncodedAuthority();
if (authority == null) {
return null;
}
// Parse out user info and then port.
int userInfoSeparator = authority.indexOf('@');
int portSeparator = authority.indexOf(':', userInfoSeparator);
String encodedHost = portSeparator == NOT_FOUND
? authority.substring(userInfoSeparator + 1)
: authority.substring(userInfoSeparator + 1, portSeparator);
return decode(encodedHost);
}
private volatile int port = NOT_CALCULATED;
public int getPort() {
return port == NOT_CALCULATED
? port = parsePort()
: port;
}
private int parsePort() {
String authority = getEncodedAuthority();
if (authority == null) {
return -1;
}
// Make sure we look for the port separtor *after* the user info
// separator. We have URLs with a ':' in the user info.
int userInfoSeparator = authority.indexOf('@');
int portSeparator = authority.indexOf(':', userInfoSeparator);
if (portSeparator == NOT_FOUND) {
return -1;
}
String portString = decode(authority.substring(portSeparator + 1));
try {
return Integer.parseInt(portString);
} catch (NumberFormatException e) {
return -1;
}
}
}
/**
* Hierarchical Uri.
*/
private static class HierarchicalUri extends AbstractHierarchicalUri {
/** Used in parcelling. */
static final int TYPE_ID = 3;
private final String scheme; // can be null
private final Part authority;
private final PathPart path;
private final Part query;
private final Part fragment;
private HierarchicalUri(String scheme, Part authority, PathPart path,
Part query, Part fragment) {
this.scheme = scheme;
this.authority = Part.nonNull(authority);
this.path = path == null ? PathPart.NULL : path;
this.query = Part.nonNull(query);
this.fragment = Part.nonNull(fragment);
}
public boolean isHierarchical() {
return true;
}
public boolean isRelative() {
return scheme == null;
}
public String getScheme() {
return scheme;
}
private Part ssp;
private Part getSsp() {
return ssp == null
? ssp = Part.fromEncoded(makeSchemeSpecificPart()) : ssp;
}
public String getEncodedSchemeSpecificPart() {
return getSsp().getEncoded();
}
public String getSchemeSpecificPart() {
return getSsp().getDecoded();
}
/**
* Creates the encoded scheme-specific part from its sub parts.
*/
private String makeSchemeSpecificPart() {
StringBuffer builder = new StringBuffer();
appendSspTo(builder);
return builder.toString();
}
private void appendSspTo(StringBuffer builder) {
String encodedAuthority = authority.getEncoded();
if (encodedAuthority != null) {
// Even if the authority is "", we still want to append "//".
builder.append("//").append(encodedAuthority);
}
String encodedPath = path.getEncoded();
if (encodedPath != null) {
builder.append(encodedPath);
}
if (!query.isEmpty()) {
builder.append('?').append(query.getEncoded());
}
}
public String getAuthority() {
return this.authority.getDecoded();
}
public String getEncodedAuthority() {
return this.authority.getEncoded();
}
public String getEncodedPath() {
return this.path.getEncoded();
}
public String getPath() {
return this.path.getDecoded();
}
public String getQuery() {
return this.query.getDecoded();
}
public String getEncodedQuery() {
return this.query.getEncoded();
}
public String getFragment() {
return this.fragment.getDecoded();
}
public String getEncodedFragment() {
return this.fragment.getEncoded();
}
public String[] getPathSegments() {
return this.path.getPathSegments().segments;
}
private volatile String uriString = NOT_CACHED;
/**
* {@inheritDoc}
*/
public String toString() {
boolean cached = (uriString != NOT_CACHED);
return cached ? uriString
: (uriString = makeUriString());
}
private String makeUriString() {
StringBuffer builder = new StringBuffer();
if (scheme != null) {
builder.append(scheme).append(':');
}
appendSspTo(builder);
if (!fragment.isEmpty()) {
builder.append('#').append(fragment.getEncoded());
}
return builder.toString();
}
public Builder buildUpon() {
return new Builder()
.scheme(scheme)
.authority(authority)
.path(path)
.query(query)
.fragment(fragment);
}
}
/**
* Helper class for building or manipulating URI references. Not safe for
* concurrent use.
*
* <p>An absolute hierarchical URI reference follows the pattern:
* {@code <scheme>://<authority><absolute path>?<query>#<fragment>}
*
* <p>Relative URI references (which are always hierarchical) follow one
* of two patterns: {@code <relative or absolute path>?<query>#<fragment>}
* or {@code //<authority><absolute path>?<query>#<fragment>}
*
* <p>An opaque URI follows this pattern:
* {@code <scheme>:<opaque part>#<fragment>}
*/
public static final class Builder {
private String scheme;
private Part opaquePart;
private Part authority;
private PathPart path;
private Part query;
private Part fragment;
/**
* Constructs a new Builder.
*/
public Builder() {}
/**
* Sets the scheme.
*
* @param scheme name or {@code null} if this is a relative Uri
*/
public Builder scheme(String scheme) {
this.scheme = scheme;
return this;
}
Builder opaquePart(Part opaquePart) {
this.opaquePart = opaquePart;
return this;
}
/**
* Encodes and sets the given opaque scheme-specific-part.
*
* @param opaquePart decoded opaque part
*/
public Builder opaquePart(String opaquePart) {
return opaquePart(Part.fromDecoded(opaquePart));
}
/**
* Sets the previously encoded opaque scheme-specific-part.
*
* @param opaquePart encoded opaque part
*/
public Builder encodedOpaquePart(String opaquePart) {
return opaquePart(Part.fromEncoded(opaquePart));
}
Builder authority(Part authority) {
// This URI will be hierarchical.
this.opaquePart = null;
this.authority = authority;
return this;
}
/**
* Encodes and sets the authority.
*/
public Builder authority(String authority) {
return authority(Part.fromDecoded(authority));
}
/**
* Sets the previously encoded authority.
*/
public Builder encodedAuthority(String authority) {
return authority(Part.fromEncoded(authority));
}
Builder path(PathPart path) {
// This URI will be hierarchical.
this.opaquePart = null;
this.path = path;
return this;
}
/**
* Sets the path. Leaves '/' characters intact but encodes others as
* necessary.
*
* <p>If the path is not null and doesn't start with a '/', and if
* you specify a scheme and/or authority, the builder will prepend the
* given path with a '/'.
*/
public Builder path(String path) {
return path(PathPart.fromDecoded(path));
}
/**
* Sets the previously encoded path.
*
* <p>If the path is not null and doesn't start with a '/', and if
* you specify a scheme and/or authority, the builder will prepend the
* given path with a '/'.
*/
public Builder encodedPath(String path) {
return path(PathPart.fromEncoded(path));
}
/**
* Encodes the given segment and appends it to the path.
*/
public Builder appendPath(String newSegment) {
return path(PathPart.appendDecodedSegment(path, newSegment));
}
/**
* Appends the given segment to the path.
*/
public Builder appendEncodedPath(String newSegment) {
return path(PathPart.appendEncodedSegment(path, newSegment));
}
Builder query(Part query) {
// This URI will be hierarchical.
this.opaquePart = null;
this.query = query;
return this;
}
/**
* Encodes and sets the query.
*/
public Builder query(String query) {
return query(Part.fromDecoded(query));
}
/**
* Sets the previously encoded query.
*/
public Builder encodedQuery(String query) {
return query(Part.fromEncoded(query));
}
Builder fragment(Part fragment) {
this.fragment = fragment;
return this;
}
/**
* Encodes and sets the fragment.
*/
public Builder fragment(String fragment) {
return fragment(Part.fromDecoded(fragment));
}
/**
* Sets the previously encoded fragment.
*/
public Builder encodedFragment(String fragment) {
return fragment(Part.fromEncoded(fragment));
}
/**
* Encodes the key and value and then appends the parameter to the
* query string.
*
* @param key which will be encoded
* @param value which will be encoded
*/
public Builder appendQueryParameter(String key, String value) {
// This URI will be hierarchical.
this.opaquePart = null;
String encodedParameter = encode(key, null) + "="
+ encode(value, null);
if (query == null) {
query = Part.fromEncoded(encodedParameter);
return this;
}
String oldQuery = query.getEncoded();
if (oldQuery == null || oldQuery.length() == 0) {
query = Part.fromEncoded(encodedParameter);
} else {
query = Part.fromEncoded(oldQuery + "&" + encodedParameter);
}
return this;
}
/**
* Constructs a Uri with the current attributes.
*
* @throws UnsupportedOperationException if the URI is opaque and the
* scheme is null
*/
public Uri build() {
if (opaquePart != null) {
if (this.scheme == null) {
throw new UnsupportedOperationException(
"An opaque URI must have a scheme.");
}
return new OpaqueUri(scheme, opaquePart, fragment);
} else {
// Hierarchical URIs should not return null for getPath().
PathPart path = this.path;
if (path == null || path == PathPart.NULL) {
path = PathPart.EMPTY;
} else {
// If we have a scheme and/or authority, the path must
// be absolute. Prepend it with a '/' if necessary.
if (hasSchemeOrAuthority()) {
path = PathPart.makeAbsolute(path);
}
}
return new HierarchicalUri(
scheme, authority, path, query, fragment);
}
}
private boolean hasSchemeOrAuthority() {
return scheme != null
|| (authority != null && authority != Part.NULL);
}
/**
* {@inheritDoc}
*/
public String toString() {
return build().toString();
}
}
/**
* Searches the query string for parameter values with the given key.
*
* @param key which will be encoded
*
* @throws UnsupportedOperationException if this isn't a hierarchical URI
* @throws NullPointerException if key is null
*
* @return a list of decoded values
*/
public String[] getQueryParameters(String key) {
if (isOpaque()) {
throw new UnsupportedOperationException(NOT_HIERARCHICAL);
}
String query = getEncodedQuery();
if (query == null) {
return new String[0];
}
String encodedKey;
try {
encodedKey = URLEncoder.encode(key, DEFAULT_ENCODING);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("AssertionError: " + e);
}
// Prepend query with "&" making the first parameter the same as the
// rest.
query = "&" + query;
// Parameter prefix.
String prefix = "&" + encodedKey + "=";
Vector values = new Vector();
int start = 0;
int length = query.length();
while (start < length) {
start = query.indexOf(prefix, start);
if (start == -1) {
// No more values.
break;
}
// Move start to start of value.
start += prefix.length();
// Find end of value.
int end = query.indexOf('&', start);
if (end == -1) {
end = query.length();
}
String value = query.substring(start, end);
values.addElement(decode(value));
start = end;
}
int size = values.size();
String[] result = new String[size];
values.copyInto(result);
return result;
}
/**
* Searches the query string for the first value with the given key.
*
* @param key which will be encoded
* @throws UnsupportedOperationException if this isn't a hierarchical URI
* @throws NullPointerException if key is null
*
* @return the decoded value or null if no parameter is found
*/
public String getQueryParameter(String key) {
if (isOpaque()) {
throw new UnsupportedOperationException(NOT_HIERARCHICAL);
}
String query = getEncodedQuery();
if (query == null) {
return null;
}
String encodedKey;
try {
encodedKey = URLEncoder.encode(key, DEFAULT_ENCODING);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("AssertionError: " + e);
}
String prefix = encodedKey + "=";
if (query.length() < prefix.length()) {
return null;
}
int start;
if (query.startsWith(prefix)) {
// It's the first parameter.
start = prefix.length();
} else {
// It must be later in the query string.
prefix = "&" + prefix;
start = query.indexOf(prefix);
if (start == -1) {
// Not found.
return null;
}
start += prefix.length();
}
// Find end of value.
int end = query.indexOf('&', start);
if (end == -1) {
end = query.length();
}
String value = query.substring(start, end);
return decode(value);
}
private static final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray();
/**
* Encodes characters in the given string as '%'-escaped octets
* using the UTF-8 scheme. Leaves letters ("A-Z", "a-z"), numbers
* ("0-9"), and unreserved characters ("_-!.~'()*") intact. Encodes
* all other characters.
*
* @param s string to encode
* @return an encoded version of s suitable for use as a URI component,
* or null if s is null
*/
public static String encode(String s) {
return encode(s, null);
}
/**
* Encodes characters in the given string as '%'-escaped octets
* using the UTF-8 scheme. Leaves letters ("A-Z", "a-z"), numbers
* ("0-9"), and unreserved characters ("_-!.~'()*") intact. Encodes
* all other characters with the exception of those specified in the
* allow argument.
*
* @param s string to encode
* @param allow set of additional characters to allow in the encoded form,
* null if no characters should be skipped
* @return an encoded version of s suitable for use as a URI component,
* or null if s is null
*/
public static String encode(String s, String allow) {
if (s == null) {
return null;
}
// Lazily-initialized buffers.
StringBuffer encoded = null;
int oldLength = s.length();
// This loop alternates between copying over allowed characters and
// encoding in chunks. This results in fewer method calls and
// allocations than encoding one character at a time.
int current = 0;
while (current < oldLength) {
// Start in "copying" mode where we copy over allowed chars.
// Find the next character which needs to be encoded.
int nextToEncode = current;
while (nextToEncode < oldLength
&& isAllowed(s.charAt(nextToEncode), allow)) {
nextToEncode++;
}
// If there's nothing more to encode...
if (nextToEncode == oldLength) {
if (current == 0) {
// We didn't need to encode anything!
return s;
} else {
// Presumably, we've already done some encoding.
encoded.append(s.substring(current, oldLength));
return encoded.toString();
}
}
if (encoded == null) {
encoded = new StringBuffer();
}
if (nextToEncode > current) {
// Append allowed characters leading up to this point.
encoded.append(s.substring(current, nextToEncode));
} else {
// assert nextToEncode == current
}
// Switch to "encoding" mode.
// Find the next allowed character.
current = nextToEncode;
int nextAllowed = current + 1;
while (nextAllowed < oldLength
&& !isAllowed(s.charAt(nextAllowed), allow)) {
nextAllowed++;
}
// Convert the substring to bytes and encode the bytes as
// '%'-escaped octets.
String toEncode = s.substring(current, nextAllowed);
try {
byte[] bytes = toEncode.getBytes(DEFAULT_ENCODING);
int bytesLength = bytes.length;
for (int i = 0; i < bytesLength; i++) {
encoded.append('%');
encoded.append(HEX_DIGITS[(bytes[i] & 0xf0) >> 4]);
encoded.append(HEX_DIGITS[bytes[i] & 0xf]);
}
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("AssertionError: " + e);
}
current = nextAllowed;
}
// Encoded could still be null at this point if s is empty.
return encoded == null ? s : encoded.toString();
}
/**
* Returns true if the given character is allowed.
*
* @param c character to check
* @param allow characters to allow
* @return true if the character is allowed or false if it should be
* encoded
*/
private static boolean isAllowed(char c, String allow) {
return (c >= 'A' && c <= 'Z')
|| (c >= 'a' && c <= 'z')
|| (c >= '0' && c <= '9')
|| "_-!.~'()*".indexOf(c) != NOT_FOUND
|| (allow != null && allow.indexOf(c) != NOT_FOUND);
}
/** Unicode replacement character: \\uFFFD. */
private static final byte[] REPLACEMENT = { (byte) 0xFF, (byte) 0xFD };
/**
* Decodes '%'-escaped octets in the given string using the UTF-8 scheme.
* Replaces invalid octets with the unicode replacement character
* ("\\uFFFD").
*
* @param s encoded string to decode
* @return the given string with escaped octets decoded, or null if
* s is null
*/
public static String decode(String s) {
/*
Compared to java.net.URLEncoderDecoder.decode(), this method decodes a
chunk at a time instead of one character at a time, and it doesn't
throw exceptions. It also only allocates memory when necessary--if
there's nothing to decode, this method won't do much.
*/
if (s == null) {
return null;
}
// Lazily-initialized buffers.
StringBuffer decoded = null;
ByteArrayOutputStream out = null;
int oldLength = s.length();
// This loop alternates between copying over normal characters and
// escaping in chunks. This results in fewer method calls and
// allocations than decoding one character at a time.
int current = 0;
while (current < oldLength) {
// Start in "copying" mode where we copy over normal characters.
// Find the next escape sequence.
int nextEscape = s.indexOf('%', current);
if (nextEscape == NOT_FOUND) {
if (decoded == null) {
// We didn't actually decode anything.
return s;
} else {
// Append the remainder and return the decoded string.
decoded.append(s.substring(current, oldLength));
return decoded.toString();
}
}
// Prepare buffers.
if (decoded == null) {
// Looks like we're going to need the buffers...
// We know the new string will be shorter. Using the old length
// may overshoot a bit, but it will save us from resizing the
// buffer.
decoded = new StringBuffer(oldLength);
out = new ByteArrayOutputStream(4);
} else {
// Clear decoding buffer.
out.reset();
}
// Append characters leading up to the escape.
if (nextEscape > current) {
decoded.append(s.substring(current, nextEscape));
current = nextEscape;
} else {
// assert current == nextEscape
}
// Switch to "decoding" mode where we decode a string of escape
// sequences.
// Decode and append escape sequences. Escape sequences look like
// "%ab" where % is literal and a and b are hex digits.
try {
do {
if (current + 2 >= oldLength) {
// Truncated escape sequence.
out.write(REPLACEMENT);
} else {
int a = Character.digit(s.charAt(current + 1), 16);
int b = Character.digit(s.charAt(current + 2), 16);
if (a == -1 || b == -1) {
// Non hex digits.
out.write(REPLACEMENT);
} else {
// Combine the hex digits into one byte and write.
out.write((a << 4) + b);
}
}
// Move passed the escape sequence.
current += 3;
} while (current < oldLength && s.charAt(current) == '%');
// Decode UTF-8 bytes into a string and append it.
decoded.append(new String(out.toByteArray(), DEFAULT_ENCODING));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("AssertionError: " + e);
} catch (IOException e) {
throw new RuntimeException("AssertionError: " + e);
}
}
// If we don't have a buffer, we didn't have to decode anything.
return decoded == null ? s : decoded.toString();
}
/**
* Support for part implementations.
*/
static abstract class AbstractPart {
/**
* Enum which indicates which representation of a given part we have.
*/
static class Representation {
static final int BOTH = 0;
static final int ENCODED = 1;
static final int DECODED = 2;
}
volatile String encoded;
volatile String decoded;
AbstractPart(String encoded, String decoded) {
this.encoded = encoded;
this.decoded = decoded;
}
abstract String getEncoded();
final String getDecoded() {
boolean hasDecoded = decoded != NOT_CACHED;
return hasDecoded ? decoded : (decoded = decode(encoded));
}
}
/**
* Immutable wrapper of encoded and decoded versions of a URI part. Lazily
* creates the encoded or decoded version from the other.
*/
static class Part extends AbstractPart {
/** A part with null values. */
static final Part NULL = new EmptyPart(null);
/** A part with empty strings for values. */
static final Part EMPTY = new EmptyPart("");
private Part(String encoded, String decoded) {
super(encoded, decoded);
}
boolean isEmpty() {
return false;
}
String getEncoded() {
boolean hasEncoded = encoded != NOT_CACHED;
return hasEncoded ? encoded : (encoded = encode(decoded));
}
/**
* Returns given part or {@link #NULL} if the given part is null.
*/
static Part nonNull(Part part) {
return part == null ? NULL : part;
}
/**
* Creates a part from the encoded string.
*
* @param encoded part string
*/
static Part fromEncoded(String encoded) {
return from(encoded, NOT_CACHED);
}
/**
* Creates a part from the decoded string.
*
* @param decoded part string
*/
static Part fromDecoded(String decoded) {
return from(NOT_CACHED, decoded);
}
/**
* Creates a part from the encoded and decoded strings.
*
* @param encoded part string
* @param decoded part string
*/
static Part from(String encoded, String decoded) {
// We have to check both encoded and decoded in case one is
// NOT_CACHED.
if (encoded == null) {
return NULL;
}
if (encoded.length() == 0) {
return EMPTY;
}
if (decoded == null) {
return NULL;
}
if (decoded .length() == 0) {
return EMPTY;
}
return new Part(encoded, decoded);
}
private static class EmptyPart extends Part {
public EmptyPart(String value) {
super(value, value);
}
/**
* {@inheritDoc}
*/
boolean isEmpty() {
return true;
}
}
}
/**
* Immutable wrapper of encoded and decoded versions of a path part. Lazily
* creates the encoded or decoded version from the other.
*/
static class PathPart extends AbstractPart {
/** A part with null values. */
static final PathPart NULL = new PathPart(null, null);
/** A part with empty strings for values. */
static final PathPart EMPTY = new PathPart("", "");
private PathPart(String encoded, String decoded) {
super(encoded, decoded);
}
String getEncoded() {
boolean hasEncoded = encoded != NOT_CACHED;
// Don't encode '/'.
return hasEncoded ? encoded : (encoded = encode(decoded, "/"));
}
/**
* Cached path segments. This doesn't need to be volatile--we don't
* care if other threads see the result.
*/
private PathSegments pathSegments;
/**
* Gets the individual path segments. Parses them if necessary.
*
* @return parsed path segments or null if this isn't a hierarchical
* URI
*/
PathSegments getPathSegments() {
if (pathSegments != null) {
return pathSegments;
}
String path = getEncoded();
if (path == null) {
return pathSegments = PathSegments.EMPTY;
}
PathSegmentsBuilder segmentBuilder = new PathSegmentsBuilder();
int previous = 0;
int current;
while ((current = path.indexOf('/', previous)) > -1) {
// This check keeps us from adding a segment if the path starts
// '/' and an empty segment for "//".
if (previous < current) {
String decodedSegment
= decode(path.substring(previous, current));
segmentBuilder.add(decodedSegment);
}
previous = current + 1;
}
// Add in the final path segment.
if (previous < path.length()) {
segmentBuilder.add(decode(path.substring(previous)));
}
return pathSegments = segmentBuilder.build();
}
static PathPart appendEncodedSegment(PathPart oldPart,
String newSegment) {
// If there is no old path, should we make the new path relative
// or absolute? I pick absolute.
if (oldPart == null) {
// No old path.
return fromEncoded("/" + newSegment);
}
String oldPath = oldPart.getEncoded();
if (oldPath == null) {
oldPath = "";
}
int oldPathLength = oldPath.length();
String newPath;
if (oldPathLength == 0) {
// No old path.
newPath = "/" + newSegment;
} else if (oldPath.charAt(oldPathLength - 1) == '/') {
newPath = oldPath + newSegment;
} else {
newPath = oldPath + "/" + newSegment;
}
return fromEncoded(newPath);
}
static PathPart appendDecodedSegment(PathPart oldPart, String decoded) {
String encoded = encode(decoded);
// TODO: Should we reuse old PathSegments? Probably not.
return appendEncodedSegment(oldPart, encoded);
}
/**
* Creates a path from the encoded string.
*
* @param encoded part string
*/
static PathPart fromEncoded(String encoded) {
return from(encoded, NOT_CACHED);
}
/**
* Creates a path from the decoded string.
*
* @param decoded part string
*/
static PathPart fromDecoded(String decoded) {
return from(NOT_CACHED, decoded);
}
/**
* Creates a path from the encoded and decoded strings.
*
* @param encoded part string
* @param decoded part string
*/
static PathPart from(String encoded, String decoded) {
if (encoded == null) {
return NULL;
}
if (encoded.length() == 0) {
return EMPTY;
}
return new PathPart(encoded, decoded);
}
/**
* Prepends path values with "/" if they're present, not empty, and
* they don't already start with "/".
*/
static PathPart makeAbsolute(PathPart oldPart) {
boolean encodedCached = oldPart.encoded != NOT_CACHED;
// We don't care which version we use, and we don't want to force
// unneccessary encoding/decoding.
String oldPath = encodedCached ? oldPart.encoded : oldPart.decoded;
if (oldPath == null || oldPath.length() == 0
|| oldPath.startsWith("/")) {
return oldPart;
}
// Prepend encoded string if present.
String newEncoded = encodedCached
? "/" + oldPart.encoded : NOT_CACHED;
// Prepend decoded string if present.
boolean decodedCached = oldPart.decoded != NOT_CACHED;
String newDecoded = decodedCached
? "/" + oldPart.decoded
: NOT_CACHED;
return new PathPart(newEncoded, newDecoded);
}
}
/**
* Creates a new Uri by appending an already-encoded path segment to a
* base Uri.
*
* @param baseUri Uri to append path segment to
* @param pathSegment encoded path segment to append
* @return a new Uri based on baseUri with the given segment appended to
* the path
* @throws NullPointerException if baseUri is null
*/
public static Uri withAppendedPath(Uri baseUri, String pathSegment) {
Builder builder = baseUri.buildUpon();
builder = builder.appendEncodedPath(pathSegment);
return builder.build();
}
}
| Java |
/**
* @license
* Copyright 2020 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.CLASS({
package: 'foam.nanos.jetty',
name: 'JettyThreadPoolConfig',
documentation: 'model of org.eclipse.jetty.server.ThreadPool',
properties: [
{
name: 'minThreads',
class: 'Int',
value: 8
},
{
name: 'maxThreads',
class: 'Int',
value: 200
},
{
name: 'idleTimeout',
class: 'Int',
value: 60000
}
]
});
| Java |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* 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.
*/
using QuantConnect.Orders;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
using System.Collections.Generic;
using QuantConnect.Data.Custom.AlphaStreams;
using QuantConnect.Algorithm.Framework.Alphas;
using QuantConnect.Algorithm.Framework.Execution;
using QuantConnect.Algorithm.Framework.Portfolio;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Example algorithm consuming an alpha streams portfolio state and trading based on it
/// </summary>
public class AlphaStreamsBasicTemplateAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
public override void Initialize()
{
SetStartDate(2018, 04, 04);
SetEndDate(2018, 04, 06);
SetAlpha(new AlphaStreamAlphaModule());
SetExecution(new ImmediateExecutionModel());
Settings.MinimumOrderMarginPortfolioPercentage = 0.01m;
SetPortfolioConstruction(new EqualWeightingAlphaStreamsPortfolioConstructionModel());
SetSecurityInitializer(new BrokerageModelSecurityInitializer(BrokerageModel,
new FuncSecuritySeeder(GetLastKnownPrices)));
foreach (var alphaId in new [] { "623b06b231eb1cc1aa3643a46", "9fc8ef73792331b11dbd5429a" })
{
AddData<AlphaStreamsPortfolioState>(alphaId);
}
}
public override void OnOrderEvent(OrderEvent orderEvent)
{
Log($"OnOrderEvent: {orderEvent}");
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public virtual Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "-0.12%"},
{"Compounding Annual Return", "-14.722%"},
{"Drawdown", "0.200%"},
{"Expectancy", "-1"},
{"Net Profit", "-0.116%"},
{"Sharpe Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "2.474"},
{"Tracking Error", "0.339"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$83000.00"},
{"Lowest Capacity Asset", "BTCUSD XJ"},
{"Fitness Score", "0.017"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "79228162514264337593543950335"},
{"Return Over Maximum Drawdown", "-138.588"},
{"Portfolio Turnover", "0.034"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "2b94bc50a74caebe06c075cdab1bc6da"}
};
}
}
| Java |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.distributed.internal.membership;
import org.apache.geode.distributed.internal.DMStats;
import org.apache.geode.distributed.internal.DistributionConfig;
import org.apache.geode.distributed.internal.LocatorStats;
import org.apache.geode.distributed.internal.membership.gms.NetLocator;
import org.apache.geode.internal.admin.remote.RemoteTransportConfig;
import org.apache.geode.internal.security.SecurityService;
import java.io.File;
import java.net.InetAddress;
/**
* This is the SPI for a provider of membership services.
*
* @see org.apache.geode.distributed.internal.membership.NetMember
*/
public interface MemberServices {
/**
* Return a new NetMember, possibly for a different host
*
* @param i the name of the host for the specified NetMember, the current host (hopefully) if
* there are any problems.
* @param port the membership port
* @param splitBrainEnabled whether the member has this feature enabled
* @param canBeCoordinator whether the member can be membership coordinator
* @param payload the payload to be associated with the resulting object
* @param version TODO
* @return the new NetMember
*/
public abstract NetMember newNetMember(InetAddress i, int port, boolean splitBrainEnabled,
boolean canBeCoordinator, MemberAttributes payload, short version);
/**
* Return a new NetMember representing current host
*
* @param i an InetAddress referring to the current host
* @param port the membership port being used
*
* @return the new NetMember
*/
public abstract NetMember newNetMember(InetAddress i, int port);
/**
* Return a new NetMember representing current host
*
* @param s a String referring to the current host
* @param p the membership port being used
* @return the new member
*/
public abstract NetMember newNetMember(String s, int p);
/**
* Create a new MembershipManager
*
* @param listener the listener to notify for callbacks
* @param transport holds configuration information that can be used by the manager to configure
* itself
* @param stats a gemfire statistics collection object for communications stats
*
* @return a MembershipManager
*/
public abstract MembershipManager newMembershipManager(DistributedMembershipListener listener,
DistributionConfig config, RemoteTransportConfig transport, DMStats stats,
SecurityService securityService);
/**
* currently this is a test method but it ought to be used by InternalLocator to create the peer
* location TcpHandler
*/
public abstract NetLocator newLocatorHandler(InetAddress bindAddress, File stateFile,
String locatorString, boolean usePreferredCoordinators,
boolean networkPartitionDetectionEnabled, LocatorStats stats, String securityUDPDHAlgo);
}
| Java |
/*
* Copyright (c) 2009 Kathryn Huxtable and Kenneth Orr.
*
* This file is part of the SeaGlass Pluggable Look and Feel.
*
* 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.
*
* $Id: org.eclipse.jdt.ui.prefs 172 2009-10-06 18:31:12Z [email protected] $
*/
package com.seaglasslookandfeel.ui;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.beans.PropertyChangeEvent;
import javax.swing.JComponent;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.UIResource;
import javax.swing.plaf.synth.SynthContext;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;
import com.seaglasslookandfeel.SeaGlassContext;
/**
* SeaGlass TextPaneUI delegate.
*
* Based on SynthTextPaneUI by Georges Saab and David Karlton.
*
* The only reason this exists is that we had to modify SynthTextPaneUI.
*
* @see javax.swing.plaf.synth.SynthTextPaneUI
*/
public class SeaGlassTextPaneUI extends SeaGlassEditorPaneUI {
/**
* Creates a UI for the JTextPane.
*
* @param c the JTextPane object
* @return the UI object
*/
public static ComponentUI createUI(JComponent c) {
return new SeaGlassTextPaneUI();
}
/**
* Fetches the name used as a key to lookup properties through the
* UIManager. This is used as a prefix to all the standard
* text properties.
*
* @return the name ("TextPane")
*/
@Override
protected String getPropertyPrefix() {
return "TextPane";
}
/**
* Installs the UI for a component. This does the following
* things.
* <ol>
* <li>
* Sets opaqueness of the associated component according to its style,
* if the opaque property has not already been set by the client program.
* <li>
* Installs the default caret and highlighter into the
* associated component. These properties are only set if their
* current value is either {@code null} or an instance of
* {@link UIResource}.
* <li>
* Attaches to the editor and model. If there is no
* model, a default one is created.
* <li>
* Creates the view factory and the view hierarchy used
* to represent the model.
* </ol>
*
* @param c the editor component
* @see javax.swing.plaf.basic.BasicTextUI#installUI
* @see ComponentUI#installUI
*/
@Override
public void installUI(JComponent c) {
super.installUI(c);
updateForeground(c.getForeground());
updateFont(c.getFont());
}
/**
* This method gets called when a bound property is changed
* on the associated JTextComponent. This is a hook
* which UI implementations may change to reflect how the
* UI displays bound properties of JTextComponent subclasses.
* If the font, foreground or document has changed, the
* the appropriate property is set in the default style of
* the document.
*
* @param evt the property change event
*/
@Override
protected void propertyChange(PropertyChangeEvent evt) {
super.propertyChange(evt);
String name = evt.getPropertyName();
if (name.equals("foreground")) {
updateForeground((Color)evt.getNewValue());
} else if (name.equals("font")) {
updateFont((Font)evt.getNewValue());
} else if (name.equals("document")) {
JComponent comp = getComponent();
updateForeground(comp.getForeground());
updateFont(comp.getFont());
}
}
/**
* Update the color in the default style of the document.
*
* @param color the new color to use or null to remove the color attribute
* from the document's style
*/
private void updateForeground(Color color) {
StyledDocument doc = (StyledDocument)getComponent().getDocument();
Style style = doc.getStyle(StyleContext.DEFAULT_STYLE);
if (style == null) {
return;
}
if (color == null) {
style.removeAttribute(StyleConstants.Foreground);
} else {
StyleConstants.setForeground(style, color);
}
}
/**
* Update the font in the default style of the document.
*
* @param font the new font to use or null to remove the font attribute
* from the document's style
*/
private void updateFont(Font font) {
StyledDocument doc = (StyledDocument)getComponent().getDocument();
Style style = doc.getStyle(StyleContext.DEFAULT_STYLE);
if (style == null) {
return;
}
if (font == null) {
style.removeAttribute(StyleConstants.FontFamily);
style.removeAttribute(StyleConstants.FontSize);
style.removeAttribute(StyleConstants.Bold);
style.removeAttribute(StyleConstants.Italic);
} else {
StyleConstants.setFontFamily(style, font.getName());
StyleConstants.setFontSize(style, font.getSize());
StyleConstants.setBold(style, font.isBold());
StyleConstants.setItalic(style, font.isItalic());
}
}
@Override
void paintBackground(SynthContext context, Graphics g, JComponent c) {
((SeaGlassContext)context).getPainter().paintTextPaneBackground(context, g, 0, 0,
c.getWidth(), c.getHeight());
}
/**
* @inheritDoc
*/
@Override
public void paintBorder(SynthContext context, Graphics g, int x,
int y, int w, int h) {
((SeaGlassContext)context).getPainter().paintTextPaneBorder(context, g, x, y, w, h);
}
}
| Java |
/**
* Most of the code in the Qalingo project is copyrighted Hoteia and licensed
* under the Apache License Version 2.0 (release version 0.8.0)
* http://www.apache.org/licenses/LICENSE-2.0
*
* Copyright (c) Hoteia, 2012-2014
* http://www.hoteia.com - http://twitter.com/hoteia - [email protected]
*
*/
package org.hoteia.qalingo.core.service.pojo;
import java.util.List;
import java.util.Set;
import org.dozer.Mapper;
import org.hoteia.qalingo.core.domain.Customer;
import org.hoteia.qalingo.core.domain.CustomerMarketArea;
import org.hoteia.qalingo.core.domain.CustomerWishlist;
import org.hoteia.qalingo.core.domain.MarketArea;
import org.hoteia.qalingo.core.pojo.customer.CustomerPojo;
import org.hoteia.qalingo.core.pojo.customer.CustomerWishlistPojo;
import org.hoteia.qalingo.core.pojo.util.mapper.PojoUtil;
import org.hoteia.qalingo.core.service.CustomerService;
import org.hoteia.qalingo.core.service.MarketService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service("customerPojoService")
@Transactional(readOnly = true)
public class CustomerPojoService {
private final Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private Mapper dozerBeanMapper;
@Autowired
protected MarketService marketService;
@Autowired
private CustomerService customerService;
public List<CustomerPojo> getAllCustomers() {
List<Customer> customers = customerService.findCustomers();
logger.debug("Found {} customers", customers.size());
return PojoUtil.mapAll(dozerBeanMapper, customers, CustomerPojo.class);
}
public CustomerPojo getCustomerById(final String id) {
Customer customer = customerService.getCustomerById(id);
logger.debug("Found customer {} for id {}", customer, id);
return customer == null ? null : dozerBeanMapper.map(customer, CustomerPojo.class);
}
public CustomerPojo getCustomerByLoginOrEmail(final String usernameOrEmail) {
Customer customer = customerService.getCustomerByLoginOrEmail(usernameOrEmail);
logger.debug("Found customer {} for usernameOrEmail {}", customer, usernameOrEmail);
return customer == null ? null : dozerBeanMapper.map(customer, CustomerPojo.class);
}
public CustomerPojo getCustomerByPermalink(final String permalink) {
Customer customer = customerService.getCustomerByPermalink(permalink);
logger.debug("Found customer {} for usernameOrEmail {}", customer, permalink);
return customer == null ? null : dozerBeanMapper.map(customer, CustomerPojo.class);
}
@Transactional
public void saveOrUpdate(final CustomerPojo customerJsonPojo) throws Exception {
Customer customer = dozerBeanMapper.map(customerJsonPojo, Customer.class);
logger.info("Saving customer {}", customer);
customerService.saveOrUpdateCustomer(customer);
}
public List<CustomerWishlistPojo> getWishlist(final Customer customer, final MarketArea marketArea) {
final CustomerMarketArea customerMarketArea = customer.getCurrentCustomerMarketArea(marketArea.getId());
Set<CustomerWishlist> wishlistProducts = customerMarketArea.getWishlistProducts();
List<CustomerWishlistPojo> wishlists = PojoUtil.mapAll(dozerBeanMapper, wishlistProducts, CustomerWishlistPojo.class);
return wishlists;
}
public void addProductSkuToWishlist(MarketArea marketArea, Customer customer, String catalogCategoryCode, String productSkuCode) throws Exception {
customerService.addProductSkuToWishlist(marketArea, customer, catalogCategoryCode, productSkuCode);
}
} | Java |
<?php
/**
* Copyright (c) 2012 Robin Appelman <[email protected]>
* This file is licensed under the Affero General Public License version 3 or
* later.
* See the COPYING-README file.
*/
abstract class OC_Archive{
/**
* open any of the supported archive types
* @param string $path
* @return OC_Archive|void
*/
public static function open($path) {
$ext=substr($path, strrpos($path, '.'));
switch($ext) {
case '.zip':
return new OC_Archive_ZIP($path);
case '.gz':
case '.bz':
case '.bz2':
case '.tgz':
case '.tar':
return new OC_Archive_TAR($path);
}
}
/**
* @param $source
*/
abstract function __construct($source);
/**
* add an empty folder to the archive
* @param string $path
* @return bool
*/
abstract function addFolder($path);
/**
* add a file to the archive
* @param string $path
* @param string $source either a local file or string data
* @return bool
*/
abstract function addFile($path, $source='');
/**
* rename a file or folder in the archive
* @param string $source
* @param string $dest
* @return bool
*/
abstract function rename($source, $dest);
/**
* get the uncompressed size of a file in the archive
* @param string $path
* @return int
*/
abstract function filesize($path);
/**
* get the last modified time of a file in the archive
* @param string $path
* @return int
*/
abstract function mtime($path);
/**
* get the files in a folder
* @param string $path
* @return array
*/
abstract function getFolder($path);
/**
* get all files in the archive
* @return array
*/
abstract function getFiles();
/**
* get the content of a file
* @param string $path
* @return string
*/
abstract function getFile($path);
/**
* extract a single file from the archive
* @param string $path
* @param string $dest
* @return bool
*/
abstract function extractFile($path, $dest);
/**
* extract the archive
* @param string $dest
* @return bool
*/
abstract function extract($dest);
/**
* check if a file or folder exists in the archive
* @param string $path
* @return bool
*/
abstract function fileExists($path);
/**
* remove a file or folder from the archive
* @param string $path
* @return bool
*/
abstract function remove($path);
/**
* get a file handler
* @param string $path
* @param string $mode
* @return resource
*/
abstract function getStream($path, $mode);
/**
* add a folder and all its content
* @param string $path
* @param string $source
* @return boolean|null
*/
function addRecursive($path, $source) {
$dh = opendir($source);
if(is_resource($dh)) {
$this->addFolder($path);
while (($file = readdir($dh)) !== false) {
if($file=='.' or $file=='..') {
continue;
}
if(is_dir($source.'/'.$file)) {
$this->addRecursive($path.'/'.$file, $source.'/'.$file);
}else{
$this->addFile($path.'/'.$file, $source.'/'.$file);
}
}
}
}
}
| Java |
/* 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.activiti.engine.impl.context;
import org.activiti.engine.impl.persistence.entity.DeploymentEntity;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.util.ProcessDefinitionUtil;
import org.activiti.engine.repository.ProcessDefinition;
/**
* @author Tom Baeyens
*/
public class ExecutionContext {
protected ExecutionEntity execution;
public ExecutionContext(ExecutionEntity execution) {
this.execution = execution;
}
public ExecutionEntity getExecution() {
return execution;
}
public ExecutionEntity getProcessInstance() {
return execution.getProcessInstance();
}
public ProcessDefinition getProcessDefinition() {
return ProcessDefinitionUtil.getProcessDefinition(execution.getProcessDefinitionId());
}
public DeploymentEntity getDeployment() {
String deploymentId = getProcessDefinition().getDeploymentId();
DeploymentEntity deployment = Context.getCommandContext().getDeploymentEntityManager().findById(deploymentId);
return deployment;
}
}
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_26) on Tue Feb 14 08:16:37 UTC 2012 -->
<TITLE>
Uses of Class org.apache.hadoop.security.AccessControlException (Hadoop 1.0.1 API)
</TITLE>
<META NAME="date" CONTENT="2012-02-14">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.hadoop.security.AccessControlException (Hadoop 1.0.1 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/hadoop/security/AccessControlException.html" title="class in org.apache.hadoop.security"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/apache/hadoop/security//class-useAccessControlException.html" target="_top"><B>FRAMES</B></A>
<A HREF="AccessControlException.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.apache.hadoop.security.AccessControlException</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Packages that use <A HREF="../../../../../org/apache/hadoop/security/AccessControlException.html" title="class in org.apache.hadoop.security">AccessControlException</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.hadoop.security.authorize"><B>org.apache.hadoop.security.authorize</B></A></TD>
<TD> </TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.hadoop.security.authorize"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../org/apache/hadoop/security/AccessControlException.html" title="class in org.apache.hadoop.security">AccessControlException</A> in <A HREF="../../../../../org/apache/hadoop/security/authorize/package-summary.html">org.apache.hadoop.security.authorize</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Subclasses of <A HREF="../../../../../org/apache/hadoop/security/AccessControlException.html" title="class in org.apache.hadoop.security">AccessControlException</A> in <A HREF="../../../../../org/apache/hadoop/security/authorize/package-summary.html">org.apache.hadoop.security.authorize</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/hadoop/security/authorize/AuthorizationException.html" title="class in org.apache.hadoop.security.authorize">AuthorizationException</A></B></CODE>
<BR>
An exception class for authorization-related issues.</TD>
</TR>
</TABLE>
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/hadoop/security/AccessControlException.html" title="class in org.apache.hadoop.security"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/apache/hadoop/security//class-useAccessControlException.html" target="_top"><B>FRAMES</B></A>
<A HREF="AccessControlException.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2009 The Apache Software Foundation
</BODY>
</HTML>
| Java |
#
# Copyright 2017 Centreon (http://www.centreon.com/)
#
# Centreon is a full-fledged industry-strength solution that meets
# the needs in IT infrastructure and application monitoring for
# service performance.
#
# 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 apps::protocols::dns::lib::dns;
use strict;
use warnings;
use Net::DNS;
my $handle;
my %map_search_field = (
MX => 'exchange',
SOA => 'mname',
NS => 'nsdname',
A => 'address',
PTR => 'name',
);
sub search {
my ($self, %options) = @_;
my @results = ();
my $search_type = $self->{option_results}->{search_type};
if (defined($search_type) && !defined($map_search_field{$search_type})) {
$self->{output}->add_option_msg(short_msg => "search-type '$search_type' is unknown or unsupported");
$self->{output}->option_exit();
}
my $error_quit = defined($options{error_quit}) ? $options{error_quit} : undef;
my $reply = $handle->search($self->{option_results}->{search}, $search_type);
if ($reply) {
foreach my $rr ($reply->answer) {
if (!defined($search_type)) {
if ($rr->type eq 'A') {
push @results, $rr->address;
}
if ($rr->type eq 'PTR') {
push @results, $rr->name;
}
next;
}
next if ($rr->type ne $search_type);
my $search_field = $map_search_field{$search_type};
push @results, $rr->$search_field;
}
} else {
if (defined($error_quit)) {
$self->{output}->output_add(severity => $error_quit,
short_msg => sprintf("DNS Query Failed: %s", $handle->errorstring));
$self->{output}->display();
$self->{output}->exit();
}
}
return sort @results;
}
sub connect {
my ($self, %options) = @_;
my %dns_options = ();
my $nameservers = [];
if (defined($self->{option_results}->{nameservers})) {
$nameservers = [@{$self->{option_results}->{nameservers}}];
}
my $searchlist = [];
if (defined($self->{option_results}->{searchlist})) {
$searchlist = [@{$self->{option_results}->{searchlist}}];
}
foreach my $option (@{$self->{option_results}->{dns_options}}) {
next if ($option !~ /^(.+?)=(.+)$/);
$dns_options{$1} = $2;
}
$handle = Net::DNS::Resolver->new(
nameservers => $nameservers,
searchlist => $searchlist,
%dns_options
);
}
1;
| Java |
# Parser Error Handler
Parser Error Handler validation is enabled by calling [IParser#setParserErrorHandler(IParserErrorHandler)](/hapi-fhir/apidocs/hapi-fhir-base/ca/uhn/fhir/parser/IParser.html#setParserErrorHandler(ca.uhn.fhir.parser.IParserErrorHandler)) on either the FhirContext or on individual parser instances. This method takes an [IParserErrorHandler](/hapi-fhir/apidocs/hapi-fhir-base/ca/uhn/fhir/parser/IParserErrorHandler.html), which is a callback that will be invoked any time a parse issue is detected.
There are two implementations of IParserErrorHandler that come built into HAPI FHIR. You can also supply your own implementation if you want.
* [**LenientErrorHandler**](/hapi-fhir/apidocs/hapi-fhir-base/ca/uhn/fhir/parser/LenientErrorHandler.html) logs any errors but does not abort parsing. By default this handler is used, and it logs errors at "warning" level. It can also be configured to silently ignore issues. LenientErrorHandler is the default.
* [**StrictErrorHandler**](/hapi-fhir/apidocs/hapi-fhir-base/ca/uhn/fhir/parser/StrictErrorHandler.html) throws a [DataFormatException](/hapi-fhir/apidocs/hapi-fhir-base/ca/uhn/fhir/parser/DataFormatException.html) if any errors are detected.
The following example shows how to configure a parser to use strict validation.
```java
{{snippet:classpath:/ca/uhn/hapi/fhir/docs/ValidatorExamples.java|parserValidation}}
```
You can also configure the error handler at the FhirContext level, which is useful for clients.
```java
{{snippet:classpath:/ca/uhn/hapi/fhir/docs/ValidatorExamples.java|clientValidation}}
```
FhirContext level validators can also be useful on servers.
```java
{{snippet:classpath:/ca/uhn/hapi/fhir/docs/ValidatorExamples.java|serverValidation}}
```
| Java |
package nak.liblinear;
import static nak.liblinear.Linear.info;
/**
* Trust Region Newton Method optimization
*/
class Tron {
private final Function fun_obj;
private final double eps;
private final int max_iter;
public Tron( final Function fun_obj ) {
this(fun_obj, 0.1);
}
public Tron( final Function fun_obj, double eps ) {
this(fun_obj, eps, 1000);
}
public Tron( final Function fun_obj, double eps, int max_iter ) {
this.fun_obj = fun_obj;
this.eps = eps;
this.max_iter = max_iter;
}
void tron(double[] w) {
// Parameters for updating the iterates.
double eta0 = 1e-4, eta1 = 0.25, eta2 = 0.75;
// Parameters for updating the trust region size delta.
double sigma1 = 0.25, sigma2 = 0.5, sigma3 = 4;
int n = fun_obj.get_nr_variable();
int i, cg_iter;
double delta, snorm, one = 1.0;
double alpha, f, fnew, prered, actred, gs;
int search = 1, iter = 1;
double[] s = new double[n];
double[] r = new double[n];
double[] w_new = new double[n];
double[] g = new double[n];
for (i = 0; i < n; i++)
w[i] = 0;
f = fun_obj.fun(w);
fun_obj.grad(w, g);
delta = euclideanNorm(g);
double gnorm1 = delta;
double gnorm = gnorm1;
if (gnorm <= eps * gnorm1) search = 0;
iter = 1;
while (iter <= max_iter && search != 0) {
cg_iter = trcg(delta, g, s, r);
System.arraycopy(w, 0, w_new, 0, n);
daxpy(one, s, w_new);
gs = dot(g, s);
prered = -0.5 * (gs - dot(s, r));
fnew = fun_obj.fun(w_new);
// Compute the actual reduction.
actred = f - fnew;
// On the first iteration, adjust the initial step bound.
snorm = euclideanNorm(s);
if (iter == 1) delta = Math.min(delta, snorm);
// Compute prediction alpha*snorm of the step.
if (fnew - f - gs <= 0)
alpha = sigma3;
else
alpha = Math.max(sigma1, -0.5 * (gs / (fnew - f - gs)));
// Update the trust region bound according to the ratio of actual to
// predicted reduction.
if (actred < eta0 * prered)
delta = Math.min(Math.max(alpha, sigma1) * snorm, sigma2 * delta);
else if (actred < eta1 * prered)
delta = Math.max(sigma1 * delta, Math.min(alpha * snorm, sigma2 * delta));
else if (actred < eta2 * prered)
delta = Math.max(sigma1 * delta, Math.min(alpha * snorm, sigma3 * delta));
else
delta = Math.max(delta, Math.min(alpha * snorm, sigma3 * delta));
info("iter %2d act %5.3e pre %5.3e delta %5.3e f %5.3e |g| %5.3e CG %3d%n", iter, actred, prered, delta, f, gnorm, cg_iter);
if (actred > eta0 * prered) {
iter++;
System.arraycopy(w_new, 0, w, 0, n);
f = fnew;
fun_obj.grad(w, g);
gnorm = euclideanNorm(g);
if (gnorm <= eps * gnorm1) break;
}
if (f < -1.0e+32) {
info("WARNING: f < -1.0e+32%n");
break;
}
if (Math.abs(actred) <= 0 && prered <= 0) {
info("WARNING: actred and prered <= 0%n");
break;
}
if (Math.abs(actred) <= 1.0e-12 * Math.abs(f) && Math.abs(prered) <= 1.0e-12 * Math.abs(f)) {
info("WARNING: actred and prered too small%n");
break;
}
}
}
private int trcg(double delta, double[] g, double[] s, double[] r) {
int n = fun_obj.get_nr_variable();
double one = 1;
double[] d = new double[n];
double[] Hd = new double[n];
double rTr, rnewTrnew, cgtol;
for (int i = 0; i < n; i++) {
s[i] = 0;
r[i] = -g[i];
d[i] = r[i];
}
cgtol = 0.1 * euclideanNorm(g);
int cg_iter = 0;
rTr = dot(r, r);
while (true) {
if (euclideanNorm(r) <= cgtol) break;
cg_iter++;
fun_obj.Hv(d, Hd);
double alpha = rTr / dot(d, Hd);
daxpy(alpha, d, s);
if (euclideanNorm(s) > delta) {
info("cg reaches trust region boundary%n");
alpha = -alpha;
daxpy(alpha, d, s);
double std = dot(s, d);
double sts = dot(s, s);
double dtd = dot(d, d);
double dsq = delta * delta;
double rad = Math.sqrt(std * std + dtd * (dsq - sts));
if (std >= 0)
alpha = (dsq - sts) / (std + rad);
else
alpha = (rad - std) / dtd;
daxpy(alpha, d, s);
alpha = -alpha;
daxpy(alpha, Hd, r);
break;
}
alpha = -alpha;
daxpy(alpha, Hd, r);
rnewTrnew = dot(r, r);
double beta = rnewTrnew / rTr;
scale(beta, d);
daxpy(one, r, d);
rTr = rnewTrnew;
}
return (cg_iter);
}
/**
* constant times a vector plus a vector
*
* <pre>
* vector2 += constant * vector1
* </pre>
*
* @since 1.8
*/
private static void daxpy(double constant, double vector1[], double vector2[]) {
if (constant == 0) return;
assert vector1.length == vector2.length;
for (int i = 0; i < vector1.length; i++) {
vector2[i] += constant * vector1[i];
}
}
/**
* returns the dot product of two vectors
*
* @since 1.8
*/
private static double dot(double vector1[], double vector2[]) {
double product = 0;
assert vector1.length == vector2.length;
for (int i = 0; i < vector1.length; i++) {
product += vector1[i] * vector2[i];
}
return product;
}
/**
* returns the euclidean norm of a vector
*
* @since 1.8
*/
private static double euclideanNorm(double vector[]) {
int n = vector.length;
if (n < 1) {
return 0;
}
if (n == 1) {
return Math.abs(vector[0]);
}
// this algorithm is (often) more accurate than just summing up the squares and taking the square-root afterwards
double scale = 0; // scaling factor that is factored out
double sum = 1; // basic sum of squares from which scale has been factored out
for (int i = 0; i < n; i++) {
if (vector[i] != 0) {
double abs = Math.abs(vector[i]);
// try to get the best scaling factor
if (scale < abs) {
double t = scale / abs;
sum = 1 + sum * (t * t);
scale = abs;
} else {
double t = abs / scale;
sum += t * t;
}
}
}
return scale * Math.sqrt(sum);
}
/**
* scales a vector by a constant
*
* @since 1.8
*/
private static void scale(double constant, double vector[]) {
if (constant == 1.0) return;
for (int i = 0; i < vector.length; i++) {
vector[i] *= constant;
}
}
}
| Java |
/*
Copyright IBM Corp. 2016 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 rawledger
import (
cb "github.com/hyperledger/fabric/protos/common"
ab "github.com/hyperledger/fabric/protos/orderer"
)
// Iterator is useful for a chain Reader to stream blocks as they are created
type Iterator interface {
// Next blocks until there is a new block available, or returns an error if the next block is no longer retrievable
Next() (*cb.Block, cb.Status)
// ReadyChan supplies a channel which will block until Next will not block
ReadyChan() <-chan struct{}
}
// Reader allows the caller to inspect the raw ledger
type Reader interface {
// Iterator retrieves an Iterator, as specified by an cb.SeekInfo message, returning an iterator, and it's starting block number
Iterator(startType ab.SeekInfo_StartType, specified uint64) (Iterator, uint64)
// Height returns the highest block number in the chain, plus one
Height() uint64
}
// Writer allows the caller to modify the raw ledger
type Writer interface {
// Append a new block to the ledger
Append(blockContents []*cb.Envelope, proof []byte) *cb.Block
}
// ReadWriter encapsulated both the reading and writing functions of the rawledger
type ReadWriter interface {
Reader
Writer
}
| Java |
package geotrellis.test.multiband.cassandra
import geotrellis.config.Dataset
import geotrellis.raster.MultibandTile
import geotrellis.spark._
import geotrellis.spark.io._
import geotrellis.test.CassandraTest
import geotrellis.test.multiband.load.HadoopLoad
import geotrellis.vector.ProjectedExtent
import org.apache.spark.SparkContext
abstract class HadoopIngestTest(dataset: Dataset) extends CassandraTest[ProjectedExtent, SpatialKey, MultibandTile](dataset) with HadoopLoad
object HadoopIngestTest {
def apply(implicit dataset: Dataset, _sc: SparkContext) = new HadoopIngestTest(dataset) {
@transient implicit val sc = _sc
}
}
| Java |
<!-- BEGIN MUNGE: UNVERSIONED_WARNING -->
<!-- END MUNGE: UNVERSIONED_WARNING -->
# Kubernetes Multi-AZ Clusters
## (previously nicknamed "Ubernetes-Lite")
## Introduction
Full Cluster Federation will offer sophisticated federation between multiple kubernetes
clusters, offering true high-availability, multiple provider support &
cloud-bursting, multiple region support etc. However, many users have
expressed a desire for a "reasonably" high-available cluster, that runs in
multiple zones on GCE or availability zones in AWS, and can tolerate the failure
of a single zone without the complexity of running multiple clusters.
Multi-AZ Clusters aim to deliver exactly that functionality: to run a single
Kubernetes cluster in multiple zones. It will attempt to make reasonable
scheduling decisions, in particular so that a replication controller's pods are
spread across zones, and it will try to be aware of constraints - for example
that a volume cannot be mounted on a node in a different zone.
Multi-AZ Clusters are deliberately limited in scope; for many advanced functions
the answer will be "use full Cluster Federation". For example, multiple-region
support is not in scope. Routing affinity (e.g. so that a webserver will
prefer to talk to a backend service in the same zone) is similarly not in
scope.
## Design
These are the main requirements:
1. kube-up must allow bringing up a cluster that spans multiple zones.
1. pods in a replication controller should attempt to spread across zones.
1. pods which require volumes should not be scheduled onto nodes in a different zone.
1. load-balanced services should work reasonably
### kube-up support
kube-up support for multiple zones will initially be considered
advanced/experimental functionality, so the interface is not initially going to
be particularly user-friendly. As we design the evolution of kube-up, we will
make multiple zones better supported.
For the initial implementation, kube-up must be run multiple times, once for
each zone. The first kube-up will take place as normal, but then for each
additional zone the user must run kube-up again, specifying
`KUBE_USE_EXISTING_MASTER=true` and `KUBE_SUBNET_CIDR=172.20.x.0/24`. This will then
create additional nodes in a different zone, but will register them with the
existing master.
### Zone spreading
This will be implemented by modifying the existing scheduler priority function
`SelectorSpread`. Currently this priority function aims to put pods in an RC
on different hosts, but it will be extended first to spread across zones, and
then to spread across hosts.
So that the scheduler does not need to call out to the cloud provider on every
scheduling decision, we must somehow record the zone information for each node.
The implementation of this will be described in the implementation section.
Note that zone spreading is 'best effort'; zones are just be one of the factors
in making scheduling decisions, and thus it is not guaranteed that pods will
spread evenly across zones. However, this is likely desirable: if a zone is
overloaded or failing, we still want to schedule the requested number of pods.
### Volume affinity
Most cloud providers (at least GCE and AWS) cannot attach their persistent
volumes across zones. Thus when a pod is being scheduled, if there is a volume
attached, that will dictate the zone. This will be implemented using a new
scheduler predicate (a hard constraint): `VolumeZonePredicate`.
When `VolumeZonePredicate` observes a pod scheduling request that includes a
volume, if that volume is zone-specific, `VolumeZonePredicate` will exclude any
nodes not in that zone.
Again, to avoid the scheduler calling out to the cloud provider, this will rely
on information attached to the volumes. This means that this will only support
PersistentVolumeClaims, because direct mounts do not have a place to attach
zone information. PersistentVolumes will then include zone information where
volumes are zone-specific.
### Load-balanced services should operate reasonably
For both AWS & GCE, Kubernetes creates a native cloud load-balancer for each
service of type LoadBalancer. The native cloud load-balancers on both AWS &
GCE are region-level, and support load-balancing across instances in multiple
zones (in the same region). For both clouds, the behaviour of the native cloud
load-balancer is reasonable in the face of failures (indeed, this is why clouds
provide load-balancing as a primitve).
For multi-AZ clusters we will therefore simply rely on the native cloud provider
load balancer behaviour, and we do not anticipate substantial code changes.
One notable shortcoming here is that load-balanced traffic still goes through
kube-proxy controlled routing, and kube-proxy does not (currently) favor
targeting a pod running on the same instance or even the same zone. This will
likely produce a lot of unnecessary cross-zone traffic (which is likely slower
and more expensive). This might be sufficiently low-hanging fruit that we
choose to address it in kube-proxy / multi-AZ clusters, but this can be addressed
after the initial implementation.
## Implementation
The main implementation points are:
1. how to attach zone information to Nodes and PersistentVolumes
1. how nodes get zone information
1. how volumes get zone information
### Attaching zone information
We must attach zone information to Nodes and PersistentVolumes, and possibly to
other resources in future. There are two obvious alternatives: we can use
labels/annotations, or we can extend the schema to include the information.
For the initial implementation, we propose to use labels. The reasoning is:
1. It is considerably easier to implement.
1. We will reserve the two labels `failure-domain.alpha.kubernetes.io/zone` and
`failure-domain.alpha.kubernetes.io/region` for the two pieces of information
we need. By putting this under the `kubernetes.io` namespace there is no risk
of collision, and by putting it under `alpha.kubernetes.io` we clearly mark
this as an experimental feature.
1. We do not yet know whether these labels will be sufficient for all
environments, nor which entities will require zone information. Labels give us
more flexibility here.
1. Because the labels are reserved, we can move to schema-defined fields in
future using our cross-version mapping techniques.
### Node labeling
We do not want to require an administrator to manually label nodes. We instead
modify the kubelet to include the appropriate labels when it registers itself.
The information is easily obtained by the kubelet from the cloud provider.
### Volume labeling
As with nodes, we do not want to require an administrator to manually label
volumes. We will create an admission controller `PersistentVolumeLabel`.
`PersistentVolumeLabel` will intercept requests to create PersistentVolumes,
and will label them appropriately by calling in to the cloud provider.
## AWS Specific Considerations
The AWS implementation here is fairly straightforward. The AWS API is
region-wide, meaning that a single call will find instances and volumes in all
zones. In addition, instance ids and volume ids are unique per-region (and
hence also per-zone). I believe they are actually globally unique, but I do
not know if this is guaranteed; in any case we only need global uniqueness if
we are to span regions, which will not be supported by multi-AZ clusters (to do
that correctly requires a full Cluster Federation type approach).
## GCE Specific Considerations
The GCE implementation is more complicated than the AWS implementation because
GCE APIs are zone-scoped. To perform an operation, we must perform one REST
call per zone and combine the results, unless we can determine in advance that
an operation references a particular zone. For many operations, we can make
that determination, but in some cases - such as listing all instances, we must
combine results from calls in all relevant zones.
A further complexity is that GCE volume names are scoped per-zone, not
per-region. Thus it is permitted to have two volumes both named `myvolume` in
two different GCE zones. (Instance names are currently unique per-region, and
thus are not a problem for multi-AZ clusters).
The volume scoping leads to a (small) behavioural change for multi-AZ clusters on
GCE. If you had two volumes both named `myvolume` in two different GCE zones,
this would not be ambiguous when Kubernetes is operating only in a single zone.
But, when operating a cluster across multiple zones, `myvolume` is no longer
sufficient to specify a volume uniquely. Worse, the fact that a volume happens
to be unambigious at a particular time is no guarantee that it will continue to
be unambigious in future, because a volume with the same name could
subsequently be created in a second zone. While perhaps unlikely in practice,
we cannot automatically enable multi-AZ clusters for GCE users if this then causes
volume mounts to stop working.
This suggests that (at least on GCE), multi-AZ clusters must be optional (i.e.
there must be a feature-flag). It may be that we can make this feature
semi-automatic in future, by detecting whether nodes are running in multiple
zones, but it seems likely that kube-up could instead simply set this flag.
For the initial implementation, creating volumes with identical names will
yield undefined results. Later, we may add some way to specify the zone for a
volume (and possibly require that volumes have their zone specified when
running in multi-AZ cluster mode). We could add a new `zone` field to the
PersistentVolume type for GCE PD volumes, or we could use a DNS-style dotted
name for the volume name (<name>.<zone>)
Initially therefore, the GCE changes will be to:
1. change kube-up to support creation of a cluster in multiple zones
1. pass a flag enabling multi-AZ clusters with kube-up
1. change the kubernetes cloud provider to iterate through relevant zones when resolving items
1. tag GCE PD volumes with the appropriate zone information
<!-- BEGIN MUNGE: IS_VERSIONED -->
<!-- TAG IS_VERSIONED -->
<!-- END MUNGE: IS_VERSIONED -->
<!-- BEGIN MUNGE: GENERATED_ANALYTICS -->
[]()
<!-- END MUNGE: GENERATED_ANALYTICS -->
| Java |
/* Copyright 2015 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.
==============================================================================*/
#ifndef TENSORFLOW_CORE_UTIL_UTIL_H_
#define TENSORFLOW_CORE_UTIL_UTIL_H_
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/lib/core/stringpiece.h"
namespace tensorflow {
// If op_name has '/' in it, then return everything before the first '/'.
// Otherwise return empty string.
StringPiece NodeNamePrefix(const StringPiece& op_name);
// If op_name has '/' in it, then return everything before the last '/'.
// Otherwise return empty string.
StringPiece NodeNameFullPrefix(const StringPiece& op_name);
class MovingAverage {
public:
explicit MovingAverage(int window);
~MovingAverage();
void Clear();
double GetAverage() const;
void AddValue(double v);
private:
const int window_; // Max size of interval
double sum_; // Sum over interval
double* data_; // Actual data values
int head_; // Offset of the newest statistic in data_
int count_; // # of valid data elements in window
};
// Returns a string printing bytes in ptr[0..n). The output looks
// like "00 01 ef cd cd ef".
string PrintMemory(const char* ptr, size_t n);
// Given a flattened index into a tensor, computes a string s so that
// StrAppend("tensor", s) is a Python indexing expression. E.g.,
// "tensor", "tensor[i]", "tensor[i, j]", etc.
string SliceDebugString(const TensorShape& shape, const int64 flat);
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_UTIL_H_
| Java |
/*
* Copyright 2000-2016 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.impl.source.xml;
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.PsiElement;
import com.intellij.psi.XmlElementFactory;
import com.intellij.psi.impl.source.xml.behavior.DefaultXmlPsiPolicy;
import com.intellij.psi.search.PsiElementProcessor;
import com.intellij.psi.xml.*;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class XmlTagValueImpl implements XmlTagValue{
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.source.xml.XmlTagValueImpl");
private final XmlTag myTag;
private final XmlTagChild[] myElements;
private volatile XmlText[] myTextElements;
private volatile String myText;
private volatile String myTrimmedText;
public XmlTagValueImpl(@NotNull XmlTagChild[] bodyElements, @NotNull XmlTag tag) {
myTag = tag;
myElements = bodyElements;
}
@Override
@NotNull
public XmlTagChild[] getChildren() {
return myElements;
}
@Override
@NotNull
public XmlText[] getTextElements() {
XmlText[] textElements = myTextElements;
if (textElements == null) {
textElements = Arrays.stream(myElements)
.filter(element -> element instanceof XmlText)
.map(element -> (XmlText)element).toArray(XmlText[]::new);
myTextElements = textElements = textElements.length == 0 ? XmlText.EMPTY_ARRAY : textElements;
}
return textElements;
}
@Override
@NotNull
public String getText() {
String text = myText;
if (text == null) {
final StringBuilder consolidatedText = new StringBuilder();
for (final XmlTagChild element : myElements) {
consolidatedText.append(element.getText());
}
myText = text = consolidatedText.toString();
}
return text;
}
@Override
@NotNull
public TextRange getTextRange() {
if(myElements.length == 0){
final ASTNode child = XmlChildRole.START_TAG_END_FINDER.findChild( (ASTNode)myTag);
if(child != null)
return new TextRange(child.getStartOffset() + 1, child.getStartOffset() + 1);
return new TextRange(myTag.getTextRange().getEndOffset(), myTag.getTextRange().getEndOffset());
}
return new TextRange(myElements[0].getTextRange().getStartOffset(), myElements[myElements.length - 1].getTextRange().getEndOffset());
}
@Override
@NotNull
public String getTrimmedText() {
String trimmedText = myTrimmedText;
if (trimmedText == null) {
final StringBuilder consolidatedText = new StringBuilder();
final XmlText[] textElements = getTextElements();
for (final XmlText textElement : textElements) {
consolidatedText.append(textElement.getValue());
}
myTrimmedText = trimmedText = consolidatedText.toString().trim();
}
return trimmedText;
}
@Override
public void setText(String value) {
setText(value, false);
}
@Override
public void setEscapedText(String value) {
setText(value, true);
}
private void setText(String value, boolean defaultPolicy) {
try {
XmlText text = null;
if (value != null) {
final XmlText[] texts = getTextElements();
if (texts.length == 0) {
text = (XmlText)myTag.add(XmlElementFactory.getInstance(myTag.getProject()).createDisplayText("x"));
} else {
text = texts[0];
}
if (StringUtil.isEmpty(value)) {
text.delete();
}
else {
if (defaultPolicy && text instanceof XmlTextImpl) {
((XmlTextImpl)text).doSetValue(value, new DefaultXmlPsiPolicy());
} else {
text.setValue(value);
}
}
}
if(myElements.length > 0){
for (final XmlTagChild child : myElements) {
if (child != text) {
child.delete();
}
}
}
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
}
@Override
public boolean hasCDATA() {
for (XmlText xmlText : getTextElements()) {
PsiElement[] children = xmlText.getChildren();
for (PsiElement child : children) {
if (child.getNode().getElementType() == XmlElementType.XML_CDATA) {
return true;
}
}
}
return false;
}
public static XmlTagValue createXmlTagValue(XmlTag tag) {
final List<XmlTagChild> bodyElements = new ArrayList<>();
tag.processElements(new PsiElementProcessor() {
boolean insideBody;
@Override
public boolean execute(@NotNull PsiElement element) {
final ASTNode treeElement = element.getNode();
if (insideBody) {
if (treeElement != null && treeElement.getElementType() == XmlTokenType.XML_END_TAG_START) return false;
if (!(element instanceof XmlTagChild)) return true;
bodyElements.add((XmlTagChild)element);
}
else if (treeElement != null && treeElement.getElementType() == XmlTokenType.XML_TAG_END) insideBody = true;
return true;
}
}, tag);
XmlTagChild[] tagChildren = bodyElements.toArray(XmlTagChild.EMPTY_ARRAY);
return new XmlTagValueImpl(tagChildren, tag);
}
}
| Java |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.syncope.core.spring.security;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.security.auth.login.AccountNotFoundException;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.lang3.tuple.Triple;
import org.apache.syncope.common.keymaster.client.api.ConfParamOps;
import org.apache.syncope.common.lib.SyncopeConstants;
import org.apache.syncope.common.lib.types.AnyTypeKind;
import org.apache.syncope.common.lib.types.AuditElements;
import org.apache.syncope.common.lib.types.EntitlementsHolder;
import org.apache.syncope.common.lib.types.IdRepoEntitlement;
import org.apache.syncope.core.persistence.api.ImplementationLookup;
import org.apache.syncope.core.persistence.api.dao.AccessTokenDAO;
import org.apache.syncope.core.persistence.api.dao.AnySearchDAO;
import org.apache.syncope.core.persistence.api.entity.AnyType;
import org.apache.syncope.core.persistence.api.entity.resource.Provision;
import org.apache.syncope.core.provisioning.api.utils.RealmUtils;
import org.apache.syncope.core.persistence.api.dao.AnyTypeDAO;
import org.apache.syncope.core.persistence.api.dao.DelegationDAO;
import org.apache.syncope.core.persistence.api.dao.GroupDAO;
import org.apache.syncope.core.persistence.api.dao.RealmDAO;
import org.apache.syncope.core.persistence.api.dao.RoleDAO;
import org.apache.syncope.core.persistence.api.dao.UserDAO;
import org.apache.syncope.core.persistence.api.dao.search.AttrCond;
import org.apache.syncope.core.persistence.api.dao.search.SearchCond;
import org.apache.syncope.core.persistence.api.entity.AccessToken;
import org.apache.syncope.core.persistence.api.entity.Delegation;
import org.apache.syncope.core.persistence.api.entity.DynRealm;
import org.apache.syncope.core.persistence.api.entity.Realm;
import org.apache.syncope.core.persistence.api.entity.Role;
import org.apache.syncope.core.persistence.api.entity.resource.ExternalResource;
import org.apache.syncope.core.persistence.api.entity.user.User;
import org.apache.syncope.core.provisioning.api.AuditManager;
import org.apache.syncope.core.provisioning.api.ConnectorManager;
import org.apache.syncope.core.provisioning.api.MappingManager;
import org.apache.syncope.core.spring.ApplicationContextProvider;
import org.identityconnectors.framework.common.objects.Uid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;
import org.springframework.transaction.annotation.Transactional;
/**
* Domain-sensible (via {@code @Transactional}) access to authentication / authorization data.
*
* @see JWTAuthenticationProvider
* @see UsernamePasswordAuthenticationProvider
* @see SyncopeAuthenticationDetails
*/
public class AuthDataAccessor {
protected static final Logger LOG = LoggerFactory.getLogger(AuthDataAccessor.class);
public static final String GROUP_OWNER_ROLE = "GROUP_OWNER";
protected static final Encryptor ENCRYPTOR = Encryptor.getInstance();
protected static final Set<SyncopeGrantedAuthority> ANONYMOUS_AUTHORITIES =
Set.of(new SyncopeGrantedAuthority(IdRepoEntitlement.ANONYMOUS));
protected static final Set<SyncopeGrantedAuthority> MUST_CHANGE_PASSWORD_AUTHORITIES =
Set.of(new SyncopeGrantedAuthority(IdRepoEntitlement.MUST_CHANGE_PASSWORD));
protected final SecurityProperties securityProperties;
protected final RealmDAO realmDAO;
protected final UserDAO userDAO;
protected final GroupDAO groupDAO;
protected final AnyTypeDAO anyTypeDAO;
protected final AnySearchDAO anySearchDAO;
protected final AccessTokenDAO accessTokenDAO;
protected final ConfParamOps confParamOps;
protected final RoleDAO roleDAO;
protected final DelegationDAO delegationDAO;
protected final ConnectorManager connectorManager;
protected final AuditManager auditManager;
protected final MappingManager mappingManager;
protected final ImplementationLookup implementationLookup;
private Map<String, JWTSSOProvider> jwtSSOProviders;
public AuthDataAccessor(
final SecurityProperties securityProperties,
final RealmDAO realmDAO,
final UserDAO userDAO,
final GroupDAO groupDAO,
final AnyTypeDAO anyTypeDAO,
final AnySearchDAO anySearchDAO,
final AccessTokenDAO accessTokenDAO,
final ConfParamOps confParamOps,
final RoleDAO roleDAO,
final DelegationDAO delegationDAO,
final ConnectorManager connectorManager,
final AuditManager auditManager,
final MappingManager mappingManager,
final ImplementationLookup implementationLookup) {
this.securityProperties = securityProperties;
this.realmDAO = realmDAO;
this.userDAO = userDAO;
this.groupDAO = groupDAO;
this.anyTypeDAO = anyTypeDAO;
this.anySearchDAO = anySearchDAO;
this.accessTokenDAO = accessTokenDAO;
this.confParamOps = confParamOps;
this.roleDAO = roleDAO;
this.delegationDAO = delegationDAO;
this.connectorManager = connectorManager;
this.auditManager = auditManager;
this.mappingManager = mappingManager;
this.implementationLookup = implementationLookup;
}
public JWTSSOProvider getJWTSSOProvider(final String issuer) {
synchronized (this) {
if (jwtSSOProviders == null) {
jwtSSOProviders = new HashMap<>();
implementationLookup.getJWTSSOProviderClasses().stream().
map(clazz -> (JWTSSOProvider) ApplicationContextProvider.getBeanFactory().
createBean(clazz, AbstractBeanDefinition.AUTOWIRE_BY_TYPE, true)).
forEach(jwtSSOProvider -> jwtSSOProviders.put(jwtSSOProvider.getIssuer(), jwtSSOProvider));
}
}
if (issuer == null) {
throw new AuthenticationCredentialsNotFoundException("A null issuer is not permitted");
}
JWTSSOProvider provider = jwtSSOProviders.get(issuer);
if (provider == null) {
throw new AuthenticationCredentialsNotFoundException(
"Could not find any registered JWTSSOProvider for issuer " + issuer);
}
return provider;
}
protected String getDelegationKey(final SyncopeAuthenticationDetails details, final String delegatedKey) {
if (details.getDelegatedBy() == null) {
return null;
}
String delegatingKey = SyncopeConstants.UUID_PATTERN.matcher(details.getDelegatedBy()).matches()
? details.getDelegatedBy()
: userDAO.findKey(details.getDelegatedBy());
if (delegatingKey == null) {
throw new SessionAuthenticationException(
"Delegating user " + details.getDelegatedBy() + " cannot be found");
}
LOG.debug("Delegation request: delegating:{}, delegated:{}", delegatingKey, delegatedKey);
return delegationDAO.findValidFor(delegatingKey, delegatedKey).
orElseThrow(() -> new SessionAuthenticationException(
"Delegation by " + delegatingKey + " was requested but none found"));
}
/**
* Attempts to authenticate the given credentials against internal storage and pass-through resources (if
* configured): the first succeeding causes global success.
*
* @param domain domain
* @param authentication given credentials
* @return {@code null} if no matching user was found, authentication result otherwise
*/
@Transactional(noRollbackFor = DisabledException.class)
public Triple<User, Boolean, String> authenticate(final String domain, final Authentication authentication) {
User user = null;
String[] authAttrValues = confParamOps.get(
domain, "authentication.attributes", new String[] { "username" }, String[].class);
for (int i = 0; user == null && i < authAttrValues.length; i++) {
if ("username".equals(authAttrValues[i])) {
user = userDAO.findByUsername(authentication.getName());
} else {
AttrCond attrCond = new AttrCond(AttrCond.Type.EQ);
attrCond.setSchema(authAttrValues[i]);
attrCond.setExpression(authentication.getName());
try {
List<User> users = anySearchDAO.search(SearchCond.getLeaf(attrCond), AnyTypeKind.USER);
if (users.size() == 1) {
user = users.get(0);
} else {
LOG.warn("Search condition {} does not uniquely match a user", attrCond);
}
} catch (IllegalArgumentException e) {
LOG.error("While searching user for authentication via {}", attrCond, e);
}
}
}
Boolean authenticated = null;
String delegationKey = null;
if (user != null) {
authenticated = false;
if (user.isSuspended() != null && user.isSuspended()) {
throw new DisabledException("User " + user.getUsername() + " is suspended");
}
String[] authStatuses = confParamOps.get(
domain, "authentication.statuses", new String[] {}, String[].class);
if (!ArrayUtils.contains(authStatuses, user.getStatus())) {
throw new DisabledException("User " + user.getUsername() + " not allowed to authenticate");
}
boolean userModified = false;
authenticated = authenticate(user, authentication.getCredentials().toString());
if (authenticated) {
delegationKey = getDelegationKey(
SyncopeAuthenticationDetails.class.cast(authentication.getDetails()), user.getKey());
if (confParamOps.get(domain, "log.lastlogindate", true, Boolean.class)) {
user.setLastLoginDate(new Date());
userModified = true;
}
if (user.getFailedLogins() != 0) {
user.setFailedLogins(0);
userModified = true;
}
} else {
user.setFailedLogins(user.getFailedLogins() + 1);
userModified = true;
}
if (userModified) {
userDAO.save(user);
}
}
return Triple.of(user, authenticated, delegationKey);
}
protected boolean authenticate(final User user, final String password) {
boolean authenticated = ENCRYPTOR.verify(password, user.getCipherAlgorithm(), user.getPassword());
LOG.debug("{} authenticated on internal storage: {}", user.getUsername(), authenticated);
for (Iterator<? extends ExternalResource> itor = getPassthroughResources(user).iterator();
itor.hasNext() && !authenticated;) {
ExternalResource resource = itor.next();
String connObjectKey = null;
try {
AnyType userType = anyTypeDAO.findUser();
Provision provision = resource.getProvision(userType).
orElseThrow(() -> new AccountNotFoundException(
"Unable to locate provision for user type " + userType.getKey()));
connObjectKey = mappingManager.getConnObjectKeyValue(user, provision).
orElseThrow(() -> new AccountNotFoundException(
"Unable to locate conn object key value for " + userType.getKey()));
Uid uid = connectorManager.getConnector(resource).authenticate(connObjectKey, password, null);
if (uid != null) {
authenticated = true;
}
} catch (Exception e) {
LOG.debug("Could not authenticate {} on {}", user.getUsername(), resource.getKey(), e);
}
LOG.debug("{} authenticated on {} as {}: {}",
user.getUsername(), resource.getKey(), connObjectKey, authenticated);
}
return authenticated;
}
protected Set<? extends ExternalResource> getPassthroughResources(final User user) {
Set<? extends ExternalResource> result = null;
// 1. look for assigned resources, pick the ones whose account policy has authentication resources
for (ExternalResource resource : userDAO.findAllResources(user)) {
if (resource.getAccountPolicy() != null && !resource.getAccountPolicy().getResources().isEmpty()) {
if (result == null) {
result = resource.getAccountPolicy().getResources();
} else {
result.retainAll(resource.getAccountPolicy().getResources());
}
}
}
// 2. look for realms, pick the ones whose account policy has authentication resources
for (Realm realm : realmDAO.findAncestors(user.getRealm())) {
if (realm.getAccountPolicy() != null && !realm.getAccountPolicy().getResources().isEmpty()) {
if (result == null) {
result = realm.getAccountPolicy().getResources();
} else {
result.retainAll(realm.getAccountPolicy().getResources());
}
}
}
return result == null ? Set.of() : result;
}
protected Set<SyncopeGrantedAuthority> getAdminAuthorities() {
return EntitlementsHolder.getInstance().getValues().stream().
map(entitlement -> new SyncopeGrantedAuthority(entitlement, SyncopeConstants.ROOT_REALM)).
collect(Collectors.toSet());
}
protected Set<SyncopeGrantedAuthority> buildAuthorities(final Map<String, Set<String>> entForRealms) {
Set<SyncopeGrantedAuthority> authorities = new HashSet<>();
entForRealms.forEach((entitlement, realms) -> {
Pair<Set<String>, Set<String>> normalized = RealmUtils.normalize(realms);
SyncopeGrantedAuthority authority = new SyncopeGrantedAuthority(entitlement);
authority.addRealms(normalized.getLeft());
authority.addRealms(normalized.getRight());
authorities.add(authority);
});
return authorities;
}
protected Set<SyncopeGrantedAuthority> getUserAuthorities(final User user) {
if (user.isMustChangePassword()) {
return MUST_CHANGE_PASSWORD_AUTHORITIES;
}
Map<String, Set<String>> entForRealms = new HashMap<>();
// Give entitlements as assigned by roles (with static or dynamic realms, where applicable) - assigned
// either statically and dynamically
userDAO.findAllRoles(user).stream().
filter(role -> !GROUP_OWNER_ROLE.equals(role.getKey())).
forEach(role -> role.getEntitlements().forEach(entitlement -> {
Set<String> realms = Optional.ofNullable(entForRealms.get(entitlement)).orElseGet(() -> {
Set<String> r = new HashSet<>();
entForRealms.put(entitlement, r);
return r;
});
realms.addAll(role.getRealms().stream().map(Realm::getFullPath).collect(Collectors.toSet()));
if (!entitlement.endsWith("_CREATE") && !entitlement.endsWith("_DELETE")) {
realms.addAll(role.getDynRealms().stream().map(DynRealm::getKey).collect(Collectors.toList()));
}
}));
// Give group entitlements for owned groups
groupDAO.findOwnedByUser(user.getKey()).forEach(group -> {
Role groupOwnerRole = roleDAO.find(GROUP_OWNER_ROLE);
if (groupOwnerRole == null) {
LOG.warn("Role {} was not found", GROUP_OWNER_ROLE);
} else {
groupOwnerRole.getEntitlements().forEach(entitlement -> {
Set<String> realms = Optional.ofNullable(entForRealms.get(entitlement)).orElseGet(() -> {
HashSet<String> r = new HashSet<>();
entForRealms.put(entitlement, r);
return r;
});
realms.add(RealmUtils.getGroupOwnerRealm(group.getRealm().getFullPath(), group.getKey()));
});
}
});
return buildAuthorities(entForRealms);
}
protected Set<SyncopeGrantedAuthority> getDelegatedAuthorities(final Delegation delegation) {
Map<String, Set<String>> entForRealms = new HashMap<>();
delegation.getRoles().stream().filter(role -> !GROUP_OWNER_ROLE.equals(role.getKey())).
forEach(role -> role.getEntitlements().forEach(entitlement -> {
Set<String> realms = Optional.ofNullable(entForRealms.get(entitlement)).orElseGet(() -> {
HashSet<String> r = new HashSet<>();
entForRealms.put(entitlement, r);
return r;
});
realms.addAll(role.getRealms().stream().map(Realm::getFullPath).collect(Collectors.toSet()));
if (!entitlement.endsWith("_CREATE") && !entitlement.endsWith("_DELETE")) {
realms.addAll(role.getDynRealms().stream().map(DynRealm::getKey).collect(Collectors.toList()));
}
}));
return buildAuthorities(entForRealms);
}
@Transactional
public Set<SyncopeGrantedAuthority> getAuthorities(final String username, final String delegationKey) {
Set<SyncopeGrantedAuthority> authorities;
if (securityProperties.getAnonymousUser().equals(username)) {
authorities = ANONYMOUS_AUTHORITIES;
} else if (securityProperties.getAdminUser().equals(username)) {
authorities = getAdminAuthorities();
} else if (delegationKey != null) {
Delegation delegation = Optional.ofNullable(delegationDAO.find(delegationKey)).
orElseThrow(() -> new UsernameNotFoundException(
"Could not find delegation " + delegationKey));
authorities = delegation.getRoles().isEmpty()
? getUserAuthorities(delegation.getDelegating())
: getDelegatedAuthorities(delegation);
} else {
User user = Optional.ofNullable(userDAO.findByUsername(username)).
orElseThrow(() -> new UsernameNotFoundException(
"Could not find any user with username " + username));
authorities = getUserAuthorities(user);
}
return authorities;
}
@Transactional
public Pair<String, Set<SyncopeGrantedAuthority>> authenticate(final JWTAuthentication authentication) {
String username;
Set<SyncopeGrantedAuthority> authorities;
if (securityProperties.getAdminUser().equals(authentication.getClaims().getSubject())) {
AccessToken accessToken = accessTokenDAO.find(authentication.getClaims().getJWTID());
if (accessToken == null) {
throw new AuthenticationCredentialsNotFoundException(
"Could not find an Access Token for JWT " + authentication.getClaims().getJWTID());
}
username = securityProperties.getAdminUser();
authorities = getAdminAuthorities();
} else {
JWTSSOProvider jwtSSOProvider = getJWTSSOProvider(authentication.getClaims().getIssuer());
Pair<User, Set<SyncopeGrantedAuthority>> resolved = jwtSSOProvider.resolve(authentication.getClaims());
if (resolved == null || resolved.getLeft() == null) {
throw new AuthenticationCredentialsNotFoundException(
"Could not find User " + authentication.getClaims().getSubject()
+ " for JWT " + authentication.getClaims().getJWTID());
}
User user = resolved.getLeft();
String delegationKey = getDelegationKey(authentication.getDetails(), user.getKey());
username = user.getUsername();
authorities = resolved.getRight() == null
? Set.of()
: delegationKey == null
? resolved.getRight()
: getAuthorities(username, delegationKey);
LOG.debug("JWT {} issued by {} resolved to User {} with authorities {}",
authentication.getClaims().getJWTID(),
authentication.getClaims().getIssuer(),
username + Optional.ofNullable(delegationKey).
map(d -> " [under delegation " + delegationKey + "]").orElse(StringUtils.EMPTY),
authorities);
if (BooleanUtils.isTrue(user.isSuspended())) {
throw new DisabledException("User " + username + " is suspended");
}
List<String> authStatuses = List.of(confParamOps.get(authentication.getDetails().getDomain(),
"authentication.statuses", new String[] {}, String[].class));
if (!authStatuses.contains(user.getStatus())) {
throw new DisabledException("User " + username + " not allowed to authenticate");
}
if (BooleanUtils.isTrue(user.isMustChangePassword())) {
LOG.debug("User {} must change password, resetting authorities", username);
authorities = MUST_CHANGE_PASSWORD_AUTHORITIES;
}
}
return Pair.of(username, authorities);
}
@Transactional
public void removeExpired(final String tokenKey) {
accessTokenDAO.delete(tokenKey);
}
@Transactional(readOnly = true)
public void audit(
final String username,
final String delegationKey,
final AuditElements.Result result,
final Object output,
final Object... input) {
auditManager.audit(
username + Optional.ofNullable(delegationKey).
map(d -> " [under delegation " + delegationKey + "]").orElse(StringUtils.EMPTY),
AuditElements.EventCategoryType.LOGIC, AuditElements.AUTHENTICATION_CATEGORY, null,
AuditElements.LOGIN_EVENT, result, null, output, input);
}
}
| Java |
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use core::prelude::*;
use io::prelude::*;
use os::unix::prelude::*;
use ffi::{self, CString, OsString, AsOsStr, OsStr};
use io::{self, Error, Seek, SeekFrom};
use libc::{self, c_int, c_void, size_t, off_t, c_char, mode_t};
use mem;
use path::{Path, PathBuf};
use ptr;
use rc::Rc;
use sys::fd::FileDesc;
use sys::{c, cvt, cvt_r};
use sys_common::FromInner;
use vec::Vec;
pub struct File(FileDesc);
pub struct FileAttr {
stat: libc::stat,
}
pub struct ReadDir {
dirp: *mut libc::DIR,
root: Rc<PathBuf>,
}
pub struct DirEntry {
buf: Vec<u8>,
dirent: *mut libc::dirent_t,
root: Rc<PathBuf>,
}
#[derive(Clone)]
pub struct OpenOptions {
flags: c_int,
read: bool,
write: bool,
mode: mode_t,
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct FilePermissions { mode: mode_t }
impl FileAttr {
pub fn is_dir(&self) -> bool {
(self.stat.st_mode as mode_t) & libc::S_IFMT == libc::S_IFDIR
}
pub fn is_file(&self) -> bool {
(self.stat.st_mode as mode_t) & libc::S_IFMT == libc::S_IFREG
}
pub fn size(&self) -> u64 { self.stat.st_size as u64 }
pub fn perm(&self) -> FilePermissions {
FilePermissions { mode: (self.stat.st_mode as mode_t) & 0o777 }
}
pub fn accessed(&self) -> u64 {
self.mktime(self.stat.st_atime as u64, self.stat.st_atime_nsec as u64)
}
pub fn modified(&self) -> u64 {
self.mktime(self.stat.st_mtime as u64, self.stat.st_mtime_nsec as u64)
}
// times are in milliseconds (currently)
fn mktime(&self, secs: u64, nsecs: u64) -> u64 {
secs * 1000 + nsecs / 1000000
}
}
impl FilePermissions {
pub fn readonly(&self) -> bool { self.mode & 0o222 == 0 }
pub fn set_readonly(&mut self, readonly: bool) {
if readonly {
self.mode &= !0o222;
} else {
self.mode |= 0o222;
}
}
}
impl FromInner<i32> for FilePermissions {
fn from_inner(mode: i32) -> FilePermissions {
FilePermissions { mode: mode as mode_t }
}
}
impl Iterator for ReadDir {
type Item = io::Result<DirEntry>;
fn next(&mut self) -> Option<io::Result<DirEntry>> {
extern {
fn rust_dirent_t_size() -> c_int;
}
let mut buf: Vec<u8> = Vec::with_capacity(unsafe {
rust_dirent_t_size() as usize
});
let ptr = buf.as_mut_ptr() as *mut libc::dirent_t;
let mut entry_ptr = ptr::null_mut();
loop {
if unsafe { libc::readdir_r(self.dirp, ptr, &mut entry_ptr) != 0 } {
return Some(Err(Error::last_os_error()))
}
if entry_ptr.is_null() {
return None
}
let entry = DirEntry {
buf: buf,
dirent: entry_ptr,
root: self.root.clone()
};
if entry.name_bytes() == b"." || entry.name_bytes() == b".." {
buf = entry.buf;
} else {
return Some(Ok(entry))
}
}
}
}
impl Drop for ReadDir {
fn drop(&mut self) {
let r = unsafe { libc::closedir(self.dirp) };
debug_assert_eq!(r, 0);
}
}
impl DirEntry {
pub fn path(&self) -> PathBuf {
self.root.join(<OsStr as OsStrExt>::from_bytes(self.name_bytes()))
}
fn name_bytes(&self) -> &[u8] {
extern {
fn rust_list_dir_val(ptr: *mut libc::dirent_t) -> *const c_char;
}
unsafe {
let ptr = rust_list_dir_val(self.dirent);
ffi::c_str_to_bytes(mem::copy_lifetime(self, &ptr))
}
}
}
impl OpenOptions {
pub fn new() -> OpenOptions {
OpenOptions {
flags: 0,
read: false,
write: false,
mode: 0o666,
}
}
pub fn read(&mut self, read: bool) {
self.read = read;
}
pub fn write(&mut self, write: bool) {
self.write = write;
}
pub fn append(&mut self, append: bool) {
self.flag(libc::O_APPEND, append);
}
pub fn truncate(&mut self, truncate: bool) {
self.flag(libc::O_TRUNC, truncate);
}
pub fn create(&mut self, create: bool) {
self.flag(libc::O_CREAT, create);
}
pub fn mode(&mut self, mode: i32) {
self.mode = mode as mode_t;
}
fn flag(&mut self, bit: c_int, on: bool) {
if on {
self.flags |= bit;
} else {
self.flags &= !bit;
}
}
}
impl File {
pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
let flags = opts.flags | match (opts.read, opts.write) {
(true, true) => libc::O_RDWR,
(false, true) => libc::O_WRONLY,
(true, false) |
(false, false) => libc::O_RDONLY,
};
let path = cstr(path);
let fd = try!(cvt_r(|| unsafe {
libc::open(path.as_ptr(), flags, opts.mode)
}));
Ok(File(FileDesc::new(fd)))
}
pub fn file_attr(&self) -> io::Result<FileAttr> {
let mut stat: libc::stat = unsafe { mem::zeroed() };
try!(cvt(unsafe { libc::fstat(self.0.raw(), &mut stat) }));
Ok(FileAttr { stat: stat })
}
pub fn fsync(&self) -> io::Result<()> {
try!(cvt_r(|| unsafe { libc::fsync(self.0.raw()) }));
Ok(())
}
pub fn datasync(&self) -> io::Result<()> {
try!(cvt_r(|| unsafe { os_datasync(self.0.raw()) }));
return Ok(());
#[cfg(any(target_os = "macos", target_os = "ios"))]
unsafe fn os_datasync(fd: c_int) -> c_int {
libc::fcntl(fd, libc::F_FULLFSYNC)
}
#[cfg(target_os = "linux")]
unsafe fn os_datasync(fd: c_int) -> c_int { libc::fdatasync(fd) }
#[cfg(not(any(target_os = "macos",
target_os = "ios",
target_os = "linux")))]
unsafe fn os_datasync(fd: c_int) -> c_int { libc::fsync(fd) }
}
pub fn truncate(&self, size: u64) -> io::Result<()> {
try!(cvt_r(|| unsafe {
libc::ftruncate(self.0.raw(), size as libc::off_t)
}));
Ok(())
}
pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
self.0.read(buf)
}
pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
self.0.write(buf)
}
pub fn flush(&self) -> io::Result<()> { Ok(()) }
pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
let (whence, pos) = match pos {
SeekFrom::Start(off) => (libc::SEEK_SET, off as off_t),
SeekFrom::End(off) => (libc::SEEK_END, off as off_t),
SeekFrom::Current(off) => (libc::SEEK_CUR, off as off_t),
};
let n = try!(cvt(unsafe { libc::lseek(self.0.raw(), pos, whence) }));
Ok(n as u64)
}
pub fn fd(&self) -> &FileDesc { &self.0 }
}
fn cstr(path: &Path) -> CString {
CString::from_slice(path.as_os_str().as_bytes())
}
pub fn mkdir(p: &Path) -> io::Result<()> {
let p = cstr(p);
try!(cvt(unsafe { libc::mkdir(p.as_ptr(), 0o777) }));
Ok(())
}
pub fn readdir(p: &Path) -> io::Result<ReadDir> {
let root = Rc::new(p.to_path_buf());
let p = cstr(p);
unsafe {
let ptr = libc::opendir(p.as_ptr());
if ptr.is_null() {
Err(Error::last_os_error())
} else {
Ok(ReadDir { dirp: ptr, root: root })
}
}
}
pub fn unlink(p: &Path) -> io::Result<()> {
let p = cstr(p);
try!(cvt(unsafe { libc::unlink(p.as_ptr()) }));
Ok(())
}
pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
let old = cstr(old);
let new = cstr(new);
try!(cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) }));
Ok(())
}
pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
let p = cstr(p);
try!(cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) }));
Ok(())
}
pub fn rmdir(p: &Path) -> io::Result<()> {
let p = cstr(p);
try!(cvt(unsafe { libc::rmdir(p.as_ptr()) }));
Ok(())
}
pub fn chown(p: &Path, uid: isize, gid: isize) -> io::Result<()> {
let p = cstr(p);
try!(cvt_r(|| unsafe {
libc::chown(p.as_ptr(), uid as libc::uid_t, gid as libc::gid_t)
}));
Ok(())
}
pub fn readlink(p: &Path) -> io::Result<PathBuf> {
let c_path = cstr(p);
let p = c_path.as_ptr();
let mut len = unsafe { libc::pathconf(p as *mut _, libc::_PC_NAME_MAX) };
if len < 0 {
len = 1024; // FIXME: read PATH_MAX from C ffi?
}
let mut buf: Vec<u8> = Vec::with_capacity(len as usize);
unsafe {
let n = try!(cvt({
libc::readlink(p, buf.as_ptr() as *mut c_char, len as size_t)
}));
buf.set_len(n as usize);
}
let s: OsString = OsStringExt::from_vec(buf);
Ok(PathBuf::new(&s))
}
pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
let src = cstr(src);
let dst = cstr(dst);
try!(cvt(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) }));
Ok(())
}
pub fn link(src: &Path, dst: &Path) -> io::Result<()> {
let src = cstr(src);
let dst = cstr(dst);
try!(cvt(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) }));
Ok(())
}
pub fn stat(p: &Path) -> io::Result<FileAttr> {
let p = cstr(p);
let mut stat: libc::stat = unsafe { mem::zeroed() };
try!(cvt(unsafe { libc::stat(p.as_ptr(), &mut stat) }));
Ok(FileAttr { stat: stat })
}
pub fn lstat(p: &Path) -> io::Result<FileAttr> {
let p = cstr(p);
let mut stat: libc::stat = unsafe { mem::zeroed() };
try!(cvt(unsafe { libc::lstat(p.as_ptr(), &mut stat) }));
Ok(FileAttr { stat: stat })
}
pub fn utimes(p: &Path, atime: u64, mtime: u64) -> io::Result<()> {
let p = cstr(p);
let buf = [super::ms_to_timeval(atime), super::ms_to_timeval(mtime)];
try!(cvt(unsafe { c::utimes(p.as_ptr(), buf.as_ptr()) }));
Ok(())
}
| Java |
/*
* Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License. See accompanying
* LICENSE file.
*/
package admin.keepalive;
import hydra.*;
//import util.*;
/**
*
* A class used to store keys for Admin API region "keep alive" Tests
*
*/
public class TestPrms extends BasePrms {
//---------------------------------------------------------------------
// Default Values
//---------------------------------------------------------------------
// Test-specific parameters
/** (boolean) controls whether CacheLoader is defined
*/
public static Long defineCacheLoaderRemote;
/*
* Returns boolean value of TestPrms.defineCacheLoaderRemote.
* Defaults to false.
*/
public static boolean getDefineCacheLoaderRemote() {
Long key = defineCacheLoaderRemote;
return (tasktab().booleanAt(key, tab().booleanAt(key, false)));
}
}
| Java |
// Copyright 2017 PingCAP, 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 testkit
import (
"testing"
"github.com/pingcap/check"
)
var _ = check.Suite(&testKitSuite{})
func TestT(t *testing.T) {
check.TestingT(t)
}
type testKitSuite struct {
}
func (s testKitSuite) TestSort(c *check.C) {
result := &Result{
rows: [][]string{{"1", "1", "<nil>", "<nil>"}, {"2", "2", "2", "3"}},
c: c,
comment: check.Commentf(""),
}
result.Sort().Check(Rows("1 1 <nil> <nil>", "2 2 2 3"))
}
| Java |
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/**
* @var yii\base\View $this
* @var app\modules\workflow\models\WorkflowForm $model
* @var yii\widgets\ActiveForm $form
*/
?>
<div class="workflow-search">
<?php $form = ActiveForm::begin(array('method' => 'get')); ?>
<?= $form->field($model, 'id'); ?>
<?= $form->field($model, 'previous_user_id'); ?>
<?= $form->field($model, 'next_user_id'); ?>
<?= $form->field($model, 'module'); ?>
<?= $form->field($model, 'wf_table'); ?>
<?php // echo $form->field($model, 'wf_id'); ?>
<?php // echo $form->field($model, 'status_from'); ?>
<?php // echo $form->field($model, 'status_to'); ?>
<?php // echo $form->field($model, 'actions_next'); ?>
<?php // echo $form->field($model, 'date_create'); ?>
<div class="form-group">
<?= Html::submitButton('Search', array('class' => 'btn btn-primary')); ?>
<?= Html::resetButton('Reset', array('class' => 'btn btn-default')); ?>
</div>
<?php ActiveForm::end(); ?>
</div>
| Java |
/* $Id$
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.etch.bindings.java.msg;
import java.util.Set;
import org.apache.etch.bindings.java.msg.Validator.Level;
/**
* Interface which defines the value factory which helps
* the idl compiler serialize and deserialize messages,
* convert values, etc.
*/
public interface ValueFactory
{
//////////
// Type //
//////////
/**
* Translates a type id into the appropriate Type object. If the type does
* not exist, and if dynamic typing is enabled, adds it to the dynamic types.
* @param id a type id.
* @return id translated into the appropriate Type.
*/
public Type getType( Integer id );
/**
* Translates a type name into the appropriate Type object. If the type does
* not exist, and if dynamic typing is enabled, adds it to the dynamic types.
* @param name a type name.
* @return name translated into the appropriate Type.
*/
public Type getType( String name );
/**
* Adds the type if it doesn't already exist. Use this to dynamically add
* types to a ValueFactory. The type is per instance of the ValueFactory,
* not global. Not available if dynamic typing is locked.
* @param type
*/
public void addType( Type type );
/**
* Locks the dynamic typing so that no new types may be created by addType
* or getType.
*/
public void lockDynamicTypes();
/**
* Unlocks the dynamic typing so that new types may be created by addType
* or getType.
*/
public void unlockDynamicTypes();
/**
* @return a collection of all the types.
*/
public Set<Type> getTypes();
/////////////////////
// STRING ENCODING //
/////////////////////
/**
* @return the encoding to use for strings.
*/
public String getStringEncoding();
////////////////
// MESSAGE ID //
////////////////
/**
* @param msg the message whose well-known message-id field is to be
* returned.
* @return the value of the well-known message-id field. This is a
* unique identifier for this message on a particular transport
* during a particular session. If there is no well-known message-id
* field defined, or if the message-id field has not been set, then
* return null.
*/
public Long getMessageId( Message msg );
/**
* Sets the value of the well-known message-id field. This is a
* unique identifier for this message on a particular transport
* during a particular session. If there is no well-known message-id
* field defined then nothing is done. If msgid is null, then the
* field is cleared.
* @param msg the message whose well-known message-id field is to
* be set.
* @param msgid the value of the well-known message-id field.
*/
public void setMessageId( Message msg, Long msgid );
/**
* @return well-known message field for message id.
*/
public Field get_mf__messageId();
/////////////////
// IN REPLY TO //
/////////////////
/**
* @param msg the message whose well-known in-reply-to field is to
* be returned.
* @return the value of the in-reply-to field, or null if there is
* none or if there is no such field defined.
*/
public Long getInReplyTo( Message msg );
/**
* @param msg the message whose well-known in-reply-to field is to
* be set.
* @param msgid the value of the well-known in-reply-to field. If
* there is no well-known in-reply-to field defined then nothing
* is done. If msgid is null, then the field is cleared.
*/
public void setInReplyTo( Message msg, Long msgid );
/**
* @return well-known message field for in reply to.
*/
public Field get_mf__inReplyTo();
//////////////////////
// VALUE CONVERSION //
//////////////////////
/**
* Converts a value to a struct value representation to be exported
* to a tagged data output.
* @param value a custom type defined by a service, or a well-known
* standard type (e.g., date).
* @return a struct value representing the value.
* @throws UnsupportedOperationException if the type cannot be exported.
*/
public StructValue exportCustomValue( Object value )
throws UnsupportedOperationException;
/**
* Converts a struct value imported from a tagged data input to
* a normal type.
* @param struct a struct value representation of a custom type, or a
* well known standard type.
* @return a custom type, or a well known standard type.
* @throws UnsupportedOperationException if the type cannot be imported.
*/
public Object importCustomValue( StructValue struct )
throws UnsupportedOperationException;
/**
* @param c the class of a custom value.
* @return the struct type of a custom value class.
* @throws UnsupportedOperationException
* @see #exportCustomValue(Object)
*/
public Type getCustomStructType( Class<?> c )
throws UnsupportedOperationException;
/**
* @return well-known message type for exception thrown by one-way
* message.
*/
public Type get_mt__exception();
/**
* @return the validation level of field StructValue.put and TaggedDataOutput.
*/
public Level getLevel();
/**
* Sets the validation level of field StructValue.put and TaggedDataOutput.
* @param level
* @return the old value
*/
public Level setLevel( Level level );
}
| Java |
/*
* @description Prace s binarnim vyheldavacim stromem
* @author Marek Salat - xsalat00
* @projekt IFJ11
* @date
*/
#ifndef BINARYTREEAVL_H_INCLUDED
#define BINARYTREEAVL_H_INCLUDED
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#define INS_OK 1 // vlozeno v poradku
#define INS_NODE_EXIST 0 // prvek se zadanym klicem uz existuje
#define INS_MALLOC -5 // chyba pri alokaci
#define INS_TREE_NULL -5 // misto stromu NULL
#define INS_KEY_NULL -5 // misto klice NULL
typedef enum {
DEFAULT, // data budou void repektive zadna, nijak se nemazou
FUNCIONS, // data se pretypuji na TFunction*
VAR, // tady jeste nevim 28.10.2011 jak bude vypadat polozka pro symbol|identifikator
} EBTreeDataType;
typedef struct TBTreeNode {
struct TBTreeNode *left; // levy podstrom
struct TBTreeNode *right; // pravy podstrom
char *key; // vyhledavaci klic
int height; // vyska nejdelsi vetve podstromu
void *data; // data uzivatele, predem nevim jaka, data si prida uzivatel
} *TNode;
typedef struct {
TNode root; // koren stromu
TNode lastAdded; // ukazatel na posledni pridanou polozku(nekdy se to muze hodit)
int nodeCount; // pocet uzlu
EBTreeDataType type; // podle typu stromu poznam jak TNode->data smazat
} TBTree;
//--------------------------------------------------------------------------------
/*
* inicializace stromu
* @param strom
* @param typ stromu
*/
void BTreeInit(TBTree*, EBTreeDataType);
//--------------------------------------------------------------------------------
/*
* funkce prida polozku do stromu
* konevce - data pridava uzivatel
* @param ukazatel na strom
* @param ukazatel na retezec
* @param ukazatel na data(jedno jaka)
* @return INS_OK pri uspesnem volozeni,
* INS_NODE_EXIST pri nevlozeni(polozka se stejnym klicem jiz ve stromu existuje),
* INS_MALLOC pri nepovedene alokaci
* INS_TREE_NULL misto stromu NULL
* INS_KEY_NULL misto klice NULL
* T->lastAdded se ulozi pozice posledni PRIDANE polozky
*/
int BTreeInsert(TBTree*, char*, void*);
//--------------------------------------------------------------------------------
/*
* smaze cely strom
* @param ukazatel na strom
*/
void BTreeDelete(TBTree*);
//--------------------------------------------------------------------------------
/*
* vyhleda ve stromu podle klice
* @param ukazatel na strom
* @param klic hledaneho uzlu
* @return pozice uzlu, pokud uzel nebyl nalezen vraci NULL
*/
TNode BTreeSearch(TBTree*, char*);
#endif // BINARYTREEAVL_H_INCLUDED
| Java |
/*
* Copyright (c) 2016, Alliance for Open Media. All rights reserved
*
* This source code is subject to the terms of the BSD 2 Clause License and
* the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
* was not distributed with this source code in the LICENSE file, you can
* obtain it at www.aomedia.org/license/software. If the Alliance for Open
* Media Patent License 1.0 was not distributed with this source code in the
* PATENTS file, you can obtain it at www.aomedia.org/license/patent.
*/
#include "third_party/googletest/src/googletest/include/gtest/gtest.h"
#include "./av1_rtcd.h"
#include "test/acm_random.h"
#include "test/clear_system_state.h"
#include "test/register_state_check.h"
#include "test/util.h"
#include "av1/common/enums.h"
namespace {
using std::tr1::tuple;
using libaom_test::ACMRandom;
typedef void (*Predictor)(uint8_t *dst, ptrdiff_t stride, int bs,
const uint8_t *above, const uint8_t *left);
// Note:
// Test parameter list:
// Reference predictor, optimized predictor, prediction mode, block size
//
typedef tuple<Predictor, Predictor, int> PredFuncMode;
typedef tuple<PredFuncMode, int> PredParams;
#if CONFIG_AOM_HIGHBITDEPTH
typedef void (*HbdPredictor)(uint16_t *dst, ptrdiff_t stride, int bs,
const uint16_t *above, const uint16_t *left,
int bd);
// Note:
// Test parameter list:
// Reference predictor, optimized predictor, prediction mode, block size,
// bit depth
//
typedef tuple<HbdPredictor, HbdPredictor, int> HbdPredFuncMode;
typedef tuple<HbdPredFuncMode, int, int> HbdPredParams;
#endif
const int MaxBlkSize = 32;
// By default, disable speed test
#define PREDICTORS_SPEED_TEST (0)
#if PREDICTORS_SPEED_TEST
const int MaxTestNum = 100000;
#else
const int MaxTestNum = 100;
#endif
class AV1FilterIntraPredOptimzTest
: public ::testing::TestWithParam<PredParams> {
public:
virtual ~AV1FilterIntraPredOptimzTest() {}
virtual void SetUp() {
PredFuncMode funcMode = GET_PARAM(0);
predFuncRef_ = std::tr1::get<0>(funcMode);
predFunc_ = std::tr1::get<1>(funcMode);
mode_ = std::tr1::get<2>(funcMode);
blockSize_ = GET_PARAM(1);
alloc_ = new uint8_t[3 * MaxBlkSize + 2];
predRef_ = new uint8_t[MaxBlkSize * MaxBlkSize];
pred_ = new uint8_t[MaxBlkSize * MaxBlkSize];
}
virtual void TearDown() {
delete[] alloc_;
delete[] predRef_;
delete[] pred_;
libaom_test::ClearSystemState();
}
protected:
void RunTest() const {
int tstIndex = 0;
int stride = blockSize_;
uint8_t *left = alloc_;
uint8_t *above = alloc_ + MaxBlkSize + 1;
while (tstIndex < MaxTestNum) {
PrepareBuffer();
predFuncRef_(predRef_, stride, blockSize_, &above[1], left);
ASM_REGISTER_STATE_CHECK(
predFunc_(pred_, stride, blockSize_, &above[1], left));
DiffPred(tstIndex);
tstIndex += 1;
}
}
void RunSpeedTestC() const {
int tstIndex = 0;
int stride = blockSize_;
uint8_t *left = alloc_;
uint8_t *above = alloc_ + MaxBlkSize + 1;
PrepareBuffer();
while (tstIndex < MaxTestNum) {
predFuncRef_(predRef_, stride, blockSize_, &above[1], left);
tstIndex += 1;
}
}
void RunSpeedTestSSE() const {
int tstIndex = 0;
int stride = blockSize_;
uint8_t *left = alloc_;
uint8_t *above = alloc_ + MaxBlkSize + 1;
PrepareBuffer();
while (tstIndex < MaxTestNum) {
predFunc_(predRef_, stride, blockSize_, &above[1], left);
tstIndex += 1;
}
}
private:
void PrepareBuffer() const {
ACMRandom rnd(ACMRandom::DeterministicSeed());
int i = 0;
while (i < (3 * MaxBlkSize + 2)) {
alloc_[i] = rnd.Rand8();
i += 1;
}
}
void DiffPred(int testNum) const {
int i = 0;
while (i < blockSize_ * blockSize_) {
EXPECT_EQ(predRef_[i], pred_[i]) << "Error at position: " << i << " "
<< "Block size: " << blockSize_ << " "
<< "Test number: " << testNum;
i += 1;
}
}
Predictor predFunc_;
Predictor predFuncRef_;
int mode_;
int blockSize_;
uint8_t *alloc_;
uint8_t *pred_;
uint8_t *predRef_;
};
#if CONFIG_AOM_HIGHBITDEPTH
class AV1HbdFilterIntraPredOptimzTest
: public ::testing::TestWithParam<HbdPredParams> {
public:
virtual ~AV1HbdFilterIntraPredOptimzTest() {}
virtual void SetUp() {
HbdPredFuncMode funcMode = GET_PARAM(0);
predFuncRef_ = std::tr1::get<0>(funcMode);
predFunc_ = std::tr1::get<1>(funcMode);
mode_ = std::tr1::get<2>(funcMode);
blockSize_ = GET_PARAM(1);
bd_ = GET_PARAM(2);
alloc_ = new uint16_t[3 * MaxBlkSize + 2];
predRef_ = new uint16_t[MaxBlkSize * MaxBlkSize];
pred_ = new uint16_t[MaxBlkSize * MaxBlkSize];
}
virtual void TearDown() {
delete[] alloc_;
delete[] predRef_;
delete[] pred_;
libaom_test::ClearSystemState();
}
protected:
void RunTest() const {
int tstIndex = 0;
int stride = blockSize_;
uint16_t *left = alloc_;
uint16_t *above = alloc_ + MaxBlkSize + 1;
while (tstIndex < MaxTestNum) {
PrepareBuffer();
predFuncRef_(predRef_, stride, blockSize_, &above[1], left, bd_);
ASM_REGISTER_STATE_CHECK(
predFunc_(pred_, stride, blockSize_, &above[1], left, bd_));
DiffPred(tstIndex);
tstIndex += 1;
}
}
void RunSpeedTestC() const {
int tstIndex = 0;
int stride = blockSize_;
uint16_t *left = alloc_;
uint16_t *above = alloc_ + MaxBlkSize + 1;
PrepareBuffer();
while (tstIndex < MaxTestNum) {
predFuncRef_(predRef_, stride, blockSize_, &above[1], left, bd_);
tstIndex += 1;
}
}
void RunSpeedTestSSE() const {
int tstIndex = 0;
int stride = blockSize_;
uint16_t *left = alloc_;
uint16_t *above = alloc_ + MaxBlkSize + 1;
PrepareBuffer();
while (tstIndex < MaxTestNum) {
predFunc_(predRef_, stride, blockSize_, &above[1], left, bd_);
tstIndex += 1;
}
}
private:
void PrepareBuffer() const {
ACMRandom rnd(ACMRandom::DeterministicSeed());
int i = 0;
while (i < (3 * MaxBlkSize + 2)) {
alloc_[i] = rnd.Rand16() & ((1 << bd_) - 1);
i += 1;
}
}
void DiffPred(int testNum) const {
int i = 0;
while (i < blockSize_ * blockSize_) {
EXPECT_EQ(predRef_[i], pred_[i]) << "Error at position: " << i << " "
<< "Block size: " << blockSize_ << " "
<< "Bit depth: " << bd_ << " "
<< "Test number: " << testNum;
i += 1;
}
}
HbdPredictor predFunc_;
HbdPredictor predFuncRef_;
int mode_;
int blockSize_;
int bd_;
uint16_t *alloc_;
uint16_t *pred_;
uint16_t *predRef_;
};
#endif // CONFIG_AOM_HIGHBITDEPTH
TEST_P(AV1FilterIntraPredOptimzTest, BitExactCheck) { RunTest(); }
#if PREDICTORS_SPEED_TEST
TEST_P(AV1FilterIntraPredOptimzTest, SpeedCheckC) { RunSpeedTestC(); }
TEST_P(AV1FilterIntraPredOptimzTest, SpeedCheckSSE) { RunSpeedTestSSE(); }
#endif
#if CONFIG_AOM_HIGHBITDEPTH
TEST_P(AV1HbdFilterIntraPredOptimzTest, BitExactCheck) { RunTest(); }
#if PREDICTORS_SPEED_TEST
TEST_P(AV1HbdFilterIntraPredOptimzTest, SpeedCheckC) { RunSpeedTestC(); }
TEST_P(AV1HbdFilterIntraPredOptimzTest, SpeedCheckSSE) { RunSpeedTestSSE(); }
#endif // PREDICTORS_SPEED_TEST
#endif // CONFIG_AOM_HIGHBITDEPTH
using std::tr1::make_tuple;
const PredFuncMode kPredFuncMdArray[] = {
make_tuple(av1_dc_filter_predictor_c, av1_dc_filter_predictor_sse4_1,
DC_PRED),
make_tuple(av1_v_filter_predictor_c, av1_v_filter_predictor_sse4_1, V_PRED),
make_tuple(av1_h_filter_predictor_c, av1_h_filter_predictor_sse4_1, H_PRED),
make_tuple(av1_d45_filter_predictor_c, av1_d45_filter_predictor_sse4_1,
D45_PRED),
make_tuple(av1_d135_filter_predictor_c, av1_d135_filter_predictor_sse4_1,
D135_PRED),
make_tuple(av1_d117_filter_predictor_c, av1_d117_filter_predictor_sse4_1,
D117_PRED),
make_tuple(av1_d153_filter_predictor_c, av1_d153_filter_predictor_sse4_1,
D153_PRED),
make_tuple(av1_d207_filter_predictor_c, av1_d207_filter_predictor_sse4_1,
D207_PRED),
make_tuple(av1_d63_filter_predictor_c, av1_d63_filter_predictor_sse4_1,
D63_PRED),
make_tuple(av1_tm_filter_predictor_c, av1_tm_filter_predictor_sse4_1,
TM_PRED),
};
const int kBlkSize[] = { 4, 8, 16, 32 };
INSTANTIATE_TEST_CASE_P(
SSE4_1, AV1FilterIntraPredOptimzTest,
::testing::Combine(::testing::ValuesIn(kPredFuncMdArray),
::testing::ValuesIn(kBlkSize)));
#if CONFIG_AOM_HIGHBITDEPTH
const HbdPredFuncMode kHbdPredFuncMdArray[] = {
make_tuple(av1_highbd_dc_filter_predictor_c,
av1_highbd_dc_filter_predictor_sse4_1, DC_PRED),
make_tuple(av1_highbd_v_filter_predictor_c,
av1_highbd_v_filter_predictor_sse4_1, V_PRED),
make_tuple(av1_highbd_h_filter_predictor_c,
av1_highbd_h_filter_predictor_sse4_1, H_PRED),
make_tuple(av1_highbd_d45_filter_predictor_c,
av1_highbd_d45_filter_predictor_sse4_1, D45_PRED),
make_tuple(av1_highbd_d135_filter_predictor_c,
av1_highbd_d135_filter_predictor_sse4_1, D135_PRED),
make_tuple(av1_highbd_d117_filter_predictor_c,
av1_highbd_d117_filter_predictor_sse4_1, D117_PRED),
make_tuple(av1_highbd_d153_filter_predictor_c,
av1_highbd_d153_filter_predictor_sse4_1, D153_PRED),
make_tuple(av1_highbd_d207_filter_predictor_c,
av1_highbd_d207_filter_predictor_sse4_1, D207_PRED),
make_tuple(av1_highbd_d63_filter_predictor_c,
av1_highbd_d63_filter_predictor_sse4_1, D63_PRED),
make_tuple(av1_highbd_tm_filter_predictor_c,
av1_highbd_tm_filter_predictor_sse4_1, TM_PRED),
};
const int kBd[] = { 10, 12 };
INSTANTIATE_TEST_CASE_P(
SSE4_1, AV1HbdFilterIntraPredOptimzTest,
::testing::Combine(::testing::ValuesIn(kHbdPredFuncMdArray),
::testing::ValuesIn(kBlkSize),
::testing::ValuesIn(kBd)));
#endif // CONFIG_AOM_HIGHBITDEPTH
} // namespace
| Java |
/*
* #%L
* ImageJ software for multidimensional image processing and analysis.
* %%
* Copyright (C) 2014 - 2017 Board of Regents of the University of
* Wisconsin-Madison, University of Konstanz and Brian Northan.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 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.
* #L%
*/
package net.imagej.ops.create.img;
import net.imagej.ops.Ops;
import net.imagej.ops.special.chain.UFViaUFSameIO;
import net.imagej.ops.special.function.Functions;
import net.imagej.ops.special.function.UnaryFunctionOp;
import net.imglib2.Interval;
import net.imglib2.img.Img;
import net.imglib2.type.numeric.real.DoubleType;
import org.scijava.plugin.Plugin;
/**
* Creates an {@link Img} from an {@link Interval} with no additional hints.
* {@link Interval} contents are not copied.
*
* @author Curtis Rueden
*/
@Plugin(type = Ops.Create.Img.class)
public class CreateImgFromInterval extends
UFViaUFSameIO<Interval, Img<DoubleType>> implements Ops.Create.Img
{
@Override
@SuppressWarnings({"rawtypes", "unchecked"})
public UnaryFunctionOp<Interval, Img<DoubleType>> createWorker(
final Interval input)
{
// NB: Intended to match CreateImgFromDimsAndType.
return (UnaryFunctionOp) Functions.unary(ops(), Ops.Create.Img.class,
Img.class, input, new DoubleType());
}
}
| Java |
# frozen_string_literal: true
require "unpack_strategy"
shared_examples "UnpackStrategy::detect" do
it "is correctly detected" do
expect(UnpackStrategy.detect(path)).to be_a described_class
end
end
shared_examples "#extract" do |children: []|
specify "#extract" do
mktmpdir do |unpack_dir|
described_class.new(path).extract(to: unpack_dir)
expect(unpack_dir.children(false).map(&:to_s)).to match_array children
end
end
end
| Java |
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<title>ReplicaStateMachine - core 0.8.3-SNAPSHOT API - kafka.controller.ReplicaStateMachine</title>
<meta name="description" content="ReplicaStateMachine - core 0.8.3 - SNAPSHOT API - kafka.controller.ReplicaStateMachine" />
<meta name="keywords" content="ReplicaStateMachine core 0.8.3 SNAPSHOT API kafka.controller.ReplicaStateMachine" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<link href="../../lib/template.css" media="screen" type="text/css" rel="stylesheet" />
<link href="../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" />
<script type="text/javascript">
if(top === self) {
var url = '../../index.html';
var hash = 'kafka.controller.ReplicaStateMachine';
var anchor = window.location.hash;
var anchor_opt = '';
if (anchor.length >= 1)
anchor_opt = '@' + anchor.substring(1);
window.location.href = url + '#' + hash + anchor_opt;
}
</script>
</head>
<body class="type">
<div id="definition">
<img src="../../lib/class_big.png" />
<p id="owner"><a href="../package.html" class="extype" name="kafka">kafka</a>.<a href="package.html" class="extype" name="kafka.controller">controller</a></p>
<h1>ReplicaStateMachine</h1>
</div>
<h4 id="signature" class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">class</span>
</span>
<span class="symbol">
<span class="name">ReplicaStateMachine</span><span class="result"> extends <a href="../utils/Logging.html" class="extype" name="kafka.utils.Logging">Logging</a></span>
</span>
</h4>
<div id="comment" class="fullcommenttop"><div class="comment cmt"><p>This class represents the state machine for replicas. It defines the states that a replica can be in, and
transitions to move the replica to another legal state. The different states that a replica can be in are -
1. NewReplica : The controller can create new replicas during partition reassignment. In this state, a
replica can only get become follower state change request. Valid previous
state is NonExistentReplica
2. OnlineReplica : Once a replica is started and part of the assigned replicas for its partition, it is in this
state. In this state, it can get either become leader or become follower state change requests.
Valid previous state are NewReplica, OnlineReplica or OfflineReplica
3. OfflineReplica : If a replica dies, it moves to this state. This happens when the broker hosting the replica
is down. Valid previous state are NewReplica, OnlineReplica
4. ReplicaDeletionStarted: If replica deletion starts, it is moved to this state. Valid previous state is OfflineReplica
5. ReplicaDeletionSuccessful: If replica responds with no error code in response to a delete replica request, it is
moved to this state. Valid previous state is ReplicaDeletionStarted
6. ReplicaDeletionIneligible: If replica deletion fails, it is moved to this state. Valid previous state is ReplicaDeletionStarted
7. NonExistentReplica: If a replica is deleted successfully, it is moved to this state. Valid previous state is
ReplicaDeletionSuccessful
</p></div><div class="toggleContainer block">
<span class="toggle">Linear Supertypes</span>
<div class="superTypes hiddenContent"><a href="../utils/Logging.html" class="extype" name="kafka.utils.Logging">Logging</a>, <span class="extype" name="scala.AnyRef">AnyRef</span>, <span class="extype" name="scala.Any">Any</span></div>
</div></div>
<div id="mbrsel">
<div id="textfilter"><span class="pre"></span><span class="input"><input id="mbrsel-input" type="text" accesskey="/" /></span><span class="post"></span></div>
<div id="order">
<span class="filtertype">Ordering</span>
<ol>
<li class="alpha in"><span>Alphabetic</span></li>
<li class="inherit out"><span>By inheritance</span></li>
</ol>
</div>
<div id="ancestors">
<span class="filtertype">Inherited<br />
</span>
<ol id="linearization">
<li class="in" name="kafka.controller.ReplicaStateMachine"><span>ReplicaStateMachine</span></li><li class="in" name="kafka.utils.Logging"><span>Logging</span></li><li class="in" name="scala.AnyRef"><span>AnyRef</span></li><li class="in" name="scala.Any"><span>Any</span></li>
</ol>
</div><div id="ancestors">
<span class="filtertype"></span>
<ol>
<li class="hideall out"><span>Hide All</span></li>
<li class="showall in"><span>Show all</span></li>
</ol>
<a href="http://docs.scala-lang.org/overviews/scaladoc/usage.html#members" target="_blank">Learn more about member selection</a>
</div>
<div id="visbl">
<span class="filtertype">Visibility</span>
<ol><li class="public in"><span>Public</span></li><li class="all out"><span>All</span></li></ol>
</div>
</div>
<div id="template">
<div id="allMembers">
<div id="constructors" class="members">
<h3>Instance Constructors</h3>
<ol><li name="kafka.controller.ReplicaStateMachine#<init>" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped">
<a id="<init>(controller:kafka.controller.KafkaController):kafka.controller.ReplicaStateMachine"></a>
<a id="<init>:ReplicaStateMachine"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">new</span>
</span>
<span class="symbol">
<span class="name">ReplicaStateMachine</span><span class="params">(<span name="controller">controller: <a href="KafkaController.html" class="extype" name="kafka.controller.KafkaController">KafkaController</a></span>)</span>
</span>
</h4>
</li></ol>
</div>
<div id="types" class="types members">
<h3>Type Members</h3>
<ol><li name="kafka.controller.ReplicaStateMachine.BrokerChangeListener" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped">
<a id="BrokerChangeListenerextendsIZkChildListenerwithLogging"></a>
<a id="BrokerChangeListener:BrokerChangeListener"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">class</span>
</span>
<span class="symbol">
<a href="ReplicaStateMachine$BrokerChangeListener.html"><span class="name">BrokerChangeListener</span></a><span class="result"> extends <span class="extype" name="org.I0Itec.zkclient.IZkChildListener">IZkChildListener</span> with <a href="../utils/Logging.html" class="extype" name="kafka.utils.Logging">Logging</a></span>
</span>
</h4>
<p class="comment cmt">This is the zookeeper listener that triggers all the state transitions for a replica
</p>
</li></ol>
</div>
<div id="values" class="values members">
<h3>Value Members</h3>
<ol><li name="scala.AnyRef#!=" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="!=(x$1:AnyRef):Boolean"></a>
<a id="!=(AnyRef):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $bang$eq" class="name">!=</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.Any#!=" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="!=(x$1:Any):Boolean"></a>
<a id="!=(Any):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $bang$eq" class="name">!=</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div>
</li><li name="scala.AnyRef###" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="##():Int"></a>
<a id="##():Int"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $hash$hash" class="name">##</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef#==" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="==(x$1:AnyRef):Boolean"></a>
<a id="==(AnyRef):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $eq$eq" class="name">==</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.Any#==" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="==(x$1:Any):Boolean"></a>
<a id="==(Any):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $eq$eq" class="name">==</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div>
</li><li name="kafka.controller.ReplicaStateMachine#areAllReplicasForTopicDeleted" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped">
<a id="areAllReplicasForTopicDeleted(topic:String):Boolean"></a>
<a id="areAllReplicasForTopicDeleted(String):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">areAllReplicasForTopicDeleted</span><span class="params">(<span name="topic">topic: <span class="extype" name="scala.Predef.String">String</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
</li><li name="scala.Any#asInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="asInstanceOf[T0]:T0"></a>
<a id="asInstanceOf[T0]:T0"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">asInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Any.asInstanceOf.T0">T0</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div>
</li><li name="scala.AnyRef#clone" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="clone():Object"></a>
<a id="clone():AnyRef"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">clone</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.AnyRef">AnyRef</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.CloneNotSupportedException]">...</span>
</span>)</span>
</dd></dl></div>
</li><li name="kafka.utils.Logging#debug" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="debug(msg:=>String,e:=>Throwable):Unit"></a>
<a id="debug(⇒String,⇒Throwable):Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">debug</span><span class="params">(<span name="msg">msg: ⇒ <span class="extype" name="scala.Predef.String">String</span></span>, <span name="e">e: ⇒ <span class="extype" name="scala.Throwable">Throwable</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../utils/Logging.html" class="extype" name="kafka.utils.Logging">Logging</a></dd></dl></div>
</li><li name="kafka.utils.Logging#debug" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="debug(e:=>Throwable):Any"></a>
<a id="debug(⇒Throwable):Any"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">debug</span><span class="params">(<span name="e">e: ⇒ <span class="extype" name="scala.Throwable">Throwable</span></span>)</span><span class="result">: <span class="extype" name="scala.Any">Any</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../utils/Logging.html" class="extype" name="kafka.utils.Logging">Logging</a></dd></dl></div>
</li><li name="kafka.utils.Logging#debug" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="debug(msg:=>String):Unit"></a>
<a id="debug(⇒String):Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">debug</span><span class="params">(<span name="msg">msg: ⇒ <span class="extype" name="scala.Predef.String">String</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../utils/Logging.html" class="extype" name="kafka.utils.Logging">Logging</a></dd></dl></div>
</li><li name="kafka.controller.ReplicaStateMachine#deregisterListeners" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped">
<a id="deregisterListeners():Unit"></a>
<a id="deregisterListeners():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">deregisterListeners</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
</li><li name="scala.AnyRef#eq" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="eq(x$1:AnyRef):Boolean"></a>
<a id="eq(AnyRef):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">eq</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#equals" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="equals(x$1:Any):Boolean"></a>
<a id="equals(Any):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">equals</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="kafka.utils.Logging#error" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="error(msg:=>String,e:=>Throwable):Unit"></a>
<a id="error(⇒String,⇒Throwable):Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">error</span><span class="params">(<span name="msg">msg: ⇒ <span class="extype" name="scala.Predef.String">String</span></span>, <span name="e">e: ⇒ <span class="extype" name="scala.Throwable">Throwable</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../utils/Logging.html" class="extype" name="kafka.utils.Logging">Logging</a></dd></dl></div>
</li><li name="kafka.utils.Logging#error" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="error(e:=>Throwable):Any"></a>
<a id="error(⇒Throwable):Any"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">error</span><span class="params">(<span name="e">e: ⇒ <span class="extype" name="scala.Throwable">Throwable</span></span>)</span><span class="result">: <span class="extype" name="scala.Any">Any</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../utils/Logging.html" class="extype" name="kafka.utils.Logging">Logging</a></dd></dl></div>
</li><li name="kafka.utils.Logging#error" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="error(msg:=>String):Unit"></a>
<a id="error(⇒String):Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">error</span><span class="params">(<span name="msg">msg: ⇒ <span class="extype" name="scala.Predef.String">String</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../utils/Logging.html" class="extype" name="kafka.utils.Logging">Logging</a></dd></dl></div>
</li><li name="kafka.utils.Logging#fatal" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="fatal(msg:=>String,e:=>Throwable):Unit"></a>
<a id="fatal(⇒String,⇒Throwable):Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">fatal</span><span class="params">(<span name="msg">msg: ⇒ <span class="extype" name="scala.Predef.String">String</span></span>, <span name="e">e: ⇒ <span class="extype" name="scala.Throwable">Throwable</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../utils/Logging.html" class="extype" name="kafka.utils.Logging">Logging</a></dd></dl></div>
</li><li name="kafka.utils.Logging#fatal" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="fatal(e:=>Throwable):Any"></a>
<a id="fatal(⇒Throwable):Any"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">fatal</span><span class="params">(<span name="e">e: ⇒ <span class="extype" name="scala.Throwable">Throwable</span></span>)</span><span class="result">: <span class="extype" name="scala.Any">Any</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../utils/Logging.html" class="extype" name="kafka.utils.Logging">Logging</a></dd></dl></div>
</li><li name="kafka.utils.Logging#fatal" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="fatal(msg:=>String):Unit"></a>
<a id="fatal(⇒String):Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">fatal</span><span class="params">(<span name="msg">msg: ⇒ <span class="extype" name="scala.Predef.String">String</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../utils/Logging.html" class="extype" name="kafka.utils.Logging">Logging</a></dd></dl></div>
</li><li name="scala.AnyRef#finalize" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="finalize():Unit"></a>
<a id="finalize():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">finalize</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="symbol">classOf[java.lang.Throwable]</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#getClass" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="getClass():Class[_]"></a>
<a id="getClass():Class[_]"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">getClass</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.Class">Class</span>[_]</span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="kafka.controller.ReplicaStateMachine#handleStateChange" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="handleStateChange(partitionAndReplica:kafka.controller.PartitionAndReplica,targetState:kafka.controller.ReplicaState,callbacks:kafka.controller.Callbacks):Unit"></a>
<a id="handleStateChange(PartitionAndReplica,ReplicaState,Callbacks):Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">handleStateChange</span><span class="params">(<span name="partitionAndReplica">partitionAndReplica: <a href="PartitionAndReplica.html" class="extype" name="kafka.controller.PartitionAndReplica">PartitionAndReplica</a></span>, <span name="targetState">targetState: <a href="ReplicaState.html" class="extype" name="kafka.controller.ReplicaState">ReplicaState</a></span>, <span name="callbacks">callbacks: <a href="Callbacks.html" class="extype" name="kafka.controller.Callbacks">Callbacks</a></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<p class="shortcomment cmt">This API exercises the replica's state machine.</p><div class="fullcomment"><div class="comment cmt"><p>This API exercises the replica's state machine. It ensures that every state transition happens from a legal
previous state to the target state. Valid state transitions are:
NonExistentReplica --> NewReplica
--send LeaderAndIsr request with current leader and isr to the new replica and UpdateMetadata request for the
partition to every live broker</p><p>NewReplica -> OnlineReplica
--add the new replica to the assigned replica list if needed</p><p>OnlineReplica,OfflineReplica -> OnlineReplica
--send LeaderAndIsr request with current leader and isr to the new replica and UpdateMetadata request for the
partition to every live broker</p><p>NewReplica,OnlineReplica,OfflineReplica,ReplicaDeletionIneligible -> OfflineReplica
--send StopReplicaRequest to the replica (w/o deletion)
--remove this replica from the isr and send LeaderAndIsr request (with new isr) to the leader replica and
UpdateMetadata request for the partition to every live broker.</p><p>OfflineReplica -> ReplicaDeletionStarted
--send StopReplicaRequest to the replica (with deletion)</p><p>ReplicaDeletionStarted -> ReplicaDeletionSuccessful
-- mark the state of the replica in the state machine</p><p>ReplicaDeletionStarted -> ReplicaDeletionIneligible
-- mark the state of the replica in the state machine</p><p>ReplicaDeletionSuccessful -> NonExistentReplica
-- remove the replica from the in memory partition replica assignment cache</p></div><dl class="paramcmts block"><dt class="param">partitionAndReplica</dt><dd class="cmt"><p>The replica for which the state transition is invoked</p></dd><dt class="param">targetState</dt><dd class="cmt"><p>The end state that the replica should be moved to
</p></dd></dl></div>
</li><li name="kafka.controller.ReplicaStateMachine#handleStateChanges" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="handleStateChanges(replicas:scala.collection.Set[kafka.controller.PartitionAndReplica],targetState:kafka.controller.ReplicaState,callbacks:kafka.controller.Callbacks):Unit"></a>
<a id="handleStateChanges(Set[PartitionAndReplica],ReplicaState,Callbacks):Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">handleStateChanges</span><span class="params">(<span name="replicas">replicas: <span class="extype" name="scala.collection.Set">Set</span>[<a href="PartitionAndReplica.html" class="extype" name="kafka.controller.PartitionAndReplica">PartitionAndReplica</a>]</span>, <span name="targetState">targetState: <a href="ReplicaState.html" class="extype" name="kafka.controller.ReplicaState">ReplicaState</a></span>, <span name="callbacks">callbacks: <a href="Callbacks.html" class="extype" name="kafka.controller.Callbacks">Callbacks</a> = <span class="symbol"><span class="name"><a href="../package.html">new CallbackBuilder).build</a></span></span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<p class="shortcomment cmt">This API is invoked by the broker change controller callbacks and the startup API of the state machine</p><div class="fullcomment"><div class="comment cmt"><p>This API is invoked by the broker change controller callbacks and the startup API of the state machine</p></div><dl class="paramcmts block"><dt class="param">replicas</dt><dd class="cmt"><p>The list of replicas (brokers) that need to be transitioned to the target state</p></dd><dt class="param">targetState</dt><dd class="cmt"><p>The state that the replicas should be moved to
The controller's allLeaders cache should have been updated before this
</p></dd></dl></div>
</li><li name="scala.AnyRef#hashCode" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="hashCode():Int"></a>
<a id="hashCode():Int"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">hashCode</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="kafka.utils.Logging#info" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="info(msg:=>String,e:=>Throwable):Unit"></a>
<a id="info(⇒String,⇒Throwable):Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">info</span><span class="params">(<span name="msg">msg: ⇒ <span class="extype" name="scala.Predef.String">String</span></span>, <span name="e">e: ⇒ <span class="extype" name="scala.Throwable">Throwable</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../utils/Logging.html" class="extype" name="kafka.utils.Logging">Logging</a></dd></dl></div>
</li><li name="kafka.utils.Logging#info" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="info(e:=>Throwable):Any"></a>
<a id="info(⇒Throwable):Any"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">info</span><span class="params">(<span name="e">e: ⇒ <span class="extype" name="scala.Throwable">Throwable</span></span>)</span><span class="result">: <span class="extype" name="scala.Any">Any</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../utils/Logging.html" class="extype" name="kafka.utils.Logging">Logging</a></dd></dl></div>
</li><li name="kafka.utils.Logging#info" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="info(msg:=>String):Unit"></a>
<a id="info(⇒String):Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">info</span><span class="params">(<span name="msg">msg: ⇒ <span class="extype" name="scala.Predef.String">String</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../utils/Logging.html" class="extype" name="kafka.utils.Logging">Logging</a></dd></dl></div>
</li><li name="kafka.controller.ReplicaStateMachine#isAnyReplicaInState" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped">
<a id="isAnyReplicaInState(topic:String,state:kafka.controller.ReplicaState):Boolean"></a>
<a id="isAnyReplicaInState(String,ReplicaState):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">isAnyReplicaInState</span><span class="params">(<span name="topic">topic: <span class="extype" name="scala.Predef.String">String</span></span>, <span name="state">state: <a href="ReplicaState.html" class="extype" name="kafka.controller.ReplicaState">ReplicaState</a></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
</li><li name="kafka.controller.ReplicaStateMachine#isAtLeastOneReplicaInDeletionStartedState" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped">
<a id="isAtLeastOneReplicaInDeletionStartedState(topic:String):Boolean"></a>
<a id="isAtLeastOneReplicaInDeletionStartedState(String):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">isAtLeastOneReplicaInDeletionStartedState</span><span class="params">(<span name="topic">topic: <span class="extype" name="scala.Predef.String">String</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
</li><li name="scala.Any#isInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="isInstanceOf[T0]:Boolean"></a>
<a id="isInstanceOf[T0]:Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">isInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div>
</li><li name="kafka.utils.Logging#logIdent" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="logIdent:String"></a>
<a id="logIdent:String"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">var</span>
</span>
<span class="symbol">
<span class="name">logIdent</span><span class="result">: <span class="extype" name="scala.Predef.String">String</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected </dd><dt>Definition Classes</dt><dd><a href="../utils/Logging.html" class="extype" name="kafka.utils.Logging">Logging</a></dd></dl></div>
</li><li name="kafka.utils.Logging#logger" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="logger:org.apache.log4j.Logger"></a>
<a id="logger:Logger"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">lazy val</span>
</span>
<span class="symbol">
<span class="name">logger</span><span class="result">: <span class="extype" name="org.apache.log4j.Logger">Logger</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../utils/Logging.html" class="extype" name="kafka.utils.Logging">Logging</a></dd></dl></div>
</li><li name="kafka.utils.Logging#loggerName" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="loggerName:String"></a>
<a id="loggerName:String"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">val</span>
</span>
<span class="symbol">
<span class="name">loggerName</span><span class="result">: <span class="extype" name="java.lang.String">String</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../utils/Logging.html" class="extype" name="kafka.utils.Logging">Logging</a></dd></dl></div>
</li><li name="scala.AnyRef#ne" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="ne(x$1:AnyRef):Boolean"></a>
<a id="ne(AnyRef):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">ne</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#notify" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="notify():Unit"></a>
<a id="notify():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">notify</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#notifyAll" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="notifyAll():Unit"></a>
<a id="notifyAll():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">notifyAll</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="kafka.controller.ReplicaStateMachine#partitionsAssignedToBroker" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped">
<a id="partitionsAssignedToBroker(topics:Seq[String],brokerId:Int):Seq[kafka.common.TopicAndPartition]"></a>
<a id="partitionsAssignedToBroker(Seq[String],Int):Seq[TopicAndPartition]"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">partitionsAssignedToBroker</span><span class="params">(<span name="topics">topics: <span class="extype" name="scala.collection.Seq">Seq</span>[<span class="extype" name="scala.Predef.String">String</span>]</span>, <span name="brokerId">brokerId: <span class="extype" name="scala.Int">Int</span></span>)</span><span class="result">: <span class="extype" name="scala.collection.Seq">Seq</span>[<a href="../common/TopicAndPartition.html" class="extype" name="kafka.common.TopicAndPartition">TopicAndPartition</a>]</span>
</span>
</h4>
</li><li name="kafka.controller.ReplicaStateMachine#registerListeners" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped">
<a id="registerListeners():Unit"></a>
<a id="registerListeners():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">registerListeners</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
</li><li name="kafka.controller.ReplicaStateMachine#replicasInDeletionStates" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped">
<a id="replicasInDeletionStates(topic:String):scala.collection.Set[kafka.controller.PartitionAndReplica]"></a>
<a id="replicasInDeletionStates(String):Set[PartitionAndReplica]"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">replicasInDeletionStates</span><span class="params">(<span name="topic">topic: <span class="extype" name="scala.Predef.String">String</span></span>)</span><span class="result">: <span class="extype" name="scala.collection.Set">Set</span>[<a href="PartitionAndReplica.html" class="extype" name="kafka.controller.PartitionAndReplica">PartitionAndReplica</a>]</span>
</span>
</h4>
</li><li name="kafka.controller.ReplicaStateMachine#replicasInState" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped">
<a id="replicasInState(topic:String,state:kafka.controller.ReplicaState):scala.collection.Set[kafka.controller.PartitionAndReplica]"></a>
<a id="replicasInState(String,ReplicaState):Set[PartitionAndReplica]"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">replicasInState</span><span class="params">(<span name="topic">topic: <span class="extype" name="scala.Predef.String">String</span></span>, <span name="state">state: <a href="ReplicaState.html" class="extype" name="kafka.controller.ReplicaState">ReplicaState</a></span>)</span><span class="result">: <span class="extype" name="scala.collection.Set">Set</span>[<a href="PartitionAndReplica.html" class="extype" name="kafka.controller.PartitionAndReplica">PartitionAndReplica</a>]</span>
</span>
</h4>
</li><li name="kafka.controller.ReplicaStateMachine#shutdown" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped">
<a id="shutdown():Unit"></a>
<a id="shutdown():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">shutdown</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<p class="shortcomment cmt">Invoked on controller shutdown.</p>
</li><li name="kafka.controller.ReplicaStateMachine#startup" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="startup():Unit"></a>
<a id="startup():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">startup</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<p class="shortcomment cmt">Invoked on successful controller election.</p><div class="fullcomment"><div class="comment cmt"><p>Invoked on successful controller election. First registers a broker change listener since that triggers all
state transitions for replicas. Initializes the state of replicas for all partitions by reading from zookeeper.
Then triggers the OnlineReplica state change for all replicas.
</p></div></div>
</li><li name="kafka.utils.Logging#swallow" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="swallow(action:=>Unit):Unit"></a>
<a id="swallow(⇒Unit):Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">swallow</span><span class="params">(<span name="action">action: ⇒ <span class="extype" name="scala.Unit">Unit</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../utils/Logging.html" class="extype" name="kafka.utils.Logging">Logging</a></dd></dl></div>
</li><li name="kafka.utils.Logging#swallowDebug" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="swallowDebug(action:=>Unit):Unit"></a>
<a id="swallowDebug(⇒Unit):Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">swallowDebug</span><span class="params">(<span name="action">action: ⇒ <span class="extype" name="scala.Unit">Unit</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../utils/Logging.html" class="extype" name="kafka.utils.Logging">Logging</a></dd></dl></div>
</li><li name="kafka.utils.Logging#swallowError" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="swallowError(action:=>Unit):Unit"></a>
<a id="swallowError(⇒Unit):Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">swallowError</span><span class="params">(<span name="action">action: ⇒ <span class="extype" name="scala.Unit">Unit</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../utils/Logging.html" class="extype" name="kafka.utils.Logging">Logging</a></dd></dl></div>
</li><li name="kafka.utils.Logging#swallowInfo" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="swallowInfo(action:=>Unit):Unit"></a>
<a id="swallowInfo(⇒Unit):Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">swallowInfo</span><span class="params">(<span name="action">action: ⇒ <span class="extype" name="scala.Unit">Unit</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../utils/Logging.html" class="extype" name="kafka.utils.Logging">Logging</a></dd></dl></div>
</li><li name="kafka.utils.Logging#swallowTrace" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="swallowTrace(action:=>Unit):Unit"></a>
<a id="swallowTrace(⇒Unit):Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">swallowTrace</span><span class="params">(<span name="action">action: ⇒ <span class="extype" name="scala.Unit">Unit</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../utils/Logging.html" class="extype" name="kafka.utils.Logging">Logging</a></dd></dl></div>
</li><li name="kafka.utils.Logging#swallowWarn" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="swallowWarn(action:=>Unit):Unit"></a>
<a id="swallowWarn(⇒Unit):Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">swallowWarn</span><span class="params">(<span name="action">action: ⇒ <span class="extype" name="scala.Unit">Unit</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../utils/Logging.html" class="extype" name="kafka.utils.Logging">Logging</a></dd></dl></div>
</li><li name="scala.AnyRef#synchronized" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="synchronized[T0](x$1:=>T0):T0"></a>
<a id="synchronized[T0](⇒T0):T0"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">synchronized</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="params">(<span name="arg0">arg0: ⇒ <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span>)</span><span class="result">: <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#toString" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="toString():String"></a>
<a id="toString():String"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">toString</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.String">String</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="kafka.utils.Logging#trace" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="trace(msg:=>String,e:=>Throwable):Unit"></a>
<a id="trace(⇒String,⇒Throwable):Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">trace</span><span class="params">(<span name="msg">msg: ⇒ <span class="extype" name="scala.Predef.String">String</span></span>, <span name="e">e: ⇒ <span class="extype" name="scala.Throwable">Throwable</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../utils/Logging.html" class="extype" name="kafka.utils.Logging">Logging</a></dd></dl></div>
</li><li name="kafka.utils.Logging#trace" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="trace(e:=>Throwable):Any"></a>
<a id="trace(⇒Throwable):Any"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">trace</span><span class="params">(<span name="e">e: ⇒ <span class="extype" name="scala.Throwable">Throwable</span></span>)</span><span class="result">: <span class="extype" name="scala.Any">Any</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../utils/Logging.html" class="extype" name="kafka.utils.Logging">Logging</a></dd></dl></div>
</li><li name="kafka.utils.Logging#trace" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="trace(msg:=>String):Unit"></a>
<a id="trace(⇒String):Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">trace</span><span class="params">(<span name="msg">msg: ⇒ <span class="extype" name="scala.Predef.String">String</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../utils/Logging.html" class="extype" name="kafka.utils.Logging">Logging</a></dd></dl></div>
</li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="wait():Unit"></a>
<a id="wait():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">wait</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.InterruptedException]">...</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="wait(x$1:Long,x$2:Int):Unit"></a>
<a id="wait(Long,Int):Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>, <span name="arg1">arg1: <span class="extype" name="scala.Int">Int</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.InterruptedException]">...</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="wait(x$1:Long):Unit"></a>
<a id="wait(Long):Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.InterruptedException]">...</span>
</span>)</span>
</dd></dl></div>
</li><li name="kafka.utils.Logging#warn" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="warn(msg:=>String,e:=>Throwable):Unit"></a>
<a id="warn(⇒String,⇒Throwable):Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">warn</span><span class="params">(<span name="msg">msg: ⇒ <span class="extype" name="scala.Predef.String">String</span></span>, <span name="e">e: ⇒ <span class="extype" name="scala.Throwable">Throwable</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../utils/Logging.html" class="extype" name="kafka.utils.Logging">Logging</a></dd></dl></div>
</li><li name="kafka.utils.Logging#warn" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="warn(e:=>Throwable):Any"></a>
<a id="warn(⇒Throwable):Any"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">warn</span><span class="params">(<span name="e">e: ⇒ <span class="extype" name="scala.Throwable">Throwable</span></span>)</span><span class="result">: <span class="extype" name="scala.Any">Any</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../utils/Logging.html" class="extype" name="kafka.utils.Logging">Logging</a></dd></dl></div>
</li><li name="kafka.utils.Logging#warn" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="warn(msg:=>String):Unit"></a>
<a id="warn(⇒String):Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">warn</span><span class="params">(<span name="msg">msg: ⇒ <span class="extype" name="scala.Predef.String">String</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../utils/Logging.html" class="extype" name="kafka.utils.Logging">Logging</a></dd></dl></div>
</li></ol>
</div>
</div>
<div id="inheritedMembers">
<div class="parent" name="kafka.utils.Logging">
<h3>Inherited from <a href="../utils/Logging.html" class="extype" name="kafka.utils.Logging">Logging</a></h3>
</div><div class="parent" name="scala.AnyRef">
<h3>Inherited from <span class="extype" name="scala.AnyRef">AnyRef</span></h3>
</div><div class="parent" name="scala.Any">
<h3>Inherited from <span class="extype" name="scala.Any">Any</span></h3>
</div>
</div>
<div id="groupedMembers">
<div class="group" name="Ungrouped">
<h3>Ungrouped</h3>
</div>
</div>
</div>
<div id="tooltip"></div>
<div id="footer"> </div>
<script defer="defer" type="text/javascript" id="jquery-js" src="../../lib/jquery.js"></script><script defer="defer" type="text/javascript" id="jquery-ui-js" src="../../lib/jquery-ui.js"></script><script defer="defer" type="text/javascript" id="tools-tooltip-js" src="../../lib/tools.tooltip.js"></script><script defer="defer" type="text/javascript" id="template-js" src="../../lib/template.js"></script>
</body>
</html> | Java |
//
// Programmer: Craig Stuart Sapp <[email protected]>
// Creation Date: Sat Aug 25 14:12:42 PDT 2018
// Last Modified: Sat Aug 25 19:47:08 PDT 2018
// Filename: tool-trillspell.cpp
// URL: https://github.com/craigsapp/humlib/blob/master/include/tool-trillspell.cpp
// Syntax: C++11; humlib
// vim: syntax=cpp ts=3 noexpandtab nowrap
//
// Description: Interface for trill tool, which assigns intervals to
// trill, mordent and turn ornaments based on the key
// signature and previous notes in a measure.
//
#include "tool-trillspell.h"
#include "Convert.h"
#include "HumRegex.h"
#include <algorithm>
#include <cmath>
using namespace std;
namespace hum {
// START_MERGE
/////////////////////////////////
//
// Tool_trillspell::Tool_trillspell -- Set the recognized options for the tool.
//
Tool_trillspell::Tool_trillspell(void) {
define("x=b", "mark trills with x (interpretation)");
}
///////////////////////////////
//
// Tool_trillspell::run -- Primary interfaces to the tool.
//
bool Tool_trillspell::run(HumdrumFileSet& infiles) {
bool status = true;
for (int i=0; i<infiles.getCount(); i++) {
status &= run(infiles[i]);
}
return status;
}
bool Tool_trillspell::run(const string& indata, ostream& out) {
HumdrumFile infile(indata);
return run(infile, out);
}
bool Tool_trillspell::run(HumdrumFile& infile, ostream& out) {
bool status = run(infile);
return status;
}
bool Tool_trillspell::run(HumdrumFile& infile) {
processFile(infile);
infile.createLinesFromTokens();
return true;
}
///////////////////////////////
//
// Tool_trillspell::processFile -- Adjust intervals of ornaments.
//
void Tool_trillspell::processFile(HumdrumFile& infile) {
m_xmark = getBoolean("x");
analyzeOrnamentAccidentals(infile);
}
//////////////////////////////
//
// Tool_trillspell::analyzeOrnamentAccidentals --
//
bool Tool_trillspell::analyzeOrnamentAccidentals(HumdrumFile& infile) {
int i, j, k;
int kindex;
int track;
// ktracks == List of **kern spines in data.
// rtracks == Reverse mapping from track to ktrack index (part/staff index).
vector<HTp> ktracks = infile.getKernSpineStartList();
vector<int> rtracks(infile.getMaxTrack()+1, -1);
for (i=0; i<(int)ktracks.size(); i++) {
track = ktracks[i]->getTrack();
rtracks[track] = i;
}
int kcount = (int)ktracks.size();
// keysigs == key signature spellings of diatonic pitch classes. This array
// is duplicated into dstates after each barline.
vector<vector<int> > keysigs;
keysigs.resize(kcount);
for (i=0; i<kcount; i++) {
keysigs[i].resize(7);
std::fill(keysigs[i].begin(), keysigs[i].end(), 0);
}
// dstates == diatonic states for every pitch in a spine.
// sub-spines are considered as a single unit, although there are
// score conventions which would keep a separate voices on a staff
// with different accidental states (i.e., two parts superimposed
// on the same staff, but treated as if on separate staves).
// Eventually this algorithm should be adjusted for dealing with
// cross-staff notes, where the cross-staff notes should be following
// the accidentals of a different spine...
vector<vector<int> > dstates; // diatonic states
dstates.resize(kcount);
for (i=0; i<kcount; i++) {
dstates[i].resize(70); // 10 octave limit for analysis
// may cause problems; maybe fix later.
std::fill(dstates[i].begin(), dstates[i].end(), 0);
}
for (i=0; i<infile.getLineCount(); i++) {
if (!infile[i].hasSpines()) {
continue;
}
if (infile[i].isInterpretation()) {
for (j=0; j<infile[i].getFieldCount(); j++) {
if (!infile[i].token(j)->isKern()) {
continue;
}
if (infile[i].token(j)->compare(0, 3, "*k[") == 0) {
track = infile[i].token(j)->getTrack();
kindex = rtracks[track];
fillKeySignature(keysigs[kindex], *infile[i].token(j));
// resetting key states of current measure. What to do if this
// key signature is in the middle of a measure?
resetDiatonicStatesWithKeySignature(dstates[kindex],
keysigs[kindex]);
}
}
} else if (infile[i].isBarline()) {
for (j=0; j<infile[i].getFieldCount(); j++) {
if (!infile[i].token(j)->isKern()) {
continue;
}
if (infile[i].token(j)->isInvisible()) {
continue;
}
track = infile[i].token(j)->getTrack();
kindex = rtracks[track];
// reset the accidental states in dstates to match keysigs.
resetDiatonicStatesWithKeySignature(dstates[kindex],
keysigs[kindex]);
}
}
if (!infile[i].isData()) {
continue;
}
for (j=0; j<infile[i].getFieldCount(); j++) {
if (!infile[i].token(j)->isKern()) {
continue;
}
if (infile[i].token(j)->isNull()) {
continue;
}
if (infile[i].token(j)->isRest()) {
continue;
}
int subcount = infile[i].token(j)->getSubtokenCount();
track = infile[i].token(j)->getTrack();
HumRegex hre;
int rindex = rtracks[track];
for (k=0; k<subcount; k++) {
string subtok = infile[i].token(j)->getSubtoken(k);
int b40 = Convert::kernToBase40(subtok);
int diatonic = Convert::kernToBase7(subtok);
if (diatonic < 0) {
// Deal with extra-low notes later.
continue;
}
int accid = Convert::kernToAccidentalCount(subtok);
dstates.at(rindex).at(diatonic) = accid;
// check for accidentals on trills, mordents and turns.
// N.B.: augmented-second intervals are not considered.
if ((subtok.find("t") != string::npos) && !hre.search(subtok, "[tT]x")) {
int nextup = getBase40(diatonic + 1, dstates[rindex][diatonic+1]);
int interval = nextup - b40;
if (interval == 6) {
// Set to major-second trill
hre.replaceDestructive(subtok, "T", "t", "g");
if (m_xmark) {
hre.replaceDestructive(subtok, "$1x", "([Tt]+)", "g");
}
infile[i].token(j)->replaceSubtoken(k, subtok);
} else {
if (m_xmark) {
hre.replaceDestructive(subtok, "$1x", "([Tt]+)", "g");
}
infile[i].token(j)->replaceSubtoken(k, subtok);
}
} else if ((subtok.find("T") != string::npos) && !hre.search(subtok, "[tT]x")) {
int nextup = getBase40(diatonic + 1, dstates[rindex][diatonic+1]);
int interval = nextup - b40;
if (interval == 5) {
// Set to minor-second trill
hre.replaceDestructive(subtok, "t", "T", "g");
if (m_xmark) {
hre.replaceDestructive(subtok, "$1x", "([Tt]+)", "g");
}
infile[i].token(j)->replaceSubtoken(k, subtok);
} else {
if (m_xmark) {
hre.replaceDestructive(subtok, "$1x", "([Tt]+)", "g");
}
infile[i].token(j)->replaceSubtoken(k, subtok);
}
} else if ((subtok.find("M") != string::npos) && !hre.search(subtok, "[Mm]x")) {
// major-second upper mordent
int nextup = getBase40(diatonic + 1, dstates[rindex][diatonic+1]);
int interval = nextup - b40;
if (interval == 5) {
// Set to minor-second upper mordent
hre.replaceDestructive(subtok, "m", "M", "g");
if (m_xmark) {
hre.replaceDestructive(subtok, "$1x", "([Mm]+)", "g");
}
infile[i].token(j)->replaceSubtoken(k, subtok);
} else {
if (m_xmark) {
hre.replaceDestructive(subtok, "$1x", "([Mm]+)", "g");
}
infile[i].token(j)->replaceSubtoken(k, subtok);
}
} else if ((subtok.find("m") != string::npos) && !hre.search(subtok, "[Mm]x")) {
// minor-second upper mordent
int nextup = getBase40(diatonic + 1, dstates[rindex][diatonic+1]);
int interval = nextup - b40;
if (interval == 6) {
// Set to major-second upper mordent
hre.replaceDestructive(subtok, "M", "m", "g");
if (m_xmark) {
hre.replaceDestructive(subtok, "$1x", "([Mm]+)", "g");
}
infile[i].token(j)->replaceSubtoken(k, subtok);
} else {
if (m_xmark) {
hre.replaceDestructive(subtok, "$1x", "([Mm]+)", "g");
}
infile[i].token(j)->replaceSubtoken(k, subtok);
}
} else if ((subtok.find("W") != string::npos) && !hre.search(subtok, "[Ww]x")) {
// major-second lower mordent
int nextdn = getBase40(diatonic - 1, dstates[rindex][diatonic-1]);
int interval = b40 - nextdn;
if (interval == 5) {
// Set to minor-second lower mordent
hre.replaceDestructive(subtok, "w", "W", "g");
if (m_xmark) {
hre.replaceDestructive(subtok, "$1x", "([Ww]+)", "g");
}
infile[i].token(j)->replaceSubtoken(k, subtok);
} else {
if (m_xmark) {
hre.replaceDestructive(subtok, "$1x", "([Ww]+)", "g");
}
infile[i].token(j)->replaceSubtoken(k, subtok);
}
} else if ((subtok.find("w") != string::npos) && !hre.search(subtok, "[Ww]x")) {
// minor-second lower mordent
int nextdn = getBase40(diatonic - 1, dstates[rindex][diatonic-1]);
int interval = b40 - nextdn;
if (interval == 6) {
// Set to major-second lower mordent
hre.replaceDestructive(subtok, "W", "w", "g");
if (m_xmark) {
hre.replaceDestructive(subtok, "$1x", "([Ww]+)", "g");
}
infile[i].token(j)->replaceSubtoken(k, subtok);
} else {
if (m_xmark) {
hre.replaceDestructive(subtok, "$1x", "([Ww]+)", "g");
}
infile[i].token(j)->replaceSubtoken(k, subtok);
}
}
// deal with turns and inverted turns here.
}
}
}
return true;
}
//////////////////////////////
//
// Tool_trillspell::resetDiatonicStatesWithKeySignature -- Only used in
// Tool_trillspell::analyzeKernAccidentals(). Resets the accidental
// states for notes
//
void Tool_trillspell::resetDiatonicStatesWithKeySignature(vector<int>&
states, vector<int>& signature) {
for (int i=0; i<(int)states.size(); i++) {
states[i] = signature[i % 7];
}
}
//////////////////////////////
//
// Tool_trillspell::fillKeySignature -- Read key signature notes and
// assign +1 to sharps, -1 to flats in the diatonic input array. Used
// only by Tool_trillspell::analyzeOrnamentAccidentals().
//
void Tool_trillspell::fillKeySignature(vector<int>& states,
const string& keysig) {
std::fill(states.begin(), states.end(), 0);
if (keysig.find("f#") != string::npos) { states[3] = +1; }
if (keysig.find("c#") != string::npos) { states[0] = +1; }
if (keysig.find("g#") != string::npos) { states[4] = +1; }
if (keysig.find("d#") != string::npos) { states[1] = +1; }
if (keysig.find("a#") != string::npos) { states[5] = +1; }
if (keysig.find("e#") != string::npos) { states[2] = +1; }
if (keysig.find("b#") != string::npos) { states[6] = +1; }
if (keysig.find("b-") != string::npos) { states[6] = -1; }
if (keysig.find("e-") != string::npos) { states[2] = -1; }
if (keysig.find("a-") != string::npos) { states[5] = -1; }
if (keysig.find("d-") != string::npos) { states[1] = -1; }
if (keysig.find("g-") != string::npos) { states[4] = -1; }
if (keysig.find("c-") != string::npos) { states[0] = -1; }
if (keysig.find("f-") != string::npos) { states[3] = -1; }
}
//////////////////////////////
//
// Tool_trillspell::getBase40 --
//
int Tool_trillspell::getBase40(int diatonic, int accidental) {
return Convert::base7ToBase40(diatonic) + accidental;
}
// END_MERGE
} // end namespace hum
| Java |
package api_test
import (
"testing"
"github.com/remind101/empire/pkg/heroku"
)
func TestFormationBatchUpdate(t *testing.T) {
c, s := NewTestClient(t)
defer s.Close()
mustDeploy(t, c, DefaultImage)
q := 2
f := mustFormationBatchUpdate(t, c, "acme-inc", []heroku.FormationBatchUpdateOpts{
{
Process: "web",
Quantity: &q,
},
})
if got, want := f[0].Quantity, 2; got != want {
t.Fatalf("Quantity => %d; want %d", got, want)
}
}
func mustFormationBatchUpdate(t testing.TB, c *heroku.Client, appName string, updates []heroku.FormationBatchUpdateOpts) []heroku.Formation {
f, err := c.FormationBatchUpdate(appName, updates, "")
if err != nil {
t.Fatal(err)
}
return f
}
| Java |
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
#include "vu2.h"
#include "vu_priv.h"
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
//-----------------------------------------------------------------------------
// VuStandardFilter
//-----------------------------------------------------------------------------
VuStandardFilter::VuStandardFilter(VuFlagBits mask, VU_TRI_STATE localSession) : VuFilter()
{
localSession_ = localSession;
idmask_.breakdown_ = mask;
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
VuStandardFilter::VuStandardFilter(ushort mask, VU_TRI_STATE localSession) : VuFilter()
{
localSession_ = localSession;
idmask_.val_ = mask;
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
VuStandardFilter::VuStandardFilter(VuStandardFilter* other) : VuFilter(other)
{
localSession_ = DONT_CARE;
idmask_.val_ = 0;
if (other)
{
idmask_.val_ = other->idmask_.val_;
localSession_ = other->localSession_;
}
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
VuStandardFilter::~VuStandardFilter()
{
// empty
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
VU_BOOL
VuStandardFilter::Notice(VuMessage* event)
{
if ((localSession_ not_eq DONT_CARE) and ((event->Type() == VU_TRANSFER_EVENT)))
{
return TRUE;
}
return FALSE;
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
VU_BOOL VuStandardFilter::Test(VuEntity* ent)
{
if
(
((ushort)(ent->FlagValue()) bitand idmask_.val_) and
(
(localSession_ == DONT_CARE) or
((localSession_ == TRUE) and (ent->IsLocal())) or
((localSession_ == FALSE) and ( not ent->IsLocal()))
)
)
{
return TRUE;
}
else
{
return FALSE;
}
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
int VuStandardFilter::Compare(VuEntity* ent1, VuEntity* ent2)
{
return (int)ent1->Id() - (int)ent2->Id();
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
VuFilter *VuStandardFilter::Copy()
{
return new VuStandardFilter(this);
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
| Java |
class Openrct2 < Formula
desc "Open source re-implementation of RollerCoaster Tycoon 2"
homepage "https://openrct2.io/"
url "https://github.com/OpenRCT2/OpenRCT2.git",
:tag => "v0.2.4",
:revision => "d645338752fbda54bed2cf2a4183ae8b44be6e95"
head "https://github.com/OpenRCT2/OpenRCT2.git", :branch => "develop"
bottle do
cellar :any
sha256 "40527c354be56c735286b5a9a5e8f7d58de0d510190e0a1da09da552a44f877a" => :catalina
sha256 "0aba8b54f6f4d5022c3a2339bbb12dd8bd3ada5894e9bdc0a2cfeb973facca63" => :mojave
sha256 "6065b8ac863f4634f38d51dc444c2b68a361b1e9135b959c1be23321976f821d" => :high_sierra
end
depends_on "cmake" => :build
depends_on "pkg-config" => :build
depends_on "freetype" # for sdl2_ttf
depends_on "icu4c"
depends_on "jansson"
depends_on "libpng"
depends_on "libzip"
depends_on :macos => :high_sierra # "missing: Threads_FOUND" on Sierra
depends_on "[email protected]"
depends_on "sdl2"
depends_on "sdl2_ttf"
depends_on "speexdsp"
resource "title-sequences" do
url "https://github.com/OpenRCT2/title-sequences/releases/download/v0.1.2a/title-sequence-v0.1.2a.zip"
sha256 "7536dbd7c8b91554306e5823128f6bb7e94862175ef09d366d25e4bce573d155"
end
resource "objects" do
url "https://github.com/OpenRCT2/objects/releases/download/v1.0.10/objects.zip"
sha256 "4f261964f1c01a04b7600d3d082fb4d3d9ec0d543c4eb66a819eb2ad01417aa0"
end
def install
# Avoid letting CMake download things during the build process.
(buildpath/"data/title").install resource("title-sequences")
(buildpath/"data/object").install resource("objects")
mkdir "build" do
system "cmake", "..", *std_cmake_args
system "make", "install"
end
# By default macOS build only looks up data in app bundle Resources
libexec.install bin/"openrct2"
(bin/"openrct2").write <<~EOS
#!/bin/bash
exec "#{libexec}/openrct2" "$@" "--openrct-data-path=#{pkgshare}"
EOS
end
test do
assert_match "OpenRCT2, v#{version}", shell_output("#{bin}/openrct2 -v")
end
end
| Java |
class JbossForge < Formula
desc "Tools to help set up and configure a project"
homepage "https://forge.jboss.org/"
url "https://downloads.jboss.org/forge/releases/3.9.0.Final/forge-distribution-3.9.0.Final-offline.zip"
version "3.9.0.Final"
sha256 "7b2013ad0629d38d487514111eadf079860a5cd230994f33ce5b7dcca82e76ad"
bottle :unneeded
depends_on :java => "1.8+"
def install
rm_f Dir["bin/*.bat"]
libexec.install %w[addons bin lib logging.properties]
bin.install_symlink libexec/"bin/forge"
end
test do
assert_match "org.jboss.forge.addon:core", shell_output("#{bin}/forge --list")
end
end
| Java |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Shared Memory Logging and Statistics — Varnish version 3.0.3 documentation</title>
<link rel="stylesheet" href="../_static/default.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: '../',
VERSION: '3.0.3',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true
};
</script>
<script type="text/javascript" src="../_static/jquery.js"></script>
<script type="text/javascript" src="../_static/underscore.js"></script>
<script type="text/javascript" src="../_static/doctools.js"></script>
<link rel="top" title="Varnish version 3.0.3 documentation" href="../index.html" />
<link rel="up" title="The Varnish Reference Manual" href="index.html" />
<link rel="next" title="VMOD - Varnish Modules" href="vmod.html" />
<link rel="prev" title="varnishtop" href="varnishtop.html" />
</head>
<body>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="vmod.html" title="VMOD - Varnish Modules"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="varnishtop.html" title="varnishtop"
accesskey="P">previous</a> |</li>
<li><a href="../index.html">Varnish version 3.0.3 documentation</a> »</li>
<li><a href="index.html" accesskey="U">The Varnish Reference Manual</a> »</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body">
<div class="section" id="shared-memory-logging-and-statistics">
<h1>Shared Memory Logging and Statistics<a class="headerlink" href="#shared-memory-logging-and-statistics" title="Permalink to this headline">¶</a></h1>
<p>Varnish uses shared memory for logging and statistics, because it
is faster and much more efficient. But it is also tricky in ways
a regular logfile is not.</p>
<p>When you open a file in "append" mode, the operating system guarantees
that whatever you write will not overwrite existing data in the file.
The neat result of this is that multiple procesess or threads writing
to the same file does not even need to know about each other, it all
works just as you would expect.</p>
<p>With a shared memory log, we get no help from the kernel, the writers
need to make sure they do not stomp on each other, and they need to
make it possible and safe for the readers to access the data.</p>
<p>The "CS101" way, is to introduce locks, and much time is spent examining
the relative merits of the many kinds of locks available.</p>
<p>Inside the varnishd (worker) process, we use mutexes to guarantee
consistency, both with respect to allocations, log entries and stats
counters.</p>
<p>We do not want a varnishncsa trying to push data through a stalled
ssh connection to stall the delivery of content, so readers like
that are purely read-only, they do not get to affect the varnishd
process and that means no locks for them.</p>
<p>Instead we use "stable storage" concepts, to make sure the view
seen by the readers is consistent at all times.</p>
<p>As long as you only add stuff, that is trivial, but taking away
stuff, such as when a backend is taken out of the configuration,
we need to give the readers a chance to discover this, a "cooling
off" period.</p>
<p>When Varnishd starts, if it finds an existing shared memory file,
and it can safely read the master_pid field, it will check if that
process is running, and if so, fail with an error message, indicating
that -n arguments collide.</p>
<p>In all other cases, it will delete and create a new shmlog file,
in order to provide running readers a cooling off period, where
they can discover that there is a new shmlog file, by doing a
stat(2) call and checking the st_dev & st_inode fields.</p>
<div class="section" id="allocations">
<h2>Allocations<a class="headerlink" href="#allocations" title="Permalink to this headline">¶</a></h2>
<p>Sections inside the shared memory file are allocated dynamically,
for instance when a new backend is added.</p>
<p>While changes happen to the linked list of allocations, the "alloc_seq"
header field is zero, and after the change, it gets a value different
from what it had before.</p>
</div>
<div class="section" id="deallocations">
<h2>Deallocations<a class="headerlink" href="#deallocations" title="Permalink to this headline">¶</a></h2>
<p>When a section is freed, its class will change to "Cool" for at
least 10 seconds, giving programs using it time to detect the
change in alloc_seq header field and/or the change of class.</p>
</div>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar">
<div class="sphinxsidebarwrapper">
<h3><a href="../index.html">Table Of Contents</a></h3>
<ul>
<li><a class="reference internal" href="#">Shared Memory Logging and Statistics</a><ul>
<li><a class="reference internal" href="#allocations">Allocations</a></li>
<li><a class="reference internal" href="#deallocations">Deallocations</a></li>
</ul>
</li>
</ul>
<h4>Previous topic</h4>
<p class="topless"><a href="varnishtop.html"
title="previous chapter">varnishtop</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="vmod.html"
title="next chapter">VMOD - Varnish Modules</a></p>
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../_sources/reference/shmem.txt"
rel="nofollow">Show Source</a></li>
</ul>
<div id="searchbox" style="display: none">
<h3>Quick search</h3>
<form class="search" action="../search.html" method="get">
<input type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
<p class="searchtip" style="font-size: 90%">
Enter search terms or a module, class or function name.
</p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="General Index"
>index</a></li>
<li class="right" >
<a href="vmod.html" title="VMOD - Varnish Modules"
>next</a> |</li>
<li class="right" >
<a href="varnishtop.html" title="varnishtop"
>previous</a> |</li>
<li><a href="../index.html">Varnish version 3.0.3 documentation</a> »</li>
<li><a href="index.html" >The Varnish Reference Manual</a> »</li>
</ul>
</div>
<div class="footer">
© Copyright 2010, Varnish Project.
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.1.3.
</div>
</body>
</html> | Java |
/*
* Copyright 2013 Stanislav Artemkin <[email protected]>.
*
* 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.
*
* 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.
*
* Implementation of 32/Z85 specification (http://rfc.zeromq.org/spec:32/Z85)
* Source repository: http://github.com/artemkin/z85
*/
#pragma once
#include <stddef.h>
#if defined (__cplusplus)
extern "C" {
#endif
/*******************************************************************************
* ZeroMQ Base-85 encoding/decoding functions with custom padding *
*******************************************************************************/
/**
* @brief Encodes 'inputSize' bytes from 'source' into 'dest'.
* If 'inputSize' is not divisible by 4 with no remainder, 'source' is padded.
* Destination buffer must be already allocated. Use Z85_encode_with_padding_bound() to
* evaluate size of the destination buffer.
*
* @param source in, input buffer (binary string to be encoded)
* @param dest out, destination buffer
* @param inputSize in, number of bytes to be encoded
* @return number of printable symbols written into 'dest' or 0 if something goes wrong
*/
size_t Z85_encode_with_padding(const char* source, char* dest, size_t inputSize);
/**
* @brief Decodes 'inputSize' printable symbols from 'source' into 'dest',
* encoded with Z85_encode_with_padding().
* Destination buffer must be already allocated. Use Z85_decode_with_padding_bound() to
* evaluate size of the destination buffer.
*
* @param source in, input buffer (printable string to be decoded)
* @param dest out, destination buffer
* @param inputSize in, number of symbols to be decoded
* @return number of bytes written into 'dest' or 0 if something goes wrong
*/
size_t Z85_decode_with_padding(const char* source, char* dest, size_t inputSize);
/**
* @brief Evaluates a size of output buffer needed to encode 'size' bytes
* into string of printable symbols using Z85_encode_with_padding().
*
* @param size in, number of bytes to be encoded
* @return minimal size of output buffer in bytes
*/
size_t Z85_encode_with_padding_bound(size_t size);
/**
* @brief Evaluates a size of output buffer needed to decode 'size' symbols
* into binary string using Z85_decode_with_padding().
*
* @param source in, input buffer (first symbol is read from 'source' to evaluate padding)
* @param size in, number of symbols to be decoded
* @return minimal size of output buffer in bytes
*/
size_t Z85_decode_with_padding_bound(const char* source, size_t size);
/*******************************************************************************
* ZeroMQ Base-85 encoding/decoding functions (specification compliant) *
*******************************************************************************/
/**
* @brief Encodes 'inputSize' bytes from 'source' into 'dest'.
* If 'inputSize' is not divisible by 4 with no remainder, 0 is retured.
* Destination buffer must be already allocated. Use Z85_encode_bound() to
* evaluate size of the destination buffer.
*
* @param source in, input buffer (binary string to be encoded)
* @param dest out, destination buffer
* @param inputSize in, number of bytes to be encoded
* @return number of printable symbols written into 'dest' or 0 if something goes wrong
*/
size_t Z85_encode(const char* source, char* dest, size_t inputSize);
/**
* @brief Decodes 'inputSize' printable symbols from 'source' into 'dest'.
* If 'inputSize' is not divisible by 5 with no remainder, 0 is returned.
* Destination buffer must be already allocated. Use Z85_decode_bound() to
* evaluate size of the destination buffer.
*
* @param source in, input buffer (printable string to be decoded)
* @param dest out, destination buffer
* @param inputSize in, number of symbols to be decoded
* @return number of bytes written into 'dest' or 0 if something goes wrong
*/
size_t Z85_decode(const char* source, char* dest, size_t inputSize);
/**
* @brief Evaluates a size of output buffer needed to encode 'size' bytes
* into string of printable symbols using Z85_encode().
*
* @param size in, number of bytes to be encoded
* @return minimal size of output buffer in bytes
*/
size_t Z85_encode_bound(size_t size);
/**
* @brief Evaluates a size of output buffer needed to decode 'size' symbols
* into binary string using Z85_decode().
*
* @param size in, number of symbols to be decoded
* @return minimal size of output buffer in bytes
*/
size_t Z85_decode_bound(size_t size);
/*******************************************************************************
* ZeroMQ Base-85 unsafe encoding/decoding functions (specification compliant) *
*******************************************************************************/
/**
* @brief Encodes bytes from [source;sourceEnd) range into 'dest'.
* It can be used for implementation of your own padding scheme.
* Preconditions:
* - (sourceEnd - source) % 4 == 0
* - destination buffer must be already allocated
*
* @param source in, begin of input buffer
* @param sourceEnd in, end of input buffer (not included)
* @param dest out, output buffer
* @return a pointer immediately after last symbol written into the 'dest'
*/
char* Z85_encode_unsafe(const char* source, const char* sourceEnd, char* dest);
/**
* @brief Decodes symbols from [source;sourceEnd) range into 'dest'.
* It can be used for implementation of your own padding scheme.
* Preconditions:
* - (sourceEnd - source) % 5 == 0
* - destination buffer must be already allocated
*
* @param source in, begin of input buffer
* @param sourceEnd in, end of input buffer (not included)
* @param dest out, output buffer
* @return a pointer immediately after last byte written into the 'dest'
*/
char* Z85_decode_unsafe(const char* source, const char* sourceEnd, char* dest);
#if defined (__cplusplus)
}
#endif
| Java |
#include "stdafx.h"
#include "com4j.h"
void error( JNIEnv* env, const char* file, int line, HRESULT hr, const char* msg ... ) {
// format the message
va_list va;
va_start(va,msg);
int len = _vscprintf(msg,va);
char* w = reinterpret_cast<char*>(alloca(len+1)); // +1 for '\0'
vsprintf(w,msg,va);
env->ExceptionClear();
env->Throw( (jthrowable)comexception_new_hr( env, env->NewStringUTF(w), hr, env->NewStringUTF(file), line ) );
}
void error( JNIEnv* env, const char* file, int line, const char* msg ... ) {
// format the message
va_list va;
va_start(va,msg);
int len = _vscprintf(msg,va);
char* w = reinterpret_cast<char*>(alloca(len+1)); // +1 for '\0'
vsprintf(w,msg,va);
env->ExceptionClear();
env->Throw( (jthrowable)comexception_new( env, env->NewStringUTF(w), env->NewStringUTF(file), line ) );
}
| Java |
{% extends "base.html" %}
{% load filters %}
{% block title %}{{project_name}}: {{record.label}}{% endblock %}
{% block css %}
<link href="/static/css/dataTables.bootstrap.css" rel="stylesheet">
{% endblock %}
{% block navbar %}
<li><a href="..">{{project_name}}</a></li>
<li><a href="/{{project_name}}/{{record.label}}/"> {{record.label}}</a></li>
{% endblock %}
{% block content %}
<!-- General information -->
<div class="panel panel-info">
<div class="panel-heading clearfix">
{% if not read_only %}
<div class="pull-right" role="group">
<button type="button" class="btn btn-danger btn-sm" data-toggle="modal" data-target="#deleteModal"><span class="glyphicon glyphicon-trash"></span> Delete record</button>
</div>
{% endif %}
<h2 class="panel-title" style="padding-top: 6px;">{{record.label}}</h2>
</div>
<div class="panel-body">
<div class="well well-sm"><code>$ {{record.command_line}}</code></div>
<p>Run on {{record.timestamp|date:"d/m/Y H:i:s"}} by {{record.user}}</p>
<dl class="dl-horizontal">
<dt>Working directory:</dt><dd>{{record.working_directory}}</dd>
<dt>Code version:</dt><dd>{{record.version}}{% if record.diff %}* (<a href="diff">diff</a>){% endif %}</dd>
<dt>Repository:</dt><dd>{{record.repository.url}}
{% if record.repository.upstream %} - cloned from {{record.repository.upstream|urlize}}{% endif %}</dd>
<dt>{{record.executable.name}} version:</dt><dd>{{record.executable.version}}</dd>
<dt>Reason:</dt><dd>
{% if not read_only %}
<button type="button" class="btn btn-xs pull-right" data-toggle="modal" data-target="#editReasonModal"><span class="glyphicon glyphicon-pencil"></span> Edit</button>
{% endif %}
{{record.reason|restructuredtext}}</dd>
<dt>Tags:</dt><dd>
{% if not read_only %}
<button type="button" class="btn btn-xs pull-right" data-toggle="modal" data-target="#editTagsModal"><span class="glyphicon glyphicon-pencil"></span> Edit</button>
{% endif %}
{% for tag in record.tag_objects %}{{tag.name|labelize_tag}} {% endfor %}</dd>
</dl>
{% if not read_only and not record.outcome %}
<p><button type="button" class="btn btn-xs btn-success pull-right" data-toggle="modal" data-target="#editOutcomeModal"><span class="glyphicon glyphicon-plus"></span> Add outcome</button></p>
{% endif %}
</div>
</div>
<!-- Outcome -->
{% if record.outcome %}
<div class="panel panel-default">
<div class="panel-heading">
{% if not read_only %}
<button type="button" class="btn btn-xs pull-right" data-toggle="modal" data-target="#editOutcomeModal"><span class="glyphicon glyphicon-pencil"></span> Edit</button>
{% endif %}
<h4 class="panel-title">
<a data-toggle="collapse" href="#outcome-panel">Outcome</a>
</h4>
</div>
<div class="panel-body collapse in" id="#outcome-panel">
{{record.outcome|restructuredtext}}
</div>
</div>
{% endif %}
<!-- Parameters -->
{% if parameters %}
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" href="#parameters-panel">Parameters</a>
</h4>
</div>
<div class="panel-body collapse in" id="parameters-panel">
{% with dict=parameters template="nested_dict.html" %}
{% include template %}
{% endwith %}
</div>
</div>
{% endif %}
<!-- Input data -->
{% if record.input_data.count %}
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" href="#input-data-panel">Input data</a></h4>
</div>
<div class="panel-body collapse in" id="input-data-panel">
<table id="input-data" class="table table-striped table-condensed">
<thead>
<tr>
<th>Filename</th>
<th>Path</th>
<th>Digest</th>
<th>Size</th>
<th>Date/Time</th>
<th>Output of</th>
<th>Input to</th>
</tr>
</thead>
<tbody>
{% for data in record.input_data.all %}
<tr>
<td>
<a href="/{{project_name}}/data/datafile?path={{data.path|urlencode}}&digest={{data.digest}}&creation={{data.creation|date:"c"}}">
{{data.path|basename|ubreak}}
</a>
</td>
<td>
{{data.path|ubreak}}
</td>
<td>
{{data.digest|truncatechars:12 }}
</td>
<td>
{{data|eval_metadata:'size'|filesizeformat}}
</td>
<td>
<span style='display:none;'>
<!-- hack for correct sorting -->
{{data.output_from_record.timestamp|date:"YmdHis"}}
</span>
{{data.output_from_record.timestamp|date:"d/m/Y H:i:s"}}
</td>
<td>
<a href="/{{project_name}}/{{data.output_from_record.label}}/">
{{data.output_from_record.label|ubreak}}
</a>
</td>
<td>
{% for record in data.input_to_records.all %}
<a href="/{{project_name}}/{{record.label}}/">
{{record.label|ubreak}}<!--
-->{% if not forloop.last %}, {% endif %}
</a>
{% endfor %}
</td>
</tr>
{% endfor %}
<tbody>
</table>
</div>
</div>
{% endif %}
<!-- Output data -->
{% if record.output_data.count %}
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" href="#output-data-panel">Output data</a>
</h4>
</div>
<div class="panel-body collapse in" id="output-data-panel">
<table id="output-data" class="table table-striped table-condensed">
<thead>
<tr>
<th>Filename</th>
<th>Path</th>
<th>Digest</th>
<th>Size</th>
<th>Date/Time</th>
<th>Output of</th>
<th>Input to</th>
</tr>
</thead>
<tbody>
{% for data in record.output_data.all %}
<tr>
<td>
<a href="/{{project_name}}/data/datafile?path={{data.path|urlencode}}&digest={{data.digest}}&creation={{data.creation|date:"c"}}">
{{data.path|basename|ubreak}}
</a>
</td>
<td>
{{data.path|ubreak}}
</td>
<td>
{{data.digest|truncatechars:12 }}
</td>
<td>
{{data|eval_metadata:'size'|filesizeformat}}
</td>
<td>
<span style='display:none;'>
<!-- hack for correct sorting -->
{{data.output_from_record.timestamp|date:"YmdHis"}}
</span>
{{data.output_from_record.timestamp|date:"d/m/Y H:i:s"}}
</td>
<td>
<a href="/{{project_name}}/{{data.output_from_record.label}}/">
{{data.output_from_record.label|ubreak}}
</a>
</td>
<td>
{% for record in data.input_to_records.all %}
<a href="/{{project_name}}/{{record.label}}/">
{{record.label|ubreak}}<!--
-->{% if not forloop.last %}, {% endif %}
</a>
{% endfor %}
</td>
</tr>
{% endfor %}
<tbody>
</table>
</div>
</div>
{% endif %}
<!-- Dependencies -->
{% if record.dependencies.count %}
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" href="#dependencies-panel">Dependencies</a>
</h4>
</div>
<div id="dependencies-panel" class="panel-body collapse in">
<table id="dependencies" class="table table-striped table-condensed">
<thead>
<tr>
<th>Name</th>
<th>Path</th>
<th>Version</th>
</tr>
</thead>
<tbody>
{% for dep in record.dependencies.all %}
<tr>
<td>{{dep.name}}</td>
<td>{{dep.path}}</td>
<td>{{dep.version}}{% if dep.diff %}* (<a href="diff/{{dep.name}}">diff</a>){% endif %}</td>
</tr>
{% endfor %}
<tbody>
</table>
</div>
</div>
{% endif %}
<!-- Platform information -->
{% if record.platforms.count %}
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" href="#platform-info-panel">Platform information</a>
</h4>
</div>
<div id="platform-info-panel" class="panel-body collapse in">
<table id="platform-info" class="table table-striped table-condensed">
<thead>
<tr>
<th>Name</th>
<th>IP address</th>
<th>Processor</th>
<th colspan="2">Architecture</th>
<th>System type</th>
<th>Release</th>
<th>Version</th>
</tr>
</thead>
<tbody>
{% for platform in record.platforms.all %}
<tr class="{% cycle 'odd' 'even' %}">
<td>{{platform.network_name}}</td>
<td>{{platform.ip_addr}}</td>
<td>{{platform.processor}} {{platform.machine}}</td>
<td style='padding-right:5px'>{{platform.architecture_bits}}</td>
<td>{{platform.architecture_linkage}}</td>
<td>{{platform.system_name}}</td>
<td>{{platform.release}}</td>
<td>{{platform.version}}</td>
</tr>{% endfor %}
<tbody>
</table>
</div>
</div>
{% endif %}
<!-- stdout and stderr -->
{% if record.stdout_stderr %}
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" href="#stdout-stderr-panel">Stdout & Stderr</a>
</h4>
</div>
<div id="stdout-stderr-panel" class="panel-body collapse in">
<code>{{ record.stdout_stderr | linebreaksbr }}</code>
</div>
</div>
{% endif %}
{% endblock content %}
<! -- Dialog boxes for editing -->
{% block dialogs %}
<div class="modal fade" id="editReasonModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Reason/Motivation</h4>
</div>
<div class="modal-body">
<div class="form-group">
<p>Use <a href="http://sphinx-doc.org/rest.html" target="_blank">reStructuredText</a> for formatting.</p>
<textarea class="form-control" rows="10" id="reason">{{record.reason}}</textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" id="saveReason">Save</button>
</div>
</div> <!-- modal-content -->
</div> <!-- modal-dialog -->
</div> <!-- modal -->
<div class="modal fade" id="editOutcomeModal">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Outcome</h4>
</div>
<div class="modal-body">
<div class="form-group">
<p>Use <a href="http://sphinx-doc.org/rest.html" target="_blank">reStructuredText</a> for formatting.</p>
<textarea class="form-control" rows="10" id="outcome">{{record.outcome}}</textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" id="saveOutcome">Save</button>
</div>
</div> <!-- modal-content -->
</div> <!-- modal-dialog -->
</div> <!-- modal -->
<div class="modal fade" id="editTagsModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Tags</h4>
</div>
<div class="modal-body">
<div class="form-group">
<p>Separate tags with commas. Tags may contain spaces.</p>
<input type="text" class="form-control" id="tag_list" value="{{record.tags}}">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" id="saveTags">Save</button>
</div>
</div> <!-- modal-content -->
</div> <!-- modal-dialog -->
</div> <!-- modal -->
<div class="modal fade" id="editStatusModal">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Status</h4>
</div>
<div class="modal-body">
<div class="form-group">
<select id="status">
{% with "initialized pre_run running finished failed killed succeeded crashed" as statuses %}
{% for status in statuses.split %}
<option value={{status}}
{% if status == record.status %}selected="selected"{% endif %}>
{{status|title}}
</option>
{% endfor %}
{% endwith %}
</select>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" id="saveStatus">Save</button>
</div>
</div> <!-- modal-content -->
</div> <!-- modal-dialog -->
</div> <!-- modal -->
<div class="modal fade" id="deleteModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Delete record</h4>
</div>
<div class="modal-body">
<p>Are you sure you want to delete this record?</p>
<div class="form-group">
<label>
<input type="checkbox" id='is_data'> Delete associated data
</label>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">No</button>
<button type="button" class="btn btn-primary" id="confirm-delete">Yes</button>
</div>
</div> <!-- modal-content -->
</div> <!-- modal-dialog -->
</div> <!-- modal -->
{% endblock %}
<! -- Javascript -->
{% block scripts %}
<script type="text/javascript" language="javascript" src="/static/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" language="javascript" src="/static/js/dataTables.bootstrap.js"></script>
<script type="text/javascript">
$(document).ready(function() {
/* Configure DataTable */
var table = $('#output-data').dataTable( {
"info": false,
"paging": false,
"ordering": false,
"filter": false
} );
/* Save the reason/motivation */
$('#saveReason').click(function() {
$.ajax({
type: 'POST',
url: '.',
data: {'reason': $('#reason').val()},
success: function() {
success = true;
},
async: false
});
if (success) {
window.open('.','_self');
};
});
/* Save the outcome */
$('#saveOutcome').click(function() {
$.ajax({
type: 'POST',
url: '.',
data: {'outcome': $('#outcome').val()},
success: function() {
success = true;
},
async: false
});
if (success) {
window.open('.','_self');
};
});
/* Save tags */
$('#saveTags').click(function() {
$.ajax({
type: 'POST',
url: '.',
data: {'tags': $('#tag_list').val()},
success: function() {
success = true;
},
async: false
});
if (success) {
window.open('.','_self');
};
});
/* Save status */
$('#saveStatus').click(function() {
$.ajax({
type: 'POST',
url: '.',
data: {'status': $('#status').val()},
success: function() {
success = true;
},
async: false
});
if (success) {
window.open('.','_self');
};
});
/* Delete this record */
$('#confirm-delete').click(function() {
var success = false;
var includeData = function(){
if ($('#is_data').attr('checked')) {
return true;
} else {
return false;
};
};
var deleteArr = new Array(); // records to delete
deleteArr.push('{{record.label}}');
console.log(deleteArr);
$.ajax({
type: 'POST',
url: '../delete/',
data: {'delete': deleteArr,
'delete_data': includeData()},
success: function() {
success = true;
},
async: false
});
if (success) {
window.open('..', '_self');
};
});
} );
</script>
{% endblock %}
<!-- TODO: initialize input-data DataTable -->
| Java |
/*
* Copyright (c), Pierre-Anthony Lemieux ([email protected])
* 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.
*
* 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.
*/
#ifndef COM_SANDFLOW_SMPTE_REGXML_DEFINITIONS_FIXEDARRAYTYPEDEFINITION_H
#define COM_SANDFLOW_SMPTE_REGXML_DEFINITIONS_FIXEDARRAYTYPEDEFINITION_H
#include "Definition.h"
#include "DefinitionVisitor.h"
namespace rxml {
struct FixedArrayTypeDefinition : public Definition {
void accept(DefinitionVisitor &visitor) const {
visitor.visit(*this);
}
AUID elementType;
unsigned int elementCount;
};
}
#endif
| Java |
from PyQt4 import QtGui, QtCore, QtSvg
from PyQt4.QtCore import QMimeData
from PyQt4.QtGui import QGraphicsScene, QGraphicsView, QWidget, QApplication
from Orange.data.io import FileFormat
class ImgFormat(FileFormat):
@staticmethod
def _get_buffer(size, filename):
raise NotImplementedError
@staticmethod
def _get_target(scene, painter, buffer):
raise NotImplementedError
@staticmethod
def _save_buffer(buffer, filename):
raise NotImplementedError
@staticmethod
def _get_exporter():
raise NotImplementedError
@staticmethod
def _export(self, exporter, filename):
raise NotImplementedError
@classmethod
def write_image(cls, filename, scene):
try:
scene = scene.scene()
scenerect = scene.sceneRect() #preserve scene bounding rectangle
viewrect = scene.views()[0].sceneRect()
scene.setSceneRect(viewrect)
backgroundbrush = scene.backgroundBrush() #preserve scene background brush
scene.setBackgroundBrush(QtCore.Qt.white)
exporter = cls._get_exporter()
cls._export(exporter(scene), filename)
scene.setBackgroundBrush(backgroundbrush) # reset scene background brush
scene.setSceneRect(scenerect) # reset scene bounding rectangle
except Exception:
if isinstance(scene, (QGraphicsScene, QGraphicsView)):
rect = scene.sceneRect()
elif isinstance(scene, QWidget):
rect = scene.rect()
rect = rect.adjusted(-15, -15, 15, 15)
buffer = cls._get_buffer(rect.size(), filename)
painter = QtGui.QPainter()
painter.begin(buffer)
painter.setRenderHint(QtGui.QPainter.Antialiasing)
target = cls._get_target(scene, painter, buffer, rect)
try:
scene.render(painter, target, rect)
except TypeError:
scene.render(painter) # PyQt4 QWidget.render() takes different params
cls._save_buffer(buffer, filename)
painter.end()
@classmethod
def write(cls, filename, scene):
if type(scene) == dict:
scene = scene['scene']
cls.write_image(filename, scene)
class PngFormat(ImgFormat):
EXTENSIONS = ('.png',)
DESCRIPTION = 'Portable Network Graphics'
PRIORITY = 50
@staticmethod
def _get_buffer(size, filename):
return QtGui.QPixmap(int(size.width()), int(size.height()))
@staticmethod
def _get_target(scene, painter, buffer, source):
try:
brush = scene.backgroundBrush()
if brush.style() == QtCore.Qt.NoBrush:
brush = QtGui.QBrush(scene.palette().color(QtGui.QPalette.Base))
except AttributeError: # not a QGraphicsView/Scene
brush = QtGui.QBrush(QtCore.Qt.white)
painter.fillRect(buffer.rect(), brush)
return QtCore.QRectF(0, 0, source.width(), source.height())
@staticmethod
def _save_buffer(buffer, filename):
buffer.save(filename, "png")
@staticmethod
def _get_exporter():
from pyqtgraph.exporters.ImageExporter import ImageExporter
return ImageExporter
@staticmethod
def _export(exporter, filename):
buffer = exporter.export(toBytes=True)
buffer.save(filename, "png")
class ClipboardFormat(PngFormat):
EXTENSIONS = ()
DESCRIPTION = 'System Clipboard'
PRIORITY = 50
@staticmethod
def _save_buffer(buffer, _):
QApplication.clipboard().setPixmap(buffer)
@staticmethod
def _export(exporter, _):
buffer = exporter.export(toBytes=True)
mimedata = QMimeData()
mimedata.setData("image/png", buffer)
QApplication.clipboard().setMimeData(mimedata)
class SvgFormat(ImgFormat):
EXTENSIONS = ('.svg',)
DESCRIPTION = 'Scalable Vector Graphics'
PRIORITY = 100
@staticmethod
def _get_buffer(size, filename):
buffer = QtSvg.QSvgGenerator()
buffer.setFileName(filename)
buffer.setSize(QtCore.QSize(int(size.width()), int(size.height())))
return buffer
@staticmethod
def _get_target(scene, painter, buffer, source):
return QtCore.QRectF(0, 0, source.width(), source.height())
@staticmethod
def _save_buffer(buffer, filename):
pass
@staticmethod
def _get_exporter():
from pyqtgraph.exporters.SVGExporter import SVGExporter
return SVGExporter
@staticmethod
def _export(exporter, filename):
exporter.export(filename)
| Java |
/*
* Copyright (C) 1999 Lars Knoll ([email protected])
* (C) 1999 Antti Koivisto ([email protected])
* Copyright (C) 2010 Apple Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#ifndef HTMLOListElement_h
#define HTMLOListElement_h
#include "HTMLElement.h"
namespace WebCore {
class HTMLOListElement : public HTMLElement {
public:
static PassRefPtr<HTMLOListElement> create(Document*);
static PassRefPtr<HTMLOListElement> create(const QualifiedName&, Document*);
int start() const { return m_hasExplicitStart ? m_start : (m_isReversed ? itemCount() : 1); }
void setStart(int);
bool isReversed() const { return m_isReversed; }
void itemCountChanged() { m_shouldRecalculateItemCount = true; }
private:
HTMLOListElement(const QualifiedName&, Document*);
void updateItemValues();
unsigned itemCount() const
{
if (m_shouldRecalculateItemCount)
const_cast<HTMLOListElement*>(this)->recalculateItemCount();
return m_itemCount;
}
void recalculateItemCount();
virtual void parseAttribute(const Attribute&) OVERRIDE;
virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
virtual void collectStyleForAttribute(const Attribute&, StylePropertySet*) OVERRIDE;
int m_start;
unsigned m_itemCount;
bool m_hasExplicitStart : 1;
bool m_isReversed : 1;
bool m_shouldRecalculateItemCount : 1;
};
} //namespace
#endif
| Java |
cask "inso" do
version "2.4.1"
sha256 "ef9510f32d5d5093f6589fe22d6629c2aa780315966381fc94f83519f2553c2d"
url "https://github.com/Kong/insomnia/releases/download/lib%40#{version}/inso-macos-#{version}.zip",
verified: "github.com/Kong/insomnia/"
name "inso"
desc "CLI HTTP and GraphQL Client"
homepage "https://insomnia.rest/products/inso"
livecheck do
url "https://github.com/Kong/insomnia/releases?q=prerelease%3Afalse+Inso+CLI"
strategy :page_match
regex(/href=.*?inso-macos-(?:latest-)*(\d+(?:\.\d+)+)\.zip/i)
end
conflicts_with cask: "homebrew/cask-versions/inso-beta"
binary "inso"
end
| Java |
class Timidity < Formula
desc "Software synthesizer"
homepage "http://timidity.sourceforge.net/"
url "https://downloads.sourceforge.net/project/timidity/TiMidity++/TiMidity++-2.14.0/TiMidity++-2.14.0.tar.bz2"
sha256 "f97fb643f049e9c2e5ef5b034ea9eeb582f0175dce37bc5df843cc85090f6476"
bottle do
sha256 "0b26a98c3e8e3706f8ff1fb2e21c014ac7245c01510799172e7f3ebdc71602ac" => :el_capitan
sha256 "2bfaec5aaaacf7ed13148f437cbeba6bb793f9eacdab739b7202d151031253b4" => :yosemite
sha256 "9e56e31b91c1cab53ebd7830114520233b02f7766f69f2e761d005b8bcd2fb58" => :mavericks
sha256 "a6c27dd89a2a68505faa01a3be6b770d5c89ae79a9b4739a5f7f1d226bfedb2d" => :mountain_lion
end
option "without-darwin", "Build without Darwin CoreAudio support"
option "without-freepats", "Build without the Freepats instrument patches from http://freepats.zenvoid.org/"
depends_on "libogg" => :recommended
depends_on "libvorbis" => :recommended
depends_on "flac" => :recommended
depends_on "speex" => :recommended
depends_on "libao" => :recommended
resource "freepats" do
url "http://freepats.zenvoid.org/freepats-20060219.zip"
sha256 "532048a5777aea717effabf19a35551d3fcc23b1ad6edd92f5de1d64600acd48"
end
def install
args = ["--disable-debug",
"--disable-dependency-tracking",
"--prefix=#{prefix}",
"--mandir=#{man}"
]
formats = []
formats << "darwin" if build.with? "darwin"
formats << "vorbis" if build.with?("libogg") && build.with?("libvorbis")
formats << "flac" if build.with? "flac"
formats << "speex" if build.with? "speex"
formats << "ao" if build.with? "libao"
if formats.any?
args << "--enable-audio=" + formats.join(",")
end
system "./configure", *args
system "make", "install"
if build.with? "freepats"
(share/"freepats").install resource("freepats")
(share/"timidity").install_symlink share/"freepats/Tone_000",
share/"freepats/Drum_000",
share/"freepats/freepats.cfg" => "timidity.cfg"
end
end
test do
system "#{bin}/timidity"
end
end
| Java |
class HapiFhirCli < Formula
desc "Command-line interface for the HAPI FHIR library"
homepage "https://hapifhir.io/hapi-fhir/docs/tools/hapi_fhir_cli.html"
url "https://github.com/jamesagnew/hapi-fhir/releases/download/v5.3.0/hapi-fhir-5.3.0-cli.zip"
sha256 "851fa036c55fee7c0eca62a1c00fd9b5f35f8296850762e002f752ad35ba0240"
license "Apache-2.0"
livecheck do
url :stable
strategy :github_latest
end
bottle :unneeded
depends_on "openjdk"
resource "test_resource" do
url "https://github.com/jamesagnew/hapi-fhir/raw/v5.1.0/hapi-fhir-structures-dstu3/src/test/resources/specimen-example.json"
sha256 "4eacf47eccec800ffd2ca23b704c70d71bc840aeb755912ffb8596562a0a0f5e"
end
def install
inreplace "hapi-fhir-cli", /SCRIPTDIR=(.*)/, "SCRIPTDIR=#{libexec}"
libexec.install "hapi-fhir-cli.jar"
bin.install "hapi-fhir-cli"
bin.env_script_all_files libexec/"bin", JAVA_HOME: Formula["openjdk"].opt_prefix
end
test do
testpath.install resource("test_resource")
system bin/"hapi-fhir-cli", "validate", "--file", "specimen-example.json",
"--fhir-version", "dstu3"
end
end
| Java |
require File.expand_path("../../language/php", __FILE__)
class PhpPlantumlwriter < Formula
include Language::PHP::Composer
desc "Create UML diagrams from your PHP source"
homepage "https://github.com/davidfuhr/php-plantumlwriter"
url "https://github.com/davidfuhr/php-plantumlwriter/archive/1.6.0.tar.gz"
sha256 "e0ee6a22877b506edfdaf174b7bac94f5fd5b113c4c7a2fc0ec9afd20fdc0568"
bottle do
cellar :any_skip_relocation
sha256 "7f82a56639fa67a63ef687771653b50f511be5d15877e86d050631350368f4ed" => :sierra
sha256 "5124040d7593dc423a8c50eeb3e3961d47f66d017d76b7805c122b4edf74361a" => :el_capitan
sha256 "a2ea4a2c54d13207042be78ed52afd7c782306638b05d4572773fec947bfdb13" => :yosemite
sha256 "b4625f6b67bc7cdfa097041c58142a9a8dc69008089bd66f1bfd46c59af5b847" => :mavericks
end
depends_on "plantuml"
def install
composer_install
libexec.install Dir["*"]
bin.install_symlink "#{libexec}/bin/php-plantumlwriter"
end
test do
(testpath/"testClass.php").write <<-EOS.undent
<?php
class OneClass
{
}
EOS
(testpath/"testClass.puml").write <<-EOS.undent
@startuml
class OneClass {
}
@enduml
EOS
system "#{bin}/php-plantumlwriter write testClass.php > output.puml"
system "diff", "-u", "output.puml", "testClass.puml"
end
end
| Java |
class NewrelicInfraAgent < Formula
desc "New Relic infrastructure agent"
homepage "https://github.com/newrelic/infrastructure-agent"
url "https://github.com/newrelic/infrastructure-agent.git",
tag: "1.20.7",
revision: "b17a417d4745da7be9c00ecc72619523867f7add"
license "Apache-2.0"
head "https://github.com/newrelic/infrastructure-agent.git", branch: "master"
bottle do
sha256 cellar: :any_skip_relocation, monterey: "ffdb274016361a220fbc8fb21cfae1b90347c03ff7c86e128d20a6c3a0a6053b"
sha256 cellar: :any_skip_relocation, big_sur: "bf1f38cc2c2f73370f92c7645eb9c228dbaf5f760b700477f1c40e7de34690b7"
sha256 cellar: :any_skip_relocation, catalina: "966da6a25822e35c9e96e518336b3d1bb3ceb9e06c88d9456c19e2305ab45570"
sha256 cellar: :any_skip_relocation, x86_64_linux: "93328d150756320c4ea4a9aba6c66dd773cdc1b7c63db1165918f64ca8409194"
end
# https://github.com/newrelic/infrastructure-agent/issues/723
depends_on "[email protected]" => :build
# https://github.com/newrelic/infrastructure-agent/issues/695
depends_on arch: :x86_64
def install
goarch = Hardware::CPU.intel? ? "amd64" : Hardware::CPU.arch.to_s
os = OS.kernel_name.downcase
ENV["VERSION"] = version.to_s
ENV["GOOS"] = os
ENV["CGO_ENABLED"] = OS.mac? ? "1" : "0"
system "make", "dist-for-os"
bin.install "dist/#{os}-newrelic-infra_#{os}_#{goarch}/newrelic-infra"
bin.install "dist/#{os}-newrelic-infra-ctl_#{os}_#{goarch}/newrelic-infra-ctl"
bin.install "dist/#{os}-newrelic-infra-service_#{os}_#{goarch}/newrelic-infra-service"
(var/"db/newrelic-infra").install "assets/licence/LICENSE.macos.txt" if OS.mac?
end
def post_install
(etc/"newrelic-infra").mkpath
(var/"log/newrelic-infra").mkpath
end
service do
run [bin/"newrelic-infra-service", "-config", etc/"newrelic-infra/newrelic-infra.yml"]
log_path var/"log/newrelic-infra/newrelic-infra.log"
error_log_path var/"log/newrelic-infra/newrelic-infra.stderr.log"
end
test do
output = shell_output("#{bin}/newrelic-infra -validate")
assert_match "config validation", output
end
end
| Java |
#include <sys/time.h>
#include <time.h>
#include "warnp.h"
#include "monoclock.h"
/**
* monoclock_get(tv):
* Store the current time in ${tv}. If CLOCK_MONOTONIC is available, use
* that clock; otherwise, use gettimeofday(2).
*/
int
monoclock_get(struct timeval * tv)
{
#ifdef CLOCK_MONOTONIC
struct timespec tp;
#endif
#ifdef CLOCK_MONOTONIC
if (clock_gettime(CLOCK_MONOTONIC, &tp)) {
warnp("clock_gettime(CLOCK_MONOTONIC)");
goto err0;
}
tv->tv_sec = tp.tv_sec;
tv->tv_usec = tp.tv_nsec / 1000;
#else
if (gettimeofday(tv, NULL)) {
warnp("gettimeofday");
goto err0;
}
#endif
/* Success! */
return (0);
err0:
/* Failure! */
return (-1);
}
| Java |
class Yaz < Formula
desc "Toolkit for Z39.50/SRW/SRU clients/servers"
homepage "https://www.indexdata.com/yaz"
url "http://ftp.indexdata.dk/pub/yaz/yaz-5.15.1.tar.gz"
sha256 "ebef25b0970ea1485bbba43a721d7001523b6faa18c8d8da4080a8f83d5e2116"
revision 1
bottle do
cellar :any
sha256 "5c92b86a99954d7c94d4fea236515387c985b4cb53ae08e7b44db3273bdf7752" => :el_capitan
sha256 "24875e71916b26cbe8758bb8ecbd8efe4a3b0cf02349fc7668fb84db99c6e048" => :yosemite
sha256 "6326adcf981c85d58153e9472797efe34605196ec5ead5cf19faf127e1d93444" => :mavericks
end
option :universal
depends_on "pkg-config" => :build
depends_on "icu4c" => :recommended
def install
ENV.universal_binary if build.universal?
system "./configure", "--disable-dependency-tracking",
"--prefix=#{prefix}",
"--with-xml2"
system "make", "install"
end
test do
# This test converts between MARC8, an obscure mostly-obsolete library
# text encoding supported by yaz-iconv, and UTF8.
marc8file = testpath/"marc8.txt"
marc8file.write "$1!0-!L,i$3i$si$Ki$Ai$O!+=(B"
result = shell_output("#{bin}/yaz-iconv -f marc8 -t utf8 #{marc8file}")
result.force_encoding(Encoding::UTF_8) if result.respond_to?(:force_encoding)
assert_equal "世界こんにちは!", result
# Test ICU support if building with ICU by running yaz-icu
# with the example icu_chain from its man page.
if build.with? "icu4c"
# The input string should be transformed to be:
# * without control characters (tab)
# * split into tokens at word boundaries (including -)
# * without whitespace and Punctuation
# * xy transformed to z
# * lowercase
configurationfile = testpath/"icu-chain.xml"
configurationfile.write <<-EOS.undent
<?xml version="1.0" encoding="UTF-8"?>
<icu_chain locale="en">
<transform rule="[:Control:] Any-Remove"/>
<tokenize rule="w"/>
<transform rule="[[:WhiteSpace:][:Punctuation:]] Remove"/>
<transliterate rule="xy > z;"/>
<display/>
<casemap rule="l"/>
</icu_chain>
EOS
inputfile = testpath/"icu-test.txt"
inputfile.write "yaz-ICU xy!"
expectedresult = <<-EOS.undent
1 1 'yaz' 'yaz'
2 1 '' ''
3 1 'icuz' 'ICUz'
4 1 '' ''
EOS
result = shell_output("#{bin}/yaz-icu -c #{configurationfile} #{inputfile}")
assert_equal expectedresult, result
end
end
end
| Java |
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* The examples provided by Facebook are for non-commercial testing and
* evaluation purposes only.
*
* Facebook reserves all rights not expressly granted.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL
* FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* @flow
*/
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var {
Text,
TextInput,
View,
StyleSheet,
} = ReactNative;
var TextEventsExample = React.createClass({
getInitialState: function() {
return {
curText: '<No Event>',
prevText: '<No Event>',
prev2Text: '<No Event>',
};
},
updateText: function(text) {
this.setState((state) => {
return {
curText: text,
prevText: state.curText,
prev2Text: state.prevText,
};
});
},
render: function() {
return (
<View>
<TextInput
autoCapitalize="none"
placeholder="Enter text to see events"
autoCorrect={false}
onFocus={() => this.updateText('onFocus')}
onBlur={() => this.updateText('onBlur')}
onChange={(event) => this.updateText(
'onChange text: ' + event.nativeEvent.text
)}
onEndEditing={(event) => this.updateText(
'onEndEditing text: ' + event.nativeEvent.text
)}
onSubmitEditing={(event) => this.updateText(
'onSubmitEditing text: ' + event.nativeEvent.text
)}
style={styles.singleLine}
/>
<Text style={styles.eventLabel}>
{this.state.curText}{'\n'}
(prev: {this.state.prevText}){'\n'}
(prev2: {this.state.prev2Text})
</Text>
</View>
);
}
});
class AutoExpandingTextInput extends React.Component {
constructor(props) {
super(props);
this.state = {
text: 'React Native enables you to build world-class application experiences on native platforms using a consistent developer experience based on JavaScript and React. The focus of React Native is on developer efficiency across all the platforms you care about — learn once, write anywhere. Facebook uses React Native in multiple production apps and will continue investing in React Native.',
height: 0,
};
}
render() {
return (
<TextInput
{...this.props}
multiline={true}
onContentSizeChange={(event) => {
this.setState({height: event.nativeEvent.contentSize.height});
}}
onChangeText={(text) => {
this.setState({text});
}}
style={[styles.default, {height: Math.max(35, this.state.height)}]}
value={this.state.text}
/>
);
}
}
class RewriteExample extends React.Component {
constructor(props) {
super(props);
this.state = {text: ''};
}
render() {
var limit = 20;
var remainder = limit - this.state.text.length;
var remainderColor = remainder > 5 ? 'blue' : 'red';
return (
<View style={styles.rewriteContainer}>
<TextInput
multiline={false}
maxLength={limit}
onChangeText={(text) => {
text = text.replace(/ /g, '_');
this.setState({text});
}}
style={styles.default}
value={this.state.text}
/>
<Text style={[styles.remainder, {color: remainderColor}]}>
{remainder}
</Text>
</View>
);
}
}
class TokenizedTextExample extends React.Component {
constructor(props) {
super(props);
this.state = {text: 'Hello #World'};
}
render() {
//define delimiter
let delimiter = /\s+/;
//split string
let _text = this.state.text;
let token, index, parts = [];
while (_text) {
delimiter.lastIndex = 0;
token = delimiter.exec(_text);
if (token === null) {
break;
}
index = token.index;
if (token[0].length === 0) {
index = 1;
}
parts.push(_text.substr(0, index));
parts.push(token[0]);
index = index + token[0].length;
_text = _text.slice(index);
}
parts.push(_text);
//highlight hashtags
parts = parts.map((text) => {
if (/^#/.test(text)) {
return <Text key={text} style={styles.hashtag}>{text}</Text>;
} else {
return text;
}
});
return (
<View>
<TextInput
multiline={true}
style={styles.multiline}
onChangeText={(text) => {
this.setState({text});
}}>
<Text>{parts}</Text>
</TextInput>
</View>
);
}
}
var BlurOnSubmitExample = React.createClass({
focusNextField(nextField) {
this.refs[nextField].focus();
},
render: function() {
return (
<View>
<TextInput
ref="1"
style={styles.singleLine}
placeholder="blurOnSubmit = false"
returnKeyType="next"
blurOnSubmit={false}
onSubmitEditing={() => this.focusNextField('2')}
/>
<TextInput
ref="2"
style={styles.singleLine}
keyboardType="email-address"
placeholder="blurOnSubmit = false"
returnKeyType="next"
blurOnSubmit={false}
onSubmitEditing={() => this.focusNextField('3')}
/>
<TextInput
ref="3"
style={styles.singleLine}
keyboardType="url"
placeholder="blurOnSubmit = false"
returnKeyType="next"
blurOnSubmit={false}
onSubmitEditing={() => this.focusNextField('4')}
/>
<TextInput
ref="4"
style={styles.singleLine}
keyboardType="numeric"
placeholder="blurOnSubmit = false"
blurOnSubmit={false}
onSubmitEditing={() => this.focusNextField('5')}
/>
<TextInput
ref="5"
style={styles.singleLine}
keyboardType="numbers-and-punctuation"
placeholder="blurOnSubmit = true"
returnKeyType="done"
/>
</View>
);
}
});
var styles = StyleSheet.create({
multiline: {
height: 60,
fontSize: 16,
padding: 4,
marginBottom: 10,
},
eventLabel: {
margin: 3,
fontSize: 12,
},
singleLine: {
fontSize: 16,
padding: 4,
},
singleLineWithHeightTextInput: {
height: 30,
},
hashtag: {
color: 'blue',
fontWeight: 'bold',
},
});
exports.title = '<TextInput>';
exports.description = 'Single and multi-line text inputs.';
exports.examples = [
{
title: 'Auto-focus',
render: function() {
return (
<TextInput
autoFocus={true}
style={styles.singleLine}
accessibilityLabel="I am the accessibility label for text input"
/>
);
}
},
{
title: "Live Re-Write (<sp> -> '_')",
render: function() {
return <RewriteExample />;
}
},
{
title: 'Auto-capitalize',
render: function() {
var autoCapitalizeTypes = [
'none',
'sentences',
'words',
'characters',
];
var examples = autoCapitalizeTypes.map((type) => {
return (
<TextInput
key={type}
autoCapitalize={type}
placeholder={'autoCapitalize: ' + type}
style={styles.singleLine}
/>
);
});
return <View>{examples}</View>;
}
},
{
title: 'Auto-correct',
render: function() {
return (
<View>
<TextInput
autoCorrect={true}
placeholder="This has autoCorrect"
style={styles.singleLine}
/>
<TextInput
autoCorrect={false}
placeholder="This does not have autoCorrect"
style={styles.singleLine}
/>
</View>
);
}
},
{
title: 'Keyboard types',
render: function() {
var keyboardTypes = [
'default',
'email-address',
'numeric',
'phone-pad',
];
var examples = keyboardTypes.map((type) => {
return (
<TextInput
key={type}
keyboardType={type}
placeholder={'keyboardType: ' + type}
style={styles.singleLine}
/>
);
});
return <View>{examples}</View>;
}
},
{
title: 'Blur on submit',
render: function(): ReactElement { return <BlurOnSubmitExample />; },
},
{
title: 'Event handling',
render: function(): ReactElement { return <TextEventsExample />; },
},
{
title: 'Colors and text inputs',
render: function() {
return (
<View>
<TextInput
style={[styles.singleLine]}
defaultValue="Default color text"
/>
<TextInput
style={[styles.singleLine, {color: 'green'}]}
defaultValue="Green Text"
/>
<TextInput
placeholder="Default placeholder text color"
style={styles.singleLine}
/>
<TextInput
placeholder="Red placeholder text color"
placeholderTextColor="red"
style={styles.singleLine}
/>
<TextInput
placeholder="Default underline color"
style={styles.singleLine}
/>
<TextInput
placeholder="Blue underline color"
style={styles.singleLine}
underlineColorAndroid="blue"
/>
<TextInput
defaultValue="Same BackgroundColor as View "
style={[styles.singleLine, {backgroundColor: 'rgba(100, 100, 100, 0.3)'}]}>
<Text style={{backgroundColor: 'rgba(100, 100, 100, 0.3)'}}>
Darker backgroundColor
</Text>
</TextInput>
<TextInput
defaultValue="Highlight Color is red"
selectionColor={'red'}
style={styles.singleLine}>
</TextInput>
</View>
);
}
},
{
title: 'Text input, themes and heights',
render: function() {
return (
<TextInput
placeholder="If you set height, beware of padding set from themes"
style={[styles.singleLineWithHeightTextInput]}
/>
);
}
},
{
title: 'fontFamily, fontWeight and fontStyle',
render: function() {
return (
<View>
<TextInput
style={[styles.singleLine, {fontFamily: 'sans-serif'}]}
placeholder="Custom fonts like Sans-Serif are supported"
/>
<TextInput
style={[styles.singleLine, {fontFamily: 'sans-serif', fontWeight: 'bold'}]}
placeholder="Sans-Serif bold"
/>
<TextInput
style={[styles.singleLine, {fontFamily: 'sans-serif', fontStyle: 'italic'}]}
placeholder="Sans-Serif italic"
/>
<TextInput
style={[styles.singleLine, {fontFamily: 'serif'}]}
placeholder="Serif"
/>
</View>
);
}
},
{
title: 'Passwords',
render: function() {
return (
<View>
<TextInput
defaultValue="iloveturtles"
secureTextEntry={true}
style={styles.singleLine}
/>
<TextInput
secureTextEntry={true}
style={[styles.singleLine, {color: 'red'}]}
placeholder="color is supported too"
placeholderTextColor="red"
/>
</View>
);
}
},
{
title: 'Editable',
render: function() {
return (
<TextInput
defaultValue="Can't touch this! (>'-')> ^(' - ')^ <('-'<) (>'-')> ^(' - ')^"
editable={false}
style={styles.singleLine}
/>
);
}
},
{
title: 'Multiline',
render: function() {
return (
<View>
<TextInput
autoCorrect={true}
placeholder="multiline, aligned top-left"
placeholderTextColor="red"
multiline={true}
style={[styles.multiline, {textAlign: "left", textAlignVertical: "top"}]}
/>
<TextInput
autoCorrect={true}
placeholder="multiline, aligned center"
placeholderTextColor="green"
multiline={true}
style={[styles.multiline, {textAlign: "center", textAlignVertical: "center"}]}
/>
<TextInput
autoCorrect={true}
multiline={true}
style={[styles.multiline, {color: 'blue'}, {textAlign: "right", textAlignVertical: "bottom"}]}>
<Text style={styles.multiline}>multiline with children, aligned bottom-right</Text>
</TextInput>
</View>
);
}
},
{
title: 'Fixed number of lines',
platform: 'android',
render: function() {
return (
<View>
<TextInput numberOfLines={2}
multiline={true}
placeholder="Two line input"
/>
<TextInput numberOfLines={5}
multiline={true}
placeholder="Five line input"
/>
</View>
);
}
},
{
title: 'Auto-expanding',
render: function() {
return (
<View>
<AutoExpandingTextInput
placeholder="height increases with content"
enablesReturnKeyAutomatically={true}
returnKeyType="done"
/>
</View>
);
}
},
{
title: 'Attributed text',
render: function() {
return <TokenizedTextExample />;
}
},
{
title: 'Return key',
render: function() {
var returnKeyTypes = [
'none',
'go',
'search',
'send',
'done',
'previous',
'next',
];
var returnKeyLabels = [
'Compile',
'React Native',
];
var examples = returnKeyTypes.map((type) => {
return (
<TextInput
key={type}
returnKeyType={type}
placeholder={'returnKeyType: ' + type}
style={styles.singleLine}
/>
);
});
var types = returnKeyLabels.map((type) => {
return (
<TextInput
key={type}
returnKeyLabel={type}
placeholder={'returnKeyLabel: ' + type}
style={styles.singleLine}
/>
);
});
return <View>{examples}{types}</View>;
}
},
{
title: 'Inline Images',
render: function() {
return (
<View>
<TextInput
inlineImageLeft="ic_menu_black_24dp"
placeholder="This has drawableLeft set"
style={styles.singleLine}
/>
<TextInput
inlineImageLeft="ic_menu_black_24dp"
inlineImagePadding={30}
placeholder="This has drawableLeft and drawablePadding set"
style={styles.singleLine}
/>
<TextInput
placeholder="This does not have drawable props set"
style={styles.singleLine}
/>
</View>
);
}
},
];
| Java |
#! /usr/bin/python
"""versioneer.py
(like a rocketeer, but for versions)
* https://github.com/warner/python-versioneer
* Brian Warner
* License: Public Domain
* Version: 0.7+
This file helps distutils-based projects manage their version number by just
creating version-control tags.
For developers who work from a VCS-generated tree (e.g. 'git clone' etc),
each 'setup.py version', 'setup.py build', 'setup.py sdist' will compute a
version number by asking your version-control tool about the current
checkout. The version number will be written into a generated _version.py
file of your choosing, where it can be included by your __init__.py
For users who work from a VCS-generated tarball (e.g. 'git archive'), it will
compute a version number by looking at the name of the directory created when
te tarball is unpacked. This conventionally includes both the name of the
project and a version number.
For users who work from a tarball built by 'setup.py sdist', it will get a
version number from a previously-generated _version.py file.
As a result, loading code directly from the source tree will not result in a
real version. If you want real versions from VCS trees (where you frequently
update from the upstream repository, or do new development), you will need to
do a 'setup.py version' after each update, and load code from the build/
directory.
You need to provide this code with a few configuration values:
versionfile_source:
A project-relative pathname into which the generated version strings
should be written. This is usually a _version.py next to your project's
main __init__.py file. If your project uses src/myproject/__init__.py,
this should be 'src/myproject/_version.py'. This file should be checked
in to your VCS as usual: the copy created below by 'setup.py
update_files' will include code that parses expanded VCS keywords in
generated tarballs. The 'build' and 'sdist' commands will replace it with
a copy that has just the calculated version string.
versionfile_build:
Like versionfile_source, but relative to the build directory instead of
the source directory. These will differ when your setup.py uses
'package_dir='. If you have package_dir={'myproject': 'src/myproject'},
then you will probably have versionfile_build='myproject/_version.py' and
versionfile_source='src/myproject/_version.py'.
tag_prefix: a string, like 'PROJECTNAME-', which appears at the start of all
VCS tags. If your tags look like 'myproject-1.2.0', then you
should use tag_prefix='myproject-'. If you use unprefixed tags
like '1.2.0', this should be an empty string.
parentdir_prefix: a string, frequently the same as tag_prefix, which
appears at the start of all unpacked tarball filenames. If
your tarball unpacks into 'myproject-1.2.0', this should
be 'myproject-'.
To use it:
1: include this file in the top level of your project
2: make the following changes to the top of your setup.py:
import versioneer
versioneer.versionfile_source = 'src/myproject/_version.py'
versioneer.versionfile_build = 'myproject/_version.py'
versioneer.tag_prefix = '' # tags are like 1.2.0
versioneer.parentdir_prefix = 'myproject-' # dirname like 'myproject-1.2.0'
3: add the following arguments to the setup() call in your setup.py:
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
4: run 'setup.py update_files', which will create _version.py, and will
append the following to your __init__.py:
from _version import __version__
5: modify your MANIFEST.in to include versioneer.py
6: add both versioneer.py and the generated _version.py to your VCS
"""
import os
import sys
import re
import subprocess
from distutils.core import Command
from distutils.command.sdist import sdist as _sdist
from distutils.command.build import build as _build
versionfile_source = None
versionfile_build = None
tag_prefix = None
parentdir_prefix = None
VCS = "git"
IN_LONG_VERSION_PY = False
GIT = "git"
LONG_VERSION_PY = '''
IN_LONG_VERSION_PY = True
# This file helps to compute a version number in source trees obtained from
# git-archive tarball (such as those provided by github's download-from-tag
# feature). Distribution tarballs (build by setup.py sdist) and build
# directories (produced by setup.py build) will contain a much shorter file
# that just contains the computed version number.
# This file is released into the public domain. Generated by
# versioneer-0.7+ (https://github.com/warner/python-versioneer)
# these strings will be replaced by git during git-archive
git_refnames = "%(DOLLAR)sFormat:%%d%(DOLLAR)s"
git_full = "%(DOLLAR)sFormat:%%H%(DOLLAR)s"
GIT = "git"
import subprocess
import sys
def run_command(args, cwd=None, verbose=False):
try:
# remember shell=False, so use git.cmd on windows, not just git
p = subprocess.Popen(args, stdout=subprocess.PIPE, cwd=cwd)
except EnvironmentError:
e = sys.exc_info()[1]
if verbose:
print("unable to run %%s" %% args[0])
print(e)
return None
stdout = p.communicate()[0].strip()
if sys.version >= '3':
stdout = stdout.decode()
if p.returncode != 0:
if verbose:
print("unable to run %%s (error)" %% args[0])
return None
return stdout
import sys
import re
import os.path
def get_expanded_variables(versionfile_source):
# the code embedded in _version.py can just fetch the value of these
# variables. When used from setup.py, we don't want to import
# _version.py, so we do it with a regexp instead. This function is not
# used from _version.py.
variables = {}
try:
for line in open(versionfile_source,"r").readlines():
if line.strip().startswith("git_refnames ="):
mo = re.search(r'=\s*"(.*)"', line)
if mo:
variables["refnames"] = mo.group(1)
if line.strip().startswith("git_full ="):
mo = re.search(r'=\s*"(.*)"', line)
if mo:
variables["full"] = mo.group(1)
except EnvironmentError:
pass
return variables
def versions_from_expanded_variables(variables, tag_prefix, verbose=False):
refnames = variables["refnames"].strip()
if refnames.startswith("$Format"):
if verbose:
print("variables are unexpanded, not using")
return {} # unexpanded, so not in an unpacked git-archive tarball
refs = set([r.strip() for r in refnames.strip("()").split(",")])
for ref in list(refs):
if not re.search(r'\d', ref):
if verbose:
print("discarding '%%s', no digits" %% ref)
refs.discard(ref)
# Assume all version tags have a digit. git's %%d expansion
# behaves like git log --decorate=short and strips out the
# refs/heads/ and refs/tags/ prefixes that would let us
# distinguish between branches and tags. By ignoring refnames
# without digits, we filter out many common branch names like
# "release" and "stabilization", as well as "HEAD" and "master".
if verbose:
print("remaining refs: %%s" %% ",".join(sorted(refs)))
for ref in sorted(refs):
# sorting will prefer e.g. "2.0" over "2.0rc1"
if ref.startswith(tag_prefix):
r = ref[len(tag_prefix):]
if verbose:
print("picking %%s" %% r)
return { "version": r,
"full": variables["full"].strip() }
# no suitable tags, so we use the full revision id
if verbose:
print("no suitable tags, using full revision id")
return { "version": variables["full"].strip(),
"full": variables["full"].strip() }
def versions_from_vcs(tag_prefix, versionfile_source, verbose=False):
# this runs 'git' from the root of the source tree. That either means
# someone ran a setup.py command (and this code is in versioneer.py, so
# IN_LONG_VERSION_PY=False, thus the containing directory is the root of
# the source tree), or someone ran a project-specific entry point (and
# this code is in _version.py, so IN_LONG_VERSION_PY=True, thus the
# containing directory is somewhere deeper in the source tree). This only
# gets called if the git-archive 'subst' variables were *not* expanded,
# and _version.py hasn't already been rewritten with a short version
# string, meaning we're inside a checked out source tree.
try:
here = os.path.realpath(__file__)
except NameError:
# some py2exe/bbfreeze/non-CPython implementations don't do __file__
return {} # not always correct
# versionfile_source is the relative path from the top of the source tree
# (where the .git directory might live) to this file. Invert this to find
# the root from __file__.
root = here
if IN_LONG_VERSION_PY:
for i in range(len(versionfile_source.split("/"))):
root = os.path.dirname(root)
else:
root = os.path.dirname(here)
if not os.path.exists(os.path.join(root, ".git")):
if verbose:
print("no .git in %%s" %% root)
return {}
stdout = run_command([GIT, "describe", "--tags", "--dirty", "--always"],
cwd=root)
if stdout is None:
return {}
if not stdout.startswith(tag_prefix):
if verbose:
print("tag '%%s' doesn't start with prefix '%%s'" %% (stdout, tag_prefix))
return {}
tag = stdout[len(tag_prefix):]
stdout = run_command([GIT, "rev-parse", "HEAD"], cwd=root)
if stdout is None:
return {}
full = stdout.strip()
if tag.endswith("-dirty"):
full += "-dirty"
return {"version": tag, "full": full}
def versions_from_parentdir(parentdir_prefix, versionfile_source, verbose=False):
if IN_LONG_VERSION_PY:
# We're running from _version.py. If it's from a source tree
# (execute-in-place), we can work upwards to find the root of the
# tree, and then check the parent directory for a version string. If
# it's in an installed application, there's no hope.
try:
here = os.path.realpath(__file__)
except NameError:
# py2exe/bbfreeze/non-CPython don't have __file__
return {} # without __file__, we have no hope
# versionfile_source is the relative path from the top of the source
# tree to _version.py. Invert this to find the root from __file__.
root = here
for i in range(len(versionfile_source.split("/"))):
root = os.path.dirname(root)
else:
# we're running from versioneer.py, which means we're running from
# the setup.py in a source tree. sys.argv[0] is setup.py in the root.
here = os.path.realpath(sys.argv[0])
root = os.path.dirname(here)
# Source tarballs conventionally unpack into a directory that includes
# both the project name and a version string.
dirname = os.path.basename(root)
if not dirname.startswith(parentdir_prefix):
if verbose:
print("guessing rootdir is '%%s', but '%%s' doesn't start with prefix '%%s'" %%
(root, dirname, parentdir_prefix))
return None
return {"version": dirname[len(parentdir_prefix):], "full": ""}
tag_prefix = "%(TAG_PREFIX)s"
parentdir_prefix = "%(PARENTDIR_PREFIX)s"
versionfile_source = "%(VERSIONFILE_SOURCE)s"
def get_versions(default={"version": "unknown", "full": ""}, verbose=False):
variables = { "refnames": git_refnames, "full": git_full }
ver = versions_from_expanded_variables(variables, tag_prefix, verbose)
if not ver:
ver = versions_from_vcs(tag_prefix, versionfile_source, verbose)
if not ver:
ver = versions_from_parentdir(parentdir_prefix, versionfile_source,
verbose)
if not ver:
ver = default
return ver
'''
def run_command(args, cwd=None, verbose=False):
try:
# remember shell=False, so use git.cmd on windows, not just git
p = subprocess.Popen(args, stdout=subprocess.PIPE, cwd=cwd)
except EnvironmentError:
e = sys.exc_info()[1]
if verbose:
print("unable to run %s" % args[0])
print(e)
return None
stdout = p.communicate()[0].strip()
if sys.version >= '3':
stdout = stdout.decode()
if p.returncode != 0:
if verbose:
print("unable to run %s (error)" % args[0])
return None
return stdout
def get_expanded_variables(versionfile_source):
# the code embedded in _version.py can just fetch the value of these
# variables. When used from setup.py, we don't want to import
# _version.py, so we do it with a regexp instead. This function is not
# used from _version.py.
variables = {}
try:
for line in open(versionfile_source,"r").readlines():
if line.strip().startswith("git_refnames ="):
mo = re.search(r'=\s*"(.*)"', line)
if mo:
variables["refnames"] = mo.group(1)
if line.strip().startswith("git_full ="):
mo = re.search(r'=\s*"(.*)"', line)
if mo:
variables["full"] = mo.group(1)
except EnvironmentError:
pass
return variables
def versions_from_expanded_variables(variables, tag_prefix, verbose=False):
refnames = variables["refnames"].strip()
if refnames.startswith("$Format"):
if verbose:
print("variables are unexpanded, not using")
return {} # unexpanded, so not in an unpacked git-archive tarball
refs = set([r.strip() for r in refnames.strip("()").split(",")])
for ref in list(refs):
if not re.search(r'\d', ref):
if verbose:
print("discarding '%s', no digits" % ref)
refs.discard(ref)
# Assume all version tags have a digit. git's %d expansion
# behaves like git log --decorate=short and strips out the
# refs/heads/ and refs/tags/ prefixes that would let us
# distinguish between branches and tags. By ignoring refnames
# without digits, we filter out many common branch names like
# "release" and "stabilization", as well as "HEAD" and "master".
if verbose:
print("remaining refs: %s" % ",".join(sorted(refs)))
for ref in sorted(refs):
# sorting will prefer e.g. "2.0" over "2.0rc1"
if ref.startswith(tag_prefix):
r = ref[len(tag_prefix):]
if verbose:
print("picking %s" % r)
return { "version": r,
"full": variables["full"].strip() }
# no suitable tags, so we use the full revision id
if verbose:
print("no suitable tags, using full revision id")
return { "version": variables["full"].strip(),
"full": variables["full"].strip() }
def versions_from_vcs(tag_prefix, versionfile_source, verbose=False):
# this runs 'git' from the root of the source tree. That either means
# someone ran a setup.py command (and this code is in versioneer.py, so
# IN_LONG_VERSION_PY=False, thus the containing directory is the root of
# the source tree), or someone ran a project-specific entry point (and
# this code is in _version.py, so IN_LONG_VERSION_PY=True, thus the
# containing directory is somewhere deeper in the source tree). This only
# gets called if the git-archive 'subst' variables were *not* expanded,
# and _version.py hasn't already been rewritten with a short version
# string, meaning we're inside a checked out source tree.
try:
here = os.path.realpath(__file__)
except NameError:
# some py2exe/bbfreeze/non-CPython implementations don't do __file__
return {} # not always correct
# versionfile_source is the relative path from the top of the source tree
# (where the .git directory might live) to this file. Invert this to find
# the root from __file__.
root = here
if IN_LONG_VERSION_PY:
for i in range(len(versionfile_source.split("/"))):
root = os.path.dirname(root)
else:
root = os.path.dirname(here)
if not os.path.exists(os.path.join(root, ".git")):
if verbose:
print("no .git in %s" % root)
return {}
stdout = run_command([GIT, "describe", "--tags", "--dirty", "--always"],
cwd=root)
if stdout is None:
return {}
if not stdout.startswith(tag_prefix):
if verbose:
print("tag '%s' doesn't start with prefix '%s'" % (stdout, tag_prefix))
return {}
tag = stdout[len(tag_prefix):]
stdout = run_command([GIT, "rev-parse", "HEAD"], cwd=root)
if stdout is None:
return {}
full = stdout.strip()
if tag.endswith("-dirty"):
full += "-dirty"
return {"version": tag, "full": full}
def versions_from_parentdir(parentdir_prefix, versionfile_source, verbose=False):
if IN_LONG_VERSION_PY:
# We're running from _version.py. If it's from a source tree
# (execute-in-place), we can work upwards to find the root of the
# tree, and then check the parent directory for a version string. If
# it's in an installed application, there's no hope.
try:
here = os.path.realpath(__file__)
except NameError:
# py2exe/bbfreeze/non-CPython don't have __file__
return {} # without __file__, we have no hope
# versionfile_source is the relative path from the top of the source
# tree to _version.py. Invert this to find the root from __file__.
root = here
for i in range(len(versionfile_source.split("/"))):
root = os.path.dirname(root)
else:
# we're running from versioneer.py, which means we're running from
# the setup.py in a source tree. sys.argv[0] is setup.py in the root.
here = os.path.realpath(sys.argv[0])
root = os.path.dirname(here)
# Source tarballs conventionally unpack into a directory that includes
# both the project name and a version string.
dirname = os.path.basename(root)
if not dirname.startswith(parentdir_prefix):
if verbose:
print("guessing rootdir is '%s', but '%s' doesn't start with prefix '%s'" %
(root, dirname, parentdir_prefix))
return None
return {"version": dirname[len(parentdir_prefix):], "full": ""}
def do_vcs_install(versionfile_source, ipy):
run_command([GIT, "add", "versioneer.py"])
run_command([GIT, "add", versionfile_source])
run_command([GIT, "add", ipy])
present = False
try:
f = open(".gitattributes", "r")
for line in f.readlines():
if line.strip().startswith(versionfile_source):
if "export-subst" in line.strip().split()[1:]:
present = True
f.close()
except EnvironmentError:
pass
if not present:
f = open(".gitattributes", "a+")
f.write("%s export-subst\n" % versionfile_source)
f.close()
run_command([GIT, "add", ".gitattributes"])
SHORT_VERSION_PY = """
# This file was generated by 'versioneer.py' (0.7+) from
# revision-control system data, or from the parent directory name of an
# unpacked source archive. Distribution tarballs contain a pre-generated copy
# of this file.
version_version = '%(version)s'
version_full = '%(full)s'
def get_versions(default={}, verbose=False):
return {'version': version_version, 'full': version_full}
"""
DEFAULT = {"version": "unknown", "full": "unknown"}
def versions_from_file(filename):
versions = {}
try:
f = open(filename)
except EnvironmentError:
return versions
for line in f.readlines():
mo = re.match("version_version = '([^']+)'", line)
if mo:
versions["version"] = mo.group(1)
mo = re.match("version_full = '([^']+)'", line)
if mo:
versions["full"] = mo.group(1)
return versions
def write_to_version_file(filename, versions):
f = open(filename, "w")
f.write(SHORT_VERSION_PY % versions)
f.close()
print("set %s to '%s'" % (filename, versions["version"]))
def get_best_versions(versionfile, tag_prefix, parentdir_prefix,
default=DEFAULT, verbose=False):
# returns dict with two keys: 'version' and 'full'
#
# extract version from first of _version.py, 'git describe', parentdir.
# This is meant to work for developers using a source checkout, for users
# of a tarball created by 'setup.py sdist', and for users of a
# tarball/zipball created by 'git archive' or github's download-from-tag
# feature.
variables = get_expanded_variables(versionfile_source)
if variables:
ver = versions_from_expanded_variables(variables, tag_prefix)
if ver:
if verbose: print("got version from expanded variable %s" % ver)
return ver
ver = versions_from_file(versionfile)
if ver:
if verbose: print("got version from file %s %s" % (versionfile, ver))
return ver
ver = versions_from_vcs(tag_prefix, versionfile_source, verbose)
if ver:
if verbose: print("got version from git %s" % ver)
return ver
ver = versions_from_parentdir(parentdir_prefix, versionfile_source, verbose)
if ver:
if verbose: print("got version from parentdir %s" % ver)
return ver
if verbose: print("got version from default %s" % ver)
return default
def get_versions(default=DEFAULT, verbose=False):
assert versionfile_source is not None, "please set versioneer.versionfile_source"
assert tag_prefix is not None, "please set versioneer.tag_prefix"
assert parentdir_prefix is not None, "please set versioneer.parentdir_prefix"
return get_best_versions(versionfile_source, tag_prefix, parentdir_prefix,
default=default, verbose=verbose)
def get_version(verbose=False):
return get_versions(verbose=verbose)["version"]
class cmd_version(Command):
description = "report generated version string"
user_options = []
boolean_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
ver = get_version(verbose=True)
print("Version is currently: %s" % ver)
class cmd_build(_build):
def run(self):
versions = get_versions(verbose=True)
_build.run(self)
# now locate _version.py in the new build/ directory and replace it
# with an updated value
target_versionfile = os.path.join(self.build_lib, versionfile_build)
print("UPDATING %s" % target_versionfile)
os.unlink(target_versionfile)
f = open(target_versionfile, "w")
f.write(SHORT_VERSION_PY % versions)
f.close()
class cmd_sdist(_sdist):
def run(self):
versions = get_versions(verbose=True)
self._versioneer_generated_versions = versions
# unless we update this, the command will keep using the old version
self.distribution.metadata.version = versions["version"]
return _sdist.run(self)
def make_release_tree(self, base_dir, files):
_sdist.make_release_tree(self, base_dir, files)
# now locate _version.py in the new base_dir directory (remembering
# that it may be a hardlink) and replace it with an updated value
target_versionfile = os.path.join(base_dir, versionfile_source)
print("UPDATING %s" % target_versionfile)
os.unlink(target_versionfile)
f = open(target_versionfile, "w")
f.write(SHORT_VERSION_PY % self._versioneer_generated_versions)
f.close()
INIT_PY_SNIPPET = """
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
"""
class cmd_update_files(Command):
description = "modify __init__.py and create _version.py"
user_options = []
boolean_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
ipy = os.path.join(os.path.dirname(versionfile_source), "__init__.py")
print(" creating %s" % versionfile_source)
f = open(versionfile_source, "w")
f.write(LONG_VERSION_PY % {"DOLLAR": "$",
"TAG_PREFIX": tag_prefix,
"PARENTDIR_PREFIX": parentdir_prefix,
"VERSIONFILE_SOURCE": versionfile_source,
})
f.close()
try:
old = open(ipy, "r").read()
except EnvironmentError:
old = ""
if INIT_PY_SNIPPET not in old:
print(" appending to %s" % ipy)
f = open(ipy, "a")
f.write(INIT_PY_SNIPPET)
f.close()
else:
print(" %s unmodified" % ipy)
do_vcs_install(versionfile_source, ipy)
def get_cmdclass():
return {'version': cmd_version,
'update_files': cmd_update_files,
'build': cmd_build,
'sdist': cmd_sdist,
}
| Java |
<?php
/**
* TOP API: taobao.tmc.user.get request
*
* @author auto create
* @since 1.0, 2015.12.04
*/
class TmcUserGetRequest
{
/**
* 需返回的字段列表,多个字段以半角逗号分隔。可选值:TmcUser结构体中的所有字段,一定要返回topic。
**/
private $fields;
/**
* 用户昵称
**/
private $nick;
/**
* 用户所属的平台类型,tbUIC:淘宝用户; icbu: icbu用户
**/
private $userPlatform;
private $apiParas = array();
public function setFields($fields)
{
$this->fields = $fields;
$this->apiParas["fields"] = $fields;
}
public function getFields()
{
return $this->fields;
}
public function setNick($nick)
{
$this->nick = $nick;
$this->apiParas["nick"] = $nick;
}
public function getNick()
{
return $this->nick;
}
public function setUserPlatform($userPlatform)
{
$this->userPlatform = $userPlatform;
$this->apiParas["user_platform"] = $userPlatform;
}
public function getUserPlatform()
{
return $this->userPlatform;
}
public function getApiMethodName()
{
return "taobao.tmc.user.get";
}
public function getApiParas()
{
return $this->apiParas;
}
public function check()
{
RequestCheckUtil::checkNotNull($this->fields,"fields");
RequestCheckUtil::checkNotNull($this->nick,"nick");
RequestCheckUtil::checkMaxLength($this->nick,100,"nick");
}
public function putOtherTextParam($key, $value) {
$this->apiParas[$key] = $value;
$this->$key = $value;
}
}
| Java |
# Linux Eclipse Dev
Eclipse can be used on Linux (and probably Windows and Mac) as an IDE for
developing Chromium. It's unpolished, but here's what works:
* Editing code works well (especially if you're used to it or Visual Studio).
* Navigating around the code works well. There are multiple ways to do this
(F3, control-click, outlines).
* Building works fairly well and it does a decent job of parsing errors so
that you can click and jump to the problem spot.
* Debugging is hit & miss. You can set breakpoints and view variables. STL
containers give it (and gdb) a bit of trouble. Also, the debugger can get
into a bad state occasionally and eclipse will need to be restarted.
* Refactoring seems to work in some instances, but be afraid of refactors that
touch a lot of files.
[TOC]
## Setup
### Get & Configure Eclipse
Eclipse 4.3 (Kepler) is known to work with Chromium for Linux.
* [Download](http://www.eclipse.org/downloads/) the distribution appropriate
for your OS. For example, for Linux 64-bit/Java 64-bit, use the Linux 64 bit
package (Eclipse Packages Tab -> Linux 64 bit (link in bottom right)).
* Tip: The packaged version of eclipse in distros may not work correctly
with the latest CDT plugin (installed below). Best to get them all from
the same source.
* Googlers: The version installed on Goobuntu works fine. The UI will be
much more responsive if you do not install the google3 plug-ins. Just
uncheck all the boxes at first launch.
* Unpack the distribution and edit the eclipse/eclipse.ini to increase the
heap available to java. For instance:
* Change `-Xms40m` to `-Xms1024m` (minimum heap) and `-Xmx256m` to
`-Xmx3072m` (maximum heap).
* Googlers: Edit `~/.eclipse/init.sh` to add this:
```
export ECLIPSE_MEM_START="1024M"
export ECLIPSE_MEM_MAX="3072M"
```
The large heap size prevents out of memory errors if you include many Chrome
subprojects that Eclipse is maintaining code indices for.
* Turn off Hyperlink detection in the Eclipse preferences. (Window ->
Preferences, search for "Hyperlinking, and uncheck "Enable on demand
hyperlink style navigation").
Pressing the control key on (for keyboard shortcuts such as copy/paste) can
trigger the hyperlink detector. This occurs on the UI thread and can result in
the reading of jar files on the Eclipse classpath, which can tie up the editor
due to the size of the classpath in Chromium.
### A short word about paths
Before you start setting up your work space - here are a few hints:
* Don't put your checkout on a remote file system (e.g. NFS filer). It's too
slow both for building and for Eclipse.
* Make sure there is no file system link in your source path because Ninja
will resolve it for a faster build and Eclipse / GDB will get confused.
(Note: This means that the source will possibly not reside in your user
directory since it would require a link from filer to your local
repository.)
* You may want to start Eclipse from the source root. To do this you can add
an icon to your task bar as launcher. It should point to a shell script
which will set the current path to your source base, and then start Eclipse.
The result would probably look like this:
```shell
~/.bashrc
cd /usr/local/google/chromium/src
export PATH=/home/skuhne/depot_tools:/usr/local/google/goma/goma:/opt/eclipse:/usr/local/symlinks:/usr/local/scripts:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
/opt/eclipse/eclipse -vm /usr/bin/java
```
(Note: Things work fine for me without launching Eclipse from a special
directory. [email protected] 2012-06-1)
### Run Eclipse & Set your workspace
Run eclipse/eclipse in a way that your regular build environment (export CC,
CXX, etc...) will be visible to the eclipse process.
Set the Workspace to be a directory on a local disk (e.g.
`/work/workspaces/chrome`). Placing it on an NFS share is not recommended --
it's too slow and Eclipse will block on access. Don't put the workspace in the
same directory as your checkout.
### Install the C Development Tools ("CDT")
1. From the Help menu, select Install New Software...
1. Select the 'Workd with' URL for the CDT
If it's not there you can click Add... and add it.
See https://eclipse.org/cdt/downloads.php for up to date versions,
e.g. with CDT 8.7.0 for Eclipse Mars, use
http://download.eclipse.org/tools/cdt/releases/8.7
1. Googlers: We have a local mirror, but be sure you run prodaccess before
trying to use it.
1. Select & install the Main and Optional features.
1. Restart Eclipse
1. Go to Window > Open Perspective > Other... > C/C++ to switch to the C++
perspective (window layout).
1. Right-click on the "Java" perspective in the top-right corner and select
"Close" to remove it.
### Create your project(s)
First, turn off automatic workspace refresh and automatic building, as Eclipse
tries to do these too often and gets confused:
1. Open Window > Preferences
1. Search for "workspace"
1. Turn off "Build automatically"
1. Turn off "Refresh using native hooks or polling"
1. Click "Apply"
Chromium uses C++11, so tell the indexer about it. Otherwise it will get
confused about things like std::unique_ptr.
1. Open Window > Preferences > C/C++ > Build > Settings > Discovery >
CDT GCC Build-in Compiler Settings
1. In the text box entitled Command to get compiler specs append "-std=c++11"
Create a single Eclipse project for everything:
1. From the File menu, select New > Project...
1. Select C/C++ Project > Makefile Project with Existing Code
1. Name the project the exact name of the directory: "src"
1. Provide a path to the code, like /work/chromium/src
1. Select toolchain: Linux GCC
1. Click Finish.
Chromium has a huge amount of code, enough that Eclipse can take a very long
time to perform operations like "go to definition" and "open resource". You need
to set it up to operate on a subset of the code.
In the Project Explorer on the left side:
1. Right-click on "src" and select "Properties..."
1. Open Resource > Resource Filters
1. Click "Add..."
1. Add the following filter:
* Include only
* Files, all children (recursive)
* Name matches
`.*\.(c|cc|cpp|h|mm|inl|idl|js|json|css|html|gyp|gypi|grd|grdp|gn)`
regular expression
1. Add another filter:
* Exclude all
* Folders
* Name matches `out_.*|\.git|\.svn|LayoutTests` regular expression
* If you aren't working on WebKit, adding `|WebKit` will remove more
files
1. Click "OK"
Don't exclude the primary "out" directory, as it contains generated header files
for things like string resources and Eclipse will miss a lot of symbols if you
do.
Eclipse will refresh the workspace and start indexing your code. It won't find
most header files, however. Give it more help finding them:
1. Open Window > Preferences
1. Search for "Indexer"
1. Turn on "Allow heuristic resolution of includes"
1. Select "Use active build configuration"
1. Set Cache limits > Index database > Limit relative... to 20%
1. Set Cache limits > Index database > Absolute limit to 256 MB
1. Click "OK"
Now the indexer will find many more include files, regardless of which approach
you take below.
#### Optional: Manual header paths and symbols
You can manually tell Eclipse where to find header files, which will allow it to
create the source code index before you do a real build.
1. Right-click on "src" and select "Properties..."
* Open C++ General > Paths and Symbols > Includes
* Click "GNU C++"
* Click "Add..."
* Add `/path/to/chromium/src`
* Check "Add to all configurations" and "Add to all languages"
1. Repeat the above for:
* `/path/to/chromium/src/testing/gtest/include`
You may also find it helpful to define some symbols.
1. Add `OS_LINUX`:
* Select the "Symbols" tab
* Click "GNU C++"
* Click "Add..."
* Add name `OS_LINUX` with value 1
* Click "Add to all configurations" and "Add to all languages"
1. Repeat for `ENABLE_EXTENSIONS 1`
1. Repeat for `HAS_OUT_OF_PROC_TEST_RUNNER 1`
1. Click "OK".
1. Eclipse will ask if you want to rebuild the index. Click "Yes".
Let the C++ indexer run. It will take a while (10s of minutes).
### Optional: Building inside Eclipse
This allows Eclipse to automatically discover include directories and symbols.
If you use gold or ninja (both recommended) you'll need to tell Eclipse about
your path.
1. echo $PATH from a shell and copy it to the clipboard
1. Open Window > Preferences > C/C++ > Build > Environment
1. Select "Replace native environment with specified one" (since gold and ninja
must be at the start of your path)
1. Click "Add..."
1. For name, enter `PATH`
1. For value, paste in your path with the ninja and gold directories.
1. Click "OK"
To create a Make target:
1. From the Window menu, select Show View > Make Target
1. In the Make Target view, right-click on the project and select New...
1. name the target (e.g. base\_unittests)
1. Unclick the Build Command: Use builder Settings and type whatever build
command you would use to build this target (e.g.
`ninja -C out/Debug base_unittests`).
1. Return to the project properties page a under the C/C++ Build, change the
Build Location/Build Directory to be /path/to/chromium/src
1. In theory `${workspace_loc}` should work, but it doesn't for me.
1. If you put your workspace in `/path/to/chromium`, then
`${workspace_loc:/src}` will work too.
1. Now in the Make Targets view, select the target and click the hammer icon
(Build Make Target).
You should see the build proceeding in the Console View and errors will be
parsed and appear in the Problems View. (Note that sometimes multi-line compiler
errors only show up partially in the Problems view and you'll want to look at
the full error in the Console).
(Eclipse 3.8 has a bug where the console scrolls too slowly if you're doing a
fast build, e.g. with goma. To work around, go to Window > Preferences and
search for "console". Under C/C++ console, set "Limit console output" to
2147483647, the maximum value.)
### Optional: Multiple build targets
If you want to build multiple different targets in Eclipse (`chrome`,
`unit_tests`, etc.):
1. Window > Show Toolbar (if you had it off)
1. Turn on special toolbar menu item (hammer) or menu bar item (Project > Build
configurations > Set Active > ...)
1. Window > Customize Perspective... > "Command Groups Availability"
1. Check "Build configuration"
1. Add more Build targets
1. Project > Properties > C/C++ Build > Manage Configurations
1. Select "New..."
1. Duplicate from current and give it a name like "Unit tests".
1. Change under “Behavior” > Build > the target to e.g. `unit_tests`.
You can also drag the toolbar to the bottom of your window to save vertical
space.
### Optional: Debugging
1. From the toolbar at the top, click the arrow next to the debug icon and
select Debug Configurations...
1. Select C/C++ Application and click the New Launch Configuration icon. This
will create a new run/debug con figuration under the C/C++ Application header.
1. Name it something useful (e.g. `base_unittests`).
1. Under the Main Tab, enter the path to the executable (e.g.
`.../out/Debug/base_unittests`)
1. Select the Debugger Tab, select Debugger: gdb and unclick "Stop on startup
in (main)" unless you want this.
1. Set a breakpoint somewhere in your code and click the debug icon to start
debugging.
### Optional: Accurate symbol information
If setup properly, Eclipse can do a great job of semantic navigation of C++ code
(showing type hierarchies, finding all references to a particular method even
when other classes have methods of the same name, etc.). But doing this well
requires the Eclipse knows correct include paths and pre-processor definitions.
After fighting with with a number of approaches, I've found the below to work
best for me.
*The instrcutions below are out-of-date since it references GYP. Please see
`gn help gen` for how to generate an Eclipse CDT file in GN. If you use
Eclipse and make it work, please update this documentation.*
1. From a shell in your src directory, run
`GYP_GENERATORS=ninja,eclipse build/gyp_chromium`
1. This generates <project root>/out/Debug/eclipse-cdt-settings.xml which
is used below.
1. This creates a single list of include directories and preprocessor
definitions to be used for all source files, and so is a little
inaccurate. Here are some tips for compensating for the limitations:
1. Use `-R <target>` to restrict the output to considering only certain
targets (avoiding unnecessary includes that are likely to cause
trouble). Eg. for a blink project, use `-R blink`.
1. If you care about blink, move 'third\_party/Webkit/Source' to the
top of the list to better resolve ambiguous include paths (eg.
`config.h`).
1. Import paths and symbols
1. Right click on the project and select Properties > C/C++ General > Paths
and Symbols
1. Click Restore Defaults to clear any old settings
1. Click Import Settings... > Browse... and select
`<project root>/out/Debug/eclipse-cdt-settings.xml`
1. Click the Finish button. The entire preferences dialog should go away.
1. Right click on the project and select Index > Rebuild
### Alternative: Per-file accurate include/pre-processor information
Instead of generating a fixed list of include paths and pre-processor
definitions for a project (above), it is also possible to have Eclipse determine
the correct setting on a file-by-file basis using a built output parser. I
(rbyers) used this successfully for a long time, but it doesn't seem much better
in practice than the simpler (and less bug-prone) approach above.
1. Install the latest version of Eclipse IDE for C/C++ developers
([Juno SR1](http://www.eclipse.org/downloads/packages/eclipse-ide-cc-developers/junosr1)
at the time of this writing)
1. Setup build to generate a build log that includes the g++ command lines for
the files you want to index:
1. Project Properties -> C/C++ Build
1. Uncheck "Use default build command"
1. Enter your build command, eg: `ninja -v`
1. Note that for better performance, you can use a command that
doesn't actually builds, just prints the commands that would be
run. For ninja/make this means adding -n. This only prints the
compile commands for changed files (so be sure to move your
existing out directory out of the way temporarily to force a
full "build"). ninja also supports "-t commands" which will
print all build commands for the specified target and runs even
faster as it doesn't have to check file timestamps.
1. Build directory: your build path including out/Debug
1. Note that for the relative paths to be parsed correctly you
can't use ninja's `-C <dir>` to change directories as you might
from the command line.
1. Build: potentially change `all` to the target you want to analyze,
eg. `chrome`
1. Deselect 'clean'
1. If you're using Ninja, you need to teach eclipse to ignore the prefix it
adds (eg. `[10/1234]` to each line in build output):
1. Project properties -> C/C++ General -> Preprocessor includes
1. Providers -> CDT GCC Build Output Parser -> Compiler command pattern
1. `(\[.*\] )?((gcc)|([gc]\+\+)|(clang(\+\+)?))`
1. Note that there appears to be a bug with "Share setting entries
between projects" - it will keep resetting to off. I suggest using
per-project settings and using the "folder" as the container to keep
discovered entries ("file" may work as well).
1. Eclipse / GTK has bugs where lots of output to the build console can
slow down the UI dramatically and cause it to hang (basically spends all
it's time trying to position the cursor correctly in the build console
window). To avoid this, close the console window and disable
automatically opening it on build:
1. Preferences->C/C++->Build->Console -> Uncheck "Open console when
building"
1. note you can still see the build log in
`<workspace>/.metadata/.plugins/org.eclipse.cdt.ui`
1. Now build the project (select project, click on hammer). If all went well:
1. Right click on a cpp file -> properties -> C/C++ general -> Preprocessor
includes -> GNU C++ -> CDT GCC Build output Parser
1. You will be able to expand and see all the include paths and
pre-processor definitions used for this file
1. Rebuild index (right-click on project, index, rebuild). If all went well:
1. Open a CPP file and look at problems windows
1. Should be no (or very few) errors
1. Should be able to hit F3 on most symbols and jump to their definitioin
1. CDT has some issues with complex C++ syntax like templates (eg.
`PassOwnPtr` functions)
1. See
[this page](http://wiki.eclipse.org/CDT/User/FAQ#Why_does_Open_Declaration_.28F3.29_not_work.3F_.28also_applies_to_other_functions_using_the_indexer.29)
for more information.
### Optional: static code and style guide analysis using cpplint.py
1. From the toolbar at the top, click the Project -> Properties and go to
C/C++Build.
1. Click on the right side of the pop up windows, "Manage
Configurations...", then on New, and give it a name, f.i. "Lint current
file", and close the small window, then select it in the Configuration
drop down list.
1. Under Builder settings tab, unclick "Use default build command" and type
as build command the full path to your `depot_tools/cpplint.py`
1. Under behaviour tab, unselect Clean, select Build(incremental build) and
in Make build target, add `--verbose=0 ${selected_resource_loc}`
1. Go back to the left side of the current window, and to C/C++Build ->
Settings, and click on error parsers tab, make sure CDT GNU C/C++ Error
Parser, CDT pushd/popd CWD Locator are set, then click Apply and OK.
1. Select a file and click on the hammer icon drop down triangle next to it,
and make sure the build configuration is selected "Lint current file", then
click on the hammer.
1. Note: If you get the `cpplint.py help` output, make sure you have selected a
file, by clicking inside the editor window or on its tab header, and make
sure the editor is not maximized inside Eclipse, i.e. you should see more
subwindows around.
### Additional tips
1. Mozilla's
[Eclipse CDT guide](https://developer.mozilla.org/en-US/docs/Eclipse_CDT)
is helpful:
1. For improved performance, I use medium-granularity projects (eg. one for
WebKit/Source) instead of putting all of 'src/' in one project.
1. For working in Blink (which uses WebKit code style), feel free to use
[this](https://drive.google.com/file/d/0B2LVVIKSxUVYM3R6U0tUa1dmY0U/view?usp=sharing)
code-style formatter XML profile
| Java |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef NET_SPDY_SPDY_FRAMER_H_
#define NET_SPDY_SPDY_FRAMER_H_
#include <map>
#include <memory>
#include <string>
#include <utility>
#include "base/gtest_prod_util.h"
#include "base/memory/scoped_ptr.h"
#include "base/strings/string_piece.h"
#include "base/sys_byteorder.h"
#include "net/base/net_export.h"
#include "net/spdy/hpack/hpack_decoder.h"
#include "net/spdy/hpack/hpack_encoder.h"
#include "net/spdy/spdy_alt_svc_wire_format.h"
#include "net/spdy/spdy_header_block.h"
#include "net/spdy/spdy_protocol.h"
// TODO(akalin): Remove support for CREDENTIAL frames.
typedef struct z_stream_s z_stream; // Forward declaration for zlib.
namespace net {
class HttpProxyClientSocketPoolTest;
class HttpNetworkLayer;
class HttpNetworkTransactionTest;
class SpdyHttpStreamTest;
class SpdyNetworkTransactionTest;
class SpdyProxyClientSocketTest;
class SpdySessionTest;
class SpdyStreamTest;
class SpdyFramer;
class SpdyFrameBuilder;
namespace test {
class TestSpdyVisitor;
class SpdyFramerPeer;
} // namespace test
// A datastructure for holding the ID and flag fields for SETTINGS.
// Conveniently handles converstion to/from wire format.
class NET_EXPORT_PRIVATE SettingsFlagsAndId {
public:
static SettingsFlagsAndId FromWireFormat(SpdyMajorVersion version,
uint32 wire);
SettingsFlagsAndId() : flags_(0), id_(0) {}
// TODO(hkhalil): restrict to enums instead of free-form ints.
SettingsFlagsAndId(uint8 flags, uint32 id);
uint32 GetWireFormat(SpdyMajorVersion version) const;
uint32 id() const { return id_; }
uint8 flags() const { return flags_; }
private:
static void ConvertFlagsAndIdForSpdy2(uint32* val);
uint8 flags_;
uint32 id_;
};
// SettingsMap has unique (flags, value) pair for given SpdySettingsIds ID.
typedef std::pair<SpdySettingsFlags, uint32> SettingsFlagsAndValue;
typedef std::map<SpdySettingsIds, SettingsFlagsAndValue> SettingsMap;
// SpdyFramerVisitorInterface is a set of callbacks for the SpdyFramer.
// Implement this interface to receive event callbacks as frames are
// decoded from the framer.
//
// Control frames that contain SPDY header blocks (SYN_STREAM, SYN_REPLY,
// HEADER, and PUSH_PROMISE) are processed in fashion that allows the
// decompressed header block to be delivered in chunks to the visitor.
// The following steps are followed:
// 1. OnSynStream, OnSynReply, OnHeaders, or OnPushPromise is called.
// 2. Repeated: OnControlFrameHeaderData is called with chunks of the
// decompressed header block. In each call the len parameter is greater
// than zero.
// 3. OnControlFrameHeaderData is called with len set to zero, indicating
// that the full header block has been delivered for the control frame.
// During step 2 the visitor may return false, indicating that the chunk of
// header data could not be handled by the visitor (typically this indicates
// resource exhaustion). If this occurs the framer will discontinue
// delivering chunks to the visitor, set a SPDY_CONTROL_PAYLOAD_TOO_LARGE
// error, and clean up appropriately. Note that this will cause the header
// decompressor to lose synchronization with the sender's header compressor,
// making the SPDY session unusable for future work. The visitor's OnError
// function should deal with this condition by closing the SPDY connection.
class NET_EXPORT_PRIVATE SpdyFramerVisitorInterface {
public:
virtual ~SpdyFramerVisitorInterface() {}
// Called if an error is detected in the SpdyFrame protocol.
virtual void OnError(SpdyFramer* framer) = 0;
// Called when a data frame header is received. The frame's data
// payload will be provided via subsequent calls to
// OnStreamFrameData().
virtual void OnDataFrameHeader(SpdyStreamId stream_id,
size_t length,
bool fin) = 0;
// Called when data is received.
// |stream_id| The stream receiving data.
// |data| A buffer containing the data received.
// |len| The length of the data buffer.
// When the other side has finished sending data on this stream,
// this method will be called with a zero-length buffer.
virtual void OnStreamFrameData(SpdyStreamId stream_id,
const char* data,
size_t len,
bool fin) = 0;
// Called when padding is received (padding length field or padding octets).
// |stream_id| The stream receiving data.
// |len| The number of padding octets.
virtual void OnStreamPadding(SpdyStreamId stream_id, size_t len) = 0;
// Called when a chunk of header data is available. This is called
// after OnSynStream, OnSynReply, OnHeaders(), or OnPushPromise.
// |stream_id| The stream receiving the header data.
// |header_data| A buffer containing the header data chunk received.
// |len| The length of the header data buffer. A length of zero indicates
// that the header data block has been completely sent.
// When this function returns true the visitor indicates that it accepted
// all of the data. Returning false indicates that that an unrecoverable
// error has occurred, such as bad header data or resource exhaustion.
virtual bool OnControlFrameHeaderData(SpdyStreamId stream_id,
const char* header_data,
size_t len) = 0;
// Called when a SYN_STREAM frame is received.
// Note that header block data is not included. See
// OnControlFrameHeaderData().
virtual void OnSynStream(SpdyStreamId stream_id,
SpdyStreamId associated_stream_id,
SpdyPriority priority,
bool fin,
bool unidirectional) = 0;
// Called when a SYN_REPLY frame is received.
// Note that header block data is not included. See
// OnControlFrameHeaderData().
virtual void OnSynReply(SpdyStreamId stream_id, bool fin) = 0;
// Called when a RST_STREAM frame has been parsed.
virtual void OnRstStream(SpdyStreamId stream_id,
SpdyRstStreamStatus status) = 0;
// Called when a SETTINGS frame is received.
// |clear_persisted| True if the respective flag is set on the SETTINGS frame.
virtual void OnSettings(bool clear_persisted) {}
// Called when a complete setting within a SETTINGS frame has been parsed and
// validated.
virtual void OnSetting(SpdySettingsIds id, uint8 flags, uint32 value) = 0;
// Called when a SETTINGS frame is received with the ACK flag set.
virtual void OnSettingsAck() {}
// Called before and after parsing SETTINGS id and value tuples.
virtual void OnSettingsEnd() = 0;
// Called when a PING frame has been parsed.
virtual void OnPing(SpdyPingId unique_id, bool is_ack) = 0;
// Called when a GOAWAY frame has been parsed.
virtual void OnGoAway(SpdyStreamId last_accepted_stream_id,
SpdyGoAwayStatus status) = 0;
// Called when a HEADERS frame is received.
// Note that header block data is not included. See
// OnControlFrameHeaderData().
// |stream_id| The stream receiving the header.
// |has_priority| Whether or not the headers frame included a priority value,
// and, if protocol version >= HTTP2, stream dependency info.
// |priority| If |has_priority| is true and protocol version > SPDY3,
// priority value for the receiving stream, else 0.
// |parent_stream_id| If |has_priority| is true and protocol
// version >= HTTP2, the parent stream of the receiving stream, else 0.
// |exclusive| If |has_priority| is true and protocol
// version >= HTTP2, the exclusivity of dependence on the parent stream,
// else false.
// |fin| Whether FIN flag is set in frame headers.
// |end| False if HEADERs frame is to be followed by a CONTINUATION frame,
// or true if not.
virtual void OnHeaders(SpdyStreamId stream_id,
bool has_priority,
SpdyPriority priority,
SpdyStreamId parent_stream_id,
bool exclusive,
bool fin,
bool end) = 0;
// Called when a WINDOW_UPDATE frame has been parsed.
virtual void OnWindowUpdate(SpdyStreamId stream_id,
int delta_window_size) = 0;
// Called when a goaway frame opaque data is available.
// |goaway_data| A buffer containing the opaque GOAWAY data chunk received.
// |len| The length of the header data buffer. A length of zero indicates
// that the header data block has been completely sent.
// When this function returns true the visitor indicates that it accepted
// all of the data. Returning false indicates that that an error has
// occurred while processing the data. Default implementation returns true.
virtual bool OnGoAwayFrameData(const char* goaway_data, size_t len);
// Called when rst_stream frame opaque data is available.
// |rst_stream_data| A buffer containing the opaque RST_STREAM
// data chunk received.
// |len| The length of the header data buffer. A length of zero indicates
// that the opaque data has been completely sent.
// When this function returns true the visitor indicates that it accepted
// all of the data. Returning false indicates that that an error has
// occurred while processing the data. Default implementation returns true.
virtual bool OnRstStreamFrameData(const char* rst_stream_data, size_t len);
// Called when a BLOCKED frame has been parsed.
virtual void OnBlocked(SpdyStreamId stream_id) {}
// Called when a PUSH_PROMISE frame is received.
// Note that header block data is not included. See
// OnControlFrameHeaderData().
virtual void OnPushPromise(SpdyStreamId stream_id,
SpdyStreamId promised_stream_id,
bool end) = 0;
// Called when a CONTINUATION frame is received.
// Note that header block data is not included. See
// OnControlFrameHeaderData().
virtual void OnContinuation(SpdyStreamId stream_id, bool end) = 0;
// Called when an ALTSVC frame has been parsed.
virtual void OnAltSvc(
SpdyStreamId stream_id,
base::StringPiece origin,
const SpdyAltSvcWireFormat::AlternativeServiceVector& altsvc_vector) {}
// Called when a PRIORITY frame is received.
virtual void OnPriority(SpdyStreamId stream_id,
SpdyStreamId parent_stream_id,
uint8 weight,
bool exclusive) {}
// Called when a frame type we don't recognize is received.
// Return true if this appears to be a valid extension frame, false otherwise.
// We distinguish between extension frames and nonsense by checking
// whether the stream id is valid.
virtual bool OnUnknownFrame(SpdyStreamId stream_id, int frame_type) = 0;
};
// Optionally, and in addition to SpdyFramerVisitorInterface, a class supporting
// SpdyFramerDebugVisitorInterface may be used in conjunction with SpdyFramer in
// order to extract debug/internal information about the SpdyFramer as it
// operates.
//
// Most SPDY implementations need not bother with this interface at all.
class NET_EXPORT_PRIVATE SpdyFramerDebugVisitorInterface {
public:
virtual ~SpdyFramerDebugVisitorInterface() {}
// Called after compressing a frame with a payload of
// a list of name-value pairs.
// |payload_len| is the uncompressed payload size.
// |frame_len| is the compressed frame size.
virtual void OnSendCompressedFrame(SpdyStreamId stream_id,
SpdyFrameType type,
size_t payload_len,
size_t frame_len) {}
// Called when a frame containing a compressed payload of
// name-value pairs is received.
// |frame_len| is the compressed frame size.
virtual void OnReceiveCompressedFrame(SpdyStreamId stream_id,
SpdyFrameType type,
size_t frame_len) {}
};
class NET_EXPORT_PRIVATE SpdyFramer {
public:
// SPDY states.
// TODO(mbelshe): Can we move these into the implementation
// and avoid exposing through the header. (Needed for test)
enum SpdyState {
SPDY_ERROR,
SPDY_READY_FOR_FRAME, // Framer is ready for reading the next frame.
SPDY_FRAME_COMPLETE, // Framer has finished reading a frame, need to reset.
SPDY_READING_COMMON_HEADER,
SPDY_CONTROL_FRAME_PAYLOAD,
SPDY_READ_DATA_FRAME_PADDING_LENGTH,
SPDY_CONSUME_PADDING,
SPDY_IGNORE_REMAINING_PAYLOAD,
SPDY_FORWARD_STREAM_FRAME,
SPDY_CONTROL_FRAME_BEFORE_HEADER_BLOCK,
SPDY_CONTROL_FRAME_HEADER_BLOCK,
SPDY_GOAWAY_FRAME_PAYLOAD,
SPDY_RST_STREAM_FRAME_PAYLOAD,
SPDY_SETTINGS_FRAME_PAYLOAD,
SPDY_ALTSVC_FRAME_PAYLOAD,
};
// SPDY error codes.
enum SpdyError {
SPDY_NO_ERROR,
SPDY_INVALID_CONTROL_FRAME, // Control frame is mal-formatted.
SPDY_CONTROL_PAYLOAD_TOO_LARGE, // Control frame payload was too large.
SPDY_ZLIB_INIT_FAILURE, // The Zlib library could not initialize.
SPDY_UNSUPPORTED_VERSION, // Control frame has unsupported version.
SPDY_DECOMPRESS_FAILURE, // There was an error decompressing.
SPDY_COMPRESS_FAILURE, // There was an error compressing.
SPDY_GOAWAY_FRAME_CORRUPT, // GOAWAY frame could not be parsed.
SPDY_RST_STREAM_FRAME_CORRUPT, // RST_STREAM frame could not be parsed.
SPDY_INVALID_DATA_FRAME_FLAGS, // Data frame has invalid flags.
SPDY_INVALID_CONTROL_FRAME_FLAGS, // Control frame has invalid flags.
SPDY_UNEXPECTED_FRAME, // Frame received out of order.
LAST_ERROR, // Must be the last entry in the enum.
};
// Constant for invalid (or unknown) stream IDs.
static const SpdyStreamId kInvalidStream;
// The maximum size of header data chunks delivered to the framer visitor
// through OnControlFrameHeaderData. (It is exposed here for unit test
// purposes.)
static const size_t kHeaderDataChunkMaxSize;
// Serializes a SpdyHeaderBlock.
static void WriteHeaderBlock(SpdyFrameBuilder* frame,
const SpdyMajorVersion spdy_version,
const SpdyHeaderBlock* headers);
// Retrieve serialized length of SpdyHeaderBlock.
// TODO(hkhalil): Remove, or move to quic code.
static size_t GetSerializedLength(
const SpdyMajorVersion spdy_version,
const SpdyHeaderBlock* headers);
// Create a new Framer, provided a SPDY version.
explicit SpdyFramer(SpdyMajorVersion version);
virtual ~SpdyFramer();
// Set callbacks to be called from the framer. A visitor must be set, or
// else the framer will likely crash. It is acceptable for the visitor
// to do nothing. If this is called multiple times, only the last visitor
// will be used.
void set_visitor(SpdyFramerVisitorInterface* visitor) {
visitor_ = visitor;
}
// Set debug callbacks to be called from the framer. The debug visitor is
// completely optional and need not be set in order for normal operation.
// If this is called multiple times, only the last visitor will be used.
void set_debug_visitor(SpdyFramerDebugVisitorInterface* debug_visitor) {
debug_visitor_ = debug_visitor;
}
// Sets whether or not ProcessInput returns after finishing a frame, or
// continues processing additional frames. Normally ProcessInput processes
// all input, but this method enables the caller (and visitor) to work with
// a single frame at a time (or that portion of the frame which is provided
// as input). Reset() does not change the value of this flag.
void set_process_single_input_frame(bool v) {
process_single_input_frame_ = v;
}
// Pass data into the framer for parsing.
// Returns the number of bytes consumed. It is safe to pass more bytes in
// than may be consumed.
size_t ProcessInput(const char* data, size_t len);
// Resets the framer state after a frame has been successfully decoded.
// TODO(mbelshe): can we make this private?
void Reset();
// Check the state of the framer.
SpdyError error_code() const { return error_code_; }
SpdyState state() const { return state_; }
bool HasError() const { return state_ == SPDY_ERROR; }
// Given a buffer containing a decompressed header block in SPDY
// serialized format, parse out a SpdyHeaderBlock, putting the results
// in the given header block.
// Returns number of bytes consumed if successfully parsed, 0 otherwise.
size_t ParseHeaderBlockInBuffer(const char* header_data,
size_t header_length,
SpdyHeaderBlock* block) const;
// Serialize a data frame.
SpdySerializedFrame* SerializeData(const SpdyDataIR& data) const;
// Serializes the data frame header and optionally padding length fields,
// excluding actual data payload and padding.
SpdySerializedFrame* SerializeDataFrameHeaderWithPaddingLengthField(
const SpdyDataIR& data) const;
// Serializes a SYN_STREAM frame.
SpdySerializedFrame* SerializeSynStream(const SpdySynStreamIR& syn_stream);
// Serialize a SYN_REPLY SpdyFrame.
SpdySerializedFrame* SerializeSynReply(const SpdySynReplyIR& syn_reply);
SpdySerializedFrame* SerializeRstStream(
const SpdyRstStreamIR& rst_stream) const;
// Serializes a SETTINGS frame. The SETTINGS frame is
// used to communicate name/value pairs relevant to the communication channel.
SpdySerializedFrame* SerializeSettings(const SpdySettingsIR& settings) const;
// Serializes a PING frame. The unique_id is used to
// identify the ping request/response.
SpdySerializedFrame* SerializePing(const SpdyPingIR& ping) const;
// Serializes a GOAWAY frame. The GOAWAY frame is used
// prior to the shutting down of the TCP connection, and includes the
// stream_id of the last stream the sender of the frame is willing to process
// to completion.
SpdySerializedFrame* SerializeGoAway(const SpdyGoAwayIR& goaway) const;
// Serializes a HEADERS frame. The HEADERS frame is used
// for sending additional headers outside of a SYN_STREAM/SYN_REPLY.
SpdySerializedFrame* SerializeHeaders(const SpdyHeadersIR& headers);
// Serializes a WINDOW_UPDATE frame. The WINDOW_UPDATE
// frame is used to implement per stream flow control in SPDY.
SpdySerializedFrame* SerializeWindowUpdate(
const SpdyWindowUpdateIR& window_update) const;
// Serializes a BLOCKED frame. The BLOCKED frame is used to
// indicate to the remote endpoint that this endpoint believes itself to be
// flow-control blocked but otherwise ready to send data. The BLOCKED frame
// is purely advisory and optional.
SpdySerializedFrame* SerializeBlocked(const SpdyBlockedIR& blocked) const;
// Serializes a PUSH_PROMISE frame. The PUSH_PROMISE frame is used
// to inform the client that it will be receiving an additional stream
// in response to the original request. The frame includes synthesized
// headers to explain the upcoming data.
SpdySerializedFrame* SerializePushPromise(
const SpdyPushPromiseIR& push_promise);
// Serializes a CONTINUATION frame. The CONTINUATION frame is used
// to continue a sequence of header block fragments.
// TODO(jgraettinger): This implementation is incorrect. The continuation
// frame continues a previously-begun HPACK encoding; it doesn't begin a
// new one. Figure out whether it makes sense to keep SerializeContinuation().
SpdySerializedFrame* SerializeContinuation(
const SpdyContinuationIR& continuation);
// Serializes an ALTSVC frame. The ALTSVC frame advertises the
// availability of an alternative service to the client.
SpdySerializedFrame* SerializeAltSvc(const SpdyAltSvcIR& altsvc);
// Serializes a PRIORITY frame. The PRIORITY frame advises a change in
// the relative priority of the given stream.
SpdySerializedFrame* SerializePriority(const SpdyPriorityIR& priority) const;
// Serialize a frame of unknown type.
SpdySerializedFrame* SerializeFrame(const SpdyFrameIR& frame);
// NOTES about frame compression.
// We want spdy to compress headers across the entire session. As long as
// the session is over TCP, frames are sent serially. The client & server
// can each compress frames in the same order and then compress them in that
// order, and the remote can do the reverse. However, we ultimately want
// the creation of frames to be less sensitive to order so that they can be
// placed over a UDP based protocol and yet still benefit from some
// compression. We don't know of any good compression protocol which does
// not build its state in a serial (stream based) manner.... For now, we're
// using zlib anyway.
// Compresses a SpdyFrame.
// On success, returns a new SpdyFrame with the payload compressed.
// Compression state is maintained as part of the SpdyFramer.
// Returned frame must be freed with "delete".
// On failure, returns NULL.
SpdyFrame* CompressFrame(const SpdyFrame& frame);
// For ease of testing and experimentation we can tweak compression on/off.
void set_enable_compression(bool value) {
enable_compression_ = value;
}
// Used only in log messages.
void set_display_protocol(const std::string& protocol) {
display_protocol_ = protocol;
}
// Returns the (minimum) size of frames (sans variable-length portions).
size_t GetDataFrameMinimumSize() const;
size_t GetControlFrameHeaderSize() const;
size_t GetSynStreamMinimumSize() const;
size_t GetSynReplyMinimumSize() const;
size_t GetRstStreamMinimumSize() const;
size_t GetSettingsMinimumSize() const;
size_t GetPingSize() const;
size_t GetGoAwayMinimumSize() const;
size_t GetHeadersMinimumSize() const;
size_t GetWindowUpdateSize() const;
size_t GetBlockedSize() const;
size_t GetPushPromiseMinimumSize() const;
size_t GetContinuationMinimumSize() const;
size_t GetAltSvcMinimumSize() const;
size_t GetPrioritySize() const;
// Returns the minimum size a frame can be (data or control).
size_t GetFrameMinimumSize() const;
// Returns the maximum size a frame can be (data or control).
size_t GetFrameMaximumSize() const;
// Returns the maximum payload size of a DATA frame.
size_t GetDataFrameMaximumPayload() const;
// Returns the prefix length for the given frame type.
size_t GetPrefixLength(SpdyFrameType type) const;
// For debugging.
static const char* StateToString(int state);
static const char* ErrorCodeToString(int error_code);
static const char* StatusCodeToString(int status_code);
static const char* FrameTypeToString(SpdyFrameType type);
SpdyMajorVersion protocol_version() const { return protocol_version_; }
bool probable_http_response() const { return probable_http_response_; }
SpdyPriority GetLowestPriority() const {
return protocol_version_ < SPDY3 ? 3 : 7;
}
SpdyPriority GetHighestPriority() const { return 0; }
// Interpolates SpdyPriority values into SPDY4/HTTP2 priority weights,
// and vice versa.
static uint8 MapPriorityToWeight(SpdyPriority priority);
static SpdyPriority MapWeightToPriority(uint8 weight);
// Deliver the given control frame's compressed headers block to the visitor
// in decompressed form, in chunks. Returns true if the visitor has
// accepted all of the chunks.
bool IncrementallyDecompressControlFrameHeaderData(
SpdyStreamId stream_id,
const char* data,
size_t len);
// Updates the maximum size of header compression table.
void UpdateHeaderTableSizeSetting(uint32 value);
// Returns bound of header compression table size.
size_t header_table_size_bound() const;
protected:
friend class HttpNetworkLayer; // This is temporary for the server.
friend class HttpNetworkTransactionTest;
friend class HttpProxyClientSocketPoolTest;
friend class SpdyHttpStreamTest;
friend class SpdyNetworkTransactionTest;
friend class SpdyProxyClientSocketTest;
friend class SpdySessionTest;
friend class SpdyStreamTest;
friend class test::TestSpdyVisitor;
friend class test::SpdyFramerPeer;
private:
class CharBuffer {
public:
explicit CharBuffer(size_t capacity);
~CharBuffer();
void CopyFrom(const char* data, size_t size);
void Rewind();
const char* data() const { return buffer_.get(); }
size_t len() const { return len_; }
private:
scoped_ptr<char[]> buffer_;
size_t capacity_;
size_t len_;
};
// Scratch space necessary for processing SETTINGS frames.
struct SpdySettingsScratch {
SpdySettingsScratch();
void Reset();
// Buffer contains up to one complete key/value pair.
CharBuffer buffer;
// The ID of the last setting that was processed in the current SETTINGS
// frame. Used for detecting out-of-order or duplicate keys within a
// settings frame. Set to -1 before first key/value pair is processed.
int last_setting_id;
};
// Internal breakouts from ProcessInput. Each returns the number of bytes
// consumed from the data.
size_t ProcessCommonHeader(const char* data, size_t len);
size_t ProcessControlFramePayload(const char* data, size_t len);
size_t ProcessControlFrameBeforeHeaderBlock(const char* data, size_t len);
// HPACK data is re-encoded as SPDY3 and re-entrantly delivered through
// |ProcessControlFrameHeaderBlock()|. |is_hpack_header_block| controls
// whether data is treated as HPACK- vs SPDY3-encoded.
size_t ProcessControlFrameHeaderBlock(const char* data,
size_t len,
bool is_hpack_header_block);
size_t ProcessDataFramePaddingLength(const char* data, size_t len);
size_t ProcessFramePadding(const char* data, size_t len);
size_t ProcessDataFramePayload(const char* data, size_t len);
size_t ProcessGoAwayFramePayload(const char* data, size_t len);
size_t ProcessRstStreamFramePayload(const char* data, size_t len);
size_t ProcessSettingsFramePayload(const char* data, size_t len);
size_t ProcessAltSvcFramePayload(const char* data, size_t len);
size_t ProcessIgnoredControlFramePayload(/*const char* data,*/ size_t len);
// TODO(jgraettinger): To be removed with migration to
// SpdyHeadersHandlerInterface. Serializes the last-processed
// header block of |hpack_decoder_| as a SPDY3 format block, and
// delivers it to the visitor via reentrant call to
// ProcessControlFrameHeaderBlock(). |compressed_len| is used for
// logging compression percentage.
void DeliverHpackBlockAsSpdy3Block(size_t compressed_len);
// Helpers for above internal breakouts from ProcessInput.
void ProcessControlFrameHeader(int control_frame_type_field);
// Always passed exactly 1 setting's worth of data.
bool ProcessSetting(const char* data);
// Retrieve serialized length of SpdyHeaderBlock. If compression is enabled, a
// maximum estimate is returned.
size_t GetSerializedLength(const SpdyHeaderBlock& headers);
// Get (and lazily initialize) the ZLib state.
z_stream* GetHeaderCompressor();
z_stream* GetHeaderDecompressor();
// Get (and lazily initialize) the HPACK state.
HpackEncoder* GetHpackEncoder();
HpackDecoder* GetHpackDecoder();
size_t GetNumberRequiredContinuationFrames(size_t size);
void WritePayloadWithContinuation(SpdyFrameBuilder* builder,
const std::string& hpack_encoding,
SpdyStreamId stream_id,
SpdyFrameType type,
int padding_payload_len);
// Deliver the given control frame's uncompressed headers block to the
// visitor in chunks. Returns true if the visitor has accepted all of the
// chunks.
bool IncrementallyDeliverControlFrameHeaderData(SpdyStreamId stream_id,
const char* data,
size_t len);
// Utility to copy the given data block to the current frame buffer, up
// to the given maximum number of bytes, and update the buffer
// data (pointer and length). Returns the number of bytes
// read, and:
// *data is advanced the number of bytes read.
// *len is reduced by the number of bytes read.
size_t UpdateCurrentFrameBuffer(const char** data, size_t* len,
size_t max_bytes);
void WriteHeaderBlockToZ(const SpdyHeaderBlock* headers,
z_stream* out) const;
void SerializeHeaderBlockWithoutCompression(
SpdyFrameBuilder* builder,
const SpdyHeaderBlock& header_block) const;
// Compresses automatically according to enable_compression_.
void SerializeHeaderBlock(SpdyFrameBuilder* builder,
const SpdyFrameWithHeaderBlockIR& frame);
// Set the error code and moves the framer into the error state.
void set_error(SpdyError error);
// The size of the control frame buffer.
// Since this is only used for control frame headers, the maximum control
// frame header size (SYN_STREAM) is sufficient; all remaining control
// frame data is streamed to the visitor.
static const size_t kControlFrameBufferSize;
// The maximum size of the control frames that we support.
// This limit is arbitrary. We can enforce it here or at the application
// layer. We chose the framing layer, but this can be changed (or removed)
// if necessary later down the line.
static const size_t kMaxControlFrameSize;
SpdyState state_;
SpdyState previous_state_;
SpdyError error_code_;
// Note that for DATA frame, remaining_data_length_ is sum of lengths of
// frame header, padding length field (optional), data payload (optional) and
// padding payload (optional).
size_t remaining_data_length_;
// The length (in bytes) of the padding payload to be processed.
size_t remaining_padding_payload_length_;
// The number of bytes remaining to read from the current control frame's
// headers. Note that header data blocks (for control types that have them)
// are part of the frame's payload, and not the frame's headers.
size_t remaining_control_header_;
CharBuffer current_frame_buffer_;
// The type of the frame currently being read.
SpdyFrameType current_frame_type_;
// The total length of the frame currently being read, including frame header.
uint32 current_frame_length_;
// The stream ID field of the frame currently being read, if applicable.
SpdyStreamId current_frame_stream_id_;
// Set this to the current stream when we receive a HEADERS, PUSH_PROMISE, or
// CONTINUATION frame without the END_HEADERS(0x4) bit set. These frames must
// be followed by a CONTINUATION frame, or else we throw a PROTOCOL_ERROR.
// A value of 0 indicates that we are not expecting a CONTINUATION frame.
SpdyStreamId expect_continuation_;
// Scratch space for handling SETTINGS frames.
// TODO(hkhalil): Unify memory for this scratch space with
// current_frame_buffer_.
SpdySettingsScratch settings_scratch_;
scoped_ptr<CharBuffer> altsvc_scratch_;
// SPDY header compressors.
scoped_ptr<z_stream> header_compressor_;
scoped_ptr<z_stream> header_decompressor_;
scoped_ptr<HpackEncoder> hpack_encoder_;
scoped_ptr<HpackDecoder> hpack_decoder_;
SpdyFramerVisitorInterface* visitor_;
SpdyFramerDebugVisitorInterface* debug_visitor_;
std::string display_protocol_;
// The protocol version to be spoken/understood by this framer.
const SpdyMajorVersion protocol_version_;
// The flags field of the frame currently being read.
uint8 current_frame_flags_;
// Determines whether HPACK or gzip compression is used.
bool enable_compression_;
// Tracks if we've ever gotten far enough in framing to see a control frame of
// type SYN_STREAM or SYN_REPLY.
//
// If we ever get something which looks like a data frame before we've had a
// SYN, we explicitly check to see if it looks like we got an HTTP response
// to a SPDY request. This boolean lets us do that.
bool syn_frame_processed_;
// If we ever get a data frame before a SYN frame, we check to see if it
// starts with HTTP. If it does, we likely have an HTTP response. This
// isn't guaranteed though: we could have gotten a settings frame and then
// corrupt data that just looks like HTTP, but deterministic checking requires
// a lot more state.
bool probable_http_response_;
// If a HEADERS frame is followed by a CONTINUATION frame, the FIN/END_STREAM
// flag is still carried in the HEADERS frame. If it's set, flip this so that
// we know to terminate the stream when the entire header block has been
// processed.
bool end_stream_when_done_;
// If true, then ProcessInput returns after processing a full frame,
// rather than reading all available input.
bool process_single_input_frame_ = false;
// Last acknowledged value for SETTINGS_HEADER_TABLE_SIZE.
size_t header_table_size_bound_;
};
} // namespace net
#endif // NET_SPDY_SPDY_FRAMER_H_
| Java |
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.utils.decorators import method_decorator
from django.views import generic
from regressiontests.generic_views.models import Artist, Author, Book, Page
from regressiontests.generic_views.forms import AuthorForm
class CustomTemplateView(generic.TemplateView):
template_name = 'generic_views/about.html'
def get_context_data(self, **kwargs):
return {
'params': kwargs,
'key': 'value'
}
class ObjectDetail(generic.DetailView):
template_name = 'generic_views/detail.html'
def get_object(self):
return {'foo': 'bar'}
class ArtistDetail(generic.DetailView):
queryset = Artist.objects.all()
class AuthorDetail(generic.DetailView):
queryset = Author.objects.all()
class PageDetail(generic.DetailView):
queryset = Page.objects.all()
template_name_field = 'template'
class DictList(generic.ListView):
"""A ListView that doesn't use a model."""
queryset = [
{'first': 'John', 'last': 'Lennon'},
{'last': 'Yoko', 'last': 'Ono'}
]
template_name = 'generic_views/list.html'
class AuthorList(generic.ListView):
queryset = Author.objects.all()
class ArtistCreate(generic.CreateView):
model = Artist
class NaiveAuthorCreate(generic.CreateView):
queryset = Author.objects.all()
class AuthorCreate(generic.CreateView):
model = Author
success_url = '/list/authors/'
class SpecializedAuthorCreate(generic.CreateView):
model = Author
form_class = AuthorForm
template_name = 'generic_views/form.html'
context_object_name = 'thingy'
def get_success_url(self):
return reverse('author_detail', args=[self.object.id,])
class AuthorCreateRestricted(AuthorCreate):
post = method_decorator(login_required)(AuthorCreate.post)
class ArtistUpdate(generic.UpdateView):
model = Artist
class NaiveAuthorUpdate(generic.UpdateView):
queryset = Author.objects.all()
class AuthorUpdate(generic.UpdateView):
model = Author
success_url = '/list/authors/'
class SpecializedAuthorUpdate(generic.UpdateView):
model = Author
form_class = AuthorForm
template_name = 'generic_views/form.html'
context_object_name = 'thingy'
def get_success_url(self):
return reverse('author_detail', args=[self.object.id,])
class NaiveAuthorDelete(generic.DeleteView):
queryset = Author.objects.all()
class AuthorDelete(generic.DeleteView):
model = Author
success_url = '/list/authors/'
class SpecializedAuthorDelete(generic.DeleteView):
queryset = Author.objects.all()
template_name = 'generic_views/confirm_delete.html'
context_object_name = 'thingy'
def get_success_url(self):
return reverse('authors_list')
class BookConfig(object):
queryset = Book.objects.all()
date_field = 'pubdate'
class BookArchive(BookConfig, generic.ArchiveIndexView):
pass
class BookYearArchive(BookConfig, generic.YearArchiveView):
pass
class BookMonthArchive(BookConfig, generic.MonthArchiveView):
pass
class BookWeekArchive(BookConfig, generic.WeekArchiveView):
pass
class BookDayArchive(BookConfig, generic.DayArchiveView):
pass
class BookTodayArchive(BookConfig, generic.TodayArchiveView):
pass
class BookDetail(BookConfig, generic.DateDetailView):
pass
| Java |
// 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.
#include <utility>
#include "base/bind.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "remoting/base/constants.h"
#include "remoting/protocol/fake_session.h"
#include "remoting/protocol/fake_video_renderer.h"
#include "remoting/protocol/ice_connection_to_client.h"
#include "remoting/protocol/ice_connection_to_host.h"
#include "remoting/protocol/protocol_mock_objects.h"
#include "remoting/protocol/transport_context.h"
#include "remoting/protocol/video_stream.h"
#include "remoting/protocol/webrtc_connection_to_client.h"
#include "remoting/protocol/webrtc_connection_to_host.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/webrtc/modules/desktop_capture/desktop_capturer.h"
#include "third_party/webrtc/modules/desktop_capture/desktop_frame.h"
using ::testing::_;
using ::testing::InvokeWithoutArgs;
using ::testing::NotNull;
using ::testing::StrictMock;
namespace remoting {
namespace protocol {
namespace {
MATCHER_P(EqualsCapabilitiesMessage, message, "") {
return arg.capabilities() == message.capabilities();
}
MATCHER_P(EqualsKeyEvent, event, "") {
return arg.usb_keycode() == event.usb_keycode() &&
arg.pressed() == event.pressed();
}
ACTION_P(QuitRunLoop, run_loop) {
run_loop->Quit();
}
class MockConnectionToHostEventCallback
: public ConnectionToHost::HostEventCallback {
public:
MockConnectionToHostEventCallback() {}
~MockConnectionToHostEventCallback() override {}
MOCK_METHOD2(OnConnectionState,
void(ConnectionToHost::State state, ErrorCode error));
MOCK_METHOD1(OnConnectionReady, void(bool ready));
MOCK_METHOD2(OnRouteChanged,
void(const std::string& channel_name,
const TransportRoute& route));
};
class TestScreenCapturer : public webrtc::DesktopCapturer {
public:
TestScreenCapturer() {}
~TestScreenCapturer() override {}
// webrtc::DesktopCapturer interface.
void Start(Callback* callback) override {
callback_ = callback;
}
void Capture(const webrtc::DesktopRegion& region) override {
// Return black 10x10 frame.
std::unique_ptr<webrtc::DesktopFrame> frame(
new webrtc::BasicDesktopFrame(webrtc::DesktopSize(100, 100)));
memset(frame->data(), 0, frame->stride() * frame->size().height());
frame->mutable_updated_region()->SetRect(
webrtc::DesktopRect::MakeSize(frame->size()));
callback_->OnCaptureCompleted(frame.release());
}
private:
Callback* callback_ = nullptr;
};
} // namespace
class ConnectionTest : public testing::Test,
public testing::WithParamInterface<bool> {
public:
ConnectionTest() {}
protected:
bool is_using_webrtc() { return GetParam(); }
void SetUp() override {
// Create fake sessions.
host_session_ = new FakeSession();
owned_client_session_.reset(new FakeSession());
client_session_ = owned_client_session_.get();
// Create Connection objects.
if (is_using_webrtc()) {
host_connection_.reset(new WebrtcConnectionToClient(
base::WrapUnique(host_session_),
TransportContext::ForTests(protocol::TransportRole::SERVER),
message_loop_.task_runner()));
client_connection_.reset(new WebrtcConnectionToHost());
} else {
host_connection_.reset(new IceConnectionToClient(
base::WrapUnique(host_session_),
TransportContext::ForTests(protocol::TransportRole::SERVER),
message_loop_.task_runner()));
client_connection_.reset(new IceConnectionToHost());
}
// Setup host side.
host_connection_->SetEventHandler(&host_event_handler_);
host_connection_->set_clipboard_stub(&host_clipboard_stub_);
host_connection_->set_host_stub(&host_stub_);
host_connection_->set_input_stub(&host_input_stub_);
// Setup client side.
client_connection_->set_client_stub(&client_stub_);
client_connection_->set_clipboard_stub(&client_clipboard_stub_);
client_connection_->set_video_renderer(&client_video_renderer_);
}
void Connect() {
{
testing::InSequence sequence;
EXPECT_CALL(host_event_handler_,
OnConnectionAuthenticating(host_connection_.get()));
EXPECT_CALL(host_event_handler_,
OnConnectionAuthenticated(host_connection_.get()));
}
EXPECT_CALL(host_event_handler_,
OnConnectionChannelsConnected(host_connection_.get()))
.WillOnce(
InvokeWithoutArgs(this, &ConnectionTest::OnHostConnected));
EXPECT_CALL(host_event_handler_, OnRouteChange(_, _, _))
.Times(testing::AnyNumber());
{
testing::InSequence sequence;
EXPECT_CALL(client_event_handler_,
OnConnectionState(ConnectionToHost::CONNECTING, OK));
EXPECT_CALL(client_event_handler_,
OnConnectionState(ConnectionToHost::AUTHENTICATED, OK));
EXPECT_CALL(client_event_handler_,
OnConnectionState(ConnectionToHost::CONNECTED, OK))
.WillOnce(InvokeWithoutArgs(
this, &ConnectionTest::OnClientConnected));
}
EXPECT_CALL(client_event_handler_, OnRouteChanged(_, _))
.Times(testing::AnyNumber());
client_connection_->Connect(
std::move(owned_client_session_),
TransportContext::ForTests(protocol::TransportRole::CLIENT),
&client_event_handler_);
client_session_->SimulateConnection(host_session_);
run_loop_.reset(new base::RunLoop());
run_loop_->Run();
EXPECT_TRUE(client_connected_);
EXPECT_TRUE(host_connected_);
}
void TearDown() override {
client_connection_.reset();
host_connection_.reset();
base::RunLoop().RunUntilIdle();
}
void OnHostConnected() {
host_connected_ = true;
if (client_connected_ && run_loop_)
run_loop_->Quit();
}
void OnClientConnected() {
client_connected_ = true;
if (host_connected_ && run_loop_)
run_loop_->Quit();
}
base::MessageLoopForIO message_loop_;
std::unique_ptr<base::RunLoop> run_loop_;
MockConnectionToClientEventHandler host_event_handler_;
MockClipboardStub host_clipboard_stub_;
MockHostStub host_stub_;
MockInputStub host_input_stub_;
std::unique_ptr<ConnectionToClient> host_connection_;
FakeSession* host_session_; // Owned by |host_connection_|.
bool host_connected_ = false;
MockConnectionToHostEventCallback client_event_handler_;
MockClientStub client_stub_;
MockClipboardStub client_clipboard_stub_;
FakeVideoRenderer client_video_renderer_;
std::unique_ptr<ConnectionToHost> client_connection_;
FakeSession* client_session_; // Owned by |client_connection_|.
std::unique_ptr<FakeSession> owned_client_session_;
bool client_connected_ = false;
private:
DISALLOW_COPY_AND_ASSIGN(ConnectionTest);
};
INSTANTIATE_TEST_CASE_P(Ice, ConnectionTest, ::testing::Values(false));
INSTANTIATE_TEST_CASE_P(Webrtc, ConnectionTest, ::testing::Values(true));
TEST_P(ConnectionTest, RejectConnection) {
EXPECT_CALL(client_event_handler_,
OnConnectionState(ConnectionToHost::CONNECTING, OK));
EXPECT_CALL(client_event_handler_,
OnConnectionState(ConnectionToHost::CLOSED, OK));
client_connection_->Connect(
std::move(owned_client_session_),
TransportContext::ForTests(protocol::TransportRole::CLIENT),
&client_event_handler_);
client_session_->event_handler()->OnSessionStateChange(Session::CLOSED);
}
TEST_P(ConnectionTest, Disconnect) {
Connect();
EXPECT_CALL(client_event_handler_,
OnConnectionState(ConnectionToHost::CLOSED, OK));
EXPECT_CALL(host_event_handler_,
OnConnectionClosed(host_connection_.get(), OK));
client_session_->Close(OK);
base::RunLoop().RunUntilIdle();
}
TEST_P(ConnectionTest, Control) {
Connect();
Capabilities capabilities_msg;
capabilities_msg.set_capabilities("test_capability");
base::RunLoop run_loop;
EXPECT_CALL(client_stub_,
SetCapabilities(EqualsCapabilitiesMessage(capabilities_msg)))
.WillOnce(QuitRunLoop(&run_loop));
// Send capabilities from the host.
host_connection_->client_stub()->SetCapabilities(capabilities_msg);
run_loop.Run();
}
TEST_P(ConnectionTest, Events) {
Connect();
KeyEvent event;
event.set_usb_keycode(3);
event.set_pressed(true);
base::RunLoop run_loop;
EXPECT_CALL(host_event_handler_,
OnInputEventReceived(host_connection_.get(), _));
EXPECT_CALL(host_input_stub_, InjectKeyEvent(EqualsKeyEvent(event)))
.WillOnce(QuitRunLoop(&run_loop));
// Send capabilities from the client.
client_connection_->input_stub()->InjectKeyEvent(event);
run_loop.Run();
}
TEST_P(ConnectionTest, Video) {
Connect();
std::unique_ptr<VideoStream> video_stream =
host_connection_->StartVideoStream(
base::WrapUnique(new TestScreenCapturer()));
base::RunLoop run_loop;
// Expect frames to be passed to FrameConsumer when WebRTC is used, or to
// VideoStub otherwise.
if (is_using_webrtc()) {
client_video_renderer_.GetFrameConsumer()->set_on_frame_callback(
base::Bind(&base::RunLoop::Quit, base::Unretained(&run_loop)));
} else {
client_video_renderer_.GetVideoStub()->set_on_frame_callback(
base::Bind(&base::RunLoop::Quit, base::Unretained(&run_loop)));
}
run_loop.Run();
if (is_using_webrtc()) {
EXPECT_EQ(
client_video_renderer_.GetFrameConsumer()->received_frames().size(),
1U);
EXPECT_EQ(client_video_renderer_.GetVideoStub()->received_packets().size(),
0U);
} else {
EXPECT_EQ(
client_video_renderer_.GetFrameConsumer()->received_frames().size(),
0U);
EXPECT_EQ(client_video_renderer_.GetVideoStub()->received_packets().size(),
1U);
}
}
} // namespace protocol
} // namespace remoting
| Java |
<html>
<head>
<script src="../../../http/tests/inspector/inspector-test.js"></script>
<script src="../../../http/tests/inspector/debugger-test.js"></script>
<script>
var a = 1;
function testFunction()
{
var a = 2;
debugger;
}
var test = function()
{
InspectorTest.startDebuggerTest(step1);
function step1()
{
InspectorTest.runTestFunctionAndWaitUntilPaused(step2);
}
function step2()
{
InspectorTest.evaluateInConsole("a", step3);
}
function step3(result)
{
InspectorTest.addResult("Evaluated in console in the top frame context: a = " + result);
InspectorTest.completeDebuggerTest();
}
}
</script>
</head>
<body onload="runTest()">
<p>
Test that evaluation in the context of top frame will see values
of its local variables, even if there are global variables with
same names. On success the test will print a = 2(value of the
local variable a). <a href="https://bugs.webkit.org/show_bug.cgi?id=47358">Bug 47358.</a>
</p>
</body>
</html>
| Java |
"""A connection adapter that tries to use the best polling method for the
platform pika is running on.
"""
import os
import logging
import socket
import select
import errno
import time
from operator import itemgetter
from collections import defaultdict
import threading
import pika.compat
from pika.compat import dictkeys
from pika.adapters.base_connection import BaseConnection
LOGGER = logging.getLogger(__name__)
# One of select, epoll, kqueue or poll
SELECT_TYPE = None
# Use epoll's constants to keep life easy
READ = 0x0001
WRITE = 0x0004
ERROR = 0x0008
if pika.compat.PY2:
_SELECT_ERROR = select.error
else:
# select.error was deprecated and replaced by OSError in python 3.3
_SELECT_ERROR = OSError
def _get_select_errno(error):
if pika.compat.PY2:
assert isinstance(error, select.error), repr(error)
return error.args[0]
else:
assert isinstance(error, OSError), repr(error)
return error.errno
class SelectConnection(BaseConnection):
"""An asynchronous connection adapter that attempts to use the fastest
event loop adapter for the given platform.
"""
def __init__(self,
parameters=None,
on_open_callback=None,
on_open_error_callback=None,
on_close_callback=None,
stop_ioloop_on_close=True,
custom_ioloop=None):
"""Create a new instance of the Connection object.
:param pika.connection.Parameters parameters: Connection parameters
:param method on_open_callback: Method to call on connection open
:param on_open_error_callback: Method to call if the connection cant
be opened
:type on_open_error_callback: method
:param method on_close_callback: Method to call on connection close
:param bool stop_ioloop_on_close: Call ioloop.stop() if disconnected
:param custom_ioloop: Override using the global IOLoop in Tornado
:raises: RuntimeError
"""
ioloop = custom_ioloop or IOLoop()
super(SelectConnection, self).__init__(parameters, on_open_callback,
on_open_error_callback,
on_close_callback, ioloop,
stop_ioloop_on_close)
def _adapter_connect(self):
"""Connect to the RabbitMQ broker, returning True on success, False
on failure.
:rtype: bool
"""
error = super(SelectConnection, self)._adapter_connect()
if not error:
self.ioloop.add_handler(self.socket.fileno(), self._handle_events,
self.event_state)
return error
def _adapter_disconnect(self):
"""Disconnect from the RabbitMQ broker"""
if self.socket:
self.ioloop.remove_handler(self.socket.fileno())
super(SelectConnection, self)._adapter_disconnect()
class IOLoop(object):
"""Singlton wrapper that decides which type of poller to use, creates an
instance of it in start_poller and keeps the invoking application in a
blocking state by calling the pollers start method. Poller should keep
looping until IOLoop.instance().stop() is called or there is a socket
error.
Passes through all operations to the loaded poller object.
"""
def __init__(self):
self._poller = self._get_poller()
def __getattr__(self, attr):
return getattr(self._poller, attr)
def _get_poller(self):
"""Determine the best poller to use for this enviroment."""
poller = None
if hasattr(select, 'epoll'):
if not SELECT_TYPE or SELECT_TYPE == 'epoll':
LOGGER.debug('Using EPollPoller')
poller = EPollPoller()
if not poller and hasattr(select, 'kqueue'):
if not SELECT_TYPE or SELECT_TYPE == 'kqueue':
LOGGER.debug('Using KQueuePoller')
poller = KQueuePoller()
if (not poller and hasattr(select, 'poll') and
hasattr(select.poll(), 'modify')): # pylint: disable=E1101
if not SELECT_TYPE or SELECT_TYPE == 'poll':
LOGGER.debug('Using PollPoller')
poller = PollPoller()
if not poller:
LOGGER.debug('Using SelectPoller')
poller = SelectPoller()
return poller
class SelectPoller(object):
"""Default behavior is to use Select since it's the widest supported and has
all of the methods we need for child classes as well. One should only need
to override the update_handler and start methods for additional types.
"""
# Drop out of the poll loop every POLL_TIMEOUT secs as a worst case, this
# is only a backstop value. We will run timeouts when they are scheduled.
POLL_TIMEOUT = 5
# if the poller uses MS specify 1000
POLL_TIMEOUT_MULT = 1
def __init__(self):
"""Create an instance of the SelectPoller
"""
# fd-to-handler function mappings
self._fd_handlers = dict()
# event-to-fdset mappings
self._fd_events = {READ: set(), WRITE: set(), ERROR: set()}
self._stopping = False
self._timeouts = {}
self._next_timeout = None
self._processing_fd_event_map = {}
# Mutex for controlling critical sections where ioloop-interrupt sockets
# are created, used, and destroyed. Needed in case `stop()` is called
# from a thread.
self._mutex = threading.Lock()
# ioloop-interrupt socket pair; initialized in start()
self._r_interrupt = None
self._w_interrupt = None
def get_interrupt_pair(self):
""" Use a socketpair to be able to interrupt the ioloop if called
from another thread. Socketpair() is not supported on some OS (Win)
so use a pair of simple UDP sockets instead. The sockets will be
closed and garbage collected by python when the ioloop itself is.
"""
try:
read_sock, write_sock = socket.socketpair()
except AttributeError:
LOGGER.debug("Using custom socketpair for interrupt")
read_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
read_sock.bind(('localhost', 0))
write_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
write_sock.connect(read_sock.getsockname())
read_sock.setblocking(0)
write_sock.setblocking(0)
return read_sock, write_sock
def read_interrupt(self, interrupt_sock,
events, write_only): # pylint: disable=W0613
""" Read the interrupt byte(s). We ignore the event mask and write_only
flag as we can ony get here if there's data to be read on our fd.
:param int interrupt_sock: The file descriptor to read from
:param int events: (unused) The events generated for this fd
:param bool write_only: (unused) True if poll was called to trigger a
write
"""
try:
os.read(interrupt_sock, 512)
except OSError as err:
if err.errno != errno.EAGAIN:
raise
def add_timeout(self, deadline, callback_method):
"""Add the callback_method to the IOLoop timer to fire after deadline
seconds. Returns a handle to the timeout. Do not confuse with
Tornado's timeout where you pass in the time you want to have your
callback called. Only pass in the seconds until it's to be called.
:param int deadline: The number of seconds to wait to call callback
:param method callback_method: The callback method
:rtype: str
"""
timeout_at = time.time() + deadline
value = {'deadline': timeout_at, 'callback': callback_method}
timeout_id = hash(frozenset(value.items()))
self._timeouts[timeout_id] = value
if not self._next_timeout or timeout_at < self._next_timeout:
self._next_timeout = timeout_at
return timeout_id
def remove_timeout(self, timeout_id):
"""Remove a timeout if it's still in the timeout stack
:param str timeout_id: The timeout id to remove
"""
try:
timeout = self._timeouts.pop(timeout_id)
if timeout['deadline'] == self._next_timeout:
self._next_timeout = None
except KeyError:
pass
def get_next_deadline(self):
"""Get the interval to the next timeout event, or a default interval
"""
if self._next_timeout:
timeout = max((self._next_timeout - time.time(), 0))
elif self._timeouts:
deadlines = [t['deadline'] for t in self._timeouts.values()]
self._next_timeout = min(deadlines)
timeout = max((self._next_timeout - time.time(), 0))
else:
timeout = SelectPoller.POLL_TIMEOUT
timeout = min((timeout, SelectPoller.POLL_TIMEOUT))
return timeout * SelectPoller.POLL_TIMEOUT_MULT
def process_timeouts(self):
"""Process the self._timeouts event stack"""
now = time.time()
to_run = [timer for timer in self._timeouts.values()
if timer['deadline'] <= now]
# Run the timeouts in order of deadlines. Although this shouldn't
# be strictly necessary it preserves old behaviour when timeouts
# were only run periodically.
for t in sorted(to_run, key=itemgetter('deadline')):
t['callback']()
del self._timeouts[hash(frozenset(t.items()))]
self._next_timeout = None
def add_handler(self, fileno, handler, events):
"""Add a new fileno to the set to be monitored
:param int fileno: The file descriptor
:param method handler: What is called when an event happens
:param int events: The event mask
"""
self._fd_handlers[fileno] = handler
self.update_handler(fileno, events)
def update_handler(self, fileno, events):
"""Set the events to the current events
:param int fileno: The file descriptor
:param int events: The event mask
"""
for ev in (READ, WRITE, ERROR):
if events & ev:
self._fd_events[ev].add(fileno)
else:
self._fd_events[ev].discard(fileno)
def remove_handler(self, fileno):
"""Remove a file descriptor from the set
:param int fileno: The file descriptor
"""
try:
del self._processing_fd_event_map[fileno]
except KeyError:
pass
self.update_handler(fileno, 0)
del self._fd_handlers[fileno]
def start(self):
"""Start the main poller loop. It will loop here until self._stopping"""
LOGGER.debug('Starting IOLoop')
self._stopping = False
with self._mutex:
# Watch out for reentry
if self._r_interrupt is None:
# Create ioloop-interrupt socket pair and register read handler.
# NOTE: we defer their creation because some users (e.g.,
# BlockingConnection adapter) don't use the event loop and these
# sockets would get reported as leaks
self._r_interrupt, self._w_interrupt = self.get_interrupt_pair()
self.add_handler(self._r_interrupt.fileno(),
self.read_interrupt,
READ)
interrupt_sockets_created = True
else:
interrupt_sockets_created = False
try:
# Run event loop
while not self._stopping:
self.poll()
self.process_timeouts()
finally:
# Unregister and close ioloop-interrupt socket pair
if interrupt_sockets_created:
with self._mutex:
self.remove_handler(self._r_interrupt.fileno())
self._r_interrupt.close()
self._r_interrupt = None
self._w_interrupt.close()
self._w_interrupt = None
def stop(self):
"""Request exit from the ioloop."""
LOGGER.debug('Stopping IOLoop')
self._stopping = True
with self._mutex:
if self._w_interrupt is None:
return
try:
# Send byte to interrupt the poll loop, use write() for
# consitency.
os.write(self._w_interrupt.fileno(), b'X')
except OSError as err:
if err.errno != errno.EWOULDBLOCK:
raise
except Exception as err:
# There's nothing sensible to do here, we'll exit the interrupt
# loop after POLL_TIMEOUT secs in worst case anyway.
LOGGER.warning("Failed to send ioloop interrupt: %s", err)
raise
def poll(self, write_only=False):
"""Wait for events on interested filedescriptors.
:param bool write_only: Passed through to the hadnlers to indicate
that they should only process write events.
"""
while True:
try:
read, write, error = select.select(self._fd_events[READ],
self._fd_events[WRITE],
self._fd_events[ERROR],
self.get_next_deadline())
break
except _SELECT_ERROR as error:
if _get_select_errno(error) == errno.EINTR:
continue
else:
raise
# Build an event bit mask for each fileno we've recieved an event for
fd_event_map = defaultdict(int)
for fd_set, ev in zip((read, write, error), (READ, WRITE, ERROR)):
for fileno in fd_set:
fd_event_map[fileno] |= ev
self._process_fd_events(fd_event_map, write_only)
def _process_fd_events(self, fd_event_map, write_only):
""" Processes the callbacks for each fileno we've recieved events.
Before doing so we re-calculate the event mask based on what is
currently set in case it has been changed under our feet by a
previous callback. We also take a store a refernce to the
fd_event_map in the class so that we can detect removal of an
fileno during processing of another callback and not generate
spurious callbacks on it.
:param dict fd_event_map: Map of fds to events recieved on them.
"""
self._processing_fd_event_map = fd_event_map
for fileno in dictkeys(fd_event_map):
if fileno not in fd_event_map:
# the fileno has been removed from the map under our feet.
continue
events = fd_event_map[fileno]
for ev in [READ, WRITE, ERROR]:
if fileno not in self._fd_events[ev]:
events &= ~ev
if events:
handler = self._fd_handlers[fileno]
handler(fileno, events, write_only=write_only)
class KQueuePoller(SelectPoller):
"""KQueuePoller works on BSD based systems and is faster than select"""
def __init__(self):
"""Create an instance of the KQueuePoller
:param int fileno: The file descriptor to check events for
:param method handler: What is called when an event happens
:param int events: The events to look for
"""
self._kqueue = select.kqueue()
super(KQueuePoller, self).__init__()
def update_handler(self, fileno, events):
"""Set the events to the current events
:param int fileno: The file descriptor
:param int events: The event mask
"""
kevents = list()
if not events & READ:
if fileno in self._fd_events[READ]:
kevents.append(select.kevent(fileno,
filter=select.KQ_FILTER_READ,
flags=select.KQ_EV_DELETE))
else:
if fileno not in self._fd_events[READ]:
kevents.append(select.kevent(fileno,
filter=select.KQ_FILTER_READ,
flags=select.KQ_EV_ADD))
if not events & WRITE:
if fileno in self._fd_events[WRITE]:
kevents.append(select.kevent(fileno,
filter=select.KQ_FILTER_WRITE,
flags=select.KQ_EV_DELETE))
else:
if fileno not in self._fd_events[WRITE]:
kevents.append(select.kevent(fileno,
filter=select.KQ_FILTER_WRITE,
flags=select.KQ_EV_ADD))
for event in kevents:
self._kqueue.control([event], 0)
super(KQueuePoller, self).update_handler(fileno, events)
def _map_event(self, kevent):
"""return the event type associated with a kevent object
:param kevent kevent: a kevent object as returned by kqueue.control()
"""
if kevent.filter == select.KQ_FILTER_READ:
return READ
elif kevent.filter == select.KQ_FILTER_WRITE:
return WRITE
elif kevent.flags & select.KQ_EV_ERROR:
return ERROR
def poll(self, write_only=False):
"""Check to see if the events that are cared about have fired.
:param bool write_only: Don't look at self.events, just look to see if
the adapter can write.
"""
while True:
try:
kevents = self._kqueue.control(None, 1000,
self.get_next_deadline())
break
except _SELECT_ERROR as error:
if _get_select_errno(error) == errno.EINTR:
continue
else:
raise
fd_event_map = defaultdict(int)
for event in kevents:
fileno = event.ident
fd_event_map[fileno] |= self._map_event(event)
self._process_fd_events(fd_event_map, write_only)
class PollPoller(SelectPoller):
"""Poll works on Linux and can have better performance than EPoll in
certain scenarios. Both are faster than select.
"""
POLL_TIMEOUT_MULT = 1000
def __init__(self):
"""Create an instance of the KQueuePoller
:param int fileno: The file descriptor to check events for
:param method handler: What is called when an event happens
:param int events: The events to look for
"""
self._poll = self.create_poller()
super(PollPoller, self).__init__()
def create_poller(self):
return select.poll() # pylint: disable=E1101
def add_handler(self, fileno, handler, events):
"""Add a file descriptor to the poll set
:param int fileno: The file descriptor to check events for
:param method handler: What is called when an event happens
:param int events: The events to look for
"""
self._poll.register(fileno, events)
super(PollPoller, self).add_handler(fileno, handler, events)
def update_handler(self, fileno, events):
"""Set the events to the current events
:param int fileno: The file descriptor
:param int events: The event mask
"""
super(PollPoller, self).update_handler(fileno, events)
self._poll.modify(fileno, events)
def remove_handler(self, fileno):
"""Remove a fileno to the set
:param int fileno: The file descriptor
"""
super(PollPoller, self).remove_handler(fileno)
self._poll.unregister(fileno)
def poll(self, write_only=False):
"""Poll until the next timeout waiting for an event
:param bool write_only: Only process write events
"""
while True:
try:
events = self._poll.poll(self.get_next_deadline())
break
except _SELECT_ERROR as error:
if _get_select_errno(error) == errno.EINTR:
continue
else:
raise
fd_event_map = defaultdict(int)
for fileno, event in events:
fd_event_map[fileno] |= event
self._process_fd_events(fd_event_map, write_only)
class EPollPoller(PollPoller):
"""EPoll works on Linux and can have better performance than Poll in
certain scenarios. Both are faster than select.
"""
POLL_TIMEOUT_MULT = 1
def create_poller(self):
return select.epoll() # pylint: disable=E1101
| Java |
/*
* Copyright 2016 The WebRTC 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 in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <map>
#include <memory>
#include "webrtc/sdk/android/src/jni/classreferenceholder.h"
#include "webrtc/sdk/android/src/jni/jni_helpers.h"
#include "webrtc/system_wrappers/include/metrics.h"
#include "webrtc/system_wrappers/include/metrics_default.h"
// Enables collection of native histograms and creating them.
namespace webrtc_jni {
JOW(void, Metrics_nativeEnable)(JNIEnv* jni, jclass) {
webrtc::metrics::Enable();
}
// Gets and clears native histograms.
JOW(jobject, Metrics_nativeGetAndReset)(JNIEnv* jni, jclass) {
jclass j_metrics_class = jni->FindClass("org/webrtc/Metrics");
jmethodID j_add =
GetMethodID(jni, j_metrics_class, "add",
"(Ljava/lang/String;Lorg/webrtc/Metrics$HistogramInfo;)V");
jclass j_info_class = jni->FindClass("org/webrtc/Metrics$HistogramInfo");
jmethodID j_add_sample = GetMethodID(jni, j_info_class, "addSample", "(II)V");
// Create |Metrics|.
jobject j_metrics = jni->NewObject(
j_metrics_class, GetMethodID(jni, j_metrics_class, "<init>", "()V"));
std::map<std::string, std::unique_ptr<webrtc::metrics::SampleInfo>>
histograms;
webrtc::metrics::GetAndReset(&histograms);
for (const auto& kv : histograms) {
// Create and add samples to |HistogramInfo|.
jobject j_info = jni->NewObject(
j_info_class, GetMethodID(jni, j_info_class, "<init>", "(III)V"),
kv.second->min, kv.second->max,
static_cast<int>(kv.second->bucket_count));
for (const auto& sample : kv.second->samples) {
jni->CallVoidMethod(j_info, j_add_sample, sample.first, sample.second);
}
// Add |HistogramInfo| to |Metrics|.
jstring j_name = jni->NewStringUTF(kv.first.c_str());
jni->CallVoidMethod(j_metrics, j_add, j_name, j_info);
jni->DeleteLocalRef(j_name);
jni->DeleteLocalRef(j_info);
}
CHECK_EXCEPTION(jni);
return j_metrics;
}
} // namespace webrtc_jni
| Java |
{% extends 'djangopypi/base.html' %}
{% block title %}Manage {{ package.name }}{% endblock %}
{% block body %}
<h1>Manage {{ package.name }}</h1>
<div>
<form action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit">
</form>
</div>
{% endblock %}
| Java |
//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2020, Cinesite VFX Ltd. 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 John Haddon nor the names of
// any other contributors to this software 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.
//
//////////////////////////////////////////////////////////////////////////
#ifndef GAFFERSCENE_MERGESCENES_H
#define GAFFERSCENE_MERGESCENES_H
#include "GafferScene/SceneProcessor.h"
#include <bitset>
namespace GafferScene
{
class GAFFERSCENE_API MergeScenes : public SceneProcessor
{
public :
MergeScenes( const std::string &name=defaultName<MergeScenes>() );
~MergeScenes() override;
GAFFER_GRAPHCOMPONENT_DECLARE_TYPE( GafferScene::MergeScenes, MergeScenesTypeId, SceneProcessor );
enum class Mode
{
Keep,
Replace,
Merge
};
Gaffer::IntPlug *transformModePlug();
const Gaffer::IntPlug *transformModePlug() const;
Gaffer::IntPlug *attributesModePlug();
const Gaffer::IntPlug *attributesModePlug() const;
Gaffer::IntPlug *objectModePlug();
const Gaffer::IntPlug *objectModePlug() const;
Gaffer::IntPlug *globalsModePlug();
const Gaffer::IntPlug *globalsModePlug() const;
Gaffer::BoolPlug *adjustBoundsPlug();
const Gaffer::BoolPlug *adjustBoundsPlug() const;
void affects( const Gaffer::Plug *input, AffectedPlugsContainer &outputs ) const override;
protected :
void hash( const Gaffer::ValuePlug *output, const Gaffer::Context *context, IECore::MurmurHash &h ) const override;
void compute( Gaffer::ValuePlug *output, const Gaffer::Context *context ) const override;
void hashBound( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent, IECore::MurmurHash &h ) const override;
Imath::Box3f computeBound( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent ) const override;
void hashTransform( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent, IECore::MurmurHash &h ) const override;
Imath::M44f computeTransform( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent ) const override;
void hashAttributes( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent, IECore::MurmurHash &h ) const override;
IECore::ConstCompoundObjectPtr computeAttributes( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent ) const override;
void hashObject( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent, IECore::MurmurHash &h ) const override;
IECore::ConstObjectPtr computeObject( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent ) const override;
void hashChildNames( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent, IECore::MurmurHash &h ) const override;
IECore::ConstInternedStringVectorDataPtr computeChildNames( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent ) const override;
void hashGlobals( const Gaffer::Context *context, const ScenePlug *parent, IECore::MurmurHash &h ) const override;
IECore::ConstCompoundObjectPtr computeGlobals( const Gaffer::Context *context, const ScenePlug *parent ) const override;
void hashSetNames( const Gaffer::Context *context, const ScenePlug *parent, IECore::MurmurHash &h ) const override;
IECore::ConstInternedStringVectorDataPtr computeSetNames( const Gaffer::Context *context, const ScenePlug *parent ) const override;
void hashSet( const IECore::InternedString &setName, const Gaffer::Context *context, const ScenePlug *parent, IECore::MurmurHash &h ) const override;
IECore::ConstPathMatcherDataPtr computeSet( const IECore::InternedString &setName, const Gaffer::Context *context, const ScenePlug *parent ) const override;
private :
using InputMask = std::bitset<32>;
// Plugs used to track which inputs are valid
// at the current location. The value can be
// converted directly to an `InputMask` for use
// with `visit()`.
Gaffer::IntPlug *activeInputsPlug();
const Gaffer::IntPlug *activeInputsPlug() const;
Gaffer::AtomicBox3fPlug *mergedDescendantsBoundPlug();
const Gaffer::AtomicBox3fPlug *mergedDescendantsBoundPlug() const;
void hashActiveInputs( const Gaffer::Context *context, IECore::MurmurHash &h ) const;
int computeActiveInputs( const Gaffer::Context *context ) const;
void hashMergedDescendantsBound( const Gaffer::Context *context, IECore::MurmurHash &h ) const;
const Imath::Box3f computeMergedDescendantsBound( const Gaffer::Context *context ) const;
enum class InputType
{
Sole,
First,
Other
};
enum VisitOrder
{
Forwards,
Backwards,
FirstOnly,
LastOnly
};
VisitOrder visitOrder( Mode mode, VisitOrder replaceOrder = VisitOrder::LastOnly ) const;
InputMask connectedInputs() const;
// Calls `visitor( inputType, inputIndex, input )` for all inputs specified by `inputMask`.
// Visitor may return `true` to continue to subsequent inputs or `false` to stop iteration.
template<typename Visitor>
void visit( InputMask inputMask, Visitor &&visitor, VisitOrder order = VisitOrder::Forwards ) const;
static size_t g_firstPlugIndex;
};
IE_CORE_DECLAREPTR( MergeScenes )
} // namespace GafferScene
#endif // GAFFERSCENE_MERGESCENES_H
| Java |
/*
Copyright (c) 2007, Arvid Norberg
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 author 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 "libtorrent/udp_socket.hpp"
#include "libtorrent/connection_queue.hpp"
#include "libtorrent/escape_string.hpp"
#include <stdlib.h>
#include <boost/bind.hpp>
#include <boost/array.hpp>
#if BOOST_VERSION < 103500
#include <asio/read.hpp>
#else
#include <boost/asio/read.hpp>
#endif
using namespace libtorrent;
udp_socket::udp_socket(asio::io_service& ios, udp_socket::callback_t const& c
, connection_queue& cc)
: m_callback(c)
, m_ipv4_sock(ios)
#if TORRENT_USE_IPV6
, m_ipv6_sock(ios)
#endif
, m_bind_port(0)
, m_v4_outstanding(0)
#if TORRENT_USE_IPV6
, m_v6_outstanding(0)
#endif
, m_socks5_sock(ios)
, m_connection_ticket(-1)
, m_cc(cc)
, m_resolver(ios)
, m_queue_packets(false)
, m_tunnel_packets(false)
, m_abort(false)
, m_outstanding_ops(0)
{
#ifdef TORRENT_DEBUG
m_magic = 0x1337;
m_started = false;
m_outstanding_when_aborted = -1;
#endif
}
udp_socket::~udp_socket()
{
#if TORRENT_USE_IPV6
TORRENT_ASSERT(m_v6_outstanding == 0);
#endif
TORRENT_ASSERT(m_v4_outstanding == 0);
TORRENT_ASSERT(m_magic == 0x1337);
TORRENT_ASSERT(!m_callback || !m_started);
#ifdef TORRENT_DEBUG
m_magic = 0;
#endif
TORRENT_ASSERT(m_outstanding_ops == 0);
}
#ifdef TORRENT_DEBUG
#define CHECK_MAGIC check_magic_ cm_(m_magic)
struct check_magic_
{
check_magic_(int& m_): m(m_) { TORRENT_ASSERT(m == 0x1337); }
~check_magic_() { TORRENT_ASSERT(m == 0x1337); }
int& m;
};
#else
#define CHECK_MAGIC do {} while (false)
#endif
bool udp_socket::maybe_clear_callback(mutex_t::scoped_lock& l)
{
if (m_outstanding_ops + m_v4_outstanding + m_v6_outstanding == 0)
{
// "this" may be destructed in the callback
// that's why we need to unlock
callback_t tmp = m_callback;
m_callback.clear();
l.unlock();
return true;
}
return false;
}
void udp_socket::send(udp::endpoint const& ep, char const* p, int len, error_code& ec)
{
CHECK_MAGIC;
TORRENT_ASSERT(is_open());
// if the sockets are closed, the udp_socket is closing too
if (!is_open()) return;
if (m_tunnel_packets)
{
// send udp packets through SOCKS5 server
wrap(ep, p, len, ec);
return;
}
if (m_queue_packets)
{
m_queue.push_back(queued_packet());
queued_packet& qp = m_queue.back();
qp.ep = ep;
qp.buf.insert(qp.buf.begin(), p, p + len);
return;
}
#if TORRENT_USE_IPV6
if (ep.address().is_v4() && m_ipv4_sock.is_open())
#endif
m_ipv4_sock.send_to(asio::buffer(p, len), ep, 0, ec);
#if TORRENT_USE_IPV6
else
m_ipv6_sock.send_to(asio::buffer(p, len), ep, 0, ec);
#endif
}
void udp_socket::on_read(udp::socket* s, error_code const& e, std::size_t bytes_transferred)
{
TORRENT_ASSERT(m_magic == 0x1337);
mutex_t::scoped_lock l(m_mutex);
#if TORRENT_USE_IPV6
if (s == &m_ipv6_sock)
{
TORRENT_ASSERT(m_v6_outstanding > 0);
--m_v6_outstanding;
}
else
#endif
{
TORRENT_ASSERT(m_v4_outstanding > 0);
--m_v4_outstanding;
}
if (m_abort)
{
maybe_clear_callback(l);
return;
}
CHECK_MAGIC;
if (!m_callback) return;
if (e)
{
l.unlock();
#ifndef BOOST_NO_EXCEPTIONS
try {
#endif
#if TORRENT_USE_IPV6
if (s == &m_ipv4_sock)
#endif
m_callback(e, m_v4_ep, 0, 0);
#if TORRENT_USE_IPV6
else
m_callback(e, m_v6_ep, 0, 0);
#endif
#ifndef BOOST_NO_EXCEPTIONS
} catch(std::exception&) {}
#endif
l.lock();
// don't stop listening on recoverable errors
if (e != asio::error::host_unreachable
&& e != asio::error::fault
&& e != asio::error::connection_reset
&& e != asio::error::connection_refused
&& e != asio::error::connection_aborted
&& e != asio::error::operation_aborted
&& e != asio::error::message_size)
{
maybe_clear_callback(l);
return;
}
if (m_abort) return;
#if TORRENT_USE_IPV6
if (s == &m_ipv4_sock && m_v4_outstanding == 0)
#endif
{
++m_v4_outstanding;
s->async_receive_from(asio::buffer(m_v4_buf, sizeof(m_v4_buf))
, m_v4_ep, boost::bind(&udp_socket::on_read, self(), s, _1, _2));
}
#if TORRENT_USE_IPV6
else if (m_v6_outstanding == 0)
{
++m_v6_outstanding;
s->async_receive_from(asio::buffer(m_v6_buf, sizeof(m_v6_buf))
, m_v6_ep, boost::bind(&udp_socket::on_read, self(), s, _1, _2));
}
#endif
#ifdef TORRENT_DEBUG
m_started = true;
#endif
return;
}
#if TORRENT_USE_IPV6
if (s == &m_ipv4_sock)
#endif
{
#ifndef BOOST_NO_EXCEPTIONS
try {
#endif
if (m_tunnel_packets)
{
l.unlock();
// if the source IP doesn't match the proxy's, ignore the packet
if (m_v4_ep == m_proxy_addr)
unwrap(e, m_v4_buf, bytes_transferred);
}
else
{
l.unlock();
m_callback(e, m_v4_ep, m_v4_buf, bytes_transferred);
}
l.lock();
#ifndef BOOST_NO_EXCEPTIONS
} catch(std::exception&) {}
#endif
if (m_abort) return;
if (m_v4_outstanding == 0)
{
++m_v4_outstanding;
s->async_receive_from(asio::buffer(m_v4_buf, sizeof(m_v4_buf))
, m_v4_ep, boost::bind(&udp_socket::on_read, self(), s, _1, _2));
}
}
#if TORRENT_USE_IPV6
else
{
#ifndef BOOST_NO_EXCEPTIONS
try {
#endif
if (m_tunnel_packets)
{
l.unlock();
// if the source IP doesn't match the proxy's, ignore the packet
if (m_v6_ep == m_proxy_addr)
unwrap(e, m_v6_buf, bytes_transferred);
}
else
{
l.unlock();
m_callback(e, m_v6_ep, m_v6_buf, bytes_transferred);
}
#ifndef BOOST_NO_EXCEPTIONS
} catch(std::exception&) {}
#endif
l.lock();
if (m_abort) return;
if (m_v6_outstanding == 0)
{
++m_v6_outstanding;
s->async_receive_from(asio::buffer(m_v6_buf, sizeof(m_v6_buf))
, m_v6_ep, boost::bind(&udp_socket::on_read, self(), s, _1, _2));
}
}
#endif // TORRENT_USE_IPV6
#ifdef TORRENT_DEBUG
m_started = true;
#endif
}
void udp_socket::wrap(udp::endpoint const& ep, char const* p, int len, error_code& ec)
{
CHECK_MAGIC;
using namespace libtorrent::detail;
char header[25];
char* h = header;
write_uint16(0, h); // reserved
write_uint8(0, h); // fragment
write_uint8(ep.address().is_v4()?1:4, h); // atyp
write_address(ep.address(), h);
write_uint16(ep.port(), h);
boost::array<asio::const_buffer, 2> iovec;
iovec[0] = asio::const_buffer(header, h - header);
iovec[1] = asio::const_buffer(p, len);
#if TORRENT_USE_IPV6
if (m_proxy_addr.address().is_v4() && m_ipv4_sock.is_open())
#endif
m_ipv4_sock.send_to(iovec, m_proxy_addr, 0, ec);
#if TORRENT_USE_IPV6
else
m_ipv6_sock.send_to(iovec, m_proxy_addr, 0, ec);
#endif
}
// unwrap the UDP packet from the SOCKS5 header
void udp_socket::unwrap(error_code const& e, char const* buf, int size)
{
CHECK_MAGIC;
using namespace libtorrent::detail;
// the minimum socks5 header size
if (size <= 10) return;
char const* p = buf;
p += 2; // reserved
int frag = read_uint8(p);
// fragmentation is not supported
if (frag != 0) return;
udp::endpoint sender;
int atyp = read_uint8(p);
if (atyp == 1)
{
// IPv4
sender = read_v4_endpoint<udp::endpoint>(p);
}
#if TORRENT_USE_IPV6
else if (atyp == 4)
{
// IPv6
sender = read_v6_endpoint<udp::endpoint>(p);
}
#endif
else
{
// domain name not supported
return;
}
m_callback(e, sender, p, size - (p - buf));
}
void udp_socket::close()
{
mutex_t::scoped_lock l(m_mutex);
TORRENT_ASSERT(m_magic == 0x1337);
error_code ec;
m_ipv4_sock.close(ec);
#if TORRENT_USE_IPV6
m_ipv6_sock.close(ec);
#endif
m_socks5_sock.close(ec);
m_resolver.cancel();
m_abort = true;
#ifdef TORRENT_DEBUG
m_outstanding_when_aborted = m_v4_outstanding + m_v6_outstanding;
#endif
if (m_connection_ticket >= 0)
{
m_cc.done(m_connection_ticket);
m_connection_ticket = -1;
// we just called done, which means on_timeout
// won't be called. Decrement the outstanding
// ops counter for that
TORRENT_ASSERT(m_outstanding_ops > 0);
--m_outstanding_ops;
if (m_abort)
{
maybe_clear_callback(l);
return;
}
}
maybe_clear_callback(l);
}
void udp_socket::bind(udp::endpoint const& ep, error_code& ec)
{
mutex_t::scoped_lock l(m_mutex);
CHECK_MAGIC;
TORRENT_ASSERT(m_abort == false);
if (m_abort) return;
if (m_ipv4_sock.is_open()) m_ipv4_sock.close(ec);
#if TORRENT_USE_IPV6
if (m_ipv6_sock.is_open()) m_ipv6_sock.close(ec);
#endif
if (ep.address().is_v4())
{
m_ipv4_sock.open(udp::v4(), ec);
if (ec) return;
m_ipv4_sock.bind(ep, ec);
if (ec) return;
if (m_v4_outstanding == 0)
{
++m_v4_outstanding;
m_ipv4_sock.async_receive_from(asio::buffer(m_v4_buf, sizeof(m_v4_buf))
, m_v4_ep, boost::bind(&udp_socket::on_read, self(), &m_ipv4_sock, _1, _2));
}
}
#if TORRENT_USE_IPV6
else
{
m_ipv6_sock.set_option(v6only(true), ec);
if (ec) return;
m_ipv6_sock.bind(ep, ec);
if (ec) return;
if (m_v6_outstanding == 0)
{
++m_v6_outstanding;
m_ipv6_sock.async_receive_from(asio::buffer(m_v6_buf, sizeof(m_v6_buf))
, m_v6_ep, boost::bind(&udp_socket::on_read, self(), &m_ipv6_sock, _1, _2));
}
}
#endif
#ifdef TORRENT_DEBUG
m_started = true;
#endif
m_bind_port = ep.port();
}
void udp_socket::bind(int port)
{
mutex_t::scoped_lock l(m_mutex);
CHECK_MAGIC;
TORRENT_ASSERT(m_abort == false);
if (m_abort) return;
error_code ec;
if (m_ipv4_sock.is_open()) m_ipv4_sock.close(ec);
#if TORRENT_USE_IPV6
if (m_ipv6_sock.is_open()) m_ipv6_sock.close(ec);
#endif
m_ipv4_sock.open(udp::v4(), ec);
if (!ec)
{
m_ipv4_sock.bind(udp::endpoint(address_v4::any(), port), ec);
if (m_v4_outstanding == 0)
{
++m_v4_outstanding;
m_ipv4_sock.async_receive_from(asio::buffer(m_v4_buf, sizeof(m_v4_buf))
, m_v4_ep, boost::bind(&udp_socket::on_read, self(), &m_ipv4_sock, _1, _2));
}
}
#if TORRENT_USE_IPV6
m_ipv6_sock.open(udp::v6(), ec);
if (!ec)
{
m_ipv6_sock.set_option(v6only(true), ec);
m_ipv6_sock.bind(udp::endpoint(address_v6::any(), port), ec);
if (m_v6_outstanding == 0)
{
++m_v6_outstanding;
m_ipv6_sock.async_receive_from(asio::buffer(m_v6_buf, sizeof(m_v6_buf))
, m_v6_ep, boost::bind(&udp_socket::on_read, self(), &m_ipv6_sock, _1, _2));
}
}
#endif // TORRENT_USE_IPV6
#ifdef TORRENT_DEBUG
m_started = true;
#endif
m_bind_port = port;
}
void udp_socket::set_proxy_settings(proxy_settings const& ps)
{
mutex_t::scoped_lock l(m_mutex);
CHECK_MAGIC;
error_code ec;
m_socks5_sock.close(ec);
m_tunnel_packets = false;
m_proxy_settings = ps;
if (ps.type == proxy_settings::socks5
|| ps.type == proxy_settings::socks5_pw)
{
m_queue_packets = true;
// connect to socks5 server and open up the UDP tunnel
tcp::resolver::query q(ps.hostname, to_string(ps.port).elems);
++m_outstanding_ops;
m_resolver.async_resolve(q, boost::bind(
&udp_socket::on_name_lookup, self(), _1, _2));
}
}
void udp_socket::on_name_lookup(error_code const& e, tcp::resolver::iterator i)
{
mutex_t::scoped_lock l(m_mutex);
TORRENT_ASSERT(m_outstanding_ops > 0);
--m_outstanding_ops;
if (m_abort)
{
maybe_clear_callback(l);
return;
}
CHECK_MAGIC;
if (e == asio::error::operation_aborted) return;
if (e)
{
#ifndef BOOST_NO_EXCEPTIONS
try {
#endif
m_callback(e, udp::endpoint(), 0, 0);
#ifndef BOOST_NO_EXCEPTIONS
} catch(std::exception&) {}
#endif
return;
}
m_proxy_addr.address(i->endpoint().address());
m_proxy_addr.port(i->endpoint().port());
l.unlock();
// on_connect may be called from within this thread
// the semantics for on_connect and on_timeout is
// a bit complicated. See comments in connection_queue.hpp
// for more details. This semantic determines how and
// when m_outstanding_ops may be decremented
// To simplyfy this, it's probably a good idea to
// merge on_connect and on_timeout to a single function
++m_outstanding_ops;
m_cc.enqueue(boost::bind(&udp_socket::on_connect, self(), _1)
, boost::bind(&udp_socket::on_timeout, self()), seconds(10));
}
void udp_socket::on_timeout()
{
mutex_t::scoped_lock l(m_mutex);
CHECK_MAGIC;
error_code ec;
m_socks5_sock.close(ec);
m_connection_ticket = -1;
}
void udp_socket::on_connect(int ticket)
{
mutex_t::scoped_lock l(m_mutex);
TORRENT_ASSERT(m_outstanding_ops > 0);
--m_outstanding_ops;
if (m_abort)
{
maybe_clear_callback(l);
return;
}
CHECK_MAGIC;
if (is_closed()) return;
m_connection_ticket = ticket;
// at this point on_timeout may be called before on_connected
// so increment the outstanding ops
// it may also not be called in case we call
// connection_queue::done first, so be sure to
// decrement if that happens
++m_outstanding_ops;
error_code ec;
m_socks5_sock.open(m_proxy_addr.address().is_v4()?tcp::v4():tcp::v6(), ec);
++m_outstanding_ops;
m_socks5_sock.async_connect(tcp::endpoint(m_proxy_addr.address(), m_proxy_addr.port())
, boost::bind(&udp_socket::on_connected, self(), _1));
}
void udp_socket::on_connected(error_code const& e)
{
mutex_t::scoped_lock l(m_mutex);
TORRENT_ASSERT(m_outstanding_ops > 0);
--m_outstanding_ops;
if (m_abort)
{
maybe_clear_callback(l);
return;
}
CHECK_MAGIC;
if (e == asio::error::operation_aborted) return;
m_cc.done(m_connection_ticket);
m_connection_ticket = -1;
// we just called done, which meand on_timeout
// won't be called. Decrement the outstanding
// ops counter for that
TORRENT_ASSERT(m_outstanding_ops > 0);
--m_outstanding_ops;
if (m_abort)
{
maybe_clear_callback(l);
return;
}
if (e)
{
#ifndef BOOST_NO_EXCEPTIONS
try {
#endif
m_callback(e, udp::endpoint(), 0, 0);
#ifndef BOOST_NO_EXCEPTIONS
} catch(std::exception&) {}
#endif
return;
}
if (is_closed()) return;
using namespace libtorrent::detail;
// send SOCKS5 authentication methods
char* p = &m_tmp_buf[0];
write_uint8(5, p); // SOCKS VERSION 5
if (m_proxy_settings.username.empty()
|| m_proxy_settings.type == proxy_settings::socks5)
{
write_uint8(1, p); // 1 authentication method (no auth)
write_uint8(0, p); // no authentication
}
else
{
write_uint8(2, p); // 2 authentication methods
write_uint8(0, p); // no authentication
write_uint8(2, p); // username/password
}
++m_outstanding_ops;
asio::async_write(m_socks5_sock, asio::buffer(m_tmp_buf, p - m_tmp_buf)
, boost::bind(&udp_socket::handshake1, self(), _1));
}
void udp_socket::handshake1(error_code const& e)
{
mutex_t::scoped_lock l(m_mutex);
TORRENT_ASSERT(m_outstanding_ops > 0);
--m_outstanding_ops;
if (m_abort)
{
maybe_clear_callback(l);
return;
}
CHECK_MAGIC;
if (e) return;
++m_outstanding_ops;
asio::async_read(m_socks5_sock, asio::buffer(m_tmp_buf, 2)
, boost::bind(&udp_socket::handshake2, self(), _1));
}
void udp_socket::handshake2(error_code const& e)
{
mutex_t::scoped_lock l(m_mutex);
TORRENT_ASSERT(m_outstanding_ops > 0);
--m_outstanding_ops;
if (m_abort)
{
maybe_clear_callback(l);
return;
}
CHECK_MAGIC;
if (e) return;
using namespace libtorrent::detail;
char* p = &m_tmp_buf[0];
int version = read_uint8(p);
int method = read_uint8(p);
if (version < 5) return;
if (method == 0)
{
socks_forward_udp(l);
}
else if (method == 2)
{
if (m_proxy_settings.username.empty())
{
error_code ec;
m_socks5_sock.close(ec);
return;
}
// start sub-negotiation
char* p = &m_tmp_buf[0];
write_uint8(1, p);
write_uint8(m_proxy_settings.username.size(), p);
write_string(m_proxy_settings.username, p);
write_uint8(m_proxy_settings.password.size(), p);
write_string(m_proxy_settings.password, p);
++m_outstanding_ops;
asio::async_write(m_socks5_sock, asio::buffer(m_tmp_buf, p - m_tmp_buf)
, boost::bind(&udp_socket::handshake3, self(), _1));
}
else
{
error_code ec;
m_socks5_sock.close(ec);
return;
}
}
void udp_socket::handshake3(error_code const& e)
{
mutex_t::scoped_lock l(m_mutex);
TORRENT_ASSERT(m_outstanding_ops > 0);
--m_outstanding_ops;
if (m_abort)
{
maybe_clear_callback(l);
return;
}
CHECK_MAGIC;
if (e) return;
++m_outstanding_ops;
asio::async_read(m_socks5_sock, asio::buffer(m_tmp_buf, 2)
, boost::bind(&udp_socket::handshake4, self(), _1));
}
void udp_socket::handshake4(error_code const& e)
{
mutex_t::scoped_lock l(m_mutex);
TORRENT_ASSERT(m_outstanding_ops > 0);
--m_outstanding_ops;
if (m_abort)
{
maybe_clear_callback(l);
return;
}
CHECK_MAGIC;
if (e) return;
using namespace libtorrent::detail;
char* p = &m_tmp_buf[0];
int version = read_uint8(p);
int status = read_uint8(p);
if (version != 1) return;
if (status != 0) return;
socks_forward_udp(l);
}
void udp_socket::socks_forward_udp(mutex_t::scoped_lock& l)
{
TORRENT_ASSERT(m_outstanding_ops > 0);
--m_outstanding_ops;
if (m_abort)
{
maybe_clear_callback(l);
return;
}
CHECK_MAGIC;
using namespace libtorrent::detail;
// send SOCKS5 UDP command
char* p = &m_tmp_buf[0];
write_uint8(5, p); // SOCKS VERSION 5
write_uint8(3, p); // UDP ASSOCIATE command
write_uint8(0, p); // reserved
write_uint8(1, p); // ATYP IPv4
write_uint32(0, p); // IP any
write_uint16(m_bind_port, p);
++m_outstanding_ops;
asio::async_write(m_socks5_sock, asio::buffer(m_tmp_buf, p - m_tmp_buf)
, boost::bind(&udp_socket::connect1, self(), _1));
}
void udp_socket::connect1(error_code const& e)
{
mutex_t::scoped_lock l(m_mutex);
TORRENT_ASSERT(m_outstanding_ops > 0);
--m_outstanding_ops;
if (m_abort)
{
maybe_clear_callback(l);
return;
}
CHECK_MAGIC;
if (e) return;
++m_outstanding_ops;
asio::async_read(m_socks5_sock, asio::buffer(m_tmp_buf, 10)
, boost::bind(&udp_socket::connect2, self(), _1));
}
void udp_socket::connect2(error_code const& e)
{
mutex_t::scoped_lock l(m_mutex);
TORRENT_ASSERT(m_outstanding_ops > 0);
--m_outstanding_ops;
if (m_abort)
{
m_queue.clear();
maybe_clear_callback(l);
return;
}
CHECK_MAGIC;
if (e)
{
m_queue.clear();
return;
}
using namespace libtorrent::detail;
char* p = &m_tmp_buf[0];
int version = read_uint8(p); // VERSION
int status = read_uint8(p); // STATUS
++p; // RESERVED
int atyp = read_uint8(p); // address type
if (version != 5 || status != 0)
{
m_queue.clear();
return;
}
if (atyp == 1)
{
m_proxy_addr.address(address_v4(read_uint32(p)));
m_proxy_addr.port(read_uint16(p));
}
else
{
// in this case we need to read more data from the socket
TORRENT_ASSERT(false && "not implemented yet!");
m_queue.clear();
return;
}
m_tunnel_packets = true;
m_queue_packets = false;
// forward all packets that were put in the queue
while (!m_queue.empty())
{
queued_packet const& p = m_queue.front();
error_code ec;
udp_socket::send(p.ep, &p.buf[0], p.buf.size(), ec);
m_queue.pop_front();
}
++m_outstanding_ops;
asio::async_read(m_socks5_sock, asio::buffer(m_tmp_buf, 10)
, boost::bind(&udp_socket::hung_up, self(), _1));
}
void udp_socket::hung_up(error_code const& e)
{
mutex_t::scoped_lock l(m_mutex);
TORRENT_ASSERT(m_outstanding_ops > 0);
--m_outstanding_ops;
if (m_abort)
{
maybe_clear_callback(l);
return;
}
CHECK_MAGIC;
if (e == asio::error::operation_aborted || m_abort) return;
l.unlock();
// the socks connection was closed, re-open it
set_proxy_settings(m_proxy_settings);
}
rate_limited_udp_socket::rate_limited_udp_socket(io_service& ios
, callback_t const& c, connection_queue& cc)
: udp_socket(ios, c, cc)
, m_timer(ios)
, m_queue_size_limit(200)
, m_rate_limit(4000)
, m_quota(4000)
, m_last_tick(time_now())
{
error_code ec;
m_timer.expires_from_now(seconds(1), ec);
m_timer.async_wait(boost::bind(&rate_limited_udp_socket::on_tick
, boost::intrusive_ptr<rate_limited_udp_socket>(this), _1));
TORRENT_ASSERT(!ec);
}
bool rate_limited_udp_socket::send(udp::endpoint const& ep, char const* p, int len, error_code& ec, int flags)
{
if (m_quota < len)
{
// bit 1 of flags means "don't drop"
if (int(m_queue.size()) >= m_queue_size_limit && (flags & 1) == 0)
return false;
m_queue.push_back(queued_packet());
queued_packet& qp = m_queue.back();
qp.ep = ep;
qp.buf.insert(qp.buf.begin(), p, p + len);
return true;
}
m_quota -= len;
udp_socket::send(ep, p, len, ec);
return true;
}
void rate_limited_udp_socket::on_tick(error_code const& e)
{
if (e) return;
if (is_closed()) return;
error_code ec;
ptime now = time_now_hires();
m_timer.expires_at(now + seconds(1), ec);
m_timer.async_wait(boost::bind(&rate_limited_udp_socket::on_tick
, boost::intrusive_ptr<rate_limited_udp_socket>(this), _1));
time_duration delta = now - m_last_tick;
m_last_tick = now;
if (m_quota < m_rate_limit) m_quota += m_rate_limit * total_milliseconds(delta) / 1000;
if (m_queue.empty()) return;
while (!m_queue.empty() && int(m_queue.front().buf.size()) <= m_quota)
{
queued_packet const& p = m_queue.front();
TORRENT_ASSERT(m_quota >= int(p.buf.size()));
m_quota -= p.buf.size();
error_code ec;
udp_socket::send(p.ep, &p.buf[0], p.buf.size(), ec);
m_queue.pop_front();
}
}
void rate_limited_udp_socket::close()
{
error_code ec;
m_timer.cancel(ec);
udp_socket::close();
}
| Java |
package VCP::DB_File::sdbm;
=head1 NAME
VCP::DB_File::sdbm - Subclass providing SDBM_File storage
=head1 SYNOPSIS
use VCP::DB_File;
VCP::DB_File->new;
=head1 DESCRIPTION
To write your own DB_File filetype, copy this file and alter it. Then
ask us to add an option to the .vcp file parsing to enable it.
=over
=for test_script t/01db_file_sdbm.t
=cut
$VERSION = 1 ;
@ISA = qw( VCP::DB_File );
use strict ;
use VCP::Debug qw( :debug );
use Fcntl;
use File::Spec;
use SDBM_File;
use VCP::DB_File;
use VCP::Debug qw( :debug );
use VCP::Logger qw( BUG );
#use base qw( VCP::DB_File );
#use fields (
# 'Hash', ## The hash we tie
#);
sub db_file {
my $self = shift;
return File::Spec->catfile(
$self->store_loc,
"db"
);
}
sub close_db {
my $self = shift;
return unless $self->{Hash};
$self->SUPER::close_db;
$self->{Hash} = undef;
}
sub delete_db {
my $self = shift;
my $store_files_pattern = $self->store_loc . "/*";
my $has_store_files = -e $self->store_loc;
if ( $has_store_files ) {
require File::Glob;
my @store_files = File::Glob::glob( $store_files_pattern );
$has_store_files &&= @store_files;
}
return
unless $has_store_files;
$self->SUPER::delete_db;
$self->rmdir_store_loc unless $ENV{VCPNODELETE};
}
sub open_db {
my $self = shift;
$self->SUPER::open_db;
$self->mkdir_store_loc;
$self->{Hash} = {};
my $fn = $self->db_file;
tie %{$self->{Hash}}, "SDBM_File", $fn, O_RDWR|O_CREAT, 0660
or die "$! while opening DB_File SDBM file '$fn'";
}
sub open_existing_db {
my $self = shift;
$self->SUPER::open_db;
$self->mkdir_store_loc;
$self->{Hash} = {};
my $fn = $self->db_file;
tie %{$self->{Hash}}, "SDBM_File", $fn, O_RDWR, 0
or die "$! while opening DB_File SDBM file '$fn'";
}
sub raw_set { ## so big_records.pm can call us with prepacked stuff
my $self = shift;
my $key = shift;
$self->{Hash}->{$key} = shift;
}
sub set {
my $self = shift;
my $key_parts = shift;
BUG "key must be an ARRAY reference"
unless ref $key_parts eq "ARRAY";
debug "setting ",
ref $self, " ",
join( ",", @$key_parts ), " => ",
join( ",", @_ )
if debugging;
$self->raw_set(
$self->pack_values( @$key_parts ),
$self->pack_values( @_ )
);
}
sub raw_get {
my $self = shift;
my $key = shift;
$self->{Hash}->{$key};
}
sub get {
my $self = shift;
my $key_parts = shift;
BUG "key must be an ARRAY reference"
unless ref $key_parts eq "ARRAY";
BUG "extra args found"
if @_;
BUG "called in scalar context"
if defined wantarray && !wantarray;
my $key = $self->pack_values( @$key_parts );
my $v = $self->raw_get( $key );
return unless defined $v;
$self->unpack_values( $v );
}
sub exists {
my $self = shift;
my $key_parts = shift;
BUG "key must be an ARRAY reference"
unless ref $key_parts eq "ARRAY";
my $key = $self->pack_values( @$key_parts );
return $self->{Hash}->{$key} ? 1 : 0;
}
sub keys {
my $self = shift;
map [ $self->unpack_values( $_ ) ], keys %{$self->{Hash}};
}
=item dump
$db->dump( \*STDOUT );
my $s = $db->dump;
my @l = $db->dump;
Dumps keys and values from a DB, in lexically sorted key order.
If a filehandle reference is provided, prints to that filehandle.
Otherwise, returns a string or array containing the entire dump,
depending on context.
=cut
sub dump {
my $self = shift;
my $fh = @_ ? shift : undef;
my( @keys, %vals );
my @w;
while ( my ( $k, $v ) = each %{$self->{Hash}} ) {
my @key = $self->unpack_values( $k );
for ( my $i = 0; $i <= $#key; ++$i ) {
$w[$i] = length $key[$i]
if ! defined $w[$i] || length $key[$i] > $w[$i];
}
push @keys, $k;
$vals{$k} = [ $self->unpack_values( $v ) ];
}
## This does not take file separators in to account, but that's ok
## for a debugging tool and the ids that are used as key values
## are supposed to be opaque anyway
@keys = sort @keys;
# build format string
my $f = join( " ", map "%-${w[$_]}s", 0..$#w ) . " => %s\n";
my @lines;
while ( @keys ) {
my $k = shift @keys;
my @v = map { "'$_'" } @{$vals{$k}};
my $s = sprintf $f,
$self->unpack_values( $k ),
@v == 1 ? $v[0] : join join( ",", @v ), "(", ")";
if( defined $fh ) {
print $fh $s;
}
else {
push @lines, $s;
}
}
unless( defined $fh ) {
if( wantarray ) {
chomp @lines;
return @lines;
}
return join "", @lines;
}
}
=back
=head1 LIMITATIONS
There is no way (yet) of telling the mapper to continue processing the
rules list. We could implement labels like C< <<I<label>>> > to be
allowed before pattern expressions (but not between pattern and result),
and we could then impelement C< <<goto I<label>>> >. And a C< <<next>>
> could be used to fall through to the next label. All of which is
wonderful, but I want to gain some real world experience with the
current system and find a use case for gotos and fallthroughs before I
implement them. This comment is here to solicit feedback :).
=head1 AUTHOR
Barrie Slaymaker <[email protected]>
=head1 COPYRIGHT
Copyright (c) 2000, 2001, 2002 Perforce Software, Inc.
All rights reserved.
See L<VCP::License|VCP::License> (C<vcp help license>) for the terms of use.
=cut
1
| Java |
/*
* Copyright (c) 2015, Simone Margaritelli <evilsocket at gmail dot com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * 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 ARM Inject 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.
*/
#ifndef LINKER_H_
#define LINKER_H_
#include <elf.h>
#define ANDROID_ARM_LINKER 1
#define SOINFO_NAME_LEN 128
struct link_map
{
uintptr_t l_addr;
char * l_name;
uintptr_t l_ld;
struct link_map * l_next;
struct link_map * l_prev;
};
struct soinfo
{
const char name[SOINFO_NAME_LEN];
Elf32_Phdr *phdr;
int phnum;
unsigned entry;
unsigned base;
unsigned size;
int unused; // DO NOT USE, maintained for compatibility.
unsigned *dynamic;
unsigned wrprotect_start;
unsigned wrprotect_end;
struct soinfo *next;
unsigned flags;
const char *strtab;
Elf32_Sym *symtab;
unsigned nbucket;
unsigned nchain;
unsigned *bucket;
unsigned *chain;
unsigned *plt_got;
Elf32_Rel *plt_rel;
unsigned plt_rel_count;
Elf32_Rel *rel;
unsigned rel_count;
unsigned *preinit_array;
unsigned preinit_array_count;
unsigned *init_array;
unsigned init_array_count;
unsigned *fini_array;
unsigned fini_array_count;
void (*init_func)(void);
void (*fini_func)(void);
#ifdef ANDROID_ARM_LINKER
/* ARM EABI section used for stack unwinding. */
unsigned *ARM_exidx;
unsigned ARM_exidx_count;
#endif
unsigned refcount;
struct link_map linkmap;
int constructors_called;
Elf32_Addr gnu_relro_start;
unsigned gnu_relro_len;
};
#define R_ARM_ABS32 2
#define R_ARM_COPY 20
#define R_ARM_GLOB_DAT 21
#define R_ARM_JUMP_SLOT 22
#define R_ARM_RELATIVE 23
#endif
| Java |
Specifies a list of libraries and projects to link against.
```lua
links { "references" }
```
### Parameters ###
`references` is a list of library and project names.
When linking against another project in the same workspace, specify the project name here, rather than the library name. Premake will figure out the correct library to link against for the current configuration, and will also create a dependency between the projects to ensure a proper build order.
When linking against system libraries, do not include any prefix or file extension. Premake will use the appropriate naming conventions for the current platform. With two exceptions:
* Managed C++ projects can link against managed assemblies by explicitly specifying the ".dll" file extension. Unmanaged libraries should continue to be specified without any decoration.
* Objective C frameworks can be linked by explicitly including the ".framework" file extension.
* For Visual Studio, this will add the specified project into References. In contrast, 'dependson' generates a build order dependency in the solution between two projects.
### Applies To ###
Project configurations.
### Availability ###
Premake 4.0 or later.
### Examples ###
Link against some system libraries.
```lua
filter { "system:windows" }
links { "user32", "gdi32" }
filter { "system:linux" }
links { "m", "png" }
filter { "system:macosx" }
-- OS X frameworks need the extension to be handled properly
links { "Cocoa.framework", "png" }
```
In a workspace with two projects, link the library into the executable. Note that the project name is used to specify the link; Premake will automatically figure out the correct library file name and directory and create a project dependency.
```lua
workspace "MyWorkspace"
configurations { "Debug", "Release" }
language "C++"
project "MyExecutable"
kind "ConsoleApp"
files "**.cpp"
links { "MyLibrary" }
project "MyLibrary"
kind "SharedLib"
files "**.cpp"
```
You may also create links between non-library projects. In this case, Premake will generate a build dependency (the linked project will build first), but not an actual link. In this example, MyProject uses a build dependency to ensure that MyTool gets built first. It then uses MyTool as part of its build process.
```lua
workspace "MyWorkspace"
configurations { "Debug", "Release" }
language "C++"
project "MyProject"
kind "ConsoleApp"
files "**.cpp"
links { "MyTool" }
prebuildcommands { "MyTool --dosomething" }
project "MyTool"
kind "ConsoleApp"
files "**.cpp"
```
| Java |
<!DOCTYPE html>
<html>
<head>
<title>Flatty - Flat Administration Template</title>
<meta content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no' name='viewport'>
<meta content='text/html;charset=utf-8' http-equiv='content-type'>
<meta content='Flat administration template for Twitter Bootstrap.' name='description'>
<link href='<?php echo Yii::app()->theme->baseUrl; ?>/assets/images/meta_icons/favicon.ico' rel='shortcut icon' type='image/x-icon'>
<link href='<?php echo Yii::app()->theme->baseUrl; ?>/assets/images/meta_icons/apple-touch-icon.png' rel='apple-touch-icon-precomposed'>
<link href='<?php echo Yii::app()->theme->baseUrl; ?>/assets/images/meta_icons/apple-touch-icon-57x57.png' rel='apple-touch-icon-precomposed' sizes='57x57'>
<link href='<?php echo Yii::app()->theme->baseUrl; ?>/assets/images/meta_icons/apple-touch-icon-72x72.png' rel='apple-touch-icon-precomposed' sizes='72x72'>
<link href='<?php echo Yii::app()->theme->baseUrl; ?>/assets/images/meta_icons/apple-touch-icon-114x114.png' rel='apple-touch-icon-precomposed' sizes='114x114'>
<link href='<?php echo Yii::app()->theme->baseUrl; ?>/assets/images/meta_icons/apple-touch-icon-144x144.png' rel='apple-touch-icon-precomposed' sizes='144x144'>
<!--[if lt IE 9]>
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/html5shiv.js" type="text/javascript"></script>
<![endif]-->
<!-- / bootstrap [required files] -->
<link href="<?php echo Yii::app()->theme->baseUrl; ?>/assets/stylesheets/bootstrap/bootstrap.css" media="all" rel="stylesheet" type="text/css" />
<link href="<?php echo Yii::app()->theme->baseUrl; ?>/assets/stylesheets/bootstrap/bootstrap-responsive.css" media="all" rel="stylesheet" type="text/css" />
<!-- / jquery ui -->
<link href="<?php echo Yii::app()->theme->baseUrl; ?>/assets/stylesheets/jquery_ui/jquery.ui-1.10.0.custom.css" media="all" rel="stylesheet" type="text/css" />
<link href="<?php echo Yii::app()->theme->baseUrl; ?>/assets/stylesheets/jquery_ui/jquery.ui.1.10.0.ie.css" media="all" rel="stylesheet" type="text/css" />
<!-- / switch buttons -->
<link href="<?php echo Yii::app()->theme->baseUrl; ?>/assets/stylesheets/plugins/bootstrap_switch/bootstrap-switch.css" media="all" rel="stylesheet" type="text/css" />
<!-- / xeditable -->
<link href="<?php echo Yii::app()->theme->baseUrl; ?>/assets/stylesheets/plugins/xeditable/bootstrap-editable.css" media="all" rel="stylesheet" type="text/css" />
<link href="<?php echo Yii::app()->theme->baseUrl; ?>/assets/stylesheets/plugins/common/bootstrap-wysihtml5.css" media="all" rel="stylesheet" type="text/css" />
<!-- / wysihtml5 (wysywig) -->
<link href="<?php echo Yii::app()->theme->baseUrl; ?>/assets/stylesheets/plugins/common/bootstrap-wysihtml5.css" media="all" rel="stylesheet" type="text/css" />
<!-- / jquery file upload -->
<link href="<?php echo Yii::app()->theme->baseUrl; ?>/assets/stylesheets/plugins/jquery_fileupload/jquery.fileupload-ui.css" media="all" rel="stylesheet" type="text/css" />
<!-- / full calendar -->
<link href="<?php echo Yii::app()->theme->baseUrl; ?>/assets/stylesheets/plugins/fullcalendar/fullcalendar.css" media="all" rel="stylesheet" type="text/css" />
<!-- / select2 -->
<link href="<?php echo Yii::app()->theme->baseUrl; ?>/assets/stylesheets/plugins/select2/select2.css" media="all" rel="stylesheet" type="text/css" />
<!-- / mention -->
<link href="<?php echo Yii::app()->theme->baseUrl; ?>/assets/stylesheets/plugins/mention/mention.css" media="all" rel="stylesheet" type="text/css" />
<!-- / tabdrop (responsive tabs) -->
<link href="<?php echo Yii::app()->theme->baseUrl; ?>/assets/stylesheets/plugins/tabdrop/tabdrop.css" media="all" rel="stylesheet" type="text/css" />
<!-- / jgrowl notifications -->
<link href="<?php echo Yii::app()->theme->baseUrl; ?>/assets/stylesheets/plugins/jgrowl/jquery.jgrowl.min.css" media="all" rel="stylesheet" type="text/css" />
<!-- / datatables -->
<link href="<?php echo Yii::app()->theme->baseUrl; ?>/assets/stylesheets/plugins/datatables/bootstrap-datatable.css" media="all" rel="stylesheet" type="text/css" />
<!-- / dynatrees (file trees) -->
<link href="<?php echo Yii::app()->theme->baseUrl; ?>/assets/stylesheets/plugins/dynatree/ui.dynatree.css" media="all" rel="stylesheet" type="text/css" />
<!-- / color picker -->
<link href="<?php echo Yii::app()->theme->baseUrl; ?>/assets/stylesheets/plugins/bootstrap_colorpicker/bootstrap-colorpicker.css" media="all" rel="stylesheet" type="text/css" />
<!-- / datetime picker -->
<link href="<?php echo Yii::app()->theme->baseUrl; ?>/assets/stylesheets/plugins/bootstrap_datetimepicker/bootstrap-datetimepicker.min.css" media="all" rel="stylesheet" type="text/css" />
<!-- / daterange picker) -->
<link href="<?php echo Yii::app()->theme->baseUrl; ?>/assets/stylesheets/plugins/bootstrap_daterangepicker/bootstrap-daterangepicker.css" media="all" rel="stylesheet" type="text/css" />
<!-- / flags (country flags) -->
<link href="<?php echo Yii::app()->theme->baseUrl; ?>/assets/stylesheets/plugins/flags/flags.css" media="all" rel="stylesheet" type="text/css" />
<!-- / slider nav (address book) -->
<link href="<?php echo Yii::app()->theme->baseUrl; ?>/assets/stylesheets/plugins/slider_nav/slidernav.css" media="all" rel="stylesheet" type="text/css" />
<!-- / fuelux (wizard) -->
<link href="<?php echo Yii::app()->theme->baseUrl; ?>/assets/stylesheets/plugins/fuelux/wizard.css" media="all" rel="stylesheet" type="text/css" />
<!-- / theme files [required files] -->
<link href="<?php echo Yii::app()->theme->baseUrl; ?>/assets/stylesheets/light-theme.css" media="all" id="color-settings-body-color" rel="stylesheet" type="text/css" />
<link href="<?php echo Yii::app()->theme->baseUrl; ?>/assets/stylesheets/theme-colors.css" media="all" rel="stylesheet" type="text/css" />
<link href="<?php echo Yii::app()->theme->baseUrl; ?>/assets/stylesheets/demo.css" media="all" rel="stylesheet" type="text/css" />
</head>
<body class='contrast-purple sign-in contrast-background'>
<div id='wrapper'>
<div class='application'>
<div class='application-content'>
<a href='#'>
<div class='icon-heart'></div>
<span>Yincart开源商城</span>
</a>
</div>
</div>
<div class='controls'>
<div class='caret'></div>
<div class='form-wrapper'>
<h1 class='text-center'>Sign in</h1>
<!-- <form action='--><?php //echo Yii::app()->createUrl('/site/login') ?><!--' method='post'>-->
<?php $form=$this->beginWidget('bootstrap.widgets.TbActiveForm', array(
'id'=>'user-login',
// 'type'=>'horizontal',
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
)); ?>
<?php echo $form->errorSummary($model); ?>
<div class='row-fluid'>
<div class='span12 icon-over-input'>
<input value="" placeholder="Username" class="span12" name="UserLogin[username]" type="text" />
<i class='icon-user muted'></i>
</div>
</div>
<div class='row-fluid'>
<div class='span12 icon-over-input'>
<input value="" placeholder="Password" class="span12" name="UserLogin[password]" type="password" />
<i class='icon-lock muted'></i>
</div>
</div>
<label class='checkbox' for='remember_me'>
<input id='LoginForm_rememberMe' name='UserLogin[rememberMe]' type='checkbox' value='1'>
记住我
</label>
<button class='btn btn-block'>登录</button>
</form>
<div class='text-center'>
<hr class='hr-normal'>
<?php //echo CHtml::link("Forgot your password?", array('/user/recovery/recovery')); ?>
</div>
<?php $this->endWidget(); ?>
</div>
</div>
<div class='login-action text-center'>
<!-- <a href='--><?php //echo Yii::app()->createUrl('/site/sign_up') ?><!--'>-->
<!-- <i class='icon-user'></i>-->
<!-- New to Yincart?-->
<!-- <strong>Sign up</strong>-->
<!-- </a>-->
<span style="color:#ffffff">后台管理员账号:admin 密码:admin123</span>
</div>
</div>
<!-- / jquery -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/jquery/jquery.min.js" type="text/javascript"></script>
<!-- / jquery mobile events (for touch and slide) -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/mobile_events/jquery.mobile-events.min.js" type="text/javascript"></script>
<!-- / jquery migrate (for compatibility with new jquery) -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/jquery/jquery-migrate.min.js" type="text/javascript"></script>
<!-- / jquery ui -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/jquery_ui/jquery-ui.min.js" type="text/javascript"></script>
<!-- / jQuery UI Touch Punch -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/jquery_ui_touch_punch/jquery.ui.touch-punch.min.js" type="text/javascript"></script>
<!-- / bootstrap -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/bootstrap/bootstrap.min.js" type="text/javascript"></script>
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/flot/excanvas.js" type="text/javascript"></script>
<!-- / sparklines -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/sparklines/jquery.sparkline.min.js" type="text/javascript"></script>
<!-- / flot charts -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/flot/flot.min.js" type="text/javascript"></script>
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/flot/flot.resize.js" type="text/javascript"></script>
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/flot/flot.pie.js" type="text/javascript"></script>
<!-- / bootstrap switch -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/bootstrap_switch/bootstrapSwitch.min.js" type="text/javascript"></script>
<!-- / fullcalendar -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/fullcalendar/fullcalendar.min.js" type="text/javascript"></script>
<!-- / datatables -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/datatables/jquery.dataTables.min.js" type="text/javascript"></script>
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/datatables/jquery.dataTables.columnFilter.js" type="text/javascript"></script>
<!-- / wysihtml5 -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/common/wysihtml5.min.js" type="text/javascript"></script>
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/common/bootstrap-wysihtml5.js" type="text/javascript"></script>
<!-- / select2 -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/select2/select2.js" type="text/javascript"></script>
<!-- / color picker -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/bootstrap_colorpicker/bootstrap-colorpicker.min.js" type="text/javascript"></script>
<!-- / mention -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/mention/mention.min.js" type="text/javascript"></script>
<!-- / input mask -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/input_mask/bootstrap-inputmask.min.js" type="text/javascript"></script>
<!-- / fileinput -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/fileinput/bootstrap-fileinput.js" type="text/javascript"></script>
<!-- / modernizr -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/modernizr/modernizr.min.js" type="text/javascript"></script>
<!-- / retina -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/retina/retina.js" type="text/javascript"></script>
<!-- / fileupload -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/fileupload/tmpl.min.js" type="text/javascript"></script>
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/fileupload/load-image.min.js" type="text/javascript"></script>
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/fileupload/canvas-to-blob.min.js" type="text/javascript"></script>
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/fileupload/jquery.iframe-transport.min.js" type="text/javascript"></script>
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/fileupload/jquery.fileupload.min.js" type="text/javascript"></script>
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/fileupload/jquery.fileupload-fp.min.js" type="text/javascript"></script>
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/fileupload/jquery.fileupload-ui.min.js" type="text/javascript"></script>
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/fileupload/jquery.fileupload-init.js" type="text/javascript"></script>
<!-- / timeago -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/timeago/jquery.timeago.js" type="text/javascript"></script>
<!-- / slimscroll -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/slimscroll/jquery.slimscroll.min.js" type="text/javascript"></script>
<!-- / autosize (for textareas) -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/autosize/jquery.autosize-min.js" type="text/javascript"></script>
<!-- / charCount -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/charCount/charCount.js" type="text/javascript"></script>
<!-- / validate -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/validate/jquery.validate.min.js" type="text/javascript"></script>
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/validate/additional-methods.js" type="text/javascript"></script>
<!-- / naked password -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/naked_password/naked_password-0.2.4.min.js" type="text/javascript"></script>
<!-- / nestable -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/nestable/jquery.nestable.js" type="text/javascript"></script>
<!-- / tabdrop -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/tabdrop/bootstrap-tabdrop.js" type="text/javascript"></script>
<!-- / jgrowl -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/jgrowl/jquery.jgrowl.min.js" type="text/javascript"></script>
<!-- / bootbox -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/bootbox/bootbox.min.js" type="text/javascript"></script>
<!-- / inplace editing -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/xeditable/bootstrap-editable.min.js" type="text/javascript"></script>
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/xeditable/wysihtml5.js" type="text/javascript"></script>
<!-- / ckeditor -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/ckeditor/ckeditor.js" type="text/javascript"></script>
<!-- / filetrees -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/dynatree/jquery.dynatree.min.js" type="text/javascript"></script>
<!-- / datetime picker -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/bootstrap_datetimepicker/bootstrap-datetimepicker.js" type="text/javascript"></script>
<!-- / daterange picker -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/bootstrap_daterangepicker/moment.min.js" type="text/javascript"></script>
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/bootstrap_daterangepicker/bootstrap-daterangepicker.js" type="text/javascript"></script>
<!-- / max length -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/bootstrap_maxlength/bootstrap-maxlength.min.js" type="text/javascript"></script>
<!-- / dropdown hover -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/bootstrap_hover_dropdown/twitter-bootstrap-hover-dropdown.min.js" type="text/javascript"></script>
<!-- / slider nav (address book) -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/slider_nav/slidernav-min.js" type="text/javascript"></script>
<!-- / fuelux -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/plugins/fuelux/wizard.js" type="text/javascript"></script>
<!-- / flatty theme [required files] -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/nav.js" type="text/javascript"></script>
<!-- / flatty theme -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/tables.js" type="text/javascript"></script>
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/theme.js" type="text/javascript"></script>
<!-- / demo -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/demo/jquery.mockjax.js" type="text/javascript"></script>
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/demo/inplace_editing.js" type="text/javascript"></script>
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/demo/charts.js" type="text/javascript"></script>
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/assets/javascripts/demo/demo.js" type="text/javascript"></script>
</body>
</html>
| Java |
package org.hisp.dhis.system.filter;
/*
* Copyright (c) 2004-2015, University of Oslo
* 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 HISP project 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.
*/
import com.google.common.collect.Sets;
import org.hisp.dhis.common.ValueType;
import org.hisp.dhis.commons.filter.Filter;
import org.hisp.dhis.dataelement.DataElement;
import java.util.Set;
/**
* @author Lars Helge Overland
*/
public class AggregatableDataElementFilter
implements Filter<DataElement>
{
public static final AggregatableDataElementFilter INSTANCE = new AggregatableDataElementFilter();
private static final Set<ValueType> VALUE_TYPES = Sets.newHashSet(
ValueType.BOOLEAN, ValueType.TRUE_ONLY, ValueType.TEXT, ValueType.LONG_TEXT, ValueType.LETTER,
ValueType.INTEGER, ValueType.INTEGER_POSITIVE, ValueType.INTEGER_NEGATIVE, ValueType.INTEGER_ZERO_OR_POSITIVE,
ValueType.NUMBER, ValueType.UNIT_INTERVAL, ValueType.PERCENTAGE, ValueType.COORDINATE
);
@Override
public boolean retain( DataElement object )
{
return object != null && VALUE_TYPES.contains( object.getValueType() );
}
}
| Java |
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_CHROMEOS_POLICY_USER_CLOUD_POLICY_MANAGER_FACTORY_CHROMEOS_H_
#define CHROME_BROWSER_CHROMEOS_POLICY_USER_CLOUD_POLICY_MANAGER_FACTORY_CHROMEOS_H_
#include <map>
#include "base/basictypes.h"
#include "base/memory/ref_counted.h"
#include "base/memory/singleton.h"
#include "components/keyed_service/content/browser_context_keyed_base_factory.h"
class Profile;
namespace base {
class SequencedTaskRunner;
}
namespace content {
class BrowserContext;
}
namespace policy {
class UserCloudPolicyManagerChromeOS;
// BrowserContextKeyedBaseFactory implementation
// for UserCloudPolicyManagerChromeOS instances that initialize per-profile
// cloud policy settings on ChromeOS.
//
// UserCloudPolicyManagerChromeOS is handled different than other
// KeyedServices because it is a dependency of PrefService.
// Therefore, lifetime of instances is managed by Profile, Profile startup code
// invokes CreateForProfile() explicitly, takes ownership, and the instance
// is only deleted after PrefService destruction.
//
// TODO(mnissler): Remove the special lifetime management in favor of
// PrefService directly depending on UserCloudPolicyManagerChromeOS once the
// former has been converted to a KeyedService.
// See also http://crbug.com/131843 and http://crbug.com/131844.
class UserCloudPolicyManagerFactoryChromeOS
: public BrowserContextKeyedBaseFactory {
public:
// Returns an instance of the UserCloudPolicyManagerFactoryChromeOS singleton.
static UserCloudPolicyManagerFactoryChromeOS* GetInstance();
// Returns the UserCloudPolicyManagerChromeOS instance associated with
// |profile|.
static UserCloudPolicyManagerChromeOS* GetForProfile(Profile* profile);
// Creates an instance for |profile|. Note that the caller is responsible for
// managing the lifetime of the instance. Subsequent calls to GetForProfile()
// will return the created instance as long as it lives.
//
// If |force_immediate_load| is true, policy is loaded synchronously from
// UserCloudPolicyStore at startup.
static scoped_ptr<UserCloudPolicyManagerChromeOS> CreateForProfile(
Profile* profile,
bool force_immediate_load,
scoped_refptr<base::SequencedTaskRunner> background_task_runner);
private:
friend struct DefaultSingletonTraits<UserCloudPolicyManagerFactoryChromeOS>;
UserCloudPolicyManagerFactoryChromeOS();
virtual ~UserCloudPolicyManagerFactoryChromeOS();
// See comments for the static versions above.
UserCloudPolicyManagerChromeOS* GetManagerForProfile(Profile* profile);
scoped_ptr<UserCloudPolicyManagerChromeOS> CreateManagerForProfile(
Profile* profile,
bool force_immediate_load,
scoped_refptr<base::SequencedTaskRunner> background_task_runner);
// BrowserContextKeyedBaseFactory:
virtual void BrowserContextShutdown(
content::BrowserContext* context) OVERRIDE;
virtual void BrowserContextDestroyed(
content::BrowserContext* context) OVERRIDE;
virtual void SetEmptyTestingFactory(
content::BrowserContext* context) OVERRIDE;
virtual void CreateServiceNow(content::BrowserContext* context) OVERRIDE;
typedef std::map<Profile*, UserCloudPolicyManagerChromeOS*> ManagerMap;
ManagerMap managers_;
DISALLOW_COPY_AND_ASSIGN(UserCloudPolicyManagerFactoryChromeOS);
};
} // namespace policy
#endif // CHROME_BROWSER_CHROMEOS_POLICY_USER_CLOUD_POLICY_MANAGER_FACTORY_CHROMEOS_H_
| Java |
// 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.
#include "content/browser/mojo/mojo_app_connection_impl.h"
#include <stdint.h>
#include <utility>
#include "base/bind.h"
#include "content/browser/mojo/mojo_shell_context.h"
namespace content {
const char kBrowserMojoAppUrl[] = "system:content_browser";
namespace {
void OnGotInstanceID(shell::mojom::ConnectResult result,
const std::string& user_id,
uint32_t remote_id) {}
} // namespace
// static
std::unique_ptr<MojoAppConnection> MojoAppConnection::Create(
const std::string& user_id,
const std::string& name,
const std::string& requestor_name) {
return std::unique_ptr<MojoAppConnection>(
new MojoAppConnectionImpl(user_id, name, requestor_name));
}
MojoAppConnectionImpl::MojoAppConnectionImpl(
const std::string& user_id,
const std::string& name,
const std::string& requestor_name) {
MojoShellContext::ConnectToApplication(
user_id, name, requestor_name, mojo::GetProxy(&interfaces_),
shell::mojom::InterfaceProviderPtr(), base::Bind(&OnGotInstanceID));
}
MojoAppConnectionImpl::~MojoAppConnectionImpl() {
}
void MojoAppConnectionImpl::GetInterface(
const std::string& interface_name,
mojo::ScopedMessagePipeHandle handle) {
interfaces_->GetInterface(interface_name, std::move(handle));
}
} // namespace content
| Java |
# encoding: utf-8
require_relative './job'
module CartoDB
module Importer2
class FormatLinter
CHARACTER_LIMIT = 1000
def self.supported?(extension)
extension == '.kml'
end
# INFO: importer_config not used but needed for compatibility with other normalizers
def initialize(filepath, job = nil, importer_config = nil)
@filepath = filepath
@job = job || Job.new
end
def run
data = File.open(filepath, 'r')
sample = data.read(CHARACTER_LIMIT)
data.close
raise KmlNetworkLinkError if sample =~ /NetworkLink.*href.*NetworkLink/m
self
end
def converted_filepath
filepath
end
private
attr_reader :filepath, :job
end # FormatLinter
end # Importer2
end # CartoDB
| Java |
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the documentation of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "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 Digia Plc and its Subsidiary(-ies) 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."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtGui>
#include "buttonwidget.h"
//! [0]
ButtonWidget::ButtonWidget(QStringList texts, QWidget *parent)
: QWidget(parent)
{
signalMapper = new QSignalMapper(this);
QGridLayout *gridLayout = new QGridLayout;
for (int i = 0; i < texts.size(); ++i) {
QPushButton *button = new QPushButton(texts[i]);
connect(button, SIGNAL(clicked()), signalMapper, SLOT(map()));
//! [0] //! [1]
signalMapper->setMapping(button, texts[i]);
gridLayout->addWidget(button, i / 3, i % 3);
}
connect(signalMapper, SIGNAL(mapped(QString)),
//! [1] //! [2]
this, SIGNAL(clicked(QString)));
setLayout(gridLayout);
}
//! [2]
| Java |
from __future__ import division, absolute_import, print_function
import sys
if sys.version_info[0] >= 3:
from io import StringIO
else:
from io import StringIO
import compiler
import inspect
import textwrap
import tokenize
from .compiler_unparse import unparse
class Comment(object):
""" A comment block.
"""
is_comment = True
def __init__(self, start_lineno, end_lineno, text):
# int : The first line number in the block. 1-indexed.
self.start_lineno = start_lineno
# int : The last line number. Inclusive!
self.end_lineno = end_lineno
# str : The text block including '#' character but not any leading spaces.
self.text = text
def add(self, string, start, end, line):
""" Add a new comment line.
"""
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
self.text += string
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno, self.text)
class NonComment(object):
""" A non-comment block of code.
"""
is_comment = False
def __init__(self, start_lineno, end_lineno):
self.start_lineno = start_lineno
self.end_lineno = end_lineno
def add(self, string, start, end, line):
""" Add lines to the block.
"""
if string.strip():
# Only add if not entirely whitespace.
self.start_lineno = min(self.start_lineno, start[0])
self.end_lineno = max(self.end_lineno, end[0])
def __repr__(self):
return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno,
self.end_lineno)
class CommentBlocker(object):
""" Pull out contiguous comment blocks.
"""
def __init__(self):
# Start with a dummy.
self.current_block = NonComment(0, 0)
# All of the blocks seen so far.
self.blocks = []
# The index mapping lines of code to their associated comment blocks.
self.index = {}
def process_file(self, file):
""" Process a file object.
"""
if sys.version_info[0] >= 3:
nxt = file.__next__
else:
nxt = file.next
for token in tokenize.generate_tokens(nxt):
self.process_token(*token)
self.make_index()
def process_token(self, kind, string, start, end, line):
""" Process a single token.
"""
if self.current_block.is_comment:
if kind == tokenize.COMMENT:
self.current_block.add(string, start, end, line)
else:
self.new_noncomment(start[0], end[0])
else:
if kind == tokenize.COMMENT:
self.new_comment(string, start, end, line)
else:
self.current_block.add(string, start, end, line)
def new_noncomment(self, start_lineno, end_lineno):
""" We are transitioning from a noncomment to a comment.
"""
block = NonComment(start_lineno, end_lineno)
self.blocks.append(block)
self.current_block = block
def new_comment(self, string, start, end, line):
""" Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block.
"""
prefix = line[:start[1]]
if prefix.strip():
# Oops! Trailing comment, not a comment block.
self.current_block.add(string, start, end, line)
else:
# A comment block.
block = Comment(start[0], end[0], string)
self.blocks.append(block)
self.current_block = block
def make_index(self):
""" Make the index mapping lines of actual code to their associated
prefix comments.
"""
for prev, block in zip(self.blocks[:-1], self.blocks[1:]):
if not block.is_comment:
self.index[block.start_lineno] = prev
def search_for_comment(self, lineno, default=None):
""" Find the comment block just before the given line number.
Returns None (or the specified default) if there is no such block.
"""
if not self.index:
self.make_index()
block = self.index.get(lineno, None)
text = getattr(block, 'text', default)
return text
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
def get_class_traits(klass):
""" Yield all of the documentation for trait definitions on a class object.
"""
# FIXME: gracefully handle errors here or in the caller?
source = inspect.getsource(klass)
cb = CommentBlocker()
cb.process_file(StringIO(source))
mod_ast = compiler.parse(source)
class_ast = mod_ast.node.nodes[0]
for node in class_ast.code.nodes:
# FIXME: handle other kinds of assignments?
if isinstance(node, compiler.ast.Assign):
name = node.nodes[0].name
rhs = unparse(node.expr).strip()
doc = strip_comment_marker(cb.search_for_comment(node.lineno, default=''))
yield name, rhs, doc
| Java |
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ResponderEventPlugin
*/
'use strict';
var EventConstants = require('EventConstants');
var EventPluginUtils = require('EventPluginUtils');
var EventPropagators = require('EventPropagators');
var ResponderSyntheticEvent = require('ResponderSyntheticEvent');
var ResponderTouchHistoryStore = require('ResponderTouchHistoryStore');
var accumulate = require('accumulate');
var invariant = require('invariant');
var keyOf = require('keyOf');
var isStartish = EventPluginUtils.isStartish;
var isMoveish = EventPluginUtils.isMoveish;
var isEndish = EventPluginUtils.isEndish;
var executeDirectDispatch = EventPluginUtils.executeDirectDispatch;
var hasDispatches = EventPluginUtils.hasDispatches;
var executeDispatchesInOrderStopAtTrue =
EventPluginUtils.executeDispatchesInOrderStopAtTrue;
/**
* Instance of element that should respond to touch/move types of interactions,
* as indicated explicitly by relevant callbacks.
*/
var responderInst = null;
/**
* Count of current touches. A textInput should become responder iff the
* selection changes while there is a touch on the screen.
*/
var trackedTouchCount = 0;
/**
* Last reported number of active touches.
*/
var previousActiveTouches = 0;
var changeResponder = function(nextResponderInst, blockHostResponder) {
var oldResponderInst = responderInst;
responderInst = nextResponderInst;
if (ResponderEventPlugin.GlobalResponderHandler !== null) {
ResponderEventPlugin.GlobalResponderHandler.onChange(
oldResponderInst,
nextResponderInst,
blockHostResponder
);
}
};
var eventTypes = {
/**
* On a `touchStart`/`mouseDown`, is it desired that this element become the
* responder?
*/
startShouldSetResponder: {
phasedRegistrationNames: {
bubbled: keyOf({onStartShouldSetResponder: null}),
captured: keyOf({onStartShouldSetResponderCapture: null}),
},
},
/**
* On a `scroll`, is it desired that this element become the responder? This
* is usually not needed, but should be used to retroactively infer that a
* `touchStart` had occurred during momentum scroll. During a momentum scroll,
* a touch start will be immediately followed by a scroll event if the view is
* currently scrolling.
*
* TODO: This shouldn't bubble.
*/
scrollShouldSetResponder: {
phasedRegistrationNames: {
bubbled: keyOf({onScrollShouldSetResponder: null}),
captured: keyOf({onScrollShouldSetResponderCapture: null}),
},
},
/**
* On text selection change, should this element become the responder? This
* is needed for text inputs or other views with native selection, so the
* JS view can claim the responder.
*
* TODO: This shouldn't bubble.
*/
selectionChangeShouldSetResponder: {
phasedRegistrationNames: {
bubbled: keyOf({onSelectionChangeShouldSetResponder: null}),
captured: keyOf({onSelectionChangeShouldSetResponderCapture: null}),
},
},
/**
* On a `touchMove`/`mouseMove`, is it desired that this element become the
* responder?
*/
moveShouldSetResponder: {
phasedRegistrationNames: {
bubbled: keyOf({onMoveShouldSetResponder: null}),
captured: keyOf({onMoveShouldSetResponderCapture: null}),
},
},
/**
* Direct responder events dispatched directly to responder. Do not bubble.
*/
responderStart: {registrationName: keyOf({onResponderStart: null})},
responderMove: {registrationName: keyOf({onResponderMove: null})},
responderEnd: {registrationName: keyOf({onResponderEnd: null})},
responderRelease: {registrationName: keyOf({onResponderRelease: null})},
responderTerminationRequest: {
registrationName: keyOf({onResponderTerminationRequest: null}),
},
responderGrant: {registrationName: keyOf({onResponderGrant: null})},
responderReject: {registrationName: keyOf({onResponderReject: null})},
responderTerminate: {registrationName: keyOf({onResponderTerminate: null})},
};
/**
*
* Responder System:
* ----------------
*
* - A global, solitary "interaction lock" on a view.
* - If a node becomes the responder, it should convey visual feedback
* immediately to indicate so, either by highlighting or moving accordingly.
* - To be the responder means, that touches are exclusively important to that
* responder view, and no other view.
* - While touches are still occurring, the responder lock can be transferred to
* a new view, but only to increasingly "higher" views (meaning ancestors of
* the current responder).
*
* Responder being granted:
* ------------------------
*
* - Touch starts, moves, and scrolls can cause an ID to become the responder.
* - We capture/bubble `startShouldSetResponder`/`moveShouldSetResponder` to
* the "appropriate place".
* - If nothing is currently the responder, the "appropriate place" is the
* initiating event's `targetID`.
* - If something *is* already the responder, the "appropriate place" is the
* first common ancestor of the event target and the current `responderInst`.
* - Some negotiation happens: See the timing diagram below.
* - Scrolled views automatically become responder. The reasoning is that a
* platform scroll view that isn't built on top of the responder system has
* began scrolling, and the active responder must now be notified that the
* interaction is no longer locked to it - the system has taken over.
*
* - Responder being released:
* As soon as no more touches that *started* inside of descendants of the
* *current* responderInst, an `onResponderRelease` event is dispatched to the
* current responder, and the responder lock is released.
*
* TODO:
* - on "end", a callback hook for `onResponderEndShouldRemainResponder` that
* determines if the responder lock should remain.
* - If a view shouldn't "remain" the responder, any active touches should by
* default be considered "dead" and do not influence future negotiations or
* bubble paths. It should be as if those touches do not exist.
* -- For multitouch: Usually a translate-z will choose to "remain" responder
* after one out of many touches ended. For translate-y, usually the view
* doesn't wish to "remain" responder after one of many touches end.
* - Consider building this on top of a `stopPropagation` model similar to
* `W3C` events.
* - Ensure that `onResponderTerminate` is called on touch cancels, whether or
* not `onResponderTerminationRequest` returns `true` or `false`.
*
*/
/* Negotiation Performed
+-----------------------+
/ \
Process low level events to + Current Responder + wantsResponderID
determine who to perform negot-| (if any exists at all) |
iation/transition | Otherwise just pass through|
-------------------------------+----------------------------+------------------+
Bubble to find first ID | |
to return true:wantsResponderID| |
| |
+-------------+ | |
| onTouchStart| | |
+------+------+ none | |
| return| |
+-----------v-------------+true| +------------------------+ |
|onStartShouldSetResponder|----->|onResponderStart (cur) |<-----------+
+-----------+-------------+ | +------------------------+ | |
| | | +--------+-------+
| returned true for| false:REJECT +-------->|onResponderReject
| wantsResponderID | | | +----------------+
| (now attempt | +------------------+-----+ |
| handoff) | | onResponder | |
+------------------->| TerminationRequest| |
| +------------------+-----+ |
| | | +----------------+
| true:GRANT +-------->|onResponderGrant|
| | +--------+-------+
| +------------------------+ | |
| | onResponderTerminate |<-----------+
| +------------------+-----+ |
| | | +----------------+
| +-------->|onResponderStart|
| | +----------------+
Bubble to find first ID | |
to return true:wantsResponderID| |
| |
+-------------+ | |
| onTouchMove | | |
+------+------+ none | |
| return| |
+-----------v-------------+true| +------------------------+ |
|onMoveShouldSetResponder |----->|onResponderMove (cur) |<-----------+
+-----------+-------------+ | +------------------------+ | |
| | | +--------+-------+
| returned true for| false:REJECT +-------->|onResponderRejec|
| wantsResponderID | | | +----------------+
| (now attempt | +------------------+-----+ |
| handoff) | | onResponder | |
+------------------->| TerminationRequest| |
| +------------------+-----+ |
| | | +----------------+
| true:GRANT +-------->|onResponderGrant|
| | +--------+-------+
| +------------------------+ | |
| | onResponderTerminate |<-----------+
| +------------------+-----+ |
| | | +----------------+
| +-------->|onResponderMove |
| | +----------------+
| |
| |
Some active touch started| |
inside current responder | +------------------------+ |
+------------------------->| onResponderEnd | |
| | +------------------------+ |
+---+---------+ | |
| onTouchEnd | | |
+---+---------+ | |
| | +------------------------+ |
+------------------------->| onResponderEnd | |
No active touches started| +-----------+------------+ |
inside current responder | | |
| v |
| +------------------------+ |
| | onResponderRelease | |
| +------------------------+ |
| |
+ + */
/**
* A note about event ordering in the `EventPluginHub`.
*
* Suppose plugins are injected in the following order:
*
* `[R, S, C]`
*
* To help illustrate the example, assume `S` is `SimpleEventPlugin` (for
* `onClick` etc) and `R` is `ResponderEventPlugin`.
*
* "Deferred-Dispatched Events":
*
* - The current event plugin system will traverse the list of injected plugins,
* in order, and extract events by collecting the plugin's return value of
* `extractEvents()`.
* - These events that are returned from `extractEvents` are "deferred
* dispatched events".
* - When returned from `extractEvents`, deferred-dispatched events contain an
* "accumulation" of deferred dispatches.
* - These deferred dispatches are accumulated/collected before they are
* returned, but processed at a later time by the `EventPluginHub` (hence the
* name deferred).
*
* In the process of returning their deferred-dispatched events, event plugins
* themselves can dispatch events on-demand without returning them from
* `extractEvents`. Plugins might want to do this, so that they can use event
* dispatching as a tool that helps them decide which events should be extracted
* in the first place.
*
* "On-Demand-Dispatched Events":
*
* - On-demand-dispatched events are not returned from `extractEvents`.
* - On-demand-dispatched events are dispatched during the process of returning
* the deferred-dispatched events.
* - They should not have side effects.
* - They should be avoided, and/or eventually be replaced with another
* abstraction that allows event plugins to perform multiple "rounds" of event
* extraction.
*
* Therefore, the sequence of event dispatches becomes:
*
* - `R`s on-demand events (if any) (dispatched by `R` on-demand)
* - `S`s on-demand events (if any) (dispatched by `S` on-demand)
* - `C`s on-demand events (if any) (dispatched by `C` on-demand)
* - `R`s extracted events (if any) (dispatched by `EventPluginHub`)
* - `S`s extracted events (if any) (dispatched by `EventPluginHub`)
* - `C`s extracted events (if any) (dispatched by `EventPluginHub`)
*
* In the case of `ResponderEventPlugin`: If the `startShouldSetResponder`
* on-demand dispatch returns `true` (and some other details are satisfied) the
* `onResponderGrant` deferred dispatched event is returned from
* `extractEvents`. The sequence of dispatch executions in this case
* will appear as follows:
*
* - `startShouldSetResponder` (`ResponderEventPlugin` dispatches on-demand)
* - `touchStartCapture` (`EventPluginHub` dispatches as usual)
* - `touchStart` (`EventPluginHub` dispatches as usual)
* - `responderGrant/Reject` (`EventPluginHub` dispatches as usual)
*/
function setResponderAndExtractTransfer(
topLevelType,
targetInst,
nativeEvent,
nativeEventTarget
) {
var shouldSetEventType =
isStartish(topLevelType) ? eventTypes.startShouldSetResponder :
isMoveish(topLevelType) ? eventTypes.moveShouldSetResponder :
topLevelType === EventConstants.topLevelTypes.topSelectionChange ?
eventTypes.selectionChangeShouldSetResponder :
eventTypes.scrollShouldSetResponder;
// TODO: stop one short of the current responder.
var bubbleShouldSetFrom = !responderInst ?
targetInst :
EventPluginUtils.getLowestCommonAncestor(responderInst, targetInst);
// When capturing/bubbling the "shouldSet" event, we want to skip the target
// (deepest ID) if it happens to be the current responder. The reasoning:
// It's strange to get an `onMoveShouldSetResponder` when you're *already*
// the responder.
var skipOverBubbleShouldSetFrom = bubbleShouldSetFrom === responderInst;
var shouldSetEvent = ResponderSyntheticEvent.getPooled(
shouldSetEventType,
bubbleShouldSetFrom,
nativeEvent,
nativeEventTarget
);
shouldSetEvent.touchHistory = ResponderTouchHistoryStore.touchHistory;
if (skipOverBubbleShouldSetFrom) {
EventPropagators.accumulateTwoPhaseDispatchesSkipTarget(shouldSetEvent);
} else {
EventPropagators.accumulateTwoPhaseDispatches(shouldSetEvent);
}
var wantsResponderInst = executeDispatchesInOrderStopAtTrue(shouldSetEvent);
if (!shouldSetEvent.isPersistent()) {
shouldSetEvent.constructor.release(shouldSetEvent);
}
if (!wantsResponderInst || wantsResponderInst === responderInst) {
return null;
}
var extracted;
var grantEvent = ResponderSyntheticEvent.getPooled(
eventTypes.responderGrant,
wantsResponderInst,
nativeEvent,
nativeEventTarget
);
grantEvent.touchHistory = ResponderTouchHistoryStore.touchHistory;
EventPropagators.accumulateDirectDispatches(grantEvent);
var blockHostResponder = executeDirectDispatch(grantEvent) === true;
if (responderInst) {
var terminationRequestEvent = ResponderSyntheticEvent.getPooled(
eventTypes.responderTerminationRequest,
responderInst,
nativeEvent,
nativeEventTarget
);
terminationRequestEvent.touchHistory = ResponderTouchHistoryStore.touchHistory;
EventPropagators.accumulateDirectDispatches(terminationRequestEvent);
var shouldSwitch = !hasDispatches(terminationRequestEvent) ||
executeDirectDispatch(terminationRequestEvent);
if (!terminationRequestEvent.isPersistent()) {
terminationRequestEvent.constructor.release(terminationRequestEvent);
}
if (shouldSwitch) {
var terminateEvent = ResponderSyntheticEvent.getPooled(
eventTypes.responderTerminate,
responderInst,
nativeEvent,
nativeEventTarget
);
terminateEvent.touchHistory = ResponderTouchHistoryStore.touchHistory;
EventPropagators.accumulateDirectDispatches(terminateEvent);
extracted = accumulate(extracted, [grantEvent, terminateEvent]);
changeResponder(wantsResponderInst, blockHostResponder);
} else {
var rejectEvent = ResponderSyntheticEvent.getPooled(
eventTypes.responderReject,
wantsResponderInst,
nativeEvent,
nativeEventTarget
);
rejectEvent.touchHistory = ResponderTouchHistoryStore.touchHistory;
EventPropagators.accumulateDirectDispatches(rejectEvent);
extracted = accumulate(extracted, rejectEvent);
}
} else {
extracted = accumulate(extracted, grantEvent);
changeResponder(wantsResponderInst, blockHostResponder);
}
return extracted;
}
/**
* A transfer is a negotiation between a currently set responder and the next
* element to claim responder status. Any start event could trigger a transfer
* of responderInst. Any move event could trigger a transfer.
*
* @param {string} topLevelType Record from `EventConstants`.
* @return {boolean} True if a transfer of responder could possibly occur.
*/
function canTriggerTransfer(topLevelType, topLevelInst, nativeEvent) {
return topLevelInst && (
// responderIgnoreScroll: We are trying to migrate away from specifically
// tracking native scroll events here and responderIgnoreScroll indicates we
// will send topTouchCancel to handle canceling touch events instead
(topLevelType === EventConstants.topLevelTypes.topScroll &&
!nativeEvent.responderIgnoreScroll) ||
(trackedTouchCount > 0 &&
topLevelType === EventConstants.topLevelTypes.topSelectionChange) ||
isStartish(topLevelType) ||
isMoveish(topLevelType)
);
}
/**
* Returns whether or not this touch end event makes it such that there are no
* longer any touches that started inside of the current `responderInst`.
*
* @param {NativeEvent} nativeEvent Native touch end event.
* @return {boolean} Whether or not this touch end event ends the responder.
*/
function noResponderTouches(nativeEvent) {
var touches = nativeEvent.touches;
if (!touches || touches.length === 0) {
return true;
}
for (var i = 0; i < touches.length; i++) {
var activeTouch = touches[i];
var target = activeTouch.target;
if (target !== null && target !== undefined && target !== 0) {
// Is the original touch location inside of the current responder?
var targetInst = EventPluginUtils.getInstanceFromNode(target);
if (EventPluginUtils.isAncestor(responderInst, targetInst)) {
return false;
}
}
}
return true;
}
var ResponderEventPlugin = {
/* For unit testing only */
_getResponderID: function() {
return responderInst ? responderInst._rootNodeID : null;
},
eventTypes: eventTypes,
/**
* We must be resilient to `targetInst` being `null` on `touchMove` or
* `touchEnd`. On certain platforms, this means that a native scroll has
* assumed control and the original touch targets are destroyed.
*/
extractEvents: function(
topLevelType,
targetInst,
nativeEvent,
nativeEventTarget
) {
if (isStartish(topLevelType)) {
trackedTouchCount += 1;
} else if (isEndish(topLevelType)) {
trackedTouchCount -= 1;
invariant(
trackedTouchCount >= 0,
'Ended a touch event which was not counted in trackedTouchCount.'
);
}
ResponderTouchHistoryStore.recordTouchTrack(topLevelType, nativeEvent, nativeEventTarget);
var extracted = canTriggerTransfer(topLevelType, targetInst, nativeEvent) ?
setResponderAndExtractTransfer(
topLevelType,
targetInst,
nativeEvent,
nativeEventTarget) :
null;
// Responder may or may not have transferred on a new touch start/move.
// Regardless, whoever is the responder after any potential transfer, we
// direct all touch start/move/ends to them in the form of
// `onResponderMove/Start/End`. These will be called for *every* additional
// finger that move/start/end, dispatched directly to whoever is the
// current responder at that moment, until the responder is "released".
//
// These multiple individual change touch events are are always bookended
// by `onResponderGrant`, and one of
// (`onResponderRelease/onResponderTerminate`).
var isResponderTouchStart = responderInst && isStartish(topLevelType);
var isResponderTouchMove = responderInst && isMoveish(topLevelType);
var isResponderTouchEnd = responderInst && isEndish(topLevelType);
var incrementalTouch =
isResponderTouchStart ? eventTypes.responderStart :
isResponderTouchMove ? eventTypes.responderMove :
isResponderTouchEnd ? eventTypes.responderEnd :
null;
if (incrementalTouch) {
var gesture =
ResponderSyntheticEvent.getPooled(
incrementalTouch,
responderInst,
nativeEvent,
nativeEventTarget
);
gesture.touchHistory = ResponderTouchHistoryStore.touchHistory;
EventPropagators.accumulateDirectDispatches(gesture);
extracted = accumulate(extracted, gesture);
}
var isResponderTerminate =
responderInst &&
topLevelType === EventConstants.topLevelTypes.topTouchCancel;
var isResponderRelease =
responderInst &&
!isResponderTerminate &&
isEndish(topLevelType) &&
noResponderTouches(nativeEvent);
var finalTouch =
isResponderTerminate ? eventTypes.responderTerminate :
isResponderRelease ? eventTypes.responderRelease :
null;
if (finalTouch) {
var finalEvent = ResponderSyntheticEvent.getPooled(
finalTouch, responderInst, nativeEvent, nativeEventTarget
);
finalEvent.touchHistory = ResponderTouchHistoryStore.touchHistory;
EventPropagators.accumulateDirectDispatches(finalEvent);
extracted = accumulate(extracted, finalEvent);
changeResponder(null);
}
var numberActiveTouches =
ResponderTouchHistoryStore.touchHistory.numberActiveTouches;
if (ResponderEventPlugin.GlobalInteractionHandler &&
numberActiveTouches !== previousActiveTouches) {
ResponderEventPlugin.GlobalInteractionHandler.onChange(
numberActiveTouches
);
}
previousActiveTouches = numberActiveTouches;
return extracted;
},
GlobalResponderHandler: null,
GlobalInteractionHandler: null,
injection: {
/**
* @param {{onChange: (ReactID, ReactID) => void} GlobalResponderHandler
* Object that handles any change in responder. Use this to inject
* integration with an existing touch handling system etc.
*/
injectGlobalResponderHandler: function(GlobalResponderHandler) {
ResponderEventPlugin.GlobalResponderHandler = GlobalResponderHandler;
},
/**
* @param {{onChange: (numberActiveTouches) => void} GlobalInteractionHandler
* Object that handles any change in the number of active touches.
*/
injectGlobalInteractionHandler: function(GlobalInteractionHandler) {
ResponderEventPlugin.GlobalInteractionHandler = GlobalInteractionHandler;
},
},
};
module.exports = ResponderEventPlugin;
| Java |
/*
* BridJ - Dynamic and blazing-fast native interop for Java.
* http://bridj.googlecode.com/
*
* Copyright (c) 2010-2015, Olivier Chafik (http://ochafik.com/)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * 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 Olivier Chafik 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 OLIVIER CHAFIK 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 REGENTS AND 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.
*/
package org.bridj;
import static org.bridj.Pointer.allocate;
import static org.bridj.Pointer.allocateArray;
import java.util.AbstractList;
import java.util.Collection;
import java.util.RandomAccess;
import org.bridj.Pointer.ListType;
/**
* TODO : smart rewrite by chunks for removeAll and retainAll !
*
* @author ochafik
* @param <T> component type
*/
class DefaultNativeList<T> extends AbstractList<T> implements NativeList<T>, RandomAccess {
/*
* For optimization purposes, please look at AbstractList.java and AbstractCollection.java :
* http://www.koders.com/java/fidCFCB47A1819AB345234CC04B6A1EA7554C2C17C0.aspx?s=iso
* http://www.koders.com/java/fidA34BB0789922998CD34313EE49D61B06851A4397.aspx?s=iso
*
* We've reimplemented more methods than needed on purpose, for performance reasons (mainly using a native-optimized indexOf, that uses memmem and avoids deserializing too many elements)
*/
final ListType type;
final PointerIO<T> io;
volatile Pointer<T> pointer;
volatile long size;
public Pointer<?> getPointer() {
return pointer;
}
/**
* Create a native list that uses the provided storage and implementation
* strategy
*
* @param pointer
* @param type Implementation type
*/
DefaultNativeList(Pointer<T> pointer, ListType type) {
if (pointer == null || type == null) {
throw new IllegalArgumentException("Cannot build a " + getClass().getSimpleName() + " with " + pointer + " and " + type);
}
this.io = pointer.getIO("Cannot create a list out of untyped pointer " + pointer);
this.type = type;
this.size = pointer.getValidElements();
this.pointer = pointer;
}
protected void checkModifiable() {
if (type == ListType.Unmodifiable) {
throw new UnsupportedOperationException("This list is unmodifiable");
}
}
protected int safelyCastLongToInt(long i, String content) {
if (i > Integer.MAX_VALUE) {
throw new RuntimeException(content + " is bigger than Java int's maximum value : " + i);
}
return (int) i;
}
@Override
public int size() {
return safelyCastLongToInt(size, "Size of the native list");
}
@Override
public void clear() {
checkModifiable();
size = 0;
}
@Override
public T get(int i) {
if (i >= size || i < 0) {
throw new IndexOutOfBoundsException("Invalid index : " + i + " (list has size " + size + ")");
}
return pointer.get(i);
}
@Override
public T set(int i, T e) {
checkModifiable();
if (i >= size || i < 0) {
throw new IndexOutOfBoundsException("Invalid index : " + i + " (list has size " + size + ")");
}
T old = pointer.get(i);
pointer.set(i, e);
return old;
}
@SuppressWarnings("deprecation")
void add(long i, T e) {
checkModifiable();
if (i > size || i < 0) {
throw new IndexOutOfBoundsException("Invalid index : " + i + " (list has size " + size + ")");
}
requireSize(size + 1);
if (i < size) {
pointer.moveBytesAtOffsetTo(i, pointer, i + 1, size - i);
}
pointer.set(i, e);
size++;
}
@Override
public void add(int i, T e) {
add((long) i, e);
}
protected void requireSize(long newSize) {
if (newSize > pointer.getValidElements()) {
switch (type) {
case Dynamic:
long nextSize = newSize < 5 ? newSize + 1 : (long) (newSize * 1.6);
Pointer<T> newPointer = allocateArray(io, nextSize);
pointer.copyTo(newPointer);
pointer = newPointer;
break;
case FixedCapacity:
throw new UnsupportedOperationException("This list has a fixed capacity, cannot grow its storage");
case Unmodifiable:
// should not happen !
checkModifiable();
}
}
}
@SuppressWarnings("deprecation")
T remove(long i) {
checkModifiable();
if (i >= size || i < 0) {
throw new IndexOutOfBoundsException("Invalid index : " + i + " (list has size " + size + ")");
}
T old = pointer.get(i);
long targetSize = io.getTargetSize();
pointer.moveBytesAtOffsetTo((i + 1) * targetSize, pointer, i * targetSize, targetSize);
size--;
return old;
}
@Override
public T remove(int i) {
return remove((long) i);
}
@Override
public boolean remove(Object o) {
checkModifiable();
long i = indexOf(o, true, 0);
if (i < 0) {
return false;
}
remove(i);
return true;
}
@SuppressWarnings("unchecked")
long indexOf(Object o, boolean last, int offset) {
Pointer<T> pointer = this.pointer;
assert offset >= 0 && (last || offset > 0);
if (offset > 0) {
pointer = pointer.next(offset);
}
Pointer<T> needle = allocate(io);
needle.set((T) o);
Pointer<T> occurrence = last ? pointer.findLast(needle) : pointer.find(needle);
if (occurrence == null) {
return -1;
}
return occurrence.getPeer() - pointer.getPeer();
}
@Override
public int indexOf(Object o) {
return safelyCastLongToInt(indexOf(o, false, 0), "Index of the object");
}
@Override
public int lastIndexOf(Object o) {
return safelyCastLongToInt(indexOf(o, true, 0), "Last index of the object");
}
@Override
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
@Override
public boolean addAll(int i, Collection<? extends T> clctn) {
if (i >= 0 && i < size) {
requireSize(size + clctn.size());
}
return super.addAll(i, clctn);
}
@Override
public Object[] toArray() {
return pointer.validElements(size).toArray();
}
@SuppressWarnings("hiding")
@Override
public <T> T[] toArray(T[] ts) {
return pointer.validElements(size).toArray(ts);
}
}
| Java |
//
// MCOMessageHeader+Private.h
// mailcore2
//
// Created by DINH Viêt Hoà on 3/11/13.
// Copyright (c) 2013 MailCore. All rights reserved.
//
#ifndef __MAILCORE_MCOMESSAGEHEADER_PRIVATE_H_
#define __MAILCORE_MCOMESSAGEHEADER_PRIVATE_H_
#ifdef __cplusplus
namespace mailcore {
class MessageHeader;
}
@interface MCOMessageHeader (Private)
- (id) initWithMCMessageHeader:(mailcore::MessageHeader *)header;
+ (MCOAddress *) addressWithMCMessageHeader:(mailcore::MessageHeader *)header;
@end
#endif
#endif
| Java |
/*-
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Chris Torek.
*
* Copyright (c) 2011 The FreeBSD Foundation
* All rights reserved.
* Portions of this software were developed by David Chisnall
* under sponsorship from the FreeBSD Foundation.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University 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 REGENTS 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 REGENTS 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.
*/
#if 0
#if defined(LIBC_SCCS) && !defined(lint)
static char sccsid[] = "@(#)vfprintf.c 8.1 (Berkeley) 6/4/93";
#endif /* LIBC_SCCS and not lint */
#endif
#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");
/*
* Actual wprintf innards.
*
* Avoid making gratuitous changes to this source file; it should be kept
* as close as possible to vfprintf.c for ease of maintenance.
*/
#include "namespace.h"
#include <sys/types.h>
#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <locale.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
#include <wctype.h>
#include "un-namespace.h"
#include "libc_private.h"
#include "local.h"
#include "fvwrite.h"
#include "printflocal.h"
#include "xlocale_private.h"
static int __sprint(FILE *, struct __suio *, locale_t);
static int __sbprintf(FILE *, locale_t, const wchar_t *, va_list) __noinline;
static wint_t __xfputwc(wchar_t, FILE *, locale_t);
static wchar_t *__mbsconv(char *, int);
#define CHAR wchar_t
#include "printfcommon.h"
struct grouping_state {
wchar_t thousands_sep; /* locale-specific thousands separator */
const char *grouping; /* locale-specific numeric grouping rules */
int lead; /* sig figs before decimal or group sep */
int nseps; /* number of group separators with ' */
int nrepeats; /* number of repeats of the last group */
};
static const mbstate_t initial_mbs;
static inline wchar_t
get_decpt(locale_t locale)
{
mbstate_t mbs;
wchar_t decpt;
int nconv;
mbs = initial_mbs;
nconv = mbrtowc(&decpt, localeconv_l(locale)->decimal_point, MB_CUR_MAX, &mbs);
if (nconv == (size_t)-1 || nconv == (size_t)-2)
decpt = '.'; /* failsafe */
return (decpt);
}
static inline wchar_t
get_thousep(locale_t locale)
{
mbstate_t mbs;
wchar_t thousep;
int nconv;
mbs = initial_mbs;
nconv = mbrtowc(&thousep, localeconv_l(locale)->thousands_sep,
MB_CUR_MAX, &mbs);
if (nconv == (size_t)-1 || nconv == (size_t)-2)
thousep = '\0'; /* failsafe */
return (thousep);
}
/*
* Initialize the thousands' grouping state in preparation to print a
* number with ndigits digits. This routine returns the total number
* of wide characters that will be printed.
*/
static int
grouping_init(struct grouping_state *gs, int ndigits, locale_t locale)
{
gs->grouping = localeconv_l(locale)->grouping;
gs->thousands_sep = get_thousep(locale);
gs->nseps = gs->nrepeats = 0;
gs->lead = ndigits;
while (*gs->grouping != CHAR_MAX) {
if (gs->lead <= *gs->grouping)
break;
gs->lead -= *gs->grouping;
if (*(gs->grouping+1)) {
gs->nseps++;
gs->grouping++;
} else
gs->nrepeats++;
}
return (gs->nseps + gs->nrepeats);
}
/*
* Print a number with thousands' separators.
*/
static int
grouping_print(struct grouping_state *gs, struct io_state *iop,
const CHAR *cp, const CHAR *ep, locale_t locale)
{
const CHAR *cp0 = cp;
if (io_printandpad(iop, cp, ep, gs->lead, zeroes, locale))
return (-1);
cp += gs->lead;
while (gs->nseps > 0 || gs->nrepeats > 0) {
if (gs->nrepeats > 0)
gs->nrepeats--;
else {
gs->grouping--;
gs->nseps--;
}
if (io_print(iop, &gs->thousands_sep, 1, locale))
return (-1);
if (io_printandpad(iop, cp, ep, *gs->grouping, zeroes, locale))
return (-1);
cp += *gs->grouping;
}
if (cp > ep)
cp = ep;
return (cp - cp0);
}
/*
* Flush out all the vectors defined by the given uio,
* then reset it so that it can be reused.
*
* XXX The fact that we do this a character at a time and convert to a
* multibyte character sequence even if the destination is a wide
* string eclipses the benefits of buffering.
*/
static int
__sprint(FILE *fp, struct __suio *uio, locale_t locale)
{
struct __siov *iov;
wchar_t *p;
int i, len;
iov = uio->uio_iov;
for (; uio->uio_resid != 0; uio->uio_resid -= len, iov++) {
p = (wchar_t *)iov->iov_base;
len = iov->iov_len;
for (i = 0; i < len; i++) {
if (__xfputwc(p[i], fp, locale) == WEOF)
return (-1);
}
}
uio->uio_iovcnt = 0;
return (0);
}
/*
* Helper function for `fprintf to unbuffered unix file': creates a
* temporary buffer. We only work on write-only files; this avoids
* worries about ungetc buffers and so forth.
*/
static int
__sbprintf(FILE *fp, locale_t locale, const wchar_t *fmt, va_list ap)
{
int ret;
FILE fake;
unsigned char buf[BUFSIZ];
/* XXX This is probably not needed. */
if (prepwrite(fp) != 0)
return (EOF);
/* copy the important variables */
fake._flags = fp->_flags & ~__SNBF;
fake._file = fp->_file;
fake._cookie = fp->_cookie;
fake._write = fp->_write;
fake._orientation = fp->_orientation;
fake._mbstate = fp->_mbstate;
/* set up the buffer */
fake._bf._base = fake._p = buf;
fake._bf._size = fake._w = sizeof(buf);
fake._lbfsize = 0; /* not actually used, but Just In Case */
/* do the work, then copy any error status */
ret = __vfwprintf(&fake, locale, fmt, ap);
if (ret >= 0 && __fflush(&fake))
ret = WEOF;
if (fake._flags & __SERR)
fp->_flags |= __SERR;
return (ret);
}
/*
* Like __fputwc, but handles fake string (__SSTR) files properly.
* File must already be locked.
*/
static wint_t
__xfputwc(wchar_t wc, FILE *fp, locale_t locale)
{
mbstate_t mbs;
char buf[MB_LEN_MAX];
struct __suio uio;
struct __siov iov;
size_t len;
if ((fp->_flags & __SSTR) == 0)
return (__fputwc(wc, fp, locale));
mbs = initial_mbs;
if ((len = wcrtomb(buf, wc, &mbs)) == (size_t)-1) {
fp->_flags |= __SERR;
return (WEOF);
}
uio.uio_iov = &iov;
uio.uio_resid = len;
uio.uio_iovcnt = 1;
iov.iov_base = buf;
iov.iov_len = len;
return (__sfvwrite(fp, &uio) != EOF ? (wint_t)wc : WEOF);
}
/*
* Convert a multibyte character string argument for the %s format to a wide
* string representation. ``prec'' specifies the maximum number of bytes
* to output. If ``prec'' is greater than or equal to zero, we can't assume
* that the multibyte char. string ends in a null character.
*/
static wchar_t *
__mbsconv(char *mbsarg, int prec)
{
mbstate_t mbs;
wchar_t *convbuf, *wcp;
const char *p;
size_t insize, nchars, nconv;
if (mbsarg == NULL)
return (NULL);
/*
* Supplied argument is a multibyte string; convert it to wide
* characters first.
*/
if (prec >= 0) {
/*
* String is not guaranteed to be NUL-terminated. Find the
* number of characters to print.
*/
p = mbsarg;
insize = nchars = nconv = 0;
mbs = initial_mbs;
while (nchars != (size_t)prec) {
nconv = mbrlen(p, MB_CUR_MAX, &mbs);
if (nconv == 0 || nconv == (size_t)-1 ||
nconv == (size_t)-2)
break;
p += nconv;
nchars++;
insize += nconv;
}
if (nconv == (size_t)-1 || nconv == (size_t)-2)
return (NULL);
} else {
insize = strlen(mbsarg);
nconv = 0;
}
/*
* Allocate buffer for the result and perform the conversion,
* converting at most `size' bytes of the input multibyte string to
* wide characters for printing.
*/
convbuf = malloc((insize + 1) * sizeof(*convbuf));
if (convbuf == NULL)
return (NULL);
wcp = convbuf;
p = mbsarg;
mbs = initial_mbs;
while (insize != 0) {
nconv = mbrtowc(wcp, p, insize, &mbs);
if (nconv == 0 || nconv == (size_t)-1 || nconv == (size_t)-2)
break;
wcp++;
p += nconv;
insize -= nconv;
}
if (nconv == (size_t)-1 || nconv == (size_t)-2) {
free(convbuf);
return (NULL);
}
*wcp = L'\0';
return (convbuf);
}
/*
* MT-safe version
*/
int
vfwprintf_l(FILE * __restrict fp, locale_t locale,
const wchar_t * __restrict fmt0, va_list ap)
{
int ret;
FIX_LOCALE(locale);
FLOCKFILE(fp);
/* optimise fprintf(stderr) (and other unbuffered Unix files) */
if ((fp->_flags & (__SNBF|__SWR|__SRW)) == (__SNBF|__SWR) &&
fp->_file >= 0)
ret = __sbprintf(fp, locale, fmt0, ap);
else
ret = __vfwprintf(fp, locale, fmt0, ap);
FUNLOCKFILE(fp);
return (ret);
}
int
vfwprintf(FILE * __restrict fp, const wchar_t * __restrict fmt0, va_list ap)
{
return vfwprintf_l(fp, __get_locale(), fmt0, ap);
}
/*
* The size of the buffer we use as scratch space for integer
* conversions, among other things. We need enough space to
* write a uintmax_t in octal (plus one byte).
*/
#if UINTMAX_MAX <= UINT64_MAX
#define BUF 32
#else
#error "BUF must be large enough to format a uintmax_t"
#endif
/*
* Non-MT-safe version
*/
int
__vfwprintf(FILE *fp, locale_t locale, const wchar_t *fmt0, va_list ap)
{
wchar_t *fmt; /* format string */
wchar_t ch; /* character from fmt */
int n, n2; /* handy integer (short term usage) */
wchar_t *cp; /* handy char pointer (short term usage) */
int flags; /* flags as above */
int ret; /* return value accumulator */
int width; /* width from format (%8d), or 0 */
int prec; /* precision from format; <0 for N/A */
wchar_t sign; /* sign prefix (' ', '+', '-', or \0) */
struct grouping_state gs; /* thousands' grouping info */
#ifndef NO_FLOATING_POINT
/*
* We can decompose the printed representation of floating
* point numbers into several parts, some of which may be empty:
*
* [+|-| ] [0x|0X] MMM . NNN [e|E|p|P] [+|-] ZZ
* A B ---C--- D E F
*
* A: 'sign' holds this value if present; '\0' otherwise
* B: ox[1] holds the 'x' or 'X'; '\0' if not hexadecimal
* C: cp points to the string MMMNNN. Leading and trailing
* zeros are not in the string and must be added.
* D: expchar holds this character; '\0' if no exponent, e.g. %f
* F: at least two digits for decimal, at least one digit for hex
*/
wchar_t decimal_point; /* locale specific decimal point */
int signflag; /* true if float is negative */
union { /* floating point arguments %[aAeEfFgG] */
double dbl;
long double ldbl;
} fparg;
int expt; /* integer value of exponent */
char expchar; /* exponent character: [eEpP\0] */
char *dtoaend; /* pointer to end of converted digits */
int expsize; /* character count for expstr */
int ndig; /* actual number of digits returned by dtoa */
wchar_t expstr[MAXEXPDIG+2]; /* buffer for exponent string: e+ZZZ */
char *dtoaresult; /* buffer allocated by dtoa */
#endif
u_long ulval; /* integer arguments %[diouxX] */
uintmax_t ujval; /* %j, %ll, %q, %t, %z integers */
int base; /* base for [diouxX] conversion */
int dprec; /* a copy of prec if [diouxX], 0 otherwise */
int realsz; /* field size expanded by dprec, sign, etc */
int size; /* size of converted field or string */
int prsize; /* max size of printed field */
const char *xdigs; /* digits for [xX] conversion */
struct io_state io; /* I/O buffering state */
wchar_t buf[BUF]; /* buffer with space for digits of uintmax_t */
wchar_t ox[2]; /* space for 0x hex-prefix */
union arg *argtable; /* args, built due to positional arg */
union arg statargtable [STATIC_ARG_TBL_SIZE];
int nextarg; /* 1-based argument index */
va_list orgap; /* original argument pointer */
wchar_t *convbuf; /* multibyte to wide conversion result */
static const char xdigs_lower[16] = "0123456789abcdef";
static const char xdigs_upper[16] = "0123456789ABCDEF";
/* BEWARE, these `goto error' on error. */
#define PRINT(ptr, len) do { \
if (io_print(&io, (ptr), (len), locale)) \
goto error; \
} while (0)
#define PAD(howmany, with) { \
if (io_pad(&io, (howmany), (with), locale)) \
goto error; \
}
#define PRINTANDPAD(p, ep, len, with) { \
if (io_printandpad(&io, (p), (ep), (len), (with), locale)) \
goto error; \
}
#define FLUSH() { \
if (io_flush(&io, locale)) \
goto error; \
}
/*
* Get the argument indexed by nextarg. If the argument table is
* built, use it to get the argument. If its not, get the next
* argument (and arguments must be gotten sequentially).
*/
#define GETARG(type) \
((argtable != NULL) ? *((type*)(&argtable[nextarg++])) : \
(nextarg++, va_arg(ap, type)))
/*
* To extend shorts properly, we need both signed and unsigned
* argument extraction methods.
*/
#define SARG() \
(flags&LONGINT ? GETARG(long) : \
flags&SHORTINT ? (long)(short)GETARG(int) : \
flags&CHARINT ? (long)(signed char)GETARG(int) : \
(long)GETARG(int))
#define UARG() \
(flags&LONGINT ? GETARG(u_long) : \
flags&SHORTINT ? (u_long)(u_short)GETARG(int) : \
flags&CHARINT ? (u_long)(u_char)GETARG(int) : \
(u_long)GETARG(u_int))
#define INTMAX_SIZE (INTMAXT|SIZET|PTRDIFFT|LLONGINT)
#define SJARG() \
(flags&INTMAXT ? GETARG(intmax_t) : \
flags&SIZET ? (intmax_t)GETARG(ssize_t) : \
flags&PTRDIFFT ? (intmax_t)GETARG(ptrdiff_t) : \
(intmax_t)GETARG(long long))
#define UJARG() \
(flags&INTMAXT ? GETARG(uintmax_t) : \
flags&SIZET ? (uintmax_t)GETARG(size_t) : \
flags&PTRDIFFT ? (uintmax_t)GETARG(ptrdiff_t) : \
(uintmax_t)GETARG(unsigned long long))
/*
* Get * arguments, including the form *nn$. Preserve the nextarg
* that the argument can be gotten once the type is determined.
*/
#define GETASTER(val) \
n2 = 0; \
cp = fmt; \
while (is_digit(*cp)) { \
n2 = 10 * n2 + to_digit(*cp); \
cp++; \
} \
if (*cp == '$') { \
int hold = nextarg; \
if (argtable == NULL) { \
argtable = statargtable; \
if (__find_warguments (fmt0, orgap, &argtable)) { \
ret = EOF; \
goto error; \
} \
} \
nextarg = n2; \
val = GETARG (int); \
nextarg = hold; \
fmt = ++cp; \
} else { \
val = GETARG (int); \
}
/* sorry, fwprintf(read_only_file, L"") returns WEOF, not 0 */
if (prepwrite(fp) != 0) {
errno = EBADF;
return (EOF);
}
convbuf = NULL;
fmt = (wchar_t *)fmt0;
argtable = NULL;
nextarg = 1;
va_copy(orgap, ap);
io_init(&io, fp);
ret = 0;
#ifndef NO_FLOATING_POINT
decimal_point = get_decpt(locale);
#endif
/*
* Scan the format for conversions (`%' character).
*/
for (;;) {
for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
/* void */;
if ((n = fmt - cp) != 0) {
if ((unsigned)ret + n > INT_MAX) {
ret = EOF;
errno = EOVERFLOW;
goto error;
}
PRINT(cp, n);
ret += n;
}
if (ch == '\0')
goto done;
fmt++; /* skip over '%' */
flags = 0;
dprec = 0;
width = 0;
prec = -1;
gs.grouping = NULL;
sign = '\0';
ox[1] = '\0';
rflag: ch = *fmt++;
reswitch: switch (ch) {
case ' ':
/*-
* ``If the space and + flags both appear, the space
* flag will be ignored.''
* -- ANSI X3J11
*/
if (!sign)
sign = ' ';
goto rflag;
case '#':
flags |= ALT;
goto rflag;
case '*':
/*-
* ``A negative field width argument is taken as a
* - flag followed by a positive field width.''
* -- ANSI X3J11
* They don't exclude field widths read from args.
*/
GETASTER (width);
if (width >= 0)
goto rflag;
width = -width;
/* FALLTHROUGH */
case '-':
flags |= LADJUST;
goto rflag;
case '+':
sign = '+';
goto rflag;
case '\'':
flags |= GROUPING;
goto rflag;
case '.':
if ((ch = *fmt++) == '*') {
GETASTER (prec);
goto rflag;
}
prec = 0;
while (is_digit(ch)) {
prec = 10 * prec + to_digit(ch);
ch = *fmt++;
}
goto reswitch;
case '0':
/*-
* ``Note that 0 is taken as a flag, not as the
* beginning of a field width.''
* -- ANSI X3J11
*/
flags |= ZEROPAD;
goto rflag;
case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
n = 0;
do {
n = 10 * n + to_digit(ch);
ch = *fmt++;
} while (is_digit(ch));
if (ch == '$') {
nextarg = n;
if (argtable == NULL) {
argtable = statargtable;
if (__find_warguments (fmt0, orgap,
&argtable)) {
ret = EOF;
goto error;
}
}
goto rflag;
}
width = n;
goto reswitch;
#ifndef NO_FLOATING_POINT
case 'L':
flags |= LONGDBL;
goto rflag;
#endif
case 'h':
if (flags & SHORTINT) {
flags &= ~SHORTINT;
flags |= CHARINT;
} else
flags |= SHORTINT;
goto rflag;
case 'j':
flags |= INTMAXT;
goto rflag;
case 'l':
if (flags & LONGINT) {
flags &= ~LONGINT;
flags |= LLONGINT;
} else
flags |= LONGINT;
goto rflag;
case 'q':
flags |= LLONGINT; /* not necessarily */
goto rflag;
case 't':
flags |= PTRDIFFT;
goto rflag;
case 'z':
flags |= SIZET;
goto rflag;
case 'C':
flags |= LONGINT;
/*FALLTHROUGH*/
case 'c':
if (flags & LONGINT)
*(cp = buf) = (wchar_t)GETARG(wint_t);
else
*(cp = buf) = (wchar_t)btowc(GETARG(int));
size = 1;
sign = '\0';
break;
case 'D':
flags |= LONGINT;
/*FALLTHROUGH*/
case 'd':
case 'i':
if (flags & INTMAX_SIZE) {
ujval = SJARG();
if ((intmax_t)ujval < 0) {
ujval = -ujval;
sign = '-';
}
} else {
ulval = SARG();
if ((long)ulval < 0) {
ulval = -ulval;
sign = '-';
}
}
base = 10;
goto number;
#ifndef NO_FLOATING_POINT
case 'a':
case 'A':
if (ch == 'a') {
ox[1] = 'x';
xdigs = xdigs_lower;
expchar = 'p';
} else {
ox[1] = 'X';
xdigs = xdigs_upper;
expchar = 'P';
}
if (prec >= 0)
prec++;
if (flags & LONGDBL) {
fparg.ldbl = GETARG(long double);
dtoaresult =
__hldtoa(fparg.ldbl, xdigs, prec,
&expt, &signflag, &dtoaend);
} else {
fparg.dbl = GETARG(double);
dtoaresult =
__hdtoa(fparg.dbl, xdigs, prec,
&expt, &signflag, &dtoaend);
}
if (prec < 0)
prec = dtoaend - dtoaresult;
if (expt == INT_MAX)
ox[1] = '\0';
if (convbuf != NULL)
free(convbuf);
ndig = dtoaend - dtoaresult;
cp = convbuf = __mbsconv(dtoaresult, -1);
freedtoa(dtoaresult);
goto fp_common;
case 'e':
case 'E':
expchar = ch;
if (prec < 0) /* account for digit before decpt */
prec = DEFPREC + 1;
else
prec++;
goto fp_begin;
case 'f':
case 'F':
expchar = '\0';
goto fp_begin;
case 'g':
case 'G':
expchar = ch - ('g' - 'e');
if (prec == 0)
prec = 1;
fp_begin:
if (prec < 0)
prec = DEFPREC;
if (convbuf != NULL)
free(convbuf);
if (flags & LONGDBL) {
fparg.ldbl = GETARG(long double);
dtoaresult =
__ldtoa(&fparg.ldbl, expchar ? 2 : 3, prec,
&expt, &signflag, &dtoaend);
} else {
fparg.dbl = GETARG(double);
dtoaresult =
dtoa(fparg.dbl, expchar ? 2 : 3, prec,
&expt, &signflag, &dtoaend);
if (expt == 9999)
expt = INT_MAX;
}
ndig = dtoaend - dtoaresult;
cp = convbuf = __mbsconv(dtoaresult, -1);
freedtoa(dtoaresult);
fp_common:
if (signflag)
sign = '-';
if (expt == INT_MAX) { /* inf or nan */
if (*cp == 'N') {
cp = (ch >= 'a') ? L"nan" : L"NAN";
sign = '\0';
} else
cp = (ch >= 'a') ? L"inf" : L"INF";
size = 3;
flags &= ~ZEROPAD;
break;
}
flags |= FPT;
if (ch == 'g' || ch == 'G') {
if (expt > -4 && expt <= prec) {
/* Make %[gG] smell like %[fF] */
expchar = '\0';
if (flags & ALT)
prec -= expt;
else
prec = ndig - expt;
if (prec < 0)
prec = 0;
} else {
/*
* Make %[gG] smell like %[eE], but
* trim trailing zeroes if no # flag.
*/
if (!(flags & ALT))
prec = ndig;
}
}
if (expchar) {
expsize = exponent(expstr, expt - 1, expchar);
size = expsize + prec;
if (prec > 1 || flags & ALT)
++size;
} else {
/* space for digits before decimal point */
if (expt > 0)
size = expt;
else /* "0" */
size = 1;
/* space for decimal pt and following digits */
if (prec || flags & ALT)
size += prec + 1;
if ((flags & GROUPING) && expt > 0)
size += grouping_init(&gs, expt, locale);
}
break;
#endif /* !NO_FLOATING_POINT */
case 'n':
/*
* Assignment-like behavior is specified if the
* value overflows or is otherwise unrepresentable.
* C99 says to use `signed char' for %hhn conversions.
*/
if (flags & LLONGINT)
*GETARG(long long *) = ret;
else if (flags & SIZET)
*GETARG(ssize_t *) = (ssize_t)ret;
else if (flags & PTRDIFFT)
*GETARG(ptrdiff_t *) = ret;
else if (flags & INTMAXT)
*GETARG(intmax_t *) = ret;
else if (flags & LONGINT)
*GETARG(long *) = ret;
else if (flags & SHORTINT)
*GETARG(short *) = ret;
else if (flags & CHARINT)
*GETARG(signed char *) = ret;
else
*GETARG(int *) = ret;
continue; /* no output */
case 'O':
flags |= LONGINT;
/*FALLTHROUGH*/
case 'o':
if (flags & INTMAX_SIZE)
ujval = UJARG();
else
ulval = UARG();
base = 8;
goto nosign;
case 'p':
/*-
* ``The argument shall be a pointer to void. The
* value of the pointer is converted to a sequence
* of printable characters, in an implementation-
* defined manner.''
* -- ANSI X3J11
*/
ujval = (uintmax_t)(uintptr_t)GETARG(void *);
base = 16;
xdigs = xdigs_lower;
flags = flags | INTMAXT;
ox[1] = 'x';
goto nosign;
case 'S':
flags |= LONGINT;
/*FALLTHROUGH*/
case 's':
if (flags & LONGINT) {
if ((cp = GETARG(wchar_t *)) == NULL)
cp = L"(null)";
} else {
char *mbp;
if (convbuf != NULL)
free(convbuf);
if ((mbp = GETARG(char *)) == NULL)
cp = L"(null)";
else {
convbuf = __mbsconv(mbp, prec);
if (convbuf == NULL) {
fp->_flags |= __SERR;
goto error;
}
cp = convbuf;
}
}
size = (prec >= 0) ? wcsnlen(cp, prec) : wcslen(cp);
sign = '\0';
break;
case 'U':
flags |= LONGINT;
/*FALLTHROUGH*/
case 'u':
if (flags & INTMAX_SIZE)
ujval = UJARG();
else
ulval = UARG();
base = 10;
goto nosign;
case 'X':
xdigs = xdigs_upper;
goto hex;
case 'x':
xdigs = xdigs_lower;
hex:
if (flags & INTMAX_SIZE)
ujval = UJARG();
else
ulval = UARG();
base = 16;
/* leading 0x/X only if non-zero */
if (flags & ALT &&
(flags & INTMAX_SIZE ? ujval != 0 : ulval != 0))
ox[1] = ch;
flags &= ~GROUPING;
/* unsigned conversions */
nosign: sign = '\0';
/*-
* ``... diouXx conversions ... if a precision is
* specified, the 0 flag will be ignored.''
* -- ANSI X3J11
*/
number: if ((dprec = prec) >= 0)
flags &= ~ZEROPAD;
/*-
* ``The result of converting a zero value with an
* explicit precision of zero is no characters.''
* -- ANSI X3J11
*
* ``The C Standard is clear enough as is. The call
* printf("%#.0o", 0) should print 0.''
* -- Defect Report #151
*/
cp = buf + BUF;
if (flags & INTMAX_SIZE) {
if (ujval != 0 || prec != 0 ||
(flags & ALT && base == 8))
cp = __ujtoa(ujval, cp, base,
flags & ALT, xdigs);
} else {
if (ulval != 0 || prec != 0 ||
(flags & ALT && base == 8))
cp = __ultoa(ulval, cp, base,
flags & ALT, xdigs);
}
size = buf + BUF - cp;
if (size > BUF) /* should never happen */
abort();
if ((flags & GROUPING) && size != 0)
size += grouping_init(&gs, size, locale);
break;
default: /* "%?" prints ?, unless ? is NUL */
if (ch == '\0')
goto done;
/* pretend it was %c with argument ch */
cp = buf;
*cp = ch;
size = 1;
sign = '\0';
break;
}
/*
* All reasonable formats wind up here. At this point, `cp'
* points to a string which (if not flags&LADJUST) should be
* padded out to `width' places. If flags&ZEROPAD, it should
* first be prefixed by any sign or other prefix; otherwise,
* it should be blank padded before the prefix is emitted.
* After any left-hand padding and prefixing, emit zeroes
* required by a decimal [diouxX] precision, then print the
* string proper, then emit zeroes required by any leftover
* floating precision; finally, if LADJUST, pad with blanks.
*
* Compute actual size, so we know how much to pad.
* size excludes decimal prec; realsz includes it.
*/
realsz = dprec > size ? dprec : size;
if (sign)
realsz++;
if (ox[1])
realsz += 2;
prsize = width > realsz ? width : realsz;
if ((unsigned)ret + prsize > INT_MAX) {
ret = EOF;
errno = EOVERFLOW;
goto error;
}
/* right-adjusting blank padding */
if ((flags & (LADJUST|ZEROPAD)) == 0)
PAD(width - realsz, blanks);
/* prefix */
if (sign)
PRINT(&sign, 1);
if (ox[1]) { /* ox[1] is either x, X, or \0 */
ox[0] = '0';
PRINT(ox, 2);
}
/* right-adjusting zero padding */
if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
PAD(width - realsz, zeroes);
/* the string or number proper */
#ifndef NO_FLOATING_POINT
if ((flags & FPT) == 0) {
#endif
/* leading zeroes from decimal precision */
PAD(dprec - size, zeroes);
if (gs.grouping) {
if (grouping_print(&gs, &io, cp, buf+BUF, locale) < 0)
goto error;
} else {
PRINT(cp, size);
}
#ifndef NO_FLOATING_POINT
} else { /* glue together f_p fragments */
if (!expchar) { /* %[fF] or sufficiently short %[gG] */
if (expt <= 0) {
PRINT(zeroes, 1);
if (prec || flags & ALT)
PRINT(&decimal_point, 1);
PAD(-expt, zeroes);
/* already handled initial 0's */
prec += expt;
} else {
if (gs.grouping) {
n = grouping_print(&gs, &io,
cp, convbuf + ndig, locale);
if (n < 0)
goto error;
cp += n;
} else {
PRINTANDPAD(cp, convbuf + ndig,
expt, zeroes);
cp += expt;
}
if (prec || flags & ALT)
PRINT(&decimal_point, 1);
}
PRINTANDPAD(cp, convbuf + ndig, prec, zeroes);
} else { /* %[eE] or sufficiently long %[gG] */
if (prec > 1 || flags & ALT) {
buf[0] = *cp++;
buf[1] = decimal_point;
PRINT(buf, 2);
PRINT(cp, ndig-1);
PAD(prec - ndig, zeroes);
} else /* XeYYY */
PRINT(cp, 1);
PRINT(expstr, expsize);
}
}
#endif
/* left-adjusting padding (always blank) */
if (flags & LADJUST)
PAD(width - realsz, blanks);
/* finally, adjust ret */
ret += prsize;
FLUSH(); /* copy out the I/O vectors */
}
done:
FLUSH();
error:
va_end(orgap);
if (convbuf != NULL)
free(convbuf);
if (__sferror(fp))
ret = EOF;
if ((argtable != NULL) && (argtable != statargtable))
free (argtable);
return (ret);
/* NOTREACHED */
}
| Java |
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns(
'popcorn_gallery.users.views',
url(r'^edit/$', 'edit', name='users_edit'),
url(r'^delete/$', 'delete_profile', name='users_delete'),
url(r'^(?P<username>[\w-]+)/$', 'profile', name='users_profile'),
)
| Java |
/*
* Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
* Copyright Siemens AG 2020
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/http.h>
#include <openssl/pem.h>
#include <openssl/x509v3.h>
#include <string.h>
#include "testutil.h"
static const ASN1_ITEM *x509_it = NULL;
static X509 *x509 = NULL;
#define RPATH "/path/result.crt"
typedef struct {
BIO *out;
char version;
int keep_alive;
} server_args;
/*-
* Pretty trivial HTTP mock server:
* For POST, copy request headers+body from mem BIO 'in' as response to 'out'.
* For GET, redirect to RPATH, else respond with 'rsp' of ASN1 type 'it'.
* Respond with HTTP version 1.'version' and 'keep_alive' (unless implicit).
*/
static int mock_http_server(BIO *in, BIO *out, char version, int keep_alive,
ASN1_VALUE *rsp, const ASN1_ITEM *it)
{
const char *req, *path;
long count = BIO_get_mem_data(in, (unsigned char **)&req);
const char *hdr = (char *)req;
int is_get = count >= 4 && strncmp(hdr, "GET ", 4) == 0;
int len;
/* first line should contain "<GET or POST> <path> HTTP/1.x" */
if (is_get)
hdr += 4;
else if (TEST_true(count >= 5 && strncmp(hdr, "POST ", 5) == 0))
hdr += 5;
else
return 0;
path = hdr;
hdr = strchr(hdr, ' ');
if (hdr == NULL)
return 0;
len = strlen("HTTP/1.");
if (!TEST_strn_eq(++hdr, "HTTP/1.", len))
return 0;
hdr += len;
/* check for HTTP version 1.0 .. 1.1 */
if (!TEST_char_le('0', *hdr) || !TEST_char_le(*hdr++, '1'))
return 0;
if (!TEST_char_eq(*hdr++, '\r') || !TEST_char_eq(*hdr++, '\n'))
return 0;
count -= (hdr - req);
if (count < 0 || out == NULL)
return 0;
if (strncmp(path, RPATH, strlen(RPATH)) != 0) {
if (!is_get)
return 0;
return BIO_printf(out, "HTTP/1.%c 301 Moved Permanently\r\n"
"Location: %s\r\n\r\n",
version, RPATH) > 0; /* same server */
}
if (BIO_printf(out, "HTTP/1.%c 200 OK\r\n", version) <= 0)
return 0;
if ((version == '0') == keep_alive) /* otherwise, default */
if (BIO_printf(out, "Connection: %s\r\n",
version == '0' ? "keep-alive" : "close") <= 0)
return 0;
if (is_get) { /* construct new header and body */
if ((len = ASN1_item_i2d(rsp, NULL, it)) <= 0)
return 0;
if (BIO_printf(out, "Content-Type: application/x-x509-ca-cert\r\n"
"Content-Length: %d\r\n\r\n", len) <= 0)
return 0;
return ASN1_item_i2d_bio(it, out, rsp);
} else {
len = strlen("Connection: ");
if (strncmp(hdr, "Connection: ", len) == 0) {
/* skip req Connection header */
hdr = strstr(hdr + len, "\r\n");
if (hdr == NULL)
return 0;
hdr += 2;
}
/* echo remaining request header and body */
return BIO_write(out, hdr, count) == count;
}
}
static long http_bio_cb_ex(BIO *bio, int oper, const char *argp, size_t len,
int cmd, long argl, int ret, size_t *processed)
{
server_args *args = (server_args *)BIO_get_callback_arg(bio);
if (oper == (BIO_CB_CTRL | BIO_CB_RETURN) && cmd == BIO_CTRL_FLUSH)
ret = mock_http_server(bio, args->out, args->version, args->keep_alive,
(ASN1_VALUE *)x509, x509_it);
return ret;
}
static int test_http_x509(int do_get)
{
X509 *rcert = NULL;
BIO *wbio = BIO_new(BIO_s_mem());
BIO *rbio = BIO_new(BIO_s_mem());
server_args mock_args = { NULL, '0', 0 };
BIO *rsp, *req = ASN1_item_i2d_mem_bio(x509_it, (ASN1_VALUE *)x509);
STACK_OF(CONF_VALUE) *headers = NULL;
const char content_type[] = "application/x-x509-ca-cert";
int res = 0;
if (wbio == NULL || rbio == NULL || req == NULL)
goto err;
mock_args.out = rbio;
BIO_set_callback_ex(wbio, http_bio_cb_ex);
BIO_set_callback_arg(wbio, (char *)&mock_args);
rsp = do_get ?
OSSL_HTTP_get("/will-be-redirected",
NULL /* proxy */, NULL /* no_proxy */,
wbio, rbio, NULL /* bio_update_fn */, NULL /* arg */,
0 /* buf_size */, headers, content_type,
1 /* expect_asn1 */,
OSSL_HTTP_DEFAULT_MAX_RESP_LEN, 0 /* timeout */)
: OSSL_HTTP_transfer(NULL, NULL /* host */, NULL /* port */, RPATH,
0 /* use_ssl */,NULL /* proxy */, NULL /* no_pr */,
wbio, rbio, NULL /* bio_fn */, NULL /* arg */,
0 /* buf_size */, headers, content_type,
req, content_type, 1 /* expect_asn1 */,
OSSL_HTTP_DEFAULT_MAX_RESP_LEN, 0 /* timeout */,
0 /* keep_alive */);
rcert = d2i_X509_bio(rsp, NULL);
BIO_free(rsp);
res = TEST_ptr(rcert) && TEST_int_eq(X509_cmp(x509, rcert), 0);
err:
X509_free(rcert);
BIO_free(req);
BIO_free(wbio);
BIO_free(rbio);
sk_CONF_VALUE_pop_free(headers, X509V3_conf_free);
return res;
}
static int test_http_keep_alive(char version, int keep_alive, int kept_alive)
{
BIO *wbio = BIO_new(BIO_s_mem());
BIO *rbio = BIO_new(BIO_s_mem());
BIO *rsp;
server_args mock_args = { NULL, '0', 0 };
const char *const content_type = "application/x-x509-ca-cert";
OSSL_HTTP_REQ_CTX *rctx = NULL;
int i, res = 0;
if (wbio == NULL || rbio == NULL)
goto err;
mock_args.out = rbio;
mock_args.version = version;
mock_args.keep_alive = kept_alive;
BIO_set_callback_ex(wbio, http_bio_cb_ex);
BIO_set_callback_arg(wbio, (char *)&mock_args);
for (res = 1, i = 1; res && i <= 2; i++) {
rsp = OSSL_HTTP_transfer(&rctx, NULL /* server */, NULL /* port */,
RPATH, 0 /* use_ssl */,
NULL /* proxy */, NULL /* no_proxy */,
wbio, rbio, NULL /* bio_update_fn */, NULL,
0 /* buf_size */, NULL /* headers */,
NULL /* content_type */, NULL /* req => GET */,
content_type, 0 /* ASN.1 not expected */,
0 /* max_resp_len */, 0 /* timeout */,
keep_alive);
if (keep_alive == 2 && kept_alive == 0)
res = res && TEST_ptr_null(rsp)
&& TEST_int_eq(OSSL_HTTP_is_alive(rctx), 0);
else
res = res && TEST_ptr(rsp)
&& TEST_int_eq(OSSL_HTTP_is_alive(rctx), keep_alive > 0);
BIO_free(rsp);
(void)BIO_reset(rbio); /* discard response contents */
keep_alive = 0;
}
OSSL_HTTP_close(rctx, res);
err:
BIO_free(wbio);
BIO_free(rbio);
return res;
}
static int test_http_url_ok(const char *url, int exp_ssl, const char *exp_host,
const char *exp_port, const char *exp_path)
{
char *user, *host, *port, *path, *query, *frag;
int exp_num, num, ssl;
int res;
if (!TEST_int_eq(sscanf(exp_port, "%d", &exp_num), 1))
return 0;
res = TEST_true(OSSL_HTTP_parse_url(url, &ssl, &user, &host, &port, &num,
&path, &query, &frag))
&& TEST_str_eq(host, exp_host)
&& TEST_str_eq(port, exp_port)
&& TEST_int_eq(num, exp_num)
&& TEST_str_eq(path, exp_path)
&& TEST_int_eq(ssl, exp_ssl);
if (res && *user != '\0')
res = TEST_str_eq(user, "user:pass");
if (res && *frag != '\0')
res = TEST_str_eq(frag, "fr");
if (res && *query != '\0')
res = TEST_str_eq(query, "q");
OPENSSL_free(user);
OPENSSL_free(host);
OPENSSL_free(port);
OPENSSL_free(path);
OPENSSL_free(query);
OPENSSL_free(frag);
return res;
}
static int test_http_url_path_query_ok(const char *url, const char *exp_path_qu)
{
char *host, *path;
int res;
res = TEST_true(OSSL_HTTP_parse_url(url, NULL, NULL, &host, NULL, NULL,
&path, NULL, NULL))
&& TEST_str_eq(host, "host")
&& TEST_str_eq(path, exp_path_qu);
OPENSSL_free(host);
OPENSSL_free(path);
return res;
}
static int test_http_url_dns(void)
{
return test_http_url_ok("host:65535/path", 0, "host", "65535", "/path");
}
static int test_http_url_path_query(void)
{
return test_http_url_path_query_ok("http://usr@host:1/p?q=x#frag", "/p?q=x")
&& test_http_url_path_query_ok("http://host?query#frag", "/?query")
&& test_http_url_path_query_ok("http://host:9999#frag", "/");
}
static int test_http_url_userinfo_query_fragment(void)
{
return test_http_url_ok("user:pass@host/p?q#fr", 0, "host", "80", "/p");
}
static int test_http_url_ipv4(void)
{
return test_http_url_ok("https://1.2.3.4/p/q", 1, "1.2.3.4", "443", "/p/q");
}
static int test_http_url_ipv6(void)
{
return test_http_url_ok("http://[FF01::101]:6", 0, "[FF01::101]", "6", "/");
}
static int test_http_url_invalid(const char *url)
{
char *host = "1", *port = "1", *path = "1";
int num = 1, ssl = 1;
int res;
res = TEST_false(OSSL_HTTP_parse_url(url, &ssl, NULL, &host, &port, &num,
&path, NULL, NULL))
&& TEST_ptr_null(host)
&& TEST_ptr_null(port)
&& TEST_ptr_null(path);
if (!res) {
OPENSSL_free(host);
OPENSSL_free(port);
OPENSSL_free(path);
}
return res;
}
static int test_http_url_invalid_prefix(void)
{
return test_http_url_invalid("htttps://1.2.3.4:65535/pkix");
}
static int test_http_url_invalid_port(void)
{
return test_http_url_invalid("https://1.2.3.4:65536/pkix");
}
static int test_http_url_invalid_path(void)
{
return test_http_url_invalid("https://[FF01::101]pkix");
}
static int test_http_get_x509(void)
{
return test_http_x509(1);
}
static int test_http_post_x509(void)
{
return test_http_x509(0);
}
static int test_http_keep_alive_0_no_no(void)
{
return test_http_keep_alive('0', 0, 0);
}
static int test_http_keep_alive_1_no_no(void)
{
return test_http_keep_alive('1', 0, 0);
}
static int test_http_keep_alive_0_prefer_yes(void)
{
return test_http_keep_alive('0', 1, 1);
}
static int test_http_keep_alive_1_prefer_yes(void)
{
return test_http_keep_alive('1', 1, 1);
}
static int test_http_keep_alive_0_require_yes(void)
{
return test_http_keep_alive('0', 2, 1);
}
static int test_http_keep_alive_1_require_yes(void)
{
return test_http_keep_alive('1', 2, 1);
}
static int test_http_keep_alive_0_require_no(void)
{
return test_http_keep_alive('0', 2, 0);
}
static int test_http_keep_alive_1_require_no(void)
{
return test_http_keep_alive('1', 2, 0);
}
void cleanup_tests(void)
{
X509_free(x509);
}
OPT_TEST_DECLARE_USAGE("cert.pem\n")
int setup_tests(void)
{
if (!test_skip_common_options())
return 0;
x509_it = ASN1_ITEM_rptr(X509);
if (!TEST_ptr((x509 = load_cert_pem(test_get_argument(0), NULL))))
return 0;
ADD_TEST(test_http_url_dns);
ADD_TEST(test_http_url_path_query);
ADD_TEST(test_http_url_userinfo_query_fragment);
ADD_TEST(test_http_url_ipv4);
ADD_TEST(test_http_url_ipv6);
ADD_TEST(test_http_url_invalid_prefix);
ADD_TEST(test_http_url_invalid_port);
ADD_TEST(test_http_url_invalid_path);
ADD_TEST(test_http_get_x509);
ADD_TEST(test_http_post_x509);
ADD_TEST(test_http_keep_alive_0_no_no);
ADD_TEST(test_http_keep_alive_1_no_no);
ADD_TEST(test_http_keep_alive_0_prefer_yes);
ADD_TEST(test_http_keep_alive_1_prefer_yes);
ADD_TEST(test_http_keep_alive_0_require_yes);
ADD_TEST(test_http_keep_alive_1_require_yes);
ADD_TEST(test_http_keep_alive_0_require_no);
ADD_TEST(test_http_keep_alive_1_require_no);
return 1;
}
| Java |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CSSParserFastPaths_h
#define CSSParserFastPaths_h
#include "core/CSSPropertyNames.h"
#include "core/CSSValueKeywords.h"
#include "platform/graphics/Color.h"
#include "platform/heap/Handle.h"
#include "wtf/Allocator.h"
#include "wtf/Forward.h"
namespace blink {
class CSSValue;
class CSSParserFastPaths {
STATIC_ONLY(CSSParserFastPaths);
public:
// Parses simple values like '10px' or 'green', but makes no guarantees
// about handling any property completely.
static CSSValue* maybeParseValue(CSSPropertyID, const String&, CSSParserMode);
// Properties handled here shouldn't be explicitly handled in CSSPropertyParser
static bool isKeywordPropertyID(CSSPropertyID);
static bool isValidKeywordPropertyAndValue(CSSPropertyID, CSSValueID, CSSParserMode);
static CSSValue* parseColor(const String&, CSSParserMode);
};
} // namespace blink
#endif // CSSParserFastPaths_h
| Java |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.util.lz4;
import javax.annotation.*;
import java.nio.*;
import org.lwjgl.*;
import org.lwjgl.system.*;
import static org.lwjgl.system.Checks.*;
import static org.lwjgl.system.MemoryUtil.*;
import static org.lwjgl.util.lz4.LZ4HC.LZ4_STREAMHCSIZE_VOIDP;
/**
* <h3>Layout</h3>
*
* <pre><code>
* union LZ4_streamHC_t {
* size_t table[LZ4_STREAMHCSIZE_VOIDP];
* {@link LZ4HCCCtxInternal struct LZ4HC_CCtx_internal} internal_donotuse;
* }</code></pre>
*/
@NativeType("union LZ4_streamHC_t")
public class LZ4StreamHC extends Struct {
/** The struct size in bytes. */
public static final int SIZEOF;
/** The struct alignment in bytes. */
public static final int ALIGNOF;
/** The struct member offsets. */
public static final int
TABLE,
INTERNAL_DONOTUSE;
static {
Layout layout = __union(
__array(POINTER_SIZE, LZ4_STREAMHCSIZE_VOIDP),
__member(LZ4HCCCtxInternal.SIZEOF, LZ4HCCCtxInternal.ALIGNOF)
);
SIZEOF = layout.getSize();
ALIGNOF = layout.getAlignment();
TABLE = layout.offsetof(0);
INTERNAL_DONOTUSE = layout.offsetof(1);
}
/**
* Creates a {@code LZ4StreamHC} instance at the current position of the specified {@link ByteBuffer} container. Changes to the buffer's content will be
* visible to the struct instance and vice versa.
*
* <p>The created instance holds a strong reference to the container object.</p>
*/
public LZ4StreamHC(ByteBuffer container) {
super(memAddress(container), __checkContainer(container, SIZEOF));
}
@Override
public int sizeof() { return SIZEOF; }
/** @return a {@link PointerBuffer} view of the {@code table} field. */
@NativeType("size_t[LZ4_STREAMHCSIZE_VOIDP]")
public PointerBuffer table() { return ntable(address()); }
/** @return the value at the specified index of the {@code table} field. */
@NativeType("size_t")
public long table(int index) { return ntable(address(), index); }
/** @return a {@link LZ4HCCCtxInternal} view of the {@code internal_donotuse} field. */
@NativeType("struct LZ4HC_CCtx_internal")
public LZ4HCCCtxInternal internal_donotuse() { return ninternal_donotuse(address()); }
// -----------------------------------
/** Returns a new {@code LZ4StreamHC} instance for the specified memory address. */
public static LZ4StreamHC create(long address) {
return wrap(LZ4StreamHC.class, address);
}
/** Like {@link #create(long) create}, but returns {@code null} if {@code address} is {@code NULL}. */
@Nullable
public static LZ4StreamHC createSafe(long address) {
return address == NULL ? null : wrap(LZ4StreamHC.class, address);
}
/**
* Create a {@link LZ4StreamHC.Buffer} instance at the specified memory.
*
* @param address the memory address
* @param capacity the buffer capacity
*/
public static LZ4StreamHC.Buffer create(long address, int capacity) {
return wrap(Buffer.class, address, capacity);
}
/** Like {@link #create(long, int) create}, but returns {@code null} if {@code address} is {@code NULL}. */
@Nullable
public static LZ4StreamHC.Buffer createSafe(long address, int capacity) {
return address == NULL ? null : wrap(Buffer.class, address, capacity);
}
// -----------------------------------
/** Unsafe version of {@link #table}. */
public static PointerBuffer ntable(long struct) { return memPointerBuffer(struct + LZ4StreamHC.TABLE, LZ4_STREAMHCSIZE_VOIDP); }
/** Unsafe version of {@link #table(int) table}. */
public static long ntable(long struct, int index) {
return memGetAddress(struct + LZ4StreamHC.TABLE + check(index, LZ4_STREAMHCSIZE_VOIDP) * POINTER_SIZE);
}
/** Unsafe version of {@link #internal_donotuse}. */
public static LZ4HCCCtxInternal ninternal_donotuse(long struct) { return LZ4HCCCtxInternal.create(struct + LZ4StreamHC.INTERNAL_DONOTUSE); }
// -----------------------------------
/** An array of {@link LZ4StreamHC} structs. */
public static class Buffer extends StructBuffer<LZ4StreamHC, Buffer> {
private static final LZ4StreamHC ELEMENT_FACTORY = LZ4StreamHC.create(-1L);
/**
* Creates a new {@code LZ4StreamHC.Buffer} instance backed by the specified container.
*
* Changes to the container's content will be visible to the struct buffer instance and vice versa. The two buffers' position, limit, and mark values
* will be independent. The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided
* by {@link LZ4StreamHC#SIZEOF}, and its mark will be undefined.
*
* <p>The created buffer instance holds a strong reference to the container object.</p>
*/
public Buffer(ByteBuffer container) {
super(container, container.remaining() / SIZEOF);
}
public Buffer(long address, int cap) {
super(address, null, -1, 0, cap, cap);
}
Buffer(long address, @Nullable ByteBuffer container, int mark, int pos, int lim, int cap) {
super(address, container, mark, pos, lim, cap);
}
@Override
protected Buffer self() {
return this;
}
@Override
protected LZ4StreamHC getElementFactory() {
return ELEMENT_FACTORY;
}
/** @return a {@link PointerBuffer} view of the {@code table} field. */
@NativeType("size_t[LZ4_STREAMHCSIZE_VOIDP]")
public PointerBuffer table() { return LZ4StreamHC.ntable(address()); }
/** @return the value at the specified index of the {@code table} field. */
@NativeType("size_t")
public long table(int index) { return LZ4StreamHC.ntable(address(), index); }
/** @return a {@link LZ4HCCCtxInternal} view of the {@code internal_donotuse} field. */
@NativeType("struct LZ4HC_CCtx_internal")
public LZ4HCCCtxInternal internal_donotuse() { return LZ4StreamHC.ninternal_donotuse(address()); }
}
} | Java |
import copy
from django import forms
from django.db import models
from django.core.exceptions import ValidationError, ImproperlyConfigured
from django.db.models.fields.subclassing import Creator
from djangae.forms.fields import ListFormField
from django.utils.text import capfirst
class _FakeModel(object):
"""
An object of this class can pass itself off as a model instance
when used as an arguments to Field.pre_save method (item_fields
of iterable fields are not actually fields of any model).
"""
def __init__(self, field, value):
setattr(self, field.attname, value)
class IterableField(models.Field):
__metaclass__ = models.SubfieldBase
@property
def _iterable_type(self): raise NotImplementedError()
def db_type(self, connection):
return 'list'
def get_prep_lookup(self, lookup_type, value):
if hasattr(value, 'prepare'):
return value.prepare()
if hasattr(value, '_prepare'):
return value._prepare()
if value is None:
raise ValueError("You can't query an iterable field with None")
if lookup_type == 'isnull' and value in (True, False):
return value
if lookup_type != 'exact' and lookup_type != 'in':
raise ValueError("You can only query using exact and in lookups on iterable fields")
if isinstance(value, (list, set)):
return [ self.item_field_type.to_python(x) for x in value ]
return self.item_field_type.to_python(value)
def get_prep_value(self, value):
if value is None:
raise ValueError("You can't set a {} to None (did you mean {}?)".format(
self.__class__.__name__, str(self._iterable_type())
))
if isinstance(value, basestring):
# Catch accidentally assigning a string to a ListField
raise ValueError("Tried to assign a string to a {}".format(self.__class__.__name__))
return super(IterableField, self).get_prep_value(value)
def __init__(self, item_field_type, *args, **kwargs):
# This seems bonkers, we shout at people for specifying null=True, but then do it ourselves. But this is because
# *we* abuse None values for our own purposes (to represent an empty iterable) if someone else tries to then
# all hell breaks loose
if kwargs.get("null", False):
raise RuntimeError("IterableFields cannot be set as nullable (as the datastore doesn't differentiate None vs []")
kwargs["null"] = True
default = kwargs.get("default", [])
self._original_item_field_type = copy.deepcopy(item_field_type) # For deconstruction purposes
if default is not None and not callable(default):
kwargs["default"] = lambda: self._iterable_type(default)
if hasattr(item_field_type, 'attname'):
item_field_type = item_field_type.__class__
if callable(item_field_type):
item_field_type = item_field_type()
if isinstance(item_field_type, models.ForeignKey):
raise ImproperlyConfigured("Lists of ForeignKeys aren't supported, use RelatedSetField instead")
self.item_field_type = item_field_type
# We'll be pretending that item_field is a field of a model
# with just one "value" field.
assert not hasattr(self.item_field_type, 'attname')
self.item_field_type.set_attributes_from_name('value')
super(IterableField, self).__init__(*args, **kwargs)
def deconstruct(self):
name, path, args, kwargs = super(IterableField, self).deconstruct()
args = (self._original_item_field_type,)
del kwargs["null"]
return name, path, args, kwargs
def contribute_to_class(self, cls, name):
self.item_field_type.model = cls
self.item_field_type.name = name
super(IterableField, self).contribute_to_class(cls, name)
# If items' field uses SubfieldBase we also need to.
item_metaclass = getattr(self.item_field_type, '__metaclass__', None)
if item_metaclass and issubclass(item_metaclass, models.SubfieldBase):
setattr(cls, self.name, Creator(self))
def _map(self, function, iterable, *args, **kwargs):
return self._iterable_type(function(element, *args, **kwargs) for element in iterable)
def to_python(self, value):
if value is None:
return self._iterable_type([])
# Because a set cannot be defined in JSON, we must allow a list to be passed as the value
# of a SetField, as otherwise SetField data can't be loaded from fixtures
if not hasattr(value, "__iter__"): # Allows list/set, not string
raise ValueError("Tried to assign a {} to a {}".format(value.__class__.__name__, self.__class__.__name__))
return self._map(self.item_field_type.to_python, value)
def pre_save(self, model_instance, add):
"""
Gets our value from the model_instance and passes its items
through item_field's pre_save (using a fake model instance).
"""
value = getattr(model_instance, self.attname)
if value is None:
return None
return self._map(lambda item: self.item_field_type.pre_save(_FakeModel(self.item_field_type, item), add), value)
def get_db_prep_value(self, value, connection, prepared=False):
if not prepared:
value = self.get_prep_value(value)
if value is None:
return None
# If the value is an empty iterable, store None
if value == self._iterable_type([]):
return None
return self._map(self.item_field_type.get_db_prep_save, value,
connection=connection)
def get_db_prep_lookup(self, lookup_type, value, connection,
prepared=False):
"""
Passes the value through get_db_prep_lookup of item_field.
"""
return self.item_field_type.get_db_prep_lookup(
lookup_type, value, connection=connection, prepared=prepared)
def validate(self, value_list, model_instance):
""" We want to override the default validate method from django.db.fields.Field, because it
is only designed to deal with a single choice from the user.
"""
if not self.editable:
# Skip validation for non-editable fields
return
# Validate choices
if self.choices:
valid_values = []
for choice in self.choices:
if isinstance(choice[0], (list, tuple)):
# this is an optgroup, so look inside it for the options
for optgroup_choice in choice[0]:
valid_values.append(optgroup_choice[0])
else:
valid_values.append(choice[0])
for value in value_list:
if value not in valid_values:
# TODO: if there is more than 1 invalid value then this should show all of the invalid values
raise ValidationError(self.error_messages['invalid_choice'] % value)
# Validate null-ness
if value_list is None and not self.null:
raise ValidationError(self.error_messages['null'])
if not self.blank and not value_list:
raise ValidationError(self.error_messages['blank'])
# apply the default items validation rules
for value in value_list:
self.item_field_type.clean(value, model_instance)
def formfield(self, **kwargs):
""" If this field has choices, then we can use a multiple choice field.
NB: The choices must be set on *this* field, e.g. this_field = ListField(CharField(), choices=x)
as opposed to: this_field = ListField(CharField(choices=x))
"""
#Largely lifted straight from Field.formfield() in django.models.__init__.py
defaults = {'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text}
if self.has_default(): #No idea what this does
if callable(self.default):
defaults['initial'] = self.default
defaults['show_hidden_initial'] = True
else:
defaults['initial'] = self.get_default()
if self.choices:
form_field_class = forms.MultipleChoiceField
defaults['choices'] = self.get_choices(include_blank=False) #no empty value on a multi-select
else:
form_field_class = ListFormField
defaults.update(**kwargs)
return form_field_class(**defaults)
class ListField(IterableField):
def __init__(self, *args, **kwargs):
self.ordering = kwargs.pop('ordering', None)
if self.ordering is not None and not callable(self.ordering):
raise TypeError("'ordering' has to be a callable or None, "
"not of type %r." % type(self.ordering))
super(ListField, self).__init__(*args, **kwargs)
def pre_save(self, model_instance, add):
value = super(ListField, self).pre_save(model_instance, add)
if value and self.ordering:
value.sort(key=self.ordering)
return value
@property
def _iterable_type(self):
return list
def deconstruct(self):
name, path, args, kwargs = super(ListField, self).deconstruct()
kwargs['ordering'] = self.ordering
return name, path, args, kwargs
class SetField(IterableField):
@property
def _iterable_type(self):
return set
def db_type(self, connection):
return 'set'
def get_db_prep_save(self, *args, **kwargs):
ret = super(SetField, self).get_db_prep_save(*args, **kwargs)
if ret:
ret = list(ret)
return ret
def get_db_prep_lookup(self, *args, **kwargs):
ret = super(SetField, self).get_db_prep_lookup(*args, **kwargs)
if ret:
ret = list(ret)
return ret
def value_to_string(self, obj):
"""
Custom method for serialization, as JSON doesn't support
serializing sets.
"""
return str(list(self._get_val_from_obj(obj)))
| Java |
from __future__ import absolute_import
from datetime import datetime
from django.utils import timezone
from django.core.urlresolvers import reverse
from sentry.models import (
ProcessingIssue, EventError, RawEvent, EventProcessingIssue
)
from sentry.testutils import APITestCase
class ProjectProjectProcessingIssuesTest(APITestCase):
def test_simple(self):
self.login_as(user=self.user)
team = self.create_team()
project1 = self.create_project(team=team, name='foo')
raw_event = RawEvent.objects.create(
project_id=project1.id,
event_id='abc'
)
issue, _ = ProcessingIssue.objects.get_or_create(
project_id=project1.id,
checksum='abc',
type=EventError.NATIVE_MISSING_DSYM
)
EventProcessingIssue.objects.get_or_create(
raw_event=raw_event,
processing_issue=issue,
)
url = reverse('sentry-api-0-project-processing-issues', kwargs={
'organization_slug': project1.organization.slug,
'project_slug': project1.slug,
})
response = self.client.get(url, format='json')
assert response.status_code == 200, response.content
assert response.data['hasIssues'] is True
assert response.data['hasMoreResolveableIssues'] is False
assert response.data['numIssues'] == 1
assert response.data['issuesProcessing'] == 0
assert response.data['resolveableIssues'] == 0
def test_issues(self):
self.login_as(user=self.user)
team = self.create_team()
project1 = self.create_project(team=team, name='foo')
raw_event = RawEvent.objects.create(
project_id=project1.id,
event_id='abc'
)
issue, _ = ProcessingIssue.objects.get_or_create(
project_id=project1.id,
checksum='abc',
type=EventError.NATIVE_MISSING_DSYM,
datetime=datetime(2013, 8, 13, 3, 8, 25, tzinfo=timezone.utc),
)
issue2, _ = ProcessingIssue.objects.get_or_create(
project_id=project1.id,
checksum='abcd',
type=EventError.NATIVE_MISSING_DSYM,
datetime=datetime(2014, 8, 13, 3, 8, 25, tzinfo=timezone.utc),
)
EventProcessingIssue.objects.get_or_create(
raw_event=raw_event,
processing_issue=issue,
)
url = reverse('sentry-api-0-project-processing-issues', kwargs={
'organization_slug': project1.organization.slug,
'project_slug': project1.slug,
})
response = self.client.get(url + '?detailed=1', format='json')
assert response.status_code == 200, response.content
assert len(response.data['issues']) == 2
assert response.data['numIssues'] == 2
assert response.data['lastSeen'] == issue2.datetime
assert response.data['hasIssues'] is True
assert response.data['hasMoreResolveableIssues'] is False
assert response.data['issuesProcessing'] == 0
assert response.data['resolveableIssues'] == 0
assert response.data['issues'][0]['checksum'] == issue.checksum
assert response.data['issues'][0]['numEvents'] == 1
assert response.data['issues'][0]['type'] == EventError.NATIVE_MISSING_DSYM
assert response.data['issues'][1]['checksum'] == issue2.checksum
def test_resolvable_issues(self):
self.login_as(user=self.user)
team = self.create_team()
project1 = self.create_project(team=team, name='foo')
RawEvent.objects.create(
project_id=project1.id,
event_id='abc'
)
url = reverse('sentry-api-0-project-processing-issues', kwargs={
'organization_slug': project1.organization.slug,
'project_slug': project1.slug,
})
response = self.client.get(url + '?detailed=1', format='json')
assert response.status_code == 200, response.content
assert response.data['numIssues'] == 0
assert response.data['resolveableIssues'] == 1
assert response.data['lastSeen'] is None
assert response.data['hasIssues'] is False
assert response.data['hasMoreResolveableIssues'] is False
assert response.data['numIssues'] == 0
assert response.data['issuesProcessing'] == 0
| Java |
// 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 "base/basictypes.h"
#include "chrome/browser/sync/profile_sync_service_harness.h"
#include "chrome/test/live_sync/live_themes_sync_test.h"
class SingleClientLiveThemesSyncTest : public LiveThemesSyncTest {
public:
SingleClientLiveThemesSyncTest() : LiveThemesSyncTest(SINGLE_CLIENT) {}
virtual ~SingleClientLiveThemesSyncTest() {}
private:
DISALLOW_COPY_AND_ASSIGN(SingleClientLiveThemesSyncTest);
};
// TODO(akalin): Add tests for model association (i.e., tests that
// start with SetupClients(), change the theme state, then call
// SetupSync()).
IN_PROC_BROWSER_TEST_F(SingleClientLiveThemesSyncTest, CustomTheme) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
ASSERT_FALSE(UsingCustomTheme(GetProfile(0)));
ASSERT_FALSE(UsingCustomTheme(verifier()));
UseCustomTheme(GetProfile(0), 0);
UseCustomTheme(verifier(), 0);
ASSERT_EQ(GetCustomTheme(0), GetThemeID(GetProfile(0)));
ASSERT_EQ(GetCustomTheme(0), GetThemeID(verifier()));
ASSERT_TRUE(GetClient(0)->AwaitSyncCycleCompletion(
"Waiting for custom themes change."));
ASSERT_EQ(GetCustomTheme(0), GetThemeID(GetProfile(0)));
ASSERT_EQ(GetCustomTheme(0), GetThemeID(verifier()));
}
IN_PROC_BROWSER_TEST_F(SingleClientLiveThemesSyncTest, NativeTheme) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
UseCustomTheme(GetProfile(0), 0);
UseCustomTheme(verifier(), 0);
ASSERT_FALSE(UsingNativeTheme(GetProfile(0)));
ASSERT_FALSE(UsingNativeTheme(verifier()));
ASSERT_TRUE(GetClient(0)->AwaitSyncCycleCompletion(
"Waiting for custom themes change."));
UseNativeTheme(GetProfile(0));
UseNativeTheme(verifier());
ASSERT_TRUE(UsingNativeTheme(GetProfile(0)));
ASSERT_TRUE(UsingNativeTheme(verifier()));
ASSERT_TRUE(GetClient(0)->AwaitSyncCycleCompletion(
"Waiting for native themes change."));
ASSERT_TRUE(UsingNativeTheme(GetProfile(0)));
ASSERT_TRUE(UsingNativeTheme(verifier()));
}
IN_PROC_BROWSER_TEST_F(SingleClientLiveThemesSyncTest, DefaultTheme) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
UseCustomTheme(GetProfile(0), 0);
UseCustomTheme(verifier(), 0);
ASSERT_FALSE(UsingDefaultTheme(GetProfile(0)));
ASSERT_FALSE(UsingDefaultTheme(verifier()));
ASSERT_TRUE(GetClient(0)->AwaitSyncCycleCompletion(
"Waiting for custom themes change."));
UseDefaultTheme(GetProfile(0));
UseDefaultTheme(verifier());
ASSERT_TRUE(UsingDefaultTheme(GetProfile(0)));
ASSERT_TRUE(UsingDefaultTheme(verifier()));
ASSERT_TRUE(GetClient(0)->AwaitSyncCycleCompletion(
"Waiting for native themes change."));
ASSERT_TRUE(UsingDefaultTheme(GetProfile(0)));
ASSERT_TRUE(UsingDefaultTheme(verifier()));
}
| Java |
// 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.
#ifndef CHROME_BROWSER_UI_GTK_DOWNLOAD_DOWNLOAD_SHELF_CONTEXT_MENU_GTK_H_
#define CHROME_BROWSER_UI_GTK_DOWNLOAD_DOWNLOAD_SHELF_CONTEXT_MENU_GTK_H_
#include "base/basictypes.h"
#include "base/compiler_specific.h"
#include "base/memory/scoped_ptr.h"
#include "chrome/browser/download/download_shelf_context_menu.h"
#include "chrome/browser/ui/gtk/menu_gtk.h"
class DownloadItemGtk;
class DownloadItemModel;
class DownloadShelfContextMenuGtk : public DownloadShelfContextMenu,
public MenuGtk::Delegate {
public:
DownloadShelfContextMenuGtk(DownloadItemModel* model,
DownloadItemGtk* download_item,
content::PageNavigator* navigator);
virtual ~DownloadShelfContextMenuGtk();
void Popup(GtkWidget* widget, GdkEventButton* event);
private:
// MenuGtk::Delegate:
virtual void StoppedShowing() OVERRIDE;
virtual GtkWidget* GetImageForCommandId(int command_id) const OVERRIDE;
// The menu we show on Popup(). We keep a pointer to it for a couple reasons:
// * we don't want to have to recreate the menu every time it's popped up.
// * we have to keep it in scope for longer than the duration of Popup(), or
// completing the user-selected action races against the menu's
// destruction.
scoped_ptr<MenuGtk> menu_;
// The download item that created us.
DownloadItemGtk* download_item_gtk_;
DISALLOW_COPY_AND_ASSIGN(DownloadShelfContextMenuGtk);
};
#endif // CHROME_BROWSER_UI_GTK_DOWNLOAD_DOWNLOAD_SHELF_CONTEXT_MENU_GTK_H_
| Java |
$.ajax({
url: './data/population.json',
success: function (data) {
var max = -Infinity;
data = data.map(function (item) {
max = Math.max(item[2], max);
return {
geoCoord: item.slice(0, 2),
value: item[2]
}
});
data.forEach(function (item) {
item.barHeight = item.value / max * 50 + 0.1
});
myChart.setOption({
title : {
text: 'Gridded Population of the World (2000)',
subtext: 'Data from Socioeconomic Data and Applications Center',
sublink : 'http://sedac.ciesin.columbia.edu/data/set/gpw-v3-population-density/data-download#close',
x:'center',
y:'top',
textStyle: {
color: 'white'
}
},
tooltip: {
formatter: '{b}'
},
dataRange: {
min: 0,
max: max,
text:['High','Low'],
realtime: false,
calculable : true,
color: ['red','yellow','lightskyblue']
},
series: [{
type: 'map3d',
mapType: 'world',
baseLayer: {
backgroundColor: 'rgba(0, 150, 200, 0.5)'
},
data: [{}],
itemStyle: {
normal: {
areaStyle: {
color: 'rgba(0, 150, 200, 0.8)'
},
borderColor: '#777'
}
},
markBar: {
barSize: 0.6,
data: data
},
autoRotate: true,
}]
});
}
}); | Java |
/*
* Copyright (C) 1999 Lars Knoll ([email protected])
* (C) 1999 Antti Koivisto ([email protected])
* (C) 2001 Peter Kelly ([email protected])
* (C) 2001 Dirk Mueller ([email protected])
* Copyright (C) 2003-2011, 2013, 2014 Apple Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#ifndef Element_h
#define Element_h
#include "core/CSSPropertyNames.h"
#include "core/CoreExport.h"
#include "core/HTMLNames.h"
#include "core/css/CSSPrimitiveValue.h"
#include "core/css/CSSSelector.h"
#include "core/dom/AXObjectCache.h"
#include "core/dom/Attribute.h"
#include "core/dom/ContainerNode.h"
#include "core/dom/Document.h"
#include "core/dom/ElementData.h"
#include "core/dom/SpaceSplitString.h"
#include "core/html/CollectionType.h"
#include "platform/heap/Handle.h"
#include "public/platform/WebFocusType.h"
namespace blink {
class ElementAnimations;
class Attr;
class Attribute;
class CSSStyleDeclaration;
class ClientRect;
class ClientRectList;
class CompositorMutation;
class V0CustomElementDefinition;
class DOMStringMap;
class DOMTokenList;
class Dictionary;
class ElementRareData;
class ElementShadow;
class ExceptionState;
class Image;
class IntSize;
class Locale;
class MutableStylePropertySet;
class NodeIntersectionObserverData;
class PropertySetCSSStyleDeclaration;
class PseudoElement;
class ScrollState;
class ScrollStateCallback;
class ScrollToOptions;
class ShadowRoot;
class ShadowRootInit;
class StylePropertySet;
class StylePropertyMap;
enum SpellcheckAttributeState {
SpellcheckAttributeTrue,
SpellcheckAttributeFalse,
SpellcheckAttributeDefault
};
enum ElementFlags {
TabIndexWasSetExplicitly = 1 << 0,
StyleAffectedByEmpty = 1 << 1,
IsInCanvasSubtree = 1 << 2,
ContainsFullScreenElement = 1 << 3,
IsInTopLayer = 1 << 4,
HasPendingResources = 1 << 5,
NumberOfElementFlags = 6, // Required size of bitfield used to store the flags.
};
enum class ShadowRootType;
enum class SelectionBehaviorOnFocus {
Reset,
Restore,
None,
};
struct FocusParams {
STACK_ALLOCATED();
FocusParams() {}
FocusParams(SelectionBehaviorOnFocus selection, WebFocusType focusType, InputDeviceCapabilities* capabilities)
: selectionBehavior(selection)
, type(focusType)
, sourceCapabilities(capabilities) {}
SelectionBehaviorOnFocus selectionBehavior = SelectionBehaviorOnFocus::Restore;
WebFocusType type = WebFocusTypeNone;
Member<InputDeviceCapabilities> sourceCapabilities = nullptr;
};
typedef HeapVector<Member<Attr>> AttrNodeList;
class CORE_EXPORT Element : public ContainerNode {
DEFINE_WRAPPERTYPEINFO();
public:
static Element* create(const QualifiedName&, Document*);
~Element() override;
DEFINE_ATTRIBUTE_EVENT_LISTENER(beforecopy);
DEFINE_ATTRIBUTE_EVENT_LISTENER(beforecut);
DEFINE_ATTRIBUTE_EVENT_LISTENER(beforepaste);
DEFINE_ATTRIBUTE_EVENT_LISTENER(copy);
DEFINE_ATTRIBUTE_EVENT_LISTENER(cut);
DEFINE_ATTRIBUTE_EVENT_LISTENER(gotpointercapture);
DEFINE_ATTRIBUTE_EVENT_LISTENER(lostpointercapture);
DEFINE_ATTRIBUTE_EVENT_LISTENER(paste);
DEFINE_ATTRIBUTE_EVENT_LISTENER(search);
DEFINE_ATTRIBUTE_EVENT_LISTENER(selectstart);
DEFINE_ATTRIBUTE_EVENT_LISTENER(wheel);
bool hasAttribute(const QualifiedName&) const;
const AtomicString& getAttribute(const QualifiedName&) const;
// Passing nullAtom as the second parameter removes the attribute when calling either of these set methods.
void setAttribute(const QualifiedName&, const AtomicString& value);
void setSynchronizedLazyAttribute(const QualifiedName&, const AtomicString& value);
void removeAttribute(const QualifiedName&);
// Typed getters and setters for language bindings.
int getIntegralAttribute(const QualifiedName& attributeName) const;
void setIntegralAttribute(const QualifiedName& attributeName, int value);
void setUnsignedIntegralAttribute(const QualifiedName& attributeName, unsigned value);
double getFloatingPointAttribute(const QualifiedName& attributeName, double fallbackValue = std::numeric_limits<double>::quiet_NaN()) const;
void setFloatingPointAttribute(const QualifiedName& attributeName, double value);
// Call this to get the value of an attribute that is known not to be the style
// attribute or one of the SVG animatable attributes.
bool fastHasAttribute(const QualifiedName&) const;
const AtomicString& fastGetAttribute(const QualifiedName&) const;
#if DCHECK_IS_ON()
bool fastAttributeLookupAllowed(const QualifiedName&) const;
#endif
#ifdef DUMP_NODE_STATISTICS
bool hasNamedNodeMap() const;
#endif
bool hasAttributes() const;
bool hasAttribute(const AtomicString& name) const;
bool hasAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName) const;
const AtomicString& getAttribute(const AtomicString& name) const;
const AtomicString& getAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName) const;
void setAttribute(const AtomicString& name, const AtomicString& value, ExceptionState&);
static bool parseAttributeName(QualifiedName&, const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState&);
void setAttributeNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, const AtomicString& value, ExceptionState&);
const AtomicString& getIdAttribute() const;
void setIdAttribute(const AtomicString&);
const AtomicString& getNameAttribute() const;
const AtomicString& getClassAttribute() const;
bool shouldIgnoreAttributeCase() const;
// Call this to get the value of the id attribute for style resolution purposes.
// The value will already be lowercased if the document is in compatibility mode,
// so this function is not suitable for non-style uses.
const AtomicString& idForStyleResolution() const;
// This getter takes care of synchronizing all attributes before returning the
// AttributeCollection. If the Element has no attributes, an empty AttributeCollection
// will be returned. This is not a trivial getter and its return value should be cached
// for performance.
AttributeCollection attributes() const;
// This variant will not update the potentially invalid attributes. To be used when not interested
// in style attribute or one of the SVG animation attributes.
AttributeCollection attributesWithoutUpdate() const;
void scrollIntoView(bool alignToTop = true);
void scrollIntoViewIfNeeded(bool centerIfNeeded = true);
int offsetLeft();
int offsetTop();
int offsetWidth();
int offsetHeight();
Element* offsetParent();
int clientLeft();
int clientTop();
int clientWidth();
int clientHeight();
double scrollLeft();
double scrollTop();
void setScrollLeft(double);
void setScrollTop(double);
int scrollWidth();
int scrollHeight();
void scrollBy(double x, double y);
virtual void scrollBy(const ScrollToOptions&);
void scrollTo(double x, double y);
virtual void scrollTo(const ScrollToOptions&);
IntRect boundsInViewport() const;
ClientRectList* getClientRects();
ClientRect* getBoundingClientRect();
bool hasNonEmptyLayoutSize() const;
const AtomicString& computedRole();
String computedName();
void didMoveToNewDocument(Document&) override;
void removeAttribute(const AtomicString& name);
void removeAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName);
Attr* detachAttribute(size_t index);
Attr* getAttributeNode(const AtomicString& name);
Attr* getAttributeNodeNS(const AtomicString& namespaceURI, const AtomicString& localName);
Attr* setAttributeNode(Attr*, ExceptionState&);
Attr* setAttributeNodeNS(Attr*, ExceptionState&);
Attr* removeAttributeNode(Attr*, ExceptionState&);
Attr* attrIfExists(const QualifiedName&);
Attr* ensureAttr(const QualifiedName&);
AttrNodeList* attrNodeList();
CSSStyleDeclaration* style();
StylePropertyMap* styleMap();
const QualifiedName& tagQName() const { return m_tagName; }
String tagName() const { return nodeName(); }
bool hasTagName(const QualifiedName& tagName) const { return m_tagName.matches(tagName); }
bool hasTagName(const HTMLQualifiedName& tagName) const { return ContainerNode::hasTagName(tagName); }
bool hasTagName(const SVGQualifiedName& tagName) const { return ContainerNode::hasTagName(tagName); }
// Should be called only by Document::createElementNS to fix up m_tagName immediately after construction.
void setTagNameForCreateElementNS(const QualifiedName&);
// A fast function for checking the local name against another atomic string.
bool hasLocalName(const AtomicString& other) const { return m_tagName.localName() == other; }
const AtomicString& localName() const { return m_tagName.localName(); }
AtomicString localNameForSelectorMatching() const;
const AtomicString& prefix() const { return m_tagName.prefix(); }
const AtomicString& namespaceURI() const { return m_tagName.namespaceURI(); }
const AtomicString& locateNamespacePrefix(const AtomicString& namespaceURI) const;
String nodeName() const override;
Element* cloneElementWithChildren();
Element* cloneElementWithoutChildren();
void scheduleSVGFilterLayerUpdateHack();
void setBooleanAttribute(const QualifiedName&, bool);
virtual const StylePropertySet* additionalPresentationAttributeStyle() { return nullptr; }
void invalidateStyleAttribute();
const StylePropertySet* inlineStyle() const { return elementData() ? elementData()->m_inlineStyle.get() : nullptr; }
void setInlineStyleProperty(CSSPropertyID, CSSValueID identifier, bool important = false);
void setInlineStyleProperty(CSSPropertyID, double value, CSSPrimitiveValue::UnitType, bool important = false);
void setInlineStyleProperty(CSSPropertyID, CSSValue*, bool important = false);
bool setInlineStyleProperty(CSSPropertyID, const String& value, bool important = false);
bool removeInlineStyleProperty(CSSPropertyID);
void removeAllInlineStyleProperties();
void synchronizeStyleAttributeInternal() const;
const StylePropertySet* presentationAttributeStyle();
virtual bool isPresentationAttribute(const QualifiedName&) const { return false; }
virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) { }
// For exposing to DOM only.
NamedNodeMap* attributesForBindings() const;
enum AttributeModificationReason {
ModifiedDirectly,
ModifiedByCloning
};
// This method is called whenever an attribute is added, changed or removed.
virtual void attributeChanged(const QualifiedName&, const AtomicString& oldValue, const AtomicString& newValue, AttributeModificationReason = ModifiedDirectly);
virtual void parseAttribute(const QualifiedName&, const AtomicString& oldValue, const AtomicString& newValue);
virtual bool hasLegalLinkAttribute(const QualifiedName&) const;
virtual const QualifiedName& subResourceAttributeName() const;
// Only called by the parser immediately after element construction.
void parserSetAttributes(const Vector<Attribute>&);
// Remove attributes that might introduce scripting from the vector leaving the element unchanged.
void stripScriptingAttributes(Vector<Attribute>&) const;
bool sharesSameElementData(const Element& other) const { return elementData() == other.elementData(); }
// Clones attributes only.
void cloneAttributesFromElement(const Element&);
// Clones all attribute-derived data, including subclass specifics (through copyNonAttributeProperties.)
void cloneDataFromElement(const Element&);
bool hasEquivalentAttributes(const Element* other) const;
virtual void copyNonAttributePropertiesFromElement(const Element&) { }
void attach(const AttachContext& = AttachContext()) override;
void detach(const AttachContext& = AttachContext()) override;
virtual LayoutObject* createLayoutObject(const ComputedStyle&);
virtual bool layoutObjectIsNeeded(const ComputedStyle&);
void recalcStyle(StyleRecalcChange, Text* nextTextSibling = nullptr);
void pseudoStateChanged(CSSSelector::PseudoType);
void setAnimationStyleChange(bool);
void clearAnimationStyleChange();
void setNeedsAnimationStyleRecalc();
void setNeedsCompositingUpdate();
bool supportsStyleSharing() const;
ElementShadow* shadow() const;
ElementShadow& ensureShadow();
// If type of ShadowRoot (either closed or open) is explicitly specified, creation of multiple
// shadow roots is prohibited in any combination and throws an exception. Multiple shadow roots
// are allowed only when createShadowRoot() is used without any parameters from JavaScript.
ShadowRoot* createShadowRoot(const ScriptState*, ExceptionState&);
ShadowRoot* attachShadow(const ScriptState*, const ShadowRootInit&, ExceptionState&);
ShadowRoot* createShadowRootInternal(ShadowRootType, ExceptionState&);
ShadowRoot* openShadowRoot() const;
ShadowRoot* closedShadowRoot() const;
ShadowRoot* authorShadowRoot() const;
ShadowRoot* userAgentShadowRoot() const;
ShadowRoot* youngestShadowRoot() const;
ShadowRoot* shadowRootIfV1() const;
ShadowRoot& ensureUserAgentShadowRoot();
bool isInDescendantTreeOf(const Element* shadowHost) const;
const ComputedStyle* ensureComputedStyle(PseudoId = PseudoIdNone);
// Methods for indicating the style is affected by dynamic updates (e.g., children changing, our position changing in our sibling list, etc.)
bool styleAffectedByEmpty() const { return hasElementFlag(StyleAffectedByEmpty); }
void setStyleAffectedByEmpty() { setElementFlag(StyleAffectedByEmpty); }
void setIsInCanvasSubtree(bool value) { setElementFlag(IsInCanvasSubtree, value); }
bool isInCanvasSubtree() const { return hasElementFlag(IsInCanvasSubtree); }
bool isDefined() const { return getCustomElementState() != CustomElementState::Undefined; }
bool isUpgradedV0CustomElement() { return getV0CustomElementState() == V0Upgraded; }
bool isUnresolvedV0CustomElement() { return getV0CustomElementState() == V0WaitingForUpgrade; }
AtomicString computeInheritedLanguage() const;
Locale& locale() const;
virtual void accessKeyAction(bool /*sendToAnyEvent*/) { }
virtual bool isURLAttribute(const Attribute&) const { return false; }
virtual bool isHTMLContentAttribute(const Attribute&) const { return false; }
bool isJavaScriptURLAttribute(const Attribute&) const;
virtual bool isSVGAnimationAttributeSettingJavaScriptURL(const Attribute&) const { return false; }
virtual bool isLiveLink() const { return false; }
KURL hrefURL() const;
KURL getURLAttribute(const QualifiedName&) const;
KURL getNonEmptyURLAttribute(const QualifiedName&) const;
virtual const AtomicString imageSourceURL() const;
virtual Image* imageContents() { return nullptr; }
virtual void focus(const FocusParams& = FocusParams());
virtual void updateFocusAppearance(SelectionBehaviorOnFocus);
virtual void blur();
void setDistributeScroll(ScrollStateCallback*, String nativeScrollBehavior);
void nativeDistributeScroll(ScrollState&);
void setApplyScroll(ScrollStateCallback*, String nativeScrollBehavior);
void removeApplyScroll();
void nativeApplyScroll(ScrollState&);
void callDistributeScroll(ScrollState&);
void callApplyScroll(ScrollState&);
ScrollStateCallback* getApplyScroll();
// Whether this element can receive focus at all. Most elements are not
// focusable but some elements, such as form controls and links, are. Unlike
// layoutObjectIsFocusable(), this method may be called when layout is not up to
// date, so it must not use the layoutObject to determine focusability.
virtual bool supportsFocus() const;
// isFocusable(), isKeyboardFocusable(), and isMouseFocusable() check
// whether the element can actually be focused. Callers should ensure
// ComputedStyle is up to date;
// e.g. by calling Document::updateLayoutTreeIgnorePendingStylesheets().
bool isFocusable() const;
virtual bool isKeyboardFocusable() const;
virtual bool isMouseFocusable() const;
bool isFocusedElementInDocument() const;
virtual void dispatchFocusEvent(Element* oldFocusedElement, WebFocusType, InputDeviceCapabilities* sourceCapabilities = nullptr);
virtual void dispatchBlurEvent(Element* newFocusedElement, WebFocusType, InputDeviceCapabilities* sourceCapabilities = nullptr);
virtual void dispatchFocusInEvent(const AtomicString& eventType, Element* oldFocusedElement, WebFocusType, InputDeviceCapabilities* sourceCapabilities = nullptr);
void dispatchFocusOutEvent(const AtomicString& eventType, Element* newFocusedElement, InputDeviceCapabilities* sourceCapabilities = nullptr);
String innerText();
String outerText();
String innerHTML() const;
String outerHTML() const;
void setInnerHTML(const String&, ExceptionState&);
void setOuterHTML(const String&, ExceptionState&);
Element* insertAdjacentElement(const String& where, Element* newChild, ExceptionState&);
void insertAdjacentText(const String& where, const String& text, ExceptionState&);
void insertAdjacentHTML(const String& where, const String& html, ExceptionState&);
void setPointerCapture(int pointerId, ExceptionState&);
void releasePointerCapture(int pointerId, ExceptionState&);
String textFromChildren();
virtual String title() const { return String(); }
virtual String defaultToolTip() const { return String(); }
virtual const AtomicString& shadowPseudoId() const;
// The specified string must start with "-webkit-" or "-internal-". The
// former can be used as a selector in any places, and the latter can be
// used only in UA stylesheet.
void setShadowPseudoId(const AtomicString&);
LayoutSize minimumSizeForResizing() const;
void setMinimumSizeForResizing(const LayoutSize&);
virtual void didBecomeFullscreenElement() { }
virtual void willStopBeingFullscreenElement() { }
// Called by the parser when this element's close tag is reached,
// signaling that all child tags have been parsed and added.
// This is needed for <applet> and <object> elements, which can't lay themselves out
// until they know all of their nested <param>s. [Radar 3603191, 4040848].
// Also used for script elements and some SVG elements for similar purposes,
// but making parsing a special case in this respect should be avoided if possible.
virtual void finishParsingChildren();
void beginParsingChildren() { setIsFinishedParsingChildren(false); }
PseudoElement* pseudoElement(PseudoId) const;
LayoutObject* pseudoElementLayoutObject(PseudoId) const;
virtual bool matchesDefaultPseudoClass() const { return false; }
virtual bool matchesEnabledPseudoClass() const { return false; }
virtual bool matchesReadOnlyPseudoClass() const { return false; }
virtual bool matchesReadWritePseudoClass() const { return false; }
virtual bool matchesValidityPseudoClasses() const { return false; }
bool matches(const String& selectors, ExceptionState&);
Element* closest(const String& selectors, ExceptionState&);
virtual bool shouldAppearIndeterminate() const { return false; }
DOMTokenList& classList();
DOMStringMap& dataset();
virtual bool isDateTimeEditElement() const { return false; }
virtual bool isDateTimeFieldElement() const { return false; }
virtual bool isPickerIndicatorElement() const { return false; }
virtual bool isFormControlElement() const { return false; }
virtual bool isSpinButtonElement() const { return false; }
virtual bool isTextFormControl() const { return false; }
virtual bool isOptionalFormControl() const { return false; }
virtual bool isRequiredFormControl() const { return false; }
virtual bool willValidate() const { return false; }
virtual bool isValidElement() { return false; }
virtual bool isInRange() const { return false; }
virtual bool isOutOfRange() const { return false; }
virtual bool isClearButtonElement() const { return false; }
bool canContainRangeEndPoint() const override { return true; }
// Used for disabled form elements; if true, prevents mouse events from being dispatched
// to event listeners, and prevents DOMActivate events from being sent at all.
virtual bool isDisabledFormControl() const { return false; }
bool hasPendingResources() const { return hasElementFlag(HasPendingResources); }
void setHasPendingResources() { setElementFlag(HasPendingResources); }
void clearHasPendingResources() { clearElementFlag(HasPendingResources); }
virtual void buildPendingResource() { }
void setCustomElementDefinition(V0CustomElementDefinition*);
V0CustomElementDefinition* customElementDefinition() const;
bool containsFullScreenElement() const { return hasElementFlag(ContainsFullScreenElement); }
void setContainsFullScreenElement(bool);
void setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(bool);
bool isInTopLayer() const { return hasElementFlag(IsInTopLayer); }
void setIsInTopLayer(bool);
void requestPointerLock();
bool isSpellCheckingEnabled() const;
// FIXME: public for LayoutTreeBuilder, we shouldn't expose this though.
PassRefPtr<ComputedStyle> styleForLayoutObject();
bool hasID() const;
bool hasClass() const;
const SpaceSplitString& classNames() const;
IntSize savedLayerScrollOffset() const;
void setSavedLayerScrollOffset(const IntSize&);
ElementAnimations* elementAnimations() const;
ElementAnimations& ensureElementAnimations();
bool hasAnimations() const;
void synchronizeAttribute(const AtomicString& localName) const;
MutableStylePropertySet& ensureMutableInlineStyle();
void clearMutableInlineStyleIfEmpty();
void setTabIndex(int);
short tabIndex() const override;
// A compositor proxy is a very limited wrapper around an element. It
// exposes only those properties that are requested at the time the proxy is
// created. In order to know which properties are actually proxied, we
// maintain a count of the number of compositor proxies associated with each
// property.
bool hasCompositorProxy() const;
void incrementCompositorProxiedProperties(uint32_t mutableProperties);
void decrementCompositorProxiedProperties(uint32_t mutableProperties);
uint32_t compositorMutableProperties() const;
void updateFromCompositorMutation(const CompositorMutation&);
// Helpers for V8DOMActivityLogger::logEvent. They call logEvent only if
// the element is inShadowIncludingDocument() and the context is an isolated world.
void logAddElementIfIsolatedWorldAndInDocument(const char element[], const QualifiedName& attr1);
void logAddElementIfIsolatedWorldAndInDocument(const char element[], const QualifiedName& attr1, const QualifiedName& attr2);
void logAddElementIfIsolatedWorldAndInDocument(const char element[], const QualifiedName& attr1, const QualifiedName& attr2, const QualifiedName& attr3);
void logUpdateAttributeIfIsolatedWorldAndInDocument(const char element[], const QualifiedName& attributeName, const AtomicString& oldValue, const AtomicString& newValue);
DECLARE_VIRTUAL_TRACE();
DECLARE_VIRTUAL_TRACE_WRAPPERS();
SpellcheckAttributeState spellcheckAttributeState() const;
NodeIntersectionObserverData* intersectionObserverData() const;
NodeIntersectionObserverData& ensureIntersectionObserverData();
protected:
Element(const QualifiedName& tagName, Document*, ConstructionType);
const ElementData* elementData() const { return m_elementData.get(); }
UniqueElementData& ensureUniqueElementData();
void addPropertyToPresentationAttributeStyle(MutableStylePropertySet*, CSSPropertyID, CSSValueID identifier);
void addPropertyToPresentationAttributeStyle(MutableStylePropertySet*, CSSPropertyID, double value, CSSPrimitiveValue::UnitType);
void addPropertyToPresentationAttributeStyle(MutableStylePropertySet*, CSSPropertyID, const String& value);
void addPropertyToPresentationAttributeStyle(MutableStylePropertySet*, CSSPropertyID, CSSValue*);
InsertionNotificationRequest insertedInto(ContainerNode*) override;
void removedFrom(ContainerNode*) override;
void childrenChanged(const ChildrenChange&) override;
virtual void willRecalcStyle(StyleRecalcChange);
virtual void didRecalcStyle(StyleRecalcChange);
virtual PassRefPtr<ComputedStyle> customStyleForLayoutObject();
virtual bool shouldRegisterAsNamedItem() const { return false; }
virtual bool shouldRegisterAsExtraNamedItem() const { return false; }
bool supportsSpatialNavigationFocus() const;
void clearTabIndexExplicitlyIfNeeded();
void setTabIndexExplicitly(short);
// Subclasses may override this method to affect focusability. This method
// must be called on an up-to-date ComputedStyle, so it may use existence of
// layoutObject and the LayoutObject::style() to reason about focusability.
// However, it must not retrieve layout information like position and size.
// This method cannot be moved to LayoutObject because some focusable nodes
// don't have layoutObjects. e.g., HTMLOptionElement.
// TODO(tkent): Rename this to isFocusableStyle.
virtual bool layoutObjectIsFocusable() const;
// classAttributeChanged() exists to share code between
// parseAttribute (called via setAttribute()) and
// svgAttributeChanged (called when element.className.baseValue is set)
void classAttributeChanged(const AtomicString& newClassString);
static bool attributeValueIsJavaScriptURL(const Attribute&);
PassRefPtr<ComputedStyle> originalStyleForLayoutObject();
Node* insertAdjacent(const String& where, Node* newChild, ExceptionState&);
virtual void parserDidSetAttributes() { }
private:
void scrollLayoutBoxBy(const ScrollToOptions&);
void scrollLayoutBoxTo(const ScrollToOptions&);
void scrollFrameBy(const ScrollToOptions&);
void scrollFrameTo(const ScrollToOptions&);
bool hasElementFlag(ElementFlags mask) const { return hasRareData() && hasElementFlagInternal(mask); }
void setElementFlag(ElementFlags, bool value = true);
void clearElementFlag(ElementFlags);
bool hasElementFlagInternal(ElementFlags) const;
bool isElementNode() const = delete; // This will catch anyone doing an unnecessary check.
bool isDocumentFragment() const = delete; // This will catch anyone doing an unnecessary check.
bool isDocumentNode() const = delete; // This will catch anyone doing an unnecessary check.
void styleAttributeChanged(const AtomicString& newStyleString, AttributeModificationReason);
void updatePresentationAttributeStyle();
void inlineStyleChanged();
PropertySetCSSStyleDeclaration* inlineStyleCSSOMWrapper();
void setInlineStyleFromString(const AtomicString&);
StyleRecalcChange recalcOwnStyle(StyleRecalcChange);
inline void checkForEmptyStyleChange();
void updatePseudoElement(PseudoId, StyleRecalcChange);
bool updateFirstLetter(Element*);
inline void createPseudoElementIfNeeded(PseudoId);
ShadowRoot* shadowRoot() const;
// FIXME: Everyone should allow author shadows.
virtual bool areAuthorShadowsAllowed() const { return true; }
virtual void didAddUserAgentShadowRoot(ShadowRoot&) { }
virtual bool alwaysCreateUserAgentShadowRoot() const { return false; }
enum SynchronizationOfLazyAttribute { NotInSynchronizationOfLazyAttribute = 0, InSynchronizationOfLazyAttribute };
void didAddAttribute(const QualifiedName&, const AtomicString&);
void willModifyAttribute(const QualifiedName&, const AtomicString& oldValue, const AtomicString& newValue);
void didModifyAttribute(const QualifiedName&, const AtomicString& oldValue, const AtomicString& newValue);
void didRemoveAttribute(const QualifiedName&, const AtomicString& oldValue);
void synchronizeAllAttributes() const;
void synchronizeAttribute(const QualifiedName&) const;
void updateId(const AtomicString& oldId, const AtomicString& newId);
void updateId(TreeScope&, const AtomicString& oldId, const AtomicString& newId);
void updateName(const AtomicString& oldName, const AtomicString& newName);
NodeType getNodeType() const final;
bool childTypeAllowed(NodeType) const final;
void setAttributeInternal(size_t index, const QualifiedName&, const AtomicString& value, SynchronizationOfLazyAttribute);
void appendAttributeInternal(const QualifiedName&, const AtomicString& value, SynchronizationOfLazyAttribute);
void removeAttributeInternal(size_t index, SynchronizationOfLazyAttribute);
void attributeChangedFromParserOrByCloning(const QualifiedName&, const AtomicString&, AttributeModificationReason);
#ifndef NDEBUG
void formatForDebugger(char* buffer, unsigned length) const override;
#endif
bool pseudoStyleCacheIsInvalid(const ComputedStyle* currentStyle, ComputedStyle* newStyle);
void cancelFocusAppearanceUpdate();
const ComputedStyle* virtualEnsureComputedStyle(PseudoId pseudoElementSpecifier = PseudoIdNone) override { return ensureComputedStyle(pseudoElementSpecifier); }
inline void updateCallbackSelectors(const ComputedStyle* oldStyle, const ComputedStyle* newStyle);
inline void removeCallbackSelectors();
inline void addCallbackSelectors();
// cloneNode is private so that non-virtual cloneElementWithChildren and cloneElementWithoutChildren
// are used instead.
Node* cloneNode(bool deep) override;
virtual Element* cloneElementWithoutAttributesAndChildren();
QualifiedName m_tagName;
void updateNamedItemRegistration(const AtomicString& oldName, const AtomicString& newName);
void updateExtraNamedItemRegistration(const AtomicString& oldName, const AtomicString& newName);
void createUniqueElementData();
bool shouldInvalidateDistributionWhenAttributeChanged(ElementShadow*, const QualifiedName&, const AtomicString&);
ElementRareData* elementRareData() const;
ElementRareData& ensureElementRareData();
AttrNodeList& ensureAttrNodeList();
void removeAttrNodeList();
void detachAllAttrNodesFromElement();
void detachAttrNodeFromElementWithValue(Attr*, const AtomicString& value);
void detachAttrNodeAtIndex(Attr*, size_t index);
v8::Local<v8::Object> wrapCustomElement(v8::Isolate*, v8::Local<v8::Object> creationContext);
Member<ElementData> m_elementData;
};
DEFINE_NODE_TYPE_CASTS(Element, isElementNode());
template <typename T> bool isElementOfType(const Node&);
template <> inline bool isElementOfType<const Element>(const Node& node) { return node.isElementNode(); }
template <typename T> inline bool isElementOfType(const Element& element) { return isElementOfType<T>(static_cast<const Node&>(element)); }
template <> inline bool isElementOfType<const Element>(const Element&) { return true; }
// Type casting.
template<typename T> inline T& toElement(Node& node)
{
ASSERT_WITH_SECURITY_IMPLICATION(isElementOfType<const T>(node));
return static_cast<T&>(node);
}
template<typename T> inline T* toElement(Node* node)
{
ASSERT_WITH_SECURITY_IMPLICATION(!node || isElementOfType<const T>(*node));
return static_cast<T*>(node);
}
template<typename T> inline const T& toElement(const Node& node)
{
ASSERT_WITH_SECURITY_IMPLICATION(isElementOfType<const T>(node));
return static_cast<const T&>(node);
}
template<typename T> inline const T* toElement(const Node* node)
{
ASSERT_WITH_SECURITY_IMPLICATION(!node || isElementOfType<const T>(*node));
return static_cast<const T*>(node);
}
template<typename T, typename U> inline T* toElement(const RefPtr<U>& node) { return toElement<T>(node.get()); }
inline bool isDisabledFormControl(const Node* node)
{
return node->isElementNode() && toElement(node)->isDisabledFormControl();
}
inline Element* Node::parentElement() const
{
ContainerNode* parent = parentNode();
return parent && parent->isElementNode() ? toElement(parent) : nullptr;
}
inline bool Element::fastHasAttribute(const QualifiedName& name) const
{
#if DCHECK_IS_ON()
DCHECK(fastAttributeLookupAllowed(name));
#endif
return elementData() && elementData()->attributes().findIndex(name) != kNotFound;
}
inline const AtomicString& Element::fastGetAttribute(const QualifiedName& name) const
{
#if DCHECK_IS_ON()
DCHECK(fastAttributeLookupAllowed(name));
#endif
if (elementData()) {
if (const Attribute* attribute = elementData()->attributes().find(name))
return attribute->value();
}
return nullAtom;
}
inline AttributeCollection Element::attributes() const
{
if (!elementData())
return AttributeCollection();
synchronizeAllAttributes();
return elementData()->attributes();
}
inline AttributeCollection Element::attributesWithoutUpdate() const
{
if (!elementData())
return AttributeCollection();
return elementData()->attributes();
}
inline bool Element::hasAttributes() const
{
return !attributes().isEmpty();
}
inline const AtomicString& Element::idForStyleResolution() const
{
DCHECK(hasID());
return elementData()->idForStyleResolution();
}
inline const AtomicString& Element::getIdAttribute() const
{
return hasID() ? fastGetAttribute(HTMLNames::idAttr) : nullAtom;
}
inline const AtomicString& Element::getNameAttribute() const
{
return hasName() ? fastGetAttribute(HTMLNames::nameAttr) : nullAtom;
}
inline const AtomicString& Element::getClassAttribute() const
{
if (!hasClass())
return nullAtom;
if (isSVGElement())
return getAttribute(HTMLNames::classAttr);
return fastGetAttribute(HTMLNames::classAttr);
}
inline void Element::setIdAttribute(const AtomicString& value)
{
setAttribute(HTMLNames::idAttr, value);
}
inline const SpaceSplitString& Element::classNames() const
{
DCHECK(hasClass());
DCHECK(elementData());
return elementData()->classNames();
}
inline bool Element::hasID() const
{
return elementData() && elementData()->hasID();
}
inline bool Element::hasClass() const
{
return elementData() && elementData()->hasClass();
}
inline UniqueElementData& Element::ensureUniqueElementData()
{
if (!elementData() || !elementData()->isUnique())
createUniqueElementData();
return toUniqueElementData(*m_elementData);
}
inline Node::InsertionNotificationRequest Node::insertedInto(ContainerNode* insertionPoint)
{
DCHECK(!childNeedsStyleInvalidation());
DCHECK(!needsStyleInvalidation());
DCHECK(insertionPoint->inShadowIncludingDocument() || insertionPoint->isInShadowTree() || isContainerNode());
if (insertionPoint->inShadowIncludingDocument()) {
setFlag(InDocumentFlag);
insertionPoint->document().incrementNodeCount();
}
if (parentOrShadowHostNode()->isInShadowTree())
setFlag(IsInShadowTreeFlag);
if (childNeedsDistributionRecalc() && !insertionPoint->childNeedsDistributionRecalc())
insertionPoint->markAncestorsWithChildNeedsDistributionRecalc();
if (document().shadowCascadeOrder() == ShadowCascadeOrder::ShadowCascadeV1)
updateAssignmentForInsertedInto(insertionPoint);
return InsertionDone;
}
inline void Node::removedFrom(ContainerNode* insertionPoint)
{
DCHECK(insertionPoint->inShadowIncludingDocument() || isContainerNode() || isInShadowTree());
if (insertionPoint->inShadowIncludingDocument()) {
clearFlag(InDocumentFlag);
insertionPoint->document().decrementNodeCount();
}
if (isInShadowTree() && !treeScope().rootNode().isShadowRoot())
clearFlag(IsInShadowTreeFlag);
if (AXObjectCache* cache = document().existingAXObjectCache())
cache->remove(this);
}
inline void Element::invalidateStyleAttribute()
{
DCHECK(elementData());
elementData()->m_styleAttributeIsDirty = true;
}
inline const StylePropertySet* Element::presentationAttributeStyle()
{
if (!elementData())
return nullptr;
if (elementData()->m_presentationAttributeStyleIsDirty)
updatePresentationAttributeStyle();
// Need to call elementData() again since updatePresentationAttributeStyle()
// might swap it with a UniqueElementData.
return elementData()->presentationAttributeStyle();
}
inline void Element::setTagNameForCreateElementNS(const QualifiedName& tagName)
{
// We expect this method to be called only to reset the prefix.
DCHECK_EQ(tagName.localName(), m_tagName.localName());
DCHECK_EQ(tagName.namespaceURI(), m_tagName.namespaceURI());
m_tagName = tagName;
}
inline AtomicString Element::localNameForSelectorMatching() const
{
if (isHTMLElement() || !document().isHTMLDocument())
return localName();
return localName().lower();
}
inline bool isShadowHost(const Node* node)
{
return node && node->isElementNode() && toElement(node)->shadow();
}
inline bool isShadowHost(const Node& node)
{
return node.isElementNode() && toElement(node).shadow();
}
inline bool isShadowHost(const Element* element)
{
return element && element->shadow();
}
inline bool isShadowHost(const Element& element)
{
return element.shadow();
}
inline bool isAtShadowBoundary(const Element* element)
{
if (!element)
return false;
ContainerNode* parentNode = element->parentNode();
return parentNode && parentNode->isShadowRoot();
}
// These macros do the same as their NODE equivalents but additionally provide a template specialization
// for isElementOfType<>() so that the Traversal<> API works for these Element types.
#define DEFINE_ELEMENT_TYPE_CASTS(thisType, predicate) \
template <> inline bool isElementOfType<const thisType>(const Node& node) { return node.predicate; } \
DEFINE_NODE_TYPE_CASTS(thisType, predicate)
#define DEFINE_ELEMENT_TYPE_CASTS_WITH_FUNCTION(thisType) \
template <> inline bool isElementOfType<const thisType>(const Node& node) { return is##thisType(node); } \
DEFINE_NODE_TYPE_CASTS_WITH_FUNCTION(thisType)
#define DECLARE_ELEMENT_FACTORY_WITH_TAGNAME(T) \
static T* create(const QualifiedName&, Document&)
#define DEFINE_ELEMENT_FACTORY_WITH_TAGNAME(T) \
T* T::create(const QualifiedName& tagName, Document& document) \
{ \
return new T(tagName, document); \
}
} // namespace blink
#endif // Element_h
| Java |
Подробная инструкция по установке:
[http://yupe.ru/docs/install.html](http://yupe.ru/docs/install.html)
Настройка операционной системы (Ubuntu):
[http://yupe.ru/docs/ubuntu.html](http://yupe.ru/docs/ubuntu.html)
После установки
---------------
- [Расскажите нам о новом сайте на Юпи!](http://yupe.ru/contacts). Нам будет очень приятно!
- [Сообщайте об ошибках, замечаниях или предложениях](https://github.com/yupe/yupe/issues)
- Расскажите друзьям о Юпи!
- [Следите за обновлениями в twitter](https://twitter.com/YupeCms)
- [Общайтесь на форуме](http://yupe.ru/talk/)
- [Помогайте проекту](http://yupe.ru/docs/yupe/assistance.project.html)
- [Присылайте pull requests](https://github.com/yupe/yupe/pulls) (патчи)
- Отдыхайте и наслаждайтесь жизнью!
При возникновении проблем [мы](http://amylabs.ru/contact) готовы Вам помочь! | Java |
"""Tools for manipulating of large commutative expressions. """
from __future__ import print_function, division
from sympy.core.add import Add
from sympy.core.compatibility import iterable, is_sequence, SYMPY_INTS
from sympy.core.mul import Mul, _keep_coeff
from sympy.core.power import Pow
from sympy.core.basic import Basic, preorder_traversal
from sympy.core.expr import Expr
from sympy.core.sympify import sympify
from sympy.core.numbers import Rational, Integer, Number, I
from sympy.core.singleton import S
from sympy.core.symbol import Dummy
from sympy.core.coreerrors import NonCommutativeExpression
from sympy.core.containers import Tuple, Dict
from sympy.utilities import default_sort_key
from sympy.utilities.iterables import (common_prefix, common_suffix,
variations, ordered)
from collections import defaultdict
def _isnumber(i):
return isinstance(i, (SYMPY_INTS, float)) or i.is_Number
def decompose_power(expr):
"""
Decompose power into symbolic base and integer exponent.
This is strictly only valid if the exponent from which
the integer is extracted is itself an integer or the
base is positive. These conditions are assumed and not
checked here.
Examples
========
>>> from sympy.core.exprtools import decompose_power
>>> from sympy.abc import x, y
>>> decompose_power(x)
(x, 1)
>>> decompose_power(x**2)
(x, 2)
>>> decompose_power(x**(2*y))
(x**y, 2)
>>> decompose_power(x**(2*y/3))
(x**(y/3), 2)
"""
base, exp = expr.as_base_exp()
if exp.is_Number:
if exp.is_Rational:
if not exp.is_Integer:
base = Pow(base, Rational(1, exp.q))
exp = exp.p
else:
base, exp = expr, 1
else:
exp, tail = exp.as_coeff_Mul(rational=True)
if exp is S.NegativeOne:
base, exp = Pow(base, tail), -1
elif exp is not S.One:
tail = _keep_coeff(Rational(1, exp.q), tail)
base, exp = Pow(base, tail), exp.p
else:
base, exp = expr, 1
return base, exp
class Factors(object):
"""Efficient representation of ``f_1*f_2*...*f_n``."""
__slots__ = ['factors', 'gens']
def __init__(self, factors=None): # Factors
"""Initialize Factors from dict or expr.
Examples
========
>>> from sympy.core.exprtools import Factors
>>> from sympy.abc import x
>>> from sympy import I
>>> e = 2*x**3
>>> Factors(e)
Factors({2: 1, x: 3})
>>> Factors(e.as_powers_dict())
Factors({2: 1, x: 3})
>>> f = _
>>> f.factors # underlying dictionary
{2: 1, x: 3}
>>> f.gens # base of each factor
frozenset([2, x])
>>> Factors(0)
Factors({0: 1})
>>> Factors(I)
Factors({I: 1})
Notes
=====
Although a dictionary can be passed, only minimal checking is
performed: powers of -1 and I are made canonical.
"""
if isinstance(factors, (SYMPY_INTS, float)):
factors = S(factors)
if isinstance(factors, Factors):
factors = factors.factors.copy()
elif factors is None or factors is S.One:
factors = {}
elif factors is S.Zero or factors == 0:
factors = {S.Zero: S.One}
elif isinstance(factors, Number):
n = factors
factors = {}
if n < 0:
factors[S.NegativeOne] = S.One
n = -n
if n is not S.One:
if n.is_Float or n.is_Integer or n is S.Infinity:
factors[n] = S.One
elif n.is_Rational:
# since we're processing Numbers, the denominator is
# stored with a negative exponent; all other factors
# are left .
if n.p != 1:
factors[Integer(n.p)] = S.One
factors[Integer(n.q)] = S.NegativeOne
else:
raise ValueError('Expected Float|Rational|Integer, not %s' % n)
elif isinstance(factors, Basic) and not factors.args:
factors = {factors: S.One}
elif isinstance(factors, Expr):
c, nc = factors.args_cnc()
i = c.count(I)
for _ in range(i):
c.remove(I)
factors = dict(Mul._from_args(c).as_powers_dict())
if i:
factors[I] = S.One*i
if nc:
factors[Mul(*nc, evaluate=False)] = S.One
else:
factors = factors.copy() # /!\ should be dict-like
# tidy up -/+1 and I exponents if Rational
handle = []
for k in factors:
if k is I or k in (-1, 1):
handle.append(k)
if handle:
i1 = S.One
for k in handle:
if not _isnumber(factors[k]):
continue
i1 *= k**factors.pop(k)
if i1 is not S.One:
for a in i1.args if i1.is_Mul else [i1]: # at worst, -1.0*I*(-1)**e
if a is S.NegativeOne:
factors[a] = S.One
elif a is I:
factors[I] = S.One
elif a.is_Pow:
if S.NegativeOne not in factors:
factors[S.NegativeOne] = S.Zero
factors[S.NegativeOne] += a.exp
elif a == 1:
factors[a] = S.One
elif a == -1:
factors[-a] = S.One
factors[S.NegativeOne] = S.One
else:
raise ValueError('unexpected factor in i1: %s' % a)
self.factors = factors
try:
self.gens = frozenset(factors.keys())
except AttributeError:
raise TypeError('expecting Expr or dictionary')
def __hash__(self): # Factors
keys = tuple(ordered(self.factors.keys()))
values = [self.factors[k] for k in keys]
return hash((keys, values))
def __repr__(self): # Factors
return "Factors({%s})" % ', '.join(
['%s: %s' % (k, v) for k, v in ordered(self.factors.items())])
@property
def is_zero(self): # Factors
"""
>>> from sympy.core.exprtools import Factors
>>> Factors(0).is_zero
True
"""
f = self.factors
return len(f) == 1 and S.Zero in f
@property
def is_one(self): # Factors
"""
>>> from sympy.core.exprtools import Factors
>>> Factors(1).is_one
True
"""
return not self.factors
def as_expr(self): # Factors
"""Return the underlying expression.
Examples
========
>>> from sympy.core.exprtools import Factors
>>> from sympy.abc import x, y
>>> Factors((x*y**2).as_powers_dict()).as_expr()
x*y**2
"""
args = []
for factor, exp in self.factors.items():
if exp != 1:
b, e = factor.as_base_exp()
if isinstance(exp, int):
e = _keep_coeff(Integer(exp), e)
elif isinstance(exp, Rational):
e = _keep_coeff(exp, e)
else:
e *= exp
args.append(b**e)
else:
args.append(factor)
return Mul(*args)
def mul(self, other): # Factors
"""Return Factors of ``self * other``.
Examples
========
>>> from sympy.core.exprtools import Factors
>>> from sympy.abc import x, y, z
>>> a = Factors((x*y**2).as_powers_dict())
>>> b = Factors((x*y/z).as_powers_dict())
>>> a.mul(b)
Factors({x: 2, y: 3, z: -1})
>>> a*b
Factors({x: 2, y: 3, z: -1})
"""
if not isinstance(other, Factors):
other = Factors(other)
if any(f.is_zero for f in (self, other)):
return Factors(S.Zero)
factors = dict(self.factors)
for factor, exp in other.factors.items():
if factor in factors:
exp = factors[factor] + exp
if not exp:
del factors[factor]
continue
factors[factor] = exp
return Factors(factors)
def normal(self, other):
"""Return ``self`` and ``other`` with ``gcd`` removed from each.
The only differences between this and method ``div`` is that this
is 1) optimized for the case when there are few factors in common and
2) this does not raise an error if ``other`` is zero.
See Also
========
div
"""
if not isinstance(other, Factors):
other = Factors(other)
if other.is_zero:
return (Factors(), Factors(S.Zero))
if self.is_zero:
return (Factors(S.Zero), Factors())
self_factors = dict(self.factors)
other_factors = dict(other.factors)
for factor, self_exp in self.factors.items():
try:
other_exp = other.factors[factor]
except KeyError:
continue
exp = self_exp - other_exp
if not exp:
del self_factors[factor]
del other_factors[factor]
elif _isnumber(exp):
if exp > 0:
self_factors[factor] = exp
del other_factors[factor]
else:
del self_factors[factor]
other_factors[factor] = -exp
else:
r = self_exp.extract_additively(other_exp)
if r is not None:
if r:
self_factors[factor] = r
del other_factors[factor]
else: # should be handled already
del self_factors[factor]
del other_factors[factor]
else:
sc, sa = self_exp.as_coeff_Add()
if sc:
oc, oa = other_exp.as_coeff_Add()
diff = sc - oc
if diff > 0:
self_factors[factor] -= oc
other_exp = oa
elif diff < 0:
self_factors[factor] -= sc
other_factors[factor] -= sc
other_exp = oa - diff
else:
self_factors[factor] = sa
other_exp = oa
if other_exp:
other_factors[factor] = other_exp
else:
del other_factors[factor]
return Factors(self_factors), Factors(other_factors)
def div(self, other): # Factors
"""Return ``self`` and ``other`` with ``gcd`` removed from each.
This is optimized for the case when there are many factors in common.
Examples
========
>>> from sympy.core.exprtools import Factors
>>> from sympy.abc import x, y, z
>>> from sympy import S
>>> a = Factors((x*y**2).as_powers_dict())
>>> a.div(a)
(Factors({}), Factors({}))
>>> a.div(x*z)
(Factors({y: 2}), Factors({z: 1}))
The ``/`` operator only gives ``quo``:
>>> a/x
Factors({y: 2})
Factors treats its factors as though they are all in the numerator, so
if you violate this assumption the results will be correct but will
not strictly correspond to the numerator and denominator of the ratio:
>>> a.div(x/z)
(Factors({y: 2}), Factors({z: -1}))
Factors is also naive about bases: it does not attempt any denesting
of Rational-base terms, for example the following does not become
2**(2*x)/2.
>>> Factors(2**(2*x + 2)).div(S(8))
(Factors({2: 2*x + 2}), Factors({8: 1}))
factor_terms can clean up such Rational-bases powers:
>>> from sympy.core.exprtools import factor_terms
>>> n, d = Factors(2**(2*x + 2)).div(S(8))
>>> n.as_expr()/d.as_expr()
2**(2*x + 2)/8
>>> factor_terms(_)
2**(2*x)/2
"""
quo, rem = dict(self.factors), {}
if not isinstance(other, Factors):
other = Factors(other)
if other.is_zero:
raise ZeroDivisionError
if self.is_zero:
return (Factors(S.Zero), Factors())
for factor, exp in other.factors.items():
if factor in quo:
d = quo[factor] - exp
if _isnumber(d):
if d <= 0:
del quo[factor]
if d >= 0:
if d:
quo[factor] = d
continue
exp = -d
else:
r = quo[factor].extract_additively(exp)
if r is not None:
if r:
quo[factor] = r
else: # should be handled already
del quo[factor]
else:
other_exp = exp
sc, sa = quo[factor].as_coeff_Add()
if sc:
oc, oa = other_exp.as_coeff_Add()
diff = sc - oc
if diff > 0:
quo[factor] -= oc
other_exp = oa
elif diff < 0:
quo[factor] -= sc
other_exp = oa - diff
else:
quo[factor] = sa
other_exp = oa
if other_exp:
rem[factor] = other_exp
else:
assert factor not in rem
continue
rem[factor] = exp
return Factors(quo), Factors(rem)
def quo(self, other): # Factors
"""Return numerator Factor of ``self / other``.
Examples
========
>>> from sympy.core.exprtools import Factors
>>> from sympy.abc import x, y, z
>>> a = Factors((x*y**2).as_powers_dict())
>>> b = Factors((x*y/z).as_powers_dict())
>>> a.quo(b) # same as a/b
Factors({y: 1})
"""
return self.div(other)[0]
def rem(self, other): # Factors
"""Return denominator Factors of ``self / other``.
Examples
========
>>> from sympy.core.exprtools import Factors
>>> from sympy.abc import x, y, z
>>> a = Factors((x*y**2).as_powers_dict())
>>> b = Factors((x*y/z).as_powers_dict())
>>> a.rem(b)
Factors({z: -1})
>>> a.rem(a)
Factors({})
"""
return self.div(other)[1]
def pow(self, other): # Factors
"""Return self raised to a non-negative integer power.
Examples
========
>>> from sympy.core.exprtools import Factors
>>> from sympy.abc import x, y
>>> a = Factors((x*y**2).as_powers_dict())
>>> a**2
Factors({x: 2, y: 4})
"""
if isinstance(other, Factors):
other = other.as_expr()
if other.is_Integer:
other = int(other)
if isinstance(other, SYMPY_INTS) and other >= 0:
factors = {}
if other:
for factor, exp in self.factors.items():
factors[factor] = exp*other
return Factors(factors)
else:
raise ValueError("expected non-negative integer, got %s" % other)
def gcd(self, other): # Factors
"""Return Factors of ``gcd(self, other)``. The keys are
the intersection of factors with the minimum exponent for
each factor.
Examples
========
>>> from sympy.core.exprtools import Factors
>>> from sympy.abc import x, y, z
>>> a = Factors((x*y**2).as_powers_dict())
>>> b = Factors((x*y/z).as_powers_dict())
>>> a.gcd(b)
Factors({x: 1, y: 1})
"""
if not isinstance(other, Factors):
other = Factors(other)
if other.is_zero:
return Factors(self.factors)
factors = {}
for factor, exp in self.factors.items():
if factor in other.factors:
exp = min(exp, other.factors[factor])
factors[factor] = exp
return Factors(factors)
def lcm(self, other): # Factors
"""Return Factors of ``lcm(self, other)`` which are
the union of factors with the maximum exponent for
each factor.
Examples
========
>>> from sympy.core.exprtools import Factors
>>> from sympy.abc import x, y, z
>>> a = Factors((x*y**2).as_powers_dict())
>>> b = Factors((x*y/z).as_powers_dict())
>>> a.lcm(b)
Factors({x: 1, y: 2, z: -1})
"""
if not isinstance(other, Factors):
other = Factors(other)
if any(f.is_zero for f in (self, other)):
return Factors(S.Zero)
factors = dict(self.factors)
for factor, exp in other.factors.items():
if factor in factors:
exp = max(exp, factors[factor])
factors[factor] = exp
return Factors(factors)
def __mul__(self, other): # Factors
return self.mul(other)
def __divmod__(self, other): # Factors
return self.div(other)
def __div__(self, other): # Factors
return self.quo(other)
__truediv__ = __div__
def __mod__(self, other): # Factors
return self.rem(other)
def __pow__(self, other): # Factors
return self.pow(other)
def __eq__(self, other): # Factors
if not isinstance(other, Factors):
other = Factors(other)
return self.factors == other.factors
def __ne__(self, other): # Factors
return not self.__eq__(other)
class Term(object):
"""Efficient representation of ``coeff*(numer/denom)``. """
__slots__ = ['coeff', 'numer', 'denom']
def __init__(self, term, numer=None, denom=None): # Term
if numer is None and denom is None:
if not term.is_commutative:
raise NonCommutativeExpression(
'commutative expression expected')
coeff, factors = term.as_coeff_mul()
numer, denom = defaultdict(int), defaultdict(int)
for factor in factors:
base, exp = decompose_power(factor)
if base.is_Add:
cont, base = base.primitive()
coeff *= cont**exp
if exp > 0:
numer[base] += exp
else:
denom[base] += -exp
numer = Factors(numer)
denom = Factors(denom)
else:
coeff = term
if numer is None:
numer = Factors()
if denom is None:
denom = Factors()
self.coeff = coeff
self.numer = numer
self.denom = denom
def __hash__(self): # Term
return hash((self.coeff, self.numer, self.denom))
def __repr__(self): # Term
return "Term(%s, %s, %s)" % (self.coeff, self.numer, self.denom)
def as_expr(self): # Term
return self.coeff*(self.numer.as_expr()/self.denom.as_expr())
def mul(self, other): # Term
coeff = self.coeff*other.coeff
numer = self.numer.mul(other.numer)
denom = self.denom.mul(other.denom)
numer, denom = numer.normal(denom)
return Term(coeff, numer, denom)
def inv(self): # Term
return Term(1/self.coeff, self.denom, self.numer)
def quo(self, other): # Term
return self.mul(other.inv())
def pow(self, other): # Term
if other < 0:
return self.inv().pow(-other)
else:
return Term(self.coeff ** other,
self.numer.pow(other),
self.denom.pow(other))
def gcd(self, other): # Term
return Term(self.coeff.gcd(other.coeff),
self.numer.gcd(other.numer),
self.denom.gcd(other.denom))
def lcm(self, other): # Term
return Term(self.coeff.lcm(other.coeff),
self.numer.lcm(other.numer),
self.denom.lcm(other.denom))
def __mul__(self, other): # Term
if isinstance(other, Term):
return self.mul(other)
else:
return NotImplemented
def __div__(self, other): # Term
if isinstance(other, Term):
return self.quo(other)
else:
return NotImplemented
__truediv__ = __div__
def __pow__(self, other): # Term
if isinstance(other, SYMPY_INTS):
return self.pow(other)
else:
return NotImplemented
def __eq__(self, other): # Term
return (self.coeff == other.coeff and
self.numer == other.numer and
self.denom == other.denom)
def __ne__(self, other): # Term
return not self.__eq__(other)
def _gcd_terms(terms, isprimitive=False, fraction=True):
"""Helper function for :func:`gcd_terms`.
If ``isprimitive`` is True then the call to primitive
for an Add will be skipped. This is useful when the
content has already been extrated.
If ``fraction`` is True then the expression will appear over a common
denominator, the lcm of all term denominators.
"""
if isinstance(terms, Basic) and not isinstance(terms, Tuple):
terms = Add.make_args(terms)
terms = list(map(Term, [t for t in terms if t]))
# there is some simplification that may happen if we leave this
# here rather than duplicate it before the mapping of Term onto
# the terms
if len(terms) == 0:
return S.Zero, S.Zero, S.One
if len(terms) == 1:
cont = terms[0].coeff
numer = terms[0].numer.as_expr()
denom = terms[0].denom.as_expr()
else:
cont = terms[0]
for term in terms[1:]:
cont = cont.gcd(term)
for i, term in enumerate(terms):
terms[i] = term.quo(cont)
if fraction:
denom = terms[0].denom
for term in terms[1:]:
denom = denom.lcm(term.denom)
numers = []
for term in terms:
numer = term.numer.mul(denom.quo(term.denom))
numers.append(term.coeff*numer.as_expr())
else:
numers = [t.as_expr() for t in terms]
denom = Term(S(1)).numer
cont = cont.as_expr()
numer = Add(*numers)
denom = denom.as_expr()
if not isprimitive and numer.is_Add:
_cont, numer = numer.primitive()
cont *= _cont
return cont, numer, denom
def gcd_terms(terms, isprimitive=False, clear=True, fraction=True):
"""Compute the GCD of ``terms`` and put them together.
``terms`` can be an expression or a non-Basic sequence of expressions
which will be handled as though they are terms from a sum.
If ``isprimitive`` is True the _gcd_terms will not run the primitive
method on the terms.
``clear`` controls the removal of integers from the denominator of an Add
expression. When True (default), all numerical denominator will be cleared;
when False the denominators will be cleared only if all terms had numerical
denominators other than 1.
``fraction``, when True (default), will put the expression over a common
denominator.
Examples
========
>>> from sympy.core import gcd_terms
>>> from sympy.abc import x, y
>>> gcd_terms((x + 1)**2*y + (x + 1)*y**2)
y*(x + 1)*(x + y + 1)
>>> gcd_terms(x/2 + 1)
(x + 2)/2
>>> gcd_terms(x/2 + 1, clear=False)
x/2 + 1
>>> gcd_terms(x/2 + y/2, clear=False)
(x + y)/2
>>> gcd_terms(x/2 + 1/x)
(x**2 + 2)/(2*x)
>>> gcd_terms(x/2 + 1/x, fraction=False)
(x + 2/x)/2
>>> gcd_terms(x/2 + 1/x, fraction=False, clear=False)
x/2 + 1/x
>>> gcd_terms(x/2/y + 1/x/y)
(x**2 + 2)/(2*x*y)
>>> gcd_terms(x/2/y + 1/x/y, fraction=False, clear=False)
(x + 2/x)/(2*y)
The ``clear`` flag was ignored in this case because the returned
expression was a rational expression, not a simple sum.
See Also
========
factor_terms, sympy.polys.polytools.terms_gcd
"""
def mask(terms):
"""replace nc portions of each term with a unique Dummy symbols
and return the replacements to restore them"""
args = [(a, []) if a.is_commutative else a.args_cnc() for a in terms]
reps = []
for i, (c, nc) in enumerate(args):
if nc:
nc = Mul._from_args(nc)
d = Dummy()
reps.append((d, nc))
c.append(d)
args[i] = Mul._from_args(c)
else:
args[i] = c
return args, dict(reps)
isadd = isinstance(terms, Add)
addlike = isadd or not isinstance(terms, Basic) and \
is_sequence(terms, include=set) and \
not isinstance(terms, Dict)
if addlike:
if isadd: # i.e. an Add
terms = list(terms.args)
else:
terms = sympify(terms)
terms, reps = mask(terms)
cont, numer, denom = _gcd_terms(terms, isprimitive, fraction)
numer = numer.xreplace(reps)
coeff, factors = cont.as_coeff_Mul()
return _keep_coeff(coeff, factors*numer/denom, clear=clear)
if not isinstance(terms, Basic):
return terms
if terms.is_Atom:
return terms
if terms.is_Mul:
c, args = terms.as_coeff_mul()
return _keep_coeff(c, Mul(*[gcd_terms(i, isprimitive, clear, fraction)
for i in args]), clear=clear)
def handle(a):
# don't treat internal args like terms of an Add
if not isinstance(a, Expr):
if isinstance(a, Basic):
return a.func(*[handle(i) for i in a.args])
return type(a)([handle(i) for i in a])
return gcd_terms(a, isprimitive, clear, fraction)
if isinstance(terms, Dict):
return Dict(*[(k, handle(v)) for k, v in terms.args])
return terms.func(*[handle(i) for i in terms.args])
def factor_terms(expr, radical=False, clear=False, fraction=False, sign=True):
"""Remove common factors from terms in all arguments without
changing the underlying structure of the expr. No expansion or
simplification (and no processing of non-commutatives) is performed.
If radical=True then a radical common to all terms will be factored
out of any Add sub-expressions of the expr.
If clear=False (default) then coefficients will not be separated
from a single Add if they can be distributed to leave one or more
terms with integer coefficients.
If fraction=True (default is False) then a common denominator will be
constructed for the expression.
If sign=True (default) then even if the only factor in common is a -1,
it will be factored out of the expression.
Examples
========
>>> from sympy import factor_terms, Symbol
>>> from sympy.abc import x, y
>>> factor_terms(x + x*(2 + 4*y)**3)
x*(8*(2*y + 1)**3 + 1)
>>> A = Symbol('A', commutative=False)
>>> factor_terms(x*A + x*A + x*y*A)
x*(y*A + 2*A)
When ``clear`` is False, a rational will only be factored out of an
Add expression if all terms of the Add have coefficients that are
fractions:
>>> factor_terms(x/2 + 1, clear=False)
x/2 + 1
>>> factor_terms(x/2 + 1, clear=True)
(x + 2)/2
This only applies when there is a single Add that the coefficient
multiplies:
>>> factor_terms(x*y/2 + y, clear=True)
y*(x + 2)/2
>>> factor_terms(x*y/2 + y, clear=False) == _
True
If a -1 is all that can be factored out, to *not* factor it out, the
flag ``sign`` must be False:
>>> factor_terms(-x - y)
-(x + y)
>>> factor_terms(-x - y, sign=False)
-x - y
>>> factor_terms(-2*x - 2*y, sign=False)
-2*(x + y)
See Also
========
gcd_terms, sympy.polys.polytools.terms_gcd
"""
from sympy.simplify.simplify import bottom_up
def do(expr):
is_iterable = iterable(expr)
if not isinstance(expr, Basic) or expr.is_Atom:
if is_iterable:
return type(expr)([do(i) for i in expr])
return expr
if expr.is_Pow or expr.is_Function or \
is_iterable or not hasattr(expr, 'args_cnc'):
args = expr.args
newargs = tuple([do(i) for i in args])
if newargs == args:
return expr
return expr.func(*newargs)
cont, p = expr.as_content_primitive(radical=radical)
if p.is_Add:
list_args = [do(a) for a in Add.make_args(p)]
# get a common negative (if there) which gcd_terms does not remove
if all(a.as_coeff_Mul()[0] < 0 for a in list_args):
cont = -cont
list_args = [-a for a in list_args]
# watch out for exp(-(x+2)) which gcd_terms will change to exp(-x-2)
special = {}
for i, a in enumerate(list_args):
b, e = a.as_base_exp()
if e.is_Mul and e != Mul(*e.args):
list_args[i] = Dummy()
special[list_args[i]] = a
# rebuild p not worrying about the order which gcd_terms will fix
p = Add._from_args(list_args)
p = gcd_terms(p,
isprimitive=True,
clear=clear,
fraction=fraction).xreplace(special)
elif p.args:
p = p.func(
*[do(a) for a in p.args])
rv = _keep_coeff(cont, p, clear=clear, sign=sign)
return rv
expr = sympify(expr)
return do(expr)
def _mask_nc(eq, name=None):
"""
Return ``eq`` with non-commutative objects replaced with Dummy
symbols. A dictionary that can be used to restore the original
values is returned: if it is None, the expression is noncommutative
and cannot be made commutative. The third value returned is a list
of any non-commutative symbols that appear in the returned equation.
``name``, if given, is the name that will be used with numered Dummy
variables that will replace the non-commutative objects and is mainly
used for doctesting purposes.
Notes
=====
All non-commutative objects other than Symbols are replaced with
a non-commutative Symbol. Identical objects will be identified
by identical symbols.
If there is only 1 non-commutative object in an expression it will
be replaced with a commutative symbol. Otherwise, the non-commutative
entities are retained and the calling routine should handle
replacements in this case since some care must be taken to keep
track of the ordering of symbols when they occur within Muls.
Examples
========
>>> from sympy.physics.secondquant import Commutator, NO, F, Fd
>>> from sympy import symbols, Mul
>>> from sympy.core.exprtools import _mask_nc
>>> from sympy.abc import x, y
>>> A, B, C = symbols('A,B,C', commutative=False)
One nc-symbol:
>>> _mask_nc(A**2 - x**2, 'd')
(_d0**2 - x**2, {_d0: A}, [])
Multiple nc-symbols:
>>> _mask_nc(A**2 - B**2, 'd')
(A**2 - B**2, None, [A, B])
An nc-object with nc-symbols but no others outside of it:
>>> _mask_nc(1 + x*Commutator(A, B), 'd')
(_d0*x + 1, {_d0: Commutator(A, B)}, [])
>>> _mask_nc(NO(Fd(x)*F(y)), 'd')
(_d0, {_d0: NO(CreateFermion(x)*AnnihilateFermion(y))}, [])
Multiple nc-objects:
>>> eq = x*Commutator(A, B) + x*Commutator(A, C)*Commutator(A, B)
>>> _mask_nc(eq, 'd')
(x*_d0 + x*_d1*_d0, {_d0: Commutator(A, B), _d1: Commutator(A, C)}, [_d0, _d1])
Multiple nc-objects and nc-symbols:
>>> eq = A*Commutator(A, B) + B*Commutator(A, C)
>>> _mask_nc(eq, 'd')
(A*_d0 + B*_d1, {_d0: Commutator(A, B), _d1: Commutator(A, C)}, [_d0, _d1, A, B])
If there is an object that:
- doesn't contain nc-symbols
- but has arguments which derive from Basic, not Expr
- and doesn't define an _eval_is_commutative routine
then it will give False (or None?) for the is_commutative test. Such
objects are also removed by this routine:
>>> from sympy import Basic
>>> eq = (1 + Mul(Basic(), Basic(), evaluate=False))
>>> eq.is_commutative
False
>>> _mask_nc(eq, 'd')
(_d0**2 + 1, {_d0: Basic()}, [])
"""
name = name or 'mask'
# Make Dummy() append sequential numbers to the name
def numbered_names():
i = 0
while True:
yield name + str(i)
i += 1
names = numbered_names()
def Dummy(*args, **kwargs):
from sympy import Dummy
return Dummy(next(names), *args, **kwargs)
expr = eq
if expr.is_commutative:
return eq, {}, []
# identify nc-objects; symbols and other
rep = []
nc_obj = set()
nc_syms = set()
pot = preorder_traversal(expr, keys=default_sort_key)
for i, a in enumerate(pot):
if any(a == r[0] for r in rep):
pot.skip()
elif not a.is_commutative:
if a.is_Symbol:
nc_syms.add(a)
elif not (a.is_Add or a.is_Mul or a.is_Pow):
if all(s.is_commutative for s in a.free_symbols):
rep.append((a, Dummy()))
else:
nc_obj.add(a)
pot.skip()
# If there is only one nc symbol or object, it can be factored regularly
# but polys is going to complain, so replace it with a Dummy.
if len(nc_obj) == 1 and not nc_syms:
rep.append((nc_obj.pop(), Dummy()))
elif len(nc_syms) == 1 and not nc_obj:
rep.append((nc_syms.pop(), Dummy()))
# Any remaining nc-objects will be replaced with an nc-Dummy and
# identified as an nc-Symbol to watch out for
nc_obj = sorted(nc_obj, key=default_sort_key)
for n in nc_obj:
nc = Dummy(commutative=False)
rep.append((n, nc))
nc_syms.add(nc)
expr = expr.subs(rep)
nc_syms = list(nc_syms)
nc_syms.sort(key=default_sort_key)
return expr, dict([(v, k) for k, v in rep]) or None, nc_syms
def factor_nc(expr):
"""Return the factored form of ``expr`` while handling non-commutative
expressions.
**examples**
>>> from sympy.core.exprtools import factor_nc
>>> from sympy import Symbol
>>> from sympy.abc import x
>>> A = Symbol('A', commutative=False)
>>> B = Symbol('B', commutative=False)
>>> factor_nc((x**2 + 2*A*x + A**2).expand())
(x + A)**2
>>> factor_nc(((x + A)*(x + B)).expand())
(x + A)*(x + B)
"""
from sympy.simplify.simplify import powsimp
from sympy.polys import gcd, factor
def _pemexpand(expr):
"Expand with the minimal set of hints necessary to check the result."
return expr.expand(deep=True, mul=True, power_exp=True,
power_base=False, basic=False, multinomial=True, log=False)
expr = sympify(expr)
if not isinstance(expr, Expr) or not expr.args:
return expr
if not expr.is_Add:
return expr.func(*[factor_nc(a) for a in expr.args])
expr, rep, nc_symbols = _mask_nc(expr)
if rep:
return factor(expr).subs(rep)
else:
args = [a.args_cnc() for a in Add.make_args(expr)]
c = g = l = r = S.One
hit = False
# find any commutative gcd term
for i, a in enumerate(args):
if i == 0:
c = Mul._from_args(a[0])
elif a[0]:
c = gcd(c, Mul._from_args(a[0]))
else:
c = S.One
if c is not S.One:
hit = True
c, g = c.as_coeff_Mul()
if g is not S.One:
for i, (cc, _) in enumerate(args):
cc = list(Mul.make_args(Mul._from_args(list(cc))/g))
args[i][0] = cc
for i, (cc, _) in enumerate(args):
cc[0] = cc[0]/c
args[i][0] = cc
# find any noncommutative common prefix
for i, a in enumerate(args):
if i == 0:
n = a[1][:]
else:
n = common_prefix(n, a[1])
if not n:
# is there a power that can be extracted?
if not args[0][1]:
break
b, e = args[0][1][0].as_base_exp()
ok = False
if e.is_Integer:
for t in args:
if not t[1]:
break
bt, et = t[1][0].as_base_exp()
if et.is_Integer and bt == b:
e = min(e, et)
else:
break
else:
ok = hit = True
l = b**e
il = b**-e
for i, a in enumerate(args):
args[i][1][0] = il*args[i][1][0]
break
if not ok:
break
else:
hit = True
lenn = len(n)
l = Mul(*n)
for i, a in enumerate(args):
args[i][1] = args[i][1][lenn:]
# find any noncommutative common suffix
for i, a in enumerate(args):
if i == 0:
n = a[1][:]
else:
n = common_suffix(n, a[1])
if not n:
# is there a power that can be extracted?
if not args[0][1]:
break
b, e = args[0][1][-1].as_base_exp()
ok = False
if e.is_Integer:
for t in args:
if not t[1]:
break
bt, et = t[1][-1].as_base_exp()
if et.is_Integer and bt == b:
e = min(e, et)
else:
break
else:
ok = hit = True
r = b**e
il = b**-e
for i, a in enumerate(args):
args[i][1][-1] = args[i][1][-1]*il
break
if not ok:
break
else:
hit = True
lenn = len(n)
r = Mul(*n)
for i, a in enumerate(args):
args[i][1] = a[1][:len(a[1]) - lenn]
if hit:
mid = Add(*[Mul(*cc)*Mul(*nc) for cc, nc in args])
else:
mid = expr
# sort the symbols so the Dummys would appear in the same
# order as the original symbols, otherwise you may introduce
# a factor of -1, e.g. A**2 - B**2) -- {A:y, B:x} --> y**2 - x**2
# and the former factors into two terms, (A - B)*(A + B) while the
# latter factors into 3 terms, (-1)*(x - y)*(x + y)
rep1 = [(n, Dummy()) for n in sorted(nc_symbols, key=default_sort_key)]
unrep1 = [(v, k) for k, v in rep1]
unrep1.reverse()
new_mid, r2, _ = _mask_nc(mid.subs(rep1))
new_mid = powsimp(factor(new_mid))
new_mid = new_mid.subs(r2).subs(unrep1)
if new_mid.is_Pow:
return _keep_coeff(c, g*l*new_mid*r)
if new_mid.is_Mul:
# XXX TODO there should be a way to inspect what order the terms
# must be in and just select the plausible ordering without
# checking permutations
cfac = []
ncfac = []
for f in new_mid.args:
if f.is_commutative:
cfac.append(f)
else:
b, e = f.as_base_exp()
if e.is_Integer:
ncfac.extend([b]*e)
else:
ncfac.append(f)
pre_mid = g*Mul(*cfac)*l
target = _pemexpand(expr/c)
for s in variations(ncfac, len(ncfac)):
ok = pre_mid*Mul(*s)*r
if _pemexpand(ok) == target:
return _keep_coeff(c, ok)
# mid was an Add that didn't factor successfully
return _keep_coeff(c, g*l*mid*r)
| Java |
/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include <stdexcept>
#include "mitkTestingMacros.h"
#include <mitkITKImageImport.h>
#include <mitkImageAccessByItk.h>
#define TestImageType(type, dim) \
MITK_TEST_CONDITION(typeid(type) == typeid(TPixel) && dim == VDimension, \
"Checking for correct type itk::Image<" #type "," #dim ">")
#define TestVectorImageType(type, dim) \
MITK_TEST_CONDITION(typeid(type) == typeid(TPixel) && dim == VDimension && \
typeid(itk::VariableLengthVector<type>) == typeid(typename ImageType::PixelType), \
"Checking for correct type itk::VectorImage<" #type "," #dim ">")
class AccessByItkTest
{
public:
typedef AccessByItkTest Self;
typedef itk::Image<int, 2> IntImage2D;
typedef itk::Image<int, 3> IntImage3D;
typedef itk::Image<float, 2> FloatImage2D;
typedef itk::Image<float, 3> FloatImage3D;
typedef itk::VectorImage<int, 3> IntVectorImage3D;
enum EImageType
{
Unknown = 0,
Int2D,
Int3D,
Float2D,
Float3D
};
void testAccessByItk()
{
mitk::Image::Pointer mitkIntImage2D = createMitkImage<IntImage2D>();
mitk::Image::ConstPointer mitkIntImage3D(createMitkImage<IntImage3D>());
mitk::Image::ConstPointer mitkFloatImage2D(createMitkImage<FloatImage2D>());
mitk::Image::Pointer mitkFloatImage3D = createMitkImage<FloatImage3D>();
AccessByItk(mitkIntImage2D, AccessItkImage);
AccessByItk(mitkIntImage3D, AccessItkImage);
AccessByItk(mitkFloatImage2D, AccessItkImage);
AccessByItk(mitkFloatImage3D, AccessItkImage);
AccessByItk_n(mitkIntImage2D, AccessItkImage, (Int2D, 2));
AccessByItk_n(mitkIntImage3D, AccessItkImage, (Int3D, 2));
AccessByItk_n(mitkFloatImage2D, AccessItkImage, (Float2D, 2));
AccessByItk_n(mitkFloatImage3D, AccessItkImage, (Float3D, 2));
mitk::Image::Pointer mitkIntVectorImage3D = createMitkImage<IntVectorImage3D>(2);
// Test for wrong pixel type (the AccessByItk macro multi-plexes integral
// types only by default)
MITK_TEST_FOR_EXCEPTION_BEGIN(const mitk::AccessByItkException &)
AccessByItk(mitkIntVectorImage3D, AccessItkImage);
MITK_TEST_FOR_EXCEPTION_END(const mitk::AccessByItkException &)
// Test for correct handling of vector images
AccessVectorPixelTypeByItk(mitkIntVectorImage3D, AccessItkImage);
AccessVectorPixelTypeByItk_n(mitkIntVectorImage3D, AccessItkImage, (Int3D, 2));
}
void testAccessFixedDimensionByItk()
{
mitk::Image::Pointer mitkIntImage2D = createMitkImage<IntImage2D>();
mitk::Image::ConstPointer mitkIntImage3D(createMitkImage<IntImage3D>());
mitk::Image::ConstPointer mitkFloatImage2D(createMitkImage<FloatImage2D>());
mitk::Image::Pointer mitkFloatImage3D = createMitkImage<FloatImage3D>();
AccessFixedDimensionByItk(mitkIntImage2D, AccessItkImage, 2);
AccessFixedDimensionByItk(mitkIntImage3D, AccessItkImage, 3);
AccessFixedDimensionByItk(mitkFloatImage2D, AccessItkImage, 2);
AccessFixedDimensionByItk(mitkFloatImage3D, AccessItkImage, 3);
AccessFixedDimensionByItk_n(mitkIntImage2D, AccessItkImage, 2, (Int2D, 2));
AccessFixedDimensionByItk_n(mitkIntImage3D, AccessItkImage, 3, (Int3D, 2));
AccessFixedDimensionByItk_n(mitkFloatImage2D, AccessItkImage, 2, (Float2D, 2));
AccessFixedDimensionByItk_n(mitkFloatImage3D, AccessItkImage, 3, (Float3D, 2));
// Test for wrong dimension
MITK_TEST_FOR_EXCEPTION_BEGIN(const mitk::AccessByItkException &)
AccessFixedDimensionByItk(mitkFloatImage3D, AccessItkImage, 2);
MITK_TEST_FOR_EXCEPTION_END(const mitk::AccessByItkException &)
MITK_TEST_FOR_EXCEPTION_BEGIN(const mitk::AccessByItkException &)
AccessFixedDimensionByItk_n(mitkFloatImage3D, AccessItkImage, 2, (Float3D, 2));
MITK_TEST_FOR_EXCEPTION_END(const mitk::AccessByItkException &)
}
void testAccessFixedPixelTypeByItk()
{
mitk::Image::Pointer mitkIntImage2D = createMitkImage<IntImage2D>();
mitk::Image::ConstPointer mitkIntImage3D(createMitkImage<IntImage3D>());
mitk::Image::ConstPointer mitkFloatImage2D(createMitkImage<FloatImage2D>());
mitk::Image::Pointer mitkFloatImage3D = createMitkImage<FloatImage3D>();
AccessFixedPixelTypeByItk(mitkIntImage2D, AccessItkImage, (int)(float));
AccessFixedPixelTypeByItk(mitkIntImage3D, AccessItkImage, (int)(float));
AccessFixedPixelTypeByItk(mitkFloatImage2D, AccessItkImage, (int)(float));
AccessFixedPixelTypeByItk(mitkFloatImage3D, AccessItkImage, (int)(float));
AccessFixedPixelTypeByItk_n(mitkIntImage2D, AccessItkImage, (int)(float), (Int2D, 2));
AccessFixedPixelTypeByItk_n(mitkIntImage3D, AccessItkImage, (int)(float), (Int3D, 2));
AccessFixedPixelTypeByItk_n(mitkFloatImage2D, AccessItkImage, (int)(float), (Float2D, 2));
AccessFixedPixelTypeByItk_n(mitkFloatImage3D, AccessItkImage, (int)(float), (Float3D, 2));
// Test for wrong pixel type
MITK_TEST_FOR_EXCEPTION_BEGIN(const mitk::AccessByItkException &)
AccessFixedPixelTypeByItk(mitkFloatImage3D, AccessItkImage, (int));
MITK_TEST_FOR_EXCEPTION_END(const mitk::AccessByItkException &)
MITK_TEST_FOR_EXCEPTION_BEGIN(const mitk::AccessByItkException &)
AccessFixedPixelTypeByItk_n(mitkFloatImage3D, AccessItkImage, (int), (Float3D, 2));
MITK_TEST_FOR_EXCEPTION_END(const mitk::AccessByItkException &)
}
void testAccessFixedTypeByItk()
{
mitk::Image::Pointer mitkIntImage2D = createMitkImage<IntImage2D>();
mitk::Image::ConstPointer mitkIntImage3D(createMitkImage<IntImage3D>());
mitk::Image::ConstPointer mitkFloatImage2D(createMitkImage<FloatImage2D>());
mitk::Image::Pointer mitkFloatImage3D = createMitkImage<FloatImage3D>();
AccessFixedTypeByItk(mitkIntImage2D, AccessItkImage, (int)(float), (2)(3));
AccessFixedTypeByItk(mitkIntImage3D, AccessItkImage, (int)(float), (2)(3));
AccessFixedTypeByItk(mitkFloatImage2D, AccessItkImage, (int)(float), (2)(3));
AccessFixedTypeByItk(mitkFloatImage3D, AccessItkImage, (int)(float), (2)(3));
AccessFixedTypeByItk_n(mitkIntImage2D, AccessItkImage, (int)(float), (2)(3), (Int2D, 2));
AccessFixedTypeByItk_n(mitkIntImage3D, AccessItkImage, (int)(float), (2)(3), (Int3D, 2));
AccessFixedTypeByItk_n(mitkFloatImage2D, AccessItkImage, (int)(float), (2)(3), (Float2D, 2));
AccessFixedTypeByItk_n(mitkFloatImage3D, AccessItkImage, (int)(float), (2)(3), (Float3D, 2));
// Test for wrong dimension
MITK_TEST_FOR_EXCEPTION_BEGIN(const mitk::AccessByItkException &)
AccessFixedTypeByItk(mitkFloatImage3D, AccessItkImage, (float), (2));
MITK_TEST_FOR_EXCEPTION_END(const mitk::AccessByItkException &)
MITK_TEST_FOR_EXCEPTION_BEGIN(const mitk::AccessByItkException &)
AccessFixedTypeByItk_n(mitkFloatImage3D, AccessItkImage, (float), (2), (Float3D, 2));
MITK_TEST_FOR_EXCEPTION_END(const mitk::AccessByItkException &)
// Test for wrong pixel type
MITK_TEST_FOR_EXCEPTION_BEGIN(const mitk::AccessByItkException &)
AccessFixedTypeByItk(mitkFloatImage3D, AccessItkImage, (int), (3));
MITK_TEST_FOR_EXCEPTION_END(const mitk::AccessByItkException &)
MITK_TEST_FOR_EXCEPTION_BEGIN(const mitk::AccessByItkException &)
AccessFixedTypeByItk_n(mitkFloatImage3D, AccessItkImage, (int), (3), (Float3D, 2));
MITK_TEST_FOR_EXCEPTION_END(const mitk::AccessByItkException &)
}
void testAccessTwoImagesFixedDimensionByItk()
{
mitk::Image::Pointer mitkIntImage2D = createMitkImage<IntImage2D>();
mitk::Image::ConstPointer mitkFloatImage2D(createMitkImage<FloatImage2D>());
AccessTwoImagesFixedDimensionByItk(mitkIntImage2D, mitkFloatImage2D, AccessTwoItkImages, 2);
}
template <typename TPixel, unsigned int VDimension>
void AccessItkImage(const itk::Image<TPixel, VDimension> *,
EImageType param1 = Unknown,
int param2 = 0,
int param3 = 0)
{
switch (param1)
{
case Int2D:
TestImageType(int, 2) break;
case Int3D:
TestImageType(int, 3) break;
case Float2D:
TestImageType(float, 2) break;
case Float3D:
TestImageType(float, 3) break;
default:
break;
}
if (param2)
{
MITK_TEST_CONDITION(param2 == 2, "Checking for correct second parameter")
}
if (param3)
{
MITK_TEST_CONDITION(param3 == 3, "Checking for correct third parameter")
}
}
template <typename TPixel, unsigned int VDimension>
void AccessItkImage(itk::VectorImage<TPixel, VDimension> *,
EImageType param1 = Unknown,
int param2 = 0,
int param3 = 0)
{
typedef itk::VectorImage<TPixel, VDimension> ImageType;
switch (param1)
{
case Int2D:
TestVectorImageType(int, 2) break;
case Int3D:
TestVectorImageType(int, 3) break;
case Float2D:
TestVectorImageType(float, 2) break;
case Float3D:
TestVectorImageType(float, 3) break;
default:
break;
}
if (param2)
{
MITK_TEST_CONDITION(param2 == 2, "Checking for correct second parameter")
}
if (param3)
{
MITK_TEST_CONDITION(param3 == 3, "Checking for correct third parameter")
}
}
private:
template <typename TPixel1, unsigned int VDimension1, typename TPixel2, unsigned int VDimension2>
void AccessTwoItkImages(itk::Image<TPixel1, VDimension1> * /*itkImage1*/,
itk::Image<TPixel2, VDimension2> * /*itkImage2*/)
{
if (!(typeid(int) == typeid(TPixel1) && typeid(float) == typeid(TPixel2) && VDimension1 == 2 && VDimension2 == 2))
{
throw std::runtime_error("Image type mismatch");
}
}
template <typename ImageType>
mitk::Image::Pointer createMitkImage()
{
typename ImageType::Pointer itkImage = ImageType::New();
typename ImageType::IndexType start;
start.Fill(0);
typename ImageType::SizeType size;
size.Fill(3);
typename ImageType::RegionType region;
region.SetSize(size);
region.SetIndex(start);
itkImage->SetRegions(region);
itkImage->Allocate();
return mitk::GrabItkImageMemory(itkImage);
}
template <typename ImageType>
mitk::Image::Pointer createMitkImage(std::size_t vectorLength)
{
typename ImageType::Pointer itkImage = ImageType::New();
typename ImageType::IndexType start;
start.Fill(0);
typename ImageType::SizeType size;
size.Fill(3);
typename ImageType::RegionType region;
region.SetSize(size);
region.SetIndex(start);
itkImage->SetRegions(region);
itkImage->SetVectorLength(vectorLength);
itkImage->Allocate();
return mitk::GrabItkImageMemory(itkImage);
}
};
int mitkAccessByItkTest(int /*argc*/, char * /*argv*/ [])
{
MITK_TEST_BEGIN("AccessByItk")
AccessByItkTest accessTest;
MITK_TEST_OUTPUT(<< "Testing AccessByItk macro")
accessTest.testAccessByItk();
MITK_TEST_OUTPUT(<< "Testing AccessFixedDimensionByItk macro")
accessTest.testAccessFixedDimensionByItk();
MITK_TEST_OUTPUT(<< "Testing AccessFixedTypeByItk macro")
accessTest.testAccessFixedTypeByItk();
MITK_TEST_OUTPUT(<< "Testing AccessFixedPixelTypeByItk macro")
accessTest.testAccessFixedPixelTypeByItk();
MITK_TEST_OUTPUT(<< "Testing AccessTwoImagesFixedDimensionByItk macro")
accessTest.testAccessTwoImagesFixedDimensionByItk();
MITK_TEST_END()
}
| Java |
/**
* OpenAL cross platform audio library
* Copyright (C) 1999-2007 by authors.
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library 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.
* Or go to http://www.gnu.org/copyleft/lgpl.html
*/
#include "config.h"
#include <stdlib.h>
#include "alMain.h"
#include "alu.h"
#include "alFilter.h"
#include "alThunk.h"
#include "alError.h"
static void InitFilterParams(ALfilter *filter, ALenum type);
AL_API ALvoid AL_APIENTRY alGenFilters(ALsizei n, ALuint *filters)
{
ALCcontext *Context;
ALsizei cur = 0;
Context = GetContextRef();
if(!Context) return;
al_try
{
ALCdevice *device = Context->Device;
ALenum err;
CHECK_VALUE(Context, n >= 0);
for(cur = 0;cur < n;cur++)
{
ALfilter *filter = calloc(1, sizeof(ALfilter));
if(!filter)
{
alDeleteFilters(cur, filters);
al_throwerr(Context, AL_OUT_OF_MEMORY);
}
InitFilterParams(filter, AL_FILTER_NULL);
err = NewThunkEntry(&filter->id);
if(err == AL_NO_ERROR)
err = InsertUIntMapEntry(&device->FilterMap, filter->id, filter);
if(err != AL_NO_ERROR)
{
FreeThunkEntry(filter->id);
memset(filter, 0, sizeof(ALfilter));
free(filter);
alDeleteFilters(cur, filters);
al_throwerr(Context, err);
}
filters[cur] = filter->id;
}
}
al_endtry;
ALCcontext_DecRef(Context);
}
AL_API ALvoid AL_APIENTRY alDeleteFilters(ALsizei n, const ALuint *filters)
{
ALCcontext *Context;
ALfilter *Filter;
ALsizei i;
Context = GetContextRef();
if(!Context) return;
al_try
{
ALCdevice *device = Context->Device;
CHECK_VALUE(Context, n >= 0);
for(i = 0;i < n;i++)
{
if(filters[i] && LookupFilter(device, filters[i]) == NULL)
al_throwerr(Context, AL_INVALID_NAME);
}
for(i = 0;i < n;i++)
{
if((Filter=RemoveFilter(device, filters[i])) == NULL)
continue;
FreeThunkEntry(Filter->id);
memset(Filter, 0, sizeof(*Filter));
free(Filter);
}
}
al_endtry;
ALCcontext_DecRef(Context);
}
AL_API ALboolean AL_APIENTRY alIsFilter(ALuint filter)
{
ALCcontext *Context;
ALboolean result;
Context = GetContextRef();
if(!Context) return AL_FALSE;
result = ((!filter || LookupFilter(Context->Device, filter)) ?
AL_TRUE : AL_FALSE);
ALCcontext_DecRef(Context);
return result;
}
AL_API ALvoid AL_APIENTRY alFilteri(ALuint filter, ALenum param, ALint value)
{
ALCcontext *Context;
ALCdevice *Device;
ALfilter *ALFilter;
Context = GetContextRef();
if(!Context) return;
Device = Context->Device;
if((ALFilter=LookupFilter(Device, filter)) == NULL)
alSetError(Context, AL_INVALID_NAME);
else
{
if(param == AL_FILTER_TYPE)
{
if(value == AL_FILTER_NULL || value == AL_FILTER_LOWPASS)
InitFilterParams(ALFilter, value);
else
alSetError(Context, AL_INVALID_VALUE);
}
else
{
/* Call the appropriate handler */
ALfilter_SetParami(ALFilter, Context, param, value);
}
}
ALCcontext_DecRef(Context);
}
AL_API ALvoid AL_APIENTRY alFilteriv(ALuint filter, ALenum param, const ALint *values)
{
ALCcontext *Context;
ALCdevice *Device;
ALfilter *ALFilter;
switch(param)
{
case AL_FILTER_TYPE:
alFilteri(filter, param, values[0]);
return;
}
Context = GetContextRef();
if(!Context) return;
Device = Context->Device;
if((ALFilter=LookupFilter(Device, filter)) == NULL)
alSetError(Context, AL_INVALID_NAME);
else
{
/* Call the appropriate handler */
ALfilter_SetParamiv(ALFilter, Context, param, values);
}
ALCcontext_DecRef(Context);
}
AL_API ALvoid AL_APIENTRY alFilterf(ALuint filter, ALenum param, ALfloat value)
{
ALCcontext *Context;
ALCdevice *Device;
ALfilter *ALFilter;
Context = GetContextRef();
if(!Context) return;
Device = Context->Device;
if((ALFilter=LookupFilter(Device, filter)) == NULL)
alSetError(Context, AL_INVALID_NAME);
else
{
/* Call the appropriate handler */
ALfilter_SetParamf(ALFilter, Context, param, value);
}
ALCcontext_DecRef(Context);
}
AL_API ALvoid AL_APIENTRY alFilterfv(ALuint filter, ALenum param, const ALfloat *values)
{
ALCcontext *Context;
ALCdevice *Device;
ALfilter *ALFilter;
Context = GetContextRef();
if(!Context) return;
Device = Context->Device;
if((ALFilter=LookupFilter(Device, filter)) == NULL)
alSetError(Context, AL_INVALID_NAME);
else
{
/* Call the appropriate handler */
ALfilter_SetParamfv(ALFilter, Context, param, values);
}
ALCcontext_DecRef(Context);
}
AL_API ALvoid AL_APIENTRY alGetFilteri(ALuint filter, ALenum param, ALint *value)
{
ALCcontext *Context;
ALCdevice *Device;
ALfilter *ALFilter;
Context = GetContextRef();
if(!Context) return;
Device = Context->Device;
if((ALFilter=LookupFilter(Device, filter)) == NULL)
alSetError(Context, AL_INVALID_NAME);
else
{
if(param == AL_FILTER_TYPE)
*value = ALFilter->type;
else
{
/* Call the appropriate handler */
ALfilter_GetParami(ALFilter, Context, param, value);
}
}
ALCcontext_DecRef(Context);
}
AL_API ALvoid AL_APIENTRY alGetFilteriv(ALuint filter, ALenum param, ALint *values)
{
ALCcontext *Context;
ALCdevice *Device;
ALfilter *ALFilter;
switch(param)
{
case AL_FILTER_TYPE:
alGetFilteri(filter, param, values);
return;
}
Context = GetContextRef();
if(!Context) return;
Device = Context->Device;
if((ALFilter=LookupFilter(Device, filter)) == NULL)
alSetError(Context, AL_INVALID_NAME);
else
{
/* Call the appropriate handler */
ALfilter_GetParamiv(ALFilter, Context, param, values);
}
ALCcontext_DecRef(Context);
}
AL_API ALvoid AL_APIENTRY alGetFilterf(ALuint filter, ALenum param, ALfloat *value)
{
ALCcontext *Context;
ALCdevice *Device;
ALfilter *ALFilter;
Context = GetContextRef();
if(!Context) return;
Device = Context->Device;
if((ALFilter=LookupFilter(Device, filter)) == NULL)
alSetError(Context, AL_INVALID_NAME);
else
{
/* Call the appropriate handler */
ALfilter_GetParamf(ALFilter, Context, param, value);
}
ALCcontext_DecRef(Context);
}
AL_API ALvoid AL_APIENTRY alGetFilterfv(ALuint filter, ALenum param, ALfloat *values)
{
ALCcontext *Context;
ALCdevice *Device;
ALfilter *ALFilter;
Context = GetContextRef();
if(!Context) return;
Device = Context->Device;
if((ALFilter=LookupFilter(Device, filter)) == NULL)
alSetError(Context, AL_INVALID_NAME);
else
{
/* Call the appropriate handler */
ALfilter_GetParamfv(ALFilter, Context, param, values);
}
ALCcontext_DecRef(Context);
}
void ALfilterState_clear(ALfilterState *filter)
{
filter->x[0] = 0.0f;
filter->x[1] = 0.0f;
filter->y[0] = 0.0f;
filter->y[1] = 0.0f;
}
void ALfilterState_setParams(ALfilterState *filter, ALfilterType type, ALfloat gain, ALfloat freq_scale, ALfloat bandwidth)
{
ALfloat alpha;
ALfloat w0;
// Limit gain to -100dB
gain = maxf(gain, 0.00001f);
w0 = 2.0f*F_PI * freq_scale;
/* Calculate filter coefficients depending on filter type */
switch(type)
{
case ALfilterType_HighShelf:
alpha = sinf(w0) / 2.0f * sqrtf((gain + 1.0f/gain) *
(1.0f/0.75f - 1.0f) + 2.0f);
filter->b[0] = gain * ((gain + 1.0f) +
(gain - 1.0f) * cosf(w0) +
2.0f * sqrtf(gain) * alpha);
filter->b[1] = -2.0f * gain * ((gain - 1.0f) +
(gain + 1.0f) * cosf(w0));
filter->b[2] = gain * ((gain + 1.0f) +
(gain - 1.0f) * cosf(w0) -
2.0f * sqrtf(gain) * alpha);
filter->a[0] = (gain + 1.0f) -
(gain - 1.0f) * cosf(w0) +
2.0f * sqrtf(gain) * alpha;
filter->a[1] = 2.0f * ((gain - 1.0f) -
(gain + 1.0f) * cosf(w0));
filter->a[2] = (gain + 1.0f) -
(gain - 1.0f) * cosf(w0) -
2.0f * sqrtf(gain) * alpha;
break;
case ALfilterType_LowShelf:
alpha = sinf(w0) / 2.0f * sqrtf((gain + 1.0f / gain) *
(1.0f / 0.75f - 1.0f) + 2.0f);
filter->b[0] = gain * ((gain + 1.0f) -
(gain - 1.0f) * cosf(w0) +
2.0f * sqrtf(gain) * alpha);
filter->b[1] = 2.0f * gain * ((gain - 1.0f) -
(gain + 1.0f) * cosf(w0));
filter->b[2] = gain * ((gain + 1.0f) -
(gain - 1.0f) * cosf(w0) -
2.0f * sqrtf(gain) * alpha);
filter->a[0] = (gain + 1.0f) +
(gain - 1.0f) * cosf(w0) +
2.0f * sqrtf(gain) * alpha;
filter->a[1] = -2.0f * ((gain - 1.0f) +
(gain + 1.0f) * cosf(w0));
filter->a[2] = (gain + 1.0f) +
(gain - 1.0f) * cosf(w0) -
2.0f * sqrtf(gain) * alpha;
break;
case ALfilterType_Peaking:
alpha = sinf(w0) * sinhf(logf(2.0f) / 2.0f * bandwidth * w0 / sinf(w0));
filter->b[0] = 1.0f + alpha * gain;
filter->b[1] = -2.0f * cosf(w0);
filter->b[2] = 1.0f - alpha * gain;
filter->a[0] = 1.0f + alpha / gain;
filter->a[1] = -2.0f * cosf(w0);
filter->a[2] = 1.0f - alpha / gain;
break;
case ALfilterType_LowPass:
alpha = sinf(w0) * sinhf(logf(2.0f) / 2.0f * bandwidth * w0 / sinf(w0));
filter->b[0] = (1.0f - cosf(w0)) / 2.0f;
filter->b[1] = 1.0f - cosf(w0);
filter->b[2] = (1.0f - cosf(w0)) / 2.0f;
filter->a[0] = 1.0f + alpha;
filter->a[1] = -2.0f * cosf(w0);
filter->a[2] = 1.0f - alpha;
break;
case ALfilterType_BandPass:
alpha = sinf(w0) * sinhf(logf(2.0f) / 2.0f * bandwidth * w0 / sinf(w0));
filter->b[0] = alpha;
filter->b[1] = 0;
filter->b[2] = -alpha;
filter->a[0] = 1.0f + alpha;
filter->a[1] = -2.0f * cosf(w0);
filter->a[2] = 1.0f - alpha;
break;
}
filter->b[2] /= filter->a[0];
filter->b[1] /= filter->a[0];
filter->b[0] /= filter->a[0];
filter->a[2] /= filter->a[0];
filter->a[1] /= filter->a[0];
filter->a[0] /= filter->a[0];
}
static void lp_SetParami(ALfilter *filter, ALCcontext *context, ALenum param, ALint val)
{ SET_ERROR_AND_RETURN(context, AL_INVALID_ENUM); (void)filter;(void)param;(void)val; }
static void lp_SetParamiv(ALfilter *filter, ALCcontext *context, ALenum param, const ALint *vals)
{ SET_ERROR_AND_RETURN(context, AL_INVALID_ENUM); (void)filter;(void)param;(void)vals; }
static void lp_SetParamf(ALfilter *filter, ALCcontext *context, ALenum param, ALfloat val)
{
switch(param)
{
case AL_LOWPASS_GAIN:
if(!(val >= AL_LOWPASS_MIN_GAIN && val <= AL_LOWPASS_MAX_GAIN))
SET_ERROR_AND_RETURN(context, AL_INVALID_VALUE);
filter->Gain = val;
break;
case AL_LOWPASS_GAINHF:
if(!(val >= AL_LOWPASS_MIN_GAINHF && val <= AL_LOWPASS_MAX_GAINHF))
SET_ERROR_AND_RETURN(context, AL_INVALID_VALUE);
filter->GainHF = val;
break;
default:
SET_ERROR_AND_RETURN(context, AL_INVALID_ENUM);
}
}
static void lp_SetParamfv(ALfilter *filter, ALCcontext *context, ALenum param, const ALfloat *vals)
{
lp_SetParamf(filter, context, param, vals[0]);
}
static void lp_GetParami(ALfilter *filter, ALCcontext *context, ALenum param, ALint *val)
{ SET_ERROR_AND_RETURN(context, AL_INVALID_ENUM); (void)filter;(void)param;(void)val; }
static void lp_GetParamiv(ALfilter *filter, ALCcontext *context, ALenum param, ALint *vals)
{ SET_ERROR_AND_RETURN(context, AL_INVALID_ENUM); (void)filter;(void)param;(void)vals; }
static void lp_GetParamf(ALfilter *filter, ALCcontext *context, ALenum param, ALfloat *val)
{
switch(param)
{
case AL_LOWPASS_GAIN:
*val = filter->Gain;
break;
case AL_LOWPASS_GAINHF:
*val = filter->GainHF;
break;
default:
SET_ERROR_AND_RETURN(context, AL_INVALID_ENUM);
}
}
static void lp_GetParamfv(ALfilter *filter, ALCcontext *context, ALenum param, ALfloat *vals)
{
lp_GetParamf(filter, context, param, vals);
}
static void null_SetParami(ALfilter *filter, ALCcontext *context, ALenum param, ALint val)
{ SET_ERROR_AND_RETURN(context, AL_INVALID_ENUM); (void)filter;(void)param;(void)val; }
static void null_SetParamiv(ALfilter *filter, ALCcontext *context, ALenum param, const ALint *vals)
{ SET_ERROR_AND_RETURN(context, AL_INVALID_ENUM); (void)filter;(void)param;(void)vals; }
static void null_SetParamf(ALfilter *filter, ALCcontext *context, ALenum param, ALfloat val)
{ SET_ERROR_AND_RETURN(context, AL_INVALID_ENUM); (void)filter;(void)param;(void)val; }
static void null_SetParamfv(ALfilter *filter, ALCcontext *context, ALenum param, const ALfloat *vals)
{ SET_ERROR_AND_RETURN(context, AL_INVALID_ENUM); (void)filter;(void)param;(void)vals; }
static void null_GetParami(ALfilter *filter, ALCcontext *context, ALenum param, ALint *val)
{ SET_ERROR_AND_RETURN(context, AL_INVALID_ENUM); (void)filter;(void)param;(void)val; }
static void null_GetParamiv(ALfilter *filter, ALCcontext *context, ALenum param, ALint *vals)
{ SET_ERROR_AND_RETURN(context, AL_INVALID_ENUM); (void)filter;(void)param;(void)vals; }
static void null_GetParamf(ALfilter *filter, ALCcontext *context, ALenum param, ALfloat *val)
{ SET_ERROR_AND_RETURN(context, AL_INVALID_ENUM); (void)filter;(void)param;(void)val; }
static void null_GetParamfv(ALfilter *filter, ALCcontext *context, ALenum param, ALfloat *vals)
{ SET_ERROR_AND_RETURN(context, AL_INVALID_ENUM); (void)filter;(void)param;(void)vals; }
ALvoid ReleaseALFilters(ALCdevice *device)
{
ALsizei i;
for(i = 0;i < device->FilterMap.size;i++)
{
ALfilter *temp = device->FilterMap.array[i].value;
device->FilterMap.array[i].value = NULL;
// Release filter structure
FreeThunkEntry(temp->id);
memset(temp, 0, sizeof(ALfilter));
free(temp);
}
}
static void InitFilterParams(ALfilter *filter, ALenum type)
{
if(type == AL_FILTER_LOWPASS)
{
filter->Gain = AL_LOWPASS_DEFAULT_GAIN;
filter->GainHF = AL_LOWPASS_DEFAULT_GAINHF;
filter->SetParami = lp_SetParami;
filter->SetParamiv = lp_SetParamiv;
filter->SetParamf = lp_SetParamf;
filter->SetParamfv = lp_SetParamfv;
filter->GetParami = lp_GetParami;
filter->GetParamiv = lp_GetParamiv;
filter->GetParamf = lp_GetParamf;
filter->GetParamfv = lp_GetParamfv;
}
else
{
filter->SetParami = null_SetParami;
filter->SetParamiv = null_SetParamiv;
filter->SetParamf = null_SetParamf;
filter->SetParamfv = null_SetParamfv;
filter->GetParami = null_GetParami;
filter->GetParamiv = null_GetParamiv;
filter->GetParamf = null_GetParamf;
filter->GetParamfv = null_GetParamfv;
}
filter->type = type;
}
| Java |
# Author: Prabhu Ramachandran <prabhu [at] aero . iitb . ac . in>
# Copyright (c) 2008, Enthought, Inc.
# License: BSD Style.
# Enthought library imports.
from tvtk.tools.tvtk_doc import TVTKFilterChooser, TVTK_FILTERS
# Local imports.
from mayavi.filters.filter_base import FilterBase
from mayavi.core.common import handle_children_state, error
from mayavi.core.pipeline_info import PipelineInfo
################################################################################
# `UserDefined` class.
################################################################################
class UserDefined(FilterBase):
"""
This filter lets the user define their own filter
dynamically/interactively. It is like `FilterBase` but allows a
user to specify the class without writing any code.
"""
# The version of this class. Used for persistence.
__version__ = 0
input_info = PipelineInfo(datasets=['any'],
attribute_types=['any'],
attributes=['any'])
output_info = PipelineInfo(datasets=['any'],
attribute_types=['any'],
attributes=['any'])
######################################################################
# `object` interface.
######################################################################
def __set_pure_state__(self, state):
# Create and set the filter.
children = [f for f in [self.filter] if f is not None]
handle_children_state(children, [state.filter])
self.filter = children[0]
self.update_pipeline()
# Restore our state.
super(UserDefined, self).__set_pure_state__(state)
######################################################################
# `UserDefined` interface.
######################################################################
def setup_filter(self):
"""Setup the filter if none has been set or check it if it
already has been."""
obj = self.filter
if not self._check_object(obj):
if obj is not None:
cname = obj.__class__.__name__
error('Invalid filter %s chosen! Try again!'%cname)
obj = self._choose_filter()
self.filter = obj
######################################################################
# Non-public interface.
######################################################################
def _choose_filter(self):
chooser = TVTKFilterChooser()
chooser.edit_traits(kind='livemodal')
obj = chooser.object
if obj is None:
error('Invalid filter chosen! Try again!')
return obj
def _check_object(self, obj):
if obj is None:
return False
if obj.__class__.__name__ in TVTK_FILTERS:
return True
return False
def _filter_changed(self, old, new):
self.name = 'UserDefined:%s'%new.__class__.__name__
super(UserDefined, self)._filter_changed(old, new)
| Java |
<!doctype html>
<title>ProgressEvent constructor</title>
<script src=../../../../resources/testharness.js></script>
<script src=../../../../resources/testharnessreport.js></script>
<div id=log></div>
<script>
test(function() {
var ev = new ProgressEvent("test")
assert_equals(ev.type, "test")
assert_equals(ev.target, null)
assert_equals(ev.currentTarget, null)
assert_equals(ev.eventPhase, Event.NONE)
assert_equals(ev.bubbles, false)
assert_equals(ev.cancelable, false)
assert_equals(ev.defaultPrevented, false)
assert_equals(ev.isTrusted, false)
assert_true(ev.timeStamp > 0)
assert_true("initEvent" in ev)
}, "Default event values.")
test(function() {
var e = document.createEvent("ProgressEvent");
var eProto = Object.getPrototypeOf(e);
assert_equals(eProto, ProgressEvent.prototype);
}, "document.createEvent() should work with ProgressEvent.");
</script>
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.