answer
stringlengths 15
1.25M
|
|---|
package org.chromium.net.impl;
import android.content.Context;
import android.os.Build;
import android.os.ConditionVariable;
import android.os.Handler;
import android.os.Looper;
import android.os.Process;
import android.util.Log;
import org.chromium.base.ObserverList;
import org.chromium.base.VisibleForTesting;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.annotations.<API key>;
import org.chromium.base.annotations.UsedByReflection;
import org.chromium.net.BidirectionalStream;
import org.chromium.net.CronetEngine;
import org.chromium.net.<API key>;
import org.chromium.net.<API key>;
import org.chromium.net.RequestFinishedInfo;
import org.chromium.net.UrlRequest;
import org.chromium.net.urlconnection.<API key>;
import org.chromium.net.urlconnection.<API key>;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.net.<API key>;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.<API key>;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.concurrent.GuardedBy;
/**
* CronetEngine using Chromium HTTP stack implementation.
*/
@JNINamespace("cronet")
@UsedByReflection("CronetEngine.java")
@VisibleForTesting
public class <API key> extends CronetEngine {
private static final int LOG_NONE = 3; // LOG(FATAL), no VLOG.
private static final int LOG_DEBUG = -1; // LOG(FATAL...INFO), VLOG(1)
private static final int LOG_VERBOSE = -2; // LOG(FATAL...INFO), VLOG(2)
static final String LOG_TAG = "ChromiumNetwork";
/**
* Synchronize access to <API key> and shutdown routine.
*/
private final Object mLock = new Object();
private final ConditionVariable mInitCompleted = new ConditionVariable(false);
private final AtomicInteger mActiveRequestCount = new AtomicInteger(0);
private long <API key> = 0;
private Thread mNetworkThread;
private boolean <API key>;
/**
* Locks operations on network quality listeners, because listener
* addition and removal may occur on a different thread from notification.
*/
private final Object mNetworkQualityLock = new Object();
/**
* Locks operations on the list of RequestFinishedInfo.Listeners, because operations can happen
* on any thread.
*/
private final Object <API key> = new Object();
@GuardedBy("mNetworkQualityLock")
private final ObserverList<<API key>> mRttListenerList =
new ObserverList<<API key>>();
@GuardedBy("mNetworkQualityLock")
private final ObserverList<<API key>> <API key> =
new ObserverList<<API key>>();
@GuardedBy("<API key>")
private final List<RequestFinishedInfo.Listener> <API key> =
new ArrayList<RequestFinishedInfo.Listener>();
/**
* Synchronize access to mCertVerifierData.
*/
private ConditionVariable <API key> = new ConditionVariable();
/** Holds CertVerifier data. */
private String mCertVerifierData;
@UsedByReflection("CronetEngine.java")
public <API key>(final CronetEngine.Builder builder) {
CronetLibraryLoader.ensureInitialized(builder.getContext(), builder);
<API key>(getLoggingLevel());
synchronized (mLock) {
<API key> = <API key>(
<API key>(builder.getContext(), builder));
if (<API key> == 0) {
throw new <API key>("Context Adapter creation failed.");
}
<API key> = builder.<API key>();
}
// Init native Chromium URLRequestContext on main UI thread.
Runnable task = new Runnable() {
@Override
public void run() {
CronetLibraryLoader.<API key>(builder.getContext());
synchronized (mLock) {
// <API key> is guaranteed to exist until
// initialization on main and network threads completes and
// initNetworkThread is called back on network thread.
<API key>(<API key>);
}
}
};
// Run task immediately or post it to the UI thread.
if (Looper.getMainLooper() == Looper.myLooper()) {
task.run();
} else {
new Handler(Looper.getMainLooper()).post(task);
}
}
@VisibleForTesting
public static long <API key>(
final Context context, CronetEngine.Builder builder) {
final long <API key> = <API key>(
builder.getUserAgent(), builder.storagePath(), builder.quicEnabled(),
builder.<API key>(context), builder.http2Enabled(),
builder.sdchEnabled(), builder.<API key>(),
builder.<API key>(), builder.<API key>(),
builder.<API key>(), builder.cacheDisabled(),
builder.httpCacheMode(), builder.httpCacheMaxSize(), builder.experimentalOptions(),
builder.mockCertVerifier(), builder.<API key>(),
builder.<API key>(),
builder.certVerifierData());
for (Builder.QuicHint quicHint : builder.quicHints()) {
nativeAddQuicHint(<API key>, quicHint.mHost, quicHint.mPort,
quicHint.mAlternatePort);
}
for (Builder.Pkp pkp : builder.publicKeyPins()) {
nativeAddPkp(<API key>, pkp.mHost, pkp.mHashes, pkp.mIncludeSubdomains,
pkp.mExpirationDate.getTime());
}
return <API key>;
}
@Override
public UrlRequest createRequest(String url, UrlRequest.Callback callback, Executor executor,
int priority, Collection<Object> requestAnnotations, boolean disableCache,
boolean <API key>) {
synchronized (mLock) {
checkHaveAdapter();
boolean <API key> = false;
synchronized (<API key>) {
<API key> = !<API key>.isEmpty();
}
return new CronetUrlRequest(this, url, priority, callback, executor, requestAnnotations,
<API key>, disableCache, <API key>);
}
}
@Override
public BidirectionalStream <API key>(String url,
BidirectionalStream.Callback callback, Executor executor, String httpMethod,
List<Map.Entry<String, String>> requestHeaders,
@BidirectionalStream.Builder.StreamPriority int priority, boolean disableAutoFlush,
boolean <API key>) {
synchronized (mLock) {
checkHaveAdapter();
return new <API key>(this, url, priority, callback, executor,
httpMethod, requestHeaders, disableAutoFlush,
<API key>);
}
}
@Override
public boolean isEnabled() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH;
}
@Override
public String getVersionString() {
return "Cronet/" + ImplVersion.getVersion();
}
@Override
public void shutdown() {
synchronized (mLock) {
checkHaveAdapter();
if (mActiveRequestCount.get() != 0) {
throw new <API key>("Cannot shutdown with active requests.");
}
// Destroying adapter stops the network thread, so it cannot be
// called on network thread.
if (Thread.currentThread() == mNetworkThread) {
throw new <API key>("Cannot shutdown from network thread.");
}
}
// Wait for init to complete on main and network thread (without lock,
// so other thread could access it).
mInitCompleted.block();
synchronized (mLock) {
// It is possible that adapter is already destroyed on another thread.
if (!<API key>()) {
return;
}
nativeDestroy(<API key>);
<API key> = 0;
}
}
@Override
public void startNetLogToFile(String fileName, boolean logAll) {
synchronized (mLock) {
checkHaveAdapter();
<API key>(<API key>, fileName, logAll);
}
}
@Override
public void stopNetLog() {
synchronized (mLock) {
checkHaveAdapter();
nativeStopNetLog(<API key>);
}
}
@Override
public String getCertVerifierData(long timeout) {
if (timeout < 0) {
throw new <API key>("timeout must be a positive value");
} else if (timeout == 0) {
timeout = 100;
}
<API key>.close();
synchronized (mLock) {
checkHaveAdapter();
<API key>(<API key>);
}
<API key>.block(timeout);
return mCertVerifierData;
}
// This method is intentionally non-static to ensure Cronet native library
// is loaded by class constructor.
@Override
public byte[] <API key>() {
return <API key>();
}
@VisibleForTesting
@Override
public void <API key>(
boolean <API key>, boolean useSmallerResponses) {
if (!<API key>) {
throw new <API key>("Network quality estimator must be enabled");
}
synchronized (mLock) {
checkHaveAdapter();
<API key>(
<API key>, <API key>, useSmallerResponses);
}
}
@Override
public void addRttListener(<API key> listener) {
if (!<API key>) {
throw new <API key>("Network quality estimator must be enabled");
}
synchronized (mNetworkQualityLock) {
if (mRttListenerList.isEmpty()) {
synchronized (mLock) {
checkHaveAdapter();
<API key>(<API key>, true);
}
}
mRttListenerList.addObserver(listener);
}
}
@Override
public void removeRttListener(<API key> listener) {
if (!<API key>) {
throw new <API key>("Network quality estimator must be enabled");
}
synchronized (mNetworkQualityLock) {
mRttListenerList.removeObserver(listener);
if (mRttListenerList.isEmpty()) {
synchronized (mLock) {
checkHaveAdapter();
<API key>(<API key>, false);
}
}
}
}
@Override
public void <API key>(<API key> listener) {
if (!<API key>) {
throw new <API key>("Network quality estimator must be enabled");
}
synchronized (mNetworkQualityLock) {
if (<API key>.isEmpty()) {
synchronized (mLock) {
checkHaveAdapter();
<API key>(<API key>, true);
}
}
<API key>.addObserver(listener);
}
}
@Override
public void <API key>(<API key> listener) {
if (!<API key>) {
throw new <API key>("Network quality estimator must be enabled");
}
synchronized (mNetworkQualityLock) {
<API key>.removeObserver(listener);
if (<API key>.isEmpty()) {
synchronized (mLock) {
checkHaveAdapter();
<API key>(<API key>, false);
}
}
}
}
@Override
public void <API key>(RequestFinishedInfo.Listener listener) {
synchronized (<API key>) {
<API key>.add(listener);
}
}
@Override
public void <API key>(RequestFinishedInfo.Listener listener) {
synchronized (<API key>) {
<API key>.remove(listener);
}
}
@Override
public URLConnection openConnection(URL url) {
return openConnection(url, Proxy.NO_PROXY);
}
@Override
public URLConnection openConnection(URL url, Proxy proxy) {
if (proxy.type() != Proxy.Type.DIRECT) {
throw new <API key>();
}
String protocol = url.getProtocol();
if ("http".equals(protocol) || "https".equals(protocol)) {
return new <API key>(url, this);
}
throw new <API key>("Unexpected protocol:" + protocol);
}
@Override
public <API key> <API key>() {
return new <API key>(this);
}
/**
* Mark request as started to prevent shutdown when there are active
* requests.
*/
void onRequestStarted() {
mActiveRequestCount.incrementAndGet();
}
/**
* Mark request as finished to allow shutdown when there are no active
* requests.
*/
void onRequestDestroyed() {
mActiveRequestCount.decrementAndGet();
}
@VisibleForTesting
public long <API key>() {
synchronized (mLock) {
checkHaveAdapter();
return <API key>;
}
}
private void checkHaveAdapter() throws <API key> {
if (!<API key>()) {
throw new <API key>("Engine is shut down.");
}
}
private boolean <API key>() {
return <API key> != 0;
}
/**
* @return loggingLevel see {@link #LOG_NONE}, {@link #LOG_DEBUG} and
* {@link #LOG_VERBOSE}.
*/
private int getLoggingLevel() {
int loggingLevel;
if (Log.isLoggable(LOG_TAG, Log.VERBOSE)) {
loggingLevel = LOG_VERBOSE;
} else if (Log.isLoggable(LOG_TAG, Log.DEBUG)) {
loggingLevel = LOG_DEBUG;
} else {
loggingLevel = LOG_NONE;
}
return loggingLevel;
}
@SuppressWarnings("unused")
@CalledByNative
private void initNetworkThread() {
synchronized (mLock) {
mNetworkThread = Thread.currentThread();
mInitCompleted.open();
}
Thread.currentThread().setName("ChromiumNet");
Process.setThreadPriority(Process.<API key>);
}
@SuppressWarnings("unused")
@CalledByNative
private void onRttObservation(final int rttMs, final long whenMs, final int source) {
synchronized (mNetworkQualityLock) {
for (final <API key> listener : mRttListenerList) {
Runnable task = new Runnable() {
@Override
public void run() {
listener.onRttObservation(rttMs, whenMs, source);
}
};
<API key>(listener.getExecutor(), task);
}
}
}
@SuppressWarnings("unused")
@CalledByNative
private void <API key>(
final int throughputKbps, final long whenMs, final int source) {
synchronized (mNetworkQualityLock) {
for (final <API key> listener : <API key>) {
Runnable task = new Runnable() {
@Override
public void run() {
listener.<API key>(throughputKbps, whenMs, source);
}
};
<API key>(listener.getExecutor(), task);
}
}
}
@SuppressWarnings("unused")
@CalledByNative
private void <API key>(String certVerifierData) {
mCertVerifierData = certVerifierData;
<API key>.open();
}
void reportFinished(final CronetUrlRequest request) {
final RequestFinishedInfo requestInfo = request.<API key>();
ArrayList<RequestFinishedInfo.Listener> currentListeners;
synchronized (<API key>) {
currentListeners = new ArrayList<RequestFinishedInfo.Listener>(<API key>);
}
for (final RequestFinishedInfo.Listener listener : currentListeners) {
Runnable task = new Runnable() {
@Override
public void run() {
listener.onRequestFinished(requestInfo);
}
};
<API key>(listener.getExecutor(), task);
}
}
private static void <API key>(Executor executor, Runnable task) {
try {
executor.execute(task);
} catch (<API key> failException) {
Log.e(<API key>.LOG_TAG, "Exception posting task to executor",
failException);
}
}
// Native methods are implemented in <API key>.cc.
private static native long <API key>(String userAgent,
String storagePath, boolean quicEnabled, String quicUserAgentId, boolean http2Enabled,
boolean sdchEnabled, String <API key>,
String <API key>, String <API key>,
String <API key>, boolean disableCache, int httpCacheMode,
long httpCacheMaxSize, String experimentalOptions, long mockCertVerifier,
boolean <API key>,
boolean <API key>, String certVerifierData);
private static native void nativeAddQuicHint(
long <API key>, String host, int port, int alternatePort);
private static native void nativeAddPkp(long <API key>, String host,
byte[][] hashes, boolean includeSubdomains, long expirationTime);
private static native long <API key>(long <API key>);
private static native int <API key>(int loggingLevel);
private static native byte[] <API key>();
@<API key>("<API key>")
private native void nativeDestroy(long nativePtr);
@<API key>("<API key>")
private native void <API key>(long nativePtr, String fileName, boolean logAll);
@<API key>("<API key>")
private native void nativeStopNetLog(long nativePtr);
@<API key>("<API key>")
private native void <API key>(long nativePtr);
@<API key>("<API key>")
private native void <API key>(long nativePtr);
@<API key>("<API key>")
private native void <API key>(
long nativePtr, boolean <API key>, boolean useSmallerResponses);
@<API key>("<API key>")
private native void <API key>(long nativePtr, boolean should);
@<API key>("<API key>")
private native void <API key>(long nativePtr, boolean should);
}
|
#ifndef <API key>
#define <API key>
#include <flux/meta/MetaObject>
namespace flux {
namespace meta {
/** \brief Duck-typed object protocol
*/
class MetaProtocol: public Object
{
public:
inline static Ref<MetaProtocol> create() {
return new MetaProtocol;
}
template<class Prototype>
Prototype *define(const String &className) {
Ref<Prototype> prototype = Prototype::create(className);
define(prototype);
return prototype;
}
template<class Prototype>
Prototype *define() {
Ref<Prototype> prototype = Prototype::create();
define(prototype);
return prototype;
}
MetaObject *define(MetaObject *prototype) {
prototype->define();
prototypes()->insert(prototype->className(), prototype);
return prototype;
}
template<class Prototype>
static Ref<MetaObject> createPrototype() {
Ref<MetaObject> prototype = Prototype::create();
prototype->define();
return prototype;
}
virtual MetaObject *lookup(String className) const {
MetaObject *prototype = 0;
if (prototypes_) prototypes_->lookup(className, &prototype);
return prototype;
}
int minCount() const { return minCount_; }
int maxCount() const { return maxCount_; }
void minCount(int newCount) { minCount_ = newCount; }
void maxCount(int newCount) { maxCount_ = newCount; }
inline bool lookup(const String &className, MetaObject **prototype) const {
*prototype = lookup(className);
return *prototype;
}
protected:
friend class YasonSyntax;
MetaProtocol():
minCount_(0),
maxCount_(flux::intMax)
{}
virtual Ref<MetaObject> produce(MetaObject *prototype) const {
return prototype->produce();
}
private:
typedef Map<String, Ref<MetaObject> > Prototypes;
Prototypes *prototypes() {
if (!prototypes_) prototypes_ = Prototypes::create();
return prototypes_;
}
Ref<Prototypes> prototypes_;
int minCount_;
int maxCount_;
};
}} // namespace flux::meta
#endif // <API key>
|
module Carto
module Configuration
def db_config
@@db_config ||= YAML.load(File.read(db_config_file)).freeze
end
def app_config
@@app_config ||= YAML.load_file(app_config_file).freeze
end
def frontend_version
@@frontend_version ||= JSON::parse(File.read(Rails.root.join("package.json")))["version"]
end
def env_app_config
app_config[ENV['RAILS_ENV'] || 'development']
end
def log_file_path(filename)
"#{log_dir_path}/#{filename}"
end
def log_dir_path
"#{log_files_root}/log"
end
def <API key>
public_uploads_path('uploads')
end
def public_uploads_path(subfolder = '')
<API key>('<API key>', subfolder) do
if env_app_config && env_app_config[:importer] && env_app_config[:importer]["uploads_path"]
env_app_config[:importer]["uploads_path"]
else
Rails.root.join('public', subfolder).to_s
end
end
end
def uploaded_file_path(path)
pathname = Pathname.new(path)
return path if pathname.exist? && pathname.absolute?
upload_path = Cartodb.get_config(:importer, 'uploads_path')
if upload_path
# Ugly patch needed for backwards compatibility
"#{upload_path}#{path}".gsub('/uploads/uploads/', '/uploads/')
else
Rails.root.join("public#{path}").to_s
end
end
def <API key>
config = env_app_config
(config && config['custom_paths'] && config['custom_paths']['views']) || Array.new
end
def saas?
Cartodb.config[:cartodb_com_hosted] == false
end
def mapzen_api_key
Cartodb.get_config(:geocoder, 'mapzen', 'search_bar_api_key')
end
def mapbox_api_key
Cartodb.get_config(:geocoder, 'mapbox', 'search_bar_api_key')
end
# Make some methods available. Remember that this sets methods as private.
# This is the chosen approach to avoid including `Configuration` all over the place. Check #12757
module_function :saas?
private
def config_files_root
rails_path('<API key>')
end
def log_files_root
rails_path('RAILS_LOG_BASE_PATH')
end
def rails_path(<API key>)
<API key>(<API key>) { Rails.root }
end
# Returns an string, block should as well
def <API key>(<API key>, <API key> = '')
if ENV[<API key>]
Pathname.new(ENV[<API key>]).join(<API key>).to_s
else
alternative = yield
alternative || ''
end
end
def db_config_file
if ENV['RAILS_DATABASE_FILE']
File.join(config_files_root, 'config/' + ENV['RAILS_DATABASE_FILE'])
else
File.join(config_files_root, 'config/database.yml')
end
end
def app_config_file
"#{config_files_root}/config/app_config.yml"
end
end
class Conf
include Carto::Configuration
end
end
|
<!DOCTYPE HTML PUBLIC "-
<!--NewPage
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_33) on Fri Jul 13 11:10:51 CEST 2012 -->
<TITLE>
Sample
</TITLE>
<META NAME="date" CONTENT="2012-07-13">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Sample";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<A NAME="navbar_top"></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/Sample.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../converter/<API key>.html" title="class in converter"><B>PREV CLASS</B></A>
<A HREF="../converter/TigerXmlConverter.html" title="class in converter"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../index.html?converter/Sample.html" target="_top"><B>FRAMES</B></A>
<A HREF="Sample.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<HR>
<H2>
<FONT SIZE="-1">
converter</FONT>
<BR>
Class Sample</H2>
<PRE>
java.lang.Object
<IMG SRC="../resources/inherit.gif" ALT="extended by "><B>converter.Sample</B>
</PRE>
<HR>
<DL>
<DT><PRE>public class <B>Sample</B><DT>extends java.lang.Object</DL>
</PRE>
<P>
<HR>
<P>
<A NAME="constructor_summary"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Constructor Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../converter/Sample.html#Sample()">Sample</A></B>()</CODE>
<BR>
</TD>
</TR>
</TABLE>
<A NAME="method_summary"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Method Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../converter/Sample.html#<API key>()"><API key></A></B>()</CODE>
<BR>
</TD>
</TR>
</TABLE>
<A NAME="<API key>.lang.Object"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="<API key>">
<TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD>
</TR>
</TABLE>
<P>
<A NAME="constructor_detail"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Constructor Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="Sample()"></A><H3>
Sample</H3>
<PRE>
public <B>Sample</B>()</PRE>
<DL>
</DL>
<A NAME="method_detail"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Method Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="<API key>()"></A><H3>
<API key></H3>
<PRE>
public void <B><API key></B>()</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="navbar_bottom"></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="<API key>"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/Sample.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../converter/<API key>.html" title="class in converter"><B>PREV CLASS</B></A>
<A HREF="../converter/TigerXmlConverter.html" title="class in converter"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../index.html?converter/Sample.html" target="_top"><B>FRAMES</B></A>
<A HREF="Sample.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<HR>
</BODY>
</HTML>
|
/**
@file speex_bits.h
@brief Handles bit packing/unpacking
*/
#ifndef BITS_H
#define BITS_H
/** @defgroup SpeexBits SpeexBits: Bit-stream manipulations
* This is the structure that holds the bit-stream when encoding or decoding
* with Speex. It allows some manipulations as well.
* @{
*/
#include "speex_types.h"
#ifdef __cplusplus
extern "C" {
#endif
/** Bit-packing data structure representing (part of) a bit-stream. */
typedef struct SpeexBits {
char *chars; /**< "raw" data */
int nbBits; /**< Total number of bits stored in the stream*/
int charPtr; /**< Position of the byte "cursor" */
int bitPtr; /**< Position of the bit "cursor" within the current char */
int owner; /**< Does the struct "own" the "raw" buffer (member "chars") */
int overflow;/**< Set to one if we try to read past the valid data */
int buf_size;/**< Allocated size for buffer */
int reserved1; /**< Reserved for future use */
void *reserved2; /**< Reserved for future use */
} SpeexBits;
/** Initializes and allocates resources for a SpeexBits struct */
PUBLIC_API void speex_bits_init(SpeexBits *bits);
/** Initializes SpeexBits struct using a pre-allocated buffer*/
PUBLIC_API void <API key>(SpeexBits *bits, void *buff, int buf_size);
/** Sets the bits in a SpeexBits struct to use data from an existing buffer (for decoding without copying data) */
PUBLIC_API void <API key>(SpeexBits *bits, void *buff, int buf_size);
/** Frees all resources associated to a SpeexBits struct. Right now this does nothing since no resources are allocated, but this could change in the future.*/
PUBLIC_API void speex_bits_destroy(SpeexBits *bits);
/** Resets bits to initial value (just after initialization, erasing content)*/
PUBLIC_API void speex_bits_reset(SpeexBits *bits);
/** Rewind the bit-stream to the beginning (ready for read) without erasing the content */
PUBLIC_API void speex_bits_rewind(SpeexBits *bits);
/** Initializes the bit-stream from the data in an area of memory */
PUBLIC_API void <API key>(SpeexBits *bits, const char *bytes, int len);
/** Append bytes to the bit-stream
*
* @param bits Bit-stream to operate on
* @param bytes pointer to the bytes what will be appended
* @param len Number of bytes of append
*/
PUBLIC_API void <API key>(SpeexBits *bits, const char *bytes, int len);
/** Write the content of a bit-stream to an area of memory
*
* @param bits Bit-stream to operate on
* @param bytes Memory location where to write the bits
* @param max_len Maximum number of bytes to write (i.e. size of the "bytes" buffer)
* @return Number of bytes written to the "bytes" buffer
*/
PUBLIC_API int speex_bits_write(SpeexBits *bits, char *bytes, int max_len);
/** Like speex_bits_write, but writes only the complete bytes in the stream. Also removes the written bytes from the stream */
PUBLIC_API int <API key>(SpeexBits *bits, char *bytes, int max_len);
/** Append bits to the bit-stream
* @param bits Bit-stream to operate on
* @param data Value to append as integer
* @param nbBits number of bits to consider in "data"
*/
PUBLIC_API void speex_bits_pack(SpeexBits *bits, int data, int nbBits);
/** Interpret the next bits in the bit-stream as a signed integer
*
* @param bits Bit-stream to operate on
* @param nbBits Number of bits to interpret
* @return A signed integer represented by the bits read
*/
PUBLIC_API int <API key>(SpeexBits *bits, int nbBits);
/** Interpret the next bits in the bit-stream as an unsigned integer
*
* @param bits Bit-stream to operate on
* @param nbBits Number of bits to interpret
* @return An unsigned integer represented by the bits read
*/
PUBLIC_API unsigned int <API key>(SpeexBits *bits, int nbBits);
/** Returns the number of bytes in the bit-stream, including the last one even if it is not "full"
*
* @param bits Bit-stream to operate on
* @return Number of bytes in the stream
*/
PUBLIC_API int speex_bits_nbytes(SpeexBits *bits);
/** Same as <API key>, but without modifying the cursor position
*
* @param bits Bit-stream to operate on
* @param nbBits Number of bits to look for
* @return Value of the bits peeked, interpreted as unsigned
*/
PUBLIC_API unsigned int <API key>(SpeexBits *bits, int nbBits);
/** Get the value of the next bit in the stream, without modifying the
* "cursor" position
*
* @param bits Bit-stream to operate on
* @return Value of the bit peeked (one bit only)
*/
PUBLIC_API int speex_bits_peek(SpeexBits *bits);
/** Advances the position of the "bit cursor" in the stream
*
* @param bits Bit-stream to operate on
* @param n Number of bits to advance
*/
PUBLIC_API void speex_bits_advance(SpeexBits *bits, int n);
/** Returns the number of bits remaining to be read in a stream
*
* @param bits Bit-stream to operate on
* @return Number of bits that can still be read from the stream
*/
PUBLIC_API int <API key>(SpeexBits *bits);
/** Insert a terminator so that the data can be sent as a packet while auto-detecting
* the number of frames in each packet
*
* @param bits Bit-stream to operate on
*/
PUBLIC_API void <API key>(SpeexBits *bits);
#ifdef __cplusplus
}
#endif
#endif
|
package org.exist.storage.index;
import java.nio.ByteBuffer;
import org.exist.storage.DBBroker;
import org.exist.storage.journal.LogException;
import org.exist.storage.txn.Txn;
/**
* @author wolf
*
*/
public class RemoveValueLoggable extends <API key> {
protected long page;
protected short tid;
protected byte[] oldData;
protected int offset = 0;
protected int len;
/**
*
*
* @param page
* @param tid
* @param oldData
* @param offset
* @param len
* @param fileId
* @param transaction
*/
public RemoveValueLoggable(Txn transaction, byte fileId, long page, short tid, byte[] oldData, int offset, int len) {
super(BFile.LOG_REMOVE_VALUE, fileId, transaction);
this.page = page;
this.tid = tid;
this.oldData = oldData;
this.offset = offset;
this.len = len;
}
/**
* @param broker
* @param transactionId
*/
public RemoveValueLoggable(DBBroker broker, long transactionId) {
super(broker, transactionId);
}
public void write(ByteBuffer out) {
super.write(out);
out.putInt((int) page);
out.putShort(tid);
out.putShort((short) len);
out.put(oldData, offset, len);
}
public void read(ByteBuffer in) {
super.read(in);
page = in.getInt();
tid = in.getShort();
len = in.getShort();
oldData = new byte[len];
in.get(oldData);
}
public int getLogSize() {
return super.getLogSize() + len + 8;
}
public void redo() throws LogException {
getIndexFile().redoRemoveValue(this);
}
public void undo() throws LogException {
getIndexFile().undoRemoveValue(this);
}
public String dump() {
return super.dump() + " - remove value with tid " + tid + " from page " + page;
}
}
|
#!/usr/bin/env perl
use strict;
use warnings;
use LWP::UserAgent;
use JSON::PP;
my $base = "http://gameai.skullspace.ca/api/";
sub failure {
print("!! " . shift(@_) . "\n");
exit(1);
}
sub info {
print("** " . shift(@_) . "\n");
}
sub parse_card {
my $abbr = shift(@_);
my %card = ("abbr" => $abbr);
my $suit = substr($abbr, 0, 1);
if ($suit eq "C") {
$card{"suit"} = "CLUBS";
}
elsif ($suit eq "D") {
$card{"suit"} = "DIAMONDS";
}
elsif ($suit eq "H") {
$card{"suit"} = "HEARTS";
}
else {
$card{"suit"} = "SPADES";
}
$card{"value"} = int(substr($abbr, 1, 2));
return %card;
}
sub rawapi {
my $method = shift(@_);
my (%params) = @_;
# Collect parameters into a JSON object.
my $json = JSON::PP->new;
my $json_params = $json->encode(\%params);
# Create the URL of the endpoint.
my $url = $base . $method . "/";
# Create a new HTTP request to the endpoint.
my $req = HTTP::Request->new(POST => $url);
# Set up the HTTP request's properties.
$req->header("Content-type" => "application/json");
# Set the HTTP request's body.
$req->content($json_params);
# Send the HTTP request.
my $con = LWP::UserAgent->new;
my $res = $con->request($req);
# Check for errors.
if (!$res->is_success) {
failure("An unknown error occurred during the API call.");
}
# Read the HTTP response code.
if ($res->code != 200) {
failure("The server responded with a status code other than 200.");
}
# Read the HTTP response body.
return $json->decode($res->decoded_content);
}
sub api {
my $method = shift(@_);
my (%params) = @_;
my $json = rawapi($method, %params);
if ($json->{"result"} eq "failure") {
failure($json->{"reason"});
}
return $json;
}
sub main {
my (@argv) = @_;
# Ensure we've been given a name and a password.
my $name;
my $pass;
if (@argv != 2) {
print("Enter your bot's name: ");
$name = <STDIN>;
chomp($name);
print("Enter your bot's password: ");
$pass = <STDIN>;
chomp($pass);
}
else {
$name = $argv[0];
$pass = $argv[1];
}
# Register the name, which will have no effect if you've already done it.
rawapi("register", ("name" => $name, "password" => $pass));
# Login with the name and password.
info("Logging in to the server...");
my $json = api("login", ("name" => $name, "password" => $pass));
info("Logged in.");
# Store the session from the login for future use.
my $session = $json->{"session"};
info("Received session '$session'.");
while (1) {
# Ask to be given an opponent to play against.
info("Attempting to start a new game...");
$json = api("new-game", ("session" => $session));
# If there's nobody to play against, start the loop from the top after
# waiting 5 seconds.
if ($json->{"result"} eq "retry") {
print("?? " . $json->{"reason"} . "\n");
sleep(5);
next;
}
# Create an object to represent the cards we have been dealt.
my @cards = @{$json->{"cards"}};
info("We have started a new game, and have been dealt: " . join(", ", @cards) . ".");
# Run the game AI.
new_game($session, @cards);
# Cleanup from our game.
info("Our role in this game is over, but we need to be sure the server has ended the game before we start a new one.");
info("If we try to start a new game without the old one being done, the server will reject our request.");
while (1) {
info("Waiting for our game to be over...");
$json = api("status", ("session" => $session));
if (!defined $json->{"game"}) {
last;
}
sleep(1);
}
info("The server has ended our game.");
}
}
sub new_game {
my $session = shift(@_);
my @hand = @_;
# Make a bid, which we'll do randomly, by choosing a number between 1 and
my $bid = int(1 + rand(13));
# Register our bid with the server.
info("Attempting to bid " . $bid . ".");
api("bid", ("session" => $session, "bid" => $bid));
info("Our bid has been accepted.");
# Check the status repeatedly, and if it's our turn play a card, until all
# cards have been played and the game ends.
while (@hand) {
# Always wait 1 second, it may not seem like much but it helps avoid
# pinning the client's CPU and flooding the server.
sleep(1);
# Request the game's status from the server.
info("Requesting the status of our game...");
my $json = api("status", ("session" => $session));
info("Status received.");
# If the game has ended prematurely, due to a forfeit from your opponent
# or some other reason, rejoice and find a new opponent.
if (!defined $json->{"game"}) {
info("Our game appears to have ended.");
return;
}
# If we're still in the bidding process, it's nobody's turn.
if (!defined $json->{"your-turn"}) {
info("Our game is still in the bidding phase, we need to wait for our opponent.");
next;
}
# If not it's not our turn yet, jump back to the top of the loop to
# check the status again.
if (not $json->{"your-turn"}) {
info("It is currently our opponent's turn, we need to wait for our opponent.");
next;
}
# Finally, it's our turn. First, we have to determine if another card
# was played first in this round. If so, it restricts our choices.
my @allowed_cards;
if (!defined $json->{"<API key>"}) {
# We can play any card we want, since we're going first in this
# round. So all the cards in our hand are allowed.
@allowed_cards = @hand;
info("We have the lead this round, so we may choose any card.");
}
else {
# We can only play cards that match the suit of the lead card, since
# we're going second in this round. Gather together all the cards in
# our hand that have the appropriate suit.
@allowed_cards = ();
my %lead_card = parse_card($json->{"<API key>"});
info("Our opponent has lead this round, so we must try to play a card that matches the lead card's suit: " . $lead_card{"suit"} . ".");
foreach my $card (@hand) {
my %card = parse_card($card);
if ($card{"suit"} eq $lead_card{"suit"}) {
push(@allowed_cards, $card{"abbr"});
}
}
# Check if we actually found any cards in our hand with the
# appropriate suit. If we don't have any, there are no restrictions
# on the card we can then play.
if (!@allowed_cards) {
info("We have no " . $lead_card{"suit"} . " in our hand, so we can play any suit we choose.");
@allowed_cards = @hand;
}
}
# Among the cards that we have determined are valid, according to the
# rules, choose one to play at random.
my $idx = int(rand(@allowed_cards));
my $card = $allowed_cards[$idx];
info("We have randomly chosen " . $card . ".");
# Now that the card has been chosen, play it.
info("Attempting to play " . $card . "...");
api("play", ("session" => $session, "card" => $card));
info("Card has been played.");
# Remove the card from our hand.
my @new_hand = ();
foreach my $card_in_hand (@hand) {
if ($card_in_hand ne $card) {
push(@new_hand, $card_in_hand);
}
}
@hand = @new_hand;
}
}
main(@ARGV);
|
<!DOCTYPE html>
<html xmlns="http:
<head>
<meta charset="utf-8" />
<title>statsmodels.robust.robust_linear_model.RLMResults.pvalues — statsmodels v0.10.2 documentation</title>
<link rel="stylesheet" href="../_static/nature.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<link rel="stylesheet" type="text/css" href="../_static/graphviz.css" />
<script type="text/javascript" id="<API key>" data-url_root="../" src="../_static/<API key>.js"></script>
<script type="text/javascript" src="../_static/jquery.js"></script>
<script type="text/javascript" src="../_static/underscore.js"></script>
<script type="text/javascript" src="../_static/doctools.js"></script>
<script type="text/javascript" src="../_static/language_data.js"></script>
<script async="async" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=<API key>"></script>
<link rel="shortcut icon" href="../_static/<API key>.ico"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="next" title="statsmodels.robust.robust_linear_model.RLMResults.remove_data" href="statsmodels.robust.robust_linear_model.RLMResults.remove_data.html" />
<link rel="prev" title="statsmodels.robust.robust_linear_model.RLMResults.predict" href="statsmodels.robust.robust_linear_model.RLMResults.predict.html" />
<link rel="stylesheet" href="../_static/examples.css" type="text/css" />
<link rel="stylesheet" href="../_static/facebox.css" type="text/css" />
<script type="text/javascript" src="../_static/scripts.js">
</script>
<script type="text/javascript" src="../_static/facebox.js">
</script>
<script type="text/javascript">
$.facebox.settings.closeImage = "../_static/closelabel.png"
$.facebox.settings.loadingImage = "../_static/loading.gif"
</script>
<script>
$(document).ready(function() {
$.getJSON("../../versions.json", function(versions) {
var dropdown = document.createElement("div");
dropdown.className = "dropdown";
var button = document.createElement("button");
button.className = "dropbtn";
button.innerHTML = "Other Versions";
var content = document.createElement("div");
content.className = "dropdown-content";
dropdown.appendChild(button);
dropdown.appendChild(content);
$(".header").prepend(dropdown);
for (var i = 0; i < versions.length; i++) {
if (versions[i].substring(0, 1) == "v") {
versions[i] = [versions[i], versions[i].substring(1)];
} else {
versions[i] = [versions[i], versions[i]];
};
};
for (var i = 0; i < versions.length; i++) {
var a = document.createElement("a");
a.innerHTML = versions[i][1];
a.href = "../../" + versions[i][0] + "/index.html";
a.title = versions[i][1];
$(".dropdown-content").append(a);
};
});
});
</script>
</head><body>
<div class="headerwrap">
<div class = "header">
<a href = "../index.html">
<img src="../_static/<API key>.png" alt="Logo"
style="padding-left: 15px"/></a>
</div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="../py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li class="right" >
<a href="statsmodels.robust.robust_linear_model.RLMResults.remove_data.html" title="statsmodels.robust.robust_linear_model.RLMResults.remove_data"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="statsmodels.robust.robust_linear_model.RLMResults.predict.html" title="statsmodels.robust.robust_linear_model.RLMResults.predict"
accesskey="P">previous</a> |</li>
<li><a href ="../install.html">Install</a></li> |
<li><a href="https://groups.google.com/forum/?hl=en#!forum/pystatsmodels">Support</a></li> |
<li><a href="https://github.com/statsmodels/statsmodels/issues">Bugs</a></li> |
<li><a href="../dev/index.html">Develop</a></li> |
<li><a href="../examples/index.html">Examples</a></li> |
<li><a href="../faq.html">FAQ</a></li> |
<li class="nav-item nav-item-1"><a href="../rlm.html" >Robust Linear Models</a> |</li>
<li class="nav-item nav-item-2"><a href="statsmodels.robust.robust_linear_model.RLMResults.html" accesskey="U">statsmodels.robust.robust_linear_model.RLMResults</a> |</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="<API key>">
<h1>statsmodels.robust.robust_linear_model.RLMResults.pvalues<a class="headerlink" href="
<p>method</p>
<dl class="method">
<dt id="statsmodels.robust.robust_linear_model.RLMResults.pvalues">
<code class="sig-prename descclassname">RLMResults.</code><code class="sig-name descname">pvalues</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="../_modules/statsmodels/robust/robust_linear_model.html
<dd><p>The two-tailed p values for the t-stats of the params.</p>
</dd></dl>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="<API key>">
<h4>Previous topic</h4>
<p class="topless"><a href="statsmodels.robust.robust_linear_model.RLMResults.predict.html"
title="previous chapter">statsmodels.robust.robust_linear_model.RLMResults.predict</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="statsmodels.robust.robust_linear_model.RLMResults.remove_data.html"
title="next chapter">statsmodels.robust.robust_linear_model.RLMResults.remove_data</a></p>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../_sources/generated/statsmodels.robust.robust_linear_model.RLMResults.pvalues.rst.txt"
rel="nofollow">Show Source</a></li>
</ul>
</div>
<div id="searchbox" style="display: none" role="search">
<h3 id="searchlabel">Quick search</h3>
<div class="searchformwrapper">
<form class="search" action="../search.html" method="get">
<input type="text" name="q" aria-labelledby="searchlabel" />
<input type="submit" value="Go" />
</form>
</div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="footer" role="contentinfo">
&
Created using <a href="http://sphinx-doc.org/">Sphinx</a> 2.2.1.
</div>
</body>
</html>
|
// This file is part of the RDKit.
// of the RDKit source tree.
#include <GraphMol/RDKitBase.h>
#include <GraphMol/Fingerprints/AtomPairs.h>
#include <GraphMol/Subgraphs/Subgraphs.h>
#include <DataStructs/SparseIntVect.h>
#include <RDGeneral/hash/hash.hpp>
#include <boost/cstdint.hpp>
#include <boost/dynamic_bitset.hpp>
#include <boost/foreach.hpp>
namespace RDKit {
namespace AtomPairs {
unsigned int numPiElectrons(const Atom *atom) {
PRECONDITION(atom, "no atom");
unsigned int res = 0;
if (atom->getIsAromatic()) {
res = 1;
} else if (atom->getHybridization() != Atom::SP3) {
unsigned int val = static_cast<unsigned int>(atom->getExplicitValence());
val -= atom->getNumExplicitHs();
CHECK_INVARIANT(val >= atom->getDegree(),
"explicit valence exceeds atom degree");
res = val - atom->getDegree();
}
return res;
}
boost::uint32_t getAtomCode(const Atom *atom, unsigned int branchSubtract,
bool includeChirality) {
PRECONDITION(atom, "no atom");
boost::uint32_t code;
unsigned int numBranches = 0;
if (atom->getDegree() > branchSubtract) {
numBranches = atom->getDegree() - branchSubtract;
}
code = numBranches % maxNumBranches;
unsigned int nPi = numPiElectrons(atom) % maxNumPi;
code |= nPi << numBranchBits;
unsigned int typeIdx = 0;
unsigned int nTypes = 1 << numTypeBits;
while (typeIdx < nTypes) {
if (atomNumberTypes[typeIdx] ==
static_cast<unsigned int>(atom->getAtomicNum())) {
break;
} else if (atomNumberTypes[typeIdx] >
static_cast<unsigned int>(atom->getAtomicNum())) {
typeIdx = nTypes;
break;
}
++typeIdx;
}
if (typeIdx == nTypes) --typeIdx;
code |= typeIdx << (numBranchBits + numPiBits);
if (includeChirality) {
std::string cipCode;
if (atom->getPropIfPresent(common_properties::_CIPCode, cipCode)) {
boost::uint32_t offset = numBranchBits + numPiBits + numTypeBits;
if (cipCode == "R") {
code |= 1 << offset;
} else if (cipCode == "S") {
code |= 2 << offset;
}
}
}
POSTCONDITION(code < (1 << (codeSize + (includeChirality ? 2 : 0))),
"code exceeds number of bits");
return code;
};
boost::uint32_t getAtomPairCode(boost::uint32_t codeI, boost::uint32_t codeJ,
unsigned int dist, bool includeChirality) {
PRECONDITION(dist < maxPathLen, "dist too long");
boost::uint32_t res = dist;
res |= std::min(codeI, codeJ) << numPathBits;
res |= std::max(codeI, codeJ)
<< (numPathBits + codeSize + (includeChirality ? numChiralBits : 0));
return res;
}
template <typename T1, typename T2>
void updateElement(SparseIntVect<T1> &v, T2 elem) {
v.setVal(elem, v.getVal(elem) + 1);
}
template <typename T1>
void updateElement(ExplicitBitVect &v, T1 elem) {
v.setBit(elem % v.getNumBits());
}
template <typename T>
void setAtomPairBit(boost::uint32_t i, boost::uint32_t j,
boost::uint32_t nAtoms,
const std::vector<boost::uint32_t> &atomCodes,
const double *dm, T *bv, unsigned int minLength,
unsigned int maxLength, bool includeChirality) {
unsigned int dist = static_cast<unsigned int>(floor(dm[i * nAtoms + j]));
if (dist >= minLength && dist <= maxLength) {
boost::uint32_t bitId =
getAtomPairCode(atomCodes[i], atomCodes[j], dist, includeChirality);
updateElement(*bv, static_cast<boost::uint32_t>(bitId));
}
}
SparseIntVect<boost::int32_t> *<API key>(
const ROMol &mol, const std::vector<boost::uint32_t> *fromAtoms,
const std::vector<boost::uint32_t> *ignoreAtoms,
const std::vector<boost::uint32_t> *atomInvariants, bool includeChirality,
bool use2D, int confId) {
return <API key>(mol, 1, maxPathLen - 1, fromAtoms, ignoreAtoms,
atomInvariants, includeChirality, use2D,
confId);
};
SparseIntVect<boost::int32_t> *<API key>(
const ROMol &mol, unsigned int minLength, unsigned int maxLength,
const std::vector<boost::uint32_t> *fromAtoms,
const std::vector<boost::uint32_t> *ignoreAtoms,
const std::vector<boost::uint32_t> *atomInvariants, bool includeChirality,
bool use2D, int confId) {
PRECONDITION(minLength <= maxLength, "bad lengths provided");
PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),
"bad atomInvariants size");
SparseIntVect<boost::int32_t> *res = new SparseIntVect<boost::int32_t>(
1 << (<API key> + 2 * (includeChirality ? 2 : 0)));
const double *dm;
if (use2D) {
dm = MolOps::getDistanceMat(mol);
} else {
dm = MolOps::get3DDistanceMat(mol, confId);
}
const unsigned int nAtoms = mol.getNumAtoms();
std::vector<boost::uint32_t> atomCodes;
for (ROMol::ConstAtomIterator atomItI = mol.beginAtoms();
atomItI != mol.endAtoms(); ++atomItI) {
if (!atomInvariants) {
atomCodes.push_back(getAtomCode(*atomItI, 0, includeChirality));
} else {
atomCodes.push_back((*atomInvariants)[(*atomItI)->getIdx()] %
((1 << codeSize) - 1));
}
}
for (ROMol::ConstAtomIterator atomItI = mol.beginAtoms();
atomItI != mol.endAtoms(); ++atomItI) {
unsigned int i = (*atomItI)->getIdx();
if (ignoreAtoms &&
std::find(ignoreAtoms->begin(), ignoreAtoms->end(), i) !=
ignoreAtoms->end()) {
continue;
}
if (!fromAtoms) {
for (ROMol::ConstAtomIterator atomItJ = atomItI + 1;
atomItJ != mol.endAtoms(); ++atomItJ) {
unsigned int j = (*atomItJ)->getIdx();
if (ignoreAtoms &&
std::find(ignoreAtoms->begin(), ignoreAtoms->end(), j) !=
ignoreAtoms->end()) {
continue;
}
setAtomPairBit(i, j, nAtoms, atomCodes, dm, res, minLength, maxLength,
includeChirality);
}
} else {
BOOST_FOREACH (boost::uint32_t j, *fromAtoms) {
if (j != i) {
if (ignoreAtoms &&
std::find(ignoreAtoms->begin(), ignoreAtoms->end(), j) !=
ignoreAtoms->end()) {
continue;
}
setAtomPairBit(i, j, nAtoms, atomCodes, dm, res, minLength, maxLength,
includeChirality);
}
}
}
}
return res;
}
SparseIntVect<boost::int32_t> *<API key>(
const ROMol &mol, unsigned int nBits, unsigned int minLength,
unsigned int maxLength, const std::vector<boost::uint32_t> *fromAtoms,
const std::vector<boost::uint32_t> *ignoreAtoms,
const std::vector<boost::uint32_t> *atomInvariants, bool includeChirality,
bool use2D, int confId) {
PRECONDITION(minLength <= maxLength, "bad lengths provided");
PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),
"bad atomInvariants size");
SparseIntVect<boost::int32_t> *res = new SparseIntVect<boost::int32_t>(nBits);
const double *dm;
if (use2D) {
dm = MolOps::getDistanceMat(mol);
} else {
dm = MolOps::get3DDistanceMat(mol, confId);
}
const unsigned int nAtoms = mol.getNumAtoms();
std::vector<boost::uint32_t> atomCodes;
atomCodes.reserve(nAtoms);
for (ROMol::ConstAtomIterator atomItI = mol.beginAtoms();
atomItI != mol.endAtoms(); ++atomItI) {
if (!atomInvariants) {
atomCodes.push_back(getAtomCode(*atomItI, 0, includeChirality));
} else {
atomCodes.push_back((*atomInvariants)[(*atomItI)->getIdx()]);
}
}
for (ROMol::ConstAtomIterator atomItI = mol.beginAtoms();
atomItI != mol.endAtoms(); ++atomItI) {
unsigned int i = (*atomItI)->getIdx();
if (ignoreAtoms &&
std::find(ignoreAtoms->begin(), ignoreAtoms->end(), i) !=
ignoreAtoms->end()) {
continue;
}
if (!fromAtoms) {
for (ROMol::ConstAtomIterator atomItJ = atomItI + 1;
atomItJ != mol.endAtoms(); ++atomItJ) {
unsigned int j = (*atomItJ)->getIdx();
if (ignoreAtoms &&
std::find(ignoreAtoms->begin(), ignoreAtoms->end(), j) !=
ignoreAtoms->end()) {
continue;
}
unsigned int dist =
static_cast<unsigned int>(floor(dm[i * nAtoms + j]));
if (dist >= minLength && dist <= maxLength) {
boost::uint32_t bit = 0;
gboost::hash_combine(bit, std::min(atomCodes[i], atomCodes[j]));
gboost::hash_combine(bit, dist);
gboost::hash_combine(bit, std::max(atomCodes[i], atomCodes[j]));
updateElement(*res, static_cast<boost::int32_t>(bit % nBits));
}
}
} else {
BOOST_FOREACH (boost::uint32_t j, *fromAtoms) {
if (j != i) {
if (ignoreAtoms &&
std::find(ignoreAtoms->begin(), ignoreAtoms->end(), j) !=
ignoreAtoms->end()) {
continue;
}
unsigned int dist =
static_cast<unsigned int>(floor(dm[i * nAtoms + j]));
if (dist >= minLength && dist <= maxLength) {
boost::uint32_t bit = 0;
gboost::hash_combine(bit, std::min(atomCodes[i], atomCodes[j]));
gboost::hash_combine(bit, dist);
gboost::hash_combine(bit, std::max(atomCodes[i], atomCodes[j]));
updateElement(*res, static_cast<boost::int32_t>(bit % nBits));
}
}
}
}
}
return res;
}
ExplicitBitVect *<API key>(
const ROMol &mol, unsigned int nBits, unsigned int minLength,
unsigned int maxLength, const std::vector<boost::uint32_t> *fromAtoms,
const std::vector<boost::uint32_t> *ignoreAtoms,
const std::vector<boost::uint32_t> *atomInvariants,
unsigned int nBitsPerEntry, bool includeChirality, bool use2D, int confId) {
PRECONDITION(minLength <= maxLength, "bad lengths provided");
PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),
"bad atomInvariants size");
static int bounds[4] = {1, 2, 4, 8};
unsigned int blockLength = nBits / nBitsPerEntry;
SparseIntVect<boost::int32_t> *sres = <API key>(
mol, blockLength, minLength, maxLength, fromAtoms, ignoreAtoms,
atomInvariants, includeChirality, use2D, confId);
ExplicitBitVect *res = new ExplicitBitVect(nBits);
if (nBitsPerEntry != 4) {
BOOST_FOREACH (SparseIntVect<boost::int64_t>::StorageType::value_type val,
sres->getNonzeroElements()) {
for (unsigned int i = 0; i < nBitsPerEntry; ++i) {
if (val.second > static_cast<int>(i))
res->setBit(val.first * nBitsPerEntry + i);
}
}
} else {
BOOST_FOREACH (SparseIntVect<boost::int64_t>::StorageType::value_type val,
sres->getNonzeroElements()) {
for (unsigned int i = 0; i < nBitsPerEntry; ++i) {
if (val.second >= bounds[i]) {
res->setBit(val.first * nBitsPerEntry + i);
}
}
}
}
delete sres;
return res;
}
boost::uint64_t <API key>(
const std::vector<boost::uint32_t> &pathCodes, bool includeChirality) {
bool reverseIt = false;
unsigned int i = 0;
unsigned int j = pathCodes.size() - 1;
while (i < j) {
if (pathCodes[i] > pathCodes[j]) {
reverseIt = true;
break;
} else if (pathCodes[i] < pathCodes[j]) {
break;
}
++i;
--j;
}
int shiftSize = codeSize + (includeChirality ? numChiralBits : 0);
boost::uint64_t res = 0;
if (reverseIt) {
for (unsigned int i = 0; i < pathCodes.size(); ++i) {
res |= static_cast<boost::uint64_t>(pathCodes[pathCodes.size() - i - 1])
<< (shiftSize * i);
}
} else {
for (unsigned int i = 0; i < pathCodes.size(); ++i) {
res |= static_cast<boost::uint64_t>(pathCodes[i]) << (shiftSize * i);
}
}
return res;
}
size_t <API key>(
const std::vector<boost::uint32_t> &pathCodes) {
bool reverseIt = false;
unsigned int i = 0;
unsigned int j = pathCodes.size() - 1;
while (i < j) {
if (pathCodes[i] > pathCodes[j]) {
reverseIt = true;
break;
} else if (pathCodes[i] < pathCodes[j]) {
break;
}
++i;
--j;
}
boost::uint32_t res = 0;
if (reverseIt) {
for (unsigned int i = 0; i < pathCodes.size(); ++i) {
gboost::hash_combine(res, pathCodes[pathCodes.size() - i - 1]);
}
} else {
for (unsigned int i = 0; i < pathCodes.size(); ++i) {
gboost::hash_combine(res, pathCodes[i]);
}
}
return res;
}
SparseIntVect<boost::int64_t> *<API key>(
const ROMol &mol, unsigned int targetSize,
const std::vector<boost::uint32_t> *fromAtoms,
const std::vector<boost::uint32_t> *ignoreAtoms,
const std::vector<boost::uint32_t> *atomInvariants, bool includeChirality) {
PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),
"bad atomInvariants size");
boost::uint64_t sz = 1;
sz = (sz << (targetSize *
(codeSize + (includeChirality ? numChiralBits : 0))));
// NOTE: this -1 is incorrect but it's needed for backwards compatibility.
// hopefully we'll never have a case with a torsion that hits this.
// mmm, bug compatible.
sz -= 1;
SparseIntVect<boost::int64_t> *res = new SparseIntVect<boost::int64_t>(sz);
std::vector<boost::uint32_t> atomCodes;
atomCodes.reserve(mol.getNumAtoms());
for (ROMol::ConstAtomIterator atomItI = mol.beginAtoms();
atomItI != mol.endAtoms(); ++atomItI) {
if (!atomInvariants) {
atomCodes.push_back(getAtomCode(*atomItI, 0, includeChirality));
} else {
// need to add to the atomCode here because we subtract off up to 2 below
// as part of the branch correction
atomCodes.push_back(
(*atomInvariants)[(*atomItI)->getIdx()] % ((1 << codeSize) - 1) + 2);
}
}
boost::dynamic_bitset<> *fromAtomsBV = 0;
if (fromAtoms) {
fromAtomsBV = new boost::dynamic_bitset<>(mol.getNumAtoms());
BOOST_FOREACH (boost::uint32_t fAt, *fromAtoms) { fromAtomsBV->set(fAt); }
}
boost::dynamic_bitset<> *ignoreAtomsBV = 0;
if (ignoreAtoms) {
ignoreAtomsBV = new boost::dynamic_bitset<>(mol.getNumAtoms());
BOOST_FOREACH (boost::uint32_t fAt, *ignoreAtoms) {
ignoreAtomsBV->set(fAt);
}
}
boost::dynamic_bitset<> pAtoms(mol.getNumAtoms());
PATH_LIST paths = <API key>(mol, targetSize, false);
for (PATH_LIST::const_iterator pathIt = paths.begin(); pathIt != paths.end();
++pathIt) {
bool keepIt = true;
if (fromAtomsBV) {
keepIt = false;
}
std::vector<boost::uint32_t> pathCodes;
const PATH_TYPE &path = *pathIt;
if (fromAtomsBV) {
if (fromAtomsBV->test(static_cast<boost::uint32_t>(path.front())) ||
fromAtomsBV->test(static_cast<boost::uint32_t>(path.back()))) {
keepIt = true;
}
}
if (keepIt && ignoreAtomsBV) {
BOOST_FOREACH (int pElem, path) {
if (ignoreAtomsBV->test(pElem)) {
keepIt = false;
break;
}
}
}
if (keepIt) {
pAtoms.reset();
for (PATH_TYPE::const_iterator pIt = path.begin(); pIt < path.end();
++pIt) {
// look for a cycle that doesn't start at the first atom
// we can't effectively canonicalize these at the moment
// (was github #811)
if (pIt != path.begin() && *pIt != *(path.begin()) && pAtoms[*pIt]) {
pathCodes.clear();
break;
}
pAtoms.set(*pIt);
unsigned int code = atomCodes[*pIt] - 1;
// subtract off the branching number:
if (pIt != path.begin() && pIt + 1 != path.end()) {
--code;
}
pathCodes.push_back(code);
}
if (pathCodes.size()) {
boost::int64_t code =
<API key>(pathCodes, includeChirality);
updateElement(*res, code);
}
}
}
delete fromAtomsBV;
delete ignoreAtomsBV;
return res;
}
namespace {
template <typename T>
void TorsionFpCalc(T *res, const ROMol &mol, unsigned int nBits,
unsigned int targetSize,
const std::vector<boost::uint32_t> *fromAtoms,
const std::vector<boost::uint32_t> *ignoreAtoms,
const std::vector<boost::uint32_t> *atomInvariants,
bool includeChirality) {
PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),
"bad atomInvariants size");
std::vector<boost::uint32_t> atomCodes;
atomCodes.reserve(mol.getNumAtoms());
for (ROMol::ConstAtomIterator atomItI = mol.beginAtoms();
atomItI != mol.endAtoms(); ++atomItI) {
if (!atomInvariants) {
atomCodes.push_back(getAtomCode(*atomItI, 0, includeChirality));
} else {
// need to add to the atomCode here because we subtract off up to 2 below
// as part of the branch correction
atomCodes.push_back(((*atomInvariants)[(*atomItI)->getIdx()] << 1) + 1);
}
}
boost::dynamic_bitset<> *fromAtomsBV = 0;
if (fromAtoms) {
fromAtomsBV = new boost::dynamic_bitset<>(mol.getNumAtoms());
BOOST_FOREACH (boost::uint32_t fAt, *fromAtoms) { fromAtomsBV->set(fAt); }
}
boost::dynamic_bitset<> *ignoreAtomsBV = 0;
if (ignoreAtoms) {
ignoreAtomsBV = new boost::dynamic_bitset<>(mol.getNumAtoms());
BOOST_FOREACH (boost::uint32_t fAt, *ignoreAtoms) {
ignoreAtomsBV->set(fAt);
}
}
PATH_LIST paths = <API key>(mol, targetSize, false);
for (PATH_LIST::const_iterator pathIt = paths.begin(); pathIt != paths.end();
++pathIt) {
bool keepIt = true;
if (fromAtomsBV) {
keepIt = false;
}
const PATH_TYPE &path = *pathIt;
if (fromAtomsBV) {
if (fromAtomsBV->test(static_cast<boost::uint32_t>(path.front())) ||
fromAtomsBV->test(static_cast<boost::uint32_t>(path.back()))) {
keepIt = true;
}
}
if (keepIt && ignoreAtomsBV) {
BOOST_FOREACH (int pElem, path) {
if (ignoreAtomsBV->test(pElem)) {
keepIt = false;
break;
}
}
}
if (keepIt) {
std::vector<boost::uint32_t> pathCodes(targetSize);
for (unsigned int i = 0; i < targetSize; ++i) {
unsigned int code = atomCodes[path[i]] - 1;
// subtract off the branching number:
if (i > 0 && i < targetSize - 1) {
--code;
}
pathCodes[i] = code;
}
size_t bit = <API key>(pathCodes);
updateElement(*res, bit % nBits);
}
}
delete fromAtomsBV;
delete ignoreAtomsBV;
}
} // end of local namespace
SparseIntVect<boost::int64_t> *<API key>(
const ROMol &mol, unsigned int nBits, unsigned int targetSize,
const std::vector<boost::uint32_t> *fromAtoms,
const std::vector<boost::uint32_t> *ignoreAtoms,
const std::vector<boost::uint32_t> *atomInvariants, bool includeChirality) {
PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),
"bad atomInvariants size");
SparseIntVect<boost::int64_t> *res = new SparseIntVect<boost::int64_t>(nBits);
TorsionFpCalc(res, mol, nBits, targetSize, fromAtoms, ignoreAtoms,
atomInvariants, includeChirality);
return res;
}
ExplicitBitVect *<API key>(
const ROMol &mol, unsigned int nBits, unsigned int targetSize,
const std::vector<boost::uint32_t> *fromAtoms,
const std::vector<boost::uint32_t> *ignoreAtoms,
const std::vector<boost::uint32_t> *atomInvariants,
unsigned int nBitsPerEntry, bool includeChirality) {
PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),
"bad atomInvariants size");
static int bounds[4] = {1, 2, 4, 8};
unsigned int blockLength = nBits / nBitsPerEntry;
SparseIntVect<boost::int64_t> *sres =
new SparseIntVect<boost::int64_t>(blockLength);
TorsionFpCalc(sres, mol, blockLength, targetSize, fromAtoms, ignoreAtoms,
atomInvariants, includeChirality);
ExplicitBitVect *res = new ExplicitBitVect(nBits);
if (nBitsPerEntry != 4) {
BOOST_FOREACH (SparseIntVect<boost::int64_t>::StorageType::value_type val,
sres->getNonzeroElements()) {
for (unsigned int i = 0; i < nBitsPerEntry; ++i) {
if (val.second > static_cast<int>(i))
res->setBit(val.first * nBitsPerEntry + i);
}
}
} else {
BOOST_FOREACH (SparseIntVect<boost::int64_t>::StorageType::value_type val,
sres->getNonzeroElements()) {
for (unsigned int i = 0; i < nBitsPerEntry; ++i) {
if (val.second >= bounds[i]) {
res->setBit(val.first * nBitsPerEntry + i);
}
}
}
}
delete sres;
return res;
}
} // end of namespace AtomPairs
} // end of namespace RDKit
|
<?php
namespace Zend\Ldap\Collection;
use Zend\Ldap;
use Zend\Ldap\Exception;
use Zend\Stdlib\ErrorHandler;
/**
* Zend\Ldap\Collection\DefaultIterator is the default collection iterator implementation
* using ext/ldap
*
* @category Zend
* @package Zend_Ldap
*/
class DefaultIterator implements \Iterator, \Countable
{
const ATTRIBUTE_TO_LOWER = 1;
const ATTRIBUTE_TO_UPPER = 2;
const ATTRIBUTE_NATIVE = 3;
/**
* LDAP Connection
*
* @var \Zend\Ldap\Ldap
*/
protected $ldap = null;
/**
* Result identifier resource
*
* @var resource
*/
protected $resultId = null;
/**
* Current result entry identifier
*
* @var resource
*/
protected $current = null;
/**
* Number of items in query result
*
* @var integer
*/
protected $itemCount = -1;
/**
* The method that will be applied to the attribute's names.
*
* @var integer|callable
*/
protected $<API key> = self::ATTRIBUTE_TO_LOWER;
/**
* Constructor.
*
* @param \Zend\Ldap\Ldap $ldap
* @param resource $resultId
* @throws \Zend\Ldap\Exception\LdapException if no entries was found.
* @return DefaultIterator
*/
public function __construct(Ldap\Ldap $ldap, $resultId)
{
$this->ldap = $ldap;
$this->resultId = $resultId;
$resource = $ldap->getResource();
ErrorHandler::start();
$this->itemCount = ldap_count_entries($resource, $resultId);
ErrorHandler::stop();
if ($this->itemCount === false) {
throw new Exception\LdapException($this->ldap, 'counting entries');
}
}
public function __destruct()
{
$this->close();
}
/**
* Closes the current result set
*
* @return bool
*/
public function close()
{
$isClosed = false;
if (is_resource($this->resultId)) {
ErrorHandler::start();
$isClosed = ldap_free_result($this->resultId);
ErrorHandler::stop();
$this->resultId = null;
$this->current = null;
}
return $isClosed;
}
/**
* Gets the current LDAP connection.
*
* @return \Zend\Ldap\Ldap
*/
public function getLDAP()
{
return $this->ldap;
}
/**
* Sets the attribute name treatment.
*
* Can either be one of the following constants
* - Zend\Ldap\Collection\DefaultIterator::ATTRIBUTE_TO_LOWER
* - Zend\Ldap\Collection\DefaultIterator::ATTRIBUTE_TO_UPPER
* - Zend\Ldap\Collection\DefaultIterator::ATTRIBUTE_NATIVE
* or a valid callback accepting the attribute's name as it's only
* argument and returning the new attribute's name.
*
* @param integer|callable $<API key>
* @return DefaultIterator Provides a fluent interface
*/
public function <API key>($<API key>)
{
if (is_callable($<API key>)) {
if (is_string($<API key>) && !function_exists($<API key>)) {
$this-><API key> = self::ATTRIBUTE_TO_LOWER;
} elseif (is_array($<API key>)
&& !method_exists($<API key>[0], $<API key>[1])
) {
$this-><API key> = self::ATTRIBUTE_TO_LOWER;
} else {
$this-><API key> = $<API key>;
}
} else {
$<API key> = (int)$<API key>;
switch ($<API key>) {
case self::ATTRIBUTE_TO_LOWER:
case self::ATTRIBUTE_TO_UPPER:
case self::ATTRIBUTE_NATIVE:
$this-><API key> = $<API key>;
break;
default:
$this-><API key> = self::ATTRIBUTE_TO_LOWER;
break;
}
}
return $this;
}
/**
* Returns the currently set attribute name treatment
*
* @return integer|callable
*/
public function <API key>()
{
return $this-><API key>;
}
/**
* Returns the number of items in current result
* Implements Countable
*
* @return int
*/
public function count()
{
return $this->itemCount;
}
/**
* Return the current result item
* Implements Iterator
*
* @return array|null
* @throws \Zend\Ldap\Exception\LdapException
*/
public function current()
{
if (!is_resource($this->current)) {
$this->rewind();
}
if (!is_resource($this->current)) {
return null;
}
$entry = array('dn' => $this->key());
$ber_identifier = null;
$resource = $this->ldap->getResource();
ErrorHandler::start();
$name = <API key>(
$resource, $this->current,
$ber_identifier
);
ErrorHandler::stop();
while ($name) {
ErrorHandler::start();
$data = ldap_get_values_len($resource, $this->current, $name);
ErrorHandler::stop();
if (!$data) {
$data = array();
}
if (isset($data['count'])) {
unset($data['count']);
}
switch ($this-><API key>) {
case self::ATTRIBUTE_TO_LOWER:
$attrName = strtolower($name);
break;
case self::ATTRIBUTE_TO_UPPER:
$attrName = strtoupper($name);
break;
case self::ATTRIBUTE_NATIVE:
$attrName = $name;
break;
default:
$attrName = call_user_func($this-><API key>, $name);
break;
}
$entry[$attrName] = $data;
ErrorHandler::start();
$name = ldap_next_attribute(
$resource, $this->current,
$ber_identifier
);
ErrorHandler::stop();
}
ksort($entry, SORT_LOCALE_STRING);
return $entry;
}
/**
* Return the result item key
* Implements Iterator
*
* @throws \Zend\Ldap\Exception\LdapException
* @return string|null
*/
public function key()
{
if (!is_resource($this->current)) {
$this->rewind();
}
if (is_resource($this->current)) {
$resource = $this->ldap->getResource();
ErrorHandler::start();
$currentDn = ldap_get_dn($resource, $this->current);
ErrorHandler::stop();
if ($currentDn === false) {
throw new Exception\LdapException($this->ldap, 'getting dn');
}
return $currentDn;
} else {
return null;
}
}
/**
* Move forward to next result item
* Implements Iterator
*
* @throws \Zend\Ldap\Exception\LdapException
*/
public function next()
{
$code = 0;
if (is_resource($this->current) && $this->itemCount > 0) {
$resource = $this->ldap->getResource();
ErrorHandler::start();
$this->current = ldap_next_entry($resource, $this->current);
ErrorHandler::stop();
if ($this->current === false) {
$msg = $this->ldap->getLastError($code);
if ($code === Exception\LdapException::<API key>) {
// we have reached the size limit enforced by the server
return;
} elseif ($code > Exception\LdapException::LDAP_SUCCESS) {
throw new Exception\LdapException($this->ldap, 'getting next entry (' . $msg . ')');
}
}
} else {
$this->current = false;
}
}
/**
* Rewind the Iterator to the first result item
* Implements Iterator
*
*
* @throws \Zend\Ldap\Exception\LdapException
*/
public function rewind()
{
if (is_resource($this->resultId)) {
$resource = $this->ldap->getResource();
ErrorHandler::start();
$this->current = ldap_first_entry($resource, $this->resultId);
ErrorHandler::stop();
if ($this->current === false
&& $this->ldap->getLastErrorCode() > Exception\LdapException::LDAP_SUCCESS
) {
throw new Exception\LdapException($this->ldap, 'getting first entry');
}
}
}
/**
* Check if there is a current result item
* after calls to rewind() or next()
* Implements Iterator
*
* @return boolean
*/
public function valid()
{
return (is_resource($this->current));
}
}
|
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model app\models\HalfproductSearch */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="halfproduct-search">
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
]); ?>
<?= $form->field($model, 'id_product') ?>
<?= $form->field($model, 'kode') ?>
<?= $form->field($model, 'nama') ?>
<?= $form->field($model, 'package') ?>
<?= $form->field($model, 'panjang') ?>
<?php // echo $form->field($model, 'lebar') ?>
<?php // echo $form->field($model, 'berat') ?>
<?php // echo $form->field($model, 'flag') ?>
<div class="form-group">
<?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
<?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
|
WakaTime

=======


[
{
instance = gameObject.GetComponent<AudioHurtHandler>();
}
public void playSound ()
{
audio.PlayOneShot(myClip[Random.Range(0,myClip.Length)]);
//wait ();
}
IEnumerator wait()
{
yield return new WaitForSeconds(1);
}
}
|
<?php namespace estvoyage\risingsun\comparison\unary\container\payload;
use estvoyage\risingsun\{ container, comparison, ointeger, block };
class disjunction
implements
comparison\unary\container\payload
{
private
$operand,
$recipient
;
function __construct($operand, comparison\recipient $recipient)
{
$this->operand = $operand;
$this->recipient = $recipient;
}
function <API key>(comparison\unary $comparison, ointeger $position, container\iterator\engine\controller $controller)
{
$comparison
-><API key>(
$this->operand,
new comparison\recipient\block(
new block\functor(
function($nboolean) use ($controller)
{
$this->recipient->nbooleanIs($nboolean);
(new comparison\unary\with\true\boolean)
-><API key>(
$nboolean,
new comparison\recipient\functor\ok(
function() use ($controller)
{
$controller-><API key>();
}
)
)
;
}
)
)
)
;
}
}
|
<?php
namespace UForm\Form\Element;
use UForm\Filtering\FilterChain;
use UForm\Form\Element;
/**
* Element that intends to contain other elements.
* It only aims to be a common parent for Group and Collection
*
* In some ways it is opposed to the Primary element that cant contain other elements
*
* @see UForm\Form\Element\Container\Group
* @see UForm\Form\Element\Container\Collection
* @see UForm\Form\Element\Container\Primary
* @semanticType container
*/
abstract class Container extends Element
{
public function __construct($name = null)
{
parent::__construct($name);
$this->addSemanticType('container');
}
/**
* Get an element by its name
* @param $name
* @return Element
*/
abstract public function getElement($name);
/**
* Get the elements contained in this container.
* Values are required because a collection requires values to be generated
* @param mixed $values used for the "collection" element that is rendered according to a value set
* @return Element[] the elements contained in this container
*/
abstract public function getElements($values = null);
/**
* Get an element located directly in this element. There is an exception for unnamed elements :
* we will search inside directElements of unnamed elements
* @param string $name name of the element to get
* @param mixed $values used for the "collection" element that is rendered according to a value set
* @return null|Element|Container the element found or null if the element does not exist
*/
public function getDirectElement($name, $values = null)
{
foreach ($this->getElements($values) as $elm) {
if ($name == $elm->getName()) {
return $elm;
} elseif (!$elm->getName() && $elm instanceof Container) {
/* @var $elm \UForm\Form\Element\Container */
$element = $elm->getDirectElement($name);
if ($element) {
return $element;
}
}
}
return null;
}
/**
* Get direct elements with the given name
* @param $name
* @param null $values
* @return Element[]
*/
public function getDirectElements($name, $values = null)
{
$elements = [];
foreach ($this->getElements($values) as $elm) {
if ($name == $elm->getName()) {
$elements[] = $elm;
} elseif (!$elm->getName() && $elm instanceof Container) {
/* @var $elm \UForm\Form\Element\Container */
$elements += $elm->getDirectElements($name, $values);
}
}
return $elements;
}
/**
* check if this element contains at least one element that is an instance of the given type
* @param string $className the name of the class to search for
* @return bool true if the instance was found
*/
public function <API key>($className)
{
foreach ($this->getElements() as $el) {
if (is_a($el, $className)) {
return true;
}
}
return false;
}
/**
* Check if this element contains at least one element with the given semantic type
* @param string $type the type to search for
* @return bool true if the semantic type was found
*/
public function <API key>($type)
{
foreach ($this->getElements() as $el) {
if ($el->hasSemanticType($type)) {
return true;
}
}
return false;
}
public function prepareFilterChain(FilterChain $filterChain)
{
parent::prepareFilterChain($filterChain);
foreach ($this->getElements() as $v) {
$v->prepareFilterChain($filterChain);
}
}
/**
* @inheritdoc
*/
public function setParent(Container $parent)
{
$r = parent::setParent($parent);
foreach ($this->getElements() as $element) {
$element->refreshParent();
}
return $r;
}
}
|
# -*- coding: utf-8 -*-
import pandas
from qstkutil import DataAccess as da
import numpy as np
import math
import copy
import qstkutil.qsdateutil as du
import datetime as dt
import qstkutil.DataAccess as da
import qstkutil.tsutil as tsu
import qstkstudy.EventProfiler as ep
"""
Accepts a list of symbols along with start and end date
Returns the Event Matrix which is a pandas Datamatrix
Event matrix has the following structure :
|IBM |GOOG|XOM |MSFT| GS | JP |
(d1)|nan |nan | 1 |nan |nan | 1 |
(d2)|nan | 1 |nan |nan |nan |nan |
(d3)| 1 |nan | 1 |nan | 1 |nan |
(d4)|nan | 1 |nan | 1 |nan |nan |
................................
................................
Also, d1 = start date
nan = no information about any event.
1 = status bit(positively confirms the event occurence)
"""
# Get the data from the data store
storename = "NSEData" # get data from our daily prices source
# Available field names: open, close, high, low, close, actual_close, volume
closefield = "close"
volumefield = "volume"
window = 10
def getHalfYearEndDates(timestamps):
newTS=[]
tempYear=timestamps[0].year
flag=1
for x in range(0, len(timestamps)-1):
if(timestamps[x].year==tempYear):
if(timestamps[x].month==4 and flag==1):
newTS.append(timestamps[x-1])
flag=0
if(timestamps[x].month==10):
newTS.append(timestamps[x-1])
tempYear=timestamps[x].year+1
flag=1
return newTS
def findEvents(symbols, startday,endday, marketSymbol,verbose=False):
# Reading the Data for the list of Symbols.
timeofday=dt.timedelta(hours=16)
timestamps = du.getNSEdays(startday,endday,timeofday)
endOfHalfYear=getHalfYearEndDates(timestamps)
dataobj = da.DataAccess('NSEData')
if verbose:
print __name__ + " reading data"
# Reading the Data
close = dataobj.get_data(timestamps, symbols, closefield)
# Completing the Data - Removing the NaN values from the Matrix
close = (close.fillna(method='ffill')).fillna(method='backfill')
# Calculating Daily Returns for the Market
tsu.returnize0(close.values)
# Calculating the Returns of the Stock Relative to the Market
# So if a Stock went up 5% and the Market rised 3%. The the return relative to market is 2%
mktneutDM = close - close[marketSymbol]
np_eventmat = copy.deepcopy(mktneutDM)
for sym in symbols:
for time in timestamps:
np_eventmat[sym][time]=np.NAN
if verbose:
print __name__ + " finding events"
# Generating the Event Matrix
# Event described is : Analyzing half year events for given stocks.
for symbol in symbols:
for i in endOfHalfYear:
np_eventmat[symbol][i] = 1.0 #overwriting by the bit, marking the event
return np_eventmat
symbols = np.loadtxt('NSE500port.csv',dtype='S13',comments='#', skiprows=1)
# You might get a message about some files being missing, don't worry about it.
#symbols =['SPY','BFRE','ATCS','RSERF','GDNEF','LAST','ATTUF','JBFCF','CYVA','SPF','XPO','EHECF','TEMO','AOLS','CSNT','REMI','GLRP','AIFLY','BEE','DJRT','CHSTF','AICAF']
#symbols=['NSE','3MINDIA.NS','AARTIIND.NS','ABAN.NS','ABB.NS','ABGSHIP.NS','ABIRLANUV.NS','ACC.NS','ADANIENT.NS','ADANIPORT.NS','ADANIPOWE.NS','ADVANTA.NS','ALLCARGO.NS','AIAENG.NS','AIL.NS','AZKOINDIA.NS']
startday = dt.datetime(2011,1,1)
endday = dt.datetime(2012,1,1)
eventMatrix = findEvents(symbols,startday,endday,marketSymbol='NSE500',verbose=True)
eventMatrix.to_csv('eventmatrix.csv', sep=',')
eventProfiler = ep.EventProfiler(eventMatrix,startday,endday,lookback_days=20,lookforward_days=20,verbose=True)
eventProfiler.study(filename="HalfYearEventStudy.jpg",plotErrorBars=True,plotMarketNeutral=True,plotEvents=False,marketSymbol='NSE500')
|
<?php
include_once '<API key>.php';
/**
* This is the model class for table "THEME_MANAGEMENT".
*
* The followings are the available columns in table 'THEME_MANAGEMENT':
* @property string $PID
* @property string $THEME
*/
class Theme_Management extends CActiveRecord
{
/**
* Returns the static model of the specified AR class.
* @param string $className active record class name.
* @return Theme_Management the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
/**
* @return string the associated database table name
*/
public function tableName()
{
return 'THEME_MANAGEMENT';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('THEME', 'length', 'max'=>20),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('USER_ID,ID, THEME', 'safe', 'on'=>'search'),
);
}
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'USER_ID' => 'Userid',
'THEME' => 'Theme',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
* @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
*/
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('USER_ID',$this->USER_ID,true);
$criteria->compare('THEME',$this->THEME,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
}
|
# Makefile for Sphinx documentation
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = build
# User-friendly check for sphinx-build
ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)
$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/)
endif
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
.PHONY: help
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " applehelp to make an Apple Help Book"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " xml to make Docutils-native XML files"
@echo " pseudoxml to make pseudoxml-XML files for display purposes"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
@echo " coverage to run coverage check of the documentation (if enabled)"
.PHONY: clean
clean:
|
#include "native_client/src/include/portability_string.h"
#include "native_client/src/include/nacl_macros.h"
#include "native_client/src/include/nacl_platform.h"
#include "native_client/src/shared/platform/nacl_check.h"
#include "native_client/src/trusted/service_runtime/<API key>.h"
#include "native_client/src/trusted/service_runtime/nacl_globals.h"
#include "native_client/src/trusted/service_runtime/sel_ldr.h"
#include "native_client/src/trusted/service_runtime/sel_memory.h"
#include "native_client/src/trusted/service_runtime/springboard.h"
#include "native_client/src/trusted/service_runtime/arch/x86/sel_ldr_x86.h"
#include "native_client/src/trusted/service_runtime/arch/x86_64/tramp_64.h"
static uintptr_t AddDispatchThunk(uintptr_t *next_addr,
uintptr_t target_routine) {
struct NaClPatchInfo patch_info;
struct NaClPatch jmp_target;
jmp_target.target = (((uintptr_t) &<API key>)
- sizeof(uintptr_t));
jmp_target.value = target_routine;
NaClPatchInfoCtor(&patch_info);
patch_info.abs64 = &jmp_target;
patch_info.num_abs64 = 1;
patch_info.dst = *next_addr;
patch_info.src = (uintptr_t) &NaClDispatchThunk;
patch_info.nbytes = ((uintptr_t) &<API key>
- (uintptr_t) &NaClDispatchThunk);
<API key>(&patch_info);
*next_addr += patch_info.nbytes;
return patch_info.dst;
}
int <API key>(struct NaClApp *nap) {
int retval = 0; /* fail */
int error;
void *thunk_addr = NULL;
uintptr_t next_addr;
uintptr_t dispatch_thunk = 0;
uintptr_t get_tls_fast_path1 = 0;
uintptr_t get_tls_fast_path2 = 0;
NaClLog(2, "Entered <API key>\n");
if (0 != nap->dispatch_thunk) {
NaClLog(LOG_ERROR, " dispatch_thunk already initialized!\n");
return 1;
}
if (0 != (error = <API key>(&thunk_addr,
NACL_MAP_PAGESIZE))) {
NaClLog(LOG_INFO,
"<API key>::NaCl_page_alloc failed, errno %d\n",
-error);
retval = 0;
goto cleanup;
}
NaClLog(2, "<API key>: got addr 0x%"NACL_PRIxPTR"\n",
(uintptr_t) thunk_addr);
if (0 != (error = NaCl_mprotect(thunk_addr,
NACL_MAP_PAGESIZE,
PROT_READ | PROT_WRITE))) {
NaClLog(LOG_INFO,
"<API key>::NaCl_mprotect r/w failed, errno %d\n",
-error);
retval = 0;
goto cleanup;
}
<API key>(thunk_addr, NACL_MAP_PAGESIZE);
next_addr = (uintptr_t) thunk_addr;
dispatch_thunk =
AddDispatchThunk(&next_addr, (uintptr_t) &NaClSyscallSeg);
get_tls_fast_path1 =
AddDispatchThunk(&next_addr, (uintptr_t) &NaClGetTlsFastPath1);
get_tls_fast_path2 =
AddDispatchThunk(&next_addr, (uintptr_t) &NaClGetTlsFastPath2);
if (0 != (error = NaCl_mprotect(thunk_addr,
NACL_MAP_PAGESIZE,
PROT_EXEC|PROT_READ))) {
NaClLog(LOG_INFO,
"<API key>::NaCl_mprotect r/x failed, errno %d\n",
-error);
retval = 0;
goto cleanup;
}
retval = 1;
cleanup:
if (0 == retval) {
if (NULL != thunk_addr) {
NaCl_page_free(thunk_addr, NACL_MAP_PAGESIZE);
thunk_addr = NULL;
}
} else {
nap->dispatch_thunk = dispatch_thunk;
nap->get_tls_fast_path1 = get_tls_fast_path1;
nap->get_tls_fast_path2 = get_tls_fast_path2;
}
return retval;
}
/*
* Install a syscall trampoline at target_addr. NB: Thread-safe.
*/
void <API key>(uintptr_t call_target_addr,
uintptr_t target_addr) {
struct NaClPatchInfo patch_info;
struct NaClPatch call_target;
NaClLog(6, "call_target_addr = 0x%"NACL_PRIxPTR"\n", call_target_addr);
CHECK(0 != call_target_addr);
call_target.target = (((uintptr_t) &<API key>)
- sizeof(uintptr_t));
call_target.value = call_target_addr;
NaClPatchInfoCtor(&patch_info);
patch_info.abs64 = &call_target;
patch_info.num_abs64 = 1;
patch_info.dst = target_addr;
patch_info.src = (uintptr_t) &<API key>;
patch_info.nbytes = ((uintptr_t) &<API key>
- (uintptr_t) &<API key>);
<API key>(&patch_info);
}
void <API key>(struct NaClApp *nap,
uintptr_t target_addr) {
uintptr_t call_target_addr;
call_target_addr = nap->dispatch_thunk;
<API key>(call_target_addr, target_addr);
}
void <API key>(void *start, size_t size) {
CHECK(!(size % NACL_HALT_LEN));
/* Tell valgrind that this memory is accessible and undefined */
<API key>(start, size);
memset(start, NACL_HALT_OPCODE, size);
}
void <API key>(struct NaClApp *nap) {
<API key>(
(void *) (nap->mem_start + <API key>),
<API key>);
}
void NaClLoadSpringboard(struct NaClApp *nap) {
/*
* There is no springboard for x86-64.
*/
<API key>(nap);
}
|
#include "platform/fonts/shaping/RunSegmenter.h"
#include "platform/fonts/ScriptRunIterator.h"
#include "platform/fonts/SmallCapsIterator.h"
#include "platform/fonts/SymbolsIterator.h"
#include "platform/fonts/UTF16TextIterator.h"
#include "platform/text/Character.h"
#include "wtf/Assertions.h"
namespace blink {
RunSegmenter::RunSegmenter(const UChar* buffer, unsigned bufferSize, FontOrientation runOrientation, FontVariant variant)
: m_bufferSize(bufferSize)
, m_candidateRange({ 0, 0, <API key>, OrientationIterator::OrientationKeep, SmallCapsIterator::SmallCapsSameCase })
, m_scriptRunIterator(adoptPtr(new ScriptRunIterator(buffer, bufferSize)))
, <API key>(runOrientation == FontOrientation::VerticalMixed ? adoptPtr(new OrientationIterator(buffer, bufferSize, runOrientation)) : nullptr)
, m_smallCapsIterator(variant == <API key> ? adoptPtr(new SmallCapsIterator(buffer, bufferSize)) : nullptr)
, m_symbolsIterator(adoptPtr(new SymbolsIterator(buffer, bufferSize)))
, m_lastSplit(0)
, <API key>(0)
, <API key>(runOrientation == FontOrientation::VerticalMixed ? 0 : m_bufferSize)
, <API key>(variant == <API key> ? 0 : m_bufferSize)
, <API key>(0)
, m_atEnd(false)
{
}
void RunSegmenter::<API key>()
{
ASSERT(m_scriptRunIterator);
if (<API key> <= m_lastSplit && <API key> < m_bufferSize) {
while (m_scriptRunIterator->consume(<API key>, m_candidateRange.script)) {
if (<API key> > m_lastSplit)
return;
}
}
}
void RunSegmenter::<API key>()
{
if (<API key> && <API key> <= m_lastSplit && <API key> < m_bufferSize) {
while (<API key>->consume(&<API key>, &m_candidateRange.renderOrientation)) {
if (<API key> > m_lastSplit)
return;
}
}
}
void RunSegmenter::<API key>()
{
if (m_smallCapsIterator && <API key> <= m_lastSplit && <API key> < m_bufferSize) {
while (m_smallCapsIterator->consume(&<API key>, &m_candidateRange.smallCapsBehavior)) {
if (<API key> > m_lastSplit)
return;
}
}
}
void RunSegmenter::<API key>()
{
ASSERT(m_symbolsIterator);
if (<API key> <= m_lastSplit && <API key> < m_bufferSize) {
while (m_symbolsIterator->consume(&<API key>, &m_candidateRange.<API key>)) {
if (<API key> > m_lastSplit)
return;
}
}
}
bool RunSegmenter::consume(RunSegmenterRange* nextRange)
{
if (m_atEnd || !m_bufferSize)
return false;
<API key>();
<API key>();
<API key>();
<API key>();
if (<API key> <= <API key>
&& <API key> <= <API key>
&& <API key> <= <API key>) {
m_lastSplit = <API key>;
}
if (<API key> <= <API key>
&& <API key> <= <API key>
&& <API key> <= <API key>) {
m_lastSplit = <API key>;
}
if (<API key> <= <API key>
&& <API key> <= <API key>
&& <API key> <= <API key>) {
m_lastSplit = <API key>;
}
if (<API key> <= <API key>
&& <API key> <= <API key>
&& <API key> <= <API key>) {
m_lastSplit = <API key>;
}
m_candidateRange.start = m_candidateRange.end;
m_candidateRange.end = m_lastSplit;
*nextRange = m_candidateRange;
m_atEnd = m_lastSplit == m_bufferSize;
return true;
}
} // namespace blink
|
{% macro vital(addon, type) %}
<div class="vital">
{% if type in ('updated', 'created') %}
<span class="updated">
{% if type == 'updated' %}
{# L10n: {0} is a date. #}
{{ _('Updated {0}')|f(addon.last_updated|datetime) }}
{% else %}
{# L10n: {0} is a date. #}
{{ _('Added {0}')|f(addon.created|datetime) }}
{% endif %}
</span>
{% elif type in ('downloads', 'adu') %}
{% if type == 'downloads' %}
<span class="downloads adu">
{% trans cnt=addon.weekly_downloads,
num=addon.weekly_downloads|numberfmt %}
{{ num }} weekly download
{% pluralize %}
{{ num }} weekly downloads
{% endtrans %}
</span>
{% else %}
<span class="adu">
{% set adu=addon.average_daily_users %}
{% trans cnt=adu, num=adu|numberfmt %}
{{ num }} user
{% pluralize %}
{{ num }} users
{% endtrans %}
</span>
{% endif %}
{% endif %}
</div>
{% endmacro %}
{% macro addon_heading(addon, version) %}
<h1{{ addon.name|locale_html }}>
{{ addon.name }}
{% if version %}
<span class="version">{{ version.version }}</span>
{% endif %}
</h1>
{% endmacro %}
{% macro sort_vital(addon, field) %}
{% if field in ('popular', 'downloads') or not addon.show_adu() %}
<div class="adu downloads">
{% with num=addon.weekly_downloads %}
{# L10n: {0} is the number of downloads. #}
{{ ngettext('{0} weekly download', '{0} weekly downloads',
num)|f(num|numberfmt) }}
{% endwith %}
</div>
{% else %}
<div class="adu">
{% with num=addon.average_daily_users %}
{# L10n: {0} is the number of users. #}
{{ ngettext('{0} user', '{0} users', num)|f(num|numberfmt) }}
{% endwith %}
</div>
{% endif %}
{% if field in ('created', 'updated') %}
<div class="updated">
{% if field == 'created' %}
{# L10n: {0} is a date. #}
{{ _('Added {0}')|f(addon.created|datetime) }}
{% else %}
{# L10n: {0} is a date. #}
{{ _('Updated {0}')|f(addon.last_updated|datetime) }}
{% endif %}
</div>
{% endif %}
{% endmacro %}
|
<!DOCTYPE HTML PUBLIC "-
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_101) on Sat Aug 20 05:41:48 EDT 2016 -->
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Uses of Class org.apache.solr.search.Sorting (Solr 6.2.0 API)</title>
<meta name="date" content="2016-08-20">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.solr.search.Sorting (Solr 6.2.0 API)";
}
}
catch(err) {
}
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="topNav"><a name="navbar.top">
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/apache/solr/search/Sorting.html" title="class in org.apache.solr.search">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/solr/search/class-use/Sorting.html" target="_top">Frames</a></li>
<li><a href="Sorting.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<a name="skip.navbar.top">
</a></div>
<div class="header">
<h2 title="Uses of Class org.apache.solr.search.Sorting" class="title">Uses of Class<br>org.apache.solr.search.Sorting</h2>
</div>
<div class="classUseContainer">No usage of org.apache.solr.search.Sorting</div>
<div class="bottomNav"><a name="navbar.bottom">
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/apache/solr/search/Sorting.html" title="class in org.apache.solr.search">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/solr/search/class-use/Sorting.html" target="_top">Frames</a></li>
<li><a href="Sorting.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<a name="skip.navbar.bottom">
</a></div>
<p class="legalCopy"><small>
<i>Copyright © 2000-2016 Apache Software Foundation. All Rights Reserved.</i>
<script src='../../../../../prettify.js' type='text/javascript'></script>
<script type='text/javascript'>
(function(){
var oldonload = window.onload;
if (typeof oldonload != 'function') {
window.onload = prettyPrint;
} else {
window.onload = function() {
oldonload();
prettyPrint();
}
}
})();
</script>
</small></p>
</body>
</html>
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http:
<html xmlns="http:
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>statsmodels.genmod.families.family.InverseGaussian.loglike — statsmodels 0.9.0 documentation</title>
<link rel="stylesheet" href="../_static/nature.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<script type="text/javascript" src="../_static/<API key>.js"></script>
<script type="text/javascript" src="../_static/jquery.js"></script>
<script type="text/javascript" src="../_static/underscore.js"></script>
<script type="text/javascript" src="../_static/doctools.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=<API key>"></script>
<link rel="shortcut icon" href="../_static/<API key>.ico"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="next" title="statsmodels.genmod.families.family.InverseGaussian.loglike_obs" href="statsmodels.genmod.families.family.InverseGaussian.loglike_obs.html" />
<link rel="prev" title="statsmodels.genmod.families.family.InverseGaussian.fitted" href="statsmodels.genmod.families.family.InverseGaussian.fitted.html" />
<link rel="stylesheet" href="../_static/examples.css" type="text/css" />
<link rel="stylesheet" href="../_static/facebox.css" type="text/css" />
<script type="text/javascript" src="../_static/scripts.js">
</script>
<script type="text/javascript" src="../_static/facebox.js">
</script>
<script type="text/javascript">
$.facebox.settings.closeImage = "../_static/closelabel.png"
$.facebox.settings.loadingImage = "../_static/loading.gif"
</script>
</head><body>
<div class="headerwrap">
<div class = "header">
<a href = "../index.html">
<img src="../_static/<API key>.png" alt="Logo"
style="padding-left: 15px"/></a>
</div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="../py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li class="right" >
<a href="statsmodels.genmod.families.family.InverseGaussian.loglike_obs.html" title="statsmodels.genmod.families.family.InverseGaussian.loglike_obs"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="statsmodels.genmod.families.family.InverseGaussian.fitted.html" title="statsmodels.genmod.families.family.InverseGaussian.fitted"
accesskey="P">previous</a> |</li>
<li><a href ="../install.html">Install</a></li> |
<li><a href="https://groups.google.com/forum/?hl=en#!forum/pystatsmodels">Support</a></li> |
<li><a href="https://github.com/statsmodels/statsmodels/issues">Bugs</a></li> |
<li><a href="../dev/index.html">Develop</a></li> |
<li><a href="../examples/index.html">Examples</a></li> |
<li><a href="../faq.html">FAQ</a></li> |
<li class="nav-item nav-item-1"><a href="../glm.html" >Generalized Linear Models</a> |</li>
<li class="nav-item nav-item-2"><a href="statsmodels.genmod.families.family.InverseGaussian.html" accesskey="U">statsmodels.genmod.families.family.InverseGaussian</a> |</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="<API key>">
<h1>statsmodels.genmod.families.family.InverseGaussian.loglike<a class="headerlink" href="
<dl class="method">
<dt id="statsmodels.genmod.families.family.InverseGaussian.loglike">
<code class="descclassname">InverseGaussian.</code><code class="descname">loglike</code><span class="sig-paren">(</span><em>endog</em>, <em>mu</em>, <em>var_weights=1.0</em>, <em>freq_weights=1.0</em>, <em>scale=1.0</em><span class="sig-paren">)</span><a class="headerlink" href="
<dd><p>The log-likelihood function in terms of the fitted mean response.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first simple">
<li><strong>endog</strong> (<em>array</em>) – Usually the endogenous response variable.</li>
<li><strong>mu</strong> (<em>array</em>) – Usually but not always the fitted mean response variable.</li>
<li><strong>var_weights</strong> (<em>array-like</em>) – 1d array of variance (analytic) weights. The default is 1.</li>
<li><strong>freq_weights</strong> (<em>array-like</em>) – 1d array of frequency weights. The default is 1.</li>
<li><strong>scale</strong> (<em>float</em>) – The scale parameter. The default is 1.</li>
</ul>
</td>
</tr>
<tr class="field-even field"><th class="field-name">Returns:</th><td class="field-body"><p class="first"><strong>ll</strong> – The value of the loglikelihood evaluated at
(endog, mu, var_weights, freq_weights, scale) as defined below.</p>
</td>
</tr>
<tr class="field-odd field"><th class="field-name">Return type:</th><td class="field-body"><p class="first last">float</p>
</td>
</tr>
</tbody>
</table>
<p class="rubric">Notes</p>
<p>Where <span class="math notranslate nohighlight">\(ll_i\)</span> is the by-observation log-likelihood:</p>
<div class="math notranslate nohighlight">
\[ll = \sum(ll_i * freq\_weights_i)\]</div>
<p><code class="docutils literal notranslate"><span class="pre">ll_i</span></code> is defined for each family. endog and mu are not restricted
to <code class="docutils literal notranslate"><span class="pre">endog</span></code> and <code class="docutils literal notranslate"><span class="pre">mu</span></code> respectively. For instance, you could call
both <code class="docutils literal notranslate"><span class="pre">loglike(endog,</span> <span class="pre">endog)</span></code> and <code class="docutils literal notranslate"><span class="pre">loglike(endog,</span> <span class="pre">mu)</span></code> to get the
log-likelihood ratio.</p>
</dd></dl>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="<API key>">
<h4>Previous topic</h4>
<p class="topless"><a href="statsmodels.genmod.families.family.InverseGaussian.fitted.html"
title="previous chapter">statsmodels.genmod.families.family.InverseGaussian.fitted</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="statsmodels.genmod.families.family.InverseGaussian.loglike_obs.html"
title="next chapter">statsmodels.genmod.families.family.InverseGaussian.loglike_obs</a></p>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../_sources/generated/statsmodels.genmod.families.family.InverseGaussian.loglike.rst.txt"
rel="nofollow">Show Source</a></li>
</ul>
</div>
<div id="searchbox" style="display: none" role="search">
<h3>Quick search</h3>
<div class="searchformwrapper">
<form class="search" action="../search.html" method="get">
<input type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="footer" role="contentinfo">
&
Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.7.4.
</div>
</body>
</html>
|
<?php
return [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=campus_rec',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
];
|
require_dependency 'spree/calculator'
module Spree
class PaymentCalculator::PerItem < Calculator
preference :amount, :decimal, :default => 0
attr_accessible :preferred_amount
def self.description
I18n.t(:flat_rate_per_item)
end
def compute(object=nil)
return 0 if object.nil?
self.preferred_amount * object.line_items.reduce(0) do |sum, value|
if !matching_products || matching_products.include?(value.product)
value_to_add = value.quantity
else
value_to_add = 0
end
sum + value_to_add
end
end
# Returns all products that match this calculator, but only if the calculator
# is attached to a promotion. If attached to a ShippingMethod, nil is returned.
def matching_products
# Regression check for #1596
# Calculator::PerItem can be used in two cases.
# The first is in a typical promotion, providing a discount per item of a particular item
# The second is a ShippingMethod, where it applies to an entire order
# Shipping methods do not have promotions attached, but promotions do
# Therefore we must check for promotions
if self.calculable.respond_to?(:promotion)
self.calculable.promotion.rules.map(&:products).flatten
end
end
end
end
|
<?php
// Call <API key>::main() if this source file is executed directly.
if (!defined("PHPUnit_MAIN_METHOD")) {
define("PHPUnit_MAIN_METHOD", "<API key>::main");
}
/** <API key> */
require_once 'Zend/Dojo/Form/SubForm.php';
/** Zend_View */
require_once 'Zend/View.php';
class <API key> extends <API key>
{
/**
* Runs the test methods of this class.
*
* @return void
*/
public static function main()
{
$suite = new <API key>("<API key>");
$result = <API key>::run($suite);
}
/**
* Sets up the fixture, for example, open a network connection.
* This method is called before a test is executed.
*
* @return void
*/
public function setUp()
{
$this->form = new <API key>();
$this->form->addElement('TextBox', 'foo')
->addDisplayGroup(array('foo'), 'dg')
->setView(new Zend_View());
}
/**
* Tears down the fixture, for example, close a network connection.
* This method is called after a test is executed.
*
* @return void
*/
public function tearDown()
{
}
public function <API key>()
{
$paths = $this->form->getPluginLoader('decorator')->getPaths('<API key>');
$this->assertTrue(is_array($paths));
}
public function <API key>()
{
$paths = $this->form->getPluginLoader('element')->getPaths('<API key>');
$this->assertTrue(is_array($paths));
}
public function <API key>()
{
$paths = $this->form->foo->getPluginLoader('decorator')->getPaths('<API key>');
$this->assertTrue(is_array($paths));
}
public function <API key>()
{
$paths = $this->form->dg->getPluginLoader()->getPaths('<API key>');
$this->assertTrue(is_array($paths));
}
public function <API key>()
{
$this->assertEquals('<API key>', $this->form-><API key>());
}
public function <API key>()
{
$this->assertNotNull($this->form->getDecorator('ContentPane'));
}
public function <API key>()
{
$view = $this->form->getView();
$loader = $view->getPluginLoader('helper');
$paths = $loader->getPaths('<API key>');
$this->assertTrue(is_array($paths));
}
}
// Call <API key>::main() if this source file is executed directly.
if (PHPUnit_MAIN_METHOD == "<API key>::main") {
<API key>::main();
}
|
// AppDelegate.h
// DemoApp
#import <UIKit/UIKit.h>
@class ViewController;
@class AdObserver;
@interface AppDelegate : UIResponder <<API key>>
@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) ViewController *viewController;
@property (strong, nonatomic) AdObserver *adObserver;
@end
|
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Nov 22 2016 05:57:16).
@protocol <API key>
- (void)<API key>:(void (^)(char *, unsigned long long))arg1;
@end
|
#flash-messages {position: absolute;}
#flash-messages .success ul, .notice ul, .error ul { list-style: none; margin: 0; padding: 0; }
#flash-messages .success ul li, .notice ul li, .error ul li { float: none; display: block; }
#flash-messages .success ul, .notice ul, .error ul { list-style: none; margin: 0; padding: 0; font-weight: bold; }
#flash-messages .success ul li, .notice ul li, .error ul li { float: none; display: block; text-align: center;}
#flash-messages div.success, div.notice, div.error {
-<API key>: 8px;
-moz-border-radius: 8px;
border-radius: 8px;
-moz-box-shadow: 0 2px 4px #ccc;
-webkit-box-shadow: 0 2px 4px #ccc;
box-shadow: 0 2px 4px #ccc;
position: relative;
z-index: 1;
}
#flash-messages span.close {
position: absolute;
top: 1px;
right: 6px;
cursor: pointer;
font-weight: bold;
}
|
import {InputWidget, InputWidgetView} from "./input_widget"
import {input} from "core/dom"
import * as p from "core/properties"
import {bk_input} from "styles/widgets/inputs"
export class TextInputView extends InputWidgetView {
model: TextInput
protected input_el: HTMLInputElement
connect_signals(): void {
super.connect_signals()
this.connect(this.model.properties.name.change, () => this.input_el.name = this.model.name || "")
this.connect(this.model.properties.value.change, () => this.input_el.value = this.model.value)
this.connect(this.model.properties.disabled.change, () => this.input_el.disabled = this.model.disabled)
this.connect(this.model.properties.placeholder.change, () => this.input_el.placeholder = this.model.placeholder)
}
render(): void {
super.render()
this.input_el = input({
type: "text",
class: bk_input,
name: this.model.name,
value: this.model.value,
disabled: this.model.disabled,
placeholder: this.model.placeholder,
})
this.input_el.addEventListener("change", () => this.change_input())
this.group_el.appendChild(this.input_el)
}
change_input(): void {
this.model.value = this.input_el.value
super.change_input()
}
}
export namespace TextInput {
export type Attrs = p.AttrsOf<Props>
export type Props = InputWidget.Props & {
value: p.Property<string>
placeholder: p.Property<string>
}
}
export interface TextInput extends TextInput.Attrs {}
export class TextInput extends InputWidget {
properties: TextInput.Props
constructor(attrs?: Partial<TextInput.Attrs>) {
super(attrs)
}
static initClass(): void {
this.prototype.default_view = TextInputView
this.define<TextInput.Props>({
value: [ p.String, "" ],
placeholder: [ p.String, "" ],
})
}
}
TextInput.initClass()
|
# User: debian
# Passwd: /dev/null
FROM scratch
ADD jessie.tgz /
ADD qemu-arm-static /usr/bin/qemu-arm-static
CMD ["/bin/bash"]
|
#!/usr/bin/python
"""
A chain with four possible intermediates with different notBefore and notAfter
dates, for testing path bulding prioritization.
"""
import sys
sys.path += ['../..']
import gencerts
DATE_A = '150101120000Z'
DATE_B = '150102120000Z'
DATE_C = '180101120000Z'
DATE_D = '180102120000Z'
root = gencerts.<API key>('Root')
root.set_validity_range(DATE_A, DATE_D)
int_ac = gencerts.<API key>('Intermediate', root)
int_ac.set_validity_range(DATE_A, DATE_C)
int_ad = gencerts.<API key>('Intermediate', root)
int_ad.set_validity_range(DATE_A, DATE_D)
int_ad.set_key(int_ac.get_key())
int_bc = gencerts.<API key>('Intermediate', root)
int_bc.set_validity_range(DATE_B, DATE_C)
int_bc.set_key(int_ac.get_key())
int_bd = gencerts.<API key>('Intermediate', root)
int_bd.set_validity_range(DATE_B, DATE_D)
int_bd.set_key(int_ac.get_key())
target = gencerts.<API key>('Target', int_ac)
target.set_validity_range(DATE_A, DATE_D)
gencerts.write_chain('The root', [root], out_pem='root.pem')
gencerts.write_chain('Intermediate with validity range A..C',
[int_ac], out_pem='int_ac.pem')
gencerts.write_chain('Intermediate with validity range A..D',
[int_ad], out_pem='int_ad.pem')
gencerts.write_chain('Intermediate with validity range B..C',
[int_bc], out_pem='int_bc.pem')
gencerts.write_chain('Intermediate with validity range B..D',
[int_bd], out_pem='int_bd.pem')
gencerts.write_chain('The target', [target], out_pem='target.pem')
|
<?php
include_once "../../includes/easyparliament/init.php";
if (($date = get_http_var('d')) && preg_match('#^\d\d\d\d-\d\d-\d\d$#', $date)) {
$this_page = 'hansard_date';
$PAGE-><API key>(array('date'=>$date));
$URL = new URL($this_page);
$db = new ParlDB;
$q = $db->query("SELECT MIN(hdate) AS hdate FROM hansard WHERE hdate > '$date'");
if ($q->rows() > 0 && $q->field(0, 'hdate') != NULL) {
$URL->insert( array( 'd'=>$q->field(0, 'hdate') ) );
$title = format_date($q->field(0, 'hdate'), SHORTDATEFORMAT);
$nextprevdata['next'] = array (
'hdate' => $q->field(0, 'hdate'),
'url' => $URL->generate(),
'body' => 'Next day',
'title' => $title
);
}
$q = $db->query("SELECT MAX(hdate) AS hdate FROM hansard WHERE hdate < '$date'");
if ($q->rows() > 0 && $q->field(0, 'hdate') != NULL) {
$URL->insert( array( 'd'=>$q->field(0, 'hdate') ) );
$title = format_date($q->field(0, 'hdate'), SHORTDATEFORMAT);
$nextprevdata['prev'] = array (
'hdate' => $q->field(0, 'hdate'),
'url' => $URL->generate(),
'body' => 'Previous day',
'title' => $title
);
}
# $year = substr($date, 0, 4);
# $URL = new URL($hansardmajors[1]['page_year']);
# $URL->insert(array('y'=>$year));
# $nextprevdata['up'] = array (
# 'body' => "All of $year",
# 'title' => '',
# 'url' => $URL->generate()
$DATA->set_page_metadata($this_page, 'nextprev', $nextprevdata);
$PAGE->page_start();
$PAGE->stripe_start();
include_once INCLUDESPATH . 'easyparliament/recess.php';
$time = strtotime($date);
$dayofweek = date('w', $time);
$recess = recess_prettify(date('j', $time), date('n', $time), date('Y', $time), 1);
if ($recess[0]) {
print '<p>The Houses of Parliament are in their ' . $recess[0] . ' at this time.</p>';
} elseif ($dayofweek == 0 || $dayofweek == 6) {
print '<p>The Houses of Parliament do not meet at weekends.</p>';
} else {
$data = array(
'date' => $date
);
foreach (array_keys($hansardmajors) as $major) {
$URL = new URL($hansardmajors[$major]['page_all']);
$URL->insert(array('d'=>$date));
$data[$major] = array('listurl'=>$URL->generate());
}
major_summary($data);
}
$PAGE->stripe_end(array(
array (
'type' => 'nextprev'
),
));
$PAGE->page_end();
} else {
header("Location: http://" . DOMAIN . "/");
exit;
}
|
#include "src/gpu/dawn/GrDawnBuffer.h"
#include "src/gpu/dawn/GrDawnStagingBuffer.h"
#include "src/gpu/dawn/GrDawnGpu.h"
namespace {
wgpu::BufferUsage <API key>(GrGpuBufferType type) {
switch (type) {
case GrGpuBufferType::kVertex:
return wgpu::BufferUsage::Vertex;
case GrGpuBufferType::kIndex:
return wgpu::BufferUsage::Index;
case GrGpuBufferType::kXferCpuToGpu:
return wgpu::BufferUsage::CopySrc;
case GrGpuBufferType::kXferGpuToCpu:
return wgpu::BufferUsage::CopyDst;
default:
SkASSERT(!"buffer type not supported by Dawn");
return wgpu::BufferUsage::Vertex;
}
}
}
GrDawnBuffer::GrDawnBuffer(GrDawnGpu* gpu, size_t sizeInBytes, GrGpuBufferType type,
GrAccessPattern pattern)
: INHERITED(gpu, sizeInBytes, type, pattern) {
wgpu::BufferDescriptor bufferDesc;
bufferDesc.size = sizeInBytes;
bufferDesc.usage = <API key>(type) | wgpu::BufferUsage::CopyDst;
fBuffer = this->getDawnGpu()->device().CreateBuffer(&bufferDesc);
this->registerWithCache(SkBudgeted::kYes);
}
GrDawnBuffer::~GrDawnBuffer() {
}
void GrDawnBuffer::onMap() {
if (this->wasDestroyed()) {
return;
}
GrStagingBuffer::Slice slice = getGpu()-><API key>(this->size());
fStagingBuffer = static_cast<GrDawnStagingBuffer*>(slice.fBuffer)->buffer();
fStagingOffset = slice.fOffset;
fMapPtr = slice.fData;
}
void GrDawnBuffer::onUnmap() {
if (this->wasDestroyed()) {
return;
}
fMapPtr = nullptr;
getDawnGpu()->getCopyEncoder()
.CopyBufferToBuffer(fStagingBuffer, fStagingOffset, fBuffer, 0, this->size());
}
bool GrDawnBuffer::onUpdateData(const void* src, size_t srcSizeInBytes) {
if (this->wasDestroyed()) {
return false;
}
this->onMap();
memcpy(fMapPtr, src, srcSizeInBytes);
this->onUnmap();
return true;
}
GrDawnGpu* GrDawnBuffer::getDawnGpu() const {
SkASSERT(!this->wasDestroyed());
return static_cast<GrDawnGpu*>(this->getGpu());
}
|
<?php
namespace Doctrine\ORM\Mapping;
/**
* A MappingException indicates that something is wrong with the mapping setup.
*
* @since 2.0
*/
class MappingException extends \Doctrine\ORM\ORMException
{
public static function pathRequired()
{
return new self("Specifying the paths to your entities is required ".
"in the AnnotationDriver to retrieve all class names.");
}
public static function identifierRequired($entityName)
{
return new self("No identifier/primary key specified for Entity '$entityName'."
. " Every Entity must have an identifier/primary key.");
}
public static function <API key>($entityName, $type)
{
return new self("The inheritance type '$type' specified for '$entityName' does not exist.");
}
public static function <API key>()
{
return new self("Id generators can't be used with a composite id.");
}
public static function missingFieldName()
{
return new self("The association mapping misses the 'fieldName' attribute.");
}
public static function missingTargetEntity($fieldName)
{
return new self("The association mapping '$fieldName' misses the 'targetEntity' attribute.");
}
public static function missingSourceEntity($fieldName)
{
return new self("The association mapping '$fieldName' misses the 'sourceEntity' attribute.");
}
public static function mappingFileNotFound($entityName, $fileName)
{
return new self("No mapping file found named '$fileName' for class '$entityName'.");
}
public static function mappingNotFound($className, $fieldName)
{
return new self("No mapping found for field '$fieldName' on class '$className'.");
}
public static function <API key>($fieldName)
{
return new self("OneToMany mapping on field '$fieldName' requires the 'mappedBy' attribute.");
}
public static function joinTableRequired($fieldName)
{
return new self("The mapping of field '$fieldName' requires an the 'joinTable' attribute.");
}
/**
* Called if a required option was not found but is required
*
* @param string $field which field cannot be processed?
* @param string $expectedOption which option is required
* @param string $hint Can optionally be used to supply a tip for common mistakes,
* e.g. "Did you think of the plural s?"
* @return MappingException
*/
static function <API key>($field, $expectedOption, $hint = '')
{
$message = "The mapping of field '{$field}' is invalid: The option '{$expectedOption}' is required.";
if ( ! empty($hint)) {
$message .= ' (Hint: ' . $hint . ')';
}
return new self($message);
}
/**
* Generic exception for invalid mappings.
*
* @param string $fieldName
*/
public static function invalidMapping($fieldName)
{
return new self("The mapping of field '$fieldName' is invalid.");
}
/**
* Exception for reflection exceptions - adds the entity name,
* because there might be long classnames that will be shortened
* within the stacktrace
*
* @param string $entity The entity's name
* @param \ReflectionException $previousException
*/
public static function reflectionFailure($entity, \ReflectionException $previousException)
{
return new self('An error occurred in ' . $entity, 0, $previousException);
}
public static function <API key>($className, $joinColumn)
{
return new self('The column ' . $joinColumn . ' must be mapped to a field in class '
. $className . ' since it is referenced by a join column of another class.');
}
public static function <API key>($className)
{
return new self('Class '.$className.' is not a valid entity or mapped super class.');
}
public static function <API key>($className, $propertyName)
{
return new self("The attribute 'type' is required for the column description of property ".$className."::\$".$propertyName.".");
}
public static function <API key>($className)
{
return new self("TableIdGenerator is not yet implemented for use with class ".$className);
}
/**
*
* @param string $entity The entity's name
* @param string $fieldName The name of the field that was already declared
*/
public static function <API key>($entity, $fieldName) {
return new self('Property "'.$fieldName.'" in "'.$entity.'" was already declared, but it must be declared only once');
}
public static function <API key>($entity, $fieldName) {
return new self('Property "'.$fieldName.'" in "'.$entity.'" was already declared, but it must be declared only once');
}
public static function <API key>($entity) {
return new self('Single id is not allowed on composite primary key in entity '.$entity);
}
public static function <API key>($entity, $fieldName, $unsupportedType) {
return new self('Locking type "'.$unsupportedType.'" (specified in "'.$entity.'", field "'.$fieldName.'") '
.'is not supported by Doctrine.'
);
}
public static function <API key>($path = null)
{
if ( ! empty($path)) {
$path = '[' . $path . ']';
}
return new self(
'File mapping drivers must have a valid directory path, ' .
'however the given path ' . $path . ' seems to be incorrect!'
);
}
/**
* Throws an exception that indicates that a class used in a discriminator map does not exist.
* An example would be an outdated (maybe renamed) classname.
*
* @param string $className The class that could not be found
* @param string $owningClass The class that declares the discriminator map.
* @return self
*/
public static function <API key>($className, $owningClass) {
return new self(
"Entity class '$className' used in the discriminator map of class '$owningClass' ".
"does not exist."
);
}
public static function <API key>($className)
{
return new self("Entity class '$className' is using inheritance but no discriminator map was defined.");
}
public static function <API key>($className)
{
return new self("Entity class '$className' is using inheritance but no discriminator column was defined.");
}
public static function <API key>($className, $type)
{
return new self("Discriminator column type on entity class '$className' is not allowed to be '$type'. 'string' or 'integer' type variables are suggested!");
}
public static function <API key>($className, $fieldName)
{
return new self("Setting Id field '$fieldName' as versionale in entity class '$className' is not supported.");
}
/**
* @param string $className
* @param string $columnName
* @return self
*/
public static function duplicateColumnName($className, $columnName)
{
return new self("Duplicate definition of column '".$columnName."' on entity '".$className."' in a field or discriminator column mapping.");
}
}
|
# Try to find hwloc libraries and headers.
# Usage of this module:
# find_package(hwloc)
# Variables defined by this module:
# HWLOC_FOUND System has hwloc libraries and headers
# HWLOC_LIBRARIES The hwloc library
# HWLOC_INCLUDE_DIRS The location of HWLOC headers
find_path(
HWLOC_PREFIX
NAMES include/hwloc.h
)
if (NOT HWLOC_PREFIX AND NOT $ENV{HWLOC_BASE} STREQUAL "")
set(HWLOC_PREFIX $ENV{HWLOC_BASE})
endif()
message(STATUS "Searching for hwloc library in path " ${HWLOC_PREFIX})
find_library(
HWLOC_LIBRARIES
NAMES hwloc
HINTS ${HWLOC_PREFIX}/lib
)
find_path(
HWLOC_INCLUDE_DIRS
NAMES hwloc.h
HINTS ${HWLOC_PREFIX}/include
)
include(<API key>)
<API key>(
HWLOC DEFAULT_MSG
HWLOC_LIBRARIES
HWLOC_INCLUDE_DIRS
)
mark_as_advanced(
HWLOC_LIBRARIES
HWLOC_INCLUDE_DIRS
)
if (HWLOC_FOUND)
if (NOT $ENV{HWLOC_LIB} STREQUAL "")
# set(HWLOC_LIBRARIES "$ENV{HWLOC_LIB}")
endif()
message(STATUS "hwloc includes: " ${HWLOC_INCLUDE_DIRS})
message(STATUS "hwloc libraries: " ${HWLOC_LIBRARIES})
endif()
|
package com.salesforce.dva.argus.service.metric.transform;
import com.salesforce.dva.argus.entity.Metric;
import com.salesforce.dva.argus.system.SystemAssert;
import java.util.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* COUNT, GROUP, UNION.
*
* @author rzhang
*/
public class <API key> implements Transform {
/** The metric name for this transform is result. */
public static final String RESULT_METRIC_NAME = "result";
private final ValueReducer valueUnionReducer;
private final String defaultScope;
private final String defaultMetricName;
/**
* Creates a new ReduceTransform object.
*
* @param valueUnionReducer <API key> The valueMapping.
*/
protected <API key>(ValueReducer valueUnionReducer) {
this.defaultScope = TransformFactory.Function.UNION.name();
this.defaultMetricName = TransformFactory.DEFAULT_METRIC_NAME;
this.valueUnionReducer = valueUnionReducer;
}
@Override
public String getResultScopeName() {
return defaultScope;
}
/**
* If constants is not null, apply mapping transform to metrics list. Otherwise, apply reduce transform to metrics list
*
* @param metrics The metrics to transform.
*
* @return The transformed metrics.
*/
@Override
public List<Metric> transform(List<Metric> metrics) {
return union(metrics);
}
/**
* Performs a columnar union of metrics.
*
* @param metrics The metrics to merge.
*
* @return The merged metrics.
*/
public List<Metric> union(List<Metric> metrics) {
SystemAssert.requireArgument(metrics != null, "Cannot transform empty metric/metrics");
if (metrics.isEmpty()) {
return metrics;
}
Metric newMetric = reduce(metrics);
Map<Long, String> reducedDatapoints = newMetric.getDatapoints();
Set<Long> sharedTimestamps = reducedDatapoints.keySet();
Map<Long, String> unionDatapoints = new TreeMap<Long, String>();
for (Metric metric : metrics) {
for (Map.Entry<Long, String> entry : metric.getDatapoints().entrySet()) {
if (!sharedTimestamps.contains(entry.getKey())) {
unionDatapoints.put(entry.getKey(), entry.getValue());
}
}
}
newMetric.addDatapoints(unionDatapoints);
return Arrays.asList(newMetric);
}
/**
* Reduce transform for the list of metrics.
*
* @param metrics The list of metrics to reduce.
*
* @return The reduced metric.
*/
protected Metric reduce(List<Metric> metrics) {
SystemAssert.requireArgument(metrics != null, "Cannot transform empty metric/metrics");
/*
* if (metrics.isEmpty()) { return new Metric(defaultScope, defaultMetricName); }
*/
MetricDistiller distiller = new MetricDistiller();
distiller.distill(metrics);
Map<Long, List<String>> collated = collate(metrics);
Map<Long, String> minDatapoints = reduce(collated, metrics);
String newMetricName = distiller.getMetric() == null ? defaultMetricName : distiller.getMetric();
Metric newMetric = new Metric(defaultScope, newMetricName);
newMetric.setDisplayName(distiller.getDisplayName());
newMetric.setUnits(distiller.getUnits());
newMetric.setTags(distiller.getTags());
newMetric.setDatapoints(minDatapoints);
return newMetric;
}
private Map<Long, List<String>> collate(List<Metric> metrics) {
Map<Long, List<String>> collated = new HashMap<Long, List<String>>();
for (Metric metric : metrics) {
for (Map.Entry<Long, String> point : metric.getDatapoints().entrySet()) {
if (!collated.containsKey(point.getKey())) {
collated.put(point.getKey(), new ArrayList<String>());
}
collated.get(point.getKey()).add(point.getValue());
}
}
return collated;
}
private Map<Long, String> reduce(Map<Long, List<String>> collated, List<Metric> metrics) {
Map<Long, String> reducedDatapoints = new HashMap<>();
for (Map.Entry<Long, List<String>> entry : collated.entrySet()) {
if (entry.getValue().size() < metrics.size()) {
continue;
}
reducedDatapoints.put(entry.getKey(), this.valueUnionReducer.reduce(entry.getValue()));
}
return reducedDatapoints;
}
@Override
public List<Metric> transform(List<Metric> metrics, List<String> constants) {
throw new <API key>("Union transform can't be used with constants!");
}
@Override
public List<Metric> transform(List<Metric>... listOfList) {
throw new <API key>("Union doesn't need list of list");
}
}
|
#include "net/url_request/url_fetcher_core.h"
#include <stdint.h>
#include "base/bind.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "base/profiler/scoped_tracker.h"
#include "base/<API key>.h"
#include "base/<API key>.h"
#include "base/stl_util.h"
#include "base/<API key>.h"
#include "base/tracked_objects.h"
#include "net/base/<API key>.h"
#include "net/base/io_buffer.h"
#include "net/base/load_flags.h"
#include "net/base/net_errors.h"
#include "net/base/request_priority.h"
#include "net/base/<API key>.h"
#include "net/base/upload_data_stream.h"
#include "net/base/<API key>.h"
#include "net/http/<API key>.h"
#include "net/url_request/redirect_info.h"
#include "net/url_request/<API key>.h"
#include "net/url_request/<API key>.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/<API key>.h"
#include "net/url_request/<API key>.h"
namespace {
const int kBufferSize = 4096;
const int <API key> = 100;
bool <API key> = false;
void <API key>(int result) {}
} // namespace
namespace net {
URLFetcherCore::Registry::Registry() {}
URLFetcherCore::Registry::~Registry() {}
void URLFetcherCore::Registry::AddURLFetcherCore(URLFetcherCore* core) {
DCHECK(!ContainsKey(fetchers_, core));
fetchers_.insert(core);
}
void URLFetcherCore::Registry::<API key>(URLFetcherCore* core) {
DCHECK(ContainsKey(fetchers_, core));
fetchers_.erase(core);
}
void URLFetcherCore::Registry::CancelAll() {
while (!fetchers_.empty())
(*fetchers_.begin())->CancelURLRequest(ERR_ABORTED);
}
// static
base::LazyInstance<URLFetcherCore::Registry>
URLFetcherCore::g_registry = <API key>;
URLFetcherCore::URLFetcherCore(URLFetcher* fetcher,
const GURL& original_url,
URLFetcher::RequestType request_type,
URLFetcherDelegate* d)
: fetcher_(fetcher),
original_url_(original_url),
request_type_(request_type),
delegate_(d),
<API key>(base::<API key>::Get()),
load_flags_(LOAD_NORMAL),
response_code_(URLFetcher::<API key>),
buffer_(new IOBuffer(kBufferSize)),
<API key>(NULL),
<API key>(false),
upload_content_set_(false),
<API key>(0),
<API key>(0),
referrer_policy_(
URLRequest::<API key>),
is_chunked_upload_(false),
was_cancelled_(false),
stop_on_redirect_(false),
<API key>(false),
<API key>(true),
num_retries_on_5xx_(0),
max_retries_on_5xx_(0),
<API key>(0),
<API key>(0),
<API key>(-1),
<API key>(0),
<API key>(-1) {
CHECK(original_url_.is_valid());
}
void URLFetcherCore::Start() {
DCHECK(<API key>.get());
DCHECK(<API key>.get()) << "We need an URLRequestContext!";
if (<API key>.get()) {
DCHECK_EQ(<API key>,
<API key>-><API key>());
} else {
<API key> = <API key>-><API key>();
}
DCHECK(<API key>.get()) << "We need an IO task runner";
<API key>->PostTask(
FROM_HERE, base::Bind(&URLFetcherCore::StartOnIOThread, this));
}
void URLFetcherCore::Stop() {
if (<API key>.get()) // May be NULL in tests.
DCHECK(<API key>-><API key>());
delegate_ = NULL;
fetcher_ = NULL;
if (!<API key>.get())
return;
if (<API key>-><API key>()) {
CancelURLRequest(ERR_ABORTED);
} else {
<API key>->PostTask(
FROM_HERE,
base::Bind(&URLFetcherCore::CancelURLRequest, this, ERR_ABORTED));
}
}
void URLFetcherCore::SetUploadData(const std::string& upload_content_type,
const std::string& upload_content) {
<API key>();
DCHECK(!is_chunked_upload_);
DCHECK(<API key>.empty());
// Empty |upload_content_type| is allowed iff the |upload_content| is empty.
DCHECK(upload_content.empty() || !upload_content_type.empty());
<API key> = upload_content_type;
upload_content_ = upload_content;
upload_content_set_ = true;
}
void URLFetcherCore::SetUploadFilePath(
const std::string& upload_content_type,
const base::FilePath& file_path,
uint64 range_offset,
uint64 range_length,
scoped_refptr<base::TaskRunner> file_task_runner) {
<API key>();
DCHECK(!is_chunked_upload_);
DCHECK_EQ(<API key>, 0ULL);
DCHECK_EQ(<API key>, 0ULL);
DCHECK(<API key>.empty());
DCHECK(!upload_content_type.empty());
<API key> = upload_content_type;
upload_file_path_ = file_path;
<API key> = range_offset;
<API key> = range_length;
<API key> = file_task_runner;
upload_content_set_ = true;
}
void URLFetcherCore::<API key>(
const std::string& upload_content_type,
const URLFetcher::<API key>& factory) {
<API key>();
DCHECK(!is_chunked_upload_);
DCHECK(<API key>.empty());
<API key> = upload_content_type;
<API key> = factory;
upload_content_set_ = true;
}
void URLFetcherCore::SetChunkedUpload(const std::string& content_type) {
if (!is_chunked_upload_) {
<API key>();
DCHECK(<API key>.empty());
}
// Empty |content_type| is not allowed here, because it is impossible
// to ensure non-empty upload content as it is not yet supplied.
DCHECK(!content_type.empty());
<API key> = content_type;
upload_content_.clear();
is_chunked_upload_ = true;
}
void URLFetcherCore::AppendChunkToUpload(const std::string& content,
bool is_last_chunk) {
DCHECK(<API key>.get());
DCHECK(<API key>.get());
<API key>->PostTask(
FROM_HERE,
base::Bind(&URLFetcherCore::<API key>, this, content,
is_last_chunk));
}
void URLFetcherCore::SetLoadFlags(int load_flags) {
load_flags_ = load_flags;
}
int URLFetcherCore::GetLoadFlags() const {
return load_flags_;
}
void URLFetcherCore::SetReferrer(const std::string& referrer) {
referrer_ = referrer;
}
void URLFetcherCore::SetReferrerPolicy(
URLRequest::ReferrerPolicy referrer_policy) {
referrer_policy_ = referrer_policy;
}
void URLFetcherCore::<API key>(
const std::string& <API key>) {
<API key>.Clear();
<API key>.<API key>(<API key>);
}
void URLFetcherCore::<API key>(const std::string& header_line) {
<API key>.AddHeaderFromString(header_line);
}
void URLFetcherCore::SetRequestContext(
<API key>* <API key>) {
DCHECK(!<API key>.get());
DCHECK(<API key>);
<API key> = <API key>;
}
void URLFetcherCore::<API key>(
const GURL& <API key>) {
DCHECK(<API key>.is_empty());
<API key> = <API key>;
}
void URLFetcherCore::<API key>(
const void* key,
const URLFetcher::CreateDataCallback& <API key>) {
DCHECK(key);
DCHECK(!<API key>.is_null());
<API key> = key;
<API key> = <API key>;
}
void URLFetcherCore::SetStopOnRedirect(bool stop_on_redirect) {
stop_on_redirect_ = stop_on_redirect;
}
void URLFetcherCore::<API key>(bool retry) {
<API key> = retry;
}
void URLFetcherCore::SetMaxRetriesOn5xx(int max_retries) {
max_retries_on_5xx_ = max_retries;
}
int URLFetcherCore::GetMaxRetriesOn5xx() const {
return max_retries_on_5xx_;
}
base::TimeDelta URLFetcherCore::GetBackoffDelay() const {
return backoff_delay_;
}
void URLFetcherCore::<API key>(int max_retries) {
<API key> = max_retries;
}
void URLFetcherCore::<API key>(
const base::FilePath& file_path,
scoped_refptr<base::SequencedTaskRunner> file_task_runner) {
DCHECK(<API key>-><API key>());
<API key>(scoped_ptr<<API key>>(
new <API key>(file_task_runner, file_path)));
}
void URLFetcherCore::<API key>(
scoped_refptr<base::SequencedTaskRunner> file_task_runner) {
DCHECK(<API key>-><API key>());
<API key>(scoped_ptr<<API key>>(
new <API key>(file_task_runner, base::FilePath())));
}
void URLFetcherCore::<API key>(
scoped_ptr<<API key>> response_writer) {
DCHECK(<API key>-><API key>());
response_writer_ = response_writer.Pass();
}
HttpResponseHeaders* URLFetcherCore::GetResponseHeaders() const {
return response_headers_.get();
}
// TODO(panayiotis): socket_address_ is written in the IO thread,
// if this is accessed in the UI thread, this could result in a race.
// Same for response_headers_ above and <API key> below.
HostPortPair URLFetcherCore::GetSocketAddress() const {
return socket_address_;
}
bool URLFetcherCore::WasFetchedViaProxy() const {
return <API key>;
}
const GURL& URLFetcherCore::GetOriginalURL() const {
return original_url_;
}
const GURL& URLFetcherCore::GetURL() const {
return url_;
}
const URLRequestStatus& URLFetcherCore::GetStatus() const {
return status_;
}
int URLFetcherCore::GetResponseCode() const {
return response_code_;
}
const ResponseCookies& URLFetcherCore::GetCookies() const {
return cookies_;
}
void URLFetcherCore::<API key>() {
DCHECK(<API key>-><API key>());
if (<API key>.get()) {
<API key>->PostTask(
FROM_HERE, base::Bind(&URLFetcherCore::<API key>, this));
}
}
bool URLFetcherCore::GetResponseAsString(
std::string* out_response_string) const {
<API key>* string_writer =
response_writer_ ? response_writer_->AsStringWriter() : NULL;
if (!string_writer)
return false;
*out_response_string = string_writer->data();
<API key>("UrlFetcher.StringResponseSize",
(string_writer->data().length() / 1024));
return true;
}
bool URLFetcherCore::<API key>(bool take_ownership,
base::FilePath* out_response_path) {
DCHECK(<API key>-><API key>());
<API key>* file_writer =
response_writer_ ? response_writer_->AsFileWriter() : NULL;
if (!file_writer)
return false;
*out_response_path = file_writer->file_path();
if (take_ownership) {
// Intentionally calling a file_writer_ method directly without posting
// the task to <API key>.
// This is for correctly handling the case when file_writer_->DisownFile()
// is soon followed by URLFetcherCore::Stop(). We have to make sure that
// DisownFile takes effect before Stop deletes file_writer_.
// This direct call should be thread-safe, since DisownFile itself does no
// file operation. It just flips the state to be referred in destruction.
file_writer->DisownFile();
}
return true;
}
void URLFetcherCore::OnReceivedRedirect(URLRequest* request,
const RedirectInfo& redirect_info,
bool* defer_redirect) {
DCHECK_EQ(request, request_.get());
DCHECK(<API key>-><API key>());
if (stop_on_redirect_) {
<API key> = true;
url_ = redirect_info.new_url;
response_code_ = request_->GetResponseCode();
<API key> = request_-><API key>();
request->Cancel();
OnReadCompleted(request, 0);
}
}
void URLFetcherCore::OnResponseStarted(URLRequest* request) {
DCHECK_EQ(request, request_.get());
DCHECK(<API key>-><API key>());
if (request_->status().is_success()) {
response_code_ = request_->GetResponseCode();
response_headers_ = request_->response_headers();
socket_address_ = request_->GetSocketAddress();
<API key> = request_-><API key>();
<API key> = request_-><API key>();
}
ReadResponse();
}
void URLFetcherCore::<API key>(
URLRequest* request,
SSLCertRequestInfo* cert_request_info) {
DCHECK_EQ(request, request_.get());
DCHECK(<API key>-><API key>());
if (<API key>) {
request-><API key>(NULL);
} else {
request->Cancel();
}
}
void URLFetcherCore::OnReadCompleted(URLRequest* request,
int bytes_read) {
DCHECK(request == request_);
DCHECK(<API key>-><API key>());
if (!<API key>)
url_ = request->url();
<API key>* throttler_manager =
request->context()->throttler_manager();
if (throttler_manager)
<API key> = throttler_manager->RegisterRequestUrl(url_);
do {
if (!request_->status().is_success() || bytes_read <= 0)
break;
<API key> += bytes_read;
<API key>();
const int result =
WriteBuffer(new DrainableIOBuffer(buffer_.get(), bytes_read));
if (result < 0) {
// Write failed or waiting for write completion.
return;
}
} while (request_->Read(buffer_.get(), kBufferSize, &bytes_read));
const URLRequestStatus status = request_->status();
if (status.is_success())
request_->GetResponseCookies(&cookies_);
// See comments re: HEAD requests in ReadResponse().
if (!status.is_io_pending() || request_type_ == URLFetcher::HEAD) {
status_ = status;
ReleaseRequest();
// No more data to write.
const int result = response_writer_->Finish(
base::Bind(&URLFetcherCore::DidFinishWriting, this));
if (result != ERR_IO_PENDING)
DidFinishWriting(result);
}
}
void URLFetcherCore::CancelAll() {
g_registry.Get().CancelAll();
}
int URLFetcherCore::GetNumFetcherCores() {
return g_registry.Get().size();
}
void URLFetcherCore::<API key>(bool ignored) {
<API key> = ignored;
}
URLFetcherCore::~URLFetcherCore() {
// |request_| should be NULL. If not, it's unsafe to delete it here since we
// may not be on the IO thread.
DCHECK(!request_.get());
}
void URLFetcherCore::StartOnIOThread() {
DCHECK(<API key>-><API key>());
if (!response_writer_)
response_writer_.reset(new <API key>);
const int result = response_writer_->Initialize(
base::Bind(&URLFetcherCore::DidInitializeWriter, this));
if (result != ERR_IO_PENDING)
DidInitializeWriter(result);
}
void URLFetcherCore::StartURLRequest() {
DCHECK(<API key>-><API key>());
if (was_cancelled_) {
// Since StartURLRequest() is posted as a *delayed* task, it may
// run after the URLFetcher was already stopped.
return;
}
DCHECK(<API key>.get());
DCHECK(!request_.get());
g_registry.Get().AddURLFetcherCore(this);
<API key> = 0;
request_ = <API key>-><API key>()->CreateRequest(
original_url_, DEFAULT_PRIORITY, this);
request_->set_stack_trace(stack_trace_);
int flags = request_->load_flags() | load_flags_;
if (is_chunked_upload_)
request_->EnableChunkedUpload();
request_->SetLoadFlags(flags);
request_->SetReferrer(referrer_);
request_->set_referrer_policy(referrer_policy_);
request_-><API key>(<API key>.is_empty() ?
original_url_ : <API key>);
if (<API key> && !<API key>.is_null()) {
request_->SetUserData(<API key>,
<API key>.Run());
}
switch (request_type_) {
case URLFetcher::GET:
break;
case URLFetcher::POST:
case URLFetcher::PUT:
case URLFetcher::PATCH: {
// Upload content must be set.
DCHECK(is_chunked_upload_ || upload_content_set_);
request_->set_method(
request_type_ == URLFetcher::POST ? "POST" :
request_type_ == URLFetcher::PUT ? "PUT" : "PATCH");
if (!<API key>.empty()) {
<API key>.SetHeader(HttpRequestHeaders::kContentType,
<API key>);
}
if (!upload_content_.empty()) {
scoped_ptr<UploadElementReader> reader(new <API key>(
upload_content_.data(), upload_content_.size()));
request_->set_upload(
<API key>::CreateWithReader(reader.Pass(), 0));
} else if (!upload_file_path_.empty()) {
scoped_ptr<UploadElementReader> reader(
new <API key>(<API key>.get(),
upload_file_path_,
<API key>,
<API key>,
base::Time()));
request_->set_upload(
<API key>::CreateWithReader(reader.Pass(), 0));
} else if (!<API key>.is_null()) {
scoped_ptr<UploadDataStream> stream = <API key>.Run();
DCHECK(stream);
request_->set_upload(stream.Pass());
}
<API key> = -1;
// layer and avoid using timer here.
<API key>.reset(
new base::RepeatingTimer<URLFetcherCore>());
<API key>->Start(
FROM_HERE,
base::TimeDelta::FromMilliseconds(<API key>),
this,
&URLFetcherCore::<API key>);
break;
}
case URLFetcher::HEAD:
request_->set_method("HEAD");
break;
case URLFetcher::DELETE_REQUEST:
request_->set_method("DELETE");
break;
default:
NOTREACHED();
}
if (!<API key>.IsEmpty())
request_-><API key>(<API key>);
request_->Start();
}
void URLFetcherCore::DidInitializeWriter(int result) {
if (result != OK) {
CancelURLRequest(result);
<API key>->PostTask(
FROM_HERE,
base::Bind(&URLFetcherCore::<API key>, this));
return;
}
<API key>();
}
void URLFetcherCore::<API key>() {
DCHECK(<API key>-><API key>());
if (was_cancelled_)
return;
DCHECK(<API key>.get());
int64 delay = 0;
if (!<API key>.get()) {
<API key>* manager =
<API key>-><API key>()->throttler_manager();
if (manager) {
<API key> =
manager->RegisterRequestUrl(original_url_);
}
}
if (<API key>.get()) {
delay = <API key>-><API key>(
<API key>());
}
if (delay == 0) {
StartURLRequest();
} else {
base::<API key>::Get()->PostDelayedTask(
FROM_HERE, base::Bind(&URLFetcherCore::StartURLRequest, this),
base::TimeDelta::FromMilliseconds(delay));
}
}
void URLFetcherCore::CancelURLRequest(int error) {
DCHECK(<API key>-><API key>());
if (request_.get()) {
request_->CancelWithError(error);
ReleaseRequest();
}
// Set the error manually.
// Normally, calling URLRequest::CancelWithError() results in calling
// OnReadCompleted() with bytes_read = -1 via an asynchronous task posted by
// URLRequestJob::NotifyDone(). But, because the request was released
// immediately after being canceled, the request could not call
// OnReadCompleted() which overwrites |status_| with the error status.
status_.set_status(URLRequestStatus::CANCELED);
status_.set_error(error);
// Release the reference to the request context. There could be multiple
// references to URLFetcher::Core at this point so it may take a while to
// delete the object, but we cannot delay the destruction of the request
// context.
<API key> = NULL;
<API key> = GURL();
<API key> = NULL;
<API key>.Reset();
was_cancelled_ = true;
}
void URLFetcherCore::<API key>(
base::TimeDelta backoff_delay) {
DCHECK(<API key>-><API key>());
// Save the status and backoff_delay so that delegates can read it.
if (delegate_) {
backoff_delay_ = backoff_delay;
<API key>();
}
}
void URLFetcherCore::<API key>() {
DCHECK(<API key>-><API key>());
if (delegate_)
delegate_->OnURLFetchComplete(fetcher_);
}
void URLFetcherCore::<API key>() {
DCHECK(<API key>-><API key>());
if (<API key>.get()) {
int status_code = response_code_;
if (status_code == URLFetcher::<API key>) {
// The status code will generally be known by the time clients
// call the |<API key>()| function (which ends up
// calling the current function) but if it's not, we need to assume
// the response was successful so that the total failure count
// used to calculate exponential back-off goes up.
status_code = 200;
}
<API key>-><API key>(status_code);
}
}
void URLFetcherCore::DidFinishWriting(int result) {
if (result != OK) {
CancelURLRequest(result);
<API key>->PostTask(
FROM_HERE,
base::Bind(&URLFetcherCore::<API key>, this));
return;
}
// If the file was successfully closed, then the URL request is complete.
<API key>();
}
void URLFetcherCore::<API key>() {
DCHECK(<API key>-><API key>());
base::TimeDelta backoff_delay;
// Checks the response from server.
if (response_code_ >= 500 ||
status_.error() == <API key>) {
// When encountering a server error, we will send the request again
// after backoff time.
++num_retries_on_5xx_;
// Note that backoff_delay may be 0 because (a) the
// <API key> and related code does not
// necessarily back off on the first error, (b) it only backs off
// have a throttler manager.
base::TimeTicks <API key> = <API key>();
backoff_delay = <API key> - base::TimeTicks::Now();
if (backoff_delay < base::TimeDelta())
backoff_delay = base::TimeDelta();
if (<API key> &&
num_retries_on_5xx_ <= max_retries_on_5xx_) {
StartOnIOThread();
return;
}
} else {
backoff_delay = base::TimeDelta();
}
// Retry if the request failed due to network changes.
if (status_.error() == ERR_NETWORK_CHANGED &&
<API key> < <API key>) {
++<API key>;
// Retry soon, after flushing all the current tasks which may include
// further network change observers.
<API key>->PostTask(
FROM_HERE, base::Bind(&URLFetcherCore::StartOnIOThread, this));
return;
}
<API key> = NULL;
<API key> = GURL();
<API key> = NULL;
<API key>.Reset();
bool posted = <API key>->PostTask(
FROM_HERE,
base::Bind(&URLFetcherCore::<API key>, this, backoff_delay));
// If the delegate message loop does not exist any more, then the delegate
// should be gone too.
DCHECK(posted || !delegate_);
}
void URLFetcherCore::ReleaseRequest() {
<API key>.reset();
request_.reset();
g_registry.Get().<API key>(this);
}
base::TimeTicks URLFetcherCore::<API key>() {
DCHECK(<API key>-><API key>());
if (!<API key>.get())
return base::TimeTicks();
base::TimeTicks <API key> =
<API key>-><API key>();
base::TimeTicks <API key>;
if (<API key>.get() &&
<API key>.get() != <API key>.get()) {
<API key> =
<API key>-><API key>();
}
return <API key> > <API key> ?
<API key> : <API key>;
}
void URLFetcherCore::<API key>(
const std::string& content, bool is_last_chunk) {
if (was_cancelled_) {
// Since <API key>() is posted as a *delayed* task, it
// may run after the URLFetcher was already stopped.
return;
}
DCHECK(is_chunked_upload_);
DCHECK(request_.get());
DCHECK(!content.empty());
request_->AppendChunkToUpload(content.data(),
static_cast<int>(content.length()),
is_last_chunk);
}
int URLFetcherCore::WriteBuffer(scoped_refptr<DrainableIOBuffer> data) {
while (data->BytesRemaining() > 0) {
const int result = response_writer_->Write(
data.get(),
data->BytesRemaining(),
base::Bind(&URLFetcherCore::DidWriteBuffer, this, data));
if (result < 0) {
if (result != ERR_IO_PENDING)
DidWriteBuffer(data, result);
return result;
}
data->DidConsume(result);
}
return OK;
}
void URLFetcherCore::DidWriteBuffer(scoped_refptr<DrainableIOBuffer> data,
int result) {
if (result < 0) { // Handle errors.
CancelURLRequest(result);
response_writer_->Finish(base::Bind(&<API key>));
<API key>->PostTask(
FROM_HERE,
base::Bind(&URLFetcherCore::<API key>, this));
return;
}
// Continue writing.
data->DidConsume(result);
if (WriteBuffer(data) < 0)
return;
// Finished writing buffer_. Read some more, unless the request has been
// cancelled and deleted.
DCHECK_EQ(0, data->BytesRemaining());
if (request_.get())
ReadResponse();
}
void URLFetcherCore::ReadResponse() {
// Some servers may treat HEAD requests as GET requests. To free up the
// network connection as soon as possible, signal that the request has
// completed immediately, without trying to read any data back (all we care
// about is the response code and headers, which we already have).
int bytes_read = 0;
if (request_->status().is_success() &&
(request_type_ != URLFetcher::HEAD)) {
if (!request_->Read(buffer_.get(), kBufferSize, &bytes_read))
bytes_read = -1; // Match OnReadCompleted() interface contract.
}
OnReadCompleted(request_.get(), bytes_read);
}
void URLFetcherCore::<API key>() {
DCHECK(<API key>-><API key>());
if (request_.get()) {
int64 current = request_->GetUploadProgress().position();
if (<API key> != current) {
<API key> = current;
int64 total = -1;
if (!is_chunked_upload_) {
total = static_cast<int64>(request_->GetUploadProgress().size());
// Total may be zero if the UploadDataStream::Init has not been called
// yet. Don't send the upload progress until the size is initialized.
if (!total)
return;
}
<API key>->PostTask(
FROM_HERE,
base::Bind(
&URLFetcherCore::<API key>,
this, current, total));
}
}
}
void URLFetcherCore::<API key>(
int64 current, int64 total) {
DCHECK(<API key>-><API key>());
if (delegate_)
delegate_-><API key>(fetcher_, current, total);
}
void URLFetcherCore::<API key>() {
DCHECK(<API key>-><API key>());
// TODO(pkasting): Remove ScopedTracker below once crbug.com/455952 is fixed.
tracked_objects::ScopedTracker tracking_profile2(
<API key>(
"455952 <API key>->PostTask()"));
<API key>->PostTask(
FROM_HERE,
base::Bind(
&URLFetcherCore::<API key>,
this, <API key>, <API key>));
}
void URLFetcherCore::<API key>(
int64 current, int64 total) {
DCHECK(<API key>-><API key>());
if (delegate_)
delegate_-><API key>(fetcher_, current, total);
}
void URLFetcherCore::<API key>() const {
DCHECK(!upload_content_set_);
DCHECK(upload_content_.empty());
DCHECK(upload_file_path_.empty());
DCHECK(<API key>.is_null());
}
} // namespace net
|
<?php
class SortWeightRegistry {
public static $<API key> = true;
public static $relations = array();
public static $default_sorts = array(); // original default_sort
public static $add_weight_columns = array();
public static $direction = 'ASC'; // ASC || DESC
public static $module_path;
public static function set_module_path($directory)
{
self::$module_path = $directory;
}
public static function decorate($class, $relationName = null) {
if(!isset(self::$relations[$class]))
{
self::$relations[$class] = array();
}
// if relationName is false, enable the sorting on object iteslf (skip SortWeight map)
if(!class_exists($class) || !$sng = new $class())
{
user_error('Unknown class passed (' . $class .')', E_USER_WARNING);
}
elseif($relationName === null )
{
user_error('You must provide the Component to order for ' . $class, E_USER_WARNING);
}
elseif(!$sng->hasMethod($relationName) || !$component = $sng->$relationName())
{
user_error('Component "' . $relationName . '" must exist on ' . $class,E_USER_WARNING);
}
elseif(isset(self::$relations[$class][$relationName]))
{
user_error('Component "' . $relationName . '" already decorates ' . $class,E_USER_WARNING);
}
else
{
$relationClass = ($component->is_a('ComponentSet')) ?
$component->childClass : $component->class;
self::$relations[$class][$relationName] = $relationClass;
$current_sort = Object::get_static($relationClass, 'default_sort');
if(self::$<API key> || empty($current_sort))
{
Object::set_static($relationClass,'default_sort','[SortWeight]');
if($current_sort != '[SortWeight]')
{
self::$default_sorts[$relationClass] = $current_sort;
}
}
if(!Object::has_extension($relationClass,'<API key>'))
{
Object::add_extension($relationClass,'<API key>');
}
return;
}
return user_error('SortWeight decoration failed for ' . __CLASS__ . '::' . __FUNCTION__ . "(\"$class\",\"$relationName\")",E_USER_WARNING);
}
}
|
#ifndef <API key>
#define <API key>
#include "ui/gfx/geometry/mojom/<API key>.h"
#include "ui/gfx/mojom/rrect_f.mojom-shared.h"
#include "ui/gfx/rrect_f.h"
#include "ui/gfx/rrect_f_builder.h"
namespace mojo {
namespace {
gfx::mojom::RRectFType GfxRRectFTypeToMojo(gfx::RRectF::Type type) {
switch (type) {
case gfx::RRectF::Type::kEmpty:
return gfx::mojom::RRectFType::kEmpty;
case gfx::RRectF::Type::kRect:
return gfx::mojom::RRectFType::kRect;
case gfx::RRectF::Type::kSingle:
return gfx::mojom::RRectFType::kSingle;
case gfx::RRectF::Type::kSimple:
return gfx::mojom::RRectFType::kSimple;
case gfx::RRectF::Type::kOval:
return gfx::mojom::RRectFType::kOval;
case gfx::RRectF::Type::kComplex:
return gfx::mojom::RRectFType::kComplex;
}
NOTREACHED();
return gfx::mojom::RRectFType::kEmpty;
}
gfx::RRectF::Type MojoRRectFTypeToGfx(gfx::mojom::RRectFType type) {
switch (type) {
case gfx::mojom::RRectFType::kEmpty:
return gfx::RRectF::Type::kEmpty;
case gfx::mojom::RRectFType::kRect:
return gfx::RRectF::Type::kRect;
case gfx::mojom::RRectFType::kSingle:
return gfx::RRectF::Type::kSingle;
case gfx::mojom::RRectFType::kSimple:
return gfx::RRectF::Type::kSimple;
case gfx::mojom::RRectFType::kOval:
return gfx::RRectF::Type::kOval;
case gfx::mojom::RRectFType::kComplex:
return gfx::RRectF::Type::kComplex;
}
NOTREACHED();
return gfx::RRectF::Type::kEmpty;
}
} // namespace
template <>
struct StructTraits<gfx::mojom::RRectFDataView, gfx::RRectF> {
static gfx::mojom::RRectFType type(const gfx::RRectF& input) {
return GfxRRectFTypeToMojo(input.GetType());
}
static gfx::RectF rect(const gfx::RRectF& input) { return input.rect(); }
static gfx::Vector2dF upper_left(const gfx::RRectF& input) {
return input.GetCornerRadii(gfx::RRectF::Corner::kUpperLeft);
}
static gfx::Vector2dF upper_right(const gfx::RRectF& input) {
return input.GetCornerRadii(gfx::RRectF::Corner::kUpperRight);
}
static gfx::Vector2dF lower_right(const gfx::RRectF& input) {
return input.GetCornerRadii(gfx::RRectF::Corner::kLowerRight);
}
static gfx::Vector2dF lower_left(const gfx::RRectF& input) {
return input.GetCornerRadii(gfx::RRectF::Corner::kLowerLeft);
}
static bool Read(gfx::mojom::RRectFDataView data, gfx::RRectF* out) {
gfx::RRectF::Type type(MojoRRectFTypeToGfx(data.type()));
gfx::RectF rect;
if (!data.ReadRect(&rect))
return false;
if (type <= gfx::RRectF::Type::kRect) {
*out = gfx::RRectFBuilder().set_rect(rect).Build();
return true;
}
gfx::Vector2dF upper_left;
if (!data.ReadUpperLeft(&upper_left))
return false;
if (type <= gfx::RRectF::Type::kSimple) {
*out = gfx::RRectFBuilder()
.set_rect(rect)
.set_radius(upper_left.x(), upper_left.y())
.Build();
return true;
}
gfx::Vector2dF upper_right;
gfx::Vector2dF lower_right;
gfx::Vector2dF lower_left;
if (!data.ReadUpperRight(&upper_right) ||
!data.ReadLowerRight(&lower_right) ||
!data.ReadLowerLeft(&lower_left)) {
return false;
}
*out = gfx::RRectFBuilder()
.set_rect(rect)
.set_upper_left(upper_left.x(), upper_left.y())
.set_upper_right(upper_right.x(), upper_right.y())
.set_lower_right(lower_right.x(), lower_right.y())
.set_lower_left(lower_left.x(), lower_left.y())
.Build();
return true;
}
};
} // namespace mojo
#endif // <API key>
|
#include "components/password_manager/core/browser/sql_table_builder.h"
#include <algorithm>
#include <set>
#include <utility>
#include "base/numerics/safe_conversions.h"
#include "base/stl_util.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "sql/database.h"
#include "sql/transaction.h"
namespace password_manager {
namespace {
// Appends |name| to |list_of_names|, separating items with ", ".
void Append(const std::string& name, std::string* list_of_names) {
if (list_of_names->empty())
*list_of_names = name;
else
*list_of_names += ", " + name;
}
} // namespace
// static
unsigned constexpr SQLTableBuilder::kInvalidVersion;
struct SQLTableBuilder::Column {
std::string name;
std::string type;
// Whether this column is the table's PRIMARY KEY.
bool is_primary_key;
// Whether this column is part of the table's UNIQUE constraint.
bool part_of_unique_key;
// The first version this column is part of.
unsigned min_version;
// The last version this column is part of. The value of kInvalidVersion
// means that it is part of all versions since |min_version|.
unsigned max_version;
// Renaming of a column is stored as a sequence of one removed and one added
// column in |columns_|. To distinguish it from an unrelated removal and
// addition, the following bit is set to true for the added columns which
// are part of renaming. Those columns will get the data of their
// predecessors. If the bit is false, the column will be filled with the
// default value on creation.
bool gets_previous_data;
};
struct SQLTableBuilder::Index {
// The name of this index.
std::string name;
// The names of columns this index is built from.
std::vector<std::string> columns;
// The first version this index is part of.
unsigned min_version;
// The last version this index is part of. The value of kInvalidVersion
// means that it is part of all versions since |min_version|.
unsigned max_version;
};
SQLTableBuilder::SQLTableBuilder(const std::string& table_name)
: table_name_(table_name) {}
SQLTableBuilder::~SQLTableBuilder() = default;
void SQLTableBuilder::AddColumn(std::string name, std::string type) {
DCHECK(<API key>(name) == columns_.rend());
columns_.push_back({std::move(name), std::move(type), false, false,
sealed_version_ + 1, kInvalidVersion, false});
}
void SQLTableBuilder::AddPrimaryKeyColumn(std::string name) {
for (const Column& column : columns_) {
DCHECK(!column.is_primary_key);
}
AddColumn(std::move(name), "INTEGER");
columns_.back().is_primary_key = true;
}
void SQLTableBuilder::<API key>(std::string name, std::string type) {
AddColumn(std::move(name), std::move(type));
columns_.back().part_of_unique_key = true;
}
void SQLTableBuilder::RenameColumn(const std::string& old_name,
const std::string& new_name) {
auto old_column = <API key>(old_name);
DCHECK(old_column != columns_.rend());
if (old_name == new_name) // The easy case.
return;
DCHECK(<API key>(new_name) == columns_.rend());
// Check there is no index in the current version that references |old_name|.
DCHECK(std::none_of(indices_.begin(), indices_.end(),
[&old_name](const Index& index) {
return index.max_version == kInvalidVersion &&
base::Contains(index.columns, old_name);
}));
if (sealed_version_ != kInvalidVersion &&
old_column->min_version <= sealed_version_) {
// This column exists in the last sealed version. Therefore it cannot be
// just replaced, it needs to be kept for generating the migration code.
Column new_column = {new_name,
old_column->type,
old_column->is_primary_key,
old_column->part_of_unique_key,
sealed_version_ + 1,
kInvalidVersion,
true};
old_column->max_version = sealed_version_;
auto past_old =
old_column.base(); // Points one element after |old_column|.
columns_.insert(past_old, std::move(new_column));
} else {
// This column was just introduced in the currently unsealed version. To
// rename it, it is enough just to modify the entry in columns_.
old_column->name = new_name;
}
}
// Removes column |name|. |name| must have been added in the past.
void SQLTableBuilder::DropColumn(const std::string& name) {
auto column = <API key>(name);
DCHECK(column != columns_.rend());
// Check there is no index in the current version that references |old_name|.
DCHECK(std::none_of(indices_.begin(), indices_.end(),
[&name](const Index& index) {
return index.max_version == kInvalidVersion &&
base::Contains(index.columns, name);
}));
if (sealed_version_ != kInvalidVersion &&
column->min_version <= sealed_version_) {
// This column exists in the last sealed version. Therefore it cannot be
// just deleted, it needs to be kept for generating the migration code.
column->max_version = sealed_version_;
} else {
// This column was just introduced in the currently unsealed version. It
// can be just erased from |columns_|.
columns_.erase(
--(column.base())); // base() points one element after |column|.
}
}
void SQLTableBuilder::AddIndex(std::string name,
std::vector<std::string> columns) {
DCHECK(!columns.empty());
// Check if all entries of |columns| are unique.
DCHECK_EQ(std::set<std::string>(columns.begin(), columns.end()).size(),
columns.size());
// |name| must not have been added before.
DCHECK(FindLastIndexByName(name) == indices_.rend());
// Check that all referenced columns are present in the last version by making
// sure that the inner predicate applies to all columns names in |columns|.
DCHECK(std::all_of(
columns.begin(), columns.end(), [this](const std::string& column_name) {
// Check if there is any column with the required name which is also
// present in the latest version. Note that we don't require the last
// version to be sealed.
return std::any_of(columns_.begin(), columns_.end(),
[&column_name](const Column& column) {
return column.name == column_name &&
column.max_version == kInvalidVersion;
});
}));
indices_.push_back({std::move(name), std::move(columns), sealed_version_ + 1,
kInvalidVersion});
}
std::string SQLTableBuilder::ComputeConstraints(unsigned version) const {
std::string unique_key;
for (const Column& column : columns_) {
// Ignore dropped columns.
if (column.max_version < version)
continue;
// Ignore columns columns from future versions.
if (column.min_version > version)
continue;
if (column.part_of_unique_key)
Append(column.name, &unique_key);
}
std::string constraints;
if (!unique_key.empty())
Append("UNIQUE (" + unique_key + ")", &constraints);
return constraints;
}
unsigned SQLTableBuilder::SealVersion() {
return ++sealed_version_;
}
bool SQLTableBuilder::MigrateFrom(
unsigned old_version,
sql::Database* db,
const base::RepeatingCallback<bool(sql::Database*, unsigned)>&
<API key>) const {
for (; old_version < sealed_version_; ++old_version) {
if (!MigrateToNextFrom(old_version, db))
return false;
if (<API key> &&
!<API key>.Run(db, old_version + 1))
return false;
}
return true;
}
bool SQLTableBuilder::CreateTable(sql::Database* db) const {
DCHECK(<API key>(sealed_version_));
if (db->DoesTableExist(table_name_.c_str()))
return true;
std::string constraints = ComputeConstraints(sealed_version_);
DCHECK(!constraints.empty() || std::any_of(columns_.begin(), columns_.end(),
[](const Column& column) {
return column.is_primary_key;
}));
std::string names; // Names and types of the current columns.
for (const Column& column : columns_) {
if (<API key>(column)) {
std::string suffix;
if (column.is_primary_key)
suffix = " PRIMARY KEY AUTOINCREMENT";
Append(column.name + " " + column.type + suffix, &names);
}
}
std::vector<std::string>
create_index_sqls; // CREATE INDEX statements for the current indices.
for (const Index& index : indices_) {
if (<API key>(index)) {
create_index_sqls.push_back(base::StringPrintf(
"CREATE INDEX %s ON %s (%s)", index.name.c_str(), table_name_.c_str(),
base::JoinString(index.columns, ", ").c_str()));
}
}
std::string <API key> =
constraints.empty()
? base::StringPrintf("CREATE TABLE %s (%s)", table_name_.c_str(),
names.c_str())
: base::StringPrintf("CREATE TABLE %s (%s, %s)", table_name_.c_str(),
names.c_str(), constraints.c_str());
sql::Transaction transaction(db);
return transaction.Begin() && db->Execute(<API key>.c_str()) &&
std::all_of(create_index_sqls.begin(), create_index_sqls.end(),
[&db](const std::string& sql) {
return db->Execute(sql.c_str());
}) &&
transaction.Commit();
}
std::string SQLTableBuilder::ListAllColumnNames() const {
DCHECK(<API key>(sealed_version_));
std::string result;
for (const Column& column : columns_) {
if (<API key>(column))
Append(column.name, &result);
}
return result;
}
std::string SQLTableBuilder::<API key>() const {
DCHECK(<API key>(sealed_version_));
std::string result;
for (const Column& column : columns_) {
if (<API key>(column) &&
!(column.is_primary_key || column.part_of_unique_key))
Append(column.name + "=?", &result);
}
return result;
}
std::string SQLTableBuilder::<API key>() const {
DCHECK(<API key>(sealed_version_));
std::string result;
for (const Column& column : columns_) {
if (<API key>(column) && column.part_of_unique_key) {
if (!result.empty())
result += " AND ";
result += column.name + "=?";
}
}
return result;
}
std::vector<base::StringPiece> SQLTableBuilder::AllPrimaryKeyNames() const {
DCHECK(<API key>(sealed_version_));
std::vector<base::StringPiece> result;
result.reserve(columns_.size());
for (const Column& column : columns_) {
if (<API key>(column) && column.is_primary_key) {
result.emplace_back(column.name);
}
}
DCHECK(result.size() < 2);
return result;
}
size_t SQLTableBuilder::NumberOfColumns() const {
DCHECK(<API key>(sealed_version_));
return base::checked_cast<size_t>(std::count_if(
columns_.begin(), columns_.end(),
[this](const Column& column) { return <API key>(column); }));
}
bool SQLTableBuilder::MigrateToNextFrom(unsigned old_version,
sql::Database* db) const {
DCHECK_LT(old_version, sealed_version_);
DCHECK_GE(old_version, 0u);
DCHECK(<API key>(sealed_version_));
// Names of columns from old version, values of which are copied. This
// contains only the names without their types.
std::string <API key>;
// Names of columns in new version, except for added ones.
std::string <API key>;
// Names of columns in new version, except for added ones. This contains only
// the names without their types.
std::string <API key>;
std::vector<std::string>
<API key>; // Names of added columns.
// A temporary table will be needed if some columns are dropped or renamed,
// because that is not supported by a single SQLite command.
bool needs_temp_table = false;
bool has_primary_key = false;
for (auto column = columns_.begin(); column != columns_.end(); ++column) {
if (column->max_version == old_version) {
// This column was deleted after |old_version|. It can have two reasons:
needs_temp_table = true;
auto next_column = std::next(column);
if (next_column != columns_.end() && next_column->gets_previous_data) {
// (1) The column is being renamed.
DCHECK_EQ(column->type, next_column->type);
DCHECK_NE(column->name, next_column->name);
Append(column->name, &<API key>);
Append(next_column->name + " " + next_column->type,
&<API key>);
Append(next_column->name, &<API key>);
++column; // Avoid processing next_column in the next loop.
} else {
// (2) The column is being dropped.
}
} else if (column->min_version == old_version + 1) {
// This column was added after old_version.
if (column->is_primary_key || column->part_of_unique_key)
needs_temp_table = true;
std::string suffix;
if (column->is_primary_key) {
suffix = " PRIMARY KEY AUTOINCREMENT";
has_primary_key = true;
}
<API key>.push_back(column->name + " " + column->type +
suffix);
} else if (column->min_version <= old_version &&
(column->max_version == kInvalidVersion ||
column->max_version > old_version)) {
std::string suffix;
if (column->is_primary_key) {
suffix = " PRIMARY KEY AUTOINCREMENT";
has_primary_key = true;
}
// This column stays.
Append(column->name, &<API key>);
Append(column->name + " " + column->type + suffix,
&<API key>);
Append(column->name, &<API key>);
}
}
if (<API key>.empty()) {
// Table didn't exist in this version, and nothing to migrate.
return true;
}
if (needs_temp_table) {
// Following the instructions from
// https://www.sqlite.org/lang_altertable.html#otheralter, this code works
// around the fact that SQLite does not allow dropping or renaming
// columns. Instead, a new table is constructed, with the new column
// names, and data from all but dropped columns from the current table are
// copied into it. After that, the new table is renamed to the current
// one.
std::string constraints = ComputeConstraints(old_version + 1);
DCHECK(has_primary_key || !constraints.empty());
// Foreign key constraints are not enabled for the login database, so no
// PRAGMA foreign_keys=off needed.
const std::string temp_table_name = "temp_" + table_name_;
std::string <API key> = <API key>;
for (const std::string& new_column : <API key>) {
Append(new_column, &<API key>);
}
std::string <API key> =
constraints.empty()
? base::StringPrintf("CREATE TABLE %s (%s)",
temp_table_name.c_str(),
<API key>.c_str())
: base::StringPrintf(
"CREATE TABLE %s (%s, %s)", temp_table_name.c_str(),
<API key>.c_str(), constraints.c_str());
sql::Transaction transaction(db);
if (!(transaction.Begin() && db->Execute(<API key>.c_str()) &&
db->Execute(base::StringPrintf(
"INSERT OR REPLACE INTO %s (%s) SELECT %s FROM %s",
temp_table_name.c_str(),
<API key>.c_str(),
<API key>.c_str(),
table_name_.c_str())
.c_str()) &&
db->Execute(base::StringPrintf("DROP TABLE %s", table_name_.c_str())
.c_str()) &&
db->Execute(base::StringPrintf("ALTER TABLE %s RENAME TO %s",
temp_table_name.c_str(),
table_name_.c_str())
.c_str()) &&
transaction.Commit())) {
return false;
}
} else if (!<API key>.empty()) {
// If no new table has been created, we need to add the new columns here if
// any.
sql::Transaction transaction(db);
if (!(transaction.Begin() &&
std::all_of(<API key>.begin(),
<API key>.end(),
[this, &db](const std::string& name) {
return db->Execute(
base::StringPrintf("ALTER TABLE %s ADD COLUMN %s",
table_name_.c_str(),
name.c_str())
.c_str());
}) &&
transaction.Commit())) {
return false;
}
}
return <API key>(old_version, db);
}
bool SQLTableBuilder::<API key>(unsigned old_version,
sql::Database* db) const {
DCHECK_LT(old_version, sealed_version_);
DCHECK(<API key>(sealed_version_));
sql::Transaction transaction(db);
if (!transaction.Begin())
return false;
for (const auto& index : indices_) {
std::string sql;
if (index.max_version <= old_version) {
// Index is not supposed to exist in the new version.
sql = base::StringPrintf("DROP INDEX IF EXISTS %s", index.name.c_str());
} else if (index.min_version <= old_version + 1) {
// Index is supposed to exist in the new version.
sql = base::StringPrintf("CREATE INDEX IF NOT EXISTS %s ON %s (%s)",
index.name.c_str(), table_name_.c_str(),
base::JoinString(index.columns, ", ").c_str());
} else {
continue;
}
if (!db->Execute(sql.c_str()))
return false;
}
return transaction.Commit();
}
std::vector<SQLTableBuilder::Column>::reverse_iterator
SQLTableBuilder::<API key>(const std::string& name) {
return std::find_if(
columns_.rbegin(), columns_.rend(),
[&name](const Column& column) { return name == column.name; });
}
std::vector<SQLTableBuilder::Index>::reverse_iterator
SQLTableBuilder::FindLastIndexByName(const std::string& name) {
return std::find_if(
indices_.rbegin(), indices_.rend(),
[&name](const Index& index) { return name == index.name; });
}
bool SQLTableBuilder::<API key>(unsigned version) const {
// Is |version| the last sealed one?
if (sealed_version_ != version)
return false;
// Is the current version the last sealed one? In other words, is there
// neither a column or index added past the sealed version (min_version >
// sealed) nor deleted one version after the sealed (max_version == sealed)?
return std::none_of(columns_.begin(), columns_.end(),
[this](const Column& column) {
return column.min_version > sealed_version_ ||
column.max_version == sealed_version_;
}) &&
std::none_of(indices_.begin(), indices_.end(),
[this](const Index& index) {
return index.min_version > sealed_version_ ||
index.max_version == sealed_version_;
});
}
bool SQLTableBuilder::<API key>(const Column& column) const {
DCHECK(<API key>(sealed_version_));
return (column.min_version <= sealed_version_ &&
(column.max_version == kInvalidVersion ||
column.max_version >= sealed_version_));
}
bool SQLTableBuilder::<API key>(const Index& index) const {
DCHECK(<API key>(sealed_version_));
return (index.min_version <= sealed_version_ &&
(index.max_version == kInvalidVersion ||
index.max_version >= sealed_version_));
}
} // namespace password_manager
|
from simulation.aivika.modeler.model import *
from simulation.aivika.modeler.port import *
from simulation.aivika.modeler.stream import *
from simulation.aivika.modeler.data_type import *
from simulation.aivika.modeler.pdf import *
def <API key>(transact_type, min_delay, max_delay):
"""Return a new stream of transacts with random delays distributed uniformly."""
<API key>(transact_type)
model = transact_type.get_model()
code = 'return $ mapStream (\\a -> ' + transact_type.coerce_arrival('a') + ') $ '
code += 'randomUniformStream ' + str(min_delay) + ' ' + str(max_delay)
y = StreamPort(model, transact_type.get_data_type())
y.bind_to_input()
y.write(code)
return y
def <API key>(transact_type, min_delay, max_delay):
"""Return a new stream of transacts with integer random delays distributed uniformly."""
<API key>(transact_type)
model = transact_type.get_model()
code = 'return $ mapStream (\\a -> ' + transact_type.coerce_arrival('a') + ') $ '
code += '<API key> ' + str(min_delay) + ' ' + str(max_delay)
y = StreamPort(model, transact_type.get_data_type())
y.bind_to_input()
y.write(code)
return y
def <API key>(transact_type, min_delay, median_delay, max_delay):
"""Return a new stream of transacts with random delays having the triangular distribution."""
<API key>(transact_type)
model = transact_type.get_model()
code = 'return $ mapStream (\\a -> ' + transact_type.coerce_arrival('a') + ') $ '
code += '<API key> ' + str(min_delay) + ' ' + str(median_delay) + ' ' + str(max_delay)
y = StreamPort(model, transact_type.get_data_type())
y.bind_to_input()
y.write(code)
return y
def <API key>(transact_type, mean_delay, delay_deviation):
"""Return a new stream of transacts with random delays having the normal distribution."""
<API key>(transact_type)
model = transact_type.get_model()
code = 'return $ mapStream (\\a -> ' + transact_type.coerce_arrival('a') + ') $ '
code += 'randomNormalStream ' + str(mean_delay) + ' ' + str(delay_deviation)
y = StreamPort(model, transact_type.get_data_type())
y.bind_to_input()
y.write(code)
return y
def <API key>(transact_type, normal_mean_delay, <API key>):
"""Return a new stream of transacts with random delays having the lognormal distribution.
The numerical parameters are related to the normal distribution that
this distribution is derived from.
"""
<API key>(transact_type)
model = transact_type.get_model()
code = 'return $ mapStream (\\a -> ' + transact_type.coerce_arrival('a') + ') $ '
code += '<API key> ' + str(normal_mean_delay) + ' ' + str(<API key>)
y = StreamPort(model, transact_type.get_data_type())
y.bind_to_input()
y.write(code)
return y
def <API key>(transact_type, mean_delay):
"""Return a new stream of transacts with random delays having the exponential distribution with the specified mean (a reciprocal of the rate)."""
<API key>(transact_type)
model = transact_type.get_model()
code = 'return $ mapStream (\\a -> ' + transact_type.coerce_arrival('a') + ') $ '
code += '<API key> ' + str(mean_delay)
y = StreamPort(model, transact_type.get_data_type())
y.bind_to_input()
y.write(code)
return y
def <API key>(transact_type, scale, shape):
"""Return a new stream of transacts with random delays having the Erlang distribution with the specified scale (a reciprocal of the rate) and shape parameters."""
<API key>(transact_type)
model = transact_type.get_model()
code = 'return $ mapStream (\\a -> ' + transact_type.coerce_arrival('a') + ') $ '
code += 'randomErlangStream ' + str(scale) + ' ' + str(shape)
y = StreamPort(model, transact_type.get_data_type())
y.bind_to_input()
y.write(code)
return y
def <API key>(transact_type, mean_delay):
"""Return a new stream of transacts with random delays having the Poisson distribution with the specified mean."""
<API key>(transact_type)
model = transact_type.get_model()
code = 'return $ mapStream (\\a -> ' + transact_type.coerce_arrival('a') + ') $ '
code += 'randomPoissonStream ' + str(mean_delay)
y = StreamPort(model, transact_type.get_data_type())
y.bind_to_input()
y.write(code)
return y
def <API key>(transact_type, probability, trials):
"""Return a new stream of transacts with random delays having the binomial distribution with the specified probability and trials."""
<API key>(transact_type)
model = transact_type.get_model()
code = 'return $ mapStream (\\a -> ' + transact_type.coerce_arrival('a') + ') $ '
code += '<API key> ' + str(probability) + ' ' + str(trials)
y = StreamPort(model, transact_type.get_data_type())
y.bind_to_input()
y.write(code)
return y
def gamma_random_stream(transact_type, shape, scale):
"""Return a new stream of transacts with random delays having the Gamma distribution by the specified shape and scale."""
<API key>(transact_type)
model = transact_type.get_model()
code = 'return $ mapStream (\\a -> ' + transact_type.coerce_arrival('a') + ') $ '
code += 'randomGammaStream ' + str(shape) + ' ' + str(scale)
y = StreamPort(model, transact_type.get_data_type())
y.bind_to_input()
y.write(code)
return y
def beta_random_stream(transact_type, alpha, beta):
"""Return a new stream of transacts with random delays having the Beta distribution by the specified shape parameters (alpha and beta)."""
<API key>(transact_type)
model = transact_type.get_model()
code = 'return $ mapStream (\\a -> ' + transact_type.coerce_arrival('a') + ') $ '
code += 'randomBetaStream ' + str(alpha) + ' ' + str(beta)
y = StreamPort(model, transact_type.get_data_type())
y.bind_to_input()
y.write(code)
return y
def <API key>(transact_type, shape, scale):
"""Return a new stream of transacts with random delays having the Weibull distribution by the specified shape and scale."""
<API key>(transact_type)
model = transact_type.get_model()
code = 'return $ mapStream (\\a -> ' + transact_type.coerce_arrival('a') + ') $ '
code += 'randomWeibullStream ' + str(shape) + ' ' + str(scale)
y = StreamPort(model, transact_type.get_data_type())
y.bind_to_input()
y.write(code)
return y
def <API key>(transact_type, pdf):
"""Return a new stream of transacts with random delays having the discrete distribution by the specified probability density function."""
<API key>(transact_type)
model = transact_type.get_model()
code = 'return $ mapStream (\\a -> ' + transact_type.coerce_arrival('a') + ') $ '
code += '<API key> ' + encode_pdf(pdf)
y = StreamPort(model, transact_type.get_data_type())
y.bind_to_input()
y.write(code)
return y
|
# apis_v1/<API key>/<API key>.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def <API key>(url_root):
"""
Show documentation about voterStarOnSave
"""
<API key> = [
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string
'description': 'The unique key provided to any organization using the WeVoteServer APIs',
},
{
'name': 'voter_device_id',
'value': 'string', # boolean, integer, long, string
'description': 'An 88 character unique identifier linked to a voter record on the server',
},
{
'name': 'kind_of_ballot_item',
'value': 'string', # boolean, integer, long, string
'description': 'What is the type of ballot item for which we are saving the \'on\' status? '
'(kind_of_ballot_item is either "OFFICE", "CANDIDATE", "POLITICIAN" or "MEASURE")',
},
{
'name': 'ballot_item_id',
'value': 'integer', # boolean, integer, long, string
'description': 'The unique internal identifier for this ballot_item '
'(either ballot_item_id OR <API key> required -- not both. '
'If it exists, ballot_item_id is used instead of <API key>)',
},
{
'name': '<API key>',
'value': 'string', # boolean, integer, long, string
'description': 'The unique identifier for this ballot_item across all networks '
'(either ballot_item_id OR <API key> required -- not both. '
'NOTE: In the future we might support other identifiers used in the industry.',
},
]
<API key> = [
]
<API key> = [
{
'code': '<API key>',
'description': 'Cannot proceed. A valid voter_device_id parameter was not included.',
},
{
'code': '<API key>',
'description': 'Cannot proceed. Missing voter_id while trying to save.',
},
{
'code': 'STAR_ON_OFFICE CREATE/UPDATE ITEM_STARRED',
'description': '',
},
{
'code': 'STAR_ON_CANDIDATE CREATE/UPDATE ITEM_STARRED',
'description': '',
},
{
'code': 'STAR_ON_MEASURE CREATE/UPDATE ITEM_STARRED',
'description': '',
},
]
<API key> = {
'kind_of_ballot_item': 'CANDIDATE',
'ballot_item_id': '5655',
}
api_response = '{\n' \
' "status": string (description of what happened),\n' \
' "success": boolean (did the save happen?),\n' \
' "ballot_item_id": integer,\n' \
' "<API key>": string,\n' \
' "kind_of_ballot_item": string (CANDIDATE, MEASURE),\n' \
'}'
template_values = {
'api_name': 'voterStarOnSave',
'api_slug': 'voterStarOnSave',
'api_introduction':
"Save or create private 'star on' state for the current voter for a measure, an office or candidate.",
'try_now_link': 'apis_v1:voterStarOnSaveView',
'<API key>': <API key>,
'url_root': url_root,
'get_or_post': 'GET',
'<API key>': <API key>,
'<API key>': <API key>,
'api_response': api_response,
'api_response_notes':
"",
'<API key>': <API key>,
}
return template_values
|
define(['../Property', '../Model', 'dojo/_base/declare', 'json-schema/lib/validate'],
function (Property, Model, declare, jsonSchemaValidator) {
// module:
// dstore/extensions/JsonSchema
// summary:
// This module generates a dstore schema from a JSON Schema to enabled validation of objects
// and property changes with JSON Schema
return function (jsonSchema) {
// create the schema that can be used by dstore/Model
var modelSchema = {};
var properties = jsonSchema.properties || jsonSchema;
// the validation function, this can be used for all the properties
function checkForErrors() {
var value = this.valueOf();
var key = this.name;
// get the current value and test it against the property's definition
var validation = jsonSchemaValidator.validate(value, properties[key]);
// set any errors
var errors = validation.errors;
if (errors) {
// assign the property names to the errors
for (var i = 0; i < errors.length; i++) {
errors[i].property = key;
}
}
return errors;
}
// iterate through the schema properties, creating property validators
for (var i in properties) {
var jsDefinition = properties[i];
var definition = modelSchema[i] = new Property({
checkForErrors: checkForErrors
});
if (typeof jsDefinition.type === 'string') {
// copy the type so it can be used for coercion
definition.type = jsDefinition.type;
}
if (typeof jsDefinition['default'] === 'string') {
// and copy the default
definition['default'] = jsDefinition['default'];
}
}
return declare(Model, {
schema: modelSchema
});
};
});
|
using System;
using System.Collections.Generic;
using System.Linq;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
namespace <API key>.iOS
{
public class Application
{
// This is the main entry point of the application.
static void Main(string[] args)
{
// if you want to use a different Application Delegate class from "AppDelegate"
// you can specify it here.
UIApplication.Main(args, null, "AppDelegate");
}
}
}
|
<?php
namespace Competitions;
use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;
class Module
{
public function onBootstrap(MvcEvent $e)
{
$e->getApplication()->getServiceManager()->get('translator');
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
}
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}
}
|
#include "stdafx.h"
#include "CGGuildApply.h"
BOOL CGGuildApply::Read( SocketInputStream& iStream )
{
__ENTER_FUNCTION
iStream.Read( (CHAR*)(&m_GuildNameSize), sizeof(BYTE) );
if(m_GuildNameSize<MAX_GUILD_NAME_SIZE)
{
iStream.Read( (CHAR*)(m_GuildName), m_GuildNameSize );
}
iStream.Read( (CHAR*)(&m_GuildDescSize), sizeof(BYTE) );
if(m_GuildDescSize<MAX_GUILD_DESC_SIZE)
{
iStream.Read( (CHAR*)(m_GuildDesc), m_GuildDescSize);
}
return TRUE;
__LEAVE_FUNCTION
return FALSE;
}
BOOL CGGuildApply::Write( SocketOutputStream& oStream ) const
{
__ENTER_FUNCTION
oStream.Write( (CHAR*)(&m_GuildNameSize), sizeof(BYTE) );
if(m_GuildNameSize<MAX_GUILD_NAME_SIZE)
{
oStream.Write( (CHAR*)(m_GuildName), m_GuildNameSize );
}
oStream.Write( (CHAR*)(&m_GuildDescSize), sizeof(BYTE) );
if(m_GuildDescSize<MAX_GUILD_DESC_SIZE)
{
oStream.Write( (CHAR*)(m_GuildDesc), m_GuildDescSize);
}
return TRUE;
__LEAVE_FUNCTION
return FALSE;
}
UINT CGGuildApply::Execute( Player* pPlayer )
{
__ENTER_FUNCTION
return CGGuildApplyHandler::Execute( this, pPlayer );
__LEAVE_FUNCTION
return FALSE;
}
|
<?php namespace Laravella\Ravel\Facades;
Class Facade
{
protected static $resolvedInstance;
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
throw new \RuntimeException("Facade does not implement getFacadeAccessor method.");
}
/**
* Resolve the facade root instance from the container.
*
* @param string $name
* @return mixed
*/
protected static function <API key>($name)
{
if (is_object($name)) return $name;
if (isset(static::$resolvedInstance[$name]))
{
return static::$resolvedInstance[$name];
}
$NP = ucfirst($name);
$classInstance = "Laravella\\Ravel\\$NP\\$NP";
return static::$resolvedInstance[$name] = new $classInstance;
}
public static function resolveMethod($method, $args)
{
$instance = static::<API key>(static::getFacadeAccessor());
return <API key>(array($instance, $method), $args);
}
public static function __callStatic($method, $args)
{
return static::resolveMethod($method, $args);
}
public function __call($method, $args)
{
return static::resolveMethod($method, $args);
}
}
|
import numpy as np
from nose.tools import (assert_true, assert_false, assert_equal,
assert_almost_equal)
from numpy.testing import (assert_array_equal, <API key>,
assert_)
from dipy.sims.voxel import (_check_directions, SingleTensor, MultiTensor,
multi_tensor_odf, all_tensor_evecs, add_noise,
single_tensor, sticks_and_ball, multi_tensor_dki,
kurtosis_element, DKI_signal)
from dipy.core.geometry import (vec2vec_rotmat, sphere2cart)
from dipy.data import get_data, get_sphere
from dipy.core.gradients import gradient_table
from dipy.io.gradients import read_bvals_bvecs
fimg, fbvals, fbvecs = get_data('small_64D')
bvals, bvecs = read_bvals_bvecs(fbvals, fbvecs)
gtab = gradient_table(bvals, bvecs)
# 2 shells for techniques that requires multishell data
bvals_2s = np.concatenate((bvals, bvals * 2), axis=0)
bvecs_2s = np.concatenate((bvecs, bvecs), axis=0)
gtab_2s = gradient_table(bvals_2s, bvecs_2s)
def diff2eigenvectors(dx, dy, dz):
""" numerical derivatives 2 eigenvectors
"""
u = np.array([dx, dy, dz])
u = u / np.linalg.norm(u)
R = vec2vec_rotmat(basis[:, 0], u)
eig0 = u
eig1 = np.dot(R, basis[:, 1])
eig2 = np.dot(R, basis[:, 2])
eigs = np.zeros((3, 3))
eigs[:, 0] = eig0
eigs[:, 1] = eig1
eigs[:, 2] = eig2
return eigs, R
def <API key>():
# Testing spherical angles for two principal coordinate axis
angles = [(0, 0)] # axis z
sticks = _check_directions(angles)
<API key>(sticks, [[0, 0, 1]])
angles = [(0, 90)] # axis z again (phi can be anything it theta is zero)
sticks = _check_directions(angles)
<API key>(sticks, [[0, 0, 1]])
angles = [(90, 0)] # axis x
sticks = _check_directions(angles)
<API key>(sticks, [[1, 0, 0]])
# Testing if directions are already given in cartesian coordinates
angles = [(0, 0, 1)]
sticks = _check_directions(angles)
<API key>(sticks, [[0, 0, 1]])
# Testing more than one direction simultaneously
angles = np.array([[90, 0], [30, 0]])
sticks = _check_directions(angles)
ref_vec = [np.sin(np.pi*30/180), 0, np.cos(np.pi*30/180)]
<API key>(sticks, [[1, 0, 0], ref_vec])
# Testing directions not aligned to planes x = 0, y = 0, or z = 0
the1 = 0
phi1 = 90
the2 = 30
phi2 = 45
angles = np.array([(the1, phi1), (the2, phi2)])
sticks = _check_directions(angles)
ref_vec1 = (np.sin(np.pi*the1/180) * np.cos(np.pi*phi1/180),
np.sin(np.pi*the1/180) * np.sin(np.pi*phi1/180),
np.cos(np.pi*the1/180))
ref_vec2 = (np.sin(np.pi*the2/180) * np.cos(np.pi*phi2/180),
np.sin(np.pi*the2/180) * np.sin(np.pi*phi2/180),
np.cos(np.pi*the2/180))
<API key>(sticks, [ref_vec1, ref_vec2])
def <API key>():
d = 0.0015
S, sticks = sticks_and_ball(gtab, d=d, S0=1, angles=[(0, 0), ],
fractions=[100], snr=None)
assert_array_equal(sticks, [[0, 0, 1]])
S_st = SingleTensor(gtab, 1, evals=[d, 0, 0], evecs=[[0, 0, 0],
[0, 0, 0],
[1, 0, 0]])
<API key>(S, S_st)
def test_single_tensor():
evals = np.array([1.4, .35, .35]) * 10 ** (-3)
evecs = np.eye(3)
S = SingleTensor(gtab, 100, evals, evecs, snr=None)
<API key>(S[gtab.b0s_mask], 100)
assert_(np.mean(S[~gtab.b0s_mask]) < 100)
from dipy.reconst.dti import TensorModel
m = TensorModel(gtab)
t = m.fit(S)
<API key>(t.fa, 0.707, decimal=3)
def test_multi_tensor():
sphere = get_sphere('symmetric724')
vertices = sphere.vertices
mevals = np.array(([0.0015, 0.0003, 0.0003],
[0.0015, 0.0003, 0.0003]))
e0 = np.array([np.sqrt(2) / 2., np.sqrt(2) / 2., 0])
e1 = np.array([0, np.sqrt(2) / 2., np.sqrt(2) / 2.])
mevecs = [all_tensor_evecs(e0), all_tensor_evecs(e1)]
# odf = multi_tensor_odf(vertices, [0.5, 0.5], mevals, mevecs)
# assert_(odf.shape == (len(vertices),))
# assert_(np.all(odf <= 1) & np.all(odf >= 0))
fimg, fbvals, fbvecs = get_data('small_101D')
bvals, bvecs = read_bvals_bvecs(fbvals, fbvecs)
gtab = gradient_table(bvals, bvecs)
s1 = single_tensor(gtab, 100, mevals[0], mevecs[0], snr=None)
s2 = single_tensor(gtab, 100, mevals[1], mevecs[1], snr=None)
Ssingle = 0.5*s1 + 0.5*s2
S, sticks = MultiTensor(gtab, mevals, S0=100, angles=[(90, 45), (45, 90)],
fractions=[50, 50], snr=None)
<API key>(S, Ssingle)
def test_snr():
np.random.seed(1978)
s = single_tensor(gtab)
# For reasonably large SNR, var(signal) ~= sigma**2, where sigma = 1/SNR
for snr in [5, 10, 20]:
sigma = 1.0 / snr
for j in range(1000):
s_noise = add_noise(s, snr, 1, noise_type='rician')
<API key>(np.var(s_noise - s), sigma ** 2, decimal=2)
def <API key>():
e0 = np.array([1/np.sqrt(2), 1/np.sqrt(2), 0])
desired = np.array([[1/np.sqrt(2), 1/np.sqrt(2), 0],
[-1/np.sqrt(2), 1/np.sqrt(2), 0],
[0, 0, 1]]).T
<API key>(all_tensor_evecs(e0), desired)
def <API key>():
""" Testing symmetry of the elements of the KT
As an 4th order tensor, KT has 81 elements. However, due to diffusion
symmetry the KT is fully characterized by 15 independent elements. This
test checks for this property.
"""
# two fiber not aligned to planes x = 0, y = 0, or z = 0
mevals = np.array([[0.00099, 0, 0], [0.00226, 0.00087, 0.00087],
[0.00099, 0, 0], [0.00226, 0.00087, 0.00087]])
angles = [(80, 10), (80, 10), (20, 30), (20, 30)]
fie = 0.49 # intra axonal water fraction
frac = [fie * 50, (1-fie) * 50, fie * 50, (1-fie) * 50]
sticks = _check_directions(angles)
mD = np.zeros((len(frac), 3, 3))
for i in range(len(frac)):
R = all_tensor_evecs(sticks[i])
mD[i] = np.dot(np.dot(R, np.diag(mevals[i])), R.T)
# compute global DT
D = np.zeros((3, 3))
for i in range(len(frac)):
D = D + frac[i]*mD[i]
# compute voxel's MD
MD = (D[0][0] + D[1][1] + D[2][2]) / 3
# Reference dictionary with the 15 independent elements.
# Note: The multiplication of the indexes (i+1) * (j+1) * (k+1) * (l+1)
# for of an elements is only equal to this multiplication for another
# element if an only if the element corresponds to an symmetry element.
# Thus indexes multiplication is used as key of the reference dictionary
kt_ref = {1: kurtosis_element(mD, frac, 0, 0, 0, 0),
16: kurtosis_element(mD, frac, 1, 1, 1, 1),
81: kurtosis_element(mD, frac, 2, 2, 2, 2),
2: kurtosis_element(mD, frac, 0, 0, 0, 1),
3: kurtosis_element(mD, frac, 0, 0, 0, 2),
8: kurtosis_element(mD, frac, 0, 1, 1, 1),
24: kurtosis_element(mD, frac, 1, 1, 1, 2),
27: kurtosis_element(mD, frac, 0, 2, 2, 2),
54: kurtosis_element(mD, frac, 1, 2, 2, 2),
4: kurtosis_element(mD, frac, 0, 0, 1, 1),
9: kurtosis_element(mD, frac, 0, 0, 2, 2),
36: kurtosis_element(mD, frac, 1, 1, 2, 2),
6: kurtosis_element(mD, frac, 0, 0, 1, 2),
12: kurtosis_element(mD, frac, 0, 1, 1, 2),
18: kurtosis_element(mD, frac, 0, 1, 2, 2)}
# Testing all 81 possible elements
xyz = [0, 1, 2]
for i in xyz:
for j in xyz:
for k in xyz:
for l in xyz:
key = (i+1) * (j+1) * (k+1) * (l+1)
assert_almost_equal(kurtosis_element(mD, frac, i, k, j, l),
kt_ref[key])
# Testing optional funtion inputs
assert_almost_equal(kurtosis_element(mD, frac, i, k, j, l),
kurtosis_element(mD, frac, i, k, j, l,
D, MD))
def <API key>():
"""
Testing DKI simulations when aligning the same fiber to different axis.
If biological parameters don't change, kt[0] of a fiber aligned to axis x
has to be equal to kt[1] of a fiber aligned to the axis y and equal to
kt[2] of a fiber aligned to axis z. The same is applicable for dt
"""
# Defining parameters based on Neto Henriques et al., 2015. NeuroImage 111
mevals = np.array([[0.00099, 0, 0], # Intra-cellular
[0.00226, 0.00087, 0.00087]]) # Extra-cellular
frac = [49, 51] # Compartment volume fraction
# axis x
angles = [(90, 0), (90, 0)]
signal_fx, dt_fx, kt_fx = multi_tensor_dki(gtab_2s, mevals, angles=angles,
fractions=frac)
# axis y
angles = [(90, 90), (90, 90)]
signal_fy, dt_fy, kt_fy = multi_tensor_dki(gtab_2s, mevals, angles=angles,
fractions=frac)
# axis z
angles = [(0, 0), (0, 0)]
signal_fz, dt_fz, kt_fz = multi_tensor_dki(gtab_2s, mevals, angles=angles,
fractions=frac)
assert_array_equal([kt_fx[0], kt_fx[1], kt_fx[2]],
[kt_fy[1], kt_fy[0], kt_fy[2]])
assert_array_equal([kt_fx[0], kt_fx[1], kt_fx[2]],
[kt_fz[2], kt_fz[0], kt_fz[1]])
assert_array_equal([dt_fx[0], dt_fx[2], dt_fx[5]],
[dt_fy[2], dt_fy[0], dt_fy[5]])
assert_array_equal([dt_fx[0], dt_fx[2], dt_fx[5]],
[dt_fz[5], dt_fz[0], dt_fz[2]])
# testing S signal along axis x, y and z
bvals = np.array([0, 0, 0, 1000, 1000, 1000, 2000, 2000, 2000])
bvecs = np.asarray([[1, 0, 0], [0, 1, 0], [0, 0, 1],
[1, 0, 0], [0, 1, 0], [0, 0, 1],
[1, 0, 0], [0, 1, 0], [0, 0, 1]])
gtab_axis = gradient_table(bvals, bvecs)
# axis x
S_fx = DKI_signal(gtab_axis, dt_fx, kt_fx, S0=100)
<API key>(S_fx[0:3], [100, 100, 100]) # test S f0r b=0
# axis y
S_fy = DKI_signal(gtab_axis, dt_fy, kt_fy, S0=100)
<API key>(S_fy[0:3], [100, 100, 100]) # test S f0r b=0
# axis z
S_fz = DKI_signal(gtab_axis, dt_fz, kt_fz, S0=100)
<API key>(S_fz[0:3], [100, 100, 100]) # test S f0r b=0
# test S for b = 1000
<API key>([S_fx[3], S_fx[4], S_fx[5]],
[S_fy[4], S_fy[3], S_fy[5]])
<API key>([S_fx[3], S_fx[4], S_fx[5]],
[S_fz[5], S_fz[3], S_fz[4]])
# test S for b = 2000
<API key>([S_fx[6], S_fx[7], S_fx[8]],
[S_fy[7], S_fy[6], S_fy[8]])
<API key>([S_fx[6], S_fx[7], S_fx[8]],
[S_fz[8], S_fz[6], S_fz[7]])
def <API key>():
""" Testing DKI simulations of a crossing fiber
"""
# two fiber not aligned to planes x = 0, y = 0, or z = 0
mevals = np.array([[0.00099, 0, 0], [0.00226, 0.00087, 0.00087],
[0.00099, 0, 0], [0.00226, 0.00087, 0.00087]])
angles = [(80, 10), (80, 10), (20, 30), (20, 30)]
fie = 0.49
frac = [fie*50, (1 - fie)*50, fie*50, (1 - fie)*50]
signal, dt, kt = multi_tensor_dki(gtab_2s, mevals, angles=angles,
fractions=frac, snr=None)
# in this simulations dt and kt cannot have zero elements
for i in range(len(dt)):
assert dt[i] != 0
for i in range(len(kt)):
assert kt[i] != 0
# test S, dt and kt relative to the expected values computed from another
# DKI package - UDKI (Neto Henriques et al., 2015)
dt_ref = [1.0576161e-3, 0.1292542e-3, 0.4786179e-3,
0.2667081e-3, 0.1136643e-3, 0.9888660e-3]
kt_ref = [2.3529944, 0.8226448, 2.3011221, 0.2017312, -0.0437535,
0.0404011, 0.0355281, 0.2449859, 0.2157668, 0.3495910,
0.0413366, 0.3461519, -0.0537046, 0.0133414, -0.017441]
<API key>(dt, dt_ref)
<API key>(kt, kt_ref)
<API key>(signal,
DKI_signal(gtab_2s, dt_ref, kt_ref, S0=100,
snr=None),
decimal=5)
if __name__ == "__main__":
test_multi_tensor()
|
import Ember from 'ember';
import ajax from 'ic-ajax';
import config from '../config/environment';
import SlydApi from '../utils/slyd-api';
import Timer from '../utils/timer';
import ApplicationUtils from '../mixins/application-utils';
var UUID = Ember.Object.extend(ApplicationUtils, {});
export function initialize(container, application) {
application.deferReadiness();
var hash = {};
hash.type = 'GET';
hash.url = (config.SLYD_URL || window.location.protocol + '
window.location.host) + '/server_capabilities';
ajax(hash).then(function(settings) {
this.set('serverCapabilities', settings['capabilities']);
this.set('serverCustomization', settings['custom']);
container.register('api:capabilities',
Ember.Object.create().setProperties(application.get('serverCapabilities')),
{ instantiate: false });
container.register('app:custom',
Ember.Object.create().setProperties(application.get('serverCustomization')),
{ instantiate: false });
var api = new SlydApi();
api.set('username', settings.username);
api.set('sessionid', new UUID().shortGuid());
api.set('serverCapabilities', container.lookup('api:capabilities'));
api.set('timer', new Timer());
container.register('api:slyd', api, { instantiate: false });
application.inject('route', 'slyd', 'api:slyd');
application.inject('adapter', 'slyd', 'api:slyd');
application.inject('controller', 'slyd', 'api:slyd');
application.inject('component', 'slyd', 'api:slyd');
application.inject('controller', 'customizations', 'app:custom');
application.inject('component', 'customizations', 'app:custom');
application.inject('controller', 'capabilities', 'api:capabilities');
application.inject('route', 'capabilities', 'api:capabilities');
this.advanceReadiness();
}.bind(application));
}
export default {
name: 'register-api',
initialize: initialize
};
|
''''
Tune the 3 most promissing algorithms and compare them
'''
# Load libraries
import os
import time
import pandas
import numpy
import matplotlib.pyplot as plt
from pandas.tools.plotting import scatter_matrix
from pandas import DataFrame
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import MinMaxScaler
from sklearn import cross_validation
from sklearn.metrics import <API key>
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
from sklearn.pipeline import Pipeline
from sklearn.grid_search import GridSearchCV
from sklearn.linear_model import LogisticRegression
from sklearn.tree import <API key>
from sklearn.neighbors import <API key>
from sklearn.<API key> import <API key>
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC
from sklearn.ensemble import AdaBoostClassifier
from sklearn.ensemble import <API key>
from sklearn.ensemble import <API key>
from sklearn.ensemble import <API key>
from sklearn.datasets import load_digits
from sklearn.model_selection import GridSearchCV
from sklearn.decomposition import PCA, NMF
from sklearn.feature_selection import SelectKBest, chi2
import lib.eda1 as eda1
import lib.eda3 as eda3
#constants
N_DIGITS = 3
NUM_FOLDS = 10
RAND_SEED = 7
SCORING = 'accuracy'
VALIDATION_SIZE = 0.20
N_JOBS = 6
#global variables
start = time.clock()
imageidx = 1
createImages = True
results = []
names = []
params = []
bestResults = []
# <API key>
def tuneRF(X_train, Y_train, outputPath):
global results, names, params, bestResults
print 'tune LR (Random Forest Classifier)'
pipeline = Pipeline([('PCA', PCA()),('MinMaxScaler', MinMaxScaler(feature_range=(0, 1))),('Scaler', StandardScaler())])
scaler = pipeline.fit(X_train)
rescaledX = scaler.transform(X_train)
#tune para meters
#n_estimators_values = [5, 10, 100, 1000, 3000]
n_estimators_values = [1000]
max_features_values = [0.1, 'auto', 'sqrt', 'log2', None] # (float)0.1=>10%
criterion_values = ['gini', 'entropy']
param_grid = dict(n_estimators=n_estimators_values, max_features=max_features_values, criterion=criterion_values)
model = <API key>()
kfold = cross_validation.KFold(n=len(X_train), n_folds=NUM_FOLDS, random_state=RAND_SEED)
grid = GridSearchCV(n_jobs=N_JOBS, verbose=10, estimator=model, param_grid=param_grid, scoring=SCORING, cv=kfold)
grid_result = grid.fit(rescaledX, Y_train)
print("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_))
best_idx = grid_result.best_index_
#TODO: check it out if 'mean_test_score' is really what I want here
cv_results = grid_result.cv_results_['mean_test_score']
results.append(cv_results)
grid_scores = sorted(grid_result.grid_scores_, key=lambda x: x[2].mean(), reverse=True)
first = True
for param, mean_score, scores in grid_scores:
if first:
bestResults.append({'name':'RF', 'mean':scores.mean(), 'std':scores.std(), 'params':param})
first = False
print("%f (%f) with: %r" % (scores.mean(), scores.std(), param))
# <API key>
def tuneET(X_train, Y_train, outputPath):
global results, names, params, bestResults
print 'tune ET (Extra Trees Classifier)'
pipeline = Pipeline([('PCA', PCA()),('MinMaxScaler', MinMaxScaler(feature_range=(0, 1))),('Scaler', StandardScaler())])
scaler = pipeline.fit(X_train)
rescaledX = scaler.transform(X_train)
#tune para meters
#n_estimators_values = [5, 10, 100, 1000, 3000]
n_estimators_values = [1000]
max_features_values = [0.1, 'auto', 'sqrt', 'log2', None] # (float)0.1=>10%
criterion_values = ['gini', 'entropy']
param_grid = dict(n_estimators=n_estimators_values, max_features=max_features_values, criterion=criterion_values)
model = <API key>()
kfold = cross_validation.KFold(n=len(X_train), n_folds=NUM_FOLDS, random_state=RAND_SEED)
grid = GridSearchCV(n_jobs=N_JOBS, verbose=10, estimator=model, param_grid=param_grid, scoring=SCORING, cv=kfold)
grid_result = grid.fit(rescaledX, Y_train)
print("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_))
best_idx = grid_result.best_index_
#TODO: check it out if 'mean_test_score' is really what a want here
cv_results = grid_result.cv_results_['mean_test_score']
results.append(cv_results)
grid_scores = sorted(grid_result.grid_scores_, key=lambda x: x[2].mean(), reverse=True)
first = True
for param, mean_score, scores in grid_scores:
if first:
bestResults.append({'name':'ET', 'mean':scores.mean(), 'std':scores.std(), 'params':param})
first = False
print("%f (%f) with: %r" % (scores.mean(), scores.std(), param))
# Tune scaled SVM
def tuneSVM(X_train, Y_train, outputPath):
global results, names, params, bestResults
print 'tune SVM (Support Vector Machines Classifier)'
pipeline = Pipeline([('PCA', PCA()),('MinMaxScaler', MinMaxScaler(feature_range=(0, 1))),('Scaler', StandardScaler())])
scaler = pipeline.fit(X_train)
rescaledX = scaler.transform(X_train)
#c_values = [0.1, 1.0, 100.0, 10000.0, 100000.0]
c_values = [10000.0, 100000.0]
kernel_values = ['linear', 'poly', 'rbf', 'sigmoid']
param_grid = dict(C=c_values, kernel=kernel_values)
model = SVC()
kfold = cross_validation.KFold(n=len(X_train), n_folds=NUM_FOLDS, random_state=RAND_SEED)
grid = GridSearchCV(n_jobs=N_JOBS, verbose=10, estimator=model, param_grid=param_grid, scoring=SCORING, cv=kfold)
grid_result = grid.fit(rescaledX, Y_train)
print("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_))
best_idx = grid_result.best_index_
#TODO: check it out if 'mean_test_score' is really what a want here
cv_results = grid_result.cv_results_['mean_test_score']
results.append(cv_results)
grid_scores = sorted(grid_result.grid_scores_, key=lambda x: x[2].mean(), reverse=True)
first = True
for param, mean_score, scores in grid_scores:
if first:
bestResults.append({'name':'SVM', 'mean':scores.mean(), 'std':scores.std(), 'params':param})
first = False
print("%f (%f) with: %r" % (scores.mean(), scores.std(), param))
def <API key>(results, names, outputPath):
global imageidx
print '\n === Tuned Algorithms Comparison ===\n'
#print bestResults
for x in bestResults:
print x
# Compare Algorithms
if (createImages):
fig = plt.figure()
fig.suptitle('Final Tuned-Algorithms Comparison')
ax = fig.add_subplot(111)
plt.boxplot(results)
ax.set_xticklabels(names)
#plt.show()
plt.savefig(outputPath + str(imageidx).zfill(N_DIGITS) + '-<API key>.png')
imageidx += 1
plt.close('all')
def set_createImages(value):
global createImages
createImages = value
def run(inputFilePath, outputPath, createImagesFlag, dropColumns):
global start
print '
print '
print '
print ''
set_createImages(createImagesFlag)
start = time.clock()
eda1.reset_imageidx()
eda1.set_createImages(createImagesFlag)
if not os.path.exists(outputPath):
os.makedirs(outputPath)
# Load dataset
dataframe = eda1.loadDataframe(inputFilePath)
# drop out 'not fair' features
dataframe = eda1.dataCleansing(dataframe, dropColumns)
#Split-out train/validation dataset
X_train, X_validation, Y_train, Y_validation = eda1.<API key>(dataframe)
'''
# tune each algorithm
try:
tuneRF(X_train, Y_train, outputPath)
except Exception as e:
print "ERROR: couldn't tune RF"
print "Message: %s" % str(e)
try:
tuneET(X_train, Y_train, outputPath)
except Exception as e:
print "ERROR: couldn't tune ET"
print "Message: %s" % str(e)
'''
try:
tuneSVM(X_train, Y_train, outputPath)
except Exception as e:
print "ERROR: couldn't tune SVM"
print "Message: %s" % str(e)
#print the results comparing the algorithms with the best tune for each one
<API key>(results, names, outputPath)
print '\n<<< THEN END - Running Exploratory Data Analysis
#RF - Best: 0.853451 using {'max_features': 'log2', 'n_estimators': 1000, 'criterion': 'gini'}
#ET - Best: 0.855320 using {'max_features': None, 'n_estimators': 1000, 'criterion': 'gini'}
|
/* $KAME: fsm.h,v 1.2 2005/05/25 01:49:24 keiichi Exp $ */
#ifndef _SHISAD_FSM_H_
#define _SHISAD_FSM_H_
/* states for the primary fsm. */
#define <API key> 0
#define <API key> 1
#define <API key> 2
#define <API key> 3
#define <API key> 4
#define <API key> 5
#define <API key> 6
#define <API key> 7
#define <API key> 8
/* states for the secondary fsm. */
#define <API key> 0
#define <API key> 1
#define <API key> 2
#define <API key> 3
#define <API key>(bul) \
(((bul)->bul_rr_fsm_state == <API key>) \
|| ((bul)->bul_rr_fsm_state == <API key>) \
|| ((bul)->bul_rr_fsm_state == <API key>))
/* events for the registration fsm. */
#define <API key> 0
#define <API key> 1
#define <API key> 2
#define <API key> 3
#define <API key> 4
#define <API key> 5
#define <API key> 6
#define <API key> 7
#define <API key> 8
#define <API key> 9
#define <API key> 10
#define <API key> 11
#define <API key> 12
#define <API key> 13
#define <API key>(ev) \
(((ev) >= 0) \
&& ((ev) <= <API key>))
/* events for the rr fsm. */
#define <API key> 20
#define <API key> 21
#define <API key> 22
#define <API key> 23
#define <API key> 24
#define <API key>(ev) \
(((ev) >= <API key>) \
&& (((ev) <= <API key>)))
/* timeout events */
#define <API key> 30
struct fsm_message {
struct in6_addr *fsmm_src;
struct in6_addr *fsmm_dst;
struct in6_addr *fsmm_hoa;
struct in6_addr *fsmm_rtaddr;
void *fsmm_data;
size_t fsmm_datalen;
};
int bul_kick_fsm_by_mh(struct in6_addr *, struct in6_addr *, struct in6_addr *,
struct in6_addr *, struct ip6_mh *, int);
int bul_kick_fsm(struct binding_update_list *, int, struct fsm_message *);
void bul_retrans_timer(void *);
void bul_expire_timer(void *);
#endif /* !_SHISAD_FSM_H_ */
|
import numpy as np
from scipy.linalg import norm
from .base import <API key>
class <API key>(<API key>):
@property
def algorithm(self):
return 'Simultaneous-FA'
def _fit(self, lk_fitting, max_iters=20, project=True):
# Initial error > eps
error = self.eps + 1
image = lk_fitting.image
lk_fitting.weights = []
n_iters = 0
# Number of shape weights
n_params = self.transform.n_parameters
# Initial appearance weights
if project:
# Obtained weights by projection
IWxp = image.warp_to(self.template.mask, self.transform,
interpolator=self.interpolator)
weights = self.appearance_model.project(IWxp)
# Reset template
self.template = self.appearance_model.instance(weights)
else:
# Set all weights to 0 (yielding the mean)
weights = np.zeros(self.appearance_model.n_active_components)
lk_fitting.weights.append(weights)
# Compute appearance model Jacobian wrt weights
appearance_jacobian = self.appearance_model._jacobian.T
# Forward Additive Algorithm
while n_iters < max_iters and error > self.eps:
# Compute warped image with current weights
IWxp = image.warp_to(self.template.mask, self.transform,
interpolator=self.interpolator)
# Compute warp Jacobian
dW_dp = self.transform.jacobian(
self.template.mask.true_indices)
# Compute steepest descent images, VI_dW_dp
J = self.residual.<API key>(
image, dW_dp, forward=(self.template, self.transform,
self.interpolator))
# Concatenate VI_dW_dp with appearance model Jacobian
self._J = np.hstack((J, appearance_jacobian))
# Compute Hessian and inverse
self._H = self.residual.calculate_hessian(self._J)
# Compute steepest descent parameter updates
sd_delta_p = self.residual.<API key>(
self._J, self.template, IWxp)
# Compute gradient descent parameter updates
delta_p = np.real(self._calculate_delta_p(sd_delta_p))
# Update warp weights
parameters = self.transform.as_vector() + delta_p[:n_params]
self.transform.from_vector_inplace(parameters)
lk_fitting.parameters.append(parameters)
# Update appearance weights
weights -= delta_p[n_params:]
self.template = self.appearance_model.instance(weights)
lk_fitting.weights.append(weights)
# Test convergence
error = np.abs(norm(delta_p))
n_iters += 1
lk_fitting.fitted = True
return lk_fitting
class <API key>(<API key>):
@property
def algorithm(self):
return 'Simultaneous-FC'
def _set_up(self):
# Compute warp Jacobian
self._dW_dp = self.transform.jacobian(
self.template.mask.true_indices)
def _fit(self, lk_fitting, max_iters=20, project=True):
# Initial error > eps
error = self.eps + 1
image = lk_fitting.image
lk_fitting.weights = []
n_iters = 0
# Number of shape weights
n_params = self.transform.n_parameters
# Initial appearance weights
if project:
# Obtained weights by projection
IWxp = image.warp_to(self.template.mask, self.transform,
interpolator=self.interpolator)
weights = self.appearance_model.project(IWxp)
# Reset template
self.template = self.appearance_model.instance(weights)
else:
# Set all weights to 0 (yielding the mean)
weights = np.zeros(self.appearance_model.n_active_components)
lk_fitting.weights.append(weights)
# Compute appearance model Jacobian wrt weights
appearance_jacobian = self.appearance_model._jacobian.T
# Forward Additive Algorithm
while n_iters < max_iters and error > self.eps:
# Compute warped image with current weights
IWxp = image.warp_to(self.template.mask, self.transform,
interpolator=self.interpolator)
# Compute steepest descent images, VI_dW_dp
J = self.residual.<API key>(IWxp, self._dW_dp)
# Concatenate VI_dW_dp with appearance model Jacobian
self._J = np.hstack((J, appearance_jacobian))
# Compute Hessian and inverse
self._H = self.residual.calculate_hessian(self._J)
# Compute steepest descent parameter updates
sd_delta_p = self.residual.<API key>(
self._J, self.template, IWxp)
# Compute gradient descent parameter updates
delta_p = np.real(self._calculate_delta_p(sd_delta_p))
# Update warp weights
self.transform.<API key>(delta_p[:n_params])
lk_fitting.parameters.append(self.transform.as_vector())
# Update appearance weights
weights -= delta_p[n_params:]
self.template = self.appearance_model.instance(weights)
lk_fitting.weights.append(weights)
# Test convergence
error = np.abs(norm(delta_p))
n_iters += 1
lk_fitting.fitted = True
return lk_fitting
class <API key>(<API key>):
@property
def algorithm(self):
return 'Simultaneous-IA'
def _set_up(self):
# Compute the Jacobian of the warp
self._dW_dp = self.transform.jacobian(
self.appearance_model.mean.mask.true_indices)
def _fit(self, lk_fitting, max_iters=20, project=True):
# Initial error > eps
error = self.eps + 1
image = lk_fitting.image
lk_fitting.weights = []
n_iters = 0
# Number of shape weights
n_params = self.transform.n_parameters
# Initial appearance weights
if project:
# Obtained weights by projection
IWxp = image.warp_to(self.template.mask, self.transform,
interpolator=self.interpolator)
weights = self.appearance_model.project(IWxp)
# Reset template
self.template = self.appearance_model.instance(weights)
else:
# Set all weights to 0 (yielding the mean)
weights = np.zeros(self.appearance_model.n_active_components)
lk_fitting.weights.append(weights)
# Compute appearance model Jacobian wrt weights
appearance_jacobian = -self.appearance_model._jacobian.T
# Baker-Matthews, Inverse Compositional Algorithm
while n_iters < max_iters and error > self.eps:
# Compute warped image with current weights
IWxp = image.warp_to(self.template.mask, self.transform,
interpolator=self.interpolator)
# Compute steepest descent images, VT_dW_dp
J = self.residual.<API key>(self.template,
self._dW_dp)
# Concatenate VI_dW_dp with appearance model Jacobian
self._J = np.hstack((J, appearance_jacobian))
# Compute Hessian and inverse
self._H = self.residual.calculate_hessian(self._J)
# Compute steepest descent parameter updates
sd_delta_p = self.residual.<API key>(
self._J, IWxp, self.template)
# Compute gradient descent parameter updates
delta_p = -np.real(self._calculate_delta_p(sd_delta_p))
# Update warp weights
self.transform.<API key>(delta_p[:n_params])
lk_fitting.parameters.append(self.transform.as_vector())
# Update appearance weights
weights -= delta_p[n_params:]
self.template = self.appearance_model.instance(weights)
lk_fitting.weights.append(weights)
# Test convergence
error = np.abs(norm(delta_p))
n_iters += 1
lk_fitting.fitted = True
return lk_fitting
|
package org.cagrid.gme.common.exceptions;
import java.io.IOException;
@SuppressWarnings("serial")
public class <API key> extends IOException {
public <API key>() {
super();
}
public <API key>(String s) {
super(s);
}
}
|
#ifndef <API key>
#define <API key>
#include "ui/events/events_export.h"
namespace ui {
class DragEventAndroid;
class GestureEventAndroid;
class KeyEventAndroid;
class MotionEventAndroid;
// Dispatches events to appropriate targets. The default implementations of
// all of the specific handlers do nothing. Implementations should set
// themselves to the ViewAndroid in the view tree to get the calls routed.
// Use bool return type to stop propagating the call i.e. overriden method
// should return true to indicate that the event was handled and stop
// the processing.
class EVENTS_EXPORT EventHandlerAndroid {
public:
virtual bool OnDragEvent(const DragEventAndroid& event);
virtual bool OnTouchEvent(const MotionEventAndroid& event);
virtual bool OnMouseEvent(const MotionEventAndroid& event);
virtual bool OnMouseWheelEvent(const MotionEventAndroid& event);
virtual bool OnGestureEvent(const GestureEventAndroid& event);
virtual void OnSizeChanged();
virtual void <API key>();
virtual void <API key>();
virtual bool <API key>(const MotionEventAndroid& event);
virtual bool OnKeyUp(const KeyEventAndroid& event);
virtual bool DispatchKeyEvent(const KeyEventAndroid& event);
virtual bool ScrollBy(float delta_x, float delta_y);
virtual bool ScrollTo(float x, float y);
};
} // namespace ui
#endif // <API key>
|
// .NAME <API key> - draw text labels at 2D dataset points
// .SECTION Description
// <API key> is a mapper that renders text at dataset
// points such that the labels do not overlap.
// Various items can be labeled including point ids, scalars,
// vectors, normals, texture coordinates, tensors, and field data components.
// This mapper assumes that the points are located on the x-y plane
// and that the camera remains perpendicular to that plane with a y-up
// axis (this can be constrained using vtkImageInteractor).
// On the first render, the mapper computes the visiblility of all labels
// at all scales, and queries this information on successive renders.
// This causes the first render to be much slower. The visibility algorithm
// is a greedy approach based on the point id, so the label for a point
// will be drawn unless the label for a point with lower id overlaps it.
// .SECTION Caveats
// Use this filter in combination with <API key> if you want
// to label only points that are visible. If you want to label cells rather
// than points, use the filter vtkCellCenters to generate points at the
// center of the cells. Also, you can use the class vtkIdFilter to
// generate ids as scalars or field data, which can then be labeled.
// .SECTION See Also
// <API key>
// .SECTION Thanks
// This algorithm was developed in the paper
// Ken Been and Chee Yap. Dynamic Map Labeling. IEEE Transactions on
// Visualization and Computer Graphics, Vol. 12, No. 5, 2006. pp. 773-780.
#ifndef <API key>
#define <API key>
#include "<API key>.h" // For export macro
#include "<API key>.h"
class <API key> <API key> : public <API key>
{
public:
// Description:
// Instantiate object with %%-#6.3g label format. By default, point ids
// are labeled.
static <API key> *New();
vtkTypeMacro(<API key>, <API key>);
void PrintSelf(ostream& os, vtkIndent indent);
// Description:
// Set the points array name to use to give priority to labels.
// Defaults to "priority".
void <API key>(const char* name);
// Description:
// Whether to reverse the priority order (i.e. low values have high priority).
// Default is off.
vtkSetMacro(ReversePriority, bool);
vtkGetMacro(ReversePriority, bool);
vtkBooleanMacro(ReversePriority, bool);
// Description:
// Set the label height padding as a percentage. The percentage
// is a percentage of your label height.
// Default is 50%.
vtkSetMacro(LabelHeightPadding, float);
vtkGetMacro(LabelHeightPadding, float);
// Description:
// Set the label width padding as a percentage. The percentage
// is a percentage of your label ^height^ (yes, not a typo).
// Default is 50%.
vtkSetMacro(LabelWidthPadding, float);
vtkGetMacro(LabelWidthPadding, float);
// Description:
// Draw non-overlapping labels to the screen.
void <API key>(vtkViewport* viewport, vtkActor2D* actor);
void RenderOverlay(vtkViewport *viewport, vtkActor2D *actor);
protected:
<API key>();
~<API key>();
// Description:
// Calculate the current zoom scale of the viewport.
double GetCurrentScale(vtkViewport *viewport);
float* LabelWidth;
float* LabelHeight;
float* Cutoff;
float ReferenceScale;
float LabelHeightPadding;
float LabelWidthPadding;
bool ReversePriority;
private:
<API key>(const <API key>&); // Not implemented.
void operator=(const <API key>&); // Not implemented.
};
#endif
|
require 'erb'
describe "ERB.new" do
before :all do
@eruby_str = <<'END'
<ul>
<% list = [1,2,3] %>
<% for item in list %>
<% if item %>
<li><%= item %></li>
<% end %>
<% end %>
</ul>
END
@eruby_str2 = <<'END'
<ul>
% list = [1,2,3]
%for item in list
% if item
<li><%= item %>
<% end %>
<% end %>
</ul>
%%%
END
end
it "compiles eRuby script into ruby code when trim mode is 0 or not specified" do
expected = "<ul>\n\n\n\n<li>1</li>\n\n\n\n<li>2</li>\n\n\n\n<li>3</li>\n\n\n</ul>\n"
[0, '', nil].each do |trim_mode|
ERB.new(@eruby_str, nil, trim_mode).result.should == expected
end
end
it "removes '\n' when trim_mode is 1 or '>'" do
expected = "<ul>\n<li>1</li>\n<li>2</li>\n<li>3</li>\n</ul>\n"
[1, '>'].each do |trim_mode|
ERB.new(@eruby_str, nil, trim_mode).result.should == expected
end
end
it "removes spaces at beginning of line and '\n' when trim_mode is 2 or '<>'" do
expected = "<ul>\n<li>1</li>\n<li>2</li>\n<li>3</li>\n</ul>\n"
[2, '<>'].each do |trim_mode|
ERB.new(@eruby_str, nil, trim_mode).result.should == expected
end
end
it "removes spaces around '<%- -%>' when trim_mode is '-'" do
expected = "<ul>\n <li>1 <li>2 <li>3</ul>\n"
input = <<'END'
<ul>
<%- for item in [1,2,3] -%>
<%- if item -%>
<li><%= item -%>
<%- end -%>
<%- end -%>
</ul>
END
ERB.new(input, nil, '-').result.should == expected
end
it "not support '<%-= expr %> even when trim_mode is '-'" do
input = <<'END'
<p>
<%= expr -%>
<%-= expr -%>
</p>
END
lambda { ERB.new(input, nil, '-').result }.should raise_error
end
ruby_bug "#213", "1.8.7" do
it "regards lines starting with '%' as '<% ... %>' when trim_mode is '%'" do
expected = "<ul>\n <li>1\n \n <li>2\n \n <li>3\n \n\n</ul>\n%%\n"
ERB.new(@eruby_str2, nil, "%").result.should == expected
end
end
it "regards lines starting with '%' as '<% ... %>' and remove \"\\n\" when trim_mode is '%>'" do
expected = "<ul>\n <li>1 <li>2 <li>3 </ul>\n%%\n"
ERB.new(@eruby_str2, nil, '%>').result.should == expected
end
it "regard lines starting with '%' as '<% ... %>' and remove \"\\n\" when trim_mode is '%<>'" do
expected = "<ul>\n <li>1\n \n <li>2\n \n <li>3\n \n</ul>\n%%\n"
ERB.new(@eruby_str2, nil, '%<>').result.should == expected
end
it "regard lines starting with '%' as '<% ... %>' and spaces around '<%- -%>' when trim_mode is '%-'" do
expected = "<ul>\n<li>1</li>\n<li>2</li>\n</ul>\n%%\n"
input = <<'END'
<ul>
%list = [1,2]
%for item in list
<li><%= item %></li>
<% end %></ul>
%%%
END
trim_mode = '%-'
ERB.new(input, nil, '%-').result.should == expected
end
not_compliant_on :rubinius do
it "accepts a safe level as second argument" do
input = "<b><%=- 2+2 %>"
safe_level = 3
lambda { ERB.new(input, safe_level).result }.should_not raise_error
end
end
it "changes '_erbout' variable name in the produced source" do
input = @eruby_str
match_erbout = ERB.new(input, nil, nil).src
match_buf = ERB.new(input, nil, nil, 'buf').src
match_erbout.gsub("_erbout", "buf").should == match_buf
end
it "ignores '<%
input = <<'END'
<%# for item in list %>
<b><%#= item %></b>
<%# end %>
END
ERB.new(input).result.should == "\n<b></b>\n\n"
ERB.new(input, nil, '<>').result.should == "<b></b>\n"
end
ruby_version_is ""..."2.0" do
it "remember local variables defined previous one" do
ERB.new(@eruby_str).result
ERB.new("<%= list.inspect %>").result.should == "[1, 2, 3]"
end
end
ruby_version_is "2.0" do
it "forget local variables defined previous one" do
ERB.new(@eruby_str).result
lambda{ ERB.new("<%= list %>").result }.should raise_error(NameError)
end
end
end
|
#include "config.h"
#include "HTMLMediaSource.h"
namespace WebCore {
URLRegistry* HTMLMediaSource::s_registry = 0;
void HTMLMediaSource::setRegistry(URLRegistry* registry)
{
ASSERT(!s_registry);
s_registry = registry;
}
}
|
#ifndef CAN_H
#define CAN_H
/** \file
* \brief Generic CAN communication
* Common commands used to communicate via the CAN protocol.
* These methods are implemented by all CAN communication backends.
*/
#include <tulibs/config.h>
/** Predefined CAN constants
*/
#define <API key> "can"
/** Predefined CAN error codes
*/
#define CAN_ERROR_NONE 0
#define CAN_ERROR_OPEN 1
#define CAN_ERROR_SETUP 2
#define CAN_ERROR_CLOSE 3
#define CAN_ERROR_SEND 4
#define CAN_ERROR_RECEIVE 5
/** \brief Predefined CAN error descriptions
*/
extern const char* can_errors[];
/** \brief Structure defining a CAN message
*/
typedef struct can_message_t {
int id; //!< The CAN message identifier.
unsigned char content[8]; //!< The actual CAN message content.
ssize_t length; //!< The length of the CAN message.
} can_message_t, *can_message_p;
/** \brief Structure defining a CAN device
*/
typedef struct can_device_t {
void* comm_dev; //!< The CAN communication device.
config_t config; //!< The CAN configuration parameters.
ssize_t num_references; //!< Number of references to this device.
ssize_t num_sent; //!< The number of CAN messages sent.
ssize_t num_received; //!< The number of CAN messages read.
} can_device_t, *can_device_p;
/** \brief Predefined CAN default configuration
*/
extern config_t can_default_config;
/** \brief Initialize CAN device
* \param[in] dev The CAN device to be initialized.
* \param[in] config The optional CAN device configuration parameters.
* Can be null.
*/
void can_init(
can_device_p dev,
config_p config);
/** \brief Initialize CAN device from command line arguments
* \param[in] dev The CAN device to be initialized.
* \param[in] argc The number of supplied command line arguments.
* \param[in] argv The list of supplied command line arguments.
* \param[in] prefix An optional argument prefix.
*/
void can_init_arg(
can_device_p dev,
int argc,
char **argv,
const char* prefix);
/** \brief Destroy an existing CAN device
* \param[in] dev The CAN device to be destroyed.
*/
void can_destroy(
can_device_p dev);
/** \brief Open CAN communication
* \note This method is implemented by the CAN communication backend.
* \param[in] dev The initialized CAN device to be opened.
* \return The resulting error code.
*/
int can_open(
can_device_p dev);
/** \brief Close CAN communication
* \note This method is implemented by the CAN communication backend.
* \param[in] dev The opened CAN device to be closed.
* \return The resulting error code.
*/
int can_close(
can_device_p dev);
/** \brief Send a CAN message
* \note This method is implemented by the CAN communication backend.
* \param[in] dev The CAN device to be used for sending the message.
* \param[in] message The CAN message to be sent.
* \return The resulting error code.
*/
int can_send_message(
can_device_p dev,
can_message_p message);
/** \brief Synchronously receive a CAN message
* \note This method is implemented by the CAN communication backend.
* \param[in] dev The CAN device to be used for receiving the message.
* \param[in,out] message The sent CAN message that will be transformed
* into the CAN message received.
* \return The resulting error code.
*/
int can_receive_message(
can_device_p dev,
can_message_p message);
#endif
|
package vtk.text.tl.expr;
import java.math.BigDecimal;
import vtk.text.tl.Symbol;
public class Multiply extends NumericOperator {
public Multiply(Symbol symbol) {
super(symbol);
}
@Override
protected Object evalNumeric(BigDecimal n1, BigDecimal n2) {
return n1.multiply(n2);
}
}
|
// Definition of ModelTypePayloadMap and various utility functions.
#ifndef <API key>
#define <API key>
#include <map>
#include <string>
#include "sync/base/sync_export.h"
#include "sync/internal_api/public/base/model_type.h"
// TODO(akalin): Move the non-exported functions in this file to a
// private header.
namespace base {
class DictionaryValue;
}
namespace syncer {
// A container that contains a set of datatypes with possible string
// payloads.
typedef std::map<ModelType, std::string> ModelTypePayloadMap;
// Helper functions for building <API key>.
// Make a TypePayloadMap from all the types in a ModelTypeSet using a
// default payload.
SYNC_EXPORT ModelTypePayloadMap <API key>(
ModelTypeSet model_types, const std::string& payload);
ModelTypeSet <API key>(
const ModelTypePayloadMap& payload_map);
std::string <API key>(
const ModelTypePayloadMap& model_type_payloads);
// Caller takes ownership of the returned dictionary.
base::DictionaryValue* <API key>(
const ModelTypePayloadMap& model_type_payloads);
// Coalesce |update| into |original|, overwriting only when |update| has
// a non-empty payload.
void CoalescePayloads(ModelTypePayloadMap* original,
const ModelTypePayloadMap& update);
} // namespace syncer
#endif // <API key>
|
"""Provides fakes for several of Telemetry's internal objects.
These allow code like story_runner and Benchmark to be run and tested
without compiling or starting a browser. Class names prepended with an
underscore are intended to be implementation details, and should not
be subclassed; however, some, like _FakeBrowser, have public APIs that
may need to be called in tests.
"""
from telemetry.internal.backends.chrome_inspector import websocket
from telemetry.internal.browser import browser_options
from telemetry.internal.platform import system_info
from telemetry.page import shared_page_state
from telemetry.util import image_util
from telemetry.testing.internal import fake_gpu_info
from types import ModuleType
# Classes and functions which are intended to be part of the public
# fakes API.
class FakePlatform(object):
def __init__(self):
self._network_controller = None
self._tracing_controller = None
self._has_battor = False
self._os_name = 'FakeOS'
self._device_type_name = 'abc'
self._is_svelte = False
self._is_aosp = True
@property
def is_host_platform(self):
raise NotImplementedError
@property
def network_controller(self):
if self._network_controller is None:
self._network_controller = <API key>()
return self._network_controller
@property
def tracing_controller(self):
if self._tracing_controller is None:
self._tracing_controller = <API key>()
return self._tracing_controller
def Initialize(self):
pass
def <API key>(self):
return False
def <API key>(self):
return False
def <API key>(self):
return False
def GetArchName(self):
raise NotImplementedError
def SetOSName(self, name):
self._os_name = name
def GetOSName(self):
return self._os_name
def GetOSVersionName(self):
raise NotImplementedError
def <API key>(self):
raise NotImplementedError
def StopAllLocalServers(self):
pass
def <API key>(self, _):
pass
def HasBattOrConnected(self):
return self._has_battor
def SetBattOrDetected(self, b):
assert isinstance(b, bool)
self._has_battor = b
# TODO(rnephew): Investigate moving from setters to @property.
def SetDeviceTypeName(self, name):
self._device_type_name = name
def GetDeviceTypeName(self):
return self._device_type_name
def SetIsSvelte(self, b):
assert isinstance(b, bool)
self._is_svelte = b
def IsSvelte(self):
if self._os_name != 'android':
raise NotImplementedError
return self._is_svelte
def SetIsAosp(self, b):
assert isinstance(b, bool)
self._is_aosp = b
def IsAosp(self):
return self._is_aosp and self._os_name == 'android'
class FakeLinuxPlatform(FakePlatform):
def __init__(self):
super(FakeLinuxPlatform, self).__init__()
self.screenshot_png_data = None
self.<API key> = []
self.http_server = FakeHTTPServer()
@property
def is_host_platform(self):
return True
def GetDeviceTypeName(self):
return 'Desktop'
def GetArchName(self):
return 'x86_64'
def GetOSName(self):
return 'linux'
def GetOSVersionName(self):
return 'trusty'
def <API key>(self):
return ''
def CanTakeScreenshot(self):
return bool(self.screenshot_png_data)
def TakeScreenshot(self, file_path):
if not self.CanTakeScreenshot():
raise NotImplementedError
img = image_util.FromBase64Png(self.screenshot_png_data)
image_util.WritePngFile(img, file_path)
return True
def <API key>(self, paths):
self.<API key>.append(paths)
class FakeHTTPServer(object):
def UrlOf(self, url):
del url # unused
return 'file:///foo'
class FakePossibleBrowser(object):
def __init__(self, execute_on_startup=None,
<API key>=None):
self._returned_browser = _FakeBrowser(FakeLinuxPlatform())
self.browser_type = 'linux'
self.<API key> = False
self.is_remote = False
self.execute_on_startup = execute_on_startup
self.<API key> = <API key>
@property
def returned_browser(self):
"""The browser object that will be returned through later API calls."""
return self._returned_browser
def Create(self, finder_options):
if self.execute_on_startup is not None:
self.execute_on_startup()
del finder_options # unused
if self.<API key> is not None:
self.<API key>(self._returned_browser)
return self.returned_browser
@property
def platform(self):
"""The platform object from the returned browser.
To change this or set it up, change the returned browser's
platform.
"""
return self.returned_browser.platform
def IsRemote(self):
return self.is_remote
def SetCredentialsPath(self, _):
pass
class FakeSharedPageState(shared_page_state.SharedPageState):
def __init__(self, test, finder_options, story_set):
super(FakeSharedPageState, self).__init__(test, finder_options, story_set)
def _GetPossibleBrowser(self, test, finder_options):
p = FakePossibleBrowser()
self.<API key>(p)
return p
def <API key>(self, possible_browser):
"""Override this to configure the PossibleBrowser.
Can make changes to the browser's configuration here via e.g.:
possible_browser.returned_browser.<API key> = ...
"""
pass
def DidRunStory(self, results):
# TODO(kbr): add a test which throws an exception from DidRunStory
super(FakeSharedPageState, self).DidRunStory(results)
class FakeSystemInfo(system_info.SystemInfo):
def __init__(self, model_name='', gpu_dict=None, command_line=''):
if gpu_dict == None:
gpu_dict = fake_gpu_info.FAKE_GPU_INFO
super(FakeSystemInfo, self).__init__(model_name, gpu_dict, command_line)
class <API key>(browser_options.<API key>):
def __init__(self, execute_on_startup=None,
<API key>=None, *args, **kwargs):
browser_options.<API key>.__init__(self, *args, **kwargs)
self.<API key> = \
FakePossibleBrowser(
execute_on_startup=execute_on_startup,
<API key>=<API key>)
def <API key>(browser_type=None, execute_on_startup=None,
<API key>=None):
"""Creates fake browser finder options for discovering a browser."""
return <API key>(
browser_type=browser_type,
execute_on_startup=execute_on_startup,
<API key>=<API key>)
# Internal classes. Note that end users may still need to both call
# and mock out methods of these classes, but they should not be
# subclassed.
class _FakeBrowser(object):
def __init__(self, platform):
self._tabs = _FakeTabList(self)
# Fake the creation of the first tab.
self._tabs.New()
self.<API key> = FakeSystemInfo()
self._platform = platform
self._browser_type = 'release'
self._is_crashed = False
@property
def platform(self):
return self._platform
@platform.setter
def platform(self, incoming):
"""Allows overriding of the fake browser's platform object."""
assert isinstance(incoming, FakePlatform)
self._platform = incoming
@property
def <API key>(self):
"""The object which will be returned from calls to GetSystemInfo."""
return self.<API key>
@<API key>.setter
def <API key>(self, incoming):
"""Allows overriding of the returned SystemInfo object.
Incoming argument must be an instance of FakeSystemInfo."""
assert isinstance(incoming, FakeSystemInfo)
self.<API key> = incoming
@property
def browser_type(self):
"""The browser_type this browser claims to be ('debug', 'release', etc.)"""
return self._browser_type
@browser_type.setter
def browser_type(self, incoming):
"""Allows setting of the browser_type."""
self._browser_type = incoming
@property
def credentials(self):
return _FakeCredentials()
def Close(self):
self._is_crashed = False
@property
def <API key>(self):
return True
def GetSystemInfo(self):
return self.<API key>
@property
def <API key>(self):
return True
@property
def tabs(self):
return self._tabs
def <API key>(self):
pass
class _FakeCredentials(object):
def <API key>(self, _):
pass
class <API key>(object):
def __init__(self):
self._is_tracing = False
def StartTracing(self, tracing_config, timeout=10):
self._is_tracing = True
del tracing_config
del timeout
def StopTracing(self):
self._is_tracing = False
@property
def is_tracing_running(self):
return self._is_tracing
def ClearStateIfNeeded(self):
pass
def <API key>(self):
return True
class <API key>(object):
def __init__(self):
self.wpr_mode = None
self.extra_wpr_args = None
self.is_initialized = False
self.is_open = False
self.use_live_traffic = None
def InitializeIfNeeded(self, use_live_traffic=False):
self.use_live_traffic = use_live_traffic
def <API key>(self, <API key>=None,
<API key>=None, <API key>=None):
pass
def Open(self, wpr_mode, extra_wpr_args, use_wpr_go=False):
del use_wpr_go # Unused.
self.wpr_mode = wpr_mode
self.extra_wpr_args = extra_wpr_args
self.is_open = True
def Close(self):
self.wpr_mode = None
self.extra_wpr_args = None
self.is_initialized = False
self.is_open = False
def StartReplay(self, archive_path, <API key>=False):
del <API key> # Unused.
assert self.is_open
self.is_initialized = archive_path is not None
def StopReplay(self):
self.is_initialized = False
class _FakeTab(object):
def __init__(self, browser, tab_id):
self._browser = browser
self._tab_id = str(tab_id)
self.<API key> = 0
self.test_png = None
@property
def <API key>(self):
return self.<API key>
@property
def id(self):
return self._tab_id
@property
def browser(self):
return self._browser
def <API key>(self, timeout=0):
pass
def Navigate(self, url, <API key>=None,
timeout=0):
del <API key>, timeout # unused
if url == 'chrome://crash':
self.browser._is_crashed = True
raise Exception
def <API key>(self, timeout=0):
pass
def <API key>(self, timeout=0):
pass
def IsAlive(self):
return True
def CloseConnections(self):
pass
def CollectGarbage(self):
self.<API key> += 1
def Close(self):
pass
@property
def <API key>(self):
return self.test_png is not None
def Screenshot(self):
assert self.<API key>, 'Screenshot is not supported'
return image_util.FromBase64Png(self.test_png)
class _FakeTabList(object):
_current_tab_id = 0
def __init__(self, browser):
self._tabs = []
self._browser = browser
def New(self, timeout=300):
del timeout # unused
type(self)._current_tab_id += 1
t = _FakeTab(self._browser, type(self)._current_tab_id)
self._tabs.append(t)
return t
def __iter__(self):
return self._tabs.__iter__()
def __len__(self):
return len(self._tabs)
def __getitem__(self, index):
if self._tabs[index].browser._is_crashed:
raise Exception
else:
return self._tabs[index]
def GetTabById(self, identifier):
"""The identifier of a tab can be accessed with tab.id."""
for tab in self._tabs:
if tab.id == identifier:
return tab
return None
class <API key>(object):
_NOTIFICATION_EVENT = 1
<API key> = 2
"""A fake InspectorWebsocket.
A fake that allows tests to send pregenerated data. Normal
InspectorWebsockets allow for any number of domain handlers. This fake only
allows up to 1 domain handler, and assumes that the domain of the response
always matches that of the handler.
"""
def __init__(self, mock_timer):
self._mock_timer = mock_timer
self._notifications = []
self._response_handlers = {}
self._pending_callbacks = {}
self._handler = None
def RegisterDomain(self, _, handler):
self._handler = handler
def AddEvent(self, method, params, time):
if self._notifications:
assert self._notifications[-1][1] < time, (
'Current response is scheduled earlier than previous response.')
response = {'method': method, 'params': params}
self._notifications.append((response, time, self._NOTIFICATION_EVENT))
def AddAsyncResponse(self, method, result, time):
if self._notifications:
assert self._notifications[-1][1] < time, (
'Current response is scheduled earlier than previous response.')
response = {'method': method, 'result': result}
self._notifications.append((response, time, self.<API key>))
def AddResponseHandler(self, method, handler):
self._response_handlers[method] = handler
def SyncRequest(self, request, *args, **kwargs):
del args, kwargs # unused
handler = self._response_handlers[request['method']]
return handler(request) if handler else None
def AsyncRequest(self, request, callback):
self._pending_callbacks.setdefault(request['method'], []).append(callback)
def <API key>(self, request):
pass
def Connect(self, _):
pass
def <API key>(self, timeout):
current_time = self._mock_timer.time()
if not self._notifications:
self._mock_timer.SetTime(current_time + timeout + 1)
raise websocket.<API key>()
response, time, kind = self._notifications[0]
if time - current_time > timeout:
self._mock_timer.SetTime(current_time + timeout + 1)
raise websocket.<API key>()
self._notifications.pop(0)
self._mock_timer.SetTime(time + 1)
if kind == self._NOTIFICATION_EVENT:
self._handler(response)
elif kind == self.<API key>:
callback = self._pending_callbacks.get(response['method']).pop(0)
callback(response)
else:
raise Exception('Unexpected response type')
class FakeTimer(object):
""" A fake timer to fake out the timing for a module.
Args:
module: module to fake out the time
"""
def __init__(self, module=None):
self._elapsed_time = 0
self._module = module
self._actual_time = None
if module:
assert isinstance(module, ModuleType)
self._actual_time = module.time
self._module.time = self
def sleep(self, time):
self._elapsed_time += time
def time(self):
return self._elapsed_time
def SetTime(self, time):
self._elapsed_time = time
def __del__(self):
self.Restore()
def Restore(self):
if self._module:
self._module.time = self._actual_time
self._module = None
self._actual_time = None
|
FILE(REMOVE_RECURSE
"CMakeFiles/dynamic_object_test.dir/unittests/dynamic_object_test.cpp.o"
"dynamic_object_test.pdb"
"dynamic_object_test"
)
# Per-language clean rules from dependency scanning.
FOREACH(lang CXX)
INCLUDE(CMakeFiles/dynamic_object_test.dir/cmake_clean_${lang}.cmake OPTIONAL)
ENDFOREACH(lang)
|
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* the project. */
package edu.wpi.first.wpilibj.templates;
import edu.wpi.first.wpilibj.Compressor;
import edu.wpi.first.wpilibj.Jaguar;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.Servo;
import edu.wpi.first.wpilibj.SimpleRobot;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the SimpleRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class RobotTemplate extends SimpleRobot {
private Joystick joystick = new Joystick(1);
private Drivetrain drivetrain;
private BowlerArm arm;
Compressor compressor;
Pan pan;
//int port_1 = 7; //these ports were placeholders, no longer applicable
//int port_2 = 7;
public RobotTemplate() {
drivetrain = new Drivetrain();
arm = new BowlerArm();
pan = new Pan();
compressor = new Compressor(7, 7);//7 for the switch, 7 for the relay
}
/**
* This function is called once each time the robot enters autonomous mode.
*/
public void autonomous() {
drivetrain.set(1, 1);
sleep(5000);
drivetrain.set(0,0);
// arm.auto();
}
/**
* This function is called once each time the robot enters operator control.
*/
public void operatorControl() {
compressor.start();
arm.setSolenoid(-1);
while (isOperatorControl()) {
//drivetrain updates
double lstick = -joystick.getRawAxis(2);
double rstick = -joystick.getRawAxis(4);
drivetrain.set(Math.abs(lstick) * lstick, Math.abs(rstick) * rstick); //If I'm not mistaken, this is the most convenient way to square in Java?
//pan updates version 2 (Amita); this is basic and can be used for backup
if(joystick.getRawButton(10)){
pan.endGame();
}
else{
pan.resetServo();
}
//bowler arm updates
if (joystick.getRawButton(7)) {
arm.rampDown();
} else if (joystick.getRawButton(5)) {
arm.rampUp();
} else {
arm.setRamp(0);
}
arm.setSolenoid((int) joystick.getRawAxis(6));
}
}
/*
*changes the servo state based on the button being pressed.
*once it is pressed, it is set to the opposite of what is was at the start, ditto for release.
*/
/**
* This function is called once each time the robot enters test mode.
*/
public void test() {
}
public void updateDrivetrain(){
}
public void updateArm(){
}
public void updatePan(){
}
public static void sleep(long ms){
long t=System.currentTimeMillis()+ms;
while(System.currentTimeMillis()<t){
//do nothing!
}
}
}
|
#include "<API key>.moc.h"
#include <QtToolbox/CollapsibleWidget.moc.h>
#include <QtToolbox/SingleSlidingValue.moc.h>
#include <QtToolbox/SingleSlidingHDR.moc.h>
#include <QGridLayout>
#include <QPushButton>
namespace EPI
{
<API key>::<API key>( const Ptr<Universe::NodeEmitter>& pNodeE,
const Ptr<Universe::PartEffectTranslate>& pEffect,
const Core::String& title)
: PtyPartEffect(pNodeE, pEffect, title)
{
updateProperty();
}
<API key>::<API key>(const Ptr<Universe::NodeEmitter>& pNodeE, const Core::String& title)
: PtyPartEffect(
pNodeE,
Ptr<Universe::PartEffectTranslate>(new Universe::PartEffectTranslate()),
title)
{
updateProperty();
}
<API key>::~<API key>()
{}
Ptr<PropertyWidget> <API key>::<API key>(const Ptr<<API key>>& pDataProxy, QWidget * parent)
{
Ptr<<API key>> pPW (new <API key>(pDataProxy, parent));
return pPW;
}
void <API key>::updateData()
{
Ptr<Universe::PartEffectTranslate> pEffet = LM_DEBUG_PTR_CAST<Universe::PartEffectTranslate> (getEffect());
pEffet->setConstSpeed(_constSpeed);
pEffet->setRandSpeed(_randSpeed);
}
void <API key>::updateProperty()
{
Ptr<Universe::PartEffectTranslate> pEffet = LM_DEBUG_PTR_CAST<Universe::PartEffectTranslate> (getEffect());
_constSpeed = pEffet->getConstSpeed();
_randSpeed = pEffet->getRandSpeed();
}
void <API key>::internalResurrect(const Ptr<Universe::World>& pWorld, const Ptr<Universe::World>& pWorldInfoContent, const Ptr<Property>& pty)
{
LM_ASSERT(getEffect()==null);
Ptr<Universe::IPartEffect> pEffet = Ptr<Universe::PartEffectTranslate>(new Universe::PartEffectTranslate());
setEffect(pEffet);
<API key>()->addEffect(getEffect());
updateData();
}
Ptr<Property> <API key>::clone() const
{
return Ptr<Property>(new <API key>( *this ));
}
void <API key>::internalCopy(const Ptr<Property>& pSrc)
{
PtyPartEffect::internalCopy(pSrc);
Ptr<<API key>> pPty = LM_DEBUG_PTR_CAST<<API key>>(pSrc);
_constSpeed = pPty->_constSpeed;
_randSpeed = pPty->_randSpeed;
updateData();
}
<API key>::<API key>(const Ptr<<API key>>& data, QWidget * parent)
: PropertyWidget(data, parent)
{
setupUi();
}
<API key>::~<API key>()
{}
void <API key>::readProperty()
{
Ptr<<API key>> pP = LM_DEBUG_PTR_CAST<<API key>>(getDataProxy()->getProperty());
_constSpeedX->setSingleValue(pP->_constSpeed.x);
_constSpeedY->setSingleValue(pP->_constSpeed.y);
_constSpeedZ->setSingleValue(pP->_constSpeed.z);
_randSpeedX->setSingleValue(pP->_randSpeed.x);
_randSpeedY->setSingleValue(pP->_randSpeed.y);
_randSpeedZ->setSingleValue(pP->_randSpeed.z);
}
void <API key>::writeProperty(QWidget* pWidget)
{
Ptr<<API key>> pP = LM_DEBUG_PTR_CAST<<API key>>(getDataProxy()->getProperty());
double x = 0.0;
double y = 0.0;
double z = 0.0;
_constSpeedX->getSingleValue(x);
_constSpeedY->getSingleValue(y);
_constSpeedZ->getSingleValue(z);
pP->_constSpeed = Core::Vector3f(float(x), float(y), float(z));
_randSpeedX->getSingleValue(x);
_randSpeedY->getSingleValue(y);
_randSpeedZ->getSingleValue(z);
pP->_randSpeed = Core::Vector3f(float(x), float(y), float(z));
}
void <API key>::setupUi()
{
_layout = new QGridLayout(this);
_layout->setContentsMargins(0, 0, 0, 0);
_layout->setSpacing(0);
_groupBox = new QtToolbox::CollapsibleWidget(this, "Translate effect");
_del = new QPushButton(QIcon(":/icons/smallClearBW.png"), "", this);
_constSpeedX = new QtToolbox::SingleSlidingHDR(this, "Const X", true);
_constSpeedY = new QtToolbox::SingleSlidingHDR(this, "Const Y", true);
_constSpeedZ = new QtToolbox::SingleSlidingHDR(this, "Const Z", true);
_randSpeedX = new QtToolbox::SingleSlidingHDR(this, "Rand X", true);
_randSpeedY = new QtToolbox::SingleSlidingHDR(this, "Rand Y", true);
_randSpeedZ = new QtToolbox::SingleSlidingHDR(this, "Rand Z", true);
_groupBox->addWidgetToTitle(_del);
_groupBox->getLayout()->addWidget(_constSpeedX);
_groupBox->getLayout()->addWidget(_constSpeedY);
_groupBox->getLayout()->addWidget(_constSpeedZ);
_groupBox->getLayout()->addWidget(_randSpeedX);
_groupBox->getLayout()->addWidget(_randSpeedY);
_groupBox->getLayout()->addWidget(_randSpeedZ);
_layout->addWidget(_groupBox);
setLayout(_layout);
<API key>().push_back(_constSpeedX);
<API key>().push_back(_constSpeedY);
<API key>().push_back(_constSpeedZ);
<API key>().push_back(_randSpeedX);
<API key>().push_back(_randSpeedY);
<API key>().push_back(_randSpeedZ);
PropertyWidget::setupUi();
connect(_del, SIGNAL(clicked()), this, SLOT(deleteWidget()));
}
void <API key>::deleteWidget()
{
emit <API key>(this);
}
}//namespace EPI
|
# -*- coding: utf-8 -*-
"""
Quality Control based on fuzzy logic.
"""
import logging
import numpy as np
from .core import QCCheckVar
from .gradient import gradient
from .spike import spike
from .woa_normbias import woa_normbias
from cotede.fuzzy import fuzzy_uncertainty
module_logger = logging.getLogger(__name__)
def fuzzylogic(features, cfg, require="all"):
"""
FIXME: Think about, should I return 0, or have an assert, and at qc.py
all qc tests are applied with a try, and in case it fails it flag
0s.
"""
require = cfg.get("require", require)
if (require == "all") and not np.all([f in features for f in cfg["features"]]):
module_logger.warning(
"Not all features (%s) required by fuzzy logic are available".format(
cfg["features"].keys()
)
)
raise KeyError
uncertainty = fuzzy_uncertainty(
data=features, features=cfg["features"], output=cfg["output"], require=require
)
return uncertainty
class FuzzyLogic(QCCheckVar):
def set_features(self):
self.features = {}
for v in [f for f in self.cfg["features"] if f not in self.features]:
if v == "woa_bias":
woa_comparison = woa_normbias(self.data, self.varname, self.attrs)
self.features[v] = woa_comparison["woa_bias"]
elif v == "woa_normbias":
woa_comparison = woa_normbias(self.data, self.varname, self.attrs)
self.features[v] = woa_comparison["woa_normbias"]
elif v == "spike":
self.features[v] = spike(self.data[self.varname])
elif v == "gradient":
self.features[v] = gradient(self.data[self.varname])
self.features["fuzzylogic"] = fuzzylogic(self.features, self.cfg)
def test(self):
self.flags = {}
cfg = self.cfg
flag = np.zeros(np.shape(self.data[self.varname]), dtype="i1")
uncertainty = self.features["fuzzylogic"]
# FIXME: As it is now, it will have no zero flag value. Think about cases
# where some values in a profile would not be estimated, hence flag=0
# I needed to use np.nonzeros because now uncertainty is a masked array,
# to accept when a feature is masked.
flag[np.nonzero(uncertainty <= 0.29)] = 1
flag[np.nonzero((uncertainty > 0.29) & (uncertainty <= 0.34))] = 2
flag[np.nonzero((uncertainty > 0.34) & (uncertainty <= 0.72))] = 3
flag[np.nonzero(uncertainty > 0.72)] = 4
self.flags["fuzzylogic"] = flag
|
# Spree PayPal Express
This is a "re-do" of the official [<API key>][4] extension. The old extension is extremely hard to maintain and complex.
Behind-the-scenes, this extension uses [PayPal's Merchant Ruby SDK](https://github.com/paypal/merchant-sdk-ruby).
## Installation
1. Add this extension to your Gemfile with this line:
gem '<API key>', :github => "spree-contrib/<API key>", :branch => "2-2-stable"
2. Install the gem using Bundler:
bundle install
3. Copy & run migrations
bundle exec rails g <API key>:install
4. Restart your server
If your server was running, restart it so that it can find the assets properly.
Sandbox Setup
# PayPal
Go to [PayPal's Developer Website](https://developer.paypal.com/), sign in with your PayPal account, click "Applications" then "Sandbox Accounts" and create a new "Business" account. Once the account is created, click on the triangle next to its email address, then "Profile". The "API Credentials" tab will provide your API credentials (probably). If this tab is blank, try refreshing the page.
You will also need a "Personal" account to test the transactions on your site. Create this in the same way, finding the account information under "Profile" as well. You may need to set a password in order to be able to log in to PayPal's sandbox for this user.
# Spree Setup
In Spree, go to the admin backend, click "Configuration" and then "Payment Methods" and create a new payment method. Select "Spree::Gateway::PayPalExpress" as the provider, and click "Create". Enter the email address, password and signature from the "API Credentials" tab for the **Business** account on PayPal.
Production setup
# PayPal
Sign in to PayPal, then click "Profile" and then (under "Account Information" on the left), click "API Access". On this page, select "Option 2" and click "View API Signature". The username, password and signature will be displayed on this screen.
If you are unable to find it, then follow [PayPal's own documentation](https://developer.paypal.com/webapps/developer/docs/classic/api/apiCredentials/).
# Spree Setup
Same as sandbox setup, but change "Server" from "sandbox" to "live".
## Configuration
The PayPal Express Checkout has [no less than 4.5 billion configuration options](https://github.com/paypal/merchant-sdk-ruby/blob/<SHA1-like>/lib/paypal-sdk/merchant/data_types.rb#L830-L959).
This Spree extension supports *some* of those. If your favourite is not here, then please submit an issue about it, or better still a patch to add it in.
Solution Type
Determines whether or not a user needs a PayPal account to check out.
ruby
payment_method.<API key> = "Mark"
payment_method.<API key> = "Sole"
"Mark" if you do want users to have a paypal account, "Sole" otherwise.
Landing Page
Determines which page to show users once they're redirected to PayPal.
ruby
payment_method.<API key> = "Login"
payment_method.<API key> = "Billing"
"Login" will show the users the login form for PayPal, and "Billing" will show them a form where they can enter their credit card data and possibly sign up for a PayPal account (depending on the Solution Type setting above).
Logo
Determines what logo, if any, to display at the top left of the PayPal express checkout:
ruby
payment_method.preferred_logourl = 'http://yoursite.com/images/checkout.jpg'
**Must** be an absolute path to the image.
## Caveats
*Caveat venditor*
Paypal will refuse any order with a zero cost item.
Any such item will be skipped and not displayed.
PayPal will also refuse any order where item total (before taxes and shipping costs) is zero.
In this case the PayPal checkout page will simply display "Current order".
## Contributing
In the spirit of [free software][1], **everyone** is encouraged to help improve this project.
Here are some ways *you* can contribute:
* by using prerelease versions
* by reporting [bugs][2]
* by suggesting new features
* by writing or editing documentation
* by writing specifications
* by writing code (*no patch is too small*: fix typos, add comments, clean up inconsistent whitespace)
* by refactoring code
* by resolving [issues][2]
* by reviewing patches
Starting point:
* Fork the repo
* Clone your repo
* Run `bundle install`
* Run `bundle exec rake test_app` to create the test application in `spec/dummy`
* Make your changes
* Ensure specs pass by running `bundle exec rspec spec`
* Submit your pull request
Copyright (c) 2014 Spree Commerce and contributors, released under the [New BSD License][3]
[1]: http:
[2]: https://github.com/spree/<API key>/issues
[3]: https:
[4]: https://github.com/spree/<API key>
|
package org.chromium.ui.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.IdRes;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import org.chromium.base.BuildConfig;
import java.lang.ref.WeakReference;
/**
* An {@link <API key>} that increases the speed of frequent view lookup by ID by caching
* the result of the lookup. Adding or removing a view with the same ID as a cached version will
* cause the cache to be invalidated for that view and cause a re-lookup the next time it is
* queried. The goal of this view type is to be used in cases where child views are frequently
* accessed or reused, for example as part of a {@link androidx.recyclerview.widget.RecyclerView}.
* The logic in the {@link #fastFindViewById(int)} method would be in {@link #findViewById(int)} if
* it weren't final on the {@link View} class.
*
* {@link android.view.ViewGroup.<API key>}s cannot be used on ViewGroups that are
* children of this group since they would overwrite the listeners that are critical to this class'
* functionality.
*
* Usage:
* Use the same way that you would use a normal {@link android.widget.FrameLayout}, but instead
* of using {@link #findViewById(int)} to access views, use {@link #fastFindViewById(int)}.
*/
public class <API key> extends <API key> {
/** A map containing views that have had lookup performed on them for quicker access. */
private final SparseArray<WeakReference<View>> mCachedViews = new SparseArray<>();
/** The hierarchy listener responsible for notifying the cache that the tree has changed. */
@VisibleForTesting
final <API key> mListener = new <API key>() {
@Override
public void onChildViewAdded(View parent, View child) {
mCachedViews.remove(child.getId());
<API key>(child, this);
}
@Override
public void onChildViewRemoved(View parent, View child) {
mCachedViews.remove(child.getId());
<API key>(child, null);
}
};
/** Default constructor for use in XML. */
public <API key>(Context context, AttributeSet atts) {
super(context, atts);
<API key>(mListener);
}
@Override
public void <API key>(<API key> listener) {
assert listener == mListener : "Hierarchy change listeners cannot be set for this group!";
super.<API key>(listener);
}
/**
* Set the hierarchy listener that invalidates relevant parts of the cache when subtrees change.
* @param view The root of the tree to attach listeners to.
* @param listener The listener to attach (null to unset).
*/
private void <API key>(View view, <API key> listener) {
if (!(view instanceof ViewGroup)) return;
ViewGroup group = (ViewGroup) view;
group.<API key>(listener);
for (int i = 0; i < group.getChildCount(); i++) {
<API key>(group.getChildAt(i), listener);
}
}
/**
* Does the same thing as {@link #findViewById(int)} but caches the result if not null.
* Subsequent lookups are cheaper as a result. Adding or removing a child view invalidates
* the cache for the ID of the view removed and causes a re-lookup.
* @param id The ID of the view to lookup.
* @return The view if it exists.
*/
@Nullable
public View fastFindViewById(@IdRes int id) {
WeakReference<View> ref = mCachedViews.get(id);
View view = null;
if (ref != null) view = ref.get();
if (view == null) view = findViewById(id);
if (BuildConfig.DCHECK_IS_ON) {
assert view == findViewById(id) : "View caching logic is broken!";
assert ref == null
|| ref.get() != null : "Cache held reference to garbage collected view!";
}
if (view != null) mCachedViews.put(id, new WeakReference<>(view));
return view;
}
@VisibleForTesting
SparseArray<WeakReference<View>> getCache() {
return mCachedViews;
}
}
|
<!DOCTYPE HTML PUBLIC "-
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_91) on Tue Dec 29 12:44:17 AEDT 2015 -->
<title>org.bouncycastle.math.raw (Bouncy Castle Library 1.54 API Specification)</title>
<meta name="date" content="2015-12-29">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="org.bouncycastle.math.raw (Bouncy Castle Library 1.54 API Specification)";
}
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="topNav"><a name="navbar_top">
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><em><b>Bouncy Castle Cryptography Library 1.54</b></em></div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/bouncycastle/math/field/package-summary.html">Prev Package</a></li>
<li><a href="../../../../org/bouncycastle/math/raw/test/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/bouncycastle/math/raw/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<a name="skip-navbar_top">
</a></div>
<div class="header">
<h1 title="Package" class="title">Package org.bouncycastle.math.raw</h1>
<div class="docSummary">
<div class="block">Math support for raw multi-precision calculations.</div>
</div>
<p>See: <a href="#package_description">Description</a></p>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="packageSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation">
<caption><span>Class Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Class</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../../org/bouncycastle/math/raw/Interleave.html" title="class in org.bouncycastle.math.raw">Interleave</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../org/bouncycastle/math/raw/Mod.html" title="class in org.bouncycastle.math.raw">Mod</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../org/bouncycastle/math/raw/Mont256.html" title="class in org.bouncycastle.math.raw">Mont256</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../org/bouncycastle/math/raw/Nat.html" title="class in org.bouncycastle.math.raw">Nat</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../org/bouncycastle/math/raw/Nat128.html" title="class in org.bouncycastle.math.raw">Nat128</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../org/bouncycastle/math/raw/Nat160.html" title="class in org.bouncycastle.math.raw">Nat160</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../org/bouncycastle/math/raw/Nat192.html" title="class in org.bouncycastle.math.raw">Nat192</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../org/bouncycastle/math/raw/Nat224.html" title="class in org.bouncycastle.math.raw">Nat224</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../org/bouncycastle/math/raw/Nat256.html" title="class in org.bouncycastle.math.raw">Nat256</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../org/bouncycastle/math/raw/Nat320.html" title="class in org.bouncycastle.math.raw">Nat320</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../org/bouncycastle/math/raw/Nat384.html" title="class in org.bouncycastle.math.raw">Nat384</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../org/bouncycastle/math/raw/Nat448.html" title="class in org.bouncycastle.math.raw">Nat448</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../org/bouncycastle/math/raw/Nat512.html" title="class in org.bouncycastle.math.raw">Nat512</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../org/bouncycastle/math/raw/Nat576.html" title="class in org.bouncycastle.math.raw">Nat576</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
</ul>
<a name="package_description">
</a>
<h2 title="Package org.bouncycastle.math.raw Description">Package org.bouncycastle.math.raw Description</h2>
<div class="block">Math support for raw multi-precision calculations.</div>
</div>
<div class="bottomNav"><a name="navbar_bottom">
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><em><b>Bouncy Castle Cryptography Library 1.54</b></em></div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/bouncycastle/math/field/package-summary.html">Prev Package</a></li>
<li><a href="../../../../org/bouncycastle/math/raw/test/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/bouncycastle/math/raw/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<a name="skip-navbar_bottom">
</a></div>
</body>
</html>
|
from setuptools import setup, find_packages
setup(name='gelato.models',
version='0.1.2',
description='Gelato models',
namespace_packages=['gelato'],
long_description='',
author='',
author_email='',
license='',
url='',
<API key>=True,
packages=find_packages(exclude=['tests']),
install_requires=['django', 'tower'])
|
{-# LANGUAGE <API key>, FlexibleInstances, TypeFamilies #-}
module Rubik.Turn where
import Data.Array
import Rubik.Negate as N
import Rubik.Key
data Turn = NoTurn | Clock | OneEighty | CounterClock
deriving (Eq,Ord,Show,Enum,Ix)
instance Negate Turn where
negate NoTurn = NoTurn
negate Clock = CounterClock
negate OneEighty = OneEighty
negate CounterClock = Clock
instance Key Turn where
universe = [ NoTurn, Clock, OneEighty, CounterClock ]
class Rotate a where
type SideOf a
rotate :: SideOf a -> a -> a
-- never used
--instance (Negate a, Rotate a b) => Rotate a (b -> c) where
-- rotate t f a = f (rotate (N.negate t) a)
{-
-- Split into its own module
class Rotate a where
type SideOf a
rotate :: SideOf a -> a -> a
-- can complete either
turn :: a -> a
turn = rotateBy Clock
rotateBy :: Turn -> a -> a
rotateBy Clock = turn
rotateBy OneEighty = turn . turn
rotateBy CounterClock = turn . turn . turn
-- We invert the rotate because it is the co-varient position
instance Rotate a => Rotate (a -> b) where
type SideOf (a -> b) = SideOf a
rotateBy t f a = f (rotateBy (N.negate t) a)
instance (Rotate a,Rotate b) => Rotate (a,b) where
rotateBy t (a,b) = (rotateBy t a, rotateBy t b)
data Apply a b = Apply (a -> b) a
apply :: Apply a b -> b
apply (Apply f a) = f a
instance Rotate a => Rotate (Apply a b) where
turn (Apply f a) = Apply f (turn a)
-}
|
/* -*- mode: c++; fill-column: 132; c-basic-offset: 4; indent-tabs-mode: nil -*- */
#include "irods_auth_object.hpp"
namespace irods {
auth_object::auth_object(
rError_t* _r_error ) : r_error_( _r_error ) {
// TODO - stub
}
auth_object::~auth_object() {
// TODO - stub
}
auth_object::auth_object(
const auth_object& _rhs ) {
r_error_ = _rhs.r_error();
request_result_ = _rhs.request_result();
context_ = _rhs.context();
}
auth_object& auth_object::operator=(
const auth_object& _rhs ) {
r_error_ = _rhs.r_error();
request_result_ = _rhs.request_result();
context_ = _rhs.context();
return *this;
}
bool auth_object::operator==(
const auth_object& _rhs ) const {
// For the base class just always return true
return ( r_error_ == _rhs.r_error() &&
request_result_ == _rhs.request_result() &&
context_ == _rhs.context() );
}
}; // namespace irods
|
package operation
import (
"fmt"
"os"
"github.com/runabove/sail/internal"
"github.com/spf13/cobra"
)
var cmdOperationAttach = &cobra.Command{
Use: "attach",
Short: "Attach to an ongoing operation output: sail operation attach [applicationName] <operationId>",
Long: `Attach to an ongoing operation output: sail operation attach [applicationName] <operationId>
Example: sail operation attach devel/redis <API key>
If the applicationName is not passed, the default application name will be used (the user's username).
`,
Run: func(cmd *cobra.Command, args []string) {
switch len(args) {
case 1:
// applicationName was not passed. Using default one.
applicationName := internal.GetUserName()
operationAttach(applicationName, args[0])
case 2:
operationAttach(args[0], args[1])
default:
fmt.Fprintln(os.Stderr, "Invalid usage. sail operation attach [applicationName] <operationId>. Please see sail operation attach --help")
}
},
}
func operationAttach(app, operationID string) {
// Split namespace and service
internal.StreamPrint("GET", fmt.Sprintf("/applications/%s/operation/%s/attach", app, operationID), nil)
internal.ExitAfterCtrlC()
}
|
package com.groupon.lex.metrics;
import org.hamcrest.Matchers;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import org.junit.Test;
/**
*
* @author ariane
*/
public class SimpleMetricTest {
@Test
public void constructor_number() {
Metric m = new SimpleMetric(MetricName.valueOf("foobar"), (short)7);
assertEquals(MetricName.valueOf("foobar"), m.getName());
assertNotNull(m.getValue());
MetricValueTest.validateNumber(true, 7, m.getValue());
}
@Test
public void constructor_string() {
Metric m = new SimpleMetric(MetricName.valueOf("foobar"), "chocoladevla");
assertEquals(MetricName.valueOf("foobar"), m.getName());
assertNotNull(m.getValue());
MetricValueTest.validateString("chocoladevla", m.getValue());
}
@Test
public void constructor_bool() {
Metric m = new SimpleMetric(MetricName.valueOf("foobar"), true);
assertEquals(MetricName.valueOf("foobar"), m.getName());
assertNotNull(m.getValue());
MetricValueTest.validateBoolean(true, m.getValue());
}
@Test
public void constructor_metric() {
Metric m = new SimpleMetric(MetricName.valueOf("foobar"), MetricValue.fromNumberValue(9000));
assertEquals(MetricName.valueOf("foobar"), m.getName());
assertNotNull(m.getValue());
MetricValueTest.validateNumber(true, 9000, m.getValue());
}
@Test
public void constructor_empty() {
Metric m = new SimpleMetric(MetricName.valueOf("foobar"), MetricValue.EMPTY);
assertEquals(MetricName.valueOf("foobar"), m.getName());
assertNotNull(m.getValue());
MetricValueTest.validateEmpty(m.getValue());
}
@Test
public void to_string() {
Metric m = new SimpleMetric(MetricName.valueOf("foobar"), MetricValue.fromIntValue(19));
assertThat(m.toString(), Matchers.allOf(containsString("foobar"), containsString("19")));
}
@Test
public void equality() {
Metric m0 = new SimpleMetric(MetricName.valueOf("foobar"), MetricValue.fromIntValue(19));
Metric m1 = new SimpleMetric(MetricName.valueOf("foobar"), MetricValue.fromIntValue(19));
assertEquals(m0, m1);
assertEquals(m0.hashCode(), m1.hashCode());
}
@Test
public void inequality() {
Metric m0 = new SimpleMetric(MetricName.valueOf("foobar"), MetricValue.fromIntValue(17));
Metric m1 = new SimpleMetric(MetricName.valueOf("foobar"), MetricValue.fromIntValue(19));
Metric m2 = new SimpleMetric(MetricName.valueOf("fizzbuzz"), MetricValue.fromIntValue(19));
assertNotEquals(m0, m1);
assertNotEquals(m0, m2);
assertNotEquals(m1, m0);
assertNotEquals(m1, m2);
assertNotEquals(m2, m0);
assertNotEquals(m2, m1);
}
@Test
public void equal_across_types() {
Metric m = new SimpleMetric(MetricName.valueOf("foobar"), MetricValue.fromIntValue(19));
assertFalse(m.equals(null));
assertFalse(m.equals(new Object()));
}
}
|
import sys
import warnings
try:
import itertools.izip as zip
except ImportError:
pass
from itertools import product
import numpy as np
from .. import util
from ..dimension import dimension_name
from ..element import Element
from ..ndmapping import NdMapping, item_check, sorted_context
from .interface import DataError, Interface
from .pandas import PandasInterface
from .util import finite_range
class cuDFInterface(PandasInterface):
datatype = 'cuDF'
types = ()
@classmethod
def loaded(cls):
return 'cudf' in sys.modules
@classmethod
def applies(cls, obj):
if not cls.loaded():
return False
import cudf
return isinstance(obj, (cudf.DataFrame, cudf.Series))
@classmethod
def init(cls, eltype, data, kdims, vdims):
import cudf
import pandas as pd
element_params = eltype.param.objects()
kdim_param = element_params['kdims']
vdim_param = element_params['vdims']
if isinstance(data, (cudf.Series, pd.Series)):
data = data.to_frame()
if not isinstance(data, cudf.DataFrame):
data, _, _ = PandasInterface.init(eltype, data, kdims, vdims)
data = cudf.from_pandas(data)
columns = list(data.columns)
ncols = len(columns)
index_names = [data.index.name]
if index_names == [None]:
index_names = ['index']
if eltype._auto_indexable_1d and ncols == 1 and kdims is None:
kdims = list(index_names)
if isinstance(kdim_param.bounds[1], int):
ndim = min([kdim_param.bounds[1], len(kdim_param.default)])
else:
ndim = None
nvdim = vdim_param.bounds[1] if isinstance(vdim_param.bounds[1], int) else None
if kdims and vdims is None:
vdims = [c for c in columns if c not in kdims]
elif vdims and kdims is None:
kdims = [c for c in columns if c not in vdims][:ndim]
elif kdims is None:
kdims = list(columns[:ndim])
if vdims is None:
vdims = [d for d in columns[ndim:((ndim+nvdim) if nvdim else None)]
if d not in kdims]
elif kdims == [] and vdims is None:
vdims = list(columns[:nvdim if nvdim else None])
# Handle reset of index if kdims reference index by name
for kd in kdims:
kd = dimension_name(kd)
if kd in columns:
continue
if any(kd == ('index' if name is None else name)
for name in index_names):
data = data.reset_index()
break
if any(isinstance(d, (np.int64, int)) for d in kdims+vdims):
raise DataError("cudf DataFrame column names used as dimensions "
"must be strings not integers.", cls)
if kdims:
kdim = dimension_name(kdims[0])
if eltype._auto_indexable_1d and ncols == 1 and kdim not in columns:
data = data.copy()
data.insert(0, kdim, np.arange(len(data)))
for d in kdims+vdims:
d = dimension_name(d)
if len([c for c in columns if c == d]) > 1:
raise DataError('Dimensions may not reference duplicated DataFrame '
'columns (found duplicate %r columns). If you want to plot '
'a column against itself simply declare two dimensions '
'with the same name. '% d, cls)
return data, {'kdims':kdims, 'vdims':vdims}, {}
@classmethod
def range(cls, dataset, dimension):
dimension = dataset.get_dimension(dimension, strict=True)
column = dataset.data[dimension.name]
if dimension.nodata is not None:
column = cls.replace_value(column, dimension.nodata)
if column.dtype.kind == 'O':
return np.NaN, np.NaN
else:
return finite_range(column, column.min(), column.max())
@classmethod
def values(cls, dataset, dim, expanded=True, flat=True, compute=True,
keep_index=False):
dim = dataset.get_dimension(dim, strict=True)
data = dataset.data[dim.name]
if not expanded:
data = data.unique()
return data.values_host if compute else data.values
elif keep_index:
return data
elif compute:
return data.values_host
try:
return data.values
except Exception:
return data.values_host
@classmethod
def groupby(cls, dataset, dimensions, container_type, group_type, **kwargs):
# Get dimensions information
dimensions = [dataset.get_dimension(d).name for d in dimensions]
kdims = [kdim for kdim in dataset.kdims if kdim not in dimensions]
# Update the kwargs appropriately for Element group types
group_kwargs = {}
group_type = dict if group_type == 'raw' else group_type
if issubclass(group_type, Element):
group_kwargs.update(util.get_param_values(dataset))
group_kwargs['kdims'] = kdims
group_kwargs.update(kwargs)
# Propagate dataset
group_kwargs['dataset'] = dataset.dataset
# Find all the keys along supplied dimensions
keys = product(*(dataset.data[dimensions[0]].unique().values_host for d in dimensions))
# Iterate over the unique entries applying selection masks
grouped_data = []
for unique_key in util.unique_iterator(keys):
group_data = dataset.select(**dict(zip(dimensions, unique_key)))
if not len(group_data):
continue
group_data = group_type(group_data, **group_kwargs)
grouped_data.append((unique_key, group_data))
if issubclass(container_type, NdMapping):
with item_check(False), sorted_context(False):
kdims = [dataset.get_dimension(d) for d in dimensions]
return container_type(grouped_data, kdims=kdims)
else:
return container_type(grouped_data)
@classmethod
def select_mask(cls, dataset, selection):
"""
Given a Dataset object and a dictionary with dimension keys and
selection keys (i.e. tuple ranges, slices, sets, lists, or literals)
return a boolean mask over the rows in the Dataset object that
have been selected.
"""
mask = None
for dim, sel in selection.items():
if isinstance(sel, tuple):
sel = slice(*sel)
arr = cls.values(dataset, dim, keep_index=True)
if util.isdatetime(arr) and util.pd:
try:
sel = util.<API key>(sel)
except:
pass
new_masks = []
if isinstance(sel, slice):
with warnings.catch_warnings():
warnings.filterwarnings('ignore', r'invalid value encountered')
if sel.start is not None:
new_masks.append(sel.start <= arr)
if sel.stop is not None:
new_masks.append(arr < sel.stop)
if not new_masks:
continue
new_mask = new_masks[0]
for imask in new_masks[1:]:
new_mask &= imask
elif isinstance(sel, (set, list)):
for v in sel:
new_masks.append(arr==v)
if not new_masks:
continue
new_mask = new_masks[0]
for imask in new_masks[1:]:
new_mask |= imask
elif callable(sel):
new_mask = sel(arr)
else:
new_mask = arr == sel
if mask is None:
mask = new_mask
else:
mask &= new_mask
return mask
@classmethod
def select(cls, dataset, selection_mask=None, **selection):
df = dataset.data
if selection_mask is None:
selection_mask = cls.select_mask(dataset, selection)
indexed = cls.indexed(dataset, selection)
if selection_mask is not None:
df = df.loc[selection_mask]
if indexed and len(df) == 1 and len(dataset.vdims) == 1:
return df[dataset.vdims[0].name].iloc[0]
return df
@classmethod
def concat_fn(cls, dataframes, **kwargs):
import cudf
return cudf.concat(dataframes, **kwargs)
@classmethod
def add_dimension(cls, dataset, dimension, dim_pos, values, vdim):
data = dataset.data.copy()
if dimension.name not in data:
data[dimension.name] = values
return data
@classmethod
def aggregate(cls, dataset, dimensions, function, **kwargs):
data = dataset.data
cols = [d.name for d in dataset.kdims if d in dimensions]
vdims = dataset.dimensions('value', label='name')
reindexed = data[cols+vdims]
agg = function.__name__
if len(dimensions):
agg_map = {'amin': 'min', 'amax': 'max'}
agg = agg_map.get(agg, agg)
grouped = reindexed.groupby(cols, sort=False)
if not hasattr(grouped, agg):
raise ValueError('%s aggregation is not supported on cudf DataFrame.' % agg)
df = getattr(grouped, agg)().reset_index()
else:
agg_map = {'amin': 'min', 'amax': 'max', 'size': 'count'}
agg = agg_map.get(agg, agg)
if not hasattr(reindexed, agg):
raise ValueError('%s aggregation is not supported on cudf DataFrame.' % agg)
agg = getattr(reindexed, agg)()
data = dict(((col, [v]) for col, v in zip(agg.index.values_host, agg.to_array())))
df = util.pd.DataFrame(data, columns=list(agg.index.values_host))
dropped = []
for vd in vdims:
if vd not in df.columns:
dropped.append(vd)
return df, dropped
@classmethod
def iloc(cls, dataset, index):
import cudf
rows, cols = index
scalar = False
columns = list(dataset.data.columns)
if isinstance(cols, slice):
cols = [d.name for d in dataset.dimensions()][cols]
elif np.isscalar(cols):
scalar = np.isscalar(rows)
cols = [dataset.get_dimension(cols).name]
else:
cols = [dataset.get_dimension(d).name for d in index[1]]
col_index = [columns.index(c) for c in cols]
if np.isscalar(rows):
rows = [rows]
if scalar:
return dataset.data[cols[0]].iloc[rows[0]]
result = dataset.data.iloc[rows, col_index]
# cuDF does not handle single rows and cols indexing correctly
# as of cudf=0.10.0 so we have to convert Series back to DataFrame
if isinstance(result, cudf.Series):
if len(cols) == 1:
result = result.to_frame(cols[0])
else:
result = result.to_frame().T
return result
@classmethod
def sort(cls, dataset, by=[], reverse=False):
cols = [dataset.get_dimension(d, strict=True).name for d in by]
return dataset.data.sort_values(by=cols, ascending=not reverse)
@classmethod
def dframe(cls, dataset, dimensions):
if dimensions:
return dataset.data[dimensions].to_pandas()
else:
return dataset.data.to_pandas()
Interface.register(cuDFInterface)
|
using System;
using OpenViewer.Model;
namespace OpenViewer.UI
{
public abstract class UIBase : IUI
{
protected MetaverseSession m_model;
public abstract string GetName();
public abstract void Initialize(MetaverseSession model, string renderingEngine, string loginURI, string username, string password);
public abstract void Run();
}
}
|
<?php
return array(
'router' => array(
'routes' => array(
// The following is a route to simplify getting started creating
// new controllers and actions without needing to create a new
// module. Simply drop new controllers in, and you can access them
// using the path /api/:controller/:action
'api' => array(
'type' => 'Hostname',
'options' => array(
'route' => 'api.vuongquocbalo.com',
),
),
),
),
);
|
<?php
namespace Jazzee\Element;
class Phonenumber extends TextInput
{
const PAGEBUILDER_SCRIPT = 'resource/scripts/element_types/<API key>.js';
public function addToField(\Foundation\Form\Field $field)
{
$element = $field->newElement('TextInput', 'el' . $this->_element->getId());
$element->setLabel($this->_element->getTitle());
$element->setInstructions($this->_element->getInstructions());
$element->setFormat($this->_element->getFormat());
$element->setDefaultValue($this->_element->getDefaultValue());
if ($this->_element->isRequired()) {
$validator = new \Foundation\Form\Validator\NotEmpty($element);
$element->addValidator($validator);
}
$validator = new \Foundation\Form\Validator\Phonenumber($element);
$element->addValidator($validator);
$filter = new \Foundation\Form\Filter\Phonenumber($element);
$element->addFilter($filter);
return $element;
}
}
|
# for
for i in 1..10 do
puts i
end
|
# modification, are permitted provided that the following conditions are met:
# and/or other materials provided with the distribution.
# - Neither the Indiana University nor the names of its contributors may be used
# to endorse or promote products derived from this software without specific
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# 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.
from corepy.spre.spe import Instruction, DispatchInstruction, Register
from spu_insts import *
__doc__="""
ISA for the Cell Broadband Engine's SPU.
"""
class lqx(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':452}
cycles = (1, 6, 0)
class stqx(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':324}
cycles = (1, 6, 0)
class cbx(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':468}
cycles = (1, 4, 0)
class chx(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':469}
cycles = (1, 4, 0)
class cwx(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':470}
cycles = (1, 4, 0)
class cdx(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':471}
cycles = (1, 4, 0)
class ah(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':200}
cycles = (0, 2, 0)
class a(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':192}
cycles = (0, 2, 0)
class sfh(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':72}
cycles = (0, 2, 0)
class sf(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':64}
cycles = (0, 2, 0)
class addx(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':832}
cycles = (0, 2, 0)
class cg(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':194}
cycles = (0, 2, 0)
class cgx(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':834}
cycles = (0, 2, 0)
class sfx(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':833}
cycles = (0, 2, 0)
class bg(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':66}
cycles = (0, 2, 0)
class bgx(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':835}
cycles = (0, 2, 0)
class mpy(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':964}
cycles = (0, 7, 0)
class mpyu(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':972}
cycles = (0, 7, 0)
class mpyh(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':965}
cycles = (0, 7, 0)
class mpys(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':967}
cycles = (0, 7, 0)
class mpyhh(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':966}
cycles = (0, 7, 0)
class mpyhha(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':838}
cycles = (0, 7, 0)
class mpyhhu(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':974}
cycles = (0, 7, 0)
class mpyhhau(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':846}
cycles = (0, 7, 0)
class clz(Instruction):
machine_inst = OPCD_A_T
params = {'OPCD':677}
cycles = (0, 2, 0)
class cntb(Instruction):
machine_inst = OPCD_A_T
params = {'OPCD':692}
cycles = (0, 4, 0)
class fsmb(Instruction):
machine_inst = OPCD_A_T
params = {'OPCD':438}
cycles = (1, 4, 0)
class fsmh(Instruction):
machine_inst = OPCD_A_T
params = {'OPCD':437}
cycles = (1, 4, 0)
class fsm(Instruction):
machine_inst = OPCD_A_T
params = {'OPCD':436}
cycles = (1, 4, 0)
class gbb(Instruction):
machine_inst = OPCD_A_T
params = {'OPCD':434}
cycles = (1, 4, 0)
class gbh(Instruction):
machine_inst = OPCD_A_T
params = {'OPCD':433}
cycles = (1, 4, 0)
class gb(Instruction):
machine_inst = OPCD_A_T
params = {'OPCD':432}
cycles = (1, 4, 0)
class avgb(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':211}
cycles = (0, 4, 0)
class absdb(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':83}
cycles = (0, 4, 0)
class sumb(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':595}
cycles = (0, 4, 0)
class xsbh(Instruction):
machine_inst = OPCD_A_T
params = {'OPCD':694}
cycles = (0, 2, 0)
class xshw(Instruction):
machine_inst = OPCD_A_T
params = {'OPCD':686}
cycles = (0, 2, 0)
class xswd(Instruction):
machine_inst = OPCD_A_T
params = {'OPCD':678}
cycles = (0, 2, 0)
class and_(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':193}
cycles = (0, 2, 0)
class andc(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':705}
cycles = (0, 2, 0)
class or_(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':65}
cycles = (0, 2, 0)
class orc(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':713}
cycles = (0, 2, 0)
class orx(Instruction):
machine_inst = OPCD_A_T
params = {'OPCD':496}
cycles = (1, 4, 0)
class xor(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':577}
cycles = (0, 2, 0)
class nand(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':201}
cycles = (0, 2, 0)
class nor(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':73}
cycles = (0, 2, 0)
class eqv(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':585}
cycles = (0, 2, 0)
class shlh(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':95}
cycles = (0, 4, 0)
class shl(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':91}
cycles = (0, 4, 0)
class shlqbi(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':475}
cycles = (1, 4, 0)
class shlqby(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':479}
cycles = (1, 4, 0)
class shlqbybi(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':463}
cycles = (1, 4, 0)
class roth(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':92}
cycles = (0, 4, 0)
class rot(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':88}
cycles = (0, 4, 0)
class rotqby(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':476}
cycles = (1, 4, 0)
class rotqbybi(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':460}
cycles = (1, 4, 0)
class rotqbi(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':472}
cycles = (1, 4, 0)
class rothm(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':93}
cycles = (0, 4, 0)
class rotm(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':89}
cycles = (0, 4, 0)
class rotqmby(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':477}
cycles = (1, 4, 0)
class rotqmbybi(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':461}
cycles = (1, 4, 0)
class rotqmbi(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':473}
cycles = (1, 4, 0)
class rotmah(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':94}
cycles = (0, 4, 0)
class rotma(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':90}
cycles = (0, 4, 0)
class heq(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':984}
cycles = (0, 2, 0)
class hgt(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':600}
cycles = (0, 2, 0)
class hlgt(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':728}
cycles = (0, 2, 0)
class ceqb(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':976}
cycles = (0, 2, 0)
class ceqh(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':968}
cycles = (0, 2, 0)
class ceq(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':960}
cycles = (0, 2, 0)
class cgtb(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':592}
cycles = (0, 2, 0)
class cgth(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':584}
cycles = (0, 2, 0)
class cgt(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':576}
cycles = (0, 2, 0)
class clgtb(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':720}
cycles = (0, 2, 0)
class clgth(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':712}
cycles = (0, 2, 0)
class clgt(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':704}
cycles = (0, 2, 0)
class bi(Instruction):
machine_inst = OPCD_A_D_E
params = {'OPCD':424}
cycles = (1, 4, 0)
class iret(Instruction):
machine_inst = OPCD_A_D_E
params = {'OPCD':426}
cycles = (1, 4, 0)
class bisled(Instruction):
machine_inst = OPCD_A_T_D_E
params = {'OPCD':427}
cycles = (1, 4, 0)
class bisl(Instruction):
machine_inst = OPCD_A_T_D_E
params = {'OPCD':425}
cycles = (1, 4, 0)
class biz(Instruction):
machine_inst = OPCD_A_T_D_E
params = {'OPCD':296}
cycles = (1, 4, 0)
class binz(Instruction):
machine_inst = OPCD_A_T_D_E
params = {'OPCD':297}
cycles = (1, 4, 0)
class bihz(Instruction):
machine_inst = OPCD_A_T_D_E
params = {'OPCD':294}
cycles = (1, 4, 0)
class bihnz(Instruction):
machine_inst = OPCD_A_T_D_E
params = {'OPCD':299}
cycles = (1, 4, 0)
# TODO - can we check that if P is set then RO is zero as required?
class hbr(DispatchInstruction):
cycles = (1, 15, 0)
dispatch = (
(OPCD_RO_A_P, {'OPCD':428}),
(OPCD_LBL9_A_P, {'OPCD':428}))
class fa(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':708}
cycles = (0, 6, 0)
class dfa(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':716}
cycles = (0, 13, 6)
class fs(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':709}
cycles = (0, 6, 0)
class dfs(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':717}
cycles = (0, 13, 6)
class fm(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':710}
cycles = (0, 6, 0)
class dfm(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':718}
cycles = (0, 13, 6)
class dfma(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':860}
cycles = (0, 13, 6)
class dfnms(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':862}
cycles = (0, 13, 6)
class dfms(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':861}
cycles = (0, 13, 6)
class dfnma(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':863}
cycles = (0, 13, 6)
class frest(Instruction):
machine_inst = OPCD_A_T
params = {'OPCD':440}
cycles = (1, 4, 0)
class frsqest(Instruction):
machine_inst = OPCD_A_T
params = {'OPCD':441}
cycles = (1, 4, 0)
class fi(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':980}
cycles = (0, 7, 0)
class frds(Instruction):
machine_inst = OPCD_A_T
params = {'OPCD':953}
cycles = (0, 13, 6)
class fesd(Instruction):
machine_inst = OPCD_A_T
params = {'OPCD':952}
cycles = (0, 13, 6)
class fceq(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':962}
cycles = (0, 2, 0)
class fcmeq(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':970}
cycles = (0, 2, 0)
class fcgt(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':706}
cycles = (0, 2, 0)
class fcmgt(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':714}
cycles = (0, 2, 0)
class fscrwr(Instruction):
machine_inst = OPCD_A_T
params = {'OPCD':954}
cycles = (0, 7, 0)
class fscrrd(Instruction):
machine_inst = OPCD_T
params = {'OPCD':920}
cycles = (0, 13, 6)
class stop(Instruction):
machine_inst = OPCD_STOP_SIG
params = {'OPCD':0}
cycles = (1, 4, 0)
class stopd(Instruction):
machine_inst = OPCD_B_A_T
params = {'OPCD':320}
cycles = (1, 4, 0)
class lnop(Instruction):
machine_inst = OPCD
params = {'OPCD':1}
cycles = (1, 0, 0)
class nop(Instruction):
machine_inst = OPCD_T
params = {'OPCD':513}
cycles = (0, 0, 0)
class sync(Instruction):
machine_inst = OPCD_CF
params = {'OPCD':2}
cycles = (1, 4, 0)
class dsync(Instruction):
machine_inst = OPCD
params = {'OPCD':3}
cycles = (1, 4, 0)
class mfspr(Instruction):
machine_inst = OPCD_SA_T
params = {'OPCD':12}
cycles = (1, 6, 0)
class mtspr(Instruction):
machine_inst = OPCD_SA_T
params = {'OPCD':268}
cycles = (1, 6, 0)
class rdch(Instruction):
machine_inst = OPCD_A_T
params = {'OPCD':13}
cycles = (1, 6, 0)
class rchcnt(Instruction):
machine_inst = OPCD_A_T
params = {'OPCD':15}
cycles = (1, 6, 0)
class wrch(Instruction):
machine_inst = OPCD_A_T
params = {'OPCD':269}
cycles = (1, 6, 0)
class mpya(Instruction):
machine_inst = OPCD_T_B_A_C
params = {'OPCD':12}
cycles = (0, 7, 0)
class selb(Instruction):
machine_inst = OPCD_T_B_A_C
params = {'OPCD':8}
cycles = (0, 2, 0)
class shufb(Instruction):
machine_inst = OPCD_T_B_A_C
params = {'OPCD':11}
cycles = (1, 4, 0)
class fma(Instruction):
machine_inst = OPCD_T_B_A_C
params = {'OPCD':14}
cycles = (0, 6, 0)
class fnms(Instruction):
machine_inst = OPCD_T_B_A_C
params = {'OPCD':13}
cycles = (0, 6, 0)
class fms(Instruction):
machine_inst = OPCD_T_B_A_C
params = {'OPCD':15}
cycles = (0, 6, 0)
class cbd(Instruction):
machine_inst = OPCD_I7_A_T
params = {'OPCD':500}
cycles = (1, 4, 0)
class chd(Instruction):
machine_inst = OPCD_I7_A_T
params = {'OPCD':501}
cycles = (1, 4, 0)
class cwd(Instruction):
machine_inst = OPCD_I7_A_T
params = {'OPCD':502}
cycles = (1, 4, 0)
class cdd(Instruction):
machine_inst = OPCD_I7_A_T
params = {'OPCD':503}
cycles = (1, 4, 0)
class shlhi(Instruction):
machine_inst = OPCD_I7_A_T
params = {'OPCD':127}
cycles = (0, 4, 0)
class shli(Instruction):
machine_inst = OPCD_I7_A_T
params = {'OPCD':123}
cycles = (0, 4, 0)
class shlqbii(Instruction):
machine_inst = OPCD_I7_A_T
params = {'OPCD':507}
cycles = (1, 4, 0)
class shlqbyi(Instruction):
machine_inst = OPCD_I7_A_T
params = {'OPCD':511}
cycles = (1, 4, 0)
class rothi(Instruction):
machine_inst = OPCD_I7_A_T
params = {'OPCD':124}
cycles = (0, 4, 0)
class roti(Instruction):
machine_inst = OPCD_I7_A_T
params = {'OPCD':120}
cycles = (0, 4, 0)
class rotqbyi(Instruction):
machine_inst = OPCD_I7_A_T
params = {'OPCD':508}
cycles = (1, 4, 0)
class rotqbii(Instruction):
machine_inst = OPCD_I7_A_T
params = {'OPCD':504}
cycles = (1, 4, 0)
class rothmi(Instruction):
machine_inst = OPCD_I7_A_T
params = {'OPCD':125}
cycles = (0, 4, 0)
class rotmi(Instruction):
machine_inst = OPCD_I7_A_T
params = {'OPCD':121}
cycles = (0, 4, 0)
class rotqmbyi(Instruction):
machine_inst = OPCD_I7_A_T
params = {'OPCD':509}
cycles = (1, 4, 0)
class rotqmbii(Instruction):
machine_inst = OPCD_I7_A_T
params = {'OPCD':505}
cycles = (1, 4, 0)
class rotmahi(Instruction):
machine_inst = OPCD_I7_A_T
params = {'OPCD':126}
cycles = (0, 4, 0)
class rotmai(Instruction):
machine_inst = OPCD_I7_A_T
params = {'OPCD':122}
cycles = (0, 4, 0)
class csflt(Instruction):
machine_inst = OPCD_I8_A_T
params = {'OPCD':474}
cycles = (0, 7, 0)
class cflts(Instruction):
machine_inst = OPCD_I8_A_T
params = {'OPCD':472}
cycles = (0, 7, 0)
class cuflt(Instruction):
machine_inst = OPCD_I8_A_T
params = {'OPCD':475}
cycles = (0, 7, 0)
class cfltu(Instruction):
machine_inst = OPCD_I8_A_T
params = {'OPCD':473}
cycles = (0, 7, 0)
class lqd(Instruction):
machine_inst = OPCD_I10_A_T
params = {'OPCD':52}
cycles = (1, 6, 0)
class stqd(Instruction):
machine_inst = OPCD_I10_A_T
params = {'OPCD':36}
cycles = (1, 6, 0)
class ahi(Instruction):
machine_inst = OPCD_I10_A_T
params = {'OPCD':29}
cycles = (0, 2, 0)
class ai(Instruction):
machine_inst = OPCD_I10_A_T
params = {'OPCD':28}
cycles = (0, 2, 0)
class sfhi(Instruction):
machine_inst = OPCD_I10_A_T
params = {'OPCD':13}
cycles = (0, 2, 0)
class sfi(Instruction):
machine_inst = OPCD_I10_A_T
params = {'OPCD':12}
cycles = (0, 2, 0)
class mpyi(Instruction):
machine_inst = OPCD_I10_A_T
params = {'OPCD':116}
cycles = (0, 7, 0)
class mpyui(Instruction):
machine_inst = OPCD_I10_A_T
params = {'OPCD':117}
cycles = (0, 7, 0)
class andbi(Instruction):
machine_inst = OPCD_I10_A_T
params = {'OPCD':22}
cycles = (0, 2, 0)
class andhi(Instruction):
machine_inst = OPCD_I10_A_T
params = {'OPCD':21}
cycles = (0, 2, 0)
class andi(Instruction):
machine_inst = OPCD_I10_A_T
params = {'OPCD':20}
cycles = (0, 2, 0)
class orbi(Instruction):
machine_inst = OPCD_I10_A_T
params = {'OPCD':6}
cycles = (0, 2, 0)
class orhi(Instruction):
machine_inst = OPCD_I10_A_T
params = {'OPCD':5}
cycles = (0, 2, 0)
class ori(Instruction):
machine_inst = OPCD_I10_A_T
params = {'OPCD':4}
cycles = (0, 2, 0)
class xorbi(Instruction):
machine_inst = OPCD_I10_A_T
params = {'OPCD':70}
cycles = (0, 2, 0)
class xorhi(Instruction):
machine_inst = OPCD_I10_A_T
params = {'OPCD':69}
cycles = (0, 2, 0)
class xori(Instruction):
machine_inst = OPCD_I10_A_T
params = {'OPCD':68}
cycles = (0, 2, 0)
class heqi(Instruction):
machine_inst = OPCD_I10_A_T
params = {'OPCD':127}
cycles = (0, 2, 0)
class hgti(Instruction):
machine_inst = OPCD_I10_A_T
params = {'OPCD':79}
cycles = (0, 2, 0)
class hlgti(Instruction):
machine_inst = OPCD_I10_A_T
params = {'OPCD':95}
cycles = (0, 2, 0)
class ceqbi(Instruction):
machine_inst = OPCD_I10_A_T
params = {'OPCD':126}
cycles = (0, 2, 0)
class ceqhi(Instruction):
machine_inst = OPCD_I10_A_T
params = {'OPCD':125}
cycles = (0, 2, 0)
class ceqi(Instruction):
machine_inst = OPCD_I10_A_T
params = {'OPCD':124}
cycles = (0, 2, 0)
class cgtbi(Instruction):
machine_inst = OPCD_I10_A_T
params = {'OPCD':78}
cycles = (0, 2, 0)
class cgthi(Instruction):
machine_inst = OPCD_I10_A_T
params = {'OPCD':77}
cycles = (0, 2, 0)
class cgti(Instruction):
machine_inst = OPCD_I10_A_T
params = {'OPCD':76}
cycles = (0, 2, 0)
class clgtbi(Instruction):
machine_inst = OPCD_I10_A_T
params = {'OPCD':94}
cycles = (0, 2, 0)
class clgthi(Instruction):
machine_inst = OPCD_I10_A_T
params = {'OPCD':93}
cycles = (0, 2, 0)
class clgti(Instruction):
machine_inst = OPCD_I10_A_T
params = {'OPCD':92}
cycles = (0, 2, 0)
class lqa(Instruction):
machine_inst = OPCD_I16_T
params = {'OPCD':97}
cycles = (1, 6, 0)
class lqr(Instruction):
machine_inst = OPCD_I16_T
params = {'OPCD':103}
cycles = (1, 6, 0)
class stqa(Instruction):
machine_inst = OPCD_I16_T
params = {'OPCD':65}
cycles = (1, 6, 0)
class stqr(Instruction):
machine_inst = OPCD_I16_T
params = {'OPCD':71}
cycles = (1, 6, 0)
class ilh(Instruction):
machine_inst = OPCD_I16_T
params = {'OPCD':131}
cycles = (0, 2, 0)
class ilhu(Instruction):
machine_inst = OPCD_I16_T
params = {'OPCD':130}
cycles = (0, 2, 0)
class il(Instruction):
machine_inst = OPCD_I16_T
params = {'OPCD':129}
cycles = (0, 2, 0)
class iohl(Instruction):
machine_inst = OPCD_I16_T
params = {'OPCD':193}
cycles = (0, 2, 0)
class fsmbi(Instruction):
machine_inst = OPCD_I16_T
params = {'OPCD':101}
cycles = (1, 4, 0)
class br(DispatchInstruction):
cycles = (1, 4, 0)
dispatch = (
(OPCD_I16, {'OPCD':100}),
(OPCD_LBL16, {'OPCD':100}))
# TODO - how can I do absolute branches?
class bra(Instruction):
machine_inst = OPCD_I16
params = {'OPCD':96}
cycles = (1, 4, 0)
# TODO - I16 has two zero bits appended, do I handle this correctly?
# What is the correct way, anyway?
class brsl(DispatchInstruction):
cycles = (1, 4, 0)
dispatch = (
(OPCD_I16_T, {'OPCD':102}),
(OPCD_LBL16_T, {'OPCD':102}))
class brasl(Instruction):
machine_inst = OPCD_I16_T
params = {'OPCD':98}
cycles = (1, 4, 0)
class brnz(DispatchInstruction):
cycles = (1, 4, 0)
dispatch = (
(OPCD_I16_T, {'OPCD':66}),
(OPCD_LBL16_T, {'OPCD':66}))
class brz(DispatchInstruction):
cycles = (1, 4, 0)
dispatch = (
(OPCD_I16_T, {'OPCD':64}),
(OPCD_LBL16_T, {'OPCD':64}))
class brhnz(DispatchInstruction):
cycles = (1, 4, 0)
dispatch = (
(OPCD_I16, {'OPCD':70}),
(OPCD_LBL16, {'OPCD':70}))
class brhz(DispatchInstruction):
cycles = (1, 4, 0)
dispatch = (
(OPCD_I16, {'OPCD':68}),
(OPCD_LBL16, {'OPCD':68}))
class hbra(Instruction):
machine_inst = OPCD_LBL9_I16
params = {'OPCD':8}
cycles = (1, 15, 0)
class hbrr(DispatchInstruction):
cycles = (1, 15, 0)
dispatch = (
(OPCD_ROA_I16, {'OPCD':9}),
(OPCD_LBL9_LBL16, {'OPCD':9}))
class ila(Instruction):
machine_inst = OPCD_I18_T
params = {'OPCD':33}
cycles = (0, 2, 0)
|
package gov.hhs.fha.nhinc.patientdiscovery.inbound.deferred.request;
import gov.hhs.fha.nhinc.aspect.<API key>;
import gov.hhs.fha.nhinc.common.nhinccommon.AssertionType;
import gov.hhs.fha.nhinc.nhinclib.NhincConstants;
import gov.hhs.fha.nhinc.patientdiscovery.<API key>;
import gov.hhs.fha.nhinc.patientdiscovery.adapter.deferred.request.proxy.<API key>;
import gov.hhs.fha.nhinc.patientdiscovery.adapter.deferred.request.proxy.<API key>;
import gov.hhs.fha.nhinc.patientdiscovery.aspect.<API key>;
import gov.hhs.fha.nhinc.patientdiscovery.aspect.<API key>;
import org.hl7.v3.MCCIIN000002UV01;
import org.hl7.v3.PRPAIN201305UV02;
public abstract class <API key> implements <API key> {
private final <API key> adapterFactory;
public <API key>(<API key> factory) {
adapterFactory = factory;
}
abstract MCCIIN000002UV01 process(PRPAIN201305UV02 request, AssertionType assertion);
abstract <API key> getAuditLogger();
/**
* Processes the PD Deferred request message. This call will audit the message and send it to the Nhin.
*
* @param request
* @param assertion
* @return MCCIIN000002UV01
*/
@<API key>(beforeBuilder = <API key>.class,
<API key> = <API key>.class,
serviceType = "Patient Discovery Deferred Request",
version = "1.0")
public MCCIIN000002UV01 <API key>(PRPAIN201305UV02 request, AssertionType assertion) {
<API key>(request, assertion);
MCCIIN000002UV01 response = process(request, assertion);
auditResponseToNhin(response, assertion);
return response;
}
protected MCCIIN000002UV01 sendToAdapter(PRPAIN201305UV02 request, AssertionType assertion) {
<API key> proxy = adapterFactory.<API key>();
return proxy.<API key>(request, assertion);
}
private void <API key>(PRPAIN201305UV02 request, AssertionType assertion) {
getAuditLogger().<API key>(request, assertion, NhincConstants.<API key>);
}
private void auditResponseToNhin(MCCIIN000002UV01 response, AssertionType assertion) {
getAuditLogger().auditAck(response, assertion, NhincConstants.<API key>,
NhincConstants.<API key>);
}
protected void <API key>(PRPAIN201305UV02 request, AssertionType assertion) {
getAuditLogger().<API key>(request, assertion, NhincConstants.<API key>);
}
protected void <API key>(MCCIIN000002UV01 response, AssertionType assertion) {
getAuditLogger().auditAck(response, assertion, NhincConstants.<API key>,
NhincConstants.<API key>);
}
}
|
import * as fs from "fs"
import * as path from "path"
import * as ts from "typescript"
const coffee = require("coffeescript")
const less = require("less")
import {argv} from "yargs"
import {collect_deps} from "./dependencies"
const mkCoffeescriptError = (error: any, file?: string) => {
const message = error.message
if (error.location == null) {
const text = [file || "<string>", message].join(":")
return {message, text}
} else {
const location = error.location
const line = location.first_line + 1
const column = location.first_column + 1
const text = [file || "<string>", line, column, message].join(":")
let markerLen = 2
if (location.first_line === location.last_line)
markerLen += location.last_column - location.first_column
const extract = error.code.split('\n')[line - 1]
const annotated = [
text,
" " + extract,
" " + Array(column).join(' ') + Array(markerLen).join('^'),
].join('\n')
return {message, line, column, text, extract, annotated}
}
}
const mkLessError = (error: any, file?: string) => {
const message = error.message
const line = error.line
const column = error.column + 1
const text = [file || "<string>", line, column, message].join(":")
const extract = error.extract[line]
const annotated = [text, " " + extract].join("\n")
return {message, line, column, text, extract, annotated}
}
const reply = (data: any) => {
process.stdout.write(JSON.stringify(data))
process.stdout.write("\n")
}
type Files = {[name: string]: string}
function compile_typescript(inputs: Files, bokehjs_dir: string): {outputs: Files, error?: string} {
const options: ts.CompilerOptions = {
noImplicitAny: true,
noImplicitThis: true,
noImplicitReturns: true,
noUnusedLocals: true,
noUnusedParameters: true,
strictNullChecks: true,
strictBindCallApply: false,
strictFunctionTypes: false,
<API key>: false,
alwaysStrict: true,
noErrorTruncation: true,
noEmitOnError: false,
declaration: false,
sourceMap: false,
importHelpers: false,
<API key>: true,
module: ts.ModuleKind.CommonJS,
moduleResolution: ts.<API key>.NodeJs,
target: ts.ScriptTarget.ES5,
lib: [
"lib.es5.d.ts",
"lib.dom.d.ts",
"lib.es2015.core.d.ts",
"lib.es2015.promise.d.ts",
"lib.es2015.symbol.d.ts",
"lib.es2015.iterable.d.ts",
],
types: [],
baseUrl: ".",
paths: {
"*": [
|
# -*- coding: utf-8 -*-
# modification, are permitted provided that the following conditions are met:
# documentation and/or other materials provided with the distribution.
# may be used to endorse or promote products derived from this software without
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# 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.
from .fetchers import <API key>
from .fetchers import NUMetadatasFetcher
from .fetchers import <API key>
from bambou import NURESTObject
class NUVMResync(NURESTObject):
""" Represents a VMResync in the VSD
Notes:
Provide information about the state of a VM resync request.
"""
__rest_name__ = "resync"
__resource_name__ = "resync"
## Constants
<API key> = "IN_PROGRESS"
<API key> = "GLOBAL"
<API key> = "SUCCESS"
<API key> = "ENTERPRISE"
def __init__(self, **kwargs):
""" Initializes a VMResync instance
Notes:
You can specify all parameters while calling this methods.
A special argument named `data` will enable you to load the
object from a Python dictionary
Examples:
vmresync = NUVMResync(id=u'xxxx-xxx-xxx-xxx', name=u'VMResync')
vmresync = NUVMResync(data=my_dict)
"""
super(NUVMResync, self).__init__()
# Read/Write Attributes
self.<API key> = None
self.<API key> = None
self._last_updated_by = None
self._last_updated_date = None
self._embedded_metadata = None
self._entity_scope = None
self._creation_date = None
self._status = None
self._owner = None
self._external_id = None
self.expose_attribute(local_name="<API key>", remote_name="<API key>", attribute_type=int, is_required=False, is_unique=False)
self.expose_attribute(local_name="<API key>", remote_name="<API key>", attribute_type=int, is_required=False, is_unique=False)
self.expose_attribute(local_name="last_updated_by", remote_name="lastUpdatedBy", attribute_type=str, is_required=False, is_unique=False)
self.expose_attribute(local_name="last_updated_date", remote_name="lastUpdatedDate", attribute_type=str, is_required=False, is_unique=False)
self.expose_attribute(local_name="embedded_metadata", remote_name="embeddedMetadata", attribute_type=list, is_required=False, is_unique=False)
self.expose_attribute(local_name="entity_scope", remote_name="entityScope", attribute_type=str, is_required=False, is_unique=False, choices=[u'ENTERPRISE', u'GLOBAL'])
self.expose_attribute(local_name="creation_date", remote_name="creationDate", attribute_type=str, is_required=False, is_unique=False)
self.expose_attribute(local_name="status", remote_name="status", attribute_type=str, is_required=False, is_unique=False, choices=[u'IN_PROGRESS', u'SUCCESS'])
self.expose_attribute(local_name="owner", remote_name="owner", attribute_type=str, is_required=False, is_unique=False)
self.expose_attribute(local_name="external_id", remote_name="externalID", attribute_type=str, is_required=False, is_unique=True)
# Fetchers
self.permissions = <API key>.fetcher_with_object(parent_object=self, relationship="child")
self.metadatas = NUMetadatasFetcher.fetcher_with_object(parent_object=self, relationship="child")
self.global_metadatas = <API key>.fetcher_with_object(parent_object=self, relationship="child")
self._compute_args(**kwargs)
# Properties
@property
def <API key>(self):
""" Get <API key> value.
Notes:
Time of the last timestamp received
This attribute is named `<API key>` in VSD API.
"""
return self.<API key>
@<API key>.setter
def <API key>(self, value):
""" Set <API key> value.
Notes:
Time of the last timestamp received
This attribute is named `<API key>` in VSD API.
"""
self.<API key> = value
@property
def <API key>(self):
""" Get <API key> value.
Notes:
Time that the resync was initiated
This attribute is named `<API key>` in VSD API.
"""
return self.<API key>
@<API key>.setter
def <API key>(self, value):
""" Set <API key> value.
Notes:
Time that the resync was initiated
This attribute is named `<API key>` in VSD API.
"""
self.<API key> = value
@property
def last_updated_by(self):
""" Get last_updated_by value.
Notes:
ID of the user who last updated the object.
This attribute is named `lastUpdatedBy` in VSD API.
"""
return self._last_updated_by
@last_updated_by.setter
def last_updated_by(self, value):
""" Set last_updated_by value.
Notes:
ID of the user who last updated the object.
This attribute is named `lastUpdatedBy` in VSD API.
"""
self._last_updated_by = value
@property
def last_updated_date(self):
""" Get last_updated_date value.
Notes:
Time stamp when this object was last updated.
This attribute is named `lastUpdatedDate` in VSD API.
"""
return self._last_updated_date
@last_updated_date.setter
def last_updated_date(self, value):
""" Set last_updated_date value.
Notes:
Time stamp when this object was last updated.
This attribute is named `lastUpdatedDate` in VSD API.
"""
self._last_updated_date = value
@property
def embedded_metadata(self):
""" Get embedded_metadata value.
Notes:
Metadata objects associated with this entity. This will contain a list of Metadata objects if the API request is made using the special flag to enable the embedded Metadata feature. Only a maximum of Metadata objects is returned based on the value set in the system configuration.
This attribute is named `embeddedMetadata` in VSD API.
"""
return self._embedded_metadata
@embedded_metadata.setter
def embedded_metadata(self, value):
""" Set embedded_metadata value.
Notes:
Metadata objects associated with this entity. This will contain a list of Metadata objects if the API request is made using the special flag to enable the embedded Metadata feature. Only a maximum of Metadata objects is returned based on the value set in the system configuration.
This attribute is named `embeddedMetadata` in VSD API.
"""
self._embedded_metadata = value
@property
def entity_scope(self):
""" Get entity_scope value.
Notes:
Specify if scope of entity is Data center or Enterprise level
This attribute is named `entityScope` in VSD API.
"""
return self._entity_scope
@entity_scope.setter
def entity_scope(self, value):
""" Set entity_scope value.
Notes:
Specify if scope of entity is Data center or Enterprise level
This attribute is named `entityScope` in VSD API.
"""
self._entity_scope = value
@property
def creation_date(self):
""" Get creation_date value.
Notes:
Time stamp when this object was created.
This attribute is named `creationDate` in VSD API.
"""
return self._creation_date
@creation_date.setter
def creation_date(self, value):
""" Set creation_date value.
Notes:
Time stamp when this object was created.
This attribute is named `creationDate` in VSD API.
"""
self._creation_date = value
@property
def status(self):
""" Get status value.
Notes:
Status of the resync
"""
return self._status
@status.setter
def status(self, value):
""" Set status value.
Notes:
Status of the resync
"""
self._status = value
@property
def owner(self):
""" Get owner value.
Notes:
Identifies the user that has created this object.
"""
return self._owner
@owner.setter
def owner(self, value):
""" Set owner value.
Notes:
Identifies the user that has created this object.
"""
self._owner = value
@property
def external_id(self):
""" Get external_id value.
Notes:
External object ID. Used for integration with third party systems
This attribute is named `externalID` in VSD API.
"""
return self._external_id
@external_id.setter
def external_id(self, value):
""" Set external_id value.
Notes:
External object ID. Used for integration with third party systems
This attribute is named `externalID` in VSD API.
"""
self._external_id = value
|
from mock import patch
from nose.tools import eq_
from helper import TestCase
import appvalidator.submain as submain
class TestSubmainPackage(TestCase):
@patch("appvalidator.submain.test_inner_package",
lambda x, z: "success")
def test_package_pass(self):
"Tests the test_package function with simple data"
self.setup_err()
name = "tests/resources/submain/install_rdf.xpi"
with open(name) as pack:
result = submain.test_package(self.err, pack, name)
self.assert_silent()
eq_(result, "success")
@patch("appvalidator.submain.test_inner_package",
lambda x, z: "success")
def <API key>(self):
"Tests the test_package function fails with a non-zip"
self.setup_err()
name = "tests/resources/junk.xpi"
with open(name) as pack:
result = submain.test_package(self.err, pack, name)
self.assert_failed()
def <API key>(self):
"Tests the test_package function fails with a corrupt file"
self.setup_err()
name = "tests/resources/corrupt.xpi"
result = submain.test_package(self.err, name, name)
self.assert_failed(with_errors=True, with_warnings=True)
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="scaffolded-by" content="https://github.com/google/stagehand">
<title>futures_api</title>
<link rel="stylesheet" href="styles.css">
<link rel="icon" href="favicon.ico">
<script defer src="main.dart.js"></script>
</head>
<body>
<div id="output"></div>
</body>
</html>
|
Directory for interactive development of c2po plots.
Install deps via:
bundle install
then run
bundle exec guard
execute some of the code in `scratch.rb` and view your plots at `http://localhost:3000/`.
|
package com.mistraltech.smogen.codegenerator.javabuilder;
public class <API key> extends <API key><<API key>> {
private <API key>() {
}
public static <API key> anInterfaceMethod() {
return new <API key>();
}
@Override
public String build(JavaBuilderContext context) {
return super.build(context) + ";";
}
}
|
#ifndef <API key>
#define <API key>
#include <stdint.h>
#include <string>
#include <vector>
#include "base/logging.h"
#include "build/build_config.h"
#include "components/cloud_devices/common/description_items.h"
// Defines printer options, CDD and CJT items.
namespace cloud_devices {
namespace printer {
struct <API key>;
class <API key>;
typedef SelectionCapability<<API key>,
<API key>>
<API key>;
typedef std::string ContentType;
struct Copies {
// Default requested number of copies.
int32_t default_value = 1;
// Maximum number of copies supported, sourced from
// <API key>.copies_max.
int32_t max_value = 1;
};
enum class DocumentSheetBack {
NORMAL,
ROTATED,
MANUAL_TUMBLE,
FLIPPED,
};
enum class <API key> {
SGRAY_8 = 22,
SRGB_8 = 23,
};
struct PwgRasterConfig {
PwgRasterConfig();
~PwgRasterConfig();
std::vector<<API key>> <API key>;
DocumentSheetBack document_sheet_back;
bool <API key>;
bool rotate_all_pages;
};
class <API key> {
public:
enum class ValueType {
FLOAT,
INTEGER,
};
<API key>();
<API key>(ValueType value_type,
const std::string& min_value,
const std::string& max_value);
<API key>(ValueType value_type,
const std::string& min_value,
const std::string& max_value,
const std::string& default_value);
<API key>(<API key>&& other);
~<API key>();
<API key>& operator=(<API key>&& other);
bool operator==(const <API key>& other) const;
bool operator!=(const <API key>& other) const {
return !(*this == other);
}
bool IsValid() const;
bool LoadFrom(const base::Value& dict);
void SaveTo(base::Value* dict) const;
private:
ValueType value_type_;
std::string min_value_;
std::string max_value_;
std::string default_value_;
<API key>(<API key>);
};
struct <API key> {
<API key>();
<API key>(const std::string& value,
const std::string& display_name);
~<API key>();
bool IsValid() const;
bool operator==(const <API key>& other) const;
bool operator!=(const <API key>& other) const {
return !(*this == other);
}
std::string value;
std::string display_name;
};
class <API key> {
public:
enum class ValueType {
BOOLEAN,
FLOAT,
INTEGER,
STRING,
};
<API key>();
explicit <API key>(ValueType value_type);
<API key>(ValueType value_type,
const std::string& default_value);
<API key>(<API key>&& other);
~<API key>();
<API key>& operator=(<API key>&& other);
bool operator==(const <API key>& other) const;
bool operator!=(const <API key>& other) const {
return !(*this == other);
}
bool IsValid() const;
bool LoadFrom(const base::Value& dict);
void SaveTo(base::Value* dict) const;
private:
ValueType value_type_;
std::string default_value_;
<API key>(<API key>);
};
class VendorCapability {
public:
enum class Type {
NONE,
RANGE,
SELECT,
TYPED_VALUE,
};
VendorCapability();
VendorCapability(const std::string& id,
const std::string& display_name,
<API key> range_capability);
VendorCapability(const std::string& id,
const std::string& display_name,
<API key> select_capability);
VendorCapability(const std::string& id,
const std::string& display_name,
<API key> <API key>);
VendorCapability(VendorCapability&& other);
~VendorCapability();
bool operator==(const VendorCapability& other) const;
bool operator!=(const VendorCapability& other) const {
return !(*this == other);
}
bool IsValid() const;
bool LoadFrom(const base::Value& dict);
void SaveTo(base::Value* dict) const;
private:
void InternalCleanup();
Type type_;
std::string id_;
std::string display_name_;
// If the CDD is valid, exactly one of the capabilities has a value.
union {
<API key> range_capability_;
<API key> select_capability_;
<API key> <API key>;
};
<API key>(VendorCapability);
};
enum class ColorType {
STANDARD_COLOR,
STANDARD_MONOCHROME,
CUSTOM_COLOR,
CUSTOM_MONOCHROME,
AUTO_COLOR,
};
struct Color {
Color();
explicit Color(ColorType type);
bool IsValid() const;
bool operator==(const Color& other) const;
bool operator!=(const Color& other) const { return !(*this == other); }
ColorType type;
std::string vendor_id;
std::string custom_display_name;
};
enum class DuplexType {
NO_DUPLEX,
LONG_EDGE,
SHORT_EDGE,
};
enum class OrientationType {
PORTRAIT,
LANDSCAPE,
AUTO_ORIENTATION,
};
enum class MarginsType {
NO_MARGINS,
STANDARD_MARGINS,
CUSTOM_MARGINS,
};
struct Margins {
Margins();
Margins(MarginsType type,
int32_t top_um,
int32_t right_um,
int32_t bottom_um,
int32_t left_um);
bool operator==(const Margins& other) const;
bool operator!=(const Margins& other) const { return !(*this == other); }
MarginsType type;
int32_t top_um;
int32_t right_um;
int32_t bottom_um;
int32_t left_um;
};
struct Dpi {
Dpi();
Dpi(int32_t horizontal, int32_t vertical);
bool IsValid() const;
bool operator==(const Dpi& other) const;
bool operator!=(const Dpi& other) const { return !(*this == other); }
int32_t horizontal;
int32_t vertical;
};
enum class FitToPageType {
NO_FITTING,
FIT_TO_PAGE,
GROW_TO_PAGE,
SHRINK_TO_PAGE,
FILL_PAGE,
};
enum class MediaType {
CUSTOM_MEDIA,
// North American standard sheet media names.
NA_INDEX_3X5,
NA_PERSONAL,
NA_MONARCH,
NA_NUMBER_9,
NA_INDEX_4X6,
NA_NUMBER_10,
NA_A2,
NA_NUMBER_11,
NA_NUMBER_12,
NA_5X7,
NA_INDEX_5X8,
NA_NUMBER_14,
NA_INVOICE,
NA_INDEX_4X6_EXT,
NA_6X9,
NA_C5,
NA_7X9,
NA_EXECUTIVE,
NA_GOVT_LETTER,
NA_GOVT_LEGAL,
NA_QUARTO,
NA_LETTER,
NA_FANFOLD_EUR,
NA_LETTER_PLUS,
NA_FOOLSCAP,
NA_LEGAL,
NA_SUPER_A,
NA_9X11,
NA_ARCH_A,
NA_LETTER_EXTRA,
NA_LEGAL_EXTRA,
NA_10X11,
NA_10X13,
NA_10X14,
NA_10X15,
NA_11X12,
NA_EDP,
NA_FANFOLD_US,
NA_11X15,
NA_LEDGER,
NA_EUR_EDP,
NA_ARCH_B,
NA_12X19,
NA_B_PLUS,
NA_SUPER_B,
NA_C,
NA_ARCH_C,
NA_D,
NA_ARCH_D,
NA_ASME_F,
NA_WIDE_FORMAT,
NA_E,
NA_ARCH_E,
NA_F,
// Chinese standard sheet media size names.
ROC_16K,
ROC_8K,
PRC_32K,
PRC_1,
PRC_2,
PRC_4,
PRC_5,
PRC_8,
PRC_6,
PRC_3,
PRC_16K,
PRC_7,
OM_JUURO_KU_KAI,
OM_PA_KAI,
OM_DAI_PA_KAI,
PRC_10,
// ISO standard sheet media size names.
ISO_A10,
ISO_A9,
ISO_A8,
ISO_A7,
ISO_A6,
ISO_A5,
ISO_A5_EXTRA,
ISO_A4,
ISO_A4_TAB,
ISO_A4_EXTRA,
ISO_A3,
ISO_A4X3,
ISO_A4X4,
ISO_A4X5,
ISO_A4X6,
ISO_A4X7,
ISO_A4X8,
ISO_A4X9,
ISO_A3_EXTRA,
ISO_A2,
ISO_A3X3,
ISO_A3X4,
ISO_A3X5,
ISO_A3X6,
ISO_A3X7,
ISO_A1,
ISO_A2X3,
ISO_A2X4,
ISO_A2X5,
ISO_A0,
ISO_A1X3,
ISO_A1X4,
ISO_2A0,
ISO_A0X3,
ISO_B10,
ISO_B9,
ISO_B8,
ISO_B7,
ISO_B6,
ISO_B6C4,
ISO_B5,
ISO_B5_EXTRA,
ISO_B4,
ISO_B3,
ISO_B2,
ISO_B1,
ISO_B0,
ISO_C10,
ISO_C9,
ISO_C8,
ISO_C7,
ISO_C7C6,
ISO_C6,
ISO_C6C5,
ISO_C5,
ISO_C4,
ISO_C3,
ISO_C2,
ISO_C1,
ISO_C0,
ISO_DL,
ISO_RA2,
ISO_SRA2,
ISO_RA1,
ISO_SRA1,
ISO_RA0,
ISO_SRA0,
// Japanese standard sheet media size names.
JIS_B10,
JIS_B9,
JIS_B8,
JIS_B7,
JIS_B6,
JIS_B5,
JIS_B4,
JIS_B3,
JIS_B2,
JIS_B1,
JIS_B0,
JIS_EXEC,
JPN_CHOU4,
JPN_HAGAKI,
JPN_YOU4,
JPN_CHOU2,
JPN_CHOU3,
JPN_OUFUKU,
JPN_KAHU,
JPN_KAKU2,
// Other metric standard sheet media size names.
OM_SMALL_PHOTO,
OM_ITALIAN,
OM_POSTFIX,
OM_LARGE_PHOTO,
OM_FOLIO,
OM_FOLIO_SP,
OM_INVITE,
};
struct Media {
Media();
explicit Media(MediaType type);
Media(MediaType type, int32_t width_um, int32_t height_um);
Media(const std::string& custom_display_name,
const std::string& vendor_id,
int32_t width_um,
int32_t height_um);
Media(const Media& other);
bool MatchBySize();
bool IsValid() const;
bool operator==(const Media& other) const;
bool operator!=(const Media& other) const { return !(*this == other); }
MediaType type;
int32_t width_um;
int32_t height_um;
bool is_continuous_feed;
std::string custom_display_name;
std::string vendor_id;
};
struct Interval {
Interval();
Interval(int32_t start, int32_t end);
explicit Interval(int32_t start);
bool operator==(const Interval& other) const;
bool operator!=(const Interval& other) const { return !(*this == other); }
int32_t start;
int32_t end;
};
typedef std::vector<Interval> PageRange;
class ContentTypeTraits;
class <API key>;
class <API key>;
class ColorTraits;
class DuplexTraits;
class OrientationTraits;
class MarginsTraits;
class DpiTraits;
class FitToPageTraits;
class MediaTraits;
class PageRangeTraits;
class CollateTraits;
class <API key>;
class <API key>;
typedef ListCapability<ContentType, ContentTypeTraits> <API key>;
typedef ValueCapability<PwgRasterConfig, <API key>>
<API key>;
typedef ListCapability<VendorCapability, <API key>>
VendorCapabilities;
typedef SelectionCapability<Color, ColorTraits> ColorCapability;
typedef SelectionCapability<DuplexType, DuplexTraits> DuplexCapability;
typedef SelectionCapability<OrientationType, OrientationTraits>
<API key>;
typedef SelectionCapability<Margins, MarginsTraits> MarginsCapability;
typedef SelectionCapability<Dpi, DpiTraits> DpiCapability;
typedef SelectionCapability<FitToPageType, FitToPageTraits> FitToPageCapability;
typedef SelectionCapability<Media, MediaTraits> MediaCapability;
typedef ValueCapability<Copies, class <API key>> CopiesCapability;
typedef EmptyCapability<class PageRangeTraits> PageRangeCapability;
typedef BooleanCapability<class CollateTraits> CollateCapability;
typedef BooleanCapability<class ReverseTraits> ReverseCapability;
#if defined(OS_CHROMEOS)
// This capability is not a part of standard CDD description. It's used for
// providing PIN printing opportunity in Chrome OS native printing.
typedef ValueCapability<bool, class PinTraits> PinCapability;
#endif // defined(OS_CHROMEOS)
typedef TicketItem<PwgRasterConfig, <API key>>
<API key>;
typedef TicketItem<Color, ColorTraits> ColorTicketItem;
typedef TicketItem<DuplexType, DuplexTraits> DuplexTicketItem;
typedef TicketItem<OrientationType, OrientationTraits> <API key>;
typedef TicketItem<Margins, MarginsTraits> MarginsTicketItem;
typedef TicketItem<Dpi, DpiTraits> DpiTicketItem;
typedef TicketItem<FitToPageType, FitToPageTraits> FitToPageTicketItem;
typedef TicketItem<Media, MediaTraits> MediaTicketItem;
typedef TicketItem<int32_t, <API key>> CopiesTicketItem;
typedef TicketItem<PageRange, PageRangeTraits> PageRangeTicketItem;
typedef TicketItem<bool, CollateTraits> CollateTicketItem;
typedef TicketItem<bool, ReverseTraits> ReverseTicketItem;
} // namespace printer
} // namespace cloud_devices
#endif // <API key>
|
class ProductTag < ActiveRecord::Base
has_attached_file :icon,
:url => "/assets/product_tags/:id/:basename.:extension",
:path => ":rails_root/public/assets/product_tags/:id/:basename.:extension"
validates :name, :presence => true, :uniqueness => true
has_many :products
end
|
"use strict"
function <API key>(config:Object) : Object {
let mentionBotEnvConfig;
try {
mentionBotEnvConfig = JSON.parse(process.env.MENTION_BOT_CONFIG);
} catch(e) {
mentionBotEnvConfig = {};
}
return Object.keys(config).reduce((previousValue, key) => {
let defaultConfigValue = config[key];
let environmentVariable = mentionBotEnvConfig[key];
let configElement = {};
configElement[key] = environmentVariable === undefined ? defaultConfigValue
: environmentVariable;
return {...previousValue, ...configElement};
}, {});
}
module.exports = {
<API key>
}
|
#include "cc/resources/<API key>.h"
#include "base/debug/trace_event.h"
#include "base/time.h"
#include "cc/debug/<API key>.h"
#include "cc/resources/layer_painter.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkPaint.h"
#include "third_party/skia/include/core/SkRect.h"
#include "third_party/skia/include/core/SkScalar.h"
#include "ui/gfx/rect_conversions.h"
#include "ui/gfx/rect_f.h"
namespace cc {
ContentLayerUpdater::ContentLayerUpdater(
scoped_ptr<LayerPainter> painter,
<API key>* <API key>)
: <API key>(<API key>),
painter_(painter.Pass()) {}
ContentLayerUpdater::~ContentLayerUpdater() {}
void ContentLayerUpdater::PaintContents(SkCanvas* canvas,
gfx::Rect content_rect,
float <API key>,
float <API key>,
gfx::Rect* <API key>,
RenderingStats* stats) {
TRACE_EVENT0("cc", "ContentLayerUpdater::PaintContents");
canvas->save();
canvas->translate(SkFloatToScalar(-content_rect.x()),
SkFloatToScalar(-content_rect.y()));
gfx::Rect layer_rect = content_rect;
if (<API key> != 1.f || <API key> != 1.f) {
canvas->scale(SkFloatToScalar(<API key>),
SkFloatToScalar(<API key>));
gfx::RectF rect = gfx::ScaleRect(
content_rect, 1.f / <API key>, 1.f / <API key>);
layer_rect = gfx::ToEnclosingRect(rect);
}
SkPaint paint;
paint.setAntiAlias(false);
paint.setXfermodeMode(SkXfermode::kClear_Mode);
SkRect layer_sk_rect = SkRect::MakeXYWH(
layer_rect.x(), layer_rect.y(), layer_rect.width(), layer_rect.height());
canvas->drawRect(layer_sk_rect, paint);
canvas->clipRect(layer_sk_rect);
gfx::RectF opaque_layer_rect;
base::TimeTicks paint_begin_time;
if (stats)
paint_begin_time = base::TimeTicks::Now();
painter_->Paint(canvas, layer_rect, &opaque_layer_rect);
if (stats) {
stats->total_paint_time += base::TimeTicks::Now() - paint_begin_time;
stats-><API key> += content_rect.width() * content_rect.height();
}
canvas->restore();
gfx::RectF opaque_content_rect = gfx::ScaleRect(
opaque_layer_rect, <API key>, <API key>);
*<API key> = gfx::ToEnclosedRect(opaque_content_rect);
content_rect_ = content_rect;
}
} // namespace cc
|
# Aplicacion de las TIC basadas en Fuentes Abiertas, Spain.
# modification, are permitted provided that the following conditions
# are met:
# the documentation and/or other materials provided with the
# distribution.
# Neither the name of the CENATIC nor the names of its contributors
# may be used to endorse or promote products derived from this
# "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
# 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.
# de Servicios Sociales: C/ Vistahermosa, 1, 3ra planta, 06200
# Almendralejo (Badajoz), Spain
from DBSlayer import Query
def get_type_name (type_id):
l = get_type (type_id)
if not l:
return None
return l['name']
def get_type (type_id):
q = "SELECT id, type "\
"FROM asset_types WHERE id=%(type_id)s;" % locals()
query = Query(q)
if len(query) != 1:
return None
ret = {'id': type_id,
'name': query['type'][0]}
return ret
def get_types ():
q = "SELECT id, type "\
"FROM asset_types;" % locals()
query = Query(q)
if not len(query):
return None
ret = []
for x in query:
d={'id': query[x]['id'],
'name': query[x]['type']}
ret.append(d)
return ret
def test ():
import sys
try:
type_id = sys.argv[1]
except IndexError:
print 'Required test parameters: type_id'
sys.exit(1)
print 'Types:', get_types()
print 'type_id %s, type_name %s' % (type_id, get_type_name(type_id))
print get_type(type_id),
if __name__ == '__main__':
test()
|
# -*- coding: utf-8 -*-
'''
Production Configurations
- Use djangosecure
- Use mailgun to send emails
- Use redis
'''
from __future__ import absolute_import, unicode_literals
from django.utils import six
from .common import * # noqa
# SECRET CONFIGURATION
# Raises <API key> exception if DJANO_SECRET_KEY not in os.environ
SECRET_KEY = env("DJANGO_SECRET_KEY")
# This ensures that Django will be able to detect a secure connection
# properly on Heroku.
<API key> = ('<API key>', 'https')
# django-secure
INSTALLED_APPS += ("djangosecure", )
MIDDLEWARE_CLASSES = (
# Make sure djangosecure.middleware.SecurityMiddleware is listed first
'djangosecure.middleware.SecurityMiddleware',
) + MIDDLEWARE_CLASSES
# set this to 60 seconds and then to 518400 when you can prove it works
SECURE_HSTS_SECONDS = 60
<API key> = env.bool("<API key>", default=True)
SECURE_FRAME_DENY = env.bool("<API key>", default=True)
<API key> = env.bool("<API key>", default=True)
<API key> = True
<API key> = False
<API key> = True
SECURE_SSL_REDIRECT = env.bool("<API key>", default=True)
# SITE CONFIGURATION
# Hosts/domain names that are valid for this site
ALLOWED_HOSTS = ["*"]
# END SITE CONFIGURATION
# EMAIL
DEFAULT_FROM_EMAIL = env('<API key>',
default='{{cookiecutter.project_name}} <noreply@{{cookiecutter.domain_name}}>')
EMAIL_BACKEND = 'django_mailgun.MailgunBackend'
MAILGUN_ACCESS_KEY = env('<API key>')
MAILGUN_SERVER_NAME = env('<API key>')
<API key> = env("<API key>", default='[{{cookiecutter.project_name}}] ')
SERVER_EMAIL = env('DJANGO_SERVER_EMAIL', default=DEFAULT_FROM_EMAIL)
# TEMPLATE CONFIGURATION
TEMPLATES[0]['OPTIONS']['loaders'] = [
('django.template.loaders.cached.Loader', [
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
]),
]
# CACHE CONFIGURATION
CACHES = {
'default': {
'BACKEND': 'redis_cache.RedisCache',
'LOCATION': [
'redis:6379',
],
'OPTIONS': {
'DB': 1,
'PARSER_CLASS': 'redis.connection.HiredisParser',
'<API key>': 'redis.<API key>',
'<API key>': {
'max_connections': 50,
'timeout': 20,
},
'MAX_CONNECTIONS': 1000,
'PICKLE_VERSION': -1,
},
},
}
# ASSET CONFIGURATION
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATIC_ROOT = '/static'
MEDIA_ROOT = '/media'
STATICFILES_DIRS = (
unicode(APPS_DIR.path("static")),
)
{% if cookiecutter.use_celery %}
# CELERY BROKER CONFIGURATION
BROKER_URL = "amqp://guest:guest@rabbitmq:5672//"
{% endif %}
{% if cookiecutter.use_sentry %}
# SENTRY CONFIGURATION
RAVEN_CONFIG = {
'dsn': env("SENTRY_URL"),
}
INSTALLED_APPS = INSTALLED_APPS + (
'raven.contrib.django.raven_compat',
)
{% endif %}
# Your production stuff: Below this line define 3rd party library settings
|
package org.chromium.chrome.browser.sync;
import android.test.FlakyTest;
import android.test.suitebuilder.annotation.LargeTest;
import android.util.Pair;
import org.chromium.base.ThreadUtils;
import org.chromium.base.test.util.Feature;
import org.chromium.chrome.browser.ChromeApplication;
import org.chromium.chrome.browser.tabmodel.TabModelSelector;
import org.chromium.chrome.browser.tabmodel.TabModelUtils;
import org.chromium.chrome.browser.util.FeatureUtilities;
import org.chromium.chrome.test.util.browser.sync.SyncTestUtil;
import org.chromium.content.browser.test.util.Criteria;
import org.chromium.sync.protocol.EntitySpecifics;
import org.chromium.sync.protocol.SessionHeader;
import org.chromium.sync.protocol.SessionSpecifics;
import org.chromium.sync.protocol.SessionTab;
import org.chromium.sync.protocol.SessionWindow;
import org.chromium.sync.protocol.SyncEnums;
import org.chromium.sync.protocol.TabNavigation;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
/**
* Test suite for the open tabs (sessions) sync data type.
*/
public class OpenTabsTest extends SyncTestBase {
private static final String TAG = "OpenTabsTest";
private static final String OPEN_TABS_TYPE = "Sessions";
// EmbeddedTestServer is preferred here but it can't be used. The test server
// serves pages on localhost and Chrome doesn't sync localhost URLs as typed URLs.
// This type of URL requires no external data connection or resources.
private static final String URL = "data:text,OpenTabsTestURL";
private static final String URL2 = "data:text,OpenTabsTestURL2";
private static final String URL3 = "data:text,OpenTabsTestURL3";
private static final String SESSION_TAG_PREFIX = "FakeSessionTag";
private static final String FAKE_CLIENT = "FakeClient";
// The client name for tabs generated locally will vary based on the device the test is
// running on, so it is determined once in the setUp() method and cached here.
private String mClientName;
// A counter used for generating unique session tags. Resets to 0 in setUp().
private int mSessionTagCounter;
// A container to store OpenTabs information for data verification.
private static class OpenTabs {
public final String headerId;
public final List<String> tabIds;
public final List<String> urls;
private OpenTabs(String headerId, List<String> tabIds, List<String> urls) {
this.headerId = headerId;
this.tabIds = tabIds;
this.urls = urls;
}
}
@Override
protected void setUp() throws Exception {
super.setUp();
<API key>();
mClientName = getClientName();
mSessionTagCounter = 0;
}
// Test syncing an open tab from client to server.
@LargeTest
@Feature({"Sync"})
public void testUploadOpenTab() throws Exception {
loadUrl(URL);
<API key>(mClientName, URL);
waitForServerTabs(URL);
}
@FlakyTest
public void <API key>() throws Exception {
loadUrl(URL);
loadUrlInNewTab(URL2);
loadUrlInNewTab(URL3);
<API key>(mClientName, URL, URL2, URL3);
waitForServerTabs(URL, URL2, URL3);
}
@FlakyTest
public void <API key>() throws Exception {
loadUrl(URL);
// Can't have zero tabs, so we have to open two to test closing one.
loadUrlInNewTab(URL2);
<API key>(mClientName, URL, URL2);
waitForServerTabs(URL, URL2);
ThreadUtils.<API key>(new Runnable() {
@Override
public void run() {
TabModelSelector selector = FeatureUtilities.isDocumentMode(getActivity())
? ChromeApplication.<API key>()
: getActivity().getTabModelSelector();
assertTrue(TabModelUtils.closeCurrentTab(selector.getCurrentModel()));
}
});
<API key>(mClientName, URL);
waitForServerTabs(URL);
}
// Test syncing an open tab from server to client.
@LargeTest
@Feature({"Sync"})
public void testDownloadOpenTab() throws Exception {
addFakeServerTabs(FAKE_CLIENT, URL);
SyncTestUtil.triggerSync();
<API key>(FAKE_CLIENT, URL);
}
// Test syncing multiple open tabs from server to client.
@LargeTest
@Feature({"Sync"})
public void <API key>() throws Exception {
addFakeServerTabs(FAKE_CLIENT, URL, URL2, URL3);
SyncTestUtil.triggerSync();
<API key>(FAKE_CLIENT, URL, URL2, URL3);
}
// Test syncing a tab deletion from server to client.
@LargeTest
@Feature({"Sync"})
public void <API key>() throws Exception {
// Add the entity to test deleting.
addFakeServerTabs(FAKE_CLIENT, URL);
SyncTestUtil.triggerSync();
<API key>(FAKE_CLIENT, URL);
// Delete on server, sync, and verify deleted locally.
<API key>(FAKE_CLIENT);
SyncTestUtil.triggerSync();
<API key>(FAKE_CLIENT);
}
// Test syncing multiple tab deletions from server to client.
@LargeTest
@Feature({"Sync"})
public void <API key>() throws Exception {
// Add the entity to test deleting.
addFakeServerTabs(FAKE_CLIENT, URL, URL2, URL3);
SyncTestUtil.triggerSync();
<API key>(FAKE_CLIENT, URL, URL2, URL3);
// Delete on server, sync, and verify deleted locally.
<API key>(FAKE_CLIENT);
SyncTestUtil.triggerSync();
<API key>(FAKE_CLIENT);
}
private String makeSessionTag() {
return SESSION_TAG_PREFIX + (mSessionTagCounter++);
}
private void addFakeServerTabs(String clientName, String... urls)
throws <API key> {
String tag = makeSessionTag();
EntitySpecifics header = makeSessionEntity(tag, clientName, urls.length);
mFakeServerHelper.<API key>(tag, header);
for (int i = 0; i < urls.length; i++) {
EntitySpecifics tab = makeTabEntity(tag, urls[i], i);
// It is critical that the name here is "<tag> <tabNodeId>", otherwise sync crashes
// when it tries to sync due to the use of TabIdToTag in <API key>.cc.
mFakeServerHelper.<API key>(tag + " " + i, tab);
}
}
private EntitySpecifics makeSessionEntity(String tag, String clientName, int numTabs) {
EntitySpecifics specifics = new EntitySpecifics();
specifics.session = new SessionSpecifics();
specifics.session.sessionTag = tag;
specifics.session.header = new SessionHeader();
specifics.session.header.clientName = clientName;
specifics.session.header.deviceType = SyncEnums.TYPE_PHONE;
SessionWindow window = new SessionWindow();
window.windowId = 0;
window.selectedTabIndex = 0;
window.tab = new int[numTabs];
for (int i = 0; i < numTabs; i++) {
window.tab[i] = i;
}
specifics.session.header.window = new SessionWindow[] { window };
return specifics;
}
private EntitySpecifics makeTabEntity(String tag, String url, int id) {
EntitySpecifics specifics = new EntitySpecifics();
specifics.session = new SessionSpecifics();
specifics.session.sessionTag = tag;
specifics.session.tabNodeId = id;
SessionTab tab = new SessionTab();
tab.tabId = id;
tab.<API key> = 0;
TabNavigation nav = new TabNavigation();
nav.virtualUrl = url;
tab.navigation = new TabNavigation[] { nav };
specifics.session.tab = tab;
return specifics;
}
private void <API key>(String clientName) throws JSONException {
OpenTabs openTabs = <API key>(clientName);
mFakeServerHelper.deleteEntity(openTabs.headerId);
for (String tabId : openTabs.tabIds) {
mFakeServerHelper.deleteEntity(tabId);
}
}
private void <API key>(final String clientName, String... urls)
throws <API key> {
final List<String> urlList = new ArrayList<String>(urls.length);
for (String url : urls) urlList.add(url);
<API key>(Criteria.equals(urlList, new Callable<List<String>>() {
@Override
public List<String> call() throws Exception {
return <API key>(clientName).urls;
}
}));
}
private void waitForServerTabs(final String... urls)
throws <API key> {
<API key>(
new Criteria("Expected server open tabs: " + Arrays.toString(urls)) {
@Override
public boolean isSatisfied() {
try {
return mFakeServerHelper.verifySessions(urls);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
});
}
private String getClientName() throws Exception {
<API key>(Criteria.equals(2, new Callable<Integer>() {
@Override
public Integer call() throws Exception {
return SyncTestUtil.getLocalData(mContext, OPEN_TABS_TYPE).size();
}
}));
List<Pair<String, JSONObject>> tabEntities = SyncTestUtil.getLocalData(
mContext, OPEN_TABS_TYPE);
for (Pair<String, JSONObject> tabEntity : tabEntities) {
if (tabEntity.second.has("header")) {
return tabEntity.second.getJSONObject("header").getString("client_name");
}
}
throw new <API key>("No client name found.");
}
private static class HeaderInfo {
public final String sessionTag;
public final String headerId;
public final List<String> tabIds;
public HeaderInfo(String sessionTag, String headerId, List<String> tabIds) {
this.sessionTag = sessionTag;
this.headerId = headerId;
this.tabIds = tabIds;
}
}
// Distills the local session data into a simple data object for the given client.
private OpenTabs <API key>(String clientName) throws JSONException {
List<Pair<String, JSONObject>> tabEntities = SyncTestUtil.getLocalData(
mContext, OPEN_TABS_TYPE);
// Output lists.
List<String> urls = new ArrayList<String>();
List<String> tabEntityIds = new ArrayList<String>();
HeaderInfo info = <API key>(clientName, tabEntities);
if (info.sessionTag == null) {
// No client was found. Here we still want to return an empty list of urls.
return new OpenTabs("", tabEntityIds, urls);
}
Map<String, String> tabIdsToUrls = new HashMap<String, String>();
Map<String, String> tabIdsToEntityIds = new HashMap<String, String>();
findTabMappings(info.sessionTag, tabEntities, tabIdsToUrls, tabIdsToEntityIds);
// Convert the tabId list to the url list.
for (String tabId : info.tabIds) {
urls.add(tabIdsToUrls.get(tabId));
tabEntityIds.add(tabIdsToEntityIds.get(tabId));
}
return new OpenTabs(info.headerId, tabEntityIds, urls);
}
// Find the header entity for clientName and extract its sessionTag and tabId list.
private HeaderInfo <API key>(
String clientName, List<Pair<String, JSONObject>> tabEntities) throws JSONException {
String sessionTag = null;
String headerId = null;
List<String> tabIds = new ArrayList<String>();
for (Pair<String, JSONObject> tabEntity : tabEntities) {
JSONObject header = tabEntity.second.optJSONObject("header");
if (header != null && header.getString("client_name").equals(clientName)) {
sessionTag = tabEntity.second.getString("session_tag");
headerId = tabEntity.first;
JSONArray windows = header.getJSONArray("window");
if (windows.length() == 0) {
// The client was found but there are no tabs.
break;
}
assertEquals("Only single windows are supported.", 1, windows.length());
JSONArray tabs = windows.getJSONObject(0).getJSONArray("tab");
for (int i = 0; i < tabs.length(); i++) {
tabIds.add(tabs.getString(i));
}
break;
}
}
return new HeaderInfo(sessionTag, headerId, tabIds);
}
// Find the associated tabs and record their tabId -> url and entityId mappings.
private void findTabMappings(String sessionTag, List<Pair<String, JSONObject>> tabEntities,
// Populating these maps is the output of this function.
Map<String, String> tabIdsToUrls, Map<String, String> tabIdsToEntityIds)
throws JSONException {
for (Pair<String, JSONObject> tabEntity : tabEntities) {
JSONObject json = tabEntity.second;
if (json.has("tab") && json.getString("session_tag").equals(sessionTag)) {
JSONObject tab = json.getJSONObject("tab");
int i = tab.getInt("<API key>");
String tabId = tab.getString("tab_id");
String url = tab.getJSONArray("navigation")
.getJSONObject(i).getString("virtual_url");
tabIdsToUrls.put(tabId, url);
tabIdsToEntityIds.put(tabId, tabEntity.first);
}
}
}
}
|
#include "chrome/browser/password_manager/password_store_mac.h"
#include "base/basictypes.h"
#include "base/files/scoped_temp_dir.h"
#include "base/scoped_observer.h"
#include "base/stl_util.h"
#include "base/strings/string_util.h"
#include "base/strings/<API key>.h"
#include "base/synchronization/waitable_event.h"
#include "base/test/histogram_tester.h"
#include "base/<API key>.h"
#include "chrome/browser/password_manager/<API key>.h"
#include "chrome/common/chrome_paths.h"
#include "components/os_crypt/os_crypt.h"
#include "components/password_manager/core/browser/login_database.h"
#include "components/password_manager/core/browser/<API key>.h"
#include "components/password_manager/core/browser/<API key>.h"
#include "content/public/test/test_browser_thread.h"
#include "content/public/test/test_utils.h"
#include "crypto/mock_apple_keychain.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using autofill::PasswordForm;
using base::ASCIIToUTF16;
using base::WideToUTF16;
using content::BrowserThread;
using crypto::MockAppleKeychain;
using <API key>::FormsMatchForMerge;
using <API key>::STRICT_FORM_MATCH;
using password_manager::Create<API key>;
using password_manager::LoginDatabase;
using password_manager::PasswordFormData;
using password_manager::PasswordStore;
using password_manager::PasswordStoreChange;
using password_manager::<API key>;
using password_manager::<API key>;
using testing::_;
using testing::DoAll;
using testing::Invoke;
using testing::IsEmpty;
using testing::SizeIs;
using testing::WithArg;
namespace {
ACTION(QuitUIMessageLoop) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
base::MessageLoop::current()->Quit();
}
// From the mock's argument #0 of type const std::vector<PasswordForm*>& takes
// the first form and copies it to the form pointed to by |target_form_ptr|.
ACTION_P(<API key>, target_form_ptr) {
ASSERT_FALSE(arg0.empty());
*target_form_ptr = *arg0[0];
}
void Noop() {
}
class <API key> : public <API key> {
public:
MOCK_METHOD1(OnGet<API key>,
void(const std::vector<PasswordForm*>&));
// GMock cannot mock methods with move-only args.
void <API key>(ScopedVector<PasswordForm> results) override {
OnGet<API key>(results.get());
}
};
class <API key> : public PasswordStore::Observer {
public:
MOCK_METHOD1(OnLoginsChanged,
void(const password_manager::<API key>& changes));
};
// A LoginDatabase that simulates an Init() method that takes a long time.
class <API key> : public password_manager::LoginDatabase {
public:
// Creates an instance whose Init() method will block until |event| is
// signaled. |event| must outlive |this|.
<API key>(const base::FilePath& db_path,
base::WaitableEvent* event)
: password_manager::LoginDatabase(db_path), event_(event) {}
~<API key>() override {}
// LoginDatabase:
bool Init() override {
event_->Wait();
return password_manager::LoginDatabase::Init();
}
private:
base::WaitableEvent* event_;
<API key>(<API key>);
};
#pragma mark -
// Macro to simplify calling <API key> with a useful label.
#define CHECK_FORMS(forms, expectations, i) \
<API key>(forms, expectations, #forms, i)
// Ensures that the data in |forms| match |expectations|, causing test failures
// for any discrepencies.
// TODO(stuartmorgan): This is current order-dependent; ideally it shouldn't
// matter if |forms| and |expectations| are scrambled.
void <API key>(
const std::vector<PasswordForm*>& forms,
const std::vector<PasswordFormData*>& expectations,
const char* forms_label, unsigned int test_number) {
EXPECT_EQ(expectations.size(), forms.size()) << forms_label << " in test "
<< test_number;
if (expectations.size() != forms.size())
return;
for (unsigned int i = 0; i < expectations.size(); ++i) {
SCOPED_TRACE(testing::Message() << forms_label << " in test " << test_number
<< ", item " << i);
PasswordForm* form = forms[i];
PasswordFormData* expectation = expectations[i];
EXPECT_EQ(expectation->scheme, form->scheme);
EXPECT_EQ(std::string(expectation->signon_realm), form->signon_realm);
EXPECT_EQ(GURL(expectation->origin), form->origin);
EXPECT_EQ(GURL(expectation->action), form->action);
EXPECT_EQ(WideToUTF16(expectation->submit_element), form->submit_element);
EXPECT_EQ(WideToUTF16(expectation->username_element),
form->username_element);
EXPECT_EQ(WideToUTF16(expectation->password_element),
form->password_element);
if (expectation->username_value) {
EXPECT_EQ(WideToUTF16(expectation->username_value), form->username_value);
EXPECT_EQ(WideToUTF16(expectation->username_value), form->display_name);
EXPECT_TRUE(form->skip_zero_click);
if (expectation->password_value &&
wcscmp(expectation->password_value,
password_manager::<API key>) == 0) {
EXPECT_TRUE(form->password_value.empty());
EXPECT_EQ(GURL(password_manager::<API key>),
form->federation_url);
} else {
EXPECT_EQ(WideToUTF16(expectation->password_value),
form->password_value);
EXPECT_TRUE(form->federation_url.is_empty());
}
} else {
EXPECT_TRUE(form->blacklisted_by_user);
}
EXPECT_EQ(expectation->preferred, form->preferred);
EXPECT_EQ(expectation->ssl_valid, form->ssl_valid);
EXPECT_DOUBLE_EQ(expectation->creation_time,
form->date_created.ToDoubleT());
base::Time created = base::Time::FromDoubleT(expectation->creation_time);
EXPECT_EQ(
created + base::TimeDelta::FromDays(
password_manager::<API key>),
form->date_synced);
EXPECT_EQ(GURL(password_manager::kTestingIconUrlSpec), form->icon_url);
}
}
<API key> AddChangeForForm(const PasswordForm& form) {
return <API key>(
1, PasswordStoreChange(PasswordStoreChange::ADD, form));
}
} // namespace
#pragma mark -
class <API key> : public testing::Test {
public:
void SetUp() override {
MockAppleKeychain::KeychainTestData test_data[] = {
// Basic HTML form.
{kSec<API key>,
"some.domain.com",
<API key>,
NULL,
0,
NULL,
"20020601171500Z",
"joe_user",
"sekrit",
false},
// HTML form with path.
{kSec<API key>,
"some.domain.com",
<API key>,
"/insecure.html",
0,
NULL,
"19991231235959Z",
"joe_user",
"sekrit",
false},
// Secure HTML form with path.
{kSec<API key>,
"some.domain.com",
<API key>,
"/secure.html",
0,
NULL,
"20100908070605Z",
"secure_user",
"password",
false},
// True negative item.
{kSec<API key>,
"dont.remember.com",
<API key>,
NULL,
0,
NULL,
"20000101000000Z",
"",
"",
true},
// De-facto negative item, type one.
{kSec<API key>,
"dont.remember.com",
<API key>,
NULL,
0,
NULL,
"20000101000000Z",
"Password Not Stored",
"",
false},
// De-facto negative item, type two.
{kSec<API key>,
"dont.remember.com",
<API key>,
NULL,
0,
NULL,
"20000101000000Z",
"Password Not Stored",
" ",
false},
// HTTP auth basic, with port and path.
{kSec<API key>,
"some.domain.com",
<API key>,
"/insecure.html",
4567,
"low_security",
"19980330100000Z",
"basic_auth_user",
"basic",
false},
// HTTP auth digest, secure.
{kSec<API key>,
"some.domain.com",
<API key>,
NULL,
0,
"high_security",
"19980330100000Z",
"digest_auth_user",
"digest",
false},
// An FTP password with an invalid date, for edge-case testing.
{kSec<API key>,
"a.server.com",
kSecProtocolTypeFTP,
NULL,
0,
NULL,
"20010203040",
"abc",
"123",
false},
// Password for an Android application.
{kSec<API key>,
"android://hash@com.domain.some/",
<API key>,
"",
0,
NULL,
"20150515141312Z",
"joe_user",
"secret",
false},
};
keychain_ = new MockAppleKeychain();
for (unsigned int i = 0; i < arraysize(test_data); ++i) {
keychain_->AddTestItem(test_data[i]);
}
}
void TearDown() override {
<API key>();
<API key>();
delete keychain_;
}
protected:
// Causes a test failure unless everything returned from keychain_'s
// <API key>, <API key>, and SearchCopyNext
// was correctly freed.
void <API key>() {
EXPECT_EQ(0, keychain_->UnfreedSearchCount());
EXPECT_EQ(0, keychain_-><API key>());
EXPECT_EQ(0, keychain_-><API key>());
}
// Causes a test failure unless any Keychain items added during the test have
// their creator code set.
void <API key>() {
EXPECT_TRUE(keychain_-><API key>());
}
MockAppleKeychain* keychain_;
};
#pragma mark -
TEST_F(<API key>, <API key>) {
typedef struct {
const PasswordForm::Scheme scheme;
const char* signon_realm;
const char* origin;
const wchar_t* username; // Set to NULL to check for a blacklist entry.
const wchar_t* password;
const bool ssl_valid;
const int creation_year;
const int creation_month;
const int creation_day;
const int creation_hour;
const int creation_minute;
const int creation_second;
} TestExpectations;
TestExpectations expected[] = {
{ PasswordForm::SCHEME_HTML, "http://some.domain.com/",
"http://some.domain.com/", L"joe_user", L"sekrit", false,
2002, 6, 1, 17, 15, 0 },
{ PasswordForm::SCHEME_HTML, "http://some.domain.com/",
"http://some.domain.com/insecure.html", L"joe_user", L"sekrit", false,
1999, 12, 31, 23, 59, 59 },
{ PasswordForm::SCHEME_HTML, "https://some.domain.com/",
"https://some.domain.com/secure.html", L"secure_user", L"password", true,
2010, 9, 8, 7, 6, 5 },
{ PasswordForm::SCHEME_HTML, "http://dont.remember.com/",
"http://dont.remember.com/", NULL, NULL, false,
2000, 1, 1, 0, 0, 0 },
{ PasswordForm::SCHEME_HTML, "http://dont.remember.com/",
"http://dont.remember.com/", NULL, NULL, false,
2000, 1, 1, 0, 0, 0 },
{ PasswordForm::SCHEME_HTML, "https://dont.remember.com/",
"https://dont.remember.com/", NULL, NULL, true,
2000, 1, 1, 0, 0, 0 },
{ PasswordForm::SCHEME_BASIC, "http://some.domain.com:4567/low_security",
"http://some.domain.com:4567/insecure.html", L"basic_auth_user", L"basic",
false, 1998, 03, 30, 10, 00, 00 },
{ PasswordForm::SCHEME_DIGEST, "https://some.domain.com/high_security",
"https://some.domain.com/", L"digest_auth_user", L"digest", true,
1998, 3, 30, 10, 0, 0 },
// This one gives us an invalid date, which we will treat as a "NULL" date
// which is 1601.
{ PasswordForm::SCHEME_OTHER, "http://a.server.com/",
"http://a.server.com/", L"abc", L"123", false,
1601, 1, 1, 0, 0, 0 },
{ PasswordForm::SCHEME_HTML, "android://hash@com.domain.some/",
"", L"joe_user", L"secret", true,
2015, 5, 15, 14, 13, 12 },
};
for (unsigned int i = 0; i < arraysize(expected); ++i) {
// Create our fake KeychainItemRef; see MockAppleKeychain docs.
SecKeychainItemRef keychain_item =
reinterpret_cast<SecKeychainItemRef>(i + 1);
PasswordForm form;
bool parsed = <API key>::Fill<API key>(
*keychain_, keychain_item, &form, true);
EXPECT_TRUE(parsed) << "In iteration " << i;
EXPECT_EQ(expected[i].scheme, form.scheme) << "In iteration " << i;
EXPECT_EQ(GURL(expected[i].origin), form.origin) << "In iteration " << i;
EXPECT_EQ(expected[i].ssl_valid, form.ssl_valid) << "In iteration " << i;
EXPECT_EQ(std::string(expected[i].signon_realm), form.signon_realm)
<< "In iteration " << i;
if (expected[i].username) {
EXPECT_EQ(WideToUTF16(expected[i].username), form.username_value)
<< "In iteration " << i;
EXPECT_EQ(WideToUTF16(expected[i].password), form.password_value)
<< "In iteration " << i;
EXPECT_FALSE(form.blacklisted_by_user) << "In iteration " << i;
} else {
EXPECT_TRUE(form.blacklisted_by_user) << "In iteration " << i;
}
base::Time::Exploded exploded_time;
form.date_created.UTCExplode(&exploded_time);
EXPECT_EQ(expected[i].creation_year, exploded_time.year)
<< "In iteration " << i;
EXPECT_EQ(expected[i].creation_month, exploded_time.month)
<< "In iteration " << i;
EXPECT_EQ(expected[i].creation_day, exploded_time.day_of_month)
<< "In iteration " << i;
EXPECT_EQ(expected[i].creation_hour, exploded_time.hour)
<< "In iteration " << i;
EXPECT_EQ(expected[i].creation_minute, exploded_time.minute)
<< "In iteration " << i;
EXPECT_EQ(expected[i].creation_second, exploded_time.second)
<< "In iteration " << i;
}
{
// Use an invalid ref, to make sure errors are reported.
SecKeychainItemRef keychain_item = reinterpret_cast<SecKeychainItemRef>(99);
PasswordForm form;
bool parsed = <API key>::Fill<API key>(
*keychain_, keychain_item, &form, true);
EXPECT_FALSE(parsed);
}
}
TEST_F(<API key>, TestKeychainSearch) {
struct <API key> {
const PasswordFormData data;
const size_t <API key>;
const size_t <API key>;
};
// Most fields are left blank because we don't care about them for searching.
/* clang-format off */
<API key> test_data[] = {
// An HTML form we've seen.
{ { PasswordForm::SCHEME_HTML, "http://some.domain.com/",
NULL, NULL, NULL, NULL, NULL, L"joe_user", NULL, false, false, 0 },
2, 2 },
{ { PasswordForm::SCHEME_HTML, "http://some.domain.com/",
NULL, NULL, NULL, NULL, NULL, L"wrong_user", NULL, false, false, 0 },
2, 0 },
// An HTML form we haven't seen
{ { PasswordForm::SCHEME_HTML, "http:
NULL, NULL, NULL, NULL, NULL, L"joe_user", NULL, false, false, 0 },
0, 0 },
// Basic auth that should match.
{ { PasswordForm::SCHEME_BASIC, "http://some.domain.com:4567/low_security",
NULL, NULL, NULL, NULL, NULL, L"basic_auth_user", NULL, false, false,
0 },
1, 1 },
// Basic auth with the wrong port.
{ { PasswordForm::SCHEME_BASIC, "http://some.domain.com:1111/low_security",
NULL, NULL, NULL, NULL, NULL, L"basic_auth_user", NULL, false, false,
0 },
0, 0 },
// Digest auth we've saved under https, visited with http.
{ { PasswordForm::SCHEME_DIGEST, "http://some.domain.com/high_security",
NULL, NULL, NULL, NULL, NULL, L"digest_auth_user", NULL, false, false,
0 },
0, 0 },
// Digest auth that should match.
{ { PasswordForm::SCHEME_DIGEST, "https://some.domain.com/high_security",
NULL, NULL, NULL, NULL, NULL, L"wrong_user", NULL, false, true, 0 },
1, 0 },
// Digest auth with the wrong domain.
{ { PasswordForm::SCHEME_DIGEST, "https://some.domain.com/other_domain",
NULL, NULL, NULL, NULL, NULL, L"digest_auth_user", NULL, false, true,
0 },
0, 0 },
// Android credentials (both legacy ones with origin, and without).
{ { PasswordForm::SCHEME_HTML, "android://hash@com.domain.some/",
"android://hash@com.domain.some/", NULL, NULL, NULL, NULL, L"joe_user",
NULL, false, true, 0 },
1, 1 },
{ { PasswordForm::SCHEME_HTML, "android://hash@com.domain.some/",
NULL, NULL, NULL, NULL, NULL, L"joe_user", NULL, false, true, 0 },
1, 1 },
// Federated logins do not have a corresponding Keychain entry, and should
// not match the username/password stored for the same application. Note
// that it will match for filling, however, because that part does not know
// that it is a federated login.
{ { PasswordForm::SCHEME_HTML, "android://hash@com.domain.some/",
NULL, NULL, NULL, NULL, NULL, L"joe_user",
password_manager::<API key>, false, true, 0 },
1, 0 },
Garbage forms should have no matches.
{ { PasswordForm::SCHEME_HTML, "foo/bar/baz",
NULL, NULL, NULL, NULL, NULL, NULL, NULL, false, false, 0 }, 0, 0 },
};
/* clang-format on */
<API key> keychain_adapter(keychain_);
<API key> <API key>(keychain_);
<API key>.<API key>(true);
for (unsigned int i = 0; i < arraysize(test_data); ++i) {
scoped_ptr<PasswordForm> query_form =
Create<API key>(test_data[i].data);
// Check matches treating the form as a fill target.
ScopedVector<autofill::PasswordForm> matching_items =
keychain_adapter.<API key>(query_form->signon_realm,
query_form->scheme);
EXPECT_EQ(test_data[i].<API key>, matching_items.size());
// Check matches treating the form as a merging target.
EXPECT_EQ(test_data[i].<API key> > 0,
keychain_adapter.Has<API key>(*query_form));
std::vector<SecKeychainItemRef> keychain_items;
std::vector<<API key>::ItemFormPair> item_form_pairs =
<API key>::
<API key>(&keychain_items,
*keychain_);
matching_items =
<API key>::Extract<API key>(
*keychain_, item_form_pairs, *query_form);
EXPECT_EQ(test_data[i].<API key>, matching_items.size());
<API key>(item_form_pairs.begin(),
item_form_pairs.end());
for (std::vector<SecKeychainItemRef>::iterator i = keychain_items.begin();
i != keychain_items.end(); ++i) {
keychain_->Free(*i);
}
// None of the pre-seeded items are owned by us, so none should match an
// <API key> search.
matching_items = <API key>.<API key>(
query_form->signon_realm, query_form->scheme);
EXPECT_EQ(0U, matching_items.size());
}
}
// Changes just the origin path of |form|.
static void SetPasswordFormPath(PasswordForm* form, const char* path) {
GURL::Replacements replacement;
std::string new_value(path);
replacement.SetPathStr(new_value);
form->origin = form->origin.ReplaceComponents(replacement);
}
// Changes just the signon_realm port of |form|.
static void SetPasswordFormPort(PasswordForm* form, const char* port) {
GURL::Replacements replacement;
std::string new_value(port);
replacement.SetPortStr(new_value);
GURL signon_gurl = GURL(form->signon_realm);
form->signon_realm = signon_gurl.ReplaceComponents(replacement).spec();
}
// Changes just the signon_ream auth realm of |form|.
static void <API key>(PasswordForm* form, const char* realm) {
GURL::Replacements replacement;
std::string new_value(realm);
replacement.SetPathStr(new_value);
GURL signon_gurl = GURL(form->signon_realm);
form->signon_realm = signon_gurl.ReplaceComponents(replacement).spec();
}
TEST_F(<API key>, <API key>) {
<API key> keychain_adapter(keychain_);
PasswordFormData base_form_data[] = {
{ PasswordForm::SCHEME_HTML, "http://some.domain.com/",
"http://some.domain.com/insecure.html",
NULL, NULL, NULL, NULL, L"joe_user", NULL, true, false, 0 },
{ PasswordForm::SCHEME_BASIC, "http://some.domain.com:4567/low_security",
"http://some.domain.com:4567/insecure.html",
NULL, NULL, NULL, NULL, L"basic_auth_user", NULL, true, false, 0 },
{ PasswordForm::SCHEME_DIGEST, "https://some.domain.com/high_security",
"https://some.domain.com",
NULL, NULL, NULL, NULL, L"digest_auth_user", NULL, true, true, 0 },
};
for (unsigned int i = 0; i < arraysize(base_form_data); ++i) {
// Create a base form and make sure we find a match.
scoped_ptr<PasswordForm> base_form =
Create<API key>(base_form_data[i]);
EXPECT_TRUE(keychain_adapter.Has<API key>(*base_form));
EXPECT_TRUE(keychain_adapter.Has<API key>(*base_form));
// Make sure that the matching isn't looser than it should be by checking
// that slightly altered forms don't match.
ScopedVector<autofill::PasswordForm> modified_forms;
modified_forms.push_back(new PasswordForm(*base_form));
modified_forms.back()->username_value = ASCIIToUTF16("wrong_user");
modified_forms.push_back(new PasswordForm(*base_form));
SetPasswordFormPath(modified_forms.back(), "elsewhere.html");
modified_forms.push_back(new PasswordForm(*base_form));
modified_forms.back()->scheme = PasswordForm::SCHEME_OTHER;
modified_forms.push_back(new PasswordForm(*base_form));
SetPasswordFormPort(modified_forms.back(), "1234");
modified_forms.push_back(new PasswordForm(*base_form));
modified_forms.back()->blacklisted_by_user = true;
if (base_form->scheme == PasswordForm::SCHEME_BASIC ||
base_form->scheme == PasswordForm::SCHEME_DIGEST) {
modified_forms.push_back(new PasswordForm(*base_form));
<API key>(modified_forms.back(), "incorrect");
}
for (unsigned int j = 0; j < modified_forms.size(); ++j) {
bool match = keychain_adapter.Has<API key>(
*modified_forms[j]);
EXPECT_FALSE(match) << "In modified version " << j
<< " of base form " << i;
}
}
}
TEST_F(<API key>, TestKeychainAdd) {
struct <API key> {
PasswordFormData data;
bool should_succeed;
};
/* clang-format off */
<API key> test_data[] = {
// Test a variety of scheme/port/protocol/path variations.
{ { PasswordForm::SCHEME_HTML, "http://web.site.com/",
"http://web.site.com/path/to/page.html", NULL, NULL, NULL, NULL,
L"anonymous", L"knock-knock", false, false, 0 }, true },
{ { PasswordForm::SCHEME_HTML, "https://web.site.com/",
"https://web.site.com/", NULL, NULL, NULL, NULL,
L"admin", L"p4ssw0rd", false, false, 0 }, true },
{ { PasswordForm::SCHEME_BASIC, "http://a.site.com:2222/therealm",
"http://a.site.com:2222/", NULL, NULL, NULL, NULL,
L"username", L"password", false, false, 0 }, true },
{ { PasswordForm::SCHEME_DIGEST, "https://digest.site.com/differentrealm",
"https://digest.site.com/secure.html", NULL, NULL, NULL, NULL,
L"testname", L"testpass", false, false, 0 }, true },
// Test that Android credentials can be stored. Also check the legacy form
// when |origin| was still filled with the Android URI (and not left empty).
{ { PasswordForm::SCHEME_HTML, "android://hash@com.example.alpha/",
"", NULL, NULL, NULL, NULL,
L"joe_user", L"password", false, true, 0 }, true },
{ { PasswordForm::SCHEME_HTML, "android://hash@com.example.beta/",
"android://hash@com.example.beta/", NULL, NULL, NULL, NULL,
L"jane_user", L"password2", false, true, 0 }, true },
// Make sure that garbage forms are rejected.
{ { PasswordForm::SCHEME_HTML, "gobbledygook",
"gobbledygook", NULL, NULL, NULL, NULL,
L"anonymous", L"knock-knock", false, false, 0 }, false },
// Test that failing to update a duplicate (forced using the magic failure
// password; see MockAppleKeychain::<API key>) is
// reported.
{ { PasswordForm::SCHEME_HTML, "http://some.domain.com",
"http://some.domain.com/insecure.html", NULL, NULL, NULL, NULL,
L"joe_user", L"fail_me", false, false, 0 }, false },
};
/* clang-format on */
<API key> <API key>(keychain_);
<API key>.<API key>(true);
for (unsigned int i = 0; i < arraysize(test_data); ++i) {
scoped_ptr<PasswordForm> in_form =
Create<API key>(test_data[i].data);
bool add_succeeded = <API key>.AddPassword(*in_form);
EXPECT_EQ(test_data[i].should_succeed, add_succeeded);
if (add_succeeded) {
EXPECT_TRUE(<API key>.Has<API key>(
*in_form));
EXPECT_TRUE(<API key>.Has<API key>(
*in_form));
}
}
// Test that adding duplicate item updates the existing item.
// TODO(engedy): Add a test to verify that updating Android credentials work.
{
PasswordFormData data = {
PasswordForm::SCHEME_HTML, "http://some.domain.com",
"http://some.domain.com/insecure.html", NULL,
NULL, NULL, NULL, L"joe_user", L"updated_password", false, false, 0
};
scoped_ptr<PasswordForm> update_form =
Create<API key>(data);
<API key> keychain_adapter(keychain_);
EXPECT_TRUE(keychain_adapter.AddPassword(*update_form));
SecKeychainItemRef keychain_item = reinterpret_cast<SecKeychainItemRef>(2);
PasswordForm stored_form;
<API key>::Fill<API key>(*keychain_,
keychain_item,
&stored_form,
true);
EXPECT_EQ(update_form->password_value, stored_form.password_value);
}
}
TEST_F(<API key>, TestKeychainRemove) {
struct <API key> {
PasswordFormData data;
bool should_succeed;
};
/* clang-format off */
<API key> test_data[] = {
// Test deletion of an item that we add.
{ { PasswordForm::SCHEME_HTML, "http://web.site.com/",
"http://web.site.com/path/to/page.html", NULL, NULL, NULL, NULL,
L"anonymous", L"knock-knock", false, false, 0 }, true },
// Test that Android credentials can be removed. Also check the legacy case
// when |origin| was still filled with the Android URI (and not left empty).
{ { PasswordForm::SCHEME_HTML, "android://hash@com.example.alpha/",
"", NULL, NULL, NULL, NULL,
L"joe_user", L"secret", false, true, 0 }, true },
{ { PasswordForm::SCHEME_HTML, "android://hash@com.example.beta/",
"android://hash@com.example.beta/", NULL, NULL, NULL, NULL,
L"jane_user", L"secret", false, true, 0 }, true },
// Make sure we don't delete items we don't own.
{ { PasswordForm::SCHEME_HTML, "http://some.domain.com/",
"http://some.domain.com/insecure.html", NULL, NULL, NULL, NULL,
L"joe_user", NULL, true, false, 0 }, false },
};
/* clang-format on */
<API key> <API key>(keychain_);
<API key>.<API key>(true);
// Add our test items (except the last one) so that we can delete them.
for (unsigned int i = 0; i + 1 < arraysize(test_data); ++i) {
scoped_ptr<PasswordForm> add_form =
Create<API key>(test_data[i].data);
EXPECT_TRUE(<API key>.AddPassword(*add_form));
}
for (unsigned int i = 0; i < arraysize(test_data); ++i) {
scoped_ptr<PasswordForm> form =
Create<API key>(test_data[i].data);
EXPECT_EQ(test_data[i].should_succeed,
<API key>.RemovePassword(*form));
<API key> keychain_adapter(keychain_);
bool match = keychain_adapter.Has<API key>(*form);
EXPECT_EQ(test_data[i].should_succeed, !match);
}
}
TEST_F(<API key>, TestFormMatch) {
PasswordForm base_form;
base_form.signon_realm = std::string("http://some.domain.com/");
base_form.origin = GURL("http://some.domain.com/page.html");
base_form.username_value = ASCIIToUTF16("joe_user");
{
// Check that everything unimportant can be changed.
PasswordForm different_form(base_form);
different_form.username_element = ASCIIToUTF16("username");
different_form.submit_element = ASCIIToUTF16("submit");
different_form.username_element = ASCIIToUTF16("password");
different_form.password_value = ASCIIToUTF16("sekrit");
different_form.action = GURL("http://some.domain.com/action.cgi");
different_form.ssl_valid = true;
different_form.preferred = true;
different_form.date_created = base::Time::Now();
EXPECT_TRUE(
FormsMatchForMerge(base_form, different_form, STRICT_FORM_MATCH));
// Check that path differences don't prevent a match.
base_form.origin = GURL("http://some.domain.com/other_page.html");
EXPECT_TRUE(
FormsMatchForMerge(base_form, different_form, STRICT_FORM_MATCH));
}
// Check that any one primary key changing is enough to prevent matching.
{
PasswordForm different_form(base_form);
different_form.scheme = PasswordForm::SCHEME_DIGEST;
EXPECT_FALSE(
FormsMatchForMerge(base_form, different_form, STRICT_FORM_MATCH));
}
{
PasswordForm different_form(base_form);
different_form.signon_realm = std::string("http://some.domain.com:8080/");
EXPECT_FALSE(
FormsMatchForMerge(base_form, different_form, STRICT_FORM_MATCH));
}
{
PasswordForm different_form(base_form);
different_form.username_value = ASCIIToUTF16("john.doe");
EXPECT_FALSE(
FormsMatchForMerge(base_form, different_form, STRICT_FORM_MATCH));
}
{
PasswordForm different_form(base_form);
different_form.blacklisted_by_user = true;
EXPECT_FALSE(
FormsMatchForMerge(base_form, different_form, STRICT_FORM_MATCH));
}
// Blacklist forms should *never* match for merging, even when identical
// (and certainly not when only one is a blacklist entry).
{
PasswordForm form_a(base_form);
form_a.blacklisted_by_user = true;
PasswordForm form_b(form_a);
EXPECT_FALSE(FormsMatchForMerge(form_a, form_b, STRICT_FORM_MATCH));
}
// Federated login forms should never match for merging either.
{
PasswordForm form_b(base_form);
form_b.federation_url = GURL(password_manager::<API key>);
EXPECT_FALSE(FormsMatchForMerge(base_form, form_b, STRICT_FORM_MATCH));
EXPECT_FALSE(FormsMatchForMerge(form_b, base_form, STRICT_FORM_MATCH));
EXPECT_FALSE(FormsMatchForMerge(form_b, form_b, STRICT_FORM_MATCH));
}
}
TEST_F(<API key>, TestFormMerge) {
// Set up a bunch of test data to use in varying combinations.
/* clang-format off */
PasswordFormData keychain_user_1 =
{ PasswordForm::SCHEME_HTML, "http://some.domain.com/",
"http://some.domain.com/", "", L"", L"", L"", L"joe_user", L"sekrit",
false, false, 1010101010 };
PasswordFormData <API key> =
{ PasswordForm::SCHEME_HTML, "http://some.domain.com/",
"http://some.domain.com/page.html",
"", L"", L"", L"", L"joe_user", L"otherpassword",
false, false, 1010101010 };
PasswordFormData keychain_user_2 =
{ PasswordForm::SCHEME_HTML, "http://some.domain.com/",
"http://some.domain.com/", "", L"", L"", L"", L"john.doe", L"sesame",
false, false, 958739876 };
PasswordFormData keychain_blacklist =
{ PasswordForm::SCHEME_HTML, "http://some.domain.com/",
"http://some.domain.com/", "", L"", L"", L"", NULL, NULL,
false, false, 1010101010 };
PasswordFormData keychain_android =
{ PasswordForm::SCHEME_HTML, "android://hash@com.domain.some/",
"", "", L"", L"", L"", L"joe_user", L"secret",
false, true, 1234567890 };
PasswordFormData db_user_1 =
{ PasswordForm::SCHEME_HTML, "http://some.domain.com/",
"http:
L"submit", L"username", L"password", L"joe_user", L"",
true, false, 1212121212 };
PasswordFormData db_user_1_with_path =
{ PasswordForm::SCHEME_HTML, "http://some.domain.com/",
"http://some.domain.com/page.html",
"http://some.domain.com/handlepage.cgi",
L"submit", L"username", L"password", L"joe_user", L"",
true, false, 1234567890 };
PasswordFormData db_user_3_with_path =
{ PasswordForm::SCHEME_HTML, "http://some.domain.com/",
"http://some.domain.com/page.html",
"http://some.domain.com/handlepage.cgi",
L"submit", L"username", L"password", L"second-account", L"",
true, false, 1240000000 };
PasswordFormData <API key> =
{ PasswordForm::SCHEME_HTML, "http://some.domain.com/",
"http:
L"submit", L"username", L"password", NULL, NULL,
true, false, 1212121212 };
PasswordFormData db_android =
{ PasswordForm::SCHEME_HTML, "android://hash@com.domain.some/",
"android://hash@com.domain.some/", "", L"", L"", L"", L"joe_user", L"",
false, true, 1234567890 };
PasswordFormData db_federated =
{ PasswordForm::SCHEME_HTML, "android://hash@com.domain.some/",
"android://hash@com.domain.some/", "", L"", L"", L"", L"joe_user",
password_manager::<API key>,
false, true, 3434343434 };
PasswordFormData merged_user_1 =
{ PasswordForm::SCHEME_HTML, "http://some.domain.com/",
"http:
L"submit", L"username", L"password", L"joe_user", L"sekrit",
true, false, 1212121212 };
PasswordFormData <API key> =
{ PasswordForm::SCHEME_HTML, "http://some.domain.com/",
"http://some.domain.com/page.html",
"http://some.domain.com/handlepage.cgi",
L"submit", L"username", L"password", L"joe_user", L"sekrit",
true, false, 1234567890 };
PasswordFormData <API key> =
{ PasswordForm::SCHEME_HTML, "http://some.domain.com/",
"http://some.domain.com/page.html",
"http://some.domain.com/handlepage.cgi",
L"submit", L"username", L"password", L"joe_user", L"otherpassword",
true, false, 1234567890 };
PasswordFormData merged_android =
{ PasswordForm::SCHEME_HTML, "android://hash@com.domain.some/",
"android://hash@com.domain.some/", "", L"", L"", L"", L"joe_user",
L"secret", false, true, 1234567890 };
/* clang-format on */
// Build up the big multi-dimensional array of data sets that will actually
// drive the test. Use vectors rather than arrays so that initialization is
// simple.
enum {
KEYCHAIN_INPUT = 0,
DATABASE_INPUT,
MERGE_OUTPUT,
KEYCHAIN_OUTPUT,
DATABASE_OUTPUT,
<API key> // termination marker
};
const unsigned int kTestCount = 5;
std::vector< std::vector< std::vector<PasswordFormData*> > > test_data(
<API key>, std::vector< std::vector<PasswordFormData*> >(
kTestCount, std::vector<PasswordFormData*>()));
unsigned int current_test = 0;
// Test a merge with a few accounts in both systems, with partial overlap.
CHECK(current_test < kTestCount);
test_data[KEYCHAIN_INPUT][current_test].push_back(&keychain_user_1);
test_data[KEYCHAIN_INPUT][current_test].push_back(&keychain_user_2);
test_data[DATABASE_INPUT][current_test].push_back(&db_user_1);
test_data[DATABASE_INPUT][current_test].push_back(&db_user_1_with_path);
test_data[DATABASE_INPUT][current_test].push_back(&db_user_3_with_path);
test_data[MERGE_OUTPUT][current_test].push_back(&merged_user_1);
test_data[MERGE_OUTPUT][current_test].push_back(&<API key>);
test_data[KEYCHAIN_OUTPUT][current_test].push_back(&keychain_user_2);
test_data[DATABASE_OUTPUT][current_test].push_back(&db_user_3_with_path);
// Test a merge where Chrome has a blacklist entry, and the keychain has
// a stored account.
++current_test;
CHECK(current_test < kTestCount);
test_data[KEYCHAIN_INPUT][current_test].push_back(&keychain_user_1);
test_data[DATABASE_INPUT][current_test].push_back(
&<API key>);
// We expect both to be present because a blacklist could be specific to a
// subpath, and we want access to the password on other paths.
test_data[MERGE_OUTPUT][current_test].push_back(
&<API key>);
test_data[KEYCHAIN_OUTPUT][current_test].push_back(&keychain_user_1);
// Test a merge where Chrome has an account, and Keychain has a blacklist
// (from another browser) and the Chrome password data.
++current_test;
CHECK(current_test < kTestCount);
test_data[KEYCHAIN_INPUT][current_test].push_back(&keychain_blacklist);
test_data[KEYCHAIN_INPUT][current_test].push_back(&keychain_user_1);
test_data[DATABASE_INPUT][current_test].push_back(&db_user_1);
test_data[MERGE_OUTPUT][current_test].push_back(&merged_user_1);
test_data[KEYCHAIN_OUTPUT][current_test].push_back(&keychain_blacklist);
// Test that matches are done using exact path when possible.
++current_test;
CHECK(current_test < kTestCount);
test_data[KEYCHAIN_INPUT][current_test].push_back(&keychain_user_1);
test_data[KEYCHAIN_INPUT][current_test].push_back(&<API key>);
test_data[DATABASE_INPUT][current_test].push_back(&db_user_1);
test_data[DATABASE_INPUT][current_test].push_back(&db_user_1_with_path);
test_data[MERGE_OUTPUT][current_test].push_back(&merged_user_1);
test_data[MERGE_OUTPUT][current_test].push_back(
&<API key>);
// Test that Android credentails are matched correctly and that federated
// credentials are not tried to be matched with a Keychain item.
++current_test;
CHECK(current_test < kTestCount);
test_data[KEYCHAIN_INPUT][current_test].push_back(&keychain_android);
test_data[DATABASE_INPUT][current_test].push_back(&db_federated);
test_data[DATABASE_INPUT][current_test].push_back(&db_android);
test_data[MERGE_OUTPUT][current_test].push_back(&db_federated);
test_data[MERGE_OUTPUT][current_test].push_back(&merged_android);
for (unsigned int test_case = 0; test_case <= current_test; ++test_case) {
ScopedVector<autofill::PasswordForm> keychain_forms;
for (std::vector<PasswordFormData*>::iterator i =
test_data[KEYCHAIN_INPUT][test_case].begin();
i != test_data[KEYCHAIN_INPUT][test_case].end(); ++i) {
keychain_forms.push_back(
Create<API key>(*(*i)).release());
}
ScopedVector<autofill::PasswordForm> database_forms;
for (std::vector<PasswordFormData*>::iterator i =
test_data[DATABASE_INPUT][test_case].begin();
i != test_data[DATABASE_INPUT][test_case].end(); ++i) {
database_forms.push_back(
Create<API key>(*(*i)).release());
}
ScopedVector<autofill::PasswordForm> merged_forms;
<API key>::MergePasswordForms(&keychain_forms,
&database_forms,
&merged_forms);
CHECK_FORMS(keychain_forms.get(), test_data[KEYCHAIN_OUTPUT][test_case],
test_case);
CHECK_FORMS(database_forms.get(), test_data[DATABASE_OUTPUT][test_case],
test_case);
CHECK_FORMS(merged_forms.get(), test_data[MERGE_OUTPUT][test_case],
test_case);
}
}
TEST_F(<API key>, <API key>) {
PasswordFormData db_data[] = {
{ PasswordForm::SCHEME_HTML, "http://some.domain.com/",
"http:
L"submit", L"username", L"password", L"joe_user", L"",
true, false, 1212121212 },
{ PasswordForm::SCHEME_HTML, "http://some.domain.com/",
"http://some.domain.com/page.html",
"http://some.domain.com/handlepage.cgi",
L"submit", L"username", L"password", L"joe_user", L"",
true, false, 1234567890 },
{ PasswordForm::SCHEME_HTML, "http://some.domain.com/",
"http://some.domain.com/page.html",
"http://some.domain.com/handlepage.cgi",
L"submit", L"username", L"password", L"second-account", L"",
true, false, 1240000000 },
{ PasswordForm::SCHEME_HTML, "http://dont.remember.com/",
"http://dont.remember.com/",
"http://dont.remember.com/handlepage.cgi",
L"submit", L"username", L"password", L"joe_user", L"",
true, false, 1240000000 },
{ PasswordForm::SCHEME_HTML, "http://some.domain.com/",
"http:
L"submit", L"username", L"password", NULL, NULL,
true, false, 1212121212 },
};
ScopedVector<autofill::PasswordForm> database_forms;
for (unsigned int i = 0; i < arraysize(db_data); ++i) {
database_forms.push_back(
Create<API key>(db_data[i]).release());
}
ScopedVector<autofill::PasswordForm> merged_forms;
<API key>::<API key>(*keychain_, &database_forms,
&merged_forms);
EXPECT_EQ(2U, database_forms.size());
ASSERT_EQ(3U, merged_forms.size());
EXPECT_EQ(ASCIIToUTF16("sekrit"), merged_forms[0]->password_value);
EXPECT_EQ(ASCIIToUTF16("sekrit"), merged_forms[1]->password_value);
EXPECT_TRUE(merged_forms[2]->blacklisted_by_user);
}
TEST_F(<API key>, <API key>) {
PasswordFormData db_data[] = {
{ PasswordForm::SCHEME_HTML, "http://dont.remember.com/",
"http://dont.remember.com/",
"http://dont.remember.com/handlepage.cgi",
L"submit", L"username", L"password", L"joe_user", L"non_empty_password",
true, false, 1240000000 },
{ PasswordForm::SCHEME_HTML, "https://dont.remember.com/",
"https://dont.remember.com/",
"https://dont.remember.com/handlepage_secure.cgi",
L"submit", L"username", L"password", L"joe_user", L"non_empty_password",
true, false, 1240000000 },
};
ScopedVector<autofill::PasswordForm> database_forms;
for (unsigned int i = 0; i < arraysize(db_data); ++i) {
database_forms.push_back(
Create<API key>(db_data[i]).release());
}
ScopedVector<autofill::PasswordForm> merged_forms;
<API key>::<API key>(*keychain_, &database_forms,
&merged_forms);
EXPECT_EQ(2U, database_forms.size());
ASSERT_EQ(0U, merged_forms.size());
}
TEST_F(<API key>, TestFill<API key>) {
// When |<API key>| is false, the password field must be empty,
// and |blacklisted_by_user| must be false.
SecKeychainItemRef keychain_item = reinterpret_cast<SecKeychainItemRef>(1);
PasswordForm <API key>;
bool parsed = <API key>::Fill<API key>(
*keychain_,
keychain_item,
&<API key>,
false); // Do not extract password.
EXPECT_TRUE(parsed);
ASSERT_TRUE(<API key>.password_value.empty());
ASSERT_FALSE(<API key>.blacklisted_by_user);
// When |<API key>| is true and the keychain entry has a non-empty
// password, the password field must be non-empty, and the value of
// |blacklisted_by_user| must be false.
keychain_item = reinterpret_cast<SecKeychainItemRef>(1);
PasswordForm <API key>;
parsed = <API key>::Fill<API key>(
*keychain_,
keychain_item,
&<API key>,
true); // Extract password.
EXPECT_TRUE(parsed);
ASSERT_EQ(ASCIIToUTF16("sekrit"),
<API key>.password_value);
ASSERT_FALSE(<API key>.blacklisted_by_user);
// When |<API key>| is true and the keychain entry has an empty
// username and password (""), the password field must be empty, and the value
// of |blacklisted_by_user| must be true.
keychain_item = reinterpret_cast<SecKeychainItemRef>(4);
PasswordForm negative_form;
parsed = <API key>::Fill<API key>(
*keychain_,
keychain_item,
&negative_form,
true); // Extract password.
EXPECT_TRUE(parsed);
ASSERT_TRUE(negative_form.username_value.empty());
ASSERT_TRUE(negative_form.password_value.empty());
ASSERT_TRUE(negative_form.blacklisted_by_user);
// When |<API key>| is true and the keychain entry has an empty
// password (""), the password field must be empty (""), and the value of
// |blacklisted_by_user| must be true.
keychain_item = reinterpret_cast<SecKeychainItemRef>(5);
PasswordForm <API key>;
parsed = <API key>::Fill<API key>(
*keychain_,
keychain_item,
&<API key>,
true); // Extract password.
EXPECT_TRUE(parsed);
ASSERT_TRUE(<API key>.password_value.empty());
ASSERT_TRUE(<API key>.blacklisted_by_user);
// When |<API key>| is true and the keychain entry has a single
// space password (" "), the password field must be a single space (" "), and
// the value of |blacklisted_by_user| must be true.
keychain_item = reinterpret_cast<SecKeychainItemRef>(6);
PasswordForm <API key>;
parsed = <API key>::Fill<API key>(
*keychain_,
keychain_item,
&<API key>,
true); // Extract password.
EXPECT_TRUE(parsed);
ASSERT_EQ(ASCIIToUTF16(" "),
<API key>.password_value);
ASSERT_TRUE(<API key>.blacklisted_by_user);
}
TEST_F(<API key>, TestPasswordGetAll) {
<API key> keychain_adapter(keychain_);
<API key> <API key>(keychain_);
<API key>.<API key>(true);
// Add a few passwords of various types so that we own some.
PasswordFormData owned_password_data[] = {
{ PasswordForm::SCHEME_HTML, "http://web.site.com/",
"http://web.site.com/path/to/page.html", NULL, NULL, NULL, NULL,
L"anonymous", L"knock-knock", false, false, 0 },
{ PasswordForm::SCHEME_BASIC, "http://a.site.com:2222/therealm",
"http://a.site.com:2222/", NULL, NULL, NULL, NULL,
L"username", L"password", false, false, 0 },
{ PasswordForm::SCHEME_DIGEST, "https://digest.site.com/differentrealm",
"https://digest.site.com/secure.html", NULL, NULL, NULL, NULL,
L"testname", L"testpass", false, false, 0 },
};
for (unsigned int i = 0; i < arraysize(owned_password_data); ++i) {
scoped_ptr<PasswordForm> form =
Create<API key>(owned_password_data[i]);
<API key>.AddPassword(*form);
}
ScopedVector<autofill::PasswordForm> all_passwords =
keychain_adapter.<API key>();
EXPECT_EQ(9 + arraysize(owned_password_data), all_passwords.size());
ScopedVector<autofill::PasswordForm> owned_passwords =
<API key>.<API key>();
EXPECT_EQ(arraysize(owned_password_data), owned_passwords.size());
}
#pragma mark -
class <API key> : public testing::Test {
public:
<API key>() : ui_thread_(BrowserThread::UI, &message_loop_) {}
void SetUp() override {
ASSERT_TRUE(db_dir_.CreateUniqueTempDir());
histogram_tester_.reset(new base::HistogramTester);
// Ensure that LoginDatabase will use the mock keychain if it needs to
// encrypt/decrypt a password.
OSCrypt::UseMockKeychain(true);
login_db_.reset(
new password_manager::LoginDatabase(<API key>()));
thread_.reset(new base::Thread("<API key>"));
ASSERT_TRUE(thread_->Start());
ASSERT_TRUE(thread_->task_runner()->PostTask(
FROM_HERE, base::Bind(&<API key>::InitLoginDatabase,
base::Unretained(login_db_.get()))));
<API key>(login_db_.get());
// Make sure deferred initialization is performed before some tests start
// accessing the |login_db| directly.
<API key>();
}
void TearDown() override {
ClosePasswordStore();
thread_.reset();
login_db_.reset();
// Whatever a test did, PasswordStoreMac stores only empty password values
// in LoginDatabase. The empty valus do not require encryption and therefore
// OSCrypt shouldn't call the Keychain. The histogram doesn't cover the
// internet passwords.
if (histogram_tester_) {
scoped_ptr<base::HistogramSamples> samples =
histogram_tester_-><API key>(
"OSX.Keychain.Access");
EXPECT_TRUE(!samples || samples->TotalCount() == 0);
}
}
static void InitLoginDatabase(password_manager::LoginDatabase* login_db) {
ASSERT_TRUE(login_db->Init());
}
void <API key>(password_manager::LoginDatabase* login_db) {
store_ = new PasswordStoreMac(
base::<API key>::Get(), nullptr,
make_scoped_ptr<AppleKeychain>(new MockAppleKeychain));
ASSERT_TRUE(thread_->task_runner()->PostTask(
FROM_HERE, base::Bind(&PasswordStoreMac::InitWithTaskRunner, store_,
thread_->task_runner())));
ASSERT_TRUE(thread_->task_runner()->PostTask(
FROM_HERE, base::Bind(&PasswordStoreMac::<API key>, store_,
base::Unretained(login_db))));
}
void ClosePasswordStore() {
if (!store_)
return;
store_->Shutdown();
store_ = nullptr;
}
// Verifies that the given |form| can be properly stored so that it can be
// retrieved by FillMatchingLogins() and <API key>(), and then it
// can be properly removed.
void <API key>(const PasswordForm& form) {
// Run everything twice to make sure no garbage is left behind that would
// prevent storing the form a second time.
for (size_t iteration = 0; iteration < 2; ++iteration) {
SCOPED_TRACE(testing::Message("Iteration: ") << iteration);
<API key> mock_consumer;
EXPECT_CALL(mock_consumer, OnGet<API key>(IsEmpty()))
.WillOnce(QuitUIMessageLoop());
store()-><API key>(&mock_consumer);
base::MessageLoop::current()->Run();
::testing::Mock::<API key>(&mock_consumer);
store()->AddLogin(form);
<API key>();
PasswordForm returned_form;
EXPECT_CALL(mock_consumer, OnGet<API key>(SizeIs(1u)))
.WillOnce(
DoAll(<API key>(&returned_form), QuitUIMessageLoop()));
// The query operations will also do some housekeeping: they will remove
// dangling credentials in the LoginDatabase without a matching Keychain
// item when one is expected. If the logic that stores the Keychain item
// is incorrect, this will wipe the newly added form before the second
// query.
store()-><API key>(&mock_consumer);
base::MessageLoop::current()->Run();
::testing::Mock::<API key>(&mock_consumer);
EXPECT_EQ(form, returned_form);
PasswordForm query_form = form;
query_form.password_value.clear();
query_form.username_value.clear();
EXPECT_CALL(mock_consumer, OnGet<API key>(SizeIs(1u)))
.WillOnce(
DoAll(<API key>(&returned_form), QuitUIMessageLoop()));
store()->GetLogins(query_form, PasswordStore::ALLOW_PROMPT,
&mock_consumer);
base::MessageLoop::current()->Run();
::testing::Mock::<API key>(&mock_consumer);
EXPECT_EQ(form, returned_form);
store()->RemoveLogin(form);
}
}
base::FilePath <API key>() const {
return db_dir_.path().Append(FILE_PATH_LITERAL("login.db"));
}
password_manager::LoginDatabase* login_db() const {
return store_->login_metadata_db();
}
MockAppleKeychain* keychain() {
return static_cast<MockAppleKeychain*>(store_->keychain());
}
void <API key>() {
scoped_refptr<content::MessageLoopRunner> runner =
new content::MessageLoopRunner;
ASSERT_TRUE(thread_->task_runner()->PostTaskAndReply(
FROM_HERE, base::Bind(&Noop), runner->QuitClosure()));
runner->Run();
}
PasswordStoreMac* store() { return store_.get(); }
protected:
base::MessageLoopForUI message_loop_;
content::TestBrowserThread ui_thread_;
// Thread that the synchronous methods are run on.
scoped_ptr<base::Thread> thread_;
base::ScopedTempDir db_dir_;
scoped_ptr<password_manager::LoginDatabase> login_db_;
scoped_refptr<PasswordStoreMac> store_;
scoped_ptr<base::HistogramTester> histogram_tester_;
};
TEST_F(<API key>, TestStoreUpdate) {
// Insert a password into both the database and the keychain.
// This is done manually, rather than through store_->AddLogin, because the
// Mock Keychain isn't smart enough to be able to support update generically,
// so some.domain.com triggers special handling to test it that make inserting
// fail.
PasswordFormData joint_data = {
PasswordForm::SCHEME_HTML, "http://some.domain.com/",
"http://some.domain.com/insecure.html", "login.cgi",
L"username", L"password", L"submit", L"joe_user", L"sekrit", true, false, 1
};
scoped_ptr<PasswordForm> joint_form =
Create<API key>(joint_data);
EXPECT_EQ(AddChangeForForm(*joint_form), login_db()->AddLogin(*joint_form));
MockAppleKeychain::KeychainTestData joint_keychain_data = {
kSec<API key>, "some.domain.com",
<API key>, "/insecure.html", 0, NULL, "20020601171500Z",
"joe_user", "sekrit", false };
keychain()->AddTestItem(joint_keychain_data);
// Insert a password into the keychain only.
MockAppleKeychain::KeychainTestData keychain_only_data = {
kSec<API key>, "keychain.only.com",
<API key>, NULL, 0, NULL, "20020601171500Z",
"keychain", "only", false
};
keychain()->AddTestItem(keychain_only_data);
struct UpdateData {
PasswordFormData form_data;
const char* password; // NULL indicates no entry should be present.
};
// Make a series of update calls.
UpdateData updates[] = {
// Update the keychain+db passwords (the normal password update case).
{ { PasswordForm::SCHEME_HTML, "http://some.domain.com/",
"http://some.domain.com/insecure.html", "login.cgi",
L"username", L"password", L"submit", L"joe_user", L"53krit",
true, false, 2 },
"53krit",
},
// Update the keychain-only password; this simulates the initial use of a
// password stored by another browsers.
{ { PasswordForm::SCHEME_HTML, "http://keychain.only.com/",
"http://keychain.only.com/login.html", "login.cgi",
L"username", L"password", L"submit", L"keychain", L"only",
true, false, 2 },
"only",
},
// Update a password that doesn't exist in either location. This tests the
// case where a form is filled, then the stored login is removed, then the
// form is submitted.
{ { PasswordForm::SCHEME_HTML, "http://different.com/",
"http://different.com/index.html", "login.cgi",
L"username", L"password", L"submit", L"abc", L"123",
true, false, 2 },
NULL,
},
};
for (unsigned int i = 0; i < arraysize(updates); ++i) {
scoped_ptr<PasswordForm> form =
Create<API key>(updates[i].form_data);
store_->UpdateLogin(*form);
}
<API key>();
<API key> keychain_adapter(keychain());
for (unsigned int i = 0; i < arraysize(updates); ++i) {
scoped_ptr<PasswordForm> query_form =
Create<API key>(updates[i].form_data);
ScopedVector<autofill::PasswordForm> matching_items =
keychain_adapter.<API key>(query_form->signon_realm,
query_form->scheme);
if (updates[i].password) {
EXPECT_GT(matching_items.size(), 0U) << "iteration " << i;
if (matching_items.size() >= 1)
EXPECT_EQ(ASCIIToUTF16(updates[i].password),
matching_items[0]->password_value) << "iteration " << i;
} else {
EXPECT_EQ(0U, matching_items.size()) << "iteration " << i;
}
EXPECT_TRUE(login_db()->GetLogins(*query_form, &matching_items));
EXPECT_EQ(updates[i].password ? 1U : 0U, matching_items.size())
<< "iteration " << i;
}
}
TEST_F(<API key>, <API key>) {
// Tests that association between the keychain and login database parts of a
// password added by fuzzy (PSL) matching works.
// 2. Get a password for m.facebook.com. This fuzzy matches and returns the
// 3. Add the returned password for m.facebook.com.
// 4. Remove both passwords.
// -> check: that both are gone from the login DB and the keychain
// This test should in particular ensure that we don't keep passwords in the
// keychain just before we think we still have other (fuzzy-)matching entries
// for them in the login database. (For example, here if we deleted the
// from deleting it from the keystore just becaus the m.facebook.com password
PasswordFormData www_form_data = {
PasswordForm::SCHEME_HTML, "http:
"http:
L"username", L"password", L"submit", L"joe_user", L"sekrit", true, false, 1
};
scoped_ptr<PasswordForm> www_form =
Create<API key>(www_form_data);
EXPECT_EQ(AddChangeForForm(*www_form), login_db()->AddLogin(*www_form));
<API key> <API key>(keychain());
<API key>.<API key>(true);
<API key>.AddPassword(*www_form);
// 2. Get a password for m.facebook.com.
PasswordForm m_form(*www_form);
m_form.signon_realm = "http://m.facebook.com";
m_form.origin = GURL("http://m.facebook.com/index.html");
<API key> consumer;
store_->GetLogins(m_form, PasswordStore::ALLOW_PROMPT, &consumer);
PasswordForm returned_form;
EXPECT_CALL(consumer, OnGet<API key>(SizeIs(1u)))
.WillOnce(
DoAll(<API key>(&returned_form), QuitUIMessageLoop()));
base::MessageLoop::current()->Run();
// 3. Add the returned password for m.facebook.com.
EXPECT_EQ(AddChangeForForm(returned_form),
login_db()->AddLogin(returned_form));
<API key>.AddPassword(m_form);
// 4. Remove both passwords.
store_->RemoveLogin(*www_form);
store_->RemoveLogin(m_form);
<API key>();
ScopedVector<autofill::PasswordForm> matching_items =
<API key>.<API key>(www_form->signon_realm,
www_form->scheme);
EXPECT_EQ(0u, matching_items.size());
EXPECT_TRUE(login_db()->GetLogins(*www_form, &matching_items));
EXPECT_EQ(0u, matching_items.size());
// No trace of m.facebook.com.
matching_items = <API key>.<API key>(
m_form.signon_realm, m_form.scheme);
EXPECT_EQ(0u, matching_items.size());
EXPECT_TRUE(login_db()->GetLogins(m_form, &matching_items));
EXPECT_EQ(0u, matching_items.size());
}
namespace {
class <API key> :
public password_manager::PasswordStore::Observer {
public:
<API key>(PasswordStoreMac* store) : observer_(this) {
observer_.Add(store);
}
void WaitAndVerify(<API key>* test) {
test-><API key>();
::testing::Mock::<API key>(this);
}
// password_manager::PasswordStore::Observer:
MOCK_METHOD1(OnLoginsChanged,
void(const password_manager::<API key>& changes));
private:
ScopedObserver<password_manager::PasswordStore,
<API key>> observer_;
};
password_manager::<API key> GetAddChangeList(
const PasswordForm& form) {
password_manager::PasswordStoreChange change(
password_manager::PasswordStoreChange::ADD, form);
return password_manager::<API key>(1, change);
}
// Tests <API key> or <API key> depending on
// |check_created|.
void <API key>(<API key>* test, bool check_created) {
PasswordFormData <API key> = {
PasswordForm::SCHEME_HTML, "http:
"http:
L"password", L"joe_user", L"sekrit", true, false, 0 };
// The old form doesn't have elements names.
PasswordFormData <API key> = {
PasswordForm::SCHEME_HTML, "http:
"http:
L"", L"joe_user", L"oldsekrit", true, false, 0 };
PasswordFormData www_form_data_other = {
PasswordForm::SCHEME_HTML, "http://different.com/",
"http://different.com/index.html", "login", L"submit", L"username",
L"password", L"different_joe_user", L"sekrit", true, false, 0 };
scoped_ptr<PasswordForm> form_facebook =
Create<API key>(<API key>);
scoped_ptr<PasswordForm> form_facebook_old =
Create<API key>(<API key>);
scoped_ptr<PasswordForm> form_other =
Create<API key>(www_form_data_other);
base::Time now = base::Time::Now();
// TODO(vasilii): remove the next line once crbug/374132 is fixed.
now = base::Time::FromTimeT(now.ToTimeT());
base::Time next_day = now + base::TimeDelta::FromDays(1);
if (check_created) {
form_facebook_old->date_created = now;
form_facebook->date_created = next_day;
form_other->date_created = next_day;
} else {
form_facebook_old->date_synced = now;
form_facebook->date_synced = next_day;
form_other->date_synced = next_day;
}
<API key> observer(test->store());
test->store()->AddLogin(*form_facebook_old);
test->store()->AddLogin(*form_facebook);
test->store()->AddLogin(*form_other);
EXPECT_CALL(observer, OnLoginsChanged(GetAddChangeList(*form_facebook_old)));
EXPECT_CALL(observer, OnLoginsChanged(GetAddChangeList(*form_facebook)));
EXPECT_CALL(observer, OnLoginsChanged(GetAddChangeList(*form_other)));
observer.WaitAndVerify(test);
// Check the keychain content.
<API key> <API key>(test->keychain());
<API key>.<API key>(false);
ScopedVector<PasswordForm> matching_items(
<API key>.<API key>(form_facebook->signon_realm,
form_facebook->scheme));
EXPECT_EQ(1u, matching_items.size());
matching_items = <API key>.<API key>(
form_other->signon_realm, form_other->scheme);
EXPECT_EQ(1u, matching_items.size());
// Remove facebook.
if (check_created) {
test->store()-><API key>(base::Time(), next_day,
base::Closure());
} else {
test->store()-><API key>(base::Time(), next_day);
}
password_manager::<API key> list;
form_facebook_old->password_value.clear();
form_facebook->password_value.clear();
list.push_back(password_manager::PasswordStoreChange(
password_manager::PasswordStoreChange::REMOVE, *form_facebook_old));
list.push_back(password_manager::PasswordStoreChange(
password_manager::PasswordStoreChange::REMOVE, *form_facebook));
EXPECT_CALL(observer, OnLoginsChanged(list));
list.clear();
observer.WaitAndVerify(test);
matching_items = <API key>.<API key>(
form_facebook->signon_realm, form_facebook->scheme);
EXPECT_EQ(0u, matching_items.size());
matching_items = <API key>.<API key>(
form_other->signon_realm, form_other->scheme);
EXPECT_EQ(1u, matching_items.size());
// Remove form_other.
if (check_created) {
test->store()-><API key>(next_day, base::Time(),
base::Closure());
} else {
test->store()-><API key>(next_day, base::Time());
}
form_other->password_value.clear();
list.push_back(password_manager::PasswordStoreChange(
password_manager::PasswordStoreChange::REMOVE, *form_other));
EXPECT_CALL(observer, OnLoginsChanged(list));
observer.WaitAndVerify(test);
matching_items = <API key>.<API key>(
form_other->signon_realm, form_other->scheme);
EXPECT_EQ(0u, matching_items.size());
}
} // namespace
TEST_F(<API key>, <API key>) {
<API key>(this, true);
}
TEST_F(<API key>, <API key>) {
<API key>(this, false);
}
TEST_F(<API key>, <API key>) {
// Make sure that <API key> does affect only the correct
// profile.
// Add a third-party password.
MockAppleKeychain::KeychainTestData keychain_data = {
kSec<API key>, "some.domain.com",
<API key>, "/insecure.html", 0, NULL, "20020601171500Z",
"joe_user", "sekrit", false };
keychain()->AddTestItem(keychain_data);
// Add a password through the adapter. It has the "Chrome" creator tag.
// However, it's not referenced by the password database.
<API key> <API key>(keychain());
<API key>.<API key>(true);
PasswordFormData www_form_data1 = {
PasswordForm::SCHEME_HTML, "http:
"http:
L"submit", L"joe_user", L"sekrit", true, false, 1 };
scoped_ptr<PasswordForm> www_form =
Create<API key>(www_form_data1);
EXPECT_TRUE(<API key>.AddPassword(*www_form));
// Add a password from the current profile.
PasswordFormData www_form_data2 = {
PasswordForm::SCHEME_HTML, "http:
"http:
L"submit", L"not_joe_user", L"12345", true, false, 1 };
www_form = Create<API key>(www_form_data2);
store_->AddLogin(*www_form);
<API key>();
ScopedVector<PasswordForm> matching_items;
EXPECT_TRUE(login_db()->GetLogins(*www_form, &matching_items));
EXPECT_EQ(1u, matching_items.size());
store_-><API key>(base::Time(), base::Time(),
base::Closure());
<API key>();
// Check the second facebook form is gone.
EXPECT_TRUE(login_db()->GetLogins(*www_form, &matching_items));
EXPECT_EQ(0u, matching_items.size());
// Check the first facebook form is still there.
matching_items = <API key>.<API key>(
www_form->signon_realm, www_form->scheme);
ASSERT_EQ(1u, matching_items.size());
EXPECT_EQ(ASCIIToUTF16("joe_user"), matching_items[0]->username_value);
// Check the third-party password is still there.
<API key>.<API key>(false);
matching_items = <API key>.<API key>(
"http://some.domain.com/insecure.html", PasswordForm::SCHEME_HTML);
ASSERT_EQ(1u, matching_items.size());
}
// Add a facebook form to the store but not to the keychain. The form is to be
// implicitly deleted. However, the observers shouldn't get notified about
// deletion of non-existent forms like m.facebook.com.
TEST_F(<API key>, <API key>) {
testing::StrictMock<<API key>> mock_observer;
store()->AddObserver(&mock_observer);
PasswordFormData www_form_data = {
PasswordForm::SCHEME_HTML, "http:
"http:
L"username", L"password", L"submit", L"joe_user", L"", true, false, 1
};
scoped_ptr<PasswordForm> www_form(
Create<API key>(www_form_data));
EXPECT_EQ(AddChangeForForm(*www_form), login_db()->AddLogin(*www_form));
// 2. Get a PSL-matched password for m.facebook.com. The observer isn't
// notified because the form isn't in the database.
PasswordForm m_form(*www_form);
m_form.signon_realm = "http://m.facebook.com";
m_form.origin = GURL("http://m.facebook.com/index.html");
<API key> consumer;
ON_CALL(consumer, OnGet<API key>(_))
.WillByDefault(QuitUIMessageLoop());
EXPECT_CALL(mock_observer, OnLoginsChanged(_)).Times(0);
// The PSL-matched form isn't returned because there is no actual password in
// the keychain.
EXPECT_CALL(consumer, OnGet<API key>(IsEmpty()));
store_->GetLogins(m_form, PasswordStore::ALLOW_PROMPT, &consumer);
base::MessageLoop::current()->Run();
ScopedVector<autofill::PasswordForm> all_forms;
EXPECT_TRUE(login_db()-><API key>(&all_forms));
EXPECT_EQ(1u, all_forms.size());
::testing::Mock::<API key>(&mock_observer);
// the observer is notified.
password_manager::<API key> list;
list.push_back(password_manager::PasswordStoreChange(
password_manager::PasswordStoreChange::REMOVE, *www_form));
EXPECT_CALL(mock_observer, OnLoginsChanged(list));
EXPECT_CALL(consumer, OnGet<API key>(IsEmpty()));
store_->GetLogins(*www_form, PasswordStore::ALLOW_PROMPT, &consumer);
base::MessageLoop::current()->Run();
EXPECT_TRUE(login_db()-><API key>(&all_forms));
EXPECT_EQ(0u, all_forms.size());
}
// Verify that Android app passwords can be stored, retrieved, and deleted.
TEST_F(<API key>, <API key>) {
PasswordForm form;
form.signon_realm = "android://<API key>@net.rateflix.app/";
form.username_value = base::UTF8ToUTF16("randomusername");
form.password_value = base::UTF8ToUTF16("password");
<API key>(form);
}
// Verify that federated credentials can be stored, retrieved and deleted.
TEST_F(<API key>, <API key>) {
PasswordForm form;
form.signon_realm = "android://<API key>@net.rateflix.app/";
form.federation_url = GURL(password_manager::<API key>);
form.username_value = base::UTF8ToUTF16("randomusername");
form.password_value = base::UTF8ToUTF16(""); // No password.
<API key>(form);
}
void <API key>(PasswordStoreMac::MigrationResult expected_result,
PasswordStoreMac::MigrationResult result) {
EXPECT_EQ(expected_result, result);
QuitUIMessageLoop();
}
// Import the passwords from the Keychain to LoginDatabase.
TEST_F(<API key>, ImportFromKeychain) {
PasswordForm form1;
form1.origin = GURL("http://accounts.google.com/LoginAuth");
form1.signon_realm = "http://accounts.google.com/";
form1.username_value = ASCIIToUTF16("my_username");
form1.password_value = ASCIIToUTF16("my_password");
PasswordForm form2;
form2.origin = GURL("http://facebook.com/Login");
form2.signon_realm = "http://facebook.com/";
form2.username_value = ASCIIToUTF16("my_username");
form2.password_value = ASCIIToUTF16("my_password");
PasswordForm blacklisted_form;
blacklisted_form.origin = GURL("http://badsite.com/Login");
blacklisted_form.signon_realm = "http://badsite.com/";
blacklisted_form.blacklisted_by_user = true;
store()->AddLogin(form1);
store()->AddLogin(form2);
store()->AddLogin(blacklisted_form);
<API key>();
ASSERT_TRUE(base::<API key>(
thread_->task_runner().get(), FROM_HERE,
base::Bind(&PasswordStoreMac::ImportFromKeychain, store()),
base::Bind(&<API key>, PasswordStoreMac::MIGRATION_OK)));
<API key>();
// The password should be stored in the database by now.
ScopedVector<PasswordForm> matching_items;
EXPECT_TRUE(login_db()->GetLogins(form1, &matching_items));
ASSERT_EQ(1u, matching_items.size());
EXPECT_EQ(form1, *matching_items[0]);
EXPECT_TRUE(login_db()->GetLogins(form2, &matching_items));
ASSERT_EQ(1u, matching_items.size());
EXPECT_EQ(form2, *matching_items[0]);
EXPECT_TRUE(login_db()->GetLogins(blacklisted_form, &matching_items));
ASSERT_EQ(1u, matching_items.size());
EXPECT_EQ(blacklisted_form, *matching_items[0]);
// The passwords are encrypted using a key from the Keychain.
EXPECT_TRUE(histogram_tester_-><API key>(
"OSX.Keychain.Access")->TotalCount());
histogram_tester_.reset();
}
// Import a federated credential while the Keychain is locked.
TEST_F(<API key>, <API key>) {
keychain()->set_locked(true);
PasswordForm form1;
form1.origin = GURL("http://example.com/Login");
form1.signon_realm = "http://example.com/";
form1.username_value = ASCIIToUTF16("my_username");
form1.federation_url = GURL("https://accounts.google.com/");
store()->AddLogin(form1);
<API key>();
ASSERT_TRUE(base::<API key>(
thread_->task_runner().get(), FROM_HERE,
base::Bind(&PasswordStoreMac::ImportFromKeychain, store()),
base::Bind(&<API key>, PasswordStoreMac::MIGRATION_OK)));
<API key>();
ScopedVector<PasswordForm> matching_items;
EXPECT_TRUE(login_db()->GetLogins(form1, &matching_items));
ASSERT_EQ(1u, matching_items.size());
EXPECT_EQ(form1, *matching_items[0]);
}
// Try to import while the Keychain is locked but the encryption key had been
// read earlier.
TEST_F(<API key>, <API key>) {
PasswordForm form1;
form1.origin = GURL("http://accounts.google.com/LoginAuth");
form1.signon_realm = "http://accounts.google.com/";
form1.username_value = ASCIIToUTF16("my_username");
form1.password_value = ASCIIToUTF16("my_password");
store()->AddLogin(form1);
<API key>();
// Add a second keychain item matching the Database entry.
PasswordForm form2 = form1;
form2.origin = GURL("http://accounts.google.com/Login");
form2.password_value = ASCIIToUTF16("1234");
<API key> adapter(keychain());
EXPECT_TRUE(adapter.AddPassword(form2));
keychain()->set_locked(true);
ASSERT_TRUE(base::<API key>(
thread_->task_runner().get(), FROM_HERE,
base::Bind(&PasswordStoreMac::ImportFromKeychain, store()),
base::Bind(&<API key>, PasswordStoreMac::KEYCHAIN_BLOCKED)));
<API key>();
ScopedVector<PasswordForm> matching_items;
EXPECT_TRUE(login_db()->GetLogins(form1, &matching_items));
ASSERT_EQ(1u, matching_items.size());
EXPECT_EQ(base::string16(), matching_items[0]->password_value);
histogram_tester_->ExpectUniqueSample(
"PasswordManager.KeychainMigration.<API key>", 1, 1);
histogram_tester_->ExpectUniqueSample(
"PasswordManager.KeychainMigration.NumFailedPasswords", 1, 1);
histogram_tester_->ExpectUniqueSample(
"PasswordManager.KeychainMigration.<API key>",
2, 1);
// Don't test the encryption key access.
histogram_tester_.reset();
}
|
package gov.nih.nci.nbia.restAPI;
import gov.nih.nci.nbia.dao.<API key>;
import gov.nih.nci.nbia.util.<API key>;
import gov.nih.nci.security.<API key>;
import gov.nih.nci.security.<API key>;
import gov.nih.nci.security.authorization.domainobjects.ProtectionGroup;
import gov.nih.nci.security.authorization.domainobjects.ProtectionElement;
import gov.nih.nci.security.authorization.domainobjects.Role;
import gov.nih.nci.security.dao.RoleSearchCriteria;
import gov.nih.nci.security.dao.SearchCriteria;
import gov.nih.nci.security.exceptions.<API key>;
import gov.nih.nci.security.exceptions.CSException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.springframework.dao.DataAccessException;
@Path("/v3/<API key>")
public class <API key> extends getData{
private static final String[] columns={"pgName", "description", "dataSetName"};
public final static String TEXT_CSV = "text/csv";
@Context private HttpServletRequest httpRequest;
/**
* This method get a list of names of protection group
*
* @return String - list of names of protection group
*/
@GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.TEXT_HTML, TEXT_CSV})
public Response constructResponse(@QueryParam("format") String format) {
List<Object[]> data = null;
try {
<API key> upm = getUpm();
java.util.List<ProtectionGroup> protectionGrpLst = upm.getProtectionGroups();
if ( protectionGrpLst != null) {
data = new ArrayList<Object []>();
for(ProtectionGroup pg : protectionGrpLst) {
List<ProtectionElement> pes = new ArrayList<ProtectionElement>(upm.<API key>(pg.<API key>().toString()));
for (ProtectionElement pe : pes) {
Object [] objs = {pg.<API key>(),
pg.<API key>(),
pe.<API key>()};
data.add(objs);
}
}
}
else {
Object [] objs = {"Warning: No Protection Group has defined yet!", "NA", "NA"};
data.add(objs);
}
} catch (<API key> e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (CSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return formatResponse(format, data, columns);
}
}
|
#ifndef <API key>
#define <API key>
#include <string>
#include <vector>
#include "base/basictypes.h"
#include "content/public/browser/<API key>.h"
#include "ui/base/clipboard/clipboard.h"
class GURL;
namespace content {
class <API key> : public <API key> {
public:
<API key>();
virtual void <API key>(
const IPC::Message& message,
BrowserThread::ID* thread) OVERRIDE;
virtual bool OnMessageReceived(const IPC::Message& message,
bool* message_was_ok) OVERRIDE;
private:
virtual ~<API key>();
void OnWriteObjectsAsync(const ui::Clipboard::ObjectMap& objects);
void OnWriteObjectsSync(const ui::Clipboard::ObjectMap& objects,
base::SharedMemoryHandle bitmap_handle);
void OnGetSequenceNumber(const ui::Clipboard::Buffer buffer,
uint64* sequence_number);
void OnIsFormatAvailable(const ui::Clipboard::FormatType& format,
ui::Clipboard::Buffer buffer,
bool* result);
void OnClear(ui::Clipboard::Buffer buffer);
void <API key>(ui::Clipboard::Buffer buffer,
std::vector<string16>* types,
bool* contains_filenames);
void OnReadText(ui::Clipboard::Buffer buffer, string16* result);
void OnReadAsciiText(ui::Clipboard::Buffer buffer, std::string* result);
void OnReadHTML(ui::Clipboard::Buffer buffer, string16* markup, GURL* url,
uint32* fragment_start, uint32* fragment_end);
void OnReadRTF(ui::Clipboard::Buffer buffer, std::string* result);
void OnReadImage(ui::Clipboard::Buffer buffer, IPC::Message* reply_msg);
void OnReadImageReply(const SkBitmap& bitmap, IPC::Message* reply_msg);
void OnReadCustomData(ui::Clipboard::Buffer buffer,
const string16& type,
string16* result);
#if defined(OS_MACOSX)
void <API key>(const string16& text);
#endif
// We have our own clipboard because we want to access the clipboard on the
// IO thread instead of forwarding (possibly synchronous) messages to the UI
// thread. This instance of the clipboard should be accessed only on the IO
// thread.
static ui::Clipboard* GetClipboard();
<API key>(<API key>);
};
} // namespace content
#endif // <API key>
|
# modification, are permitted provided that the following conditions are met:
# and/or other materials provided with the distribution.
# may be used to endorse or promote products derived from this software
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
# OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""Package containing the different outputs.
Each output type is defined inside a module.
"""
|
package org.knopflerfish.service.repositorymanager;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceReference;
import org.osgi.service.repository.Repository;
public class RepositoryInfo implements Comparable<RepositoryInfo> {
final private long id;
final private int rank;
final ServiceReference<Repository> sr;
public RepositoryInfo(ServiceReference<Repository> sr) {
this.id = ((Long)sr.getProperty(Constants.SERVICE_ID)).longValue();
Object r = sr.getProperty(Constants.SERVICE_RANKING);
if (r != null && r instanceof Integer) {
this.rank = ((Integer)r).intValue();
} else {
this.rank = 0;
}
this.sr = sr;
}
public RepositoryInfo(RepositoryInfo old, int rank) {
this.id = old.id;
this.rank = rank;
this.sr = old.sr;
}
public long getId() {
return id;
}
public int getRank() {
return rank;
}
public Object getProperty(String prop) {
return sr.getProperty(prop);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (id ^ (id >>> 32));
return result;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null)
return false;
if (getClass() != o.getClass())
return false;
RepositoryInfo rio = (RepositoryInfo) o;
if (id != rio.id || rank != rio.rank)
return false;
return true;
}
@Override
public int compareTo(RepositoryInfo o) {
if (equals(o)) {
return 0;
}
if (rank != o.rank) {
return o.rank - rank;
} else {
return id < o.id ? -1 : 1;
}
}
public ServiceReference<Repository> getServiceReference() {
return sr;
}
@Override
public String toString() {
return "RepositoryInfo [id=" + id + ", rank=" + rank + "]";
}
}
|
// GB_Descriptor_get: get the status of a descriptor
// A descriptor modifies how the behavoir of a GraphBLAS operation. In the
// current GraphBLAS spec, the following descriptor fields may be set.
// Descriptor field: Descriptor value:
// desc->out GxB_DEFAULT or GrB_REPLACE
// GrB_REPLACE means that the output matrix C is cleared just
// prior to writing results back into it, via C<Mask> = results. This
// descriptor does not affect how C is used to compute the results. If
// GxB_DEFAULT, then C is not cleared before doing C<Mask>=results.
// desc->mask GxB_DEFAULT or GrB_SCMP
// An optional 'write mask' defines how the results are to be written back
// into C. The boolean Mask matrix has the same size as C (Mask is
// typecasted to boolean if it has another type). If the Mask input to
// the GraphBLAS method is NULL, then implicitly Mask(i,j)=1 for all i and
// j. Let Z be the results to be written into C (the same dimension as
// C). If desc->mask is GxB_DEFAULT, and Mask(i,j)=1, then C(i,j) is
// over-written with Z(i,j). Otherwise, if Mask(i,j)=0 C(i,j) is left
// unmodified (it remains an implicit zero if it is so, or its value is
// unchanged if it has one). If desc->mask is GrB_SCMP, then the use of
// Mask is negated: Mask(i,j)=0 means that C(i,j) is overwritten with
// Z(i,j), and Mask(i,j)=1 means that C(i,j) is left unchanged.
// Writing results Z into C via the Mask is written as C<Mask>=Z in
// GraphBLAS notation.
// Note that it is the value of Mask(i,j) that determines how C(i,j) is
// overwritten. If the (i,j) entry is present in the Mask matrix data
// structure but has a numerical value of zero, then it is the same as if
// (i,j) is not present and thus implicitly zero. Both mean 'Mask(i,j)=0'
// in the description above of how the Mask works.
// desc->in0 and desc->in1 GxB_DEFAULT or GrB_TRAN
// A GrB_Matrix passed as an input parameter to GraphBLAS methods can
// optionally transpose them prior to using them. desc->in0 always refers
// to the first input to the method, and desc->in1 always refers to the
// second one.
// If the value of this descriptor is GxB_DEFAULT, then the matrix is used
// as-is. Otherwise, it is transposed first. That is, the results are
// the same as if the transpose of the matrix was passed to the method.
// desc->axb see GraphBLAS.h; can be:
// GrB_DEFAULT automatic selection
// GxB_AxB_GUSTAVSON gather-scatter saxpy method
// GxB_AxB_HEAP heap-based saxpy method
// GxB_AxB_DOT dot product
#include "GB.h"
GrB_Info GB_Descriptor_get // get the contents of a descriptor
(
const GrB_Descriptor desc, // descriptor to query, may be NULL
bool *C_replace, // if true replace C before C<Mask>=Z
bool *Mask_comp, // if true use logical negation of Mask
bool *In0_transpose, // if true transpose first input
bool *In1_transpose, // if true transpose second input
GrB_Desc_Value *AxB_method, // method for C=A*B
GB_Context Context
)
{
// check inputs
// desc may be null, but if not NULL it must be initialized
GB_RETURN_IF_FAULTY (desc) ;
// get the contents of the descriptor
// default values if descriptor is NULL
GrB_Desc_Value C_desc = GxB_DEFAULT ;
GrB_Desc_Value Mask_desc = GxB_DEFAULT ;
GrB_Desc_Value In0_desc = GxB_DEFAULT ;
GrB_Desc_Value In1_desc = GxB_DEFAULT ;
GrB_Desc_Value AxB_desc = GxB_DEFAULT ;
// non-defaults descriptors
if (desc != NULL)
{
// get the contents
C_desc = desc->out ; // DEFAULT or REPLACE
Mask_desc = desc->mask ; // DEFAULT or SCMP
In0_desc = desc->in0 ; // DEFAULT or TRAN
In1_desc = desc->in1 ; // DEFAULT or TRAN
AxB_desc = desc->axb ; // DEFAULT, GUSTAVSON, HEAP, or DOT
}
// check for valid values of each descriptor field
if (!(C_desc == GxB_DEFAULT || C_desc == GrB_REPLACE) ||
!(Mask_desc == GxB_DEFAULT || Mask_desc == GrB_SCMP) ||
!(In0_desc == GxB_DEFAULT || In0_desc == GrB_TRAN) ||
!(In1_desc == GxB_DEFAULT || In1_desc == GrB_TRAN) ||
!(AxB_desc == GxB_DEFAULT || AxB_desc == GxB_AxB_GUSTAVSON ||
AxB_desc == GxB_AxB_DOT || AxB_desc == GxB_AxB_HEAP))
{
return (GB_ERROR (GrB_INVALID_OBJECT, (GB_LOG, "Descriptor invalid"))) ;
}
if (C_replace != NULL)
{
*C_replace = (C_desc == GrB_REPLACE) ;
}
if (Mask_comp != NULL)
{
*Mask_comp = (Mask_desc == GrB_SCMP) ;
}
if (In0_transpose != NULL)
{
*In0_transpose = (In0_desc == GrB_TRAN) ;
}
if (In1_transpose != NULL)
{
*In1_transpose = (In1_desc == GrB_TRAN) ;
}
if (AxB_method != NULL)
{
*AxB_method = AxB_desc ;
}
return (GrB_SUCCESS) ;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.