code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30
values | license stringclasses 15
values | size int64 3 1.01M |
|---|---|---|---|---|---|
package com.fincatto.documentofiscal.nfe400.utils.qrcode20;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.commons.lang3.StringUtils;
import com.fincatto.documentofiscal.DFAmbiente;
import com.fincatto.documentofiscal.nfe.NFeConfig;
import com.fincatto.documentofiscal.nfe400.classes.nota.NFNota;
/**
* Classe abstrata para a implementação da geração do QRCode 2.0.
*
* Deve ser feita a implementação para emissão normal (1) e para contingência offline (9).
*/
public abstract class NFGeraQRCode20 {
public static final String VERSAO_QRCODE = "2";
protected final NFNota nota;
protected final NFeConfig config;
public NFGeraQRCode20(final NFNota nota, final NFeConfig config) {
this.nota = nota;
this.config = config;
}
/**
* Método responsável pela geração do qrcode.
*
* @return URL para consulta da nota via qrcode20.
* @throws NoSuchAlgorithmException
*/
public abstract String getQRCode() throws NoSuchAlgorithmException;
public String getUrlQRCode(){
String url = this.config.getAmbiente().equals(DFAmbiente.PRODUCAO) ? this.nota.getInfo().getIdentificacao().getUf().getQrCodeProducao() : this.nota.getInfo().getIdentificacao().getUf().getQrCodeHomologacao();
if (StringUtils.isBlank(url)) {
throw new IllegalArgumentException("URL para consulta do QRCode nao informada para uf " + this.nota.getInfo().getIdentificacao().getUf() + "!");
}
if (StringUtils.isBlank(this.config.getCodigoSegurancaContribuinte())) {
throw new IllegalArgumentException("CSC nao informado nas configuracoes!");
}
if ((this.config.getCodigoSegurancaContribuinteID() == null) || (this.config.getCodigoSegurancaContribuinteID() == 0)) {
throw new IllegalArgumentException("IdCSC nao informado nas configuracoes!");
}
return url;
}
public static String createHash(final String campos, final String csc) throws NoSuchAlgorithmException {
return sha1(campos + csc);
}
public static String toHex(final String arg) {
return String.format("%040x", new BigInteger(1, arg.getBytes(Charset.forName("UTF-8"))));
}
public static String sha1(final String input) throws NoSuchAlgorithmException {
final StringBuilder sb = new StringBuilder();
for (final byte element : MessageDigest.getInstance("SHA1").digest(input.getBytes(Charset.forName("UTF-8")))) {
sb.append(Integer.toString((element & 0xff) + 0x100, 16).substring(1));
}
return sb.toString().toUpperCase();
}
public String urlConsultaChaveAcesso(){
return this.config.getAmbiente().equals(DFAmbiente.PRODUCAO) ? this.nota.getInfo().getIdentificacao().getUf().getConsultaChaveAcessoProducao() : this.nota.getInfo().getIdentificacao().getUf().getConsultaChaveAcessoHomologacao();
}
} | fincatto/nfe | src/main/java/com/fincatto/documentofiscal/nfe400/utils/qrcode20/NFGeraQRCode20.java | Java | apache-2.0 | 3,031 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.builder.component.dsl;
import javax.annotation.Generated;
import org.apache.camel.Component;
import org.apache.camel.builder.component.AbstractComponentBuilder;
import org.apache.camel.builder.component.ComponentBuilder;
import org.apache.camel.component.mina.MinaComponent;
/**
* Socket level networking using TCP or UDP with Apache Mina 2.x.
*
* Generated by camel-package-maven-plugin - do not edit this file!
*/
@Generated("org.apache.camel.maven.packaging.ComponentDslMojo")
public interface MinaComponentBuilderFactory {
/**
* Mina (camel-mina)
* Socket level networking using TCP or UDP with Apache Mina 2.x.
*
* Category: networking,tcp,udp
* Since: 2.10
* Maven coordinates: org.apache.camel:camel-mina
*
* @return the dsl builder
*/
static MinaComponentBuilder mina() {
return new MinaComponentBuilderImpl();
}
/**
* Builder for the Mina component.
*/
interface MinaComponentBuilder extends ComponentBuilder<MinaComponent> {
/**
* Whether or not to disconnect(close) from Mina session right after
* use. Can be used for both consumer and producer.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: common
*
* @param disconnect the value to set
* @return the dsl builder
*/
default MinaComponentBuilder disconnect(boolean disconnect) {
doSetProperty("disconnect", disconnect);
return this;
}
/**
* You can enable the Apache MINA logging filter. Apache MINA uses slf4j
* logging at INFO level to log all input and output.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: common
*
* @param minaLogger the value to set
* @return the dsl builder
*/
default MinaComponentBuilder minaLogger(boolean minaLogger) {
doSetProperty("minaLogger", minaLogger);
return this;
}
/**
* Setting to set endpoint as one-way or request-response.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: common
*
* @param sync the value to set
* @return the dsl builder
*/
default MinaComponentBuilder sync(boolean sync) {
doSetProperty("sync", sync);
return this;
}
/**
* You can configure the timeout that specifies how long to wait for a
* response from a remote server. The timeout unit is in milliseconds,
* so 60000 is 60 seconds.
*
* The option is a: <code>long</code> type.
*
* Default: 30000
* Group: common
*
* @param timeout the value to set
* @return the dsl builder
*/
default MinaComponentBuilder timeout(long timeout) {
doSetProperty("timeout", timeout);
return this;
}
/**
* Maximum amount of time it should take to send data to the MINA
* session. Default is 10000 milliseconds.
*
* The option is a: <code>long</code> type.
*
* Default: 10000
* Group: common
*
* @param writeTimeout the value to set
* @return the dsl builder
*/
default MinaComponentBuilder writeTimeout(long writeTimeout) {
doSetProperty("writeTimeout", writeTimeout);
return this;
}
/**
* Allows for bridging the consumer to the Camel routing Error Handler,
* which mean any exceptions occurred while the consumer is trying to
* pickup incoming messages, or the likes, will now be processed as a
* message and handled by the routing Error Handler. By default the
* consumer will use the org.apache.camel.spi.ExceptionHandler to deal
* with exceptions, that will be logged at WARN or ERROR level and
* ignored.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: consumer
*
* @param bridgeErrorHandler the value to set
* @return the dsl builder
*/
default MinaComponentBuilder bridgeErrorHandler(
boolean bridgeErrorHandler) {
doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
return this;
}
/**
* If the clientMode is true, mina consumer will connect the address as
* a TCP client.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: consumer
*
* @param clientMode the value to set
* @return the dsl builder
*/
default MinaComponentBuilder clientMode(boolean clientMode) {
doSetProperty("clientMode", clientMode);
return this;
}
/**
* If sync is enabled then this option dictates MinaConsumer if it
* should disconnect where there is no reply to send back.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: consumer (advanced)
*
* @param disconnectOnNoReply the value to set
* @return the dsl builder
*/
default MinaComponentBuilder disconnectOnNoReply(
boolean disconnectOnNoReply) {
doSetProperty("disconnectOnNoReply", disconnectOnNoReply);
return this;
}
/**
* If sync is enabled this option dictates MinaConsumer which logging
* level to use when logging a there is no reply to send back.
*
* The option is a:
* <code>org.apache.camel.LoggingLevel</code> type.
*
* Default: WARN
* Group: consumer (advanced)
*
* @param noReplyLogLevel the value to set
* @return the dsl builder
*/
default MinaComponentBuilder noReplyLogLevel(
org.apache.camel.LoggingLevel noReplyLogLevel) {
doSetProperty("noReplyLogLevel", noReplyLogLevel);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default MinaComponentBuilder lazyStartProducer(boolean lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* Whether to create the InetAddress once and reuse. Setting this to
* false allows to pickup DNS changes in the network.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: producer (advanced)
*
* @param cachedAddress the value to set
* @return the dsl builder
*/
default MinaComponentBuilder cachedAddress(boolean cachedAddress) {
doSetProperty("cachedAddress", cachedAddress);
return this;
}
/**
* Sessions can be lazily created to avoid exceptions, if the remote
* server is not up and running when the Camel producer is started.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: producer (advanced)
*
* @param lazySessionCreation the value to set
* @return the dsl builder
*/
default MinaComponentBuilder lazySessionCreation(
boolean lazySessionCreation) {
doSetProperty("lazySessionCreation", lazySessionCreation);
return this;
}
/**
* Whether autowiring is enabled. This is used for automatic autowiring
* options (the option must be marked as autowired) by looking up in the
* registry to find if there is a single instance of matching type,
* which then gets configured on the component. This can be used for
* automatic configuring JDBC data sources, JMS connection factories,
* AWS Clients, etc.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: advanced
*
* @param autowiredEnabled the value to set
* @return the dsl builder
*/
default MinaComponentBuilder autowiredEnabled(boolean autowiredEnabled) {
doSetProperty("autowiredEnabled", autowiredEnabled);
return this;
}
/**
* To use the shared mina configuration.
*
* The option is a:
* <code>org.apache.camel.component.mina.MinaConfiguration</code> type.
*
* Group: advanced
*
* @param configuration the value to set
* @return the dsl builder
*/
default MinaComponentBuilder configuration(
org.apache.camel.component.mina.MinaConfiguration configuration) {
doSetProperty("configuration", configuration);
return this;
}
/**
* Number of worker threads in the worker pool for TCP and UDP.
*
* The option is a: <code>int</code> type.
*
* Default: 16
* Group: advanced
*
* @param maximumPoolSize the value to set
* @return the dsl builder
*/
default MinaComponentBuilder maximumPoolSize(int maximumPoolSize) {
doSetProperty("maximumPoolSize", maximumPoolSize);
return this;
}
/**
* Whether to use ordered thread pool, to ensure events are processed
* orderly on the same channel.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: advanced
*
* @param orderedThreadPoolExecutor the value to set
* @return the dsl builder
*/
default MinaComponentBuilder orderedThreadPoolExecutor(
boolean orderedThreadPoolExecutor) {
doSetProperty("orderedThreadPoolExecutor", orderedThreadPoolExecutor);
return this;
}
/**
* Only used for TCP. You can transfer the exchange over the wire
* instead of just the body. The following fields are transferred: In
* body, Out body, fault body, In headers, Out headers, fault headers,
* exchange properties, exchange exception. This requires that the
* objects are serializable. Camel will exclude any non-serializable
* objects and log it at WARN level.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: advanced
*
* @param transferExchange the value to set
* @return the dsl builder
*/
default MinaComponentBuilder transferExchange(boolean transferExchange) {
doSetProperty("transferExchange", transferExchange);
return this;
}
/**
* The mina component installs a default codec if both, codec is null
* and textline is false. Setting allowDefaultCodec to false prevents
* the mina component from installing a default codec as the first
* element in the filter chain. This is useful in scenarios where
* another filter must be the first in the filter chain, like the SSL
* filter.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: codec
*
* @param allowDefaultCodec the value to set
* @return the dsl builder
*/
default MinaComponentBuilder allowDefaultCodec(boolean allowDefaultCodec) {
doSetProperty("allowDefaultCodec", allowDefaultCodec);
return this;
}
/**
* To use a custom minda codec implementation.
*
* The option is a:
* <code>org.apache.mina.filter.codec.ProtocolCodecFactory</code> type.
*
* Group: codec
*
* @param codec the value to set
* @return the dsl builder
*/
default MinaComponentBuilder codec(
org.apache.mina.filter.codec.ProtocolCodecFactory codec) {
doSetProperty("codec", codec);
return this;
}
/**
* To set the textline protocol decoder max line length. By default the
* default value of Mina itself is used which are 1024.
*
* The option is a: <code>int</code> type.
*
* Default: 1024
* Group: codec
*
* @param decoderMaxLineLength the value to set
* @return the dsl builder
*/
default MinaComponentBuilder decoderMaxLineLength(
int decoderMaxLineLength) {
doSetProperty("decoderMaxLineLength", decoderMaxLineLength);
return this;
}
/**
* To set the textline protocol encoder max line length. By default the
* default value of Mina itself is used which are Integer.MAX_VALUE.
*
* The option is a: <code>int</code> type.
*
* Default: -1
* Group: codec
*
* @param encoderMaxLineLength the value to set
* @return the dsl builder
*/
default MinaComponentBuilder encoderMaxLineLength(
int encoderMaxLineLength) {
doSetProperty("encoderMaxLineLength", encoderMaxLineLength);
return this;
}
/**
* You can configure the encoding (a charset name) to use for the TCP
* textline codec and the UDP protocol. If not provided, Camel will use
* the JVM default Charset.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: codec
*
* @param encoding the value to set
* @return the dsl builder
*/
default MinaComponentBuilder encoding(java.lang.String encoding) {
doSetProperty("encoding", encoding);
return this;
}
/**
* You can set a list of Mina IoFilters to use.
*
* The option is a:
* <code>java.util.List&lt;org.apache.mina.core.filterchain.IoFilter&gt;</code> type.
*
* Group: codec
*
* @param filters the value to set
* @return the dsl builder
*/
default MinaComponentBuilder filters(
java.util.List<org.apache.mina.core.filterchain.IoFilter> filters) {
doSetProperty("filters", filters);
return this;
}
/**
* Only used for TCP. If no codec is specified, you can use this flag to
* indicate a text line based codec; if not specified or the value is
* false, then Object Serialization is assumed over TCP.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: codec
*
* @param textline the value to set
* @return the dsl builder
*/
default MinaComponentBuilder textline(boolean textline) {
doSetProperty("textline", textline);
return this;
}
/**
* Only used for TCP and if textline=true. Sets the text line delimiter
* to use. If none provided, Camel will use DEFAULT. This delimiter is
* used to mark the end of text.
*
* The option is a:
* <code>org.apache.camel.component.mina.MinaTextLineDelimiter</code> type.
*
* Group: codec
*
* @param textlineDelimiter the value to set
* @return the dsl builder
*/
default MinaComponentBuilder textlineDelimiter(
org.apache.camel.component.mina.MinaTextLineDelimiter textlineDelimiter) {
doSetProperty("textlineDelimiter", textlineDelimiter);
return this;
}
/**
* Whether to auto start SSL handshake.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: security
*
* @param autoStartTls the value to set
* @return the dsl builder
*/
default MinaComponentBuilder autoStartTls(boolean autoStartTls) {
doSetProperty("autoStartTls", autoStartTls);
return this;
}
/**
* To configure SSL security.
*
* The option is a:
* <code>org.apache.camel.support.jsse.SSLContextParameters</code> type.
*
* Group: security
*
* @param sslContextParameters the value to set
* @return the dsl builder
*/
default MinaComponentBuilder sslContextParameters(
org.apache.camel.support.jsse.SSLContextParameters sslContextParameters) {
doSetProperty("sslContextParameters", sslContextParameters);
return this;
}
/**
* Enable usage of global SSL context parameters.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: security
*
* @param useGlobalSslContextParameters the value to set
* @return the dsl builder
*/
default MinaComponentBuilder useGlobalSslContextParameters(
boolean useGlobalSslContextParameters) {
doSetProperty("useGlobalSslContextParameters", useGlobalSslContextParameters);
return this;
}
}
class MinaComponentBuilderImpl
extends
AbstractComponentBuilder<MinaComponent>
implements
MinaComponentBuilder {
@Override
protected MinaComponent buildConcreteComponent() {
return new MinaComponent();
}
private org.apache.camel.component.mina.MinaConfiguration getOrCreateConfiguration(
org.apache.camel.component.mina.MinaComponent component) {
if (component.getConfiguration() == null) {
component.setConfiguration(new org.apache.camel.component.mina.MinaConfiguration());
}
return component.getConfiguration();
}
@Override
protected boolean setPropertyOnComponent(
Component component,
String name,
Object value) {
switch (name) {
case "disconnect": getOrCreateConfiguration((MinaComponent) component).setDisconnect((boolean) value); return true;
case "minaLogger": getOrCreateConfiguration((MinaComponent) component).setMinaLogger((boolean) value); return true;
case "sync": getOrCreateConfiguration((MinaComponent) component).setSync((boolean) value); return true;
case "timeout": getOrCreateConfiguration((MinaComponent) component).setTimeout((long) value); return true;
case "writeTimeout": getOrCreateConfiguration((MinaComponent) component).setWriteTimeout((long) value); return true;
case "bridgeErrorHandler": ((MinaComponent) component).setBridgeErrorHandler((boolean) value); return true;
case "clientMode": getOrCreateConfiguration((MinaComponent) component).setClientMode((boolean) value); return true;
case "disconnectOnNoReply": getOrCreateConfiguration((MinaComponent) component).setDisconnectOnNoReply((boolean) value); return true;
case "noReplyLogLevel": getOrCreateConfiguration((MinaComponent) component).setNoReplyLogLevel((org.apache.camel.LoggingLevel) value); return true;
case "lazyStartProducer": ((MinaComponent) component).setLazyStartProducer((boolean) value); return true;
case "cachedAddress": getOrCreateConfiguration((MinaComponent) component).setCachedAddress((boolean) value); return true;
case "lazySessionCreation": getOrCreateConfiguration((MinaComponent) component).setLazySessionCreation((boolean) value); return true;
case "autowiredEnabled": ((MinaComponent) component).setAutowiredEnabled((boolean) value); return true;
case "configuration": ((MinaComponent) component).setConfiguration((org.apache.camel.component.mina.MinaConfiguration) value); return true;
case "maximumPoolSize": getOrCreateConfiguration((MinaComponent) component).setMaximumPoolSize((int) value); return true;
case "orderedThreadPoolExecutor": getOrCreateConfiguration((MinaComponent) component).setOrderedThreadPoolExecutor((boolean) value); return true;
case "transferExchange": getOrCreateConfiguration((MinaComponent) component).setTransferExchange((boolean) value); return true;
case "allowDefaultCodec": getOrCreateConfiguration((MinaComponent) component).setAllowDefaultCodec((boolean) value); return true;
case "codec": getOrCreateConfiguration((MinaComponent) component).setCodec((org.apache.mina.filter.codec.ProtocolCodecFactory) value); return true;
case "decoderMaxLineLength": getOrCreateConfiguration((MinaComponent) component).setDecoderMaxLineLength((int) value); return true;
case "encoderMaxLineLength": getOrCreateConfiguration((MinaComponent) component).setEncoderMaxLineLength((int) value); return true;
case "encoding": getOrCreateConfiguration((MinaComponent) component).setEncoding((java.lang.String) value); return true;
case "filters": getOrCreateConfiguration((MinaComponent) component).setFilters((java.util.List) value); return true;
case "textline": getOrCreateConfiguration((MinaComponent) component).setTextline((boolean) value); return true;
case "textlineDelimiter": getOrCreateConfiguration((MinaComponent) component).setTextlineDelimiter((org.apache.camel.component.mina.MinaTextLineDelimiter) value); return true;
case "autoStartTls": getOrCreateConfiguration((MinaComponent) component).setAutoStartTls((boolean) value); return true;
case "sslContextParameters": getOrCreateConfiguration((MinaComponent) component).setSslContextParameters((org.apache.camel.support.jsse.SSLContextParameters) value); return true;
case "useGlobalSslContextParameters": ((MinaComponent) component).setUseGlobalSslContextParameters((boolean) value); return true;
default: return false;
}
}
}
} | nikhilvibhav/camel | core/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/MinaComponentBuilderFactory.java | Java | apache-2.0 | 24,837 |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Guidelines for Boost Authors</title>
<link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../index.html" title="Boost.Config">
<link rel="up" href="../index.html" title="Boost.Config">
<link rel="prev" href="boost_macro_reference.html" title="Boost Macro Reference">
<link rel="next" href="rationale.html" title="Rationale">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../boost.png"></td>
<td align="center"><a href="../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="boost_macro_reference.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../index.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="rationale.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h2 class="title" style="clear: both">
<a name="boost_config.guidelines_for_boost_authors"></a><a class="link" href="guidelines_for_boost_authors.html" title="Guidelines for Boost Authors">Guidelines for
Boost Authors</a>
</h2></div></div></div>
<div class="toc"><dl class="toc">
<dt><span class="section"><a href="guidelines_for_boost_authors.html#boost_config.guidelines_for_boost_authors.warnings">Disabling
Compiler Warnings</a></span></dt>
<dt><span class="section"><a href="guidelines_for_boost_authors.html#boost_config.guidelines_for_boost_authors.adding_new_defect_macros">Adding
New Defect Macros</a></span></dt>
<dt><span class="section"><a href="guidelines_for_boost_authors.html#boost_config.guidelines_for_boost_authors.adding_new_feature_test_macros">Adding
New Feature Test Macros</a></span></dt>
<dt><span class="section"><a href="guidelines_for_boost_authors.html#boost_config.guidelines_for_boost_authors.modifying_the_boost_configuration_headers">Modifying
the Boost Configuration Headers</a></span></dt>
</dl></div>
<p>
The <a href="../../../../../boost/config.hpp" target="_top"><boost/config.hpp></a>
header is used to pass configuration information to other boost files, allowing
them to cope with platform dependencies such as arithmetic byte ordering, compiler
pragmas, or compiler shortcomings. Without such configuration information,
many current compilers would not work with the Boost libraries.
</p>
<p>
Centralizing configuration information in this header reduces the number of
files that must be modified when porting libraries to new platforms, or when
compilers are updated. Ideally, no other files would have to be modified when
porting to a new platform.
</p>
<p>
Configuration headers are controversial because some view them as condoning
broken compilers and encouraging non-standard subsets. Adding settings for
additional platforms and maintaining existing settings can also be a problem.
In other words, configuration headers are a necessary evil rather than a desirable
feature. The boost config.hpp policy is designed to minimize the problems and
maximize the benefits of a configuration header.
</p>
<p>
Note that:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; ">
<li class="listitem">
Boost library implementers are not required to "<code class="computeroutput"><span class="preprocessor">#include</span>
<span class="special"><</span><span class="identifier">boost</span><span class="special">/</span><span class="identifier">config</span><span class="special">.</span><span class="identifier">hpp</span><span class="special">></span></code>", and are not required in any
way to support compilers that do not comply with the C++ Standard (ISO/IEC
14882).
</li>
<li class="listitem">
If a library implementer wishes to support some non-conforming compiler,
or to support some platform specific feature, "<code class="computeroutput"><span class="preprocessor">#include</span>
<span class="special"><</span><span class="identifier">boost</span><span class="special">/</span><span class="identifier">config</span><span class="special">.</span><span class="identifier">hpp</span><span class="special">></span></code>" is the preferred way to obtain
configuration information not available from the standard headers such
as <code class="computeroutput"><span class="special"><</span><span class="identifier">climits</span><span class="special">></span></code>, etc.
</li>
<li class="listitem">
If configuration information can be deduced from standard headers such
as <code class="computeroutput"><span class="special"><</span><span class="identifier">climits</span><span class="special">></span></code>, use those standard headers rather
than <code class="computeroutput"><span class="special"><</span><span class="identifier">boost</span><span class="special">/</span><span class="identifier">config</span><span class="special">.</span><span class="identifier">hpp</span><span class="special">></span></code>.
</li>
<li class="listitem">
Boost files that use macros defined in <code class="computeroutput"><span class="special"><</span><span class="identifier">boost</span><span class="special">/</span><span class="identifier">config</span><span class="special">.</span><span class="identifier">hpp</span><span class="special">></span></code>
should have sensible, standard conforming, default behavior if the macro
is not defined. This means that the starting point for porting <code class="computeroutput"><span class="special"><</span><span class="identifier">boost</span><span class="special">/</span><span class="identifier">config</span><span class="special">.</span><span class="identifier">hpp</span><span class="special">></span></code> to a new platform is simply to define
nothing at all specific to that platform. In the rare case where there
is no sensible default behavior, an #error message should describe the
problem.
</li>
<li class="listitem">
If a Boost library implementer wants something added to <code class="computeroutput"><span class="identifier">config</span><span class="special">.</span><span class="identifier">hpp</span></code>,
post a request on the Boost mailing list. There is no guarantee such a
request will be honored; the intent is to limit the complexity of config.hpp.
</li>
<li class="listitem">
The intent is to support only compilers which appear on their way to becoming
C++ Standard compliant, and only recent releases of those compilers at
that.
</li>
<li class="listitem">
The intent is not to disable mainstream features now well-supported by
the majority of compilers, such as namespaces, exceptions, RTTI, or templates.
</li>
</ul></div>
<div class="section">
<div class="titlepage"><div><div><h3 class="title">
<a name="boost_config.guidelines_for_boost_authors.warnings"></a><a class="link" href="guidelines_for_boost_authors.html#boost_config.guidelines_for_boost_authors.warnings" title="Disabling Compiler Warnings">Disabling
Compiler Warnings</a>
</h3></div></div></div>
<p>
The header <code class="computeroutput"><span class="special"><</span><span class="identifier">boost</span><span class="special">/</span><span class="identifier">config</span><span class="special">/</span><span class="identifier">warning_disable</span><span class="special">.</span><span class="identifier">hpp</span><span class="special">></span></code>
can be used to disable certain compiler warnings that are hard or impossible
to otherwise remove.
</p>
<p>
Note that:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; ">
<li class="listitem">
This header <span class="bold"><strong><span class="emphasis"><em>should never be included
by another Boost header</em></span></strong></span>, it should only ever be
used by a library source file or a test case.
</li>
<li class="listitem">
The header should be included <span class="bold"><strong><span class="emphasis"><em>before
you include any other header</em></span></strong></span>.
</li>
<li class="listitem">
This header only disables warnings that are hard or impossible to otherwise
deal with, and which are typically emitted by one compiler only, or in
one compilers own standard library headers.
</li>
</ul></div>
<p>
Currently it disables the following warnings:
</p>
<div class="informaltable"><table class="table">
<colgroup>
<col>
<col>
</colgroup>
<thead><tr>
<th>
<p>
Compiler
</p>
</th>
<th>
<p>
Warning
</p>
</th>
</tr></thead>
<tbody>
<tr>
<td>
<p>
Visual C++ 8 and later
</p>
</td>
<td>
<p>
<a href="http://msdn2.microsoft.com/en-us/library/ttcz0bys(VS.80).aspx" target="_top">C4996</a>:
Error 'function': was declared deprecated
</p>
</td>
</tr>
<tr>
<td>
<p>
Intel C++
</p>
</td>
<td>
<p>
Warning 1786: relates to the use of "deprecated" standard
library functions rather like C4996 in Visual C++.
</p>
</td>
</tr>
</tbody>
</table></div>
</div>
<div class="section">
<div class="titlepage"><div><div><h3 class="title">
<a name="boost_config.guidelines_for_boost_authors.adding_new_defect_macros"></a><a class="link" href="guidelines_for_boost_authors.html#boost_config.guidelines_for_boost_authors.adding_new_defect_macros" title="Adding New Defect Macros">Adding
New Defect Macros</a>
</h3></div></div></div>
<p>
When you need to add a new defect macro - either to fix a problem with an
existing library, or when adding a new library - distil the issue down to
a simple test case; often, at this point other (possibly better) workarounds
may become apparent. Secondly always post the test case code to the boost
mailing list and invite comments; remember that C++ is complex and that sometimes
what may appear a defect, may in fact turn out to be a problem with the authors
understanding of the standard.
</p>
<p>
When you name the macro, follow the <code class="computeroutput"><span class="identifier">BOOST_NO_</span></code><span class="emphasis"><em>SOMETHING</em></span>
naming convention, so that it's obvious that this is a macro reporting a
defect.
</p>
<p>
Finally, add the test program to the regression tests. You will need to place
the test case in a <code class="computeroutput"><span class="special">.</span><span class="identifier">ipp</span></code>
file with the following comments near the top:
</p>
<pre class="programlisting"><span class="comment">// MACRO: BOOST_NO_FOO</span>
<span class="comment">// TITLE: foo</span>
<span class="comment">// DESCRIPTION: If the compiler fails to support foo</span>
</pre>
<p>
These comments are processed by the autoconf script, so make sure the format
follows the one given. The file should be named "<code class="computeroutput"><span class="identifier">boost_no_foo</span><span class="special">.</span><span class="identifier">ipp</span></code>",
where foo is the defect description - try and keep the file name under the
Mac 30 character filename limit though. You will also need to provide a function
prototype "<code class="computeroutput"><span class="keyword">int</span> <span class="identifier">test</span><span class="special">()</span></code>" that is declared in a namespace with
the same name as the macro, but in all lower case, and which returns zero
on success:
</p>
<pre class="programlisting"><span class="keyword">namespace</span> <span class="identifier">boost_no_foo</span> <span class="special">{</span>
<span class="keyword">int</span> <span class="identifier">test</span><span class="special">()</span>
<span class="special">{</span>
<span class="comment">// test code goes here:</span>
<span class="comment">//</span>
<span class="keyword">return</span> <span class="number">0</span><span class="special">;</span>
<span class="special">}</span>
<span class="special">}</span>
</pre>
<p>
Once the test code is in place in libs/config/test, updating the configuration
test system proceeds as:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; ">
<li class="listitem">
cd into <code class="computeroutput"><span class="identifier">libs</span><span class="special">/</span><span class="identifier">config</span><span class="special">/</span><span class="identifier">tools</span></code> and run <code class="computeroutput"><span class="identifier">bjam</span></code>.
This generates the <code class="computeroutput"><span class="special">.</span><span class="identifier">cpp</span></code>
file test cases from the <code class="computeroutput"><span class="special">.</span><span class="identifier">ipp</span></code> file, updates the libs/config/test/all/Jamfile.v2,
<code class="computeroutput"><span class="identifier">config_test</span><span class="special">.</span><span class="identifier">cpp</span></code> and <code class="computeroutput"><span class="identifier">config_info</span><span class="special">.</span><span class="identifier">cpp</span></code>.<br>
<br>
</li>
<li class="listitem">
cd into <code class="computeroutput"><span class="identifier">libs</span><span class="special">/</span><span class="identifier">config</span><span class="special">/</span><span class="identifier">test</span><span class="special">/</span><span class="identifier">all</span></code> and run <code class="computeroutput"><span class="identifier">bjam</span>
</code><span class="emphasis"><em>MACRONAME<code class="computeroutput"> <span class="identifier">compiler</span><span class="special">-</span><span class="identifier">list</span></code></em></span>,
where <span class="emphasis"><em>MACRONAME</em></span> is the name of the new macro, and
<span class="emphasis"><em><code class="computeroutput"><span class="identifier">compiler</span><span class="special">-</span><span class="identifier">list</span></code></em></span> is a space separated
list of compilers to test with.<br> <br> The xxx_pass_test and the
xxx_fail_test <span class="bold"><strong>should both report <code class="computeroutput"><span class="special">**</span><span class="identifier">passed</span><span class="special">**</span></code></strong></span>.<br> <br> If <span class="emphasis"><em>MACRONAME</em></span>
is not defined when it should be defined, xxx_pass_test will not report
<code class="computeroutput"><span class="special">**</span><span class="identifier">passed</span><span class="special">**</span></code>. If <span class="emphasis"><em>MACRONAME</em></span>
is defined when it should not be defined, xxx_fail_test will not report
<code class="computeroutput"><span class="special">**</span><span class="identifier">passed</span><span class="special">**</span></code>.<br> <br>
</li>
<li class="listitem">
cd into <code class="computeroutput"><span class="identifier">libs</span><span class="special">/</span><span class="identifier">config</span><span class="special">/</span><span class="identifier">test</span></code> and run <code class="computeroutput"><span class="identifier">bjam</span>
<span class="identifier">config_info</span> <span class="identifier">config_test</span>
</code><span class="emphasis"><em><code class="computeroutput"><span class="identifier">compiler</span><span class="special">-</span><span class="identifier">list</span></code></em></span>.
<code class="computeroutput"><span class="identifier">config_info</span></code> should build
and run cleanly for all the compilers in <span class="emphasis"><em><code class="computeroutput"><span class="identifier">compiler</span><span class="special">-</span><span class="identifier">list</span></code></em></span>
while <code class="computeroutput"><span class="identifier">config_test</span></code> should
fail for those that have the defect, and pass for those that do not.
</li>
</ul></div>
<p>
Then you should:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; ">
<li class="listitem">
Define the defect macro in those config headers that require it.
</li>
<li class="listitem">
Document the macro in this documentation (please do not forget this step!!)
</li>
<li class="listitem">
Commit everything.
</li>
<li class="listitem">
Keep an eye on the regression tests for new failures in Boost.Config
caused by the addition.
</li>
<li class="listitem">
Start using the macro.
</li>
</ul></div>
</div>
<div class="section">
<div class="titlepage"><div><div><h3 class="title">
<a name="boost_config.guidelines_for_boost_authors.adding_new_feature_test_macros"></a><a class="link" href="guidelines_for_boost_authors.html#boost_config.guidelines_for_boost_authors.adding_new_feature_test_macros" title="Adding New Feature Test Macros">Adding
New Feature Test Macros</a>
</h3></div></div></div>
<p>
When you need to add a macro that describes a feature that the standard does
not require, follow the convention for adding a new defect macro (above),
but call the macro <code class="computeroutput"><span class="identifier">BOOST_HAS_FOO</span></code>,
and name the test file "<code class="computeroutput"><span class="identifier">boost_has_foo</span><span class="special">.</span><span class="identifier">ipp</span></code>".
Try not to add feature test macros unnecessarily, if there is a platform
specific macro that can already be used (for example <code class="computeroutput"><span class="identifier">_WIN32</span></code>,
<code class="computeroutput"><span class="identifier">__BEOS__</span></code>, or <code class="computeroutput"><span class="identifier">__linux</span></code>) to identify the feature then use
that. Try to keep the macro to a feature group, or header name, rather than
one specific API (for example <code class="computeroutput"><span class="identifier">BOOST_HAS_NL_TYPES_H</span></code>
rather than <code class="computeroutput"><span class="identifier">BOOST_HAS_CATOPEN</span></code>).
If the macro describes a POSIX feature group, then add boilerplate code to
<a href="../../../../../boost/config/user.hpp" target="_top"><boost/config/suffix.hpp></a>
to auto-detect the feature where possible (if you are wondering why we can't
use POSIX feature test macro directly, remember that many of these features
can be added by third party libraries, and are not therefore identified inside
<code class="computeroutput"><span class="special"><</span><span class="identifier">unistd</span><span class="special">.</span><span class="identifier">h</span><span class="special">></span></code>).
</p>
</div>
<div class="section">
<div class="titlepage"><div><div><h3 class="title">
<a name="boost_config.guidelines_for_boost_authors.modifying_the_boost_configuration_headers"></a><a class="link" href="guidelines_for_boost_authors.html#boost_config.guidelines_for_boost_authors.modifying_the_boost_configuration_headers" title="Modifying the Boost Configuration Headers">Modifying
the Boost Configuration Headers</a>
</h3></div></div></div>
<p>
The aim of boost's configuration setup is that the configuration headers
should be relatively stable - a boost user should not have to recompile their
code just because the configuration for some compiler that they're not interested
in has changed. Separating the configuration into separate compiler/standard
library/platform sections provides for part of this stability, but boost
authors require some amount of restraint as well, in particular:
</p>
<p>
<a href="../../../../../boost/config.hpp" target="_top"><boost/config.hpp></a>
should never change, don't alter this file.
</p>
<p>
<a href="../../../../../boost/config/user.hpp" target="_top"><boost/config/user.hpp></a>
is included by default, don't add extra code to this file unless you have
to. If you do, please remember to update <a href="../../../tools/configure.in" target="_top">libs/config/tools/configure.in</a>
as well.
</p>
<p>
<a href="../../../../../boost/config/user.hpp" target="_top"><boost/config/suffix.hpp></a>
is always included so be careful about modifying this file as it breaks dependencies
for everyone. This file should include only "boilerplate" configuration
code, and generally should change only when new macros are added.
</p>
<p>
<a href="../../../../../boost/config/select_compiler_config.hpp" target="_top"><boost/config/select_compiler_config.hpp></a>,
<a href="../../../../../boost/config/select_platform_config.hpp" target="_top"><boost/config/select_platform_config.hpp></a>
and <a href="../../../../../boost/config/select_stdlib_config.hpp" target="_top"><boost/config/select_stdlib_config.hpp></a>
are included by default and should change only if support for a new compiler/standard
library/platform is added.
</p>
<p>
The compiler/platform/standard library selection code is set up so that unknown
platforms are ignored and assumed to be fully standards compliant - this
gives unknown platforms a "sporting chance" of working "as
is" even without running the configure script.
</p>
<p>
When adding or modifying the individual mini-configs, assume that future,
as yet unreleased versions of compilers, have all the defects of the current
version. Although this is perhaps unnecessarily pessimistic, it cuts down
on the maintenance of these files, and experience suggests that pessimism
is better placed than optimism here!
</p>
</div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2001-2007 Beman Dawes, Vesa Karvonen, John
Maddock<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="boost_macro_reference.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../index.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="rationale.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| NixaSoftware/CVis | venv/bin/libs/config/doc/html/boost_config/guidelines_for_boost_authors.html | HTML | apache-2.0 | 24,988 |
/**
* Sitespeed.io - How speedy is your site? (https://www.sitespeed.io)
* Copyright (c) 2014, Peter Hedenskog, Tobias Lidskog
* and other contributors
* Released under the Apache 2.0 License
*/
'use strict';
var util = require('../util/util'),
RequestTiming = require('../requestTiming'),
Stats = require('fast-stats').Stats,
winston = require('winston');
var domains = {};
exports.processPage = function(pageData) {
var log = winston.loggers.get('sitespeed.io');
var harData = [];
if (pageData.browsertime && pageData.browsertime.har) {
Array.prototype.push.apply(harData, pageData.browsertime.har);
}
if (pageData.webpagetest && pageData.webpagetest.har) {
Array.prototype.push.apply(harData, pageData.webpagetest.har);
}
// Workaround to avoid issues when bt doesn't generate a har due to useProxy being set to false
harData = harData.filter(function(har) {
return !!har;
});
var pageURL = util.getURLFromPageData(pageData);
harData.forEach(function(har) {
har.log.entries.forEach(function(entry) {
var domain = domains[util.getHostname(entry.request.url)];
var total;
if (domain) {
if (entry.timings) {
total = entry.timings.blocked + entry.timings.dns + entry.timings.connect + entry.timings.ssl +
entry.timings
.send + entry.timings.wait + entry.timings.receive;
domain.blocked.add(entry.timings.blocked, entry.request.url, pageURL);
domain.dns.add(entry.timings.dns, entry.request.url, pageURL);
domain.connect.add(entry.timings.connect, entry.request.url, pageURL);
domain.ssl.add(entry.timings.ssl, entry.request.url, pageURL);
domain.send.add(entry.timings.send, entry.request.url, pageURL);
domain.wait.add(entry.timings.wait, entry.request.url, pageURL);
domain.receive.add(entry.timings.receive, entry.request.url, pageURL);
domain.total.add(total, entry.request.url, pageURL);
domain.accumulatedTime += total;
} else {
log.log('info', 'Missing timings in the HAR');
}
} else {
if (entry.timings) {
total = entry.timings.blocked + entry.timings.dns + entry.timings.connect + entry.timings.ssl +
entry.timings
.send + entry.timings.wait + entry.timings.receive;
domains[util.getHostname(entry.request.url)] = {
domain: util.getHostname(entry.request.url),
blocked: new RequestTiming(entry.timings.blocked, entry.request.url, pageURL),
dns: new RequestTiming(entry.timings.dns, entry.request.url, pageURL),
connect: new RequestTiming(entry.timings.connect, entry.request.url, pageURL),
ssl: new RequestTiming(entry.timings.ssl, entry.request.url, pageURL),
send: new RequestTiming(entry.timings.send, entry.request.url, pageURL),
wait: new RequestTiming(entry.timings.wait, entry.request.url, pageURL),
receive: new RequestTiming(entry.timings.receive, entry.request.url, pageURL),
total: new RequestTiming(total, entry.request.url, pageURL),
accumulatedTime: total
};
} else {
log.log('info', 'Missing timings in the HAR');
}
}
});
});
// we have HAR files with one page tested multiple times,
// make sure we only get data from the first run
// and we kind of add items & size for requests missing
// but only for the first one
var pageref = '';
// add request & size, just do it for the first run
if (harData.length > 0) {
harData[0].log.entries.forEach(function(entry) {
if (pageref === '' || entry.pageref === pageref) {
pageref = entry.pageref;
var domain = domains[util.getHostname(entry.request.url)];
if (domain.count) {
domain.count++;
} else {
domain.count = 1;
}
if (domain.size) {
domain.size.total += entry.response.content.size;
domain.size[util.getContentType(entry.response.content.mimeType)] +=
entry.response.content.size;
} else {
domain.size = {
total: entry.response.content.size,
css: 0,
doc: 0,
js: 0,
image: 0,
font: 0,
flash: 0,
unknown: 0
};
domain.size[util.getContentType(entry.response.content.mimeType)] = entry.response.content.size;
}
} else {
// all other har files
var daDomain = domains[util.getHostname(entry.request.url)];
if (!daDomain.count) {
daDomain.count = 1;
}
if (!daDomain.size) {
// this is not perfect, we will miss request in other HAR..s
daDomain.size = {
total: entry.response.content.size,
css: 0,
doc: 0,
js: 0,
image: 0,
font: 0,
flash: 0,
unknown: 0
};
daDomain.size[util.getContentType(entry.response.content.mimeType)] = entry.response.content.size;
}
}
});
}
};
exports.generateResults = function() {
var values = Object.keys(domains).map(function(key) {
return domains[key];
});
return {
id: 'domains',
list: values
};
};
exports.clear = function() {
domains = {};
};
| yesman82/sitespeed.io | lib/collectors/domains.js | JavaScript | apache-2.0 | 5,405 |
/*
* 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.
*/
#include <axutil_dll_desc.h>
#include <axutil_class_loader.h>
struct axutil_dll_desc
{
axis2_char_t *dll_name;
axis2_char_t *path_qualified_dll_name;
axis2_dll_type_t dll_type;
int load_options;
AXIS2_DLHANDLER dl_handler;
CREATE_FUNCT create_funct;
DELETE_FUNCT delete_funct;
AXIS2_TIME_T timestamp;
axutil_error_codes_t error_code;
};
AXIS2_EXTERN axutil_dll_desc_t *AXIS2_CALL
axutil_dll_desc_create(
const axutil_env_t *env)
{
axutil_dll_desc_t *dll_desc = NULL;
AXIS2_ENV_CHECK(env, NULL);
dll_desc = (axutil_dll_desc_t *)AXIS2_MALLOC(env->allocator, sizeof(axutil_dll_desc_t));
if(!dll_desc)
{
AXIS2_ERROR_SET(env->error, AXIS2_ERROR_NO_MEMORY, AXIS2_FAILURE);
AXIS2_LOG_ERROR(env->log, AXIS2_LOG_SI, "Out of memory");
return NULL;
}
dll_desc->dll_name = NULL;
dll_desc->path_qualified_dll_name = NULL;
dll_desc->dll_type = 0;
dll_desc->load_options = 0;
dll_desc->dl_handler = NULL;
dll_desc->create_funct = NULL;
dll_desc->delete_funct = NULL;
dll_desc->timestamp = 0;
dll_desc->error_code = AXIS2_ERROR_NONE;
return dll_desc;
}
AXIS2_EXTERN void AXIS2_CALL
axutil_dll_desc_free(
axutil_dll_desc_t *dll_desc,
const axutil_env_t *env)
{
AXIS2_ENV_CHECK(env, AXIS2_FAILURE);
if(dll_desc->dl_handler)
{
axutil_class_loader_delete_dll(env, dll_desc);
}
if(dll_desc->dll_name)
{
AXIS2_FREE(env->allocator, dll_desc->dll_name);
dll_desc->dll_name = NULL;
}
if(dll_desc->path_qualified_dll_name)
{
AXIS2_FREE(env->allocator, dll_desc->path_qualified_dll_name);
dll_desc->path_qualified_dll_name = NULL;
}
if(dll_desc)
{
AXIS2_FREE(env->allocator, dll_desc);
}
return;
}
AXIS2_EXTERN void AXIS2_CALL
axutil_dll_desc_free_void_arg(
void *dll_desc,
const axutil_env_t *env)
{
axutil_dll_desc_t *dll_desc_l = NULL;
AXIS2_ENV_CHECK(env, AXIS2_FAILURE);
dll_desc_l = (axutil_dll_desc_t *)dll_desc;
axutil_dll_desc_free(dll_desc_l, env);
return;
}
AXIS2_EXTERN axis2_status_t AXIS2_CALL
axutil_dll_desc_set_name(
axutil_dll_desc_t *dll_desc,
const axutil_env_t *env,
axis2_char_t *name)
{
AXIS2_ENV_CHECK(env, AXIS2_FAILURE);
AXIS2_PARAM_CHECK(env->error, name, AXIS2_FAILURE);
if(dll_desc->path_qualified_dll_name)
{
AXIS2_FREE(env->allocator, dll_desc->path_qualified_dll_name);
dll_desc->path_qualified_dll_name = NULL;
}
dll_desc->path_qualified_dll_name = axutil_strdup(env, name);
if(!dll_desc->path_qualified_dll_name)
{
return AXIS2_FAILURE;
}
return AXIS2_SUCCESS;
}
AXIS2_EXTERN axis2_char_t *AXIS2_CALL
axutil_dll_desc_get_name(
axutil_dll_desc_t *dll_desc,
const axutil_env_t *env)
{
return dll_desc->path_qualified_dll_name;
}
AXIS2_EXTERN axis2_status_t AXIS2_CALL
axutil_dll_desc_set_load_options(
axutil_dll_desc_t *dll_desc,
const axutil_env_t *env,
int options)
{
AXIS2_ENV_CHECK(env, AXIS2_FAILURE);
dll_desc->load_options = options;
return AXIS2_SUCCESS;
}
AXIS2_EXTERN axis2_status_t AXIS2_CALL
axutil_dll_desc_set_type(
axutil_dll_desc_t *dll_desc,
const axutil_env_t *env,
axis2_dll_type_t type)
{
AXIS2_ENV_CHECK(env, AXIS2_FAILURE);
dll_desc->dll_type = type;
return AXIS2_SUCCESS;
}
AXIS2_EXTERN axis2_dll_type_t AXIS2_CALL
axutil_dll_desc_get_type(
axutil_dll_desc_t *dll_desc,
const axutil_env_t *env)
{
return dll_desc->dll_type;
}
AXIS2_EXTERN int AXIS2_CALL
axutil_dll_desc_get_load_options(
axutil_dll_desc_t *dll_desc,
const axutil_env_t *env)
{
return dll_desc->load_options;
}
AXIS2_EXTERN axis2_status_t AXIS2_CALL
axutil_dll_desc_set_dl_handler(
axutil_dll_desc_t *dll_desc,
const axutil_env_t *env,
AXIS2_DLHANDLER dl_handler)
{
AXIS2_ENV_CHECK(env, AXIS2_FAILURE);
AXIS2_PARAM_CHECK(env->error, dl_handler, AXIS2_FAILURE);
if(dll_desc->dl_handler)
{
AXIS2_FREE(env->allocator, dll_desc->dl_handler);
}
dll_desc->dl_handler = dl_handler;
return AXIS2_SUCCESS;
}
AXIS2_EXTERN AXIS2_DLHANDLER AXIS2_CALL
axutil_dll_desc_get_dl_handler(
axutil_dll_desc_t *dll_desc,
const axutil_env_t *env)
{
return dll_desc->dl_handler;
}
AXIS2_EXTERN axis2_status_t AXIS2_CALL
axutil_dll_desc_set_create_funct(
axutil_dll_desc_t *dll_desc,
const axutil_env_t *env,
CREATE_FUNCT funct)
{
AXIS2_ENV_CHECK(env, AXIS2_FAILURE);
dll_desc->create_funct = funct;
return AXIS2_SUCCESS;
}
AXIS2_EXTERN CREATE_FUNCT AXIS2_CALL
axutil_dll_desc_get_create_funct(
axutil_dll_desc_t *dll_desc,
const axutil_env_t *env)
{
return dll_desc->create_funct;
}
AXIS2_EXTERN axis2_status_t AXIS2_CALL
axutil_dll_desc_set_delete_funct(
axutil_dll_desc_t *dll_desc,
const axutil_env_t *env,
DELETE_FUNCT funct)
{
AXIS2_ENV_CHECK(env, AXIS2_FAILURE);
dll_desc->delete_funct = funct;
return AXIS2_SUCCESS;
}
AXIS2_EXTERN DELETE_FUNCT AXIS2_CALL
axutil_dll_desc_get_delete_funct(
axutil_dll_desc_t *dll_desc,
const axutil_env_t *env)
{
return dll_desc->delete_funct;
}
AXIS2_EXTERN axis2_status_t AXIS2_CALL
axutil_dll_desc_set_timestamp(
axutil_dll_desc_t *dll_desc,
const axutil_env_t *env,
AXIS2_TIME_T timestamp)
{
AXIS2_ENV_CHECK(env, AXIS2_FAILURE);
dll_desc->timestamp = timestamp;
return AXIS2_SUCCESS;
}
AXIS2_EXTERN AXIS2_TIME_T AXIS2_CALL
axutil_dll_desc_get_timestamp(
axutil_dll_desc_t *dll_desc,
const axutil_env_t *env)
{
return dll_desc->timestamp;
}
AXIS2_EXTERN axis2_status_t AXIS2_CALL
axutil_dll_desc_set_error_code(
axutil_dll_desc_t *dll_desc,
const axutil_env_t *env,
axutil_error_codes_t error_code)
{
AXIS2_ENV_CHECK(env, AXIS2_FAILURE);
dll_desc->error_code = error_code;
return AXIS2_SUCCESS;
}
AXIS2_EXTERN axutil_error_codes_t AXIS2_CALL
axutil_dll_desc_get_error_code(
axutil_dll_desc_t *dll_desc,
const axutil_env_t *env)
{
return dll_desc->error_code;
}
AXIS2_EXTERN axis2_char_t *AXIS2_CALL
axutil_dll_desc_create_platform_specific_dll_name(
axutil_dll_desc_t *dll_desc,
const axutil_env_t *env,
const axis2_char_t *class_name)
{
axis2_char_t *temp_name = NULL;
AXIS2_ENV_CHECK(env, NULL);
/* allow config to give a literal lib name since it may want a
* versioned lib like "libfoo.so.0" */
if (axutil_strstr(class_name, AXIS2_LIB_SUFFIX)) {
/* assume the class_name is the literal lib file name */
dll_desc->dll_name = axutil_strdup(env,class_name);
return dll_desc->dll_name;
}
temp_name = axutil_stracat(env, AXIS2_LIB_PREFIX, class_name);
dll_desc->dll_name = axutil_stracat(env, temp_name, AXIS2_LIB_SUFFIX);
AXIS2_FREE(env->allocator, temp_name);
return dll_desc->dll_name;
}
| techhead/wsf_php_dist | wsf_c/axis2c/util/src/dll_desc.c | C | apache-2.0 | 7,773 |
<section id="advice">
<h2 class="page-header"><a href="#advice">A Word of Advice</a></h2>
<p class="lead">
Before you go to see your new awesome theme, here are few tips on how to familiarize yourself with it:
</p>
<ul>
<li><b>AdminLTE is based on <a href="http://getbootstrap.com/" target="_blank">Bootstrap 3</a>.</b> If you are unfamiliar with Bootstrap, visit their website and read through the documentation. All of Bootstrap components have been modified to fit the style of AdminLTE and provide a consistent look throughout the template. This way, we guarantee you will get the best of AdminLTE.</li>
<li><b>Go through the pages that are bundled with the theme.</b> Most of the template example pages contain quick tips on how to create or use a component which can be really helpful when you need to create something on the fly.</li>
<li><b>Documentation.</b> We are trying our best to make your experience with AdminLTE be smooth. One way to achieve that is to provide documentation and support. If you think that something is missing from the documentation, please do not hesitate to create an issue to tell us about it.</li>
<li><b>Built with <a href="http://lesscss.org/" target="_blank">LESS</a>.</b> This theme uses the LESS compiler to make it easier to customize and use. LESS is easy to learn if you know CSS or SASS. It is not necessary to learn LESS but it will benefit you a lot in the future.</li>
<li><b>Hosted on <a href="https://github.com/almasaeed2010/AdminLTE/" target="_blank">GitHub</a>.</b> Visit our GitHub repository to view issues, make requests, or contribute to the project.</li>
</ul>
<p>
<b>Note:</b> LESS files are better commented than the compiled CSS file.
</p>
</section>
| rogerfanrui/dubbo-monitor | src/main/resources/static/adminlte/documentation/build/include/advice.html | HTML | apache-2.0 | 1,774 |
/*
* Copyright 2016 SimplifyOps, Inc. (http://simplifyops.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dtolabs.rundeck.server.plugins.services;
import com.dtolabs.rundeck.core.plugins.BasePluggableProviderService;
import com.dtolabs.rundeck.core.plugins.ServiceProviderLoader;
import com.dtolabs.rundeck.plugins.ServiceNameConstants;
import com.dtolabs.rundeck.plugins.logging.StreamingLogReaderPlugin;
/** $INTERFACE is ... User: greg Date: 5/24/13 Time: 9:32 AM */
public class StreamingLogReaderPluginProviderService extends BasePluggableProviderService<StreamingLogReaderPlugin> {
public static final String SERVICE_NAME = ServiceNameConstants.StreamingLogReader;
private ServiceProviderLoader rundeckServerServiceProviderLoader;
public StreamingLogReaderPluginProviderService() {
super(SERVICE_NAME, StreamingLogReaderPlugin.class);
}
@Override
public ServiceProviderLoader getPluginManager() {
return getRundeckServerServiceProviderLoader();
}
public ServiceProviderLoader getRundeckServerServiceProviderLoader() {
return rundeckServerServiceProviderLoader;
}
public void setRundeckServerServiceProviderLoader(ServiceProviderLoader rundeckServerServiceProviderLoader) {
this.rundeckServerServiceProviderLoader = rundeckServerServiceProviderLoader;
}
@Override
public boolean isScriptPluggable() {
//for now
return false;
}
}
| damageboy/rundeck | rundeckapp/src/java/com/dtolabs/rundeck/server/plugins/services/StreamingLogReaderPluginProviderService.java | Java | apache-2.0 | 1,978 |
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Google Maps JavaScript API v3 Example: Directions Draggable</title>
<link href="default.css" rel="stylesheet">
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script>
var rendererOptions = {
draggable: true
};
var directionsDisplay;
var directionsService;
var map;
var australia;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);;
directionsService = new google.maps.DirectionsService();
australia = new google.maps.LatLng(-25.274398, 133.775136);
var mapOptions = {
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: australia
};
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directionsPanel'));
google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
computeTotalDistance(directionsDisplay.getDirections());
});
calcRoute();
}
function calcRoute() {
var request = {
origin: 'Sydney, NSW',
destination: 'Sydney, NSW',
waypoints:[{location: 'Bourke, NSW'}, {location: 'Broken Hill, NSW'}],
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
function computeTotalDistance(result) {
var total = 0;
var myroute = result.routes[0];
for (var i = 0; i < myroute.legs.length; i++) {
total += myroute.legs[i].distance.value;
}
total = total / 1000.
document.getElementById('total').innerHTML = total + ' km';
}
google.load('maps', '3.0', {
callback: initialize,
other_params: 'sensor=false'
});
</script>
</head>
<body>
<div id="map_canvas" style="float:left;width:70%; height:100%"></div>
<div id="directionsPanel" style="float:right;width:30%;height 100%">
<p>Total Distance: <span id="total"></span></p>
</div>
</body>
</html>
| initaldk/caja | tests/com/google/caja/apitaming/maps/directions-draggable.html | HTML | apache-2.0 | 2,510 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.cxf.jaxrs;
import org.apache.camel.example.cxf.jaxrs.resources.Book;
import org.apache.camel.example.cxf.jaxrs.resources.BookNotFoundFault;
import org.apache.camel.example.cxf.jaxrs.resources.BookStore;
public class Client {
void invoke() throws BookNotFoundFault {
// JAXWSClient invocation
JAXWSClient jaxwsClient = new JAXWSClient();
BookStore bookStore = jaxwsClient.getBookStore();
bookStore.addBook(new Book("Camel User Guide", 123L));
Book book = bookStore.getBook(123L);
System.out.println("Get the book with id 123. " + book);
try {
book = bookStore.getBook(124L);
System.out.println("Get the book with id 124. " + book);
} catch (Exception exception) {
System.out.println("Expected exception received: " + exception);
}
// JAXRSClient invocation
JAXRSClient jaxrsClient = new JAXRSClient();
bookStore = jaxrsClient.getBookStore();
bookStore.addBook(new Book("Karaf User Guide", 124L));
book = bookStore.getBook(124L);
System.out.println("Get the book with id 124. " + book);
try {
book = bookStore.getBook(126L);
System.out.println("Get the book with id 126. " + book);
} catch (Exception exception) {
System.out.println("Expected exception received: " + exception);
}
}
public static void main(String args[]) throws Exception {
Client client = new Client();
client.invoke();
}
}
| objectiser/camel | examples/camel-example-cxf/src/main/java/org/apache/camel/example/cxf/jaxrs/Client.java | Java | apache-2.0 | 2,440 |
/*++
Copyright (c) 2004, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
EfiShell.c
Abstract:
FFS Filename for EFI Shell
--*/
#include "Tiano.h"
#include EFI_GUID_DEFINITION (EfiShell)
EFI_GUID gEfiShellFileGuid = EFI_SHELL_FILE_GUID;
EFI_GUID gEfiMiniShellFileGuid = EFI_MINI_SHELL_FILE_GUID;
EFI_GUID_STRING (&gEfiShellFileGuid, "EfiShell", "Efi Shell FFS file name GUID")
EFI_GUID_STRING (&gEfiMiniShellFileGuid, "EfiMiniShell", "Efi Mini-Shell FFS file name GUID")
| google/google-ctf | third_party/edk2/EdkCompatibilityPkg/Foundation/Guid/EfiShell/EfiShell.c | C | apache-2.0 | 1,146 |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.search.aggregations.bucket.significant;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.Version;
import org.elasticsearch.common.io.stream.InputStreamStreamInput;
import org.elasticsearch.common.io.stream.OutputStreamStreamOutput;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.elasticsearch.search.SearchShardTarget;
import org.elasticsearch.search.aggregations.InternalAggregations;
import org.elasticsearch.search.aggregations.bucket.significant.heuristics.ChiSquare;
import org.elasticsearch.search.aggregations.bucket.significant.heuristics.GND;
import org.elasticsearch.search.aggregations.bucket.significant.heuristics.JLHScore;
import org.elasticsearch.search.aggregations.bucket.significant.heuristics.MutualInformation;
import org.elasticsearch.search.aggregations.bucket.significant.heuristics.PercentageScore;
import org.elasticsearch.search.aggregations.bucket.significant.heuristics.SignificanceHeuristic;
import org.elasticsearch.search.aggregations.bucket.significant.heuristics.SignificanceHeuristicBuilder;
import org.elasticsearch.search.aggregations.bucket.significant.heuristics.SignificanceHeuristicParser;
import org.elasticsearch.search.aggregations.bucket.significant.heuristics.SignificanceHeuristicParserMapper;
import org.elasticsearch.search.internal.SearchContext;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.TestSearchContext;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static org.elasticsearch.test.VersionUtils.randomVersion;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.lessThan;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
/**
*
*/
public class SignificanceHeuristicTests extends ESTestCase {
static class SignificantTermsTestSearchContext extends TestSearchContext {
@Override
public int numberOfShards() {
return 1;
}
@Override
public SearchShardTarget shardTarget() {
return new SearchShardTarget("no node, this is a unit test", "no index, this is a unit test", 0);
}
}
// test that stream output can actually be read - does not replace bwc test
public void testStreamResponse() throws Exception {
Version version = randomVersion(random());
InternalSignificantTerms[] sigTerms = getRandomSignificantTerms(getRandomSignificanceheuristic());
// write
ByteArrayOutputStream outBuffer = new ByteArrayOutputStream();
OutputStreamStreamOutput out = new OutputStreamStreamOutput(outBuffer);
out.setVersion(version);
sigTerms[0].writeTo(out);
// read
ByteArrayInputStream inBuffer = new ByteArrayInputStream(outBuffer.toByteArray());
InputStreamStreamInput in = new InputStreamStreamInput(inBuffer);
in.setVersion(version);
sigTerms[1].readFrom(in);
assertTrue(sigTerms[1].significanceHeuristic.equals(sigTerms[0].significanceHeuristic));
}
InternalSignificantTerms[] getRandomSignificantTerms(SignificanceHeuristic heuristic) {
InternalSignificantTerms[] sTerms = new InternalSignificantTerms[2];
ArrayList<InternalSignificantTerms.Bucket> buckets = new ArrayList<>();
if (randomBoolean()) {
BytesRef term = new BytesRef("123.0");
buckets.add(new SignificantLongTerms.Bucket(1, 2, 3, 4, 123, InternalAggregations.EMPTY, null));
sTerms[0] = new SignificantLongTerms(10, 20, "some_name", null, 1, 1, heuristic, buckets,
Collections.EMPTY_LIST, null);
sTerms[1] = new SignificantLongTerms();
} else {
BytesRef term = new BytesRef("someterm");
buckets.add(new SignificantStringTerms.Bucket(term, 1, 2, 3, 4, InternalAggregations.EMPTY));
sTerms[0] = new SignificantStringTerms(10, 20, "some_name", 1, 1, heuristic, buckets, Collections.EMPTY_LIST,
null);
sTerms[1] = new SignificantStringTerms();
}
return sTerms;
}
SignificanceHeuristic getRandomSignificanceheuristic() {
List<SignificanceHeuristic> heuristics = new ArrayList<>();
heuristics.add(JLHScore.INSTANCE);
heuristics.add(new MutualInformation(randomBoolean(), randomBoolean()));
heuristics.add(new GND(randomBoolean()));
heuristics.add(new ChiSquare(randomBoolean(), randomBoolean()));
return heuristics.get(randomInt(3));
}
// test that
// 1. The output of the builders can actually be parsed
// 2. The parser does not swallow parameters after a significance heuristic was defined
public void testBuilderAndParser() throws Exception {
Set<SignificanceHeuristicParser> parsers = new HashSet<>();
SignificanceHeuristicParserMapper heuristicParserMapper = new SignificanceHeuristicParserMapper(parsers, null);
SearchContext searchContext = new SignificantTermsTestSearchContext();
// test jlh with string
assertTrue(parseFromString(heuristicParserMapper, searchContext, "\"jlh\":{}") instanceof JLHScore);
// test gnd with string
assertTrue(parseFromString(heuristicParserMapper, searchContext, "\"gnd\":{}") instanceof GND);
// test mutual information with string
boolean includeNegatives = randomBoolean();
boolean backgroundIsSuperset = randomBoolean();
assertThat(parseFromString(heuristicParserMapper, searchContext, "\"mutual_information\":{\"include_negatives\": " + includeNegatives + ", \"background_is_superset\":" + backgroundIsSuperset + "}"), equalTo((SignificanceHeuristic) (new MutualInformation(includeNegatives, backgroundIsSuperset))));
assertThat(parseFromString(heuristicParserMapper, searchContext, "\"chi_square\":{\"include_negatives\": " + includeNegatives + ", \"background_is_superset\":" + backgroundIsSuperset + "}"), equalTo((SignificanceHeuristic) (new ChiSquare(includeNegatives, backgroundIsSuperset))));
// test with builders
assertTrue(parseFromBuilder(heuristicParserMapper, searchContext, new JLHScore.JLHScoreBuilder()) instanceof JLHScore);
assertTrue(parseFromBuilder(heuristicParserMapper, searchContext, new GND.GNDBuilder(backgroundIsSuperset)) instanceof GND);
assertThat(parseFromBuilder(heuristicParserMapper, searchContext, new MutualInformation.MutualInformationBuilder(includeNegatives, backgroundIsSuperset)), equalTo((SignificanceHeuristic) new MutualInformation(includeNegatives, backgroundIsSuperset)));
assertThat(parseFromBuilder(heuristicParserMapper, searchContext, new ChiSquare.ChiSquareBuilder(includeNegatives, backgroundIsSuperset)), equalTo((SignificanceHeuristic) new ChiSquare(includeNegatives, backgroundIsSuperset)));
// test exceptions
String faultyHeuristicdefinition = "\"mutual_information\":{\"include_negatives\": false, \"some_unknown_field\": false}";
String expectedError = "unknown field [some_unknown_field]";
checkParseException(heuristicParserMapper, searchContext, faultyHeuristicdefinition, expectedError);
faultyHeuristicdefinition = "\"chi_square\":{\"unknown_field\": true}";
expectedError = "unknown field [unknown_field]";
checkParseException(heuristicParserMapper, searchContext, faultyHeuristicdefinition, expectedError);
faultyHeuristicdefinition = "\"jlh\":{\"unknown_field\": true}";
expectedError = "expected an empty object, but found ";
checkParseException(heuristicParserMapper, searchContext, faultyHeuristicdefinition, expectedError);
faultyHeuristicdefinition = "\"gnd\":{\"unknown_field\": true}";
expectedError = "unknown field [unknown_field]";
checkParseException(heuristicParserMapper, searchContext, faultyHeuristicdefinition, expectedError);
}
protected void checkParseException(SignificanceHeuristicParserMapper heuristicParserMapper, SearchContext searchContext, String faultyHeuristicDefinition, String expectedError) throws IOException {
try {
XContentParser stParser = JsonXContent.jsonXContent.createParser("{\"field\":\"text\", " + faultyHeuristicDefinition + ",\"min_doc_count\":200}");
stParser.nextToken();
new SignificantTermsParser(heuristicParserMapper).parse("testagg", stParser, searchContext);
fail();
} catch (ElasticsearchParseException e) {
assertTrue(e.getMessage().contains(expectedError));
}
}
protected SignificanceHeuristic parseFromBuilder(SignificanceHeuristicParserMapper heuristicParserMapper, SearchContext searchContext, SignificanceHeuristicBuilder significanceHeuristicBuilder) throws IOException {
SignificantTermsBuilder stBuilder = new SignificantTermsBuilder("testagg");
stBuilder.significanceHeuristic(significanceHeuristicBuilder).field("text").minDocCount(200);
XContentBuilder stXContentBuilder = XContentFactory.jsonBuilder();
stBuilder.internalXContent(stXContentBuilder, null);
XContentParser stParser = JsonXContent.jsonXContent.createParser(stXContentBuilder.string());
return parseSignificanceHeuristic(heuristicParserMapper, searchContext, stParser);
}
private SignificanceHeuristic parseSignificanceHeuristic(SignificanceHeuristicParserMapper heuristicParserMapper, SearchContext searchContext, XContentParser stParser) throws IOException {
stParser.nextToken();
SignificantTermsAggregatorFactory aggregatorFactory = (SignificantTermsAggregatorFactory) new SignificantTermsParser(heuristicParserMapper).parse("testagg", stParser, searchContext);
stParser.nextToken();
assertThat(aggregatorFactory.getBucketCountThresholds().getMinDocCount(), equalTo(200l));
assertThat(stParser.currentToken(), equalTo(null));
stParser.close();
return aggregatorFactory.getSignificanceHeuristic();
}
protected SignificanceHeuristic parseFromString(SignificanceHeuristicParserMapper heuristicParserMapper, SearchContext searchContext, String heuristicString) throws IOException {
XContentParser stParser = JsonXContent.jsonXContent.createParser("{\"field\":\"text\", " + heuristicString + ", \"min_doc_count\":200}");
return parseSignificanceHeuristic(heuristicParserMapper, searchContext, stParser);
}
void testBackgroundAssertions(SignificanceHeuristic heuristicIsSuperset, SignificanceHeuristic heuristicNotSuperset) {
try {
heuristicIsSuperset.getScore(2, 3, 1, 4);
fail();
} catch (IllegalArgumentException illegalArgumentException) {
assertNotNull(illegalArgumentException.getMessage());
assertTrue(illegalArgumentException.getMessage().contains("subsetFreq > supersetFreq"));
}
try {
heuristicIsSuperset.getScore(1, 4, 2, 3);
fail();
} catch (IllegalArgumentException illegalArgumentException) {
assertNotNull(illegalArgumentException.getMessage());
assertTrue(illegalArgumentException.getMessage().contains("subsetSize > supersetSize"));
}
try {
heuristicIsSuperset.getScore(2, 1, 3, 4);
fail();
} catch (IllegalArgumentException illegalArgumentException) {
assertNotNull(illegalArgumentException.getMessage());
assertTrue(illegalArgumentException.getMessage().contains("subsetFreq > subsetSize"));
}
try {
heuristicIsSuperset.getScore(1, 2, 4, 3);
fail();
} catch (IllegalArgumentException illegalArgumentException) {
assertNotNull(illegalArgumentException.getMessage());
assertTrue(illegalArgumentException.getMessage().contains("supersetFreq > supersetSize"));
}
try {
heuristicIsSuperset.getScore(1, 3, 4, 4);
fail();
} catch (IllegalArgumentException assertionError) {
assertNotNull(assertionError.getMessage());
assertTrue(assertionError.getMessage().contains("supersetFreq - subsetFreq > supersetSize - subsetSize"));
}
try {
int idx = randomInt(3);
long[] values = {1, 2, 3, 4};
values[idx] *= -1;
heuristicIsSuperset.getScore(values[0], values[1], values[2], values[3]);
fail();
} catch (IllegalArgumentException illegalArgumentException) {
assertNotNull(illegalArgumentException.getMessage());
assertTrue(illegalArgumentException.getMessage().contains("Frequencies of subset and superset must be positive"));
}
try {
heuristicNotSuperset.getScore(2, 1, 3, 4);
fail();
} catch (IllegalArgumentException illegalArgumentException) {
assertNotNull(illegalArgumentException.getMessage());
assertTrue(illegalArgumentException.getMessage().contains("subsetFreq > subsetSize"));
}
try {
heuristicNotSuperset.getScore(1, 2, 4, 3);
fail();
} catch (IllegalArgumentException illegalArgumentException) {
assertNotNull(illegalArgumentException.getMessage());
assertTrue(illegalArgumentException.getMessage().contains("supersetFreq > supersetSize"));
}
try {
int idx = randomInt(3);
long[] values = {1, 2, 3, 4};
values[idx] *= -1;
heuristicNotSuperset.getScore(values[0], values[1], values[2], values[3]);
fail();
} catch (IllegalArgumentException illegalArgumentException) {
assertNotNull(illegalArgumentException.getMessage());
assertTrue(illegalArgumentException.getMessage().contains("Frequencies of subset and superset must be positive"));
}
}
void testAssertions(SignificanceHeuristic heuristic) {
try {
int idx = randomInt(3);
long[] values = {1, 2, 3, 4};
values[idx] *= -1;
heuristic.getScore(values[0], values[1], values[2], values[3]);
fail();
} catch (IllegalArgumentException illegalArgumentException) {
assertNotNull(illegalArgumentException.getMessage());
assertTrue(illegalArgumentException.getMessage().contains("Frequencies of subset and superset must be positive"));
}
try {
heuristic.getScore(1, 2, 4, 3);
fail();
} catch (IllegalArgumentException illegalArgumentException) {
assertNotNull(illegalArgumentException.getMessage());
assertTrue(illegalArgumentException.getMessage().contains("supersetFreq > supersetSize"));
}
try {
heuristic.getScore(2, 1, 3, 4);
fail();
} catch (IllegalArgumentException illegalArgumentException) {
assertNotNull(illegalArgumentException.getMessage());
assertTrue(illegalArgumentException.getMessage().contains("subsetFreq > subsetSize"));
}
}
public void testAssertions() throws Exception {
testBackgroundAssertions(new MutualInformation(true, true), new MutualInformation(true, false));
testBackgroundAssertions(new ChiSquare(true, true), new ChiSquare(true, false));
testBackgroundAssertions(new GND(true), new GND(false));
testAssertions(PercentageScore.INSTANCE);
testAssertions(JLHScore.INSTANCE);
}
public void testBasicScoreProperties() {
basicScoreProperties(JLHScore.INSTANCE, true);
basicScoreProperties(new GND(true), true);
basicScoreProperties(PercentageScore.INSTANCE, true);
basicScoreProperties(new MutualInformation(true, true), false);
basicScoreProperties(new ChiSquare(true, true), false);
}
public void basicScoreProperties(SignificanceHeuristic heuristic, boolean test0) {
assertThat(heuristic.getScore(1, 1, 1, 3), greaterThan(0.0));
assertThat(heuristic.getScore(1, 1, 2, 3), lessThan(heuristic.getScore(1, 1, 1, 3)));
assertThat(heuristic.getScore(1, 1, 3, 4), lessThan(heuristic.getScore(1, 1, 2, 4)));
if (test0) {
assertThat(heuristic.getScore(0, 1, 2, 3), equalTo(0.0));
}
double score = 0.0;
try {
long a = randomLong();
long b = randomLong();
long c = randomLong();
long d = randomLong();
score = heuristic.getScore(a, b, c, d);
} catch (IllegalArgumentException e) {
}
assertThat(score, greaterThanOrEqualTo(0.0));
}
public void testScoreMutual() throws Exception {
SignificanceHeuristic heuristic = new MutualInformation(true, true);
assertThat(heuristic.getScore(1, 1, 1, 3), greaterThan(0.0));
assertThat(heuristic.getScore(1, 1, 2, 3), lessThan(heuristic.getScore(1, 1, 1, 3)));
assertThat(heuristic.getScore(2, 2, 2, 4), equalTo(1.0));
assertThat(heuristic.getScore(0, 2, 2, 4), equalTo(1.0));
assertThat(heuristic.getScore(2, 2, 4, 4), equalTo(0.0));
assertThat(heuristic.getScore(1, 2, 2, 4), equalTo(0.0));
assertThat(heuristic.getScore(3, 6, 9, 18), equalTo(0.0));
double score = 0.0;
try {
long a = randomLong();
long b = randomLong();
long c = randomLong();
long d = randomLong();
score = heuristic.getScore(a, b, c, d);
} catch (IllegalArgumentException e) {
}
assertThat(score, lessThanOrEqualTo(1.0));
assertThat(score, greaterThanOrEqualTo(0.0));
heuristic = new MutualInformation(false, true);
assertThat(heuristic.getScore(0, 1, 2, 3), equalTo(Double.NEGATIVE_INFINITY));
heuristic = new MutualInformation(true, false);
score = heuristic.getScore(2, 3, 1, 4);
assertThat(score, greaterThanOrEqualTo(0.0));
assertThat(score, lessThanOrEqualTo(1.0));
score = heuristic.getScore(1, 4, 2, 3);
assertThat(score, greaterThanOrEqualTo(0.0));
assertThat(score, lessThanOrEqualTo(1.0));
score = heuristic.getScore(1, 3, 4, 4);
assertThat(score, greaterThanOrEqualTo(0.0));
assertThat(score, lessThanOrEqualTo(1.0));
}
public void testGNDCornerCases() throws Exception {
GND gnd = new GND(true);
//term is only in the subset, not at all in the other set but that is because the other set is empty.
// this should actually not happen because only terms that are in the subset are considered now,
// however, in this case the score should be 0 because a term that does not exist cannot be relevant...
assertThat(gnd.getScore(0, randomIntBetween(1, 2), 0, randomIntBetween(2,3)), equalTo(0.0));
// the terms do not co-occur at all - should be 0
assertThat(gnd.getScore(0, randomIntBetween(1, 2), randomIntBetween(2, 3), randomIntBetween(5,6)), equalTo(0.0));
// comparison between two terms that do not exist - probably not relevant
assertThat(gnd.getScore(0, 0, 0, randomIntBetween(1,2)), equalTo(0.0));
// terms co-occur perfectly - should be 1
assertThat(gnd.getScore(1, 1, 1, 1), equalTo(1.0));
gnd = new GND(false);
assertThat(gnd.getScore(0, 0, 0, 0), equalTo(0.0));
}
}
| PhaedrusTheGreek/elasticsearch | core/src/test/java/org/elasticsearch/search/aggregations/bucket/significant/SignificanceHeuristicTests.java | Java | apache-2.0 | 20,764 |
/// <reference path='fourslash.ts' />
// @noUnusedLocals: true
// @noUnusedParameters: true
////function g(a, b) { b; }
////g(1, 2);
verify.not.codeFixAvailable("Remove unused declaration for: 'a'");
| Microsoft/TypeScript | tests/cases/fourslash/codeFixUnusedIdentifier_parameter.ts | TypeScript | apache-2.0 | 203 |
/*
* Copyright 2016 Detlef Gregor Herm
*
* 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.
*/
/* JavaFX CSS - Leave this comment until you have at least create one rule which uses -fx-Property */
| DGHerm/RetrievalTrainer | src/main/resources/de/herm_detlef/java/application/mvc/view/preferences/preferences.css | CSS | apache-2.0 | 715 |
/*
* Copyright 2000-2012 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;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiField;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.PsiShortNamesCache;
import com.intellij.util.ArrayUtil;
import com.intellij.util.CommonProcessors;
import com.intellij.util.Processor;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.indexing.IdFilter;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.Set;
public class CompositeShortNamesCache extends PsiShortNamesCache {
private final PsiShortNamesCache[] myCaches;
public CompositeShortNamesCache(Project project) {
myCaches = project.isDefault() ? new PsiShortNamesCache[0] : project.getExtensions(PsiShortNamesCache.EP_NAME);
}
@Override
@NotNull
public PsiFile[] getFilesByName(@NotNull String name) {
Merger<PsiFile> merger = null;
for (PsiShortNamesCache cache : myCaches) {
PsiFile[] classes = cache.getFilesByName(name);
if (classes.length != 0) {
if (merger == null) merger = new Merger<>();
merger.add(classes);
}
}
PsiFile[] result = merger == null ? null : merger.getResult();
return result != null ? result : PsiFile.EMPTY_ARRAY;
}
@Override
@NotNull
public String[] getAllFileNames() {
Merger<String> merger = new Merger<>();
for (PsiShortNamesCache cache : myCaches) {
merger.add(cache.getAllFileNames());
}
String[] result = merger.getResult();
return result != null ? result : ArrayUtil.EMPTY_STRING_ARRAY;
}
@Override
@NotNull
public PsiClass[] getClassesByName(@NotNull String name, @NotNull GlobalSearchScope scope) {
Merger<PsiClass> merger = null;
for (PsiShortNamesCache cache : myCaches) {
PsiClass[] classes = cache.getClassesByName(name, scope);
if (classes.length != 0) {
if (merger == null) merger = new Merger<>();
merger.add(classes);
}
}
PsiClass[] result = merger == null ? null : merger.getResult();
return result != null ? result : PsiClass.EMPTY_ARRAY;
}
@Override
@NotNull
public String[] getAllClassNames() {
Merger<String> merger = new Merger<>();
for (PsiShortNamesCache cache : myCaches) {
String[] names = cache.getAllClassNames();
merger.add(names);
}
String[] result = merger.getResult();
return result != null ? result : ArrayUtil.EMPTY_STRING_ARRAY;
}
@Override
public boolean processAllClassNames(@NotNull Processor<String> processor) {
CommonProcessors.UniqueProcessor<String> uniqueProcessor = new CommonProcessors.UniqueProcessor<>(processor);
for (PsiShortNamesCache cache : myCaches) {
if (!cache.processAllClassNames(uniqueProcessor)) {
return false;
}
}
return true;
}
@Override
public boolean processAllClassNames(@NotNull Processor<String> processor, @NotNull GlobalSearchScope scope, IdFilter filter) {
for (PsiShortNamesCache cache : myCaches) {
if (!cache.processAllClassNames(processor, scope, filter)) {
return false;
}
}
return true;
}
@Override
public boolean processAllMethodNames(@NotNull Processor<String> processor, @NotNull GlobalSearchScope scope, IdFilter filter) {
for (PsiShortNamesCache cache : myCaches) {
if (!cache.processAllMethodNames(processor, scope, filter)) {
return false;
}
}
return true;
}
@Override
public boolean processAllFieldNames(@NotNull Processor<String> processor, @NotNull GlobalSearchScope scope, IdFilter filter) {
for (PsiShortNamesCache cache : myCaches) {
if (!cache.processAllFieldNames(processor, scope, filter)) {
return false;
}
}
return true;
}
@Override
@NotNull
public PsiMethod[] getMethodsByName(@NotNull String name, @NotNull GlobalSearchScope scope) {
Merger<PsiMethod> merger = null;
for (PsiShortNamesCache cache : myCaches) {
PsiMethod[] methods = cache.getMethodsByName(name, scope);
if (methods.length != 0) {
if (merger == null) merger = new Merger<>();
merger.add(methods);
}
}
PsiMethod[] result = merger == null ? null : merger.getResult();
return result == null ? PsiMethod.EMPTY_ARRAY : result;
}
@Override
@NotNull
public PsiMethod[] getMethodsByNameIfNotMoreThan(@NonNls @NotNull final String name, @NotNull final GlobalSearchScope scope, final int maxCount) {
Merger<PsiMethod> merger = null;
for (PsiShortNamesCache cache : myCaches) {
PsiMethod[] methods = cache.getMethodsByNameIfNotMoreThan(name, scope, maxCount);
if (methods.length == maxCount) return methods;
if (methods.length != 0) {
if (merger == null) merger = new Merger<>();
merger.add(methods);
}
}
PsiMethod[] result = merger == null ? null : merger.getResult();
return result == null ? PsiMethod.EMPTY_ARRAY : result;
}
@NotNull
@Override
public PsiField[] getFieldsByNameIfNotMoreThan(@NonNls @NotNull String name, @NotNull GlobalSearchScope scope, int maxCount) {
Merger<PsiField> merger = null;
for (PsiShortNamesCache cache : myCaches) {
PsiField[] fields = cache.getFieldsByNameIfNotMoreThan(name, scope, maxCount);
if (fields.length == maxCount) return fields;
if (fields.length != 0) {
if (merger == null) merger = new Merger<>();
merger.add(fields);
}
}
PsiField[] result = merger == null ? null : merger.getResult();
return result == null ? PsiField.EMPTY_ARRAY : result;
}
@Override
public boolean processMethodsWithName(@NonNls @NotNull String name,
@NotNull GlobalSearchScope scope,
@NotNull Processor<PsiMethod> processor) {
return processMethodsWithName(name, processor, scope, null);
}
@Override
public boolean processMethodsWithName(@NonNls @NotNull String name,
@NotNull Processor<? super PsiMethod> processor,
@NotNull GlobalSearchScope scope,
@Nullable IdFilter idFilter) {
for (PsiShortNamesCache cache : myCaches) {
if (!cache.processMethodsWithName(name, processor, scope, idFilter)) return false;
}
return true;
}
@Override
@NotNull
public String[] getAllMethodNames() {
Merger<String> merger = new Merger<>();
for (PsiShortNamesCache cache : myCaches) {
merger.add(cache.getAllMethodNames());
}
String[] result = merger.getResult();
return result != null ? result : ArrayUtil.EMPTY_STRING_ARRAY;
}
@Override
@NotNull
public PsiField[] getFieldsByName(@NotNull String name, @NotNull GlobalSearchScope scope) {
Merger<PsiField> merger = null;
for (PsiShortNamesCache cache : myCaches) {
PsiField[] classes = cache.getFieldsByName(name, scope);
if (classes.length != 0) {
if (merger == null) merger = new Merger<>();
merger.add(classes);
}
}
PsiField[] result = merger == null ? null : merger.getResult();
return result == null ? PsiField.EMPTY_ARRAY : result;
}
@Override
@NotNull
public String[] getAllFieldNames() {
Merger<String> merger = null;
for (PsiShortNamesCache cache : myCaches) {
String[] classes = cache.getAllFieldNames();
if (classes.length != 0) {
if (merger == null) merger = new Merger<>();
merger.add(classes);
}
}
String[] result = merger == null ? null : merger.getResult();
return result == null ? ArrayUtil.EMPTY_STRING_ARRAY : result;
}
@Override
public boolean processFieldsWithName(@NotNull String key,
@NotNull Processor<? super PsiField> processor,
@NotNull GlobalSearchScope scope,
@Nullable IdFilter filter) {
for (PsiShortNamesCache cache : myCaches) {
if (!cache.processFieldsWithName(key, processor, scope, filter)) return false;
}
return true;
}
@Override
public boolean processClassesWithName(@NotNull String key,
@NotNull Processor<? super PsiClass> processor,
@NotNull GlobalSearchScope scope,
@Nullable IdFilter filter) {
for (PsiShortNamesCache cache : myCaches) {
if (!cache.processClassesWithName(key, processor, scope, filter)) return false;
}
return true;
}
private static class Merger<T> {
private T[] mySingleItem;
private Set<T> myAllItems;
public void add(@NotNull T[] items) {
if (items.length == 0) return;
if (mySingleItem == null) {
mySingleItem = items;
return;
}
if (myAllItems == null) {
T[] elements = mySingleItem;
myAllItems = ContainerUtil.addAll(new THashSet<>(elements.length), elements);
}
ContainerUtil.addAll(myAllItems, items);
}
public T[] getResult() {
if (myAllItems == null) return mySingleItem;
return myAllItems.toArray(mySingleItem);
}
}
@SuppressWarnings({"HardCodedStringLiteral"})
@Override
public String toString() {
return "Composite cache: " + Arrays.asList(myCaches);
}
}
| jk1/intellij-community | java/java-indexing-impl/src/com/intellij/psi/impl/CompositeShortNamesCache.java | Java | apache-2.0 | 10,218 |
/*************************GO-LICENSE-START*********************************
* Copyright 2014 ThoughtWorks, 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.
*************************GO-LICENSE-END***********************************/
package com.thoughtworks.go.domain.materials.git;
import com.thoughtworks.go.domain.materials.Modification;
import com.thoughtworks.go.util.DateUtils;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GitModificationParser {
private LinkedList<Modification> modifications = new LinkedList<>();
private static final String SPACES = "\\s+";
private static final String COMMENT_INDENT = "\\s{4}";
private static final String COMMENT_TEXT = "(.*)";
private static final String HASH = "(\\w+)";
private static final String DATE = "(.+)";
private static final String AUTHOR = "(.+)";
private static final Pattern COMMIT_PATTERN = Pattern.compile("^commit" + SPACES + HASH + "$");
private static final Pattern AUTHOR_PATTERN = Pattern.compile("^Author:"+ SPACES + AUTHOR + "$");
private static final Pattern DATE_PATTERN = Pattern.compile("^Date:" + SPACES + DATE + "$");
private static final Pattern COMMENT_PATTERN = Pattern.compile("^" + COMMENT_INDENT + COMMENT_TEXT + "$");
public List<Modification> parse(List<String> output) {
for (String line : output) {
processLine(line);
}
return modifications;
}
public List<Modification> getModifications() {
return modifications;
}
public void processLine(String line) {
Matcher matcher = COMMIT_PATTERN.matcher(line);
if (matcher.matches()) {
modifications.add(new Modification("", "", null, null, matcher.group(1)));
}
Matcher authorMatcher = AUTHOR_PATTERN.matcher(line);
if (authorMatcher.matches()) {
modifications.getLast().setUserName(authorMatcher.group(1));
}
Matcher dateMatcher = DATE_PATTERN.matcher(line);
if (dateMatcher.matches()) {
modifications.getLast().setModifiedTime(DateUtils.parseISO8601(dateMatcher.group(1)));
}
Matcher commentMatcher = COMMENT_PATTERN.matcher(line);
if (commentMatcher.matches()) {
Modification last = modifications.getLast();
String comment = Optional.ofNullable(last.getComment()).orElse("");
if (!comment.isEmpty()) comment += "\n";
last.setComment(comment + commentMatcher.group(1));
}
}
}
| varshavaradarajan/gocd | domain/src/main/java/com/thoughtworks/go/domain/materials/git/GitModificationParser.java | Java | apache-2.0 | 3,128 |
/*
* $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.struts2.showcase.chat;
import java.io.Serializable;
import java.util.Date;
/**
* Represends a user in the Chat example.
*/
public class User implements Serializable {
private static final long serialVersionUID = -1434958919516089297L;
private String name;
private Date creationDate;
public User(String name) {
this.name = name;
this.creationDate = new Date(System.currentTimeMillis());
}
public Date getCreationDate() {
return creationDate;
}
public String getName() {
return name;
}
}
| Ile2/struts2-showcase-demo | src/apps/showcase/src/main/java/org/apache/struts2/showcase/chat/User.java | Java | apache-2.0 | 1,350 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.svn;
import com.intellij.openapi.vcs.VcsConfiguration;
import com.intellij.openapi.vcs.changes.Change;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.vcsUtil.VcsUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.idea.svn.conflict.ConflictAction;
import org.jetbrains.idea.svn.conflict.ConflictOperation;
import org.jetbrains.idea.svn.conflict.ConflictVersion;
import org.jetbrains.idea.svn.conflict.TreeConflictDescription;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.util.function.BiConsumer;
import static com.intellij.testFramework.EdtTestUtil.runInEdtAndWait;
import static org.junit.Assert.*;
public class SvnTreeConflictDataTest extends SvnTestCase {
private VirtualFile myTheirs;
private SvnClientRunnerImpl mySvnClientRunner;
@Override
@Before
public void before() throws Exception {
myWcRootName = "wcRootConflictData";
myTraceClient = true;
super.before();
disableSilentOperation(VcsConfiguration.StandardConfirmation.ADD);
myTheirs = myTempDirFixture.findOrCreateDir("theirs");
mySvnClientRunner = new SvnClientRunnerImpl(myRunner);
mySvnClientRunner.checkout(myRepoUrl, myTheirs);
}
@Test
public void testFile2File_MINE_UNV_THEIRS_ADD() throws Exception {
assertConflict(TreeConflictData.FileToFile.MINE_UNV_THEIRS_ADD, false, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction());
assertNull(beforeDescription.getSourceLeftVersion());
final ConflictVersion version = beforeDescription.getSourceRightVersion();
assertNotNull(version);
assertTrue(version.isFile());
});
}
@Test
public void testFile2File_MINE_EDIT_THEIRS_DELETE() throws Exception {
assertConflict(TreeConflictData.FileToFile.MINE_EDIT_THEIRS_DELETE, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.DELETE, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion();
assertNotNull(leftVersion);
assertTrue(leftVersion.isFile());
final ConflictVersion version = beforeDescription.getSourceRightVersion();
assertNotNull(version);
assertTrue(version.isNone());
});
}
private String createConflict(@NotNull TreeConflictData.Data data, boolean createSubtree) throws Exception {
if (createSubtree) {
mySvnClientRunner.testSvnVersion(myWorkingCopyDir);
createSubTree();
}
runInEdtAndWait(() -> new ConflictCreator(vcs, myTheirs, myWorkingCopyDir, data, mySvnClientRunner).create());
return data.getConflictFile();
}
@Test
public void testFile2File_MINE_DELETE_THEIRS_EDIT() throws Exception {
assertConflict(TreeConflictData.FileToFile.MINE_DELETE_THEIRS_EDIT, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.EDIT, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion();
assertNotNull(leftVersion);
assertTrue(leftVersion.isFile());
final ConflictVersion version = beforeDescription.getSourceRightVersion();
assertNotNull(version);
assertTrue(version.isFile());
});
}
@Test
public void testFile2File_MINE_EDIT_THEIRS_MOVE() throws Exception {
assertConflict(TreeConflictData.FileToFile.MINE_EDIT_THEIRS_MOVE, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.DELETE, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion();
assertNotNull(leftVersion);
assertTrue(leftVersion.isFile());
final ConflictVersion version = beforeDescription.getSourceRightVersion();
assertNotNull(version);
assertTrue(version.isNone());
});
}
@Test
public void testFile2File_MINE_UNV_THEIRS_MOVE() throws Exception {
assertConflict(TreeConflictData.FileToFile.MINE_UNV_THEIRS_MOVE, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion();
assertNull(leftVersion);
final ConflictVersion version = beforeDescription.getSourceRightVersion();
assertNotNull(version);
assertTrue(version.isFile());
});
}
@Test
public void testFile2File_MINE_MOVE_THEIRS_EDIT() throws Exception {
assertConflict(TreeConflictData.FileToFile.MINE_MOVE_THEIRS_EDIT, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.EDIT, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion();
assertNotNull(leftVersion);
assertTrue(leftVersion.isFile());
final ConflictVersion version = beforeDescription.getSourceRightVersion();
assertNotNull(version);
assertTrue(version.isFile());
});
}
@Test
public void testFile2File_MINE_MOVE_THEIRS_ADD() throws Exception {
assertConflict(TreeConflictData.FileToFile.MINE_MOVE_THEIRS_ADD, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion();
assertNull(leftVersion);
//Assert.assertEquals(NodeKind.FILE, leftVersion.getKind());
final ConflictVersion version = beforeDescription.getSourceRightVersion();
assertNotNull(version);
assertTrue(version.isFile());
});
}
//---------------------------------- dirs --------------------------------------------------------
@Test
public void testDir2Dir_MINE_UNV_THEIRS_ADD() throws Exception {
assertConflict(TreeConflictData.DirToDir.MINE_UNV_THEIRS_ADD, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion();
assertNull(leftVersion);
final ConflictVersion version = beforeDescription.getSourceRightVersion();
assertNotNull(version);
assertTrue(version.isDirectory());
});
}
// not a conflict in Subversion 1.7.7. "mine" file becomes added
/*@Test
public void testDir2Dir_MINE_EDIT_THEIRS_DELETE() throws Exception {
final String conflictFile = createConflict(TreeConflictData.DirToDir.MINE_EDIT_THEIRS_DELETE);
VcsDirtyScopeManager.getInstance(myProject).markEverythingDirty();
ChangeListManager changeListManager = ChangeListManager.getInstance(myProject);
changeListManager.ensureUpToDate(false);
VirtualFile vf = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(new File(myWorkingCopyDir.getPath(), conflictFile));
Assert.assertNotNull(vf);
final Change change = changeListManager.getChange(vf);
Assert.assertTrue(change instanceof ConflictedSvnChange);
TreeConflictDescription beforeDescription = ((ConflictedSvnChange)change).getBeforeDescription();
Assert.assertNotNull(beforeDescription);
final TreeConflictDescription afterDescription = ((ConflictedSvnChange)change).getAfterDescription();
Assert.assertNull(afterDescription);
Assert.assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
Assert.assertEquals(ConflictAction.DELETE, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion();
Assert.assertNotNull(leftVersion);
Assert.assertEquals(NodeKind.DIR, leftVersion.getKind());
final ConflictVersion version = beforeDescription.getSourceRightVersion();
Assert.assertNotNull(version);
Assert.assertEquals(NodeKind.NONE, version.getKind());
}*/
@Test
public void testDir2Dir_MINE_DELETE_THEIRS_EDIT() throws Exception {
assertConflict(TreeConflictData.DirToDir.MINE_DELETE_THEIRS_EDIT, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.EDIT, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion();
assertNotNull(leftVersion);
assertTrue(leftVersion.isDirectory());
final ConflictVersion version = beforeDescription.getSourceRightVersion();
assertNotNull(version);
assertTrue(version.isDirectory());
});
}
@Test
public void testDir2Dir_MINE_EDIT_THEIRS_MOVE() throws Exception {
assertConflict(TreeConflictData.DirToDir.MINE_EDIT_THEIRS_MOVE, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.DELETE, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion();
assertNotNull(leftVersion);
assertTrue(leftVersion.isDirectory());
final ConflictVersion version = beforeDescription.getSourceRightVersion();
assertNotNull(version);
assertTrue(version.isNone());
});
}
@Test
public void testDir2Dir_MINE_UNV_THEIRS_MOVE() throws Exception {
assertConflict(TreeConflictData.DirToDir.MINE_UNV_THEIRS_MOVE, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion();
assertNull(leftVersion);
final ConflictVersion version = beforeDescription.getSourceRightVersion();
assertNotNull(version);
assertTrue(version.isDirectory());
});
}
@Test
public void testDir2Dir_MINE_MOVE_THEIRS_EDIT() throws Exception {
assertConflict(TreeConflictData.DirToDir.MINE_MOVE_THEIRS_EDIT, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.EDIT, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion();
assertNotNull(leftVersion);
assertTrue(leftVersion.isDirectory());
final ConflictVersion version = beforeDescription.getSourceRightVersion();
assertNotNull(version);
assertTrue(version.isDirectory());
});
}
@Test
public void testDir2Dir_MINE_MOVE_THEIRS_ADD() throws Exception {
assertConflict(TreeConflictData.DirToDir.MINE_MOVE_THEIRS_ADD, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion();
assertNull(leftVersion);
//Assert.assertEquals(NodeKind.DIR, leftVersion.getKind());
final ConflictVersion version = beforeDescription.getSourceRightVersion();
assertNotNull(version);
assertTrue(version.isDirectory());
});
}
//---------------------------------
@Test
public void testFile2Dir_MINE_UNV_THEIRS_ADD() throws Exception {
assertConflict(TreeConflictData.FileToDir.MINE_UNV_THEIRS_ADD, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion();
assertNull(leftVersion);
final ConflictVersion version = beforeDescription.getSourceRightVersion();
assertNotNull(version);
assertTrue(version.isDirectory());
});
}
@Test
public void testFile2Dir_MINE_ADD_THEIRS_ADD() throws Exception {
assertConflict(TreeConflictData.FileToDir.MINE_ADD_THEIRS_ADD, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion();
assertNull(leftVersion);
final ConflictVersion version = beforeDescription.getSourceRightVersion();
assertNotNull(version);
assertTrue(version.isDirectory());
});
}
@Test
public void testFile2Dir_MINE_UNV_THEIRS_MOVE() throws Exception {
assertConflict(TreeConflictData.FileToDir.MINE_UNV_THEIRS_MOVE, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion();
assertNull(leftVersion);
final ConflictVersion version = beforeDescription.getSourceRightVersion();
assertNotNull(version);
assertTrue(version.isDirectory());
});
}
@Test
public void testFile2Dir_MINE_ADD_THEIRS_MOVE() throws Exception {
assertConflict(TreeConflictData.FileToDir.MINE_ADD_THEIRS_MOVE, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion();
assertNull(leftVersion);
final ConflictVersion version = beforeDescription.getSourceRightVersion();
assertNotNull(version);
assertTrue(version.isDirectory());
});
}
@Test
public void testFile2Dir_MINE_MOVE_THEIRS_ADD() throws Exception {
assertConflict(TreeConflictData.FileToDir.MINE_MOVE_THEIRS_ADD, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion();
assertNull(leftVersion);
final ConflictVersion version = beforeDescription.getSourceRightVersion();
assertNotNull(version);
assertTrue(version.isDirectory());
});
}
//******************************************
// dir -> file (mine, theirs)
@Test
public void testDir2File_MINE_UNV_THEIRS_ADD() throws Exception {
assertConflict(TreeConflictData.DirToFile.MINE_UNV_THEIRS_ADD, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion();
assertNull(leftVersion);
final ConflictVersion version = beforeDescription.getSourceRightVersion();
assertNotNull(version);
assertTrue(version.isFile());
});
}
@Test
public void testDir2File_MINE_ADD_THEIRS_ADD() throws Exception {
assertConflict(TreeConflictData.DirToFile.MINE_ADD_THEIRS_ADD, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion();
assertNull(leftVersion);
final ConflictVersion version = beforeDescription.getSourceRightVersion();
assertNotNull(version);
assertTrue(version.isFile());
});
}
@Test
public void testDir2File_MINE_UNV_THEIRS_MOVE() throws Exception {
assertConflict(TreeConflictData.DirToFile.MINE_UNV_THEIRS_MOVE, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion();
assertNull(leftVersion);
final ConflictVersion version = beforeDescription.getSourceRightVersion();
assertNotNull(version);
assertTrue(version.isFile());
});
}
@Test
public void testDir2File_MINE_ADD_THEIRS_MOVE() throws Exception {
assertConflict(TreeConflictData.DirToFile.MINE_ADD_THEIRS_MOVE, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion();
assertNull(leftVersion);
final ConflictVersion version = beforeDescription.getSourceRightVersion();
assertNotNull(version);
assertTrue(version.isFile());
});
}
@Test
public void testDir2File_MINE_MOVE_THEIRS_ADD() throws Exception {
assertConflict(TreeConflictData.DirToFile.MINE_MOVE_THEIRS_ADD, (beforeDescription, afterDescription) -> {
assertEquals(ConflictOperation.UPDATE, beforeDescription.getOperation());
assertEquals(ConflictAction.ADD, beforeDescription.getConflictAction());
ConflictVersion leftVersion = beforeDescription.getSourceLeftVersion();
assertNull(leftVersion);
final ConflictVersion version = beforeDescription.getSourceRightVersion();
assertNotNull(version);
assertTrue(version.isFile());
});
}
private void createSubTree() throws Exception {
enableSilentOperation(VcsConfiguration.StandardConfirmation.ADD);
enableSilentOperation(VcsConfiguration.StandardConfirmation.REMOVE);
new SubTree(myWorkingCopyDir);
mySvnClientRunner.checkin(myWorkingCopyDir);
mySvnClientRunner.update(myTheirs);
mySvnClientRunner.update(myWorkingCopyDir);
disableSilentOperation(VcsConfiguration.StandardConfirmation.ADD);
disableSilentOperation(VcsConfiguration.StandardConfirmation.REMOVE);
}
private void assertConflict(@NotNull TreeConflictData.Data data,
@NotNull BiConsumer<TreeConflictDescription, TreeConflictDescription> checker) throws Exception {
assertConflict(data, true, checker);
}
private void assertConflict(@NotNull TreeConflictData.Data data,
boolean createSubtree,
@NotNull BiConsumer<TreeConflictDescription, TreeConflictDescription> checker) throws Exception {
String conflictFile = createConflict(data, createSubtree);
refreshChanges();
Change change;
if (data == TreeConflictData.DirToDir.MINE_DELETE_THEIRS_EDIT ||
data == TreeConflictData.DirToDir.MINE_MOVE_THEIRS_EDIT ||
data == TreeConflictData.DirToDir.MINE_MOVE_THEIRS_ADD) {
change = changeListManager.getChange(VcsUtil.getFilePath(new File(myWorkingCopyDir.getPath(), conflictFile), true));
}
else {
VirtualFile vf = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(new File(myWorkingCopyDir.getPath(), conflictFile));
assertNotNull(vf);
change = changeListManager.getChange(vf);
}
assertTrue(change instanceof ConflictedSvnChange);
TreeConflictDescription beforeDescription = ((ConflictedSvnChange)change).getBeforeDescription();
TreeConflictDescription afterDescription = ((ConflictedSvnChange)change).getAfterDescription();
assertNotNull(beforeDescription);
assertNull(afterDescription);
checker.accept(beforeDescription, afterDescription);
}
}
| smmribeiro/intellij-community | plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnTreeConflictDataTest.java | Java | apache-2.0 | 20,363 |
/*
* Copyright (C) 2015 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.
*/
package com.github.retrofit2.app;
import auto.parcel.AutoParcel;
import android.os.Parcelable;
import android.support.annotation.Nullable;
@AutoParcel
public abstract class Item implements Parcelable {
@Nullable
public abstract String icon();
@Nullable
public abstract String text1();
@AutoParcel.Builder
public abstract static class Builder {
public abstract Builder icon(String s);
public abstract Builder text1(String s);
public abstract Item build();
}
public static Builder builder() {
return new AutoParcel_Item.Builder();
}
public abstract Builder toBuilder();
}
| yongjhih/NotRetrofit | retrofit2-github-app/src/main/java/com/github/retrofit2/app/Item.java | Java | apache-2.0 | 1,268 |
package org.jboss.resteasy.api.validation;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author <a href="ron.sigal@jboss.com">Ron Sigal</a>
* @version $Revision: 1.1 $
*
* Copyright Jun 4, 2013
*/
@XmlRootElement(name="resteasyConstraintViolation")
@XmlAccessorType(XmlAccessType.FIELD)
public class ResteasyConstraintViolation implements Serializable
{
private static final long serialVersionUID = -5441628046215135260L;
private ConstraintType.Type constraintType;
private String path;
private String message;
private String value;
public ResteasyConstraintViolation(ConstraintType.Type constraintType, String path, String message, String value)
{
this.constraintType = constraintType;
this.path = path;
this.message = message;
this.value = value;
}
public ResteasyConstraintViolation()
{
}
/**
* @return type of constraint
*/
public ConstraintType.Type getConstraintType()
{
return constraintType;
}
/**
* @return description of element violating constraint
*/
public String getPath()
{
return path;
}
/**
* @return description of constraint violation
*/
public String getMessage()
{
return message;
}
/**
* @return object in violation of constraint
*/
public String getValue()
{
return value;
}
/**
* @return String representation of violation
*/
public String toString()
{
return "[" + type() + "]\r[" + path + "]\r[" + message + "]\r[" + value + "]\r";
}
/**
* @return String form of violation type
*/
public String type()
{
return constraintType.toString();
}
} | psakar/Resteasy | resteasy-jaxrs/src/main/java/org/jboss/resteasy/api/validation/ResteasyConstraintViolation.java | Java | apache-2.0 | 1,810 |
/*
* Copyright 2004-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.compass.core.lucene.engine.optimizer;
import java.io.IOException;
import org.apache.lucene.index.LuceneSubIndexInfo;
import org.compass.core.engine.SearchEngineException;
import org.compass.core.lucene.engine.manager.LuceneSearchEngineIndexManager;
/**
* @author kimchy
*/
public abstract class AbstractIndexInfoOptimizer extends AbstractOptimizer {
protected void doOptimize(String subIndex) throws SearchEngineException {
LuceneSubIndexInfo indexInfo = doGetIndexInfo(subIndex);
if (indexInfo == null) {
return;
}
doOptimize(subIndex, indexInfo);
}
protected void doForceOptimize(String subIndex) throws SearchEngineException {
LuceneSubIndexInfo indexInfo = doGetIndexInfo(subIndex);
if (indexInfo == null) {
return;
}
doForceOptimize(subIndex, indexInfo);
}
protected LuceneSubIndexInfo doGetIndexInfo(String subIndex) {
LuceneSearchEngineIndexManager indexManager = getSearchEngineFactory().getLuceneIndexManager();
LuceneSubIndexInfo indexInfo;
try {
indexInfo = LuceneSubIndexInfo.getIndexInfo(subIndex, indexManager);
} catch (IOException e) {
throw new SearchEngineException("Failed to read index info for sub index [" + subIndex + "]", e);
}
if (indexInfo == null) {
// no index data, simply continue
return null;
}
if (!isRunning()) {
return null;
}
return indexInfo;
}
protected abstract void doOptimize(String subIndex, LuceneSubIndexInfo indexInfo) throws SearchEngineException;
protected abstract void doForceOptimize(String subIndex, LuceneSubIndexInfo indexInfo) throws SearchEngineException;
}
| baboune/compass | src/main/src/org/compass/core/lucene/engine/optimizer/AbstractIndexInfoOptimizer.java | Java | apache-2.0 | 2,416 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.stubindex;
import com.intellij.openapi.project.Project;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.stubs.StubIndex;
import com.intellij.psi.stubs.StubIndexKey;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.psi.KtNamedFunction;
import java.util.Collection;
/**
* Stores package top level function (both extension and non-extension) full qualified names.
*/
public class KotlinTopLevelFunctionFqnNameIndex extends AbstractStringStubIndexExtension<KtNamedFunction> {
private static final StubIndexKey<String, KtNamedFunction> KEY = KotlinIndexUtil.createIndexKey(KotlinTopLevelFunctionFqnNameIndex.class);
private static final KotlinTopLevelFunctionFqnNameIndex INSTANCE = new KotlinTopLevelFunctionFqnNameIndex();
@NotNull
public static KotlinTopLevelFunctionFqnNameIndex getInstance() {
return INSTANCE;
}
private KotlinTopLevelFunctionFqnNameIndex() {
super(KtNamedFunction.class);
}
@NotNull
@Override
public StubIndexKey<String, KtNamedFunction> getKey() {
return KEY;
}
@NotNull
@Override
public Collection<KtNamedFunction> get(@NotNull String s, @NotNull Project project, @NotNull GlobalSearchScope scope) {
return StubIndex.getElements(KEY, s, project, scope, KtNamedFunction.class);
}
// temporary hack, see comments in findCandidateDeclarationsInIndex (findDecompiledDeclaration.kt)
@NotNull
public Collection<KtNamedFunction> getNoScopeWrap(@NotNull String s, @NotNull Project project, @NotNull GlobalSearchScope scope) {
return StubIndex.getElements(KEY, s, project, scope, KtNamedFunction.class);
}
}
| smmribeiro/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinTopLevelFunctionFqnNameIndex.java | Java | apache-2.0 | 1,887 |
/*
* 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 gov.nasa.jpl.mudrod.ssearch.ranking;
import gov.nasa.jpl.mudrod.discoveryengine.MudrodAbstract;
import gov.nasa.jpl.mudrod.driver.ESDriver;
import gov.nasa.jpl.mudrod.driver.SparkDriver;
import gov.nasa.jpl.mudrod.main.MudrodConstants;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
/**
* Supports the ability to importing training set into Elasticsearch
*/
public class TrainingImporter extends MudrodAbstract {
/**
*
*/
private static final long serialVersionUID = 1L;
public TrainingImporter(Properties props, ESDriver es, SparkDriver spark) {
super(props, es, spark);
es.deleteAllByQuery(props.getProperty(MudrodConstants.ES_INDEX_NAME), "trainingranking", QueryBuilders.matchAllQuery());
addMapping();
}
/**
* Method of adding mapping to traning set type
*/
public void addMapping() {
XContentBuilder Mapping;
try {
Mapping = jsonBuilder().startObject().startObject("trainingranking").startObject("properties").startObject("query").field("type", "string").field("index", "not_analyzed").endObject()
.startObject("dataID").field("type", "string").field("index", "not_analyzed").endObject().startObject("label").field("type", "string").field("index", "not_analyzed").endObject().endObject()
.endObject().endObject();
es.getClient().admin().indices().preparePutMapping(props.getProperty("indexName")).setType("trainingranking").setSource(Mapping).execute().actionGet();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Method of importing training set in to Elasticsearch
*
* @param dataFolder the path to the traing set
* @throws IOException IOException
*/
public void importTrainingSet(String dataFolder) throws IOException {
es.createBulkProcessor();
File[] files = new File(dataFolder).listFiles();
for (File file : files) {
BufferedReader br = new BufferedReader(new FileReader(file.getAbsolutePath()));
br.readLine();
String line = br.readLine();
while (line != null) {
String[] list = line.split(",");
String query = file.getName().replace(".csv", "");
if (list.length > 0) {
IndexRequest ir = new IndexRequest(props.getProperty("indexName"), "trainingranking")
.source(jsonBuilder().startObject().field("query", query).field("dataID", list[0]).field("label", list[list.length - 1]).endObject());
es.getBulkProcessor().add(ir);
}
line = br.readLine();
}
br.close();
}
es.destroyBulkProcessor();
}
}
| quintinali/mudrod | core/src/main/java/gov/nasa/jpl/mudrod/ssearch/ranking/TrainingImporter.java | Java | apache-2.0 | 3,467 |
/*
* 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.pdfbox.text;
import java.io.InputStream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.pdfbox.contentstream.PDFStreamEngine;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.font.encoding.GlyphList;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDSimpleFont;
import org.apache.pdfbox.pdmodel.font.PDType3Font;
import org.apache.pdfbox.pdmodel.graphics.state.PDGraphicsState;
import java.io.IOException;
import org.apache.pdfbox.util.Matrix;
import org.apache.pdfbox.util.Vector;
import org.apache.pdfbox.contentstream.operator.DrawObject;
import org.apache.pdfbox.contentstream.operator.state.Concatenate;
import org.apache.pdfbox.contentstream.operator.state.Restore;
import org.apache.pdfbox.contentstream.operator.state.Save;
import org.apache.pdfbox.contentstream.operator.state.SetGraphicsStateParameters;
import org.apache.pdfbox.contentstream.operator.state.SetMatrix;
import org.apache.pdfbox.contentstream.operator.text.BeginText;
import org.apache.pdfbox.contentstream.operator.text.EndText;
import org.apache.pdfbox.contentstream.operator.text.SetFontAndSize;
import org.apache.pdfbox.contentstream.operator.text.SetTextHorizontalScaling;
import org.apache.pdfbox.contentstream.operator.text.ShowTextAdjusted;
import org.apache.pdfbox.contentstream.operator.text.ShowTextLine;
import org.apache.pdfbox.contentstream.operator.text.ShowTextLineAndSpace;
import org.apache.pdfbox.contentstream.operator.text.MoveText;
import org.apache.pdfbox.contentstream.operator.text.MoveTextSetLeading;
import org.apache.pdfbox.contentstream.operator.text.NextLine;
import org.apache.pdfbox.contentstream.operator.text.SetCharSpacing;
import org.apache.pdfbox.contentstream.operator.text.SetTextLeading;
import org.apache.pdfbox.contentstream.operator.text.SetTextRenderingMode;
import org.apache.pdfbox.contentstream.operator.text.SetTextRise;
import org.apache.pdfbox.contentstream.operator.text.SetWordSpacing;
import org.apache.pdfbox.contentstream.operator.text.ShowText;
/**
* PDFStreamEngine subclass for advanced processing of text via TextPosition.
*
* @see org.apache.pdfbox.text.TextPosition
* @author Ben Litchfield
* @author John Hewson
*/
class PDFTextStreamEngine extends PDFStreamEngine
{
private static final Log LOG = LogFactory.getLog(PDFTextStreamEngine.class);
private int pageRotation;
private PDRectangle pageSize;
private final GlyphList glyphList;
/**
* Constructor.
*/
PDFTextStreamEngine() throws IOException
{
addOperator(new BeginText());
addOperator(new Concatenate());
addOperator(new DrawObject()); // special text version
addOperator(new EndText());
addOperator(new SetGraphicsStateParameters());
addOperator(new Save());
addOperator(new Restore());
addOperator(new NextLine());
addOperator(new SetCharSpacing());
addOperator(new MoveText());
addOperator(new MoveTextSetLeading());
addOperator(new SetFontAndSize());
addOperator(new ShowText());
addOperator(new ShowTextAdjusted());
addOperator(new SetTextLeading());
addOperator(new SetMatrix());
addOperator(new SetTextRenderingMode());
addOperator(new SetTextRise());
addOperator(new SetWordSpacing());
addOperator(new SetTextHorizontalScaling());
addOperator(new ShowTextLine());
addOperator(new ShowTextLineAndSpace());
// load additional glyph list for Unicode mapping
String path = "org/apache/pdfbox/resources/glyphlist/additional.txt";
InputStream input = GlyphList.class.getClassLoader().getResourceAsStream(path);
glyphList = new GlyphList(GlyphList.getAdobeGlyphList(), input);
}
/**
* This will initialise and process the contents of the stream.
*
* @param page the page to process
* @throws java.io.IOException if there is an error accessing the stream.
*/
@Override
public void processPage(PDPage page) throws IOException
{
this.pageRotation = page.getRotation();
this.pageSize = page.getCropBox();
super.processPage(page);
}
/**
* This method was originally written by Ben Litchfield for PDFStreamEngine.
*/
@Override
protected void showGlyph(Matrix textRenderingMatrix, PDFont font, int code, String unicode,
Vector displacement) throws IOException
{
//
// legacy calculations which were previously in PDFStreamEngine
//
PDGraphicsState state = getGraphicsState();
Matrix ctm = state.getCurrentTransformationMatrix();
float fontSize = state.getTextState().getFontSize();
float horizontalScaling = state.getTextState().getHorizontalScaling() / 100f;
Matrix textMatrix = getTextMatrix();
// 1/2 the bbox is used as the height todo: why?
float glyphHeight = font.getBoundingBox().getHeight() / 2;
// transformPoint from glyph space -> text space
float height = font.getFontMatrix().transformPoint(0, glyphHeight).y;
// (modified) combined displacement, this is calculated *without* taking the character
// spacing and word spacing into account, due to legacy code in TextStripper
float tx = displacement.getX() * fontSize * horizontalScaling;
float ty = 0; // todo: support vertical writing mode
// (modified) combined displacement matrix
Matrix td = Matrix.getTranslateInstance(tx, ty);
// (modified) text rendering matrix
Matrix nextTextRenderingMatrix = td.multiply(textMatrix).multiply(ctm); // text space -> device space
float nextX = nextTextRenderingMatrix.getTranslateX();
float nextY = nextTextRenderingMatrix.getTranslateY();
// (modified) width and height calculations
float dxDisplay = nextX - textRenderingMatrix.getTranslateX();
float dyDisplay = height * textRenderingMatrix.getScalingFactorY();
//
// start of the original method
//
// Note on variable names. There are three different units being used in this code.
// Character sizes are given in glyph units, text locations are initially given in text
// units, and we want to save the data in display units. The variable names should end with
// Text or Disp to represent if the values are in text or disp units (no glyph units are
// saved).
float fontSizeText = getGraphicsState().getTextState().getFontSize();
float horizontalScalingText = getGraphicsState().getTextState().getHorizontalScaling()/100f;
//Matrix ctm = getGraphicsState().getCurrentTransformationMatrix();
float glyphSpaceToTextSpaceFactor = 1 / 1000f;
if (font instanceof PDType3Font)
{
// This will typically be 1000 but in the case of a type3 font
// this might be a different number
glyphSpaceToTextSpaceFactor = 1f / font.getFontMatrix().getScaleX();
}
float spaceWidthText = 0;
try
{
// to avoid crash as described in PDFBOX-614, see what the space displacement should be
spaceWidthText = font.getSpaceWidth() * glyphSpaceToTextSpaceFactor;
}
catch (Throwable exception)
{
LOG.warn(exception, exception);
}
if (spaceWidthText == 0)
{
spaceWidthText = font.getAverageFontWidth() * glyphSpaceToTextSpaceFactor;
// the average space width appears to be higher than necessary so make it smaller
spaceWidthText *= .80f;
}
if (spaceWidthText == 0)
{
spaceWidthText = 1.0f; // if could not find font, use a generic value
}
// the space width has to be transformed into display units
float spaceWidthDisplay = spaceWidthText * fontSizeText * horizontalScalingText *
textRenderingMatrix.getScalingFactorX() * ctm.getScalingFactorX();
// use our additional glyph list for Unicode mapping
unicode = font.toUnicode(code, glyphList);
// when there is no Unicode mapping available, Acrobat simply coerces the character code
// into Unicode, so we do the same. Subclasses of PDFStreamEngine don't necessarily want
// this, which is why we leave it until this point in PDFTextStreamEngine.
if (unicode == null)
{
if (font instanceof PDSimpleFont)
{
char c = (char) code;
unicode = new String(new char[] { c });
}
else
{
// Acrobat doesn't seem to coerce composite font's character codes, instead it
// skips them. See the "allah2.pdf" TestTextStripper file.
return;
}
}
processTextPosition(new TextPosition(pageRotation, pageSize.getWidth(),
pageSize.getHeight(), textRenderingMatrix, nextX, nextY,
dyDisplay, dxDisplay,
spaceWidthDisplay, unicode, new int[] { code } , font, fontSize,
(int)(fontSize * textRenderingMatrix.getScalingFactorX())));
}
/**
* A method provided as an event interface to allow a subclass to perform some specific
* functionality when text needs to be processed.
*
* @param text The text to be processed.
*/
protected void processTextPosition(TextPosition text)
{
// subclasses can override to provide specific functionality
}
}
| ZhenyaM/veraPDF-pdfbox | pdfbox/src/main/java/org/apache/pdfbox/text/PDFTextStreamEngine.java | Java | apache-2.0 | 10,595 |
#include "test_stl.h"
#include <QSet>
#include <QtTest/QtTest>
#include <vector>
#include <cstring>
#include <cwchar>
#include "../src/utils/stl.h"
void STLTest::testBufferArry() {
using utils::BufferArray;
// constructor
std::string test1("123456789abcdefg");
BufferArray buffer(test1);
QVERIFY(test1.size() + 1 == buffer.size());
QVERIFY(buffer.capacity() == buffer.size());
QVERIFY(strncmp(test1.data(), buffer.data(), test1.size()) == 0);
// operator[]
QVERIFY(test1[0] == '1');
QVERIFY(test1[1] == '2');
QVERIFY(test1[2] == '3');
// reserve
buffer.resize(30);
QVERIFY(buffer.capacity() == 30);
// shrink_to_fit
buffer.shrink_to_fit();
QVERIFY(buffer.capacity() == buffer.size());
// resize
buffer.resize(9);
std::string test2("12345678");
QVERIFY(test2.size() + 1 == buffer.size());
QVERIFY(buffer.capacity() > buffer.size());
QVERIFY(strncmp(test2.data(), buffer.data(), test2.size()) == 0);
// shrink_to_fit
buffer.shrink_to_fit();
QVERIFY(buffer.capacity() == buffer.size());
#ifdef UTILS_CXX11_MODE
// move
std::string test3("gqjdiw913abc_123d");
BufferArray other_buffer(test3);
buffer = std::move(other_buffer);
QVERIFY(test3.size() + 1 == buffer.size());
QVERIFY(buffer.capacity() == buffer.size());
QVERIFY(strncmp(test3.data(), buffer.data(), test3.size()) == 0);
// constructor2
const char test_string[] = "abcdefg";
size_t test_size = sizeof(test_string);
buffer = BufferArray(test_string);
QVERIFY(test_size == buffer.size());
QVERIFY(buffer.capacity() == buffer.size());
QVERIFY(memcmp(test_string, buffer.data(), test_size) == 0);
#endif
}
void STLTest::testWBufferArry() {
using utils::WBufferArray;
// constructor
std::wstring test1(L"123456789abcdefg");
WBufferArray buffer(test1);
QVERIFY(test1.size() + 1 == buffer.size());
QVERIFY(buffer.capacity() == buffer.size());
QVERIFY(wcsncmp(test1.data(), buffer.data(), test1.size()) == 0);
// operator[]
QVERIFY(test1[0] == L'1');
QVERIFY(test1[1] == L'2');
QVERIFY(test1[2] == L'3');
// reserve
buffer.resize(30);
QVERIFY(buffer.capacity() == 30);
// shrink_to_fit
buffer.shrink_to_fit();
QVERIFY(buffer.capacity() == buffer.size());
// resize
buffer.resize(9);
std::wstring test2(L"12345678");
QVERIFY(test2.size() + 1 == buffer.size());
QVERIFY(buffer.capacity() > buffer.size());
QVERIFY(wcsncmp(test2.data(), buffer.data(), test2.size()) == 0);
#ifdef UTILS_CXX11_MODE
// move
std::wstring test3(L"gqjdiw913abc_123d");
WBufferArray other_buffer(test3);
buffer = std::move(other_buffer);
QVERIFY(test3.size() + 1 == buffer.size());
QVERIFY(buffer.capacity() == buffer.size());
QVERIFY(wcsncmp(test3.data(), buffer.data(), test3.size()) == 0);
// constructor2
const wchar_t test_string[] = L"abcdefg";
size_t test_size = sizeof(test_string) / sizeof(wchar_t);
buffer = WBufferArray(test_string);
QVERIFY(test_size == buffer.size());
QVERIFY(buffer.capacity() == buffer.size());
QVERIFY(memcmp(test_string, buffer.data(), test_size) == 0);
#endif
}
QTEST_APPLESS_MAIN(STLTest)
| lucius-feng/seafile-client | tests/test_stl.cpp | C++ | apache-2.0 | 3,120 |
//
//Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
//Copyright (C) 2016 LunarG, Inc.
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions
//are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// Neither the name of 3Dlabs Inc. Ltd. 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 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.
//
#ifndef _LOCAL_INTERMEDIATE_INCLUDED_
#define _LOCAL_INTERMEDIATE_INCLUDED_
#include "../Include/intermediate.h"
#include "../Public/ShaderLang.h"
#include "Versions.h"
#include <algorithm>
#include <set>
class TInfoSink;
namespace glslang {
struct TVectorFields {
TVectorFields() { }
TVectorFields(int c0, int c1, int c2, int c3) : num(4)
{
offsets[0] = c0;
offsets[1] = c1;
offsets[2] = c2;
offsets[3] = c3;
}
int offsets[4];
int num;
};
//
// Some helper structures for TIntermediate. Their contents are encapsulated
// by TIntermediate.
//
// Used for detecting recursion: A "call" is a pair: <caller, callee>.
struct TCall {
TCall(const TString& pCaller, const TString& pCallee) : caller(pCaller), callee(pCallee) { }
TString caller;
TString callee;
bool visited;
bool currentPath;
bool errorGiven;
};
// A generic 1-D range.
struct TRange {
TRange(int start, int last) : start(start), last(last) { }
bool overlap(const TRange& rhs) const
{
return last >= rhs.start && start <= rhs.last;
}
int start;
int last;
};
// An IO range is a 3-D rectangle; the set of (location, component, index) triples all lying
// within the same location range, component range, and index value. Locations don't alias unless
// all other dimensions of their range overlap.
struct TIoRange {
TIoRange(TRange location, TRange component, TBasicType basicType, int index)
: location(location), component(component), basicType(basicType), index(index) { }
bool overlap(const TIoRange& rhs) const
{
return location.overlap(rhs.location) && component.overlap(rhs.component) && index == rhs.index;
}
TRange location;
TRange component;
TBasicType basicType;
int index;
};
// An offset range is a 2-D rectangle; the set of (binding, offset) pairs all lying
// within the same binding and offset range.
struct TOffsetRange {
TOffsetRange(TRange binding, TRange offset)
: binding(binding), offset(offset) { }
bool overlap(const TOffsetRange& rhs) const
{
return binding.overlap(rhs.binding) && offset.overlap(rhs.offset);
}
TRange binding;
TRange offset;
};
// Things that need to be tracked per xfb buffer.
struct TXfbBuffer {
TXfbBuffer() : stride(TQualifier::layoutXfbStrideEnd), implicitStride(0), containsDouble(false) { }
std::vector<TRange> ranges; // byte offsets that have already been assigned
unsigned int stride;
unsigned int implicitStride;
bool containsDouble;
};
class TSymbolTable;
class TSymbol;
class TVariable;
//
// Set of helper functions to help parse and build the tree.
//
class TIntermediate {
public:
explicit TIntermediate(EShLanguage l, int v = 0, EProfile p = ENoProfile) :
source(EShSourceNone), language(l), profile(p), version(v), treeRoot(0),
numMains(0), numErrors(0), numPushConstants(0), recursive(false),
invocations(TQualifier::layoutNotSet), vertices(TQualifier::layoutNotSet), inputPrimitive(ElgNone), outputPrimitive(ElgNone),
pixelCenterInteger(false), originUpperLeft(false),
vertexSpacing(EvsNone), vertexOrder(EvoNone), pointMode(false), earlyFragmentTests(false), depthLayout(EldNone), depthReplacing(false), blendEquations(0),
multiStream(false), xfbMode(false)
{
localSize[0] = 1;
localSize[1] = 1;
localSize[2] = 1;
localSizeSpecId[0] = TQualifier::layoutNotSet;
localSizeSpecId[1] = TQualifier::layoutNotSet;
localSizeSpecId[2] = TQualifier::layoutNotSet;
xfbBuffers.resize(TQualifier::layoutXfbBufferEnd);
}
void setLimits(const TBuiltInResource& r) { resources = r; }
bool postProcess(TIntermNode*, EShLanguage);
void output(TInfoSink&, bool tree);
void removeTree();
void setSource(EShSource s) { source = s; }
EShSource getSource() const { return source; }
void setEntryPoint(const char* ep) { entryPoint = ep; }
const std::string& getEntryPoint() const { return entryPoint; }
void setVersion(int v) { version = v; }
int getVersion() const { return version; }
void setProfile(EProfile p) { profile = p; }
EProfile getProfile() const { return profile; }
void setSpv(const SpvVersion& s) { spvVersion = s; }
const SpvVersion& getSpv() const { return spvVersion; }
EShLanguage getStage() const { return language; }
void addRequestedExtension(const char* extension) { requestedExtensions.insert(extension); }
const std::set<std::string>& getRequestedExtensions() const { return requestedExtensions; }
void setTreeRoot(TIntermNode* r) { treeRoot = r; }
TIntermNode* getTreeRoot() const { return treeRoot; }
void addMainCount() { ++numMains; }
int getNumMains() const { return numMains; }
int getNumErrors() const { return numErrors; }
void addPushConstantCount() { ++numPushConstants; }
bool isRecursive() const { return recursive; }
TIntermSymbol* addSymbol(const TVariable&);
TIntermSymbol* addSymbol(const TVariable&, const TSourceLoc&);
TIntermSymbol* addSymbol(const TType&, const TSourceLoc&);
TIntermTyped* addConversion(TOperator, const TType&, TIntermTyped*) const;
TIntermTyped* addShapeConversion(TOperator, const TType&, TIntermTyped*);
TIntermTyped* addBinaryMath(TOperator, TIntermTyped* left, TIntermTyped* right, TSourceLoc);
TIntermTyped* addAssign(TOperator op, TIntermTyped* left, TIntermTyped* right, TSourceLoc);
TIntermTyped* addIndex(TOperator op, TIntermTyped* base, TIntermTyped* index, TSourceLoc);
TIntermTyped* addUnaryMath(TOperator, TIntermTyped* child, TSourceLoc);
TIntermTyped* addBuiltInFunctionCall(const TSourceLoc& line, TOperator, bool unary, TIntermNode*, const TType& returnType);
bool canImplicitlyPromote(TBasicType from, TBasicType to, TOperator op = EOpNull) const;
TOperator mapTypeToConstructorOp(const TType&) const;
TIntermAggregate* growAggregate(TIntermNode* left, TIntermNode* right);
TIntermAggregate* growAggregate(TIntermNode* left, TIntermNode* right, const TSourceLoc&);
TIntermAggregate* makeAggregate(TIntermNode* node);
TIntermAggregate* makeAggregate(TIntermNode* node, const TSourceLoc&);
TIntermTyped* setAggregateOperator(TIntermNode*, TOperator, const TType& type, TSourceLoc);
bool areAllChildConst(TIntermAggregate* aggrNode);
TIntermNode* addSelection(TIntermTyped* cond, TIntermNodePair code, const TSourceLoc&);
TIntermTyped* addSelection(TIntermTyped* cond, TIntermTyped* trueBlock, TIntermTyped* falseBlock, const TSourceLoc&);
TIntermTyped* addComma(TIntermTyped* left, TIntermTyped* right, const TSourceLoc&);
TIntermTyped* addMethod(TIntermTyped*, const TType&, const TString*, const TSourceLoc&);
TIntermConstantUnion* addConstantUnion(const TConstUnionArray&, const TType&, const TSourceLoc&, bool literal = false) const;
TIntermConstantUnion* addConstantUnion(int, const TSourceLoc&, bool literal = false) const;
TIntermConstantUnion* addConstantUnion(unsigned int, const TSourceLoc&, bool literal = false) const;
TIntermConstantUnion* addConstantUnion(long long, const TSourceLoc&, bool literal = false) const;
TIntermConstantUnion* addConstantUnion(unsigned long long, const TSourceLoc&, bool literal = false) const;
TIntermConstantUnion* addConstantUnion(bool, const TSourceLoc&, bool literal = false) const;
TIntermConstantUnion* addConstantUnion(double, TBasicType, const TSourceLoc&, bool literal = false) const;
TIntermTyped* promoteConstantUnion(TBasicType, TIntermConstantUnion*) const;
bool parseConstTree(TIntermNode*, TConstUnionArray, TOperator, const TType&, bool singleConstantParam = false);
TIntermLoop* addLoop(TIntermNode*, TIntermTyped*, TIntermTyped*, bool testFirst, const TSourceLoc&);
TIntermAggregate* addForLoop(TIntermNode*, TIntermNode*, TIntermTyped*, TIntermTyped*, bool testFirst, const TSourceLoc&);
TIntermBranch* addBranch(TOperator, const TSourceLoc&);
TIntermBranch* addBranch(TOperator, TIntermTyped*, const TSourceLoc&);
TIntermTyped* addSwizzle(TVectorFields&, const TSourceLoc&);
// Constant folding (in Constant.cpp)
TIntermTyped* fold(TIntermAggregate* aggrNode);
TIntermTyped* foldConstructor(TIntermAggregate* aggrNode);
TIntermTyped* foldDereference(TIntermTyped* node, int index, const TSourceLoc&);
TIntermTyped* foldSwizzle(TIntermTyped* node, TVectorFields& fields, const TSourceLoc&);
// Tree ops
static const TIntermTyped* findLValueBase(const TIntermTyped*, bool swizzleOkay);
// Linkage related
void addSymbolLinkageNodes(TIntermAggregate*& linkage, EShLanguage, TSymbolTable&);
void addSymbolLinkageNode(TIntermAggregate*& linkage, TSymbolTable&, const TString&);
void addSymbolLinkageNode(TIntermAggregate*& linkage, const TSymbol&);
bool setInvocations(int i)
{
if (invocations != TQualifier::layoutNotSet)
return invocations == i;
invocations = i;
return true;
}
int getInvocations() const { return invocations; }
bool setVertices(int m)
{
if (vertices != TQualifier::layoutNotSet)
return vertices == m;
vertices = m;
return true;
}
int getVertices() const { return vertices; }
bool setInputPrimitive(TLayoutGeometry p)
{
if (inputPrimitive != ElgNone)
return inputPrimitive == p;
inputPrimitive = p;
return true;
}
TLayoutGeometry getInputPrimitive() const { return inputPrimitive; }
bool setVertexSpacing(TVertexSpacing s)
{
if (vertexSpacing != EvsNone)
return vertexSpacing == s;
vertexSpacing = s;
return true;
}
TVertexSpacing getVertexSpacing() const { return vertexSpacing; }
bool setVertexOrder(TVertexOrder o)
{
if (vertexOrder != EvoNone)
return vertexOrder == o;
vertexOrder = o;
return true;
}
TVertexOrder getVertexOrder() const { return vertexOrder; }
void setPointMode() { pointMode = true; }
bool getPointMode() const { return pointMode; }
bool setLocalSize(int dim, int size)
{
if (localSize[dim] > 1)
return size == localSize[dim];
localSize[dim] = size;
return true;
}
unsigned int getLocalSize(int dim) const { return localSize[dim]; }
bool setLocalSizeSpecId(int dim, int id)
{
if (localSizeSpecId[dim] != TQualifier::layoutNotSet)
return id == localSizeSpecId[dim];
localSizeSpecId[dim] = id;
return true;
}
int getLocalSizeSpecId(int dim) const { return localSizeSpecId[dim]; }
void setXfbMode() { xfbMode = true; }
bool getXfbMode() const { return xfbMode; }
void setMultiStream() { multiStream = true; }
bool isMultiStream() const { return multiStream; }
bool setOutputPrimitive(TLayoutGeometry p)
{
if (outputPrimitive != ElgNone)
return outputPrimitive == p;
outputPrimitive = p;
return true;
}
TLayoutGeometry getOutputPrimitive() const { return outputPrimitive; }
void setOriginUpperLeft() { originUpperLeft = true; }
bool getOriginUpperLeft() const { return originUpperLeft; }
void setPixelCenterInteger() { pixelCenterInteger = true; }
bool getPixelCenterInteger() const { return pixelCenterInteger; }
void setEarlyFragmentTests() { earlyFragmentTests = true; }
bool getEarlyFragmentTests() const { return earlyFragmentTests; }
bool setDepth(TLayoutDepth d)
{
if (depthLayout != EldNone)
return depthLayout == d;
depthLayout = d;
return true;
}
TLayoutDepth getDepth() const { return depthLayout; }
void setDepthReplacing() { depthReplacing = true; }
bool isDepthReplacing() const { return depthReplacing; }
void addBlendEquation(TBlendEquationShift b) { blendEquations |= (1 << b); }
unsigned int getBlendEquations() const { return blendEquations; }
void addToCallGraph(TInfoSink&, const TString& caller, const TString& callee);
void merge(TInfoSink&, TIntermediate&);
void finalCheck(TInfoSink&);
void addIoAccessed(const TString& name) { ioAccessed.insert(name); }
bool inIoAccessed(const TString& name) const { return ioAccessed.find(name) != ioAccessed.end(); }
int addUsedLocation(const TQualifier&, const TType&, bool& typeCollision);
int checkLocationRange(int set, const TIoRange& range, const TType&, bool& typeCollision);
int addUsedOffsets(int binding, int offset, int numOffsets);
bool addUsedConstantId(int id);
int computeTypeLocationSize(const TType&) const;
bool setXfbBufferStride(int buffer, unsigned stride)
{
if (xfbBuffers[buffer].stride != TQualifier::layoutXfbStrideEnd)
return xfbBuffers[buffer].stride == stride;
xfbBuffers[buffer].stride = stride;
return true;
}
int addXfbBufferOffset(const TType&);
unsigned int computeTypeXfbSize(const TType&, bool& containsDouble) const;
static int getBaseAlignment(const TType&, int& size, int& stride, bool std140, bool rowMajor);
protected:
TIntermSymbol* addSymbol(int Id, const TString&, const TType&, const TConstUnionArray&, TIntermTyped* subtree, const TSourceLoc&);
void error(TInfoSink& infoSink, const char*);
void mergeBodies(TInfoSink&, TIntermSequence& globals, const TIntermSequence& unitGlobals);
void mergeLinkerObjects(TInfoSink&, TIntermSequence& linkerObjects, const TIntermSequence& unitLinkerObjects);
void mergeImplicitArraySizes(TType&, const TType&);
void mergeErrorCheck(TInfoSink&, const TIntermSymbol&, const TIntermSymbol&, bool crossStage);
void checkCallGraphCycles(TInfoSink&);
void inOutLocationCheck(TInfoSink&);
TIntermSequence& findLinkerObjects() const;
bool userOutputUsed() const;
static int getBaseAlignmentScalar(const TType&, int& size);
bool isSpecializationOperation(const TIntermOperator&) const;
const EShLanguage language; // stage, known at construction time
EShSource source; // source language, known a bit later
std::string entryPoint;
EProfile profile;
int version;
SpvVersion spvVersion;
TIntermNode* treeRoot;
std::set<std::string> requestedExtensions; // cumulation of all enabled or required extensions; not connected to what subset of the shader used them
TBuiltInResource resources;
int numMains;
int numErrors;
int numPushConstants;
bool recursive;
int invocations;
int vertices;
TLayoutGeometry inputPrimitive;
TLayoutGeometry outputPrimitive;
bool pixelCenterInteger;
bool originUpperLeft;
TVertexSpacing vertexSpacing;
TVertexOrder vertexOrder;
bool pointMode;
int localSize[3];
int localSizeSpecId[3];
bool earlyFragmentTests;
TLayoutDepth depthLayout;
bool depthReplacing;
int blendEquations; // an 'or'ing of masks of shifts of TBlendEquationShift
bool xfbMode;
bool multiStream;
typedef std::list<TCall> TGraph;
TGraph callGraph;
std::set<TString> ioAccessed; // set of names of statically read/written I/O that might need extra checking
std::vector<TIoRange> usedIo[4]; // sets of used locations, one for each of in, out, uniform, and buffers
std::vector<TOffsetRange> usedAtomics; // sets of bindings used by atomic counters
std::vector<TXfbBuffer> xfbBuffers; // all the data we need to track per xfb buffer
std::unordered_set<int> usedConstantId; // specialization constant ids used
private:
void operator=(TIntermediate&); // prevent assignments
};
} // end namespace glslang
#endif // _LOCAL_INTERMEDIATE_INCLUDED_
| eternity74/gapid | third_party/khronos/glslang/glslang/MachineIndependent/localintermediate.h | C | apache-2.0 | 17,502 |
/**
* Copyright 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.waveprotocol.wave.model.supplement;
import org.waveprotocol.wave.model.id.WaveletId;
import org.waveprotocol.wave.model.wave.SourcesEvents;
/**
*/
public interface ObservablePrimitiveSupplement extends PrimitiveSupplement,
SourcesEvents<ObservablePrimitiveSupplement.Listener> {
public interface Listener {
/**
* Notifies this listener that the last-read version of a blip has changed.
*/
void onLastReadBlipVersionChanged(WaveletId wid, String bid, int oldVersion, int newVersion);
/**
* Notifies this listener that the minimum last-read version of all wave
* parts has changed.
*/
void onLastReadWaveletVersionChanged(WaveletId wid, int oldVersion, int newVersion);
/**
* Notifies this listener that the last-read version of the
* participants-collection has changed.
*/
void onLastReadParticipantsVersionChanged(WaveletId wid, int oldVersion, int newVersion);
/**
* Notifies this listener that the last-read version of the tags has
* changed.
*/
void onLastReadTagsVersionChanged(WaveletId wid, int oldVersion, int newVersion);
/**
* Notifies this listener that the followed state has been set to true.
*/
void onFollowed();
/**
* Notifies this listener that the followed state has been set to false.
*/
void onUnfollowed();
/**
* Notifies this listener that the followed state has been cleared.
*/
void onFollowCleared();
/**
* Notifies this listener that last-archived version of a wavelet has
* changed.
*/
void onArchiveVersionChanged(WaveletId wid, int oldVersion, int newVersion);
/**
* Notifies this listener that archive value has been set.
*/
// TODO(hearnden/fabio) remove the 'cleared' field from the primitive model
void onArchiveClearChanged(boolean oldValue, boolean newValue);
/**
* Notifies this listener that a folder id has been added.
*/
void onFolderAdded(int newFolder);
/**
* Notifies this listener that a folder id has been removed.
*/
void onFolderRemoved(int oldFolder);
/**
* Notifies this listener that the wanted-evaluations of a wavelet has
* changed.
*/
void onWantedEvaluationsChanged(WaveletId wid);
/**
* Notifies this listener that a thread's state has been changed
* ThreadState values shall never be null.
*/
void onThreadStateChanged(WaveletId wid, String tid,
ThreadState oldState, ThreadState newState);
/**
* Notifies this listener that gadget state has been changed.
*/
void onGadgetStateChanged(String gadgetId, String key, String oldValue, String newValue);
}
}
| JaredMiller/Wave | src/org/waveprotocol/wave/model/supplement/ObservablePrimitiveSupplement.java | Java | apache-2.0 | 3,341 |
/*
* Copyright (c) 2013 Intel 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.
*/
#ifndef _VMEXIT_MSR_H_
#define _VMEXIT_MSR_H_
#include "list.h"
// return TRUE if instruction was executed, FAULSE in case of exception
typedef BOOLEAN (*MSR_ACCESS_HANDLER)(GUEST_CPU_HANDLE gcpu,
MSR_ID msr_id,
UINT64 *p_value,
void *context);
typedef struct _MSR_VMEXIT_CONTROL
{
UINT8 *msr_bitmap;
LIST_ELEMENT msr_list[1];
} MSR_VMEXIT_CONTROL;
// FUNCTION : msr_vmexit_on_all()
// PURPOSE : Turns VMEXIT on all ON/OFF
// ARGUMENTS: GUEST_CPU_HANDLE gcpu
// : BOOLEAN enable
// RETURNS : none, must succeed.
void msr_vmexit_on_all(GUEST_CPU_HANDLE gcpu, BOOLEAN enable) ;
// FUNCTION : msr_vmexit_guest_setup()
// PURPOSE : Allocates structures for MSR virtualization
// : Must be called prior any other function from the package on this gcpu,
// : but after gcpu VMCS was loaded
// ARGUMENTS: GUEST_HANDLE guest
// RETURNS : none, must succeed.
void msr_vmexit_guest_setup(GUEST_HANDLE guest);
// FUNCTION : msr_vmexit_activate()
// PURPOSE : Register MSR related structures with HW (VMCS)
// ARGUMENTS: GUEST_CPU_HANDLE gcpu
// RETURNS : none, must succeed.
void msr_vmexit_activate(GUEST_CPU_HANDLE gcpu);
// FUNCTION : msr_vmexit_handler_register()
// PURPOSE : Register specific MSR handler with VMEXIT
// ARGUMENTS: GUEST_HANDLE guest
// : MSR_ID msr_id
// : MSR_ACCESS_HANDLER msr_handler,
// : RW_ACCESS access
// : void *context
// RETURNS : VMM_OK if succeeded
VMM_STATUS msr_vmexit_handler_register( GUEST_HANDLE guest,
MSR_ID msr_id, MSR_ACCESS_HANDLER msr_handler,
RW_ACCESS access, void *context);
// FUNCTION : msr_vmexit_handler_unregister()
// PURPOSE : Unregister specific MSR VMEXIT handler
// ARGUMENTS: GUEST_HANDLE guest
// : MSR_ID msr_id
// RETURNS : VMM_OK if succeeded
VMM_STATUS msr_vmexit_handler_unregister( GUEST_HANDLE guest,
MSR_ID msr_id, RW_ACCESS access);
// FUNCTION : msr_guest_access_inhibit()
// PURPOSE : Install handler which prevents access to MSR from the guest space
// ARGUMENTS: GUEST_HANDLE guest
// : MSR_ID msr_id
// RETURNS : VMM_OK if succeeded
VMM_STATUS msr_guest_access_inhibit( GUEST_HANDLE guest,
MSR_ID msr_id);
// FUNCTION : msr_trial_access()
// PURPOSE : Try to execute real MSR read/write
// : If exception was generated, inject it into guest
// ARGUMENTS: GUEST_CPU_HANDLE gcpu
// : MSR_ID msr_id
// : RW_ACCESS access
// RETURNS : TRUE if instruction was executed, FALSE otherwise (fault occured)
BOOLEAN msr_trial_access( GUEST_CPU_HANDLE gcpu,
MSR_ID msr_id, RW_ACCESS access, UINT64 *msr_value);
// FUNCTION : vmexit_enable_disable_for_msr_in_exclude_list()
// PURPOSE : enable/disable msr read/write vmexit for msrs in the exclude list
// ARGUMENTS: GUEST_CPU_HANDLE gcpu
// : MSR_ID msr_id
// : RW_ACCESS access
// : BOOLEAN TRUE to enable write/read vmexit, FALSE to disable vmexit
// RETURNS : TRUE if parameters are correct.
BOOLEAN vmexit_register_unregister_for_efer( GUEST_HANDLE guest,
MSR_ID msr_id, RW_ACCESS access, BOOLEAN reg_dereg);
#endif // _VMEXIT_MSR_H_
| cjpatton/cloudproxy | cpvmm/vmm/include/vmexit_msr.h | C | apache-2.0 | 4,020 |
/*
* 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 com.taobao.weex.dom;
import android.support.v4.util.ArrayMap;
import com.alibaba.fastjson.JSONObject;
import com.taobao.weex.dom.binding.ELUtils;
import com.taobao.weex.dom.binding.JSONUtils;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Store value of component event
*/
public class WXEvent extends ArrayList<String> implements Serializable, Cloneable {
private static final long serialVersionUID = -8186587029452440107L;
/**
* event data format
* {
* type: 'appear',
* params: [
* { '@binding': 'index' },
* 'static',
* { '@binding': 'item.name' },
* { '@binding': '$event' }
* ]
* }
* */
public static final String EVENT_KEY_TYPE = "type";
public static final String EVENT_KEY_ARGS = "params";
/**
* dynamic binding event args, can be null, only weex use
* */
private ArrayMap mEventBindingArgs;
private ArrayMap<String, List<Object>> mEventBindingArgsValues;
@Override
public void clear() {
if(mEventBindingArgs != null){
mEventBindingArgs.clear();
}
if(mEventBindingArgsValues != null){
mEventBindingArgsValues.clear();
}
super.clear();
}
public boolean remove(String o) {
if(mEventBindingArgs != null){
mEventBindingArgs.remove(o);
}
if(mEventBindingArgsValues != null){
mEventBindingArgsValues.remove(o);
}
return super.remove(o);
}
/**
* can by null
* */
public ArrayMap getEventBindingArgs() {
return mEventBindingArgs;
}
public ArrayMap<String, List<Object>> getEventBindingArgsValues() {
return mEventBindingArgsValues;
}
public void addEvent(Object event) {
if(event instanceof CharSequence){
if(JSONUtils.isJSON(event.toString())){
addEvent(JSONUtils.toJSON(event.toString()));
return;
}
String eventName = event.toString();
if(!contains(eventName)){
add(eventName);
}
}else if(event instanceof JSONObject){
JSONObject bindings = (JSONObject) event;
addBindingEvent(bindings);
}
}
public static String getEventName(Object event){
if(event instanceof CharSequence){
return event.toString();
}else if(event instanceof JSONObject){
JSONObject bindings = (JSONObject) event;
String eventName = bindings.getString(WXEvent.EVENT_KEY_TYPE);
return eventName;
}
if(event == null){
return null;
}
return event.toString();
}
public void parseStatements() {
if(!isEmpty()){
for(int i=0; i<size(); i++){
String event = get(i);
if(JSONUtils.isJSON(event)){
JSONObject object = JSONUtils.toJSON(event);
String eventName = addBindingEvent(object);
set(i, eventName);
}
}
}
}
private String addBindingEvent(JSONObject bindings){
String eventName = bindings.getString(WXEvent.EVENT_KEY_TYPE);
Object args = bindings.get(WXEvent.EVENT_KEY_ARGS);
if (eventName != null) {
addBindingArgsEvent(eventName, args);
}
return eventName;
}
private void addBindingArgsEvent(String eventName, Object args){
if(!contains(eventName)){
add(eventName);
}
if(args != null){
if(mEventBindingArgs == null){
mEventBindingArgs = new ArrayMap();
}
mEventBindingArgs.put(eventName, ELUtils.bindingBlock(args));
}
}
public void putEventBindingArgsValue(String event, List<Object> value){
if(mEventBindingArgsValues == null){
mEventBindingArgsValues = new ArrayMap();
}
if(value == null){
mEventBindingArgsValues.remove(event);
}else{
mEventBindingArgsValues.put(event, value);
}
}
@Override
public WXEvent clone() {
WXEvent event = new WXEvent();
event.addAll(this);
if(mEventBindingArgs != null) {
event.mEventBindingArgs = new ArrayMap(mEventBindingArgs);
}
event.mEventBindingArgsValues = null; //this should not be clone, it dynamic args
return event;
}
}
| erha19/incubator-weex | android/sdk/src/main/java/com/taobao/weex/dom/WXEvent.java | Java | apache-2.0 | 4,905 |
package org.jb2011.lnf.beautyeye.winlnfutils.d;
///*
// * @(#)XPStyle.java 1.28 07/01/09
// *
// * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
// * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
// */
//
///*
// * <p>These classes are designed to be used while the
// * corresponding <code>LookAndFeel</code> class has been installed
// * (<code>UIManager.setLookAndFeel(new <i>XXX</i>LookAndFeel())</code>).
// * Using them while a different <code>LookAndFeel</code> is installed
// * may produce unexpected results, including exceptions.
// * Additionally, changing the <code>LookAndFeel</code>
// * maintained by the <code>UIManager</code> without updating the
// * corresponding <code>ComponentUI</code> of any
// * <code>JComponent</code>s may also produce unexpected results,
// * such as the wrong colors showing up, and is generally not
// * encouraged.
// *
// */
//
//package org.jb2011.lnf.beautyeye.winlnfutils;
//
//import java.awt.Color;
//import java.awt.Component;
//import java.awt.Dimension;
//import java.awt.Graphics;
//import java.awt.GraphicsConfiguration;
//import java.awt.Image;
//import java.awt.Insets;
//import java.awt.Point;
//import java.awt.Rectangle;
//import java.awt.Toolkit;
//import java.awt.image.BufferedImage;
//import java.awt.image.DataBufferInt;
//import java.awt.image.WritableRaster;
//import java.security.AccessController;
//import java.util.HashMap;
//
//import javax.swing.AbstractButton;
//import javax.swing.JButton;
//import javax.swing.JCheckBox;
//import javax.swing.JRadioButton;
//import javax.swing.JToolBar;
//import javax.swing.UIManager;
//import javax.swing.border.AbstractBorder;
//import javax.swing.border.Border;
//import javax.swing.border.EmptyBorder;
//import javax.swing.border.LineBorder;
//import javax.swing.plaf.ColorUIResource;
//import javax.swing.plaf.InsetsUIResource;
//import javax.swing.plaf.UIResource;
//import javax.swing.text.JTextComponent;
//
//import org.jb2011.lnf.beautyeye.winlnfutils.BETMSchema.Part;
//import org.jb2011.lnf.beautyeye.winlnfutils.BETMSchema.Prop;
//import org.jb2011.lnf.beautyeye.winlnfutils.BETMSchema.State;
//import org.jb2011.lnf.beautyeye.winlnfutils.BETMSchema.TypeEnum;
//
//import sun.awt.windows.ThemeReader;
//import sun.security.action.GetPropertyAction;
//import sun.swing.CachedPainter;
//
//import com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel;
//
///*
// * 本类实际就是XP主题包中的类,未作任何改变.
// * 代码参考java源码,仅作兼容性修改
// * Add by js 2009-09-01.
// */
///**
// * Implements Windows XP Styles for the Windows Look and Feel.
// *
// * @version 1.28 01/09/07
// * @author Leif Samuelsson
// */
//public class BEXPStyle {
// // Singleton instance of this class
// private static BEXPStyle xp;
//
// // Singleton instance of SkinPainter
// private static SkinPainter skinPainter = new SkinPainter();
//
// private static Boolean themeActive = null;
//
// private HashMap<String, Border> borderMap;
// private HashMap<String, Color> colorMap;
//
// private boolean flatMenus;
//
// static {
// invalidateStyle();
// }
//
// /** Static method for clearing the hashmap and loading the
// * current XP style and theme
// */
// static synchronized void invalidateStyle() {
// xp = null;
// themeActive = null;
// }
//
// /** Get the singleton instance of this class
// *
// * @return the singleton instance of this class or null if XP styles
// * are not active or if this is not Windows XP
// */
// public static synchronized BEXPStyle getXP() {
// if (themeActive == null) {
// Toolkit toolkit = Toolkit.getDefaultToolkit();
// themeActive =
// (Boolean)toolkit.getDesktopProperty("win.xpstyle.themeActive");
// if (themeActive == null) {
// themeActive = Boolean.FALSE;
// }
// if (themeActive.booleanValue()) {
// GetPropertyAction propertyAction =
// new GetPropertyAction("swing.noxp");
// if (AccessController.doPrivileged(propertyAction) == null &&
// ThemeReader.isThemed() &&
// !(UIManager.getLookAndFeel()
// instanceof WindowsClassicLookAndFeel)) {
//
// xp = new BEXPStyle();
// }
// }
// }
// return xp;
// }
//
//
//
// /** Get a named <code>String</code> value from the current style
// *
// * @param part a <code>Part</code>
// * @param state a <code>String</code>
// * @param attributeKey a <code>String</code>
// * @return a <code>String</code> or null if key is not found
// * in the current style
// *
// * This is currently only used by WindowsInternalFrameTitlePane for painting
// * title foregound and can be removed when no longer needed
// */
// String getString(Component c, Part part, State state, Prop prop) {
// return getTypeEnumName(c, part, state, prop);
// }
//
// private static String getTypeEnumName(Component c, Part part, State state, Prop prop) {
// int enumValue = ThemeReader.getEnum(part.getControlName(c), part.getValue(),
// State.getValue(part, state),
// prop.getValue());
// if (enumValue == -1) {
// return null;
// }
// return TypeEnum.getTypeEnum(prop, enumValue).getName();
// }
//
//
//
//
// /** Get a named <code>int</code> value from the current style
// *
// * @param part a <code>Part</code>
// * @return an <code>int</code> or null if key is not found
// * in the current style
// */
// int getInt(Component c, Part part, State state, Prop prop, int fallback) {
// return ThemeReader.getInt(part.getControlName(c), part.getValue(),
// State.getValue(part, state),
// prop.getValue());
// }
//
// /** Get a named <code>Dimension</code> value from the current style
// *
// * @param key a <code>String</code>
// * @return a <code>Dimension</code> or null if key is not found
// * in the current style
// *
// * This is currently only used by WindowsProgressBarUI and the value
// * should probably be cached there instead of here.
// */
// Dimension getDimension(Component c, Part part, State state, Prop prop) {
// return ThemeReader.getPosition(part.getControlName(c), part.getValue(),
// State.getValue(part, state),
// prop.getValue());
// }
//
// /** Get a named <code>Point</code> (e.g. a location or an offset) value
// * from the current style
// *
// * @param key a <code>String</code>
// * @return a <code>Point</code> or null if key is not found
// * in the current style
// *
// * This is currently only used by WindowsInternalFrameTitlePane for painting
// * title foregound and can be removed when no longer needed
// */
// Point getPoint(Component c, Part part, State state, Prop prop) {
// Dimension d = ThemeReader.getPosition(part.getControlName(c), part.getValue(),
// State.getValue(part, state),
// prop.getValue());
// if (d != null) {
// return new Point(d.width, d.height);
// } else {
// return null;
// }
// }
//
// /** Get a named <code>Insets</code> value from the current style
// *
// * @param key a <code>String</code>
// * @return an <code>Insets</code> object or null if key is not found
// * in the current style
// *
// * This is currently only used to create borders and by
// * WindowsInternalFrameTitlePane for painting title foregound.
// * The return value is already cached in those places.
// */
// Insets getMargin(Component c, Part part, State state, Prop prop) {
// return ThemeReader.getThemeMargins(part.getControlName(c), part.getValue(),
// State.getValue(part, state),
// prop.getValue());
// }
//
//
// /** Get a named <code>Color</code> value from the current style
// *
// * @param part a <code>Part</code>
// * @return a <code>Color</code> or null if key is not found
// * in the current style
// */
// synchronized Color getColor(Skin skin, Prop prop, Color fallback) {
// String key = skin.toString() + "." + prop.name();
// Part part = skin.part;
// Color color = colorMap.get(key);
// if (color == null) {
// color = ThemeReader.getColor(part.getControlName(null), part.getValue(),
// State.getValue(part, skin.state),
// prop.getValue());
// if (color != null) {
// color = new ColorUIResource(color);
// colorMap.put(key, color);
// }
// }
// return (color != null) ? color : fallback;
// }
//
// public Color getColor(Component c, Part part, State state, Prop prop, Color fallback) {
// return getColor(new Skin(c, part, state), prop, fallback);
// }
//
//
//
// /** Get a named <code>Border</code> value from the current style
// *
// * @param part a <code>Part</code>
// * @return a <code>Border</code> or null if key is not found
// * in the current style or if the style for the particular
// * part is not defined as "borderfill".
// */
// public synchronized Border getBorder(Component c, Part part) {
// if (part == Part.MENU) {
// // Special case because XP has no skin for menus
// if (flatMenus) {
// // TODO: The classic border uses this color, but we should
// // create a new UI property called "PopupMenu.borderColor"
// // instead.
// return new XPFillBorder(UIManager.getColor("InternalFrame.borderShadow"),
// 1);
// } else {
// return null; // Will cause L&F to use classic border
// }
// }
// Skin skin = new Skin(c, part, null);
// Border border = borderMap.get(skin.string);
// if (border == null) {
// String bgType = getTypeEnumName(c, part, null, Prop.BGTYPE);
// if ("borderfill".equalsIgnoreCase(bgType)) {
// int thickness = getInt(c, part, null, Prop.BORDERSIZE, 1);
// Color color = getColor(skin, Prop.BORDERCOLOR, Color.black);
// border = new XPFillBorder(color, thickness);
// } else if ("imagefile".equalsIgnoreCase(bgType)) {
// Insets m = getMargin(c, part, null, Prop.SIZINGMARGINS);
// if (m != null) {
// if (getBoolean(c, part, null, Prop.BORDERONLY)) {
// border = new XPImageBorder(c, part);
// } else {
// if(part == Part.TP_BUTTON) {
// border = new XPEmptyBorder(new Insets(3,3,3,3));
// } else {
// border = new XPEmptyBorder(m);
// }
// }
// }
// }
// if (border != null) {
// borderMap.put(skin.string, border);
// }
// }
// return border;
// }
//
// private class XPFillBorder extends LineBorder implements UIResource {
// XPFillBorder(Color color, int thickness) {
// super(color, thickness);
// }
//
// public Insets getBorderInsets(Component c) {
// return getBorderInsets(c, new Insets(0,0,0,0));
// }
//
// public Insets getBorderInsets(Component c, Insets insets) {
// Insets margin = null;
// //
// // Ideally we'd have an interface defined for classes which
// // support margins (to avoid this hackery), but we've
// // decided against it for simplicity
// //
// if (c instanceof AbstractButton) {
// margin = ((AbstractButton)c).getMargin();
// } else if (c instanceof JToolBar) {
// margin = ((JToolBar)c).getMargin();
// } else if (c instanceof JTextComponent) {
// margin = ((JTextComponent)c).getMargin();
// }
// insets.top = (margin != null? margin.top : 0) + thickness;
// insets.left = (margin != null? margin.left : 0) + thickness;
// insets.bottom = (margin != null? margin.bottom : 0) + thickness;
// insets.right = (margin != null? margin.right : 0) + thickness;
//
// return insets;
// }
// }
//
// private class XPImageBorder extends AbstractBorder implements UIResource {
// Skin skin;
//
// XPImageBorder(Component c, Part part) {
// this.skin = getSkin(c, part);
// }
//
// public void paintBorder(Component c, Graphics g,
// int x, int y, int width, int height) {
// skin.paintSkin(g, x, y, width, height, null);
// }
//
// public Insets getBorderInsets(Component c) {
// return getBorderInsets(c, new Insets(0,0,0,0));
// }
//
// public Insets getBorderInsets(Component c, Insets insets) {
// Insets margin = null;
// Insets borderInsets = skin.getContentMargin();
// //
// // Ideally we'd have an interface defined for classes which
// // support margins (to avoid this hackery), but we've
// // decided against it for simplicity
// //
// if (c instanceof AbstractButton) {
// margin = ((AbstractButton)c).getMargin();
// } else if (c instanceof JToolBar) {
// margin = ((JToolBar)c).getMargin();
// } else if (c instanceof JTextComponent) {
// margin = ((JTextComponent)c).getMargin();
// }
// insets.top = (margin != null? margin.top : 0) + borderInsets.top;
// insets.left = (margin != null? margin.left : 0) + borderInsets.left;
// insets.bottom = (margin != null? margin.bottom : 0) + borderInsets.bottom;
// insets.right = (margin != null? margin.right : 0) + borderInsets.right;
//
// return insets;
// }
// }
//
// private class XPEmptyBorder extends EmptyBorder implements UIResource {
// XPEmptyBorder(Insets m) {
// super(m.top+2, m.left+2, m.bottom+2, m.right+2);
// }
//
// public Insets getBorderInsets(Component c) {
// return getBorderInsets(c, getBorderInsets());
// }
//
// public Insets getBorderInsets(Component c, Insets insets) {
// insets = super.getBorderInsets(c, insets);
//
// Insets margin = null;
// if (c instanceof AbstractButton) {
// Insets m = ((AbstractButton)c).getMargin();
// // if this is a toolbar button then ignore getMargin()
// // and subtract the padding added by the constructor
// if(c.getParent() instanceof JToolBar
// && ! (c instanceof JRadioButton)
// && ! (c instanceof JCheckBox)
// && m instanceof InsetsUIResource) {
// insets.top -= 2;
// insets.left -= 2;
// insets.bottom -= 2;
// insets.right -= 2;
// } else {
// margin = m;
// }
// } else if (c instanceof JToolBar) {
// margin = ((JToolBar)c).getMargin();
// } else if (c instanceof JTextComponent) {
// margin = ((JTextComponent)c).getMargin();
// }
// if (margin != null) {
// insets.top = margin.top + 2;
// insets.left = margin.left + 2;
// insets.bottom = margin.bottom + 2;
// insets.right = margin.right + 2;
// }
// return insets;
// }
// }
//
// public boolean isSkinDefined(Component c, Part part) {
// return (part.getValue() == 0)
// || ThemeReader.isThemePartDefined(
// part.getControlName(c), part.getValue(), 0);
// }
//
// /** Get a <code>Skin</code> object from the current style
// * for a named part (component type)
// *
// * @param part a <code>Part</code>
// * @return a <code>Skin</code> object
// */
// public synchronized Skin getSkin(Component c, Part part) {
// assert isSkinDefined(c, part) : "part " + part + " is not defined";
// return new Skin(c, part, null);
// }
//
//
//
//
// /** A class which encapsulates attributes for a given part
// * (component type) and which provides methods for painting backgrounds
// * and glyphs
// */
// public static class Skin {
// final Component component;
// final Part part;
// final State state;
//
// private final String string;
// private Dimension size = null;
//
// Skin(Component component, Part part) {
// this(component, part, null);
// }
//
// Skin(Part part, State state) {
// this(null, part, state);
// }
//
// Skin(Component component, Part part, State state) {
// this.component = component;
// this.part = part;
// this.state = state;
//
// String str = part.getControlName(component) +"." + part.name();
// if (state != null) {
// str += "("+state.name()+")";
// }
// string = str;
// }
//
// public Insets getContentMargin() {
// // This is only called by WindowsTableHeaderUI so far.
// return ThemeReader.getThemeMargins(part.getControlName(null), part.getValue(),
// 0, Prop.SIZINGMARGINS.getValue());
// }
//
// private int getWidth(State state) {
// if (size == null) {
// size = getPartSize(part, state);
// }
// return size.width;
// }
//
// public int getWidth() {
// return getWidth((state != null) ? state : State.NORMAL);
// }
//
// private int getHeight(State state) {
// if (size == null) {
// size = getPartSize(part, state);
// }
// return size.height;
// }
//
// public int getHeight() {
// return getHeight((state != null) ? state : State.NORMAL);
// }
//
// public String toString() {
// return string;
// }
//
// public boolean equals(Object obj) {
// return (obj instanceof Skin && ((Skin)obj).string.equals(string));
// }
//
// public int hashCode() {
// return string.hashCode();
// }
//
// /** Paint a skin at x, y.
// *
// * @param g the graphics context to use for painting
// * @param dx the destination <i>x</i> coordinate.
// * @param dy the destination <i>y</i> coordinate.
// * @param state which state to paint
// */
// public void paintSkin(Graphics g, int dx, int dy, State state) {
// if (state == null) {
// state = this.state;
// }
// paintSkin(g, dx, dy, getWidth(state), getHeight(state), state);
// }
//
// /** Paint a skin in an area defined by a rectangle.
// *
// * @param g the graphics context to use for painting
// * @param r a <code>Rectangle</code> defining the area to fill,
// * may cause the image to be stretched or tiled
// * @param state which state to paint
// */
// void paintSkin(Graphics g, Rectangle r, State state) {
// paintSkin(g, r.x, r.y, r.width, r.height, state);
// }
//
// /** Paint a skin at a defined position and size
// *
// * @param g the graphics context to use for painting
// * @param dx the destination <i>x</i> coordinate.
// * @param dy the destination <i>y</i> coordinate.
// * @param dw the width of the area to fill, may cause
// * the image to be stretched or tiled
// * @param dh the height of the area to fill, may cause
// * the image to be stretched or tiled
// * @param state which state to paint
// */
// public void paintSkin(Graphics g, int dx, int dy, int dw, int dh, State state) {
// skinPainter.paint(null, g, dx, dy, dw, dh, this, state);
// }
// /**
// * Paint a skin at a defined position and size
// *
// * @param g the graphics context to use for painting
// * @param dx the destination <i>x</i> coordinate
// * @param dy the destination <i>y</i> coordinate
// * @param dw the width of the area to fill, may cause
// * the image to be stretched or tiled
// * @param dh the height of the area to fill, may cause
// * the image to be stretched or tiled
// * @param state which state to paint
// * @param borderFill should test if the component uses a border fill
// * and skip painting if it is
// */
// void paintSkin(Graphics g, int dx, int dy, int dw, int dh, State state,
// boolean borderFill) {
// if(borderFill && "borderfill".equals(getTypeEnumName(component, part,
// state, Prop.BGTYPE))) {
// return;
// }
// skinPainter.paint(null, g, dx, dy, dw, dh, this, state);
// }
// }
//
// private static class SkinPainter extends CachedPainter {
// SkinPainter() {
// super(30);
// flush();
// }
//
// protected void paintToImage(Component c, Image image, Graphics g,
// int w, int h, Object[] args) {
// Skin skin = (Skin)args[0];
// Part part = skin.part;
// State state = (State)args[1];
// if (state == null) {
// state = skin.state;
// }
// if (c == null) {
// c = skin.component;
// }
// WritableRaster raster = ((BufferedImage)image).getRaster();
// DataBufferInt buffer = (DataBufferInt)raster.getDataBuffer();
// ThemeReader.paintBackground(buffer.getData(),
// part.getControlName(c), part.getValue(),
// State.getValue(part, state),
// 0, 0, w, h, w);
// }
//
// protected Image createImage(Component c, int w, int h,
// GraphicsConfiguration config, Object[] args) {
// return new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
// }
// }
//
// static class GlyphButton extends JButton {
// private Skin skin;
//
// public GlyphButton(Component parent, Part part) {
// BEXPStyle xp = getXP();
// skin = xp.getSkin(parent, part);
// setBorder(null);
// setContentAreaFilled(false);
// }
//
// public boolean isFocusTraversable() {
// return false;
// }
//
// protected State getState() {
// State state = State.NORMAL;
// if (!isEnabled()) {
// state = State.DISABLED;
// } else if (getModel().isPressed()) {
// state = State.PRESSED;
// } else if (getModel().isRollover()) {
// state = State.HOT;
// }
// return state;
// }
//
// public void paintComponent(Graphics g) {
// Dimension d = getSize();
// skin.paintSkin(g, 0, 0, d.width, d.height, getState());
// }
//
// public void setPart(Component parent, Part part) {
// BEXPStyle xp = getXP();
// skin = xp.getSkin(parent, part);
// revalidate();
// repaint();
// }
//
// protected void paintBorder(Graphics g) {
// }
//
// public Dimension getPreferredSize() {
// return new Dimension(16, 16);
// }
//
// public Dimension getMinimumSize() {
// return new Dimension(5, 5);
// }
//
// public Dimension getMaximumSize() {
// return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE);
// }
// }
//
// // Private constructor
// private BEXPStyle() {
// flatMenus = getSysBoolean(Prop.FLATMENUS);
//
// colorMap = new HashMap<String, Color>();
// borderMap = new HashMap<String, Border>();
// // Note: All further access to the maps must be synchronized
// }
//
//
// private boolean getBoolean(Component c, Part part, State state, Prop prop) {
// return ThemeReader.getBoolean(part.getControlName(c), part.getValue(),
// State.getValue(part, state),
// prop.getValue());
// }
//
// private static Dimension getPartSize(Part part, State state) {
// return ThemeReader.getPartSize(part.getControlName(null), part.getValue(),
// State.getValue(part, state));
// }
//
// private static boolean getSysBoolean(Prop prop) {
// // We can use any widget name here, I guess.
// return ThemeReader.getSysBoolean("window", prop.getValue());
// }
//}
| JackJiang2011/beautyeye | src_all/beautyeye_v3.7_utf8/src/org/jb2011/lnf/beautyeye/winlnfutils/d/BEXPStyle.java | Java | apache-2.0 | 26,390 |
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>template test</title>
<script src="js/jquery-1.7.2.min.js"></script>
<script src="js/highcharts.js"></script>
<script src="../dist/template-native.js"></script>
<script src="js/tmpl.js"></script>
<script src="js/doT.js"></script>
<script src="js/juicer.js"></script>
<script src="js/kissy.js"></script>
<script src="js/template.js"></script>
<script src="js/mustache.js"></script>
<script src="js/handlebars.js"></script>
<script src="js/baiduTemplate.js"></script>
<script src="js/jquery.tmpl.js"></script>
<script src="js/easytemplate.js"></script>
<script src="js/underscore.js"></script>
<script src="js/etpl.js"></script>
<script>
// 数据量
var length = 100;
// 渲染次数
var number = 10000;
var data = {
list: []
};
for (var i = 0; i < length; i ++) {
data.list.push({
index: i,
user: '<strong style="color:red">糖饼</strong>',
site: 'http://www.planeart.cn',
weibo: 'http://weibo.com/planeart',
QQweibo: 'http://t.qq.com/tangbin'
});
};
// 待测试的引擎列表
var testList = [
{
name: 'artTemplate',
tester: function () {
//template.config('escape', false);
var source = document.getElementById('template').innerHTML;
var fn = template.compile(source);
for (var i = 0; i < number; i ++) {
fn(data);
}
}
},
{
name: 'juicer',
tester: function () {
var config = {cache:true};
var source = document.getElementById('juicer').innerHTML;
for (var i = 0; i < number; i ++) {
juicer.to_html(source, data, config);
}
}
},
{
name: 'doT',
tester: function () {
var source = document.getElementById('doT').innerHTML;
var doTtmpl = doT.template(source);
for (var i = 0; i < number; i ++) {
doTtmpl(data);
}
}
},
{
name: 'Handlebars',
tester: function () {
var source = document.getElementById('Handlebars').innerHTML;
var fn = Handlebars.compile(source);
for (var i = 0; i < number; i ++) {
fn(data);
}
}
},
{
name: 'etpl',
tester: function () {
// dont escape html
etpl.config({
defaultFilter: ''
});
var source = document.getElementById('etpl').innerHTML;
var fn = etpl.compile(source);
for (var i = 0; i < number; i ++) {
fn(data);
}
}
},
{
name: 'tmpl',
tester: function () {
var source = document.getElementById('tmpl').innerHTML;
var fn = tmpl(source);
for (var i = 0; i < number; i ++) {
fn(data);
}
}
},
{
name: 'easyTemplate',
tester: function () {
var source = document.getElementById('easyTemplate').innerHTML;
var fn = easyTemplate(source);
for (var i = 0; i < number; i ++) {
// easyTemplate 渲染方法被重写到 toString(), 需要取值操作才会运行
fn(data) + '';
}
}
},
{
name: 'underscoreTemplate',
tester: function () {
var source = document.getElementById('underscoreTemplate').innerHTML;
var fn = _.template(source);
for (var i = 0; i < number; i ++) {
fn(data);
}
}
},
{
name: 'baiduTemplate',
tester: function () {
var bt=baidu.template;
bt.ESCAPE = false;
for (var i = 0; i < number; i ++) {
bt('baidu-template', data);
}
}
},
// jqueryTmpl 太慢,可能导致浏览器停止响应
/*{
name: 'jqueryTmpl',
tester: function () {
var source = document.getElementById("jqueryTmpl").innerHTML;
for (var i = 0; i < number; i ++) {
$.tmpl(source, data);
}
}
},*/
{
name: 'Mustache',
tester: function () {
var source = document.getElementById('Mustache').innerHTML;
for (var i = 0; i < number; i ++) {
Mustache.to_html(source, data);
}
}
}
];
KISSY.use('template',function(S,T) {
testList.push({
name: 'kissyTemplate',
tester: function () {
var source= document.getElementById('kissy').innerHTML;
for (var i = 0; i < number; i ++) {
T(source).render(data);
}
}
});
});
var startTest = function () {
var Timer = function (){
this.startTime = + new Date;
};
Timer.prototype.stop = function(){
return + new Date - this.startTime;
};
var colors = Highcharts.getOptions().colors;
var categories = [];
for (var i = 0; i < testList.length; i ++) {
categories.push(testList[i].name);
}
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
height: categories.length * 40,
type: 'bar'
},
title: {
text: 'JavaScript 模板引擎负荷测试'
},
subtitle: {
text: length + ' 条数据 × ' + number + ' 次渲染'
},
xAxis: {
categories: categories,
labels: {
align: 'right',
style: {
fontSize: '12px',
fontFamily: 'Verdana, sans-serif'
}
}
},
yAxis: {
min: 0,
title: {
text: '耗时(毫秒)'
}
},
legend: {
enabled: false
},
tooltip: {
formatter: function() {
return '<b>'+ this.x +'</b><br/>'+
this.y + '毫秒';
}
},
credits: {
enabled: false
},
plotOptions: {
bar: {
dataLabels: {
enabled: true,
formatter: function () {
return this.y + 'ms';
}
}
}
},
series: [{
data : []
}]
});
var log = function (message) {
document.getElementById('log').innerHTML = message;
};
var tester = function (target) {
var time = new Timer;
target.tester();
var endTime = time.stop();
chart.series[0].addPoint({
color: colors.shift(),
y: endTime
});
if (!testList.length) {
log('测试已完成,请不要迷恋速度');
return;
}
target = testList.shift();
log('正在测试: ' + target.name + '..');
setTimeout(function () {
tester(target);
}, 500);
};
var target = testList.shift();
log('正在测试: ' + target.name + '..');
tester(target);
};
</script>
<!-- artTemplate 的模板 -->
<script id="template" type="text/tmpl">
<ul>
<% for (i = 0, l = list.length; i < l; i ++) { %>
<li>用户: <%=#list[i].user%>/ 网站:<%=#list[i].site%></li>
<% } %>
</ul>
</script>
<!-- baidu-template 的模板 -->
<script id="baidu-template" type="text/tmpl">
<ul>
<% for (var val, i = 0, l = list.length; i < l; i ++) { %>
<% val = list[i]; %>
<li>用户: <%:=val.user%>/ 网站:<%:=val.site%></li>
<% } %>
</ul>
</script>
<!-- easyTemplate 的模板 -->
<script id="easyTemplate" type="text/tmpl">
<ul>
<#list data.list as item>
<li>用户: ${item.user}/ 网站:${item.site}</li>
</#list>
</ul>
</script>
<!-- tmpl 的模板 -->
<script id="tmpl" type="text/tmpl">
<ul>
<% for (var val, i = 0, l = list.length; i < l; i ++) { %>
<% val = list[i]; %>
<li>用户: <%=val.user%>/ 网站:<%=val.site%></li>
<% } %>
</ul>
</script>
<!-- jqueryTmpl 的模板 -->
<script id="jqueryTmpl" type="text/tmpl">
<ul>
{{each list}}
<li>用户: ${$value.user}/ 网站:${$value.site}</li>
{{/each}}
</ul>
</script>
<!--juicer 的模板 -->
<script id="juicer" type="text/tmpl">
<ul>
{@each list as val}
<li>用户: $${val.user}/ 网站:$${val.site}</li>
{@/each}
</ul>
</script>
<!--etpl 的模板 -->
<script id="etpl" type="text/tmpl">
<ul>
<!--for: ${list} as ${val} -->
<li>用户: ${val.user}/ 网站:${val.site}</li>
<!--/for-->
</ul>
</script>
<!-- doT 的模板 -->
<script id="doT" type="text/tmpl">
<ul>
{{ for (var val, i = 0, l = it.list.length; i < l; i ++) { }}
{{ val = it.list; }}
<li>用户: {{=val[i].user}}/ 网站:{{=val[i].site}}</li>
{{ } }}
</ul>
</script>
<!--Mustache 的模板 -->
<script id="Mustache" type="text/tmpl">
<ul>
{{#list}}
<li>用户: {{{user}}}/ 网站:{{{site}}}</li>
{{/list}}
</ul>
</script>
<!--Handlebars 的模板 -->
<script id="Handlebars" type="text/tmpl">
<ul>
{{#list}}
<li>用户: {{{user}}}/ 网站:{{{site}}}</li>
{{/list}}
</ul>
</script>
<!--kissy 的模板 -->
<script id="kissy" type="text/tmpl">
<ul>
{{#each list as val}}
<li>用户: {{val.user}}/ 网站:{{val.site}}</li>
{{/each}}
</ul>
</script>
<!-- ejs 的模板 -->
<script id="ejs" type="text/tmpl">
<ul>
<& for (var val, i = 0, l = @list.length; i < l; i ++) { &>
<& val = @list[i]; &>
<li>用户: <&= val.user &>; 网站:<&= val.site &></li>
<& } &>
</ul>
</script>
<!-- underscore 的模板 -->
<script id="underscoreTemplate" type="text/tmpl">
<ul>
<% for (var i = 0, l = list.length; i < l; i ++) { %>
<li>用户: <%=list[i].user%>/ 网站:<%=list[i].site%></li>
<% } %>
</ul>
</script>
</head>
<body>
<h1>引擎渲染速度测试</h1>
<p><strong><script>document.write(length)</script></strong> 条数据 × <strong><script>document.write(number)</script></strong> 次渲染测试 [escape:false, cache:true]</p>
<p><em>建议在拥有 v8 javascript 引擎的 chrome 浏览器上进行测试,避免浏览器停止响应</em></p>
<p><button id="button-test" onclick="this.disabled=true;startTest()" style="padding: 5px;">开始测试»</button> <span id="log" style="font-size:12px"><script>for (var i = 0; i < testList.length; i ++) {document.write(testList[i].name + '; ')}</script></span></p>
<div id="container" style="min-width: 400px; margin: 0 auto"></div>
</body>
</html> | WTXGBG/loltpc | tp5/public/assets/libs/art-template/test/test-speed.html | HTML | apache-2.0 | 11,011 |
/*
* 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.redis.internal.executor.transactions;
import io.netty.buffer.ByteBuf;
import java.util.Queue;
import org.apache.geode.cache.CacheTransactionManager;
import org.apache.geode.cache.CommitConflictException;
import org.apache.geode.cache.TransactionId;
import org.apache.geode.redis.internal.Coder;
import org.apache.geode.redis.internal.Command;
import org.apache.geode.redis.internal.ExecutionHandlerContext;
import org.apache.geode.redis.internal.RedisConstants;
public class ExecExecutor extends TransactionExecutor {
@Override
public void executeCommand(Command command, ExecutionHandlerContext context) {
CacheTransactionManager txm = context.getCacheTransactionManager();
if (!context.hasTransaction()) {
command.setResponse(Coder.getNilResponse(context.getByteBufAllocator()));
return;
}
TransactionId transactionId = context.getTransactionID();
txm.resume(transactionId);
boolean hasError = hasError(context.getTransactionQueue());
if (hasError)
txm.rollback();
else {
try {
txm.commit();
} catch (CommitConflictException e) {
command.setResponse(Coder.getErrorResponse(context.getByteBufAllocator(),
RedisConstants.ERROR_COMMIT_CONFLICT));
context.clearTransaction();
return;
}
}
ByteBuf response = constructResponseExec(context);
command.setResponse(response);
context.clearTransaction();
}
private ByteBuf constructResponseExec(ExecutionHandlerContext context) {
Queue<Command> cQ = context.getTransactionQueue();
ByteBuf response = context.getByteBufAllocator().buffer();
response.writeByte(Coder.ARRAY_ID);
response.writeBytes(Coder.intToBytes(cQ.size()));
response.writeBytes(Coder.CRLFar);
for (Command c : cQ) {
ByteBuf r = c.getResponse();
response.writeBytes(r);
}
return response;
}
private boolean hasError(Queue<Command> queue) {
for (Command c : queue) {
if (c.hasError())
return true;
}
return false;
}
}
| charliemblack/geode | geode-core/src/main/java/org/apache/geode/redis/internal/executor/transactions/ExecExecutor.java | Java | apache-2.0 | 2,868 |
/**
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.waveprotocol.wave.model.waveref;
import junit.framework.TestCase;
import org.waveprotocol.wave.model.id.WaveId;
import org.waveprotocol.wave.model.id.WaveletId;
/**
* Unit tests for {@link WaveRef}
*
* @author meade@google.com <Edwina Mead>
*/
public class WaveRefTest extends TestCase {
public void testBasicEquals() {
WaveRef first = WaveRef.of(WaveId.of("example.com", "w+1234abcd"));
WaveRef second = WaveRef.of(WaveId.of("example.com", "w+1234abcd"));
WaveRef different = WaveRef.of(WaveId.of("test.com", "w+1234abcd"));
assertFalse(first.equals(null));
assertTrue(first.equals(first));
assertTrue(first.equals(second));
assertFalse(first.equals(different));
}
public void testEqualsWithSameWaveIdDifferentOtherFields() {
WaveRef first = WaveRef.of(WaveId.of("example.com", "w+1234abcd"));
WaveRef second = WaveRef.of(WaveId.of("example.com", "w+1234abcd"),
WaveletId.of("example.com", "conv+root"));
WaveRef third = WaveRef.of(WaveId.of("example.com", "w+1234abcd"),
WaveletId.of("example.com", "conv+root"),
"b+12345");
assertTrue(second.equals(second));
assertTrue(third.equals(third));
assertFalse(first.equals(second));
assertFalse(first.equals(third));
assertFalse(second.equals(third));
}
public void testEqualsWithDifferentWaveIdSameOtherFields() {
WaveRef first = WaveRef.of(WaveId.of("test.com", "w+1234"),
WaveletId.of("example.com", "conv+root"),
"b+12345");
WaveRef second = WaveRef.of(WaveId.of("example.com", "w+1234"),
WaveletId.of("example.com", "conv+root"),
"b+12345");
assertFalse(first.equals(second));
}
public void testHashCode() {
WaveRef first = WaveRef.of(WaveId.of("example.com", "w+1234"));
WaveRef second = WaveRef.of(WaveId.of("example.com", "w+1234"),
WaveletId.of("example.com", "conv+root"));
WaveRef third = WaveRef.of(WaveId.of("example.com", "w+1234"),
WaveletId.of("example.com", "conv+root"), "b+12345");
WaveRef sameAsFirst = WaveRef.of(WaveId.of("example.com", "w+1234"));
WaveRef sameAsThird = WaveRef.of(WaveId.of("example.com", "w+1234"),
WaveletId.of("example.com", "conv+root"), "b+12345");
assertEquals(first.hashCode(), sameAsFirst.hashCode());
assertEquals(third.hashCode(), sameAsThird.hashCode());
assertFalse(first.hashCode() == second.hashCode());
assertFalse(first.hashCode() == third.hashCode());
assertFalse(second.hashCode() == third.hashCode());
}
}
| gburd/wave | test/org/waveprotocol/wave/model/waveref/WaveRefTest.java | Java | apache-2.0 | 3,152 |
//
// Licensed to Green Energy Corp (www.greenenergycorp.com) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. Green Enery Corp 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.
//
#ifndef __TYPES_H_
#define __TYPES_H_
#include <boost/cstdint.hpp>
namespace apl
{
#ifndef SIZE_MAX
#define SIZE_MAX ~0
#endif
typedef boost::int64_t millis_t;
#ifdef _DEBUG
//#define STRONGLY_TYPED_TIMESTAMPS
#endif
#ifdef STRONGLY_TYPED_TIMESTAMPS
class TimeStamp_t_Explicit
{
millis_t value;
public:
explicit TimeStamp_t_Explicit(millis_t aT): value(aT) {}
operator millis_t () const {
return value;
}
};
class UTCTimeStamp_t_Explicit
{
millis_t value;
public:
explicit UTCTimeStamp_t_Explicit(millis_t aT): value(aT) {}
operator millis_t () const {
return value;
}
};
//this is some c++ trickery to make sure that we get strong
//typesaftey on the 2 different types of timestamp
typedef TimeStamp_t_Explicit TimeStamp_t;
typedef UTCTimeStamp_t_Explicit UTCTimeStamp_t;
#else
//if we are not using the strong typing it should be faster
//since the values are all simple 64bit value types rather than
//overloaded classes.
typedef millis_t TimeStamp_t;
typedef millis_t UTCTimeStamp_t;
#endif
} //end namespace
#endif
| gec/dnp3 | src/opendnp3/APL/Types.h | C | apache-2.0 | 1,866 |
import type { Config } from '../src/core/config'
import type VNode from '../src/core/vdom/vnode'
import type Watcher from '../src/core/observer/watcher'
declare interface Component {
// constructor information
static cid: number;
static options: Object;
// extend
static extend: (options: Object) => Function;
static superOptions: Object;
static extendOptions: Object;
static sealedOptions: Object;
static super: Class<Component>;
// assets
static directive: (id: string, def?: Function | Object) => Function | Object | void;
static component: (id: string, def?: Class<Component> | Object) => Class<Component>;
static filter: (id: string, def?: Function) => Function | void;
// public properties
$el: any; // so that we can attach __vue__ to it
$data: Object;
$options: ComponentOptions;
$parent: Component | void;
$root: Component;
$children: Array<Component>;
$refs: { [key: string]: Component | Element | Array<Component | Element> | void };
$slots: { [key: string]: Array<VNode> };
$scopedSlots: { [key: string]: () => VNodeChildren };
$vnode: VNode; // the placeholder node for the component in parent's render tree
$isServer: boolean;
$props: Object;
// public methods
$mount: (el?: Element | string, hydrating?: boolean) => Component;
$forceUpdate: () => void;
$destroy: () => void;
$set: <T>(target: Object | Array<T>, key: string | number, val: T) => T;
$delete: <T>(target: Object | Array<T>, key: string | number) => void;
$watch: (expOrFn: string | Function, cb: Function, options?: Object) => Function;
$on: (event: string | Array<string>, fn: Function) => Component;
$once: (event: string, fn: Function) => Component;
$off: (event?: string | Array<string>, fn?: Function) => Component;
$emit: (event: string, ...args: Array<mixed>) => Component;
$nextTick: (fn: Function) => void | Promise<*>;
$createElement: (tag?: string | Component, data?: Object, children?: VNodeChildren) => VNode;
// private properties
_uid: number;
_name: string; // this only exists in dev mode
_isVue: true;
_self: Component;
_renderProxy: Component;
_renderContext: ?Component;
_watcher: Watcher;
_watchers: Array<Watcher>;
_computedWatchers: { [key: string]: Watcher };
_data: Object;
_props: Object;
_events: Object;
_inactive: boolean | null;
_directInactive: boolean;
_isMounted: boolean;
_isDestroyed: boolean;
_isBeingDestroyed: boolean;
_vnode: ?VNode; // self root node
_staticTrees: ?Array<VNode>;
_hasHookEvent: boolean;
_provided: ?Object;
// private methods
// lifecycle
_init: Function;
_mount: (el?: Element | void, hydrating?: boolean) => Component;
_update: (vnode: VNode, hydrating?: boolean) => void;
// rendering
_render: () => VNode;
__patch__: (a: Element | VNode | void, b: VNode) => any;
// createElement
// _c is internal that accepts `normalizationType` optimization hint
_c: (vnode?: VNode, data?: VNodeData, children?: VNodeChildren, normalizationType?: number) => VNode | void;
// renderStatic
_m: (index: number, isInFor?: boolean) => VNode | VNodeChildren;
// markOnce
_o: (vnode: VNode | Array<VNode>, index: number, key: string) => VNode | VNodeChildren;
// toString
_s: (value: mixed) => string;
// text to VNode
_v: (value: string | number) => VNode;
// toNumber
_n: (value: string) => number | string;
// empty vnode
_e: () => VNode;
// loose equal
_q: (a: mixed, b: mixed) => boolean;
// loose indexOf
_i: (arr: Array<mixed>, val: mixed) => number;
// resolveFilter
_f: (id: string) => Function;
// renderList
_l: (val: mixed, render: Function) => ?Array<VNode>;
// renderSlot
_t: (name: string, fallback: ?Array<VNode>, props: ?Object) => ?Array<VNode>;
// apply v-bind object
_b: (data: any, value: any, asProp?: boolean) => VNodeData;
// check custom keyCode
_k: (eventKeyCode: number, key: string, builtInAlias: number | Array<number> | void) => boolean;
// resolve scoped slots
_u: (scopedSlots: ScopedSlotsData, res?: Object) => { [key: string]: Function };
// allow dynamic method registration
[key: string]: any
}
| search5/nanumlectures | static/bower_components/vue/flow/component.js | JavaScript | apache-2.0 | 4,160 |
/**
* @@@ START COPYRIGHT @@@
*
* 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.
*
* @@@ END COPYRIGHT @@@
**/
package org.trafodion.wms.rest;
import com.sun.jersey.api.core.PackagesResourceConfig;
public class ResourceConfig extends PackagesResourceConfig {
public ResourceConfig() {
super("org.trafodion.wms.rest");
}
}
| apache/incubator-trafodion | wms/src/main/java/org/trafodion/wms/rest/ResourceConfig.java | Java | apache-2.0 | 1,068 |
/*
* Copyright 2013 zhongl
*
* 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.github.zhongl.housemd.command
import instrument.Instrumentation
import management.ManagementFactory
import com.cedarsoftware.util.io.JsonWriter
import com.github.zhongl.housemd.misc.ObjUtils
import com.github.zhongl.yascli.PrintOut
import com.github.zhongl.housemd.misc.ReflectionUtils._
import java.util.Date
import collection.immutable.SortedSet
import com.github.zhongl.housemd.instrument.{Hook, Context}
import org.objectweb.asm.Type
import java.io.{BufferedWriter, FileWriter, File}
/**
* @author <a href="mailto:zhong.lunfu@gmail.com">zhongl<a>
*/
class Trace(val inst: Instrumentation, out: PrintOut)
extends TransformCommand("trace", "display or output infomation of method invocaton.", inst, out)
with MethodFilterCompleter {
val outputRoot = {
val dir = new File("/tmp/" + name + "/" + ManagementFactory.getRuntimeMXBean.getName)
dir.mkdirs()
dir
}
val detailFile = new File(outputRoot, "detail")
val stackFile = new File(outputRoot, "stack")
private val detailable = flag("-d" :: "--detail" :: Nil, "enable append invocation detail to " + detailFile + ".")
private val detailInJson = flag("-j" :: "--json" :: Nil, "convert detail info into json format.")
private val stackable = flag("-s" :: "--stack" :: Nil, "enable append invocation calling stack to " + stackFile + ".")
private val methodFilters = parameter[Array[MethodFilter]]("method-filter", "method filter pattern like \"ClassSimpleName.methodName\" or \"ClassSimpleName\".")
protected def isCandidate(klass: Class[_]) = methodFilters().find(_.filter(klass)).isDefined
protected def isDecorating(klass: Class[_], methodName: String) =
methodFilters().find(_.filter(klass, methodName)).isDefined
override protected def hook = new Hook() {
val enableDetail = detailable()
val enableStack = stackable()
val showDetailInJson = detailInJson()
implicit val statisticOrdering = Ordering.by((_: Statistic).methodSign)
var statistics = SortedSet.empty[Statistic]
var maxMethodSignLength = 0
var maxClassLoaderLength = 0
if (showDetailInJson) ObjUtils.useJsonFormat() else ObjUtils.useToStringFormat()
lazy val detailWriter = new DetailWriter(new BufferedWriter(new FileWriter(detailFile, true)))
lazy val stackWriter = new StackWriter(new BufferedWriter(new FileWriter(stackFile, true)))
override def enterWith(context: Context) {}
override def exitWith(context: Context) {
if (enableDetail) detailWriter.write(context)
if (enableStack) stackWriter.write(context)
val statistic = new Statistic(context, 1L, context.stopped.get - context.started)
maxClassLoaderLength = math.max(maxClassLoaderLength, statistic.loader.length)
maxMethodSignLength = math.max(maxMethodSignLength, statistic.methodSign.length)
statistics = statistics find { _.filter(context) } match {
case Some(s) => (statistics - s) + (s + statistic)
case None => statistics + statistic
}
}
override def heartbeat(now: Long) {
if (statistics.isEmpty) println("No traced method invoked")
else statistics foreach { s => println(s.reps(maxMethodSignLength, maxClassLoaderLength)) }
println()
}
override def finalize(throwable: Option[Throwable]) {
heartbeat(0L) // last print
if (enableDetail) {
detailWriter.close()
info("You can get invocation detail from " + detailFile)
}
if (enableStack) {
stackWriter.close()
info("You can get invocation stack from " + stackFile)
}
}
}
class Statistic(val context: Context, val totalTimes: Long, val totalElapseMills: Long) {
lazy val methodSign = "%1$s.%2$s(%3$s)".format(
simpleNameOf(context.className),
context.methodName,
Type.getArgumentTypes(context.descriptor).map(t => simpleNameOf(t.getClassName)).mkString(", ")
)
lazy val loader = if (context.loader == null) "BootClassLoader" else getOrForceToNativeString(context.loader)
private val NaN = "-"
private lazy val thisObjectString = context match {
case c if c.thisObject == null => "[Static Method]"
case c if isInit(c.methodName) => "[Initialize Method]"
case _ => getOrForceToNativeString(context.thisObject)
}
private lazy val avgElapseMillis =
if (totalTimes == 0) NaN else if (totalElapseMills < totalTimes) "<1" else totalElapseMills / totalTimes
def +(s: Statistic) = new Statistic(context, totalTimes + s.totalTimes, totalElapseMills + s.totalElapseMills)
def filter(context: Context) = this.context.loader == context.loader &&
this.context.className == context.className &&
this.context.methodName == context.methodName &&
this.context.arguments.size == context.arguments.size &&
this.context.descriptor == context.descriptor &&
(isInit(context.methodName) || this.context.thisObject == context.thisObject)
def reps(maxMethodSignLength: Int, maxClassLoaderLength: Int) =
"%1$-" + maxMethodSignLength + "s %2$-" + maxClassLoaderLength + "s %3$9s %4$9sms %5$s" format(
methodSign,
loader,
totalTimes,
avgElapseMillis,
thisObjectString)
private def isInit(method: String) = method == "<init>"
}
}
class DetailWriter(writer: BufferedWriter) {
def write(context: Context) {
val started = "%1$tF %1$tT" format (new Date(context.started))
val elapse = "%,dms" format (context.stopped.get - context.started)
val thread = "[" + context.thread.getName + "]"
val thisObject = if (context.thisObject == null) "null" else context.thisObject.toString
val method = context.className + "." + context.methodName
val arguments = context.arguments.mkString("[" + ObjUtils.parameterSeparator, ObjUtils.parameterSeparator, "]")
val resultOrExcption = context.resultOrException match {
case Some(x) => ObjUtils.toString(x)
case None if context.isVoidReturn => "void"
case None => "null"
}
val argumentsAndResult = "Arguments: " + arguments + ObjUtils.parameterSeparator + "Result: " + resultOrExcption
val line = (started :: elapse :: thread :: thisObject :: method :: argumentsAndResult :: Nil)
.mkString(" ")
writer.write(line)
writer.newLine()
context.resultOrException match {
case Some(x) if x.isInstanceOf[Throwable] => x.asInstanceOf[Throwable].getStackTrace.foreach {
s =>
writer.write("\tat " + s)
writer.newLine()
}
case _ =>
}
}
def close() {
try {writer.close()} catch {case _ => }
}
}
class StackWriter(writer: BufferedWriter) {
def write(context: Context) {
// TODO Avoid duplicated stack
val head = "%1$s.%2$s%3$s call by thread [%4$s]"
.format(context.className, context.methodName, context.descriptor, context.thread.getName)
writer.write(head)
writer.newLine()
context.stack foreach { s => writer.write("\t" + s); writer.newLine() }
writer.newLine()
}
def close() {
try {writer.close()} catch {case _ => }
}
}
| chosen0ne/HouseMD | src/main/scala/com/github/zhongl/housemd/command/Trace.scala | Scala | apache-2.0 | 7,974 |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System;
using System.Globalization;
using System.Runtime.InteropServices;
using EnvDTE;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudioTools.Project.Automation {
[ComVisible(true)]
public class OAProject : EnvDTE.Project, EnvDTE.ISupportVSProperties {
#region fields
private ProjectNode project;
EnvDTE.ConfigurationManager configurationManager;
#endregion
#region properties
public object Project {
get { return this.project; }
}
internal ProjectNode ProjectNode {
get { return this.project; }
}
#endregion
#region ctor
internal OAProject(ProjectNode project) {
this.project = project;
}
#endregion
#region EnvDTE.Project
/// <summary>
/// Gets or sets the name of the object.
/// </summary>
public virtual string Name {
get {
return project.Caption;
}
set {
CheckProjectIsValid();
using (AutomationScope scope = new AutomationScope(this.project.Site)) {
ProjectNode.Site.GetUIThread().Invoke(() => {
project.SetEditLabel(value);
});
}
}
}
public void Dispose() {
configurationManager = null;
}
/// <summary>
/// Microsoft Internal Use Only. Gets the file name of the project.
/// </summary>
public virtual string FileName {
get {
return project.ProjectFile;
}
}
/// <summary>
/// Microsoft Internal Use Only. Specfies if the project is dirty.
/// </summary>
public virtual bool IsDirty {
get {
int dirty;
ErrorHandler.ThrowOnFailure(project.IsDirty(out dirty));
return dirty != 0;
}
set {
CheckProjectIsValid();
using (AutomationScope scope = new AutomationScope(this.project.Site)) {
ProjectNode.Site.GetUIThread().Invoke(() => {
project.isDirty = value;
});
}
}
}
internal void CheckProjectIsValid() {
if (this.project == null || this.project.Site == null || this.project.IsClosed) {
throw new InvalidOperationException();
}
}
/// <summary>
/// Gets the Projects collection containing the Project object supporting this property.
/// </summary>
public virtual EnvDTE.Projects Collection {
get { return null; }
}
/// <summary>
/// Gets the top-level extensibility object.
/// </summary>
public virtual EnvDTE.DTE DTE {
get {
return (EnvDTE.DTE)this.project.Site.GetService(typeof(EnvDTE.DTE));
}
}
/// <summary>
/// Gets a GUID string indicating the kind or type of the object.
/// </summary>
public virtual string Kind {
get { return project.ProjectGuid.ToString("B"); }
}
/// <summary>
/// Gets a ProjectItems collection for the Project object.
/// </summary>
public virtual EnvDTE.ProjectItems ProjectItems {
get {
return new OAProjectItems(this, project);
}
}
/// <summary>
/// Gets a collection of all properties that pertain to the Project object.
/// </summary>
public virtual EnvDTE.Properties Properties {
get {
return new OAProperties(this.project.NodeProperties);
}
}
/// <summary>
/// Returns the name of project as a relative path from the directory containing the solution file to the project file
/// </summary>
/// <value>Unique name if project is in a valid state. Otherwise null</value>
public virtual string UniqueName {
get {
if (this.project == null || this.project.IsClosed) {
return null;
} else {
// Get Solution service
IVsSolution solution = this.project.GetService(typeof(IVsSolution)) as IVsSolution;
Utilities.CheckNotNull(solution);
// Ask solution for unique name of project
string uniqueName;
ErrorHandler.ThrowOnFailure(
solution.GetUniqueNameOfProject(
project.GetOuterInterface<IVsHierarchy>(),
out uniqueName
)
);
return uniqueName;
}
}
}
/// <summary>
/// Gets an interface or object that can be accessed by name at run time.
/// </summary>
public virtual object Object {
get { return this.project.Object; }
}
/// <summary>
/// Gets the requested Extender object if it is available for this object.
/// </summary>
/// <param name="name">The name of the extender object.</param>
/// <returns>An Extender object. </returns>
public virtual object get_Extender(string name) {
Utilities.ArgumentNotNull("name", name);
return DTE.ObjectExtenders.GetExtender(project.NodeProperties.ExtenderCATID.ToUpper(), name, project.NodeProperties);
}
/// <summary>
/// Gets a list of available Extenders for the object.
/// </summary>
public virtual object ExtenderNames {
get { return DTE.ObjectExtenders.GetExtenderNames(project.NodeProperties.ExtenderCATID.ToUpper(), project.NodeProperties); }
}
/// <summary>
/// Gets the Extender category ID (CATID) for the object.
/// </summary>
public virtual string ExtenderCATID {
get { return project.NodeProperties.ExtenderCATID; }
}
/// <summary>
/// Gets the full path and name of the Project object's file.
/// </summary>
public virtual string FullName {
get {
string filename;
uint format;
ErrorHandler.ThrowOnFailure(project.GetCurFile(out filename, out format));
return filename;
}
}
/// <summary>
/// Gets or sets a value indicatingwhether the object has not been modified since last being saved or opened.
/// </summary>
public virtual bool Saved {
get {
return !this.IsDirty;
}
set {
IsDirty = !value;
}
}
/// <summary>
/// Gets the ConfigurationManager object for this Project .
/// </summary>
public virtual EnvDTE.ConfigurationManager ConfigurationManager {
get {
return ProjectNode.Site.GetUIThread().Invoke(() => {
if (this.configurationManager == null) {
IVsExtensibility3 extensibility = this.project.Site.GetService(typeof(IVsExtensibility)) as IVsExtensibility3;
Utilities.CheckNotNull(extensibility);
object configurationManagerAsObject;
ErrorHandler.ThrowOnFailure(extensibility.GetConfigMgr(
this.project.GetOuterInterface<IVsHierarchy>(),
VSConstants.VSITEMID_ROOT,
out configurationManagerAsObject
));
Utilities.CheckNotNull(configurationManagerAsObject);
this.configurationManager = (ConfigurationManager)configurationManagerAsObject;
}
return this.configurationManager;
});
}
}
/// <summary>
/// Gets the Globals object containing add-in values that may be saved in the solution (.sln) file, the project file, or in the user's profile data.
/// </summary>
public virtual EnvDTE.Globals Globals {
get { return null; }
}
/// <summary>
/// Gets a ProjectItem object for the nested project in the host project.
/// </summary>
public virtual EnvDTE.ProjectItem ParentProjectItem {
get { return null; }
}
/// <summary>
/// Gets the CodeModel object for the project.
/// </summary>
public virtual EnvDTE.CodeModel CodeModel {
get { return null; }
}
/// <summary>
/// Saves the project.
/// </summary>
/// <param name="fileName">The file name with which to save the solution, project, or project item. If the file exists, it is overwritten</param>
/// <exception cref="InvalidOperationException">Is thrown if the save operation failes.</exception>
/// <exception cref="ArgumentNullException">Is thrown if fileName is null.</exception>
public virtual void SaveAs(string fileName) {
ProjectNode.Site.GetUIThread().Invoke(() => {
this.DoSave(true, fileName);
});
}
/// <summary>
/// Saves the project
/// </summary>
/// <param name="fileName">The file name of the project</param>
/// <exception cref="InvalidOperationException">Is thrown if the save operation failes.</exception>
/// <exception cref="ArgumentNullException">Is thrown if fileName is null.</exception>
public virtual void Save(string fileName) {
ProjectNode.Site.GetUIThread().Invoke(() => {
this.DoSave(false, fileName);
});
}
/// <summary>
/// Removes the project from the current solution.
/// </summary>
public virtual void Delete() {
CheckProjectIsValid();
using (AutomationScope scope = new AutomationScope(this.project.Site)) {
ProjectNode.Site.GetUIThread().Invoke(() => {
this.project.Remove(false);
});
}
}
#endregion
#region ISupportVSProperties methods
/// <summary>
/// Microsoft Internal Use Only.
/// </summary>
public virtual void NotifyPropertiesDelete() {
}
#endregion
#region private methods
/// <summary>
/// Saves or Save Asthe project.
/// </summary>
/// <param name="isCalledFromSaveAs">Flag determining which Save method called , the SaveAs or the Save.</param>
/// <param name="fileName">The name of the project file.</param>
private void DoSave(bool isCalledFromSaveAs, string fileName) {
Utilities.ArgumentNotNull("fileName", fileName);
CheckProjectIsValid();
using (AutomationScope scope = new AutomationScope(this.project.Site)) {
// If an empty file name is passed in for Save then make the file name the project name.
if (!isCalledFromSaveAs && string.IsNullOrEmpty(fileName)) {
// Use the solution service to save the project file. Note that we have to use the service
// so that all the shell's elements are aware that we are inside a save operation and
// all the file change listenters registered by the shell are suspended.
// Get the cookie of the project file from the RTD.
IVsRunningDocumentTable rdt = this.project.Site.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable;
Utilities.CheckNotNull(rdt);
IVsHierarchy hier;
uint itemid;
IntPtr unkData;
uint cookie;
ErrorHandler.ThrowOnFailure(rdt.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, this.project.Url, out hier,
out itemid, out unkData, out cookie));
if (IntPtr.Zero != unkData) {
Marshal.Release(unkData);
}
// Verify that we have a cookie.
if (0 == cookie) {
// This should never happen because if the project is open, then it must be in the RDT.
throw new InvalidOperationException();
}
// Get the IVsHierarchy for the project.
IVsHierarchy prjHierarchy = project.GetOuterInterface<IVsHierarchy>();
// Now get the soulution.
IVsSolution solution = this.project.Site.GetService(typeof(SVsSolution)) as IVsSolution;
// Verify that we have both solution and hierarchy.
Utilities.CheckNotNull(prjHierarchy);
Utilities.CheckNotNull(solution);
ErrorHandler.ThrowOnFailure(solution.SaveSolutionElement((uint)__VSSLNSAVEOPTIONS.SLNSAVEOPT_SaveIfDirty, prjHierarchy, cookie));
} else {
// We need to make some checks before we can call the save method on the project node.
// This is mainly because it is now us and not the caller like in case of SaveAs or Save that should validate the file name.
// The IPersistFileFormat.Save method only does a validation that is necessary to be performed. Example: in case of Save As the
// file name itself is not validated only the whole path. (thus a file name like file\file is accepted, since as a path is valid)
// 1. The file name has to be valid.
string fullPath = fileName;
try {
fullPath = CommonUtils.GetAbsoluteFilePath(((ProjectNode)Project).ProjectFolder, fileName);
}
// We want to be consistent in the error message and exception we throw. fileName could be for example #¤&%"¤&"% and that would trigger an ArgumentException on Path.IsRooted.
catch (ArgumentException ex) {
throw new InvalidOperationException(SR.GetString(SR.ErrorInvalidFileName, fileName), ex);
}
// It might be redundant but we validate the file and the full path of the file being valid. The SaveAs would also validate the path.
// If we decide that this is performance critical then this should be refactored.
Utilities.ValidateFileName(this.project.Site, fullPath);
if (!isCalledFromSaveAs) {
// 2. The file name has to be the same
if (!CommonUtils.IsSamePath(fullPath, this.project.Url)) {
throw new InvalidOperationException();
}
ErrorHandler.ThrowOnFailure(this.project.Save(fullPath, 1, 0));
} else {
ErrorHandler.ThrowOnFailure(this.project.Save(fullPath, 0, 0));
}
}
}
}
#endregion
}
/// <summary>
/// Specifies an alternate name for a property which cannot be fully captured using
/// .NET attribute names.
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
class PropertyNameAttribute : Attribute {
public readonly string Name;
public PropertyNameAttribute(string name) {
Name = name;
}
}
}
| munyirik/nodejstools | Common/Product/SharedProject/Automation/OAProject.cs | C# | apache-2.0 | 16,787 |
/*
* 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.isis.core.metamodel.services.appfeat;
import java.util.SortedSet;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import org.apache.isis.applib.IsisApplibModule;
import org.apache.isis.applib.annotation.Programmatic;
import org.apache.isis.applib.annotation.SemanticsOf;
import org.apache.isis.applib.services.appfeat.ApplicationFeatureRepository;
import org.apache.isis.applib.services.appfeat.ApplicationMemberType;
import org.apache.isis.applib.util.ObjectContracts;
/**
* Canonical application feature, identified by {@link ApplicationFeatureId},
* and wired together with other application features and cached by {@link ApplicationFeatureRepository}.
*
* <p>
* Note that this is NOT a view model; instead it can be converted to a string using methods of
* {@link ApplicationFeatureRepository}, eg {@link ApplicationFeatureRepository#classNamesContainedIn(String, ApplicationMemberType)}.
* </p>
*/
public class ApplicationFeature implements Comparable<ApplicationFeature> {
public static abstract class PropertyDomainEvent<T> extends IsisApplibModule.PropertyDomainEvent<ApplicationFeature, T> {}
public static abstract class CollectionDomainEvent<T> extends IsisApplibModule.CollectionDomainEvent<ApplicationFeature, T> {}
public static abstract class ActionDomainEvent extends IsisApplibModule.ActionDomainEvent<ApplicationFeature> {}
//region > constants
// using same value for all to neaten up rendering
public static final int TYPICAL_LENGTH_PKG_FQN = 50;
public static final int TYPICAL_LENGTH_CLS_NAME = 50;
public static final int TYPICAL_LENGTH_MEMBER_NAME = 50;
//endregion
//region > constructors
public ApplicationFeature() {
this(null);
}
public ApplicationFeature(final ApplicationFeatureId featureId) {
setFeatureId(featureId);
}
//endregion
//region > featureId
private ApplicationFeatureId featureId;
@Programmatic
public ApplicationFeatureId getFeatureId() {
return featureId;
}
public void setFeatureId(final ApplicationFeatureId applicationFeatureId) {
this.featureId = applicationFeatureId;
}
//endregion
//region > memberType
private ApplicationMemberType memberType;
/**
* Only for {@link ApplicationFeatureType#MEMBER member}s.
*/
@Programmatic
public ApplicationMemberType getMemberType() {
return memberType;
}
public void setMemberType(final ApplicationMemberType memberType) {
this.memberType = memberType;
}
//endregion
//region > returnTypeName (for: properties, collections, actions)
private String returnTypeName;
/**
* Only for {@link ApplicationMemberType#ACTION action}s.
*/
@Programmatic
public String getReturnTypeName() {
return returnTypeName;
}
public void setReturnTypeName(final String returnTypeName) {
this.returnTypeName = returnTypeName;
}
//endregion
//region > contributed (for: properties, collections, actions)
private boolean contributed;
@Programmatic
public boolean isContributed() {
return contributed;
}
public void setContributed(final boolean contributed) {
this.contributed = contributed;
}
//endregion
//region > derived (properties and collections)
private Boolean derived;
/**
* Only for {@link ApplicationMemberType#PROPERTY} and {@link ApplicationMemberType#COLLECTION}
*/
@Programmatic
public Boolean isDerived() {
return derived;
}
public void setDerived(final Boolean derived) {
this.derived = derived;
}
//endregion
//region > propertyMaxLength (properties only)
private Integer propertyMaxLength;
/**
* Only for {@link ApplicationMemberType#ACTION action}s.
*/
@Programmatic
public Integer getPropertyMaxLength() {
return propertyMaxLength;
}
public void setPropertyMaxLength(final Integer propertyMaxLength) {
this.propertyMaxLength = propertyMaxLength;
}
//endregion
//region > propertyTypicalLength (properties only)
private Integer propertyTypicalLength;
/**
* Only for {@link ApplicationMemberType#ACTION action}s.
*/
@Programmatic
public Integer getPropertyTypicalLength() {
return propertyTypicalLength;
}
public void setPropertyTypicalLength(final Integer propertyTypicalLength) {
this.propertyTypicalLength = propertyTypicalLength;
}
//endregion
//region > actionSemantics (actions only)
private SemanticsOf actionSemantics;
/**
* Only for {@link ApplicationMemberType#ACTION action}s.
*/
@Programmatic
public SemanticsOf getActionSemantics() {
return actionSemantics;
}
public void setActionSemantics(final SemanticsOf actionSemantics) {
this.actionSemantics = actionSemantics;
}
//endregion
//region > packages: Contents
private final SortedSet<ApplicationFeatureId> contents = Sets.newTreeSet();
@Programmatic
public SortedSet<ApplicationFeatureId> getContents() {
ApplicationFeatureType.ensurePackage(this.getFeatureId());
return contents;
}
@Programmatic
public void addToContents(final ApplicationFeatureId contentId) {
ApplicationFeatureType.ensurePackage(this.getFeatureId());
ApplicationFeatureType.ensurePackageOrClass(contentId);
this.contents.add(contentId);
}
//endregion
//region > classes: Properties, Collections, Actions
private final SortedSet<ApplicationFeatureId> properties = Sets.newTreeSet();
@Programmatic
public SortedSet<ApplicationFeatureId> getProperties() {
ApplicationFeatureType.ensureClass(this.getFeatureId());
return properties;
}
private final SortedSet<ApplicationFeatureId> collections = Sets.newTreeSet();
@Programmatic
public SortedSet<ApplicationFeatureId> getCollections() {
ApplicationFeatureType.ensureClass(this.getFeatureId());
return collections;
}
private final SortedSet<ApplicationFeatureId> actions = Sets.newTreeSet();
@Programmatic
public SortedSet<ApplicationFeatureId> getActions() {
ApplicationFeatureType.ensureClass(this.getFeatureId());
return actions;
}
@Programmatic
public void addToMembers(final ApplicationFeatureId memberId, final ApplicationMemberType memberType) {
ApplicationFeatureType.ensureClass(this.getFeatureId());
ApplicationFeatureType.ensureMember(memberId);
membersOf(memberType).add(memberId);
}
@Programmatic
public SortedSet<ApplicationFeatureId> membersOf(final ApplicationMemberType memberType) {
ApplicationFeatureType.ensureClass(this.getFeatureId());
switch (memberType) {
case PROPERTY:
return properties;
case COLLECTION:
return collections;
default: // case ACTION:
return actions;
}
}
//endregion
//region > Functions
public static class Functions {
private Functions(){}
public static final Function<? super ApplicationFeature, ? extends String> GET_FQN = new Function<ApplicationFeature, String>() {
@Override
public String apply(final ApplicationFeature input) {
return input.getFeatureId().getFullyQualifiedName();
}
};
public static final Function<ApplicationFeature, ApplicationFeatureId> GET_ID =
new Function<ApplicationFeature, ApplicationFeatureId>() {
@Override
public ApplicationFeatureId apply(final ApplicationFeature input) {
return input.getFeatureId();
}
};
}
public static class Predicates {
private Predicates(){}
public static Predicate<ApplicationFeature> packageContainingClasses(
final ApplicationMemberType memberType, final ApplicationFeatureRepositoryDefault applicationFeatures) {
return new Predicate<ApplicationFeature>() {
@Override
public boolean apply(final ApplicationFeature input) {
// all the classes in this package
final Iterable<ApplicationFeatureId> classIds =
Iterables.filter(input.getContents(),
ApplicationFeatureId.Predicates.isClassContaining(memberType, applicationFeatures));
return classIds.iterator().hasNext();
}
};
}
}
//endregion
//region > equals, hashCode, compareTo, toString
private final static String propertyNames = "featureId";
@Override
public int compareTo(final ApplicationFeature other) {
return ObjectContracts.compare(this, other, propertyNames);
}
@Override
public boolean equals(final Object obj) {
return ObjectContracts.equals(this, obj, propertyNames);
}
@Override
public int hashCode() {
return ObjectContracts.hashCode(this, propertyNames);
}
@Override
public String toString() {
return ObjectContracts.toString(this, propertyNames);
}
//endregion
}
| niv0/isis | core/metamodel/src/main/java/org/apache/isis/core/metamodel/services/appfeat/ApplicationFeature.java | Java | apache-2.0 | 10,327 |
/*
* 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.isis.core.runtime.authentication.standard;
import java.util.List;
import org.apache.isis.core.commons.components.InstallerAbstract;
import org.apache.isis.core.commons.config.IsisConfiguration;
import org.apache.isis.core.runtime.authentication.AuthenticationManager;
import org.apache.isis.core.runtime.authentication.AuthenticationManagerInstaller;
public abstract class AuthenticationManagerStandardInstallerAbstract extends InstallerAbstract implements AuthenticationManagerInstaller {
public AuthenticationManagerStandardInstallerAbstract(
final String name,
final IsisConfiguration isisConfiguration) {
super(name, isisConfiguration);
}
@Override
public final AuthenticationManager createAuthenticationManager() {
final AuthenticationManagerStandard authenticationManager = createAuthenticationManagerStandard();
for (final Authenticator authenticator : createAuthenticators()) {
authenticationManager.addAuthenticator(authenticator);
}
return authenticationManager;
}
protected AuthenticationManagerStandard createAuthenticationManagerStandard() {
return new AuthenticationManagerStandard(getConfiguration());
}
/**
* Hook method
*
* @return
*/
protected abstract List<Authenticator> createAuthenticators();
@Override
public List<Class<?>> getTypes() {
return listOf(AuthenticationManager.class);
}
}
| niv0/isis | core/metamodel/src/main/java/org/apache/isis/core/runtime/authentication/standard/AuthenticationManagerStandardInstallerAbstract.java | Java | apache-2.0 | 2,324 |
/*
* Copyright (C) 2014 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.
*/
package com.android.systemui.volume;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.view.animation.Interpolator;
public class IconPulser {
private static final float PULSE_SCALE = 1.1f;
private final Interpolator mFastOutSlowInInterpolator;
public IconPulser(Context context) {
mFastOutSlowInInterpolator = AnimationUtils.loadInterpolator(context,
android.R.interpolator.fast_out_slow_in);
}
public void start(final View target) {
if (target == null || target.getScaleX() != 1) return; // n/a, or already running
target.animate().cancel();
target.animate().scaleX(PULSE_SCALE).scaleY(PULSE_SCALE)
.setInterpolator(mFastOutSlowInInterpolator)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
target.animate().scaleX(1).scaleY(1).setListener(null);
}
});
}
}
| Ant-Droid/android_frameworks_base_OLD | packages/SystemUI/src/com/android/systemui/volume/IconPulser.java | Java | apache-2.0 | 1,800 |
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
function plural(n) {
if (n === 0)
return 0;
if (n === 1)
return 1;
if (n === 2)
return 2;
if (n % 100 === Math.floor(n % 100) && n % 100 >= 3 && n % 100 <= 10)
return 3;
if (n % 100 === Math.floor(n % 100) && n % 100 >= 11 && n % 100 <= 99)
return 4;
return 5;
}
export default [
'ar-JO',
[
['ص', 'م'],
,
],
[['ص', 'م'], , ['صباحًا', 'مساءً']],
[
['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'],
[
'الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس',
'الجمعة', 'السبت'
],
,
['أحد', 'إثنين', 'ثلاثاء', 'أربعاء', 'خميس', 'جمعة', 'سبت']
],
,
[
['ك', 'ش', 'آ', 'ن', 'أ', 'ح', 'ت', 'آ', 'أ', 'ت', 'ت', 'ك'],
[
'كانون الثاني', 'شباط', 'آذار', 'نيسان', 'أيار', 'حزيران',
'تموز', 'آب', 'أيلول', 'تشرين الأول', 'تشرين الثاني',
'كانون الأول'
],
],
,
[['ق.م', 'م'], , ['قبل الميلاد', 'ميلادي']], 6, [5, 6],
['d\u200f/M\u200f/y', 'dd\u200f/MM\u200f/y', 'd MMMM y', 'EEEE، d MMMM y'],
['h:mm a', 'h:mm:ss a', 'h:mm:ss a z', 'h:mm:ss a zzzz'],
[
'{1} {0}',
,
,
],
[
'.', ',', ';', '\u200e%\u200e', '\u200e+', '\u200e-', 'E', '×', '‰', '∞',
'ليس رقمًا', ':'
],
['#,##0.###', '#,##0%', '¤ #,##0.00', '#E0'], 'د.أ.\u200f', 'دينار أردني', plural
];
//# sourceMappingURL=ar-JO.js.map | rospilot/rospilot | share/web_assets/nodejs_deps/node_modules/@angular/common/locales/ar-JO.js | JavaScript | apache-2.0 | 1,996 |
/*
* Copyright 2010-2015 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/elasticloadbalancing/model/SetLoadBalancerPoliciesForBackendServerResult.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <utility>
using namespace Aws::ElasticLoadBalancing::Model;
using namespace Aws::Utils::Xml;
using namespace Aws::Utils;
using namespace Aws;
SetLoadBalancerPoliciesForBackendServerResult::SetLoadBalancerPoliciesForBackendServerResult()
{
}
SetLoadBalancerPoliciesForBackendServerResult::SetLoadBalancerPoliciesForBackendServerResult(const AmazonWebServiceResult<XmlDocument>& result)
{
*this = result;
}
SetLoadBalancerPoliciesForBackendServerResult& SetLoadBalancerPoliciesForBackendServerResult::operator =(const AmazonWebServiceResult<XmlDocument>& result)
{
const XmlDocument& xmlDocument = result.GetPayload();
XmlNode rootNode = xmlDocument.GetRootElement();
XmlNode resultNode = rootNode.FirstChild("SetLoadBalancerPoliciesForBackendServerResult");
if(!resultNode.IsNull())
{
}
XmlNode responseMetadataNode = rootNode.FirstChild("ResponseMetadata");
m_responseMetadata = responseMetadataNode;
return *this;
}
| bmildner/aws-sdk-cpp | aws-cpp-sdk-elasticloadbalancing/source/model/SetLoadBalancerPoliciesForBackendServerResult.cpp | C++ | apache-2.0 | 1,747 |
/*
* 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.kafka.clients;
/**
* A callback interface for attaching an action to be executed when a request is complete and the corresponding response
* has been received. This handler will also be invoked if there is a disconnection while handling the request.
*/
public interface RequestCompletionHandler {
void onComplete(ClientResponse response);
}
| guozhangwang/kafka | clients/src/main/java/org/apache/kafka/clients/RequestCompletionHandler.java | Java | apache-2.0 | 1,168 |
from __future__ import print_function
import shlex
import subprocess
import sys
from .config import Configuration
class PkgConfig(object):
class Error(Exception):
"""Raised when information could not be obtained from pkg-config."""
def __init__(self, package_name):
"""Query pkg-config for information about a package.
:type package_name: str
:param package_name: The name of the package to query.
:raises PkgConfig.Error: When a call to pkg-config fails.
"""
self.package_name = package_name
self._cflags = self._call("--cflags")
self._cflags_only_I = self._call("--cflags-only-I")
self._cflags_only_other = self._call("--cflags-only-other")
self._libs = self._call("--libs")
self._libs_only_l = self._call("--libs-only-l")
self._libs_only_L = self._call("--libs-only-L")
self._libs_only_other = self._call("--libs-only-other")
def _call(self, *pkg_config_args):
try:
cmd = [Configuration.current.pkg_config] + list(pkg_config_args) + [self.package_name]
print("Executing command '{}'".format(cmd), file=sys.stderr)
return shlex.split(subprocess.check_output(cmd).decode('utf-8'))
except subprocess.CalledProcessError as e:
raise self.Error("pkg-config exited with error code {}".format(e.returncode))
@property
def swiftc_flags(self):
"""Flags for this package in a format suitable for passing to `swiftc`.
:rtype: list[str]
"""
return (
["-Xcc {}".format(s) for s in self._cflags_only_other]
+ ["-Xlinker {}".format(s) for s in self._libs_only_other]
+ self._cflags_only_I
+ self._libs_only_L
+ self._libs_only_l)
@property
def cflags(self):
"""CFLAGS for this package.
:rtype: list[str]
"""
return self._cflags
@property
def ldflags(self):
"""LDFLAGS for this package.
:rtype: list[str]
"""
return self._libs
| JGiola/swift-corelibs-foundation | lib/pkg_config.py | Python | apache-2.0 | 2,114 |
// Declare internals
var internals = {};
// Plugin registration
exports.register = function (plugin, options, next) {
plugin.route({ path: '/test2', method: 'GET', handler: function (request, reply) { reply('testing123'); } });
plugin.route({ path: '/test2/path', method: 'GET', handler: function (request, reply) { reply(plugin.path); } });
plugin.log('test', 'abc');
return next();
};
| thebillkidy/WebRTC-Stream | server/node_modules/hapi/test/integration/pack/--test2/lib/index.js | JavaScript | apache-2.0 | 409 |
/*
* 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.cache.query.internal.parse;
import antlr.*;
import org.apache.geode.cache.query.internal.QCompiler;
public class ASTTypeCast extends GemFireAST {
private static final long serialVersionUID = -6368577668325776355L;
public ASTTypeCast() {}
public ASTTypeCast(Token t) {
super(t);
}
@Override
public void compile(QCompiler compiler) {
super.compile(compiler);
// there's a type on the stack now
compiler.typecast();
}
}
| pivotal-amurmann/geode | geode-core/src/main/java/org/apache/geode/cache/query/internal/parse/ASTTypeCast.java | Java | apache-2.0 | 1,274 |
# -*- coding: utf-8 -*-
#
# cloudtracker documentation build configuration file, created by
# sphinx-quickstart on Fri Aug 5 12:45:40 2011.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('..'))
sys.path.insert(0, os.path.abspath('../cloudtracker/'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.pngmath']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'cloudtracker'
copyright = u'2011, Jordan Dawe'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '1.0'
# The full version, including alpha/beta/rc tags.
release = '1.0'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'cloudtrackerdoc'
# -- Options for LaTeX output --------------------------------------------------
# The paper size ('letter' or 'a4').
#latex_paper_size = 'letter'
# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'cloudtracker.tex', u'cloudtracker Documentation',
u'Jordan Dawe', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Additional stuff for the LaTeX preamble.
#latex_preamble = ''
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'cloudtracker', u'cloudtracker Documentation',
[u'Jordan Dawe'], 1)
]
| freedryk/cloudtracker | doc/conf.py | Python | bsd-2-clause | 7,125 |
{% extends "graphos/gchart/base.html" %}
{% block create_chart %}
var chart = new google.visualization.LineChart(document.getElementById('{{ chart.get_html_id }}'));
{% endblock %} | aorzh/django-graphos | graphos/templates/graphos/gchart/line_chart.html | HTML | bsd-2-clause | 183 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Minim : : AudioPlayer : : close</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link href="stylesheet.css" rel="stylesheet" type="text/css">
</head>
<body>
<center>
<table width="600" border="0" cellspacing="0" cellpadding="0">
<tr>
<td height="100" valign="top" class="header">
<span class="libName">Minim</span><br>
<a href="index.html">core</a><br/>
<a href="index_ugens.html">ugens</a><br/>
<a href="index_analysis.html">analysis</a>
</td>
<td width="450" class="descList"> </td>
</tr>
<tr>
<td valign="top" class="mainTextName">Name</td>
<td class="methodName">close</td>
</tr>
<tr>
<td valign=top class="mainText">Examples</td>
<td valign=top class="descList"><pre>None available</pre></td>
</tr>
<tr>
<td valign=top class="mainText">Description</td>
<td valign=top class="descList">Release the resources associated with playing this file.
All AudioPlayers returned by Minim's loadFile method
will be closed by Minim when it's stop method is called.
If you are using Processing, Minim's stop method will be
called automatically when your application exits.</td>
</tr>
<tr>
<td valign=top class="mainText">Syntax</td>
<td valign=top class="descList"><pre>close();
</pre></td>
</tr>
<!-- begin parameters -->
<!-- end parameters -->
<!-- begin return -->
<tr>
<td valign=top class="mainText">Returns</td>
<td class="descList">None</td>
</tr>
<!-- end return -->
<tr>
<td valign=top class="mainText">Usage</td>
<td class="descList">Web & Application</td>
</tr>
<tr>
<td valign=top class="mainText">Related</td>
<td class="descList"></td>
</tr>
<tr>
<td></td>
<td class="descList"> </td>
</tr>
</table>
</center>
</body>
</html>
| UTSDataArena/examples | processing/sketchbook/libraries/minim/documentation/audioplayer_method_close.html | HTML | bsd-2-clause | 2,021 |
// Copyright (C) 2015 André Bargull. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: Compound Assignment Operator evaluates its operands from left to right.
description: >
The left-hand side expression is evaluated before the right-hand side.
Left-hand side expression is MemberExpression: base[prop]. base is the
undefined value.
Check operator is "x <<= y".
---*/
function DummyError() { }
assert.throws(DummyError, function() {
var base = undefined;
var prop = function() {
throw new DummyError();
};
var expr = function() {
$ERROR("right-hand side expression evaluated");
};
base[prop()] <<= expr();
});
assert.throws(TypeError, function() {
var base = undefined;
var prop = {
toString: function() {
$ERROR("property key evaluated");
}
};
var expr = function() {
$ERROR("right-hand side expression evaluated");
};
base[prop] <<= expr();
});
| sebastienros/jint | Jint.Tests.Test262/test/language/expressions/compound-assignment/S11.13.2_A7.6_T2.js | JavaScript | bsd-2-clause | 974 |
/*!
* FileInput Polish Translations
*
* This file must be loaded after 'fileinput.js'. Patterns in braces '{}', or
* any HTML markup tags in the messages must not be converted or translated.
*
* @see http://github.com/kartik-v/bootstrap-fileinput
*
* NOTE: this file must be saved in UTF-8 encoding.
*/
(function ($) {
"use strict";
$.fn.fileinputLocales['pl'] = {
fileSingle: 'plik',
filePlural: 'pliki',
browseLabel: 'Przeglądaj …',
removeLabel: 'Usuń',
removeTitle: 'Usuń zaznaczone pliki',
cancelLabel: 'Przerwij',
cancelTitle: 'Anuluj wysyłanie',
pauseLabel: 'Wstrzymaj',
pauseTitle: 'Wstrzymaj trwające przesyłanie',
uploadLabel: 'Wgraj',
uploadTitle: 'Wgraj zaznaczone pliki',
msgNo: 'Nie',
msgNoFilesSelected: 'Brak zaznaczonych plików',
msgPaused: 'Wstrzymano',
msgCancelled: 'Odwołany',
msgPlaceholder: 'Wybierz {files} ...',
msgZoomModalHeading: 'Szczegółowy podgląd',
msgFileRequired: 'Musisz wybrać plik do wgrania.',
msgSizeTooSmall: 'Plik "{name}" (<b>{size} KB</b>) jest zbyt mały i musi być większy niż <b>{minSize} KB</b>.',
msgSizeTooLarge: 'Plik o nazwie "{name}" (<b>{size} KB</b>) przekroczył maksymalną dopuszczalną wielkość pliku wynoszącą <b>{maxSize} KB</b>.',
msgFilesTooLess: 'Minimalna liczba plików do wgrania: <b>{n}</b>.',
msgFilesTooMany: 'Liczba plików wybranych do wgrania w liczbie <b>({n})</b>, przekracza maksymalny dozwolony limit wynoszący <b>{m}</b>.',
msgTotalFilesTooMany: 'Możesz wgrać maksymalnie <b>{m}</b> plików (wykryto <b>{n}</b>).',
msgFileNotFound: 'Plik "{name}" nie istnieje!',
msgFileSecured: 'Ustawienia zabezpieczeń uniemożliwiają odczyt pliku "{name}".',
msgFileNotReadable: 'Plik "{name}" nie jest plikiem do odczytu.',
msgFilePreviewAborted: 'Podgląd pliku "{name}" został przerwany.',
msgFilePreviewError: 'Wystąpił błąd w czasie odczytu pliku "{name}".',
msgInvalidFileName: 'Nieprawidłowe lub nieobsługiwane znaki w nazwie pliku "{name}".',
msgInvalidFileType: 'Nieznany typ pliku "{name}". Tylko następujące rodzaje plików są dozwolone: "{types}".',
msgInvalidFileExtension: 'Złe rozszerzenie dla pliku "{name}". Tylko następujące rozszerzenia plików są dozwolone: "{extensions}".',
msgUploadAborted: 'Przesyłanie pliku zostało przerwane',
msgUploadThreshold: 'Przetwarzanie …',
msgUploadBegin: 'Rozpoczynanie …',
msgUploadEnd: 'Gotowe!',
msgUploadResume: 'Wznawianie przesyłania …',
msgUploadEmpty: 'Brak poprawnych danych do przesłania.',
msgUploadError: 'Błąd przesyłania',
msgDeleteError: 'Błąd usuwania',
msgProgressError: 'Błąd',
msgValidationError: 'Błąd walidacji',
msgLoading: 'Wczytywanie pliku {index} z {files} …',
msgProgress: 'Wczytywanie pliku {index} z {files} - {name} - {percent}% zakończone.',
msgSelected: '{n} Plików zaznaczonych',
msgFoldersNotAllowed: 'Metodą przeciągnij i upuść, można przenosić tylko pliki. Pominięto {n} katalogów.',
msgImageWidthSmall: 'Szerokość pliku obrazu "{name}" musi być co najmniej {size} px.',
msgImageHeightSmall: 'Wysokość pliku obrazu "{name}" musi być co najmniej {size} px.',
msgImageWidthLarge: 'Szerokość pliku obrazu "{name}" nie może przekraczać {size} px.',
msgImageHeightLarge: 'Wysokość pliku obrazu "{name}" nie może przekraczać {size} px.',
msgImageResizeError: 'Nie udało się uzyskać wymiaru obrazu, aby zmienić rozmiar.',
msgImageResizeException: 'Błąd podczas zmiany rozmiaru obrazu.<pre>{errors}</pre>',
msgAjaxError: 'Coś poczło nie tak podczas {operation}. Spróbuj ponownie!',
msgAjaxProgressError: '{operation} nie powiodło się',
msgDuplicateFile: 'Plik "{name}" o identycznym rozmiarze "{size} KB" został wgrany wcześniej. Pomijanie zduplikowanego pliku.',
msgResumableUploadRetriesExceeded: 'Przekroczono limit <b>{max}</b> prób wgrania pliku <b>{file}</b>! Szczegóły błędu: <pre>{error}</pre>',
msgPendingTime: 'Pozostało {time}',
msgCalculatingTime: 'obliczanie pozostałego czasu',
ajaxOperations: {
deleteThumb: 'usuwanie pliku',
uploadThumb: 'przesyłanie pliku',
uploadBatch: 'masowe przesyłanie plików',
uploadExtra: 'przesyłanie danych formularza'
},
dropZoneTitle: 'Przeciągnij i upuść pliki tutaj …',
dropZoneClickTitle: '<br>(lub kliknij tutaj i wybierz {files} z komputera)',
fileActionSettings: {
removeTitle: 'Usuń plik',
uploadTitle: 'Przesyłanie pliku',
uploadRetryTitle: 'Ponów',
downloadTitle: 'Pobierz plik',
zoomTitle: 'Pokaż szczegóły',
dragTitle: 'Przenies / Ponownie zaaranżuj',
indicatorNewTitle: 'Jeszcze nie przesłany',
indicatorSuccessTitle: 'Dodane',
indicatorErrorTitle: 'Błąd',
indicatorPausedTitle: 'Przesyłanie zatrzymane',
indicatorLoadingTitle: 'Przesyłanie …'
},
previewZoomButtonTitles: {
prev: 'Pokaż poprzedni plik',
next: 'Pokaż następny plik',
toggleheader: 'Włącz / wyłącz nagłówek',
fullscreen: 'Włącz / wyłącz pełny ekran',
borderless: 'Włącz / wyłącz tryb bez ramek',
close: 'Zamknij szczegółowy widok'
}
};
})(window.jQuery);
| OlliL/lalaMoneyflow | client/contrib/bootstrap-fileinput/js/locales/pl.js | JavaScript | bsd-2-clause | 5,901 |
using UnityEngine;
using System.Collections;
/// <summary>
/// Key input enumeration for easy input sending.
/// </summary>
public enum KeyInput
{
GoLeft = 0,
GoRight,
GoDown,
Jump,
Count
} | tutsplus/A-Star-Pathfinding-for-Platformers | OneWayPlatforms/Assets/Scripts/KeyInput.cs | C# | bsd-2-clause | 198 |
<?php
namespace Aura\Web\Response;
class CookiesTest extends \PHPUnit_Framework_TestCase
{
protected $cookies;
protected function setUp()
{
$this->cookies = new Cookies;
}
public function testSetAndGet()
{
$this->cookies->set('foo', 'bar', '88', '/path', 'example.com');
$expect = array(
'value' => 'bar',
'expire' => 88,
'path' => '/path',
'domain' => 'example.com',
'secure' => false,
'httponly' => true,
);
$actual = $this->cookies->get('foo');
$this->assertSame($expect, $actual);
}
public function testGetAll()
{
$this->cookies->set('foo', 'bar', '88', '/path', 'example.com');
$this->cookies->set('baz', 'dib', date('Y-m-d H:i:s', '88'), '/path', 'example.com');
$expect = array(
'foo' => array(
'value' => 'bar',
'expire' => 88,
'path' => '/path',
'domain' => 'example.com',
'secure' => false,
'httponly' => true,
),
'baz' => array(
'value' => 'dib',
'expire' => 88,
'path' => '/path',
'domain' => 'example.com',
'secure' => false,
'httponly' => true,
),
);
$actual = $this->cookies->get();
$this->assertSame($expect, $actual);
}
public function testDefault()
{
// set a cookie name and value
$this->cookies->set('foo', 'bar');
// get before defaults
$expect = array(
'value' => 'bar',
'expire' => 0,
'path' => '',
'domain' => '',
'secure' => false,
'httponly' => true,
);
$actual = $this->cookies->get('foo');
$this->assertSame($expect, $actual);
// set and get defaults
$this->cookies->setExpire(88);
$this->cookies->setPath('/path');
$this->cookies->setDomain('example.com');
$this->cookies->setSecure(true);
$this->cookies->setHttponly(false);
// get after defaults
$expect = array(
'value' => null,
'expire' => 88,
'path' => '/path',
'domain' => 'example.com',
'secure' => true,
'httponly' => false,
);
$actual = $this->cookies->getDefault();
$this->assertSame($expect, $actual);
}
}
| auraphp/Aura.Web | tests/Response/CookiesTest.php | PHP | bsd-2-clause | 2,511 |
/* $NetBSD: citrus_gbk2k.h,v 1.2 2003/06/25 09:51:43 tshiozak Exp $ */
/*-
* Copyright (c)2003 Citrus Project,
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#ifndef _CITRUS_GBK2K_H_
#define _CITRUS_GBK2K_H_
__BEGIN_DECLS
_CITRUS_CTYPE_GETOPS_FUNC(GBK2K);
_CITRUS_STDENC_GETOPS_FUNC(GBK2K);
__END_DECLS
#endif
| evrom/bsdlibc | src/lib/libc/citrus/modules/citrus_gbk2k.h | C | bsd-2-clause | 1,583 |
var path = require('path');
var url = require('url');
var closure = require('closure-util');
var nomnom = require('nomnom');
var log = closure.log;
var options = nomnom.options({
port: {
abbr: 'p',
'default': 4000,
help: 'Port for incoming connections',
metavar: 'PORT'
},
loglevel: {
abbr: 'l',
choices: ['silly', 'verbose', 'info', 'warn', 'error'],
'default': 'info',
help: 'Log level',
metavar: 'LEVEL'
}
}).parse();
/** @type {string} */
log.level = options.loglevel;
log.info('ol3-cesium', 'Parsing dependencies ...');
var manager = new closure.Manager({
closure: true, // use the bundled Closure Library
lib: [
'src/**/*.js'
],
ignoreRequires: '^ol\\.'
});
manager.on('error', function(e) {
log.error('ol3-cesium', e.message);
});
manager.on('ready', function() {
var server = new closure.Server({
manager: manager,
loader: '/@loader'
});
server.listen(options.port, function() {
log.info('ol3-cesium', 'Listening on http://localhost:' +
options.port + '/ (Ctrl+C to stop)');
});
server.on('error', function(err) {
log.error('ol3-cesium', 'Server failed to start: ' + err.message);
process.exit(1);
});
});
| GistdaDev/ol3-cesium | build/serve.js | JavaScript | bsd-2-clause | 1,218 |
#region BSD License
/*
Copyright (c) 2012, Clarius Consulting
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.
*/
#endregion
namespace Clide.VisualStudio
{
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
internal static class VsServiceProviderExtensions
{
public static VsToolWindow ToolWindow(this IServiceProvider serviceProvider, Guid toolWindowId)
{
return new VsToolWindow(serviceProvider, toolWindowId);
}
public static IVsHierarchy GetSelectedHierarchy(this IVsMonitorSelection monitorSelection, IUIThread uiThread)
{
var hierarchyPtr = IntPtr.Zero;
var selectionContainer = IntPtr.Zero;
return uiThread.Invoke(() =>
{
try
{
// Get the current project hierarchy, project item, and selection container for the current selection
// If the selection spans multiple hierarchies, hierarchyPtr is Zero.
// So fast path is for non-zero result (most common case of single active project/item).
uint itemid;
IVsMultiItemSelect multiItemSelect = null;
ErrorHandler.ThrowOnFailure(monitorSelection.GetCurrentSelection(out hierarchyPtr, out itemid, out multiItemSelect, out selectionContainer));
// There may be no selection at all.
if (itemid == VSConstants.VSITEMID_NIL)
return null;
if (itemid == VSConstants.VSITEMID_ROOT)
{
// The root selection could be the solution itself, so no project is active.
if (hierarchyPtr == IntPtr.Zero)
return null;
else
return (IVsHierarchy)Marshal.GetTypedObjectForIUnknown(hierarchyPtr, typeof(IVsHierarchy));
}
// We may have a single item selection, so we can safely pick its owning project/hierarchy.
if (itemid != VSConstants.VSITEMID_SELECTION)
return (IVsHierarchy)Marshal.GetTypedObjectForIUnknown(hierarchyPtr, typeof(IVsHierarchy));
// Otherwise, this is a multiple item selection within the same hierarchy,
// we select he hierarchy.
uint numberOfSelectedItems;
int isSingleHierarchyInt;
ErrorHandler.ThrowOnFailure(multiItemSelect.GetSelectionInfo(out numberOfSelectedItems, out isSingleHierarchyInt));
var isSingleHierarchy = (isSingleHierarchyInt != 0);
if (isSingleHierarchy)
return (IVsHierarchy)Marshal.GetTypedObjectForIUnknown(hierarchyPtr, typeof(IVsHierarchy));
return null;
}
finally
{
if (hierarchyPtr != IntPtr.Zero)
{
Marshal.Release(hierarchyPtr);
}
if (selectionContainer != IntPtr.Zero)
{
Marshal.Release(selectionContainer);
}
}
});
}
public static IEnumerable<Tuple<IVsHierarchy, uint>> GetSelection(this IVsMonitorSelection monitorSelection, IUIThread uiThread, IVsHierarchy solution)
{
var hierarchyPtr = IntPtr.Zero;
var selectionContainer = IntPtr.Zero;
return uiThread.Invoke(() =>
{
try
{
// Get the current project hierarchy, project item, and selection container for the current selection
// If the selection spans multiple hierarchies, hierarchyPtr is Zero
uint itemid;
IVsMultiItemSelect multiItemSelect = null;
ErrorHandler.ThrowOnFailure(monitorSelection.GetCurrentSelection(out hierarchyPtr, out itemid, out multiItemSelect, out selectionContainer));
if (itemid == VSConstants.VSITEMID_NIL)
return Enumerable.Empty<Tuple<IVsHierarchy, uint>>();
if (itemid == VSConstants.VSITEMID_ROOT)
{
if (hierarchyPtr == IntPtr.Zero)
return new[] { Tuple.Create(solution, VSConstants.VSITEMID_ROOT) };
else
return new[] { Tuple.Create(
(IVsHierarchy)Marshal.GetTypedObjectForIUnknown(hierarchyPtr, typeof(IVsHierarchy)),
VSConstants.VSITEMID_ROOT) };
}
if (itemid != VSConstants.VSITEMID_SELECTION)
return new[] { Tuple.Create(
(IVsHierarchy)Marshal.GetTypedObjectForIUnknown(hierarchyPtr, typeof(IVsHierarchy)),
itemid) };
// This is a multiple item selection.
uint numberOfSelectedItems;
int isSingleHierarchyInt;
ErrorHandler.ThrowOnFailure(multiItemSelect.GetSelectionInfo(out numberOfSelectedItems, out isSingleHierarchyInt));
var isSingleHierarchy = (isSingleHierarchyInt != 0);
var vsItemSelections = new VSITEMSELECTION[numberOfSelectedItems];
var flags = (isSingleHierarchy) ? (uint)__VSGSIFLAGS.GSI_fOmitHierPtrs : 0;
ErrorHandler.ThrowOnFailure(multiItemSelect.GetSelectedItems(flags, numberOfSelectedItems, vsItemSelections));
return vsItemSelections.Where(sel => sel.pHier != null)
// NOTE: we can return lazy results here, since
// the GetSelectedItems has already returned in the UI thread
// the array of results. We're just delaying the creation of the tuples
// in case they aren't all needed.
.Select(sel => Tuple.Create(sel.pHier, sel.itemid));
}
finally
{
if (hierarchyPtr != IntPtr.Zero)
{
Marshal.Release(hierarchyPtr);
}
if (selectionContainer != IntPtr.Zero)
{
Marshal.Release(selectionContainer);
}
}
});
}
}
}
| austinvernsonger/clide | Src/Clide/VisualStudio/VsServiceProviderExtensions.cs | C# | bsd-2-clause | 8,017 |
/**
* This is specifically for the builder where the
* dependencies have been resolved and you just want
* to access the component.jsons locally.
*/
var semver = require('semver');
var fs = require('graceful-fs');
var join = require('path').join;
var resolve = require('path').resolve;
var debug = require('debug')('remotes:local');
var Remote = require('../remote')
module.exports = Local
Remote.extend(Local)
function Local(options) {
if (!(this instanceof Local))
return new Local(options)
options = Object.create(options || {});
this.out = resolve(options.out
|| options.dir
|| 'components')
debug('checking local components at %s', this.out);
Remote.call(this, options)
}
Local.prototype.name = 'local';
/**
* Local resolution is a little different than other remotes.
* In particular, if no `ref` is set,
* we check for any version.
*
* @param {String} repo
* @return {this}
* @api public
*/
Local.prototype.resolve = function* (remotes, repo, ref) {
debug('resolving local remote');
if (typeof remotes === 'string') {
ref = repo;
repo = remotes;
} else if (Array.isArray(remotes) && !~remotes.indexOf('local')) {
// if the current remote is not in this list,
// then it's obviously not valid.
return;
}
var folders = yield* this.folders(repo);
// none installed
if (!folders || !folders.length) return;
// no specific version we care about
if (!ref) return this;
// exact tag version
if (~folders.indexOf(ref)) return this;
// check for equal semantic versions
if (semver.maxSatisfying(folders.filter(valid), ref)) return this;
}
/**
* Get the currently downloaded versions of a repo.
*
* @param {String} repo
* @return {Array} folders
* @api public
*/
Local.prototype.folders = function* (repo) {
try {
var frags = repo.toLowerCase().split('/');
// ignore malformed repos for now
if (frags.length !== 2) return;
var folder = join(this.out, frags[0], frags[1]);
debug('checking folder: %s', folder);
var folders = yield readdir(folder);
debug('got folders: %s', folders.join(', '));
return folders.filter(noLeadingDot);
} catch (err) {
if (err.code === 'ENOENT') return;
throw err;
}
}
/**
* Return the currently downloaded components' semantic versions.
*
* @param {String} repo
* @return {Array} references
* @api public
*/
Local.prototype._versions = function* (repo) {
return yield* this.folders(repo);
}
/**
* Return the existing component.json, if any.
* @param {String} repo
* @param {String} reference
* @return {Object} component.json
* @api public
*/
Local.prototype._json = function* (repo, ref) {
var body;
var filename = join(this.out, repo, ref, 'component.json');
try {
body = yield read(filename);
} catch (err) {
if (err.code === 'ENOENT') return;
throw err;
}
try {
return JSON.parse(body);
} catch (_err) {
throw new Error('JSON parsing error with "' + filename + '"');
}
}
/**
* NOT RELEVANT WITH THIS REMOTE
*/
Local.prototype._tree = function* () {
/* jshint noyield:true */
}
function valid(x) {
return semver.valid(x, true);
}
function noLeadingDot(x) {
return x[0] !== '.';
}
function readdir(root) {
return function (done) {
fs.readdir(root, done)
}
}
function read(filename) {
return function (done) {
fs.readFile(filename, 'utf8', done)
}
}
| bmanth60/workflow-test | node_modules/component/node_modules/component-remotes/lib/remotes/local.js | JavaScript | bsd-3-clause | 3,407 |
@(user: User = null, scripts: Html = Html(""))(content: Html)
<!DOCTYPE html>
<html>
<head>
<title>@Messages("title")</title>
<link rel="stylesheet" media="screen" href="@routes.Assets.at("stylesheets/bootstrap.css")">
<link rel="stylesheet" media="screen" href="@routes.Assets.at("stylesheets/main.css")">
<link rel="shortcut icon" type="image/png" href="@routes.Assets.at("images/favicon.png")">
<script src="@routes.Assets.at("javascripts/jquery/jquery-2.1.0.min.js")" type="text/javascript"></script>
<script src="@routes.Assets.at("javascripts/bootstrap.js")" type="text/javascript"></script>
<link rel="stylesheet" media="screen" href="@routes.Assets.at("stylesheets/font-awesome.min.css")">
@scripts
</head>
<body>
<div ng-controller="MenuCtrl" class="navbar navbar-inverse navbar-default" role="navigation">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="fa fa-bars fa-lg fa-inverse"></span>
</button>
<a class="navbar-brand" href="@routes.Application.index()">
<i class="fa fa-rocket"></i> Project name
</a>
<ul class="nav navbar-nav navbar-right">
<li class=""><a href="@routes.Application.index()">Home</a></li>
</ul>
</div>
@logged(user)
</div>
<div class="container">
<div class="row">
@content
</div>
</div>
<hr>
<div class="footer text-center">
<div>
<small>
Hello! I'm your friendly footer. If you're actually reading this, I'm impressed....
<a href="https://github.com/yesnault/PlayStartApp">Fork me on Github</a> <i class="fa fa-github fa-1"></i> <a href="https://github.com/yesnault/PlayStartApp">https://github.com/yesnault/PlayStartApp</a>
</small>
</div>
</div>
</body>
</html>
| haroldoramirez/PlayStartApp2 | app/views/main.scala.html | HTML | bsd-3-clause | 2,234 |
/* ========================================================================= *
* *
* OpenMesh *
* Copyright (c) 2001-2015, RWTH-Aachen University *
* Department of Computer Graphics and Multimedia *
* All rights reserved. *
* www.openmesh.org *
* *
*---------------------------------------------------------------------------*
* This file is part of OpenMesh. *
*---------------------------------------------------------------------------*
* *
* 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 copyright holder nor the names of its *
* contributors may be used to endorse or promote products derived from *
* this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS *
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED *
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A *
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER *
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, *
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, *
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR *
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF *
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING *
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS *
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
* *
* ========================================================================= */
/*===========================================================================*\
* *
* $Revision$ *
* $Date$ *
* *
\*===========================================================================*/
/** \file BaseDecimaterT.hh
*/
//=============================================================================
//
// CLASS McDecimaterT
//
//=============================================================================
#ifndef OPENMESH_BASE_DECIMATER_DECIMATERT_HH
#define OPENMESH_BASE_DECIMATER_DECIMATERT_HH
//== INCLUDES =================================================================
#include <memory>
#include <OpenMesh/Core/Utils/Property.hh>
#include <OpenMesh/Tools/Decimater/ModBaseT.hh>
#include <OpenMesh/Core/Utils/Noncopyable.hh>
#include <OpenMesh/Tools/Decimater/Observer.hh>
//== NAMESPACE ================================================================
namespace OpenMesh {
namespace Decimater {
//== CLASS DEFINITION =========================================================
/** base class decimater framework
\see BaseDecimaterT, \ref decimater_docu
*/
class BaseDecimaterModule
{
};
template < typename MeshT >
class BaseDecimaterT : private Utils::Noncopyable
{
public: //-------------------------------------------------------- public types
typedef BaseDecimaterT< MeshT > Self;
typedef MeshT Mesh;
typedef CollapseInfoT<MeshT> CollapseInfo;
typedef ModBaseT<MeshT> Module;
typedef std::vector< Module* > ModuleList;
typedef typename ModuleList::iterator ModuleListIterator;
public: //------------------------------------------------------ public methods
BaseDecimaterT(Mesh& _mesh);
virtual ~BaseDecimaterT();
/** Initialize decimater and decimating modules.
Return values:
true ok
false No ore more than one non-binary module exist. In that case
the decimater is uninitialized!
*/
bool initialize();
/// Returns whether decimater has been successfully initialized.
bool is_initialized() const { return initialized_; }
/// Print information about modules to _os
void info( std::ostream& _os );
public: //--------------------------------------------------- module management
/** \brief Add observer
*
* You can set an observer which is used as a callback to check the decimators progress and to
* abort it if necessary.
*
* @param _o Observer to be used
*/
void set_observer(Observer* _o)
{
observer_ = _o;
}
/// Get current observer of a decimater
Observer* observer()
{
return observer_;
}
/// access mesh. used in modules.
Mesh& mesh() { return mesh_; }
/// add module to decimater
template < typename _Module >
bool add( ModHandleT<_Module>& _mh )
{
if (_mh.is_valid())
return false;
_mh.init( new _Module(mesh()) );
all_modules_.push_back( _mh.module() );
set_uninitialized();
return true;
}
/// remove module
template < typename _Module >
bool remove( ModHandleT<_Module>& _mh )
{
if (!_mh.is_valid())
return false;
typename ModuleList::iterator it = std::find(all_modules_.begin(),
all_modules_.end(),
_mh.module() );
if ( it == all_modules_.end() ) // module not found
return false;
delete *it;
all_modules_.erase( it ); // finally remove from list
_mh.clear();
set_uninitialized();
return true;
}
/// get module referenced by handle _mh
template < typename Module >
Module& module( ModHandleT<Module>& _mh )
{
assert( _mh.is_valid() );
return *_mh.module();
}
protected:
/// returns false, if abort requested by observer
bool notify_observer(size_t _n_collapses)
{
if (observer() && _n_collapses % observer()->get_interval() == 0)
{
observer()->notify(_n_collapses);
return !observer()->abort();
}
return true;
}
/// Reset the initialized flag, and clear the bmodules_ and cmodule_
void set_uninitialized() {
initialized_ = false;
cmodule_ = 0;
bmodules_.clear();
}
void update_modules(CollapseInfo& _ci)
{
typename ModuleList::iterator m_it, m_end = bmodules_.end();
for (m_it = bmodules_.begin(); m_it != m_end; ++m_it)
(*m_it)->postprocess_collapse(_ci);
cmodule_->postprocess_collapse(_ci);
}
protected: //---------------------------------------------------- private methods
/// Is an edge collapse legal? Performs topological test only.
/// The method evaluates the status bit Locked, Deleted, and Feature.
/// \attention The method temporarily sets the bit Tagged. After usage
/// the bit will be disabled!
bool is_collapse_legal(const CollapseInfo& _ci);
/// Calculate priority of an halfedge collapse (using the modules)
float collapse_priority(const CollapseInfo& _ci);
/// Pre-process a collapse
void preprocess_collapse(CollapseInfo& _ci);
/// Post-process a collapse
void postprocess_collapse(CollapseInfo& _ci);
/**
* This provides a function that allows the setting of a percentage
* of the original constraint of the modules
*
* Note that some modules might re-initialize in their
* set_error_tolerance_factor function as necessary
* @param _factor has to be in the closed interval between 0.0 and 1.0
*/
void set_error_tolerance_factor(double _factor);
/** Reset the status of this class
*
* You have to call initialize again!!
*/
void reset(){ initialized_ = false; };
private: //------------------------------------------------------- private data
/// reference to mesh
Mesh& mesh_;
/// list of binary modules
ModuleList bmodules_;
/// the current priority module
Module* cmodule_;
/// list of all allocated modules (including cmodule_ and all of bmodules_)
ModuleList all_modules_;
/// Flag if all modules were initialized
bool initialized_;
/// observer
Observer* observer_;
};
//=============================================================================
} // END_NS_DECIMATER
} // END_NS_OPENMESH
//=============================================================================
#if defined(OM_INCLUDE_TEMPLATES) && !defined(OPENMESH_BASE_DECIMATER_DECIMATERT_CC)
#define OPENMESH_BASE_DECIMATER_TEMPLATES
#include "BaseDecimaterT.cc"
#endif
//=============================================================================
#endif // OPENMESH_BASE_DECIMATER_DECIMATERT_HH defined
//=============================================================================
| svn2github/OpenMesh2 | src/OpenMesh/Tools/Decimater/BaseDecimaterT.hh | C++ | bsd-3-clause | 10,044 |
namespace Org.BouncyCastle.Crypto.Tls
{
/// <summary>
/// RFC 2246 6.1
/// </summary>
public enum CompressionMethod : byte
{
NULL = 0,
/*
* RFC 3749 2
*/
DEFLATE = 1
/*
* Values from 224 decimal (0xE0) through 255 decimal (0xFF)
* inclusive are reserved for private use.
*/
}
}
| GaloisInc/hacrypto | src/C#/BouncyCastle/BouncyCastle-1.7/crypto/src/crypto/tls/CompressionMethod.cs | C# | bsd-3-clause | 332 |
#!/bin/bash
./start_all.sh
sleep 1
./show_cluster.sh
sleep 2
../output/bin/ins_cli --ins_cmd=register --flagfile=ins.flag --ins_key=zhangkai --ins_value=123456
#../output/bin/ins_cli --ins_cmd=register --flagfile=ins.flag --ins_key=fxsjy --ins_value=123456
sleep 1
nohup ../output/bin/ins_cli --ins_cmd=login --flagfile=ins.flag --ins_key=zhangkai --ins_value=123456 <op1.txt &>out1.log &
nohup ../output/bin/ins_cli --ins_cmd=login --flagfile=ins.flag --ins_key=zhangkai --ins_value=123456 <op2.txt &>out2.log &
| fxsjy/ins | sandbox/quick_test.sh | Shell | bsd-3-clause | 518 |
None
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import os
# simple json is a python 2.5 library you need to install
import json
# json comes bundled with python 2.6. use one or the other
#import json
def run():
print "starting"
from receiver.models import Submission
from xformmanager.models import FormDefModel
# this part of the script walks through all the registered
# form definitions and bundles them with the original xsd
# schema for resubmission
domain = None
# you can manually set a single domain here. if you don't then
# all the data will be exported.
domain = "Grameen"
if domain:
all_schemas = FormDefModel.objects.filter(domain__name__iexact=domain)
else:
all_schemas = FormDefModel.objects.all()
for schema in all_schemas:
print "processsing %s" % schema
file_loc = schema.xsd_file_location
print "xsd file: %s" % file_loc
if file_loc:
headers = {
"original-submit-time" : str(schema.submit_time),
"original-submit-ip" : str(schema.submit_ip),
"bytes-received" : schema.bytes_received,
"form-name" : schema.form_name,
"form-display-name" : schema.form_display_name,
"target-namespace" : schema.target_namespace,
"date-created" : str(schema.date_created),
"domain" : str(schema.get_domain)
}
dir, filename = os.path.split(file_loc)
new_dir = os.path.join(dir, "export")
if not os.path.exists(new_dir):
os.makedirs(new_dir)
write_file = os.path.join(new_dir, filename.replace(".xml", ".xsdexport"))
fout = open(write_file, 'w')
jsoned = json.dumps(headers)
print jsoned
fout.write(jsoned)
fout.write("\n\n")
xsd_file = open(file_loc, "r")
payload = xsd_file.read()
xsd_file.close()
fout.write(payload)
fout.close()
# this part of the script walks through all the submissions
# and bundles them in an exportable format with the original
# submitting IP and time, as well as a reference to the
# original post
#all_submissions = Submission.objects.all()
if domain:
all_submissions = Submission.objects.filter(domain__name__iexact=domain)
else:
all_submissions = Submission.objects.all()
for submission in all_submissions:
#print "processing %s (%s)" % (submission,submission.raw_post)
post_file = open(submission.raw_post, "r")
submit_time = str(submission.submit_time)
# first line is content type
content_type = post_file.readline().split(":")[1].strip()
# second line is content length
content_length = post_file.readline().split(":")[1].strip()
# third line is empty
post_file.readline()
# the rest is the actual body of the post
headers = { "content-type" : content_type,
"content-length" : content_length,
"time-received" : str(submission.submit_time),
"original-ip" : str(submission.submit_ip),
"domain" : submission.domain.name
}
# check the directory and create it if it doesn't exist
dir, filename = os.path.split(submission.raw_post)
new_dir = os.path.join(dir, "export")
if not os.path.exists(new_dir):
os.makedirs(new_dir)
# the format will be:
# {headers} (dict)
# (empty line)
# <body>
write_file = os.path.join(new_dir, filename.replace("postdata", "postexport"))
fout = open(write_file, 'w')
jsoned = json.dumps(headers)
fout.write(jsoned)
fout.write("\n\n")
try:
payload = post_file.read()
fout.write(payload)
except Exception:
print "error processing %s" % write_file
fout.close()
print "done"
| commtrack/temp-aquatest | utilities/data_migration/data_export_script_new.py | Python | bsd-3-clause | 4,187 |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chromecast/base/metrics/cast_metrics_test_helper.h"
#include "base/logging.h"
#include "base/macros.h"
#include "chromecast/base/metrics/cast_metrics_helper.h"
namespace chromecast {
namespace metrics {
namespace {
class CastMetricsHelperStub : public CastMetricsHelper {
public:
CastMetricsHelperStub();
~CastMetricsHelperStub() override;
void UpdateCurrentAppInfo(const std::string& app_id,
const std::string& session_id) override;
void UpdateSDKInfo(const std::string& sdk_version) override;
void LogMediaPlay() override;
void LogMediaPause() override;
void LogTimeToFirstAudio() override;
void LogTimeToBufferAv(BufferingType buffering_type,
base::TimeDelta time) override;
std::string GetMetricsNameWithAppName(
const std::string& prefix, const std::string& suffix) const override;
void SetMetricsSink(MetricsSink* delegate) override;
void RecordSimpleAction(const std::string& action) override;
private:
DISALLOW_COPY_AND_ASSIGN(CastMetricsHelperStub);
};
bool stub_instance_exists = false;
CastMetricsHelperStub::CastMetricsHelperStub()
: CastMetricsHelper() {
DCHECK(!stub_instance_exists);
stub_instance_exists = true;
}
CastMetricsHelperStub::~CastMetricsHelperStub() {
DCHECK(stub_instance_exists);
stub_instance_exists = false;
}
void CastMetricsHelperStub::UpdateCurrentAppInfo(
const std::string& app_id,
const std::string& session_id) {
}
void CastMetricsHelperStub::UpdateSDKInfo(const std::string& sdk_version) {
}
void CastMetricsHelperStub::LogMediaPlay() {
}
void CastMetricsHelperStub::LogMediaPause() {
}
void CastMetricsHelperStub::LogTimeToFirstAudio() {
}
void CastMetricsHelperStub::LogTimeToBufferAv(BufferingType buffering_type,
base::TimeDelta time) {
}
std::string CastMetricsHelperStub::GetMetricsNameWithAppName(
const std::string& prefix,
const std::string& suffix) const {
return "";
}
void CastMetricsHelperStub::SetMetricsSink(MetricsSink* delegate) {
}
} // namespace
void CastMetricsHelperStub::RecordSimpleAction(const std::string& action) {
}
void InitializeMetricsHelperForTesting() {
if (!stub_instance_exists) {
new CastMetricsHelperStub();
}
}
} // namespace metrics
} // namespace chromecast
| axinging/chromium-crosswalk | chromecast/base/metrics/cast_metrics_test_helper.cc | C++ | bsd-3-clause | 2,506 |
//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2009, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design 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 IE_CORE_INDEXEDIOTEST_H
#define IE_CORE_INDEXEDIOTEST_H
#include "IECore/Export.h"
#include "IECore/IECore.h"
#include "IECore/IndexedIO.h"
IECORE_PUSH_DEFAULT_VISIBILITY
#include "boost/test/unit_test.hpp"
IECORE_POP_DEFAULT_VISIBILITY
#include "boost/test/floating_point_comparison.hpp"
#include <cassert>
#include <iostream>
#include <string>
#include <vector>
namespace IECore
{
void addIndexedIOTest(boost::unit_test::test_suite* test);
typedef std::vector<std::string> FilenameList;
template<typename T>
struct IndexedIOTestDataTraits
{
static std::string name()
{
assert(false);
return "";
}
static T value()
{
assert(false);
return T();
}
static void check(const T& v1)
{
BOOST_CHECK_EQUAL(v1, value());
}
};
template<typename T>
struct IndexedIOTestDataTraits<T*>
{
static std::string name()
{
assert(false);
return "";
}
static T* value()
{
assert(false);
return 0;
}
static void check(T *v1)
{
for (int i = 0; i < 10; i++)
{
BOOST_CHECK_EQUAL(v1[i], value()[i]);
}
}
};
template<typename T>
struct IndexedIOTest
{
IndexedIOTest(const FilenameList &filenames) : m_filenames(filenames) {};
template<typename D>
void test()
{
for (FilenameList::const_iterator it = m_filenames.begin(); it != m_filenames.end(); ++it)
{
IndexedIOPtr io = new T(*it, IndexedIO::rootPath, IndexedIO::Read );
bool exists = true;
try
{
io->entry( IndexedIOTestDataTraits<D>::name() );
}
catch (...)
{
exists = false;
}
if ( exists )
{
D v;
io->read(IndexedIOTestDataTraits<D>::name(), v );
IndexedIOTestDataTraits<D>::check(v);
}
}
}
template<typename D>
void testArray()
{
for (FilenameList::const_iterator it = m_filenames.begin(); it != m_filenames.end(); ++it)
{
IndexedIOPtr io = new T(*it, IndexedIO::rootPath, IndexedIO::Read );
bool exists = true;
try
{
io->entry( IndexedIOTestDataTraits<D>::name() );
}
catch (...)
{
exists = false;
}
if ( exists )
{
D *v = new D[10] ;
io->read(IndexedIOTestDataTraits<D*>::name(), v, 10 );
IndexedIOTestDataTraits<D*>::check(v);
delete[] v;
}
}
}
template<typename D>
void write( IndexedIOPtr io)
{
assert(io);
io->write( IndexedIOTestDataTraits<D>::name(), IndexedIOTestDataTraits<D>::value() );
io->entry( IndexedIOTestDataTraits<D>::name() );
}
template<typename D>
void writeArray( IndexedIOPtr io)
{
assert(io);
io->write( IndexedIOTestDataTraits<D*>::name(), IndexedIOTestDataTraits<D*>::value(), 10 );
io->entry( IndexedIOTestDataTraits<D*>::name() );
}
void write(const std::string &filename)
{
IndexedIOPtr io = new T(filename, IndexedIO::rootPath, IndexedIO::Write );
write<float>(io);
write<double>(io);
write<half>(io);
write<int>(io);
write<int64_t>(io);
write<uint64_t>(io);
write<std::string>(io);
write<unsigned int>(io);
write<char>(io);
write<unsigned char>(io);
write<short>(io);
write<unsigned short>(io);
writeArray<float>(io);
writeArray<double>(io);
writeArray<half>(io);
writeArray<int>(io);
writeArray<int64_t>(io);
writeArray<uint64_t>(io);
writeArray<std::string>(io);
writeArray<unsigned int>(io);
writeArray<char>(io);
writeArray<unsigned char>(io);
writeArray<short>(io);
writeArray<unsigned short>(io);
}
FilenameList m_filenames;
};
template<typename T>
struct IndexedIOTestSuite : public boost::unit_test::test_suite
{
IndexedIOTestSuite() : boost::unit_test::test_suite("IndexedIOTestSuite")
{
FilenameList filenames;
getFilenames(filenames);
static boost::shared_ptr<IndexedIOTest<T> > instance(new IndexedIOTest<T>(filenames));
/// Uncomment this line to write out new test data - change architecture first
//instance->write("./test/IECore/data/" + extension() + "Files/" + IECore::versionString() + "/cent5.x86_64/types." + extension());
add( BOOST_CLASS_TEST_CASE( &IndexedIOTest<T>::template test<float>, instance ) );
add( BOOST_CLASS_TEST_CASE( &IndexedIOTest<T>::template test<double>, instance ) );
add( BOOST_CLASS_TEST_CASE( &IndexedIOTest<T>::template test<half>, instance ) );
add( BOOST_CLASS_TEST_CASE( &IndexedIOTest<T>::template test<int>, instance ) );
add( BOOST_CLASS_TEST_CASE( &IndexedIOTest<T>::template test<int64_t>, instance ) );
add( BOOST_CLASS_TEST_CASE( &IndexedIOTest<T>::template test<uint64_t>, instance ) );
add( BOOST_CLASS_TEST_CASE( &IndexedIOTest<T>::template test<std::string>, instance ) );
add( BOOST_CLASS_TEST_CASE( &IndexedIOTest<T>::template test<unsigned int>, instance ) );
add( BOOST_CLASS_TEST_CASE( &IndexedIOTest<T>::template test<char>, instance ) );
add( BOOST_CLASS_TEST_CASE( &IndexedIOTest<T>::template test<unsigned char>, instance ) );
add( BOOST_CLASS_TEST_CASE( &IndexedIOTest<T>::template testArray<float>, instance ) );
add( BOOST_CLASS_TEST_CASE( &IndexedIOTest<T>::template testArray<double>, instance ) );
add( BOOST_CLASS_TEST_CASE( &IndexedIOTest<T>::template testArray<half>, instance ) );
add( BOOST_CLASS_TEST_CASE( &IndexedIOTest<T>::template testArray<int>, instance ) );
add( BOOST_CLASS_TEST_CASE( &IndexedIOTest<T>::template testArray<int64_t>, instance ) );
add( BOOST_CLASS_TEST_CASE( &IndexedIOTest<T>::template testArray<uint64_t>, instance ) );
add( BOOST_CLASS_TEST_CASE( &IndexedIOTest<T>::template testArray<std::string>, instance ) );
add( BOOST_CLASS_TEST_CASE( &IndexedIOTest<T>::template testArray<unsigned int>, instance ) );
add( BOOST_CLASS_TEST_CASE( &IndexedIOTest<T>::template testArray<char>, instance ) );
add( BOOST_CLASS_TEST_CASE( &IndexedIOTest<T>::template testArray<unsigned char>, instance ) );
}
std::string extension() const;
void getFilenames( FilenameList &filenames );
};
}
#endif
| appleseedhq/cortex | test/IECore/IndexedIOTest.h | C | bsd-3-clause | 7,631 |
;; GCC machine description for CRX.
;; Copyright (C) 1988, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
;; 2001, 2002, 2003, 2004, 2007
;; Free Software Foundation, Inc.
;;
;; This file is part of GCC.
;;
;; GCC is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3, or (at your option)
;; any later version.
;;
;; GCC is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with GCC; see the file COPYING3. If not see
;; <http://www.gnu.org/licenses/>. */
;; Register numbers
(define_constants
[(SP_REGNUM 15) ; Stack pointer
(RA_REGNUM 14) ; Return address
(LO_REGNUM 16) ; LO register
(HI_REGNUM 17) ; HI register
(CC_REGNUM 18) ; Condition code register
]
)
(define_attr "length" "" ( const_int 6 ))
(define_asm_attributes
[(set_attr "length" "6")]
)
;; Predicates
(define_predicate "u4bits_operand"
(match_code "const_int,const_double")
{
if (GET_CODE (op) == CONST_DOUBLE)
return crx_const_double_ok (op);
return (UNSIGNED_INT_FITS_N_BITS(INTVAL(op), 4)) ? 1 : 0;
}
)
(define_predicate "cst4_operand"
(and (match_code "const_int")
(match_test "INT_CST4(INTVAL(op))")))
(define_predicate "reg_or_u4bits_operand"
(ior (match_operand 0 "u4bits_operand")
(match_operand 0 "register_operand")))
(define_predicate "reg_or_cst4_operand"
(ior (match_operand 0 "cst4_operand")
(match_operand 0 "register_operand")))
(define_predicate "reg_or_sym_operand"
(ior (match_code "symbol_ref")
(match_operand 0 "register_operand")))
(define_predicate "nosp_reg_operand"
(and (match_operand 0 "register_operand")
(match_test "REGNO (op) != SP_REGNUM")))
(define_predicate "store_operand"
(and (match_operand 0 "memory_operand")
(not (match_operand 0 "push_operand"))))
;; Mode Macro Definitions
(define_mode_macro ALLMT [QI HI SI SF DI DF])
(define_mode_macro CRXMM [QI HI SI SF])
(define_mode_macro CRXIM [QI HI SI])
(define_mode_macro DIDFM [DI DF])
(define_mode_macro SISFM [SI SF])
(define_mode_macro SHORT [QI HI])
(define_mode_attr tIsa [(QI "b") (HI "w") (SI "d") (SF "d")])
(define_mode_attr lImmArith [(QI "4") (HI "4") (SI "6")])
(define_mode_attr lImmRotl [(QI "2") (HI "2") (SI "4")])
(define_mode_attr IJK [(QI "I") (HI "J") (SI "K")])
(define_mode_attr iF [(QI "i") (HI "i") (SI "i") (DI "i") (SF "F") (DF "F")])
(define_mode_attr JG [(QI "J") (HI "J") (SI "J") (DI "J") (SF "G") (DF "G")])
; In HI or QI mode we push 4 bytes.
(define_mode_attr pushCnstr [(QI "X") (HI "X") (SI "<") (SF "<") (DI "<") (DF "<")])
(define_mode_attr tpush [(QI "") (HI "") (SI "") (SF "") (DI "sp, ") (DF "sp, ")])
(define_mode_attr lpush [(QI "2") (HI "2") (SI "2") (SF "2") (DI "4") (DF "4")])
;; Code Macro Definitions
(define_code_macro sz_xtnd [sign_extend zero_extend])
(define_code_attr sIsa [(sign_extend "") (zero_extend "u")])
(define_code_attr sPat [(sign_extend "s") (zero_extend "u")])
(define_code_attr szPat [(sign_extend "") (zero_extend "zero_")])
(define_code_attr szIsa [(sign_extend "s") (zero_extend "z")])
(define_code_macro sh_oprnd [ashift ashiftrt lshiftrt])
(define_code_attr shIsa [(ashift "ll") (ashiftrt "ra") (lshiftrt "rl")])
(define_code_attr shPat [(ashift "ashl") (ashiftrt "ashr") (lshiftrt "lshr")])
(define_code_macro mima_oprnd [smax umax smin umin])
(define_code_attr mimaIsa [(smax "maxs") (umax "maxu") (smin "mins") (umin "minu")])
(define_code_macro any_cond [eq ne gt gtu lt ltu ge geu le leu])
;; Addition Instructions
(define_insn "adddi3"
[(set (match_operand:DI 0 "register_operand" "=r,r")
(plus:DI (match_operand:DI 1 "register_operand" "%0,0")
(match_operand:DI 2 "nonmemory_operand" "r,i")))
(clobber (reg:CC CC_REGNUM))]
""
"addd\t%L2, %L1\;addcd\t%H2, %H1"
[(set_attr "length" "4,12")]
)
(define_insn "add<mode>3"
[(set (match_operand:CRXIM 0 "register_operand" "=r,r")
(plus:CRXIM (match_operand:CRXIM 1 "register_operand" "%0,0")
(match_operand:CRXIM 2 "nonmemory_operand" "r,i")))
(clobber (reg:CC CC_REGNUM))]
""
"add<tIsa>\t%2, %0"
[(set_attr "length" "2,<lImmArith>")]
)
;; Subtract Instructions
(define_insn "subdi3"
[(set (match_operand:DI 0 "register_operand" "=r,r")
(minus:DI (match_operand:DI 1 "register_operand" "0,0")
(match_operand:DI 2 "nonmemory_operand" "r,i")))
(clobber (reg:CC CC_REGNUM))]
""
"subd\t%L2, %L1\;subcd\t%H2, %H1"
[(set_attr "length" "4,12")]
)
(define_insn "sub<mode>3"
[(set (match_operand:CRXIM 0 "register_operand" "=r,r")
(minus:CRXIM (match_operand:CRXIM 1 "register_operand" "0,0")
(match_operand:CRXIM 2 "nonmemory_operand" "r,i")))
(clobber (reg:CC CC_REGNUM))]
""
"sub<tIsa>\t%2, %0"
[(set_attr "length" "2,<lImmArith>")]
)
;; Multiply Instructions
(define_insn "mul<mode>3"
[(set (match_operand:CRXIM 0 "register_operand" "=r,r")
(mult:CRXIM (match_operand:CRXIM 1 "register_operand" "%0,0")
(match_operand:CRXIM 2 "nonmemory_operand" "r,i")))
(clobber (reg:CC CC_REGNUM))]
""
"mul<tIsa>\t%2, %0"
[(set_attr "length" "2,<lImmArith>")]
)
;; Widening-multiplication Instructions
(define_insn "<sIsa>mulsidi3"
[(set (match_operand:DI 0 "register_operand" "=k")
(mult:DI (sz_xtnd:DI (match_operand:SI 1 "register_operand" "%r"))
(sz_xtnd:DI (match_operand:SI 2 "register_operand" "r"))))
(clobber (reg:CC CC_REGNUM))]
""
"mull<sPat>d\t%2, %1"
[(set_attr "length" "4")]
)
(define_insn "<sIsa>mulhisi3"
[(set (match_operand:SI 0 "register_operand" "=r")
(mult:SI (sz_xtnd:SI (match_operand:HI 1 "register_operand" "%0"))
(sz_xtnd:SI (match_operand:HI 2 "register_operand" "r"))))
(clobber (reg:CC CC_REGNUM))]
""
"mul<sPat>wd\t%2, %0"
[(set_attr "length" "4")]
)
(define_insn "<sIsa>mulqihi3"
[(set (match_operand:HI 0 "register_operand" "=r")
(mult:HI (sz_xtnd:HI (match_operand:QI 1 "register_operand" "%0"))
(sz_xtnd:HI (match_operand:QI 2 "register_operand" "r"))))
(clobber (reg:CC CC_REGNUM))]
""
"mul<sPat>bw\t%2, %0"
[(set_attr "length" "4")]
)
;; Logical Instructions - and
(define_insn "and<mode>3"
[(set (match_operand:CRXIM 0 "register_operand" "=r,r")
(and:CRXIM (match_operand:CRXIM 1 "register_operand" "%0,0")
(match_operand:CRXIM 2 "nonmemory_operand" "r,i")))
(clobber (reg:CC CC_REGNUM))]
""
"and<tIsa>\t%2, %0"
[(set_attr "length" "2,<lImmArith>")]
)
;; Logical Instructions - or
(define_insn "ior<mode>3"
[(set (match_operand:CRXIM 0 "register_operand" "=r,r")
(ior:CRXIM (match_operand:CRXIM 1 "register_operand" "%0,0")
(match_operand:CRXIM 2 "nonmemory_operand" "r,i")))
(clobber (reg:CC CC_REGNUM))]
""
"or<tIsa>\t%2, %0"
[(set_attr "length" "2,<lImmArith>")]
)
;; Logical Instructions - xor
(define_insn "xor<mode>3"
[(set (match_operand:CRXIM 0 "register_operand" "=r,r")
(xor:CRXIM (match_operand:CRXIM 1 "register_operand" "%0,0")
(match_operand:CRXIM 2 "nonmemory_operand" "r,i")))
(clobber (reg:CC CC_REGNUM))]
""
"xor<tIsa>\t%2, %0"
[(set_attr "length" "2,<lImmArith>")]
)
;; Sign and Zero Extend Instructions
(define_insn "<szPat>extendhisi2"
[(set (match_operand:SI 0 "register_operand" "=r")
(sz_xtnd:SI (match_operand:HI 1 "register_operand" "r")))
(clobber (reg:CC CC_REGNUM))]
""
"<szIsa>extwd\t%1, %0"
[(set_attr "length" "4")]
)
(define_insn "<szPat>extendqisi2"
[(set (match_operand:SI 0 "register_operand" "=r")
(sz_xtnd:SI (match_operand:QI 1 "register_operand" "r")))
(clobber (reg:CC CC_REGNUM))]
""
"<szIsa>extbd\t%1, %0"
[(set_attr "length" "4")]
)
(define_insn "<szPat>extendqihi2"
[(set (match_operand:HI 0 "register_operand" "=r")
(sz_xtnd:HI (match_operand:QI 1 "register_operand" "r")))
(clobber (reg:CC CC_REGNUM))]
""
"<szIsa>extbw\t%1, %0"
[(set_attr "length" "4")]
)
;; Negation Instructions
(define_insn "neg<mode>2"
[(set (match_operand:CRXIM 0 "register_operand" "=r")
(neg:CRXIM (match_operand:CRXIM 1 "register_operand" "r")))
(clobber (reg:CC CC_REGNUM))]
""
"neg<tIsa>\t%1, %0"
[(set_attr "length" "4")]
)
;; Absolute Instructions
(define_insn "abs<mode>2"
[(set (match_operand:CRXIM 0 "register_operand" "=r")
(abs:CRXIM (match_operand:CRXIM 1 "register_operand" "r")))
(clobber (reg:CC CC_REGNUM))]
""
"abs<tIsa>\t%1, %0"
[(set_attr "length" "4")]
)
;; Max and Min Instructions
(define_insn "<code><mode>3"
[(set (match_operand:CRXIM 0 "register_operand" "=r")
(mima_oprnd:CRXIM (match_operand:CRXIM 1 "register_operand" "%0")
(match_operand:CRXIM 2 "register_operand" "r")))]
""
"<mimaIsa><tIsa>\t%2, %0"
[(set_attr "length" "4")]
)
;; One's Complement
(define_insn "one_cmpl<mode>2"
[(set (match_operand:CRXIM 0 "register_operand" "=r")
(not:CRXIM (match_operand:CRXIM 1 "register_operand" "0")))
(clobber (reg:CC CC_REGNUM))]
""
"xor<tIsa>\t$-1, %0"
[(set_attr "length" "2")]
)
;; Rotate Instructions
(define_insn "rotl<mode>3"
[(set (match_operand:CRXIM 0 "register_operand" "=r,r")
(rotate:CRXIM (match_operand:CRXIM 1 "register_operand" "0,0")
(match_operand:CRXIM 2 "nonmemory_operand" "r,<IJK>")))
(clobber (reg:CC CC_REGNUM))]
""
"@
rotl<tIsa>\t%2, %0
rot<tIsa>\t%2, %0"
[(set_attr "length" "4,<lImmRotl>")]
)
(define_insn "rotr<mode>3"
[(set (match_operand:CRXIM 0 "register_operand" "=r")
(rotatert:CRXIM (match_operand:CRXIM 1 "register_operand" "0")
(match_operand:CRXIM 2 "register_operand" "r")))
(clobber (reg:CC CC_REGNUM))]
""
"rotr<tIsa>\t%2, %0"
[(set_attr "length" "4")]
)
;; Arithmetic Left and Right Shift Instructions
(define_insn "<shPat><mode>3"
[(set (match_operand:CRXIM 0 "register_operand" "=r,r")
(sh_oprnd:CRXIM (match_operand:CRXIM 1 "register_operand" "0,0")
(match_operand:QI 2 "nonmemory_operand" "r,<IJK>")))
(clobber (reg:CC CC_REGNUM))]
""
"s<shIsa><tIsa>\t%2, %0"
[(set_attr "length" "2,2")]
)
;; Bit Set Instructions
(define_insn "extv"
[(set (match_operand:SI 0 "register_operand" "=r")
(sign_extract:SI (match_operand:SI 1 "register_operand" "r")
(match_operand:SI 2 "const_int_operand" "n")
(match_operand:SI 3 "const_int_operand" "n")))]
""
{
static char buf[100];
int strpntr;
int size = INTVAL (operands[2]);
int pos = INTVAL (operands[3]);
strpntr = sprintf (buf, "ram\t$%d, $31, $%d, %%1, %%0\;",
BITS_PER_WORD - (size + pos), BITS_PER_WORD - size);
sprintf (buf + strpntr, "srad\t$%d, %%0", BITS_PER_WORD - size);
return buf;
}
[(set_attr "length" "6")]
)
(define_insn "extzv"
[(set (match_operand:SI 0 "register_operand" "=r")
(zero_extract:SI (match_operand:SI 1 "register_operand" "r")
(match_operand:SI 2 "const_int_operand" "n")
(match_operand:SI 3 "const_int_operand" "n")))]
""
{
static char buf[40];
int size = INTVAL (operands[2]);
int pos = INTVAL (operands[3]);
sprintf (buf, "ram\t$%d, $%d, $0, %%1, %%0",
(BITS_PER_WORD - pos) % BITS_PER_WORD, size - 1);
return buf;
}
[(set_attr "length" "4")]
)
(define_insn "insv"
[(set (zero_extract:SI (match_operand:SI 0 "register_operand" "+r")
(match_operand:SI 1 "const_int_operand" "n")
(match_operand:SI 2 "const_int_operand" "n"))
(match_operand:SI 3 "register_operand" "r"))]
""
{
static char buf[40];
int size = INTVAL (operands[1]);
int pos = INTVAL (operands[2]);
sprintf (buf, "rim\t$%d, $%d, $%d, %%3, %%0",
pos, size + pos - 1, pos);
return buf;
}
[(set_attr "length" "4")]
)
;; Move Instructions
(define_expand "mov<mode>"
[(set (match_operand:ALLMT 0 "nonimmediate_operand" "")
(match_operand:ALLMT 1 "general_operand" ""))]
""
{
if (!(reload_in_progress || reload_completed))
{
if (!register_operand (operands[0], <MODE>mode))
{
if (push_operand (operands[0], <MODE>mode) ?
!nosp_reg_operand (operands[1], <MODE>mode) :
!reg_or_u4bits_operand (operands[1], <MODE>mode))
{
operands[1] = copy_to_mode_reg (<MODE>mode, operands[1]);
}
}
}
}
)
(define_insn "push<mode>_internal"
[(set (match_operand:ALLMT 0 "push_operand" "=<pushCnstr>")
(match_operand:ALLMT 1 "nosp_reg_operand" "b"))]
""
"push\t<tpush>%p1"
[(set_attr "length" "<lpush>")]
)
(define_insn "mov<mode>_regs"
[(set (match_operand:SISFM 0 "register_operand" "=r, r, r, k")
(match_operand:SISFM 1 "nonmemory_operand" "r, <iF>, k, r"))]
""
"@
movd\t%1, %0
movd\t%1, %0
mfpr\t%1, %0
mtpr\t%1, %0"
[(set_attr "length" "2,6,4,4")]
)
(define_insn "mov<mode>_regs"
[(set (match_operand:DIDFM 0 "register_operand" "=r, r, r, k")
(match_operand:DIDFM 1 "nonmemory_operand" "r, <iF>, k, r"))]
""
{
switch (which_alternative)
{
case 0: if (REGNO (operands[0]) > REGNO (operands[1]))
return "movd\t%H1, %H0\;movd\t%L1, %L0";
else
return "movd\t%L1, %L0\;movd\t%H1, %H0";
case 1: return "movd\t%H1, %H0\;movd\t%L1, %L0";
case 2: return "mfpr\t%H1, %H0\;mfpr\t%L1, %L0";
case 3: return "mtpr\t%H1, %H0\;mtpr\t%L1, %L0";
default: gcc_unreachable ();
}
}
[(set_attr "length" "4,12,8,8")]
)
(define_insn "mov<mode>_regs" ; no HI/QI mode in HILO regs
[(set (match_operand:SHORT 0 "register_operand" "=r, r")
(match_operand:SHORT 1 "nonmemory_operand" "r, i"))]
""
"mov<tIsa>\t%1, %0"
[(set_attr "length" "2,<lImmArith>")]
)
(define_insn "mov<mode>_load"
[(set (match_operand:CRXMM 0 "register_operand" "=r")
(match_operand:CRXMM 1 "memory_operand" "m"))]
""
"load<tIsa>\t%1, %0"
[(set_attr "length" "6")]
)
(define_insn "mov<mode>_load"
[(set (match_operand:DIDFM 0 "register_operand" "=r")
(match_operand:DIDFM 1 "memory_operand" "m"))]
""
{
rtx first_dest_reg = gen_rtx_REG (SImode, REGNO (operands[0]));
if (reg_overlap_mentioned_p (first_dest_reg, operands[1]))
return "loadd\t%H1, %H0\;loadd\t%L1, %L0";
return "loadd\t%L1, %L0\;loadd\t%H1, %H0";
}
[(set_attr "length" "12")]
)
(define_insn "mov<mode>_store"
[(set (match_operand:CRXMM 0 "store_operand" "=m, m")
(match_operand:CRXMM 1 "reg_or_u4bits_operand" "r, <JG>"))]
""
"stor<tIsa>\t%1, %0"
[(set_attr "length" "6")]
)
(define_insn "mov<mode>_store"
[(set (match_operand:DIDFM 0 "store_operand" "=m, m")
(match_operand:DIDFM 1 "reg_or_u4bits_operand" "r, <JG>"))]
""
"stord\t%H1, %H0\;stord\t%L1, %L0"
[(set_attr "length" "12")]
)
;; Movmem Instruction
(define_expand "movmemsi"
[(use (match_operand:BLK 0 "memory_operand" ""))
(use (match_operand:BLK 1 "memory_operand" ""))
(use (match_operand:SI 2 "nonmemory_operand" ""))
(use (match_operand:SI 3 "const_int_operand" ""))]
""
{
if (crx_expand_movmem (operands[0], operands[1], operands[2], operands[3]))
DONE;
else
FAIL;
}
)
;; Compare and Branch Instructions
(define_insn "cbranch<mode>4"
[(set (pc)
(if_then_else (match_operator 0 "comparison_operator"
[(match_operand:CRXIM 1 "register_operand" "r")
(match_operand:CRXIM 2 "reg_or_cst4_operand" "rL")])
(label_ref (match_operand 3 "" ""))
(pc)))
(clobber (reg:CC CC_REGNUM))]
""
"cmpb%d0<tIsa>\t%2, %1, %l3"
[(set_attr "length" "6")]
)
;; Compare Instructions
(define_expand "cmp<mode>"
[(set (reg:CC CC_REGNUM)
(compare:CC (match_operand:CRXIM 0 "register_operand" "")
(match_operand:CRXIM 1 "nonmemory_operand" "")))]
""
{
crx_compare_op0 = operands[0];
crx_compare_op1 = operands[1];
DONE;
}
)
(define_insn "cmp<mode>_internal"
[(set (reg:CC CC_REGNUM)
(compare:CC (match_operand:CRXIM 0 "register_operand" "r,r")
(match_operand:CRXIM 1 "nonmemory_operand" "r,i")))]
""
"cmp<tIsa>\t%1, %0"
[(set_attr "length" "2,<lImmArith>")]
)
;; Conditional Branch Instructions
(define_expand "b<code>"
[(set (pc)
(if_then_else (any_cond (reg:CC CC_REGNUM)
(const_int 0))
(label_ref (match_operand 0 ""))
(pc)))]
""
{
crx_expand_branch (<CODE>, operands[0]);
DONE;
}
)
(define_insn "bCOND_internal"
[(set (pc)
(if_then_else (match_operator 0 "comparison_operator"
[(reg:CC CC_REGNUM)
(const_int 0)])
(label_ref (match_operand 1 ""))
(pc)))]
""
"b%d0\t%l1"
[(set_attr "length" "6")]
)
;; Scond Instructions
(define_expand "s<code>"
[(set (match_operand:SI 0 "register_operand")
(any_cond:SI (reg:CC CC_REGNUM) (const_int 0)))]
""
{
crx_expand_scond (<CODE>, operands[0]);
DONE;
}
)
(define_insn "sCOND_internal"
[(set (match_operand:SI 0 "register_operand" "=r")
(match_operator:SI 1 "comparison_operator"
[(reg:CC CC_REGNUM) (const_int 0)]))]
""
"s%d1\t%0"
[(set_attr "length" "2")]
)
;; Jumps and Branches
(define_insn "indirect_jump_return"
[(parallel
[(set (pc)
(reg:SI RA_REGNUM))
(return)])
]
"reload_completed"
"jump\tra"
[(set_attr "length" "2")]
)
(define_insn "indirect_jump"
[(set (pc)
(match_operand:SI 0 "reg_or_sym_operand" "r,i"))]
""
"@
jump\t%0
br\t%a0"
[(set_attr "length" "2,6")]
)
(define_insn "interrupt_return"
[(parallel
[(unspec_volatile [(const_int 0)] 0)
(return)])]
""
{
return crx_prepare_push_pop_string (1);
}
[(set_attr "length" "14")]
)
(define_insn "jump_to_imm"
[(set (pc)
(match_operand 0 "immediate_operand" "i"))]
""
"br\t%c0"
[(set_attr "length" "6")]
)
(define_insn "jump"
[(set (pc)
(label_ref (match_operand 0 "" "")))]
""
"br\t%l0"
[(set_attr "length" "6")]
)
;; Function Prologue and Epilogue
(define_expand "prologue"
[(const_int 0)]
""
{
crx_expand_prologue ();
DONE;
}
)
(define_insn "push_for_prologue"
[(parallel
[(set (reg:SI SP_REGNUM)
(minus:SI (reg:SI SP_REGNUM)
(match_operand:SI 0 "immediate_operand" "i")))])]
"reload_completed"
{
return crx_prepare_push_pop_string (0);
}
[(set_attr "length" "4")]
)
(define_expand "epilogue"
[(return)]
""
{
crx_expand_epilogue ();
DONE;
}
)
(define_insn "pop_and_popret_return"
[(parallel
[(set (reg:SI SP_REGNUM)
(plus:SI (reg:SI SP_REGNUM)
(match_operand:SI 0 "immediate_operand" "i")))
(use (reg:SI RA_REGNUM))
(return)])
]
"reload_completed"
{
return crx_prepare_push_pop_string (1);
}
[(set_attr "length" "4")]
)
(define_insn "popret_RA_return"
[(parallel
[(use (reg:SI RA_REGNUM))
(return)])
]
"reload_completed"
"popret\tra"
[(set_attr "length" "2")]
)
;; Table Jump
(define_insn "tablejump"
[(set (pc)
(match_operand:SI 0 "register_operand" "r"))
(use (label_ref:SI (match_operand 1 "" "" )))]
""
"jump\t%0"
[(set_attr "length" "2")]
)
;; Call Instructions
(define_expand "call"
[(call (match_operand:QI 0 "memory_operand" "")
(match_operand 1 "" ""))]
""
{
emit_call_insn (gen_crx_call (operands[0], operands[1]));
DONE;
}
)
(define_expand "crx_call"
[(parallel
[(call (match_operand:QI 0 "memory_operand" "")
(match_operand 1 "" ""))
(clobber (reg:SI RA_REGNUM))])]
""
""
)
(define_insn "crx_call_insn_branch"
[(call (mem:QI (match_operand:SI 0 "immediate_operand" "i"))
(match_operand 1 "" ""))
(clobber (match_operand:SI 2 "register_operand" "+r"))]
""
"bal\tra, %a0"
[(set_attr "length" "6")]
)
(define_insn "crx_call_insn_jump"
[(call (mem:QI (match_operand:SI 0 "register_operand" "r"))
(match_operand 1 "" ""))
(clobber (match_operand:SI 2 "register_operand" "+r"))]
""
"jal\t%0"
[(set_attr "length" "2")]
)
(define_insn "crx_call_insn_jalid"
[(call (mem:QI (mem:SI (plus:SI
(match_operand:SI 0 "register_operand" "r")
(match_operand:SI 1 "register_operand" "r"))))
(match_operand 2 "" ""))
(clobber (match_operand:SI 3 "register_operand" "+r"))]
""
"jalid\t%0, %1"
[(set_attr "length" "4")]
)
;; Call Value Instructions
(define_expand "call_value"
[(set (match_operand 0 "general_operand" "")
(call (match_operand:QI 1 "memory_operand" "")
(match_operand 2 "" "")))]
""
{
emit_call_insn (gen_crx_call_value (operands[0], operands[1], operands[2]));
DONE;
}
)
(define_expand "crx_call_value"
[(parallel
[(set (match_operand 0 "general_operand" "")
(call (match_operand 1 "memory_operand" "")
(match_operand 2 "" "")))
(clobber (reg:SI RA_REGNUM))])]
""
""
)
(define_insn "crx_call_value_insn_branch"
[(set (match_operand 0 "" "=g")
(call (mem:QI (match_operand:SI 1 "immediate_operand" "i"))
(match_operand 2 "" "")))
(clobber (match_operand:SI 3 "register_operand" "+r"))]
""
"bal\tra, %a1"
[(set_attr "length" "6")]
)
(define_insn "crx_call_value_insn_jump"
[(set (match_operand 0 "" "=g")
(call (mem:QI (match_operand:SI 1 "register_operand" "r"))
(match_operand 2 "" "")))
(clobber (match_operand:SI 3 "register_operand" "+r"))]
""
"jal\t%1"
[(set_attr "length" "2")]
)
(define_insn "crx_call_value_insn_jalid"
[(set (match_operand 0 "" "=g")
(call (mem:QI (mem:SI (plus:SI
(match_operand:SI 1 "register_operand" "r")
(match_operand:SI 2 "register_operand" "r"))))
(match_operand 3 "" "")))
(clobber (match_operand:SI 4 "register_operand" "+r"))]
""
"jalid\t%0, %1"
[(set_attr "length" "4")]
)
;; Nop
(define_insn "nop"
[(const_int 0)]
""
""
)
;; Multiply and Accumulate Instructions
(define_insn "<sPat>madsidi3"
[(set (match_operand:DI 0 "register_operand" "+k")
(plus:DI
(mult:DI (sz_xtnd:DI (match_operand:SI 1 "register_operand" "%r"))
(sz_xtnd:DI (match_operand:SI 2 "register_operand" "r")))
(match_dup 0)))
(clobber (reg:CC CC_REGNUM))]
"TARGET_MAC"
"mac<sPat>d\t%2, %1"
[(set_attr "length" "4")]
)
(define_insn "<sPat>madhisi3"
[(set (match_operand:SI 0 "register_operand" "+l")
(plus:SI
(mult:SI (sz_xtnd:SI (match_operand:HI 1 "register_operand" "%r"))
(sz_xtnd:SI (match_operand:HI 2 "register_operand" "r")))
(match_dup 0)))
(clobber (reg:CC CC_REGNUM))]
"TARGET_MAC"
"mac<sPat>w\t%2, %1"
[(set_attr "length" "4")]
)
(define_insn "<sPat>madqihi3"
[(set (match_operand:HI 0 "register_operand" "+l")
(plus:HI
(mult:HI (sz_xtnd:HI (match_operand:QI 1 "register_operand" "%r"))
(sz_xtnd:HI (match_operand:QI 2 "register_operand" "r")))
(match_dup 0)))
(clobber (reg:CC CC_REGNUM))]
"TARGET_MAC"
"mac<sPat>b\t%2, %1"
[(set_attr "length" "4")]
)
;; Loop Instructions
(define_expand "doloop_end"
[(use (match_operand 0 "" "")) ; loop pseudo
(use (match_operand 1 "" "")) ; iterations; zero if unknown
(use (match_operand 2 "" "")) ; max iterations
(use (match_operand 3 "" "")) ; loop level
(use (match_operand 4 "" ""))] ; label
""
{
if (INTVAL (operands[3]) > crx_loop_nesting)
FAIL;
switch (GET_MODE (operands[0]))
{
case SImode:
emit_jump_insn (gen_doloop_end_si (operands[4], operands[0]));
break;
case HImode:
emit_jump_insn (gen_doloop_end_hi (operands[4], operands[0]));
break;
case QImode:
emit_jump_insn (gen_doloop_end_qi (operands[4], operands[0]));
break;
default:
FAIL;
}
DONE;
}
)
; CRX dbnz[bwd] used explicitly (see above) but also by the combiner.
(define_insn "doloop_end_<mode>"
[(set (pc)
(if_then_else (ne (match_operand:CRXIM 1 "register_operand" "+r,!m")
(const_int 1))
(label_ref (match_operand 0 "" ""))
(pc)))
(set (match_dup 1) (plus:CRXIM (match_dup 1) (const_int -1)))
(clobber (match_scratch:CRXIM 2 "=X,r"))
(clobber (reg:CC CC_REGNUM))]
""
"@
dbnz<tIsa>\t%1, %l0
load<tIsa>\t%1, %2\;add<tIsa>\t$-1, %2\;stor<tIsa>\t%2, %1\;bne\t%l0"
[(set_attr "length" "6, 12")]
)
| shaotuanchen/sunflower_exp | tools/source/gcc-4.2.4/gcc/config/crx/crx.md | Markdown | bsd-3-clause | 24,012 |
@echo off
for /D %%f in (*) do for %%i in (%%f\*.vcxproj) do call :SUB_RENAME "%%i"
goto END
:SUB_RENAME
set filename=%~n1
if "%filename:~-4%" == "2012" goto END
if "%filename:~-4%" == "2010" goto END
if "%filename:~-4%" == "2008" goto END
if "%filename:~-4%" == "2005" goto END
if "%filename:~-4%" == "2003" goto END
echo %1 will be renamed
rename %~p1%filename%.vcxproj %filename%.2012.vcxproj
rename %~p1%filename%.vcxproj.filters %filename%.2012.vcxproj.filters
rename %~p1%filename%.vcxproj.user %filename%.2012.vcxproj.user
goto END
:END
| akrzemi1/Mach7 | media/papers/OpenPatternMatching/artifact/code/msvc/rename-vcxproj.bat | Batchfile | bsd-3-clause | 575 |
#include <xpcc/architecture/platform.hpp>
#include <xpcc/debug/logger.hpp>
// ----------------------------------------------------------------------------
// Set the log level
#undef XPCC_LOG_LEVEL
#define XPCC_LOG_LEVEL xpcc::log::INFO
typedef GpioInputC0 Adc1In;
typedef GpioInputC2 Adc2In;
typedef GpioInputB13 Adc3In;
typedef GpioInputB12 Adc4In;
xpcc::IODeviceWrapper< Usart2, xpcc::IOBuffer::BlockIfFull > loggerDevice;
xpcc::log::Logger xpcc::log::info(loggerDevice);
static void
printAdc()
{
const float maxVoltage = 3.3;
float voltage = 0.0;
int adcValue = 0;
adcValue = Adc1::getValue();
XPCC_LOG_INFO << "Adc1: value=" << adcValue;
voltage = adcValue * maxVoltage / 0xfff;
XPCC_LOG_INFO << "; voltage=" << voltage << xpcc::endl;
/*
adcValue = Adc2::getValue();
XPCC_LOG_INFO << "Adc2: value=" << adcValue;
voltage = adcValue * maxVoltage / 0xfff;
XPCC_LOG_INFO << "; voltage=" << voltage << xpcc::endl;
adcValue = Adc3::getValue();
XPCC_LOG_INFO << "Adc3: value=" << adcValue;
voltage = adcValue * maxVoltage / 0xfff;
XPCC_LOG_INFO << "; voltage=" << voltage << xpcc::endl;
adcValue = Adc4::getValue();
XPCC_LOG_INFO << "Adc4: value=" << adcValue;
voltage = adcValue * maxVoltage / 0xfff;
XPCC_LOG_INFO << "; voltage=" << voltage << xpcc::endl;
*/
}
// ----------------------------------------------------------------------------
int
main()
{
Board::initialize();
// initialize Uart2 for XPCC_LOG_INFO
GpioOutputA2::connect(Usart2::Tx);
GpioInputA3::connect(Usart2::Rx, Gpio::InputType::PullUp);
Usart2::initialize<Board::systemClock, 115200>(12);
// initialize Adc
Adc1::initialize(Adc1::ClockMode::Asynchronous, Adc1::Prescaler::Div128,
Adc1::CalibrationMode::SingleEndedInputsMode, true);
Adc1::setFreeRunningMode(true);
Adc1In::connect(Adc1::Channel6);
Adc1::setChannel(Adc1In::Adc1Channel, Adc1::SampleTime::Cycles2);
Adc1::startConversion();
Adc2::initialize(Adc2::ClockMode::Asynchronous, Adc2::Prescaler::Div128,
Adc2::CalibrationMode::SingleEndedInputsMode, true);
Adc2::setFreeRunningMode(true);
Adc2In::connect(Adc2::Channel8);
Adc2::setChannel(Adc2In::Adc2Channel, Adc2::SampleTime::Cycles2);
Adc2::startConversion();
Adc3::initialize(Adc3::ClockMode::Asynchronous, Adc3::Prescaler::Div128,
Adc3::CalibrationMode::SingleEndedInputsMode, true);
Adc3::setFreeRunningMode(true);
Adc3In::connect(Adc3::Channel5);
Adc3::setChannel(Adc3In::Adc3Channel, Adc3::SampleTime::Cycles2);
Adc3::startConversion();
Adc4::initialize(Adc4::ClockMode::Asynchronous, Adc4::Prescaler::Div128,
Adc4::CalibrationMode::SingleEndedInputsMode, true);
Adc4::setFreeRunningMode(true);
Adc4In::connect(Adc4::Channel3);
Adc4::setChannel(Adc4In::Adc4Channel, Adc4::SampleTime::Cycles2);
Adc4::startConversion();
while (1)
{
xpcc::delayMilliseconds(200);
printAdc();
}
return 0;
}
| dergraaf/xpcc | examples/stm32f3_discovery/adc/continous/main.cpp | C++ | bsd-3-clause | 2,861 |
hc := ghc
hcflags := --make -O2 -fvia-C -optc-O2
examples := words spellchecker
all: $(examples)
words: Words.hs
$(hc) $(hcflags) -o $@ $^
spellchecker: SpellChecker.hs
$(hc) $(hcflags) -o $@ $^
clean:
-rm -f *.hi *.o $(examples)
| bos/bloomfilter | examples/Makefile | Makefile | bsd-3-clause | 238 |
///
/// \file
///
/// This file is a part of pattern matching testing suite.
///
/// \autor Yuriy Solodkyy <yuriy.solodkyy@gmail.com>
///
/// This file is a part of the XTL framework (http://parasol.tamu.edu/xtl/).
/// Copyright (C) 2005-2012 Texas A&M University.
/// All rights reserved.
///
#include "testshape.hpp"
#include "config.hpp"
#include "ptrtools.hpp"
//------------------------------------------------------------------------------
#if !XTL_USE_MEMOIZED_CAST
#define dynamic_cast constant_time_dynamic_cast
#endif
//------------------------------------------------------------------------------
static size_t fdc_id(size_t n);
//------------------------------------------------------------------------------
template <size_t N>
struct shape_kind : shape_kind<N/2>
{
typedef shape_kind<N/2> base_class;
shape_kind(size_t n = N) : base_class(n) {}
void accept(ShapeVisitor&) const;
};
template <>
struct shape_kind<0> : OtherBase, Shape
{
typedef Shape base_class;
shape_kind(size_t n = 0) : base_class(n,fdc_id(n)) {}
void accept(ShapeVisitor&) const;
};
//------------------------------------------------------------------------------
struct ShapeVisitor
{
virtual void visit(const shape_kind<0>&) {}
#define FOR_EACH_MAX NUMBER_OF_DERIVED-2
#define FOR_EACH_N(N) virtual void visit(const shape_kind<N+1>& s) { visit(static_cast<const shape_kind<N+1>::base_class&>(s)); }
#include "loop_over_numbers.hpp"
#undef FOR_EACH_N
#undef FOR_EACH_MAX
};
//------------------------------------------------------------------------------
template <size_t N> void shape_kind<N>::accept(ShapeVisitor& v) const { v.visit(*this); }
void shape_kind<0>::accept(ShapeVisitor& v) const { v.visit(*this); }
//------------------------------------------------------------------------------
enum { fdc_size = 10 };
/// Primes numbers for each level of the binary hierarchy
const size_t constant_time_dynamic_cast_primes[fdc_size][2] =
{
{ 2, 2}, // Because the root is 2
{ 3, 5},
{ 7,11},
{13,17},
{19,23},
{29,31},
{37,41},
{43,47},
{53,59},
{61,67}
};
//------------------------------------------------------------------------------
static size_t fdc_id(size_t n)
{
XTL_ASSERT(req_bits(n) < fdc_size);
size_t id = 1;
if (n)
for (size_t m = req_bits(n), i = m; i; --i)
id *= constant_time_dynamic_cast_primes[m-i][(n & (1 << (i-1))) != 0];
//std::cout << n << "->" << id << std::endl;
return id;
}
//------------------------------------------------------------------------------
inline size_t id(size_t n) { return fdc_id(n); }
const size_t shape_ids[100] =
{
id( 0), id( 1), id( 2), id( 3), id( 4), id( 5), id( 6), id( 7), id( 8), id( 9),
id(10), id(11), id(12), id(13), id(14), id(15), id(16), id(17), id(18), id(19),
id(20), id(21), id(22), id(23), id(24), id(25), id(26), id(27), id(28), id(29),
id(30), id(31), id(32), id(33), id(34), id(35), id(36), id(37), id(38), id(39),
id(40), id(41), id(42), id(43), id(44), id(45), id(46), id(47), id(48), id(49),
id(50), id(51), id(52), id(53), id(54), id(55), id(56), id(57), id(58), id(59),
id(60), id(61), id(62), id(63), id(64), id(65), id(66), id(67), id(68), id(69),
id(70), id(71), id(72), id(73), id(74), id(75), id(76), id(77), id(78), id(79),
id(80), id(81), id(82), id(83), id(84), id(85), id(86), id(87), id(88), id(89),
id(90), id(91), id(92), id(93), id(94), id(95), id(96), id(97), id(98), id(99),
};
//------------------------------------------------------------------------------
template <size_t N>
inline const shape_kind<N>* constant_time_dynamic_cast_ex(const shape_kind<N>*, const Shape* u)
{
return u->m_fdc_id % shape_ids[N] == 0
? static_cast<const shape_kind<N>*>(u)
: 0;
}
template <typename T>
inline T constant_time_dynamic_cast(const Shape* u)
{
return constant_time_dynamic_cast_ex(static_cast<T>(0), u);
}
//------------------------------------------------------------------------------
XTL_TIMED_FUNC_BEGIN
size_t do_match(const Shape& s, size_t)
{
if (const shape_kind< 0>* p0 = dynamic_cast<const shape_kind< 0>*>(&s))
{
if (const shape_kind< 1>* p1 = dynamic_cast<const shape_kind< 1>*>(p0))
if (const shape_kind< 2>* p2 = dynamic_cast<const shape_kind< 2>*>(p1))
if (const shape_kind< 4>* p4 = dynamic_cast<const shape_kind< 4>*>(p2))
if (const shape_kind< 8>* p8 = dynamic_cast<const shape_kind< 8>*>(p4))
if (const shape_kind<16>* p16 = dynamic_cast<const shape_kind<16>*>(p8))
if (const shape_kind<32>* p32 = dynamic_cast<const shape_kind<32>*>(p16))
if (const shape_kind<64>* p64 = dynamic_cast<const shape_kind<64>*>(p32))
return p64->m_member7 + 64 ;
else
if (const shape_kind<65>* p65 = dynamic_cast<const shape_kind<65>*>(p32))
return p65->m_member7 + 65 ;
else
return p32->m_member7 + 32 ;
else
if (const shape_kind<33>* p33 = dynamic_cast<const shape_kind<33>*>(p16))
if (const shape_kind<66>* p66 = dynamic_cast<const shape_kind<66>*>(p33))
return p66->m_member7 + 66 ;
else
if (const shape_kind<67>* p67 = dynamic_cast<const shape_kind<67>*>(p33))
return p67->m_member7 + 67 ;
else
return p33->m_member7 + 33 ;
else
return p16->m_member7 + 16 ;
else
if (const shape_kind<17>* p17 = dynamic_cast<const shape_kind<17>*>(p8))
if (const shape_kind<34>* p34 = dynamic_cast<const shape_kind<34>*>(p17))
if (const shape_kind<68>* p68 = dynamic_cast<const shape_kind<68>*>(p34))
return p68->m_member7 + 68 ;
else
if (const shape_kind<69>* p69 = dynamic_cast<const shape_kind<69>*>(p34))
return p69->m_member7 + 69 ;
else
return p34->m_member7 + 34 ;
else
if (const shape_kind<35>* p35 = dynamic_cast<const shape_kind<35>*>(p17))
if (const shape_kind<70>* p70 = dynamic_cast<const shape_kind<70>*>(p35))
return p70->m_member7 + 70 ;
else
if (const shape_kind<71>* p71 = dynamic_cast<const shape_kind<71>*>(p35))
return p71->m_member7 + 71 ;
else
return p35->m_member7 + 35 ;
else
return p17->m_member7 + 17 ;
else
return p8->m_member7 + 8 ;
else
if (const shape_kind< 9>* p9 = dynamic_cast<const shape_kind< 9>*>(p4))
if (const shape_kind<18>* p18 = dynamic_cast<const shape_kind<18>*>(p9))
if (const shape_kind<36>* p36 = dynamic_cast<const shape_kind<36>*>(p18))
if (const shape_kind<72>* p72 = dynamic_cast<const shape_kind<72>*>(p36))
return p72->m_member7 + 72 ;
else
if (const shape_kind<73>* p73 = dynamic_cast<const shape_kind<73>*>(p36))
return p73->m_member7 + 73 ;
else
return p36->m_member7 + 36 ;
else
if (const shape_kind<37>* p37 = dynamic_cast<const shape_kind<37>*>(p18))
if (const shape_kind<74>* p74 = dynamic_cast<const shape_kind<74>*>(p37))
return p74->m_member7 + 74 ;
else
if (const shape_kind<75>* p75 = dynamic_cast<const shape_kind<75>*>(p37))
return p75->m_member7 + 75 ;
else
return p37->m_member7 + 37 ;
else
return p18->m_member7 + 18 ;
else
if (const shape_kind<19>* p19 = dynamic_cast<const shape_kind<19>*>(p9))
if (const shape_kind<38>* p38 = dynamic_cast<const shape_kind<38>*>(p19))
if (const shape_kind<76>* p76 = dynamic_cast<const shape_kind<76>*>(p38))
return p76->m_member7 + 76 ;
else
if (const shape_kind<77>* p77 = dynamic_cast<const shape_kind<77>*>(p38))
return p77->m_member7 + 77 ;
else
return p38->m_member7 + 38 ;
else
if (const shape_kind<39>* p39 = dynamic_cast<const shape_kind<39>*>(p19))
if (const shape_kind<78>* p78 = dynamic_cast<const shape_kind<78>*>(p39))
return p78->m_member7 + 78 ;
else
if (const shape_kind<79>* p79 = dynamic_cast<const shape_kind<79>*>(p39))
return p79->m_member7 + 79 ;
else
return p39->m_member7 + 39 ;
else
return p19->m_member7 + 19 ;
else
return p9->m_member7 + 9 ;
else
return p4->m_member7 + 4 ;
else
if (const shape_kind< 5>* p5 = dynamic_cast<const shape_kind< 5>*>(p2))
if (const shape_kind<10>* p10 = dynamic_cast<const shape_kind<10>*>(p5))
if (const shape_kind<20>* p20 = dynamic_cast<const shape_kind<20>*>(p10))
if (const shape_kind<40>* p40 = dynamic_cast<const shape_kind<40>*>(p20))
if (const shape_kind<80>* p80 = dynamic_cast<const shape_kind<80>*>(p40))
return p80->m_member7 + 80 ;
else
if (const shape_kind<81>* p81 = dynamic_cast<const shape_kind<81>*>(p40))
return p81->m_member7 + 81 ;
else
return p40->m_member7 + 40 ;
else
if (const shape_kind<41>* p41 = dynamic_cast<const shape_kind<41>*>(p20))
if (const shape_kind<82>* p82 = dynamic_cast<const shape_kind<82>*>(p41))
return p82->m_member7 + 82 ;
else
if (const shape_kind<83>* p83 = dynamic_cast<const shape_kind<83>*>(p41))
return p83->m_member7 + 83 ;
else
return p41->m_member7 + 41 ;
else
return p20->m_member7 + 20 ;
else
if (const shape_kind<21>* p21 = dynamic_cast<const shape_kind<21>*>(p10))
if (const shape_kind<42>* p42 = dynamic_cast<const shape_kind<42>*>(p21))
if (const shape_kind<84>* p84 = dynamic_cast<const shape_kind<84>*>(p42))
return p84->m_member7 + 84 ;
else
if (const shape_kind<85>* p85 = dynamic_cast<const shape_kind<85>*>(p42))
return p85->m_member7 + 85 ;
else
return p42->m_member7 + 42 ;
else
if (const shape_kind<43>* p43 = dynamic_cast<const shape_kind<43>*>(p21))
if (const shape_kind<86>* p86 = dynamic_cast<const shape_kind<86>*>(p43))
return p86->m_member7 + 86 ;
else
if (const shape_kind<87>* p87 = dynamic_cast<const shape_kind<87>*>(p43))
return p87->m_member7 + 87 ;
else
return p43->m_member7 + 43 ;
else
return p21->m_member7 + 21 ;
else
return p10->m_member7 + 10 ;
else
if (const shape_kind<11>* p11 = dynamic_cast<const shape_kind<11>*>(p5))
if (const shape_kind<22>* p22 = dynamic_cast<const shape_kind<22>*>(p11))
if (const shape_kind<44>* p44 = dynamic_cast<const shape_kind<44>*>(p22))
if (const shape_kind<88>* p88 = dynamic_cast<const shape_kind<88>*>(p44))
return p88->m_member7 + 88 ;
else
if (const shape_kind<89>* p89 = dynamic_cast<const shape_kind<89>*>(p44))
return p89->m_member7 + 89 ;
else
return p44->m_member7 + 44 ;
else
if (const shape_kind<45>* p45 = dynamic_cast<const shape_kind<45>*>(p22))
if (const shape_kind<90>* p90 = dynamic_cast<const shape_kind<90>*>(p45))
return p90->m_member7 + 90 ;
else
if (const shape_kind<91>* p91 = dynamic_cast<const shape_kind<91>*>(p45))
return p91->m_member7 + 91 ;
else
return p45->m_member7 + 45 ;
else
return p22->m_member7 + 22 ;
else
if (const shape_kind<23>* p23 = dynamic_cast<const shape_kind<23>*>(p11))
if (const shape_kind<46>* p46 = dynamic_cast<const shape_kind<46>*>(p23))
if (const shape_kind<92>* p92 = dynamic_cast<const shape_kind<92>*>(p46))
return p92->m_member7 + 92 ;
else
if (const shape_kind<93>* p93 = dynamic_cast<const shape_kind<93>*>(p46))
return p93->m_member7 + 93 ;
else
return p46->m_member7 + 46 ;
else
if (const shape_kind<47>* p47 = dynamic_cast<const shape_kind<47>*>(p23))
if (const shape_kind<94>* p94 = dynamic_cast<const shape_kind<94>*>(p47))
return p94->m_member7 + 94 ;
else
if (const shape_kind<95>* p95 = dynamic_cast<const shape_kind<95>*>(p47))
return p95->m_member7 + 95 ;
else
return p47->m_member7 + 47 ;
else
return p23->m_member7 + 23 ;
else
return p11->m_member7 + 11 ;
else
return p5->m_member7 + 5 ;
else
return p2->m_member7 + 2 ;
else
if (const shape_kind< 3>* p3 = dynamic_cast<const shape_kind< 3>*>(p1))
if (const shape_kind< 6>* p6 = dynamic_cast<const shape_kind< 6>*>(p3))
if (const shape_kind<12>* p12 = dynamic_cast<const shape_kind<12>*>(p6))
if (const shape_kind<24>* p24 = dynamic_cast<const shape_kind<24>*>(p12))
if (const shape_kind<48>* p48 = dynamic_cast<const shape_kind<48>*>(p24))
if (const shape_kind<96>* p96 = dynamic_cast<const shape_kind<96>*>(p48))
return p96->m_member7 + 96 ;
else
if (const shape_kind<97>* p97 = dynamic_cast<const shape_kind<97>*>(p48))
return p97->m_member7 + 97 ;
else
return p48->m_member7 + 48 ;
else
if (const shape_kind<49>* p49 = dynamic_cast<const shape_kind<49>*>(p24))
if (const shape_kind<98>* p98 = dynamic_cast<const shape_kind<98>*>(p49))
return p98->m_member7 + 98 ;
else
if (const shape_kind<99>* p99 = dynamic_cast<const shape_kind<99>*>(p49))
return p99->m_member7 + 99 ;
else
return p49->m_member7 + 49 ;
else
return p24->m_member7 + 24 ;
else
if (const shape_kind<25>* p25 = dynamic_cast<const shape_kind<25>*>(p12))
if (const shape_kind<50>* p50 = dynamic_cast<const shape_kind<50>*>(p25))
return p50->m_member7 + 50 ;
else
if (const shape_kind<51>* p51 = dynamic_cast<const shape_kind<51>*>(p25))
return p51->m_member7 + 51 ;
else
return p25->m_member7 + 25 ;
else
return p12->m_member7 + 12 ;
else
if (const shape_kind<13>* p13 = dynamic_cast<const shape_kind<13>*>(p6))
if (const shape_kind<26>* p26 = dynamic_cast<const shape_kind<26>*>(p13))
if (const shape_kind<52>* p52 = dynamic_cast<const shape_kind<52>*>(p26))
return p52->m_member7 + 52 ;
else
if (const shape_kind<53>* p53 = dynamic_cast<const shape_kind<53>*>(p26))
return p53->m_member7 + 53 ;
else
return p26->m_member7 + 26 ;
else
if (const shape_kind<27>* p27 = dynamic_cast<const shape_kind<27>*>(p13))
if (const shape_kind<54>* p54 = dynamic_cast<const shape_kind<54>*>(p27))
return p54->m_member7 + 54 ;
else
if (const shape_kind<55>* p55 = dynamic_cast<const shape_kind<55>*>(p27))
return p55->m_member7 + 55 ;
else
return p27->m_member7 + 27 ;
else
return p13->m_member7 + 13 ;
else
return p6->m_member7 + 6 ;
else
if (const shape_kind< 7>* p7 = dynamic_cast<const shape_kind< 7>*>(p3))
if (const shape_kind<14>* p14 = dynamic_cast<const shape_kind<14>*>(p7))
if (const shape_kind<28>* p28 = dynamic_cast<const shape_kind<28>*>(p14))
if (const shape_kind<56>* p56 = dynamic_cast<const shape_kind<56>*>(p28))
return p56->m_member7 + 56 ;
else
if (const shape_kind<57>* p57 = dynamic_cast<const shape_kind<57>*>(p28))
return p57->m_member7 + 57 ;
else
return p28->m_member7 + 28 ;
else
if (const shape_kind<29>* p29 = dynamic_cast<const shape_kind<29>*>(p14))
if (const shape_kind<58>* p58 = dynamic_cast<const shape_kind<58>*>(p29))
return p58->m_member7 + 58 ;
else
if (const shape_kind<59>* p59 = dynamic_cast<const shape_kind<59>*>(p29))
return p59->m_member7 + 59 ;
else
return p29->m_member7 + 29 ;
else
return p14->m_member7 + 14 ;
else
if (const shape_kind<15>* p15 = dynamic_cast<const shape_kind<15>*>(p7))
if (const shape_kind<30>* p30 = dynamic_cast<const shape_kind<30>*>(p15))
if (const shape_kind<60>* p60 = dynamic_cast<const shape_kind<60>*>(p30))
return p60->m_member7 + 60 ;
else
if (const shape_kind<61>* p61 = dynamic_cast<const shape_kind<61>*>(p30))
return p61->m_member7 + 61 ;
else
return p30->m_member7 + 30 ;
else
if (const shape_kind<31>* p31 = dynamic_cast<const shape_kind<31>*>(p15))
if (const shape_kind<62>* p62 = dynamic_cast<const shape_kind<62>*>(p31))
return p62->m_member7 + 62 ;
else
if (const shape_kind<63>* p63 = dynamic_cast<const shape_kind<63>*>(p31))
return p63->m_member7 + 63 ;
else
return p31->m_member7 + 31 ;
else
return p15->m_member7 + 15 ;
else
return p7->m_member7 + 7 ;
else
return p3->m_member7 + 3 ;
else
return p1->m_member7 + 1 ;
else
return p0->m_member7 + 0 ;
}
return invalid;
}
XTL_TIMED_FUNC_END
//------------------------------------------------------------------------------
XTL_TIMED_FUNC_BEGIN
size_t do_visit(const Shape& s, size_t)
{
struct Visitor : ShapeVisitor
{
#define FOR_EACH_MAX NUMBER_OF_DERIVED-1
#define FOR_EACH_N(N) virtual void visit(const shape_kind<N>& s) { result = s.m_member7 + N; }
#include "loop_over_numbers.hpp"
#undef FOR_EACH_N
#undef FOR_EACH_MAX
size_t result;
};
Visitor v;
v.result = invalid;
s.accept(v);
return v.result;
}
XTL_TIMED_FUNC_END
//------------------------------------------------------------------------------
Shape* make_shape(size_t i)
{
switch (i % NUMBER_OF_DERIVED)
{
#define FOR_EACH_MAX NUMBER_OF_DERIVED-1
#define FOR_EACH_N(N) case N: return new shape_kind<N>;
#include "loop_over_numbers.hpp"
#undef FOR_EACH_N
#undef FOR_EACH_MAX
}
return 0;
}
//------------------------------------------------------------------------------
#include "testvismat.hpp" // Utilities for timing tests
//------------------------------------------------------------------------------
int main()
{
verdict pp = test_repetitive();
verdict ps = test_sequential();
verdict pr = test_randomized();
std::cout << "OVERALL: "
<< "Repetitive: " << pp << "; "
<< "Sequential: " << ps << "; "
<< "Random: " << pr
<< std::endl;
}
//------------------------------------------------------------------------------
| vscharf/Mach7 | code/typeswitch/2012-06-11/synthetic_dynamic_cast_fast.cpp | C++ | bsd-3-clause | 25,748 |
"""
Control global computation context
"""
from collections import defaultdict
_globals = defaultdict(lambda: None)
_globals['callbacks'] = set()
class set_options(object):
""" Set global state within controled context
This lets you specify various global settings in a tightly controlled with
block
Valid keyword arguments currently include:
get - the scheduler to use
pool - a thread or process pool
cache - Cache to use for intermediate results
func_loads/func_dumps - loads/dumps functions for serialization of data
likely to contain functions. Defaults to dill.loads/dill.dumps
rerun_exceptions_locally - rerun failed tasks in master process
Example
-------
>>> with set_options(get=dask.get): # doctest: +SKIP
... x = np.array(x) # uses dask.get internally
"""
def __init__(self, **kwargs):
self.old = _globals.copy()
_globals.update(kwargs)
def __enter__(self):
return
def __exit__(self, type, value, traceback):
_globals.clear()
_globals.update(self.old)
| wiso/dask | dask/context.py | Python | bsd-3-clause | 1,121 |
.tip {
opacity:0.9;
z-index:1000;
text-align:left;
border-radius:4px;
-moz-border-radius:4px;
-webkit-border-radius:4px;
padding:8px 8px;
color: black;
background-color:#E6E6E6;
border: 1px solid #B3B3B3;
box-shadow: 2px 2px 5px #888;
pointer-events:none;
} | YingHsuan/termite_data_server | server_src/static/ScatterPlot1/css/tip.css | CSS | bsd-3-clause | 270 |
// 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 UI_COMPOSITOR_COMPOSITOR_OBSERVER_H_
#define UI_COMPOSITOR_COMPOSITOR_OBSERVER_H_
#include "base/containers/flat_set.h"
#include "base/time/time.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "components/viz/common/surfaces/frame_sink_id.h"
#include "ui/compositor/compositor_export.h"
namespace gfx {
class Size;
struct PresentationFeedback;
} // namespace gfx
namespace ui {
class Compositor;
// A compositor observer is notified when compositing completes.
class COMPOSITOR_EXPORT CompositorObserver {
public:
virtual ~CompositorObserver() = default;
// A commit proxies information from the main thread to the compositor
// thread. It typically happens when some state changes that will require a
// composite. In the multi-threaded case, many commits may happen between
// two successive composites. In the single-threaded, a single commit
// between two composites (just before the composite as part of the
// composite cycle). If the compositor is locked, it will not send this
// this signal.
virtual void OnCompositingDidCommit(Compositor* compositor) {}
// Called when compositing started: it has taken all the layer changes into
// account and has issued the graphics commands.
virtual void OnCompositingStarted(Compositor* compositor,
base::TimeTicks start_time) {}
// Called when compositing completes: the present to screen has completed.
virtual void OnCompositingEnded(Compositor* compositor) {}
// Called when a child of the compositor is resizing.
virtual void OnCompositingChildResizing(Compositor* compositor) {}
// TODO(crbug.com/1052397): Revisit the macro expression once build flag switch
// of lacros-chrome is complete.
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)
// Called when a swap with new size is completed.
virtual void OnCompositingCompleteSwapWithNewSize(ui::Compositor* compositor,
const gfx::Size& size) {}
#endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
// Called at the top of the compositor's destructor, to give observers a
// chance to remove themselves.
virtual void OnCompositingShuttingDown(Compositor* compositor) {}
// Called when the presentation feedback was received from the viz.
virtual void OnDidPresentCompositorFrame(
uint32_t frame_token,
const gfx::PresentationFeedback& feedback) {}
virtual void OnFirstAnimationStarted(Compositor* compositor) {}
virtual void OnLastAnimationEnded(Compositor* compositor) {}
virtual void OnFrameSinksToThrottleUpdated(
const base::flat_set<viz::FrameSinkId>& ids) {}
};
} // namespace ui
#endif // UI_COMPOSITOR_COMPOSITOR_OBSERVER_H_
| chromium/chromium | ui/compositor/compositor_observer.h | C | bsd-3-clause | 2,940 |
package uatparse
import (
"encoding/hex"
"errors"
"fmt"
"io/ioutil"
"strconv"
"strings"
)
const (
UPLINK_BLOCK_DATA_BITS = 576
UPLINK_BLOCK_BITS = (UPLINK_BLOCK_DATA_BITS + 160)
UPLINK_BLOCK_DATA_BYTES = (UPLINK_BLOCK_DATA_BITS / 8)
UPLINK_BLOCK_BYTES = (UPLINK_BLOCK_BITS / 8)
UPLINK_FRAME_BLOCKS = 6
UPLINK_FRAME_DATA_BITS = (UPLINK_FRAME_BLOCKS * UPLINK_BLOCK_DATA_BITS)
UPLINK_FRAME_BITS = (UPLINK_FRAME_BLOCKS * UPLINK_BLOCK_BITS)
UPLINK_FRAME_DATA_BYTES = (UPLINK_FRAME_DATA_BITS / 8)
UPLINK_FRAME_BYTES = (UPLINK_FRAME_BITS / 8)
// assume 6 byte frames: 2 header bytes, 4 byte payload
// (TIS-B heartbeat with one address, or empty FIS-B APDU)
UPLINK_MAX_INFO_FRAMES = (424 / 6)
dlac_alpha = "\x03ABCDEFGHIJKLMNOPQRSTUVWXYZ\x1A\t\x1E\n| !\"#$%&'()*+,-./0123456789:;<=>?"
)
type UATFrame struct {
Raw_data []byte
FISB_data []byte
FISB_month uint32
FISB_day uint32
FISB_hours uint32
FISB_minutes uint32
FISB_seconds uint32
FISB_length uint32
frame_length uint32
Frame_type uint32
Product_id uint32
// Text data, if applicable.
Text_data []string
// Flags.
a_f bool
g_f bool
p_f bool
s_f bool //TODO: Segmentation.
// For AIRMET/NOTAM.
//FIXME: Temporary.
Points []GeoPoint
ReportNumber uint16
ReportYear uint16
LocationIdentifier string
RecordFormat uint8
ReportStart string
ReportEnd string
}
type UATMsg struct {
// Metadata from demodulation.
RS_Err int
SignalStrength int
msg []byte
decoded bool
// Station location for uplink frames, aircraft position for downlink frames.
Lat float64
Lon float64
Frames []*UATFrame
}
func dlac_decode(data []byte, data_len uint32) string {
step := 0
tab := false
ret := ""
for i := uint32(0); i < data_len; i++ {
var ch uint32
switch step {
case 0:
ch = uint32(data[i+0]) >> 2
case 1:
ch = ((uint32(data[i-1]) & 0x03) << 4) | (uint32(data[i+0]) >> 4)
case 2:
ch = ((uint32(data[i-1]) & 0x0f) << 2) | (uint32(data[i+0]) >> 6)
i = i - 1
case 3:
ch = uint32(data[i+0]) & 0x3f
}
if tab {
for ch > 0 {
ret += " "
ch--
}
tab = false
} else if ch == 28 { // tab
tab = true
} else {
ret += string(dlac_alpha[ch])
}
step = (step + 1) % 4
}
return ret
}
// Decodes the time format and aligns 'FISB_data' accordingly.
//TODO: Make a new "FISB Time" structure that also encodes the type of timestamp received.
//TODO: pass up error.
func (f *UATFrame) decodeTimeFormat() {
if len(f.Raw_data) < 3 {
return // Can't determine time format.
}
t_opt := ((uint32(f.Raw_data[1]) & 0x01) << 1) | (uint32(f.Raw_data[2]) >> 7)
var fisb_data []byte
switch t_opt {
case 0: // Hours, Minutes.
if f.frame_length < 4 {
return
}
f.FISB_hours = (uint32(f.Raw_data[2]) & 0x7c) >> 2
f.FISB_minutes = ((uint32(f.Raw_data[2]) & 0x03) << 4) | (uint32(f.Raw_data[3]) >> 4)
f.FISB_length = f.frame_length - 4
fisb_data = f.Raw_data[4:]
case 1: // Hours, Minutes, Seconds.
if f.frame_length < 5 {
return
}
f.FISB_hours = (uint32(f.Raw_data[2]) & 0x7c) >> 2
f.FISB_minutes = ((uint32(f.Raw_data[2]) & 0x03) << 4) | (uint32(f.Raw_data[3]) >> 4)
f.FISB_seconds = ((uint32(f.Raw_data[3]) & 0x0f) << 2) | (uint32(f.Raw_data[4]) >> 6)
f.FISB_length = f.frame_length - 5
fisb_data = f.Raw_data[5:]
case 2: // Month, Day, Hours, Minutes.
if f.frame_length < 5 {
return
}
f.FISB_month = (uint32(f.Raw_data[2]) & 0x78) >> 3
f.FISB_day = ((uint32(f.Raw_data[2]) & 0x07) << 2) | (uint32(f.Raw_data[3]) >> 6)
f.FISB_hours = (uint32(f.Raw_data[3]) & 0x3e) >> 1
f.FISB_minutes = ((uint32(f.Raw_data[3]) & 0x01) << 5) | (uint32(f.Raw_data[4]) >> 3)
f.FISB_length = f.frame_length - 5
fisb_data = f.Raw_data[5:]
case 3: // Month, Day, Hours, Minutes, Seconds.
if f.frame_length < 6 {
return
}
f.FISB_month = (uint32(f.Raw_data[2]) & 0x78) >> 3
f.FISB_day = ((uint32(f.Raw_data[2]) & 0x07) << 2) | (uint32(f.Raw_data[3]) >> 6)
f.FISB_hours = (uint32(f.Raw_data[3]) & 0x3e) >> 1
f.FISB_minutes = ((uint32(f.Raw_data[3]) & 0x01) << 5) | (uint32(f.Raw_data[4]) >> 3)
f.FISB_seconds = ((uint32(f.Raw_data[4]) & 0x03) << 3) | (uint32(f.Raw_data[5]) >> 5)
f.FISB_length = f.frame_length - 6
fisb_data = f.Raw_data[6:]
default:
return // Should never reach this.
}
f.FISB_data = fisb_data
if (uint16(f.Raw_data[1]) & 0x02) != 0 {
f.s_f = true // Default false.
}
}
// Format newlines.
func formatDLACData(p string) []string {
ret := make([]string, 0)
for {
pos := strings.Index(p, "\x1E")
if pos == -1 {
pos = strings.Index(p, "\x03")
if pos == -1 {
ret = append(ret, p)
break
}
}
ret = append(ret, p[:pos])
p = p[pos+1:]
}
return ret
}
// Whole frame contents is DLAC encoded text.
func (f *UATFrame) decodeTextFrame() {
if len(f.FISB_data) < int(f.FISB_length) {
return
}
p := dlac_decode(f.FISB_data, f.FISB_length)
f.Text_data = formatDLACData(p)
}
// Gets month, day, hours, minutes.
// Formats into a string.
func airmetParseDate(b []byte, date_time_format uint8) string {
switch date_time_format {
case 0: // No date/time used.
return ""
case 1: // Month, Day, Hours, Minutes.
month := uint8(b[0])
day := uint8(b[1])
hours := uint8(b[2])
minutes := uint8(b[3])
return fmt.Sprintf("%02d-%02d %02d:%02d", month, day, hours, minutes)
case 2: // Day, Hours, Minutes.
day := uint8(b[0])
hours := uint8(b[1])
minutes := uint8(b[2])
return fmt.Sprintf("%02d %02d:%02d", day, hours, minutes)
case 3: // Hours, Minutes.
hours := uint8(b[0])
minutes := uint8(b[1])
return fmt.Sprintf("%02d:%02d", hours, minutes)
}
return ""
}
func airmetLatLng(lat_raw, lng_raw int32, alt bool) (float64, float64) {
fct := float64(0.000687)
if alt {
fct = float64(0.001373)
}
lat := fct * float64(lat_raw)
lng := fct * float64(lng_raw)
if lat > 90.0 {
lat = lat - 180.0
}
if lng > 180.0 {
lng = lng - 360.0
}
return lat, lng
}
//TODO: Ignoring flags (segmentation, etc.)
// Aero_FISB_ProdDef_Rev4.pdf
// Decode product IDs 8-13.
func (f *UATFrame) decodeAirmet() {
// APDU header: 48 bits (3-3) - assume no segmentation.
record_format := (uint8(f.FISB_data[0]) & 0xF0) >> 4
f.RecordFormat = record_format
fmt.Fprintf(ioutil.Discard, "record_format=%d\n", record_format)
product_version := (uint8(f.FISB_data[0]) & 0x0F)
fmt.Fprintf(ioutil.Discard, "product_version=%d\n", product_version)
record_count := (uint8(f.FISB_data[1]) & 0xF0) >> 4
fmt.Fprintf(ioutil.Discard, "record_count=%d\n", record_count)
location_identifier := dlac_decode(f.FISB_data[2:], 3)
fmt.Fprintf(ioutil.Discard, "%s\n", hex.Dump(f.FISB_data))
f.LocationIdentifier = location_identifier
fmt.Fprintf(ioutil.Discard, "location_identifier=%s\n", location_identifier)
record_reference := (uint8(f.FISB_data[5])) //FIXME: Special values. 0x00 means "use location_identifier". 0xFF means "use different reference". (4-3).
fmt.Fprintf(ioutil.Discard, "record_reference=%d\n", record_reference)
// Not sure when this is even used.
// rwy_designator := (record_reference & FC) >> 4
// parallel_rwy_designator := record_reference & 0x03 // 0 = NA, 1 = R, 2 = L, 3 = C (Figure 4-2).
//FIXME: Assume one record.
if record_count != 1 {
fmt.Fprintf(ioutil.Discard, "record_count=%d, != 1\n", record_count)
return
}
/*
0 - No data
1 - Unformatted ASCII Text
2 - Unformatted DLAC Text
3 - Unformatted DLAC Text w/ dictionary
4 - Formatted Text using ASN.1/PER
5-7 - Future Use
8 - Graphical Overlay
9-15 - Future Use
*/
switch record_format {
case 2:
record_length := (uint16(f.FISB_data[6]) << 8) | uint16(f.FISB_data[7])
if len(f.FISB_data)-int(record_length) < 6 {
fmt.Fprintf(ioutil.Discard, "FISB record not long enough: record_length=%d, len(f.FISB_data)=%d\n", record_length, len(f.FISB_data))
return
}
fmt.Fprintf(ioutil.Discard, "record_length=%d\n", record_length)
// Report identifier = report number + report year.
report_number := (uint16(f.FISB_data[8]) << 6) | ((uint16(f.FISB_data[9]) & 0xFC) >> 2)
f.ReportNumber = report_number
fmt.Fprintf(ioutil.Discard, "report_number=%d\n", report_number)
report_year := ((uint16(f.FISB_data[9]) & 0x03) << 5) | ((uint16(f.FISB_data[10]) & 0xF8) >> 3)
f.ReportYear = report_year
fmt.Fprintf(ioutil.Discard, "report_year=%d\n", report_year)
report_status := (uint8(f.FISB_data[10]) & 0x04) >> 2 //TODO: 0 = cancelled, 1 = active.
fmt.Fprintf(ioutil.Discard, "report_status=%d\n", report_status)
fmt.Fprintf(ioutil.Discard, "record_length=%d,len=%d\n", record_length, len(f.FISB_data))
text_data_len := record_length - 5
text_data := dlac_decode(f.FISB_data[11:], uint32(text_data_len))
fmt.Fprintf(ioutil.Discard, "text_data=%s\n", text_data)
f.Text_data = formatDLACData(text_data)
case 8:
// (6-1). (6.22 - Graphical Overlay Record Format).
record_data := f.FISB_data[6:] // Start after the record header.
record_length := (uint16(record_data[0]) << 2) | ((uint16(record_data[1]) & 0xC0) >> 6)
fmt.Fprintf(ioutil.Discard, "record_length=%d\n", record_length)
// Report identifier = report number + report year.
report_number := ((uint16(record_data[1]) & 0x3F) << 8) | uint16(record_data[2])
f.ReportNumber = report_number
fmt.Fprintf(ioutil.Discard, "report_number=%d\n", report_number)
report_year := (uint16(record_data[3]) & 0xFE) >> 1
f.ReportYear = report_year
fmt.Fprintf(ioutil.Discard, "report_year=%d\n", report_year)
overlay_record_identifier := ((uint8(record_data[4]) & 0x1E) >> 1) + 1 // Document instructs to add 1.
fmt.Fprintf(ioutil.Discard, "overlay_record_identifier=%d\n", overlay_record_identifier)
object_label_flag := uint8(record_data[4] & 0x01)
fmt.Fprintf(ioutil.Discard, "object_label_flag=%d\n", object_label_flag)
if object_label_flag == 0 { // Numeric index.
object_label := (uint8(record_data[5]) << 8) | uint8(record_data[6])
record_data = record_data[7:]
fmt.Fprintf(ioutil.Discard, "object_label=%d\n", object_label)
} else {
object_label := dlac_decode(record_data[5:], 9)
record_data = record_data[14:]
fmt.Fprintf(ioutil.Discard, "object_label=%s\n", object_label)
}
element_flag := (uint8(record_data[0]) & 0x80) >> 7
fmt.Fprintf(ioutil.Discard, "element_flag=%d\n", element_flag)
qualifier_flag := (uint8(record_data[0]) & 0x40) >> 6
fmt.Fprintf(ioutil.Discard, "qualifier_flag=%d\n", qualifier_flag)
param_flag := (uint8(record_data[0]) & 0x20) >> 5
fmt.Fprintf(ioutil.Discard, "param_flag=%d\n", param_flag)
object_element := uint8(record_data[0]) & 0x1F
fmt.Fprintf(ioutil.Discard, "object_element=%d\n", object_element)
object_type := (uint8(record_data[1]) & 0xF0) >> 4
fmt.Fprintf(ioutil.Discard, "object_type=%d\n", object_type)
object_status := uint8(record_data[1]) & 0x0F
fmt.Fprintf(ioutil.Discard, "object_status=%d\n", object_status)
//FIXME
if qualifier_flag == 0 { //TODO: Check.
record_data = record_data[2:]
} else {
object_qualifier := (uint32(record_data[2]) << 16) | (uint32(record_data[3]) << 8) | uint32(record_data[4])
fmt.Fprintf(ioutil.Discard, "object_qualifier=%d\n", object_qualifier)
fmt.Fprintf(ioutil.Discard, "%02x%02x%02x\n", record_data[2], record_data[3], record_data[4])
record_data = record_data[5:]
}
//FIXME
//if param_flag == 0 { //TODO: Check.
// record_data = record_data[2:]
//} else {
// //TODO.
// // record_data = record_data[4:]
//}
record_applicability_options := (uint8(record_data[0]) & 0xC0) >> 6
fmt.Fprintf(ioutil.Discard, "record_applicability_options=%d\n", record_applicability_options)
date_time_format := (uint8(record_data[0]) & 0x30) >> 4
fmt.Fprintf(ioutil.Discard, "date_time_format=%d\n", date_time_format)
geometry_overlay_options := uint8(record_data[0]) & 0x0F
fmt.Fprintf(ioutil.Discard, "geometry_overlay_options=%d\n", geometry_overlay_options)
overlay_operator := (uint8(record_data[1]) & 0xC0) >> 6
fmt.Fprintf(ioutil.Discard, "overlay_operator=%d\n", overlay_operator)
overlay_vertices_count := (uint8(record_data[1]) & 0x3F) + 1 // Document instructs to add 1. (6.20).
fmt.Fprintf(ioutil.Discard, "overlay_vertices_count=%d\n", overlay_vertices_count)
// Parse all of the dates.
switch record_applicability_options {
case 0: // No times given. UFN.
record_data = record_data[2:]
case 1: // Start time only. WEF.
f.ReportStart = airmetParseDate(record_data[2:], date_time_format)
record_data = record_data[6:]
case 2: // End time only. TIL.
f.ReportEnd = airmetParseDate(record_data[2:], date_time_format)
record_data = record_data[6:]
case 3: // Both start and end times. WEF.
f.ReportStart = airmetParseDate(record_data[2:], date_time_format)
f.ReportEnd = airmetParseDate(record_data[6:], date_time_format)
record_data = record_data[10:]
}
// Now we have the vertices.
switch geometry_overlay_options {
case 3: // Extended Range 3D Polygon (MSL).
points := make([]GeoPoint, 0) // Slice containing all of the points.
fmt.Fprintf(ioutil.Discard, "%d\n", len(record_data))
for i := 0; i < int(overlay_vertices_count); i++ {
lng_raw := (int32(record_data[6*i]) << 11) | (int32(record_data[6*i+1]) << 3) | (int32(record_data[6*i+2]) & 0xE0 >> 5)
lat_raw := ((int32(record_data[6*i+2]) & 0x1F) << 14) | (int32(record_data[6*i+3]) << 6) | ((int32(record_data[6*i+4]) & 0xFC) >> 2)
alt_raw := ((int32(record_data[6*i+4]) & 0x03) << 8) | int32(record_data[6*i+5])
fmt.Fprintf(ioutil.Discard, "lat_raw=%d, lng_raw=%d, alt_raw=%d\n", lat_raw, lng_raw, alt_raw)
lat, lng := airmetLatLng(lat_raw, lng_raw, false)
alt := alt_raw * 100
fmt.Fprintf(ioutil.Discard, "lat=%f,lng=%f,alt=%d\n", lat, lng, alt)
fmt.Fprintf(ioutil.Discard, "coord:%f,%f\n", lat, lng)
var point GeoPoint
point.Lat = lat
point.Lon = lng
point.Alt = alt
points = append(points, point)
f.Points = points
}
case 9: // Extended Range 3D Point (AGL). p.47.
if len(record_data) < 6 {
fmt.Fprintf(ioutil.Discard, "invalid data: Extended Range 3D Point. Should be 6 bytes; % seen.\n", len(record_data))
} else {
lng_raw := (int32(record_data[0]) << 11) | (int32(record_data[1]) << 3) | (int32(record_data[2]) & 0xE0 >> 5)
lat_raw := ((int32(record_data[2]) & 0x1F) << 14) | (int32(record_data[3]) << 6) | ((int32(record_data[4]) & 0xFC) >> 2)
alt_raw := ((int32(record_data[4]) & 0x03) << 8) | int32(record_data[5])
fmt.Fprintf(ioutil.Discard, "lat_raw=%d, lng_raw=%d, alt_raw=%d\n", lat_raw, lng_raw, alt_raw)
lat, lng := airmetLatLng(lat_raw, lng_raw, false)
alt := alt_raw * 100
fmt.Fprintf(ioutil.Discard, "lat=%f,lng=%f,alt=%d\n", lat, lng, alt)
fmt.Fprintf(ioutil.Discard, "coord:%f,%f\n", lat, lng)
var point GeoPoint
point.Lat = lat
point.Lon = lng
point.Alt = alt
f.Points = []GeoPoint{point}
}
case 7, 8: // Extended Range Circular Prism (7 = MSL, 8 = AGL)
if len(record_data) < 14 {
fmt.Fprintf(ioutil.Discard, "invalid data: Extended Range Circular Prism. Should be 14 bytes; % seen.\n", len(record_data))
} else {
lng_bot_raw := (int32(record_data[0]) << 10) | (int32(record_data[1]) << 2) | (int32(record_data[2]) & 0xC0 >> 6)
lat_bot_raw := ((int32(record_data[2]) & 0x3F) << 12) | (int32(record_data[3]) << 4) | ((int32(record_data[4]) & 0xF0) >> 4)
lng_top_raw := ((int32(record_data[4]) & 0x0F) << 14) | (int32(record_data[5]) << 6) | ((int32(record_data[6]) & 0xFC) >> 2)
lat_top_raw := ((int32(record_data[6]) & 0x03) << 16) | (int32(record_data[7]) << 8) | int32(record_data[8])
alt_bot_raw := (int32(record_data[9]) & 0xFE) >> 1
alt_top_raw := ((int32(record_data[9]) & 0x01) << 6) | ((int32(record_data[10]) & 0xFC) >> 2)
r_lng_raw := ((int32(record_data[10]) & 0x03) << 7) | ((int32(record_data[11]) & 0xFE) >> 1)
r_lat_raw := ((int32(record_data[11]) & 0x01) << 8) | int32(record_data[12])
alpha := int32(record_data[13])
lat_bot, lng_bot := airmetLatLng(lat_bot_raw, lng_bot_raw, true)
lat_top, lng_top := airmetLatLng(lat_top_raw, lng_top_raw, true)
alt_bot := alt_bot_raw * 5
alt_top := alt_top_raw * 500
r_lng := float64(r_lng_raw) * float64(0.2)
r_lat := float64(r_lat_raw) * float64(0.2)
fmt.Fprintf(ioutil.Discard, "lat_bot, lng_bot = %f, %f\n", lat_bot, lng_bot)
fmt.Fprintf(ioutil.Discard, "lat_top, lng_top = %f, %f\n", lat_top, lng_top)
if geometry_overlay_options == 8 {
fmt.Fprintf(ioutil.Discard, "alt_bot, alt_top = %d AGL, %d AGL\n", alt_bot, alt_top)
} else {
fmt.Fprintf(ioutil.Discard, "alt_bot, alt_top = %d MSL, %d MSL\n", alt_bot, alt_top)
}
fmt.Fprintf(ioutil.Discard, "r_lng, r_lat = %f, %f\n", r_lng, r_lat)
fmt.Fprintf(ioutil.Discard, "alpha=%d\n", alpha)
}
default:
fmt.Fprintf(ioutil.Discard, "unknown geometry: %d\n", geometry_overlay_options)
}
//case 1: // Unformatted ASCII Text.
default:
fmt.Fprintf(ioutil.Discard, "unknown record format: %d\n", record_format)
}
fmt.Fprintf(ioutil.Discard, "\n\n\n")
}
func (f *UATFrame) decodeInfoFrame() {
if len(f.Raw_data) < 2 {
return // Can't determine Product_id.
}
f.Product_id = ((uint32(f.Raw_data[0]) & 0x1f) << 6) | (uint32(f.Raw_data[1]) >> 2)
if f.Frame_type != 0 {
return // Not FIS-B.
}
f.decodeTimeFormat()
switch f.Product_id {
case 413:
f.decodeTextFrame()
/*
case 8, 11, 13:
f.decodeAirmet()
*/
default:
fmt.Fprintf(ioutil.Discard, "don't know what to do with product id: %d\n", f.Product_id)
}
// logger.Printf("pos=%d,len=%d,t_opt=%d,product_id=%d, time=%d:%d\n", frame_start, frame_len, t_opt, product_id, fisb_hours, fisb_minutes)
}
func (u *UATMsg) DecodeUplink() error {
// position_valid := (uint32(frame[5]) & 0x01) != 0
frame := u.msg
if len(frame) < UPLINK_FRAME_DATA_BYTES {
return errors.New(fmt.Sprintf("DecodeUplink: short read (%d).", len(frame)))
}
raw_lat := (uint32(frame[0]) << 15) | (uint32(frame[1]) << 7) | (uint32(frame[2]) >> 1)
raw_lon := ((uint32(frame[2]) & 0x01) << 23) | (uint32(frame[3]) << 15) | (uint32(frame[4]) << 7) | (uint32(frame[5]) >> 1)
lat := float64(raw_lat) * 360.0 / 16777216.0
lon := float64(raw_lon) * 360.0 / 16777216.0
if lat > 90 {
lat = lat - 180
}
if lon > 180 {
lon = lon - 360
}
u.Lat = lat
u.Lon = lon
// utc_coupled := (uint32(frame[6]) & 0x80) != 0
app_data_valid := (uint32(frame[6]) & 0x20) != 0
// slot_id := uint32(frame[6]) & 0x1f
// tisb_site_id := uint32(frame[7]) >> 4
// logger.Printf("position_valid=%t, %.04f, %.04f, %t, %t, %d, %d\n", position_valid, lat, lon, utc_coupled, app_data_valid, slot_id, tisb_site_id)
if !app_data_valid {
return nil // Not sure when this even happens?
}
app_data := frame[8:432]
num_info_frames := 0
pos := 0
total_len := len(app_data)
for (num_info_frames < UPLINK_MAX_INFO_FRAMES) && (pos+2 <= total_len) {
data := app_data[pos:]
frame_length := (uint32(data[0]) << 1) | (uint32(data[1]) >> 7)
frame_type := uint32(data[1]) & 0x0f
if pos+int(frame_length) > total_len {
break // Overrun?
}
if frame_length == 0 { // Empty frame. Quit here.
break
}
pos = pos + 2
data = data[2 : frame_length+2]
thisFrame := new(UATFrame)
thisFrame.Raw_data = data
thisFrame.frame_length = frame_length
thisFrame.Frame_type = frame_type
thisFrame.decodeInfoFrame()
// Save the decoded frame.
u.Frames = append(u.Frames, thisFrame)
pos = pos + int(frame_length)
}
u.decoded = true
return nil
}
/*
Aggregate all of the text rates across the frames in the message and return as an array.
*/
func (u *UATMsg) GetTextReports() ([]string, error) {
ret := make([]string, 0)
if !u.decoded {
err := u.DecodeUplink()
if err != nil {
return ret, err
}
}
for _, f := range u.Frames {
for _, m := range f.Text_data {
if len(m) > 0 {
ret = append(ret, m)
}
}
}
return ret, nil
}
/*
Parse out the message from the "dump978" output format.
*/
func New(buf string) (*UATMsg, error) {
ret := new(UATMsg)
buf = strings.Trim(buf, "\r\n") // Remove newlines.
x := strings.Split(buf, ";") // We want to discard everything before the first ';'.
if len(x) < 2 {
return ret, errors.New(fmt.Sprintf("New UATMsg: Invalid format (%s).", buf))
}
/*
Parse _;rs=?;ss=? - if available.
RS_Err int
SignalStrength int
*/
ret.SignalStrength = -1
ret.RS_Err = -1
for _, f := range x[1:] {
x2 := strings.Split(f, "=")
if len(x2) != 2 {
continue
}
i, err := strconv.Atoi(x2[1])
if err != nil {
continue
}
if x2[0] == "ss" {
ret.SignalStrength = i
} else if x2[0] == "rs" {
ret.RS_Err = i
}
}
s := x[0]
// Only want "long" uplink messages.
if (len(s)-1)%2 != 0 || (len(s)-1)/2 != UPLINK_FRAME_DATA_BYTES {
return ret, errors.New(fmt.Sprintf("New UATMsg: short read (%d).", len(s)))
}
if s[0] != '+' { // Only want + ("Uplink") messages currently. - (Downlink) or messages that start with other are discarded.
return ret, errors.New("New UATMsg: expecting uplink frame.")
}
s = s[1:] // Remove the preceding '+' or '-' character.
// Convert the hex string into a byte array.
frame := make([]byte, UPLINK_FRAME_DATA_BYTES)
hex.Decode(frame, []byte(s))
ret.msg = frame
return ret, nil
}
| ssokol/stratux | uatparse/uatparse.go | GO | bsd-3-clause | 21,443 |
<?php
use yii\helpers\Url;
class UrlCreationWithScriptNameTest extends UrlCreationTest
{
protected $showScriptName = true;
}
| Kolomiysev/reviews | vendor/codemix/yii2-localeurls/tests/UrlCreationWithScriptNameTest.php | PHP | bsd-3-clause | 131 |
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkGradientShader.h"
namespace skiagm {
class FillTypePerspGM : public GM {
SkPath fPath;
public:
FillTypePerspGM() {}
void makePath() {
if (fPath.isEmpty()) {
const SkScalar radius = SkIntToScalar(45);
fPath.addCircle(SkIntToScalar(50), SkIntToScalar(50), radius);
fPath.addCircle(SkIntToScalar(100), SkIntToScalar(100), radius);
}
}
protected:
SkString onShortName() SK_OVERRIDE {
return SkString("filltypespersp");
}
SkISize onISize() SK_OVERRIDE {
return SkISize::Make(835, 840);
}
void showPath(SkCanvas* canvas, int x, int y, SkPath::FillType ft,
SkScalar scale, const SkPaint& paint) {
const SkRect r = { 0, 0, SkIntToScalar(150), SkIntToScalar(150) };
canvas->save();
canvas->translate(SkIntToScalar(x), SkIntToScalar(y));
canvas->clipRect(r);
canvas->drawColor(SK_ColorWHITE);
fPath.setFillType(ft);
canvas->translate(r.centerX(), r.centerY());
canvas->scale(scale, scale);
canvas->translate(-r.centerX(), -r.centerY());
canvas->drawPath(fPath, paint);
canvas->restore();
}
void showFour(SkCanvas* canvas, SkScalar scale, bool aa) {
SkPaint paint;
SkPoint center = SkPoint::Make(SkIntToScalar(100), SkIntToScalar(100));
SkColor colors[] = {SK_ColorBLUE, SK_ColorRED, SK_ColorGREEN};
SkScalar pos[] = {0, SK_ScalarHalf, SK_Scalar1};
SkShader* s = SkGradientShader::CreateRadial(center,
SkIntToScalar(100),
colors,
pos,
SK_ARRAY_COUNT(colors),
SkShader::kClamp_TileMode);
paint.setShader(s)->unref();
paint.setAntiAlias(aa);
showPath(canvas, 0, 0, SkPath::kWinding_FillType,
scale, paint);
showPath(canvas, 200, 0, SkPath::kEvenOdd_FillType,
scale, paint);
showPath(canvas, 00, 200, SkPath::kInverseWinding_FillType,
scale, paint);
showPath(canvas, 200, 200, SkPath::kInverseEvenOdd_FillType,
scale, paint);
}
void onDraw(SkCanvas* canvas) SK_OVERRIDE {
this->makePath();
// do perspective drawPaint as the background;
SkPaint bkgnrd;
SkPoint center = SkPoint::Make(SkIntToScalar(100),
SkIntToScalar(100));
SkColor colors[] = {SK_ColorBLACK, SK_ColorCYAN,
SK_ColorYELLOW, SK_ColorWHITE};
SkScalar pos[] = {0, SK_ScalarHalf / 2,
3 * SK_ScalarHalf / 2, SK_Scalar1};
SkShader* s = SkGradientShader::CreateRadial(center,
SkIntToScalar(1000),
colors,
pos,
SK_ARRAY_COUNT(colors),
SkShader::kClamp_TileMode);
bkgnrd.setShader(s)->unref();
canvas->save();
canvas->translate(SkIntToScalar(100), SkIntToScalar(100));
SkMatrix mat;
mat.reset();
mat.setPerspY(SK_Scalar1 / 1000);
canvas->concat(mat);
canvas->drawPaint(bkgnrd);
canvas->restore();
// draw the paths in perspective
SkMatrix persp;
persp.reset();
persp.setPerspX(-SK_Scalar1 / 1800);
persp.setPerspY(SK_Scalar1 / 500);
canvas->concat(persp);
canvas->translate(SkIntToScalar(20), SkIntToScalar(20));
const SkScalar scale = SkIntToScalar(5)/4;
showFour(canvas, SK_Scalar1, false);
canvas->translate(SkIntToScalar(450), 0);
showFour(canvas, scale, false);
canvas->translate(SkIntToScalar(-450), SkIntToScalar(450));
showFour(canvas, SK_Scalar1, true);
canvas->translate(SkIntToScalar(450), 0);
showFour(canvas, scale, true);
}
private:
typedef GM INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
static GM* MyFactory(void*) { return new FillTypePerspGM; }
static GMRegistry reg(MyFactory);
}
| CTSRD-SOAAP/chromium-42.0.2311.135 | third_party/skia/gm/filltypespersp.cpp | C++ | bsd-3-clause | 4,675 |
/*
* Copyright (C) 2004, 2005, 2006, 2007 Nikolas Zimmermann <zimmermann@kde.org>
* Copyright (C) 2004, 2005 Rob Buis <buis@kde.org>
* Copyright (C) 2005 Eric Seidel <eric@webkit.org>
* Copyright (C) 2013 Google 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.
*/
#include "config.h"
#include "platform/graphics/filters/FEDiffuseLighting.h"
#include "platform/graphics/filters/LightSource.h"
#include "platform/text/TextStream.h"
namespace blink {
FEDiffuseLighting::FEDiffuseLighting(Filter* filter, const Color& lightingColor, float surfaceScale,
float diffuseConstant, PassRefPtr<LightSource> lightSource)
: FELighting(filter, DiffuseLighting, lightingColor, surfaceScale, diffuseConstant, 0, 0, lightSource)
{
}
PassRefPtrWillBeRawPtr<FEDiffuseLighting> FEDiffuseLighting::create(Filter* filter, const Color& lightingColor,
float surfaceScale, float diffuseConstant, PassRefPtr<LightSource> lightSource)
{
return adoptRefWillBeNoop(new FEDiffuseLighting(filter, lightingColor, surfaceScale, diffuseConstant, lightSource));
}
FEDiffuseLighting::~FEDiffuseLighting()
{
}
Color FEDiffuseLighting::lightingColor() const
{
return m_lightingColor;
}
bool FEDiffuseLighting::setLightingColor(const Color& lightingColor)
{
if (m_lightingColor == lightingColor)
return false;
m_lightingColor = lightingColor;
return true;
}
float FEDiffuseLighting::surfaceScale() const
{
return m_surfaceScale;
}
bool FEDiffuseLighting::setSurfaceScale(float surfaceScale)
{
if (m_surfaceScale == surfaceScale)
return false;
m_surfaceScale = surfaceScale;
return true;
}
float FEDiffuseLighting::diffuseConstant() const
{
return m_diffuseConstant;
}
bool FEDiffuseLighting::setDiffuseConstant(float diffuseConstant)
{
diffuseConstant = std::max(diffuseConstant, 0.0f);
if (m_diffuseConstant == diffuseConstant)
return false;
m_diffuseConstant = diffuseConstant;
return true;
}
const LightSource* FEDiffuseLighting::lightSource() const
{
return m_lightSource.get();
}
void FEDiffuseLighting::setLightSource(PassRefPtr<LightSource> lightSource)
{
m_lightSource = lightSource;
}
TextStream& FEDiffuseLighting::externalRepresentation(TextStream& ts, int indent) const
{
writeIndent(ts, indent);
ts << "[feDiffuseLighting";
FilterEffect::externalRepresentation(ts);
ts << " surfaceScale=\"" << m_surfaceScale << "\" " << "diffuseConstant=\"" << m_diffuseConstant << "\"]\n";
inputEffect(0)->externalRepresentation(ts, indent + 1);
return ts;
}
} // namespace blink
| Workday/OpenFrame | third_party/WebKit/Source/platform/graphics/filters/FEDiffuseLighting.cpp | C++ | bsd-3-clause | 3,336 |
<?php
// Version: 2.0; ManageMembers
global $context;
$txt['groups'] = 'Groups';
$txt['viewing_groups'] = 'Viewing Membergroups';
$txt['membergroups_title'] = 'Manage Membergroups';
$txt['membergroups_description'] = 'Membergroups are groups of members that have similar permission settings, appearance, or access rights. Some membergroups are based on the amount of posts a user has made. You can assign someone to a membergroup by selecting their profile and changing their account settings.';
$txt['membergroups_modify'] = 'Modify';
$txt['membergroups_add_group'] = 'Add group';
$txt['membergroups_regular'] = 'Regular groups';
$txt['membergroups_post'] = 'Post count based groups';
$txt['membergroups_group_name'] = 'Membergroup name';
$txt['membergroups_new_board'] = 'Visible Boards';
$txt['membergroups_new_board_desc'] = 'Boards the membergroup can see';
$txt['membergroups_new_board_post_groups'] = '<em>Note: normally, post groups don\'t need access because the group the member is in will give them access.</em>';
$txt['membergroups_new_as_inherit'] = 'inherit from';
$txt['membergroups_new_as_type'] = 'by type';
$txt['membergroups_new_as_copy'] = 'based off of';
$txt['membergroups_new_copy_none'] = '(none)';
$txt['membergroups_can_edit_later'] = 'You can edit them later.';
$txt['membergroups_edit_group'] = 'Edit Membergroup';
$txt['membergroups_edit_name'] = 'Group name';
$txt['membergroups_edit_inherit_permissions'] = 'Inherit Permissions';
$txt['membergroups_edit_inherit_permissions_desc'] = 'Select "No" to enable group to have own permission set.';
$txt['membergroups_edit_inherit_permissions_no'] = 'No - Use Unique Permissions';
$txt['membergroups_edit_inherit_permissions_from'] = 'Inherit From';
$txt['membergroups_edit_hidden'] = 'Visibility';
$txt['membergroups_edit_hidden_no'] = 'Visible';
$txt['membergroups_edit_hidden_boardindex'] = 'Visible - Except in Group Key';
$txt['membergroups_edit_hidden_all'] = 'Invisible';
// Do not use numeric entities in the below string.
$txt['membergroups_edit_hidden_warning'] = 'Are you sure you want to disallow assignment of this group as a users primary group?\\n\\nDoing so will restrict assignment to additional groups only, and will update all current "primary" members to have it as an additional group only.';
$txt['membergroups_edit_desc'] = 'Group description';
$txt['membergroups_edit_group_type'] = 'Group Type';
$txt['membergroups_edit_select_group_type'] = 'Select Group Type';
$txt['membergroups_group_type_private'] = 'Private <span class="smalltext">(Membership must be assigned)</span>';
$txt['membergroups_group_type_protected'] = 'Protected <span class="smalltext">(Only administrators can manage and assign)</span>';
$txt['membergroups_group_type_request'] = 'Requestable <span class="smalltext">(User may request membership)</span>';
$txt['membergroups_group_type_free'] = 'Free <span class="smalltext">(User may leave and join group at will)</span>';
$txt['membergroups_group_type_post'] = 'Post Based <span class="smalltext">(Membership based on post count)</span>';
$txt['membergroups_min_posts'] = 'Required posts';
$txt['membergroups_online_color'] = 'Color in online list';
$txt['membergroups_star_count'] = 'Number of star images';
$txt['membergroups_star_image'] = 'Star image filename';
$txt['membergroups_star_image_note'] = 'you can use $language for the language of the user';
$txt['membergroups_max_messages'] = 'Max personal messages';
$txt['membergroups_max_messages_note'] = '0 = unlimited';
$txt['membergroups_edit_save'] = 'Save';
$txt['membergroups_delete'] = 'Delete';
$txt['membergroups_confirm_delete'] = 'Are you sure you want to delete this group?!';
$txt['membergroups_members_title'] = 'Viewing Group';
$txt['membergroups_members_group_members'] = 'Group Members';
$txt['membergroups_members_no_members'] = 'This group is currently empty';
$txt['membergroups_members_add_title'] = 'Add a member to this group';
$txt['membergroups_members_add_desc'] = 'List of Members to Add';
$txt['membergroups_members_add'] = 'Add Members';
$txt['membergroups_members_remove'] = 'Remove from Group';
$txt['membergroups_members_last_active'] = 'Last Active';
$txt['membergroups_members_additional_only'] = 'Add as additional group only.';
$txt['membergroups_members_group_moderators'] = 'Group Moderators';
$txt['membergroups_members_description'] = 'Description';
// Use javascript escaping in the below.
$txt['membergroups_members_deadmin_confirm'] = 'Are you sure you wish to remove yourself from the Administration group?';
$txt['membergroups_postgroups'] = 'Post groups';
$txt['membergroups_settings'] = 'Membergroup Settings';
$txt['groups_manage_membergroups'] = 'Groups allowed to change membergroups';
$txt['membergroups_select_permission_type'] = 'Select permission profile';
$txt['membergroups_images_url'] = '{theme URL}/images/';
$txt['membergroups_select_visible_boards'] = 'Show boards';
$txt['membergroups_members_top'] = 'Members';
$txt['membergroups_name'] = 'Name';
$txt['membergroups_stars'] = 'Stars';
$txt['admin_browse_approve'] = 'Members whose accounts are awaiting approval';
$txt['admin_browse_approve_desc'] = 'From here you can manage all members who are waiting to have their accounts approved.';
$txt['admin_browse_activate'] = 'Members whose accounts are awaiting activation';
$txt['admin_browse_activate_desc'] = 'This screen lists all the members who have still not activated their accounts at your forum.';
$txt['admin_browse_awaiting_approval'] = 'Awaiting Approval (%1$d)';
$txt['admin_browse_awaiting_activate'] = 'Awaiting Activation (%1$d)';
$txt['admin_browse_username'] = 'Username';
$txt['admin_browse_email'] = 'Email Address';
$txt['admin_browse_ip'] = 'IP Address';
$txt['admin_browse_registered'] = 'Registered';
$txt['admin_browse_id'] = 'ID';
$txt['admin_browse_with_selected'] = 'With Selected';
$txt['admin_browse_no_members_approval'] = 'No members currently await approval.';
$txt['admin_browse_no_members_activate'] = 'No members currently have not activated their accounts.';
// Don't use entities in the below strings, except the main ones. (lt, gt, quot.)
$txt['admin_browse_warn'] = 'all selected members?';
$txt['admin_browse_outstanding_warn'] = 'all affected members?';
$txt['admin_browse_w_approve'] = 'Approve';
$txt['admin_browse_w_activate'] = 'Activate';
$txt['admin_browse_w_delete'] = 'Delete';
$txt['admin_browse_w_reject'] = 'Reject';
$txt['admin_browse_w_remind'] = 'Remind';
$txt['admin_browse_w_approve_deletion'] = 'Approve (Delete Accounts)';
$txt['admin_browse_w_email'] = 'and send email';
$txt['admin_browse_w_approve_require_activate'] = 'Approve and Require Activation';
$txt['admin_browse_filter_by'] = 'Filter By';
$txt['admin_browse_filter_show'] = 'Displaying';
$txt['admin_browse_filter_type_0'] = 'Unactivated New Accounts';
$txt['admin_browse_filter_type_2'] = 'Unactivated Email Changes';
$txt['admin_browse_filter_type_3'] = 'Unapproved New Accounts';
$txt['admin_browse_filter_type_4'] = 'Unapproved Account Deletions';
$txt['admin_browse_filter_type_5'] = 'Unapproved "Under Age" Accounts';
$txt['admin_browse_outstanding'] = 'Outstanding Members';
$txt['admin_browse_outstanding_days_1'] = 'With all members who registered longer than';
$txt['admin_browse_outstanding_days_2'] = 'days ago';
$txt['admin_browse_outstanding_perform'] = 'Perform the following action';
$txt['admin_browse_outstanding_go'] = 'Perform Action';
$txt['check_for_duplicate'] = 'Check for Duplicates';
$txt['dont_check_for_duplicate'] = 'Don\'t Check for Duplicates';
$txt['duplicates'] = 'Duplicates';
$txt['not_activated'] = 'Not activated';
?> | Karpec/gizd | smf/Themes/default/languages/ManageMembers.english.php | PHP | bsd-3-clause | 7,650 |
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import {createElementWithClassName} from 'chrome://resources/js/util.m.js';
/**
* Create by |LineChart.LineChart|.
* Create a dummy scrollbar to show the position of the line chart and to scroll
* the line chart, so we can draw the visible part of the line chart only
* instead of drawing the whole chart.
* @const
*/
export class Scrollbar {
constructor(/** function(): undefined */ callback) {
/** @const {function(): undefined} - Handle the scrolling event. */
this.callback_ = callback;
/** @type {number} - The range the scrollbar can scroll. */
this.range_ = 0;
/** @type {number} - The current position of the scrollbar. */
this.position_ = 0;
/** @type {number} - The real width of this scrollbar, in pixels. */
this.width_ = 0;
/** @type {Element} - The outer div to show the scrollbar. */
this.outerDiv_ =
createElementWithClassName('div', 'horizontal-scrollbar-outer');
this.outerDiv_.addEventListener('scroll', this.onScroll_.bind(this));
/** @type {Element} - The inner div to make outer div scrollable. */
this.innerDiv_ =
createElementWithClassName('div', 'horizontal-scrollbar-inner');
this.outerDiv_.appendChild(this.innerDiv_);
}
/**
* Scrolling event handler.
*/
onScroll_() {
const /** number */ newPosition = this.outerDiv_.scrollLeft;
if (newPosition == this.position_)
return;
this.position_ = newPosition;
this.callback_();
}
/** @return {Element} */
getRootDiv() {
return this.outerDiv_;
}
/**
* Return the height of scrollbar element.
* @return {number}
*/
getHeight() {
return this.outerDiv_.offsetHeight;
}
/** @return {number} */
getRange() {
return this.range_;
}
/**
* Position may be float point number because |document.scrollLeft| may be
* float point number.
* @return {number}
*/
getPosition() {
return Math.round(this.position_);
}
/**
* Change the size of the outer div and update the scrollbar position.
* @param {number} width
*/
resize(width) {
if (this.width_ == width)
return;
this.width_ = width;
this.updateOuterDivWidth_();
}
updateOuterDivWidth_() {
this.constructor.setNodeWidth(this.outerDiv_, this.width_);
}
/**
* Set the scrollable range to |range|. Use the inner div's width to control
* the scrollable range. If position go out of range after range update, set
* it to the boundary value.
* @param {number} range
*/
setRange(range) {
this.range_ = range;
this.updateInnerDivWidth_();
if (range < this.position_) {
this.position_ = range;
this.updateScrollbarPosition_();
}
}
updateInnerDivWidth_() {
const width = this.outerDiv_.clientWidth;
this.constructor.setNodeWidth(this.innerDiv_, width + this.range_);
}
/**
* @param {Element} node
* @param {number} width
*/
static setNodeWidth(node, width) {
node.style.width = width + 'px';
}
/**
* Set the scrollbar position to |position|. If the new position go out of
* range, set it to the boundary value.
* @param {number} position
*/
setPosition(position) {
const /** number */ newPosition =
Math.max(0, Math.min(position, this.range_));
this.position_ = newPosition;
this.updateScrollbarPosition_();
}
/**
* Update the scrollbar position via Javascript scrollbar api. Position may
* not be the same value as what we assigned even if the value is in the
* range. See crbug.com/760425.
*/
updateScrollbarPosition_() {
if (this.outerDiv_.scrollLeft == this.position_)
return;
this.outerDiv_.scrollLeft = this.position_;
}
/**
* Return true if scrollbar is at the right edge of the chart.
* @return {boolean}
*/
isScrolledToRightEdge() {
/* |scrollLeft| may become a float point number even if we set it to some
* integer value. If the distance to the right edge less than 2 pixels, we
* consider that it is scrolled to the right edge.
*/
const scrollLeftErrorAmount = 2;
return this.position_ + scrollLeftErrorAmount > this.range_;
}
/**
* Scroll the scrollbar to the right edge.
*/
scrollToRightEdge() {
this.setPosition(this.range_);
}
}
| chromium/chromium | chrome/browser/resources/chromeos/sys_internals/line_chart/scrollbar.js | JavaScript | bsd-3-clause | 4,454 |
/*
* Copyright (c) 2013 Michael Berlin, Zuse Institute Berlin
*
* Licensed under the BSD License, see LICENSE file for details.
*
*/
package org.xtreemfs.test.osd.rwre;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;
import org.xtreemfs.osd.storage.HashStorageLayout;
import org.xtreemfs.osd.storage.MetadataCache;
import org.xtreemfs.test.SetupUtils;
import org.xtreemfs.test.TestHelper;
public class FixWrongMasterEpochDirectoryTest {
@Rule
public final TestRule testLog = TestHelper.testLog;
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception {
}
@Test
public void testAutomaticMoveToCorrectDirectory() throws IOException {
final String globalFileId = "f32b0854-91eb-44d8-adf8-65bb8baf5f60:13193";
final String correctedFileId = globalFileId;
final String brokenFileId = "/" + correctedFileId;
final HashStorageLayout hsl = new HashStorageLayout(SetupUtils.createOSD1Config(), new MetadataCache());
// Cleanup previous runs.
hsl.deleteFile(brokenFileId, true);
hsl.deleteFile(correctedFileId, true);
final File brokenFileDir = new File(hsl.generateAbsoluteFilePath(brokenFileId));
final File correctedFileDir = new File(hsl.generateAbsoluteFilePath(correctedFileId));
// Set masterepoch using the wrong id.
assertFalse(brokenFileDir.isDirectory());
assertFalse(correctedFileDir.isDirectory());
hsl.setMasterEpoch(brokenFileId, 1);
assertTrue(brokenFileDir.isDirectory());
// Get the masterepoch with the correct id.
assertEquals(1, hsl.getMasterEpoch(correctedFileId));
assertFalse(brokenFileDir.isDirectory());
assertTrue(correctedFileDir.isDirectory());
// Get the masterepoch of a file which does not exist.
assertEquals(0, hsl.getMasterEpoch("fileIdDoesNotExist"));
}
}
| jswrenn/xtreemfs | java/servers/test/org/xtreemfs/test/osd/rwre/FixWrongMasterEpochDirectoryTest.java | Java | bsd-3-clause | 2,315 |
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of Intel Corporation may not 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 Intel Corporation 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.
//
//M*/
#include "precomp.hpp"
/****************************************************************************************\
* K-Nearest Neighbors Classifier *
\****************************************************************************************/
// k Nearest Neighbors
CvKNearest::CvKNearest()
{
samples = 0;
clear();
}
CvKNearest::~CvKNearest()
{
clear();
}
CvKNearest::CvKNearest( const CvMat* _train_data, const CvMat* _responses,
const CvMat* _sample_idx, bool _is_regression, int _max_k )
{
samples = 0;
train( _train_data, _responses, _sample_idx, _is_regression, _max_k, false );
}
void CvKNearest::clear()
{
while( samples )
{
CvVectors* next_samples = samples->next;
cvFree( &samples->data.fl );
cvFree( &samples );
samples = next_samples;
}
var_count = 0;
total = 0;
max_k = 0;
}
int CvKNearest::get_max_k() const { return max_k; }
int CvKNearest::get_var_count() const { return var_count; }
bool CvKNearest::is_regression() const { return regression; }
int CvKNearest::get_sample_count() const { return total; }
bool CvKNearest::train( const CvMat* _train_data, const CvMat* _responses,
const CvMat* _sample_idx, bool _is_regression,
int _max_k, bool _update_base )
{
bool ok = false;
CvMat* responses = 0;
CV_FUNCNAME( "CvKNearest::train" );
__BEGIN__;
CvVectors* _samples = 0;
float** _data = 0;
int _count = 0, _dims = 0, _dims_all = 0, _rsize = 0;
if( !_update_base )
clear();
// Prepare training data and related parameters.
// Treat categorical responses as ordered - to prevent class label compression and
// to enable entering new classes in the updates
CV_CALL( cvPrepareTrainData( "CvKNearest::train", _train_data, CV_ROW_SAMPLE,
_responses, CV_VAR_ORDERED, 0, _sample_idx, true, (const float***)&_data,
&_count, &_dims, &_dims_all, &responses, 0, 0 ));
if( !responses )
CV_ERROR( CV_StsNoMem, "Could not allocate memory for responses" );
if( _update_base && _dims != var_count )
CV_ERROR( CV_StsBadArg, "The newly added data have different dimensionality" );
if( !_update_base )
{
if( _max_k < 1 )
CV_ERROR( CV_StsOutOfRange, "max_k must be a positive number" );
regression = _is_regression;
var_count = _dims;
max_k = _max_k;
}
_rsize = _count*sizeof(float);
CV_CALL( _samples = (CvVectors*)cvAlloc( sizeof(*_samples) + _rsize ));
_samples->next = samples;
_samples->type = CV_32F;
_samples->data.fl = _data;
_samples->count = _count;
total += _count;
samples = _samples;
memcpy( _samples + 1, responses->data.fl, _rsize );
ok = true;
__END__;
if( responses && responses->data.ptr != _responses->data.ptr )
cvReleaseMat(&responses);
return ok;
}
void CvKNearest::find_neighbors_direct( const CvMat* _samples, int k, int start, int end,
float* neighbor_responses, const float** neighbors, float* dist ) const
{
int i, j, count = end - start, k1 = 0, k2 = 0, d = var_count;
CvVectors* s = samples;
for( ; s != 0; s = s->next )
{
int n = s->count;
for( j = 0; j < n; j++ )
{
for( i = 0; i < count; i++ )
{
double sum = 0;
Cv32suf si;
const float* v = s->data.fl[j];
const float* u = (float*)(_samples->data.ptr + _samples->step*(start + i));
Cv32suf* dd = (Cv32suf*)(dist + i*k);
float* nr;
const float** nn;
int t, ii, ii1;
for( t = 0; t <= d - 4; t += 4 )
{
double t0 = u[t] - v[t], t1 = u[t+1] - v[t+1];
double t2 = u[t+2] - v[t+2], t3 = u[t+3] - v[t+3];
sum += t0*t0 + t1*t1 + t2*t2 + t3*t3;
}
for( ; t < d; t++ )
{
double t0 = u[t] - v[t];
sum += t0*t0;
}
si.f = (float)sum;
for( ii = k1-1; ii >= 0; ii-- )
if( si.i > dd[ii].i )
break;
if( ii >= k-1 )
continue;
nr = neighbor_responses + i*k;
nn = neighbors ? neighbors + (start + i)*k : 0;
for( ii1 = k2 - 1; ii1 > ii; ii1-- )
{
dd[ii1+1].i = dd[ii1].i;
nr[ii1+1] = nr[ii1];
if( nn ) nn[ii1+1] = nn[ii1];
}
dd[ii+1].i = si.i;
nr[ii+1] = ((float*)(s + 1))[j];
if( nn )
nn[ii+1] = v;
}
k1 = MIN( k1+1, k );
k2 = MIN( k1, k-1 );
}
}
}
float CvKNearest::write_results( int k, int k1, int start, int end,
const float* neighbor_responses, const float* dist,
CvMat* _results, CvMat* _neighbor_responses,
CvMat* _dist, Cv32suf* sort_buf ) const
{
float result = 0.f;
int i, j, j1, count = end - start;
double inv_scale = 1./k1;
int rstep = _results && !CV_IS_MAT_CONT(_results->type) ? _results->step/sizeof(result) : 1;
for( i = 0; i < count; i++ )
{
const Cv32suf* nr = (const Cv32suf*)(neighbor_responses + i*k);
float* dst;
float r;
if( _results || start+i == 0 )
{
if( regression )
{
double s = 0;
for( j = 0; j < k1; j++ )
s += nr[j].f;
r = (float)(s*inv_scale);
}
else
{
int prev_start = 0, best_count = 0, cur_count;
Cv32suf best_val;
for( j = 0; j < k1; j++ )
sort_buf[j].i = nr[j].i;
for( j = k1-1; j > 0; j-- )
{
bool swap_fl = false;
for( j1 = 0; j1 < j; j1++ )
if( sort_buf[j1].i > sort_buf[j1+1].i )
{
int t;
CV_SWAP( sort_buf[j1].i, sort_buf[j1+1].i, t );
swap_fl = true;
}
if( !swap_fl )
break;
}
best_val.i = 0;
for( j = 1; j <= k1; j++ )
if( j == k1 || sort_buf[j].i != sort_buf[j-1].i )
{
cur_count = j - prev_start;
if( best_count < cur_count )
{
best_count = cur_count;
best_val.i = sort_buf[j-1].i;
}
prev_start = j;
}
r = best_val.f;
}
if( start+i == 0 )
result = r;
if( _results )
_results->data.fl[(start + i)*rstep] = r;
}
if( _neighbor_responses )
{
dst = (float*)(_neighbor_responses->data.ptr +
(start + i)*_neighbor_responses->step);
for( j = 0; j < k1; j++ )
dst[j] = nr[j].f;
for( ; j < k; j++ )
dst[j] = 0.f;
}
if( _dist )
{
dst = (float*)(_dist->data.ptr + (start + i)*_dist->step);
for( j = 0; j < k1; j++ )
dst[j] = dist[j + i*k];
for( ; j < k; j++ )
dst[j] = 0.f;
}
}
return result;
}
struct P1 : cv::ParallelLoopBody {
P1(const CvKNearest* _pointer, int _buf_sz, int _k, const CvMat* __samples, const float** __neighbors,
int _k1, CvMat* __results, CvMat* __neighbor_responses, CvMat* __dist, float* _result)
{
pointer = _pointer;
k = _k;
_samples = __samples;
_neighbors = __neighbors;
k1 = _k1;
_results = __results;
_neighbor_responses = __neighbor_responses;
_dist = __dist;
result = _result;
buf_sz = _buf_sz;
}
const CvKNearest* pointer;
int k;
const CvMat* _samples;
const float** _neighbors;
int k1;
CvMat* _results;
CvMat* _neighbor_responses;
CvMat* _dist;
float* result;
int buf_sz;
void operator()( const cv::Range& range ) const
{
cv::AutoBuffer<float> buf(buf_sz);
for(int i = range.start; i < range.end; i += 1 )
{
float* neighbor_responses = &buf[0];
float* dist = neighbor_responses + 1*k;
Cv32suf* sort_buf = (Cv32suf*)(dist + 1*k);
pointer->find_neighbors_direct( _samples, k, i, i + 1,
neighbor_responses, _neighbors, dist );
float r = pointer->write_results( k, k1, i, i + 1, neighbor_responses, dist,
_results, _neighbor_responses, _dist, sort_buf );
if( i == 0 )
*result = r;
}
}
};
float CvKNearest::find_nearest( const CvMat* _samples, int k, CvMat* _results,
const float** _neighbors, CvMat* _neighbor_responses, CvMat* _dist ) const
{
float result = 0.f;
const int max_blk_count = 128, max_buf_sz = 1 << 12;
if( !samples )
CV_Error( CV_StsError, "The search tree must be constructed first using train method" );
if( !CV_IS_MAT(_samples) ||
CV_MAT_TYPE(_samples->type) != CV_32FC1 ||
_samples->cols != var_count )
CV_Error( CV_StsBadArg, "Input samples must be floating-point matrix (<num_samples>x<var_count>)" );
if( _results && (!CV_IS_MAT(_results) ||
(_results->cols != 1 && _results->rows != 1) ||
_results->cols + _results->rows - 1 != _samples->rows) )
CV_Error( CV_StsBadArg,
"The results must be 1d vector containing as much elements as the number of samples" );
if( _results && CV_MAT_TYPE(_results->type) != CV_32FC1 &&
(CV_MAT_TYPE(_results->type) != CV_32SC1 || regression))
CV_Error( CV_StsUnsupportedFormat,
"The results must be floating-point or integer (in case of classification) vector" );
if( k < 1 || k > max_k )
CV_Error( CV_StsOutOfRange, "k must be within 1..max_k range" );
if( _neighbor_responses )
{
if( !CV_IS_MAT(_neighbor_responses) || CV_MAT_TYPE(_neighbor_responses->type) != CV_32FC1 ||
_neighbor_responses->rows != _samples->rows || _neighbor_responses->cols != k )
CV_Error( CV_StsBadArg,
"The neighbor responses (if present) must be floating-point matrix of <num_samples> x <k> size" );
}
if( _dist )
{
if( !CV_IS_MAT(_dist) || CV_MAT_TYPE(_dist->type) != CV_32FC1 ||
_dist->rows != _samples->rows || _dist->cols != k )
CV_Error( CV_StsBadArg,
"The distances from the neighbors (if present) must be floating-point matrix of <num_samples> x <k> size" );
}
int count = _samples->rows;
int count_scale = k*2;
int blk_count0 = MIN( count, max_blk_count );
int buf_sz = MIN( blk_count0 * count_scale, max_buf_sz );
blk_count0 = MAX( buf_sz/count_scale, 1 );
blk_count0 += blk_count0 % 2;
blk_count0 = MIN( blk_count0, count );
buf_sz = blk_count0 * count_scale + k;
int k1 = get_sample_count();
k1 = MIN( k1, k );
cv::parallel_for_(cv::Range(0, count), P1(this, buf_sz, k, _samples, _neighbors, k1,
_results, _neighbor_responses, _dist, &result)
);
return result;
}
using namespace cv;
CvKNearest::CvKNearest( const Mat& _train_data, const Mat& _responses,
const Mat& _sample_idx, bool _is_regression, int _max_k )
{
samples = 0;
train(_train_data, _responses, _sample_idx, _is_regression, _max_k, false );
}
bool CvKNearest::train( const Mat& _train_data, const Mat& _responses,
const Mat& _sample_idx, bool _is_regression,
int _max_k, bool _update_base )
{
CvMat tdata = _train_data, responses = _responses, sidx = _sample_idx;
return train(&tdata, &responses, sidx.data.ptr ? &sidx : 0, _is_regression, _max_k, _update_base );
}
float CvKNearest::find_nearest( const Mat& _samples, int k, Mat* _results,
const float** _neighbors, Mat* _neighbor_responses,
Mat* _dist ) const
{
CvMat s = _samples, results, *presults = 0, nresponses, *pnresponses = 0, dist, *pdist = 0;
if( _results )
{
if(!(_results->data && (_results->type() == CV_32F ||
(_results->type() == CV_32S && regression)) &&
(_results->cols == 1 || _results->rows == 1) &&
_results->cols + _results->rows - 1 == _samples.rows) )
_results->create(_samples.rows, 1, CV_32F);
presults = &(results = *_results);
}
if( _neighbor_responses )
{
if(!(_neighbor_responses->data && _neighbor_responses->type() == CV_32F &&
_neighbor_responses->cols == k && _neighbor_responses->rows == _samples.rows) )
_neighbor_responses->create(_samples.rows, k, CV_32F);
pnresponses = &(nresponses = *_neighbor_responses);
}
if( _dist )
{
if(!(_dist->data && _dist->type() == CV_32F &&
_dist->cols == k && _dist->rows == _samples.rows) )
_dist->create(_samples.rows, k, CV_32F);
pdist = &(dist = *_dist);
}
return find_nearest(&s, k, presults, _neighbors, pnresponses, pdist );
}
float CvKNearest::find_nearest( const cv::Mat& _samples, int k, CV_OUT cv::Mat& results,
CV_OUT cv::Mat& neighborResponses, CV_OUT cv::Mat& dists) const
{
return find_nearest(_samples, k, &results, 0, &neighborResponses, &dists);
}
/* End of file */
| grace-/opencv-3.0.0-cvpr | opencv/modules/ml/src/knearest.cpp | C++ | bsd-3-clause | 16,081 |
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import {
Context,
DocumentRegistry,
TextModelFactory
} from '@jupyterlab/docregistry';
import * as Mock from '@jupyterlab/testutils/lib/mock';
import { UUID } from '@lumino/coreutils';
import { CellRenderer, DataGrid, JSONModel } from '@lumino/datagrid';
import { CSVViewer, GridSearchService } from '../src';
function createContext(): Context<DocumentRegistry.IModel> {
const factory = new TextModelFactory();
const manager = new Mock.ServiceManagerMock();
const path = UUID.uuid4() + '.csv';
return new Context({ factory, manager, path });
}
describe('csvviewer/widget', () => {
const context = createContext();
describe('CSVViewer', () => {
describe('#constructor()', () => {
it('should instantiate a `CSVViewer`', () => {
const widget = new CSVViewer({ context });
expect(widget).toBeInstanceOf(CSVViewer);
widget.dispose();
});
});
describe('#context', () => {
it('should be the context for the file', () => {
const widget = new CSVViewer({ context });
expect(widget.context).toBe(context);
});
});
describe('#dispose()', () => {
it('should dispose of the resources held by the widget', () => {
const widget = new CSVViewer({ context });
expect(widget.isDisposed).toBe(false);
widget.dispose();
expect(widget.isDisposed).toBe(true);
});
it('should be safe to call multiple times', () => {
const widget = new CSVViewer({ context });
expect(widget.isDisposed).toBe(false);
widget.dispose();
widget.dispose();
expect(widget.isDisposed).toBe(true);
});
});
});
describe('GridSearchService', () => {
function createModel(): JSONModel {
return new JSONModel({
data: [
{ index: 0, a: 'other', b: 'match 1' },
{ index: 1, a: 'other', b: 'match 2' }
],
schema: {
primaryKey: ['index'],
fields: [
{
name: 'a'
},
{ name: 'b' }
]
}
});
}
function createGridSearchService(model: JSONModel): GridSearchService {
const grid = new DataGrid();
grid.dataModel = model;
return new GridSearchService(grid);
}
it('searches incrementally and set background color', () => {
const model = createModel();
const searchService = createGridSearchService(model);
const cellRenderer = searchService.cellBackgroundColorRendererFunc({
matchBackgroundColor: 'anotherMatch',
currentMatchBackgroundColor: 'currentMatch',
textColor: '',
horizontalAlignment: 'right'
});
/**
* fake rendering a cell and returns the background color for this coordinate.
*/
function fakeRenderCell(row: number, column: number) {
const cellConfig = {
value: model.data('body', row, column),
row,
column
} as CellRenderer.CellConfig;
return cellRenderer(cellConfig);
}
// searching for "match", cells at (0,1) and (1,1) should match.
// (0,1) is the current match
const query = /match/;
searchService.find(query);
expect(fakeRenderCell(0, 1)).toBe('currentMatch');
expect(fakeRenderCell(1, 1)).toBe('anotherMatch');
expect(fakeRenderCell(0, 0)).toBe('');
// search again, the current match "moves" to be (1,1)
searchService.find(query);
expect(fakeRenderCell(0, 1)).toBe('anotherMatch');
expect(fakeRenderCell(1, 1)).toBe('currentMatch');
});
});
});
| jupyter/jupyterlab | packages/csvviewer/test/widget.spec.ts | TypeScript | bsd-3-clause | 3,717 |
object Virt extends Application {
class Foo {
trait Inner <: { val x : Int = 3 }
}
class Bar extends Foo {
trait Inner <: { val y : Int = x }
}
}
| felixmulder/scala | test/pending/pos/virt.scala | Scala | bsd-3-clause | 165 |
//===-- ProcessRunLock.cpp ------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#ifndef _WIN32
#include "lldb/Host/ProcessRunLock.h"
namespace lldb_private {
ProcessRunLock::ProcessRunLock() : m_running(false) {
int err = ::pthread_rwlock_init(&m_rwlock, nullptr);
(void)err;
}
ProcessRunLock::~ProcessRunLock() {
int err = ::pthread_rwlock_destroy(&m_rwlock);
(void)err;
}
bool ProcessRunLock::ReadTryLock() {
::pthread_rwlock_rdlock(&m_rwlock);
if (!m_running) {
return true;
}
::pthread_rwlock_unlock(&m_rwlock);
return false;
}
bool ProcessRunLock::ReadUnlock() {
return ::pthread_rwlock_unlock(&m_rwlock) == 0;
}
bool ProcessRunLock::SetRunning() {
::pthread_rwlock_wrlock(&m_rwlock);
m_running = true;
::pthread_rwlock_unlock(&m_rwlock);
return true;
}
bool ProcessRunLock::TrySetRunning() {
bool r;
if (::pthread_rwlock_trywrlock(&m_rwlock) == 0) {
r = !m_running;
m_running = true;
::pthread_rwlock_unlock(&m_rwlock);
return r;
}
return false;
}
bool ProcessRunLock::SetStopped() {
::pthread_rwlock_wrlock(&m_rwlock);
m_running = false;
::pthread_rwlock_unlock(&m_rwlock);
return true;
}
}
#endif
| endlessm/chromium-browser | third_party/llvm/lldb/source/Host/common/ProcessRunLock.cpp | C++ | bsd-3-clause | 1,469 |
function safeMatchMedia(query) {
var m = window.matchMedia(query);
return !!m && m.matches;
}
define('capabilities', [], function() {
var capabilities = {
'JSON': window.JSON && typeof JSON.parse == 'function',
'debug': (('' + document.location).indexOf('dbg') >= 0),
'debug_in_page': (('' + document.location).indexOf('dbginpage') >= 0),
'console': window.console && (typeof window.console.log == 'function'),
'replaceState': typeof history.replaceState === 'function',
'chromeless': window.locationbar && !window.locationbar.visible,
'localStorage': false,
'sessionStorage': false,
'webApps': !!(navigator.mozApps && navigator.mozApps.install),
'app_runtime': !!(
navigator.mozApps &&
typeof navigator.mozApps.html5Implementation === 'undefined'
),
'fileAPI': !!window.FileReader,
'userAgent': navigator.userAgent,
'desktop': false,
'tablet': false,
'mobile': safeMatchMedia('(max-width: 600px)'),
'firefoxAndroid': (navigator.userAgent.indexOf('Firefox') != -1 && navigator.userAgent.indexOf('Android') != -1),
'touch': ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch,
'nativeScroll': (function() {
return 'WebkitOverflowScrolling' in document.createElement('div').style;
})(),
'performance': !!(window.performance || window.msPerformance || window.webkitPerformance || window.mozPerformance),
'navPay': !!navigator.mozPay,
'webactivities': !!(window.setMessageHandler || window.mozSetMessageHandler),
'firefoxOS': null // This is set below.
};
// We're probably tablet if we have touch and we're larger than mobile.
capabilities.tablet = capabilities.touch && safeMatchMedia('(min-width: 601px)');
// We're probably desktop if we don't have touch and we're larger than some arbitrary dimension.
capabilities.desktop = !capabilities.touch && safeMatchMedia('(min-width: 673px)');
// Packaged-app installation are supported only on Firefox OS, so this is how we sniff.
capabilities.gaia = !!(capabilities.mobile && navigator.mozApps && navigator.mozApps.installPackage);
capabilities.getDeviceType = function() {
return this.desktop ? 'desktop' : (this.tablet ? 'tablet' : 'mobile');
};
if (capabilities.tablet) {
// If we're on tablet, then we're not on desktop.
capabilities.desktop = false;
}
if (capabilities.mobile) {
// If we're on mobile, then we're not on desktop nor tablet.
capabilities.desktop = capabilities.tablet = false;
}
// Detect Firefox OS.
// This will be true if the request is from a Firefox OS phone *or*
// a desktop B2G build with the correct UA pref, such as this:
// https://github.com/mozilla/r2d2b2g/blob/master/prosthesis/defaults/preferences/prefs.js
capabilities.firefoxOS = capabilities.gaia && !capabilities.firefoxAndroid;
try {
if ('localStorage' in window && window.localStorage !== null) {
capabilities.localStorage = true;
}
} catch (e) {
}
try {
if ('sessionStorage' in window && window.sessionStorage !== null) {
capabilities.sessionStorage = true;
}
} catch (e) {
}
return capabilities;
});
z.capabilities = require('capabilities');
| Joergen/zamboni | media/js/mkt/capabilities.js | JavaScript | bsd-3-clause | 3,467 |
// 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.
#include "tools/gn/ninja_target_writer.h"
#include <sstream>
#include "base/files/file_util.h"
#include "base/strings/string_util.h"
#include "tools/gn/err.h"
#include "tools/gn/filesystem_utils.h"
#include "tools/gn/ninja_action_target_writer.h"
#include "tools/gn/ninja_binary_target_writer.h"
#include "tools/gn/ninja_copy_target_writer.h"
#include "tools/gn/ninja_group_target_writer.h"
#include "tools/gn/ninja_utils.h"
#include "tools/gn/output_file.h"
#include "tools/gn/scheduler.h"
#include "tools/gn/string_utils.h"
#include "tools/gn/substitution_writer.h"
#include "tools/gn/target.h"
#include "tools/gn/trace.h"
NinjaTargetWriter::NinjaTargetWriter(const Target* target,
std::ostream& out)
: settings_(target->settings()),
target_(target),
out_(out),
path_output_(settings_->build_settings()->build_dir(),
settings_->build_settings()->root_path_utf8(),
ESCAPE_NINJA) {
}
NinjaTargetWriter::~NinjaTargetWriter() {
}
// static
void NinjaTargetWriter::RunAndWriteFile(const Target* target) {
const Settings* settings = target->settings();
ScopedTrace trace(TraceItem::TRACE_FILE_WRITE,
target->label().GetUserVisibleName(false));
trace.SetToolchain(settings->toolchain_label());
base::FilePath ninja_file(settings->build_settings()->GetFullPath(
GetNinjaFileForTarget(target)));
if (g_scheduler->verbose_logging())
g_scheduler->Log("Writing", FilePathToUTF8(ninja_file));
base::CreateDirectory(ninja_file.DirName());
// It's rediculously faster to write to a string and then write that to
// disk in one operation than to use an fstream here.
std::stringstream file;
// Call out to the correct sub-type of writer.
if (target->output_type() == Target::COPY_FILES) {
NinjaCopyTargetWriter writer(target, file);
writer.Run();
} else if (target->output_type() == Target::ACTION ||
target->output_type() == Target::ACTION_FOREACH) {
NinjaActionTargetWriter writer(target, file);
writer.Run();
} else if (target->output_type() == Target::GROUP) {
NinjaGroupTargetWriter writer(target, file);
writer.Run();
} else if (target->output_type() == Target::EXECUTABLE ||
target->output_type() == Target::STATIC_LIBRARY ||
target->output_type() == Target::SHARED_LIBRARY ||
target->output_type() == Target::SOURCE_SET) {
NinjaBinaryTargetWriter writer(target, file);
writer.Run();
} else {
CHECK(0);
}
std::string contents = file.str();
base::WriteFile(ninja_file, contents.c_str(),
static_cast<int>(contents.size()));
}
void NinjaTargetWriter::WriteSharedVars(const SubstitutionBits& bits) {
bool written_anything = false;
// Target label.
if (bits.used[SUBSTITUTION_LABEL]) {
out_ << kSubstitutionNinjaNames[SUBSTITUTION_LABEL] << " = "
<< SubstitutionWriter::GetTargetSubstitution(
target_, SUBSTITUTION_LABEL)
<< std::endl;
written_anything = true;
}
// Root gen dir.
if (bits.used[SUBSTITUTION_ROOT_GEN_DIR]) {
out_ << kSubstitutionNinjaNames[SUBSTITUTION_ROOT_GEN_DIR] << " = "
<< SubstitutionWriter::GetTargetSubstitution(
target_, SUBSTITUTION_ROOT_GEN_DIR)
<< std::endl;
written_anything = true;
}
// Root out dir.
if (bits.used[SUBSTITUTION_ROOT_OUT_DIR]) {
out_ << kSubstitutionNinjaNames[SUBSTITUTION_ROOT_OUT_DIR] << " = "
<< SubstitutionWriter::GetTargetSubstitution(
target_, SUBSTITUTION_ROOT_OUT_DIR)
<< std::endl;
written_anything = true;
}
// Target gen dir.
if (bits.used[SUBSTITUTION_TARGET_GEN_DIR]) {
out_ << kSubstitutionNinjaNames[SUBSTITUTION_TARGET_GEN_DIR] << " = "
<< SubstitutionWriter::GetTargetSubstitution(
target_, SUBSTITUTION_TARGET_GEN_DIR)
<< std::endl;
written_anything = true;
}
// Target out dir.
if (bits.used[SUBSTITUTION_TARGET_OUT_DIR]) {
out_ << kSubstitutionNinjaNames[SUBSTITUTION_TARGET_OUT_DIR] << " = "
<< SubstitutionWriter::GetTargetSubstitution(
target_, SUBSTITUTION_TARGET_OUT_DIR)
<< std::endl;
written_anything = true;
}
// Target output name.
if (bits.used[SUBSTITUTION_TARGET_OUTPUT_NAME]) {
out_ << kSubstitutionNinjaNames[SUBSTITUTION_TARGET_OUTPUT_NAME] << " = "
<< SubstitutionWriter::GetTargetSubstitution(
target_, SUBSTITUTION_TARGET_OUTPUT_NAME)
<< std::endl;
written_anything = true;
}
// If we wrote any vars, separate them from the rest of the file that follows
// with a blank line.
if (written_anything)
out_ << std::endl;
}
OutputFile NinjaTargetWriter::WriteInputDepsStampAndGetDep(
const std::vector<const Target*>& extra_hard_deps) const {
CHECK(target_->toolchain())
<< "Toolchain not set on target "
<< target_->label().GetUserVisibleName(true);
// For an action (where we run a script only once) the sources are the same
// as the source prereqs.
bool list_sources_as_input_deps = (target_->output_type() == Target::ACTION);
// Actions get implicit dependencies on the script itself.
bool add_script_source_as_dep =
(target_->output_type() == Target::ACTION) ||
(target_->output_type() == Target::ACTION_FOREACH);
if (!add_script_source_as_dep &&
extra_hard_deps.empty() &&
target_->inputs().empty() &&
target_->recursive_hard_deps().empty() &&
(!list_sources_as_input_deps || target_->sources().empty()) &&
target_->toolchain()->deps().empty())
return OutputFile(); // No input/hard deps.
// One potential optimization is if there are few input dependencies (or
// potentially few sources that depend on these) it's better to just write
// all hard deps on each sources line than have this intermediate stamp. We
// do the stamp file because duplicating all the order-only deps for each
// source file can really explode the ninja file but this won't be the most
// optimal thing in all cases.
OutputFile input_stamp_file(
RebasePath(GetTargetOutputDir(target_).value(),
settings_->build_settings()->build_dir(),
settings_->build_settings()->root_path_utf8()));
input_stamp_file.value().append(target_->label().name());
input_stamp_file.value().append(".inputdeps.stamp");
out_ << "build ";
path_output_.WriteFile(out_, input_stamp_file);
out_ << ": "
<< GetNinjaRulePrefixForToolchain(settings_)
<< Toolchain::ToolTypeToName(Toolchain::TYPE_STAMP);
// Script file (if applicable).
if (add_script_source_as_dep) {
out_ << " ";
path_output_.WriteFile(out_, target_->action_values().script());
}
// Input files are order-only deps.
for (const auto& input : target_->inputs()) {
out_ << " ";
path_output_.WriteFile(out_, input);
}
if (list_sources_as_input_deps) {
for (const auto& source : target_->sources()) {
out_ << " ";
path_output_.WriteFile(out_, source);
}
}
// The different souces of input deps may duplicate some targets, so uniquify
// them (ordering doesn't matter for this case).
std::set<const Target*> unique_deps;
// Hard dependencies that are direct or indirect dependencies.
const std::set<const Target*>& hard_deps = target_->recursive_hard_deps();
for (const auto& dep : hard_deps)
unique_deps.insert(dep);
// Extra hard dependencies passed in.
unique_deps.insert(extra_hard_deps.begin(), extra_hard_deps.end());
// Toolchain dependencies. These must be resolved before doing anything.
// This just writs all toolchain deps for simplicity. If we find that
// toolchains often have more than one dependency, we could consider writing
// a toolchain-specific stamp file and only include the stamp here.
const LabelTargetVector& toolchain_deps = target_->toolchain()->deps();
for (const auto& toolchain_dep : toolchain_deps)
unique_deps.insert(toolchain_dep.ptr);
for (const auto& dep : unique_deps) {
DCHECK(!dep->dependency_output_file().value().empty());
out_ << " ";
path_output_.WriteFile(out_, dep->dependency_output_file());
}
out_ << "\n";
return input_stamp_file;
}
void NinjaTargetWriter::WriteStampForTarget(
const std::vector<OutputFile>& files,
const std::vector<OutputFile>& order_only_deps) {
const OutputFile& stamp_file = target_->dependency_output_file();
// First validate that the target's dependency is a stamp file. Otherwise,
// we shouldn't have gotten here!
CHECK(base::EndsWith(stamp_file.value(), ".stamp", false))
<< "Output should end in \".stamp\" for stamp file output. Instead got: "
<< "\"" << stamp_file.value() << "\"";
out_ << "build ";
path_output_.WriteFile(out_, stamp_file);
out_ << ": "
<< GetNinjaRulePrefixForToolchain(settings_)
<< Toolchain::ToolTypeToName(Toolchain::TYPE_STAMP);
path_output_.WriteFiles(out_, files);
if (!order_only_deps.empty()) {
out_ << " ||";
path_output_.WriteFiles(out_, order_only_deps);
}
out_ << std::endl;
}
| SaschaMester/delicium | tools/gn/ninja_target_writer.cc | C++ | bsd-3-clause | 9,381 |
/*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkTileImageFilter.h"
#include "SkColorSpaceXformer.h"
#include "SkCanvas.h"
#include "SkImage.h"
#include "SkImageFilterPriv.h"
#include "SkMatrix.h"
#include "SkOffsetImageFilter.h"
#include "SkPaint.h"
#include "SkReadBuffer.h"
#include "SkShader.h"
#include "SkSpecialImage.h"
#include "SkSpecialSurface.h"
#include "SkSurface.h"
#include "SkValidationUtils.h"
#include "SkWriteBuffer.h"
sk_sp<SkImageFilter> SkTileImageFilter::Make(const SkRect& srcRect, const SkRect& dstRect,
sk_sp<SkImageFilter> input) {
if (!SkIsValidRect(srcRect) || !SkIsValidRect(dstRect)) {
return nullptr;
}
if (srcRect.width() == dstRect.width() && srcRect.height() == dstRect.height()) {
SkRect ir = dstRect;
if (!ir.intersect(srcRect)) {
return input;
}
CropRect cropRect(ir);
return SkOffsetImageFilter::Make(dstRect.x() - srcRect.x(),
dstRect.y() - srcRect.y(),
std::move(input),
&cropRect);
}
return sk_sp<SkImageFilter>(new SkTileImageFilter(srcRect, dstRect, std::move(input)));
}
sk_sp<SkSpecialImage> SkTileImageFilter::onFilterImage(SkSpecialImage* source,
const Context& ctx,
SkIPoint* offset) const {
SkIPoint inputOffset = SkIPoint::Make(0, 0);
sk_sp<SkSpecialImage> input(this->filterInput(0, source, ctx, &inputOffset));
if (!input) {
return nullptr;
}
SkRect dstRect;
ctx.ctm().mapRect(&dstRect, fDstRect);
if (!dstRect.intersect(SkRect::Make(ctx.clipBounds()))) {
return nullptr;
}
const SkIRect dstIRect = dstRect.roundOut();
if (!fSrcRect.width() || !fSrcRect.height() || !dstIRect.width() || !dstIRect.height()) {
return nullptr;
}
SkRect srcRect;
ctx.ctm().mapRect(&srcRect, fSrcRect);
SkIRect srcIRect;
srcRect.roundOut(&srcIRect);
srcIRect.offset(-inputOffset);
const SkIRect inputBounds = SkIRect::MakeWH(input->width(), input->height());
if (!SkIRect::Intersects(srcIRect, inputBounds)) {
return nullptr;
}
// We create an SkImage here b.c. it needs to be a tight fit for the tiling
sk_sp<SkImage> subset;
if (inputBounds.contains(srcIRect)) {
subset = input->asImage(&srcIRect);
} else {
sk_sp<SkSurface> surf(input->makeTightSurface(ctx.outputProperties(), srcIRect.size()));
if (!surf) {
return nullptr;
}
SkCanvas* canvas = surf->getCanvas();
SkASSERT(canvas);
SkPaint paint;
paint.setBlendMode(SkBlendMode::kSrc);
input->draw(canvas,
SkIntToScalar(inputOffset.x()), SkIntToScalar(inputOffset.y()),
&paint);
subset = surf->makeImageSnapshot();
}
if (!subset) {
return nullptr;
}
SkASSERT(subset->width() == srcIRect.width());
SkASSERT(subset->height() == srcIRect.height());
sk_sp<SkSpecialSurface> surf(source->makeSurface(ctx.outputProperties(), dstIRect.size()));
if (!surf) {
return nullptr;
}
SkCanvas* canvas = surf->getCanvas();
SkASSERT(canvas);
SkPaint paint;
paint.setBlendMode(SkBlendMode::kSrc);
paint.setShader(subset->makeShader(SkShader::kRepeat_TileMode, SkShader::kRepeat_TileMode));
canvas->translate(-dstRect.fLeft, -dstRect.fTop);
canvas->drawRect(dstRect, paint);
offset->fX = dstIRect.fLeft;
offset->fY = dstIRect.fTop;
return surf->makeImageSnapshot();
}
sk_sp<SkImageFilter> SkTileImageFilter::onMakeColorSpace(SkColorSpaceXformer* xformer) const {
SkASSERT(1 == this->countInputs());
auto input = xformer->apply(this->getInput(0));
if (input.get() != this->getInput(0)) {
return SkTileImageFilter::Make(fSrcRect, fDstRect, std::move(input));
}
return this->refMe();
}
SkIRect SkTileImageFilter::onFilterNodeBounds(const SkIRect& src, const SkMatrix& ctm,
MapDirection dir, const SkIRect* inputRect) const {
SkRect rect = kReverse_MapDirection == dir ? fSrcRect : fDstRect;
ctm.mapRect(&rect);
return rect.roundOut();
}
SkIRect SkTileImageFilter::onFilterBounds(const SkIRect& src, const SkMatrix&,
MapDirection, const SkIRect* inputRect) const {
// Don't recurse into inputs.
return src;
}
SkRect SkTileImageFilter::computeFastBounds(const SkRect& src) const {
return fDstRect;
}
sk_sp<SkFlattenable> SkTileImageFilter::CreateProc(SkReadBuffer& buffer) {
SK_IMAGEFILTER_UNFLATTEN_COMMON(common, 1);
SkRect src, dst;
buffer.readRect(&src);
buffer.readRect(&dst);
return Make(src, dst, common.getInput(0));
}
void SkTileImageFilter::flatten(SkWriteBuffer& buffer) const {
this->INHERITED::flatten(buffer);
buffer.writeRect(fSrcRect);
buffer.writeRect(fDstRect);
}
| Hikari-no-Tenshi/android_external_skia | src/effects/imagefilters/SkTileImageFilter.cpp | C++ | bsd-3-clause | 5,247 |
from __future__ import unicode_literals
from django.core.exceptions import PermissionDenied
from django.core.mail import send_mail
from django.core import validators
from django.db import models
from django.db.models.manager import EmptyManager
from django.utils.crypto import get_random_string, salted_hmac
from django.utils import six
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from django.contrib import auth
from django.contrib.auth.hashers import (
check_password, make_password, is_password_usable)
from django.contrib.auth.signals import user_logged_in
from django.contrib.contenttypes.models import ContentType
from django.utils.encoding import python_2_unicode_compatible
def update_last_login(sender, user, **kwargs):
"""
A signal receiver which updates the last_login date for
the user logging in.
"""
user.last_login = timezone.now()
user.save(update_fields=['last_login'])
user_logged_in.connect(update_last_login)
class PermissionManager(models.Manager):
def get_by_natural_key(self, codename, app_label, model):
return self.get(
codename=codename,
content_type=ContentType.objects.db_manager(self.db).get_by_natural_key(app_label, model),
)
@python_2_unicode_compatible
class Permission(models.Model):
"""
The permissions system provides a way to assign permissions to specific
users and groups of users.
The permission system is used by the Django admin site, but may also be
useful in your own code. The Django admin site uses permissions as follows:
- The "add" permission limits the user's ability to view the "add" form
and add an object.
- The "change" permission limits a user's ability to view the change
list, view the "change" form and change an object.
- The "delete" permission limits the ability to delete an object.
Permissions are set globally per type of object, not per specific object
instance. It is possible to say "Mary may change news stories," but it's
not currently possible to say "Mary may change news stories, but only the
ones she created herself" or "Mary may only change news stories that have a
certain status or publication date."
Three basic permissions -- add, change and delete -- are automatically
created for each Django model.
"""
name = models.CharField(_('name'), max_length=255)
content_type = models.ForeignKey(ContentType)
codename = models.CharField(_('codename'), max_length=100)
objects = PermissionManager()
class Meta:
verbose_name = _('permission')
verbose_name_plural = _('permissions')
unique_together = (('content_type', 'codename'),)
ordering = ('content_type__app_label', 'content_type__model',
'codename')
def __str__(self):
return "%s | %s | %s" % (
six.text_type(self.content_type.app_label),
six.text_type(self.content_type),
six.text_type(self.name))
def natural_key(self):
return (self.codename,) + self.content_type.natural_key()
natural_key.dependencies = ['contenttypes.contenttype']
class GroupManager(models.Manager):
"""
The manager for the auth's Group model.
"""
def get_by_natural_key(self, name):
return self.get(name=name)
@python_2_unicode_compatible
class Group(models.Model):
"""
Groups are a generic way of categorizing users to apply permissions, or
some other label, to those users. A user can belong to any number of
groups.
A user in a group automatically has all the permissions granted to that
group. For example, if the group Site editors has the permission
can_edit_home_page, any user in that group will have that permission.
Beyond permissions, groups are a convenient way to categorize users to
apply some label, or extended functionality, to them. For example, you
could create a group 'Special users', and you could write code that would
do special things to those users -- such as giving them access to a
members-only portion of your site, or sending them members-only email
messages.
"""
name = models.CharField(_('name'), max_length=80, unique=True)
permissions = models.ManyToManyField(Permission,
verbose_name=_('permissions'), blank=True)
objects = GroupManager()
class Meta:
verbose_name = _('group')
verbose_name_plural = _('groups')
def __str__(self):
return self.name
def natural_key(self):
return (self.name,)
class BaseUserManager(models.Manager):
@classmethod
def normalize_email(cls, email):
"""
Normalize the address by lowercasing the domain part of the email
address.
"""
email = email or ''
try:
email_name, domain_part = email.strip().rsplit('@', 1)
except ValueError:
pass
else:
email = '@'.join([email_name, domain_part.lower()])
return email
def make_random_password(self, length=10,
allowed_chars='abcdefghjkmnpqrstuvwxyz'
'ABCDEFGHJKLMNPQRSTUVWXYZ'
'23456789'):
"""
Generates a random password with the given length and given
allowed_chars. Note that the default value of allowed_chars does not
have "I" or "O" or letters and digits that look similar -- just to
avoid confusion.
"""
return get_random_string(length, allowed_chars)
def get_by_natural_key(self, username):
return self.get(**{self.model.USERNAME_FIELD: username})
class UserManager(BaseUserManager):
def _create_user(self, username, email, password,
is_staff, is_superuser, **extra_fields):
"""
Creates and saves a User with the given username, email and password.
"""
now = timezone.now()
if not username:
raise ValueError('The given username must be set')
email = self.normalize_email(email)
user = self.model(username=username, email=email,
is_staff=is_staff, is_active=True,
is_superuser=is_superuser,
date_joined=now, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, username, email=None, password=None, **extra_fields):
return self._create_user(username, email, password, False, False,
**extra_fields)
def create_superuser(self, username, email, password, **extra_fields):
return self._create_user(username, email, password, True, True,
**extra_fields)
@python_2_unicode_compatible
class AbstractBaseUser(models.Model):
password = models.CharField(_('password'), max_length=128)
last_login = models.DateTimeField(_('last login'), blank=True, null=True)
is_active = True
REQUIRED_FIELDS = []
class Meta:
abstract = True
def get_username(self):
"Return the identifying username for this User"
return getattr(self, self.USERNAME_FIELD)
def __str__(self):
return self.get_username()
def natural_key(self):
return (self.get_username(),)
def is_anonymous(self):
"""
Always returns False. This is a way of comparing User objects to
anonymous users.
"""
return False
def is_authenticated(self):
"""
Always return True. This is a way to tell if the user has been
authenticated in templates.
"""
return True
def set_password(self, raw_password):
self.password = make_password(raw_password)
def check_password(self, raw_password):
"""
Returns a boolean of whether the raw_password was correct. Handles
hashing formats behind the scenes.
"""
def setter(raw_password):
self.set_password(raw_password)
self.save(update_fields=["password"])
return check_password(raw_password, self.password, setter)
def set_unusable_password(self):
# Sets a value that will never be a valid hash
self.password = make_password(None)
def has_usable_password(self):
return is_password_usable(self.password)
def get_full_name(self):
raise NotImplementedError('subclasses of AbstractBaseUser must provide a get_full_name() method')
def get_short_name(self):
raise NotImplementedError('subclasses of AbstractBaseUser must provide a get_short_name() method.')
def get_session_auth_hash(self):
"""
Returns an HMAC of the password field.
"""
key_salt = "django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash"
return salted_hmac(key_salt, self.password).hexdigest()
# A few helper functions for common logic between User and AnonymousUser.
def _user_get_all_permissions(user, obj):
permissions = set()
for backend in auth.get_backends():
if hasattr(backend, "get_all_permissions"):
permissions.update(backend.get_all_permissions(user, obj))
return permissions
def _user_has_perm(user, perm, obj):
"""
A backend can raise `PermissionDenied` to short-circuit permission checking.
"""
for backend in auth.get_backends():
if not hasattr(backend, 'has_perm'):
continue
try:
if backend.has_perm(user, perm, obj):
return True
except PermissionDenied:
return False
return False
def _user_has_module_perms(user, app_label):
"""
A backend can raise `PermissionDenied` to short-circuit permission checking.
"""
for backend in auth.get_backends():
if not hasattr(backend, 'has_module_perms'):
continue
try:
if backend.has_module_perms(user, app_label):
return True
except PermissionDenied:
return False
return False
class PermissionsMixin(models.Model):
"""
A mixin class that adds the fields and methods necessary to support
Django's Group and Permission model using the ModelBackend.
"""
is_superuser = models.BooleanField(_('superuser status'), default=False,
help_text=_('Designates that this user has all permissions without '
'explicitly assigning them.'))
groups = models.ManyToManyField(Group, verbose_name=_('groups'),
blank=True, help_text=_('The groups this user belongs to. A user will '
'get all permissions granted to each of '
'their groups.'),
related_name="user_set", related_query_name="user")
user_permissions = models.ManyToManyField(Permission,
verbose_name=_('user permissions'), blank=True,
help_text=_('Specific permissions for this user.'),
related_name="user_set", related_query_name="user")
class Meta:
abstract = True
def get_group_permissions(self, obj=None):
"""
Returns a list of permission strings that this user has through their
groups. This method queries all available auth backends. If an object
is passed in, only permissions matching this object are returned.
"""
permissions = set()
for backend in auth.get_backends():
if hasattr(backend, "get_group_permissions"):
permissions.update(backend.get_group_permissions(self, obj))
return permissions
def get_all_permissions(self, obj=None):
return _user_get_all_permissions(self, obj)
def has_perm(self, perm, obj=None):
"""
Returns True if the user has the specified permission. This method
queries all available auth backends, but returns immediately if any
backend returns True. Thus, a user who has permission from a single
auth backend is assumed to have permission in general. If an object is
provided, permissions for this specific object are checked.
"""
# Active superusers have all permissions.
if self.is_active and self.is_superuser:
return True
# Otherwise we need to check the backends.
return _user_has_perm(self, perm, obj)
def has_perms(self, perm_list, obj=None):
"""
Returns True if the user has each of the specified permissions. If
object is passed, it checks if the user has all required perms for this
object.
"""
for perm in perm_list:
if not self.has_perm(perm, obj):
return False
return True
def has_module_perms(self, app_label):
"""
Returns True if the user has any permissions in the given app label.
Uses pretty much the same logic as has_perm, above.
"""
# Active superusers have all permissions.
if self.is_active and self.is_superuser:
return True
return _user_has_module_perms(self, app_label)
class AbstractUser(AbstractBaseUser, PermissionsMixin):
"""
An abstract base class implementing a fully featured User model with
admin-compliant permissions.
Username, password and email are required. Other fields are optional.
"""
username = models.CharField(_('username'), max_length=30, unique=True,
help_text=_('Required. 30 characters or fewer. Letters, digits and '
'@/./+/-/_ only.'),
validators=[
validators.RegexValidator(r'^[\w.@+-]+$',
_('Enter a valid username. '
'This value may contain only letters, numbers '
'and @/./+/-/_ characters.'), 'invalid'),
],
error_messages={
'unique': _("A user with that username already exists."),
})
first_name = models.CharField(_('first name'), max_length=30, blank=True)
last_name = models.CharField(_('last name'), max_length=30, blank=True)
email = models.EmailField(_('email address'), blank=True)
is_staff = models.BooleanField(_('staff status'), default=False,
help_text=_('Designates whether the user can log into this admin '
'site.'))
is_active = models.BooleanField(_('active'), default=True,
help_text=_('Designates whether this user should be treated as '
'active. Unselect this instead of deleting accounts.'))
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
objects = UserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email']
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')
abstract = True
def get_full_name(self):
"""
Returns the first_name plus the last_name, with a space in between.
"""
full_name = '%s %s' % (self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
"Returns the short name for the user."
return self.first_name
def email_user(self, subject, message, from_email=None, **kwargs):
"""
Sends an email to this User.
"""
send_mail(subject, message, from_email, [self.email], **kwargs)
class User(AbstractUser):
"""
Users within the Django authentication system are represented by this
model.
Username, password and email are required. Other fields are optional.
"""
class Meta(AbstractUser.Meta):
swappable = 'AUTH_USER_MODEL'
@python_2_unicode_compatible
class AnonymousUser(object):
id = None
pk = None
username = ''
is_staff = False
is_active = False
is_superuser = False
_groups = EmptyManager(Group)
_user_permissions = EmptyManager(Permission)
def __init__(self):
pass
def __str__(self):
return 'AnonymousUser'
def __eq__(self, other):
return isinstance(other, self.__class__)
def __ne__(self, other):
return not self.__eq__(other)
def __hash__(self):
return 1 # instances always return the same hash value
def save(self):
raise NotImplementedError("Django doesn't provide a DB representation for AnonymousUser.")
def delete(self):
raise NotImplementedError("Django doesn't provide a DB representation for AnonymousUser.")
def set_password(self, raw_password):
raise NotImplementedError("Django doesn't provide a DB representation for AnonymousUser.")
def check_password(self, raw_password):
raise NotImplementedError("Django doesn't provide a DB representation for AnonymousUser.")
def _get_groups(self):
return self._groups
groups = property(_get_groups)
def _get_user_permissions(self):
return self._user_permissions
user_permissions = property(_get_user_permissions)
def get_group_permissions(self, obj=None):
return set()
def get_all_permissions(self, obj=None):
return _user_get_all_permissions(self, obj=obj)
def has_perm(self, perm, obj=None):
return _user_has_perm(self, perm, obj=obj)
def has_perms(self, perm_list, obj=None):
for perm in perm_list:
if not self.has_perm(perm, obj):
return False
return True
def has_module_perms(self, module):
return _user_has_module_perms(self, module)
def is_anonymous(self):
return True
def is_authenticated(self):
return False
| pwmarcz/django | django/contrib/auth/models.py | Python | bsd-3-clause | 17,843 |
from __future__ import absolute_import, unicode_literals
from django.core.exceptions import PermissionDenied
from django.shortcuts import get_object_or_404
from wagtail.wagtailadmin.forms import PageViewRestrictionForm
from wagtail.wagtailadmin.modal_workflow import render_modal_workflow
from wagtail.wagtailcore.models import Page, PageViewRestriction
def set_privacy(request, page_id):
page = get_object_or_404(Page, id=page_id)
page_perms = page.permissions_for_user(request.user)
if not page_perms.can_set_view_restrictions():
raise PermissionDenied
# fetch restriction records in depth order so that ancestors appear first
restrictions = page.get_view_restrictions().order_by('page__depth')
if restrictions:
restriction = restrictions[0]
restriction_exists_on_ancestor = (restriction.page != page)
else:
restriction = None
restriction_exists_on_ancestor = False
if request.method == 'POST':
form = PageViewRestrictionForm(request.POST, instance=restriction)
if form.is_valid() and not restriction_exists_on_ancestor:
if form.cleaned_data['restriction_type'] == PageViewRestriction.NONE:
# remove any existing restriction
if restriction:
restriction.delete()
else:
restriction = form.save(commit=False)
restriction.page = page
form.save()
return render_modal_workflow(
request, None, 'wagtailadmin/page_privacy/set_privacy_done.js', {
'is_public': (form.cleaned_data['restriction_type'] == 'none')
}
)
else: # request is a GET
if not restriction_exists_on_ancestor:
if restriction:
form = PageViewRestrictionForm(instance=restriction)
else:
# no current view restrictions on this page
form = PageViewRestrictionForm(initial={
'restriction_type': 'none'
})
if restriction_exists_on_ancestor:
# display a message indicating that there is a restriction at ancestor level -
# do not provide the form for setting up new restrictions
return render_modal_workflow(
request, 'wagtailadmin/page_privacy/ancestor_privacy.html', None,
{
'page_with_restriction': restriction.page,
}
)
else:
# no restriction set at ancestor level - can set restrictions here
return render_modal_workflow(
request,
'wagtailadmin/page_privacy/set_privacy.html',
'wagtailadmin/page_privacy/set_privacy.js', {
'page': page,
'form': form,
}
)
| chrxr/wagtail | wagtail/wagtailadmin/views/page_privacy.py | Python | bsd-3-clause | 2,828 |
// 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 UI_VIEWS_CONTROLS_MENU_MENU_RUNNER_H_
#define UI_VIEWS_CONTROLS_MENU_MENU_RUNNER_H_
#include "base/basictypes.h"
#include "base/compiler_specific.h"
#include "ui/views/controls/menu/menu_item_view.h"
namespace views {
class MenuButton;
class Widget;
namespace internal {
class DisplayChangeListener;
class MenuRunnerImpl;
}
// MenuRunner is responsible for showing (running) the menu and additionally
// owning the MenuItemView. RunMenuAt() runs a nested message loop. It is safe
// to delete MenuRunner at any point, but MenuRunner internally only deletes the
// MenuItemView *after* the nested message loop completes. If MenuRunner is
// deleted while the menu is showing the delegate of the menu is reset. This is
// done to ensure delegates aren't notified after they may have been deleted.
//
// NOTE: while you can delete a MenuRunner at any point, the nested message loop
// won't return immediately. This means if you delete the object that owns
// the MenuRunner while the menu is running, your object is effectively still
// on the stack. A return value of MENU_DELETED indicated this. In most cases
// if RunMenuAt() returns MENU_DELETED, you should return immediately.
//
// Similarly you should avoid creating MenuRunner on the stack. Doing so means
// MenuRunner may not be immediately destroyed if your object is destroyed,
// resulting in possible callbacks to your now deleted object. Instead you
// should define MenuRunner as a scoped_ptr in your class so that when your
// object is destroyed MenuRunner initiates the proper cleanup and ensures your
// object isn't accessed again.
class VIEWS_EXPORT MenuRunner {
public:
enum RunTypes {
// The menu has mnemonics.
HAS_MNEMONICS = 1 << 0,
// The menu is a nested context menu. For example, click a folder on the
// bookmark bar, then right click an entry to get its context menu.
IS_NESTED = 1 << 1,
// Used for showing a menu during a drop operation. This does NOT block the
// caller, instead the delegate is notified when the menu closes via the
// DropMenuClosed method.
FOR_DROP = 1 << 2,
// The menu is a context menu (not necessarily nested), for example right
// click on a link on a website in the browser.
CONTEXT_MENU = 1 << 3,
};
enum RunResult {
// Indicates RunMenuAt is returning because the MenuRunner was deleted.
MENU_DELETED,
// Indicates RunMenuAt returned and MenuRunner was not deleted.
NORMAL_EXIT
};
// Creates a new MenuRunner. MenuRunner owns the supplied menu.
explicit MenuRunner(MenuItemView* menu);
~MenuRunner();
// Returns the menu.
MenuItemView* GetMenu();
// Takes ownership of |menu|, deleting it when MenuRunner is deleted. You
// only need call this if you create additional menus from
// MenuDelegate::GetSiblingMenu.
void OwnMenu(MenuItemView* menu);
// Runs the menu. |types| is a bitmask of RunTypes. If this returns
// MENU_DELETED the method is returning because the MenuRunner was deleted.
// Typically callers should NOT do any processing if this returns
// MENU_DELETED.
RunResult RunMenuAt(Widget* parent,
MenuButton* button,
const gfx::Rect& bounds,
MenuItemView::AnchorPosition anchor,
int32 types) WARN_UNUSED_RESULT;
// Returns true if we're in a nested message loop running the menu.
bool IsRunning() const;
// Hides and cancels the menu. This does nothing if the menu is not open.
void Cancel();
private:
internal::MenuRunnerImpl* holder_;
scoped_ptr<internal::DisplayChangeListener> display_change_listener_;
DISALLOW_COPY_AND_ASSIGN(MenuRunner);
};
namespace internal {
// DisplayChangeListener is intended to listen for changes in the display size
// and cancel the menu. DisplayChangeListener is created when the menu is
// shown.
class DisplayChangeListener {
public:
virtual ~DisplayChangeListener() {}
// Creates the platform specified DisplayChangeListener, or NULL if there
// isn't one. Caller owns the returned value.
static DisplayChangeListener* Create(Widget* parent,
MenuRunner* runner);
protected:
DisplayChangeListener() {}
};
}
} // namespace views
#endif // UI_VIEWS_CONTROLS_MENU_MENU_RUNNER_H_
| leighpauls/k2cro4 | ui/views/controls/menu/menu_runner.h | C | bsd-3-clause | 4,509 |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// 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 Jaroslaw Kowalski 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.
//
#if !NET_CF && !SILVERLIGHT
namespace NLog.Targets
{
using System.ComponentModel;
using System.Text;
using System.Text.RegularExpressions;
using NLog.Config;
/// <summary>
/// Highlighting rule for Win32 colorful console.
/// </summary>
[NLogConfigurationItem]
public class ConsoleWordHighlightingRule
{
private Regex compiledRegex;
/// <summary>
/// Initializes a new instance of the <see cref="ConsoleWordHighlightingRule" /> class.
/// </summary>
public ConsoleWordHighlightingRule()
{
this.BackgroundColor = ConsoleOutputColor.NoChange;
this.ForegroundColor = ConsoleOutputColor.NoChange;
}
/// <summary>
/// Initializes a new instance of the <see cref="ConsoleWordHighlightingRule" /> class.
/// </summary>
/// <param name="text">The text to be matched..</param>
/// <param name="foregroundColor">Color of the foreground.</param>
/// <param name="backgroundColor">Color of the background.</param>
public ConsoleWordHighlightingRule(string text, ConsoleOutputColor foregroundColor, ConsoleOutputColor backgroundColor)
{
this.Text = text;
this.ForegroundColor = foregroundColor;
this.BackgroundColor = backgroundColor;
}
/// <summary>
/// Gets or sets the regular expression to be matched. You must specify either <c>text</c> or <c>regex</c>.
/// </summary>
/// <docgen category='Rule Matching Options' order='10' />
public string Regex { get; set; }
/// <summary>
/// Gets or sets the text to be matched. You must specify either <c>text</c> or <c>regex</c>.
/// </summary>
/// <docgen category='Rule Matching Options' order='10' />
public string Text { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to match whole words only.
/// </summary>
/// <docgen category='Rule Matching Options' order='10' />
[DefaultValue(false)]
public bool WholeWords { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to ignore case when comparing texts.
/// </summary>
/// <docgen category='Rule Matching Options' order='10' />
[DefaultValue(false)]
public bool IgnoreCase { get; set; }
/// <summary>
/// Gets the compiled regular expression that matches either Text or Regex property.
/// </summary>
public Regex CompiledRegex
{
get
{
if (this.compiledRegex == null)
{
string regexpression = this.Regex;
if (regexpression == null && this.Text != null)
{
regexpression = System.Text.RegularExpressions.Regex.Escape(this.Text);
if (this.WholeWords)
{
regexpression = "\b" + regexpression + "\b";
}
}
RegexOptions regexOptions = RegexOptions.Compiled;
if (this.IgnoreCase)
{
regexOptions |= RegexOptions.IgnoreCase;
}
this.compiledRegex = new Regex(regexpression, regexOptions);
}
return this.compiledRegex;
}
}
/// <summary>
/// Gets or sets the foreground color.
/// </summary>
/// <docgen category='Formatting Options' order='10' />
[DefaultValue("NoChange")]
public ConsoleOutputColor ForegroundColor { get; set; }
/// <summary>
/// Gets or sets the background color.
/// </summary>
/// <docgen category='Formatting Options' order='10' />
[DefaultValue("NoChange")]
public ConsoleOutputColor BackgroundColor { get; set; }
internal string MatchEvaluator(Match m)
{
StringBuilder result = new StringBuilder();
result.Append('\a');
result.Append((char)((int)this.ForegroundColor + 'A'));
result.Append((char)((int)this.BackgroundColor + 'A'));
result.Append(m.Value);
result.Append('\a');
result.Append('X');
return result.ToString();
}
internal string ReplaceWithEscapeSequences(string message)
{
return this.CompiledRegex.Replace(message, new MatchEvaluator(this.MatchEvaluator));
}
}
}
#endif | jkowalski/NLog | src/NLog/Targets/ConsoleWordHighlightingRule.cs | C# | bsd-3-clause | 6,309 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ORKNumericPrecision Constants Reference</title>
<link rel="stylesheet" href="../css/style.css">
<meta name="viewport" content="initial-scale=1, maximum-scale=1.4">
<meta name="generator" content="appledoc 2.2.1 (build 1334)">
</head>
<body class="appledoc">
<header>
<div class="container" class="hide-in-xcode">
<h1 id="library-title">
<a href="../index.html">ResearchKit </a>
</h1>
<p id="developer-home">
<a href="../index.html">ResearchKit</a>
</p>
</div>
</header>
<aside>
<div class="container">
<nav>
<ul id="header-buttons" role="toolbar">
<li><a href="../index.html">Index</a></li>
<li><a href="../hierarchy.html">Hierarchy</a></li>
<li id="on-this-page" role="navigation">
<label>
On This Page
<div class="chevron">
<div class="chevy chevron-left"></div>
<div class="chevy chevron-right"></div>
</div>
<select id="jump-to">
<option value="top">Jump To…</option>
</select>
</label>
</li>
</ul>
</nav>
</div>
</aside>
<article>
<div id="overview_contents" class="container">
<div id="content">
<main role="main">
<h1 class="title">ORKNumericPrecision Constants Reference</h1>
<div class="section section-specification"><table cellspacing="0"><tbody>
<tr>
<th>Declared in</th>
<td>ORKTypes.h</td>
</tr>
</tbody></table></div>
<h3 class="subsubtitle method-title">ORKNumericPrecision</h3>
<div class="section section-overview">
<p>Numeric precision.</p>
<p>Used by <a href="../Classes/ORKWeightAnswerFormat.html">ORKWeightAnswerFormat</a>.</p>
</div>
<div class="section">
<!-- display enum values -->
<h4 class="method-subtitle">Definition</h4>
<code>typedef NS_ENUM(NSInteger, ORKNumericPrecision ) {<br>
<a href="">ORKNumericPrecisionDefault</a> = 0,<br>
<a href="">ORKNumericPrecisionLow</a>,<br>
<a href="">ORKNumericPrecisionHigh</a>,<br>
};</code>
</div>
<div class="section section-methods">
<h4 class="method-subtitle">Constants</h4>
<dl class="termdef">
<dt><a name="" title="ORKNumericPrecisionDefault"></a><code>ORKNumericPrecisionDefault</code></dt>
<dd>
<p>Default numeric precision.</p>
<p>
Declared In <code class="declared-in-ref">ORKTypes.h</code>.
</p>
</dd>
<dt><a name="" title="ORKNumericPrecisionLow"></a><code>ORKNumericPrecisionLow</code></dt>
<dd>
<p>Low numeric precision.</p>
<p>
Declared In <code class="declared-in-ref">ORKTypes.h</code>.
</p>
</dd>
<dt><a name="" title="ORKNumericPrecisionHigh"></a><code>ORKNumericPrecisionHigh</code></dt>
<dd>
<p>High numeric preicision.</p>
<p>
Declared In <code class="declared-in-ref">ORKTypes.h</code>.
</p>
</dd>
</dl>
</div>
<div class="method-subsection declared-in-section">
<h4 class="method-subtitle">Declared In</h4>
<p><code class="declared-in-ref">ORKTypes.h</code></p>
</div>
</main>
<footer>
<div class="footer-copyright">
<p class="copyright">Copyright © 2018 ResearchKit. All rights reserved. Updated: 2018-07-23</p>
<p class="generator">Generated by <a href="http://appledoc.gentlebytes.com">appledoc 2.2.1 (build 1334)</a>.</p>
</div>
</footer>
</div>
</div>
</article>
<script src="../js/script.js"></script>
</body>
</html> | jeremiahyan/ResearchKit | docs/org.researchkit.ResearchKit.docset/Contents/Resources/Documents/Constants/ORKNumericPrecision.html | HTML | bsd-3-clause | 4,601 |
/*
* 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.
*/
.search-drawer-header {
flex: none;
padding: 4px;
display: flex;
}
.search-drawer-header input[type="text"].search-config-search {
-webkit-appearance: none;
padding: 0 3px;
margin: 0;
border: 1px solid rgb(163, 163, 163);
height: 20px;
border-radius: 2px;
color: #303030;
}
.search-drawer-header input[type="search"].search-config-search:focus {
border: 1px solid rgb(190, 190, 190);
outline: none;
}
:host-context(.platform-mac) .search-drawer-header input[type="search"].search-config-search {
top: 1px;
}
.search-drawer-header label.search-config-label {
margin: auto 0;
margin-left: 8px;
color: #303030;
display: flex;
}
.search-toolbar-summary {
background-color: #eee;
border-top: 1px solid #ccc;
padding-left: 5px;
flex: 0 0 19px;
display: flex;
padding-right: 5px;
}
.search-toolbar-summary .search-message {
padding-top: 2px;
padding-left: 1ex;
}
#search-results-pane-file-based li {
list-style: none;
}
#search-results-pane-file-based ol {
-webkit-padding-start: 0;
margin-top: 0;
}
#search-results-pane-file-based ol.children {
display: none;
}
#search-results-pane-file-based ol.children.expanded {
display: block;
}
#search-results-pane-file-based li.parent::before {
-webkit-user-select: none;
background-image: url(Images/toolbarButtonGlyphs.png);
background-size: 352px 168px;
opacity: 0.5;
width: 12px;
content: "a";
color: transparent;
margin-left: -5px;
padding-right: 4px;
display: inline-block;
box-sizing: border-box;
}
@media (-webkit-min-device-pixel-ratio: 1.5) {
#search-results-pane-file-based li.parent::before {
background-image: url(Images/toolbarButtonGlyphs_2x.png);
}
} /* media */
#search-results-pane-file-based li.parent::before {
background-position: -4px -96px;
}
#search-results-pane-file-based li.parent.expanded::before {
background-position: -20px -96px;
}
#search-results-pane-file-based .search-result {
font-size: 11px;
padding: 2px 0 2px 10px;
word-wrap: normal;
white-space: pre;
cursor: pointer;
}
#search-results-pane-file-based .search-result:hover {
background-color: rgba(121, 121, 121, 0.1);
}
#search-results-pane-file-based .search-result .search-result-file-name {
font-weight: bold;
color: #222;
}
#search-results-pane-file-based .search-result .search-result-matches-count {
margin-left: 5px;
color: #222;
}
#search-results-pane-file-based .show-more-matches {
padding: 4px 0;
color: #222;
cursor: pointer;
font-size: 11px;
margin-left: 20px;
}
#search-results-pane-file-based .show-more-matches:hover {
text-decoration: underline;
}
#search-results-pane-file-based .search-match {
word-wrap: normal;
white-space: pre;
}
#search-results-pane-file-based .search-match .search-match-line-number {
color: rgb(128, 128, 128);
text-align: right;
vertical-align: top;
word-break: normal;
padding-right: 4px;
padding-left: 6px;
margin-right: 5px;
border-right: 1px solid #BBB;
}
#search-results-pane-file-based .search-match:not(:hover) .search-match-line-number {
background-color: #F0F0F0;
}
#search-results-pane-file-based .search-match:hover {
background-color: rgba(56, 121, 217, 0.1);
}
#search-results-pane-file-based .search-match .highlighted-match {
background-color: #F1EA00;
}
:host-context(.-theme-with-dark-background) #search-results-pane-file-based .search-match .highlighted-match {
background-color: hsl(133, 100%, 30%) !important;
}
#search-results-pane-file-based a {
text-decoration: none;
display: block;
}
#search-results-pane-file-based .search-match .search-match-content {
color: #000;
}
.search-view .search-results {
overflow-y: auto;
display: flex;
flex: auto;
}
.search-results .empty-view {
pointer-events: none;
}
.empty-view {
font-size: 24px;
color: rgb(75%, 75%, 75%);
font-weight: bold;
padding: 10px;
display: flex;
align-items: center;
justify-content: center;
}
| ds-hwang/chromium-crosswalk | third_party/WebKit/Source/devtools/front_end/sources/sourcesSearch.css | CSS | bsd-3-clause | 4,308 |
// Copyright 2022 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_VIEWS_DOWNLOAD_BUBBLE_DOWNLOAD_BUBBLE_ROW_VIEW_H_
#define CHROME_BROWSER_UI_VIEWS_DOWNLOAD_BUBBLE_DOWNLOAD_BUBBLE_ROW_VIEW_H_
#include "base/memory/weak_ptr.h"
#include "base/task/cancelable_task_tracker.h"
#include "chrome/browser/download/download_ui_model.h"
#include "chrome/browser/ui/views/download/bubble/download_bubble_row_list_view.h"
#include "ui/base/metadata/metadata_header_macros.h"
#include "ui/views/view.h"
namespace views {
class ImageView;
} // namespace views
class DownloadBubbleRowView : public views::View {
public:
METADATA_HEADER(DownloadBubbleRowView);
explicit DownloadBubbleRowView(DownloadUIModel::DownloadUIModelPtr model);
DownloadBubbleRowView(const DownloadBubbleRowView&) = delete;
DownloadBubbleRowView& operator=(const DownloadBubbleRowView&) = delete;
~DownloadBubbleRowView() override;
// Overrides views::View:
void AddedToWidget() override;
protected:
// Overrides ui::LayerDelegate:
void OnDeviceScaleFactorChanged(float old_device_scale_factor,
float new_device_scale_factor) override;
private:
// Load the icon, from the cache or from IconManager::LoadIcon.
void LoadIcon();
// Called when icon has been loaded by IconManager::LoadIcon.
void SetIcon(gfx::Image icon);
// TODO(bhatiarohit): Add platform-independent icons.
// The icon for the file. We get platform-specific icons from IconLoader.
raw_ptr<views::ImageView> icon_ = nullptr;
// Device scale factor, used to load icons.
float current_scale_ = 1.0f;
// Tracks tasks requesting file icons.
base::CancelableTaskTracker cancelable_task_tracker_;
// The model controlling this object's state.
const DownloadUIModel::DownloadUIModelPtr model_;
base::WeakPtrFactory<DownloadBubbleRowView> weak_factory_{this};
};
#endif // CHROME_BROWSER_UI_VIEWS_DOWNLOAD_BUBBLE_DOWNLOAD_BUBBLE_ROW_VIEW_H_
| chromium/chromium | chrome/browser/ui/views/download/bubble/download_bubble_row_view.h | C | bsd-3-clause | 2,081 |
// Copyright 2020 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 COMPONENTS_PERFORMANCE_MANAGER_SERVICE_WORKER_CONTEXT_ADAPTER_H_
#define COMPONENTS_PERFORMANCE_MANAGER_SERVICE_WORKER_CONTEXT_ADAPTER_H_
#include <memory>
#include <string>
#include "base/check_op.h"
#include "base/containers/flat_map.h"
#include "base/containers/flat_set.h"
#include "base/observer_list.h"
#include "base/scoped_observation.h"
#include "content/public/browser/service_worker_context.h"
#include "content/public/browser/service_worker_context_observer.h"
namespace blink {
class StorageKey;
} // namespace blink
namespace performance_manager {
// This class adapts an existing ServiceWorkerContext to ensure that the
// OnVersionStoppedRunning() notifications are sent as soon as the render
// process of a running service worker exits.
//
// It implements ServiceWorkerContext so it can be used interchangeably where a
// ServiceWorkerContext* is needed, and it also observes the underlying context
// so that it can receive the original notifications and control when they are
// sent to the observers.
//
// Lives on the UI thread. Must outlive |underlying_context|.
//
// Note: This is a temporary class that can be removed when the representation
// of a worker in the content/ layer (ServiceWorkerVersion) is moved to
// the UI thread. At that point, it'll be able to observe its associated
// RenderProcessHost itself. See https://crbug.com/824858.
class ServiceWorkerContextAdapter
: public content::ServiceWorkerContext,
public content::ServiceWorkerContextObserver {
public:
explicit ServiceWorkerContextAdapter(
content::ServiceWorkerContext* underlying_context);
~ServiceWorkerContextAdapter() override;
// content::ServiceWorkerContext:
// Note that this is a minimal implementation for the use case of the
// PerformanceManager. Only AddObserver/RemoveObserver are implemented.
void AddObserver(content::ServiceWorkerContextObserver* observer) override;
void RemoveObserver(content::ServiceWorkerContextObserver* observer) override;
void RegisterServiceWorker(
const GURL& script_url,
const blink::StorageKey& key,
const blink::mojom::ServiceWorkerRegistrationOptions& options,
StatusCodeCallback callback) override;
void UnregisterServiceWorker(const GURL& scope,
const blink::StorageKey& key,
ResultCallback callback) override;
content::ServiceWorkerExternalRequestResult StartingExternalRequest(
int64_t service_worker_version_id,
content::ServiceWorkerExternalRequestTimeoutType timeout_type,
const std::string& request_uuid) override;
content::ServiceWorkerExternalRequestResult FinishedExternalRequest(
int64_t service_worker_version_id,
const std::string& request_uuid) override;
size_t CountExternalRequestsForTest(const blink::StorageKey& key) override;
bool ExecuteScriptForTest(
const std::string& script,
int64_t service_worker_version_id,
content::ServiceWorkerScriptExecutionCallback callback) override;
bool MaybeHasRegistrationForStorageKey(const blink::StorageKey& key) override;
void GetAllOriginsInfo(GetUsageInfoCallback callback) override;
void DeleteForStorageKey(const blink::StorageKey& key,
ResultCallback callback) override;
void CheckHasServiceWorker(const GURL& url,
const blink::StorageKey& key,
CheckHasServiceWorkerCallback callback) override;
void CheckOfflineCapability(const GURL& url,
const blink::StorageKey& key,
CheckOfflineCapabilityCallback callback) override;
void ClearAllServiceWorkersForTest(base::OnceClosure callback) override;
void StartWorkerForScope(const GURL& scope,
const blink::StorageKey& key,
StartWorkerCallback info_callback,
StatusCodeCallback failure_callback) override;
void StartServiceWorkerAndDispatchMessage(
const GURL& scope,
const blink::StorageKey& key,
blink::TransferableMessage message,
ResultCallback result_callback) override;
void StartServiceWorkerForNavigationHint(
const GURL& document_url,
const blink::StorageKey& key,
StartServiceWorkerForNavigationHintCallback callback) override;
void StopAllServiceWorkersForStorageKey(
const blink::StorageKey& key) override;
void StopAllServiceWorkers(base::OnceClosure callback) override;
const base::flat_map<int64_t /* version_id */,
content::ServiceWorkerRunningInfo>&
GetRunningServiceWorkerInfos() override;
// content::ServiceWorkerContextObserver:
void OnRegistrationCompleted(const GURL& scope) override;
void OnRegistrationStored(int64_t registration_id,
const GURL& scope) override;
void OnVersionActivated(int64_t version_id, const GURL& scope) override;
void OnVersionRedundant(int64_t version_id, const GURL& scope) override;
void OnVersionStartedRunning(
int64_t version_id,
const content::ServiceWorkerRunningInfo& running_info) override;
void OnVersionStoppedRunning(int64_t version_id) override;
void OnControlleeAdded(
int64_t version_id,
const std::string& client_uuid,
const content::ServiceWorkerClientInfo& client_info) override;
void OnControlleeRemoved(int64_t version_id,
const std::string& client_uuid) override;
void OnNoControllees(int64_t version_id, const GURL& scope) override;
void OnControlleeNavigationCommitted(
int64_t version_id,
const std::string& uuid,
content::GlobalRenderFrameHostId render_frame_host_id) override;
void OnReportConsoleMessage(int64_t version_id,
const GURL& scope,
const content::ConsoleMessage& message) override;
void OnDestruct(ServiceWorkerContext* context) override;
private:
class RunningServiceWorker;
// Invoked by a RunningServiceWorker when it observes that the render process
// has exited.
void OnRenderProcessExited(int64_t version_id);
// Adds a registration to |worker_process_host| that will result in
// |OnRenderProcessExited| with |version_id| when it exits.
void AddRunningServiceWorker(int64_t version_id,
content::RenderProcessHost* worker_process_host);
// Removes a registration made by |AddRunningServiceWorker| if one exists,
// returns true if a registration existed, false otherwise.
bool MaybeRemoveRunningServiceWorker(int64_t version_id);
base::ScopedObservation<content::ServiceWorkerContext,
content::ServiceWorkerContextObserver>
scoped_underlying_context_observation_{this};
base::ObserverList<content::ServiceWorkerContextObserver, true, false>::
Unchecked observer_list_;
// For each running service worker, tracks when their render process exits.
base::flat_map<int64_t /*version_id*/, std::unique_ptr<RunningServiceWorker>>
running_service_workers_;
// Tracks the OnControlleeAdded and OnControlleeRemoved notification for each
// service worker, with the goal of cleaning up duplicate notifications for
// observers of this class.
// TODO(1015692): Fix the underlying code in content/browser/service_worker so
// that duplicate notifications are no longer sent.
base::flat_map<int64_t /*version_id*/,
base::flat_set<std::string /*client_uuid*/>>
service_worker_clients_;
#if DCHECK_IS_ON()
// Keeps track of service worker whose render process exited early.
base::flat_set<int64_t> stopped_service_workers_;
#endif // DCHECK_IS_ON()
};
} // namespace performance_manager
#endif // COMPONENTS_PERFORMANCE_MANAGER_SERVICE_WORKER_CONTEXT_ADAPTER_H_
| chromium/chromium | components/performance_manager/service_worker_context_adapter.h | C | bsd-3-clause | 8,057 |
package ibxm;
/* A data array dynamically loaded from an InputStream. */
public class Data {
private int bufLen;
private byte[] buffer;
private java.io.InputStream stream;
public Data( java.io.InputStream inputStream ) throws java.io.IOException {
bufLen = 1 << 16;
buffer = new byte[ bufLen ];
stream = inputStream;
readFully( stream, buffer, 0, bufLen );
}
public Data( byte[] data ) {
bufLen = data.length;
buffer = data;
}
public byte sByte( int offset ) throws java.io.IOException {
load( offset, 1 );
return buffer[ offset ];
}
public int uByte( int offset ) throws java.io.IOException {
load( offset, 1 );
return buffer[ offset ] & 0xFF;
}
public int ubeShort( int offset ) throws java.io.IOException {
load( offset, 2 );
return ( ( buffer[ offset ] & 0xFF ) << 8 ) | ( buffer[ offset + 1 ] & 0xFF );
}
public int uleShort( int offset ) throws java.io.IOException {
load( offset, 2 );
return ( buffer[ offset ] & 0xFF ) | ( ( buffer[ offset + 1 ] & 0xFF ) << 8 );
}
public int uleInt( int offset ) throws java.io.IOException {
load( offset, 4 );
int value = buffer[ offset ] & 0xFF;
value = value | ( ( buffer[ offset + 1 ] & 0xFF ) << 8 );
value = value | ( ( buffer[ offset + 2 ] & 0xFF ) << 16 );
value = value | ( ( buffer[ offset + 3 ] & 0x7F ) << 24 );
return value;
}
public String strLatin1( int offset, int length ) throws java.io.IOException {
load( offset, length );
char[] str = new char[ length ];
for( int idx = 0; idx < length; idx++ ) {
int chr = buffer[ offset + idx ] & 0xFF;
str[ idx ] = chr < 32 ? 32 : ( char ) chr;
}
return new String( str );
}
public String strCp850( int offset, int length ) throws java.io.IOException {
load( offset, length );
try {
char[] str = new String( buffer, offset, length, "Cp850" ).toCharArray();
for( int idx = 0; idx < str.length; idx++ ) {
str[ idx ] = str[ idx ] < 32 ? 32 : str[ idx ];
}
return new String( str );
} catch( java.io.UnsupportedEncodingException e ) {
return strLatin1( offset, length );
}
}
public short[] samS8( int offset, int length ) throws java.io.IOException {
load( offset, length );
short[] sampleData = new short[ length ];
for( int idx = 0; idx < length; idx++ ) {
sampleData[ idx ] = ( short ) ( buffer[ offset + idx ] << 8 );
}
return sampleData;
}
public short[] samS8D( int offset, int length ) throws java.io.IOException {
load( offset, length );
short[] sampleData = new short[ length ];
int sam = 0;
for( int idx = 0; idx < length; idx++ ) {
sam += buffer[ offset + idx ];
sampleData[ idx ] = ( short ) ( sam << 8 );
}
return sampleData;
}
public short[] samU8( int offset, int length ) throws java.io.IOException {
load( offset, length );
short[] sampleData = new short[ length ];
for( int idx = 0; idx < length; idx++ ) {
sampleData[ idx ] = ( short ) ( ( ( buffer[ offset + idx ] & 0xFF ) - 128 ) << 8 );
}
return sampleData;
}
public short[] samS16( int offset, int samples ) throws java.io.IOException {
load( offset, samples * 2 );
short[] sampleData = new short[ samples ];
for( int idx = 0; idx < samples; idx++ ) {
sampleData[ idx ] = ( short ) ( ( buffer[ offset + idx * 2 ] & 0xFF ) | ( buffer[ offset + idx * 2 + 1 ] << 8 ) );
}
return sampleData;
}
public short[] samS16D( int offset, int samples ) throws java.io.IOException {
load( offset, samples * 2 );
short[] sampleData = new short[ samples ];
int sam = 0;
for( int idx = 0; idx < samples; idx++ ) {
sam += ( buffer[ offset + idx * 2 ] & 0xFF ) | ( buffer[ offset + idx * 2 + 1 ] << 8 );
sampleData[ idx ] = ( short ) sam;
}
return sampleData;
}
public short[] samU16( int offset, int samples ) throws java.io.IOException {
load( offset, samples * 2 );
short[] sampleData = new short[ samples ];
for( int idx = 0; idx < samples; idx++ ) {
int sam = ( buffer[ offset + idx * 2 ] & 0xFF ) | ( ( buffer[ offset + idx * 2 + 1 ] & 0xFF ) << 8 );
sampleData[ idx ] = ( short ) ( sam - 32768 );
}
return sampleData;
}
private void load( int offset, int length ) throws java.io.IOException {
while( offset + length > bufLen ) {
int newBufLen = bufLen << 1;
byte[] newBuf = new byte[ newBufLen ];
System.arraycopy( buffer, 0, newBuf, 0, bufLen );
if( stream != null ) {
readFully( stream, newBuf, bufLen, newBufLen - bufLen );
}
bufLen = newBufLen;
buffer = newBuf;
}
}
private static void readFully( java.io.InputStream inputStream, byte[] buffer, int offset, int length ) throws java.io.IOException {
int read = 1, end = offset + length;
while( read > 0 ) {
read = inputStream.read( buffer, offset, end - offset );
offset += read;
}
}
}
| Arcnor/micromod | ibxm/src/main/java/ibxm/Data.java | Java | bsd-3-clause | 4,767 |
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/spellcheck/browser/android/component_jni_registrar.h"
#include "base/android/jni_android.h"
#include "base/android/jni_registrar.h"
#include "components/spellcheck/browser/spellchecker_session_bridge_android.h"
namespace spellcheck {
namespace android {
static base::android::RegistrationMethod kSpellcheckRegisteredMethods[] = {
{"SpellCheckerSessionBridge", SpellCheckerSessionBridge::RegisterJNI},
};
bool RegisterSpellcheckJni(JNIEnv* env) {
return base::android::RegisterNativeMethods(
env, kSpellcheckRegisteredMethods,
std::size(kSpellcheckRegisteredMethods));
}
} // namespace android
} // namespace spellcheck
| chromium/chromium | components/spellcheck/browser/android/component_jni_registrar.cc | C++ | bsd-3-clause | 833 |
#include "../../src/gui/embedded/qmouselinuxtp_qws.h"
| KenanSulayman/node-qt | deps/qt-4.8.0/win32/ia32/include/QtGui/qmouselinuxtp_qws.h | C | bsd-3-clause | 55 |
export { enableDebugTools, disableDebugTools } from 'angular2/src/tools/tools';
| binariedMe/blogging | node_modules/angular2/tools.d.ts | TypeScript | mit | 80 |
class ValueQuestionPresenter < QuestionPresenter
include ActionView::Helpers::NumberHelper
def response_label(value)
number_with_delimiter(value)
end
end
| stwalsh/smart-answers | app/presenters/value_question_presenter.rb | Ruby | mit | 165 |
#if !NETSTANDARD2_0
using OfficeDevPnP.Core.IdentityModel.WSTrustBindings;
using System;
using System.IdentityModel.Protocols.WSTrust;
using System.IdentityModel.Tokens;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Security;
namespace OfficeDevPnP.Core.IdentityModel.TokenProviders.ADFS
{
/// <summary>
/// ADFS Active authentication based on username + password. Uses the trust/13/usernamemixed ADFS endpoint.
/// </summary>
public class UsernameMixed : BaseProvider
{
/// <summary>
/// Performs active authentication against ADFS using the trust/13/usernamemixed ADFS endpoint.
/// </summary>
/// <param name="siteUrl">Url of the SharePoint site that's secured via ADFS</param>
/// <param name="userName">Name of the user (e.g. domain\administrator) </param>
/// <param name="password">Password of th user</param>
/// <param name="userNameMixed">Uri to the ADFS usernamemixed endpoint</param>
/// <param name="relyingPartyIdentifier">Identifier of the ADFS relying party that we're hitting</param>
/// <param name="logonTokenCacheExpirationWindow">Logon TokenCache expiration window integer value</param>
/// <returns>A cookiecontainer holding the FedAuth cookie</returns>
public CookieContainer GetFedAuthCookie(string siteUrl, string userName, string password, Uri userNameMixed, string relyingPartyIdentifier, int logonTokenCacheExpirationWindow)
{
UsernameMixed adfsTokenProvider = new UsernameMixed();
var token = adfsTokenProvider.RequestToken(userName, password, userNameMixed, relyingPartyIdentifier);
string fedAuthValue = TransformSamlTokenToFedAuth(token.TokenXml.OuterXml, siteUrl, relyingPartyIdentifier);
// Construct the cookie expiration date
TimeSpan lifeTime = SamlTokenlifeTime(token.TokenXml.OuterXml);
if (lifeTime == TimeSpan.Zero)
{
lifeTime = new TimeSpan(0, 60, 0);
}
int cookieLifeTime = Math.Min((int)lifeTime.TotalMinutes, logonTokenCacheExpirationWindow);
DateTime expiresOn = DateTime.Now.AddMinutes(cookieLifeTime);
CookieContainer cc = null;
if (!string.IsNullOrEmpty(fedAuthValue))
{
cc = new CookieContainer();
Cookie samlAuth = new Cookie("FedAuth", fedAuthValue);
samlAuth.Expires = expiresOn;
samlAuth.Path = "/";
samlAuth.Secure = true;
samlAuth.HttpOnly = true;
Uri samlUri = new Uri(siteUrl);
samlAuth.Domain = samlUri.Host;
cc.Add(samlAuth);
}
return cc;
}
private GenericXmlSecurityToken RequestToken(string userName, string passWord, Uri userNameMixed, string relyingPartyIdentifier)
{
GenericXmlSecurityToken genericToken = null;
using (var factory = new WSTrustChannelFactory(new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential), new EndpointAddress(userNameMixed)))
{
factory.TrustVersion = TrustVersion.WSTrust13;
// Hookup the user and password
factory.Credentials.UserName.UserName = userName;
factory.Credentials.UserName.Password = passWord;
var requestSecurityToken = new RequestSecurityToken
{
RequestType = RequestTypes.Issue,
AppliesTo = new EndpointReference(relyingPartyIdentifier),
KeyType = KeyTypes.Bearer
};
IWSTrustChannelContract channel = factory.CreateChannel();
genericToken = channel.Issue(requestSecurityToken) as GenericXmlSecurityToken;
factory.Close();
}
return genericToken;
}
}
}
#endif | OfficeDev/PnP-Sites-Core | Core/OfficeDevPnP.Core/IdentityModel/TokenProviders/ADFS/UsernameMixed.cs | C# | mit | 3,992 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.