code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
#ifndef PYTHONIC_BUILTIN_TRUE_HPP
#define PYTHONIC_BUILTIN_TRUE_HPP
#include "pythonic/include/builtins/True.hpp"
#endif
| pombredanne/pythran | pythran/pythonic/builtins/True.hpp | C++ | bsd-3-clause | 123 |
import numpy as np
from numpy import diag, inf
from numpy import copy, dot
from numpy.linalg import norm
class ExceededMaxIterationsError(Exception):
def __init__(self, msg, matrix=[], iteration=[], ds=[]):
self.msg = msg
self.matrix = matrix
self.iteration = iteration
self.ds = ds
def __str__(self):
return repr(self.msg)
def nearcorr(A, tol=[], flag=0, max_iterations=100, n_pos_eig=0,
weights=None, verbose=False,
except_on_too_many_iterations=True):
"""
X = nearcorr(A, tol=[], flag=0, max_iterations=100, n_pos_eig=0,
weights=None, print=0)
Finds the nearest correlation matrix to the symmetric matrix A.
ARGUMENTS
~~~~~~~~~
A is a symmetric numpy array or a ExceededMaxIterationsError object
tol is a convergence tolerance, which defaults to 16*EPS.
If using flag == 1, tol must be a size 2 tuple, with first component
the convergence tolerance and second component a tolerance
for defining "sufficiently positive" eigenvalues.
flag = 0: solve using full eigendecomposition (EIG).
flag = 1: treat as "highly non-positive definite A" and solve
using partial eigendecomposition (EIGS). CURRENTLY NOT IMPLEMENTED
max_iterations is the maximum number of iterations (default 100,
but may need to be increased).
n_pos_eig (optional) is the known number of positive eigenvalues
of A. CURRENTLY NOT IMPLEMENTED
weights is an optional vector defining a diagonal weight matrix diag(W).
verbose = True for display of intermediate output.
CURRENTLY NOT IMPLEMENTED
except_on_too_many_iterations = True to raise an exeption when
number of iterations exceeds max_iterations
except_on_too_many_iterations = False to silently return the best result
found after max_iterations number of iterations
ABOUT
~~~~~~
This is a Python port by Michael Croucher, November 2014
Thanks to Vedran Sego for many useful comments and suggestions.
Original MATLAB code by N. J. Higham, 13/6/01, updated 30/1/13.
Reference: N. J. Higham, Computing the nearest correlation
matrix---A problem from finance. IMA J. Numer. Anal.,
22(3):329-343, 2002.
"""
# If input is an ExceededMaxIterationsError object this
# is a restart computation
if (isinstance(A, ExceededMaxIterationsError)):
ds = copy(A.ds)
A = copy(A.matrix)
else:
ds = np.zeros(np.shape(A))
eps = np.spacing(1)
if not np.all((np.transpose(A) == A)):
raise ValueError('Input Matrix is not symmetric')
if not tol:
tol = eps * np.shape(A)[0] * np.array([1, 1])
if weights is None:
weights = np.ones(np.shape(A)[0])
X = copy(A)
Y = copy(A)
rel_diffY = inf
rel_diffX = inf
rel_diffXY = inf
Whalf = np.sqrt(np.outer(weights, weights))
iteration = 0
while max(rel_diffX, rel_diffY, rel_diffXY) > tol[0]:
iteration += 1
if iteration > max_iterations:
if except_on_too_many_iterations:
if max_iterations == 1:
message = "No solution found in "\
+ str(max_iterations) + " iteration"
else:
message = "No solution found in "\
+ str(max_iterations) + " iterations"
raise ExceededMaxIterationsError(message, X, iteration, ds)
else:
# exceptOnTooManyIterations is false so just silently
# return the result even though it has not converged
return X
Xold = copy(X)
R = X - ds
R_wtd = Whalf*R
if flag == 0:
X = proj_spd(R_wtd)
elif flag == 1:
raise NotImplementedError("Setting 'flag' to 1 is currently\
not implemented.")
X = X / Whalf
ds = X - R
Yold = copy(Y)
Y = copy(X)
np.fill_diagonal(Y, 1)
normY = norm(Y, 'fro')
rel_diffX = norm(X - Xold, 'fro') / norm(X, 'fro')
rel_diffY = norm(Y - Yold, 'fro') / normY
rel_diffXY = norm(Y - X, 'fro') / normY
X = copy(Y)
return X
def proj_spd(A):
# NOTE: the input matrix is assumed to be symmetric
d, v = np.linalg.eigh(A)
A = (v * np.maximum(d, 0)).dot(v.T)
A = (A + A.T) / 2
return(A)
| mikecroucher/nearest_correlation | nearest_correlation.py | Python | bsd-3-clause | 4,572 |
using Shuttle.Core.Contract;
using Shuttle.Core.Pipelines;
namespace Shuttle.Esb
{
public class DistributorPipeline : Pipeline
{
public DistributorPipeline(IServiceBusConfiguration configuration,
IGetWorkMessageObserver getWorkMessageObserver,
IDeserializeTransportMessageObserver deserializeTransportMessageObserver,
IDistributorMessageObserver distributorMessageObserver,
ISerializeTransportMessageObserver serializeTransportMessageObserver,
IDispatchTransportMessageObserver dispatchTransportMessageObserver,
IAcknowledgeMessageObserver acknowledgeMessageObserver,
IDistributorExceptionObserver distributorExceptionObserver)
{
Guard.AgainstNull(configuration, nameof(configuration));
Guard.AgainstNull(getWorkMessageObserver, nameof(getWorkMessageObserver));
Guard.AgainstNull(deserializeTransportMessageObserver, nameof(deserializeTransportMessageObserver));
Guard.AgainstNull(distributorMessageObserver, nameof(distributorMessageObserver));
Guard.AgainstNull(serializeTransportMessageObserver, nameof(serializeTransportMessageObserver));
Guard.AgainstNull(dispatchTransportMessageObserver, nameof(dispatchTransportMessageObserver));
Guard.AgainstNull(acknowledgeMessageObserver, nameof(acknowledgeMessageObserver));
Guard.AgainstNull(distributorExceptionObserver, nameof(distributorExceptionObserver));
State.SetWorkQueue(configuration.Inbox.WorkQueue);
State.SetErrorQueue(configuration.Inbox.ErrorQueue);
RegisterStage("Distribute")
.WithEvent<OnGetMessage>()
.WithEvent<OnDeserializeTransportMessage>()
.WithEvent<OnAfterDeserializeTransportMessage>()
.WithEvent<OnHandleDistributeMessage>()
.WithEvent<OnAfterHandleDistributeMessage>()
.WithEvent<OnSerializeTransportMessage>()
.WithEvent<OnAfterSerializeTransportMessage>()
.WithEvent<OnDispatchTransportMessage>()
.WithEvent<OnAfterDispatchTransportMessage>()
.WithEvent<OnAcknowledgeMessage>()
.WithEvent<OnAfterAcknowledgeMessage>();
RegisterObserver(getWorkMessageObserver);
RegisterObserver(deserializeTransportMessageObserver);
RegisterObserver(distributorMessageObserver);
RegisterObserver(serializeTransportMessageObserver);
RegisterObserver(dispatchTransportMessageObserver);
RegisterObserver(acknowledgeMessageObserver);
RegisterObserver(distributorExceptionObserver); // must be last
}
}
} | Shuttle/shuttle-esb-core | Shuttle.Esb/Pipeline/Pipelines/DistributorPipeline.cs | C# | bsd-3-clause | 2,779 |
package org.basex.gui.dialog;
import static org.basex.core.Text.*;
import java.awt.*;
import java.awt.event.*;
import org.basex.gui.*;
import org.basex.gui.GUIConstants.Msg;
import org.basex.gui.layout.*;
import org.basex.util.*;
/**
* URL dialog.
*
* @author BaseX Team 2005-16, BSD License
* @author Christian Gruen
*/
final class DialogInstallURL extends BaseXDialog {
/** URL. */
private final BaseXTextField url;
/** Buttons. */
private final BaseXBack buttons;
/** Info label. */
private final BaseXLabel info;
/**
* Default constructor.
* @param dialog reference to main dialog
*/
DialogInstallURL(final BaseXDialog dialog) {
super(dialog, INSTALL_FROM_URL);
url = new BaseXTextField(this);
info = new BaseXLabel(" ");
final BaseXLabel link = new BaseXLabel("<html><u>" + Prop.REPO_URL + "</u></html>");
link.setForeground(GUIConstants.BLUE);
link.setCursor(GUIConstants.CURSORHAND);
link.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(final MouseEvent e) {
BaseXDialog.browse(gui, Prop.REPO_URL);
}
});
BaseXBack p = new BaseXBack(new BorderLayout(0, 8));
p.add(url, BorderLayout.NORTH);
p.add(info, BorderLayout.CENTER);
set(p, BorderLayout.CENTER);
p = new BaseXBack(new BorderLayout());
p.add(link, BorderLayout.WEST);
buttons = newButtons(B_OK, B_CANCEL);
p.add(buttons, BorderLayout.EAST);
set(p, BorderLayout.SOUTH);
action(null);
finish();
}
@Override
public void action(final Object cmp) {
ok = !url().isEmpty();
info.setText(ok ? null : Util.info(INVALID_X, "URL"), Msg.ERROR);
enableOK(buttons, B_OK, ok);
}
@Override
public void close() {
if(!ok) return;
super.close();
}
/**
* Returns the url.
* @return url
*/
String url() {
return url.getText();
}
}
| drmacro/basex | basex-core/src/main/java/org/basex/gui/dialog/DialogInstallURL.java | Java | bsd-3-clause | 1,896 |
#!/usr/bin/env python
from tools.load import LoadMatrix
lm=LoadMatrix()
traindat = lm.load_numbers('../data/fm_train_real.dat')
testdat = lm.load_numbers('../data/fm_test_real.dat')
parameter_list = [[traindat,testdat,1.1],[traindat,testdat,1.2]]
def kernel_sparse_gaussian (fm_train_real=traindat,fm_test_real=testdat,width=1.1 ):
from shogun import SparseRealFeatures
import shogun as sg
feats_train=SparseRealFeatures(fm_train_real)
feats_test=SparseRealFeatures(fm_test_real)
kernel=sg.create_kernel("GaussianKernel", width=width)
kernel.init(feats_train, feats_train,)
km_train=kernel.get_kernel_matrix()
kernel.init(feats_train, feats_test)
km_test=kernel.get_kernel_matrix()
return km_train,km_test,kernel
if __name__=='__main__':
print('SparseGaussian')
kernel_sparse_gaussian (*parameter_list[0])
| shogun-toolbox/shogun | examples/undocumented/python/kernel_sparse_gaussian.py | Python | bsd-3-clause | 824 |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE369_Divide_by_Zero__float_zero_33.cpp
Label Definition File: CWE369_Divide_by_Zero__float.label.xml
Template File: sources-sinks-33.tmpl.cpp
*/
/*
* @description
* CWE: 369 Divide by Zero
* BadSource: zero Fixed value of zero
* GoodSource: A hardcoded non-zero number (two)
* Sinks:
* GoodSink: Check value of or near zero before dividing
* BadSink : Divide a constant by data
* Flow Variant: 33 Data flow: use of a C++ reference to data within the same function
*
* */
#include "std_testcase.h"
#include <math.h>
namespace CWE369_Divide_by_Zero__float_zero_33
{
#ifndef OMITBAD
void bad()
{
float data;
float &dataRef = data;
/* Initialize data */
data = 0.0F;
/* POTENTIAL FLAW: Set data to zero */
data = 0.0F;
{
float data = dataRef;
{
/* POTENTIAL FLAW: Possibly divide by zero */
int result = (int)(100.0 / data);
printIntLine(result);
}
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B() uses the GoodSource with the BadSink */
static void goodG2B()
{
float data;
float &dataRef = data;
/* Initialize data */
data = 0.0F;
/* FIX: Use a hardcoded number that won't a divide by zero */
data = 2.0F;
{
float data = dataRef;
{
/* POTENTIAL FLAW: Possibly divide by zero */
int result = (int)(100.0 / data);
printIntLine(result);
}
}
}
/* goodB2G() uses the BadSource with the GoodSink */
static void goodB2G()
{
float data;
float &dataRef = data;
/* Initialize data */
data = 0.0F;
/* POTENTIAL FLAW: Set data to zero */
data = 0.0F;
{
float data = dataRef;
/* FIX: Check for value of or near zero before dividing */
if(fabs(data) > 0.000001)
{
int result = (int)(100.0 / data);
printIntLine(result);
}
else
{
printLine("This would result in a divide by zero");
}
}
}
void good()
{
goodG2B();
goodB2G();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE369_Divide_by_Zero__float_zero_33; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| JianpingZeng/xcc | xcc/test/juliet/testcases/CWE369_Divide_by_Zero/s01/CWE369_Divide_by_Zero__float_zero_33.cpp | C++ | bsd-3-clause | 3,055 |
/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkGeometryDataSerializer.h"
#include "mitkGeometryData.h"
#include "mitkGeometry3D.h"
#include "mitkIOUtil.h"
#include <tinyxml.h>
MITK_REGISTER_SERIALIZER(GeometryDataSerializer)
mitk::GeometryDataSerializer::GeometryDataSerializer()
{
}
mitk::GeometryDataSerializer::~GeometryDataSerializer()
{
}
std::string mitk::GeometryDataSerializer::Serialize()
{
// Verify good input data type
const GeometryData* ps = dynamic_cast<const GeometryData *>( m_Data.GetPointer() );
if (ps == NULL)
{
MITK_ERROR << " Object at " << (const void*) this->m_Data
<< " is not an mitk::GeometryData. Cannot serialize...";
return "";
}
// Construct the full filename to store the geometry
std::string filename(this->GetUniqueFilenameInWorkingDirectory());
filename += "_";
filename += m_FilenameHint;
filename += ".mitkgeometry";
std::string fullname(m_WorkingDirectory);
fullname += IOUtil::GetDirectorySeparator();
fullname += filename;
try
{
IOUtil::Save( ps, fullname );
// in case of success, return only the relative filename part
return filename;
}
catch (const std::exception& e)
{
MITK_ERROR << "Unable to serialize GeometryData object: "<< e.what();
}
// when failed, return empty string
return "";
}
| NifTK/MITK | Modules/SceneSerialization/src/mitkGeometryDataSerializer.cpp | C++ | bsd-3-clause | 1,794 |
<?php
include "util.inc";
$state = isset($_GET['state']) ? $_GET['state'] : "schema";
switch($state)
{
case "schema":
if (isset($_SESSION['schema'])) {
unlink($_SESSION['schema']['path']);
}
$_SESSION = array();
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time()-42000, '/');
}
session_destroy();
break;
case "params":
unset($_SESSION['params']);
break;
case "query":
unset($_SESSION['query']);
break;
}
go_home();
?>
| fresskarma/tinyos-1.x | contrib/nucleus/tools/php/nucleus/del.php | PHP | bsd-3-clause | 528 |
/*
* Copyright (c) Contributors, http://aurora-sim.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``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 CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System.Collections.Generic;
using OpenMetaverse;
using Aurora.Framework;
namespace Aurora.Framework
{
public interface IGroupsServiceConnector : IAuroraDataPlugin
{
void CreateGroup(UUID groupID, string name, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish, UUID founderID, UUID OwnerRoleID);
void UpdateGroup(UUID requestingAgentID, UUID groupID, string charter, int showInList, UUID insigniaID, int membershipFee, int openEnrollment, int allowPublish, int maturePublish);
void UpdateGroupFounder(UUID groupID, UUID newOwner, bool keepOldOwnerInGroup);
void AddGroupNotice(UUID requestingAgentID, UUID groupID, UUID noticeID, string fromName, string subject, string message, UUID ItemID, int AssetType, string ItemName);
bool EditGroupNotice(UUID requestingAgentID, UUID groupID, UUID noticeID, string subject, string message);
bool RemoveGroupNotice(UUID requestingAgentID, UUID groupID, UUID noticeID);
string SetAgentActiveGroup(UUID AgentID, UUID GroupID);
UUID GetAgentActiveGroup(UUID RequestingAgentID, UUID AgentID);
string SetAgentGroupSelectedRole(UUID AgentID, UUID GroupID, UUID RoleID);
void AddAgentToGroup(UUID requestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID);
bool RemoveAgentFromGroup(UUID requestingAgentID, UUID AgentID, UUID GroupID);
void AddRoleToGroup(UUID requestingAgentID, UUID GroupID, UUID RoleID, string Name, string Description, string Title, ulong Powers);
void UpdateRole(UUID requestingAgentID, UUID GroupID, UUID RoleID, string Name, string Desc, string Title, ulong Powers);
void RemoveRoleFromGroup(UUID requestingAgentID, UUID RoleID, UUID GroupID);
void AddAgentToRole(UUID requestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID);
void RemoveAgentFromRole(UUID requestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID);
void SetAgentGroupInfo(UUID requestingAgentID, UUID AgentID, UUID GroupID, int AcceptNotices, int ListInProfile);
void AddAgentGroupInvite(UUID requestingAgentID, UUID inviteID, UUID GroupID, UUID roleID, UUID AgentID, string FromAgentName);
void RemoveAgentInvite(UUID requestingAgentID, UUID inviteID);
uint GetNumberOfGroupNotices(UUID requestingAgentID, UUID GroupID);
uint GetNumberOfGroupNotices(UUID requestingAgentID, List<UUID> GroupIDs);
uint GetNumberOfGroups(UUID requestingAgentID, Dictionary<string, bool> boolFields);
GroupRecord GetGroupRecord(UUID requestingAgentID, UUID GroupID, string GroupName);
List<GroupRecord> GetGroupRecords(UUID requestingAgentID, uint start, uint count, Dictionary<string, bool> sort, Dictionary<string, bool> boolFields);
List<GroupRecord> GetGroupRecords(UUID requestingAgentID, List<UUID> GroupIDs);
GroupProfileData GetMemberGroupProfile(UUID requestingAgentID, UUID GroupID, UUID AgentID);
GroupMembershipData GetGroupMembershipData(UUID requestingAgentID, UUID GroupID, UUID AgentID);
List<GroupMembershipData> GetAgentGroupMemberships(UUID requestingAgentID, UUID AgentID);
GroupInviteInfo GetAgentToGroupInvite(UUID requestingAgentID, UUID inviteID);
List<GroupInviteInfo> GetGroupInvites(UUID requestingAgentID);
GroupMembersData GetAgentGroupMemberData(UUID requestingAgentID, UUID GroupID, UUID AgentID);
List<GroupMembersData> GetGroupMembers(UUID requestingAgentID, UUID GroupID);
List<DirGroupsReplyData> FindGroups(UUID requestingAgentID, string search, uint? start, uint? count, uint queryflags);
List<GroupRolesData> GetAgentGroupRoles(UUID requestingAgentID, UUID AgentID, UUID GroupID);
List<GroupRolesData> GetGroupRoles(UUID requestingAgentID, UUID GroupID);
List<GroupRoleMembersData> GetGroupRoleMembers(UUID requestingAgentID, UUID GroupID);
GroupNoticeData GetGroupNoticeData(UUID requestingAgentID, UUID noticeID);
GroupNoticeInfo GetGroupNotice(UUID requestingAgentID, UUID noticeID);
List<GroupNoticeData> GetGroupNotices(UUID requestingAgentID, uint start, uint count, UUID GroupID);
List<GroupNoticeData> GetGroupNotices(UUID requestingAgentID, uint start, uint count, List<UUID> GroupIDs);
GroupProfileData GetGroupProfile(UUID requestingAgentID, UUID GroupID);
List<GroupTitlesData> GetGroupTitles(UUID requestingAgentID, UUID GroupID);
List<GroupProposalInfo> GetActiveProposals(UUID agentID, UUID groupID);
List<GroupProposalInfo> GetInactiveProposals(UUID agentID, UUID groupID);
void VoteOnActiveProposals(UUID agentID, UUID groupID, UUID proposalID, string vote);
void AddGroupProposal(UUID agentID, GroupProposalInfo info);
}
} | NanaYngvarrdottir/Software-Testing | VirtualReality/Framework/DatabaseInterfaces/IGroupsServiceConnector.cs | C# | bsd-3-clause | 6,596 |
# $Id: __init__.py 5618 2008-07-28 08:37:32Z strank $
# Author: David Goodger <goodger@python.org>
# Copyright: This module has been placed in the public domain.
"""
This package contains Docutils Writer modules.
"""
__docformat__ = 'reStructuredText'
import os.path
import docutils
from docutils import languages, Component
from docutils.transforms import universal
class Writer(Component):
"""
Abstract base class for docutils Writers.
Each writer module or package must export a subclass also called 'Writer'.
Each writer must support all standard node types listed in
`docutils.nodes.node_class_names`.
The `write()` method is the main entry point.
"""
component_type = 'writer'
config_section = 'writers'
def get_transforms(self):
return Component.get_transforms(self) + [
universal.Messages,
universal.FilterMessages,
universal.StripClassesAndElements,]
document = None
"""The document to write (Docutils doctree); set by `write`."""
output = None
"""Final translated form of `document` (Unicode string for text, binary
string for other forms); set by `translate`."""
language = None
"""Language module for the document; set by `write`."""
destination = None
"""`docutils.io` Output object; where to write the document.
Set by `write`."""
def __init__(self):
# Currently only used by HTML writer for output fragments:
self.parts = {}
"""Mapping of document part names to fragments of `self.output`.
Values are Unicode strings; encoding is up to the client. The 'whole'
key should contain the entire document output.
"""
def write(self, document, destination):
"""
Process a document into its final form.
Translate `document` (a Docutils document tree) into the Writer's
native format, and write it out to its `destination` (a
`docutils.io.Output` subclass object).
Normally not overridden or extended in subclasses.
"""
self.document = document
self.language = languages.get_language(
document.settings.language_code)
self.destination = destination
self.translate()
output = self.destination.write(self.output)
return output
def translate(self):
"""
Do final translation of `self.document` into `self.output`. Called
from `write`. Override in subclasses.
Usually done with a `docutils.nodes.NodeVisitor` subclass, in
combination with a call to `docutils.nodes.Node.walk()` or
`docutils.nodes.Node.walkabout()`. The ``NodeVisitor`` subclass must
support all standard elements (listed in
`docutils.nodes.node_class_names`) and possibly non-standard elements
used by the current Reader as well.
"""
raise NotImplementedError('subclass must override this method')
def assemble_parts(self):
"""Assemble the `self.parts` dictionary. Extend in subclasses."""
self.parts['whole'] = self.output
self.parts['encoding'] = self.document.settings.output_encoding
self.parts['version'] = docutils.__version__
class UnfilteredWriter(Writer):
"""
A writer that passes the document tree on unchanged (e.g. a
serializer.)
Documents written by UnfilteredWriters are typically reused at a
later date using a subclass of `readers.ReReader`.
"""
def get_transforms(self):
# Do not add any transforms. When the document is reused
# later, the then-used writer will add the appropriate
# transforms.
return Component.get_transforms(self)
_writer_aliases = {
'html': 'html4css1',
'latex': 'latex2e',
'pprint': 'pseudoxml',
'pformat': 'pseudoxml',
'pdf': 'rlpdf',
'xml': 'docutils_xml',
's5': 's5_html'}
def get_writer_class(writer_name):
"""Return the Writer class from the `writer_name` module."""
writer_name = writer_name.lower()
if writer_name in _writer_aliases:
writer_name = _writer_aliases[writer_name]
module = __import__(writer_name, globals(), locals())
return module.Writer
| spreeker/democracygame | external_apps/docutils-snapshot/docutils/writers/__init__.py | Python | bsd-3-clause | 4,258 |
import numpy as np
import paths
import pyregion
from astropy import coordinates
from astropy import units as u
from astropy import table
from astropy.table import Table,Column
import latex_info
from latex_info import latexdict, exp_to_tex, format_float
tbl = Table.read(paths.tpath('PPV_H2CO_Temperature.ipac'), format='ascii.ipac')
def make_column(colname, errcolname, outcolname, unit, formatstr="${0:0.2f}\pm{1:0.2f}$"):
data = [formatstr.format(d,e) for d,e in zip(tbl[colname], tbl[errcolname])]
return Column(data=data, name=outcolname, unit=unit)
def make_column_asymm(colname, errlowcolname, errhighcolname, outcolname, unit, formatstr="${0:0.2f}^{{+{1:0.2f}}}_{{-{2:0.2f}}}$"):
data = [formatstr.format(d,el,eh) for d,el,eh in zip(tbl[colname],
tbl[colname]-tbl[errlowcolname],
tbl[errhighcolname]-tbl[colname])]
return Column(data=data, name=outcolname, unit=unit)
columns = {'_idx': 'Source ID',
'DespoticTem': '$T_{gas, turb}$',
'logh2column': 'log($n(H_2)$)',
}
#'spline_h2coratio321303': '$R_1$',
#'espline_h2coratio321303': '$\sigma(R_1)$',}
def format_float(st):
return exp_to_tex("{0:0.3g}".format(st))
def format_int(st):
return ("{0:d}".format(int(st)))
formats = {'DespoticTem': format_int,
'logh2column': format_float,
'v_rms': format_float,
'v_cen': format_float,
'$\sigma_v$': format_float,
'$v_{lsr}$': format_float,
'Max $T_B(3_{0,3})$': format_float,
#'$T_{gas}$': format_float,
}
outtbl = Table([tbl['_idx'],
make_column('ratio321303', 'eratio321303', '$R_1$', None, "${0:0.3f}\pm{1:0.3f}$"),
Column(tbl['v_rms']/1e3, name='$\sigma_v$', unit=u.km/u.s),
Column(tbl['v_cen']/1e3, name='$v_{lsr}$', unit=u.km/u.s),
Column(tbl['Smax303'], name='Max $T_B(3_{0,3})$', unit=u.K),
#make_column('spline_ampH2CO', 'espline_ampH2CO', '$T_B(H_2CO)$', u.K),
#make_column('logh2column', 'elogh2column', 'log($n(H_2)$)', u.cm**-2),
tbl['logh2column'],
make_column_asymm('temperature_chi2', 'tmin1sig_chi2', 'tmax1sig_chi2', '$T_{gas}$', u.K),
Column(data=tbl['DespoticTem'], name='DespoticTem', unit=u.K),
]
)
for old, new in columns.items():
outtbl.rename_column(old, new)
if old in formats:
formats[new] = formats[old]
latexdict['header_start'] = '\label{tab:dendroregions}'
latexdict['caption'] = '\\formaldehyde Parameters and Fit Properties for dendrogram-selected clumps'
latexdict['tablefoot'] = ('\par\n')
#latexdict['col_align'] = 'lllrr'
#latexdict['tabletype'] = 'longtable'
#latexdict['tabulartype'] = 'longtable'
outtbl.write(paths.tpath('dendro_props.tex'), format='ascii.latex',
latexdict=latexdict,
formats=formats,
)
outtbl[::10].write(paths.tpath('dendro_props_excerpt.tex'), format='ascii.latex',
latexdict=latexdict,
formats=formats,
)
| adamginsburg/APEX_CMZ_H2CO | analysis/texify_dendro_table.py | Python | bsd-3-clause | 3,226 |
/*
* Copyright (c) 2014, Apptentive, Inc. All Rights Reserved.
* Please refer to the LICENSE file for the terms and conditions
* under which redistribution and use of this file is permitted.
*/
package com.apptentive.android.sdk.module.messagecenter.view;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import com.apptentive.android.sdk.Log;
import com.apptentive.android.sdk.model.*;
/**
* @author Sky Kelsey
*/
public class MessageAdapter<T extends Message> extends ArrayAdapter<T> {
public MessageAdapter(Context context) {
super(context, 0);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Message message = getItem(position);
if (message.getBaseType() == Payload.BaseType.message) {
switch (message.getType()) {
case TextMessage:
return new TextMessageView(parent.getContext(), (TextMessage) message);
case FileMessage:
return new FileMessageView(parent.getContext(), (FileMessage) message);
case AutomatedMessage:
return new AutomatedMessageView(parent.getContext(), (AutomatedMessage) message);
default:
Log.a("Unrecognized message type: %s", message.getType());
return null;
}
}
Log.d("Can't render non-Message Payload as Message: %s", message.getType());
return null;
}
}
| apptentive/apptentive-trigger-io | forge-workspace/modules/apptentive/inspector/an-inspector/ForgeModule/src/com/apptentive/android/sdk/module/messagecenter/view/MessageAdapter.java | Java | bsd-3-clause | 1,371 |
using System.Collections.Generic;
using System.Runtime.Serialization;
using Funq;
using ServiceStack.Common;
using ServiceStack.Common.Web;
using ServiceStack.DataAnnotations;
using ServiceStack.OrmLite;
using ServiceStack.Razor;
using ServiceStack.ServiceHost;
using ServiceStack.ServiceInterface;
using ServiceStack.WebHost.Endpoints;
//The entire C# code for the stand-alone RazorRockstars demo.
namespace RazorRockstars.Console.Files
{
public class AppHost : AppHostHttpListenerBase
{
public AppHost() : base("Test Razor", typeof(AppHost).Assembly) { }
public override void Configure(Container container)
{
Plugins.Add(new RazorFormat());
container.Register<IDbConnectionFactory>(
new OrmLiteConnectionFactory(":memory:", false, SqliteDialect.Provider));
using (var db = container.Resolve<IDbConnectionFactory>().OpenDbConnection())
{
db.CreateTable<Rockstar>(overwrite: false); //Create table if not exists
db.Insert(Rockstar.SeedData); //Populate with seed data
}
}
private static void Main(string[] args)
{
var appHost = new AppHost();
appHost.Init();
appHost.Start("http://*:1337/");
System.Console.WriteLine("Listening on http://localhost:1337/ ...");
System.Console.ReadLine();
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
}
}
public class Rockstar
{
public static Rockstar[] SeedData = new[] {
new Rockstar(1, "Jimi", "Hendrix", 27),
new Rockstar(2, "Janis", "Joplin", 27),
new Rockstar(3, "Jim", "Morrisson", 27),
new Rockstar(4, "Kurt", "Cobain", 27),
new Rockstar(5, "Elvis", "Presley", 42),
new Rockstar(6, "Michael", "Jackson", 50),
};
[AutoIncrement]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int? Age { get; set; }
public Rockstar() { }
public Rockstar(int id, string firstName, string lastName, int age)
{
Id = id;
FirstName = firstName;
LastName = lastName;
Age = age;
}
}
[Route("/rockstars")]
[Route("/rockstars/aged/{Age}")]
[Route("/rockstars/delete/{Delete}")]
[Route("/rockstars/{Id}")]
public class Rockstars
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int? Age { get; set; }
public string Delete { get; set; }
public string View { get; set; }
public string Template { get; set; }
}
[DataContract] //Attrs for CSV Format to recognize it's a DTO and serialize the Enumerable property
public class RockstarsResponse
{
[DataMember] public int Total { get; set; }
[DataMember] public int? Aged { get; set; }
[DataMember] public List<Rockstar> Results { get; set; }
}
public class RockstarsService : RestServiceBase<Rockstars>
{
public IDbConnectionFactory DbFactory { get; set; }
public override object OnGet(Rockstars request)
{
using (var db = DbFactory.OpenDbConnection())
{
if (request.Delete == "reset")
{
db.DeleteAll<Rockstar>();
db.Insert(Rockstar.SeedData);
}
else if (request.Delete.IsInt())
{
db.DeleteById<Rockstar>(request.Delete.ToInt());
}
var response = new RockstarsResponse {
Aged = request.Age,
Total = db.GetScalar<int>("select count(*) from Rockstar"),
Results = request.Id != default(int) ?
db.Select<Rockstar>(q => q.Id == request.Id)
: request.Age.HasValue ?
db.Select<Rockstar>(q => q.Age == request.Age.Value)
: db.Select<Rockstar>()
};
if (request.View != null || request.Template != null)
return new HttpResult(response) {
View = request.View,
Template = request.Template,
};
return response;
}
}
public override object OnPost(Rockstars request)
{
using (var db = DbFactory.OpenDbConnection())
{
db.Insert(request.TranslateTo<Rockstar>());
return OnGet(new Rockstars());
}
}
}
} | meebey/ServiceStack | tests/RazorRockstars.Console.Files/AppHost.cs | C# | bsd-3-clause | 4,881 |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.bgfx;
import javax.annotation.*;
import java.nio.*;
import org.lwjgl.system.*;
import static org.lwjgl.system.MemoryUtil.*;
/**
* GPU info.
*
* <h3>Layout</h3>
*
* <pre><code>
* struct bgfx_caps_gpu_t {
* uint16_t {@link #vendorId};
* uint16_t {@link #deviceId};
* }</code></pre>
*/
@NativeType("struct bgfx_caps_gpu_t")
public class BGFXCapsGPU extends Struct {
/** The struct size in bytes. */
public static final int SIZEOF;
/** The struct alignment in bytes. */
public static final int ALIGNOF;
/** The struct member offsets. */
public static final int
VENDORID,
DEVICEID;
static {
Layout layout = __struct(
__member(2),
__member(2)
);
SIZEOF = layout.getSize();
ALIGNOF = layout.getAlignment();
VENDORID = layout.offsetof(0);
DEVICEID = layout.offsetof(1);
}
/**
* Creates a {@code BGFXCapsGPU} instance at the current position of the specified {@link ByteBuffer} container. Changes to the buffer's content will be
* visible to the struct instance and vice versa.
*
* <p>The created instance holds a strong reference to the container object.</p>
*/
public BGFXCapsGPU(ByteBuffer container) {
super(memAddress(container), __checkContainer(container, SIZEOF));
}
@Override
public int sizeof() { return SIZEOF; }
/** vendor PCI id. One of:<br><table><tr><td>{@link BGFX#BGFX_PCI_ID_NONE PCI_ID_NONE}</td><td>{@link BGFX#BGFX_PCI_ID_SOFTWARE_RASTERIZER PCI_ID_SOFTWARE_RASTERIZER}</td><td>{@link BGFX#BGFX_PCI_ID_AMD PCI_ID_AMD}</td><td>{@link BGFX#BGFX_PCI_ID_APPLE PCI_ID_APPLE}</td><td>{@link BGFX#BGFX_PCI_ID_INTEL PCI_ID_INTEL}</td></tr><tr><td>{@link BGFX#BGFX_PCI_ID_NVIDIA PCI_ID_NVIDIA}</td><td>{@link BGFX#BGFX_PCI_ID_MICROSOFT PCI_ID_MICROSOFT}</td></tr></table> */
@NativeType("uint16_t")
public short vendorId() { return nvendorId(address()); }
/** device id */
@NativeType("uint16_t")
public short deviceId() { return ndeviceId(address()); }
// -----------------------------------
/** Returns a new {@code BGFXCapsGPU} instance for the specified memory address. */
public static BGFXCapsGPU create(long address) {
return wrap(BGFXCapsGPU.class, address);
}
/** Like {@link #create(long) create}, but returns {@code null} if {@code address} is {@code NULL}. */
@Nullable
public static BGFXCapsGPU createSafe(long address) {
return address == NULL ? null : wrap(BGFXCapsGPU.class, address);
}
/**
* Create a {@link BGFXCapsGPU.Buffer} instance at the specified memory.
*
* @param address the memory address
* @param capacity the buffer capacity
*/
public static BGFXCapsGPU.Buffer create(long address, int capacity) {
return wrap(Buffer.class, address, capacity);
}
/** Like {@link #create(long, int) create}, but returns {@code null} if {@code address} is {@code NULL}. */
@Nullable
public static BGFXCapsGPU.Buffer createSafe(long address, int capacity) {
return address == NULL ? null : wrap(Buffer.class, address, capacity);
}
// -----------------------------------
/** Unsafe version of {@link #vendorId}. */
public static short nvendorId(long struct) { return UNSAFE.getShort(null, struct + BGFXCapsGPU.VENDORID); }
/** Unsafe version of {@link #deviceId}. */
public static short ndeviceId(long struct) { return UNSAFE.getShort(null, struct + BGFXCapsGPU.DEVICEID); }
// -----------------------------------
/** An array of {@link BGFXCapsGPU} structs. */
public static class Buffer extends StructBuffer<BGFXCapsGPU, Buffer> {
private static final BGFXCapsGPU ELEMENT_FACTORY = BGFXCapsGPU.create(-1L);
/**
* Creates a new {@code BGFXCapsGPU.Buffer} instance backed by the specified container.
*
* Changes to the container's content will be visible to the struct buffer instance and vice versa. The two buffers' position, limit, and mark values
* will be independent. The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided
* by {@link BGFXCapsGPU#SIZEOF}, and its mark will be undefined.
*
* <p>The created buffer instance holds a strong reference to the container object.</p>
*/
public Buffer(ByteBuffer container) {
super(container, container.remaining() / SIZEOF);
}
public Buffer(long address, int cap) {
super(address, null, -1, 0, cap, cap);
}
Buffer(long address, @Nullable ByteBuffer container, int mark, int pos, int lim, int cap) {
super(address, container, mark, pos, lim, cap);
}
@Override
protected Buffer self() {
return this;
}
@Override
protected BGFXCapsGPU getElementFactory() {
return ELEMENT_FACTORY;
}
/** @return the value of the {@link BGFXCapsGPU#vendorId} field. */
@NativeType("uint16_t")
public short vendorId() { return BGFXCapsGPU.nvendorId(address()); }
/** @return the value of the {@link BGFXCapsGPU#deviceId} field. */
@NativeType("uint16_t")
public short deviceId() { return BGFXCapsGPU.ndeviceId(address()); }
}
} | LWJGL-CI/lwjgl3 | modules/lwjgl/bgfx/src/generated/java/org/lwjgl/bgfx/BGFXCapsGPU.java | Java | bsd-3-clause | 5,587 |
import sys
import pytest
from numpy.testing import (
assert_, assert_array_equal, assert_raises,
)
import numpy as np
from numpy import random
class TestRegression:
def test_VonMises_range(self):
# Make sure generated random variables are in [-pi, pi].
# Regression test for ticket #986.
for mu in np.linspace(-7., 7., 5):
r = random.vonmises(mu, 1, 50)
assert_(np.all(r > -np.pi) and np.all(r <= np.pi))
def test_hypergeometric_range(self):
# Test for ticket #921
assert_(np.all(random.hypergeometric(3, 18, 11, size=10) < 4))
assert_(np.all(random.hypergeometric(18, 3, 11, size=10) > 0))
# Test for ticket #5623
args = [
(2**20 - 2, 2**20 - 2, 2**20 - 2), # Check for 32-bit systems
]
is_64bits = sys.maxsize > 2**32
if is_64bits and sys.platform != 'win32':
# Check for 64-bit systems
args.append((2**40 - 2, 2**40 - 2, 2**40 - 2))
for arg in args:
assert_(random.hypergeometric(*arg) > 0)
def test_logseries_convergence(self):
# Test for ticket #923
N = 1000
random.seed(0)
rvsn = random.logseries(0.8, size=N)
# these two frequency counts should be close to theoretical
# numbers with this large sample
# theoretical large N result is 0.49706795
freq = np.sum(rvsn == 1) / N
msg = f'Frequency was {freq:f}, should be > 0.45'
assert_(freq > 0.45, msg)
# theoretical large N result is 0.19882718
freq = np.sum(rvsn == 2) / N
msg = f'Frequency was {freq:f}, should be < 0.23'
assert_(freq < 0.23, msg)
def test_shuffle_mixed_dimension(self):
# Test for trac ticket #2074
for t in [[1, 2, 3, None],
[(1, 1), (2, 2), (3, 3), None],
[1, (2, 2), (3, 3), None],
[(1, 1), 2, 3, None]]:
random.seed(12345)
shuffled = list(t)
random.shuffle(shuffled)
expected = np.array([t[0], t[3], t[1], t[2]], dtype=object)
assert_array_equal(np.array(shuffled, dtype=object), expected)
def test_call_within_randomstate(self):
# Check that custom RandomState does not call into global state
m = random.RandomState()
res = np.array([0, 8, 7, 2, 1, 9, 4, 7, 0, 3])
for i in range(3):
random.seed(i)
m.seed(4321)
# If m.state is not honored, the result will change
assert_array_equal(m.choice(10, size=10, p=np.ones(10)/10.), res)
def test_multivariate_normal_size_types(self):
# Test for multivariate_normal issue with 'size' argument.
# Check that the multivariate_normal size argument can be a
# numpy integer.
random.multivariate_normal([0], [[0]], size=1)
random.multivariate_normal([0], [[0]], size=np.int_(1))
random.multivariate_normal([0], [[0]], size=np.int64(1))
def test_beta_small_parameters(self):
# Test that beta with small a and b parameters does not produce
# NaNs due to roundoff errors causing 0 / 0, gh-5851
random.seed(1234567890)
x = random.beta(0.0001, 0.0001, size=100)
assert_(not np.any(np.isnan(x)), 'Nans in random.beta')
def test_choice_sum_of_probs_tolerance(self):
# The sum of probs should be 1.0 with some tolerance.
# For low precision dtypes the tolerance was too tight.
# See numpy github issue 6123.
random.seed(1234)
a = [1, 2, 3]
counts = [4, 4, 2]
for dt in np.float16, np.float32, np.float64:
probs = np.array(counts, dtype=dt) / sum(counts)
c = random.choice(a, p=probs)
assert_(c in a)
assert_raises(ValueError, random.choice, a, p=probs*0.9)
def test_shuffle_of_array_of_different_length_strings(self):
# Test that permuting an array of different length strings
# will not cause a segfault on garbage collection
# Tests gh-7710
random.seed(1234)
a = np.array(['a', 'a' * 1000])
for _ in range(100):
random.shuffle(a)
# Force Garbage Collection - should not segfault.
import gc
gc.collect()
def test_shuffle_of_array_of_objects(self):
# Test that permuting an array of objects will not cause
# a segfault on garbage collection.
# See gh-7719
random.seed(1234)
a = np.array([np.arange(1), np.arange(4)], dtype=object)
for _ in range(1000):
random.shuffle(a)
# Force Garbage Collection - should not segfault.
import gc
gc.collect()
def test_permutation_subclass(self):
class N(np.ndarray):
pass
random.seed(1)
orig = np.arange(3).view(N)
perm = random.permutation(orig)
assert_array_equal(perm, np.array([0, 2, 1]))
assert_array_equal(orig, np.arange(3).view(N))
class M:
a = np.arange(5)
def __array__(self):
return self.a
random.seed(1)
m = M()
perm = random.permutation(m)
assert_array_equal(perm, np.array([2, 1, 4, 0, 3]))
assert_array_equal(m.__array__(), np.arange(5))
def test_warns_byteorder(self):
# GH 13159
other_byteord_dt = '<i4' if sys.byteorder == 'big' else '>i4'
with pytest.deprecated_call(match='non-native byteorder is not'):
random.randint(0, 200, size=10, dtype=other_byteord_dt)
def test_named_argument_initialization(self):
# GH 13669
rs1 = np.random.RandomState(123456789)
rs2 = np.random.RandomState(seed=123456789)
assert rs1.randint(0, 100) == rs2.randint(0, 100)
def test_choice_retun_dtype(self):
# GH 9867
c = np.random.choice(10, p=[.1]*10, size=2)
assert c.dtype == np.dtype(int)
c = np.random.choice(10, p=[.1]*10, replace=False, size=2)
assert c.dtype == np.dtype(int)
c = np.random.choice(10, size=2)
assert c.dtype == np.dtype(int)
c = np.random.choice(10, replace=False, size=2)
assert c.dtype == np.dtype(int)
@pytest.mark.skipif(np.iinfo('l').max < 2**32,
reason='Cannot test with 32-bit C long')
def test_randint_117(self):
# GH 14189
random.seed(0)
expected = np.array([2357136044, 2546248239, 3071714933, 3626093760,
2588848963, 3684848379, 2340255427, 3638918503,
1819583497, 2678185683], dtype='int64')
actual = random.randint(2**32, size=10)
assert_array_equal(actual, expected)
def test_p_zero_stream(self):
# Regression test for gh-14522. Ensure that future versions
# generate the same variates as version 1.16.
np.random.seed(12345)
assert_array_equal(random.binomial(1, [0, 0.25, 0.5, 0.75, 1]),
[0, 0, 0, 1, 1])
def test_n_zero_stream(self):
# Regression test for gh-14522. Ensure that future versions
# generate the same variates as version 1.16.
np.random.seed(8675309)
expected = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[3, 4, 2, 3, 3, 1, 5, 3, 1, 3]])
assert_array_equal(random.binomial([[0], [10]], 0.25, size=(2, 10)),
expected)
| simongibbons/numpy | numpy/random/tests/test_randomstate_regression.py | Python | bsd-3-clause | 7,541 |
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build darwin dragonfly freebsd linux netbsd openbsd
// DNS client: see RFC 1035.
// Has to be linked into package net for Dial.
// TODO(rsc):
// Check periodically whether /etc/resolv.conf has changed.
// Could potentially handle many outstanding lookups faster.
// Could have a small cache.
// Random UDP source port (net.Dial should do that for us).
// Random request IDs.
package net
import (
"io"
"math/rand"
"sync"
"time"
)
// Send a request on the connection and hope for a reply.
// Up to cfg.attempts attempts.
func exchange(cfg *dnsConfig, c Conn, name string, qtype uint16) (*dnsMsg, error) {
_, useTCP := c.(*TCPConn)
if len(name) >= 256 {
return nil, &DNSError{Err: "name too long", Name: name}
}
out := new(dnsMsg)
out.id = uint16(rand.Int()) ^ uint16(time.Now().UnixNano())
out.question = []dnsQuestion{
{name, qtype, dnsClassINET},
}
out.recursion_desired = true
msg, ok := out.Pack()
if !ok {
return nil, &DNSError{Err: "internal error - cannot pack message", Name: name}
}
if useTCP {
mlen := uint16(len(msg))
msg = append([]byte{byte(mlen >> 8), byte(mlen)}, msg...)
}
for attempt := 0; attempt < cfg.attempts; attempt++ {
n, err := c.Write(msg)
if err != nil {
return nil, err
}
if cfg.timeout == 0 {
c.SetReadDeadline(noDeadline)
} else {
c.SetReadDeadline(time.Now().Add(time.Duration(cfg.timeout) * time.Second))
}
buf := make([]byte, 2000)
if useTCP {
n, err = io.ReadFull(c, buf[:2])
if err != nil {
if e, ok := err.(Error); ok && e.Timeout() {
continue
}
}
mlen := int(buf[0])<<8 | int(buf[1])
if mlen > len(buf) {
buf = make([]byte, mlen)
}
n, err = io.ReadFull(c, buf[:mlen])
} else {
n, err = c.Read(buf)
}
if err != nil {
if e, ok := err.(Error); ok && e.Timeout() {
continue
}
return nil, err
}
buf = buf[:n]
in := new(dnsMsg)
if !in.Unpack(buf) || in.id != out.id {
continue
}
return in, nil
}
var server string
if a := c.RemoteAddr(); a != nil {
server = a.String()
}
return nil, &DNSError{Err: "no answer from server", Name: name, Server: server, IsTimeout: true}
}
// Do a lookup for a single name, which must be rooted
// (otherwise answer will not find the answers).
func tryOneName(cfg *dnsConfig, name string, qtype uint16) (cname string, addrs []dnsRR, err error) {
if len(cfg.servers) == 0 {
return "", nil, &DNSError{Err: "no DNS servers", Name: name}
}
for i := 0; i < len(cfg.servers); i++ {
// Calling Dial here is scary -- we have to be sure
// not to dial a name that will require a DNS lookup,
// or Dial will call back here to translate it.
// The DNS config parser has already checked that
// all the cfg.servers[i] are IP addresses, which
// Dial will use without a DNS lookup.
server := cfg.servers[i] + ":53"
c, cerr := Dial("udp", server)
if cerr != nil {
err = cerr
continue
}
msg, merr := exchange(cfg, c, name, qtype)
c.Close()
if merr != nil {
err = merr
continue
}
if msg.truncated { // see RFC 5966
c, cerr = Dial("tcp", server)
if cerr != nil {
err = cerr
continue
}
msg, merr = exchange(cfg, c, name, qtype)
c.Close()
if merr != nil {
err = merr
continue
}
}
cname, addrs, err = answer(name, server, msg, qtype)
if err == nil || err.(*DNSError).Err == noSuchHost {
break
}
}
return
}
func convertRR_A(records []dnsRR) []IP {
addrs := make([]IP, len(records))
for i, rr := range records {
a := rr.(*dnsRR_A).A
addrs[i] = IPv4(byte(a>>24), byte(a>>16), byte(a>>8), byte(a))
}
return addrs
}
func convertRR_AAAA(records []dnsRR) []IP {
addrs := make([]IP, len(records))
for i, rr := range records {
a := make(IP, IPv6len)
copy(a, rr.(*dnsRR_AAAA).AAAA[:])
addrs[i] = a
}
return addrs
}
var cfg *dnsConfig
var dnserr error
// Assume dns config file is /etc/resolv.conf here
func loadConfig() { cfg, dnserr = dnsReadConfig("/etc/resolv.conf") }
var onceLoadConfig sync.Once
func lookup(name string, qtype uint16) (cname string, addrs []dnsRR, err error) {
if !isDomainName(name) {
return name, nil, &DNSError{Err: "invalid domain name", Name: name}
}
onceLoadConfig.Do(loadConfig)
if dnserr != nil || cfg == nil {
err = dnserr
return
}
// If name is rooted (trailing dot) or has enough dots,
// try it by itself first.
rooted := len(name) > 0 && name[len(name)-1] == '.'
if rooted || count(name, '.') >= cfg.ndots {
rname := name
if !rooted {
rname += "."
}
// Can try as ordinary name.
cname, addrs, err = tryOneName(cfg, rname, qtype)
if err == nil {
return
}
}
if rooted {
return
}
// Otherwise, try suffixes.
for i := 0; i < len(cfg.search); i++ {
rname := name + "." + cfg.search[i]
if rname[len(rname)-1] != '.' {
rname += "."
}
cname, addrs, err = tryOneName(cfg, rname, qtype)
if err == nil {
return
}
}
// Last ditch effort: try unsuffixed.
rname := name
if !rooted {
rname += "."
}
cname, addrs, err = tryOneName(cfg, rname, qtype)
if err == nil {
return
}
if e, ok := err.(*DNSError); ok {
// Show original name passed to lookup, not suffixed one.
// In general we might have tried many suffixes; showing
// just one is misleading. See also golang.org/issue/6324.
e.Name = name
}
return
}
// goLookupHost is the native Go implementation of LookupHost.
// Used only if cgoLookupHost refuses to handle the request
// (that is, only if cgoLookupHost is the stub in cgo_stub.go).
// Normally we let cgo use the C library resolver instead of
// depending on our lookup code, so that Go and C get the same
// answers.
func goLookupHost(name string) (addrs []string, err error) {
// Use entries from /etc/hosts if they match.
addrs = lookupStaticHost(name)
if len(addrs) > 0 {
return
}
onceLoadConfig.Do(loadConfig)
if dnserr != nil || cfg == nil {
err = dnserr
return
}
ips, err := goLookupIP(name)
if err != nil {
return
}
addrs = make([]string, 0, len(ips))
for _, ip := range ips {
addrs = append(addrs, ip.String())
}
return
}
// goLookupIP is the native Go implementation of LookupIP.
// Used only if cgoLookupIP refuses to handle the request
// (that is, only if cgoLookupIP is the stub in cgo_stub.go).
// Normally we let cgo use the C library resolver instead of
// depending on our lookup code, so that Go and C get the same
// answers.
func goLookupIP(name string) (addrs []IP, err error) {
// Use entries from /etc/hosts if possible.
haddrs := lookupStaticHost(name)
if len(haddrs) > 0 {
for _, haddr := range haddrs {
if ip := ParseIP(haddr); ip != nil {
addrs = append(addrs, ip)
}
}
if len(addrs) > 0 {
return
}
}
onceLoadConfig.Do(loadConfig)
if dnserr != nil || cfg == nil {
err = dnserr
return
}
var records []dnsRR
var cname string
var err4, err6 error
cname, records, err4 = lookup(name, dnsTypeA)
addrs = convertRR_A(records)
if cname != "" {
name = cname
}
_, records, err6 = lookup(name, dnsTypeAAAA)
if err4 != nil && err6 == nil {
// Ignore A error because AAAA lookup succeeded.
err4 = nil
}
if err6 != nil && len(addrs) > 0 {
// Ignore AAAA error because A lookup succeeded.
err6 = nil
}
if err4 != nil {
return nil, err4
}
if err6 != nil {
return nil, err6
}
addrs = append(addrs, convertRR_AAAA(records)...)
return addrs, nil
}
// goLookupCNAME is the native Go implementation of LookupCNAME.
// Used only if cgoLookupCNAME refuses to handle the request
// (that is, only if cgoLookupCNAME is the stub in cgo_stub.go).
// Normally we let cgo use the C library resolver instead of
// depending on our lookup code, so that Go and C get the same
// answers.
func goLookupCNAME(name string) (cname string, err error) {
onceLoadConfig.Do(loadConfig)
if dnserr != nil || cfg == nil {
err = dnserr
return
}
_, rr, err := lookup(name, dnsTypeCNAME)
if err != nil {
return
}
cname = rr[0].(*dnsRR_CNAME).Cname
return
}
| TomHoenderdos/go-sunos | src/pkg/net/dnsclient_unix.go | GO | bsd-3-clause | 8,117 |
<?php
return array (
'Search' => 'Cerca',
);
| LeonidLyalin/vova | common/humhub/protected/humhub/modules/search/messages/it/base.php | PHP | bsd-3-clause | 47 |
<?php
namespace Contract\Service;
interface ContractManager {
/**
* Initiate sebuah kontrak.
*
* @param unknown $datas
*/
public function initiateContract($datas);
} | zakyalvan/eproc-ext | module/Contract/src/Contract/Service/ContractManager.php | PHP | bsd-3-clause | 177 |
dw.derive.variable = function(x) {
var variable = dw.derive.expression();
variable.transform = function(values, table) {
var result = table[x].copy();
return result;
}
return variable;
}
| uwdata/profiler | wrangler/src/transform/derive/variable.js | JavaScript | bsd-3-clause | 197 |
#!/usr/bin/env ruby
# -*- mode: ruby; coding: utf-8-unix -*-
require 'test/unit'
require 'opencv'
require File.expand_path(File.dirname(__FILE__)) + '/helper'
include OpenCV
# Tests for OpenCV::CvChain
class TestCvChain < OpenCVTestCase
def test_APPROX_OPTION
assert_equal(:approx_simple, CvChain::APPROX_CHAIN_OPTION[:method])
assert_equal(0, CvChain::APPROX_CHAIN_OPTION[:parameter])
assert_equal(0, CvChain::APPROX_CHAIN_OPTION[:minimal_parameter])
assert_false(CvChain::APPROX_CHAIN_OPTION[:recursive])
end
def test_initialize
chain = CvChain.new
assert_not_nil(chain)
assert_equal(CvChain, chain.class)
assert(chain.is_a? CvSeq)
end
def test_origin
mat0 = create_cvmat(128, 128, :cv8u, 1) { |j, i|
(j - 64) ** 2 + (i - 64) ** 2 <= (32 ** 2) ? CvColor::White : CvColor::Black
}
chain = mat0.find_contours(:mode => CV_RETR_EXTERNAL, :method => CV_CHAIN_CODE)
assert_equal(CvChain, chain.class)
assert_equal(64, chain.origin.x)
assert_equal(32, chain.origin.y)
chain.origin = CvPoint.new(32, 64)
assert_equal(32, chain.origin.x)
assert_equal(64, chain.origin.y)
end
def test_codes
mat0 = create_cvmat(128, 128, :cv8u, 1) { |j, i|
(j - 64) ** 2 + (i - 64) ** 2 <= (32 ** 2) ? CvColor::White : CvColor::Black
}
chain = mat0.find_contours(:mode => CV_RETR_EXTERNAL, :method => CV_CHAIN_CODE)
assert_equal(Array, chain.codes.class)
assert(chain.codes.all? { |a| (a.class == Fixnum) and (a >= 0 and a <= 7) })
end
def test_points
mat0 = create_cvmat(128, 128, :cv8u, 1) { |j, i|
(j - 64) ** 2 + (i - 64) ** 2 <= (32 ** 2) ? CvColor::White : CvColor::Black
}
chain = mat0.find_contours(:mode => CV_RETR_EXTERNAL, :method => CV_CHAIN_CODE)
assert_equal(Array, chain.points.class)
assert(chain.points.all? { |a| a.class == CvPoint })
end
def test_approx_chain
flunk('FIXME: CvChain#approx_chain is not implemented yet.')
end
end
| ryanfb/ruby-opencv | test/test_cvchain.rb | Ruby | bsd-3-clause | 1,989 |
/*
* RandomConditional_test.cpp
*
* Copyright (c) 2015, Norman Alan Oursland
* All rights reserved.
*/
#include "cognitoware/math/data/Vector.h"
#include "cognitoware/math/probability/RandomConditional.h"
#include "cognitoware/math/probability/RandomDistribution.h"
#include "gtest/gtest.h"
using cognitoware::math::data::Vector;
namespace cognitoware {
namespace math {
namespace probability {
DEFINE_VECTOR1(X);
DEFINE_VECTOR1(Y);
class RC : RandomConditional<X, Y> {
double ConditionalProbabilityOf(const X&, const Y&) const override {
return 0.0;
}
};
TEST(RandomConditionalTest, ctor1) {
}
} // namespace probability
} // namespace math
} // namespace cognitoware
| ashfaqfarooqui/robotics | cognitoware/math/probability/RandomConditional_test.cpp | C++ | bsd-3-clause | 695 |
package org.usfirst.frc369.Robot2017Code.commands;
import org.usfirst.frc369.Robot2017Code.Robot;
import edu.wpi.first.wpilibj.command.Command;
/**
*
*/
public class highGearShift extends Command {
public highGearShift() {
// Use requires() here to declare subsystem dependencies
// eg. requires(chassis);
requires(Robot.driveSys);
}
// Called just before this Command runs the first time
protected void initialize() {
Robot.driveSys.shiftToHighGear();
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return false;
}
// Called once after isFinished returns true
protected void end() {
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
end();
}
}
| Krudeboy51/Robot2017Code | src/org/usfirst/frc369/Robot2017Code/commands/highGearShift.java | Java | bsd-3-clause | 1,005 |
<?php
/**
* Search Work Factory
*
* PHP version 5
*
* Copyright (c) Falvey Library 2017.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category VuBib
* @package Code
* @author Falvey Library <demian.katz@villanova.edu>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https:// Main Page
*/
namespace VuBib\Action\WorkType;
use Interop\Container\ContainerInterface;
use Zend\Db\Adapter\Adapter;
use Zend\Expressive\Router\RouterInterface;
use Zend\Expressive\Template\TemplateRendererInterface;
/**
* Class Definition for SearchWorkFactory.
*
* @category VuBib
* @package Code
* @author Falvey Library <demian.katz@villanova.edu>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
*
* @link https://
*/
class SearchOptionFactory
{
/**
* Invokes required template
*
* @param ContainerInterface $container interface of a container
* that exposes methods to read its entries.
*
* @return HtmlResponse
*/
public function __invoke(ContainerInterface $container)
{
$router = $container->get(RouterInterface::class);
$template = ($container->has(TemplateRendererInterface::class))
? $container->get(TemplateRendererInterface::class)
: null;
$adapter = $container->get(Adapter::class);
//return new SearchWorkAction($router, $template, $adapter);
return new \VuBib\Action\SimpleRenderAction(
'vubib::worktype::search_attribute_option', $router,
$template, $adapter
);
}
}
| SravanthiVillanova/Learn_Bibliography | src/VuBib/Action/WorkType/SearchOptionFactory.php | PHP | bsd-3-clause | 2,231 |
<?php
namespace test\n\h;
class d { } | theosyspe/levent_01 | vendor/ZF2/bin/test/n/h/d.php | PHP | bsd-3-clause | 37 |
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule InspectorUtils
*/
'use strict';
var ReactNativeComponentTree = require('ReactNativeComponentTree');
function traverseOwnerTreeUp(hierarchy, instance) {
if (instance) {
hierarchy.unshift(instance);
traverseOwnerTreeUp(hierarchy, instance._currentElement._owner);
}
}
function findInstanceByNativeTag(nativeTag) {
var instance = ReactNativeComponentTree.getInstanceFromNode(nativeTag);
if (typeof instance.tag === 'number') {
// TODO(sema): We've disabled the inspector when using Fiber. Fix #15953531
return null;
}
return instance;
}
function getOwnerHierarchy(instance) {
var hierarchy = [];
traverseOwnerTreeUp(hierarchy, instance);
return hierarchy;
}
function lastNotNativeInstance(hierarchy) {
for (let i = hierarchy.length - 1; i > 1; i--) {
const instance = hierarchy[i];
if (!instance.viewConfig) {
return instance;
}
}
return hierarchy[0];
}
module.exports = {findInstanceByNativeTag, getOwnerHierarchy, lastNotNativeInstance};
| htc2u/react-native | Libraries/Inspector/InspectorUtils.js | JavaScript | bsd-3-clause | 1,329 |
<?php
class CestTest extends Codeception\TestCase\Test
{
/**
* @group core
*/
public function testFilename()
{
$cest = \Codeception\Util\Stub::make('\Codeception\TestCase\Cest', array(
'getTestClass' => new \Codeception\Util\Locator(),
'getTestMethod' => 'combine'
));
$this->assertEquals('Codeception.Util.Locator.combine', $cest->getFileName());
}
}
| slivas/hoz | vendor/codeception/codeception/tests/unit/Codeception/CestTest.php | PHP | bsd-3-clause | 436 |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media;
using Nitra.Runtime.Reflection;
namespace Nitra.Visualizer
{
public class ReflectionStructColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var node = (ReflectionStruct)value;
if (node.Info.IsMarker)
return Brushes.DarkGray;
if (node.Kind == ReflectionKind.Deleted)
return Brushes.Red;
if (node.Span.IsEmpty)
{
if (node.Info.CanParseEmptyString)
return Brushes.Teal;
return Brushes.Red;
}
if (node.Kind == ReflectionKind.Ambiguous)
return Brushes.DarkOrange;
if (node.Kind == ReflectionKind.Recovered && node.Children != null && node.Children.Count > 0 && node.Children.Any(r => r.Kind != ReflectionKind.Normal))
return Brushes.MediumVioletRed;
return SystemColors.ControlTextBrush;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
| JetBrains/Nitra | Nitra.Visualizer.Old/Rendering/ReflectionStructColorConverter.cs | C# | bsd-3-clause | 1,303 |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;
using VW;
using VW.Serializer;
namespace Experimentation
{
public static class OfflineTrainer
{
//private class Event
//{
// internal VowpalWabbitExampleCollection Example;
// internal string Line;
// internal int LineNr;
// internal ActionScore[] Prediction;
//}
/// <summary>
/// Train VW on offline data.
/// </summary>
/// <param name="arguments">Base arguments.</param>
/// <param name="inputFile">Path to input file.</param>
/// <param name="predictionFile">Name of the output prediction file.</param>
/// <param name="reloadInterval">The TimeSpan interval to reload model.</param>
/// <param name="learningRate">
/// Learning rate must be specified here otherwise on Reload it will be reset.
/// </param>
/// <param name="cacheFilePrefix">
/// The prefix of the cache file name to use. For example: prefix = "test" => "test.vw.cache"
/// If none or null, the input file name is used, e.g. "input.dataset" => "input.vw.cache"
/// !!! IMPORTANT !!!: Always use a new cache name if a different dataset or reload interval is used.
/// </param>
/// <remarks>
/// Both learning rates and cache file are added to initial training arguments as well as Reload arguments.
/// </remarks>
public static void Train(string arguments, string inputFile, string predictionFile = null, TimeSpan? reloadInterval = null, float? learningRate=null, string cacheFilePrefix = null)
{
var learningArgs = learningRate == null ? string.Empty : $" -l {learningRate}";
int cacheIndex = 0;
var cacheArgs = (Func<int, string>)(i => $" --cache_file {cacheFilePrefix ?? Path.GetFileNameWithoutExtension(inputFile)}-{i}.vw.cache");
using (var reader = new StreamReader(inputFile))
using (var prediction = new StreamWriter(predictionFile ?? inputFile + ".prediction"))
using (var vw = new VowpalWabbit(new VowpalWabbitSettings(arguments + learningArgs + cacheArgs(cacheIndex++))
{
Verbose = true
}))
{
string line;
int lineNr = 0;
int invalidExamples = 0;
DateTime? lastTimestamp = null;
while ((line = reader.ReadLine()) != null)
{
try
{
bool reload = false;
using (var jsonSerializer = new VowpalWabbitJsonSerializer(vw))
{
if (reloadInterval != null)
{
jsonSerializer.RegisterExtension((state, property) =>
{
if (property.Equals("_timestamp", StringComparison.Ordinal))
{
var eventTimestamp = state.Reader.ReadAsDateTime();
if (lastTimestamp == null)
lastTimestamp = eventTimestamp;
else if (lastTimestamp + reloadInterval < eventTimestamp)
{
reload = true;
lastTimestamp = eventTimestamp;
}
return true;
}
return false;
});
}
// var pred = vw.Learn(line, VowpalWabbitPredictionType.ActionProbabilities);
using (var example = jsonSerializer.ParseAndCreate(line))
{
var pred = example.Learn(VowpalWabbitPredictionType.ActionProbabilities);
prediction.WriteLine(JsonConvert.SerializeObject(
new
{
nr = lineNr,
@as = pred.Select(x => x.Action),
p = pred.Select(x => x.Score)
}));
}
if (reload)
vw.Reload(learningArgs + cacheArgs(cacheIndex++));
}
}
catch (Exception)
{
invalidExamples++;
}
lineNr++;
}
}
// memory leak and not much gain below...
//using (var vw = new VowpalWabbit(new VowpalWabbitSettings(arguments)
//{
// Verbose = true,
// EnableThreadSafeExamplePooling = true,
// MaxExamples = 1024
//}))
//using (var reader = new StreamReader(inputFile))
//using (var prediction = new StreamWriter(inputFile + ".prediction"))
//{
// int invalidExamples = 0;
// var deserializeBlock = new TransformBlock<Event, Event>(
// evt =>
// {
// try
// {
// using (var vwJsonSerializer = new VowpalWabbitJsonSerializer(vw))
// {
// evt.Example = vwJsonSerializer.ParseAndCreate(evt.Line);
// }
// // reclaim memory
// evt.Line = null;
// return evt;
// }
// catch (Exception)
// {
// Interlocked.Increment(ref invalidExamples);
// return null;
// }
// },
// new ExecutionDataflowBlockOptions
// {
// BoundedCapacity = 16,
// MaxDegreeOfParallelism = 8 // TODO: parameterize
// });
// var learnBlock = new TransformBlock<Event, Event>(
// evt =>
// {
// evt.Prediction = evt.Example.Learn(VowpalWabbitPredictionType.ActionProbabilities);
// evt.Example.Dispose();
// return evt;
// },
// new ExecutionDataflowBlockOptions
// {
// BoundedCapacity = 64,
// MaxDegreeOfParallelism = 1
// });
// var predictionBlock = new ActionBlock<Event>(
// evt => prediction.WriteLine(evt.LineNr + " " + string.Join(",", evt.Prediction.Select(a_s => $"{a_s.Action}:{a_s.Score}"))),
// new ExecutionDataflowBlockOptions
// {
// BoundedCapacity = 16,
// MaxDegreeOfParallelism = 1
// });
// var input = deserializeBlock.AsObserver();
// deserializeBlock.LinkTo(learnBlock, new DataflowLinkOptions { PropagateCompletion = true }, evt => evt != null);
// deserializeBlock.LinkTo(DataflowBlock.NullTarget<object>());
// learnBlock.LinkTo(predictionBlock, new DataflowLinkOptions { PropagateCompletion = true });
// string line;
// int lineNr = 0;
// while ((line = reader.ReadLine()) != null)
// input.OnNext(new Event { Line = line, LineNr = lineNr++ });
// input.OnCompleted();
// predictionBlock.Completion.Wait();
//Console.WriteLine($"Examples {lineNr}. Invalid: {invalidExamples}");
//}
}
}
}
| eisber/mwt-ds | Experimentation/OfflineTrainer.cs | C# | bsd-3-clause | 8,502 |
#ifndef __CINT__
#include "TMath.h"
#include "AliCDBManager.h"
#include "AliTriggerScalers.h"
#include "AliTriggerRunScalers.h"
#include "AliTimeStamp.h"
#include "AliTriggerScalersRecord.h"
#include "AliTriggerConfiguration.h"
#include "AliLHCData.h"
#include "AliTriggerClass.h"
#include "AliTriggerBCMask.h"
#include "AliCDBPath.h"
#include "AliCDBEntry.h"
#endif
UInt_t dif(UInt_t stop, UInt_t start){
UInt_t d;
if(stop >= start) d=stop-start;
else d = stop+(0xffffffff-start)+1;
return d;
};
TObjArray GetClasses(Int_t run, TString ocdbStorage, TString &partition, TString &activeDetectors, Double_t& run_duration,
ULong64_t* LMB, ULong64_t* LMA, ULong64_t* L0B, ULong64_t* L0A, ULong64_t* L1B, ULong64_t* L1A, ULong64_t* L2B, ULong64_t* L2A){
AliCDBManager* man = AliCDBManager::Instance();
man->SetDefaultStorage(ocdbStorage.Data());
man->SetRun(run);
// Get scalers
AliTriggerConfiguration* cfg = (AliTriggerConfiguration*) man->Get("GRP/CTP/Config")->GetObject();
if (!cfg) { printf("No GRP/CTP/Config object for run %i\n",run); return TObjArray(); }
partition = cfg->GetName();
activeDetectors = cfg->GetActiveDetectors();
TObjArray classes = cfg->GetClasses();
AliTriggerRunScalers* scalers = (AliTriggerRunScalers*) man->Get("GRP/CTP/Scalers")->GetObject();
if (!scalers) { printf("No GRP/CTP/Scalers object for run %i\n",run); return TObjArray(); }
Int_t nEntries = scalers->GetScalersRecords()->GetEntriesFast();
for (Int_t r=0;r<nEntries-1;r++){
// Get SOR and EOR scaler records
AliTriggerScalersRecord* record1 = scalers->GetScalersRecord(r);
AliTriggerScalersRecord* record2 = scalers->GetScalersRecord(r+1);
if (!record1) { printf("Null pointer to scalers record\n"); return TObjArray(); }
if (!record2) { printf("Null pointer to scalers record\n"); return TObjArray(); }
for (Int_t i=0;i<classes.GetEntriesFast();i++){
// Extract SOR and EOR trigger counts
Int_t classId = cfg->GetClassIndexFromName(classes.At(i)->GetName());
const AliTriggerScalers* scaler1 = record1->GetTriggerScalersForClass(classId);
const AliTriggerScalers* scaler2 = record2->GetTriggerScalersForClass(classId);
if (!scaler1) { printf("Null pointer to scalers for class\n"); return TObjArray(); }
if (!scaler2) { printf("Null pointer to scalers for class\n"); return TObjArray(); }
LMB[i] += dif(scaler2->GetLMCB(),scaler1->GetLMCB());
LMA[i] += dif(scaler2->GetLMCA(),scaler1->GetLMCA());
L0B[i] += dif(scaler2->GetLOCB(),scaler1->GetLOCB());
L0A[i] += dif(scaler2->GetLOCA(),scaler1->GetLOCA());
L1B[i] += dif(scaler2->GetL1CB(),scaler1->GetL1CB());
L1A[i] += dif(scaler2->GetL1CA(),scaler1->GetL1CA());
L2B[i] += dif(scaler2->GetL2CB(),scaler1->GetL2CB());
L2A[i] += dif(scaler2->GetL2CA(),scaler1->GetL2CA());
}
}
UInt_t t1 = scalers->GetScalersRecord(0 )->GetTimeStamp()->GetSeconds();
UInt_t t2 = scalers->GetScalersRecord(nEntries-1)->GetTimeStamp()->GetSeconds();
run_duration = dif(t2,t1);
return classes;
}
Int_t triggerInfo(Int_t run, TString ocdbStorage, TString &lhcPeriod, TString &lhcState,
Int_t &fill, Int_t &nBCsPerOrbit, Int_t &timeStart, Int_t &timeEnd){
AliCDBManager* man = AliCDBManager::Instance();
man->SetDefaultStorage(ocdbStorage.Data());
man->SetRun(run);
AliGRPObject* grp = (AliGRPObject*) man->Get("GRP/GRP/Data")->GetObject();
if (!grp) { printf("No GRP/GRP/Data object for run %i\n",run); return 1; }
lhcState = grp->GetLHCState();
lhcPeriod = grp->GetLHCPeriod();
timeStart = grp->GetTimeStart();
timeEnd = grp->GetTimeEnd();
if (run==189694) return 1; // No GRP/GRP/LHCData for this run
AliLHCData* lhc = (AliLHCData*) man->Get("GRP/GRP/LHCData")->GetObject();
if (!lhc) { printf("No GRP/GRP/LHCData object for run %i\n",run); return 1; }
fill = lhc->GetFillNumber();
nBCsPerOrbit = lhc->GetNInteractingBunchesMeasured();
return 0;
}
| pbatzing/AliPhysics | PWGPP/EVS/triggerInfo.C | C++ | bsd-3-clause | 4,004 |
package com.dslplatform.client.json.StringWithMaxLengthOf9;
import com.dslplatform.client.JsonSerialization;
import com.dslplatform.patterns.Bytes;
import java.io.IOException;
public class OneStringWithMaxLengthOf9DefaultValueTurtle {
private static JsonSerialization jsonSerialization;
@org.junit.BeforeClass
public static void initializeJsonSerialization() throws IOException {
jsonSerialization = com.dslplatform.client.StaticJson.getSerialization();
}
@org.junit.Test
public void testDefaultValueEquality() throws IOException {
final String defaultValue = "";
final Bytes defaultValueJsonSerialized = jsonSerialization.serialize(defaultValue);
final String defaultValueJsonDeserialized = jsonSerialization.deserialize(String.class, defaultValueJsonSerialized.content, defaultValueJsonSerialized.length);
com.dslplatform.ocd.javaasserts.StringWithMaxLengthOf9Asserts.assertOneEquals(defaultValue, defaultValueJsonDeserialized);
}
@org.junit.Test
public void testBorderValue1Equality() throws IOException {
final String borderValue1 = "\"";
final Bytes borderValue1JsonSerialized = jsonSerialization.serialize(borderValue1);
final String borderValue1JsonDeserialized = jsonSerialization.deserialize(String.class, borderValue1JsonSerialized.content, borderValue1JsonSerialized.length);
com.dslplatform.ocd.javaasserts.StringWithMaxLengthOf9Asserts.assertOneEquals(borderValue1, borderValue1JsonDeserialized);
}
@org.junit.Test
public void testBorderValue2Equality() throws IOException {
final String borderValue2 = "'/\\[](){}";
final Bytes borderValue2JsonSerialized = jsonSerialization.serialize(borderValue2);
final String borderValue2JsonDeserialized = jsonSerialization.deserialize(String.class, borderValue2JsonSerialized.content, borderValue2JsonSerialized.length);
com.dslplatform.ocd.javaasserts.StringWithMaxLengthOf9Asserts.assertOneEquals(borderValue2, borderValue2JsonDeserialized);
}
@org.junit.Test
public void testBorderValue3Equality() throws IOException {
final String borderValue3 = "\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t";
final Bytes borderValue3JsonSerialized = jsonSerialization.serialize(borderValue3);
final String borderValue3JsonDeserialized = jsonSerialization.deserialize(String.class, borderValue3JsonSerialized.content, borderValue3JsonSerialized.length);
com.dslplatform.ocd.javaasserts.StringWithMaxLengthOf9Asserts.assertOneEquals(borderValue3, borderValue3JsonDeserialized);
}
@org.junit.Test
public void testBorderValue4Equality() throws IOException {
final String borderValue4 = "xxxxxxxxx";
final Bytes borderValue4JsonSerialized = jsonSerialization.serialize(borderValue4);
final String borderValue4JsonDeserialized = jsonSerialization.deserialize(String.class, borderValue4JsonSerialized.content, borderValue4JsonSerialized.length);
com.dslplatform.ocd.javaasserts.StringWithMaxLengthOf9Asserts.assertOneEquals(borderValue4, borderValue4JsonDeserialized);
}
}
| ngs-doo/dsl-client-java | core/src/test/java-generated/com/dslplatform/client/json/StringWithMaxLengthOf9/OneStringWithMaxLengthOf9DefaultValueTurtle.java | Java | bsd-3-clause | 2,979 |
// Copyright 2007, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
// Google Mock - a framework for writing C++ mock classes.
//
// This file tests some commonly used argument matchers.
#include "gmock/gmock-matchers.h"
#include "gmock/gmock-more-matchers.h"
#include <string.h>
#include <deque>
#include <functional>
#include <iostream>
#include <iterator>
#include <list>
#include <map>
#include <set>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "gtest/gtest-spi.h"
namespace testing {
namespace internal {
GTEST_API_ string JoinAsTuple(const Strings& fields);
} // namespace internal
namespace gmock_matchers_test {
using std::greater;
using std::less;
using std::list;
using std::make_pair;
using std::map;
using std::multimap;
using std::multiset;
using std::ostream;
using std::pair;
using std::set;
using std::stringstream;
using std::tr1::get;
using std::tr1::make_tuple;
using std::tr1::tuple;
using std::vector;
using testing::A;
using testing::AllArgs;
using testing::AllOf;
using testing::An;
using testing::AnyOf;
using testing::ByRef;
using testing::ContainsRegex;
using testing::DoubleEq;
using testing::EndsWith;
using testing::Eq;
using testing::ExplainMatchResult;
using testing::Field;
using testing::FloatEq;
using testing::Ge;
using testing::Gt;
using testing::HasSubstr;
using testing::IsEmpty;
using testing::IsNull;
using testing::Key;
using testing::Le;
using testing::Lt;
using testing::MakeMatcher;
using testing::MakePolymorphicMatcher;
using testing::MatchResultListener;
using testing::Matcher;
using testing::MatcherCast;
using testing::MatcherInterface;
using testing::Matches;
using testing::MatchesRegex;
using testing::NanSensitiveDoubleEq;
using testing::NanSensitiveFloatEq;
using testing::Ne;
using testing::Not;
using testing::NotNull;
using testing::Pair;
using testing::Pointee;
using testing::Pointwise;
using testing::PolymorphicMatcher;
using testing::Property;
using testing::Ref;
using testing::ResultOf;
using testing::SizeIs;
using testing::StartsWith;
using testing::StrCaseEq;
using testing::StrCaseNe;
using testing::StrEq;
using testing::StrNe;
using testing::Truly;
using testing::TypedEq;
using testing::Value;
using testing::WhenSorted;
using testing::WhenSortedBy;
using testing::_;
using testing::internal::DummyMatchResultListener;
using testing::internal::ExplainMatchFailureTupleTo;
using testing::internal::FloatingEqMatcher;
using testing::internal::FormatMatcherDescription;
using testing::internal::IsReadableTypeName;
using testing::internal::JoinAsTuple;
using testing::internal::RE;
using testing::internal::StreamMatchResultListener;
using testing::internal::StringMatchResultListener;
using testing::internal::Strings;
using testing::internal::linked_ptr;
using testing::internal::scoped_ptr;
using testing::internal::string;
// For testing ExplainMatchResultTo().
class GreaterThanMatcher : public MatcherInterface<int> {
public:
explicit GreaterThanMatcher(int rhs) : rhs_(rhs) {}
virtual void DescribeTo(ostream* os) const {
*os << "is > " << rhs_;
}
virtual bool MatchAndExplain(int lhs,
MatchResultListener* listener) const {
const int diff = lhs - rhs_;
if (diff > 0) {
*listener << "which is " << diff << " more than " << rhs_;
} else if (diff == 0) {
*listener << "which is the same as " << rhs_;
} else {
*listener << "which is " << -diff << " less than " << rhs_;
}
return lhs > rhs_;
}
private:
int rhs_;
};
Matcher<int> GreaterThan(int n) {
return MakeMatcher(new GreaterThanMatcher(n));
}
string OfType(const string& type_name) {
#if GTEST_HAS_RTTI
return " (of type " + type_name + ")";
#else
return "";
#endif
}
// Returns the description of the given matcher.
template <typename T>
string Describe(const Matcher<T>& m) {
stringstream ss;
m.DescribeTo(&ss);
return ss.str();
}
// Returns the description of the negation of the given matcher.
template <typename T>
string DescribeNegation(const Matcher<T>& m) {
stringstream ss;
m.DescribeNegationTo(&ss);
return ss.str();
}
// Returns the reason why x matches, or doesn't match, m.
template <typename MatcherType, typename Value>
string Explain(const MatcherType& m, const Value& x) {
StringMatchResultListener listener;
ExplainMatchResult(m, x, &listener);
return listener.str();
}
TEST(MatchResultListenerTest, StreamingWorks) {
StringMatchResultListener listener;
listener << "hi" << 5;
EXPECT_EQ("hi5", listener.str());
// Streaming shouldn't crash when the underlying ostream is NULL.
DummyMatchResultListener dummy;
dummy << "hi" << 5;
}
TEST(MatchResultListenerTest, CanAccessUnderlyingStream) {
EXPECT_TRUE(DummyMatchResultListener().stream() == NULL);
EXPECT_TRUE(StreamMatchResultListener(NULL).stream() == NULL);
EXPECT_EQ(&std::cout, StreamMatchResultListener(&std::cout).stream());
}
TEST(MatchResultListenerTest, IsInterestedWorks) {
EXPECT_TRUE(StringMatchResultListener().IsInterested());
EXPECT_TRUE(StreamMatchResultListener(&std::cout).IsInterested());
EXPECT_FALSE(DummyMatchResultListener().IsInterested());
EXPECT_FALSE(StreamMatchResultListener(NULL).IsInterested());
}
// Makes sure that the MatcherInterface<T> interface doesn't
// change.
class EvenMatcherImpl : public MatcherInterface<int> {
public:
virtual bool MatchAndExplain(int x,
MatchResultListener* /* listener */) const {
return x % 2 == 0;
}
virtual void DescribeTo(ostream* os) const {
*os << "is an even number";
}
// We deliberately don't define DescribeNegationTo() and
// ExplainMatchResultTo() here, to make sure the definition of these
// two methods is optional.
};
// Makes sure that the MatcherInterface API doesn't change.
TEST(MatcherInterfaceTest, CanBeImplementedUsingPublishedAPI) {
EvenMatcherImpl m;
}
// Tests implementing a monomorphic matcher using MatchAndExplain().
class NewEvenMatcherImpl : public MatcherInterface<int> {
public:
virtual bool MatchAndExplain(int x, MatchResultListener* listener) const {
const bool match = x % 2 == 0;
// Verifies that we can stream to a listener directly.
*listener << "value % " << 2;
if (listener->stream() != NULL) {
// Verifies that we can stream to a listener's underlying stream
// too.
*listener->stream() << " == " << (x % 2);
}
return match;
}
virtual void DescribeTo(ostream* os) const {
*os << "is an even number";
}
};
TEST(MatcherInterfaceTest, CanBeImplementedUsingNewAPI) {
Matcher<int> m = MakeMatcher(new NewEvenMatcherImpl);
EXPECT_TRUE(m.Matches(2));
EXPECT_FALSE(m.Matches(3));
EXPECT_EQ("value % 2 == 0", Explain(m, 2));
EXPECT_EQ("value % 2 == 1", Explain(m, 3));
}
// Tests default-constructing a matcher.
TEST(MatcherTest, CanBeDefaultConstructed) {
Matcher<double> m;
}
// Tests that Matcher<T> can be constructed from a MatcherInterface<T>*.
TEST(MatcherTest, CanBeConstructedFromMatcherInterface) {
const MatcherInterface<int>* impl = new EvenMatcherImpl;
Matcher<int> m(impl);
EXPECT_TRUE(m.Matches(4));
EXPECT_FALSE(m.Matches(5));
}
// Tests that value can be used in place of Eq(value).
TEST(MatcherTest, CanBeImplicitlyConstructedFromValue) {
Matcher<int> m1 = 5;
EXPECT_TRUE(m1.Matches(5));
EXPECT_FALSE(m1.Matches(6));
}
// Tests that NULL can be used in place of Eq(NULL).
TEST(MatcherTest, CanBeImplicitlyConstructedFromNULL) {
Matcher<int*> m1 = NULL;
EXPECT_TRUE(m1.Matches(NULL));
int n = 0;
EXPECT_FALSE(m1.Matches(&n));
}
// Tests that matchers are copyable.
TEST(MatcherTest, IsCopyable) {
// Tests the copy constructor.
Matcher<bool> m1 = Eq(false);
EXPECT_TRUE(m1.Matches(false));
EXPECT_FALSE(m1.Matches(true));
// Tests the assignment operator.
m1 = Eq(true);
EXPECT_TRUE(m1.Matches(true));
EXPECT_FALSE(m1.Matches(false));
}
// Tests that Matcher<T>::DescribeTo() calls
// MatcherInterface<T>::DescribeTo().
TEST(MatcherTest, CanDescribeItself) {
EXPECT_EQ("is an even number",
Describe(Matcher<int>(new EvenMatcherImpl)));
}
// Tests Matcher<T>::MatchAndExplain().
TEST(MatcherTest, MatchAndExplain) {
Matcher<int> m = GreaterThan(0);
StringMatchResultListener listener1;
EXPECT_TRUE(m.MatchAndExplain(42, &listener1));
EXPECT_EQ("which is 42 more than 0", listener1.str());
StringMatchResultListener listener2;
EXPECT_FALSE(m.MatchAndExplain(-9, &listener2));
EXPECT_EQ("which is 9 less than 0", listener2.str());
}
// Tests that a C-string literal can be implicitly converted to a
// Matcher<string> or Matcher<const string&>.
TEST(StringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
Matcher<string> m1 = "hi";
EXPECT_TRUE(m1.Matches("hi"));
EXPECT_FALSE(m1.Matches("hello"));
Matcher<const string&> m2 = "hi";
EXPECT_TRUE(m2.Matches("hi"));
EXPECT_FALSE(m2.Matches("hello"));
}
// Tests that a string object can be implicitly converted to a
// Matcher<string> or Matcher<const string&>.
TEST(StringMatcherTest, CanBeImplicitlyConstructedFromString) {
Matcher<string> m1 = string("hi");
EXPECT_TRUE(m1.Matches("hi"));
EXPECT_FALSE(m1.Matches("hello"));
Matcher<const string&> m2 = string("hi");
EXPECT_TRUE(m2.Matches("hi"));
EXPECT_FALSE(m2.Matches("hello"));
}
#if GTEST_HAS_STRING_PIECE_
// Tests that a C-string literal can be implicitly converted to a
// Matcher<StringPiece> or Matcher<const StringPiece&>.
TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
Matcher<StringPiece> m1 = "cats";
EXPECT_TRUE(m1.Matches("cats"));
EXPECT_FALSE(m1.Matches("dogs"));
Matcher<const StringPiece&> m2 = "cats";
EXPECT_TRUE(m2.Matches("cats"));
EXPECT_FALSE(m2.Matches("dogs"));
}
// Tests that a string object can be implicitly converted to a
// Matcher<StringPiece> or Matcher<const StringPiece&>.
TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromString) {
Matcher<StringPiece> m1 = string("cats");
EXPECT_TRUE(m1.Matches("cats"));
EXPECT_FALSE(m1.Matches("dogs"));
Matcher<const StringPiece&> m2 = string("cats");
EXPECT_TRUE(m2.Matches("cats"));
EXPECT_FALSE(m2.Matches("dogs"));
}
// Tests that a StringPiece object can be implicitly converted to a
// Matcher<StringPiece> or Matcher<const StringPiece&>.
TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromStringPiece) {
Matcher<StringPiece> m1 = StringPiece("cats");
EXPECT_TRUE(m1.Matches("cats"));
EXPECT_FALSE(m1.Matches("dogs"));
Matcher<const StringPiece&> m2 = StringPiece("cats");
EXPECT_TRUE(m2.Matches("cats"));
EXPECT_FALSE(m2.Matches("dogs"));
}
#endif // GTEST_HAS_STRING_PIECE_
// Tests that MakeMatcher() constructs a Matcher<T> from a
// MatcherInterface* without requiring the user to explicitly
// write the type.
TEST(MakeMatcherTest, ConstructsMatcherFromMatcherInterface) {
const MatcherInterface<int>* dummy_impl = NULL;
Matcher<int> m = MakeMatcher(dummy_impl);
}
// Tests that MakePolymorphicMatcher() can construct a polymorphic
// matcher from its implementation using the old API.
const int g_bar = 1;
class ReferencesBarOrIsZeroImpl {
public:
template <typename T>
bool MatchAndExplain(const T& x,
MatchResultListener* /* listener */) const {
const void* p = &x;
return p == &g_bar || x == 0;
}
void DescribeTo(ostream* os) const { *os << "g_bar or zero"; }
void DescribeNegationTo(ostream* os) const {
*os << "doesn't reference g_bar and is not zero";
}
};
// This function verifies that MakePolymorphicMatcher() returns a
// PolymorphicMatcher<T> where T is the argument's type.
PolymorphicMatcher<ReferencesBarOrIsZeroImpl> ReferencesBarOrIsZero() {
return MakePolymorphicMatcher(ReferencesBarOrIsZeroImpl());
}
TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingOldAPI) {
// Using a polymorphic matcher to match a reference type.
Matcher<const int&> m1 = ReferencesBarOrIsZero();
EXPECT_TRUE(m1.Matches(0));
// Verifies that the identity of a by-reference argument is preserved.
EXPECT_TRUE(m1.Matches(g_bar));
EXPECT_FALSE(m1.Matches(1));
EXPECT_EQ("g_bar or zero", Describe(m1));
// Using a polymorphic matcher to match a value type.
Matcher<double> m2 = ReferencesBarOrIsZero();
EXPECT_TRUE(m2.Matches(0.0));
EXPECT_FALSE(m2.Matches(0.1));
EXPECT_EQ("g_bar or zero", Describe(m2));
}
// Tests implementing a polymorphic matcher using MatchAndExplain().
class PolymorphicIsEvenImpl {
public:
void DescribeTo(ostream* os) const { *os << "is even"; }
void DescribeNegationTo(ostream* os) const {
*os << "is odd";
}
template <typename T>
bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
// Verifies that we can stream to the listener directly.
*listener << "% " << 2;
if (listener->stream() != NULL) {
// Verifies that we can stream to the listener's underlying stream
// too.
*listener->stream() << " == " << (x % 2);
}
return (x % 2) == 0;
}
};
PolymorphicMatcher<PolymorphicIsEvenImpl> PolymorphicIsEven() {
return MakePolymorphicMatcher(PolymorphicIsEvenImpl());
}
TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingNewAPI) {
// Using PolymorphicIsEven() as a Matcher<int>.
const Matcher<int> m1 = PolymorphicIsEven();
EXPECT_TRUE(m1.Matches(42));
EXPECT_FALSE(m1.Matches(43));
EXPECT_EQ("is even", Describe(m1));
const Matcher<int> not_m1 = Not(m1);
EXPECT_EQ("is odd", Describe(not_m1));
EXPECT_EQ("% 2 == 0", Explain(m1, 42));
// Using PolymorphicIsEven() as a Matcher<char>.
const Matcher<char> m2 = PolymorphicIsEven();
EXPECT_TRUE(m2.Matches('\x42'));
EXPECT_FALSE(m2.Matches('\x43'));
EXPECT_EQ("is even", Describe(m2));
const Matcher<char> not_m2 = Not(m2);
EXPECT_EQ("is odd", Describe(not_m2));
EXPECT_EQ("% 2 == 0", Explain(m2, '\x42'));
}
// Tests that MatcherCast<T>(m) works when m is a polymorphic matcher.
TEST(MatcherCastTest, FromPolymorphicMatcher) {
Matcher<int> m = MatcherCast<int>(Eq(5));
EXPECT_TRUE(m.Matches(5));
EXPECT_FALSE(m.Matches(6));
}
// For testing casting matchers between compatible types.
class IntValue {
public:
// An int can be statically (although not implicitly) cast to a
// IntValue.
explicit IntValue(int a_value) : value_(a_value) {}
int value() const { return value_; }
private:
int value_;
};
// For testing casting matchers between compatible types.
bool IsPositiveIntValue(const IntValue& foo) {
return foo.value() > 0;
}
// Tests that MatcherCast<T>(m) works when m is a Matcher<U> where T
// can be statically converted to U.
TEST(MatcherCastTest, FromCompatibleType) {
Matcher<double> m1 = Eq(2.0);
Matcher<int> m2 = MatcherCast<int>(m1);
EXPECT_TRUE(m2.Matches(2));
EXPECT_FALSE(m2.Matches(3));
Matcher<IntValue> m3 = Truly(IsPositiveIntValue);
Matcher<int> m4 = MatcherCast<int>(m3);
// In the following, the arguments 1 and 0 are statically converted
// to IntValue objects, and then tested by the IsPositiveIntValue()
// predicate.
EXPECT_TRUE(m4.Matches(1));
EXPECT_FALSE(m4.Matches(0));
}
// Tests that MatcherCast<T>(m) works when m is a Matcher<const T&>.
TEST(MatcherCastTest, FromConstReferenceToNonReference) {
Matcher<const int&> m1 = Eq(0);
Matcher<int> m2 = MatcherCast<int>(m1);
EXPECT_TRUE(m2.Matches(0));
EXPECT_FALSE(m2.Matches(1));
}
// Tests that MatcherCast<T>(m) works when m is a Matcher<T&>.
TEST(MatcherCastTest, FromReferenceToNonReference) {
Matcher<int&> m1 = Eq(0);
Matcher<int> m2 = MatcherCast<int>(m1);
EXPECT_TRUE(m2.Matches(0));
EXPECT_FALSE(m2.Matches(1));
}
// Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
TEST(MatcherCastTest, FromNonReferenceToConstReference) {
Matcher<int> m1 = Eq(0);
Matcher<const int&> m2 = MatcherCast<const int&>(m1);
EXPECT_TRUE(m2.Matches(0));
EXPECT_FALSE(m2.Matches(1));
}
// Tests that MatcherCast<T&>(m) works when m is a Matcher<T>.
TEST(MatcherCastTest, FromNonReferenceToReference) {
Matcher<int> m1 = Eq(0);
Matcher<int&> m2 = MatcherCast<int&>(m1);
int n = 0;
EXPECT_TRUE(m2.Matches(n));
n = 1;
EXPECT_FALSE(m2.Matches(n));
}
// Tests that MatcherCast<T>(m) works when m is a Matcher<T>.
TEST(MatcherCastTest, FromSameType) {
Matcher<int> m1 = Eq(0);
Matcher<int> m2 = MatcherCast<int>(m1);
EXPECT_TRUE(m2.Matches(0));
EXPECT_FALSE(m2.Matches(1));
}
// Implicitly convertible form any type.
struct ConvertibleFromAny {
ConvertibleFromAny(int a_value) : value(a_value) {}
template <typename T>
ConvertibleFromAny(const T& a_value) : value(-1) {
ADD_FAILURE() << "Conversion constructor called";
}
int value;
};
bool operator==(const ConvertibleFromAny& a, const ConvertibleFromAny& b) {
return a.value == b.value;
}
ostream& operator<<(ostream& os, const ConvertibleFromAny& a) {
return os << a.value;
}
TEST(MatcherCastTest, ConversionConstructorIsUsed) {
Matcher<ConvertibleFromAny> m = MatcherCast<ConvertibleFromAny>(1);
EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
}
TEST(MatcherCastTest, FromConvertibleFromAny) {
Matcher<ConvertibleFromAny> m =
MatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
}
class Base {};
class Derived : public Base {};
// Tests that SafeMatcherCast<T>(m) works when m is a polymorphic matcher.
TEST(SafeMatcherCastTest, FromPolymorphicMatcher) {
Matcher<char> m2 = SafeMatcherCast<char>(Eq(32));
EXPECT_TRUE(m2.Matches(' '));
EXPECT_FALSE(m2.Matches('\n'));
}
// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where
// T and U are arithmetic types and T can be losslessly converted to
// U.
TEST(SafeMatcherCastTest, FromLosslesslyConvertibleArithmeticType) {
Matcher<double> m1 = DoubleEq(1.0);
Matcher<float> m2 = SafeMatcherCast<float>(m1);
EXPECT_TRUE(m2.Matches(1.0f));
EXPECT_FALSE(m2.Matches(2.0f));
Matcher<char> m3 = SafeMatcherCast<char>(TypedEq<int>('a'));
EXPECT_TRUE(m3.Matches('a'));
EXPECT_FALSE(m3.Matches('b'));
}
// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where T and U
// are pointers or references to a derived and a base class, correspondingly.
TEST(SafeMatcherCastTest, FromBaseClass) {
Derived d, d2;
Matcher<Base*> m1 = Eq(&d);
Matcher<Derived*> m2 = SafeMatcherCast<Derived*>(m1);
EXPECT_TRUE(m2.Matches(&d));
EXPECT_FALSE(m2.Matches(&d2));
Matcher<Base&> m3 = Ref(d);
Matcher<Derived&> m4 = SafeMatcherCast<Derived&>(m3);
EXPECT_TRUE(m4.Matches(d));
EXPECT_FALSE(m4.Matches(d2));
}
// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<const T&>.
TEST(SafeMatcherCastTest, FromConstReferenceToReference) {
int n = 0;
Matcher<const int&> m1 = Ref(n);
Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
int n1 = 0;
EXPECT_TRUE(m2.Matches(n));
EXPECT_FALSE(m2.Matches(n1));
}
// Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
TEST(SafeMatcherCastTest, FromNonReferenceToConstReference) {
Matcher<int> m1 = Eq(0);
Matcher<const int&> m2 = SafeMatcherCast<const int&>(m1);
EXPECT_TRUE(m2.Matches(0));
EXPECT_FALSE(m2.Matches(1));
}
// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<T>.
TEST(SafeMatcherCastTest, FromNonReferenceToReference) {
Matcher<int> m1 = Eq(0);
Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
int n = 0;
EXPECT_TRUE(m2.Matches(n));
n = 1;
EXPECT_FALSE(m2.Matches(n));
}
// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<T>.
TEST(SafeMatcherCastTest, FromSameType) {
Matcher<int> m1 = Eq(0);
Matcher<int> m2 = SafeMatcherCast<int>(m1);
EXPECT_TRUE(m2.Matches(0));
EXPECT_FALSE(m2.Matches(1));
}
TEST(SafeMatcherCastTest, ConversionConstructorIsUsed) {
Matcher<ConvertibleFromAny> m = SafeMatcherCast<ConvertibleFromAny>(1);
EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
}
TEST(SafeMatcherCastTest, FromConvertibleFromAny) {
Matcher<ConvertibleFromAny> m =
SafeMatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
}
// Tests that A<T>() matches any value of type T.
TEST(ATest, MatchesAnyValue) {
// Tests a matcher for a value type.
Matcher<double> m1 = A<double>();
EXPECT_TRUE(m1.Matches(91.43));
EXPECT_TRUE(m1.Matches(-15.32));
// Tests a matcher for a reference type.
int a = 2;
int b = -6;
Matcher<int&> m2 = A<int&>();
EXPECT_TRUE(m2.Matches(a));
EXPECT_TRUE(m2.Matches(b));
}
TEST(ATest, WorksForDerivedClass) {
Base base;
Derived derived;
EXPECT_THAT(&base, A<Base*>());
// This shouldn't compile: EXPECT_THAT(&base, A<Derived*>());
EXPECT_THAT(&derived, A<Base*>());
EXPECT_THAT(&derived, A<Derived*>());
}
// Tests that A<T>() describes itself properly.
TEST(ATest, CanDescribeSelf) {
EXPECT_EQ("is anything", Describe(A<bool>()));
}
// Tests that An<T>() matches any value of type T.
TEST(AnTest, MatchesAnyValue) {
// Tests a matcher for a value type.
Matcher<int> m1 = An<int>();
EXPECT_TRUE(m1.Matches(9143));
EXPECT_TRUE(m1.Matches(-1532));
// Tests a matcher for a reference type.
int a = 2;
int b = -6;
Matcher<int&> m2 = An<int&>();
EXPECT_TRUE(m2.Matches(a));
EXPECT_TRUE(m2.Matches(b));
}
// Tests that An<T>() describes itself properly.
TEST(AnTest, CanDescribeSelf) {
EXPECT_EQ("is anything", Describe(An<int>()));
}
// Tests that _ can be used as a matcher for any type and matches any
// value of that type.
TEST(UnderscoreTest, MatchesAnyValue) {
// Uses _ as a matcher for a value type.
Matcher<int> m1 = _;
EXPECT_TRUE(m1.Matches(123));
EXPECT_TRUE(m1.Matches(-242));
// Uses _ as a matcher for a reference type.
bool a = false;
const bool b = true;
Matcher<const bool&> m2 = _;
EXPECT_TRUE(m2.Matches(a));
EXPECT_TRUE(m2.Matches(b));
}
// Tests that _ describes itself properly.
TEST(UnderscoreTest, CanDescribeSelf) {
Matcher<int> m = _;
EXPECT_EQ("is anything", Describe(m));
}
// Tests that Eq(x) matches any value equal to x.
TEST(EqTest, MatchesEqualValue) {
// 2 C-strings with same content but different addresses.
const char a1[] = "hi";
const char a2[] = "hi";
Matcher<const char*> m1 = Eq(a1);
EXPECT_TRUE(m1.Matches(a1));
EXPECT_FALSE(m1.Matches(a2));
}
// Tests that Eq(v) describes itself properly.
class Unprintable {
public:
Unprintable() : c_('a') {}
bool operator==(const Unprintable& /* rhs */) { return true; }
private:
char c_;
};
TEST(EqTest, CanDescribeSelf) {
Matcher<Unprintable> m = Eq(Unprintable());
EXPECT_EQ("is equal to 1-byte object <61>", Describe(m));
}
// Tests that Eq(v) can be used to match any type that supports
// comparing with type T, where T is v's type.
TEST(EqTest, IsPolymorphic) {
Matcher<int> m1 = Eq(1);
EXPECT_TRUE(m1.Matches(1));
EXPECT_FALSE(m1.Matches(2));
Matcher<char> m2 = Eq(1);
EXPECT_TRUE(m2.Matches('\1'));
EXPECT_FALSE(m2.Matches('a'));
}
// Tests that TypedEq<T>(v) matches values of type T that's equal to v.
TEST(TypedEqTest, ChecksEqualityForGivenType) {
Matcher<char> m1 = TypedEq<char>('a');
EXPECT_TRUE(m1.Matches('a'));
EXPECT_FALSE(m1.Matches('b'));
Matcher<int> m2 = TypedEq<int>(6);
EXPECT_TRUE(m2.Matches(6));
EXPECT_FALSE(m2.Matches(7));
}
// Tests that TypedEq(v) describes itself properly.
TEST(TypedEqTest, CanDescribeSelf) {
EXPECT_EQ("is equal to 2", Describe(TypedEq<int>(2)));
}
// Tests that TypedEq<T>(v) has type Matcher<T>.
// Type<T>::IsTypeOf(v) compiles iff the type of value v is T, where T
// is a "bare" type (i.e. not in the form of const U or U&). If v's
// type is not T, the compiler will generate a message about
// "undefined referece".
template <typename T>
struct Type {
static bool IsTypeOf(const T& /* v */) { return true; }
template <typename T2>
static void IsTypeOf(T2 v);
};
TEST(TypedEqTest, HasSpecifiedType) {
// Verfies that the type of TypedEq<T>(v) is Matcher<T>.
Type<Matcher<int> >::IsTypeOf(TypedEq<int>(5));
Type<Matcher<double> >::IsTypeOf(TypedEq<double>(5));
}
// Tests that Ge(v) matches anything >= v.
TEST(GeTest, ImplementsGreaterThanOrEqual) {
Matcher<int> m1 = Ge(0);
EXPECT_TRUE(m1.Matches(1));
EXPECT_TRUE(m1.Matches(0));
EXPECT_FALSE(m1.Matches(-1));
}
// Tests that Ge(v) describes itself properly.
TEST(GeTest, CanDescribeSelf) {
Matcher<int> m = Ge(5);
EXPECT_EQ("is >= 5", Describe(m));
}
// Tests that Gt(v) matches anything > v.
TEST(GtTest, ImplementsGreaterThan) {
Matcher<double> m1 = Gt(0);
EXPECT_TRUE(m1.Matches(1.0));
EXPECT_FALSE(m1.Matches(0.0));
EXPECT_FALSE(m1.Matches(-1.0));
}
// Tests that Gt(v) describes itself properly.
TEST(GtTest, CanDescribeSelf) {
Matcher<int> m = Gt(5);
EXPECT_EQ("is > 5", Describe(m));
}
// Tests that Le(v) matches anything <= v.
TEST(LeTest, ImplementsLessThanOrEqual) {
Matcher<char> m1 = Le('b');
EXPECT_TRUE(m1.Matches('a'));
EXPECT_TRUE(m1.Matches('b'));
EXPECT_FALSE(m1.Matches('c'));
}
// Tests that Le(v) describes itself properly.
TEST(LeTest, CanDescribeSelf) {
Matcher<int> m = Le(5);
EXPECT_EQ("is <= 5", Describe(m));
}
// Tests that Lt(v) matches anything < v.
TEST(LtTest, ImplementsLessThan) {
Matcher<const string&> m1 = Lt("Hello");
EXPECT_TRUE(m1.Matches("Abc"));
EXPECT_FALSE(m1.Matches("Hello"));
EXPECT_FALSE(m1.Matches("Hello, world!"));
}
// Tests that Lt(v) describes itself properly.
TEST(LtTest, CanDescribeSelf) {
Matcher<int> m = Lt(5);
EXPECT_EQ("is < 5", Describe(m));
}
// Tests that Ne(v) matches anything != v.
TEST(NeTest, ImplementsNotEqual) {
Matcher<int> m1 = Ne(0);
EXPECT_TRUE(m1.Matches(1));
EXPECT_TRUE(m1.Matches(-1));
EXPECT_FALSE(m1.Matches(0));
}
// Tests that Ne(v) describes itself properly.
TEST(NeTest, CanDescribeSelf) {
Matcher<int> m = Ne(5);
EXPECT_EQ("isn't equal to 5", Describe(m));
}
// Tests that IsNull() matches any NULL pointer of any type.
TEST(IsNullTest, MatchesNullPointer) {
Matcher<int*> m1 = IsNull();
int* p1 = NULL;
int n = 0;
EXPECT_TRUE(m1.Matches(p1));
EXPECT_FALSE(m1.Matches(&n));
Matcher<const char*> m2 = IsNull();
const char* p2 = NULL;
EXPECT_TRUE(m2.Matches(p2));
EXPECT_FALSE(m2.Matches("hi"));
#if !GTEST_OS_SYMBIAN
// Nokia's Symbian compiler generates:
// gmock-matchers.h: ambiguous access to overloaded function
// gmock-matchers.h: 'testing::Matcher<void *>::Matcher(void *)'
// gmock-matchers.h: 'testing::Matcher<void *>::Matcher(const testing::
// MatcherInterface<void *> *)'
// gmock-matchers.h: (point of instantiation: 'testing::
// gmock_matchers_test::IsNullTest_MatchesNullPointer_Test::TestBody()')
// gmock-matchers.h: (instantiating: 'testing::PolymorphicMatc
Matcher<void*> m3 = IsNull();
void* p3 = NULL;
EXPECT_TRUE(m3.Matches(p3));
EXPECT_FALSE(m3.Matches(reinterpret_cast<void*>(0xbeef)));
#endif
}
TEST(IsNullTest, LinkedPtr) {
const Matcher<linked_ptr<int> > m = IsNull();
const linked_ptr<int> null_p;
const linked_ptr<int> non_null_p(new int);
EXPECT_TRUE(m.Matches(null_p));
EXPECT_FALSE(m.Matches(non_null_p));
}
TEST(IsNullTest, ReferenceToConstLinkedPtr) {
const Matcher<const linked_ptr<double>&> m = IsNull();
const linked_ptr<double> null_p;
const linked_ptr<double> non_null_p(new double);
EXPECT_TRUE(m.Matches(null_p));
EXPECT_FALSE(m.Matches(non_null_p));
}
TEST(IsNullTest, ReferenceToConstScopedPtr) {
const Matcher<const scoped_ptr<double>&> m = IsNull();
const scoped_ptr<double> null_p;
const scoped_ptr<double> non_null_p(new double);
EXPECT_TRUE(m.Matches(null_p));
EXPECT_FALSE(m.Matches(non_null_p));
}
// Tests that IsNull() describes itself properly.
TEST(IsNullTest, CanDescribeSelf) {
Matcher<int*> m = IsNull();
EXPECT_EQ("is NULL", Describe(m));
EXPECT_EQ("isn't NULL", DescribeNegation(m));
}
// Tests that NotNull() matches any non-NULL pointer of any type.
TEST(NotNullTest, MatchesNonNullPointer) {
Matcher<int*> m1 = NotNull();
int* p1 = NULL;
int n = 0;
EXPECT_FALSE(m1.Matches(p1));
EXPECT_TRUE(m1.Matches(&n));
Matcher<const char*> m2 = NotNull();
const char* p2 = NULL;
EXPECT_FALSE(m2.Matches(p2));
EXPECT_TRUE(m2.Matches("hi"));
}
TEST(NotNullTest, LinkedPtr) {
const Matcher<linked_ptr<int> > m = NotNull();
const linked_ptr<int> null_p;
const linked_ptr<int> non_null_p(new int);
EXPECT_FALSE(m.Matches(null_p));
EXPECT_TRUE(m.Matches(non_null_p));
}
TEST(NotNullTest, ReferenceToConstLinkedPtr) {
const Matcher<const linked_ptr<double>&> m = NotNull();
const linked_ptr<double> null_p;
const linked_ptr<double> non_null_p(new double);
EXPECT_FALSE(m.Matches(null_p));
EXPECT_TRUE(m.Matches(non_null_p));
}
TEST(NotNullTest, ReferenceToConstScopedPtr) {
const Matcher<const scoped_ptr<double>&> m = NotNull();
const scoped_ptr<double> null_p;
const scoped_ptr<double> non_null_p(new double);
EXPECT_FALSE(m.Matches(null_p));
EXPECT_TRUE(m.Matches(non_null_p));
}
// Tests that NotNull() describes itself properly.
TEST(NotNullTest, CanDescribeSelf) {
Matcher<int*> m = NotNull();
EXPECT_EQ("isn't NULL", Describe(m));
}
// Tests that Ref(variable) matches an argument that references
// 'variable'.
TEST(RefTest, MatchesSameVariable) {
int a = 0;
int b = 0;
Matcher<int&> m = Ref(a);
EXPECT_TRUE(m.Matches(a));
EXPECT_FALSE(m.Matches(b));
}
// Tests that Ref(variable) describes itself properly.
TEST(RefTest, CanDescribeSelf) {
int n = 5;
Matcher<int&> m = Ref(n);
stringstream ss;
ss << "references the variable @" << &n << " 5";
EXPECT_EQ(string(ss.str()), Describe(m));
}
// Test that Ref(non_const_varialbe) can be used as a matcher for a
// const reference.
TEST(RefTest, CanBeUsedAsMatcherForConstReference) {
int a = 0;
int b = 0;
Matcher<const int&> m = Ref(a);
EXPECT_TRUE(m.Matches(a));
EXPECT_FALSE(m.Matches(b));
}
// Tests that Ref(variable) is covariant, i.e. Ref(derived) can be
// used wherever Ref(base) can be used (Ref(derived) is a sub-type
// of Ref(base), but not vice versa.
TEST(RefTest, IsCovariant) {
Base base, base2;
Derived derived;
Matcher<const Base&> m1 = Ref(base);
EXPECT_TRUE(m1.Matches(base));
EXPECT_FALSE(m1.Matches(base2));
EXPECT_FALSE(m1.Matches(derived));
m1 = Ref(derived);
EXPECT_TRUE(m1.Matches(derived));
EXPECT_FALSE(m1.Matches(base));
EXPECT_FALSE(m1.Matches(base2));
}
TEST(RefTest, ExplainsResult) {
int n = 0;
EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), n),
StartsWith("which is located @"));
int m = 0;
EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), m),
StartsWith("which is located @"));
}
// Tests string comparison matchers.
TEST(StrEqTest, MatchesEqualString) {
Matcher<const char*> m = StrEq(string("Hello"));
EXPECT_TRUE(m.Matches("Hello"));
EXPECT_FALSE(m.Matches("hello"));
EXPECT_FALSE(m.Matches(NULL));
Matcher<const string&> m2 = StrEq("Hello");
EXPECT_TRUE(m2.Matches("Hello"));
EXPECT_FALSE(m2.Matches("Hi"));
}
TEST(StrEqTest, CanDescribeSelf) {
Matcher<string> m = StrEq("Hi-\'\"?\\\a\b\f\n\r\t\v\xD3");
EXPECT_EQ("is equal to \"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\xD3\"",
Describe(m));
string str("01204500800");
str[3] = '\0';
Matcher<string> m2 = StrEq(str);
EXPECT_EQ("is equal to \"012\\04500800\"", Describe(m2));
str[0] = str[6] = str[7] = str[9] = str[10] = '\0';
Matcher<string> m3 = StrEq(str);
EXPECT_EQ("is equal to \"\\012\\045\\0\\08\\0\\0\"", Describe(m3));
}
TEST(StrNeTest, MatchesUnequalString) {
Matcher<const char*> m = StrNe("Hello");
EXPECT_TRUE(m.Matches(""));
EXPECT_TRUE(m.Matches(NULL));
EXPECT_FALSE(m.Matches("Hello"));
Matcher<string> m2 = StrNe(string("Hello"));
EXPECT_TRUE(m2.Matches("hello"));
EXPECT_FALSE(m2.Matches("Hello"));
}
TEST(StrNeTest, CanDescribeSelf) {
Matcher<const char*> m = StrNe("Hi");
EXPECT_EQ("isn't equal to \"Hi\"", Describe(m));
}
TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) {
Matcher<const char*> m = StrCaseEq(string("Hello"));
EXPECT_TRUE(m.Matches("Hello"));
EXPECT_TRUE(m.Matches("hello"));
EXPECT_FALSE(m.Matches("Hi"));
EXPECT_FALSE(m.Matches(NULL));
Matcher<const string&> m2 = StrCaseEq("Hello");
EXPECT_TRUE(m2.Matches("hello"));
EXPECT_FALSE(m2.Matches("Hi"));
}
TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
string str1("oabocdooeoo");
string str2("OABOCDOOEOO");
Matcher<const string&> m0 = StrCaseEq(str1);
EXPECT_FALSE(m0.Matches(str2 + string(1, '\0')));
str1[3] = str2[3] = '\0';
Matcher<const string&> m1 = StrCaseEq(str1);
EXPECT_TRUE(m1.Matches(str2));
str1[0] = str1[6] = str1[7] = str1[10] = '\0';
str2[0] = str2[6] = str2[7] = str2[10] = '\0';
Matcher<const string&> m2 = StrCaseEq(str1);
str1[9] = str2[9] = '\0';
EXPECT_FALSE(m2.Matches(str2));
Matcher<const string&> m3 = StrCaseEq(str1);
EXPECT_TRUE(m3.Matches(str2));
EXPECT_FALSE(m3.Matches(str2 + "x"));
str2.append(1, '\0');
EXPECT_FALSE(m3.Matches(str2));
EXPECT_FALSE(m3.Matches(string(str2, 0, 9)));
}
TEST(StrCaseEqTest, CanDescribeSelf) {
Matcher<string> m = StrCaseEq("Hi");
EXPECT_EQ("is equal to (ignoring case) \"Hi\"", Describe(m));
}
TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) {
Matcher<const char*> m = StrCaseNe("Hello");
EXPECT_TRUE(m.Matches("Hi"));
EXPECT_TRUE(m.Matches(NULL));
EXPECT_FALSE(m.Matches("Hello"));
EXPECT_FALSE(m.Matches("hello"));
Matcher<string> m2 = StrCaseNe(string("Hello"));
EXPECT_TRUE(m2.Matches(""));
EXPECT_FALSE(m2.Matches("Hello"));
}
TEST(StrCaseNeTest, CanDescribeSelf) {
Matcher<const char*> m = StrCaseNe("Hi");
EXPECT_EQ("isn't equal to (ignoring case) \"Hi\"", Describe(m));
}
// Tests that HasSubstr() works for matching string-typed values.
TEST(HasSubstrTest, WorksForStringClasses) {
const Matcher<string> m1 = HasSubstr("foo");
EXPECT_TRUE(m1.Matches(string("I love food.")));
EXPECT_FALSE(m1.Matches(string("tofo")));
const Matcher<const std::string&> m2 = HasSubstr("foo");
EXPECT_TRUE(m2.Matches(std::string("I love food.")));
EXPECT_FALSE(m2.Matches(std::string("tofo")));
}
// Tests that HasSubstr() works for matching C-string-typed values.
TEST(HasSubstrTest, WorksForCStrings) {
const Matcher<char*> m1 = HasSubstr("foo");
EXPECT_TRUE(m1.Matches(const_cast<char*>("I love food.")));
EXPECT_FALSE(m1.Matches(const_cast<char*>("tofo")));
EXPECT_FALSE(m1.Matches(NULL));
const Matcher<const char*> m2 = HasSubstr("foo");
EXPECT_TRUE(m2.Matches("I love food."));
EXPECT_FALSE(m2.Matches("tofo"));
EXPECT_FALSE(m2.Matches(NULL));
}
// Tests that HasSubstr(s) describes itself properly.
TEST(HasSubstrTest, CanDescribeSelf) {
Matcher<string> m = HasSubstr("foo\n\"");
EXPECT_EQ("has substring \"foo\\n\\\"\"", Describe(m));
}
TEST(KeyTest, CanDescribeSelf) {
Matcher<const pair<std::string, int>&> m = Key("foo");
EXPECT_EQ("has a key that is equal to \"foo\"", Describe(m));
EXPECT_EQ("doesn't have a key that is equal to \"foo\"", DescribeNegation(m));
}
TEST(KeyTest, ExplainsResult) {
Matcher<pair<int, bool> > m = Key(GreaterThan(10));
EXPECT_EQ("whose first field is a value which is 5 less than 10",
Explain(m, make_pair(5, true)));
EXPECT_EQ("whose first field is a value which is 5 more than 10",
Explain(m, make_pair(15, true)));
}
TEST(KeyTest, MatchesCorrectly) {
pair<int, std::string> p(25, "foo");
EXPECT_THAT(p, Key(25));
EXPECT_THAT(p, Not(Key(42)));
EXPECT_THAT(p, Key(Ge(20)));
EXPECT_THAT(p, Not(Key(Lt(25))));
}
TEST(KeyTest, SafelyCastsInnerMatcher) {
Matcher<int> is_positive = Gt(0);
Matcher<int> is_negative = Lt(0);
pair<char, bool> p('a', true);
EXPECT_THAT(p, Key(is_positive));
EXPECT_THAT(p, Not(Key(is_negative)));
}
TEST(KeyTest, InsideContainsUsingMap) {
map<int, char> container;
container.insert(make_pair(1, 'a'));
container.insert(make_pair(2, 'b'));
container.insert(make_pair(4, 'c'));
EXPECT_THAT(container, Contains(Key(1)));
EXPECT_THAT(container, Not(Contains(Key(3))));
}
TEST(KeyTest, InsideContainsUsingMultimap) {
multimap<int, char> container;
container.insert(make_pair(1, 'a'));
container.insert(make_pair(2, 'b'));
container.insert(make_pair(4, 'c'));
EXPECT_THAT(container, Not(Contains(Key(25))));
container.insert(make_pair(25, 'd'));
EXPECT_THAT(container, Contains(Key(25)));
container.insert(make_pair(25, 'e'));
EXPECT_THAT(container, Contains(Key(25)));
EXPECT_THAT(container, Contains(Key(1)));
EXPECT_THAT(container, Not(Contains(Key(3))));
}
TEST(PairTest, Typing) {
// Test verifies the following type conversions can be compiled.
Matcher<const pair<const char*, int>&> m1 = Pair("foo", 42);
Matcher<const pair<const char*, int> > m2 = Pair("foo", 42);
Matcher<pair<const char*, int> > m3 = Pair("foo", 42);
Matcher<pair<int, const std::string> > m4 = Pair(25, "42");
Matcher<pair<const std::string, int> > m5 = Pair("25", 42);
}
TEST(PairTest, CanDescribeSelf) {
Matcher<const pair<std::string, int>&> m1 = Pair("foo", 42);
EXPECT_EQ("has a first field that is equal to \"foo\""
", and has a second field that is equal to 42",
Describe(m1));
EXPECT_EQ("has a first field that isn't equal to \"foo\""
", or has a second field that isn't equal to 42",
DescribeNegation(m1));
// Double and triple negation (1 or 2 times not and description of negation).
Matcher<const pair<int, int>&> m2 = Not(Pair(Not(13), 42));
EXPECT_EQ("has a first field that isn't equal to 13"
", and has a second field that is equal to 42",
DescribeNegation(m2));
}
TEST(PairTest, CanExplainMatchResultTo) {
// If neither field matches, Pair() should explain about the first
// field.
const Matcher<pair<int, int> > m = Pair(GreaterThan(0), GreaterThan(0));
EXPECT_EQ("whose first field does not match, which is 1 less than 0",
Explain(m, make_pair(-1, -2)));
// If the first field matches but the second doesn't, Pair() should
// explain about the second field.
EXPECT_EQ("whose second field does not match, which is 2 less than 0",
Explain(m, make_pair(1, -2)));
// If the first field doesn't match but the second does, Pair()
// should explain about the first field.
EXPECT_EQ("whose first field does not match, which is 1 less than 0",
Explain(m, make_pair(-1, 2)));
// If both fields match, Pair() should explain about them both.
EXPECT_EQ("whose both fields match, where the first field is a value "
"which is 1 more than 0, and the second field is a value "
"which is 2 more than 0",
Explain(m, make_pair(1, 2)));
// If only the first match has an explanation, only this explanation should
// be printed.
const Matcher<pair<int, int> > explain_first = Pair(GreaterThan(0), 0);
EXPECT_EQ("whose both fields match, where the first field is a value "
"which is 1 more than 0",
Explain(explain_first, make_pair(1, 0)));
// If only the second match has an explanation, only this explanation should
// be printed.
const Matcher<pair<int, int> > explain_second = Pair(0, GreaterThan(0));
EXPECT_EQ("whose both fields match, where the second field is a value "
"which is 1 more than 0",
Explain(explain_second, make_pair(0, 1)));
}
TEST(PairTest, MatchesCorrectly) {
pair<int, std::string> p(25, "foo");
// Both fields match.
EXPECT_THAT(p, Pair(25, "foo"));
EXPECT_THAT(p, Pair(Ge(20), HasSubstr("o")));
// 'first' doesnt' match, but 'second' matches.
EXPECT_THAT(p, Not(Pair(42, "foo")));
EXPECT_THAT(p, Not(Pair(Lt(25), "foo")));
// 'first' matches, but 'second' doesn't match.
EXPECT_THAT(p, Not(Pair(25, "bar")));
EXPECT_THAT(p, Not(Pair(25, Not("foo"))));
// Neither field matches.
EXPECT_THAT(p, Not(Pair(13, "bar")));
EXPECT_THAT(p, Not(Pair(Lt(13), HasSubstr("a"))));
}
TEST(PairTest, SafelyCastsInnerMatchers) {
Matcher<int> is_positive = Gt(0);
Matcher<int> is_negative = Lt(0);
pair<char, bool> p('a', true);
EXPECT_THAT(p, Pair(is_positive, _));
EXPECT_THAT(p, Not(Pair(is_negative, _)));
EXPECT_THAT(p, Pair(_, is_positive));
EXPECT_THAT(p, Not(Pair(_, is_negative)));
}
TEST(PairTest, InsideContainsUsingMap) {
map<int, char> container;
container.insert(make_pair(1, 'a'));
container.insert(make_pair(2, 'b'));
container.insert(make_pair(4, 'c'));
EXPECT_THAT(container, Contains(Pair(1, 'a')));
EXPECT_THAT(container, Contains(Pair(1, _)));
EXPECT_THAT(container, Contains(Pair(_, 'a')));
EXPECT_THAT(container, Not(Contains(Pair(3, _))));
}
// Tests StartsWith(s).
TEST(StartsWithTest, MatchesStringWithGivenPrefix) {
const Matcher<const char*> m1 = StartsWith(string(""));
EXPECT_TRUE(m1.Matches("Hi"));
EXPECT_TRUE(m1.Matches(""));
EXPECT_FALSE(m1.Matches(NULL));
const Matcher<const string&> m2 = StartsWith("Hi");
EXPECT_TRUE(m2.Matches("Hi"));
EXPECT_TRUE(m2.Matches("Hi Hi!"));
EXPECT_TRUE(m2.Matches("High"));
EXPECT_FALSE(m2.Matches("H"));
EXPECT_FALSE(m2.Matches(" Hi"));
}
TEST(StartsWithTest, CanDescribeSelf) {
Matcher<const std::string> m = StartsWith("Hi");
EXPECT_EQ("starts with \"Hi\"", Describe(m));
}
// Tests EndsWith(s).
TEST(EndsWithTest, MatchesStringWithGivenSuffix) {
const Matcher<const char*> m1 = EndsWith("");
EXPECT_TRUE(m1.Matches("Hi"));
EXPECT_TRUE(m1.Matches(""));
EXPECT_FALSE(m1.Matches(NULL));
const Matcher<const string&> m2 = EndsWith(string("Hi"));
EXPECT_TRUE(m2.Matches("Hi"));
EXPECT_TRUE(m2.Matches("Wow Hi Hi"));
EXPECT_TRUE(m2.Matches("Super Hi"));
EXPECT_FALSE(m2.Matches("i"));
EXPECT_FALSE(m2.Matches("Hi "));
}
TEST(EndsWithTest, CanDescribeSelf) {
Matcher<const std::string> m = EndsWith("Hi");
EXPECT_EQ("ends with \"Hi\"", Describe(m));
}
// Tests MatchesRegex().
TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) {
const Matcher<const char*> m1 = MatchesRegex("a.*z");
EXPECT_TRUE(m1.Matches("az"));
EXPECT_TRUE(m1.Matches("abcz"));
EXPECT_FALSE(m1.Matches(NULL));
const Matcher<const string&> m2 = MatchesRegex(new RE("a.*z"));
EXPECT_TRUE(m2.Matches("azbz"));
EXPECT_FALSE(m2.Matches("az1"));
EXPECT_FALSE(m2.Matches("1az"));
}
TEST(MatchesRegexTest, CanDescribeSelf) {
Matcher<const std::string> m1 = MatchesRegex(string("Hi.*"));
EXPECT_EQ("matches regular expression \"Hi.*\"", Describe(m1));
Matcher<const char*> m2 = MatchesRegex(new RE("a.*"));
EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2));
}
// Tests ContainsRegex().
TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) {
const Matcher<const char*> m1 = ContainsRegex(string("a.*z"));
EXPECT_TRUE(m1.Matches("az"));
EXPECT_TRUE(m1.Matches("0abcz1"));
EXPECT_FALSE(m1.Matches(NULL));
const Matcher<const string&> m2 = ContainsRegex(new RE("a.*z"));
EXPECT_TRUE(m2.Matches("azbz"));
EXPECT_TRUE(m2.Matches("az1"));
EXPECT_FALSE(m2.Matches("1a"));
}
TEST(ContainsRegexTest, CanDescribeSelf) {
Matcher<const std::string> m1 = ContainsRegex("Hi.*");
EXPECT_EQ("contains regular expression \"Hi.*\"", Describe(m1));
Matcher<const char*> m2 = ContainsRegex(new RE("a.*"));
EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2));
}
// Tests for wide strings.
#if GTEST_HAS_STD_WSTRING
TEST(StdWideStrEqTest, MatchesEqual) {
Matcher<const wchar_t*> m = StrEq(::std::wstring(L"Hello"));
EXPECT_TRUE(m.Matches(L"Hello"));
EXPECT_FALSE(m.Matches(L"hello"));
EXPECT_FALSE(m.Matches(NULL));
Matcher<const ::std::wstring&> m2 = StrEq(L"Hello");
EXPECT_TRUE(m2.Matches(L"Hello"));
EXPECT_FALSE(m2.Matches(L"Hi"));
Matcher<const ::std::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
::std::wstring str(L"01204500800");
str[3] = L'\0';
Matcher<const ::std::wstring&> m4 = StrEq(str);
EXPECT_TRUE(m4.Matches(str));
str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
Matcher<const ::std::wstring&> m5 = StrEq(str);
EXPECT_TRUE(m5.Matches(str));
}
TEST(StdWideStrEqTest, CanDescribeSelf) {
Matcher< ::std::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
Describe(m));
Matcher< ::std::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
Describe(m2));
::std::wstring str(L"01204500800");
str[3] = L'\0';
Matcher<const ::std::wstring&> m4 = StrEq(str);
EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
Matcher<const ::std::wstring&> m5 = StrEq(str);
EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
}
TEST(StdWideStrNeTest, MatchesUnequalString) {
Matcher<const wchar_t*> m = StrNe(L"Hello");
EXPECT_TRUE(m.Matches(L""));
EXPECT_TRUE(m.Matches(NULL));
EXPECT_FALSE(m.Matches(L"Hello"));
Matcher< ::std::wstring> m2 = StrNe(::std::wstring(L"Hello"));
EXPECT_TRUE(m2.Matches(L"hello"));
EXPECT_FALSE(m2.Matches(L"Hello"));
}
TEST(StdWideStrNeTest, CanDescribeSelf) {
Matcher<const wchar_t*> m = StrNe(L"Hi");
EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
}
TEST(StdWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
Matcher<const wchar_t*> m = StrCaseEq(::std::wstring(L"Hello"));
EXPECT_TRUE(m.Matches(L"Hello"));
EXPECT_TRUE(m.Matches(L"hello"));
EXPECT_FALSE(m.Matches(L"Hi"));
EXPECT_FALSE(m.Matches(NULL));
Matcher<const ::std::wstring&> m2 = StrCaseEq(L"Hello");
EXPECT_TRUE(m2.Matches(L"hello"));
EXPECT_FALSE(m2.Matches(L"Hi"));
}
TEST(StdWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
::std::wstring str1(L"oabocdooeoo");
::std::wstring str2(L"OABOCDOOEOO");
Matcher<const ::std::wstring&> m0 = StrCaseEq(str1);
EXPECT_FALSE(m0.Matches(str2 + ::std::wstring(1, L'\0')));
str1[3] = str2[3] = L'\0';
Matcher<const ::std::wstring&> m1 = StrCaseEq(str1);
EXPECT_TRUE(m1.Matches(str2));
str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
Matcher<const ::std::wstring&> m2 = StrCaseEq(str1);
str1[9] = str2[9] = L'\0';
EXPECT_FALSE(m2.Matches(str2));
Matcher<const ::std::wstring&> m3 = StrCaseEq(str1);
EXPECT_TRUE(m3.Matches(str2));
EXPECT_FALSE(m3.Matches(str2 + L"x"));
str2.append(1, L'\0');
EXPECT_FALSE(m3.Matches(str2));
EXPECT_FALSE(m3.Matches(::std::wstring(str2, 0, 9)));
}
TEST(StdWideStrCaseEqTest, CanDescribeSelf) {
Matcher< ::std::wstring> m = StrCaseEq(L"Hi");
EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
}
TEST(StdWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
EXPECT_TRUE(m.Matches(L"Hi"));
EXPECT_TRUE(m.Matches(NULL));
EXPECT_FALSE(m.Matches(L"Hello"));
EXPECT_FALSE(m.Matches(L"hello"));
Matcher< ::std::wstring> m2 = StrCaseNe(::std::wstring(L"Hello"));
EXPECT_TRUE(m2.Matches(L""));
EXPECT_FALSE(m2.Matches(L"Hello"));
}
TEST(StdWideStrCaseNeTest, CanDescribeSelf) {
Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
}
// Tests that HasSubstr() works for matching wstring-typed values.
TEST(StdWideHasSubstrTest, WorksForStringClasses) {
const Matcher< ::std::wstring> m1 = HasSubstr(L"foo");
EXPECT_TRUE(m1.Matches(::std::wstring(L"I love food.")));
EXPECT_FALSE(m1.Matches(::std::wstring(L"tofo")));
const Matcher<const ::std::wstring&> m2 = HasSubstr(L"foo");
EXPECT_TRUE(m2.Matches(::std::wstring(L"I love food.")));
EXPECT_FALSE(m2.Matches(::std::wstring(L"tofo")));
}
// Tests that HasSubstr() works for matching C-wide-string-typed values.
TEST(StdWideHasSubstrTest, WorksForCStrings) {
const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
EXPECT_FALSE(m1.Matches(NULL));
const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
EXPECT_TRUE(m2.Matches(L"I love food."));
EXPECT_FALSE(m2.Matches(L"tofo"));
EXPECT_FALSE(m2.Matches(NULL));
}
// Tests that HasSubstr(s) describes itself properly.
TEST(StdWideHasSubstrTest, CanDescribeSelf) {
Matcher< ::std::wstring> m = HasSubstr(L"foo\n\"");
EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
}
// Tests StartsWith(s).
TEST(StdWideStartsWithTest, MatchesStringWithGivenPrefix) {
const Matcher<const wchar_t*> m1 = StartsWith(::std::wstring(L""));
EXPECT_TRUE(m1.Matches(L"Hi"));
EXPECT_TRUE(m1.Matches(L""));
EXPECT_FALSE(m1.Matches(NULL));
const Matcher<const ::std::wstring&> m2 = StartsWith(L"Hi");
EXPECT_TRUE(m2.Matches(L"Hi"));
EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
EXPECT_TRUE(m2.Matches(L"High"));
EXPECT_FALSE(m2.Matches(L"H"));
EXPECT_FALSE(m2.Matches(L" Hi"));
}
TEST(StdWideStartsWithTest, CanDescribeSelf) {
Matcher<const ::std::wstring> m = StartsWith(L"Hi");
EXPECT_EQ("starts with L\"Hi\"", Describe(m));
}
// Tests EndsWith(s).
TEST(StdWideEndsWithTest, MatchesStringWithGivenSuffix) {
const Matcher<const wchar_t*> m1 = EndsWith(L"");
EXPECT_TRUE(m1.Matches(L"Hi"));
EXPECT_TRUE(m1.Matches(L""));
EXPECT_FALSE(m1.Matches(NULL));
const Matcher<const ::std::wstring&> m2 = EndsWith(::std::wstring(L"Hi"));
EXPECT_TRUE(m2.Matches(L"Hi"));
EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
EXPECT_TRUE(m2.Matches(L"Super Hi"));
EXPECT_FALSE(m2.Matches(L"i"));
EXPECT_FALSE(m2.Matches(L"Hi "));
}
TEST(StdWideEndsWithTest, CanDescribeSelf) {
Matcher<const ::std::wstring> m = EndsWith(L"Hi");
EXPECT_EQ("ends with L\"Hi\"", Describe(m));
}
#endif // GTEST_HAS_STD_WSTRING
#if GTEST_HAS_GLOBAL_WSTRING
TEST(GlobalWideStrEqTest, MatchesEqual) {
Matcher<const wchar_t*> m = StrEq(::wstring(L"Hello"));
EXPECT_TRUE(m.Matches(L"Hello"));
EXPECT_FALSE(m.Matches(L"hello"));
EXPECT_FALSE(m.Matches(NULL));
Matcher<const ::wstring&> m2 = StrEq(L"Hello");
EXPECT_TRUE(m2.Matches(L"Hello"));
EXPECT_FALSE(m2.Matches(L"Hi"));
Matcher<const ::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
::wstring str(L"01204500800");
str[3] = L'\0';
Matcher<const ::wstring&> m4 = StrEq(str);
EXPECT_TRUE(m4.Matches(str));
str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
Matcher<const ::wstring&> m5 = StrEq(str);
EXPECT_TRUE(m5.Matches(str));
}
TEST(GlobalWideStrEqTest, CanDescribeSelf) {
Matcher< ::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
Describe(m));
Matcher< ::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
Describe(m2));
::wstring str(L"01204500800");
str[3] = L'\0';
Matcher<const ::wstring&> m4 = StrEq(str);
EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
Matcher<const ::wstring&> m5 = StrEq(str);
EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
}
TEST(GlobalWideStrNeTest, MatchesUnequalString) {
Matcher<const wchar_t*> m = StrNe(L"Hello");
EXPECT_TRUE(m.Matches(L""));
EXPECT_TRUE(m.Matches(NULL));
EXPECT_FALSE(m.Matches(L"Hello"));
Matcher< ::wstring> m2 = StrNe(::wstring(L"Hello"));
EXPECT_TRUE(m2.Matches(L"hello"));
EXPECT_FALSE(m2.Matches(L"Hello"));
}
TEST(GlobalWideStrNeTest, CanDescribeSelf) {
Matcher<const wchar_t*> m = StrNe(L"Hi");
EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
}
TEST(GlobalWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
Matcher<const wchar_t*> m = StrCaseEq(::wstring(L"Hello"));
EXPECT_TRUE(m.Matches(L"Hello"));
EXPECT_TRUE(m.Matches(L"hello"));
EXPECT_FALSE(m.Matches(L"Hi"));
EXPECT_FALSE(m.Matches(NULL));
Matcher<const ::wstring&> m2 = StrCaseEq(L"Hello");
EXPECT_TRUE(m2.Matches(L"hello"));
EXPECT_FALSE(m2.Matches(L"Hi"));
}
TEST(GlobalWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
::wstring str1(L"oabocdooeoo");
::wstring str2(L"OABOCDOOEOO");
Matcher<const ::wstring&> m0 = StrCaseEq(str1);
EXPECT_FALSE(m0.Matches(str2 + ::wstring(1, L'\0')));
str1[3] = str2[3] = L'\0';
Matcher<const ::wstring&> m1 = StrCaseEq(str1);
EXPECT_TRUE(m1.Matches(str2));
str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
Matcher<const ::wstring&> m2 = StrCaseEq(str1);
str1[9] = str2[9] = L'\0';
EXPECT_FALSE(m2.Matches(str2));
Matcher<const ::wstring&> m3 = StrCaseEq(str1);
EXPECT_TRUE(m3.Matches(str2));
EXPECT_FALSE(m3.Matches(str2 + L"x"));
str2.append(1, L'\0');
EXPECT_FALSE(m3.Matches(str2));
EXPECT_FALSE(m3.Matches(::wstring(str2, 0, 9)));
}
TEST(GlobalWideStrCaseEqTest, CanDescribeSelf) {
Matcher< ::wstring> m = StrCaseEq(L"Hi");
EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
}
TEST(GlobalWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
EXPECT_TRUE(m.Matches(L"Hi"));
EXPECT_TRUE(m.Matches(NULL));
EXPECT_FALSE(m.Matches(L"Hello"));
EXPECT_FALSE(m.Matches(L"hello"));
Matcher< ::wstring> m2 = StrCaseNe(::wstring(L"Hello"));
EXPECT_TRUE(m2.Matches(L""));
EXPECT_FALSE(m2.Matches(L"Hello"));
}
TEST(GlobalWideStrCaseNeTest, CanDescribeSelf) {
Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
}
// Tests that HasSubstr() works for matching wstring-typed values.
TEST(GlobalWideHasSubstrTest, WorksForStringClasses) {
const Matcher< ::wstring> m1 = HasSubstr(L"foo");
EXPECT_TRUE(m1.Matches(::wstring(L"I love food.")));
EXPECT_FALSE(m1.Matches(::wstring(L"tofo")));
const Matcher<const ::wstring&> m2 = HasSubstr(L"foo");
EXPECT_TRUE(m2.Matches(::wstring(L"I love food.")));
EXPECT_FALSE(m2.Matches(::wstring(L"tofo")));
}
// Tests that HasSubstr() works for matching C-wide-string-typed values.
TEST(GlobalWideHasSubstrTest, WorksForCStrings) {
const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
EXPECT_FALSE(m1.Matches(NULL));
const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
EXPECT_TRUE(m2.Matches(L"I love food."));
EXPECT_FALSE(m2.Matches(L"tofo"));
EXPECT_FALSE(m2.Matches(NULL));
}
// Tests that HasSubstr(s) describes itself properly.
TEST(GlobalWideHasSubstrTest, CanDescribeSelf) {
Matcher< ::wstring> m = HasSubstr(L"foo\n\"");
EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
}
// Tests StartsWith(s).
TEST(GlobalWideStartsWithTest, MatchesStringWithGivenPrefix) {
const Matcher<const wchar_t*> m1 = StartsWith(::wstring(L""));
EXPECT_TRUE(m1.Matches(L"Hi"));
EXPECT_TRUE(m1.Matches(L""));
EXPECT_FALSE(m1.Matches(NULL));
const Matcher<const ::wstring&> m2 = StartsWith(L"Hi");
EXPECT_TRUE(m2.Matches(L"Hi"));
EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
EXPECT_TRUE(m2.Matches(L"High"));
EXPECT_FALSE(m2.Matches(L"H"));
EXPECT_FALSE(m2.Matches(L" Hi"));
}
TEST(GlobalWideStartsWithTest, CanDescribeSelf) {
Matcher<const ::wstring> m = StartsWith(L"Hi");
EXPECT_EQ("starts with L\"Hi\"", Describe(m));
}
// Tests EndsWith(s).
TEST(GlobalWideEndsWithTest, MatchesStringWithGivenSuffix) {
const Matcher<const wchar_t*> m1 = EndsWith(L"");
EXPECT_TRUE(m1.Matches(L"Hi"));
EXPECT_TRUE(m1.Matches(L""));
EXPECT_FALSE(m1.Matches(NULL));
const Matcher<const ::wstring&> m2 = EndsWith(::wstring(L"Hi"));
EXPECT_TRUE(m2.Matches(L"Hi"));
EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
EXPECT_TRUE(m2.Matches(L"Super Hi"));
EXPECT_FALSE(m2.Matches(L"i"));
EXPECT_FALSE(m2.Matches(L"Hi "));
}
TEST(GlobalWideEndsWithTest, CanDescribeSelf) {
Matcher<const ::wstring> m = EndsWith(L"Hi");
EXPECT_EQ("ends with L\"Hi\"", Describe(m));
}
#endif // GTEST_HAS_GLOBAL_WSTRING
typedef ::std::tr1::tuple<long, int> Tuple2; // NOLINT
// Tests that Eq() matches a 2-tuple where the first field == the
// second field.
TEST(Eq2Test, MatchesEqualArguments) {
Matcher<const Tuple2&> m = Eq();
EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
}
// Tests that Eq() describes itself properly.
TEST(Eq2Test, CanDescribeSelf) {
Matcher<const Tuple2&> m = Eq();
EXPECT_EQ("are an equal pair", Describe(m));
}
// Tests that Ge() matches a 2-tuple where the first field >= the
// second field.
TEST(Ge2Test, MatchesGreaterThanOrEqualArguments) {
Matcher<const Tuple2&> m = Ge();
EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
}
// Tests that Ge() describes itself properly.
TEST(Ge2Test, CanDescribeSelf) {
Matcher<const Tuple2&> m = Ge();
EXPECT_EQ("are a pair where the first >= the second", Describe(m));
}
// Tests that Gt() matches a 2-tuple where the first field > the
// second field.
TEST(Gt2Test, MatchesGreaterThanArguments) {
Matcher<const Tuple2&> m = Gt();
EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
}
// Tests that Gt() describes itself properly.
TEST(Gt2Test, CanDescribeSelf) {
Matcher<const Tuple2&> m = Gt();
EXPECT_EQ("are a pair where the first > the second", Describe(m));
}
// Tests that Le() matches a 2-tuple where the first field <= the
// second field.
TEST(Le2Test, MatchesLessThanOrEqualArguments) {
Matcher<const Tuple2&> m = Le();
EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
}
// Tests that Le() describes itself properly.
TEST(Le2Test, CanDescribeSelf) {
Matcher<const Tuple2&> m = Le();
EXPECT_EQ("are a pair where the first <= the second", Describe(m));
}
// Tests that Lt() matches a 2-tuple where the first field < the
// second field.
TEST(Lt2Test, MatchesLessThanArguments) {
Matcher<const Tuple2&> m = Lt();
EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
}
// Tests that Lt() describes itself properly.
TEST(Lt2Test, CanDescribeSelf) {
Matcher<const Tuple2&> m = Lt();
EXPECT_EQ("are a pair where the first < the second", Describe(m));
}
// Tests that Ne() matches a 2-tuple where the first field != the
// second field.
TEST(Ne2Test, MatchesUnequalArguments) {
Matcher<const Tuple2&> m = Ne();
EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
}
// Tests that Ne() describes itself properly.
TEST(Ne2Test, CanDescribeSelf) {
Matcher<const Tuple2&> m = Ne();
EXPECT_EQ("are an unequal pair", Describe(m));
}
// Tests that Not(m) matches any value that doesn't match m.
TEST(NotTest, NegatesMatcher) {
Matcher<int> m;
m = Not(Eq(2));
EXPECT_TRUE(m.Matches(3));
EXPECT_FALSE(m.Matches(2));
}
// Tests that Not(m) describes itself properly.
TEST(NotTest, CanDescribeSelf) {
Matcher<int> m = Not(Eq(5));
EXPECT_EQ("isn't equal to 5", Describe(m));
}
// Tests that monomorphic matchers are safely cast by the Not matcher.
TEST(NotTest, NotMatcherSafelyCastsMonomorphicMatchers) {
// greater_than_5 is a monomorphic matcher.
Matcher<int> greater_than_5 = Gt(5);
Matcher<const int&> m = Not(greater_than_5);
Matcher<int&> m2 = Not(greater_than_5);
Matcher<int&> m3 = Not(m);
}
// Helper to allow easy testing of AllOf matchers with num parameters.
void AllOfMatches(int num, const Matcher<int>& m) {
SCOPED_TRACE(Describe(m));
EXPECT_TRUE(m.Matches(0));
for (int i = 1; i <= num; ++i) {
EXPECT_FALSE(m.Matches(i));
}
EXPECT_TRUE(m.Matches(num + 1));
}
// Tests that AllOf(m1, ..., mn) matches any value that matches all of
// the given matchers.
TEST(AllOfTest, MatchesWhenAllMatch) {
Matcher<int> m;
m = AllOf(Le(2), Ge(1));
EXPECT_TRUE(m.Matches(1));
EXPECT_TRUE(m.Matches(2));
EXPECT_FALSE(m.Matches(0));
EXPECT_FALSE(m.Matches(3));
m = AllOf(Gt(0), Ne(1), Ne(2));
EXPECT_TRUE(m.Matches(3));
EXPECT_FALSE(m.Matches(2));
EXPECT_FALSE(m.Matches(1));
EXPECT_FALSE(m.Matches(0));
m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
EXPECT_TRUE(m.Matches(4));
EXPECT_FALSE(m.Matches(3));
EXPECT_FALSE(m.Matches(2));
EXPECT_FALSE(m.Matches(1));
EXPECT_FALSE(m.Matches(0));
m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
EXPECT_TRUE(m.Matches(0));
EXPECT_TRUE(m.Matches(1));
EXPECT_FALSE(m.Matches(3));
// The following tests for varying number of sub-matchers. Due to the way
// the sub-matchers are handled it is enough to test every sub-matcher once
// with sub-matchers using the same matcher type. Varying matcher types are
// checked for above.
AllOfMatches(2, AllOf(Ne(1), Ne(2)));
AllOfMatches(3, AllOf(Ne(1), Ne(2), Ne(3)));
AllOfMatches(4, AllOf(Ne(1), Ne(2), Ne(3), Ne(4)));
AllOfMatches(5, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5)));
AllOfMatches(6, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6)));
AllOfMatches(7, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7)));
AllOfMatches(8, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
Ne(8)));
AllOfMatches(9, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
Ne(8), Ne(9)));
AllOfMatches(10, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
Ne(9), Ne(10)));
}
// Tests that AllOf(m1, ..., mn) describes itself properly.
TEST(AllOfTest, CanDescribeSelf) {
Matcher<int> m;
m = AllOf(Le(2), Ge(1));
EXPECT_EQ("(is <= 2) and (is >= 1)", Describe(m));
m = AllOf(Gt(0), Ne(1), Ne(2));
EXPECT_EQ("(is > 0) and "
"((isn't equal to 1) and "
"(isn't equal to 2))",
Describe(m));
m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
EXPECT_EQ("((is > 0) and "
"(isn't equal to 1)) and "
"((isn't equal to 2) and "
"(isn't equal to 3))",
Describe(m));
m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
EXPECT_EQ("((is >= 0) and "
"(is < 10)) and "
"((isn't equal to 3) and "
"((isn't equal to 5) and "
"(isn't equal to 7)))",
Describe(m));
}
// Tests that AllOf(m1, ..., mn) describes its negation properly.
TEST(AllOfTest, CanDescribeNegation) {
Matcher<int> m;
m = AllOf(Le(2), Ge(1));
EXPECT_EQ("(isn't <= 2) or "
"(isn't >= 1)",
DescribeNegation(m));
m = AllOf(Gt(0), Ne(1), Ne(2));
EXPECT_EQ("(isn't > 0) or "
"((is equal to 1) or "
"(is equal to 2))",
DescribeNegation(m));
m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
EXPECT_EQ("((isn't > 0) or "
"(is equal to 1)) or "
"((is equal to 2) or "
"(is equal to 3))",
DescribeNegation(m));
m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
EXPECT_EQ("((isn't >= 0) or "
"(isn't < 10)) or "
"((is equal to 3) or "
"((is equal to 5) or "
"(is equal to 7)))",
DescribeNegation(m));
}
// Tests that monomorphic matchers are safely cast by the AllOf matcher.
TEST(AllOfTest, AllOfMatcherSafelyCastsMonomorphicMatchers) {
// greater_than_5 and less_than_10 are monomorphic matchers.
Matcher<int> greater_than_5 = Gt(5);
Matcher<int> less_than_10 = Lt(10);
Matcher<const int&> m = AllOf(greater_than_5, less_than_10);
Matcher<int&> m2 = AllOf(greater_than_5, less_than_10);
Matcher<int&> m3 = AllOf(greater_than_5, m2);
// Tests that BothOf works when composing itself.
Matcher<const int&> m4 = AllOf(greater_than_5, less_than_10, less_than_10);
Matcher<int&> m5 = AllOf(greater_than_5, less_than_10, less_than_10);
}
TEST(AllOfTest, ExplainsResult) {
Matcher<int> m;
// Successful match. Both matchers need to explain. The second
// matcher doesn't give an explanation, so only the first matcher's
// explanation is printed.
m = AllOf(GreaterThan(10), Lt(30));
EXPECT_EQ("which is 15 more than 10", Explain(m, 25));
// Successful match. Both matchers need to explain.
m = AllOf(GreaterThan(10), GreaterThan(20));
EXPECT_EQ("which is 20 more than 10, and which is 10 more than 20",
Explain(m, 30));
// Successful match. All matchers need to explain. The second
// matcher doesn't given an explanation.
m = AllOf(GreaterThan(10), Lt(30), GreaterThan(20));
EXPECT_EQ("which is 15 more than 10, and which is 5 more than 20",
Explain(m, 25));
// Successful match. All matchers need to explain.
m = AllOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
EXPECT_EQ("which is 30 more than 10, and which is 20 more than 20, "
"and which is 10 more than 30",
Explain(m, 40));
// Failed match. The first matcher, which failed, needs to
// explain.
m = AllOf(GreaterThan(10), GreaterThan(20));
EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
// Failed match. The second matcher, which failed, needs to
// explain. Since it doesn't given an explanation, nothing is
// printed.
m = AllOf(GreaterThan(10), Lt(30));
EXPECT_EQ("", Explain(m, 40));
// Failed match. The second matcher, which failed, needs to
// explain.
m = AllOf(GreaterThan(10), GreaterThan(20));
EXPECT_EQ("which is 5 less than 20", Explain(m, 15));
}
// Helper to allow easy testing of AnyOf matchers with num parameters.
void AnyOfMatches(int num, const Matcher<int>& m) {
SCOPED_TRACE(Describe(m));
EXPECT_FALSE(m.Matches(0));
for (int i = 1; i <= num; ++i) {
EXPECT_TRUE(m.Matches(i));
}
EXPECT_FALSE(m.Matches(num + 1));
}
// Tests that AnyOf(m1, ..., mn) matches any value that matches at
// least one of the given matchers.
TEST(AnyOfTest, MatchesWhenAnyMatches) {
Matcher<int> m;
m = AnyOf(Le(1), Ge(3));
EXPECT_TRUE(m.Matches(1));
EXPECT_TRUE(m.Matches(4));
EXPECT_FALSE(m.Matches(2));
m = AnyOf(Lt(0), Eq(1), Eq(2));
EXPECT_TRUE(m.Matches(-1));
EXPECT_TRUE(m.Matches(1));
EXPECT_TRUE(m.Matches(2));
EXPECT_FALSE(m.Matches(0));
m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
EXPECT_TRUE(m.Matches(-1));
EXPECT_TRUE(m.Matches(1));
EXPECT_TRUE(m.Matches(2));
EXPECT_TRUE(m.Matches(3));
EXPECT_FALSE(m.Matches(0));
m = AnyOf(Le(0), Gt(10), 3, 5, 7);
EXPECT_TRUE(m.Matches(0));
EXPECT_TRUE(m.Matches(11));
EXPECT_TRUE(m.Matches(3));
EXPECT_FALSE(m.Matches(2));
// The following tests for varying number of sub-matchers. Due to the way
// the sub-matchers are handled it is enough to test every sub-matcher once
// with sub-matchers using the same matcher type. Varying matcher types are
// checked for above.
AnyOfMatches(2, AnyOf(1, 2));
AnyOfMatches(3, AnyOf(1, 2, 3));
AnyOfMatches(4, AnyOf(1, 2, 3, 4));
AnyOfMatches(5, AnyOf(1, 2, 3, 4, 5));
AnyOfMatches(6, AnyOf(1, 2, 3, 4, 5, 6));
AnyOfMatches(7, AnyOf(1, 2, 3, 4, 5, 6, 7));
AnyOfMatches(8, AnyOf(1, 2, 3, 4, 5, 6, 7, 8));
AnyOfMatches(9, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9));
AnyOfMatches(10, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
}
// Tests that AnyOf(m1, ..., mn) describes itself properly.
TEST(AnyOfTest, CanDescribeSelf) {
Matcher<int> m;
m = AnyOf(Le(1), Ge(3));
EXPECT_EQ("(is <= 1) or (is >= 3)",
Describe(m));
m = AnyOf(Lt(0), Eq(1), Eq(2));
EXPECT_EQ("(is < 0) or "
"((is equal to 1) or (is equal to 2))",
Describe(m));
m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
EXPECT_EQ("((is < 0) or "
"(is equal to 1)) or "
"((is equal to 2) or "
"(is equal to 3))",
Describe(m));
m = AnyOf(Le(0), Gt(10), 3, 5, 7);
EXPECT_EQ("((is <= 0) or "
"(is > 10)) or "
"((is equal to 3) or "
"((is equal to 5) or "
"(is equal to 7)))",
Describe(m));
}
// Tests that AnyOf(m1, ..., mn) describes its negation properly.
TEST(AnyOfTest, CanDescribeNegation) {
Matcher<int> m;
m = AnyOf(Le(1), Ge(3));
EXPECT_EQ("(isn't <= 1) and (isn't >= 3)",
DescribeNegation(m));
m = AnyOf(Lt(0), Eq(1), Eq(2));
EXPECT_EQ("(isn't < 0) and "
"((isn't equal to 1) and (isn't equal to 2))",
DescribeNegation(m));
m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
EXPECT_EQ("((isn't < 0) and "
"(isn't equal to 1)) and "
"((isn't equal to 2) and "
"(isn't equal to 3))",
DescribeNegation(m));
m = AnyOf(Le(0), Gt(10), 3, 5, 7);
EXPECT_EQ("((isn't <= 0) and "
"(isn't > 10)) and "
"((isn't equal to 3) and "
"((isn't equal to 5) and "
"(isn't equal to 7)))",
DescribeNegation(m));
}
// Tests that monomorphic matchers are safely cast by the AnyOf matcher.
TEST(AnyOfTest, AnyOfMatcherSafelyCastsMonomorphicMatchers) {
// greater_than_5 and less_than_10 are monomorphic matchers.
Matcher<int> greater_than_5 = Gt(5);
Matcher<int> less_than_10 = Lt(10);
Matcher<const int&> m = AnyOf(greater_than_5, less_than_10);
Matcher<int&> m2 = AnyOf(greater_than_5, less_than_10);
Matcher<int&> m3 = AnyOf(greater_than_5, m2);
// Tests that EitherOf works when composing itself.
Matcher<const int&> m4 = AnyOf(greater_than_5, less_than_10, less_than_10);
Matcher<int&> m5 = AnyOf(greater_than_5, less_than_10, less_than_10);
}
TEST(AnyOfTest, ExplainsResult) {
Matcher<int> m;
// Failed match. Both matchers need to explain. The second
// matcher doesn't give an explanation, so only the first matcher's
// explanation is printed.
m = AnyOf(GreaterThan(10), Lt(0));
EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
// Failed match. Both matchers need to explain.
m = AnyOf(GreaterThan(10), GreaterThan(20));
EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20",
Explain(m, 5));
// Failed match. All matchers need to explain. The second
// matcher doesn't given an explanation.
m = AnyOf(GreaterThan(10), Gt(20), GreaterThan(30));
EXPECT_EQ("which is 5 less than 10, and which is 25 less than 30",
Explain(m, 5));
// Failed match. All matchers need to explain.
m = AnyOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20, "
"and which is 25 less than 30",
Explain(m, 5));
// Successful match. The first matcher, which succeeded, needs to
// explain.
m = AnyOf(GreaterThan(10), GreaterThan(20));
EXPECT_EQ("which is 5 more than 10", Explain(m, 15));
// Successful match. The second matcher, which succeeded, needs to
// explain. Since it doesn't given an explanation, nothing is
// printed.
m = AnyOf(GreaterThan(10), Lt(30));
EXPECT_EQ("", Explain(m, 0));
// Successful match. The second matcher, which succeeded, needs to
// explain.
m = AnyOf(GreaterThan(30), GreaterThan(20));
EXPECT_EQ("which is 5 more than 20", Explain(m, 25));
}
// The following predicate function and predicate functor are for
// testing the Truly(predicate) matcher.
// Returns non-zero if the input is positive. Note that the return
// type of this function is not bool. It's OK as Truly() accepts any
// unary function or functor whose return type can be implicitly
// converted to bool.
int IsPositive(double x) {
return x > 0 ? 1 : 0;
}
// This functor returns true if the input is greater than the given
// number.
class IsGreaterThan {
public:
explicit IsGreaterThan(int threshold) : threshold_(threshold) {}
bool operator()(int n) const { return n > threshold_; }
private:
int threshold_;
};
// For testing Truly().
const int foo = 0;
// This predicate returns true iff the argument references foo and has
// a zero value.
bool ReferencesFooAndIsZero(const int& n) {
return (&n == &foo) && (n == 0);
}
// Tests that Truly(predicate) matches what satisfies the given
// predicate.
TEST(TrulyTest, MatchesWhatSatisfiesThePredicate) {
Matcher<double> m = Truly(IsPositive);
EXPECT_TRUE(m.Matches(2.0));
EXPECT_FALSE(m.Matches(-1.5));
}
// Tests that Truly(predicate_functor) works too.
TEST(TrulyTest, CanBeUsedWithFunctor) {
Matcher<int> m = Truly(IsGreaterThan(5));
EXPECT_TRUE(m.Matches(6));
EXPECT_FALSE(m.Matches(4));
}
// A class that can be implicitly converted to bool.
class ConvertibleToBool {
public:
explicit ConvertibleToBool(int number) : number_(number) {}
operator bool() const { return number_ != 0; }
private:
int number_;
};
ConvertibleToBool IsNotZero(int number) {
return ConvertibleToBool(number);
}
// Tests that the predicate used in Truly() may return a class that's
// implicitly convertible to bool, even when the class has no
// operator!().
TEST(TrulyTest, PredicateCanReturnAClassConvertibleToBool) {
Matcher<int> m = Truly(IsNotZero);
EXPECT_TRUE(m.Matches(1));
EXPECT_FALSE(m.Matches(0));
}
// Tests that Truly(predicate) can describe itself properly.
TEST(TrulyTest, CanDescribeSelf) {
Matcher<double> m = Truly(IsPositive);
EXPECT_EQ("satisfies the given predicate",
Describe(m));
}
// Tests that Truly(predicate) works when the matcher takes its
// argument by reference.
TEST(TrulyTest, WorksForByRefArguments) {
Matcher<const int&> m = Truly(ReferencesFooAndIsZero);
EXPECT_TRUE(m.Matches(foo));
int n = 0;
EXPECT_FALSE(m.Matches(n));
}
// Tests that Matches(m) is a predicate satisfied by whatever that
// matches matcher m.
TEST(MatchesTest, IsSatisfiedByWhatMatchesTheMatcher) {
EXPECT_TRUE(Matches(Ge(0))(1));
EXPECT_FALSE(Matches(Eq('a'))('b'));
}
// Tests that Matches(m) works when the matcher takes its argument by
// reference.
TEST(MatchesTest, WorksOnByRefArguments) {
int m = 0, n = 0;
EXPECT_TRUE(Matches(AllOf(Ref(n), Eq(0)))(n));
EXPECT_FALSE(Matches(Ref(m))(n));
}
// Tests that a Matcher on non-reference type can be used in
// Matches().
TEST(MatchesTest, WorksWithMatcherOnNonRefType) {
Matcher<int> eq5 = Eq(5);
EXPECT_TRUE(Matches(eq5)(5));
EXPECT_FALSE(Matches(eq5)(2));
}
// Tests Value(value, matcher). Since Value() is a simple wrapper for
// Matches(), which has been tested already, we don't spend a lot of
// effort on testing Value().
TEST(ValueTest, WorksWithPolymorphicMatcher) {
EXPECT_TRUE(Value("hi", StartsWith("h")));
EXPECT_FALSE(Value(5, Gt(10)));
}
TEST(ValueTest, WorksWithMonomorphicMatcher) {
const Matcher<int> is_zero = Eq(0);
EXPECT_TRUE(Value(0, is_zero));
EXPECT_FALSE(Value('a', is_zero));
int n = 0;
const Matcher<const int&> ref_n = Ref(n);
EXPECT_TRUE(Value(n, ref_n));
EXPECT_FALSE(Value(1, ref_n));
}
TEST(ExplainMatchResultTest, WorksWithPolymorphicMatcher) {
StringMatchResultListener listener1;
EXPECT_TRUE(ExplainMatchResult(PolymorphicIsEven(), 42, &listener1));
EXPECT_EQ("% 2 == 0", listener1.str());
StringMatchResultListener listener2;
EXPECT_FALSE(ExplainMatchResult(Ge(42), 1.5, &listener2));
EXPECT_EQ("", listener2.str());
}
TEST(ExplainMatchResultTest, WorksWithMonomorphicMatcher) {
const Matcher<int> is_even = PolymorphicIsEven();
StringMatchResultListener listener1;
EXPECT_TRUE(ExplainMatchResult(is_even, 42, &listener1));
EXPECT_EQ("% 2 == 0", listener1.str());
const Matcher<const double&> is_zero = Eq(0);
StringMatchResultListener listener2;
EXPECT_FALSE(ExplainMatchResult(is_zero, 1.5, &listener2));
EXPECT_EQ("", listener2.str());
}
MATCHER_P(Really, inner_matcher, "") {
return ExplainMatchResult(inner_matcher, arg, result_listener);
}
TEST(ExplainMatchResultTest, WorksInsideMATCHER) {
EXPECT_THAT(0, Really(Eq(0)));
}
TEST(AllArgsTest, WorksForTuple) {
EXPECT_THAT(make_tuple(1, 2L), AllArgs(Lt()));
EXPECT_THAT(make_tuple(2L, 1), Not(AllArgs(Lt())));
}
TEST(AllArgsTest, WorksForNonTuple) {
EXPECT_THAT(42, AllArgs(Gt(0)));
EXPECT_THAT('a', Not(AllArgs(Eq('b'))));
}
class AllArgsHelper {
public:
AllArgsHelper() {}
MOCK_METHOD2(Helper, int(char x, int y));
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(AllArgsHelper);
};
TEST(AllArgsTest, WorksInWithClause) {
AllArgsHelper helper;
ON_CALL(helper, Helper(_, _))
.With(AllArgs(Lt()))
.WillByDefault(Return(1));
EXPECT_CALL(helper, Helper(_, _));
EXPECT_CALL(helper, Helper(_, _))
.With(AllArgs(Gt()))
.WillOnce(Return(2));
EXPECT_EQ(1, helper.Helper('\1', 2));
EXPECT_EQ(2, helper.Helper('a', 1));
}
// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
// matches the matcher.
TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) {
ASSERT_THAT(5, Ge(2)) << "This should succeed.";
ASSERT_THAT("Foo", EndsWith("oo"));
EXPECT_THAT(2, AllOf(Le(7), Ge(0))) << "This should succeed too.";
EXPECT_THAT("Hello", StartsWith("Hell"));
}
// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
// doesn't match the matcher.
TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) {
// 'n' must be static as it is used in an EXPECT_FATAL_FAILURE(),
// which cannot reference auto variables.
static unsigned short n; // NOLINT
n = 5;
// VC++ prior to version 8.0 SP1 has a bug where it will not see any
// functions declared in the namespace scope from within nested classes.
// EXPECT/ASSERT_(NON)FATAL_FAILURE macros use nested classes so that all
// namespace-level functions invoked inside them need to be explicitly
// resolved.
EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Gt(10)),
"Value of: n\n"
"Expected: is > 10\n"
" Actual: 5" + OfType("unsigned short"));
n = 0;
EXPECT_NONFATAL_FAILURE(
EXPECT_THAT(n, ::testing::AllOf(::testing::Le(7), ::testing::Ge(5))),
"Value of: n\n"
"Expected: (is <= 7) and (is >= 5)\n"
" Actual: 0" + OfType("unsigned short"));
}
// Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument
// has a reference type.
TEST(MatcherAssertionTest, WorksForByRefArguments) {
// We use a static variable here as EXPECT_FATAL_FAILURE() cannot
// reference auto variables.
static int n;
n = 0;
EXPECT_THAT(n, AllOf(Le(7), Ref(n)));
EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
"Value of: n\n"
"Expected: does not reference the variable @");
// Tests the "Actual" part.
EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
"Actual: 0" + OfType("int") + ", which is located @");
}
#if !GTEST_OS_SYMBIAN
// Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is
// monomorphic.
// ASSERT_THAT("hello", starts_with_he) fails to compile with Nokia's
// Symbian compiler: it tries to compile
// template<T, U> class MatcherCastImpl { ...
// virtual bool MatchAndExplain(T x, ...) const {
// return source_matcher_.MatchAndExplain(static_cast<U>(x), ...);
// with U == string and T == const char*
// With ASSERT_THAT("hello"...) changed to ASSERT_THAT(string("hello") ... )
// the compiler silently crashes with no output.
// If MatcherCastImpl is changed to use U(x) instead of static_cast<U>(x)
// the code compiles but the converted string is bogus.
TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) {
Matcher<const char*> starts_with_he = StartsWith("he");
ASSERT_THAT("hello", starts_with_he);
Matcher<const string&> ends_with_ok = EndsWith("ok");
ASSERT_THAT("book", ends_with_ok);
const string bad = "bad";
EXPECT_NONFATAL_FAILURE(EXPECT_THAT(bad, ends_with_ok),
"Value of: bad\n"
"Expected: ends with \"ok\"\n"
" Actual: \"bad\"");
Matcher<int> is_greater_than_5 = Gt(5);
EXPECT_NONFATAL_FAILURE(EXPECT_THAT(5, is_greater_than_5),
"Value of: 5\n"
"Expected: is > 5\n"
" Actual: 5" + OfType("int"));
}
#endif // !GTEST_OS_SYMBIAN
// Tests floating-point matchers.
template <typename RawType>
class FloatingPointTest : public testing::Test {
protected:
typedef typename testing::internal::FloatingPoint<RawType> Floating;
typedef typename Floating::Bits Bits;
virtual void SetUp() {
const size_t max_ulps = Floating::kMaxUlps;
// The bits that represent 0.0.
const Bits zero_bits = Floating(0).bits();
// Makes some numbers close to 0.0.
close_to_positive_zero_ = Floating::ReinterpretBits(zero_bits + max_ulps/2);
close_to_negative_zero_ = -Floating::ReinterpretBits(
zero_bits + max_ulps - max_ulps/2);
further_from_negative_zero_ = -Floating::ReinterpretBits(
zero_bits + max_ulps + 1 - max_ulps/2);
// The bits that represent 1.0.
const Bits one_bits = Floating(1).bits();
// Makes some numbers close to 1.0.
close_to_one_ = Floating::ReinterpretBits(one_bits + max_ulps);
further_from_one_ = Floating::ReinterpretBits(one_bits + max_ulps + 1);
// +infinity.
infinity_ = Floating::Infinity();
// The bits that represent +infinity.
const Bits infinity_bits = Floating(infinity_).bits();
// Makes some numbers close to infinity.
close_to_infinity_ = Floating::ReinterpretBits(infinity_bits - max_ulps);
further_from_infinity_ = Floating::ReinterpretBits(
infinity_bits - max_ulps - 1);
// Makes some NAN's.
nan1_ = Floating::ReinterpretBits(Floating::kExponentBitMask | 1);
nan2_ = Floating::ReinterpretBits(Floating::kExponentBitMask | 200);
}
void TestSize() {
EXPECT_EQ(sizeof(RawType), sizeof(Bits));
}
// A battery of tests for FloatingEqMatcher::Matches.
// matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
void TestMatches(
testing::internal::FloatingEqMatcher<RawType> (*matcher_maker)(RawType)) {
Matcher<RawType> m1 = matcher_maker(0.0);
EXPECT_TRUE(m1.Matches(-0.0));
EXPECT_TRUE(m1.Matches(close_to_positive_zero_));
EXPECT_TRUE(m1.Matches(close_to_negative_zero_));
EXPECT_FALSE(m1.Matches(1.0));
Matcher<RawType> m2 = matcher_maker(close_to_positive_zero_);
EXPECT_FALSE(m2.Matches(further_from_negative_zero_));
Matcher<RawType> m3 = matcher_maker(1.0);
EXPECT_TRUE(m3.Matches(close_to_one_));
EXPECT_FALSE(m3.Matches(further_from_one_));
// Test commutativity: matcher_maker(0.0).Matches(1.0) was tested above.
EXPECT_FALSE(m3.Matches(0.0));
Matcher<RawType> m4 = matcher_maker(-infinity_);
EXPECT_TRUE(m4.Matches(-close_to_infinity_));
Matcher<RawType> m5 = matcher_maker(infinity_);
EXPECT_TRUE(m5.Matches(close_to_infinity_));
// This is interesting as the representations of infinity_ and nan1_
// are only 1 DLP apart.
EXPECT_FALSE(m5.Matches(nan1_));
// matcher_maker can produce a Matcher<const RawType&>, which is needed in
// some cases.
Matcher<const RawType&> m6 = matcher_maker(0.0);
EXPECT_TRUE(m6.Matches(-0.0));
EXPECT_TRUE(m6.Matches(close_to_positive_zero_));
EXPECT_FALSE(m6.Matches(1.0));
// matcher_maker can produce a Matcher<RawType&>, which is needed in some
// cases.
Matcher<RawType&> m7 = matcher_maker(0.0);
RawType x = 0.0;
EXPECT_TRUE(m7.Matches(x));
x = 0.01f;
EXPECT_FALSE(m7.Matches(x));
}
// Pre-calculated numbers to be used by the tests.
static RawType close_to_positive_zero_;
static RawType close_to_negative_zero_;
static RawType further_from_negative_zero_;
static RawType close_to_one_;
static RawType further_from_one_;
static RawType infinity_;
static RawType close_to_infinity_;
static RawType further_from_infinity_;
static RawType nan1_;
static RawType nan2_;
};
template <typename RawType>
RawType FloatingPointTest<RawType>::close_to_positive_zero_;
template <typename RawType>
RawType FloatingPointTest<RawType>::close_to_negative_zero_;
template <typename RawType>
RawType FloatingPointTest<RawType>::further_from_negative_zero_;
template <typename RawType>
RawType FloatingPointTest<RawType>::close_to_one_;
template <typename RawType>
RawType FloatingPointTest<RawType>::further_from_one_;
template <typename RawType>
RawType FloatingPointTest<RawType>::infinity_;
template <typename RawType>
RawType FloatingPointTest<RawType>::close_to_infinity_;
template <typename RawType>
RawType FloatingPointTest<RawType>::further_from_infinity_;
template <typename RawType>
RawType FloatingPointTest<RawType>::nan1_;
template <typename RawType>
RawType FloatingPointTest<RawType>::nan2_;
// Instantiate FloatingPointTest for testing floats.
typedef FloatingPointTest<float> FloatTest;
TEST_F(FloatTest, FloatEqApproximatelyMatchesFloats) {
TestMatches(&FloatEq);
}
TEST_F(FloatTest, NanSensitiveFloatEqApproximatelyMatchesFloats) {
TestMatches(&NanSensitiveFloatEq);
}
TEST_F(FloatTest, FloatEqCannotMatchNaN) {
// FloatEq never matches NaN.
Matcher<float> m = FloatEq(nan1_);
EXPECT_FALSE(m.Matches(nan1_));
EXPECT_FALSE(m.Matches(nan2_));
EXPECT_FALSE(m.Matches(1.0));
}
TEST_F(FloatTest, NanSensitiveFloatEqCanMatchNaN) {
// NanSensitiveFloatEq will match NaN.
Matcher<float> m = NanSensitiveFloatEq(nan1_);
EXPECT_TRUE(m.Matches(nan1_));
EXPECT_TRUE(m.Matches(nan2_));
EXPECT_FALSE(m.Matches(1.0));
}
TEST_F(FloatTest, FloatEqCanDescribeSelf) {
Matcher<float> m1 = FloatEq(2.0f);
EXPECT_EQ("is approximately 2", Describe(m1));
EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
Matcher<float> m2 = FloatEq(0.5f);
EXPECT_EQ("is approximately 0.5", Describe(m2));
EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
Matcher<float> m3 = FloatEq(nan1_);
EXPECT_EQ("never matches", Describe(m3));
EXPECT_EQ("is anything", DescribeNegation(m3));
}
TEST_F(FloatTest, NanSensitiveFloatEqCanDescribeSelf) {
Matcher<float> m1 = NanSensitiveFloatEq(2.0f);
EXPECT_EQ("is approximately 2", Describe(m1));
EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
Matcher<float> m2 = NanSensitiveFloatEq(0.5f);
EXPECT_EQ("is approximately 0.5", Describe(m2));
EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
Matcher<float> m3 = NanSensitiveFloatEq(nan1_);
EXPECT_EQ("is NaN", Describe(m3));
EXPECT_EQ("isn't NaN", DescribeNegation(m3));
}
// Instantiate FloatingPointTest for testing doubles.
typedef FloatingPointTest<double> DoubleTest;
TEST_F(DoubleTest, DoubleEqApproximatelyMatchesDoubles) {
TestMatches(&DoubleEq);
}
TEST_F(DoubleTest, NanSensitiveDoubleEqApproximatelyMatchesDoubles) {
TestMatches(&NanSensitiveDoubleEq);
}
TEST_F(DoubleTest, DoubleEqCannotMatchNaN) {
// DoubleEq never matches NaN.
Matcher<double> m = DoubleEq(nan1_);
EXPECT_FALSE(m.Matches(nan1_));
EXPECT_FALSE(m.Matches(nan2_));
EXPECT_FALSE(m.Matches(1.0));
}
TEST_F(DoubleTest, NanSensitiveDoubleEqCanMatchNaN) {
// NanSensitiveDoubleEq will match NaN.
Matcher<double> m = NanSensitiveDoubleEq(nan1_);
EXPECT_TRUE(m.Matches(nan1_));
EXPECT_TRUE(m.Matches(nan2_));
EXPECT_FALSE(m.Matches(1.0));
}
TEST_F(DoubleTest, DoubleEqCanDescribeSelf) {
Matcher<double> m1 = DoubleEq(2.0);
EXPECT_EQ("is approximately 2", Describe(m1));
EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
Matcher<double> m2 = DoubleEq(0.5);
EXPECT_EQ("is approximately 0.5", Describe(m2));
EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
Matcher<double> m3 = DoubleEq(nan1_);
EXPECT_EQ("never matches", Describe(m3));
EXPECT_EQ("is anything", DescribeNegation(m3));
}
TEST_F(DoubleTest, NanSensitiveDoubleEqCanDescribeSelf) {
Matcher<double> m1 = NanSensitiveDoubleEq(2.0);
EXPECT_EQ("is approximately 2", Describe(m1));
EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
Matcher<double> m2 = NanSensitiveDoubleEq(0.5);
EXPECT_EQ("is approximately 0.5", Describe(m2));
EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
Matcher<double> m3 = NanSensitiveDoubleEq(nan1_);
EXPECT_EQ("is NaN", Describe(m3));
EXPECT_EQ("isn't NaN", DescribeNegation(m3));
}
TEST(PointeeTest, RawPointer) {
const Matcher<int*> m = Pointee(Ge(0));
int n = 1;
EXPECT_TRUE(m.Matches(&n));
n = -1;
EXPECT_FALSE(m.Matches(&n));
EXPECT_FALSE(m.Matches(NULL));
}
TEST(PointeeTest, RawPointerToConst) {
const Matcher<const double*> m = Pointee(Ge(0));
double x = 1;
EXPECT_TRUE(m.Matches(&x));
x = -1;
EXPECT_FALSE(m.Matches(&x));
EXPECT_FALSE(m.Matches(NULL));
}
TEST(PointeeTest, ReferenceToConstRawPointer) {
const Matcher<int* const &> m = Pointee(Ge(0));
int n = 1;
EXPECT_TRUE(m.Matches(&n));
n = -1;
EXPECT_FALSE(m.Matches(&n));
EXPECT_FALSE(m.Matches(NULL));
}
TEST(PointeeTest, ReferenceToNonConstRawPointer) {
const Matcher<double* &> m = Pointee(Ge(0));
double x = 1.0;
double* p = &x;
EXPECT_TRUE(m.Matches(p));
x = -1;
EXPECT_FALSE(m.Matches(p));
p = NULL;
EXPECT_FALSE(m.Matches(p));
}
// Minimal const-propagating pointer.
template <typename T>
class ConstPropagatingPtr {
public:
typedef T element_type;
ConstPropagatingPtr() : val_() {}
explicit ConstPropagatingPtr(T* t) : val_(t) {}
ConstPropagatingPtr(const ConstPropagatingPtr& other) : val_(other.val_) {}
T* get() { return val_; }
T& operator*() { return *val_; }
// Most smart pointers return non-const T* and T& from the next methods.
const T* get() const { return val_; }
const T& operator*() const { return *val_; }
private:
T* val_;
};
TEST(PointeeTest, WorksWithConstPropagatingPointers) {
const Matcher< ConstPropagatingPtr<int> > m = Pointee(Lt(5));
int three = 3;
const ConstPropagatingPtr<int> co(&three);
ConstPropagatingPtr<int> o(&three);
EXPECT_TRUE(m.Matches(o));
EXPECT_TRUE(m.Matches(co));
*o = 6;
EXPECT_FALSE(m.Matches(o));
EXPECT_FALSE(m.Matches(ConstPropagatingPtr<int>()));
}
TEST(PointeeTest, NeverMatchesNull) {
const Matcher<const char*> m = Pointee(_);
EXPECT_FALSE(m.Matches(NULL));
}
// Tests that we can write Pointee(value) instead of Pointee(Eq(value)).
TEST(PointeeTest, MatchesAgainstAValue) {
const Matcher<int*> m = Pointee(5);
int n = 5;
EXPECT_TRUE(m.Matches(&n));
n = -1;
EXPECT_FALSE(m.Matches(&n));
EXPECT_FALSE(m.Matches(NULL));
}
TEST(PointeeTest, CanDescribeSelf) {
const Matcher<int*> m = Pointee(Gt(3));
EXPECT_EQ("points to a value that is > 3", Describe(m));
EXPECT_EQ("does not point to a value that is > 3",
DescribeNegation(m));
}
TEST(PointeeTest, CanExplainMatchResult) {
const Matcher<const string*> m = Pointee(StartsWith("Hi"));
EXPECT_EQ("", Explain(m, static_cast<const string*>(NULL)));
const Matcher<long*> m2 = Pointee(GreaterThan(1)); // NOLINT
long n = 3; // NOLINT
EXPECT_EQ("which points to 3" + OfType("long") + ", which is 2 more than 1",
Explain(m2, &n));
}
TEST(PointeeTest, AlwaysExplainsPointee) {
const Matcher<int*> m = Pointee(0);
int n = 42;
EXPECT_EQ("which points to 42" + OfType("int"), Explain(m, &n));
}
// An uncopyable class.
class Uncopyable {
public:
explicit Uncopyable(int a_value) : value_(a_value) {}
int value() const { return value_; }
private:
const int value_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(Uncopyable);
};
// Returns true iff x.value() is positive.
bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; }
// A user-defined struct for testing Field().
struct AStruct {
AStruct() : x(0), y(1.0), z(5), p(NULL) {}
AStruct(const AStruct& rhs)
: x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {}
int x; // A non-const field.
const double y; // A const field.
Uncopyable z; // An uncopyable field.
const char* p; // A pointer field.
private:
GTEST_DISALLOW_ASSIGN_(AStruct);
};
// A derived struct for testing Field().
struct DerivedStruct : public AStruct {
char ch;
private:
GTEST_DISALLOW_ASSIGN_(DerivedStruct);
};
// Tests that Field(&Foo::field, ...) works when field is non-const.
TEST(FieldTest, WorksForNonConstField) {
Matcher<AStruct> m = Field(&AStruct::x, Ge(0));
AStruct a;
EXPECT_TRUE(m.Matches(a));
a.x = -1;
EXPECT_FALSE(m.Matches(a));
}
// Tests that Field(&Foo::field, ...) works when field is const.
TEST(FieldTest, WorksForConstField) {
AStruct a;
Matcher<AStruct> m = Field(&AStruct::y, Ge(0.0));
EXPECT_TRUE(m.Matches(a));
m = Field(&AStruct::y, Le(0.0));
EXPECT_FALSE(m.Matches(a));
}
// Tests that Field(&Foo::field, ...) works when field is not copyable.
TEST(FieldTest, WorksForUncopyableField) {
AStruct a;
Matcher<AStruct> m = Field(&AStruct::z, Truly(ValueIsPositive));
EXPECT_TRUE(m.Matches(a));
m = Field(&AStruct::z, Not(Truly(ValueIsPositive)));
EXPECT_FALSE(m.Matches(a));
}
// Tests that Field(&Foo::field, ...) works when field is a pointer.
TEST(FieldTest, WorksForPointerField) {
// Matching against NULL.
Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(NULL));
AStruct a;
EXPECT_TRUE(m.Matches(a));
a.p = "hi";
EXPECT_FALSE(m.Matches(a));
// Matching a pointer that is not NULL.
m = Field(&AStruct::p, StartsWith("hi"));
a.p = "hill";
EXPECT_TRUE(m.Matches(a));
a.p = "hole";
EXPECT_FALSE(m.Matches(a));
}
// Tests that Field() works when the object is passed by reference.
TEST(FieldTest, WorksForByRefArgument) {
Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
AStruct a;
EXPECT_TRUE(m.Matches(a));
a.x = -1;
EXPECT_FALSE(m.Matches(a));
}
// Tests that Field(&Foo::field, ...) works when the argument's type
// is a sub-type of Foo.
TEST(FieldTest, WorksForArgumentOfSubType) {
// Note that the matcher expects DerivedStruct but we say AStruct
// inside Field().
Matcher<const DerivedStruct&> m = Field(&AStruct::x, Ge(0));
DerivedStruct d;
EXPECT_TRUE(m.Matches(d));
d.x = -1;
EXPECT_FALSE(m.Matches(d));
}
// Tests that Field(&Foo::field, m) works when field's type and m's
// argument type are compatible but not the same.
TEST(FieldTest, WorksForCompatibleMatcherType) {
// The field is an int, but the inner matcher expects a signed char.
Matcher<const AStruct&> m = Field(&AStruct::x,
Matcher<signed char>(Ge(0)));
AStruct a;
EXPECT_TRUE(m.Matches(a));
a.x = -1;
EXPECT_FALSE(m.Matches(a));
}
// Tests that Field() can describe itself.
TEST(FieldTest, CanDescribeSelf) {
Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
}
// Tests that Field() can explain the match result.
TEST(FieldTest, CanExplainMatchResult) {
Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
AStruct a;
a.x = 1;
EXPECT_EQ("whose given field is 1" + OfType("int"), Explain(m, a));
m = Field(&AStruct::x, GreaterThan(0));
EXPECT_EQ(
"whose given field is 1" + OfType("int") + ", which is 1 more than 0",
Explain(m, a));
}
// Tests that Field() works when the argument is a pointer to const.
TEST(FieldForPointerTest, WorksForPointerToConst) {
Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
AStruct a;
EXPECT_TRUE(m.Matches(&a));
a.x = -1;
EXPECT_FALSE(m.Matches(&a));
}
// Tests that Field() works when the argument is a pointer to non-const.
TEST(FieldForPointerTest, WorksForPointerToNonConst) {
Matcher<AStruct*> m = Field(&AStruct::x, Ge(0));
AStruct a;
EXPECT_TRUE(m.Matches(&a));
a.x = -1;
EXPECT_FALSE(m.Matches(&a));
}
// Tests that Field() works when the argument is a reference to a const pointer.
TEST(FieldForPointerTest, WorksForReferenceToConstPointer) {
Matcher<AStruct* const&> m = Field(&AStruct::x, Ge(0));
AStruct a;
EXPECT_TRUE(m.Matches(&a));
a.x = -1;
EXPECT_FALSE(m.Matches(&a));
}
// Tests that Field() does not match the NULL pointer.
TEST(FieldForPointerTest, DoesNotMatchNull) {
Matcher<const AStruct*> m = Field(&AStruct::x, _);
EXPECT_FALSE(m.Matches(NULL));
}
// Tests that Field(&Foo::field, ...) works when the argument's type
// is a sub-type of const Foo*.
TEST(FieldForPointerTest, WorksForArgumentOfSubType) {
// Note that the matcher expects DerivedStruct but we say AStruct
// inside Field().
Matcher<DerivedStruct*> m = Field(&AStruct::x, Ge(0));
DerivedStruct d;
EXPECT_TRUE(m.Matches(&d));
d.x = -1;
EXPECT_FALSE(m.Matches(&d));
}
// Tests that Field() can describe itself when used to match a pointer.
TEST(FieldForPointerTest, CanDescribeSelf) {
Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
}
// Tests that Field() can explain the result of matching a pointer.
TEST(FieldForPointerTest, CanExplainMatchResult) {
Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
AStruct a;
a.x = 1;
EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(NULL)));
EXPECT_EQ("which points to an object whose given field is 1" + OfType("int"),
Explain(m, &a));
m = Field(&AStruct::x, GreaterThan(0));
EXPECT_EQ("which points to an object whose given field is 1" + OfType("int") +
", which is 1 more than 0", Explain(m, &a));
}
// A user-defined class for testing Property().
class AClass {
public:
AClass() : n_(0) {}
// A getter that returns a non-reference.
int n() const { return n_; }
void set_n(int new_n) { n_ = new_n; }
// A getter that returns a reference to const.
const string& s() const { return s_; }
void set_s(const string& new_s) { s_ = new_s; }
// A getter that returns a reference to non-const.
double& x() const { return x_; }
private:
int n_;
string s_;
static double x_;
};
double AClass::x_ = 0.0;
// A derived class for testing Property().
class DerivedClass : public AClass {
private:
int k_;
};
// Tests that Property(&Foo::property, ...) works when property()
// returns a non-reference.
TEST(PropertyTest, WorksForNonReferenceProperty) {
Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
AClass a;
a.set_n(1);
EXPECT_TRUE(m.Matches(a));
a.set_n(-1);
EXPECT_FALSE(m.Matches(a));
}
// Tests that Property(&Foo::property, ...) works when property()
// returns a reference to const.
TEST(PropertyTest, WorksForReferenceToConstProperty) {
Matcher<const AClass&> m = Property(&AClass::s, StartsWith("hi"));
AClass a;
a.set_s("hill");
EXPECT_TRUE(m.Matches(a));
a.set_s("hole");
EXPECT_FALSE(m.Matches(a));
}
// Tests that Property(&Foo::property, ...) works when property()
// returns a reference to non-const.
TEST(PropertyTest, WorksForReferenceToNonConstProperty) {
double x = 0.0;
AClass a;
Matcher<const AClass&> m = Property(&AClass::x, Ref(x));
EXPECT_FALSE(m.Matches(a));
m = Property(&AClass::x, Not(Ref(x)));
EXPECT_TRUE(m.Matches(a));
}
// Tests that Property(&Foo::property, ...) works when the argument is
// passed by value.
TEST(PropertyTest, WorksForByValueArgument) {
Matcher<AClass> m = Property(&AClass::s, StartsWith("hi"));
AClass a;
a.set_s("hill");
EXPECT_TRUE(m.Matches(a));
a.set_s("hole");
EXPECT_FALSE(m.Matches(a));
}
// Tests that Property(&Foo::property, ...) works when the argument's
// type is a sub-type of Foo.
TEST(PropertyTest, WorksForArgumentOfSubType) {
// The matcher expects a DerivedClass, but inside the Property() we
// say AClass.
Matcher<const DerivedClass&> m = Property(&AClass::n, Ge(0));
DerivedClass d;
d.set_n(1);
EXPECT_TRUE(m.Matches(d));
d.set_n(-1);
EXPECT_FALSE(m.Matches(d));
}
// Tests that Property(&Foo::property, m) works when property()'s type
// and m's argument type are compatible but different.
TEST(PropertyTest, WorksForCompatibleMatcherType) {
// n() returns an int but the inner matcher expects a signed char.
Matcher<const AClass&> m = Property(&AClass::n,
Matcher<signed char>(Ge(0)));
AClass a;
EXPECT_TRUE(m.Matches(a));
a.set_n(-1);
EXPECT_FALSE(m.Matches(a));
}
// Tests that Property() can describe itself.
TEST(PropertyTest, CanDescribeSelf) {
Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
EXPECT_EQ("is an object whose given property isn't >= 0",
DescribeNegation(m));
}
// Tests that Property() can explain the match result.
TEST(PropertyTest, CanExplainMatchResult) {
Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
AClass a;
a.set_n(1);
EXPECT_EQ("whose given property is 1" + OfType("int"), Explain(m, a));
m = Property(&AClass::n, GreaterThan(0));
EXPECT_EQ(
"whose given property is 1" + OfType("int") + ", which is 1 more than 0",
Explain(m, a));
}
// Tests that Property() works when the argument is a pointer to const.
TEST(PropertyForPointerTest, WorksForPointerToConst) {
Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
AClass a;
a.set_n(1);
EXPECT_TRUE(m.Matches(&a));
a.set_n(-1);
EXPECT_FALSE(m.Matches(&a));
}
// Tests that Property() works when the argument is a pointer to non-const.
TEST(PropertyForPointerTest, WorksForPointerToNonConst) {
Matcher<AClass*> m = Property(&AClass::s, StartsWith("hi"));
AClass a;
a.set_s("hill");
EXPECT_TRUE(m.Matches(&a));
a.set_s("hole");
EXPECT_FALSE(m.Matches(&a));
}
// Tests that Property() works when the argument is a reference to a
// const pointer.
TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) {
Matcher<AClass* const&> m = Property(&AClass::s, StartsWith("hi"));
AClass a;
a.set_s("hill");
EXPECT_TRUE(m.Matches(&a));
a.set_s("hole");
EXPECT_FALSE(m.Matches(&a));
}
// Tests that Property() does not match the NULL pointer.
TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) {
Matcher<const AClass*> m = Property(&AClass::x, _);
EXPECT_FALSE(m.Matches(NULL));
}
// Tests that Property(&Foo::property, ...) works when the argument's
// type is a sub-type of const Foo*.
TEST(PropertyForPointerTest, WorksForArgumentOfSubType) {
// The matcher expects a DerivedClass, but inside the Property() we
// say AClass.
Matcher<const DerivedClass*> m = Property(&AClass::n, Ge(0));
DerivedClass d;
d.set_n(1);
EXPECT_TRUE(m.Matches(&d));
d.set_n(-1);
EXPECT_FALSE(m.Matches(&d));
}
// Tests that Property() can describe itself when used to match a pointer.
TEST(PropertyForPointerTest, CanDescribeSelf) {
Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
EXPECT_EQ("is an object whose given property isn't >= 0",
DescribeNegation(m));
}
// Tests that Property() can explain the result of matching a pointer.
TEST(PropertyForPointerTest, CanExplainMatchResult) {
Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
AClass a;
a.set_n(1);
EXPECT_EQ("", Explain(m, static_cast<const AClass*>(NULL)));
EXPECT_EQ(
"which points to an object whose given property is 1" + OfType("int"),
Explain(m, &a));
m = Property(&AClass::n, GreaterThan(0));
EXPECT_EQ("which points to an object whose given property is 1" +
OfType("int") + ", which is 1 more than 0",
Explain(m, &a));
}
// Tests ResultOf.
// Tests that ResultOf(f, ...) compiles and works as expected when f is a
// function pointer.
string IntToStringFunction(int input) { return input == 1 ? "foo" : "bar"; }
TEST(ResultOfTest, WorksForFunctionPointers) {
Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(string("foo")));
EXPECT_TRUE(matcher.Matches(1));
EXPECT_FALSE(matcher.Matches(2));
}
// Tests that ResultOf() can describe itself.
TEST(ResultOfTest, CanDescribeItself) {
Matcher<int> matcher = ResultOf(&IntToStringFunction, StrEq("foo"));
EXPECT_EQ("is mapped by the given callable to a value that "
"is equal to \"foo\"", Describe(matcher));
EXPECT_EQ("is mapped by the given callable to a value that "
"isn't equal to \"foo\"", DescribeNegation(matcher));
}
// Tests that ResultOf() can explain the match result.
int IntFunction(int input) { return input == 42 ? 80 : 90; }
TEST(ResultOfTest, CanExplainMatchResult) {
Matcher<int> matcher = ResultOf(&IntFunction, Ge(85));
EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int"),
Explain(matcher, 36));
matcher = ResultOf(&IntFunction, GreaterThan(85));
EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int") +
", which is 5 more than 85", Explain(matcher, 36));
}
// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
// returns a non-reference.
TEST(ResultOfTest, WorksForNonReferenceResults) {
Matcher<int> matcher = ResultOf(&IntFunction, Eq(80));
EXPECT_TRUE(matcher.Matches(42));
EXPECT_FALSE(matcher.Matches(36));
}
// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
// returns a reference to non-const.
double& DoubleFunction(double& input) { return input; } // NOLINT
Uncopyable& RefUncopyableFunction(Uncopyable& obj) { // NOLINT
return obj;
}
TEST(ResultOfTest, WorksForReferenceToNonConstResults) {
double x = 3.14;
double x2 = x;
Matcher<double&> matcher = ResultOf(&DoubleFunction, Ref(x));
EXPECT_TRUE(matcher.Matches(x));
EXPECT_FALSE(matcher.Matches(x2));
// Test that ResultOf works with uncopyable objects
Uncopyable obj(0);
Uncopyable obj2(0);
Matcher<Uncopyable&> matcher2 =
ResultOf(&RefUncopyableFunction, Ref(obj));
EXPECT_TRUE(matcher2.Matches(obj));
EXPECT_FALSE(matcher2.Matches(obj2));
}
// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
// returns a reference to const.
const string& StringFunction(const string& input) { return input; }
TEST(ResultOfTest, WorksForReferenceToConstResults) {
string s = "foo";
string s2 = s;
Matcher<const string&> matcher = ResultOf(&StringFunction, Ref(s));
EXPECT_TRUE(matcher.Matches(s));
EXPECT_FALSE(matcher.Matches(s2));
}
// Tests that ResultOf(f, m) works when f(x) and m's
// argument types are compatible but different.
TEST(ResultOfTest, WorksForCompatibleMatcherTypes) {
// IntFunction() returns int but the inner matcher expects a signed char.
Matcher<int> matcher = ResultOf(IntFunction, Matcher<signed char>(Ge(85)));
EXPECT_TRUE(matcher.Matches(36));
EXPECT_FALSE(matcher.Matches(42));
}
// Tests that the program aborts when ResultOf is passed
// a NULL function pointer.
TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) {
EXPECT_DEATH_IF_SUPPORTED(
ResultOf(static_cast<string(*)(int dummy)>(NULL), Eq(string("foo"))),
"NULL function pointer is passed into ResultOf\\(\\)\\.");
}
// Tests that ResultOf(f, ...) compiles and works as expected when f is a
// function reference.
TEST(ResultOfTest, WorksForFunctionReferences) {
Matcher<int> matcher = ResultOf(IntToStringFunction, StrEq("foo"));
EXPECT_TRUE(matcher.Matches(1));
EXPECT_FALSE(matcher.Matches(2));
}
// Tests that ResultOf(f, ...) compiles and works as expected when f is a
// function object.
struct Functor : public ::std::unary_function<int, string> {
result_type operator()(argument_type input) const {
return IntToStringFunction(input);
}
};
TEST(ResultOfTest, WorksForFunctors) {
Matcher<int> matcher = ResultOf(Functor(), Eq(string("foo")));
EXPECT_TRUE(matcher.Matches(1));
EXPECT_FALSE(matcher.Matches(2));
}
// Tests that ResultOf(f, ...) compiles and works as expected when f is a
// functor with more then one operator() defined. ResultOf() must work
// for each defined operator().
struct PolymorphicFunctor {
typedef int result_type;
int operator()(int n) { return n; }
int operator()(const char* s) { return static_cast<int>(strlen(s)); }
};
TEST(ResultOfTest, WorksForPolymorphicFunctors) {
Matcher<int> matcher_int = ResultOf(PolymorphicFunctor(), Ge(5));
EXPECT_TRUE(matcher_int.Matches(10));
EXPECT_FALSE(matcher_int.Matches(2));
Matcher<const char*> matcher_string = ResultOf(PolymorphicFunctor(), Ge(5));
EXPECT_TRUE(matcher_string.Matches("long string"));
EXPECT_FALSE(matcher_string.Matches("shrt"));
}
const int* ReferencingFunction(const int& n) { return &n; }
struct ReferencingFunctor {
typedef const int* result_type;
result_type operator()(const int& n) { return &n; }
};
TEST(ResultOfTest, WorksForReferencingCallables) {
const int n = 1;
const int n2 = 1;
Matcher<const int&> matcher2 = ResultOf(ReferencingFunction, Eq(&n));
EXPECT_TRUE(matcher2.Matches(n));
EXPECT_FALSE(matcher2.Matches(n2));
Matcher<const int&> matcher3 = ResultOf(ReferencingFunctor(), Eq(&n));
EXPECT_TRUE(matcher3.Matches(n));
EXPECT_FALSE(matcher3.Matches(n2));
}
class DivisibleByImpl {
public:
explicit DivisibleByImpl(int a_divider) : divider_(a_divider) {}
// For testing using ExplainMatchResultTo() with polymorphic matchers.
template <typename T>
bool MatchAndExplain(const T& n, MatchResultListener* listener) const {
*listener << "which is " << (n % divider_) << " modulo "
<< divider_;
return (n % divider_) == 0;
}
void DescribeTo(ostream* os) const {
*os << "is divisible by " << divider_;
}
void DescribeNegationTo(ostream* os) const {
*os << "is not divisible by " << divider_;
}
void set_divider(int a_divider) { divider_ = a_divider; }
int divider() const { return divider_; }
private:
int divider_;
};
PolymorphicMatcher<DivisibleByImpl> DivisibleBy(int n) {
return MakePolymorphicMatcher(DivisibleByImpl(n));
}
// Tests that when AllOf() fails, only the first failing matcher is
// asked to explain why.
TEST(ExplainMatchResultTest, AllOf_False_False) {
const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
EXPECT_EQ("which is 1 modulo 4", Explain(m, 5));
}
// Tests that when AllOf() fails, only the first failing matcher is
// asked to explain why.
TEST(ExplainMatchResultTest, AllOf_False_True) {
const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
EXPECT_EQ("which is 2 modulo 4", Explain(m, 6));
}
// Tests that when AllOf() fails, only the first failing matcher is
// asked to explain why.
TEST(ExplainMatchResultTest, AllOf_True_False) {
const Matcher<int> m = AllOf(Ge(1), DivisibleBy(3));
EXPECT_EQ("which is 2 modulo 3", Explain(m, 5));
}
// Tests that when AllOf() succeeds, all matchers are asked to explain
// why.
TEST(ExplainMatchResultTest, AllOf_True_True) {
const Matcher<int> m = AllOf(DivisibleBy(2), DivisibleBy(3));
EXPECT_EQ("which is 0 modulo 2, and which is 0 modulo 3", Explain(m, 6));
}
TEST(ExplainMatchResultTest, AllOf_True_True_2) {
const Matcher<int> m = AllOf(Ge(2), Le(3));
EXPECT_EQ("", Explain(m, 2));
}
TEST(ExplainmatcherResultTest, MonomorphicMatcher) {
const Matcher<int> m = GreaterThan(5);
EXPECT_EQ("which is 1 more than 5", Explain(m, 6));
}
// The following two tests verify that values without a public copy
// ctor can be used as arguments to matchers like Eq(), Ge(), and etc
// with the help of ByRef().
class NotCopyable {
public:
explicit NotCopyable(int a_value) : value_(a_value) {}
int value() const { return value_; }
bool operator==(const NotCopyable& rhs) const {
return value() == rhs.value();
}
bool operator>=(const NotCopyable& rhs) const {
return value() >= rhs.value();
}
private:
int value_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(NotCopyable);
};
TEST(ByRefTest, AllowsNotCopyableConstValueInMatchers) {
const NotCopyable const_value1(1);
const Matcher<const NotCopyable&> m = Eq(ByRef(const_value1));
const NotCopyable n1(1), n2(2);
EXPECT_TRUE(m.Matches(n1));
EXPECT_FALSE(m.Matches(n2));
}
TEST(ByRefTest, AllowsNotCopyableValueInMatchers) {
NotCopyable value2(2);
const Matcher<NotCopyable&> m = Ge(ByRef(value2));
NotCopyable n1(1), n2(2);
EXPECT_FALSE(m.Matches(n1));
EXPECT_TRUE(m.Matches(n2));
}
TEST(IsEmptyTest, ImplementsIsEmpty) {
vector<int> container;
EXPECT_THAT(container, IsEmpty());
container.push_back(0);
EXPECT_THAT(container, Not(IsEmpty()));
container.push_back(1);
EXPECT_THAT(container, Not(IsEmpty()));
}
TEST(IsEmptyTest, WorksWithString) {
string text;
EXPECT_THAT(text, IsEmpty());
text = "foo";
EXPECT_THAT(text, Not(IsEmpty()));
text = string("\0", 1);
EXPECT_THAT(text, Not(IsEmpty()));
}
TEST(IsEmptyTest, CanDescribeSelf) {
Matcher<vector<int> > m = IsEmpty();
EXPECT_EQ("is empty", Describe(m));
EXPECT_EQ("isn't empty", DescribeNegation(m));
}
TEST(IsEmptyTest, ExplainsResult) {
Matcher<vector<int> > m = IsEmpty();
vector<int> container;
EXPECT_EQ("", Explain(m, container));
container.push_back(0);
EXPECT_EQ("whose size is 1", Explain(m, container));
}
TEST(SizeIsTest, ImplementsSizeIs) {
vector<int> container;
EXPECT_THAT(container, SizeIs(0));
EXPECT_THAT(container, Not(SizeIs(1)));
container.push_back(0);
EXPECT_THAT(container, Not(SizeIs(0)));
EXPECT_THAT(container, SizeIs(1));
container.push_back(0);
EXPECT_THAT(container, Not(SizeIs(0)));
EXPECT_THAT(container, SizeIs(2));
}
TEST(SizeIsTest, WorksWithMap) {
map<string, int> container;
EXPECT_THAT(container, SizeIs(0));
EXPECT_THAT(container, Not(SizeIs(1)));
container.insert(make_pair("foo", 1));
EXPECT_THAT(container, Not(SizeIs(0)));
EXPECT_THAT(container, SizeIs(1));
container.insert(make_pair("bar", 2));
EXPECT_THAT(container, Not(SizeIs(0)));
EXPECT_THAT(container, SizeIs(2));
}
TEST(SizeIsTest, WorksWithReferences) {
vector<int> container;
Matcher<const vector<int>&> m = SizeIs(1);
EXPECT_THAT(container, Not(m));
container.push_back(0);
EXPECT_THAT(container, m);
}
TEST(SizeIsTest, CanDescribeSelf) {
Matcher<vector<int> > m = SizeIs(2);
EXPECT_EQ("size is equal to 2", Describe(m));
EXPECT_EQ("size isn't equal to 2", DescribeNegation(m));
}
TEST(SizeIsTest, ExplainsResult) {
Matcher<vector<int> > m1 = SizeIs(2);
Matcher<vector<int> > m2 = SizeIs(Lt(2u));
Matcher<vector<int> > m3 = SizeIs(AnyOf(0, 3));
Matcher<vector<int> > m4 = SizeIs(GreaterThan(1));
vector<int> container;
EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container));
EXPECT_EQ("whose size 0 matches", Explain(m2, container));
EXPECT_EQ("whose size 0 matches", Explain(m3, container));
EXPECT_EQ("whose size 0 doesn't match, which is 1 less than 1",
Explain(m4, container));
container.push_back(0);
container.push_back(0);
EXPECT_EQ("whose size 2 matches", Explain(m1, container));
EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container));
EXPECT_EQ("whose size 2 doesn't match", Explain(m3, container));
EXPECT_EQ("whose size 2 matches, which is 1 more than 1",
Explain(m4, container));
}
#if GTEST_HAS_TYPED_TEST
// Tests ContainerEq with different container types, and
// different element types.
template <typename T>
class ContainerEqTest : public testing::Test {};
typedef testing::Types<
set<int>,
vector<size_t>,
multiset<size_t>,
list<int> >
ContainerEqTestTypes;
TYPED_TEST_CASE(ContainerEqTest, ContainerEqTestTypes);
// Tests that the filled container is equal to itself.
TYPED_TEST(ContainerEqTest, EqualsSelf) {
static const int vals[] = {1, 1, 2, 3, 5, 8};
TypeParam my_set(vals, vals + 6);
const Matcher<TypeParam> m = ContainerEq(my_set);
EXPECT_TRUE(m.Matches(my_set));
EXPECT_EQ("", Explain(m, my_set));
}
// Tests that missing values are reported.
TYPED_TEST(ContainerEqTest, ValueMissing) {
static const int vals[] = {1, 1, 2, 3, 5, 8};
static const int test_vals[] = {2, 1, 8, 5};
TypeParam my_set(vals, vals + 6);
TypeParam test_set(test_vals, test_vals + 4);
const Matcher<TypeParam> m = ContainerEq(my_set);
EXPECT_FALSE(m.Matches(test_set));
EXPECT_EQ("which doesn't have these expected elements: 3",
Explain(m, test_set));
}
// Tests that added values are reported.
TYPED_TEST(ContainerEqTest, ValueAdded) {
static const int vals[] = {1, 1, 2, 3, 5, 8};
static const int test_vals[] = {1, 2, 3, 5, 8, 46};
TypeParam my_set(vals, vals + 6);
TypeParam test_set(test_vals, test_vals + 6);
const Matcher<const TypeParam&> m = ContainerEq(my_set);
EXPECT_FALSE(m.Matches(test_set));
EXPECT_EQ("which has these unexpected elements: 46", Explain(m, test_set));
}
// Tests that added and missing values are reported together.
TYPED_TEST(ContainerEqTest, ValueAddedAndRemoved) {
static const int vals[] = {1, 1, 2, 3, 5, 8};
static const int test_vals[] = {1, 2, 3, 8, 46};
TypeParam my_set(vals, vals + 6);
TypeParam test_set(test_vals, test_vals + 5);
const Matcher<TypeParam> m = ContainerEq(my_set);
EXPECT_FALSE(m.Matches(test_set));
EXPECT_EQ("which has these unexpected elements: 46,\n"
"and doesn't have these expected elements: 5",
Explain(m, test_set));
}
// Tests duplicated value -- expect no explanation.
TYPED_TEST(ContainerEqTest, DuplicateDifference) {
static const int vals[] = {1, 1, 2, 3, 5, 8};
static const int test_vals[] = {1, 2, 3, 5, 8};
TypeParam my_set(vals, vals + 6);
TypeParam test_set(test_vals, test_vals + 5);
const Matcher<const TypeParam&> m = ContainerEq(my_set);
// Depending on the container, match may be true or false
// But in any case there should be no explanation.
EXPECT_EQ("", Explain(m, test_set));
}
#endif // GTEST_HAS_TYPED_TEST
// Tests that mutliple missing values are reported.
// Using just vector here, so order is predicatble.
TEST(ContainerEqExtraTest, MultipleValuesMissing) {
static const int vals[] = {1, 1, 2, 3, 5, 8};
static const int test_vals[] = {2, 1, 5};
vector<int> my_set(vals, vals + 6);
vector<int> test_set(test_vals, test_vals + 3);
const Matcher<vector<int> > m = ContainerEq(my_set);
EXPECT_FALSE(m.Matches(test_set));
EXPECT_EQ("which doesn't have these expected elements: 3, 8",
Explain(m, test_set));
}
// Tests that added values are reported.
// Using just vector here, so order is predicatble.
TEST(ContainerEqExtraTest, MultipleValuesAdded) {
static const int vals[] = {1, 1, 2, 3, 5, 8};
static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46};
list<size_t> my_set(vals, vals + 6);
list<size_t> test_set(test_vals, test_vals + 7);
const Matcher<const list<size_t>&> m = ContainerEq(my_set);
EXPECT_FALSE(m.Matches(test_set));
EXPECT_EQ("which has these unexpected elements: 92, 46",
Explain(m, test_set));
}
// Tests that added and missing values are reported together.
TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) {
static const int vals[] = {1, 1, 2, 3, 5, 8};
static const int test_vals[] = {1, 2, 3, 92, 46};
list<size_t> my_set(vals, vals + 6);
list<size_t> test_set(test_vals, test_vals + 5);
const Matcher<const list<size_t> > m = ContainerEq(my_set);
EXPECT_FALSE(m.Matches(test_set));
EXPECT_EQ("which has these unexpected elements: 92, 46,\n"
"and doesn't have these expected elements: 5, 8",
Explain(m, test_set));
}
// Tests to see that duplicate elements are detected,
// but (as above) not reported in the explanation.
TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) {
static const int vals[] = {1, 1, 2, 3, 5, 8};
static const int test_vals[] = {1, 2, 3, 5, 8};
vector<int> my_set(vals, vals + 6);
vector<int> test_set(test_vals, test_vals + 5);
const Matcher<vector<int> > m = ContainerEq(my_set);
EXPECT_TRUE(m.Matches(my_set));
EXPECT_FALSE(m.Matches(test_set));
// There is nothing to report when both sets contain all the same values.
EXPECT_EQ("", Explain(m, test_set));
}
// Tests that ContainerEq works for non-trivial associative containers,
// like maps.
TEST(ContainerEqExtraTest, WorksForMaps) {
map<int, std::string> my_map;
my_map[0] = "a";
my_map[1] = "b";
map<int, std::string> test_map;
test_map[0] = "aa";
test_map[1] = "b";
const Matcher<const map<int, std::string>&> m = ContainerEq(my_map);
EXPECT_TRUE(m.Matches(my_map));
EXPECT_FALSE(m.Matches(test_map));
EXPECT_EQ("which has these unexpected elements: (0, \"aa\"),\n"
"and doesn't have these expected elements: (0, \"a\")",
Explain(m, test_map));
}
TEST(ContainerEqExtraTest, WorksForNativeArray) {
int a1[] = { 1, 2, 3 };
int a2[] = { 1, 2, 3 };
int b[] = { 1, 2, 4 };
EXPECT_THAT(a1, ContainerEq(a2));
EXPECT_THAT(a1, Not(ContainerEq(b)));
}
TEST(ContainerEqExtraTest, WorksForTwoDimensionalNativeArray) {
const char a1[][3] = { "hi", "lo" };
const char a2[][3] = { "hi", "lo" };
const char b[][3] = { "lo", "hi" };
// Tests using ContainerEq() in the first dimension.
EXPECT_THAT(a1, ContainerEq(a2));
EXPECT_THAT(a1, Not(ContainerEq(b)));
// Tests using ContainerEq() in the second dimension.
EXPECT_THAT(a1, ElementsAre(ContainerEq(a2[0]), ContainerEq(a2[1])));
EXPECT_THAT(a1, ElementsAre(Not(ContainerEq(b[0])), ContainerEq(a2[1])));
}
TEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) {
const int a1[] = { 1, 2, 3 };
const int a2[] = { 1, 2, 3 };
const int b[] = { 1, 2, 3, 4 };
const int* const p1 = a1;
EXPECT_THAT(make_tuple(p1, 3), ContainerEq(a2));
EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(b)));
const int c[] = { 1, 3, 2 };
EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(c)));
}
TEST(ContainerEqExtraTest, CopiesNativeArrayParameter) {
std::string a1[][3] = {
{ "hi", "hello", "ciao" },
{ "bye", "see you", "ciao" }
};
std::string a2[][3] = {
{ "hi", "hello", "ciao" },
{ "bye", "see you", "ciao" }
};
const Matcher<const std::string(&)[2][3]> m = ContainerEq(a2);
EXPECT_THAT(a1, m);
a2[0][0] = "ha";
EXPECT_THAT(a1, m);
}
TEST(WhenSortedByTest, WorksForEmptyContainer) {
const vector<int> numbers;
EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre()));
EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1))));
}
TEST(WhenSortedByTest, WorksForNonEmptyContainer) {
vector<unsigned> numbers;
numbers.push_back(3);
numbers.push_back(1);
numbers.push_back(2);
numbers.push_back(2);
EXPECT_THAT(numbers, WhenSortedBy(greater<unsigned>(),
ElementsAre(3, 2, 2, 1)));
EXPECT_THAT(numbers, Not(WhenSortedBy(greater<unsigned>(),
ElementsAre(1, 2, 2, 3))));
}
TEST(WhenSortedByTest, WorksForNonVectorContainer) {
list<string> words;
words.push_back("say");
words.push_back("hello");
words.push_back("world");
EXPECT_THAT(words, WhenSortedBy(less<string>(),
ElementsAre("hello", "say", "world")));
EXPECT_THAT(words, Not(WhenSortedBy(less<string>(),
ElementsAre("say", "hello", "world"))));
}
TEST(WhenSortedByTest, WorksForNativeArray) {
const int numbers[] = { 1, 3, 2, 4 };
const int sorted_numbers[] = { 1, 2, 3, 4 };
EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre(1, 2, 3, 4)));
EXPECT_THAT(numbers, WhenSortedBy(less<int>(),
ElementsAreArray(sorted_numbers)));
EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1, 3, 2, 4))));
}
TEST(WhenSortedByTest, CanDescribeSelf) {
const Matcher<vector<int> > m = WhenSortedBy(less<int>(), ElementsAre(1, 2));
EXPECT_EQ("(when sorted) has 2 elements where\n"
"element #0 is equal to 1,\n"
"element #1 is equal to 2",
Describe(m));
EXPECT_EQ("(when sorted) doesn't have 2 elements, or\n"
"element #0 isn't equal to 1, or\n"
"element #1 isn't equal to 2",
DescribeNegation(m));
}
TEST(WhenSortedByTest, ExplainsMatchResult) {
const int a[] = { 2, 1 };
EXPECT_EQ("which is { 1, 2 } when sorted, whose element #0 doesn't match",
Explain(WhenSortedBy(less<int>(), ElementsAre(2, 3)), a));
EXPECT_EQ("which is { 1, 2 } when sorted",
Explain(WhenSortedBy(less<int>(), ElementsAre(1, 2)), a));
}
// WhenSorted() is a simple wrapper on WhenSortedBy(). Hence we don't
// need to test it as exhaustively as we test the latter.
TEST(WhenSortedTest, WorksForEmptyContainer) {
const vector<int> numbers;
EXPECT_THAT(numbers, WhenSorted(ElementsAre()));
EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1))));
}
TEST(WhenSortedTest, WorksForNonEmptyContainer) {
list<string> words;
words.push_back("3");
words.push_back("1");
words.push_back("2");
words.push_back("2");
EXPECT_THAT(words, WhenSorted(ElementsAre("1", "2", "2", "3")));
EXPECT_THAT(words, Not(WhenSorted(ElementsAre("3", "1", "2", "2"))));
}
TEST(WhenSortedTest, WorksForMapTypes) {
map<string, int> word_counts;
word_counts["and"] = 1;
word_counts["the"] = 1;
word_counts["buffalo"] = 2;
EXPECT_THAT(word_counts, WhenSorted(ElementsAre(
Pair("and", 1), Pair("buffalo", 2), Pair("the", 1))));
EXPECT_THAT(word_counts, Not(WhenSorted(ElementsAre(
Pair("and", 1), Pair("the", 1), Pair("buffalo", 2)))));
}
TEST(WhenSortedTest, WorksForMultiMapTypes) {
multimap<int, int> ifib;
ifib.insert(make_pair(8, 6));
ifib.insert(make_pair(2, 3));
ifib.insert(make_pair(1, 1));
ifib.insert(make_pair(3, 4));
ifib.insert(make_pair(1, 2));
ifib.insert(make_pair(5, 5));
EXPECT_THAT(ifib, WhenSorted(ElementsAre(Pair(1, 1),
Pair(1, 2),
Pair(2, 3),
Pair(3, 4),
Pair(5, 5),
Pair(8, 6))));
EXPECT_THAT(ifib, Not(WhenSorted(ElementsAre(Pair(8, 6),
Pair(2, 3),
Pair(1, 1),
Pair(3, 4),
Pair(1, 2),
Pair(5, 5)))));
}
TEST(WhenSortedTest, WorksForPolymorphicMatcher) {
std::deque<int> d;
d.push_back(2);
d.push_back(1);
EXPECT_THAT(d, WhenSorted(ElementsAre(1, 2)));
EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1))));
}
TEST(WhenSortedTest, WorksForVectorConstRefMatcher) {
std::deque<int> d;
d.push_back(2);
d.push_back(1);
Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2);
EXPECT_THAT(d, WhenSorted(vector_match));
Matcher<const std::vector<int>&> not_vector_match = ElementsAre(2, 1);
EXPECT_THAT(d, Not(WhenSorted(not_vector_match)));
}
// Deliberately bare pseudo-container.
// Offers only begin() and end() accessors, yielding InputIterator.
template <typename T>
class Streamlike {
private:
class ConstIter;
public:
typedef ConstIter const_iterator;
typedef T value_type;
template <typename InIter>
Streamlike(InIter first, InIter last) : remainder_(first, last) {}
const_iterator begin() const {
return const_iterator(this, remainder_.begin());
}
const_iterator end() const {
return const_iterator(this, remainder_.end());
}
private:
class ConstIter : public std::iterator<std::input_iterator_tag,
value_type,
ptrdiff_t,
const value_type&,
const value_type*> {
public:
ConstIter(const Streamlike* s,
typename std::list<value_type>::iterator pos)
: s_(s), pos_(pos) {}
const value_type& operator*() const { return *pos_; }
const value_type* operator->() const { return &*pos_; }
ConstIter& operator++() {
s_->remainder_.erase(pos_++);
return *this;
}
// *iter++ is required to work (see std::istreambuf_iterator).
// (void)iter++ is also required to work.
class PostIncrProxy {
public:
explicit PostIncrProxy(const value_type& value) : value_(value) {}
value_type operator*() const { return value_; }
private:
value_type value_;
};
PostIncrProxy operator++(int) {
PostIncrProxy proxy(**this);
++(*this);
return proxy;
}
friend bool operator==(const ConstIter& a, const ConstIter& b) {
return a.s_ == b.s_ && a.pos_ == b.pos_;
}
friend bool operator!=(const ConstIter& a, const ConstIter& b) {
return !(a == b);
}
private:
const Streamlike* s_;
typename std::list<value_type>::iterator pos_;
};
friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) {
os << "[";
typedef typename std::list<value_type>::const_iterator Iter;
const char* sep = "";
for (Iter it = s.remainder_.begin(); it != s.remainder_.end(); ++it) {
os << sep << *it;
sep = ",";
}
os << "]";
return os;
}
mutable std::list<value_type> remainder_; // modified by iteration
};
TEST(StreamlikeTest, Iteration) {
const int a[5] = { 2, 1, 4, 5, 3 };
Streamlike<int> s(a, a + 5);
Streamlike<int>::const_iterator it = s.begin();
const int* ip = a;
while (it != s.end()) {
SCOPED_TRACE(ip - a);
EXPECT_EQ(*ip++, *it++);
}
}
TEST(WhenSortedTest, WorksForStreamlike) {
// Streamlike 'container' provides only minimal iterator support.
// Its iterators are tagged with input_iterator_tag.
const int a[5] = { 2, 1, 4, 5, 3 };
Streamlike<int> s(a, a + 5);
EXPECT_THAT(s, WhenSorted(ElementsAre(1, 2, 3, 4, 5)));
EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
}
TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) {
const int a[5] = { 2, 1, 4, 5, 3 };
Streamlike<int> s(a, a + 5);
Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2, 3, 4, 5);
EXPECT_THAT(s, WhenSorted(vector_match));
EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
}
// Tests IsReadableTypeName().
TEST(IsReadableTypeNameTest, ReturnsTrueForShortNames) {
EXPECT_TRUE(IsReadableTypeName("int"));
EXPECT_TRUE(IsReadableTypeName("const unsigned char*"));
EXPECT_TRUE(IsReadableTypeName("MyMap<int, void*>"));
EXPECT_TRUE(IsReadableTypeName("void (*)(int, bool)"));
}
TEST(IsReadableTypeNameTest, ReturnsTrueForLongNonTemplateNonFunctionNames) {
EXPECT_TRUE(IsReadableTypeName("my_long_namespace::MyClassName"));
EXPECT_TRUE(IsReadableTypeName("int [5][6][7][8][9][10][11]"));
EXPECT_TRUE(IsReadableTypeName("my_namespace::MyOuterClass::MyInnerClass"));
}
TEST(IsReadableTypeNameTest, ReturnsFalseForLongTemplateNames) {
EXPECT_FALSE(
IsReadableTypeName("basic_string<char, std::char_traits<char> >"));
EXPECT_FALSE(IsReadableTypeName("std::vector<int, std::alloc_traits<int> >"));
}
TEST(IsReadableTypeNameTest, ReturnsFalseForLongFunctionTypeNames) {
EXPECT_FALSE(IsReadableTypeName("void (&)(int, bool, char, float)"));
}
// Tests JoinAsTuple().
TEST(JoinAsTupleTest, JoinsEmptyTuple) {
EXPECT_EQ("", JoinAsTuple(Strings()));
}
TEST(JoinAsTupleTest, JoinsOneTuple) {
const char* fields[] = { "1" };
EXPECT_EQ("1", JoinAsTuple(Strings(fields, fields + 1)));
}
TEST(JoinAsTupleTest, JoinsTwoTuple) {
const char* fields[] = { "1", "a" };
EXPECT_EQ("(1, a)", JoinAsTuple(Strings(fields, fields + 2)));
}
TEST(JoinAsTupleTest, JoinsTenTuple) {
const char* fields[] = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
EXPECT_EQ("(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)",
JoinAsTuple(Strings(fields, fields + 10)));
}
// Tests FormatMatcherDescription().
TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) {
EXPECT_EQ("is even",
FormatMatcherDescription(false, "IsEven", Strings()));
EXPECT_EQ("not (is even)",
FormatMatcherDescription(true, "IsEven", Strings()));
const char* params[] = { "5" };
EXPECT_EQ("equals 5",
FormatMatcherDescription(false, "Equals",
Strings(params, params + 1)));
const char* params2[] = { "5", "8" };
EXPECT_EQ("is in range (5, 8)",
FormatMatcherDescription(false, "IsInRange",
Strings(params2, params2 + 2)));
}
// Tests PolymorphicMatcher::mutable_impl().
TEST(PolymorphicMatcherTest, CanAccessMutableImpl) {
PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
DivisibleByImpl& impl = m.mutable_impl();
EXPECT_EQ(42, impl.divider());
impl.set_divider(0);
EXPECT_EQ(0, m.mutable_impl().divider());
}
// Tests PolymorphicMatcher::impl().
TEST(PolymorphicMatcherTest, CanAccessImpl) {
const PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
const DivisibleByImpl& impl = m.impl();
EXPECT_EQ(42, impl.divider());
}
TEST(MatcherTupleTest, ExplainsMatchFailure) {
stringstream ss1;
ExplainMatchFailureTupleTo(make_tuple(Matcher<char>(Eq('a')), GreaterThan(5)),
make_tuple('a', 10), &ss1);
EXPECT_EQ("", ss1.str()); // Successful match.
stringstream ss2;
ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
make_tuple(2, 'b'), &ss2);
EXPECT_EQ(" Expected arg #0: is > 5\n"
" Actual: 2, which is 3 less than 5\n"
" Expected arg #1: is equal to 'a' (97, 0x61)\n"
" Actual: 'b' (98, 0x62)\n",
ss2.str()); // Failed match where both arguments need explanation.
stringstream ss3;
ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
make_tuple(2, 'a'), &ss3);
EXPECT_EQ(" Expected arg #0: is > 5\n"
" Actual: 2, which is 3 less than 5\n",
ss3.str()); // Failed match where only one argument needs
// explanation.
}
// Tests Each().
TEST(EachTest, ExplainsMatchResultCorrectly) {
set<int> a; // empty
Matcher<set<int> > m = Each(2);
EXPECT_EQ("", Explain(m, a));
Matcher<const int(&)[1]> n = Each(1); // NOLINT
const int b[1] = { 1 };
EXPECT_EQ("", Explain(n, b));
n = Each(3);
EXPECT_EQ("whose element #0 doesn't match", Explain(n, b));
a.insert(1);
a.insert(2);
a.insert(3);
m = Each(GreaterThan(0));
EXPECT_EQ("", Explain(m, a));
m = Each(GreaterThan(10));
EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10",
Explain(m, a));
}
TEST(EachTest, DescribesItselfCorrectly) {
Matcher<vector<int> > m = Each(1);
EXPECT_EQ("only contains elements that is equal to 1", Describe(m));
Matcher<vector<int> > m2 = Not(m);
EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2));
}
TEST(EachTest, MatchesVectorWhenAllElementsMatch) {
vector<int> some_vector;
EXPECT_THAT(some_vector, Each(1));
some_vector.push_back(3);
EXPECT_THAT(some_vector, Not(Each(1)));
EXPECT_THAT(some_vector, Each(3));
some_vector.push_back(1);
some_vector.push_back(2);
EXPECT_THAT(some_vector, Not(Each(3)));
EXPECT_THAT(some_vector, Each(Lt(3.5)));
vector<string> another_vector;
another_vector.push_back("fee");
EXPECT_THAT(another_vector, Each(string("fee")));
another_vector.push_back("fie");
another_vector.push_back("foe");
another_vector.push_back("fum");
EXPECT_THAT(another_vector, Not(Each(string("fee"))));
}
TEST(EachTest, MatchesMapWhenAllElementsMatch) {
map<const char*, int> my_map;
const char* bar = "a string";
my_map[bar] = 2;
EXPECT_THAT(my_map, Each(make_pair(bar, 2)));
map<string, int> another_map;
EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1)));
another_map["fee"] = 1;
EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1)));
another_map["fie"] = 2;
another_map["foe"] = 3;
another_map["fum"] = 4;
EXPECT_THAT(another_map, Not(Each(make_pair(string("fee"), 1))));
EXPECT_THAT(another_map, Not(Each(make_pair(string("fum"), 1))));
EXPECT_THAT(another_map, Each(Pair(_, Gt(0))));
}
TEST(EachTest, AcceptsMatcher) {
const int a[] = { 1, 2, 3 };
EXPECT_THAT(a, Each(Gt(0)));
EXPECT_THAT(a, Not(Each(Gt(1))));
}
TEST(EachTest, WorksForNativeArrayAsTuple) {
const int a[] = { 1, 2 };
const int* const pointer = a;
EXPECT_THAT(make_tuple(pointer, 2), Each(Gt(0)));
EXPECT_THAT(make_tuple(pointer, 2), Not(Each(Gt(1))));
}
// For testing Pointwise().
class IsHalfOfMatcher {
public:
template <typename T1, typename T2>
bool MatchAndExplain(const tuple<T1, T2>& a_pair,
MatchResultListener* listener) const {
if (get<0>(a_pair) == get<1>(a_pair)/2) {
*listener << "where the second is " << get<1>(a_pair);
return true;
} else {
*listener << "where the second/2 is " << get<1>(a_pair)/2;
return false;
}
}
void DescribeTo(ostream* os) const {
*os << "are a pair where the first is half of the second";
}
void DescribeNegationTo(ostream* os) const {
*os << "are a pair where the first isn't half of the second";
}
};
PolymorphicMatcher<IsHalfOfMatcher> IsHalfOf() {
return MakePolymorphicMatcher(IsHalfOfMatcher());
}
TEST(PointwiseTest, DescribesSelf) {
vector<int> rhs;
rhs.push_back(1);
rhs.push_back(2);
rhs.push_back(3);
const Matcher<const vector<int>&> m = Pointwise(IsHalfOf(), rhs);
EXPECT_EQ("contains 3 values, where each value and its corresponding value "
"in { 1, 2, 3 } are a pair where the first is half of the second",
Describe(m));
EXPECT_EQ("doesn't contain exactly 3 values, or contains a value x at some "
"index i where x and the i-th value of { 1, 2, 3 } are a pair "
"where the first isn't half of the second",
DescribeNegation(m));
}
TEST(PointwiseTest, MakesCopyOfRhs) {
list<signed char> rhs;
rhs.push_back(2);
rhs.push_back(4);
int lhs[] = { 1, 2 };
const Matcher<const int (&)[2]> m = Pointwise(IsHalfOf(), rhs);
EXPECT_THAT(lhs, m);
// Changing rhs now shouldn't affect m, which made a copy of rhs.
rhs.push_back(6);
EXPECT_THAT(lhs, m);
}
TEST(PointwiseTest, WorksForLhsNativeArray) {
const int lhs[] = { 1, 2, 3 };
vector<int> rhs;
rhs.push_back(2);
rhs.push_back(4);
rhs.push_back(6);
EXPECT_THAT(lhs, Pointwise(Lt(), rhs));
EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
}
TEST(PointwiseTest, WorksForRhsNativeArray) {
const int rhs[] = { 1, 2, 3 };
vector<int> lhs;
lhs.push_back(2);
lhs.push_back(4);
lhs.push_back(6);
EXPECT_THAT(lhs, Pointwise(Gt(), rhs));
EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs)));
}
TEST(PointwiseTest, RejectsWrongSize) {
const double lhs[2] = { 1, 2 };
const int rhs[1] = { 0 };
EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
EXPECT_EQ("which contains 2 values",
Explain(Pointwise(Gt(), rhs), lhs));
const int rhs2[3] = { 0, 1, 2 };
EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2)));
}
TEST(PointwiseTest, RejectsWrongContent) {
const double lhs[3] = { 1, 2, 3 };
const int rhs[3] = { 2, 6, 4 };
EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs)));
EXPECT_EQ("where the value pair (2, 6) at index #1 don't match, "
"where the second/2 is 3",
Explain(Pointwise(IsHalfOf(), rhs), lhs));
}
TEST(PointwiseTest, AcceptsCorrectContent) {
const double lhs[3] = { 1, 2, 3 };
const int rhs[3] = { 2, 4, 6 };
EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs));
EXPECT_EQ("", Explain(Pointwise(IsHalfOf(), rhs), lhs));
}
TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) {
const double lhs[3] = { 1, 2, 3 };
const int rhs[3] = { 2, 4, 6 };
const Matcher<tuple<const double&, const int&> > m1 = IsHalfOf();
EXPECT_THAT(lhs, Pointwise(m1, rhs));
EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs));
// This type works as a tuple<const double&, const int&> can be
// implicitly cast to tuple<double, int>.
const Matcher<tuple<double, int> > m2 = IsHalfOf();
EXPECT_THAT(lhs, Pointwise(m2, rhs));
EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs));
}
} // namespace gmock_matchers_test
} // namespace testing
| imoldman/google-mock-svn | test/gmock-matchers_test.cc | C++ | bsd-3-clause | 142,301 |
#include "signalhandler.h"
#include "signaldata.h"
#include "signaldescription.h"
#include <lcm/lcm-cpp.hpp>
SignalHandler::SignalHandler(const SignalDescription* signalDescription, QObject* parent) : LCMSubscriber(parent)
{
mDescription = *signalDescription;
mSignalData = new SignalData();
}
SignalHandler::~SignalHandler()
{
delete mSignalData;
}
void SignalHandler::handleMessage(const lcm::ReceiveBuffer* rbuf, const std::string& channel)
{
double timeNow;
double signalValue;
(void)channel;
bool valid = this->extractSignalData(rbuf, timeNow, signalValue);
if (valid)
{
mSignalData->appendSample(timeNow, signalValue);
}
else
{
mSignalData->flagMessageError();
}
}
void SignalHandler::subscribe(lcm::LCM* lcmInstance)
{
if (mSubscription)
{
printf("error: SignalHandler::subscribe() called without first calling unsubscribe.\n");
return;
}
#if QT_VERSION >= 0x050000
mSubscription = lcmInstance->subscribe(this->channel().toLatin1().data(), &SignalHandler::handleMessage, this);
#else
mSubscription = lcmInstance->subscribe(this->channel().toAscii().data(), &SignalHandler::handleMessage, this);
#endif
}
SignalHandlerFactory& SignalHandlerFactory::instance()
{
static SignalHandlerFactory factory;
return factory;
}
SignalHandler* SignalHandlerFactory::createHandler(const SignalDescription* desc) const
{
Constructor constructor = mConstructors.value(desc->mMessageType).value(desc->mFieldName);
if (constructor == NULL)
{
return NULL;
}
return (*constructor)(desc);
}
double SignalHandlerFactory::getOffsetTime(int64_t messageTime)
{
if (mTimeOffset == 0)
{
mTimeOffset = messageTime;
}
return (messageTime - mTimeOffset) * 1e-6;
}
| openhumanoids/signal-scope | src/signal_scope/signalhandler.cpp | C++ | bsd-3-clause | 1,734 |
#!/usr/bin/python
# Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
import idlnode
import idlparser
import logging.config
import sys
import unittest
class IDLNodeTestCase(unittest.TestCase):
def _run_test(self, syntax, content, expected):
"""Utility run tests and prints extra contextual information.
Args:
syntax -- IDL grammar to use (either idlparser.WEBKIT_SYNTAX,
WEBIDL_SYNTAX or FREMONTCUT_SYNTAX). If None, will run
multiple tests, each with a different syntax.
content -- input text for the parser.
expected -- expected parse result.
"""
if syntax is None:
self._run_test(idlparser.WEBIDL_SYNTAX, content, expected)
self._run_test(idlparser.WEBKIT_SYNTAX, content, expected)
self._run_test(idlparser.FREMONTCUT_SYNTAX, content, expected)
return
actual = None
error = None
ast = None
parseResult = None
try:
parser = idlparser.IDLParser(syntax)
ast = parser.parse(content)
node = idlnode.IDLFile(ast)
actual = node.to_dict() if node else None
except SyntaxError, e:
error = e
pass
if actual == expected:
return
else:
msg = '''
SYNTAX : %s
CONTENT :
%s
EXPECTED:
%s
ACTUAL :
%s
ERROR : %s
AST :
%s
''' % (syntax, content, expected, actual, error, ast)
self.fail(msg)
def test_empty_module(self):
self._run_test(None, 'module TestModule {};',
{'modules': [{
'id': 'TestModule'
}]})
def test_empty_interface(self):
self._run_test(
None, 'module TestModule { interface Interface1 {}; };', {
'modules': [{
'interfaces': [{
'javascript_binding_name': 'Interface1',
'doc_js_name': 'Interface1',
'id': 'Interface1'
}],
'id':
'TestModule'
}]
})
def test_gcc_preprocessor(self):
self._run_test(idlparser.WEBKIT_SYNTAX,
'#if 1\nmodule TestModule {};\n#endif\n',
{'modules': [{
'id': 'TestModule'
}]})
def test_extended_attributes(self):
self._run_test(
idlparser.WEBKIT_SYNTAX,
'module M { interface [ExAt1, ExAt2] I {};};', {
'modules': [{
'interfaces': [{
'javascript_binding_name': 'I',
'doc_js_name': 'I',
'ext_attrs': {
'ExAt1': None,
'ExAt2': None
},
'id': 'I'
}],
'id':
'M'
}]
})
def test_implements_statement(self):
self._run_test(
idlparser.WEBIDL_SYNTAX, 'module M { X implements Y; };', {
'modules': [{
'implementsStatements': [{
'implementor': {
'id': 'X'
},
'implemented': {
'id': 'Y'
}
}],
'id':
'M'
}]
})
def test_attributes(self):
self._run_test(
idlparser.WEBIDL_SYNTAX, '''interface I {
attribute long a1;
readonly attribute DOMString a2;
attribute any a3;
};''', {
'interfaces': [{
'javascript_binding_name':
'I',
'attributes': [{
'type': {
'id': 'long'
},
'id': 'a1',
'doc_js_interface_name': 'I'
},
{
'type': {
'id': 'DOMString'
},
'is_read_only': True,
'id': 'a2',
'doc_js_interface_name': 'I'
},
{
'type': {
'id': 'any'
},
'id': 'a3',
'doc_js_interface_name': 'I'
}],
'id':
'I',
'doc_js_name':
'I'
}]
})
def test_operations(self):
self._run_test(
idlparser.WEBIDL_SYNTAX, '''interface I {
[ExAttr] t1 op1();
t2 op2(in int arg1, in long arg2);
getter any item(in long index);
};''', {
'interfaces': [{
'operations':
[{
'doc_js_interface_name': 'I',
'type': {
'id': 't1'
},
'ext_attrs': {
'ExAttr': None
},
'id': 'op1'
},
{
'doc_js_interface_name':
'I',
'type': {
'id': 't2'
},
'id':
'op2',
'arguments': [{
'type': {
'id': 'int'
},
'id': 'arg1'
}, {
'type': {
'id': 'long'
},
'id': 'arg2'
}]
},
{
'specials': ['getter'],
'doc_js_interface_name': 'I',
'type': {
'id': 'any'
},
'id': 'item',
'arguments': [{
'type': {
'id': 'long'
},
'id': 'index'
}]
},
{
'is_stringifier': True,
'type': {
'id': 'name'
},
'doc_js_interface_name': 'I'
}],
'javascript_binding_name':
'I',
'id':
'I',
'doc_js_name':
'I'
}]
})
def test_constants(self):
self._run_test(
None, '''interface I {
const long c1 = 0;
const long c2 = 1;
const long c3 = 0x01;
const long c4 = 10;
const boolean b1 = false;
const boolean b2 = true;
};''', {
'interfaces': [{
'javascript_binding_name':
'I',
'doc_js_name':
'I',
'id':
'I',
'constants': [{
'type': {
'id': 'long'
},
'id': 'c1',
'value': '0',
'doc_js_interface_name': 'I'
},
{
'type': {
'id': 'long'
},
'id': 'c2',
'value': '1',
'doc_js_interface_name': 'I'
},
{
'type': {
'id': 'long'
},
'id': 'c3',
'value': '0x01',
'doc_js_interface_name': 'I'
},
{
'type': {
'id': 'long'
},
'id': 'c4',
'value': '10',
'doc_js_interface_name': 'I'
},
{
'type': {
'id': 'boolean'
},
'id': 'b1',
'value': 'false',
'doc_js_interface_name': 'I'
},
{
'type': {
'id': 'boolean'
},
'id': 'b2',
'value': 'true',
'doc_js_interface_name': 'I'
}]
}]
})
def test_annotations(self):
self._run_test(
idlparser.FREMONTCUT_SYNTAX,
'@Ano1 @Ano2() @Ano3(x=1) @Ano4(x,y=2) interface I {};', {
'interfaces': [{
'javascript_binding_name': 'I',
'doc_js_name': 'I',
'id': 'I',
'annotations': {
'Ano4': {
'y': '2',
'x': None
},
'Ano1': {},
'Ano2': {},
'Ano3': {
'x': '1'
}
}
}]
})
self._run_test(
idlparser.FREMONTCUT_SYNTAX, '''interface I : @Ano1 J {
@Ano2 attribute int someAttr;
@Ano3 void someOp();
@Ano3 const int someConst = 0;
};''', {
'interfaces': [{
'operations': [{
'annotations': {
'Ano3': {}
},
'type': {
'id': 'void'
},
'id': 'someOp',
'doc_js_interface_name': 'I'
}],
'javascript_binding_name':
'I',
'parents': [{
'type': {
'id': 'J'
},
'annotations': {
'Ano1': {}
}
}],
'attributes': [{
'annotations': {
'Ano2': {}
},
'type': {
'id': 'int'
},
'id': 'someAttr',
'doc_js_interface_name': 'I'
}],
'doc_js_name':
'I',
'id':
'I',
'constants': [{
'annotations': {
'Ano3': {}
},
'type': {
'id': 'int'
},
'id': 'someConst',
'value': '0',
'doc_js_interface_name': 'I'
}]
}]
})
def test_inheritance(self):
self._run_test(
None,
'interface Shape {}; interface Rectangle : Shape {}; interface Square : Rectangle, Shape {};',
{
'interfaces': [{
'javascript_binding_name': 'Shape',
'doc_js_name': 'Shape',
'id': 'Shape'
},
{
'javascript_binding_name': 'Rectangle',
'doc_js_name': 'Rectangle',
'parents': [{
'type': {
'id': 'Shape'
}
}],
'id': 'Rectangle'
},
{
'javascript_binding_name':
'Square',
'doc_js_name':
'Square',
'parents': [{
'type': {
'id': 'Rectangle'
}
}, {
'type': {
'id': 'Shape'
}
}],
'id':
'Square'
}]
})
if __name__ == "__main__":
logging.config.fileConfig("logging.conf")
if __name__ == '__main__':
unittest.main()
| dartino/dart-sdk | tools/dom/scripts/idlnode_test.py | Python | bsd-3-clause | 14,699 |
/* Copyright (C) 2005-2011 Fabio Riccardi */
package com.lightcrafts.ui.editor;
import com.lightcrafts.app.ComboFrame;
import com.lightcrafts.ui.LightZoneSkin;
import static com.lightcrafts.ui.editor.Locale.LOCALE;
import com.lightcrafts.ui.toolkit.PaneTitle;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.undo.UndoableEdit;
import java.awt.*;
import java.awt.event.MouseWheelEvent;
import java.util.List;
/**
* Renders the live undo stack in list form, allowing selection and
* keyboard navigation of the stack.
*/
public final class DocUndoHistory
extends JPanel implements UndoableEditListener {
private DocUndoManager undo;
private DefaultListModel model;
private ListSelectionModel selection;
private JScrollPane scroll;
private JList list;
// prevent update loops
private boolean isEditing;
private boolean isSelecting;
private static final class UndoCellRenderer
extends JLabel implements ListCellRenderer {
UndoCellRenderer() {
setForeground(LightZoneSkin.Colors.ToolPanesForeground);
setBackground(LightZoneSkin.Colors.ToolPanesBackground);
}
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected,
boolean cellHasFocus) {
if (cellHasFocus || isSelected)
setBackground(LightZoneSkin.Colors.ToolsBackground.darker().darker());
else
setBackground(LightZoneSkin.Colors.ToolPanesBackground);
setText((String) value);
return this;
}
}
// A disabled component, for the no-Document display mode.
public DocUndoHistory() {
setEnabled(false);
setBackground(LightZoneSkin.Colors.ToolPanesBackground);
setOpaque(true);
setBorder(LightZoneSkin.getPaneBorder());
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
list = new JList();
list.setForeground(LightZoneSkin.Colors.ToolPanesForeground);
list.setBackground(LightZoneSkin.Colors.ToolPanesBackground);
list.setCellRenderer(new UndoCellRenderer());
scroll = new JScrollPane(list);
scroll.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED
);
scroll.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED
);
scroll.setBorder(null);
add(new PaneTitle(LOCALE.get("DocUndoHistoryTitle")));
add(scroll);
}
public DocUndoHistory(Document doc) {
this();
setEnabled(true);
this.undo = doc.getUndoManager();
model = new DefaultListModel();
model.addElement(LOCALE.get("DocUndoHistoryOriginalItem"));
list.setModel(model);
selection = list.getSelectionModel();
selection.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
undo.addUndoableEditListener(this);
selection.addListSelectionListener(
new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
if (! isSelecting) {
if (! e.getValueIsAdjusting()) {
getComboFrame().getEditor().setMode( EditorMode.ARROW );
isEditing = true;
int selected = selection.getLeadSelectionIndex();
int index = model.size() - selected - 2;
System.out.println("selected index = " + index);
undo.setEditIndex(index);
isEditing = false;
}
}
}
}
);
}
// Exposed only so the tree's bounds can be determined for the purpose of
// dispatching our custom horizontal-scroll mouse wheel events.
public JComponent getScrollPane() {
return scroll;
}
// Special handling for Mighty Mouse and two-finger trackpad
// horizontal scroll events
public void horizontalMouseWheelMoved(MouseWheelEvent e) {
if (e.getScrollType() >= 2) {
if (scroll.isWheelScrollingEnabled()) {
JScrollBar bar = scroll.getHorizontalScrollBar();
int dir = e.getWheelRotation() < 0 ? -1 : 1;
int inc = bar.getUnitIncrement(dir);
int value = bar.getValue() - e.getWheelRotation() * inc;
bar.setValue(value);
}
}
}
public ComboFrame getComboFrame() {
return (ComboFrame)SwingUtilities.getAncestorOfClass(
ComboFrame.class, this
);
}
public void undoableEditHappened(UndoableEditEvent event) {
if (! isEditing) {
isSelecting = true;
model.clear();
model.addElement(LOCALE.get("DocUndoHistoryOriginalItem"));
selection.removeSelectionInterval(0, model.getSize());
List<UndoableEdit> edits = undo.getEdits();
for (UndoableEdit edit : edits) {
model.insertElementAt(edit.getPresentationName(), 0);
}
int index = edits.size() - undo.getEditIndex() - 1;
selection.setSelectionInterval(index, index);
isSelecting = false;
}
}
}
| MarinnaCole/LightZone | lightcrafts/src/com/lightcrafts/ui/editor/DocUndoHistory.java | Java | bsd-3-clause | 5,625 |
#!/usr/bin/env python
"""Microbenchmark for function call overhead.
This measures simple function calls that are not methods, do not use varargs or
kwargs, and do not use tuple unpacking.
"""
# Python imports
#import optparse
import time
# Local imports
import util
def foo(a, b, c, d):
# 20 calls
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
def bar(a, b, c):
# 20 calls
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
def baz(a, b):
# 20 calls
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
def quux(a):
# 20 calls
qux()
qux()
qux()
qux()
qux()
qux()
qux()
qux()
qux()
qux()
qux()
qux()
qux()
qux()
qux()
qux()
qux()
qux()
qux()
qux()
def qux():
pass
def test_calls(iterations):
from browser import console
times = []
for _i in range(iterations):
console.log("iteration: %s" % _i)
t0 = time.time()
# 40 calls
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
t1 = time.time()
times.append(t1 - t0)
return times
def run(num_runs=100, take_geo_mean=True):
return util.run_benchmark(take_geo_mean, num_runs, test_calls)
#if __name__ == "__main__":
# parser = optparse.OptionParser(
# usage="%prog [options] [test]",
# description=("Test the performance of simple Python-to-Python function"
# " calls."))
# util.add_standard_options_to(parser)
# options, _ = parser.parse_args()
# # Priming run.
# test_calls(1)
# util.run_benchmark(options, options.num_runs, test_calls)
| kikocorreoso/brython | www/benchmarks/performance/bm_call_simple.py | Python | bsd-3-clause | 3,712 |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE124_Buffer_Underwrite__wchar_t_alloca_memmove_72a.cpp
Label Definition File: CWE124_Buffer_Underwrite.stack.label.xml
Template File: sources-sink-72a.tmpl.cpp
*/
/*
* @description
* CWE: 124 Buffer Underwrite
* BadSource: Set data pointer to before the allocated memory buffer
* GoodSource: Set data pointer to the allocated memory buffer
* Sinks: memmove
* BadSink : Copy string to data using memmove
* Flow Variant: 72 Data flow: data passed in a vector from one function to another in different source files
*
* */
#include "std_testcase.h"
#include <vector>
#include <wchar.h>
using namespace std;
namespace CWE124_Buffer_Underwrite__wchar_t_alloca_memmove_72
{
#ifndef OMITBAD
/* bad function declaration */
void badSink(vector<wchar_t *> dataVector);
void bad()
{
wchar_t * data;
vector<wchar_t *> dataVector;
wchar_t * dataBuffer = (wchar_t *)ALLOCA(100*sizeof(wchar_t));
wmemset(dataBuffer, L'A', 100-1);
dataBuffer[100-1] = L'\0';
/* FLAW: Set data pointer to before the allocated memory buffer */
data = dataBuffer - 8;
/* Put data in a vector */
dataVector.insert(dataVector.end(), 1, data);
dataVector.insert(dataVector.end(), 1, data);
dataVector.insert(dataVector.end(), 1, data);
badSink(dataVector);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* good function declarations */
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(vector<wchar_t *> dataVector);
static void goodG2B()
{
wchar_t * data;
vector<wchar_t *> dataVector;
wchar_t * dataBuffer = (wchar_t *)ALLOCA(100*sizeof(wchar_t));
wmemset(dataBuffer, L'A', 100-1);
dataBuffer[100-1] = L'\0';
/* FIX: Set data pointer to the allocated memory buffer */
data = dataBuffer;
/* Put data in a vector */
dataVector.insert(dataVector.end(), 1, data);
dataVector.insert(dataVector.end(), 1, data);
dataVector.insert(dataVector.end(), 1, data);
goodG2BSink(dataVector);
}
void good()
{
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
#ifdef INCLUDEMAIN
using namespace CWE124_Buffer_Underwrite__wchar_t_alloca_memmove_72; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| JianpingZeng/xcc | xcc/test/juliet/testcases/CWE124_Buffer_Underwrite/s04/CWE124_Buffer_Underwrite__wchar_t_alloca_memmove_72a.cpp | C++ | bsd-3-clause | 2,996 |
namespace Rhino.DSL
{
using System;
using Boo.Lang.Compiler.Ast;
using Module=Boo.Lang.Compiler.Ast.Module;
/// <summary>
/// Takes all the code that exists in a module's global section and put it in a specificied
/// method of a class. Allow easy handling of the Anonymous Base Class pattern
/// </summary>
public class ImplicitBaseClassCompilerStep : BaseClassCompilerStep
{
private readonly string methodName;
private readonly ParameterDeclarationCollection parameters;
/// <summary>
/// Create new instance of <seealso cref="ImplicitBaseClassCompilerStep"/>
/// </summary>
/// <param name="baseClass">The base class that will be used</param>
/// <param name="methodName">The name of the method that will get all the code from globals moved to it.</param>
/// <param name="namespaces">Namespaces that would be automatically imported into all modules</param>
public ImplicitBaseClassCompilerStep(Type baseClass, string methodName, params string[] namespaces)
: this(baseClass, methodName, null, namespaces)
{
}
/// <summary>
/// Create new instance of <seealso cref="ImplicitBaseClassCompilerStep"/>
/// </summary>
/// <param name="baseClass">The base class that will be used</param>
/// <param name="methodName">The name of the method that will get all the code from globals moved to it.</param>
/// <param name="parameters">The parameters of this method</param>
/// <param name="namespaces">Namespaces that would be automatically imported into all modules</param>
public ImplicitBaseClassCompilerStep(Type baseClass, string methodName, ParameterDeclarationCollection parameters, params string[] namespaces)
: base(baseClass, namespaces)
{
this.methodName = methodName;
this.parameters = parameters;
}
/// <summary>
/// Allow a derived class to perform additional operations on the newly created type definition.
/// </summary>
protected override void ExtendBaseClass(Module module, ClassDefinition definition)
{
Method method = new Method(methodName);
if (parameters != null)
{
foreach (ParameterDeclaration parameter in parameters)
{
method.Parameters.Add(parameter);
}
}
method.Body = module.Globals;
definition.Members.Add(method);
ExtendBaseClass(definition);
}
/// <summary>
/// Allow to extend the base class in additional ways
/// </summary>
/// <param name="definition">The definition.</param>
protected virtual void ExtendBaseClass(TypeDefinition definition)
{
}
}
}
| brumschlag/rhino-tools | rhino-dsl/Rhino.DSL/ImplicitBaseClassCompilerStep.cs | C# | bsd-3-clause | 2,848 |
from __future__ import print_function
##
## See COPYING file distributed along with the ncanda-data-integration package
## for the copyright and license terms
##
# Mail-related stuff
from builtins import str
from builtins import object
import smtplib
import time
import json
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from sibispy import sibislogger as slog
class sibis_email(object):
""" Class handling email communication with XNAT users and admin."""
# Initialize class.
def __init__(self, smtp_server, admin_email, sibis_admin_email = None):
self._sibis_admin_email = sibis_admin_email
self._admin_email = admin_email
self._admin_messages = []
self._messages_by_user = dict()
self._smtp_server = smtp_server
# Add to the message building up for a specific user
def add_user_message( self, uid, txt, uFirstName=None, uLastName=None, uEmail=None):
if uid not in self._messages_by_user:
self._messages_by_user[uid] = {'uFirst': uFirstName, 'uLast': uLastName, 'uEmail' : uEmail, 'msgList' : [txt] }
else:
self._messages_by_user[uid]['msgList'].append( txt )
# Add to the message building up for the admin
def add_admin_message( self, msg ):
self._admin_messages.append( msg )
# Send pre-formatted mail message
def send( self, subject, from_email, to_email, html, sendToAdminFlag=True ):
if not self._smtp_server :
slog.info("sibis_email.send","ERROR: smtp server not defined - email will not be sent!")
return False
if not to_email :
slog.info("sibis_email.send","ERROR: no email address for recipient defined - email will not be sent!")
return False
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = subject
msg['From'] = from_email
msg['To'] = ', '.join( to_email )
# Record the MIME types of both parts - text/plain and text/html.
text = ''
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)
# Send the message via local SMTP server.
try :
s = smtplib.SMTP( self._smtp_server )
except Exception as err_msg:
slog.info("sibis_email.send","ERROR: failed to connect to SMTP server at {} ".format(time.asctime()),
err_msg = str(err_msg),
smtp_server = self._smtp_server)
return False
try :
# sendmail function takes 3 arguments: sender's address, recipient's address
# and message to send - here it is sent as one string.
s.sendmail( from_email, to_email, msg.as_string() )
# Send email also to sibis admin if defined
if sendToAdminFlag and self._sibis_admin_email and to_email != self._sibis_admin_email :
s.sendmail( from_email, self._sibis_admin_email, msg.as_string() )
except Exception as err_msg:
slog.info("sibis_email.send","ERROR: failed to send email at {} ".format(time.asctime()),
err_msg = str(err_msg),
email_from = from_email,
email_to = to_email,
sibis_admin_email = self._sibis_admin_email,
email_msg = msg.as_string(),
smtp_server = self._smtp_server)
s.quit()
return False
s.quit()
return True
# Send mail to one user
def mail_user( self, uEmail, uFirst, uLast, title, intro_text, prolog, msglist ):
problem_list = [ '<ol>' ]
for m in msglist:
problem_list.append( '<li>%s</li>' % m )
problem_list.append( '</ol>' )
# Create the body of the message (a plain-text and an HTML version).
html = '<html>\n <head></head>\n <body>\n <p>Dear %s %s:<br><br>\n' %(uFirst,uLast) + intro_text + '\n %s\n' % ('\n'.join( problem_list ) ) + prolog + '\n</p>\n</body>\n</html>'
self.send( title, self._admin_email, [ uEmail ], html )
def mail_admin( self, title, intro_text):
problem_list = []
if len( self._messages_by_user ) > 0:
problem_list.append( '<ul>' )
for (uid,info_msglist) in self._messages_by_user.items():
problem_list.append( '<li>User: %s %s (%s)</li>' % (info_msglist['uFirst'],info_msglist['uLast'],info_msglist['uEmail']) )
problem_list.append( '<ol>' )
for m in info_msglist['msgList']:
problem_list.append( '<li>%s</li>' % m )
problem_list.append( '</ol>' )
problem_list.append( '</ul>' )
if len( self._admin_messages ) > 0:
problem_list.append( '<ol>' )
for m in self._admin_messages:
problem_list.append( '<li>%s</li>' % m )
problem_list.append( '</ol>' )
text = ''
# Create the body of the message (a plain-text and an HTML version).
html = '<html>\n\
<head></head>\n\
<body>\n' + intro_text + '\n %s\n\
</p>\n\
</body>\n\
</html>' % ('\n'.join( problem_list ))
self.send(title, self._admin_email, [ self._admin_email ], html )
def send_all( self, title, uIntro_txt, uProlog, aIntro_txt ):
# Run through list of messages by user
if len( self._messages_by_user ):
for (uid,uInfo_msg) in self._messages_by_user.items():
self.mail_user(uInfo_msg['uEmail'],uInfo_msg['uFirst'],uInfo_msg['uLast'], title, uIntro_txt, uProlog, uInfo_msg['msgList'])
if len( self._messages_by_user ) or len( self._admin_messages ):
self.mail_admin(title, aIntro_txt)
def dump_all( self ):
print("USER MESSAGES:")
print(self._messages_by_user)
print("ADMIN_MESSAGES:")
print(self._admin_messages)
class xnat_email(sibis_email):
def __init__(self, session):
self._interface = session.api['xnat']
if self._interface :
try:
# XNAT 1.7
server_config = self._interface.client.get('/xapi/siteConfig').json()
except Exception as ex:
# XNAT 1.6
server_config = self._interface._get_json('/data/services/settings')
self._site_url = server_config[u'siteUrl']
self._site_name = server_config[u'siteId']
sibis_email.__init__(self,server_config[u'smtp_host'],server_config[u'adminEmail'],session.get_email())
else:
slog.info('xnat_email.__init__',"ERROR: xnat api is not defined")
self._site_url = None
self._site_name = None
sibis_email.__init__(self,None,None,session.get_email())
self._project_name = session.get_project_name()
# Determine server config to get admin email and public URL
def add_user_message( self, uname, msg ):
if uname not in self._messages_by_user:
try:
user = self._interface.client.users[uname]
uEmail = user.email
user_firstname = user.first_name
user_lastname = user.last_name
except:
slog.info('xnat_email.add_user_message',"ERROR: failed to get detail information for user " + str(uname) + " at {}".format(time.asctime()),
msg = str(msg))
return False
sibis_email.add_user_message(self,uname,msg,user_firstname,user_lastname,uEmail)
else:
sibis_email.add_user_message(self,uname,msg)
return True
def mail_user( self, uEmail, uFirst, uLast, msglist ):
intro='We have detected the following problem(s) with data you uploaded to the <a href="%s">%s XNAT image repository</a>:' % (self._site_url, self._site_name)
prolog='Please address these issues as soon as possible (direct links to the respective data items are provided above for your convenience). If you have further questions, feel free to contact the <a href="mailto:%s">%s support</a>' % (self._admin_email, self._project_name )
title="%s XNAT: problems with your uploaded data" % ( self._project_name )
sibis_email.mail_user(self,uEmail, uFirst, uLast, title, intro, prolog, msglist)
def mail_admin(self):
title = "$s: %s XNAT problem update" % (self._project_name, self._site_name)
intro_text = 'We have detected the following problem(s) with data on <a href="%s">%s XNAT image repository</a>:' % (self._site_url, self._project_name)
sibis_email.mail_admin(self,title, intro_text)
def send_all( self ):
# Run through list of messages by user
if len( self._messages_by_user ):
for (uname,info_msglist) in self._messages_by_user.items():
self.mail_user(info_msglist['uEmail'], info_msglist['uFirst'], info_msglist['uLast'], info_msglist['msgList'])
if len( self._messages_by_user ) or len( self._admin_messages ):
self.mail_admin
| sibis-platform/sibispy | sibis_email.py | Python | bsd-3-clause | 9,495 |
"""
=============================
Straight line Hough transform
=============================
The Hough transform in its simplest form is a method to detect straight lines.
In the following example, we construct an image with a line intersection. We
then use the `Hough transform <http://en.wikipedia.org/wiki/Hough_transform>`__.
to explore a parameter space for straight lines that may run through the image.
Algorithm overview
------------------
Usually, lines are parameterised as :math:`y = mx + c`, with a gradient
:math:`m` and y-intercept `c`. However, this would mean that :math:`m` goes to
infinity for vertical lines. Instead, we therefore construct a segment
perpendicular to the line, leading to the origin. The line is represented by
the length of that segment, :math:`r`, and the angle it makes with the x-axis,
:math:`\\theta`.
The Hough transform constructs a histogram array representing the parameter
space (i.e., an :math:`M \\times N` matrix, for :math:`M` different values of
the radius and :math:`N` different values of :math:`\\theta`). For each
parameter combination, :math:`r` and :math:`\\theta`, we then find the number of
non-zero pixels in the input image that would fall close to the corresponding
line, and increment the array at position :math:`(r, \\theta)` appropriately.
We can think of each non-zero pixel "voting" for potential line candidates. The
local maxima in the resulting histogram indicates the parameters of the most
probably lines. In our example, the maxima occur at 45 and 135 degrees,
corresponding to the normal vector angles of each line.
Another approach is the Progressive Probabilistic Hough Transform [1]_. It is
based on the assumption that using a random subset of voting points give a good
approximation to the actual result, and that lines can be extracted during the
voting process by walking along connected components. This returns the
beginning and end of each line segment, which is useful.
The function `probabilistic_hough` has three parameters: a general threshold
that is applied to the Hough accumulator, a minimum line length and the line
gap that influences line merging. In the example below, we find lines longer
than 10 with a gap less than 3 pixels.
References
----------
.. [1] C. Galamhos, J. Matas and J. Kittler,"Progressive probabilistic
Hough transform for line detection", in IEEE Computer Society
Conference on Computer Vision and Pattern Recognition, 1999.
.. [2] Duda, R. O. and P. E. Hart, "Use of the Hough Transformation to
Detect Lines and Curves in Pictures," Comm. ACM, Vol. 15,
pp. 11-15 (January, 1972)
"""
from matplotlib import cm
from skimage.transform import (hough_line, hough_line_peaks,
probabilistic_hough_line)
from skimage.feature import canny
from skimage import data
import numpy as np
import matplotlib.pyplot as plt
# Constructing test image.
image = np.zeros((100, 100))
idx = np.arange(25, 75)
image[idx[::-1], idx] = 255
image[idx, idx] = 255
# Classic straight-line Hough transform.
h, theta, d = hough_line(image)
# Generating figure 1.
fig, (ax0, ax1, ax2) = plt.subplots(1, 3, figsize=(12, 6))
plt.tight_layout()
ax0.imshow(image, cmap=cm.gray)
ax0.set_title('Input image')
ax0.set_axis_off()
ax1.imshow(np.log(1 + h), extent=[np.rad2deg(theta[-1]), np.rad2deg(theta[0]),
d[-1], d[0]], cmap=cm.gray, aspect=1/1.5)
ax1.set_title('Hough transform')
ax1.set_xlabel('Angles (degrees)')
ax1.set_ylabel('Distance (pixels)')
ax1.axis('image')
ax2.imshow(image, cmap=cm.gray)
row1, col1 = image.shape
for _, angle, dist in zip(*hough_line_peaks(h, theta, d)):
y0 = (dist - 0 * np.cos(angle)) / np.sin(angle)
y1 = (dist - col1 * np.cos(angle)) / np.sin(angle)
ax2.plot((0, col1), (y0, y1), '-r')
ax2.axis((0, col1, row1, 0))
ax2.set_title('Detected lines')
ax2.set_axis_off()
# Line finding using the Probabilistic Hough Transform.
image = data.camera()
edges = canny(image, 2, 1, 25)
lines = probabilistic_hough_line(edges, threshold=10, line_length=5,
line_gap=3)
# Generating figure 2.
fig, (ax0, ax1, ax2) = plt.subplots(1, 3, figsize=(16, 6), sharex=True,
sharey=True)
plt.tight_layout()
ax0.imshow(image, cmap=cm.gray)
ax0.set_title('Input image')
ax0.set_axis_off()
ax0.set_adjustable('box-forced')
ax1.imshow(edges, cmap=cm.gray)
ax1.set_title('Canny edges')
ax1.set_axis_off()
ax1.set_adjustable('box-forced')
ax2.imshow(edges * 0)
for line in lines:
p0, p1 = line
ax2.plot((p0[0], p1[0]), (p0[1], p1[1]))
row2, col2 = image.shape
ax2.axis((0, col2, row2, 0))
ax2.set_title('Probabilistic Hough')
ax2.set_axis_off()
ax2.set_adjustable('box-forced')
plt.show()
| rjeli/scikit-image | doc/examples/edges/plot_line_hough_transform.py | Python | bsd-3-clause | 4,764 |
"""
Test basic DarwinLog functionality provided by the StructuredDataDarwinLog
plugin.
These tests are currently only supported when running against Darwin
targets.
"""
from __future__ import print_function
import lldb
import os
import re
from lldbsuite.test import decorators
from lldbsuite.test import lldbtest
from lldbsuite.test import darwin_log
class TestDarwinLogFilterRegexCategory(darwin_log.DarwinLogTestBase):
mydir = lldbtest.TestBase.compute_mydir(__file__)
def setUp(self):
# Call super's setUp().
super(TestDarwinLogFilterRegexCategory, self).setUp()
# Source filename.
self.source = 'main.c'
# Output filename.
self.exe_name = self.getBuildArtifact("a.out")
self.d = {'C_SOURCES': self.source, 'EXE': self.exe_name}
# Locate breakpoint.
self.line = lldbtest.line_number(self.source, '// break here')
def tearDown(self):
# Shut down the process if it's still running.
if self.child:
self.runCmd('process kill')
self.expect_prompt()
self.runCmd('quit')
# Let parent clean up
super(TestDarwinLogFilterRegexCategory, self).tearDown()
# ==========================================================================
# category filter tests
# ==========================================================================
@decorators.skipUnlessDarwin
def test_filter_accept_category_full_match(self):
"""Test that fall-through reject, accept regex single category works."""
self.do_test(
["--no-match-accepts false",
"--filter \"accept category regex cat2\""]
)
# We should only see the second log message as we only accept
# that category.
self.assertIsNotNone(self.child.match)
self.assertTrue(
(len(
self.child.match.groups()) > 1) and (
self.child.match.group(2) == "cat2"),
"first log line should not be present, second log line "
"should be")
@decorators.skipUnlessDarwin
def test_filter_accept_category_partial_match(self):
"""Test that fall-through reject, accept regex category via partial match works."""
self.do_test(
["--no-match-accepts false",
"--filter \"accept category regex .+2\""]
)
# We should only see the second log message as we only accept
# that category.
self.assertIsNotNone(self.child.match)
self.assertTrue(
(len(
self.child.match.groups()) > 1) and (
self.child.match.group(2) == "cat2"),
"first log line should not be present, second log line "
"should be")
@decorators.skipUnlessDarwin
def test_filter_reject_category_full_match(self):
"""Test that fall-through accept, reject regex category works."""
self.do_test(
["--no-match-accepts true",
"--filter \"reject category regex cat1\""]
)
# We should only see the second log message as we rejected the first
# via category rejection.
self.assertIsNotNone(self.child.match)
self.assertTrue(
(len(
self.child.match.groups()) > 1) and (
self.child.match.group(2) == "cat2"),
"first log line should not be present, second log line "
"should be")
@decorators.skipUnlessDarwin
def test_filter_reject_category_partial_match(self):
"""Test that fall-through accept, reject regex category by partial match works."""
self.do_test(
["--no-match-accepts true",
"--filter \"reject category regex t1\""]
)
# We should only see the second log message as we rejected the first
# via category rejection.
self.assertIsNotNone(self.child.match)
self.assertTrue(
(len(
self.child.match.groups()) > 1) and (
self.child.match.group(2) == "cat2"),
"first log line should not be present, second log line "
"should be")
@decorators.skipUnlessDarwin
def test_filter_accept_category_second_rule(self):
"""Test that fall-through reject, accept regex category on second rule works."""
self.do_test(
["--no-match-accepts false",
"--filter \"accept category regex non-existent\"",
"--filter \"accept category regex cat2\""
]
)
# We should only see the second message since we reject by default,
# the first filter doesn't match any, and the second filter matches
# the category of the second log message.
self.assertIsNotNone(self.child.match)
self.assertTrue(
(len(
self.child.match.groups()) > 1) and (
self.child.match.group(2) == "cat2"),
"first log line should not be present, second log line "
"should be")
| youtube/cobalt | third_party/llvm-project/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/category/TestDarwinLogFilterRegexCategory.py | Python | bsd-3-clause | 5,073 |
#pragma once
#include <samchon/API.hpp>
#include <samchon/protocol/ClientDriver.hpp>
#include <samchon/protocol/WebCommunicator.hpp>
namespace samchon
{
namespace protocol
{
class WebServer;
/**
* A communicator with remote web-client.
*
* The {@link WebClientDriver} class is a type of {@link WebCommunicator}, specified for communication with remote
* web-client who has connected in a {@link WebServer} object who follows the protocol of web-socket. The
* {@link WebClientDriver} takes full charge of network communication with the remote web-client.
*
* The {@link WebClientDriver} object is always created by {@link WebServer} class. When you got this
* {@link WebClientDriver} object from the {@link WebServer.addClient WebServer.addClient()}, then specify
* {@link IProtocol listener} with the {@link WebClientDriver.listen WebClientDriver.listen()} method. Below code is an
* example specifying and managing the {@link IProtocol listener} objects.
*
* - https://github.com/samchon/framework/blob/master/ts/examples/calculator/calculator-server.ts
*
* Protocol | Derived Type | Created By
* ------------------------|-------------------------|-------------------
* Samchon Framework's own | {@link ClientDriver} | {@link Server}
* Web-socket protocol | {@link WebClientDriver} | {@link WebServer}
*
* Unlike other protocol, Web-socket protocol's clients notify two parameters on their connection;
* {@link getSessionID session-id} and {@link getPath path}. The {@link getSessionID session-id} can be used to
* identify *user* of each client, and the {@link getPath path} can be used which type of *service* that client wants.
* In {@link service} module, you can see the best utilization case of them.
*
* - {@link service.User}: utlization of the {@link getSessionID session-id}.
* - {@link service.Service}: utilization of the {@link getPath path}.
*
* 
*
* @see {@link WebServer}, {@link IProtocol}
* @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/CPP-Protocol-Basic_Components#clientdriver)
* @author Jeongho Nam <http://samchon.org>
*/
class WebClientDriver
: public ClientDriver,
public WebCommunicator
{
friend class WebServer;
private:
typedef ClientDriver super;
std::string session_id;
std::string path;
public:
WebClientDriver(std::shared_ptr<boost::asio::ip::tcp::socket> socket)
: super(socket),
WebCommunicator(true)
{
};
virtual ~WebClientDriver() = default;
/**
* Get session ID, an identifier of the remote client.
*/
auto getSessionID() const -> std::string
{
return session_id;
};
/**
* Get requested path.
*/
auto getPath() const -> std::string
{
return path;
};
};
};
}; | betterwaysystems/packer | cpp/src/samchon/protocol/WebClientDriver.hpp | C++ | bsd-3-clause | 2,932 |
class TransferSpreeOrdersSignifydScoreData < ActiveRecord::Migration
disable_ddl_transaction!
def up
Spree::Order.connection.execute(<<-SQL)
insert into spree_signifyd_order_scores (order_id, score, created_at, updated_at)
select o.id, o.signifyd_score, '#{Time.now.to_s(:db)}', '#{Time.now.to_s(:db)}'
from spree_orders o
left join spree_signifyd_order_scores
on o.id = spree_signifyd_order_scores.order_id
where o.signifyd_score is not null -- where the order has a score...
and spree_signifyd_order_scores.id is null -- ...but the new table does not
SQL
end
end
| jordan-brough/solidus_signifyd | db/migrate/20150206193231_transfer_spree_orders_signifyd_score_data.rb | Ruby | bsd-3-clause | 624 |
/*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.feedback;
/**
* @author Morten Olav Hansen <mortenoh@gmail.com>
*/
public enum ErrorCode
{
/* General */
E1000( "API query must be specified" ),
E1001( "API query contains an illegal string" ),
E1002( "API version is invalid" ),
/* Basic metadata */
E1100( "Data element not found or not accessible: `{0}`" ),
E1101( "Period is invalid: `{0}`" ),
E1102( "Organisation unit not found or not accessible: `{0}`" ),
E1103( "Category option combo not found or not accessible: `{0}`" ),
E1104( "Attribute option combo not found or not accessible: `{0}`" ),
E1105( "Data set not found or not accessible: `{0}`" ),
E1106( "There are duplicate translation record for property `{0}` and locale `{1}`" ),
E1107( "Object type `{0}` is not translatable." ),
E1108( "Could not add item to collection: {0}" ),
E1109( "Could not remove item from collection: {0}" ),
/* Org unit merge */
E1500( "At least two source orgs unit must be specified" ),
E1501( "Target org unit must be specified" ),
E1502( "Target org unit cannot be a source org unit" ),
E1503( "Source org unit does not exist: `{0}`" ),
E1504( "Target org unit cannot be a descendant of a source org unit" ),
/* Org unit split */
E1510( "Source org unit must be specified" ),
E1511( "At least two target org units must be specified" ),
E1512( "Source org unit cannot be a target org unit" ),
E1513( "Primary target must be specified" ),
E1514( "Primary target must be a target org unit" ),
E1515( "Target org unit does not exist: `{0}`" ),
E1516( "Target org unit cannot be a descendant of the source org unit: `{0}`" ),
/* Org unit move */
E1520( "User `{0}` is not allowed to move organisation units" ),
E1521( "User `{0}` is not allowed to move organisation `{1}`" ),
E1522( "User `{0}` is not allowed to move organisation `{1}` unit from parent `{2}`" ),
E1523( "User `{0}` is not allowed to move organisation `{1}` unit to parent `{2}`" ),
/* Data */
E2000( "Query parameters cannot be null" ),
E2001( "At least one data element, data set or data element group must be specified" ),
E2002( "At least one period, start/end dates, last updated or last updated duration must be specified" ),
E2003( "Both periods and start/end date cannot be specified" ),
E2004( "Start date must be before end date" ),
E2005( "Duration is not valid: `{0}`" ),
E2006( "At least one organisation unit or organisation unit group must be specified" ),
E2007( "Organisation unit children cannot be included for organisation unit groups" ),
E2008( "At least one organisation unit must be specified when children are included" ),
E2009( "Limit cannot be less than zero: `{0}`" ),
E2010( "User is not allowed to read data for data set: `{0}`" ),
E2011( "User is not allowed to read data for attribute option combo: `{0}`" ),
E2012( "User is not allowed to view org unit: `{0}`" ),
E2013( "At least one data set must be specified" ),
E2014( "Unable to parse filter `{0}`" ),
E2015( "Unable to parse order param: `{0}`" ),
E2016( "Unable to parse element `{0}` on filter `{1}`. The values available are: {2}" ),
E2017( "Data set is locked" ),
E2018( "Category option combo is required but not specified" ),
E2019( "Organisation unit is closed for the selected period: `{0}`" ),
E2020( "Organisation unit is not in the hierarchy of the current user: `{0}`" ),
E2021( "Data set: `{0}` does not contain data element: `{1}`" ),
E2022( "Period: `{0}` is after latest open future period: `{1}` for data element: `{2}`" ),
E2023( "Period: `{0}` is before start date: {1} for attribute option: `{2}`" ),
E2024( "Period: `{0}` is after start date: {1} for attribute option: `{2}`" ),
E2025( "Period: `{0}` is not open for data set: `{1}`" ),
E2026( "File resource already assigned or linked to a data value" ),
E2027( "File resource is invalid: `{0}`" ),
E2028( "Comment is invalid: `{0}`" ),
E2029( "Data value is not a valid option of the data element option set: `{0}`" ),
E2030( "Data value must match data element value type: `{0}`" ),
E2031( "User does not have write access to category option combo: `{0}`" ),
E2032( "Data value does not exist" ),
E2033( "Follow-up must be specified" ),
E2034( "Filter not supported: `{0}`" ),
E2035( "Operator not supported: `{0}`" ),
E2036( "Combination not supported: `{0}`" ),
E2037( "Order not supported: `{0}`" ),
E2038( "Field not supported: `{0}`" ),
E2039( "StageOffset is allowed only for repeatable stages (`{0}` is not repeatable)" ),
/* Outlier detection */
E2200( "At least one data element must be specified" ),
E2201( "Start date and end date must be specified" ),
E2202( "Start date must be before end date" ),
E2203( "At least one organisation unit must be specified" ),
E2204( "Threshold must be a positive number" ),
E2205( "Max results must be a positive number" ),
E2206( "Max results exceeds the allowed max limit: `{0}`" ),
E2207( "Data start date must be before data end date" ),
E2208( "Non-numeric data values encountered during outlier value detection" ),
/* Followup analysis */
E2300( "At least one data element or data set must be specified" ),
E2301( "Start date and end date must be specified directly or indirectly by specifying a period" ),
/* Security */
E3000( "User `{0}` is not allowed to create objects of type {1}." ),
E3001( "User `{0}` is not allowed to update object `{1}`." ),
E3002( "User `{0}` is not allowed to delete object `{1}`." ),
E3003( "User `{0}` is not allowed to grant users access to user role `{1}`." ),
E3004( "User `{0}` is not allowed to grant users access to user groups." ),
E3005( "User `{0}` is not allowed to grant users access to user group `{1}`." ),
E3006( "User `{0}` is not allowed to externalize objects of type `{1}`." ),
E3008( "User `{0}` is not allowed to make public objects of type `{1}`." ),
E3009( "User `{0}` is not allowed to make private objects of type `{1}`." ),
E3010( "Invalid access string `{0}`." ),
E3011( "Data sharing is not enabled for type `{0}`, but access strings contain data sharing read or write." ),
E3012( "User `{0}` does not have read access for object `{1}`." ),
E3013( "Sharing settings of system default metadata object of type `{0}` cannot be modified." ),
E3014( "You do not have manage access to this object." ),
E3015( "Invalid public access string: `{0}`" ),
E3016( "Data sharing is not enabled for this object" ),
E3017( "Invalid user group access string: `{0}`" ),
E3018( "Invalid user access string: `{0}`" ),
E3019( "Sharing is not enabled for this object `{0}`" ),
/* Metadata Validation */
E4000( "Missing required property `{0}`." ),
E4001( "Maximum length of property `{0}`is {1}, but given length was {2}." ),
E4002( "Allowed length range for property `{0}` is [{1} to {2}], but given length was {3}." ),
E4003( "Property `{0}` requires a valid email address, was given `{1}`." ),
E4004( "Property `{0}` requires a valid URL, was given `{1}`." ),
E4005( "Property `{0}` requires a valid password, was given `{1}`." ),
E4006( "Property `{0}` requires a valid HEX color, was given `{1}`." ),
E4007( "Allowed size range for collection property `{0}` is [{1} to {2}], but size given was {3}." ),
E4008( "Allowed range for numeric property `{0}` is [{1} to {2}], but number given was {3}." ),
E4009( "Attribute `{0}` is unique, and value `{1}` already exist." ),
E4010( "Attribute `{0}` is not supported for type `{1}`." ),
E4011( "Attribute `{0}` is required, but no value was found." ),
E4012( "Attribute `{0}` contains elements of different period type than the data set it was added to" ),
E4013( "Invalid Closing date `{0}`, must be after Opening date `{1}`" ),
E4014( "Invalid UID `{0}` for property `{1}`" ),
E4015( "Property `{0}` refers to an object that does not exist, could not find `{1}`" ),
E4016( "Object referenced by the `{0}` property is already associated with another object, value: `{1}`" ),
E4017( "RenderingType `{0}` is not supported for ValueType `{1}`" ),
E4018( "Property `{0}` must be set when property `{1}` is `{2}`" ),
E4019( "Failed to parse pattern `{0}`. {1}" ),
E4020( "The value `{0}` does not conform to the attribute pattern `{1}`" ),
E4021( "ID-pattern is required to have 1 generated segment (RANDOM or SEQUENTIAL)." ),
E4022( "Pattern `{0}` does not conform to the value type `{1}`." ),
E4023( "Property `{0}` can not be set when property `{1}` is `{2}`. " ),
E4024( "Property `{0}` must be set when property `{1}` is `{2}`. " ),
E4025( "Properties `{0}` and `{1}` are mutually exclusive and cannot be used together." ),
E4026( "One of the properties `{0}` and `{1}` is required when property `{2}` is `{3}`." ),
E4027( "Value `{0}` is not a valid for property `{1}`" ),
E4028( "Option set `{0}` already contains option `{1}`" ),
E4029( "Job parameters cannot be null for job type: {0}" ),
E4030( "Object could not be deleted because it is associated with another object: {0}" ),
E4031( "Property `{0}` requires a valid JSON payload, was given `{1}`." ),
E4032( "Patch path `{0}` is not supported." ),
/* ProgramRuleAction validation */
E4033( "A program rule action of type `{0}` associated with program rule name `{1}` is invalid" ),
E4034( "ProgramNotificationTemplate `{0}` associated with program rule name `{1}` does not exist" ),
E4035( "ProgramNotificationTemplate cannot be null for program rule name `{0}`" ),
E4036( "ProgramStageSection cannot be null for program rule `{0}`" ),
E4037( "ProgramStageSection `{0}` associated with program rule `{1}` does not exist" ),
E4038( "ProgramStage cannot be null for program rule `{0}`" ),
E4039( "ProgramStage `{0}` associated with program rule `{1}` does not exist" ),
E4040( "Option cannot be null for program rule `{0}`" ),
E4041( "Option `{0}` associated with program rule `{1}` does not exist" ),
E4042( "OptionGroup cannot be null for program rule `{0}`" ),
E4043( "OptionGroup `{0}` associated with program rule `{1}` does not exist" ),
E4044( "DataElement or TrackedEntityAttribute cannot be null for program rule `{0}`" ),
E4045( "DataElement `{0}` associated with program rule `{1}` does not exist" ),
E4046( "TrackedEntityAttribute `{0}` associated with program rule `{1}` does not exist" ),
E4047( "DataElement `{0}` is not linked to any ProgramStageDataElement for program rule `{1}`" ),
E4048( "TrackedEntityAttribute `{0}` is not linked to ProgramTrackedEntityAttribute for program rule `{1}`" ),
E4049( "Property `{0}` requires a valid username, was given `{1}`." ),
E4050(
"One of the parameters DataElement, TrackedEntityAttribute or ProgramRuleVariable is required for program rule `{0}`" ),
/* ProgramRuleVariable validation */
E4051( "A program rule variable with name `{0}` and program uid `{1}` already exists" ),
E4052( "For program rule variable with name `{0}` following keywords are forbidden : and , or , not" ),
E4053( "Program stage `{0}` must reference a program." ),
/* SQL views */
E4300( "SQL query is null" ),
E4301( "SQL query must be a select query" ),
E4302( "SQL query can only contain a single semi-colon at the end of the query" ),
E4303( "Variables contain null key" ),
E4304( "Variables contain null value" ),
E4305( "Variable params are invalid: `{0}`" ),
E4306( "Variables are invalid: `{0}`" ),
E4307( "SQL query contains variables not provided in request: `{0}`" ),
E4308( "Criteria params are invalid: `{0}`" ),
E4309( "Criteria values are invalid: `{0}`" ),
E4310( "SQL query contains references to protected tables" ),
E4311( "SQL query contains illegal keywords" ),
E4312( "Current user is not authorised to read data from SQL view: `{0}`" ),
E4313( "SQL query contains variable names that are invalid: `{0}`" ),
E4314( "Provided `{0}`: (`{1}`) are not part of the selected `{2}`" ),
/* Preheat */
E5000( "Found matching object for reference, but import mode is CREATE. Identifier was {0}, and object was {1}." ),
E5001( "No matching object for reference. Identifier was {0}, and object was {1}." ),
E5002( "Invalid reference {0} on object {1} for association `{2}`." ),
E5003( "Property `{0}` with value `{1}` on object {2} already exists on object {3}." ),
E5004( "Id `{0}` for type `{1}` exists on more than 1 object in the payload, removing all but the first found." ),
E5005( "Properties `{0}` in objects `{1}` must be unique within the payload" ),
E5006(
"Non owner reference {0} on object {1} for association `{2}` is not allowed within payload for ERRORS_NOT_OWNER" ),
/* Metadata import */
E6000( "Program `{0}` has more than one Program Instances" ),
E6001( "ProgramStage `{0}` has invalid next event scheduling property `{1}`. " +
"This property need to be data element of value type date and belong the program stage." ),
E6002( "Class name {0} is not supported." ),
E6003( "Could not patch object with id {0}." ),
E6004( "Attribute `{0}` has invalid GeoJson value." ),
E6005( "Attribute `{0}` has unsupported GeoJson value." ),
/* File resource */
E6100( "Filename not present" ),
E6101( "File type not allowed" ),
/* Users */
E6200( "Feedback message recipients user group not defined" ),
/* Scheduling */
E7000( "Job of same type already scheduled with cron expression: `{0}`" ),
E7003( "Only interval property can be configured for non configurable job type: `{0}`" ),
E7004( "Cron expression must be not null for job with scheduling type CRON: `{0}`" ),
E7005( "Cron expression is invalid for job: `{0}` " ),
E7006( "Failed to execute job: `{0}`." ),
E7007( "Delay must be not null for job with scheduling type FIXED_DELAY: `{0}`" ),
E7010( "Failed to validate job runtime: `{0}`" ),
/* Aggregate analytics */
E7100( "Query parameters cannot be null" ),
E7101( "At least one dimension must be specified" ),
E7102( "At least one data dimension item or data element group set dimension item must be specified" ),
E7103( "Dimensions cannot be specified as dimension and filter simultaneously: `{0}`" ),
E7104( "At least one period as dimension or filter, or start and dates, must be specified" ),
E7105( "Periods and start and end dates cannot be specified simultaneously" ),
E7106( "Start date cannot be after end date" ),
E7107( "Start and end dates cannot be specified for reporting rates" ),
E7108( "Only a single indicator can be specified as filter" ),
E7109( "Only a single reporting rate can be specified as filter" ),
E7110( "Category option combos cannot be specified as filter" ),
E7111( "Dimensions cannot be specified more than once: `{0}`" ),
E7112( "Reporting rates can only be specified together with dimensions of type: `{0}`" ),
E7113( "Assigned categories cannot be specified when data elements are not specified" ),
E7114( "Assigned categories can only be specified together with data elements" ),
E7115( "Data elements must be of a value and aggregation type that allow aggregation: `{0}`" ),
E7116( "Indicator expressions cannot contain cyclic references: `{0}`" ),
E7117( "A data dimension 'dx' must be specified when output format is DATA_VALUE_SET" ),
E7118( "A period dimension 'pe' must be specified when output format is DATA_VALUE_SET" ),
E7119( "An organisation unit dimension 'ou' must be specified when output format is DATA_VALUE_SET" ),
E7120( "User: `{0}` is not allowed to view org unit: `{1}`" ),
E7121( "User: `{0}` is not allowed to read data for `{1}`: `{2}`" ),
E7122( "Data approval level does not exist: `{0}`" ),
E7123( "Current user is constrained by a dimension but has access to no dimension items: `{0}`" ),
E7124( "Dimension is present in query without any valid dimension options: `{0}`" ),
E7125( "Dimension identifier does not reference any dimension: `{0}`" ),
E7126( "Column must be present as dimension in query: `{0}`" ),
E7127( "Row must be present as dimension in query: `{0}`" ),
E7128( "Query result set exceeded max limit: `{0}`" ),
E7129( "Program is specified but does not exist: `{0}`" ),
E7130( "Program stage is specified but does not exist: `{0}`" ),
E7131( "Query failed, likely because the query timed out" ),
E7132( "An indicator expression caused division by zero operation" ),
E7133( "Query cannot be executed, possibly because of invalid types or invalid operation" ),
E7134( "Cannot retrieve total value for data elements with skip total category combination" ),
/* Event analytics */
E7200( "At least one organisation unit must be specified" ),
E7201( "Dimensions cannot be specified more than once: `{0}`" ),
E7202( "Query items cannot be specified more than once: `{0}`" ),
E7203( "Value dimension cannot also be specified as an item or item filter" ),
E7204( "Value dimension or aggregate data must be specified when aggregation type is specified" ),
E7205( "Start and end date or at least one period must be specified" ),
E7206( "Start date is after end date: `{0}`, `{1}`" ),
E7207( "Page number must be a positive number: `{0}`" ),
E7208( "Page size must be zero or a positive number: `{0}`" ),
E7209( "Limit is larger than max limit: `{0}`, `{1}`" ),
E7210( "Time field is invalid: `{0}`" ),
E7211( "Org unit field is invalid: `{0}`" ),
E7212( "Cluster size must be a positive number: `{0}`" ),
E7213( "Bbox is invalid, must be on format: 'min-lng,min-lat,max-lng,max-lat': `{0}`" ),
E7214( "Cluster field must be specified when bbox or cluster size are specified" ),
E7215( "Query item cannot specify both legend set and option set: `{0}`" ),
E7216( "Query item must be aggregateable when used in aggregate query: `{0}`" ),
E7217( "User is not allowed to view event analytics data: `{0}`" ),
E7218( "Spatial database support is not enabled" ),
E7219( "Data element must be of value type coordinate or org unit to be used as coordinate field: `{0}`" ),
E7220( "Attribute must be of value type coordinate or org unit to be used as coordinate field: `{0}`" ),
E7221( "Coordinate field is invalid: `{0}`" ),
E7222( "Query item or filter is invalid: `{0}`" ),
E7223( "Value does not refer to a data element or attribute which are numeric and part of the program: `{0}`" ),
E7224( "Item identifier does not reference any data element, attribute or indicator part of the program: `{0}`" ),
E7225( "Program stage is mandatory for data element dimensions in enrollment analytics queries: `{0}`" ),
E7226( "Dimension is not a valid query item: `{0}`" ),
E7227( "Relationship entity type not supported: `{0}`" ),
E7228( "Fallback coordinate field is invalid: `{0}` " ),
E7229( "Operator `{0}` does not allow missing value" ),
E7230( "Header param `{0}` does not exist" ),
E7231( "Legacy `{0}` can be updated only through event visualizations" ),
/* Org unit analytics */
E7300( "At least one organisation unit must be specified" ),
E7301( "At least one organisation unit group set must be specified" ),
/* Debug analytics */
E7400( "Debug query must contain at least one data element, one period and one organisation unit" ),
/* Validation Results API */
E7500( "Organisation unit does not exist: `{0}`" ),
E7501( "Validation rule does not exist: `{0}`" ),
E7502( "Filter for period is not valid: `{0}`" ),
E7503( "Filter for created date period is not valid: `{0}`" ),
/* Data import validation */
// Data Set validation
E7600( "Data set not found or not accessible: `{0}`" ),
E7601( "User does not have write access for DataSet: `{0}`" ),
E7602( "A valid dataset is required" ),
E7603( "Org unit not found or not accessible: `{0}`" ),
E7604( "Attribute option combo not found or not accessible: `{0}`" ),
// Data Value validation
E7610( "Data element not found or not accessible: `{0}`" ),
E7611( "Period not valid: `{0}`" ),
E7612( "Organisation unit not found or not accessible: `{0}`" ),
E7613( "Category option combo not found or not accessible for writing data: `{0}`" ),
E7614( "Category option combo: `{0}` option not accessible: `{1}`" ),
E7615( "Attribute option combo not found or not accessible for writing data: `{0}`" ),
E7616( "Attribute option combo: `{0}` option not accessible: `{1}`" ),
E7617( "Organisation unit: `{0}` not in hierarchy of current user: `{1}`" ),
E7618( "Data value or comment not specified for data element: `{0}`" ),
E7619( "Value must match data element''s `{0}` type constraints: {1}" ),
E7620( "Invalid comment: {0}" ),
E7621( "Data value is not a valid option of the data element option set: `{0}`" ),
// Data Value constraints
E7630( "Category option combo is required but is not specified" ),
E7631( "Attribute option combo is required but is not specified" ),
E7632( "Period type of period: `{0}` not valid for data element: `{1}`" ),
E7633( "Data element: `{0}` is not part of dataset: `{1}`" ),
E7634( "Category option combo: `{0}` must be part of category combo of data element: `{1}`" ),
E7635( "Attribute option combo: `{0}` must be part of category combo of data sets of data element: `{1}`" ),
E7636( "Data element: `{1}` must be assigned through data sets to organisation unit: `{0}`" ),
E7637( "Invalid storedBy: {0}" ),
E7638( "Period: `{0}` is not within date range of attribute option combo: `{1}`" ),
E7639( "Organisation unit: `{0}` is not valid for attribute option combo: `{1}`" ),
E7640( "Current date is past expiry days for period: `{0}` and data set: `{1}`" ),
E7641( "Period: `{0}` is after latest open future period: `{2}` for data element: `{1}`" ),
E7642(
"Data is already approved for data set: `{3}` period: `{1}` organisation unit: `{0}` attribute option combo: `{2}`" ),
E7643( "Period: `{0}` is not open for this data set at this time: `{1}`" ),
E7644( "Period: `{0}` does not conform to the open periods of associated data sets" ),
E7645( "No data value for file resource exist for the given combination for data element: `{0}`" ),
// datastore query validation
E7650( "Not a valid path: `{0}`" ),
E7651( "Illegal fields expression. Expected `,`, `[` or `]` at position {0} but found `{1}`" ),
E7652( "Illegal filter expression `{0}`: {1}" ),
E7653( "Illegal filter `{0}`: {1}" );
private String message;
ErrorCode( String message )
{
this.message = message;
}
public String getMessage()
{
return message;
}
}
| dhis2/dhis2-core | dhis-2/dhis-api/src/main/java/org/hisp/dhis/feedback/ErrorCode.java | Java | bsd-3-clause | 24,795 |
# -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""The spm module provides basic functions for interfacing with matlab
and spm to access spm tools.
Change directory to provide relative paths for doctests
>>> import os
>>> filepath = os.path.dirname( os.path.realpath( __file__ ) )
>>> datadir = os.path.realpath(os.path.join(filepath, '../../testing/data'))
>>> os.chdir(datadir)
"""
from __future__ import print_function, division, unicode_literals, absolute_import
from builtins import str, bytes
# Standard library imports
import os
from glob import glob
# Third-party imports
import numpy as np
import scipy.io as sio
# Local imports
from ... import logging
from ...utils.filemanip import (filename_to_list, list_to_filename,
split_filename)
from ..base import (Bunch, traits, TraitedSpec, File, Directory,
OutputMultiPath, InputMultiPath, isdefined)
from .base import (SPMCommand, SPMCommandInputSpec,
scans_for_fnames, ImageFileSPM)
__docformat__ = 'restructuredtext'
logger = logging.getLogger('interface')
class Level1DesignInputSpec(SPMCommandInputSpec):
spm_mat_dir = Directory(exists=True, field='dir',
desc='directory to store SPM.mat file (opt)')
timing_units = traits.Enum('secs', 'scans', field='timing.units',
desc='units for specification of onsets',
mandatory=True)
interscan_interval = traits.Float(field='timing.RT',
desc='Interscan interval in secs',
mandatory=True)
microtime_resolution = traits.Int(field='timing.fmri_t',
desc=('Number of time-bins per scan '
'in secs (opt)'))
microtime_onset = traits.Float(field='timing.fmri_t0',
desc=('The onset/time-bin in seconds for '
'alignment (opt)'))
session_info = traits.Any(field='sess',
desc=('Session specific information generated '
'by ``modelgen.SpecifyModel``'),
mandatory=True)
factor_info = traits.List(traits.Dict(traits.Enum('name', 'levels')),
field='fact',
desc=('Factor specific information '
'file (opt)'))
bases = traits.Dict(traits.Enum('hrf', 'fourier', 'fourier_han',
'gamma', 'fir'), field='bases', desc="""
dict {'name':{'basesparam1':val,...}}
name : string
Name of basis function (hrf, fourier, fourier_han,
gamma, fir)
hrf :
derivs : 2-element list
Model HRF Derivatives. No derivatives: [0,0],
Time derivatives : [1,0], Time and Dispersion
derivatives: [1,1]
fourier, fourier_han, gamma, fir:
length : int
Post-stimulus window length (in seconds)
order : int
Number of basis functions
""", mandatory=True)
volterra_expansion_order = traits.Enum(1, 2, field='volt',
desc=('Model interactions - '
'yes:1, no:2'))
global_intensity_normalization = traits.Enum('none', 'scaling',
field='global',
desc=('Global intensity '
'normalization - '
'scaling or none'))
mask_image = File(exists=True, field='mask',
desc='Image for explicitly masking the analysis')
mask_threshold = traits.Either(traits.Enum('-Inf'), traits.Float(),
desc="Thresholding for the mask",
default='-Inf', usedefault=True)
model_serial_correlations = traits.Enum('AR(1)', 'FAST', 'none',
field='cvi',
desc=('Model serial correlations '
'AR(1), FAST or none. FAST '
'is available in SPM12'))
class Level1DesignOutputSpec(TraitedSpec):
spm_mat_file = File(exists=True, desc='SPM mat file')
class Level1Design(SPMCommand):
"""Generate an SPM design matrix
http://www.fil.ion.ucl.ac.uk/spm/doc/manual.pdf#page=59
Examples
--------
>>> level1design = Level1Design()
>>> level1design.inputs.timing_units = 'secs'
>>> level1design.inputs.interscan_interval = 2.5
>>> level1design.inputs.bases = {'hrf':{'derivs': [0,0]}}
>>> level1design.inputs.session_info = 'session_info.npz'
>>> level1design.run() # doctest: +SKIP
"""
input_spec = Level1DesignInputSpec
output_spec = Level1DesignOutputSpec
_jobtype = 'stats'
_jobname = 'fmri_spec'
def _format_arg(self, opt, spec, val):
"""Convert input to appropriate format for spm
"""
if opt in ['spm_mat_dir', 'mask_image']:
return np.array([str(val)], dtype=object)
if opt in ['session_info']: # , 'factor_info']:
if isinstance(val, dict):
return [val]
else:
return val
return super(Level1Design, self)._format_arg(opt, spec, val)
def _parse_inputs(self):
"""validate spm realign options if set to None ignore
"""
einputs = super(Level1Design, self)._parse_inputs(
skip=('mask_threshold'))
for sessinfo in einputs[0]['sess']:
sessinfo['scans'] = scans_for_fnames(
filename_to_list(sessinfo['scans']), keep4d=False)
if not isdefined(self.inputs.spm_mat_dir):
einputs[0]['dir'] = np.array([str(os.getcwd())], dtype=object)
return einputs
def _make_matlab_command(self, content):
"""validates spm options and generates job structure
if mfile is True uses matlab .m file
else generates a job structure and saves in .mat
"""
if isdefined(self.inputs.mask_image):
# SPM doesn't handle explicit masking properly, especially
# when you want to use the entire mask image
postscript = "load SPM;\n"
postscript += ("SPM.xM.VM = spm_vol('%s');\n"
% list_to_filename(self.inputs.mask_image))
postscript += "SPM.xM.I = 0;\n"
postscript += "SPM.xM.T = [];\n"
postscript += ("SPM.xM.TH = ones(size(SPM.xM.TH))*(%s);\n"
% self.inputs.mask_threshold)
postscript += ("SPM.xM.xs = struct('Masking', "
"'explicit masking only');\n")
postscript += "save SPM SPM;\n"
else:
postscript = None
return super(Level1Design, self)._make_matlab_command(
content, postscript=postscript)
def _list_outputs(self):
outputs = self._outputs().get()
spm = os.path.join(os.getcwd(), 'SPM.mat')
outputs['spm_mat_file'] = spm
return outputs
class EstimateModelInputSpec(SPMCommandInputSpec):
spm_mat_file = File(exists=True, field='spmmat',
copyfile=True, mandatory=True,
desc='Absolute path to SPM.mat')
estimation_method = traits.Dict(
traits.Enum('Classical', 'Bayesian2', 'Bayesian'),
field='method', mandatory=True,
desc=('Dictionary of either Classical: 1, Bayesian: 1, '
'or Bayesian2: 1 (dict)'))
write_residuals = traits.Bool(field='write_residuals',
desc="Write individual residual images")
flags = traits.Dict(desc='Additional arguments')
class EstimateModelOutputSpec(TraitedSpec):
mask_image = ImageFileSPM(exists=True,
desc='binary mask to constrain estimation')
beta_images = OutputMultiPath(ImageFileSPM(exists=True),
desc='design parameter estimates')
residual_image = ImageFileSPM(exists=True,
desc='Mean-squared image of the residuals')
residual_images = OutputMultiPath(ImageFileSPM(exists=True),
desc="individual residual images (requires `write_residuals`")
RPVimage = ImageFileSPM(exists=True, desc='Resels per voxel image')
spm_mat_file = File(exists=True, desc='Updated SPM mat file')
labels = ImageFileSPM(exists=True, desc="label file")
SDerror = OutputMultiPath(ImageFileSPM(exists=True),
desc="Images of the standard deviation of the error")
ARcoef = OutputMultiPath(ImageFileSPM(exists=True),
desc="Images of the AR coefficient")
Cbetas = OutputMultiPath(ImageFileSPM(exists=True),
desc="Images of the parameter posteriors")
SDbetas = OutputMultiPath(ImageFileSPM(exists=True),
desc="Images of the standard deviation of parameter posteriors")
class EstimateModel(SPMCommand):
"""Use spm_spm to estimate the parameters of a model
http://www.fil.ion.ucl.ac.uk/spm/doc/manual.pdf#page=69
Examples
--------
>>> est = EstimateModel()
>>> est.inputs.spm_mat_file = 'SPM.mat'
>>> est.inputs.estimation_method = {'Classical': 1}
>>> est.run() # doctest: +SKIP
"""
input_spec = EstimateModelInputSpec
output_spec = EstimateModelOutputSpec
_jobtype = 'stats'
_jobname = 'fmri_est'
def _format_arg(self, opt, spec, val):
"""Convert input to appropriate format for spm
"""
if opt == 'spm_mat_file':
return np.array([str(val)], dtype=object)
if opt == 'estimation_method':
if isinstance(val, (str, bytes)):
return {'{}'.format(val): 1}
else:
return val
return super(EstimateModel, self)._format_arg(opt, spec, val)
def _parse_inputs(self):
"""validate spm realign options if set to None ignore
"""
einputs = super(EstimateModel, self)._parse_inputs(skip=('flags'))
if isdefined(self.inputs.flags):
einputs[0].update({flag: val for (flag, val) in
self.inputs.flags.items()})
return einputs
def _list_outputs(self):
outputs = self._outputs().get()
pth = os.path.dirname(self.inputs.spm_mat_file)
outtype = 'nii' if '12' in self.version.split('.')[0] else 'img'
spm = sio.loadmat(self.inputs.spm_mat_file, struct_as_record=False)
betas = [vbeta.fname[0] for vbeta in spm['SPM'][0, 0].Vbeta[0]]
if ('Bayesian' in self.inputs.estimation_method.keys() or
'Bayesian2' in self.inputs.estimation_method.keys()):
outputs['labels'] = os.path.join(pth,
'labels.{}'.format(outtype))
outputs['SDerror'] = glob(os.path.join(pth, 'Sess*_SDerror*'))
outputs['ARcoef'] = glob(os.path.join(pth, 'Sess*_AR_*'))
if betas:
outputs['Cbetas'] = [os.path.join(pth, 'C{}'.format(beta))
for beta in betas]
outputs['SDbetas'] = [os.path.join(pth, 'SD{}'.format(beta))
for beta in betas]
if 'Classical' in self.inputs.estimation_method.keys():
outputs['residual_image'] = os.path.join(pth,
'ResMS.{}'.format(outtype))
outputs['RPVimage'] = os.path.join(pth,
'RPV.{}'.format(outtype))
if self.inputs.write_residuals:
outputs['residual_images'] = glob(os.path.join(pth, 'Res_*'))
if betas:
outputs['beta_images'] = [os.path.join(pth, beta)
for beta in betas]
outputs['mask_image'] = os.path.join(pth,
'mask.{}'.format(outtype))
outputs['spm_mat_file'] = os.path.join(pth, 'SPM.mat')
return outputs
class EstimateContrastInputSpec(SPMCommandInputSpec):
spm_mat_file = File(exists=True, field='spmmat',
desc='Absolute path to SPM.mat',
copyfile=True,
mandatory=True)
contrasts = traits.List(
traits.Either(traits.Tuple(traits.Str,
traits.Enum('T'),
traits.List(traits.Str),
traits.List(traits.Float)),
traits.Tuple(traits.Str,
traits.Enum('T'),
traits.List(traits.Str),
traits.List(traits.Float),
traits.List(traits.Float)),
traits.Tuple(traits.Str,
traits.Enum('F'),
traits.List(traits.Either(
traits.Tuple(traits.Str,
traits.Enum('T'),
traits.List(traits.Str),
traits.List(traits.Float)),
traits.Tuple(traits.Str,
traits.Enum('T'),
traits.List(traits.Str),
traits.List(traits.Float),
traits.List(
traits.Float)))))),
desc="""List of contrasts with each contrast being a list of the form:
[('name', 'stat', [condition list], [weight list], [session list])]
If session list is None or not provided, all sessions are used. For
F contrasts, the condition list should contain previously defined
T-contrasts.""",
mandatory=True)
beta_images = InputMultiPath(File(exists=True),
desc=('Parameter estimates of the '
'design matrix'),
copyfile=False,
mandatory=True)
residual_image = File(exists=True,
desc='Mean-squared image of the residuals',
copyfile=False,
mandatory=True)
use_derivs = traits.Bool(desc='use derivatives for estimation',
xor=['group_contrast'])
group_contrast = traits.Bool(desc='higher level contrast',
xor=['use_derivs'])
class EstimateContrastOutputSpec(TraitedSpec):
con_images = OutputMultiPath(File(exists=True),
desc='contrast images from a t-contrast')
spmT_images = OutputMultiPath(File(exists=True),
desc='stat images from a t-contrast')
ess_images = OutputMultiPath(File(exists=True),
desc='contrast images from an F-contrast')
spmF_images = OutputMultiPath(File(exists=True),
desc='stat images from an F-contrast')
spm_mat_file = File(exists=True, desc='Updated SPM mat file')
class EstimateContrast(SPMCommand):
"""Use spm_contrasts to estimate contrasts of interest
Examples
--------
>>> import nipype.interfaces.spm as spm
>>> est = spm.EstimateContrast()
>>> est.inputs.spm_mat_file = 'SPM.mat'
>>> cont1 = ('Task>Baseline','T', ['Task-Odd','Task-Even'],[0.5,0.5])
>>> cont2 = ('Task-Odd>Task-Even','T', ['Task-Odd','Task-Even'],[1,-1])
>>> contrasts = [cont1,cont2]
>>> est.inputs.contrasts = contrasts
>>> est.run() # doctest: +SKIP
"""
input_spec = EstimateContrastInputSpec
output_spec = EstimateContrastOutputSpec
_jobtype = 'stats'
_jobname = 'con'
def _make_matlab_command(self, _):
"""validates spm options and generates job structure
"""
contrasts = []
cname = []
for i, cont in enumerate(self.inputs.contrasts):
cname.insert(i, cont[0])
contrasts.insert(i, Bunch(name=cont[0],
stat=cont[1],
conditions=cont[2],
weights=None,
sessions=None))
if len(cont) >= 4:
contrasts[i].weights = cont[3]
if len(cont) >= 5:
contrasts[i].sessions = cont[4]
script = "% generated by nipype.interfaces.spm\n"
script += "spm_defaults;\n"
script += ("jobs{1}.stats{1}.con.spmmat = {'%s'};\n"
% self.inputs.spm_mat_file)
script += "load(jobs{1}.stats{1}.con.spmmat{:});\n"
script += "SPM.swd = '%s';\n" % os.getcwd()
script += "save(jobs{1}.stats{1}.con.spmmat{:},'SPM');\n"
script += "names = SPM.xX.name;\n"
# get names for columns
if (isdefined(self.inputs.group_contrast) and
self.inputs.group_contrast):
script += "condnames=names;\n"
else:
if self.inputs.use_derivs:
script += "pat = 'Sn\([0-9]*\) (.*)';\n"
else:
script += ("pat = 'Sn\([0-9]*\) (.*)\*bf\(1\)|Sn\([0-9]*\) "
".*\*bf\([2-9]\)|Sn\([0-9]*\) (.*)';\n")
script += "t = regexp(names,pat,'tokens');\n"
# get sessidx for columns
script += "pat1 = 'Sn\(([0-9].*)\)\s.*';\n"
script += "t1 = regexp(names,pat1,'tokens');\n"
script += ("for i0=1:numel(t),condnames{i0}='';condsess(i0)=0;if "
"~isempty(t{i0}{1}),condnames{i0} = t{i0}{1}{1};"
"condsess(i0)=str2num(t1{i0}{1}{1});end;end;\n")
# BUILD CONTRAST SESSION STRUCTURE
for i, contrast in enumerate(contrasts):
if contrast.stat == 'T':
script += ("consess{%d}.tcon.name = '%s';\n"
% (i + 1, contrast.name))
script += ("consess{%d}.tcon.convec = zeros(1,numel(names));\n"
% (i + 1))
for c0, cond in enumerate(contrast.conditions):
script += ("idx = strmatch('%s',condnames,'exact');\n"
% (cond))
script += (("if isempty(idx), throw(MException("
"'CondName:Chk', sprintf('Condition %%s not "
"found in design','%s'))); end;\n") % cond)
if contrast.sessions:
for sno, sw in enumerate(contrast.sessions):
script += ("sidx = find(condsess(idx)==%d);\n"
% (sno + 1))
script += (("consess{%d}.tcon.convec(idx(sidx)) "
"= %f;\n")
% (i + 1, sw * contrast.weights[c0]))
else:
script += ("consess{%d}.tcon.convec(idx) = %f;\n"
% (i + 1, contrast.weights[c0]))
for i, contrast in enumerate(contrasts):
if contrast.stat == 'F':
script += ("consess{%d}.fcon.name = '%s';\n"
% (i + 1, contrast.name))
for cl0, fcont in enumerate(contrast.conditions):
try:
tidx = cname.index(fcont[0])
except:
Exception("Contrast Estimate: could not get index of"
" T contrast. probably not defined prior "
"to the F contrasts")
script += (("consess{%d}.fcon.convec{%d} = "
"consess{%d}.tcon.convec;\n")
% (i + 1, cl0 + 1, tidx + 1))
script += "jobs{1}.stats{1}.con.consess = consess;\n"
script += ("if strcmp(spm('ver'),'SPM8'), spm_jobman('initcfg');"
"jobs=spm_jobman('spm5tospm8',{jobs});end\n")
script += "spm_jobman('run',jobs);"
return script
def _list_outputs(self):
outputs = self._outputs().get()
pth, _ = os.path.split(self.inputs.spm_mat_file)
spm = sio.loadmat(self.inputs.spm_mat_file, struct_as_record=False)
con_images = []
spmT_images = []
for con in spm['SPM'][0, 0].xCon[0]:
con_images.append(str(os.path.join(pth, con.Vcon[0, 0].fname[0])))
spmT_images.append(str(os.path.join(pth, con.Vspm[0, 0].fname[0])))
if con_images:
outputs['con_images'] = con_images
outputs['spmT_images'] = spmT_images
spm12 = '12' in self.version.split('.')[0]
if spm12:
ess = glob(os.path.join(pth, 'ess*.nii'))
else:
ess = glob(os.path.join(pth, 'ess*.img'))
if len(ess) > 0:
outputs['ess_images'] = sorted(ess)
if spm12:
spmf = glob(os.path.join(pth, 'spmF*.nii'))
else:
spmf = glob(os.path.join(pth, 'spmF*.img'))
if len(spmf) > 0:
outputs['spmF_images'] = sorted(spmf)
outputs['spm_mat_file'] = self.inputs.spm_mat_file
return outputs
class ThresholdInputSpec(SPMCommandInputSpec):
spm_mat_file = File(exists=True, desc='absolute path to SPM.mat',
copyfile=True, mandatory=True)
stat_image = File(exists=True, desc='stat image',
copyfile=False, mandatory=True)
contrast_index = traits.Int(mandatory=True,
desc='which contrast in the SPM.mat to use')
use_fwe_correction = traits.Bool(True, usedefault=True,
desc=('whether to use FWE (Bonferroni) '
'correction for initial threshold '
'(height_threshold_type has to be '
'set to p-value)'))
use_topo_fdr = traits.Bool(True, usedefault=True,
desc=('whether to use FDR over cluster extent '
'probabilities'))
height_threshold = traits.Float(0.05, usedefault=True,
desc=('value for initial thresholding '
'(defining clusters)'))
height_threshold_type = traits.Enum('p-value', 'stat', usedefault=True,
desc=('Is the cluster forming '
'threshold a stat value or '
'p-value?'))
extent_fdr_p_threshold = traits.Float(0.05, usedefault=True,
desc=('p threshold on FDR corrected '
'cluster size probabilities'))
extent_threshold = traits.Int(0, usedefault=True,
desc='Minimum cluster size in voxels')
force_activation = traits.Bool(False, usedefault=True,
desc=('In case no clusters survive the '
'topological inference step this '
'will pick a culster with the highes '
'sum of t-values. Use with care.'))
class ThresholdOutputSpec(TraitedSpec):
thresholded_map = File(exists=True)
n_clusters = traits.Int()
pre_topo_fdr_map = File(exists=True)
pre_topo_n_clusters = traits.Int()
activation_forced = traits.Bool()
cluster_forming_thr = traits.Float()
class Threshold(SPMCommand):
"""Topological FDR thresholding based on cluster extent/size. Smoothness is
estimated from GLM residuals but is assumed to be the same for all of the
voxels.
Examples
--------
>>> thresh = Threshold()
>>> thresh.inputs.spm_mat_file = 'SPM.mat'
>>> thresh.inputs.stat_image = 'spmT_0001.img'
>>> thresh.inputs.contrast_index = 1
>>> thresh.inputs.extent_fdr_p_threshold = 0.05
>>> thresh.run() # doctest: +SKIP
"""
input_spec = ThresholdInputSpec
output_spec = ThresholdOutputSpec
def _gen_thresholded_map_filename(self):
_, fname, ext = split_filename(self.inputs.stat_image)
return os.path.abspath(fname + "_thr" + ext)
def _gen_pre_topo_map_filename(self):
_, fname, ext = split_filename(self.inputs.stat_image)
return os.path.abspath(fname + "_pre_topo_thr" + ext)
def _make_matlab_command(self, _):
script = "con_index = %d;\n" % self.inputs.contrast_index
script += "cluster_forming_thr = %f;\n" % self.inputs.height_threshold
if self.inputs.use_fwe_correction:
script += "thresDesc = 'FWE';\n"
else:
script += "thresDesc = 'none';\n"
if self.inputs.use_topo_fdr:
script += "use_topo_fdr = 1;\n"
else:
script += "use_topo_fdr = 0;\n"
if self.inputs.force_activation:
script += "force_activation = 1;\n"
else:
script += "force_activation = 0;\n"
script += ("cluster_extent_p_fdr_thr = %f;\n"
% self.inputs.extent_fdr_p_threshold)
script += "stat_filename = '%s';\n" % self.inputs.stat_image
script += ("height_threshold_type = '%s';\n"
% self.inputs.height_threshold_type)
script += "extent_threshold = %d;\n" % self.inputs.extent_threshold
script += "load %s;\n" % self.inputs.spm_mat_file
script += """
FWHM = SPM.xVol.FWHM;
df = [SPM.xCon(con_index).eidf SPM.xX.erdf];
STAT = SPM.xCon(con_index).STAT;
R = SPM.xVol.R;
S = SPM.xVol.S;
n = 1;
switch thresDesc
case 'FWE'
cluster_forming_thr = spm_uc(cluster_forming_thr,df,STAT,R,n,S);
case 'none'
if strcmp(height_threshold_type, 'p-value')
cluster_forming_thr = spm_u(cluster_forming_thr^(1/n),df,STAT);
end
end
stat_map_vol = spm_vol(stat_filename);
[stat_map_data, stat_map_XYZmm] = spm_read_vols(stat_map_vol);
Z = stat_map_data(:)';
[x,y,z] = ind2sub(size(stat_map_data),(1:numel(stat_map_data))');
XYZ = cat(1, x', y', z');
XYZth = XYZ(:, Z >= cluster_forming_thr);
Zth = Z(Z >= cluster_forming_thr);
"""
script += (("spm_write_filtered(Zth,XYZth,stat_map_vol.dim',"
"stat_map_vol.mat,'thresholded map', '%s');\n")
% self._gen_pre_topo_map_filename())
script += """
max_size = 0;
max_size_index = 0;
th_nclusters = 0;
nclusters = 0;
if isempty(XYZth)
thresholded_XYZ = [];
thresholded_Z = [];
else
if use_topo_fdr
V2R = 1/prod(FWHM(stat_map_vol.dim > 1));
[uc,Pc,ue] = spm_uc_clusterFDR(cluster_extent_p_fdr_thr,df,STAT,R,n,Z,XYZ,V2R,cluster_forming_thr);
end
voxel_labels = spm_clusters(XYZth);
nclusters = max(voxel_labels);
thresholded_XYZ = [];
thresholded_Z = [];
for i = 1:nclusters
cluster_size = sum(voxel_labels==i);
if cluster_size > extent_threshold && (~use_topo_fdr || (cluster_size - uc) > -1)
thresholded_XYZ = cat(2, thresholded_XYZ, XYZth(:,voxel_labels == i));
thresholded_Z = cat(2, thresholded_Z, Zth(voxel_labels == i));
th_nclusters = th_nclusters + 1;
end
if force_activation
cluster_sum = sum(Zth(voxel_labels == i));
if cluster_sum > max_size
max_size = cluster_sum;
max_size_index = i;
end
end
end
end
activation_forced = 0;
if isempty(thresholded_XYZ)
if force_activation && max_size ~= 0
thresholded_XYZ = XYZth(:,voxel_labels == max_size_index);
thresholded_Z = Zth(voxel_labels == max_size_index);
th_nclusters = 1;
activation_forced = 1;
else
thresholded_Z = [0];
thresholded_XYZ = [1 1 1]';
th_nclusters = 0;
end
end
fprintf('activation_forced = %d\\n',activation_forced);
fprintf('pre_topo_n_clusters = %d\\n',nclusters);
fprintf('n_clusters = %d\\n',th_nclusters);
fprintf('cluster_forming_thr = %f\\n',cluster_forming_thr);
"""
script += (("spm_write_filtered(thresholded_Z,thresholded_XYZ,"
"stat_map_vol.dim',stat_map_vol.mat,'thresholded map',"
" '%s');\n") % self._gen_thresholded_map_filename())
return script
def aggregate_outputs(self, runtime=None):
outputs = self._outputs()
setattr(outputs, 'thresholded_map',
self._gen_thresholded_map_filename())
setattr(outputs, 'pre_topo_fdr_map', self._gen_pre_topo_map_filename())
for line in runtime.stdout.split('\n'):
if line.startswith("activation_forced = "):
setattr(outputs, 'activation_forced',
line[len("activation_forced = "):].strip() == "1")
elif line.startswith("n_clusters = "):
setattr(outputs, 'n_clusters',
int(line[len("n_clusters = "):].strip()))
elif line.startswith("pre_topo_n_clusters = "):
setattr(outputs, 'pre_topo_n_clusters',
int(line[len("pre_topo_n_clusters = "):].strip()))
elif line.startswith("cluster_forming_thr = "):
setattr(outputs, 'cluster_forming_thr',
float(line[len("cluster_forming_thr = "):].strip()))
return outputs
def _list_outputs(self):
outputs = self._outputs().get()
outputs['thresholded_map'] = self._gen_thresholded_map_filename()
outputs['pre_topo_fdr_map'] = self._gen_pre_topo_map_filename()
return outputs
class ThresholdStatisticsInputSpec(SPMCommandInputSpec):
spm_mat_file = File(exists=True, desc='absolute path to SPM.mat',
copyfile=True, mandatory=True)
stat_image = File(exists=True, desc='stat image',
copyfile=False, mandatory=True)
contrast_index = traits.Int(mandatory=True,
desc='which contrast in the SPM.mat to use')
height_threshold = traits.Float(desc=('stat value for initial '
'thresholding (defining clusters)'),
mandatory=True)
extent_threshold = traits.Int(0, usedefault=True,
desc="Minimum cluster size in voxels")
class ThresholdStatisticsOutputSpec(TraitedSpec):
voxelwise_P_Bonf = traits.Float()
voxelwise_P_RF = traits.Float()
voxelwise_P_uncor = traits.Float()
voxelwise_P_FDR = traits.Float()
clusterwise_P_RF = traits.Float()
clusterwise_P_FDR = traits.Float()
class ThresholdStatistics(SPMCommand):
"""Given height and cluster size threshold calculate theoretical
probabilities concerning false positives
Examples
--------
>>> thresh = ThresholdStatistics()
>>> thresh.inputs.spm_mat_file = 'SPM.mat'
>>> thresh.inputs.stat_image = 'spmT_0001.img'
>>> thresh.inputs.contrast_index = 1
>>> thresh.inputs.height_threshold = 4.56
>>> thresh.run() # doctest: +SKIP
"""
input_spec = ThresholdStatisticsInputSpec
output_spec = ThresholdStatisticsOutputSpec
def _make_matlab_command(self, _):
script = "con_index = %d;\n" % self.inputs.contrast_index
script += "cluster_forming_thr = %f;\n" % self.inputs.height_threshold
script += "stat_filename = '%s';\n" % self.inputs.stat_image
script += "extent_threshold = %d;\n" % self.inputs.extent_threshold
script += "load '%s'\n" % self.inputs.spm_mat_file
script += """
FWHM = SPM.xVol.FWHM;
df = [SPM.xCon(con_index).eidf SPM.xX.erdf];
STAT = SPM.xCon(con_index).STAT;
R = SPM.xVol.R;
S = SPM.xVol.S;
n = 1;
voxelwise_P_Bonf = spm_P_Bonf(cluster_forming_thr,df,STAT,S,n)
voxelwise_P_RF = spm_P_RF(1,0,cluster_forming_thr,df,STAT,R,n)
stat_map_vol = spm_vol(stat_filename);
[stat_map_data, stat_map_XYZmm] = spm_read_vols(stat_map_vol);
Z = stat_map_data(:);
Zum = Z;
switch STAT
case 'Z'
VPs = (1-spm_Ncdf(Zum)).^n;
voxelwise_P_uncor = (1-spm_Ncdf(cluster_forming_thr)).^n
case 'T'
VPs = (1 - spm_Tcdf(Zum,df(2))).^n;
voxelwise_P_uncor = (1 - spm_Tcdf(cluster_forming_thr,df(2))).^n
case 'X'
VPs = (1-spm_Xcdf(Zum,df(2))).^n;
voxelwise_P_uncor = (1-spm_Xcdf(cluster_forming_thr,df(2))).^n
case 'F'
VPs = (1 - spm_Fcdf(Zum,df)).^n;
voxelwise_P_uncor = (1 - spm_Fcdf(cluster_forming_thr,df)).^n
end
VPs = sort(VPs);
voxelwise_P_FDR = spm_P_FDR(cluster_forming_thr,df,STAT,n,VPs)
V2R = 1/prod(FWHM(stat_map_vol.dim > 1));
clusterwise_P_RF = spm_P_RF(1,extent_threshold*V2R,cluster_forming_thr,df,STAT,R,n)
[x,y,z] = ind2sub(size(stat_map_data),(1:numel(stat_map_data))');
XYZ = cat(1, x', y', z');
[u, CPs, ue] = spm_uc_clusterFDR(0.05,df,STAT,R,n,Z,XYZ,V2R,cluster_forming_thr);
clusterwise_P_FDR = spm_P_clusterFDR(extent_threshold*V2R,df,STAT,R,n,cluster_forming_thr,CPs')
"""
return script
def aggregate_outputs(self, runtime=None, needed_outputs=None):
outputs = self._outputs()
cur_output = ""
for line in runtime.stdout.split('\n'):
if cur_output != "" and len(line.split()) != 0:
setattr(outputs, cur_output, float(line))
cur_output = ""
continue
if (len(line.split()) != 0 and
line.split()[0] in ["clusterwise_P_FDR",
"clusterwise_P_RF", "voxelwise_P_Bonf",
"voxelwise_P_FDR", "voxelwise_P_RF",
"voxelwise_P_uncor"]):
cur_output = line.split()[0]
continue
return outputs
class FactorialDesignInputSpec(SPMCommandInputSpec):
spm_mat_dir = Directory(exists=True, field='dir',
desc='directory to store SPM.mat file (opt)')
# Need to make an alias of InputMultiPath; the inputs below are not Path
covariates = InputMultiPath(traits.Dict(
key_trait=traits.Enum('vector', 'name', 'interaction', 'centering')),
field='cov',
desc=('covariate dictionary {vector, name, '
'interaction, centering}'))
threshold_mask_none = traits.Bool(field='masking.tm.tm_none',
xor=['threshold_mask_absolute',
'threshold_mask_relative'],
desc='do not use threshold masking')
threshold_mask_absolute = traits.Float(field='masking.tm.tma.athresh',
xor=['threshold_mask_none',
'threshold_mask_relative'],
desc='use an absolute threshold')
threshold_mask_relative = traits.Float(field='masking.tm.tmr.rthresh',
xor=['threshold_mask_absolute',
'threshold_mask_none'],
desc=('threshold using a '
'proportion of the global '
'value'))
use_implicit_threshold = traits.Bool(field='masking.im',
desc=('use implicit mask NaNs or '
'zeros to threshold'))
explicit_mask_file = File(field='masking.em', # requires cell
desc='use an implicit mask file to threshold')
global_calc_omit = traits.Bool(field='globalc.g_omit',
xor=['global_calc_mean',
'global_calc_values'],
desc='omit global calculation')
global_calc_mean = traits.Bool(field='globalc.g_mean',
xor=['global_calc_omit',
'global_calc_values'],
desc='use mean for global calculation')
global_calc_values = traits.List(traits.Float,
field='globalc.g_user.global_uval',
xor=['global_calc_mean',
'global_calc_omit'],
desc='omit global calculation')
no_grand_mean_scaling = traits.Bool(field='globalm.gmsca.gmsca_no',
desc=('do not perform grand mean '
'scaling'))
global_normalization = traits.Enum(1, 2, 3, field='globalm.glonorm',
desc=('global normalization None-1, '
'Proportional-2, ANCOVA-3'))
class FactorialDesignOutputSpec(TraitedSpec):
spm_mat_file = File(exists=True, desc='SPM mat file')
class FactorialDesign(SPMCommand):
"""Base class for factorial designs
http://www.fil.ion.ucl.ac.uk/spm/doc/manual.pdf#page=77
"""
input_spec = FactorialDesignInputSpec
output_spec = FactorialDesignOutputSpec
_jobtype = 'stats'
_jobname = 'factorial_design'
def _format_arg(self, opt, spec, val):
"""Convert input to appropriate format for spm
"""
if opt in ['spm_mat_dir', 'explicit_mask_file']:
return np.array([str(val)], dtype=object)
if opt in ['covariates']:
outlist = []
mapping = {'name': 'cname', 'vector': 'c',
'interaction': 'iCFI',
'centering': 'iCC'}
for dictitem in val:
outdict = {}
for key, keyval in list(dictitem.items()):
outdict[mapping[key]] = keyval
outlist.append(outdict)
return outlist
return super(FactorialDesign, self)._format_arg(opt, spec, val)
def _parse_inputs(self):
"""validate spm realign options if set to None ignore
"""
einputs = super(FactorialDesign, self)._parse_inputs()
if not isdefined(self.inputs.spm_mat_dir):
einputs[0]['dir'] = np.array([str(os.getcwd())], dtype=object)
return einputs
def _list_outputs(self):
outputs = self._outputs().get()
spm = os.path.join(os.getcwd(), 'SPM.mat')
outputs['spm_mat_file'] = spm
return outputs
class OneSampleTTestDesignInputSpec(FactorialDesignInputSpec):
in_files = traits.List(File(exists=True), field='des.t1.scans',
mandatory=True, minlen=2,
desc='input files')
class OneSampleTTestDesign(FactorialDesign):
"""Create SPM design for one sample t-test
Examples
--------
>>> ttest = OneSampleTTestDesign()
>>> ttest.inputs.in_files = ['cont1.nii', 'cont2.nii']
>>> ttest.run() # doctest: +SKIP
"""
input_spec = OneSampleTTestDesignInputSpec
def _format_arg(self, opt, spec, val):
"""Convert input to appropriate format for spm
"""
if opt in ['in_files']:
return np.array(val, dtype=object)
return super(OneSampleTTestDesign, self)._format_arg(opt, spec, val)
class TwoSampleTTestDesignInputSpec(FactorialDesignInputSpec):
# very unlikely that you will have a single image in one group, so setting
# parameters to require at least two files in each group [SG]
group1_files = traits.List(File(exists=True), field='des.t2.scans1',
mandatory=True, minlen=2,
desc='Group 1 input files')
group2_files = traits.List(File(exists=True), field='des.t2.scans2',
mandatory=True, minlen=2,
desc='Group 2 input files')
dependent = traits.Bool(field='des.t2.dept',
desc=('Are the measurements dependent between '
'levels'))
unequal_variance = traits.Bool(field='des.t2.variance',
desc=('Are the variances equal or unequal '
'between groups'))
class TwoSampleTTestDesign(FactorialDesign):
"""Create SPM design for two sample t-test
Examples
--------
>>> ttest = TwoSampleTTestDesign()
>>> ttest.inputs.group1_files = ['cont1.nii', 'cont2.nii']
>>> ttest.inputs.group2_files = ['cont1a.nii', 'cont2a.nii']
>>> ttest.run() # doctest: +SKIP
"""
input_spec = TwoSampleTTestDesignInputSpec
def _format_arg(self, opt, spec, val):
"""Convert input to appropriate format for spm
"""
if opt in ['group1_files', 'group2_files']:
return np.array(val, dtype=object)
return super(TwoSampleTTestDesign, self)._format_arg(opt, spec, val)
class PairedTTestDesignInputSpec(FactorialDesignInputSpec):
paired_files = traits.List(traits.List(File(exists=True),
minlen=2, maxlen=2),
field='des.pt.pair',
mandatory=True, minlen=2,
desc='List of paired files')
grand_mean_scaling = traits.Bool(field='des.pt.gmsca',
desc='Perform grand mean scaling')
ancova = traits.Bool(field='des.pt.ancova',
desc='Specify ancova-by-factor regressors')
class PairedTTestDesign(FactorialDesign):
"""Create SPM design for paired t-test
Examples
--------
>>> pttest = PairedTTestDesign()
>>> pttest.inputs.paired_files = [['cont1.nii','cont1a.nii'],['cont2.nii','cont2a.nii']]
>>> pttest.run() # doctest: +SKIP
"""
input_spec = PairedTTestDesignInputSpec
def _format_arg(self, opt, spec, val):
"""Convert input to appropriate format for spm
"""
if opt in ['paired_files']:
return [dict(scans=np.array(files, dtype=object)) for files in val]
return super(PairedTTestDesign, self)._format_arg(opt, spec, val)
class MultipleRegressionDesignInputSpec(FactorialDesignInputSpec):
in_files = traits.List(File(exists=True),
field='des.mreg.scans',
mandatory=True, minlen=2,
desc='List of files')
include_intercept = traits.Bool(True, field='des.mreg.incint',
usedefault=True,
desc='Include intercept in design')
user_covariates = InputMultiPath(traits.Dict(
key_trait=traits.Enum('vector', 'name', 'centering')),
field='des.mreg.mcov',
desc=('covariate dictionary {vector, '
'name, centering}'))
class MultipleRegressionDesign(FactorialDesign):
"""Create SPM design for multiple regression
Examples
--------
>>> mreg = MultipleRegressionDesign()
>>> mreg.inputs.in_files = ['cont1.nii','cont2.nii']
>>> mreg.run() # doctest: +SKIP
"""
input_spec = MultipleRegressionDesignInputSpec
def _format_arg(self, opt, spec, val):
"""Convert input to appropriate format for spm
"""
if opt in ['in_files']:
return np.array(val, dtype=object)
if opt in ['user_covariates']:
outlist = []
mapping = {'name': 'cname', 'vector': 'c',
'centering': 'iCC'}
for dictitem in val:
outdict = {}
for key, keyval in list(dictitem.items()):
outdict[mapping[key]] = keyval
outlist.append(outdict)
return outlist
return (super(MultipleRegressionDesign, self)
._format_arg(opt, spec, val))
| mick-d/nipype | nipype/interfaces/spm/model.py | Python | bsd-3-clause | 45,177 |
/*
* Copyright (C) 2010, British Broadcasting Corporation
* All Rights Reserved.
*
* Author: Philip de Nier
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the British Broadcasting Corporation nor the names
* of its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <bmx/essence_parser/VC3EssenceParser.h>
#include "EssenceParserUtils.h"
#include <bmx/Utils.h>
#include <bmx/BMXException.h>
#include <bmx/Logging.h>
using namespace std;
using namespace bmx;
#define HEADER_PREFIX 0x000000028001LL
#define HEADER_PREFIX_S 0x000002800100LL
typedef struct
{
uint32_t compression_id;
bool is_progressive;
uint16_t frame_width;
uint16_t frame_height;
uint8_t bit_depth;
uint32_t frame_size;
} CompressionParameters;
static const CompressionParameters COMPRESSION_PARAMETERS[] =
{
{1235, true, 1920, 1080, 10, 917504},
{1237, true, 1920, 1080, 8, 606208},
{1238, true, 1920, 1080, 8, 917504},
{1241, false, 1920, 1080, 10, 917504},
{1242, false, 1920, 1080, 8, 606208},
{1243, false, 1920, 1080, 8, 917504},
{1250, true, 1280, 720, 10, 458752},
{1251, true, 1280, 720, 8, 458752},
{1252, true, 1280, 720, 8, 303104},
{1253, true, 1920, 1080, 8, 188416},
};
static uint64_t get_uint64(const unsigned char *data)
{
return (((uint64_t)data[0]) << 56) |
(((uint64_t)data[1]) << 48) |
(((uint64_t)data[2]) << 40) |
(((uint64_t)data[3]) << 32) |
(((uint64_t)data[4]) << 24) |
(((uint64_t)data[5]) << 16) |
(((uint64_t)data[6]) << 8) |
(uint64_t)data[7];
}
static uint32_t get_uint32(const unsigned char *data)
{
return (((uint32_t)data[0]) << 24) |
(((uint32_t)data[1]) << 16) |
(((uint32_t)data[2]) << 8) |
(uint32_t)data[3];
}
static uint16_t get_uint16(const unsigned char *data)
{
return (((uint16_t)data[0]) << 8) |
(uint16_t)data[1];
}
VC3EssenceParser::VC3EssenceParser()
{
mCompressionId = 0;
mIsProgressive = false;
mFrameWidth = 0;
mFrameHeight = 0;
mBitDepth = 0;
mFrameSize = 0;
}
VC3EssenceParser::~VC3EssenceParser()
{
}
uint32_t VC3EssenceParser::ParseFrameStart(const unsigned char *data, uint32_t data_size)
{
BMX_CHECK(data_size != ESSENCE_PARSER_NULL_OFFSET);
uint64_t state = 0;
uint32_t i;
for (i = 0; i < data_size; i++) {
state = (state << 8) | data[i];
if ((state & 0xffffffffff00LL) == HEADER_PREFIX_S &&
(state & 0x000000000003LL) < 3) // coding unit is progressive frame or field 1
{
return i - 5;
}
}
return ESSENCE_PARSER_NULL_OFFSET;
}
uint32_t VC3EssenceParser::ParseFrameSize(const unsigned char *data, uint32_t data_size)
{
BMX_CHECK(data_size != ESSENCE_PARSER_NULL_OFFSET);
if (data_size < VC3_PARSER_MIN_DATA_SIZE)
return ESSENCE_PARSER_NULL_OFFSET;
// check header prefix
uint64_t prefix = get_uint64(data) >> 24;
BMX_CHECK((prefix & 0xffffffffffLL) == HEADER_PREFIX);
uint32_t compression_id = get_uint32(data + 40);
size_t i;
for (i = 0; i < BMX_ARRAY_SIZE(COMPRESSION_PARAMETERS); i++)
{
if (compression_id == COMPRESSION_PARAMETERS[i].compression_id) {
if (data_size >= COMPRESSION_PARAMETERS[i].frame_size)
return COMPRESSION_PARAMETERS[i].frame_size;
else
return ESSENCE_PARSER_NULL_OFFSET;
}
}
return ESSENCE_PARSER_NULL_FRAME_SIZE;
}
void VC3EssenceParser::ParseFrameInfo(const unsigned char *data, uint32_t data_size)
{
BMX_CHECK(data_size != ESSENCE_PARSER_NULL_OFFSET);
BMX_CHECK(data_size >= VC3_PARSER_MIN_DATA_SIZE);
// check header prefix
uint64_t prefix = get_uint64(data) >> 24;
BMX_CHECK((prefix & 0xffffffffffLL) == HEADER_PREFIX);
// compression id
mCompressionId = get_uint32(data + 40);
size_t param_index;
for (param_index = 0; param_index < BMX_ARRAY_SIZE(COMPRESSION_PARAMETERS); param_index++)
{
if (mCompressionId == COMPRESSION_PARAMETERS[param_index].compression_id)
break;
}
BMX_CHECK(param_index < BMX_ARRAY_SIZE(COMPRESSION_PARAMETERS));
// coding control A
uint32_t ffc_bits = get_bits(data, data_size, 5 * 8 + 6, 2);
BMX_CHECK(ffc_bits == 1 || ffc_bits == 2);
mIsProgressive = (ffc_bits == 1);
BMX_CHECK(mIsProgressive == COMPRESSION_PARAMETERS[param_index].is_progressive);
// image geometry
mFrameHeight = get_uint16(data + 24);
// Note: DNxHD_Compliance_Issue_To_Licensees-1.doc states that some Avid bitstreams,
// e.g. produced by Avid Media Composer 3.0, may have ALPF incorrectly set to 1080 for
// 1080i sources. Hence the mFrameHeight != 1080 check below
if (!mIsProgressive && mFrameHeight != 1080)
mFrameHeight *= 2;
BMX_CHECK(mFrameHeight == COMPRESSION_PARAMETERS[param_index].frame_height);
mFrameWidth = get_uint16(data + 26);
BMX_CHECK(mFrameWidth == COMPRESSION_PARAMETERS[param_index].frame_width);
uint32_t sbd_bits = get_bits(data, data_size, 33 * 8, 3);
BMX_CHECK(sbd_bits == 2 || sbd_bits == 1);
mBitDepth = (sbd_bits == 2 ? 10 : 8);
BMX_CHECK(mBitDepth == COMPRESSION_PARAMETERS[param_index].bit_depth);
mFrameSize = COMPRESSION_PARAMETERS[param_index].frame_size;
}
| kierank/bmxlib-bmx | src/essence_parser/VC3EssenceParser.cpp | C++ | bsd-3-clause | 6,934 |
// **********************************************************************
//
// Copyright (c) 2001
// IONA Technologies, Inc.
// Waltham, MA, USA
//
// All Rights Reserved
//
// **********************************************************************
#include "JTC/JTC.h"
#include <stdlib.h>
#include <assert.h>
#ifdef HAVE_IOSTREAM
# include <iostream>
#else
# include <iostream.h>
#endif
#ifdef HAVE_STD_IOSTREAM
using namespace std;
#endif
#include "UnitTestFramework.h"
UT_ADD_TEST_FILE(JTCTestTryLock);
class TrylockThread : public JTCThread
{
public:
virtual void
run()
{
assert(!m_mut.trylock());
}
JTCMutex m_mut;
};
class TrylockThread2 : public JTCThread
{
public:
virtual void
run()
{
assert(!m_mut.trylock());
}
JTCRecursiveMutex m_mut;
};
#ifndef HAVE_NO_EXPLICIT_TEMPLATES
template class JTCHandleT<TrylockThread>;
template class JTCHandleT<TrylockThread2>;
#else
# ifdef HAVE_PRAGMA_DEFINE
# pragma define(JTCHandleT<TrylockThread>)
# pragma define(JTCHandleT<TrylockThread2>)
# endif
#endif
UT_NEW_TEST(JTCTestTryLock)
{
try
{
JTCInitialize boot_jtc;
//
// Under WIN32 mutexes are actually recursive
//
#if !defined(WIN32)
JTCMutex mut;
mut.lock();
assert(!mut.trylock());
mut.unlock();
#endif
JTCRecursiveMutex rm;
rm.lock();
assert(rm.trylock());
rm.unlock();
rm.unlock();
JTCHandleT<TrylockThread> t = new TrylockThread();
t -> m_mut.lock();
t -> start();
while (t -> isAlive())
{
try
{
t -> join();
}
catch(const JTCInterruptedException&)
{
}
}
t -> m_mut.unlock();
JTCHandleT<TrylockThread2> t2 = new TrylockThread2();
t2 -> m_mut.lock();
t2 -> start();
while (t2 -> isAlive())
{
try
{
t2 -> join();
}
catch(const JTCInterruptedException&)
{
}
}
t2 -> m_mut.unlock();
}
catch(const JTCException& e)
{
UT_FAIL(e.getMessage());
}
}
| wayfinder/Wayfinder-CppCore-v2 | cpp/Targets/CommonLib/POSIX/src/JTC/Tests/JTCTestTryLock.cpp | C++ | bsd-3-clause | 1,940 |
from django.core.management.base import BaseCommand
def module_to_dict(module, omittable=lambda k: k.startswith('_') or not k.isupper()):
"""Convert a module namespace to a Python dictionary."""
return {k: repr(getattr(module, k)) for k in dir(module) if not omittable(k)}
class Command(BaseCommand):
help = """Displays differences between the current settings.py and Django's
default settings."""
requires_system_checks = []
def add_arguments(self, parser):
parser.add_argument(
'--all', action='store_true',
help=(
'Display all settings, regardless of their value. In "hash" '
'mode, default values are prefixed by "###".'
),
)
parser.add_argument(
'--default', metavar='MODULE',
help=(
"The settings module to compare the current settings against. Leave empty to "
"compare against Django's default settings."
),
)
parser.add_argument(
'--output', default='hash', choices=('hash', 'unified'),
help=(
"Selects the output format. 'hash' mode displays each changed "
"setting, with the settings that don't appear in the defaults "
"followed by ###. 'unified' mode prefixes the default setting "
"with a minus sign, followed by the changed setting prefixed "
"with a plus sign."
),
)
def handle(self, **options):
from django.conf import settings, Settings, global_settings
# Because settings are imported lazily, we need to explicitly load them.
if not settings.configured:
settings._setup()
user_settings = module_to_dict(settings._wrapped)
default = options['default']
default_settings = module_to_dict(Settings(default) if default else global_settings)
output_func = {
'hash': self.output_hash,
'unified': self.output_unified,
}[options['output']]
return '\n'.join(output_func(user_settings, default_settings, **options))
def output_hash(self, user_settings, default_settings, **options):
# Inspired by Postfix's "postconf -n".
output = []
for key in sorted(user_settings):
if key not in default_settings:
output.append("%s = %s ###" % (key, user_settings[key]))
elif user_settings[key] != default_settings[key]:
output.append("%s = %s" % (key, user_settings[key]))
elif options['all']:
output.append("### %s = %s" % (key, user_settings[key]))
return output
def output_unified(self, user_settings, default_settings, **options):
output = []
for key in sorted(user_settings):
if key not in default_settings:
output.append(self.style.SUCCESS("+ %s = %s" % (key, user_settings[key])))
elif user_settings[key] != default_settings[key]:
output.append(self.style.ERROR("- %s = %s" % (key, default_settings[key])))
output.append(self.style.SUCCESS("+ %s = %s" % (key, user_settings[key])))
elif options['all']:
output.append(" %s = %s" % (key, user_settings[key]))
return output
| theo-l/django | django/core/management/commands/diffsettings.py | Python | bsd-3-clause | 3,370 |
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
(async function() {
TestRunner.addResult(`Checks the RunMicrotasks event is emitted and nested into RunTask.\n`);
await TestRunner.loadModule('timeline'); await TestRunner.loadTestModule('performance_test_runner');
await TestRunner.showPanel('timeline');
await TestRunner.evaluateInPagePromise(`
var scriptUrl = "timeline-network-resource.js";
function performActions()
{
function promiseResolved()
{
setTimeout(() => {}, 0);
}
return new Promise(fulfill => {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => xhr.readyState === 4 ? fulfill() : 0;
xhr.onerror = fulfill;
xhr.open("GET", "../resources/test.webp", true);
xhr.send();
}).then(promiseResolved);
}
`);
await PerformanceTestRunner.invokeAsyncWithTimeline('performActions');
const microTaskEvent = PerformanceTestRunner.mainTrackEvents().find(
e => e.name === TimelineModel.TimelineModel.RecordType.RunMicrotasks);
PerformanceTestRunner.printTraceEventProperties(microTaskEvent);
const nested = PerformanceTestRunner.mainTrackEvents()
.filter(e => e.name === TimelineModel.TimelineModel.RecordType.Task)
.some(e => e.startTime <= microTaskEvent.startTime && microTaskEvent.endTime <= e.endTime);
TestRunner.addResult(`Microtask event is nested into Task event: ${nested}`);
TestRunner.completeTest();
})();
| scheib/chromium | third_party/blink/web_tests/http/tests/devtools/tracing/timeline-js/timeline-microtasks.js | JavaScript | bsd-3-clause | 1,650 |
<?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model common\models\Tag */
$this->title = Yii::t('app', 'Update {modelClass}: ', [
'modelClass' => 'Tag',
]) . ' ' . $model->name;
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Tags'), 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => $model->name, 'url' => ['view', 'id' => $model->id]];
$this->params['breadcrumbs'][] = Yii::t('app', 'Update');
?>
<div class="tag-update">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'model' => $model,
]) ?>
</div>
| hdushku/npai | frontend/views/tag/update.php | PHP | bsd-3-clause | 606 |
/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id: passthrough.hpp 3746 2011-12-31 22:19:47Z rusu $
*
*/
#ifndef PCL_FILTERS_IMPL_PASSTHROUGH_H_
#define PCL_FILTERS_IMPL_PASSTHROUGH_H_
#include "pcl/filters/passthrough.h"
#include "pcl/common/io.h"
//////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::PassThrough<PointT>::applyFilter (PointCloud &output)
{
// Has the input dataset been set already?
if (!input_)
{
PCL_WARN ("[pcl::%s::applyFilter] No input dataset given!\n", getClassName ().c_str ());
output.width = output.height = 0;
output.points.clear ();
return;
}
// Check if we're going to keep the organized structure of the cloud or not
if (keep_organized_)
{
if (filter_field_name_.empty ())
{
// Silly - if no filtering is actually done, and we want to keep the data organized,
// just copy everything. Any optimizations that can be done here???
output = *input_;
return;
}
output.width = input_->width;
output.height = input_->height;
// Check what the user value is: if !finite, set is_dense to false, true otherwise
if (!pcl_isfinite (user_filter_value_))
output.is_dense = false;
else
output.is_dense = input_->is_dense;
}
else
{
output.height = 1; // filtering breaks the organized structure
// Because we're doing explit checks for isfinite, is_dense = true
output.is_dense = true;
}
output.points.resize (input_->points.size ());
removed_indices_->resize (input_->points.size ());
int nr_p = 0;
int nr_removed_p = 0;
// If we don't want to process the entire cloud, but rather filter points far away from the viewpoint first...
if (!filter_field_name_.empty ())
{
// Get the distance field index
std::vector<sensor_msgs::PointField> fields;
int distance_idx = pcl::getFieldIndex (*input_, filter_field_name_, fields);
if (distance_idx == -1)
{
PCL_WARN ("[pcl::%s::applyFilter] Invalid filter field name. Index is %d.\n", getClassName ().c_str (), distance_idx);
output.width = output.height = 0;
output.points.clear ();
return;
}
if (keep_organized_)
{
for (size_t cp = 0; cp < input_->points.size (); ++cp)
{
if (pcl_isnan (input_->points[cp].x) ||
pcl_isnan (input_->points[cp].y) ||
pcl_isnan (input_->points[cp].z))
{
output.points[cp].x = output.points[cp].y = output.points[cp].z = user_filter_value_;
continue;
}
// Copy the point
pcl::for_each_type <FieldList> (pcl::NdConcatenateFunctor <PointT, PointT> (input_->points[cp], output.points[cp]));
// Filter it. Get the distance value
uint8_t* pt_data = (uint8_t*)&input_->points[cp];
float distance_value = 0;
memcpy (&distance_value, pt_data + fields[distance_idx].offset, sizeof (float));
if (filter_limit_negative_)
{
// Use a threshold for cutting out points which inside the interval
if ((distance_value < filter_limit_max_) && (distance_value > filter_limit_min_))
{
output.points[cp].x = output.points[cp].y = output.points[cp].z = user_filter_value_;
continue;
}
else
{
if (extract_removed_indices_)
{
(*removed_indices_)[nr_removed_p]=cp;
nr_removed_p++;
}
}
}
else
{
// Use a threshold for cutting out points which are too close/far away
if ((distance_value > filter_limit_max_) || (distance_value < filter_limit_min_))
{
output.points[cp].x = output.points[cp].y = output.points[cp].z = user_filter_value_;
continue;
}
else
{
if (extract_removed_indices_)
{
(*removed_indices_)[nr_removed_p] = cp;
nr_removed_p++;
}
}
}
}
nr_p = input_->points.size ();
}
// Remove filtered points
else
{
// Go over all points
for (size_t cp = 0; cp < input_->points.size (); ++cp)
{
// Check if the point is invalid
if (!pcl_isfinite (input_->points[cp].x) || !pcl_isfinite (input_->points[cp].y) || !pcl_isfinite (input_->points[cp].z))
{
if (extract_removed_indices_)
{
(*removed_indices_)[nr_removed_p] = cp;
nr_removed_p++;
}
continue;
}
// Get the distance value
uint8_t* pt_data = (uint8_t*)&input_->points[cp];
float distance_value = 0;
memcpy (&distance_value, pt_data + fields[distance_idx].offset, sizeof (float));
if (filter_limit_negative_)
{
// Use a threshold for cutting out points which inside the interval
if (distance_value < filter_limit_max_ && distance_value > filter_limit_min_)
{
if (extract_removed_indices_)
{
(*removed_indices_)[nr_removed_p] = cp;
nr_removed_p++;
}
continue;
}
}
else
{
// Use a threshold for cutting out points which are too close/far away
if (distance_value > filter_limit_max_ || distance_value < filter_limit_min_)
{
if (extract_removed_indices_)
{
(*removed_indices_)[nr_removed_p] = cp;
nr_removed_p++;
}
continue;
}
}
pcl::for_each_type <FieldList> (pcl::NdConcatenateFunctor <PointT, PointT> (input_->points[cp], output.points[nr_p]));
nr_p++;
}
output.width = nr_p;
} // !keep_organized_
}
// No distance filtering, process all data. No need to check for is_organized here as we did it above
else
{
// First pass: go over all points and insert them into the right leaf
for (size_t cp = 0; cp < input_->points.size (); ++cp)
{
// Check if the point is invalid
if (!pcl_isfinite (input_->points[cp].x) || !pcl_isfinite (input_->points[cp].y) || !pcl_isfinite (input_->points[cp].z))
{
if (extract_removed_indices_)
{
(*removed_indices_)[nr_removed_p] = cp;
nr_removed_p++;
}
continue;
}
pcl::for_each_type <FieldList> (pcl::NdConcatenateFunctor <PointT, PointT> (input_->points[cp], output.points[nr_p]));
nr_p++;
}
output.width = nr_p;
}
output.points.resize (output.width * output.height);
removed_indices_->resize(nr_removed_p);
}
#define PCL_INSTANTIATE_PassThrough(T) template class PCL_EXPORTS pcl::PassThrough<T>;
#endif // PCL_FILTERS_IMPL_PASSTHROUGH_H_
| ros-gbp/pcl-fuerte-release_defunct | filters/include/pcl/filters/impl/passthrough.hpp | C++ | bsd-3-clause | 8,506 |
/*
* Copyright (C) 2008-2011, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
/// \file libuco/urbi-main.cc
#include <libport/cli.hh>
#include <libport/containers.hh>
#include <urbi/umain.hh>
#include <urbi/urbi-root.hh>
extern "C"
{
int urbi_main(int argc, const char* argv[],
UrbiRoot& urbi_root, bool block, bool errors)
{
libport::program_initialize(argc, argv);
return urbi::main(argc, argv, urbi_root, block, errors);
}
int urbi_main_args(const libport::cli_args_type& args,
UrbiRoot& urbi_root, bool block, bool errors)
{
libport::program_initialize(args);
return urbi::main(args, urbi_root, block, errors);
}
}
namespace urbi
{
int
main(int argc, const char* argv[],
UrbiRoot& urbi_root, bool block, bool errors)
{
libport::program_initialize(argc, argv);
libport::cli_args_type args;
// For some reason, I failed to use std::copy here.
for (int i = 0; i < argc; ++i)
args << std::string(argv[i]);
return main(args, urbi_root, block, errors);
}
}
| urbiforge/urbi | sdk-remote/src/libuco/urbi-main.cc | C++ | bsd-3-clause | 1,282 |
<?php
/**
* Common Status Class
* User: funson
* Date: 2014/06/25
* Time: 9:50
*/
namespace funson86\cms\models;
use funson86\cms\Module;
class YesNo
{
const NO = 0;
const YES = 1;
public $id;
public $label;
public function __construct($id = null)
{
if ($id !== null) {
$this->id = $id;
$this->label = $this->getLabel($id);
}
}
public static function labels($id = null)
{
$data = [
self::YES => Module::t('cms', 'YES'),
self::NO => Module::t('cms', 'NO'),
];
if ($id !== null && isset($data[$id])) {
return $data[$id];
} else {
return $data;
}
}
public function getLabel($id)
{
$labels = self::labels();
return isset($labels[$id]) ? $labels[$id] : null;
}
}
| clh021/yii2cms | vendor/funson86/yii2-cms/models/YesNo.php | PHP | bsd-3-clause | 868 |
<?php
/**
* Console application, which extracts or replaces strings for
* translation, which cannot be gettexted
*
* @version $Id: not-gettexted.php 17220 2011-06-20 13:26:10Z nbachiyski $
* @package wordpress-i18n
* @subpackage tools
*/
// see: http://php.net/tokenizer
if (!defined('T_ML_COMMENT'))
define('T_ML_COMMENT', T_COMMENT);
else
define('T_DOC_COMMENT', T_ML_COMMENT);
require_once dirname( __FILE__ ) . '/pomo/po.php';
require_once dirname( __FILE__ ) . '/pomo/mo.php';
class NotGettexted {
var $enable_logging = false;
var $STAGE_OUTSIDE = 0;
var $STAGE_START_COMMENT = 1;
var $STAGE_WHITESPACE_BEFORE = 2;
var $STAGE_STRING = 3;
var $STAGE_WHITESPACE_AFTER = 4;
var $STAGE_END_COMMENT = 4;
var $commands = array('extract' => 'command_extract', 'replace' => 'command_replace' );
function logmsg() {
$args = func_get_args();
if ($this->enable_logging) error_log(implode(' ', $args));
}
function stderr($msg, $nl=true) {
fwrite(STDERR, $msg.($nl? "\n" : ""));
}
function cli_die($msg) {
$this->stderr($msg);
exit(1);
}
function unchanged_token($token, $s='') {
return is_array($token)? $token[1] : $token;
}
function ignore_token($token, $s='') {
return '';
}
function list_php_files($dir) {
$files = array();
$d = opendir($dir);
if (!$d) return false;
while(false !== ($item = readdir($d))) {
$full_item = $dir . '/' . $item;
if ('.' == $item || '..' == $item)
continue;
if ('.php' == substr($item, -4))
$files[] = $full_item;
if (is_dir($full_item))
$files += array_merge($files, NotGettexted::list_php_files($full_item, $files));
}
closedir($d);
return $files;
}
function make_string_aggregator($global_array_name, $filename) {
$a = $global_array_name;
return create_function('$string, $comment_id, $line_number', 'global $'.$a.'; $'.$a.'[] = array($string, $comment_id, '.var_export($filename, true).', $line_number);');
}
function make_mo_replacer($global_mo_name) {
$m = $global_mo_name;
return create_function('$token, $string', 'global $'.$m.'; return var_export($'.$m.'->translate($string), true);');
}
function walk_tokens(&$tokens, $string_action, $other_action, $register_action=null) {
$current_comment_id = '';
$current_string = '';
$current_string_line = 0;
$result = '';
$line = 1;
foreach($tokens as $token) {
if (is_array($token)) {
list($id, $text) = $token;
$line += substr_count($text, "\n");
if ((T_ML_COMMENT == $id || T_COMMENT == $id) && preg_match('|/\*\s*(/?WP_I18N_[a-z_]+)\s*\*/|i', $text, $matches)) {
if ($this->STAGE_OUTSIDE == $stage) {
$stage = $this->STAGE_START_COMMENT;
$current_comment_id = $matches[1];
$this->logmsg('start comment', $current_comment_id);
$result .= call_user_func($other_action, $token);
continue;
}
if ($this->STAGE_START_COMMENT <= $stage && $stage <= $this->STAGE_WHITESPACE_AFTER && '/'.$current_comment_id == $matches[1]) {
$stage = $this->STAGE_END_COMMENT;
$this->logmsg('end comment', $current_comment_id);
$result .= call_user_func($other_action, $token);
if (!is_null($register_action)) call_user_func($register_action, $current_string, $current_comment_id, $current_string_line);
continue;
}
} else if (T_CONSTANT_ENCAPSED_STRING == $id) {
if ($this->STAGE_START_COMMENT <= $stage && $stage < $this->STAGE_WHITESPACE_AFTER) {
eval('$current_string='.$text.';');
$this->logmsg('string', $current_string);
$current_string_line = $line;
$result .= call_user_func($string_action, $token, $current_string);
continue;
}
} else if (T_WHITESPACE == $id) {
if ($this->STAGE_START_COMMENT <= $stage && $stage < $this->STAGE_STRING) {
$stage = $this->STAGE_WHITESPACE_BEFORE;
$this->logmsg('whitespace before');
$result .= call_user_func($other_action, $token);
continue;
}
if ($this->STAGE_STRING < $stage && $stage < $this->STAGE_END_COMMENT) {
$stage = $this->STAGE_WHITESPACE_AFTER;
$this->logmsg('whitespace after');
$result .= call_user_func($other_action, $token);
continue;
}
}
}
$result .= call_user_func($other_action, $token);
$stage = $this->STAGE_OUTSIDE;
$current_comment_id = '';
$current_string = '';
$current_string_line = 0;
}
return $result;
}
function command_extract() {
$args = func_get_args();
$pot_filename = $args[0];
if (isset($args[1]) && is_array($args[1]))
$filenames = $args[1];
else
$filenames = array_slice($args, 1);
$global_name = '__entries_'.mt_rand(1, 1000);
$GLOBALS[$global_name] = array();
foreach($filenames as $filename) {
$tokens = token_get_all(file_get_contents($filename));
$aggregator = $this->make_string_aggregator($global_name, $filename);
$this->walk_tokens($tokens, array(&$this, 'ignore_token'), array(&$this, 'ignore_token'), $aggregator);
}
$potf = '-' == $pot_filename? STDOUT : @fopen($pot_filename, 'a');
if (false === $potf) {
$this->cli_die("Couldn't open pot file: $pot_filename");
}
foreach($GLOBALS[$global_name] as $item) {
@list($string, $comment_id, $filename, $line_number) = $item;
$filename = isset($filename)? preg_replace('|^\./|', '', $filename) : '';
$ref_line_number = isset($line_number)? ":$line_number" : '';
$args = array(
'singular' => $string,
'extracted_comments' => "Not gettexted string $comment_id",
'references' => array("$filename$ref_line_number"),
);
$entry = new Translation_Entry($args);
fwrite($potf, "\n".PO::export_entry($entry)."\n");
}
if ('-' != $pot_filename) fclose($potf);
return true;
}
function command_replace() {
$args = func_get_args();
$mo_filename = $args[0];
if (isset($args[1]) && is_array($args[1]))
$filenames = $args[1];
else
$filenames = array_slice($args, 1);
$global_name = '__mo_'.mt_rand(1, 1000);
$GLOBALS[$global_name] = new MO();
$replacer = $this->make_mo_replacer($global_name);
$res = $GLOBALS[$global_name]->import_from_file($mo_filename);
if (false === $res) {
$this->cli_die("Couldn't read MO file '$mo_filename'!");
}
foreach($filenames as $filename) {
$source = file_get_contents($filename);
if ( strlen($source) > 150000 ) continue;
$tokens = token_get_all($source);
$new_file = $this->walk_tokens($tokens, $replacer, array(&$this, 'unchanged_token'));
$f = fopen($filename, 'w');
fwrite($f, $new_file);
fclose($f);
}
return true;
}
function usage() {
$this->stderr('php i18n-comments.php COMMAND OUTPUTFILE INPUTFILES');
$this->stderr('Extracts and replaces strings, which cannot be gettexted');
$this->stderr('Commands:');
$this->stderr(' extract POTFILE PHPFILES appends the strings to POTFILE');
$this->stderr(' replace MOFILE PHPFILES replaces strings in PHPFILES with translations from MOFILE');
}
function cli() {
global $argv, $commands;
if (count($argv) < 4 || !in_array($argv[1], array_keys($this->commands))) {
$this->usage();
exit(1);
}
call_user_func_array(array(&$this, $this->commands[$argv[1]]), array_slice($argv, 2));
}
}
// run the CLI only if the file
// wasn't included
$included_files = get_included_files();
if ($included_files[0] == __FILE__) {
error_reporting(E_ALL);
$not_gettexted = new NotGettexted;
$not_gettexted->cli();
}
?>
| oberlin/wp-class-blogs | assets/wpi18n/not-gettexted.php | PHP | bsd-3-clause | 7,409 |
from datetime import timedelta
from time import time
import warnings
from gdbn.dbn import buildDBN
from gdbn import activationFunctions
import numpy as np
from sklearn.base import BaseEstimator
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder
warnings.warn("""
The nolearn.dbn module will be removed in nolearn 0.6. If you want to
continue to use this module, please consider copying the code into
your own project. And take a look at Lasagne and nolearn.lasagne for
a better neural net toolkit.
""")
class DBN(BaseEstimator):
"""A scikit-learn estimator based on George Dahl's DBN
implementation `gdbn`.
"""
def __init__(
self,
layer_sizes=None,
scales=0.05,
fan_outs=None,
output_act_funct=None,
real_valued_vis=True,
use_re_lu=True,
uniforms=False,
learn_rates=0.1,
learn_rate_decays=1.0,
learn_rate_minimums=0.0,
momentum=0.9,
l2_costs=0.0001,
dropouts=0,
nesterov=True,
nest_compare=True,
rms_lims=None,
learn_rates_pretrain=None,
momentum_pretrain=None,
l2_costs_pretrain=None,
nest_compare_pretrain=None,
epochs=10,
epochs_pretrain=0,
loss_funct=None,
minibatch_size=64,
minibatches_per_epoch=None,
pretrain_callback=None,
fine_tune_callback=None,
random_state=None,
verbose=0,
):
"""
Many parameters such as `learn_rates`, `dropouts` etc. will
also accept a single value, in which case that value will be
used for all layers. To control the value per layer, pass a
list of values instead; see examples below.
Parameters ending with `_pretrain` may be provided to override
the given parameter for pretraining. Consider an example
where you want the pre-training to use a lower learning rate
than the fine tuning (the backprop), then you'd maybe pass
something like::
DBN([783, 300, 10], learn_rates=0.1, learn_rates_pretrain=0.005)
If you don't pass the `learn_rates_pretrain` parameter, the
value of `learn_rates` will be used for both pre-training and
fine tuning. (Which seems to not work very well.)
:param layer_sizes: A list of integers of the form
``[n_vis_units, n_hid_units1,
n_hid_units2, ..., n_out_units]``.
An example: ``[784, 300, 10]``
The number of units in the input layer and
the output layer will be set automatically
if you set them to -1. Thus, the above
example is equivalent to ``[-1, 300, -1]``
if you pass an ``X`` with 784 features,
and a ``y`` with 10 classes.
:param scales: Scale of the randomly initialized weights. A
list of floating point values. When you find
good values for the scale of the weights you
can speed up training a lot, and also improve
performance. Defaults to `0.05`.
:param fan_outs: Number of nonzero incoming connections to a
hidden unit. Defaults to `None`, which means
that all connections have non-zero weights.
:param output_act_funct: Output activation function. Instance
of type
:class:`~gdbn.activationFunctions.Sigmoid`,
:class:`~.gdbn.activationFunctions.Linear`,
:class:`~.gdbn.activationFunctions.Softmax`
from the
:mod:`gdbn.activationFunctions`
module. Defaults to
:class:`~.gdbn.activationFunctions.Softmax`.
:param real_valued_vis: Set `True` (the default) if visible
units are real-valued.
:param use_re_lu: Set `True` to use rectified linear units.
Defaults to `False`.
:param uniforms: Not documented at this time.
:param learn_rates: A list of learning rates, one entry per
weight layer.
An example: ``[0.1, 0.1]``
:param learn_rate_decays: The number with which the
`learn_rate` is multiplied after
each epoch of fine-tuning.
:param learn_rate_minimums: The minimum `learn_rates`; after
the learn rate reaches the minimum
learn rate, the
`learn_rate_decays` no longer has
any effect.
:param momentum: Momentum
:param l2_costs: L2 costs per weight layer.
:param dropouts: Dropouts per weight layer.
:param nesterov: Not documented at this time.
:param nest_compare: Not documented at this time.
:param rms_lims: Not documented at this time.
:param learn_rates_pretrain: A list of learning rates similar
to `learn_rates_pretrain`, but
used for pretraining. Defaults
to value of `learn_rates` parameter.
:param momentum_pretrain: Momentum for pre-training. Defaults
to value of `momentum` parameter.
:param l2_costs_pretrain: L2 costs per weight layer, for
pre-training. Defaults to the value
of `l2_costs` parameter.
:param nest_compare_pretrain: Not documented at this time.
:param epochs: Number of epochs to train (with backprop).
:param epochs_pretrain: Number of epochs to pre-train (with CDN).
:param loss_funct: A function that calculates the loss. Used
for displaying learning progress and for
:meth:`score`.
:param minibatch_size: Size of a minibatch.
:param minibatches_per_epoch: Number of minibatches per epoch.
The default is to use as many as
fit into our training set.
:param pretrain_callback: An optional function that takes as
arguments the :class:`DBN` instance,
the epoch and the layer index as its
argument, and is called for each
epoch of pretraining.
:param fine_tune_callback: An optional function that takes as
arguments the :class:`DBN` instance
and the epoch, and is called for
each epoch of fine tuning.
:param random_state: An optional int used as the seed by the
random number generator.
:param verbose: Debugging output.
"""
if layer_sizes is None:
layer_sizes = [-1, -1]
if output_act_funct is None:
output_act_funct = activationFunctions.Softmax()
elif isinstance(output_act_funct, str):
output_act_funct = getattr(activationFunctions, output_act_funct)()
if random_state is not None:
raise ValueError("random_sate must be an int")
self.layer_sizes = layer_sizes
self.scales = scales
self.fan_outs = fan_outs
self.output_act_funct = output_act_funct
self.real_valued_vis = real_valued_vis
self.use_re_lu = use_re_lu
self.uniforms = uniforms
self.learn_rates = learn_rates
self.learn_rate_decays = learn_rate_decays
self.learn_rate_minimums = learn_rate_minimums
self.momentum = momentum
self.l2_costs = l2_costs
self.dropouts = dropouts
self.nesterov = nesterov
self.nest_compare = nest_compare
self.rms_lims = rms_lims
self.learn_rates_pretrain = learn_rates_pretrain
self.momentum_pretrain = momentum_pretrain
self.l2_costs_pretrain = l2_costs_pretrain
self.nest_compare_pretrain = nest_compare_pretrain
self.epochs = epochs
self.epochs_pretrain = epochs_pretrain
self.loss_funct = loss_funct
self.use_dropout = True if dropouts else False
self.minibatch_size = minibatch_size
self.minibatches_per_epoch = minibatches_per_epoch
self.pretrain_callback = pretrain_callback
self.fine_tune_callback = fine_tune_callback
self.random_state = random_state
self.verbose = verbose
def _fill_missing_layer_sizes(self, X, y):
layer_sizes = self.layer_sizes
if layer_sizes[0] == -1: # n_feat
layer_sizes[0] = X.shape[1]
if layer_sizes[-1] == -1 and y is not None: # n_classes
layer_sizes[-1] = y.shape[1]
def _vp(self, value):
num_weights = len(self.layer_sizes) - 1
if not hasattr(value, '__iter__'):
value = [value] * num_weights
return list(value)
def _build_net(self, X, y=None):
v = self._vp
self._fill_missing_layer_sizes(X, y)
if self.verbose: # pragma: no cover
print "[DBN] layers {}".format(self.layer_sizes)
if self.random_state is not None:
np.random.seed(self.random_state)
net = buildDBN(
self.layer_sizes,
v(self.scales),
v(self.fan_outs),
self.output_act_funct,
self.real_valued_vis,
self.use_re_lu,
v(self.uniforms),
)
return net
def _configure_net_pretrain(self, net):
v = self._vp
self._configure_net_finetune(net)
learn_rates = self.learn_rates_pretrain
momentum = self.momentum_pretrain
l2_costs = self.l2_costs_pretrain
nest_compare = self.nest_compare_pretrain
if learn_rates is None:
learn_rates = self.learn_rates
if momentum is None:
momentum = self.momentum
if l2_costs is None:
l2_costs = self.l2_costs
if nest_compare is None:
nest_compare = self.nest_compare
net.learnRates = v(learn_rates)
net.momentum = momentum
net.L2Costs = v(l2_costs)
net.nestCompare = nest_compare
return net
def _configure_net_finetune(self, net):
v = self._vp
net.learnRates = v(self.learn_rates)
net.momentum = self.momentum
net.L2Costs = v(self.l2_costs)
net.dropouts = v(self.dropouts)
net.nesterov = self.nesterov
net.nestCompare = self.nest_compare
net.rmsLims = v(self.rms_lims)
return net
def _minibatches(self, X, y=None):
while True:
idx = np.random.randint(X.shape[0], size=(self.minibatch_size,))
X_batch = X[idx]
if hasattr(X_batch, 'todense'):
X_batch = X_batch.todense()
if y is not None:
yield (X_batch, y[idx])
else:
yield X_batch
def _onehot(self, y):
return np.array(
OneHotEncoder().fit_transform(y.reshape(-1, 1)).todense())
def _num_mistakes(self, targets, outputs):
if hasattr(targets, 'as_numpy_array'): # pragma: no cover
targets = targets.as_numpy_array()
if hasattr(outputs, 'as_numpy_array'):
outputs = outputs.as_numpy_array()
return np.sum(outputs.argmax(1) != targets.argmax(1))
def _learn_rate_adjust(self):
if self.learn_rate_decays == 1.0:
return
learn_rate_decays = self._vp(self.learn_rate_decays)
learn_rate_minimums = self._vp(self.learn_rate_minimums)
for index, decay in enumerate(learn_rate_decays):
new_learn_rate = self.net_.learnRates[index] * decay
if new_learn_rate >= learn_rate_minimums[index]:
self.net_.learnRates[index] = new_learn_rate
if self.verbose >= 2:
print "Learn rates: {}".format(self.net_.learnRates)
def fit(self, X, y):
if self.verbose:
print "[DBN] fitting X.shape=%s" % (X.shape,)
self._enc = LabelEncoder()
y = self._enc.fit_transform(y)
y = self._onehot(y)
self.net_ = self._build_net(X, y)
minibatches_per_epoch = self.minibatches_per_epoch
if minibatches_per_epoch is None:
minibatches_per_epoch = X.shape[0] / self.minibatch_size
loss_funct = self.loss_funct
if loss_funct is None:
loss_funct = self._num_mistakes
errors_pretrain = self.errors_pretrain_ = []
losses_fine_tune = self.losses_fine_tune_ = []
errors_fine_tune = self.errors_fine_tune_ = []
if self.epochs_pretrain:
self.epochs_pretrain = self._vp(self.epochs_pretrain)
self._configure_net_pretrain(self.net_)
for layer_index in range(len(self.layer_sizes) - 1):
errors_pretrain.append([])
if self.verbose: # pragma: no cover
print "[DBN] Pre-train layer {}...".format(layer_index + 1)
time0 = time()
for epoch, err in enumerate(
self.net_.preTrainIth(
layer_index,
self._minibatches(X),
self.epochs_pretrain[layer_index],
minibatches_per_epoch,
)):
errors_pretrain[-1].append(err)
if self.verbose: # pragma: no cover
print " Epoch {}: err {}".format(epoch + 1, err)
elapsed = str(timedelta(seconds=time() - time0))
print " ({})".format(elapsed.split('.')[0])
time0 = time()
if self.pretrain_callback is not None:
self.pretrain_callback(
self, epoch + 1, layer_index)
self._configure_net_finetune(self.net_)
if self.verbose: # pragma: no cover
print "[DBN] Fine-tune..."
time0 = time()
for epoch, (loss, err) in enumerate(
self.net_.fineTune(
self._minibatches(X, y),
self.epochs,
minibatches_per_epoch,
loss_funct,
self.verbose,
self.use_dropout,
)):
losses_fine_tune.append(loss)
errors_fine_tune.append(err)
self._learn_rate_adjust()
if self.verbose: # pragma: no cover
print "Epoch {}:".format(epoch + 1)
print " loss {}".format(loss)
print " err {}".format(err)
elapsed = str(timedelta(seconds=time() - time0))
print " ({})".format(elapsed.split('.')[0])
time0 = time()
if self.fine_tune_callback is not None:
self.fine_tune_callback(self, epoch + 1)
def predict(self, X):
y_ind = np.argmax(self.predict_proba(X), axis=1)
return self._enc.inverse_transform(y_ind)
def predict_proba(self, X):
if hasattr(X, 'todense'):
return self._predict_proba_sparse(X)
res = np.zeros((X.shape[0], self.layer_sizes[-1]))
for i, el in enumerate(self.net_.predictions(X, asNumpy=True)):
res[i] = el
return res
def _predict_proba_sparse(self, X):
batch_size = self.minibatch_size
res = []
for i in xrange(0, X.shape[0], batch_size):
X_batch = X[i:min(i + batch_size, X.shape[0])].todense()
res.extend(self.net_.predictions(X_batch))
return np.array(res).reshape(X.shape[0], -1)
def score(self, X, y):
loss_funct = self.loss_funct
if loss_funct is None:
loss_funct = self._num_mistakes
outputs = self.predict_proba(X)
targets = self._onehot(self._enc.transform(y))
mistakes = loss_funct(outputs, targets)
return - float(mistakes) / len(y) + 1
@property
def classes_(self):
return self._enc.classes_
| rajegannathan/grasp-lift-eeg-cat-dog-solution-updated | python-packages/nolearn-0.5/nolearn/dbn.py | Python | bsd-3-clause | 16,813 |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE690_NULL_Deref_From_Return__int64_t_calloc_84a.cpp
Label Definition File: CWE690_NULL_Deref_From_Return.free.label.xml
Template File: source-sinks-84a.tmpl.cpp
*/
/*
* @description
* CWE: 690 Unchecked Return Value To NULL Pointer
* BadSource: calloc Allocate data using calloc()
* Sinks:
* GoodSink: Check to see if the data allocation failed and if not, use data
* BadSink : Don't check for NULL and use data
* Flow Variant: 84 Data flow: data passed to class constructor and destructor by declaring the class object on the heap and deleting it after use
*
* */
#include "std_testcase.h"
#include "CWE690_NULL_Deref_From_Return__int64_t_calloc_84.h"
namespace CWE690_NULL_Deref_From_Return__int64_t_calloc_84
{
#ifndef OMITBAD
void bad()
{
int64_t * data;
data = NULL; /* Initialize data */
CWE690_NULL_Deref_From_Return__int64_t_calloc_84_bad * badObject = new CWE690_NULL_Deref_From_Return__int64_t_calloc_84_bad(data);
delete badObject;
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodB2G uses the BadSource with the GoodSink */
static void goodB2G()
{
int64_t * data;
data = NULL; /* Initialize data */
CWE690_NULL_Deref_From_Return__int64_t_calloc_84_goodB2G * goodB2GObject = new CWE690_NULL_Deref_From_Return__int64_t_calloc_84_goodB2G(data);
delete goodB2GObject;
}
void good()
{
goodB2G();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE690_NULL_Deref_From_Return__int64_t_calloc_84; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| JianpingZeng/xcc | xcc/test/juliet/testcases/CWE690_NULL_Deref_From_Return/s01/CWE690_NULL_Deref_From_Return__int64_t_calloc_84a.cpp | C++ | bsd-3-clause | 2,320 |
function save(e, link) {
$.ajax(link.attr("href"), {
success: function(data, textStatus, jqXHR) {
link.hide();
link.closest("tr").addClass("success");
link.closest("tr").find("div.remove").show();
},
error: ajax_error_handler
});
e.preventDefault();
}
function delete_row(e, link) {
$.ajax(link.attr("href"), {
success: function(data, textStatus, jqXHR) {
link.closest("tr").removeClass("success");
link.closest("tr").find(".actions-save").show();
link.closest("div.remove").hide();
},
error: ajax_error_handler
});
e.preventDefault();
}
$(document).ready(function() {
make_active($("#id_employee_profile_automatches_menu"));
$("#id_automatches_table tr").mouseenter(function(e) {
$(this).find(".actions").show();
})
.mouseleave(function(e) {
$(this).find(".actions").hide();
});
$("#id_automatches_table a.actions-save").click(function(e) {
save(e, $(this));
});
$("#id_automatches_table a.remove").click(function(e) {
delete_row(e, $(this));
});
});
| hellhovnd/dentexchange | dentexchange/apps/matches/static/matches/js/posting_automatches.js | JavaScript | bsd-3-clause | 1,161 |
package gopher
import (
"fmt"
"io"
"log"
"math/rand"
"time"
"github.com/adamryman/gophersay/gopherart"
)
var (
sayings []string
gopherArt string
)
func init() {
// Load in gopher ascii art from go-bindata
gopherArtBytes, err := gopherart.Asset("gopherart/gopher.ascii")
if err != nil {
log.Fatal(err)
}
gopherArt = string(gopherArtBytes)
sayings = []string{
"Don't communicate by sharing memory, share memory by communicating.", "Concurrency is not parallelism.",
"Channels orchestrate; mutexes serialize.",
"The bigger the interface, the weaker the abstraction.",
"Make the zero value useful.",
"interface{} says nothing.",
"Gofmt's style is no one's favorite, yet gofmt is everyone's favorite.",
"A little copying is better than a little dependency.",
"Syscall must always be guarded with build tags.",
"Cgo must always be guarded with build tags.",
"Cgo is not Go.",
"With the unsafe package there are no guarantees.",
"Clear is better than clever.",
"Reflection is never clear.",
"Errors are values.",
"Don't just check errors, handle them gracefully.",
"Design the architecture, name the components, document the details.",
"Documentation is for users.",
"Don't panic.",
}
}
func Proverb(w io.Writer) {
rand.Seed(time.Now().UnixNano())
saying := sayings[rand.Intn(len(sayings))]
Say(w, saying)
}
func Say(w io.Writer, saying string) {
fmt.Fprintf(w, " ------------------------\n%s\n%s",
saying,
gopherArt,
)
}
| golang/scratch | zaquestion/vendor/github.com/adamryman/gophersay/gopher/say.go | GO | bsd-3-clause | 1,485 |
<?php
include_once("./eval_conf.php");
include_once("./functions.php");
include_once("./global.php");
include_once("./dwoo/dwooAutoload.php");
if (! checkAccess(GangliaAcl::ALL_VIEWS, GangliaAcl::VIEW, $conf))
die("You do not have access to view views.");
$view_name = NULL;
if (isset($_GET['vn']) && !is_proper_view_name($_GET['vn'])) {
?>
<div class="ui-widget">
<div class="ui-state-default ui-corner-all" styledefault="padding: 0 .7em;">
<p><span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;"></span>
View names valid characters are 0-9, a-z, A-Z, -, _ and space. View has not been created.</p>
</div>
</div>
<?php
exit(0);
} else {
$view_name = $_GET['vn'];
}
$viewList = new ViewList();
$dwoo = new Dwoo($conf['dwoo_compiled_dir'], $conf['dwoo_cache_dir']);
$tpl = new Dwoo_Template_File( template("view_content.tpl") );
$data = new Dwoo_Data();
$size = isset($clustergraphsize) ? $clustergraphsize : 'default';
// set to 'default' to preserve old behavior
if ($size == 'medium')
$size = 'default';
$additional_host_img_css_classes = "";
if (isset($conf['zoom_support']) && $conf['zoom_support'] === true)
$additional_host_img_css_classes = "host_${size}_zoomable";
$data->assign("additional_host_img_css_classes",
$additional_host_img_css_classes);
$view_items = NULL;
$view = $viewList->getView($view_name);
if ($view != NULL) {
$range = isset($_GET["r"]) ? escapeshellcmd(rawurldecode($_GET["r"])) : NULL;
$cs = isset($_GET["cs"]) ? escapeshellcmd($_GET["cs"]) : NULL;
$ce = isset($_GET["ce"]) ? escapeshellcmd($_GET["ce"]) : NULL;
if ($cs or $ce)
$range = "custom";
$view_items = getViewItems($view, $range, $cs, $ce);
}
if (isset($view_items)) {
$data->assign("view_items", $view_items);
$data->assign("number_of_view_items", count($view_items));
if ($view['common_y_axis'] != 0)
$data->assign("common_y_axis", 1);
}
$data->assign('GRAPH_BASE_ID', $GRAPH_BASE_ID);
$data->assign('SHOW_EVENTS_BASE_ID', $SHOW_EVENTS_BASE_ID);
$dwoo->output($tpl, $data);
?>
| luckypoem/ganglia-web | view_content.php | PHP | bsd-3-clause | 2,069 |
# coding: UTF-8
require File.expand_path(File.dirname(__FILE__) + '/../acceptance_helper')
feature "API 1.0 user layers management" do
before(:all) do
Capybara.current_driver = :rack_test
@user = create_user({:username => 'test'})
end
before(:each) do
delete_user_data @user
@table = create_table(:user_id => @user.id)
end
scenario "Create a new layer associated to the current user" do
post_json v1_user_layers_url(:host => CartoDB.hostname.sub('http://', ''), :api_key => api_key, :user_id => @user.id), {
:kind => 'carto' } do |response|
response.status.should be_success
@user.layers.size.should == 1
response.body[:id].should == @user.layers.first.id
end
end
scenario "Get all user layers" do
layer = Layer.create :kind => 'carto'
layer2 = Layer.create :kind => 'tiled'
@user.add_layer layer
@user.add_layer layer2
get_json v1_user_layers_url(:host => CartoDB.hostname.sub('http://', ''), :api_key => api_key, :user_id => @user.id) do |response|
response.status.should be_success
response.body[:total_entries].should == 2
response.body[:layers].size.should == 2
response.body[:layers][0]['id'].should == layer.id
end
end
scenario "Update a layer" do
layer = Layer.create :kind => 'carto'
@user.add_layer layer
put_json v1_user_layer_url(:host => CartoDB.hostname.sub('http://', ''), :api_key => api_key, :id => layer.id, :user_id => @user.id), {
:options => { :opt1 => 'value' },
:infowindow => ['column1', 'column2'],
:kind => 'carto' } do |response|
response.status.should be_success
response.body[:id].should == layer.id
response.body[:options].should == { 'opt1' => 'value' }
response.body[:infowindow].should == ['column1', 'column2']
response.body[:kind].should == 'carto'
end
end
scenario "Drop a layer" do
layer = Layer.create :kind => 'carto'
@user.add_layer layer
delete_json v1_user_layer_url(:host => CartoDB.hostname.sub('http://', ''), :api_key => api_key, :id => layer.id, :user_id => @user.id) do |response|
response.status.should be_success
expect { layer.refresh }.to raise_error
end
end
end
| datapolitan/cartodb20 | spec/acceptance/api/user_layers_spec.rb | Ruby | bsd-3-clause | 2,250 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// A test application for the RLZ library.
//
// These tests should not be executed on the build server:
// - They assert for the failed cases.
// - They modify machine state (registry).
//
// These tests require write access to HKLM and HKCU.
//
// The "GGLA" brand is used to test the normal code flow of the code, and the
// "TEST" brand is used to test the supplementary brand code code flow.
#include <stddef.h>
#include <memory>
#include "base/logging.h"
#include "base/posix/eintr_wrapper.h"
#include "base/single_thread_task_runner.h"
#include "build/build_config.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "rlz/lib/financial_ping.h"
#include "rlz/lib/rlz_lib.h"
#include "rlz/lib/rlz_value_store.h"
#include "rlz/test/rlz_test_helpers.h"
#if defined(OS_WIN)
#include <Windows.h>
#include "rlz/win/lib/machine_deal.h"
#endif
#if defined(RLZ_NETWORK_IMPLEMENTATION_CHROME_NET)
#include "base/mac/scoped_nsautorelease_pool.h"
#include "base/threading/thread.h"
#include "net/url_request/url_request_test_util.h"
#endif
class MachineDealCodeHelper
#if defined(OS_WIN)
: public rlz_lib::MachineDealCode
#endif
{
public:
static bool Clear() {
#if defined(OS_WIN)
return rlz_lib::MachineDealCode::Clear();
#else
return true;
#endif
}
private:
MachineDealCodeHelper() {}
~MachineDealCodeHelper() {}
};
class RlzLibTest : public RlzLibTestBase {
};
TEST_F(RlzLibTest, RecordProductEvent) {
char cgi_50[50];
EXPECT_TRUE(rlz_lib::ClearAllProductEvents(rlz_lib::TOOLBAR_NOTIFIER));
EXPECT_TRUE(rlz_lib::RecordProductEvent(rlz_lib::TOOLBAR_NOTIFIER,
rlz_lib::IE_DEFAULT_SEARCH, rlz_lib::SET_TO_GOOGLE));
EXPECT_TRUE(rlz_lib::GetProductEventsAsCgi(rlz_lib::TOOLBAR_NOTIFIER,
cgi_50, 50));
EXPECT_STREQ("events=I7S", cgi_50);
EXPECT_TRUE(rlz_lib::RecordProductEvent(rlz_lib::TOOLBAR_NOTIFIER,
rlz_lib::IE_HOME_PAGE, rlz_lib::INSTALL));
EXPECT_TRUE(rlz_lib::GetProductEventsAsCgi(rlz_lib::TOOLBAR_NOTIFIER,
cgi_50, 50));
EXPECT_STREQ("events=I7S,W1I", cgi_50);
EXPECT_TRUE(rlz_lib::RecordProductEvent(rlz_lib::TOOLBAR_NOTIFIER,
rlz_lib::IE_DEFAULT_SEARCH, rlz_lib::SET_TO_GOOGLE));
EXPECT_TRUE(rlz_lib::GetProductEventsAsCgi(rlz_lib::TOOLBAR_NOTIFIER,
cgi_50, 50));
EXPECT_STREQ("events=I7S,W1I", cgi_50);
}
TEST_F(RlzLibTest, ClearProductEvent) {
char cgi_50[50];
// Clear 1 of 1 events.
EXPECT_TRUE(rlz_lib::ClearAllProductEvents(rlz_lib::TOOLBAR_NOTIFIER));
EXPECT_TRUE(rlz_lib::RecordProductEvent(rlz_lib::TOOLBAR_NOTIFIER,
rlz_lib::IE_DEFAULT_SEARCH, rlz_lib::SET_TO_GOOGLE));
EXPECT_TRUE(rlz_lib::GetProductEventsAsCgi(rlz_lib::TOOLBAR_NOTIFIER,
cgi_50, 50));
EXPECT_STREQ("events=I7S", cgi_50);
EXPECT_TRUE(rlz_lib::ClearProductEvent(rlz_lib::TOOLBAR_NOTIFIER,
rlz_lib::IE_DEFAULT_SEARCH, rlz_lib::SET_TO_GOOGLE));
EXPECT_FALSE(rlz_lib::GetProductEventsAsCgi(rlz_lib::TOOLBAR_NOTIFIER,
cgi_50, 50));
EXPECT_STREQ("", cgi_50);
// Clear 1 of 2 events.
EXPECT_TRUE(rlz_lib::ClearAllProductEvents(rlz_lib::TOOLBAR_NOTIFIER));
EXPECT_TRUE(rlz_lib::RecordProductEvent(rlz_lib::TOOLBAR_NOTIFIER,
rlz_lib::IE_DEFAULT_SEARCH, rlz_lib::SET_TO_GOOGLE));
EXPECT_TRUE(rlz_lib::RecordProductEvent(rlz_lib::TOOLBAR_NOTIFIER,
rlz_lib::IE_HOME_PAGE, rlz_lib::INSTALL));
EXPECT_TRUE(rlz_lib::GetProductEventsAsCgi(rlz_lib::TOOLBAR_NOTIFIER,
cgi_50, 50));
EXPECT_STREQ("events=I7S,W1I", cgi_50);
EXPECT_TRUE(rlz_lib::ClearProductEvent(rlz_lib::TOOLBAR_NOTIFIER,
rlz_lib::IE_DEFAULT_SEARCH, rlz_lib::SET_TO_GOOGLE));
EXPECT_TRUE(rlz_lib::GetProductEventsAsCgi(rlz_lib::TOOLBAR_NOTIFIER,
cgi_50, 50));
EXPECT_STREQ("events=W1I", cgi_50);
// Clear a non-recorded event.
EXPECT_TRUE(rlz_lib::ClearProductEvent(rlz_lib::TOOLBAR_NOTIFIER,
rlz_lib::IETB_SEARCH_BOX, rlz_lib::FIRST_SEARCH));
EXPECT_TRUE(rlz_lib::GetProductEventsAsCgi(rlz_lib::TOOLBAR_NOTIFIER,
cgi_50, 50));
EXPECT_STREQ("events=W1I", cgi_50);
}
TEST_F(RlzLibTest, GetProductEventsAsCgi) {
char cgi_50[50];
char cgi_1[1];
EXPECT_TRUE(rlz_lib::ClearAllProductEvents(rlz_lib::TOOLBAR_NOTIFIER));
EXPECT_TRUE(rlz_lib::RecordProductEvent(rlz_lib::TOOLBAR_NOTIFIER,
rlz_lib::IE_DEFAULT_SEARCH, rlz_lib::SET_TO_GOOGLE));
EXPECT_TRUE(rlz_lib::GetProductEventsAsCgi(rlz_lib::TOOLBAR_NOTIFIER,
cgi_50, 50));
EXPECT_TRUE(rlz_lib::RecordProductEvent(rlz_lib::TOOLBAR_NOTIFIER,
rlz_lib::IE_HOME_PAGE, rlz_lib::INSTALL));
EXPECT_FALSE(rlz_lib::GetProductEventsAsCgi(rlz_lib::TOOLBAR_NOTIFIER,
cgi_1, 1));
EXPECT_TRUE(rlz_lib::GetProductEventsAsCgi(rlz_lib::TOOLBAR_NOTIFIER,
cgi_50, 50));
EXPECT_STREQ("events=I7S,W1I", cgi_50);
}
TEST_F(RlzLibTest, ClearAllAllProductEvents) {
char cgi_50[50];
EXPECT_TRUE(rlz_lib::ClearAllProductEvents(rlz_lib::TOOLBAR_NOTIFIER));
EXPECT_TRUE(rlz_lib::RecordProductEvent(rlz_lib::TOOLBAR_NOTIFIER,
rlz_lib::IE_DEFAULT_SEARCH, rlz_lib::SET_TO_GOOGLE));
EXPECT_TRUE(rlz_lib::GetProductEventsAsCgi(rlz_lib::TOOLBAR_NOTIFIER,
cgi_50, 50));
EXPECT_STREQ("events=I7S", cgi_50);
EXPECT_TRUE(rlz_lib::ClearAllProductEvents(rlz_lib::TOOLBAR_NOTIFIER));
EXPECT_FALSE(rlz_lib::GetProductEventsAsCgi(rlz_lib::TOOLBAR_NOTIFIER,
cgi_50, 50));
EXPECT_STREQ("", cgi_50);
}
TEST_F(RlzLibTest, SetAccessPointRlz) {
char rlz_50[50];
EXPECT_TRUE(rlz_lib::SetAccessPointRlz(rlz_lib::IETB_SEARCH_BOX, ""));
EXPECT_TRUE(rlz_lib::GetAccessPointRlz(rlz_lib::IETB_SEARCH_BOX, rlz_50, 50));
EXPECT_STREQ("", rlz_50);
EXPECT_TRUE(rlz_lib::SetAccessPointRlz(rlz_lib::IETB_SEARCH_BOX, "IeTbRlz"));
EXPECT_TRUE(rlz_lib::GetAccessPointRlz(rlz_lib::IETB_SEARCH_BOX, rlz_50, 50));
EXPECT_STREQ("IeTbRlz", rlz_50);
}
TEST_F(RlzLibTest, GetAccessPointRlz) {
char rlz_1[1];
char rlz_50[50];
EXPECT_TRUE(rlz_lib::SetAccessPointRlz(rlz_lib::IETB_SEARCH_BOX, ""));
EXPECT_TRUE(rlz_lib::GetAccessPointRlz(rlz_lib::IETB_SEARCH_BOX, rlz_1, 1));
EXPECT_STREQ("", rlz_1);
EXPECT_TRUE(rlz_lib::SetAccessPointRlz(rlz_lib::IETB_SEARCH_BOX, "IeTbRlz"));
EXPECT_FALSE(rlz_lib::GetAccessPointRlz(rlz_lib::IETB_SEARCH_BOX, rlz_1, 1));
EXPECT_TRUE(rlz_lib::GetAccessPointRlz(rlz_lib::IETB_SEARCH_BOX, rlz_50, 50));
EXPECT_STREQ("IeTbRlz", rlz_50);
}
TEST_F(RlzLibTest, GetPingParams) {
MachineDealCodeHelper::Clear();
EXPECT_TRUE(rlz_lib::SetAccessPointRlz(rlz_lib::IETB_SEARCH_BOX,
"TbRlzValue"));
EXPECT_TRUE(rlz_lib::SetAccessPointRlz(rlz_lib::IE_HOME_PAGE, ""));
char cgi[2048];
rlz_lib::AccessPoint points[] =
{rlz_lib::IETB_SEARCH_BOX, rlz_lib::NO_ACCESS_POINT,
rlz_lib::NO_ACCESS_POINT};
EXPECT_TRUE(rlz_lib::GetPingParams(rlz_lib::TOOLBAR_NOTIFIER, points,
cgi, 2048));
EXPECT_STREQ("rep=2&rlz=T4:TbRlzValue", cgi);
#if defined(OS_WIN)
EXPECT_TRUE(rlz_lib::MachineDealCode::Set("dcc_value"));
#define DCC_PARAM "&dcc=dcc_value"
#else
#define DCC_PARAM ""
#endif
EXPECT_TRUE(rlz_lib::SetAccessPointRlz(rlz_lib::IETB_SEARCH_BOX, ""));
EXPECT_TRUE(rlz_lib::GetPingParams(rlz_lib::TOOLBAR_NOTIFIER, points,
cgi, 2048));
EXPECT_STREQ("rep=2&rlz=T4:" DCC_PARAM, cgi);
EXPECT_TRUE(rlz_lib::SetAccessPointRlz(rlz_lib::IETB_SEARCH_BOX,
"TbRlzValue"));
EXPECT_FALSE(rlz_lib::GetPingParams(rlz_lib::TOOLBAR_NOTIFIER, points,
cgi, 23 + strlen(DCC_PARAM)));
EXPECT_STREQ("", cgi);
EXPECT_TRUE(rlz_lib::GetPingParams(rlz_lib::TOOLBAR_NOTIFIER, points,
cgi, 24 + strlen(DCC_PARAM)));
EXPECT_STREQ("rep=2&rlz=T4:TbRlzValue" DCC_PARAM, cgi);
EXPECT_TRUE(GetAccessPointRlz(rlz_lib::IE_HOME_PAGE, cgi, 2048));
points[2] = rlz_lib::IE_HOME_PAGE;
EXPECT_TRUE(rlz_lib::GetPingParams(rlz_lib::TOOLBAR_NOTIFIER, points,
cgi, 2048));
EXPECT_STREQ("rep=2&rlz=T4:TbRlzValue" DCC_PARAM, cgi);
}
TEST_F(RlzLibTest, IsPingResponseValid) {
const char* kBadPingResponses[] = {
// No checksum.
"version: 3.0.914.7250\r\n"
"url: http://www.corp.google.com/~av/45/opt/SearchWithGoogleUpdate.exe\r\n"
"launch-action: custom-action\r\n"
"launch-target: SearchWithGoogleUpdate.exe\r\n"
"signature: c08a3f4438e1442c4fe5678ee147cf6c5516e5d62bb64e\r\n"
"rlz: 1R1_____en__252\r\n"
"rlzXX: 1R1_____en__250\r\n",
// Invalid checksum.
"version: 3.0.914.7250\r\n"
"url: http://www.corp.google.com/~av/45/opt/SearchWithGoogleUpdate.exe\r\n"
"launch-action: custom-action\r\n"
"launch-target: SearchWithGoogleUpdate.exe\r\n"
"signature: c08a3f4438e1442c4fe5678ee147cf6c5516e5d62bb64e\r\n"
"rlz: 1R1_____en__252\r\n"
"rlzXX: 1R1_____en__250\r\n"
"rlzT4 1T4_____en__251\r\n"
"rlzT4: 1T4_____en__252\r\n"
"rlz\r\n"
"crc32: B12CC79A",
// Misplaced checksum.
"version: 3.0.914.7250\r\n"
"url: http://www.corp.google.com/~av/45/opt/SearchWithGoogleUpdate.exe\r\n"
"launch-action: custom-action\r\n"
"launch-target: SearchWithGoogleUpdate.exe\r\n"
"signature: c08a3f4438e1442c4fe5678ee147cf6c5516e5d62bb64e\r\n"
"rlz: 1R1_____en__252\r\n"
"rlzXX: 1R1_____en__250\r\n"
"crc32: B12CC79C\r\n"
"rlzT4 1T4_____en__251\r\n"
"rlzT4: 1T4_____en__252\r\n"
"rlz\r\n",
NULL
};
const char* kGoodPingResponses[] = {
"version: 3.0.914.7250\r\n"
"url: http://www.corp.google.com/~av/45/opt/SearchWithGoogleUpdate.exe\r\n"
"launch-action: custom-action\r\n"
"launch-target: SearchWithGoogleUpdate.exe\r\n"
"signature: c08a3f4438e1442c4fe5678ee147cf6c5516e5d62bb64e\r\n"
"rlz: 1R1_____en__252\r\n"
"rlzXX: 1R1_____en__250\r\n"
"rlzT4 1T4_____en__251\r\n"
"rlzT4: 1T4_____en__252\r\n"
"rlz\r\n"
"crc32: D6FD55A3",
"version: 3.0.914.7250\r\n"
"url: http://www.corp.google.com/~av/45/opt/SearchWithGoogleUpdate.exe\r\n"
"launch-action: custom-action\r\n"
"launch-target: SearchWithGoogleUpdate.exe\r\n"
"signature: c08a3f4438e1442c4fe5678ee147cf6c5516e5d62bb64e\r\n"
"rlz: 1R1_____en__252\r\n"
"rlzXX: 1R1_____en__250\r\n"
"rlzT4 1T4_____en__251\r\n"
"rlzT4: 1T4_____en__252\r\n"
"rlz\r\n"
"crc32: D6FD55A3\r\n"
"extradata: not checksummed",
NULL
};
for (int i = 0; kBadPingResponses[i]; i++)
EXPECT_FALSE(rlz_lib::IsPingResponseValid(kBadPingResponses[i], NULL));
for (int i = 0; kGoodPingResponses[i]; i++)
EXPECT_TRUE(rlz_lib::IsPingResponseValid(kGoodPingResponses[i], NULL));
}
TEST_F(RlzLibTest, ParsePingResponse) {
const char* kPingResponse =
"version: 3.0.914.7250\r\n"
"url: http://www.corp.google.com/~av/45/opt/SearchWithGoogleUpdate.exe\r\n"
"launch-action: custom-action\r\n"
"launch-target: SearchWithGoogleUpdate.exe\r\n"
"signature: c08a3f4438e1442c4fe5678ee147cf6c5516e5d62bb64e\r\n"
"rlz: 1R1_____en__252\r\n" // Invalid RLZ - no access point.
"rlzXX: 1R1_____en__250\r\n" // Invalid RLZ - bad access point.
"rlzT4 1T4_____en__251\r\n" // Invalid RLZ - missing colon.
"rlzT4: 1T4_____en__252\r\n" // GoodRLZ.
"events: I7S,W1I\r\n" // Clear all events.
"rlz\r\n"
"dcc: dcc_value\r\n"
"crc32: F9070F81";
#if defined(OS_WIN)
EXPECT_TRUE(rlz_lib::MachineDealCode::Set("dcc_value2"));
#endif
// Record some product events to check that they get cleared.
EXPECT_TRUE(rlz_lib::RecordProductEvent(rlz_lib::TOOLBAR_NOTIFIER,
rlz_lib::IE_DEFAULT_SEARCH, rlz_lib::SET_TO_GOOGLE));
EXPECT_TRUE(rlz_lib::RecordProductEvent(rlz_lib::TOOLBAR_NOTIFIER,
rlz_lib::IE_HOME_PAGE, rlz_lib::INSTALL));
EXPECT_TRUE(rlz_lib::SetAccessPointRlz(
rlz_lib::IETB_SEARCH_BOX, "TbRlzValue"));
EXPECT_TRUE(rlz_lib::ParsePingResponse(rlz_lib::TOOLBAR_NOTIFIER,
kPingResponse));
#if defined(OS_WIN)
EXPECT_TRUE(rlz_lib::MachineDealCode::Set("dcc_value"));
#endif
EXPECT_TRUE(rlz_lib::ParsePingResponse(rlz_lib::TOOLBAR_NOTIFIER,
kPingResponse));
char value[50];
EXPECT_TRUE(rlz_lib::GetAccessPointRlz(rlz_lib::IETB_SEARCH_BOX, value, 50));
EXPECT_STREQ("1T4_____en__252", value);
EXPECT_FALSE(rlz_lib::GetProductEventsAsCgi(rlz_lib::TOOLBAR_NOTIFIER,
value, 50));
EXPECT_STREQ("", value);
const char* kPingResponse2 =
"rlzT4: 1T4_____de__253 \r\n" // Good with extra spaces.
"crc32: 321334F5\r\n";
EXPECT_TRUE(rlz_lib::ParsePingResponse(rlz_lib::TOOLBAR_NOTIFIER,
kPingResponse2));
EXPECT_TRUE(rlz_lib::GetAccessPointRlz(rlz_lib::IETB_SEARCH_BOX, value, 50));
EXPECT_STREQ("1T4_____de__253", value);
const char* kPingResponse3 =
"crc32: 0\r\n"; // Good RLZ - empty response.
EXPECT_TRUE(rlz_lib::ParsePingResponse(rlz_lib::TOOLBAR_NOTIFIER,
kPingResponse3));
EXPECT_STREQ("1T4_____de__253", value);
}
// Test whether a stateful event will only be sent in financial pings once.
TEST_F(RlzLibTest, ParsePingResponseWithStatefulEvents) {
const char* kPingResponse =
"version: 3.0.914.7250\r\n"
"url: http://www.corp.google.com/~av/45/opt/SearchWithGoogleUpdate.exe\r\n"
"launch-action: custom-action\r\n"
"launch-target: SearchWithGoogleUpdate.exe\r\n"
"signature: c08a3f4438e1442c4fe5678ee147cf6c5516e5d62bb64e\r\n"
"rlzT4: 1T4_____en__252\r\n" // GoodRLZ.
"events: I7S,W1I\r\n" // Clear all events.
"stateful-events: W1I\r\n" // W1I as an stateful event.
"rlz\r\n"
"dcc: dcc_value\r\n"
"crc32: 55191759";
EXPECT_TRUE(rlz_lib::ClearAllProductEvents(rlz_lib::TOOLBAR_NOTIFIER));
// Record some product events to check that they get cleared.
EXPECT_TRUE(rlz_lib::RecordProductEvent(rlz_lib::TOOLBAR_NOTIFIER,
rlz_lib::IE_DEFAULT_SEARCH, rlz_lib::SET_TO_GOOGLE));
EXPECT_TRUE(rlz_lib::RecordProductEvent(rlz_lib::TOOLBAR_NOTIFIER,
rlz_lib::IE_HOME_PAGE, rlz_lib::INSTALL));
EXPECT_TRUE(rlz_lib::SetAccessPointRlz(
rlz_lib::IETB_SEARCH_BOX, "TbRlzValue"));
EXPECT_TRUE(rlz_lib::ParsePingResponse(rlz_lib::TOOLBAR_NOTIFIER,
kPingResponse));
// Check all the events sent earlier are cleared.
char value[50];
EXPECT_FALSE(rlz_lib::GetProductEventsAsCgi(rlz_lib::TOOLBAR_NOTIFIER,
value, 50));
EXPECT_STREQ("", value);
// Record both events (one is stateless and the other is stateful) again.
EXPECT_TRUE(rlz_lib::RecordProductEvent(rlz_lib::TOOLBAR_NOTIFIER,
rlz_lib::IE_DEFAULT_SEARCH, rlz_lib::SET_TO_GOOGLE));
EXPECT_TRUE(rlz_lib::RecordProductEvent(rlz_lib::TOOLBAR_NOTIFIER,
rlz_lib::IE_HOME_PAGE, rlz_lib::INSTALL));
// Check the stateful event won't be sent again while the stateless one will.
EXPECT_TRUE(rlz_lib::GetProductEventsAsCgi(rlz_lib::TOOLBAR_NOTIFIER,
value, 50));
EXPECT_STREQ("events=I7S", value);
// Test that stateful events are cleared by ClearAllProductEvents(). After
// calling it, trying to record a stateful again should result in it being
// recorded again.
EXPECT_TRUE(rlz_lib::ClearAllProductEvents(rlz_lib::TOOLBAR_NOTIFIER));
EXPECT_TRUE(rlz_lib::RecordProductEvent(rlz_lib::TOOLBAR_NOTIFIER,
rlz_lib::IE_HOME_PAGE, rlz_lib::INSTALL));
EXPECT_TRUE(rlz_lib::GetProductEventsAsCgi(rlz_lib::TOOLBAR_NOTIFIER,
value, 50));
EXPECT_STREQ("events=W1I", value);
}
class URLRequestRAII {
public:
URLRequestRAII(net::URLRequestContextGetter* context) {
rlz_lib::SetURLRequestContext(context);
}
~URLRequestRAII() {
rlz_lib::SetURLRequestContext(NULL);
}
};
TEST_F(RlzLibTest, SendFinancialPing) {
// We don't really check a value or result in this test. All this does is
// attempt to ping the financial server, which you can verify in Fiddler.
// TODO: Make this a measurable test.
#if defined(RLZ_NETWORK_IMPLEMENTATION_CHROME_NET)
#if defined(OS_MACOSX)
base::mac::ScopedNSAutoreleasePool pool;
#endif
base::Thread::Options options;
options.message_loop_type = base::MessageLoop::TYPE_IO;
base::Thread io_thread("rlz_unittest_io_thread");
ASSERT_TRUE(io_thread.StartWithOptions(options));
scoped_refptr<net::TestURLRequestContextGetter> context =
new net::TestURLRequestContextGetter(io_thread.task_runner());
rlz_lib::SetURLRequestContext(context.get());
URLRequestRAII set_context(context.get());
#endif
MachineDealCodeHelper::Clear();
#if defined(OS_WIN)
EXPECT_TRUE(rlz_lib::MachineDealCode::Set("dcc_value"));
#endif
EXPECT_TRUE(rlz_lib::SetAccessPointRlz(rlz_lib::IETB_SEARCH_BOX,
"TbRlzValue"));
EXPECT_TRUE(rlz_lib::ClearAllProductEvents(rlz_lib::TOOLBAR_NOTIFIER));
EXPECT_TRUE(rlz_lib::RecordProductEvent(rlz_lib::TOOLBAR_NOTIFIER,
rlz_lib::IE_DEFAULT_SEARCH, rlz_lib::SET_TO_GOOGLE));
EXPECT_TRUE(rlz_lib::RecordProductEvent(rlz_lib::TOOLBAR_NOTIFIER,
rlz_lib::IE_HOME_PAGE, rlz_lib::INSTALL));
rlz_lib::AccessPoint points[] =
{rlz_lib::IETB_SEARCH_BOX, rlz_lib::NO_ACCESS_POINT,
rlz_lib::NO_ACCESS_POINT};
std::string request;
rlz_lib::SendFinancialPing(rlz_lib::TOOLBAR_NOTIFIER, points,
"swg", "GGLA", "SwgProductId1234", "en-UK", false,
/*skip_time_check=*/true);
}
#if defined(RLZ_NETWORK_IMPLEMENTATION_CHROME_NET)
void ResetContext() {
rlz_lib::SetURLRequestContext(NULL);
}
TEST_F(RlzLibTest, SendFinancialPingDuringShutdown) {
// rlz_lib::SendFinancialPing fails when this is set.
if (!rlz_lib::SupplementaryBranding::GetBrand().empty())
return;
#if defined(OS_MACOSX)
base::mac::ScopedNSAutoreleasePool pool;
#endif
base::Thread::Options options;
options.message_loop_type = base::MessageLoop::TYPE_IO;
base::Thread io_thread("rlz_unittest_io_thread");
ASSERT_TRUE(io_thread.StartWithOptions(options));
scoped_refptr<net::TestURLRequestContextGetter> context =
new net::TestURLRequestContextGetter(io_thread.task_runner());
rlz_lib::SetURLRequestContext(context.get());
URLRequestRAII set_context(context.get());
rlz_lib::AccessPoint points[] =
{rlz_lib::IETB_SEARCH_BOX, rlz_lib::NO_ACCESS_POINT,
rlz_lib::NO_ACCESS_POINT};
rlz_lib::test::ResetSendFinancialPingInterrupted();
EXPECT_FALSE(rlz_lib::test::WasSendFinancialPingInterrupted());
base::MessageLoop loop;
loop.task_runner()->PostTask(FROM_HERE, base::Bind(&ResetContext));
std::string request;
EXPECT_FALSE(rlz_lib::SendFinancialPing(rlz_lib::TOOLBAR_NOTIFIER, points,
"swg", "GGLA", "SwgProductId1234", "en-UK", false,
/*skip_time_check=*/true));
EXPECT_TRUE(rlz_lib::test::WasSendFinancialPingInterrupted());
rlz_lib::test::ResetSendFinancialPingInterrupted();
}
#endif
TEST_F(RlzLibTest, ClearProductState) {
MachineDealCodeHelper::Clear();
EXPECT_TRUE(rlz_lib::SetAccessPointRlz(rlz_lib::IETB_SEARCH_BOX,
"TbRlzValue"));
EXPECT_TRUE(rlz_lib::SetAccessPointRlz(rlz_lib::GD_DESKBAND,
"GdbRlzValue"));
rlz_lib::AccessPoint points[] =
{ rlz_lib::IETB_SEARCH_BOX, rlz_lib::NO_ACCESS_POINT };
EXPECT_TRUE(rlz_lib::RecordProductEvent(rlz_lib::TOOLBAR_NOTIFIER,
rlz_lib::IE_DEFAULT_SEARCH, rlz_lib::SET_TO_GOOGLE));
EXPECT_TRUE(rlz_lib::RecordProductEvent(rlz_lib::TOOLBAR_NOTIFIER,
rlz_lib::IETB_SEARCH_BOX, rlz_lib::INSTALL));
rlz_lib::AccessPoint points2[] =
{ rlz_lib::IETB_SEARCH_BOX,
rlz_lib::GD_DESKBAND,
rlz_lib::NO_ACCESS_POINT };
char cgi[2048];
EXPECT_TRUE(rlz_lib::GetPingParams(rlz_lib::TOOLBAR_NOTIFIER, points2,
cgi, 2048));
EXPECT_STREQ("rep=2&rlz=T4:TbRlzValue,D1:GdbRlzValue", cgi);
EXPECT_TRUE(rlz_lib::GetProductEventsAsCgi(rlz_lib::TOOLBAR_NOTIFIER,
cgi, 2048));
std::string events(cgi);
EXPECT_LT(0u, events.find("I7S"));
EXPECT_LT(0u, events.find("T4I"));
EXPECT_LT(0u, events.find("T4R"));
rlz_lib::ClearProductState(rlz_lib::TOOLBAR_NOTIFIER, points);
EXPECT_TRUE(rlz_lib::GetAccessPointRlz(rlz_lib::IETB_SEARCH_BOX,
cgi, 2048));
EXPECT_STREQ("", cgi);
EXPECT_TRUE(rlz_lib::GetAccessPointRlz(rlz_lib::GD_DESKBAND,
cgi, 2048));
EXPECT_STREQ("GdbRlzValue", cgi);
EXPECT_FALSE(rlz_lib::GetProductEventsAsCgi(rlz_lib::TOOLBAR_NOTIFIER,
cgi, 2048));
EXPECT_STREQ("", cgi);
}
#if defined(OS_WIN)
template<class T>
class typed_buffer_ptr {
std::unique_ptr<char[]> buffer_;
public:
typed_buffer_ptr() {
}
explicit typed_buffer_ptr(size_t size) : buffer_(new char[size]) {
}
void reset(size_t size) {
buffer_.reset(new char[size]);
}
operator T*() {
return reinterpret_cast<T*>(buffer_.get());
}
};
namespace rlz_lib {
bool HasAccess(PSID sid, ACCESS_MASK access_mask, ACL* dacl);
}
bool EmptyAcl(ACL* acl) {
ACL_SIZE_INFORMATION info;
bool ret = GetAclInformation(acl, &info, sizeof(info), AclSizeInformation);
EXPECT_TRUE(ret);
for (DWORD i = 0; i < info.AceCount && ret; ++i) {
ret = DeleteAce(acl, 0);
EXPECT_TRUE(ret);
}
return ret;
}
TEST_F(RlzLibTest, HasAccess) {
// Create a SID that represents ALL USERS.
DWORD users_sid_size = SECURITY_MAX_SID_SIZE;
typed_buffer_ptr<SID> users_sid(users_sid_size);
CreateWellKnownSid(WinBuiltinUsersSid, NULL, users_sid, &users_sid_size);
// RLZ always asks for KEY_ALL_ACCESS access to the key. This is what we
// test here.
// No ACL mean no access.
EXPECT_FALSE(rlz_lib::HasAccess(users_sid, KEY_ALL_ACCESS, NULL));
// Create an ACL for these tests.
const DWORD kMaxAclSize = 1024;
typed_buffer_ptr<ACL> dacl(kMaxAclSize);
InitializeAcl(dacl, kMaxAclSize, ACL_REVISION);
// Empty DACL mean no access.
EXPECT_FALSE(rlz_lib::HasAccess(users_sid, KEY_ALL_ACCESS, dacl));
// ACE without all needed privileges should mean no access.
EXPECT_TRUE(AddAccessAllowedAce(dacl, ACL_REVISION, KEY_READ, users_sid));
EXPECT_FALSE(rlz_lib::HasAccess(users_sid, KEY_ALL_ACCESS, dacl));
// ACE without all needed privileges should mean no access.
EXPECT_TRUE(EmptyAcl(dacl));
EXPECT_TRUE(AddAccessAllowedAce(dacl, ACL_REVISION, KEY_WRITE, users_sid));
EXPECT_FALSE(rlz_lib::HasAccess(users_sid, KEY_ALL_ACCESS, dacl));
// A deny ACE before an allow ACE should not give access.
EXPECT_TRUE(EmptyAcl(dacl));
EXPECT_TRUE(AddAccessDeniedAce(dacl, ACL_REVISION, KEY_ALL_ACCESS,
users_sid));
EXPECT_TRUE(AddAccessAllowedAce(dacl, ACL_REVISION, KEY_ALL_ACCESS,
users_sid));
EXPECT_FALSE(rlz_lib::HasAccess(users_sid, KEY_ALL_ACCESS, dacl));
// A deny ACE before an allow ACE should not give access.
EXPECT_TRUE(EmptyAcl(dacl));
EXPECT_TRUE(AddAccessDeniedAce(dacl, ACL_REVISION, KEY_READ, users_sid));
EXPECT_TRUE(AddAccessAllowedAce(dacl, ACL_REVISION, KEY_ALL_ACCESS,
users_sid));
EXPECT_FALSE(rlz_lib::HasAccess(users_sid, KEY_ALL_ACCESS, dacl));
// An allow ACE without all required bits should not give access.
EXPECT_TRUE(EmptyAcl(dacl));
EXPECT_TRUE(AddAccessAllowedAce(dacl, ACL_REVISION, KEY_WRITE, users_sid));
EXPECT_FALSE(rlz_lib::HasAccess(users_sid, KEY_ALL_ACCESS, dacl));
// An allow ACE with all required bits should give access.
EXPECT_TRUE(EmptyAcl(dacl));
EXPECT_TRUE(AddAccessAllowedAce(dacl, ACL_REVISION, KEY_ALL_ACCESS,
users_sid));
EXPECT_TRUE(rlz_lib::HasAccess(users_sid, KEY_ALL_ACCESS, dacl));
// A deny ACE after an allow ACE should not give access.
EXPECT_TRUE(EmptyAcl(dacl));
EXPECT_TRUE(AddAccessAllowedAce(dacl, ACL_REVISION, KEY_ALL_ACCESS,
users_sid));
EXPECT_TRUE(AddAccessDeniedAce(dacl, ACL_REVISION, KEY_READ, users_sid));
EXPECT_TRUE(rlz_lib::HasAccess(users_sid, KEY_ALL_ACCESS, dacl));
// An inherit-only allow ACE should not give access.
EXPECT_TRUE(EmptyAcl(dacl));
EXPECT_TRUE(AddAccessAllowedAceEx(dacl, ACL_REVISION, INHERIT_ONLY_ACE,
KEY_ALL_ACCESS, users_sid));
EXPECT_FALSE(rlz_lib::HasAccess(users_sid, KEY_ALL_ACCESS, dacl));
// An inherit-only deny ACE should not apply.
EXPECT_TRUE(EmptyAcl(dacl));
EXPECT_TRUE(AddAccessDeniedAceEx(dacl, ACL_REVISION, INHERIT_ONLY_ACE,
KEY_ALL_ACCESS, users_sid));
EXPECT_TRUE(AddAccessAllowedAce(dacl, ACL_REVISION, KEY_ALL_ACCESS,
users_sid));
EXPECT_TRUE(rlz_lib::HasAccess(users_sid, KEY_ALL_ACCESS, dacl));
}
#endif
TEST_F(RlzLibTest, BrandingRecordProductEvent) {
// Don't run these tests if a supplementary brand is already in place. That
// way we can control the branding.
if (!rlz_lib::SupplementaryBranding::GetBrand().empty())
return;
char cgi_50[50];
// Record different events for the same product with diffrent branding, and
// make sure that the information remains separate.
EXPECT_TRUE(rlz_lib::ClearAllProductEvents(rlz_lib::TOOLBAR_NOTIFIER));
{
rlz_lib::SupplementaryBranding branding("TEST");
EXPECT_TRUE(rlz_lib::ClearAllProductEvents(rlz_lib::TOOLBAR_NOTIFIER));
}
// Test that recording events with the default brand and a supplementary
// brand don't overwrite each other.
EXPECT_TRUE(rlz_lib::RecordProductEvent(rlz_lib::TOOLBAR_NOTIFIER,
rlz_lib::IE_DEFAULT_SEARCH, rlz_lib::SET_TO_GOOGLE));
EXPECT_TRUE(rlz_lib::GetProductEventsAsCgi(rlz_lib::TOOLBAR_NOTIFIER,
cgi_50, 50));
EXPECT_STREQ("events=I7S", cgi_50);
{
rlz_lib::SupplementaryBranding branding("TEST");
EXPECT_TRUE(rlz_lib::RecordProductEvent(rlz_lib::TOOLBAR_NOTIFIER,
rlz_lib::IE_DEFAULT_SEARCH, rlz_lib::INSTALL));
EXPECT_TRUE(rlz_lib::GetProductEventsAsCgi(rlz_lib::TOOLBAR_NOTIFIER,
cgi_50, 50));
EXPECT_STREQ("events=I7I", cgi_50);
}
EXPECT_TRUE(rlz_lib::GetProductEventsAsCgi(rlz_lib::TOOLBAR_NOTIFIER,
cgi_50, 50));
EXPECT_STREQ("events=I7S", cgi_50);
}
TEST_F(RlzLibTest, BrandingSetAccessPointRlz) {
// Don't run these tests if a supplementary brand is already in place. That
// way we can control the branding.
if (!rlz_lib::SupplementaryBranding::GetBrand().empty())
return;
char rlz_50[50];
// Test that setting RLZ strings with the default brand and a supplementary
// brand don't overwrite each other.
EXPECT_TRUE(rlz_lib::SetAccessPointRlz(rlz_lib::IETB_SEARCH_BOX, "IeTbRlz"));
EXPECT_TRUE(rlz_lib::GetAccessPointRlz(rlz_lib::IETB_SEARCH_BOX, rlz_50, 50));
EXPECT_STREQ("IeTbRlz", rlz_50);
{
rlz_lib::SupplementaryBranding branding("TEST");
EXPECT_TRUE(rlz_lib::SetAccessPointRlz(rlz_lib::IETB_SEARCH_BOX, "SuppRlz"));
EXPECT_TRUE(rlz_lib::GetAccessPointRlz(rlz_lib::IETB_SEARCH_BOX, rlz_50,
50));
EXPECT_STREQ("SuppRlz", rlz_50);
}
EXPECT_TRUE(rlz_lib::GetAccessPointRlz(rlz_lib::IETB_SEARCH_BOX, rlz_50, 50));
EXPECT_STREQ("IeTbRlz", rlz_50);
}
TEST_F(RlzLibTest, BrandingWithStatefulEvents) {
// Don't run these tests if a supplementary brand is already in place. That
// way we can control the branding.
if (!rlz_lib::SupplementaryBranding::GetBrand().empty())
return;
const char* kPingResponse =
"version: 3.0.914.7250\r\n"
"url: http://www.corp.google.com/~av/45/opt/SearchWithGoogleUpdate.exe\r\n"
"launch-action: custom-action\r\n"
"launch-target: SearchWithGoogleUpdate.exe\r\n"
"signature: c08a3f4438e1442c4fe5678ee147cf6c5516e5d62bb64e\r\n"
"rlzT4: 1T4_____en__252\r\n" // GoodRLZ.
"events: I7S,W1I\r\n" // Clear all events.
"stateful-events: W1I\r\n" // W1I as an stateful event.
"rlz\r\n"
"dcc: dcc_value\r\n"
"crc32: 55191759";
EXPECT_TRUE(rlz_lib::ClearAllProductEvents(rlz_lib::TOOLBAR_NOTIFIER));
{
rlz_lib::SupplementaryBranding branding("TEST");
EXPECT_TRUE(rlz_lib::ClearAllProductEvents(rlz_lib::TOOLBAR_NOTIFIER));
}
// Record some product events for the default and supplementary brand.
// Check that they get cleared only for the default brand.
EXPECT_TRUE(rlz_lib::RecordProductEvent(rlz_lib::TOOLBAR_NOTIFIER,
rlz_lib::IE_DEFAULT_SEARCH, rlz_lib::SET_TO_GOOGLE));
EXPECT_TRUE(rlz_lib::RecordProductEvent(rlz_lib::TOOLBAR_NOTIFIER,
rlz_lib::IE_HOME_PAGE, rlz_lib::INSTALL));
{
rlz_lib::SupplementaryBranding branding("TEST");
EXPECT_TRUE(rlz_lib::RecordProductEvent(rlz_lib::TOOLBAR_NOTIFIER,
rlz_lib::IE_DEFAULT_SEARCH, rlz_lib::SET_TO_GOOGLE));
EXPECT_TRUE(rlz_lib::RecordProductEvent(rlz_lib::TOOLBAR_NOTIFIER,
rlz_lib::IE_HOME_PAGE, rlz_lib::INSTALL));
}
EXPECT_TRUE(rlz_lib::ParsePingResponse(rlz_lib::TOOLBAR_NOTIFIER,
kPingResponse));
// Check all the events sent earlier are cleared only for default brand.
char value[50];
EXPECT_FALSE(rlz_lib::GetProductEventsAsCgi(rlz_lib::TOOLBAR_NOTIFIER,
value, 50));
EXPECT_STREQ("", value);
{
rlz_lib::SupplementaryBranding branding("TEST");
EXPECT_TRUE(rlz_lib::GetProductEventsAsCgi(rlz_lib::TOOLBAR_NOTIFIER,
value, 50));
EXPECT_STREQ("events=I7S,W1I", value);
}
// Record both events (one is stateless and the other is stateful) again.
EXPECT_TRUE(rlz_lib::RecordProductEvent(rlz_lib::TOOLBAR_NOTIFIER,
rlz_lib::IE_DEFAULT_SEARCH, rlz_lib::SET_TO_GOOGLE));
EXPECT_TRUE(rlz_lib::RecordProductEvent(rlz_lib::TOOLBAR_NOTIFIER,
rlz_lib::IE_HOME_PAGE, rlz_lib::INSTALL));
// Check the stateful event won't be sent again while the stateless one will.
EXPECT_TRUE(rlz_lib::GetProductEventsAsCgi(rlz_lib::TOOLBAR_NOTIFIER,
value, 50));
EXPECT_STREQ("events=I7S", value);
{
rlz_lib::SupplementaryBranding branding("TEST");
EXPECT_TRUE(rlz_lib::ParsePingResponse(rlz_lib::TOOLBAR_NOTIFIER,
kPingResponse));
EXPECT_FALSE(rlz_lib::GetProductEventsAsCgi(rlz_lib::TOOLBAR_NOTIFIER,
value, 50));
EXPECT_STREQ("", value);
}
EXPECT_TRUE(rlz_lib::GetProductEventsAsCgi(rlz_lib::TOOLBAR_NOTIFIER,
value, 50));
EXPECT_STREQ("events=I7S", value);
}
#if defined(OS_POSIX)
class ReadonlyRlzDirectoryTest : public RlzLibTestNoMachineState {
protected:
void SetUp() override;
};
void ReadonlyRlzDirectoryTest::SetUp() {
RlzLibTestNoMachineState::SetUp();
// Make the rlz directory non-writeable.
int chmod_result = chmod(m_rlz_test_helper_.temp_dir_.path().value().c_str(),
0500);
ASSERT_EQ(0, chmod_result);
}
TEST_F(ReadonlyRlzDirectoryTest, WriteFails) {
// The rlz test runner runs every test twice: Once normally, and once with
// a SupplementaryBranding on the stack. In the latter case, the rlz lock
// has already been acquired before the rlz directory got changed to
// read-only, which makes this test pointless. So run it only in the first
// pass.
if (!rlz_lib::SupplementaryBranding::GetBrand().empty())
return;
EXPECT_FALSE(rlz_lib::RecordProductEvent(rlz_lib::TOOLBAR_NOTIFIER,
rlz_lib::IE_DEFAULT_SEARCH, rlz_lib::SET_TO_GOOGLE));
}
// Regression test for http://crbug.com/121255
TEST_F(ReadonlyRlzDirectoryTest, SupplementaryBrandingDoesNotCrash) {
// See the comment at the top of WriteFails.
if (!rlz_lib::SupplementaryBranding::GetBrand().empty())
return;
rlz_lib::SupplementaryBranding branding("TEST");
EXPECT_FALSE(rlz_lib::RecordProductEvent(rlz_lib::TOOLBAR_NOTIFIER,
rlz_lib::IE_DEFAULT_SEARCH, rlz_lib::INSTALL));
}
// Regression test for http://crbug.com/141108
TEST_F(RlzLibTest, ConcurrentStoreAccessWithProcessExitsWhileLockHeld) {
// See the comment at the top of WriteFails.
if (!rlz_lib::SupplementaryBranding::GetBrand().empty())
return;
std::vector<pid_t> pids;
for (int i = 0; i < 10; ++i) {
pid_t pid = fork();
ASSERT_NE(-1, pid);
if (pid == 0) {
// Child.
{
// SupplementaryBranding is a RAII object for the rlz lock.
rlz_lib::SupplementaryBranding branding("TEST");
// Simulate a crash while holding the lock in some of the children.
if (i > 0 && i % 3 == 0)
_exit(0);
// Note: Since this is in a forked child, a failing expectation won't
// make the test fail. It does however cause lots of "check failed"
// error output. The parent process will then check the exit code
// below to make the test fail.
bool success = rlz_lib::RecordProductEvent(rlz_lib::TOOLBAR_NOTIFIER,
rlz_lib::IE_DEFAULT_SEARCH, rlz_lib::INSTALL);
EXPECT_TRUE(success);
_exit(success ? 0 : 1);
}
_exit(0);
} else {
// Parent.
pids.push_back(pid);
}
}
int status;
for (size_t i = 0; i < pids.size(); ++i) {
if (HANDLE_EINTR(waitpid(pids[i], &status, 0)) != -1)
EXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0);
}
// No child should have the lock at this point, not even the crashed ones.
EXPECT_TRUE(rlz_lib::RecordProductEvent(rlz_lib::TOOLBAR_NOTIFIER,
rlz_lib::IE_DEFAULT_SEARCH, rlz_lib::INSTALL));
}
TEST_F(RlzLibTest, LockAcquistionSucceedsButStoreFileCannotBeCreated) {
// See the comment at the top of WriteFails.
if (!rlz_lib::SupplementaryBranding::GetBrand().empty())
return;
// Create a directory where the rlz file is supposed to appear. This way,
// the lock file can be created successfully, but creation of the rlz file
// itself will fail.
int mkdir_result = mkdir(rlz_lib::testing::RlzStoreFilenameStr().c_str(),
0500);
ASSERT_EQ(0, mkdir_result);
rlz_lib::SupplementaryBranding branding("TEST");
EXPECT_FALSE(rlz_lib::RecordProductEvent(rlz_lib::TOOLBAR_NOTIFIER,
rlz_lib::IE_DEFAULT_SEARCH, rlz_lib::INSTALL));
}
#endif
| danakj/chromium | rlz/lib/rlz_lib_test.cc | C++ | bsd-3-clause | 35,236 |
/*
**
** File: ymdeltat.c
**
** YAMAHA DELTA-T adpcm sound emulation subroutine
** used by fmopl.c (Y8950) and fm.c (YM2608 and YM2610/B)
**
** Base program is YM2610 emulator by Hiromitsu Shioya.
** Written by Tatsuyuki Satoh
** Improvements by Jarek Burczynski (bujar at mame dot net)
**
**
** History:
**
** 03-08-2003 Jarek Burczynski:
** - fixed BRDY flag implementation.
**
** 24-07-2003 Jarek Burczynski, Frits Hilderink:
** - fixed delault value for control2 in YM_DELTAT_ADPCM_Reset
**
** 22-07-2003 Jarek Burczynski, Frits Hilderink:
** - fixed external memory support
**
** 15-06-2003 Jarek Burczynski:
** - implemented CPU -> AUDIO ADPCM synthesis (via writes to the ADPCM data reg $08)
** - implemented support for the Limit address register
** - supported two bits from the control register 2 ($01): RAM TYPE (x1 bit/x8 bit), ROM/RAM
** - implemented external memory access (read/write) via the ADPCM data reg reads/writes
** Thanks go to Frits Hilderink for the example code.
**
** 14-06-2003 Jarek Burczynski:
** - various fixes to enable proper support for status register flags: BSRDY, PCM BSY, ZERO
** - modified EOS handling
**
** 05-04-2003 Jarek Burczynski:
** - implemented partial support for external/processor memory on sample replay
**
** 01-12-2002 Jarek Burczynski:
** - fixed first missing sound in gigandes thanks to previous fix (interpolator) by ElSemi
** - renamed/removed some YM_DELTAT struct fields
**
** 28-12-2001 Acho A. Tang
** - added EOS status report on ADPCM playback.
**
** 05-08-2001 Jarek Burczynski:
** - now_step is initialized with 0 at the start of play.
**
** 12-06-2001 Jarek Burczynski:
** - corrected end of sample bug in YM_DELTAT_ADPCM_CALC.
** Checked on real YM2610 chip - address register is 24 bits wide.
** Thanks go to Stefan Jokisch (stefan.jokisch@gmx.de) for tracking down the problem.
**
** TO DO:
** Check size of the address register on the other chips....
**
** Version 0.72
**
** sound chips that have this unit:
** YM2608 OPNA
** YM2610/B OPNB
** Y8950 MSX AUDIO
**
*/
#include "ymdeltat.h"
#ifndef INLINE
#define INLINE __inline
#endif
#ifndef logerror
#define logerror (void)
#endif
#define YM_DELTAT_DELTA_MAX (24576)
#define YM_DELTAT_DELTA_MIN (127)
#define YM_DELTAT_DELTA_DEF (127)
#define YM_DELTAT_DECODE_RANGE 32768
#define YM_DELTAT_DECODE_MIN (-(YM_DELTAT_DECODE_RANGE))
#define YM_DELTAT_DECODE_MAX ((YM_DELTAT_DECODE_RANGE)-1)
/* Forecast to next Forecast (rate = *8) */
/* 1/8 , 3/8 , 5/8 , 7/8 , 9/8 , 11/8 , 13/8 , 15/8 */
static const INT32 ym_deltat_decode_tableB1[16] = {
1, 3, 5, 7, 9, 11, 13, 15,
-1, -3, -5, -7, -9, -11, -13, -15,
};
/* delta to next delta (rate= *64) */
/* 0.9 , 0.9 , 0.9 , 0.9 , 1.2 , 1.6 , 2.0 , 2.4 */
static const INT32 ym_deltat_decode_tableB2[16] = {
57, 57, 57, 57, 77, 102, 128, 153,
57, 57, 57, 57, 77, 102, 128, 153
};
#if 0
void YM_DELTAT_BRDY_callback(YM_DELTAT *DELTAT)
{
logerror("BRDY_callback reached (flag set) !\n");
/* set BRDY bit in status register */
if(DELTAT->status_set_handler)
if(DELTAT->status_change_BRDY_bit)
(DELTAT->status_set_handler)(DELTAT->status_change_which_chip, DELTAT->status_change_BRDY_bit);
}
#endif
UINT8 YM_DELTAT_ADPCM_Read(YM_DELTAT *DELTAT)
{
UINT8 v = 0;
/* external memory read */
if ( (DELTAT->portstate & 0xe0)==0x20 )
{
/* two dummy reads */
if (DELTAT->memread)
{
DELTAT->now_addr = DELTAT->start << 1;
DELTAT->memread--;
return 0;
}
if ( DELTAT->now_addr != (DELTAT->end<<1) )
{
v = DELTAT->memory[DELTAT->now_addr>>1];
/*logerror("YM Delta-T memory read $%08x, v=$%02x\n", DELTAT->now_addr >> 1, v);*/
DELTAT->now_addr+=2; /* two nibbles at a time */
/* reset BRDY bit in status register, which means we are reading the memory now */
if(DELTAT->status_reset_handler)
if(DELTAT->status_change_BRDY_bit)
(DELTAT->status_reset_handler)(DELTAT->status_change_which_chip, DELTAT->status_change_BRDY_bit);
/* setup a timer that will callback us in 10 master clock cycles for Y8950
* in the callback set the BRDY flag to 1 , which means we have another data ready.
* For now, we don't really do this; we simply reset and set the flag in zero time, so that the IRQ will work.
*/
/* set BRDY bit in status register */
if(DELTAT->status_set_handler)
if(DELTAT->status_change_BRDY_bit)
(DELTAT->status_set_handler)(DELTAT->status_change_which_chip, DELTAT->status_change_BRDY_bit);
}
else
{
/* set EOS bit in status register */
if(DELTAT->status_set_handler)
if(DELTAT->status_change_EOS_bit)
(DELTAT->status_set_handler)(DELTAT->status_change_which_chip, DELTAT->status_change_EOS_bit);
}
}
return v;
}
/* 0-DRAM x1, 1-ROM, 2-DRAM x8, 3-ROM (3 is bad setting - not allowed by the manual) */
static const UINT8 dram_rightshift[4]={3,0,0,0};
/* DELTA-T ADPCM write register */
void YM_DELTAT_ADPCM_Write(YM_DELTAT *DELTAT,int r,int v)
{
if(r>=0x10) return;
DELTAT->reg[r] = v; /* stock data */
switch( r )
{
case 0x00:
/*
START:
Accessing *external* memory is started when START bit (D7) is set to "1", so
you must set all conditions needed for recording/playback before starting.
If you access *CPU-managed* memory, recording/playback starts after
read/write of ADPCM data register $08.
REC:
0 = ADPCM synthesis (playback)
1 = ADPCM analysis (record)
MEMDATA:
0 = processor (*CPU-managed*) memory (means: using register $08)
1 = external memory (using start/end/limit registers to access memory: RAM or ROM)
SPOFF:
controls output pin that should disable the speaker while ADPCM analysis
RESET and REPEAT only work with external memory.
some examples:
value: START, REC, MEMDAT, REPEAT, SPOFF, x,x,RESET meaning:
C8 1 1 0 0 1 0 0 0 Analysis (recording) from AUDIO to CPU (to reg $08), sample rate in PRESCALER register
E8 1 1 1 0 1 0 0 0 Analysis (recording) from AUDIO to EXT.MEMORY, sample rate in PRESCALER register
80 1 0 0 0 0 0 0 0 Synthesis (playing) from CPU (from reg $08) to AUDIO,sample rate in DELTA-N register
a0 1 0 1 0 0 0 0 0 Synthesis (playing) from EXT.MEMORY to AUDIO, sample rate in DELTA-N register
60 0 1 1 0 0 0 0 0 External memory write via ADPCM data register $08
20 0 0 1 0 0 0 0 0 External memory read via ADPCM data register $08
*/
/* handle emulation mode */
if(DELTAT->emulation_mode == YM_DELTAT_EMULATION_MODE_YM2610)
{
v |= 0x20; /* YM2610 always uses external memory and doesn't even have memory flag bit. */
}
DELTAT->portstate = v & (0x80|0x40|0x20|0x10|0x01); /* start, rec, memory mode, repeat flag copy, reset(bit0) */
if( DELTAT->portstate&0x80 )/* START,REC,MEMDATA,REPEAT,SPOFF,--,--,RESET */
{
/* set PCM BUSY bit */
DELTAT->PCM_BSY = 1;
/* start ADPCM */
DELTAT->now_step = 0;
DELTAT->acc = 0;
DELTAT->prev_acc = 0;
DELTAT->adpcml = 0;
DELTAT->adpcmd = YM_DELTAT_DELTA_DEF;
DELTAT->now_data = 0;
}
if( DELTAT->portstate&0x20 ) /* do we access external memory? */
{
DELTAT->now_addr = DELTAT->start << 1;
DELTAT->memread = 2; /* two dummy reads needed before accesing external memory via register $08*/
/* if yes, then let's check if ADPCM memory is mapped and big enough */
if(DELTAT->memory == 0)
{
/*logerror("YM Delta-T ADPCM rom not mapped\n");*/
DELTAT->portstate = 0x00;
DELTAT->PCM_BSY = 0;
}
else
{
if( DELTAT->end >= DELTAT->memory_size ) /* Check End in Range */
{
/*logerror("YM Delta-T ADPCM end out of range: $%08x\n", DELTAT->end);*/
DELTAT->end = DELTAT->memory_size - 1;
}
if( DELTAT->start >= DELTAT->memory_size ) /* Check Start in Range */
{
/*logerror("YM Delta-T ADPCM start out of range: $%08x\n", DELTAT->start);*/
DELTAT->portstate = 0x00;
DELTAT->PCM_BSY = 0;
}
}
}
else /* we access CPU memory (ADPCM data register $08) so we only reset now_addr here */
{
DELTAT->now_addr = 0;
}
if( DELTAT->portstate&0x01 )
{
DELTAT->portstate = 0x00;
/* clear PCM BUSY bit (in status register) */
DELTAT->PCM_BSY = 0;
/* set BRDY flag */
if(DELTAT->status_set_handler)
if(DELTAT->status_change_BRDY_bit)
(DELTAT->status_set_handler)(DELTAT->status_change_which_chip, DELTAT->status_change_BRDY_bit);
}
break;
case 0x01: /* L,R,-,-,SAMPLE,DA/AD,RAMTYPE,ROM */
/* handle emulation mode */
if(DELTAT->emulation_mode == YM_DELTAT_EMULATION_MODE_YM2610)
{
v |= 0x01; /* YM2610 always uses ROM as an external memory and doesn't tave ROM/RAM memory flag bit. */
}
DELTAT->pan = &DELTAT->output_pointer[(v>>6)&0x03];
if ((DELTAT->control2 & 3) != (v & 3))
{
/*0-DRAM x1, 1-ROM, 2-DRAM x8, 3-ROM (3 is bad setting - not allowed by the manual) */
if (DELTAT->DRAMportshift != dram_rightshift[v&3])
{
DELTAT->DRAMportshift = dram_rightshift[v&3];
/* final shift value depends on chip type and memory type selected:
8 for YM2610 (ROM only),
5 for ROM for Y8950 and YM2608,
5 for x8bit DRAMs for Y8950 and YM2608,
2 for x1bit DRAMs for Y8950 and YM2608.
*/
/* refresh addresses */
DELTAT->start = (DELTAT->reg[0x3]*0x0100 | DELTAT->reg[0x2]) << (DELTAT->portshift - DELTAT->DRAMportshift);
DELTAT->end = (DELTAT->reg[0x5]*0x0100 | DELTAT->reg[0x4]) << (DELTAT->portshift - DELTAT->DRAMportshift);
DELTAT->end += (1 << (DELTAT->portshift-DELTAT->DRAMportshift) ) - 1;
DELTAT->limit = (DELTAT->reg[0xd]*0x0100 | DELTAT->reg[0xc]) << (DELTAT->portshift - DELTAT->DRAMportshift);
}
}
DELTAT->control2 = v;
break;
case 0x02: /* Start Address L */
case 0x03: /* Start Address H */
DELTAT->start = (DELTAT->reg[0x3]*0x0100 | DELTAT->reg[0x2]) << (DELTAT->portshift - DELTAT->DRAMportshift);
/*logerror("DELTAT start: 02=%2x 03=%2x addr=%8x\n",DELTAT->reg[0x2], DELTAT->reg[0x3],DELTAT->start );*/
break;
case 0x04: /* Stop Address L */
case 0x05: /* Stop Address H */
DELTAT->end = (DELTAT->reg[0x5]*0x0100 | DELTAT->reg[0x4]) << (DELTAT->portshift - DELTAT->DRAMportshift);
DELTAT->end += (1 << (DELTAT->portshift-DELTAT->DRAMportshift) ) - 1;
/*logerror("DELTAT end : 04=%2x 05=%2x addr=%8x\n",DELTAT->reg[0x4], DELTAT->reg[0x5],DELTAT->end );*/
break;
case 0x06: /* Prescale L (ADPCM and Record frq) */
case 0x07: /* Prescale H */
break;
case 0x08: /* ADPCM data */
/*
some examples:
value: START, REC, MEMDAT, REPEAT, SPOFF, x,x,RESET meaning:
C8 1 1 0 0 1 0 0 0 Analysis (recording) from AUDIO to CPU (to reg $08), sample rate in PRESCALER register
E8 1 1 1 0 1 0 0 0 Analysis (recording) from AUDIO to EXT.MEMORY, sample rate in PRESCALER register
80 1 0 0 0 0 0 0 0 Synthesis (playing) from CPU (from reg $08) to AUDIO,sample rate in DELTA-N register
a0 1 0 1 0 0 0 0 0 Synthesis (playing) from EXT.MEMORY to AUDIO, sample rate in DELTA-N register
60 0 1 1 0 0 0 0 0 External memory write via ADPCM data register $08
20 0 0 1 0 0 0 0 0 External memory read via ADPCM data register $08
*/
/* external memory write */
if ( (DELTAT->portstate & 0xe0)==0x60 )
{
if (DELTAT->memread)
{
DELTAT->now_addr = DELTAT->start << 1;
DELTAT->memread = 0;
}
/*logerror("YM Delta-T memory write $%08x, v=$%02x\n", DELTAT->now_addr >> 1, v);*/
if ( DELTAT->now_addr != (DELTAT->end<<1) )
{
DELTAT->memory[DELTAT->now_addr>>1] = v;
DELTAT->now_addr+=2; /* two nibbles at a time */
/* reset BRDY bit in status register, which means we are processing the write */
if(DELTAT->status_reset_handler)
if(DELTAT->status_change_BRDY_bit)
(DELTAT->status_reset_handler)(DELTAT->status_change_which_chip, DELTAT->status_change_BRDY_bit);
/* setup a timer that will callback us in 10 master clock cycles for Y8950
* in the callback set the BRDY flag to 1 , which means we have written the data.
* For now, we don't really do this; we simply reset and set the flag in zero time, so that the IRQ will work.
*/
/* set BRDY bit in status register */
if(DELTAT->status_set_handler)
if(DELTAT->status_change_BRDY_bit)
(DELTAT->status_set_handler)(DELTAT->status_change_which_chip, DELTAT->status_change_BRDY_bit);
}
else
{
/* set EOS bit in status register */
if(DELTAT->status_set_handler)
if(DELTAT->status_change_EOS_bit)
(DELTAT->status_set_handler)(DELTAT->status_change_which_chip, DELTAT->status_change_EOS_bit);
}
return;
}
/* ADPCM synthesis from CPU */
if ( (DELTAT->portstate & 0xe0)==0x80 )
{
DELTAT->CPU_data = v;
/* Reset BRDY bit in status register, which means we are full of data */
if(DELTAT->status_reset_handler)
if(DELTAT->status_change_BRDY_bit)
(DELTAT->status_reset_handler)(DELTAT->status_change_which_chip, DELTAT->status_change_BRDY_bit);
return;
}
break;
case 0x09: /* DELTA-N L (ADPCM Playback Prescaler) */
case 0x0a: /* DELTA-N H */
DELTAT->delta = (DELTAT->reg[0xa]*0x0100 | DELTAT->reg[0x9]);
DELTAT->step = (UINT32)( (double)(DELTAT->delta /* *(1<<(YM_DELTAT_SHIFT-16)) */ ) * (DELTAT->freqbase) );
/*logerror("DELTAT deltan:09=%2x 0a=%2x\n",DELTAT->reg[0x9], DELTAT->reg[0xa]);*/
break;
case 0x0b: /* Output level control (volume, linear) */
{
INT32 oldvol = DELTAT->volume;
DELTAT->volume = (v&0xff) * (DELTAT->output_range/256) / YM_DELTAT_DECODE_RANGE;
/* v * ((1<<16)>>8) >> 15;
* thus: v * (1<<8) >> 15;
* thus: output_range must be (1 << (15+8)) at least
* v * ((1<<23)>>8) >> 15;
* v * (1<<15) >> 15;
*/
/*logerror("DELTAT vol = %2x\n",v&0xff);*/
if( oldvol != 0 )
{
DELTAT->adpcml = (int)((double)DELTAT->adpcml / (double)oldvol * (double)DELTAT->volume);
}
}
break;
case 0x0c: /* Limit Address L */
case 0x0d: /* Limit Address H */
DELTAT->limit = (DELTAT->reg[0xd]*0x0100 | DELTAT->reg[0xc]) << (DELTAT->portshift - DELTAT->DRAMportshift);
/*logerror("DELTAT limit: 0c=%2x 0d=%2x addr=%8x\n",DELTAT->reg[0xc], DELTAT->reg[0xd],DELTAT->limit );*/
break;
}
}
void YM_DELTAT_ADPCM_Reset(YM_DELTAT *DELTAT,int pan,int emulation_mode)
{
DELTAT->now_addr = 0;
DELTAT->now_step = 0;
DELTAT->step = 0;
DELTAT->start = 0;
DELTAT->end = 0;
DELTAT->limit = ~0; /* this way YM2610 and Y8950 (both of which don't have limit address reg) will still work */
DELTAT->volume = 0;
DELTAT->pan = &DELTAT->output_pointer[pan];
DELTAT->acc = 0;
DELTAT->prev_acc = 0;
DELTAT->adpcmd = 127;
DELTAT->adpcml = 0;
DELTAT->emulation_mode = (UINT8)emulation_mode;
DELTAT->portstate = (emulation_mode == YM_DELTAT_EMULATION_MODE_YM2610) ? 0x20 : 0;
DELTAT->control2 = (emulation_mode == YM_DELTAT_EMULATION_MODE_YM2610) ? 0x01 : 0; /* default setting depends on the emulation mode. MSX demo called "facdemo_4" doesn't setup control2 register at all and still works */
DELTAT->DRAMportshift = dram_rightshift[DELTAT->control2 & 3];
/* The flag mask register disables the BRDY after the reset, however
** as soon as the mask is enabled the flag needs to be set. */
/* set BRDY bit in status register */
if(DELTAT->status_set_handler)
if(DELTAT->status_change_BRDY_bit)
(DELTAT->status_set_handler)(DELTAT->status_change_which_chip, DELTAT->status_change_BRDY_bit);
}
#if 0
void YM_DELTAT_postload(YM_DELTAT *DELTAT,UINT8 *regs)
{
int r;
/* to keep adpcml */
DELTAT->volume = 0;
/* update */
for(r=1;r<16;r++)
YM_DELTAT_ADPCM_Write(DELTAT,r,regs[r]);
DELTAT->reg[0] = regs[0];
/* current rom data */
if (DELTAT->memory)
DELTAT->now_data = *(DELTAT->memory + (DELTAT->now_addr>>1) );
}
void YM_DELTAT_savestate(const device_config *device,YM_DELTAT *DELTAT)
{
#ifdef __STATE_H__
state_save_register_device_item(device, 0, DELTAT->portstate);
state_save_register_device_item(device, 0, DELTAT->now_addr);
state_save_register_device_item(device, 0, DELTAT->now_step);
state_save_register_device_item(device, 0, DELTAT->acc);
state_save_register_device_item(device, 0, DELTAT->prev_acc);
state_save_register_device_item(device, 0, DELTAT->adpcmd);
state_save_register_device_item(device, 0, DELTAT->adpcml);
#endif
}
#endif
#define YM_DELTAT_Limit(val,max,min) \
{ \
if ( val > max ) val = max; \
else if ( val < min ) val = min; \
}
INLINE void YM_DELTAT_synthesis_from_external_memory(YM_DELTAT *DELTAT)
{
UINT32 step;
int data;
DELTAT->now_step += DELTAT->step;
if ( DELTAT->now_step >= (1<<YM_DELTAT_SHIFT) )
{
step = DELTAT->now_step >> YM_DELTAT_SHIFT;
DELTAT->now_step &= (1<<YM_DELTAT_SHIFT)-1;
do{
if ( DELTAT->now_addr == (DELTAT->limit<<1) )
DELTAT->now_addr = 0;
if ( DELTAT->now_addr == (DELTAT->end<<1) ) { /* 12-06-2001 JB: corrected comparison. Was > instead of == */
if( DELTAT->portstate&0x10 ){
/* repeat start */
DELTAT->now_addr = DELTAT->start<<1;
DELTAT->acc = 0;
DELTAT->adpcmd = YM_DELTAT_DELTA_DEF;
DELTAT->prev_acc = 0;
}else{
/* set EOS bit in status register */
if(DELTAT->status_set_handler)
if(DELTAT->status_change_EOS_bit)
(DELTAT->status_set_handler)(DELTAT->status_change_which_chip, DELTAT->status_change_EOS_bit);
/* clear PCM BUSY bit (reflected in status register) */
DELTAT->PCM_BSY = 0;
DELTAT->portstate = 0;
DELTAT->adpcml = 0;
DELTAT->prev_acc = 0;
return;
}
}
if( DELTAT->now_addr&1 ) data = DELTAT->now_data & 0x0f;
else
{
DELTAT->now_data = *(DELTAT->memory + (DELTAT->now_addr>>1));
data = DELTAT->now_data >> 4;
}
DELTAT->now_addr++;
/* 12-06-2001 JB: */
/* YM2610 address register is 24 bits wide.*/
/* The "+1" is there because we use 1 bit more for nibble calculations.*/
/* WARNING: */
/* Side effect: we should take the size of the mapped ROM into account */
DELTAT->now_addr &= ( (1<<(24+1))-1);
/* store accumulator value */
DELTAT->prev_acc = DELTAT->acc;
/* Forecast to next Forecast */
DELTAT->acc += (ym_deltat_decode_tableB1[data] * DELTAT->adpcmd / 8);
YM_DELTAT_Limit(DELTAT->acc,YM_DELTAT_DECODE_MAX, YM_DELTAT_DECODE_MIN);
/* delta to next delta */
DELTAT->adpcmd = (DELTAT->adpcmd * ym_deltat_decode_tableB2[data] ) / 64;
YM_DELTAT_Limit(DELTAT->adpcmd,YM_DELTAT_DELTA_MAX, YM_DELTAT_DELTA_MIN );
/* ElSemi: Fix interpolator. */
/*DELTAT->prev_acc = prev_acc + ((DELTAT->acc - prev_acc) / 2 );*/
}while(--step);
}
/* ElSemi: Fix interpolator. */
DELTAT->adpcml = DELTAT->prev_acc * (int)((1<<YM_DELTAT_SHIFT)-DELTAT->now_step);
DELTAT->adpcml += (DELTAT->acc * (int)DELTAT->now_step);
DELTAT->adpcml = (DELTAT->adpcml>>YM_DELTAT_SHIFT) * (int)DELTAT->volume;
/* output for work of output channels (outd[OPNxxxx])*/
*(DELTAT->pan) += DELTAT->adpcml;
}
INLINE void YM_DELTAT_synthesis_from_CPU_memory(YM_DELTAT *DELTAT)
{
UINT32 step;
int data;
DELTAT->now_step += DELTAT->step;
if ( DELTAT->now_step >= (1<<YM_DELTAT_SHIFT) )
{
step = DELTAT->now_step >> YM_DELTAT_SHIFT;
DELTAT->now_step &= (1<<YM_DELTAT_SHIFT)-1;
do{
if( DELTAT->now_addr&1 )
{
data = DELTAT->now_data & 0x0f;
DELTAT->now_data = DELTAT->CPU_data;
/* after we used CPU_data, we set BRDY bit in status register,
* which means we are ready to accept another byte of data */
if(DELTAT->status_set_handler)
if(DELTAT->status_change_BRDY_bit)
(DELTAT->status_set_handler)(DELTAT->status_change_which_chip, DELTAT->status_change_BRDY_bit);
}
else
{
data = DELTAT->now_data >> 4;
}
DELTAT->now_addr++;
/* store accumulator value */
DELTAT->prev_acc = DELTAT->acc;
/* Forecast to next Forecast */
DELTAT->acc += (ym_deltat_decode_tableB1[data] * DELTAT->adpcmd / 8);
YM_DELTAT_Limit(DELTAT->acc,YM_DELTAT_DECODE_MAX, YM_DELTAT_DECODE_MIN);
/* delta to next delta */
DELTAT->adpcmd = (DELTAT->adpcmd * ym_deltat_decode_tableB2[data] ) / 64;
YM_DELTAT_Limit(DELTAT->adpcmd,YM_DELTAT_DELTA_MAX, YM_DELTAT_DELTA_MIN );
}while(--step);
}
/* ElSemi: Fix interpolator. */
DELTAT->adpcml = DELTAT->prev_acc * (int)((1<<YM_DELTAT_SHIFT)-DELTAT->now_step);
DELTAT->adpcml += (DELTAT->acc * (int)DELTAT->now_step);
DELTAT->adpcml = (DELTAT->adpcml>>YM_DELTAT_SHIFT) * (int)DELTAT->volume;
/* output for work of output channels (outd[OPNxxxx])*/
*(DELTAT->pan) += DELTAT->adpcml;
}
/* ADPCM B (Delta-T control type) */
void YM_DELTAT_ADPCM_CALC(YM_DELTAT *DELTAT)
{
/*
some examples:
value: START, REC, MEMDAT, REPEAT, SPOFF, x,x,RESET meaning:
80 1 0 0 0 0 0 0 0 Synthesis (playing) from CPU (from reg $08) to AUDIO,sample rate in DELTA-N register
a0 1 0 1 0 0 0 0 0 Synthesis (playing) from EXT.MEMORY to AUDIO, sample rate in DELTA-N register
C8 1 1 0 0 1 0 0 0 Analysis (recording) from AUDIO to CPU (to reg $08), sample rate in PRESCALER register
E8 1 1 1 0 1 0 0 0 Analysis (recording) from AUDIO to EXT.MEMORY, sample rate in PRESCALER register
60 0 1 1 0 0 0 0 0 External memory write via ADPCM data register $08
20 0 0 1 0 0 0 0 0 External memory read via ADPCM data register $08
*/
if ( (DELTAT->portstate & 0xe0)==0xa0 )
{
YM_DELTAT_synthesis_from_external_memory(DELTAT);
return;
}
if ( (DELTAT->portstate & 0xe0)==0x80 )
{
/* ADPCM synthesis from CPU-managed memory (from reg $08) */
YM_DELTAT_synthesis_from_CPU_memory(DELTAT); /* change output based on data in ADPCM data reg ($08) */
return;
}
//todo: ADPCM analysis
// if ( (DELTAT->portstate & 0xe0)==0xc0 )
// if ( (DELTAT->portstate & 0xe0)==0xe0 )
return;
}
| clangen/musikcube | src/plugins/gmedecoder/gme/ymdeltat.cpp | C++ | bsd-3-clause | 22,627 |
//==============================================================================
// Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II
// Copyright 2009 - 2013 LRI UMR 8623 CNRS/Univ Paris Sud XI
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef NT2_LINALG_FUNCTIONS_LAPACK_SYMMETRIC_SYSV_HPP_INCLUDED
#define NT2_LINALG_FUNCTIONS_LAPACK_SYMMETRIC_SYSV_HPP_INCLUDED
#include <nt2/linalg/functions/sysv.hpp>
#include <nt2/include/functions/zeros.hpp>
#include <nt2/linalg/details/utility/workspace.hpp>
#include <nt2/include/functions/width.hpp>
#include <nt2/linalg/details/utility/f77_wrapper.hpp>
extern "C"
{
void NT2_F77NAME(dsysv)( const char* uplo , const nt2_la_int* n
, const nt2_la_int* nhrs , double* a
, const nt2_la_int* lda , nt2_la_int* ipiv
, double* b , const nt2_la_int* ldb
, double* work , const nt2_la_int* lwork
, nt2_la_int* info
);
void NT2_F77NAME(ssysv)( const char* uplo , const nt2_la_int* n
, const nt2_la_int* nhrs , float* a
, const nt2_la_int* lda , nt2_la_int* ipiv
, float* b , const nt2_la_int* ldb
, float* work , const nt2_la_int* lwork
, nt2_la_int* info
);
void NT2_F77NAME(zsysv)( const char* uplo , const nt2_la_int* n
, const nt2_la_int* nhrs , nt2_la_complex* a
, const nt2_la_int* lda , nt2_la_int* ipiv
, nt2_la_complex* b , const nt2_la_int* ldb
, nt2_la_complex* work , const nt2_la_int* lwork
, nt2_la_int* info
);
void NT2_F77NAME(csysv)( const char* uplo , const nt2_la_int* n
, const nt2_la_int* nhrs , nt2_la_complex* a
, const nt2_la_int* lda , nt2_la_int* ipiv
, nt2_la_complex* b , const nt2_la_int* ldb
, nt2_la_complex* work , const nt2_la_int* lwork
, nt2_la_int* info
);
}
namespace nt2 { namespace ext
{
/// INTERNAL ONLY - Compute the workspace
NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::sysv_, tag::cpu_
, (A0)(S0)(A1)(S1)(A2)(S2)
, ((container_< nt2::tag::table_, double_<A0>, S0 >)) // A
((container_< nt2::tag::table_, integer_<A1>, S1 >)) // PIV
((container_< nt2::tag::table_, double_<A2>, S2 >)) // B
)
{
typedef nt2_la_int result_type;
BOOST_FORCEINLINE result_type operator()(A0& a0, A1& a1, A2& a2) const
{
result_type that;
details::workspace<typename A0::value_type> w;
nt2_la_int n = nt2::width(a0);
nt2_la_int ld = a0.leading_size();
nt2_la_int ldb = a2.leading_size();
nt2_la_int nhrs = nt2::width(a2);
char uplo = 'L';
NT2_F77NAME(dsysv) (&uplo, &n, &nhrs, 0, &ld, 0, 0, &ldb, w.main()
, details::query(), &that
);
w.prepare_main();
nt2::sysv(a0,a1,a2,w);
return that;
}
};
/// INTERNAL ONLY - Workspace is ready
NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::sysv_, tag::cpu_
, (A0)(S0)(A1)(S1)(A2)(S2)(A3)
, ((container_< nt2::tag::table_, double_<A0>, S0 >)) // A
((container_< nt2::tag::table_, integer_<A1>, S1 >)) // PIV
((container_< nt2::tag::table_, double_<A2>, S2 >)) // B
(unspecified_<A3>)
)
{
typedef nt2_la_int result_type;
BOOST_FORCEINLINE result_type operator()(A0& a0, A1& a1,A2& a2, A3& w) const
{
result_type that;
nt2_la_int n = nt2::width(a0);
nt2_la_int ld = a0.leading_size();
nt2_la_int ldb = a2.leading_size();
nt2_la_int nhrs = nt2::width(a2);
char uplo = 'L';
nt2_la_int wn = w.main_size();
NT2_F77NAME(dsysv) ( &uplo, &n, &nhrs, a0.raw(), &ld, a1.raw(), a2.raw()
, &ldb, w.main(), &wn, &that
);
return that;
}
};
/// INTERNAL ONLY - Compute the workspace
NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::sysv_, tag::cpu_
, (A0)(S0)(A1)(S1)(A2)(S2)
, ((container_< nt2::tag::table_, single_<A0>, S0 >)) // A
((container_< nt2::tag::table_, integer_<A1>, S1 >)) // PIV
((container_< nt2::tag::table_, single_<A2>, S2 >)) // B
)
{
typedef nt2_la_int result_type;
BOOST_FORCEINLINE result_type operator()(A0& a0, A1& a1, A2& a2) const
{
result_type that;
details::workspace<typename A0::value_type> w;
nt2_la_int n = nt2::width(a0);
nt2_la_int ld = a0.leading_size();
nt2_la_int ldb = a2.leading_size();
nt2_la_int nhrs = nt2::width(a2);
char uplo = 'L';
NT2_F77NAME(ssysv) (&uplo, &n, &nhrs, 0, &ld, 0, 0, &ldb, w.main()
, details::query(), &that
);
w.prepare_main();
nt2::sysv(a0,a1,a2,w);
return that;
}
};
/// INTERNAL ONLY - Workspace is ready
NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::sysv_, tag::cpu_
, (A0)(S0)(A1)(S1)(A2)(S2)(A3)
, ((container_< nt2::tag::table_, single_<A0>, S0 >)) // A
((container_< nt2::tag::table_, integer_<A1>, S1 >)) // PIV
((container_< nt2::tag::table_, single_<A2>, S2 >)) // B
(unspecified_<A3>)
)
{
typedef nt2_la_int result_type;
BOOST_FORCEINLINE result_type operator()(A0& a0, A1& a1,A2& a2, A3& w) const
{
result_type that;
nt2_la_int n = nt2::width(a0);
nt2_la_int ld = a0.leading_size();
nt2_la_int ldb = a2.leading_size();
nt2_la_int nhrs = nt2::width(a2);
char uplo = 'L';
nt2_la_int wn = w.main_size();
NT2_F77NAME(ssysv) ( &uplo, &n, &nhrs, a0.raw(), &ld, a1.raw(), a2.raw()
, &ldb, w.main(), &wn, &that
);
return that;
}
};
//--------------------------------------------Complex-----------------------------------------//
/// INTERNAL ONLY - Compute the workspace
NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::sysv_, tag::cpu_
, (A0)(S0)(A1)(S1)(A2)(S2)
, ((container_< nt2::tag::table_, complex_<double_<A0> >, S0 >)) // A
((container_< nt2::tag::table_, integer_<A1>, S1 >)) // PIV
((container_< nt2::tag::table_, complex_<double_<A2> >, S2 >)) // B
)
{
typedef nt2_la_int result_type;
BOOST_FORCEINLINE result_type operator()(A0& a0, A1& a1, A2& a2) const
{
result_type that;
details::workspace<typename A0::value_type> w;
nt2_la_int n = nt2::width(a0);
nt2_la_int ld = a0.leading_size();
nt2_la_int ldb = a2.leading_size();
nt2_la_int nhrs = nt2::width(a2);
char uplo = 'L';
NT2_F77NAME(zsysv) (&uplo, &n, &nhrs, 0, &ld, 0, 0, &ldb, w.main()
, details::query(), &that
);
w.prepare_main();
nt2::sysv(a0,a1,a2,w);
return that;
}
};
/// INTERNAL ONLY - Workspace is ready
NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::sysv_, tag::cpu_
, (A0)(S0)(A1)(S1)(A2)(S2)(A3)
, ((container_< nt2::tag::table_, complex_<double_<A0> >, S0 >)) // A
((container_< nt2::tag::table_, integer_<A1>, S1 >)) // PIV
((container_< nt2::tag::table_, complex_<double_<A2> >, S2 >)) // B
(unspecified_<A3>)
)
{
typedef nt2_la_int result_type;
BOOST_FORCEINLINE result_type operator()(A0& a0, A1& a1,A2& a2, A3& a3) const
{
result_type that;
nt2_la_int n = nt2::width(a0);
nt2_la_int ld = a0.leading_size();
nt2_la_int ldb = a2.leading_size();
nt2_la_int nhrs = nt2::width(a2);
char uplo = 'L';
nt2_la_int wn = a3.main_size();
NT2_F77NAME(zsysv) ( &uplo, &n, &nhrs, a0.raw(), &ld, a1.raw(), a2.raw()
, &ldb, a3.main(), &wn, &that
);
return that;
}
};
/// INTERNAL ONLY - Compute the workspace
NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::sysv_, tag::cpu_
, (A0)(S0)(A1)(S1)(A2)(S2)
, ((container_< nt2::tag::table_, complex_<single_<A0> >, S0 >)) // A
((container_< nt2::tag::table_, integer_<A1>, S1 >)) // PIV
((container_< nt2::tag::table_, complex_<single_<A2> >, S2 >)) // B
)
{
typedef nt2_la_int result_type;
BOOST_FORCEINLINE result_type operator()(A0& a0, A1& a1, A2& a2) const
{
result_type that;
details::workspace<typename A0::value_type> w;
nt2_la_int n = nt2::width(a0);
nt2_la_int ld = a0.leading_size();
nt2_la_int ldb = a2.leading_size();
nt2_la_int nhrs = nt2::width(a2);
char uplo = 'L';
NT2_F77NAME(csysv) (&uplo, &n, &nhrs, 0, &ld, 0, 0, &ldb, w.main()
, details::query(), &that
);
w.prepare_main();
nt2::sysv(a0,a1,a2,w);
return that;
}
};
/// INTERNAL ONLY - Workspace is ready
NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::sysv_, tag::cpu_
, (A0)(S0)(A1)(S1)(A2)(S2)(A3)
, ((container_< nt2::tag::table_, complex_<single_<A0> >, S0 >)) // A
((container_< nt2::tag::table_, integer_<A1>, S1 >)) // PIV
((container_< nt2::tag::table_, complex_<single_<A2> >, S2 >)) // B
(unspecified_<A3>)
)
{
typedef nt2_la_int result_type;
BOOST_FORCEINLINE result_type operator()(A0& a0, A1& a1,A2& a2, A3& a3) const
{
result_type that;
nt2_la_int n = nt2::width(a0);
nt2_la_int ld = a0.leading_size();
nt2_la_int ldb = a2.leading_size();
nt2_la_int nhrs = nt2::width(a2);
char uplo = 'L';
nt2_la_int wn = a3.main_size();
NT2_F77NAME(csysv) ( &uplo, &n, &nhrs, a0.raw(), &ld, a1.raw(), a2.raw()
, &ldb, a3.main(), &wn, &that
);
return that;
}
};
} }
#endif
| hainm/pythran | third_party/nt2/linalg/functions/lapack/symmetric/sysv.hpp | C++ | bsd-3-clause | 11,763 |
package net.ripe.db.whois.logsearch;
import com.google.common.collect.Sets;
import net.ripe.db.whois.logsearch.logformat.DailyLogEntry;
import net.ripe.db.whois.logsearch.logformat.LoggedUpdate;
import org.apache.lucene.queryparser.classic.ParseException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.core.io.ClassPathResource;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Set;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class LogFileSearchTest {
LoggedUpdate loggedUpdateWithPasswordId;
LoggedUpdate loggedUpdateWithOverride;
@Mock LogFileIndex logFileIndex;
LogFileSearch subject;
@Before
public void setUp() throws Exception {
final String logDir = new ClassPathResource("/log/update").getFile().getAbsolutePath();
loggedUpdateWithPasswordId = new DailyLogEntry(logDir + "/20130306/123623.428054357.0.1362569782886.JavaMail.andre/001.msg-in.txt.gz", "20130306");
loggedUpdateWithOverride = new DailyLogEntry(logDir + "/20130306/123624.428054357.0.1362569782886.JavaMail.andre/001.msg-in.txt.gz", "20130306");
subject = new LogFileSearch(new ClassPathResource("/log/update").getFile().getAbsolutePath(), logFileIndex);
}
@Test
public void searchLoggedUpdateIds() throws IOException, ParseException {
when(logFileIndex.searchByDateRangeAndContent("query", null, null)).thenReturn(Sets.newHashSet(loggedUpdateWithPasswordId));
final Set<LoggedUpdate> updateIds = subject.searchLoggedUpdateIds("query", null, null);
assertThat(updateIds, contains(loggedUpdateWithPasswordId));
}
@Test
public void writeLoggedUpdates() throws IOException {
final StringWriter writer = new StringWriter();
subject.writeLoggedUpdate(loggedUpdateWithPasswordId, writer);
final String output = writer.toString();
assertThat(output, containsString("date : 20130306"));
assertThat(output, containsString("as-block: AS222 - AS333\n"));
}
@Test
public void writeLoggedUpdates_filters_password() throws IOException {
final StringWriter writer = new StringWriter();
subject.writeLoggedUpdate(loggedUpdateWithPasswordId, writer);
final String output = writer.toString();
assertThat(output, containsString("password: FILTERED"));
assertThat(output, not(containsString("dbm")));
}
@Test
public void writeLoggedUpdates_filters_override() throws IOException {
final StringWriter writer = new StringWriter();
subject.writeLoggedUpdate(loggedUpdateWithOverride, writer);
final String output = writer.toString();
assertThat(output, containsString("override: FILTERED"));
assertThat(output, containsString("override: dbm2, FILTERED, reason"));
assertThat(output, containsString("override: dbm3, FILTERED"));
assertThat(output, not(containsString("password")));
}
}
| michelafrinic/WHOIS | whois-logsearch/src/test/java/net/ripe/db/whois/logsearch/LogFileSearchTest.java | Java | bsd-3-clause | 3,306 |
"""Utility module for creating transformation matrices
Basically this gives you the ability to construct
transformation matrices without needing OpenGL
or similar run-time engines. The result is that
design-time utilities can process files without
trading dependencies on a particular run-time.
This code is originally from the mcf.vrml processing
engine, and has only been cosmetically altered to
fit the new organizational pattern.
Note: to apply these matrices to a particular coordinate,
you would do the following:
p = ones( 4 )
p[:3] = coordinate
return dot( p, matrix)
That is, you use the homogenous coordinate, and
make it the first item in the dot'ing.
"""
from math import *
from vrml.arrays import *
# used to determine whether angles are non-null
TWOPI = pi * 2.0
RADTODEG = 360./TWOPI
DEGTORAD = TWOPI/360.
# used to determine the center point of a transform
ORIGINPOINT = array([0,0,0,1],'f')
VERY_SMALL = 1e-300
def transformMatrix(
translation = (0,0,0),
center = (0,0,0),
rotation = (0,1,0,0),
scale = (1,1,1),
scaleOrientation = (0,1,0,0),
parentMatrix = None,
):
"""Convert VRML transform values to an overall matrix
Returns 4x4 transformation matrix
Note that this uses VRML standard for rotations
(angle last, and in radians).
This should return matrices which, when applied to
local-space coordinates, give you parent-space
coordinates.
parentMatrix if provided, should be the parent's
transformation matrix, a 4x4 matrix of such as
returned by this function.
"""
T,T1 = transMatrix( translation )
C,C1 = transMatrix( center )
R,R1 = rotMatrix( rotation )
SO,SO1 = rotMatrix( scaleOrientation )
S,S1 = scaleMatrix( scale )
return compressMatrices( parentMatrix, T,C,R,SO,S,SO1,C1 )
def itransformMatrix(
translation = (0,0,0),
center = (0,0,0),
rotation = (0,1,0,0),
scale = (1,1,1),
scaleOrientation = (0,1,0,0),
parentMatrix = None,
):
"""Convert VRML transform values to an inverse transform matrix
Returns 4x4 transformation matrix
Note that this uses VRML standard for rotations
(angle last, and in radians).
This should return matrices which, when applied to
parent-space coordinates, give you local-space
coordinates for the corresponding transform.
Note: this is a substantially un-tested algorithm
though it seems to be properly constructed as far
as I can see. Whether to use dot(x, parentMatrix)
or the reverse is not immediately clear to me.
parentMatrix if provided, should be the child's
transformation matrix, a 4x4 matrix of such as
returned by this function.
"""
T,T1 = transMatrix( translation )
C,C1 = transMatrix( center )
R,R1 = rotMatrix( rotation )
SO,SO1 = rotMatrix( scaleOrientation )
S,S1 = scaleMatrix( scale )
return compressMatrices( parentMatrix, C,SO, S1, SO1, R1, C1, T1)
def transformMatrices(
translation = (0,0,0),
center = (0,0,0),
rotation = (0,1,0,0),
scale = (1,1,1),
scaleOrientation = (0,1,0,0),
parentMatrix = None,
):
"""Calculate both forward and backward matrices for these parameters"""
T,T1 = transMatrix( translation )
C,C1 = transMatrix( center )
R,R1 = rotMatrix( rotation )
SO,SO1 = rotMatrix( scaleOrientation )
S,S1 = scaleMatrix( scale )
return (
compressMatrices( parentMatrix, T,C,R,SO,S,SO1,C1 ),
compressMatrices( parentMatrix, C,SO, S1, SO1, R1, C1, T1)
)
def localMatrices(
translation = (0,0,0),
center = (0,0,0),
rotation = (0,1,0,0),
scale = (1,1,1),
scaleOrientation = (0,1,0,0),
parentMatrix = None,
):
"""Calculate (forward,inverse) matrices for this transform element"""
T,T1 = transMatrix( translation )
C,C1 = transMatrix( center )
R,R1 = rotMatrix( rotation )
SO,SO1 = rotMatrix( scaleOrientation )
S,S1 = scaleMatrix( scale )
return (
compressMatrices( T,C,R,SO,S,SO1,C1 ),
compressMatrices( C,SO, S1, SO1, R1, C1, T1)
)
def compressMatrices( *matrices ):
"""Compress a set of matrices
Any (or all) of the matrices may be None,
if *all* are None, then the result will be None,
otherwise will be the dot product of all of the
matrices...
"""
if not matrices:
return None
else:
first = matrices[0]
matrices = matrices[1:]
for item in matrices:
if item is not None:
if first is None:
first = item
else:
first = dot( item, first )
return first
def center(
translation = (0,0,0),
center = (0,0,0),
parentMatrix = None,
):
"""Determine the center of rotation for a transform node
Returns the parent-space coordinate of the
node's center of rotation.
"""
if parentMatrix is None:
parentMatrix = identity(4)
T,T1 = transMatrix( translation )
C,C1 = transMatrix( center )
for x in (T,C):
if x:
parentMatrix = dot( x, parentMatrix)
return dot( ORIGINPOINT, parentMatrix )
if tmatrixaccel:
def rotMatrix( source = None ):
"""Convert a VRML rotation to rotation matrices
Returns (R, R') (R and the inverse of R), with both
being 4x4 transformation matrices.
or
None,None if the angle is an exact multiple of 2pi
x,y,z -- (normalised) rotational vector
a -- angle in radians
"""
if source is None:
return None,None
else:
(x,y,z, a) = source
if a % TWOPI:
return tmatrixaccel.rotMatrix( x,y,z,a ),tmatrixaccel.rotMatrix( x,y,z,-a )
return None,None
def scaleMatrix( source=None ):
"""Convert a VRML scale to scale matrices
Returns (S, S') (S and the inverse of S), with both
being 4x4 transformation matrices.
or
None,None if x == y == z == 1.0
x,y,z -- scale vector
"""
if source is None:
return None,None
else:
(x,y,z) = source[:3]
if x == y == z == 1.0:
return None, None
forward = tmatrixaccel.scaleMatrix( x,y,z )
backward = tmatrixaccel.scaleMatrix( 1.0/(x or VERY_SMALL),1.0/(y or VERY_SMALL), 1.0/(z or VERY_SMALL) )
return forward, backward
def transMatrix( source=None ):
"""Convert a VRML translation to translation matrices
Returns (T, T') (T and the inverse of T), with both
being 4x4 transformation matrices.
or
None,None if x == y == z == 0.0
x,y,z -- scale vector
"""
if source is None:
return None,None
else:
(x,y,z) = source[:3]
if x == y == z == 0.0:
return None, None
return tmatrixaccel.transMatrix( x,y,z ),tmatrixaccel.transMatrix( -x, -y, -z )
perspectiveMatrix = tmatrixaccel.perspectiveMatrix
orthoMatrix = tmatrixaccel.orthoMatrix
else:
def rotMatrix( source=None ):
"""Convert a VRML rotation to rotation matrices
Returns (R, R') (R and the inverse of R), with both
being 4x4 transformation matrices.
or
None,None if the angle is an exact multiple of 2pi
x,y,z -- (normalised) rotational vector
a -- angle in radians
"""
if source is None:
return None,None
else:
(x,y,z, a) = source
if a % TWOPI:
# normalize the rotation vector!
squared = x*x + y*y + z*z
if squared != 1.0:
length = squared ** .5
x /= squared
y /= squared
z /= squared
c = cos( a )
c1 = cos( -a )
s = sin( a )
s1 = sin( -a )
t = 1-c
R = array( [
[ t*x*x+c, t*x*y+s*z, t*x*z-s*y, 0],
[ t*x*y-s*z, t*y*y+c, t*y*z+s*x, 0],
[ t*x*z+s*y, t*y*z-s*x, t*z*z+c, 0],
[ 0, 0, 0, 1]
] )
R1 = array( [
[ t*x*x+c1, t*x*y+s1*z, t*x*z-s1*y, 0],
[ t*x*y-s1*z, t*y*y+c1, t*y*z+s1*x, 0],
[ t*x*z+s1*y, t*y*z-s1*x, t*z*z+c1, 0],
[ 0, 0, 0, 1]
] )
return R, R1
else:
return None, None
def scaleMatrix( source=None ):
"""Convert a VRML scale to scale matrices
Returns (S, S') (S and the inverse of S), with both
being 4x4 transformation matrices.
or
None,None if x == y == z == 1.0
x,y,z -- scale vector
"""
if source is None:
return None,None
else:
(x,y,z) = source[:3]
if x == y == z == 1.0:
return None, None
S = array( [ [x,0,0,0], [0,y,0,0], [0,0,z,0], [0,0,0,1] ], 'f' )
S1 = array( [
[1./(x or VERY_SMALL),0,0,0],
[0,1./(y or VERY_SMALL),0,0],
[0,0,1./(z or VERY_SMALL),0],
[0,0,0,1] ], 'f'
)
return S, S1
def transMatrix( source=None ):
"""Convert a VRML translation to translation matrices
Returns (T, T') (T and the inverse of T), with both
being 4x4 transformation matrices.
or
None,None if x == y == z == 0.0
x,y,z -- scale vector
"""
if source is None:
return None,None
else:
(x,y,z) = source[:3]
if x == y == z == 0.0:
return None, None
T = array( [ [1,0,0,0], [0,1,0,0], [0,0,1,0], [x,y,z,1] ], 'f' )
T1 = array( [ [1,0,0,0], [0,1,0,0], [0,0,1,0], [-x,-y,-z,1] ], 'f' )
return T, T1
def perspectiveMatrix( fovy, aspect, zNear, zFar, inverse=False ):
"""Create a perspective matrix from given parameters
Note that this is the same matrix as for gluPerspective,
save that we are using radians...
"""
f = 1.0/tan( (fovy/2.0) ) # cotangent( fovy/2.0 )
zDelta = zNear-zFar
if inverse:
return array([
[aspect/f,0,0,0],
[0,1/(f or VERY_SMALL),0,0],
[0,0,0,zDelta/(2*zFar*zNear)],
[0,0,-1,(zFar+zNear)/(2*zFar*zNear)],
],'f')
else:
return array([
[f/aspect,0,0,0],
[0,f,0,0],
[0,0,(zFar+zNear)/zDelta,-1],
[0,0,(2*zFar*zNear)/zDelta,0]
],'f')
def orthoMatrix( left=-1.0, right=1.0, bottom=-1.0, top=1.0, zNear=-1.0, zFar=1.0 ):
"""Calculate an orthographic projection matrix
Similar to glOrtho
"""
tx = - ( right + left ) / float( right-left )
ty = - ( top + bottom ) / float( top-bottom )
tz = - ( zFar + zNear ) / float( zFar-zNear )
return array([
[2/(right-left), 0, 0, tx],
[0, 2/(top-bottom), 0, ty],
[0, 0, -2/(zFar-zNear), tz],
[0, 0, 0, 1],
], dtype='f')
| menpo/vrml97 | vrml/vrml97/transformmatrix.py | Python | bsd-3-clause | 11,368 |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE588_Attempt_to_Access_Child_of_Non_Structure_Pointer__struct_82_bad.cpp
Label Definition File: CWE588_Attempt_to_Access_Child_of_Non_Structure_Pointer__struct.label.xml
Template File: sources-sink-82_bad.tmpl.cpp
*/
/*
* @description
* CWE: 588 Attempt to Access Child of Non Structure Pointer
* BadSource: Void pointer to an int
* GoodSource: Void pointer to a twoints struct
* Sinks:
* BadSink : Print data
* Flow Variant: 82 Data flow: data passed in a parameter to an virtual method called via a pointer
*
* */
#ifndef OMITBAD
#include "std_testcase.h"
#include "CWE588_Attempt_to_Access_Child_of_Non_Structure_Pointer__struct_82.h"
namespace CWE588_Attempt_to_Access_Child_of_Non_Structure_Pointer__struct_82
{
void CWE588_Attempt_to_Access_Child_of_Non_Structure_Pointer__struct_82_bad::action(void * data)
{
/* POTENTIAL FLAW: Attempt to print a struct when data may be a non-struct data type */
printStructLine((twoIntsStruct *)data);
}
}
#endif /* OMITBAD */
| JianpingZeng/xcc | xcc/test/juliet/testcases/CWE588_Attempt_to_Access_Child_of_Non_Structure_Pointer/CWE588_Attempt_to_Access_Child_of_Non_Structure_Pointer__struct_82_bad.cpp | C++ | bsd-3-clause | 1,073 |
package org.motechproject.mrs.model;
import org.junit.Test;
import static junit.framework.Assert.assertTrue;
public class PasswordTest {
@Test
public void shouldGeneratePasswordWithUpperCaseLowerCaseAndNumberCharacterCombination() {
Password password = new Password(9);
for (int i = 0; i < 15; i++) {
assertPassword(password.create());
}
}
private void assertPassword(String word) {
boolean upperCase = false;
boolean lowerCase = false;
boolean digit = false;
for (int i = 0; i < word.length(); i++) {
if (Character.isDigit(word.charAt(i))) digit = true;
if (Character.isUpperCase(word.charAt(i))) upperCase = true;
if (Character.isLowerCase(word.charAt(i))) lowerCase = true;
}
assertTrue(lowerCase);
assertTrue(upperCase);
assertTrue(digit);
}
}
| bruceMacLeod/motech-server-pillreminder-0.18 | modules/openmrs/domain-bundle/src/test/java/org/motechproject/mrs/model/PasswordTest.java | Java | bsd-3-clause | 909 |
package org.petuum.jbosen.row.double_;
import org.petuum.jbosen.row.RowUpdate;
import java.nio.ByteBuffer;
/**
* This implementation of {@code DoubleRowUpdate} assumes a sparse set of
* columns, ie. column IDs can be any int value. In general, this class is less
* CPU and memory efficient than {@link DenseDoubleRowUpdate}.
*/
public class SparseDoubleRowUpdate extends SparseDoubleColumnMap
implements DoubleRowUpdate {
/**
* Construct a new object, this object initially contains no columns (ie.
* all columns are implicitly zero).
*/
public SparseDoubleRowUpdate() {
super();
}
/**
* Copy constructor, constructs a new, deep copy of the argument.
*
* @param other object to construct a deep copy of.
*/
public SparseDoubleRowUpdate(SparseDoubleRowUpdate other) {
super(other);
}
/**
* Construct an object by de-serializing from a {@code ByteBuffer} object.
*
* @param buffer the {@code ByteBuffer} containing the serialized data.
*/
public SparseDoubleRowUpdate(ByteBuffer buffer) {
super(buffer);
}
/**
* Returns a deep copy of this row update.
*
* @return deep copy of this row update.
*/
public SparseDoubleRowUpdate getCopy() {
return new SparseDoubleRowUpdate(this);
}
/**
* {@inheritDoc}
*/
@Override
public void inc(RowUpdate rowUpdate) {
assert rowUpdate instanceof DoubleColumnMap
: "Incorrect type for rowUpdate!";
super.incAll((DoubleColumnMap) rowUpdate);
}
}
| codeaudit/jbosen | jbosen/src/main/java/org/petuum/jbosen/row/double_/SparseDoubleRowUpdate.java | Java | bsd-3-clause | 1,609 |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE415_Double_Free__new_delete_array_char_73b.cpp
Label Definition File: CWE415_Double_Free__new_delete_array.label.xml
Template File: sources-sinks-73b.tmpl.cpp
*/
/*
* @description
* CWE: 415 Double Free
* BadSource: Allocate data using new and Deallocae data using delete
* GoodSource: Allocate data using new
* Sinks:
* GoodSink: do nothing
* BadSink : Deallocate data using delete
* Flow Variant: 73 Data flow: data passed in a list from one function to another in different source files
*
* */
#include "std_testcase.h"
#include <list>
#include <wchar.h>
using namespace std;
namespace CWE415_Double_Free__new_delete_array_char_73
{
#ifndef OMITBAD
void badSink(list<char *> dataList)
{
/* copy data out of dataList */
char * data = dataList.back();
/* POTENTIAL FLAW: Possibly deleting memory twice */
delete [] data;
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(list<char *> dataList)
{
char * data = dataList.back();
/* POTENTIAL FLAW: Possibly deleting memory twice */
delete [] data;
}
/* goodB2G uses the BadSource with the GoodSink */
void goodB2GSink(list<char *> dataList)
{
char * data = dataList.back();
/* do nothing */
/* FIX: Don't attempt to delete the memory */
; /* empty statement needed for some flow variants */
}
#endif /* OMITGOOD */
} /* close namespace */
| JianpingZeng/xcc | xcc/test/juliet/testcases/CWE415_Double_Free/s01/CWE415_Double_Free__new_delete_array_char_73b.cpp | C++ | bsd-3-clause | 1,529 |
package org.basex.query.func.fetch;
import static org.basex.query.QueryError.*;
import java.io.*;
import org.basex.io.*;
import org.basex.query.*;
import org.basex.query.func.*;
import org.basex.query.value.item.*;
import org.basex.util.*;
import org.basex.util.http.*;
/**
* Function implementation.
*
* @author BaseX Team 2005-15, BSD License
* @author Christian Gruen
*/
public final class FetchContentType extends StandardFunc {
@Override
public Item item(final QueryContext qc, final InputInfo ii) throws QueryException {
final byte[] uri = toToken(exprs[0], qc);
final IO io = IO.get(Token.string(uri));
final String path = io.path();
MediaType mt = null;
if(io instanceof IOUrl) {
try {
final String ct = ((IOUrl) io).connection().getContentType();
if(ct != null) mt = new MediaType(ct);
} catch(final IOException ex) {
throw BXFE_IO_X.get(info, ex);
}
} else if(io instanceof IOContent) {
mt = MediaType.APPLICATION_XML;
} else if(io.exists()) {
mt = MediaType.get(path);
}
if(mt == null) throw BXFE_IO_X.get(info, new FileNotFoundException(path));
return Str.get(mt.toString());
}
}
| deshmnnit04/basex | basex-core/src/main/java/org/basex/query/func/fetch/FetchContentType.java | Java | bsd-3-clause | 1,202 |
package ca.fuwafuwa.kaku.Database;
import com.j256.ormlite.dao.Dao;
import java.sql.SQLException;
public interface IDatabaseHelper
{
<T> Dao<T, Integer> getDbDao(Class clazz) throws SQLException;
}
| Xyresic/Kaku | app/src/main/java/ca/fuwafuwa/kaku/Database/IDatabaseHelper.java | Java | bsd-3-clause | 205 |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE129_rand_13.cpp
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE129.label.xml
Template File: sources-sinks-13.tmpl.cpp
*/
/*
* @description
* CWE: 122 Heap Based Buffer Overflow
* BadSource: rand Set data to result of rand(), which may be zero
* GoodSource: Larger than zero but less than 10
* Sinks:
* GoodSink: Ensure the array index is valid
* BadSink : Improperly check the array index by not checking the upper bound
* Flow Variant: 13 Control flow: if(GLOBAL_CONST_FIVE==5) and if(GLOBAL_CONST_FIVE!=5)
* */
#include "std_testcase.h"
namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE129_rand_13
{
#ifndef OMITBAD
void bad()
{
int data;
/* Initialize data */
data = -1;
if(GLOBAL_CONST_FIVE==5)
{
/* POTENTIAL FLAW: Set data to a random value */
data = RAND32();
}
if(GLOBAL_CONST_FIVE==5)
{
{
int i;
int * buffer = new int[10];
/* initialize buffer */
for (i = 0; i < 10; i++)
{
buffer[i] = 0;
}
/* POTENTIAL FLAW: Attempt to write to an index of the array that is above the upper bound
* This code does check to see if the array index is negative */
if (data >= 0)
{
buffer[data] = 1;
/* Print the array values */
for(i = 0; i < 10; i++)
{
printIntLine(buffer[i]);
}
}
else
{
printLine("ERROR: Array index is negative.");
}
delete[] buffer;
}
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodB2G1() - use badsource and goodsink by changing the second GLOBAL_CONST_FIVE==5 to GLOBAL_CONST_FIVE!=5 */
static void goodB2G1()
{
int data;
/* Initialize data */
data = -1;
if(GLOBAL_CONST_FIVE==5)
{
/* POTENTIAL FLAW: Set data to a random value */
data = RAND32();
}
if(GLOBAL_CONST_FIVE!=5)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
}
else
{
{
int i;
int * buffer = new int[10];
/* initialize buffer */
for (i = 0; i < 10; i++)
{
buffer[i] = 0;
}
/* FIX: Properly validate the array index and prevent a buffer overflow */
if (data >= 0 && data < (10))
{
buffer[data] = 1;
/* Print the array values */
for(i = 0; i < 10; i++)
{
printIntLine(buffer[i]);
}
}
else
{
printLine("ERROR: Array index is out-of-bounds");
}
delete[] buffer;
}
}
}
/* goodB2G2() - use badsource and goodsink by reversing the blocks in the second if */
static void goodB2G2()
{
int data;
/* Initialize data */
data = -1;
if(GLOBAL_CONST_FIVE==5)
{
/* POTENTIAL FLAW: Set data to a random value */
data = RAND32();
}
if(GLOBAL_CONST_FIVE==5)
{
{
int i;
int * buffer = new int[10];
/* initialize buffer */
for (i = 0; i < 10; i++)
{
buffer[i] = 0;
}
/* FIX: Properly validate the array index and prevent a buffer overflow */
if (data >= 0 && data < (10))
{
buffer[data] = 1;
/* Print the array values */
for(i = 0; i < 10; i++)
{
printIntLine(buffer[i]);
}
}
else
{
printLine("ERROR: Array index is out-of-bounds");
}
delete[] buffer;
}
}
}
/* goodG2B1() - use goodsource and badsink by changing the first GLOBAL_CONST_FIVE==5 to GLOBAL_CONST_FIVE!=5 */
static void goodG2B1()
{
int data;
/* Initialize data */
data = -1;
if(GLOBAL_CONST_FIVE!=5)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
}
else
{
/* FIX: Use a value greater than 0, but less than 10 to avoid attempting to
* access an index of the array in the sink that is out-of-bounds */
data = 7;
}
if(GLOBAL_CONST_FIVE==5)
{
{
int i;
int * buffer = new int[10];
/* initialize buffer */
for (i = 0; i < 10; i++)
{
buffer[i] = 0;
}
/* POTENTIAL FLAW: Attempt to write to an index of the array that is above the upper bound
* This code does check to see if the array index is negative */
if (data >= 0)
{
buffer[data] = 1;
/* Print the array values */
for(i = 0; i < 10; i++)
{
printIntLine(buffer[i]);
}
}
else
{
printLine("ERROR: Array index is negative.");
}
delete[] buffer;
}
}
}
/* goodG2B2() - use goodsource and badsink by reversing the blocks in the first if */
static void goodG2B2()
{
int data;
/* Initialize data */
data = -1;
if(GLOBAL_CONST_FIVE==5)
{
/* FIX: Use a value greater than 0, but less than 10 to avoid attempting to
* access an index of the array in the sink that is out-of-bounds */
data = 7;
}
if(GLOBAL_CONST_FIVE==5)
{
{
int i;
int * buffer = new int[10];
/* initialize buffer */
for (i = 0; i < 10; i++)
{
buffer[i] = 0;
}
/* POTENTIAL FLAW: Attempt to write to an index of the array that is above the upper bound
* This code does check to see if the array index is negative */
if (data >= 0)
{
buffer[data] = 1;
/* Print the array values */
for(i = 0; i < 10; i++)
{
printIntLine(buffer[i]);
}
}
else
{
printLine("ERROR: Array index is negative.");
}
delete[] buffer;
}
}
}
void good()
{
goodB2G1();
goodB2G2();
goodG2B1();
goodG2B2();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE129_rand_13; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| JianpingZeng/xcc | xcc/test/juliet/testcases/CWE122_Heap_Based_Buffer_Overflow/s01/CWE122_Heap_Based_Buffer_Overflow__cpp_CWE129_rand_13.cpp | C++ | bsd-3-clause | 7,834 |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE23_Relative_Path_Traversal__wchar_t_environment_open_01.cpp
Label Definition File: CWE23_Relative_Path_Traversal.label.xml
Template File: sources-sink-01.tmpl.cpp
*/
/*
* @description
* CWE: 23 Relative Path Traversal
* BadSource: environment Read input from an environment variable
* GoodSource: Use a fixed file name
* Sink: open
* BadSink : Open the file named in data using open()
* Flow Variant: 01 Baseline
*
* */
#include "std_testcase.h"
#ifdef _WIN32
#define BASEPATH L"c:\\temp\\"
#else
#include <wchar.h>
#define BASEPATH L"/tmp/"
#endif
#define ENV_VARIABLE L"ADD"
#ifdef _WIN32
#define GETENV _wgetenv
#else
#define GETENV getenv
#endif
#ifdef _WIN32
#define OPEN _wopen
#define CLOSE _close
#else
#include <unistd.h>
#define OPEN open
#define CLOSE close
#endif
namespace CWE23_Relative_Path_Traversal__wchar_t_environment_open_01
{
#ifndef OMITBAD
void bad()
{
wchar_t * data;
wchar_t dataBuffer[FILENAME_MAX] = BASEPATH;
data = dataBuffer;
{
/* Append input from an environment variable to data */
size_t dataLen = wcslen(data);
wchar_t * environment = GETENV(ENV_VARIABLE);
/* If there is data in the environment variable */
if (environment != NULL)
{
/* POTENTIAL FLAW: Read data from an environment variable */
wcsncat(data+dataLen, environment, FILENAME_MAX-dataLen-1);
}
}
{
int fileDesc;
/* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */
fileDesc = OPEN(data, O_RDWR|O_CREAT, S_IREAD|S_IWRITE);
if (fileDesc != -1)
{
CLOSE(fileDesc);
}
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
static void goodG2B()
{
wchar_t * data;
wchar_t dataBuffer[FILENAME_MAX] = BASEPATH;
data = dataBuffer;
/* FIX: Use a fixed file name */
wcscat(data, L"file.txt");
{
int fileDesc;
/* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */
fileDesc = OPEN(data, O_RDWR|O_CREAT, S_IREAD|S_IWRITE);
if (fileDesc != -1)
{
CLOSE(fileDesc);
}
}
}
void good()
{
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE23_Relative_Path_Traversal__wchar_t_environment_open_01; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| JianpingZeng/xcc | xcc/test/juliet/testcases/CWE23_Relative_Path_Traversal/s04/CWE23_Relative_Path_Traversal__wchar_t_environment_open_01.cpp | C++ | bsd-3-clause | 3,289 |
import getpass
from django.core.management.base import BaseCommand
from hc.accounts.forms import SignupForm
from hc.accounts.views import _make_user
class Command(BaseCommand):
help = """Create a super-user account."""
def handle(self, *args, **options):
email = None
password = None
while not email:
raw = input("Email address:")
form = SignupForm({"identity": raw})
if not form.is_valid():
self.stderr.write("Error: " + " ".join(form.errors["identity"]))
continue
email = form.cleaned_data["identity"]
while not password:
p1 = getpass.getpass()
p2 = getpass.getpass("Password (again):")
if p1.strip() == "":
self.stderr.write("Error: Blank passwords aren't allowed.")
continue
if p1 != p2:
self.stderr.write("Error: Your passwords didn't match.")
continue
password = p1
user = _make_user(email)
user.set_password(password)
user.is_staff = True
user.is_superuser = True
user.save()
return "Superuser created successfully."
| healthchecks/healthchecks | hc/accounts/management/commands/createsuperuser.py | Python | bsd-3-clause | 1,226 |
<?php
namespace AuthorBooks\Tests;
use Maghead\Testing\ModelTestCase;
use AuthorBooks\Model\Author;
use AuthorBooks\Model\AuthorSchema;
use AuthorBooks\Model\AddressSchema;
use AuthorBooks\Model\AuthorCollection;
use Maghead\Migration\Migration;
use Magsql\Universal\Syntax\Column;
use Magsql\Driver\PDOMySQLDriver;
use Magsql\Driver\PDOPgSQLDriver;
use Magsql\Driver\SQLiteDriver;
use Maghead\Migration\AutomaticMigration;
use GetOptionKit\OptionResult;
use GetOptionKit\OptionCollection;
/**
* @group mysql
* @group migration
*/
class AuthorMigrationTest extends ModelTestCase
{
public function models()
{
return [
new AddressSchema,
new AuthorSchema,
];
}
public function testImportSchema()
{
$schema = new AddressSchema;
$this->dropSchemaTables([$schema]);
$table = $schema->getTable();
AutomaticMigration::options($options = new OptionCollection);
$migrate = new AutomaticMigration(
$this->conn,
$this->queryDriver,
$this->logger,
OptionResult::create($options, [ ]));
$migrate->upgrade([$schema]);
}
public function testModifyColumn()
{
$this->forDrivers('mysql');
$schema = new AuthorSchema;
$schema->getColumn('email')
->varchar(20)
->notNull()
;
$this->buildSchemaTables([$schema], true);
AutomaticMigration::options($options = new OptionCollection);
$migrate = new AutomaticMigration(
$this->conn,
$this->queryDriver,
$this->logger,
OptionResult::create($options, [ ]));
$migrate->upgrade([$schema]);
}
public function testAddColumn()
{
// pgsql: multiple primary keys for table "authors" are not allowed
$this->skipDrivers('pgsql');
$schema = new AuthorSchema;
$this->dropSchemaTables([$schema]);
$schema->removeColumn('email');
$this->buildSchemaTables([$schema], true);
AutomaticMigration::options($options = new OptionCollection);
$migrate = new AutomaticMigration(
$this->conn,
$this->queryDriver,
$this->logger,
OptionResult::create($options, [ ]));
$migrate->upgrade([$schema]);
}
public function testRemoveColumn()
{
$this->forDrivers('mysql');
$schema = new AuthorSchema;
$schema->column('cellphone')
->varchar(30);
$this->buildSchemaTables([$schema], true);
AutomaticMigration::options($options = new OptionCollection);
$migrate = new AutomaticMigration(
$this->conn,
$this->queryDriver,
$this->logger,
OptionResult::create($options, [ ]));
$migrate->upgrade([$schema]);
}
}
| c9s/LazyRecord | examples/books/Tests/AuthorMigrationTest.php | PHP | bsd-3-clause | 2,889 |
/*L
* Copyright Oracle inc, SAIC-F
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cadsr-util/LICENSE.txt for details.
*/
package gov.nih.nci.ncicb.cadsr.common.persistence.dao;
import gov.nih.nci.ncicb.cadsr.common.resource.ClassSchemeItem;
import gov.nih.nci.ncicb.cadsr.common.resource.ClassificationScheme;
import java.util.Collection;
import java.util.List;
public interface ClassificationSchemeDAO extends AdminComponentDAO
{
/** Returns the classification schemes that are roots of the HAS-A relationship
*
* */
public Collection<ClassificationScheme> getRootClassificationSchemes(String conteIdseq);
public Collection<ClassificationScheme> getChildrenClassificationSchemes(String pCSIdseq);
public List<ClassSchemeItem> getCSCSIHierarchyByCS(String csIdseq);
public List<ClassSchemeItem> getFirstLevelCSIByCS(String csIdseq);
public List<ClassSchemeItem> getChildrenCSI(String pCsiIdseq);
} | CBIIT/cadsr-util | cadsrutil/src/java/gov/nih/nci/ncicb/cadsr/common/persistence/dao/ClassificationSchemeDAO.java | Java | bsd-3-clause | 982 |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE590_Free_Memory_Not_on_Heap__delete_char_placement_new_82_bad.cpp
Label Definition File: CWE590_Free_Memory_Not_on_Heap__delete.pointer.label.xml
Template File: sources-sink-82_bad.tmpl.cpp
*/
/*
* @description
* CWE: 590 Free Memory Not on Heap
* BadSource: placement_new Data buffer is declared on the stack
* GoodSource: Allocate memory on the heap
* Sinks:
* BadSink : Print then free data
* Flow Variant: 82 Data flow: data passed in a parameter to a virtual method called via a pointer
*
* */
#ifndef OMITBAD
#include "std_testcase.h"
#include "CWE590_Free_Memory_Not_on_Heap__delete_char_placement_new_82.h"
namespace CWE590_Free_Memory_Not_on_Heap__delete_char_placement_new_82
{
void CWE590_Free_Memory_Not_on_Heap__delete_char_placement_new_82_bad::action(char * data)
{
printHexCharLine(*data);
/* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */
delete data;
}
}
#endif /* OMITBAD */
| JianpingZeng/xcc | xcc/test/juliet/testcases/CWE590_Free_Memory_Not_on_Heap/s02/CWE590_Free_Memory_Not_on_Heap__delete_char_placement_new_82_bad.cpp | C++ | bsd-3-clause | 1,027 |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "cc/surfaces/surface_aggregator.h"
#include <stddef.h>
#include <map>
#include "base/bind.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/stl_util.h"
#include "base/trace_event/trace_event.h"
#include "cc/base/math_util.h"
#include "cc/output/compositor_frame.h"
#include "cc/output/delegated_frame_data.h"
#include "cc/quads/draw_quad.h"
#include "cc/quads/render_pass_draw_quad.h"
#include "cc/quads/shared_quad_state.h"
#include "cc/quads/surface_draw_quad.h"
#include "cc/surfaces/surface.h"
#include "cc/surfaces/surface_factory.h"
#include "cc/surfaces/surface_manager.h"
#include "cc/trees/blocking_task_runner.h"
namespace cc {
namespace {
void MoveMatchingRequests(
RenderPassId id,
std::multimap<RenderPassId, scoped_ptr<CopyOutputRequest>>* copy_requests,
std::vector<scoped_ptr<CopyOutputRequest>>* output_requests) {
auto request_range = copy_requests->equal_range(id);
for (auto it = request_range.first; it != request_range.second; ++it) {
DCHECK(it->second);
output_requests->push_back(std::move(it->second));
}
copy_requests->erase(request_range.first, request_range.second);
}
} // namespace
SurfaceAggregator::SurfaceAggregator(SurfaceManager* manager,
ResourceProvider* provider,
bool aggregate_only_damaged)
: manager_(manager),
provider_(provider),
next_render_pass_id_(1),
aggregate_only_damaged_(aggregate_only_damaged),
weak_factory_(this) {
DCHECK(manager_);
}
SurfaceAggregator::~SurfaceAggregator() {
// Notify client of all surfaces being removed.
contained_surfaces_.clear();
ProcessAddedAndRemovedSurfaces();
}
SurfaceAggregator::PrewalkResult::PrewalkResult() {}
SurfaceAggregator::PrewalkResult::~PrewalkResult() {}
// Create a clip rect for an aggregated quad from the original clip rect and
// the clip rect from the surface it's on.
SurfaceAggregator::ClipData SurfaceAggregator::CalculateClipRect(
const ClipData& surface_clip,
const ClipData& quad_clip,
const gfx::Transform& target_transform) {
ClipData out_clip;
if (surface_clip.is_clipped)
out_clip = surface_clip;
if (quad_clip.is_clipped) {
// TODO(jamesr): This only works if target_transform maps integer
// rects to integer rects.
gfx::Rect final_clip =
MathUtil::MapEnclosingClippedRect(target_transform, quad_clip.rect);
if (out_clip.is_clipped)
out_clip.rect.Intersect(final_clip);
else
out_clip.rect = final_clip;
out_clip.is_clipped = true;
}
return out_clip;
}
class SurfaceAggregator::RenderPassIdAllocator {
public:
explicit RenderPassIdAllocator(int* next_index) : next_index_(next_index) {}
~RenderPassIdAllocator() {}
void AddKnownPass(RenderPassId id) {
if (id_to_index_map_.find(id) != id_to_index_map_.end())
return;
id_to_index_map_[id] = (*next_index_)++;
}
RenderPassId Remap(RenderPassId id) {
DCHECK(id_to_index_map_.find(id) != id_to_index_map_.end());
return RenderPassId(1, id_to_index_map_[id]);
}
private:
std::unordered_map<RenderPassId, int, RenderPassIdHash> id_to_index_map_;
int* next_index_;
DISALLOW_COPY_AND_ASSIGN(RenderPassIdAllocator);
};
static void UnrefHelper(base::WeakPtr<SurfaceFactory> surface_factory,
const ReturnedResourceArray& resources,
BlockingTaskRunner* main_thread_task_runner) {
if (surface_factory)
surface_factory->UnrefResources(resources);
}
RenderPassId SurfaceAggregator::RemapPassId(RenderPassId surface_local_pass_id,
SurfaceId surface_id) {
scoped_ptr<RenderPassIdAllocator>& allocator =
render_pass_allocator_map_[surface_id];
if (!allocator)
allocator.reset(new RenderPassIdAllocator(&next_render_pass_id_));
allocator->AddKnownPass(surface_local_pass_id);
return allocator->Remap(surface_local_pass_id);
}
int SurfaceAggregator::ChildIdForSurface(Surface* surface) {
SurfaceToResourceChildIdMap::iterator it =
surface_id_to_resource_child_id_.find(surface->surface_id());
if (it == surface_id_to_resource_child_id_.end()) {
int child_id =
provider_->CreateChild(base::Bind(&UnrefHelper, surface->factory()));
if (surface->factory()) {
provider_->SetChildNeedsSyncTokens(
child_id, surface->factory()->needs_sync_points());
}
surface_id_to_resource_child_id_[surface->surface_id()] = child_id;
return child_id;
} else {
return it->second;
}
}
gfx::Rect SurfaceAggregator::DamageRectForSurface(
const Surface* surface,
const RenderPass& source,
const gfx::Rect& full_rect) const {
auto it = previous_contained_surfaces_.find(surface->surface_id());
if (it == previous_contained_surfaces_.end())
return full_rect;
int previous_index = it->second;
if (previous_index == surface->frame_index())
return gfx::Rect();
if (previous_index == surface->frame_index() - 1)
return source.damage_rect;
return full_rect;
}
void SurfaceAggregator::HandleSurfaceQuad(
const SurfaceDrawQuad* surface_quad,
const gfx::Transform& target_transform,
const ClipData& clip_rect,
RenderPass* dest_pass) {
SurfaceId surface_id = surface_quad->surface_id;
// If this surface's id is already in our referenced set then it creates
// a cycle in the graph and should be dropped.
if (referenced_surfaces_.count(surface_id))
return;
Surface* surface = manager_->GetSurfaceForId(surface_id);
if (!surface)
return;
const CompositorFrame* frame = surface->GetEligibleFrame();
if (!frame)
return;
const DelegatedFrameData* frame_data = frame->delegated_frame_data.get();
if (!frame_data)
return;
std::multimap<RenderPassId, scoped_ptr<CopyOutputRequest>> copy_requests;
surface->TakeCopyOutputRequests(©_requests);
const RenderPassList& render_pass_list = frame_data->render_pass_list;
if (!valid_surfaces_.count(surface->surface_id())) {
for (auto& request : copy_requests)
request.second->SendEmptyResult();
return;
}
SurfaceSet::iterator it = referenced_surfaces_.insert(surface_id).first;
// TODO(vmpstr): provider check is a hack for unittests that don't set up a
// resource provider.
ResourceProvider::ResourceIdMap empty_map;
const ResourceProvider::ResourceIdMap& child_to_parent_map =
provider_ ? provider_->GetChildToParentMap(ChildIdForSurface(surface))
: empty_map;
bool merge_pass =
surface_quad->shared_quad_state->opacity == 1.f && copy_requests.empty();
const RenderPassList& referenced_passes = render_pass_list;
size_t passes_to_copy =
merge_pass ? referenced_passes.size() - 1 : referenced_passes.size();
for (size_t j = 0; j < passes_to_copy; ++j) {
const RenderPass& source = *referenced_passes[j];
size_t sqs_size = source.shared_quad_state_list.size();
size_t dq_size = source.quad_list.size();
scoped_ptr<RenderPass> copy_pass(RenderPass::Create(sqs_size, dq_size));
RenderPassId remapped_pass_id = RemapPassId(source.id, surface_id);
copy_pass->SetAll(remapped_pass_id, source.output_rect, gfx::Rect(),
source.transform_to_root_target,
source.has_transparent_background);
MoveMatchingRequests(source.id, ©_requests, ©_pass->copy_requests);
// Contributing passes aggregated in to the pass list need to take the
// transform of the surface quad into account to update their transform to
// the root surface.
copy_pass->transform_to_root_target.ConcatTransform(
surface_quad->shared_quad_state->quad_to_target_transform);
copy_pass->transform_to_root_target.ConcatTransform(target_transform);
copy_pass->transform_to_root_target.ConcatTransform(
dest_pass->transform_to_root_target);
CopyQuadsToPass(source.quad_list, source.shared_quad_state_list,
child_to_parent_map, gfx::Transform(), ClipData(),
copy_pass.get(), surface_id);
dest_pass_list_->push_back(std::move(copy_pass));
}
gfx::Transform surface_transform =
surface_quad->shared_quad_state->quad_to_target_transform;
surface_transform.ConcatTransform(target_transform);
const RenderPass& last_pass = *render_pass_list.back();
if (merge_pass) {
// TODO(jamesr): Clean up last pass special casing.
const QuadList& quads = last_pass.quad_list;
// Intersect the transformed visible rect and the clip rect to create a
// smaller cliprect for the quad.
ClipData surface_quad_clip_rect(
true, MathUtil::MapEnclosingClippedRect(
surface_quad->shared_quad_state->quad_to_target_transform,
surface_quad->visible_rect));
if (surface_quad->shared_quad_state->is_clipped) {
surface_quad_clip_rect.rect.Intersect(
surface_quad->shared_quad_state->clip_rect);
}
ClipData quads_clip =
CalculateClipRect(clip_rect, surface_quad_clip_rect, target_transform);
CopyQuadsToPass(quads, last_pass.shared_quad_state_list,
child_to_parent_map, surface_transform, quads_clip,
dest_pass, surface_id);
} else {
RenderPassId remapped_pass_id = RemapPassId(last_pass.id, surface_id);
SharedQuadState* shared_quad_state =
CopySharedQuadState(surface_quad->shared_quad_state, target_transform,
clip_rect, dest_pass);
RenderPassDrawQuad* quad =
dest_pass->CreateAndAppendDrawQuad<RenderPassDrawQuad>();
quad->SetNew(shared_quad_state,
surface_quad->rect,
surface_quad->visible_rect,
remapped_pass_id,
0,
gfx::Vector2dF(),
gfx::Size(),
FilterOperations(),
gfx::Vector2dF(),
FilterOperations());
}
referenced_surfaces_.erase(it);
}
SharedQuadState* SurfaceAggregator::CopySharedQuadState(
const SharedQuadState* source_sqs,
const gfx::Transform& target_transform,
const ClipData& clip_rect,
RenderPass* dest_render_pass) {
SharedQuadState* copy_shared_quad_state =
dest_render_pass->CreateAndAppendSharedQuadState();
copy_shared_quad_state->CopyFrom(source_sqs);
// target_transform contains any transformation that may exist
// between the context that these quads are being copied from (i.e. the
// surface's draw transform when aggregated from within a surface) to the
// target space of the pass. This will be identity except when copying the
// root draw pass from a surface into a pass when the surface draw quad's
// transform is not identity.
copy_shared_quad_state->quad_to_target_transform.ConcatTransform(
target_transform);
ClipData new_clip_rect = CalculateClipRect(
clip_rect, ClipData(source_sqs->is_clipped, source_sqs->clip_rect),
target_transform);
copy_shared_quad_state->is_clipped = new_clip_rect.is_clipped;
copy_shared_quad_state->clip_rect = new_clip_rect.rect;
return copy_shared_quad_state;
}
static gfx::Rect CalculateQuadSpaceDamageRect(
const gfx::Transform& quad_to_target_transform,
const gfx::Transform& target_to_root_transform,
const gfx::Rect& root_damage_rect) {
gfx::Transform quad_to_root_transform(target_to_root_transform,
quad_to_target_transform);
gfx::Transform inverse_transform(gfx::Transform::kSkipInitialization);
bool inverse_valid = quad_to_root_transform.GetInverse(&inverse_transform);
DCHECK(inverse_valid);
return MathUtil::ProjectEnclosingClippedRect(inverse_transform,
root_damage_rect);
}
void SurfaceAggregator::CopyQuadsToPass(
const QuadList& source_quad_list,
const SharedQuadStateList& source_shared_quad_state_list,
const ResourceProvider::ResourceIdMap& child_to_parent_map,
const gfx::Transform& target_transform,
const ClipData& clip_rect,
RenderPass* dest_pass,
SurfaceId surface_id) {
const SharedQuadState* last_copied_source_shared_quad_state = nullptr;
const SharedQuadState* dest_shared_quad_state = nullptr;
// If the current frame has copy requests then aggregate the entire
// thing, as otherwise parts of the copy requests may be ignored.
const bool ignore_undamaged = aggregate_only_damaged_ && !has_copy_requests_;
// Damage rect in the quad space of the current shared quad state.
// TODO(jbauman): This rect may contain unnecessary area if
// transform isn't axis-aligned.
gfx::Rect damage_rect_in_quad_space;
#if DCHECK_IS_ON()
// If quads have come in with SharedQuadState out of order, or when quads have
// invalid SharedQuadState pointer, it should DCHECK.
SharedQuadStateList::ConstIterator sqs_iter =
source_shared_quad_state_list.begin();
for (const auto& quad : source_quad_list) {
while (sqs_iter != source_shared_quad_state_list.end() &&
quad->shared_quad_state != *sqs_iter) {
++sqs_iter;
}
DCHECK(sqs_iter != source_shared_quad_state_list.end());
}
#endif
for (const auto& quad : source_quad_list) {
if (quad->material == DrawQuad::SURFACE_CONTENT) {
const SurfaceDrawQuad* surface_quad = SurfaceDrawQuad::MaterialCast(quad);
// HandleSurfaceQuad may add other shared quad state, so reset the
// current data.
last_copied_source_shared_quad_state = nullptr;
if (ignore_undamaged) {
gfx::Transform quad_to_target_transform(
target_transform,
quad->shared_quad_state->quad_to_target_transform);
damage_rect_in_quad_space = CalculateQuadSpaceDamageRect(
quad_to_target_transform, dest_pass->transform_to_root_target,
root_damage_rect_);
if (!damage_rect_in_quad_space.Intersects(quad->visible_rect))
continue;
}
HandleSurfaceQuad(surface_quad, target_transform, clip_rect, dest_pass);
} else {
if (quad->shared_quad_state != last_copied_source_shared_quad_state) {
dest_shared_quad_state = CopySharedQuadState(
quad->shared_quad_state, target_transform, clip_rect, dest_pass);
last_copied_source_shared_quad_state = quad->shared_quad_state;
if (aggregate_only_damaged_ && !has_copy_requests_) {
damage_rect_in_quad_space = CalculateQuadSpaceDamageRect(
dest_shared_quad_state->quad_to_target_transform,
dest_pass->transform_to_root_target, root_damage_rect_);
}
}
if (ignore_undamaged) {
if (!damage_rect_in_quad_space.Intersects(quad->visible_rect))
continue;
}
DrawQuad* dest_quad;
if (quad->material == DrawQuad::RENDER_PASS) {
const RenderPassDrawQuad* pass_quad =
RenderPassDrawQuad::MaterialCast(quad);
RenderPassId original_pass_id = pass_quad->render_pass_id;
RenderPassId remapped_pass_id =
RemapPassId(original_pass_id, surface_id);
dest_quad = dest_pass->CopyFromAndAppendRenderPassDrawQuad(
pass_quad, dest_shared_quad_state, remapped_pass_id);
} else {
dest_quad =
dest_pass->CopyFromAndAppendDrawQuad(quad, dest_shared_quad_state);
}
if (!child_to_parent_map.empty()) {
for (ResourceId& resource_id : dest_quad->resources) {
ResourceProvider::ResourceIdMap::const_iterator it =
child_to_parent_map.find(resource_id);
DCHECK(it != child_to_parent_map.end());
DCHECK_EQ(it->first, resource_id);
ResourceId remapped_id = it->second;
resource_id = remapped_id;
}
}
}
}
}
void SurfaceAggregator::CopyPasses(const DelegatedFrameData* frame_data,
Surface* surface) {
// The root surface is allowed to have copy output requests, so grab them
// off its render passes.
std::multimap<RenderPassId, scoped_ptr<CopyOutputRequest>> copy_requests;
surface->TakeCopyOutputRequests(©_requests);
const RenderPassList& source_pass_list = frame_data->render_pass_list;
DCHECK(valid_surfaces_.count(surface->surface_id()));
if (!valid_surfaces_.count(surface->surface_id()))
return;
// TODO(vmpstr): provider check is a hack for unittests that don't set up a
// resource provider.
ResourceProvider::ResourceIdMap empty_map;
const ResourceProvider::ResourceIdMap& child_to_parent_map =
provider_ ? provider_->GetChildToParentMap(ChildIdForSurface(surface))
: empty_map;
for (size_t i = 0; i < source_pass_list.size(); ++i) {
const RenderPass& source = *source_pass_list[i];
size_t sqs_size = source.shared_quad_state_list.size();
size_t dq_size = source.quad_list.size();
scoped_ptr<RenderPass> copy_pass(RenderPass::Create(sqs_size, dq_size));
MoveMatchingRequests(source.id, ©_requests, ©_pass->copy_requests);
RenderPassId remapped_pass_id =
RemapPassId(source.id, surface->surface_id());
copy_pass->SetAll(remapped_pass_id, source.output_rect, gfx::Rect(),
source.transform_to_root_target,
source.has_transparent_background);
CopyQuadsToPass(source.quad_list, source.shared_quad_state_list,
child_to_parent_map, gfx::Transform(), ClipData(),
copy_pass.get(), surface->surface_id());
dest_pass_list_->push_back(std::move(copy_pass));
}
}
void SurfaceAggregator::ProcessAddedAndRemovedSurfaces() {
for (const auto& surface : previous_contained_surfaces_) {
if (!contained_surfaces_.count(surface.first)) {
// Release resources of removed surface.
SurfaceToResourceChildIdMap::iterator it =
surface_id_to_resource_child_id_.find(surface.first);
if (it != surface_id_to_resource_child_id_.end()) {
provider_->DestroyChild(it->second);
surface_id_to_resource_child_id_.erase(it);
}
// Notify client of removed surface.
Surface* surface_ptr = manager_->GetSurfaceForId(surface.first);
if (surface_ptr) {
surface_ptr->RunDrawCallbacks(SurfaceDrawStatus::DRAW_SKIPPED);
}
}
}
}
// Walk the Surface tree from surface_id. Validate the resources of the current
// surface and its descendants, check if there are any copy requests, and
// return the combined damage rect.
gfx::Rect SurfaceAggregator::PrewalkTree(SurfaceId surface_id,
PrewalkResult* result) {
// This is for debugging a possible use after free.
// TODO(jbauman): Remove this once we have enough information.
// http://crbug.com/560181
base::WeakPtr<SurfaceAggregator> debug_weak_this = weak_factory_.GetWeakPtr();
if (referenced_surfaces_.count(surface_id))
return gfx::Rect();
Surface* surface = manager_->GetSurfaceForId(surface_id);
if (!surface) {
contained_surfaces_[surface_id] = 0;
return gfx::Rect();
}
contained_surfaces_[surface_id] = surface->frame_index();
const CompositorFrame* surface_frame = surface->GetEligibleFrame();
if (!surface_frame)
return gfx::Rect();
const DelegatedFrameData* frame_data =
surface_frame->delegated_frame_data.get();
if (!frame_data)
return gfx::Rect();
int child_id = 0;
// TODO(jbauman): hack for unit tests that don't set up rp
if (provider_) {
child_id = ChildIdForSurface(surface);
if (surface->factory())
surface->factory()->RefResources(frame_data->resource_list);
provider_->ReceiveFromChild(child_id, frame_data->resource_list);
}
CHECK(debug_weak_this.get());
ResourceProvider::ResourceIdSet referenced_resources;
size_t reserve_size = frame_data->resource_list.size();
referenced_resources.reserve(reserve_size);
bool invalid_frame = false;
ResourceProvider::ResourceIdMap empty_map;
const ResourceProvider::ResourceIdMap& child_to_parent_map =
provider_ ? provider_->GetChildToParentMap(child_id) : empty_map;
CHECK(debug_weak_this.get());
// Each pair in the vector is a child surface and the transform from its
// target to the root target of this surface.
std::vector<std::pair<SurfaceId, gfx::Transform>> child_surfaces;
for (const auto& render_pass : frame_data->render_pass_list) {
for (const auto& quad : render_pass->quad_list) {
if (quad->material == DrawQuad::SURFACE_CONTENT) {
const SurfaceDrawQuad* surface_quad =
SurfaceDrawQuad::MaterialCast(quad);
gfx::Transform target_to_surface_transform(
render_pass->transform_to_root_target,
surface_quad->shared_quad_state->quad_to_target_transform);
child_surfaces.push_back(std::make_pair(surface_quad->surface_id,
target_to_surface_transform));
}
if (!provider_)
continue;
for (ResourceId resource_id : quad->resources) {
if (!child_to_parent_map.count(resource_id)) {
invalid_frame = true;
break;
}
referenced_resources.insert(resource_id);
}
}
}
if (invalid_frame)
return gfx::Rect();
CHECK(debug_weak_this.get());
valid_surfaces_.insert(surface->surface_id());
if (provider_)
provider_->DeclareUsedResourcesFromChild(child_id, referenced_resources);
CHECK(debug_weak_this.get());
gfx::Rect damage_rect;
if (!frame_data->render_pass_list.empty()) {
RenderPass* last_pass = frame_data->render_pass_list.back().get();
damage_rect =
DamageRectForSurface(surface, *last_pass, last_pass->output_rect);
}
// Avoid infinite recursion by adding current surface to
// referenced_surfaces_.
SurfaceSet::iterator it =
referenced_surfaces_.insert(surface->surface_id()).first;
for (const auto& surface_info : child_surfaces) {
gfx::Rect surface_damage = PrewalkTree(surface_info.first, result);
damage_rect.Union(
MathUtil::MapEnclosingClippedRect(surface_info.second, surface_damage));
}
CHECK(debug_weak_this.get());
for (const auto& surface_id : surface_frame->metadata.referenced_surfaces) {
if (!contained_surfaces_.count(surface_id)) {
result->undrawn_surfaces.insert(surface_id);
PrewalkTree(surface_id, result);
}
}
CHECK(debug_weak_this.get());
if (surface->factory())
surface->factory()->WillDrawSurface(surface->surface_id(), damage_rect);
CHECK(debug_weak_this.get());
for (const auto& render_pass : frame_data->render_pass_list)
result->has_copy_requests |= !render_pass->copy_requests.empty();
referenced_surfaces_.erase(it);
return damage_rect;
}
void SurfaceAggregator::CopyUndrawnSurfaces(PrewalkResult* prewalk_result) {
// undrawn_surfaces are Surfaces that were identified by prewalk as being
// referenced by a drawn Surface, but aren't contained in a SurfaceDrawQuad.
// They need to be iterated over to ensure that any copy requests on them
// (or on Surfaces they reference) are executed.
std::vector<SurfaceId> surfaces_to_copy(
prewalk_result->undrawn_surfaces.begin(),
prewalk_result->undrawn_surfaces.end());
for (size_t i = 0; i < surfaces_to_copy.size(); i++) {
SurfaceId surface_id = surfaces_to_copy[i];
Surface* surface = manager_->GetSurfaceForId(surface_id);
if (!surface)
continue;
const CompositorFrame* surface_frame = surface->GetEligibleFrame();
if (!surface_frame)
continue;
bool surface_has_copy_requests = false;
for (const auto& render_pass :
surface_frame->delegated_frame_data->render_pass_list) {
surface_has_copy_requests |= !render_pass->copy_requests.empty();
}
if (!surface_has_copy_requests) {
// Children are not necessarily included in undrawn_surfaces (because
// they weren't referenced directly from a drawn surface), but may have
// copy requests, so make sure to check them as well.
for (const auto& child_id : surface_frame->metadata.referenced_surfaces) {
// Don't iterate over the child Surface if it was already listed as a
// child of a different Surface, or in the case where there's infinite
// recursion.
if (!prewalk_result->undrawn_surfaces.count(child_id)) {
surfaces_to_copy.push_back(child_id);
prewalk_result->undrawn_surfaces.insert(child_id);
}
}
} else {
SurfaceSet::iterator it = referenced_surfaces_.insert(surface_id).first;
CopyPasses(surface_frame->delegated_frame_data.get(), surface);
referenced_surfaces_.erase(it);
}
}
}
scoped_ptr<CompositorFrame> SurfaceAggregator::Aggregate(SurfaceId surface_id) {
Surface* surface = manager_->GetSurfaceForId(surface_id);
DCHECK(surface);
contained_surfaces_[surface_id] = surface->frame_index();
const CompositorFrame* root_surface_frame = surface->GetEligibleFrame();
if (!root_surface_frame)
return nullptr;
TRACE_EVENT0("cc", "SurfaceAggregator::Aggregate");
scoped_ptr<CompositorFrame> frame(new CompositorFrame);
frame->delegated_frame_data = make_scoped_ptr(new DelegatedFrameData);
DCHECK(root_surface_frame->delegated_frame_data);
dest_resource_list_ = &frame->delegated_frame_data->resource_list;
dest_pass_list_ = &frame->delegated_frame_data->render_pass_list;
valid_surfaces_.clear();
PrewalkResult prewalk_result;
root_damage_rect_ = PrewalkTree(surface_id, &prewalk_result);
has_copy_requests_ = prewalk_result.has_copy_requests;
CopyUndrawnSurfaces(&prewalk_result);
SurfaceSet::iterator it = referenced_surfaces_.insert(surface_id).first;
CopyPasses(root_surface_frame->delegated_frame_data.get(), surface);
referenced_surfaces_.erase(it);
DCHECK(referenced_surfaces_.empty());
if (dest_pass_list_->empty())
return nullptr;
dest_pass_list_->back()->damage_rect = root_damage_rect_;
dest_pass_list_ = NULL;
ProcessAddedAndRemovedSurfaces();
contained_surfaces_.swap(previous_contained_surfaces_);
contained_surfaces_.clear();
for (SurfaceIndexMap::iterator it = previous_contained_surfaces_.begin();
it != previous_contained_surfaces_.end();
++it) {
Surface* surface = manager_->GetSurfaceForId(it->first);
if (surface)
surface->TakeLatencyInfo(&frame->metadata.latency_info);
}
// TODO(jamesr): Aggregate all resource references into the returned frame's
// resource list.
return frame;
}
void SurfaceAggregator::ReleaseResources(SurfaceId surface_id) {
SurfaceToResourceChildIdMap::iterator it =
surface_id_to_resource_child_id_.find(surface_id);
if (it != surface_id_to_resource_child_id_.end()) {
provider_->DestroyChild(it->second);
surface_id_to_resource_child_id_.erase(it);
}
}
void SurfaceAggregator::SetFullDamageForSurface(SurfaceId surface_id) {
auto it = previous_contained_surfaces_.find(surface_id);
if (it == previous_contained_surfaces_.end())
return;
// Set the last drawn index as 0 to ensure full damage next time it's drawn.
it->second = 0;
}
} // namespace cc
| highweb-project/highweb-webcl-html5spec | cc/surfaces/surface_aggregator.cc | C++ | bsd-3-clause | 27,333 |
from django.utils.datetime_safe import datetime
from django.utils.translation import ugettext_lazy as _
from poradnia.users.models import User
def users_total(*args, **kwargs):
return User.objects.count()
users_total.name = _("Users total")
users_total.description = _("Number of users registered total")
def users_monthly(*args, **kwargs):
today = datetime.today().replace(day=1)
return User.objects.filter(created_on__date__gte=today).count()
users_monthly.name = _("Users monthly")
users_monthly.description = _("Number of users registered in month")
def users_active(*args, **kwargs):
return User.objects.active().count()
users_active.name = _("Active users")
users_active.description = _("Number of active users in month")
def users_active_staff(*args, **kwargs):
return User.objects.active().filter(is_staff=True).count()
users_active_staff.name = _("Active staff member")
users_active_staff.description = _(
"Number of team members who have made at least one message in the current month."
)
| watchdogpolska/poradnia.siecobywatelska.pl | poradnia/users/metric.py | Python | bsd-3-clause | 1,040 |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE124_Buffer_Underwrite__CWE839_fscanf_83_bad.cpp
Label Definition File: CWE124_Buffer_Underwrite__CWE839.label.xml
Template File: sources-sinks-83_bad.tmpl.cpp
*/
/*
* @description
* CWE: 124 Buffer Underwrite
* BadSource: fscanf Read data from the console using fscanf()
* GoodSource: Non-negative but less than 10
* Sinks:
* GoodSink: Ensure the array index is valid
* BadSink : Improperly check the array index by not checking the lower bound
* Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack
*
* */
#ifndef OMITBAD
#include "std_testcase.h"
#include "CWE124_Buffer_Underwrite__CWE839_fscanf_83.h"
namespace CWE124_Buffer_Underwrite__CWE839_fscanf_83
{
CWE124_Buffer_Underwrite__CWE839_fscanf_83_bad::CWE124_Buffer_Underwrite__CWE839_fscanf_83_bad(int dataCopy)
{
data = dataCopy;
/* POTENTIAL FLAW: Read data from the console using fscanf() */
fscanf(stdin, "%d", &data);
}
CWE124_Buffer_Underwrite__CWE839_fscanf_83_bad::~CWE124_Buffer_Underwrite__CWE839_fscanf_83_bad()
{
{
int i;
int buffer[10] = { 0 };
/* POTENTIAL FLAW: Attempt to access a negative index of the array
* This code does not check to see if the array index is negative */
if (data < 10)
{
buffer[data] = 1;
/* Print the array values */
for(i = 0; i < 10; i++)
{
printIntLine(buffer[i]);
}
}
else
{
printLine("ERROR: Array index is negative.");
}
}
}
}
#endif /* OMITBAD */
| JianpingZeng/xcc | xcc/test/juliet/testcases/CWE124_Buffer_Underwrite/s01/CWE124_Buffer_Underwrite__CWE839_fscanf_83_bad.cpp | C++ | bsd-3-clause | 1,727 |
/* Copyright (C) 2005-2011 Fabio Riccardi */
package com.lightcrafts.utils.filecache;
import java.io.File;
/**
* A <code>FileCacheKeyMapper</code> is used to map a cache key to a file on
* disk.
*
* @author Paul J. Lucas [paul@lightcrafts.com]
*/
public interface FileCacheKeyMapper {
/**
* Gets the cache directory.
*
* @return Returns said directory.
*/
File getCacheDirectory();
/**
* Maps a key to a {@link File}.
*
* @param key The key to map.
* @param ensurePathExists If <code>true</code>, ensure the path to the
* returned file exists.
* @return Returns said {@link File}.
*/
File mapKeyToFile( String key, boolean ensurePathExists );
}
/* vim:set et sw=4 ts=4: */
| MarinnaCole/LightZone | lightcrafts/src/com/lightcrafts/utils/filecache/FileCacheKeyMapper.java | Java | bsd-3-clause | 755 |
<?php
$this->pageTitle = Yii::app()->name . ' - Login';
$this->breadcrumbs = array(
'Login',
);
?>
<div class="form">
<?php
$form = $this->beginWidget('CActiveForm', array(
'id' => 'login-form',
'enableClientValidation' => true,
// 'enableAjaxValidation'=>true,
'clientOptions' => array(
'validateOnSubmit' => true,
),
'action' => '/site/login',
));
?>
<!--
<p class="note">Fields with <span class="required">*</span> are required.</p>
-->
<div class="row">
<?php echo $form->labelEx($model, 'username'); ?>
<?php echo $form->textField($model, 'username'); ?>
<?php echo $form->error($model, 'username'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model, 'password'); ?>
<?php echo $form->passwordField($model, 'password'); ?>
<?php echo $form->error($model, 'password'); ?>
</div>
<div class="row rememberMe">
<?php echo $form->checkBox($model, 'rememberMe'); ?>
<?php echo $form->label($model, 'rememberMe'); ?>
<?php echo $form->error($model, 'rememberMe'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Login'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
| danielmoniz/red_torpedo | project-files/protected/views/site/login.php | PHP | bsd-3-clause | 1,348 |
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "sandbox/win/src/window.h"
#include <aclapi.h>
#include <memory>
#include "base/notreached.h"
#include "base/win/win_util.h"
#include "base/win/windows_version.h"
#include "sandbox/win/src/acl.h"
#include "sandbox/win/src/sid.h"
namespace {
// Gets the security attributes of a window object referenced by |handle|. The
// lpSecurityDescriptor member of the SECURITY_ATTRIBUTES parameter returned
// must be freed using LocalFree by the caller.
bool GetSecurityAttributes(HANDLE handle, SECURITY_ATTRIBUTES* attributes) {
attributes->bInheritHandle = false;
attributes->nLength = sizeof(SECURITY_ATTRIBUTES);
PACL dacl = nullptr;
DWORD result = ::GetSecurityInfo(
handle, SE_WINDOW_OBJECT, DACL_SECURITY_INFORMATION, nullptr, nullptr,
&dacl, nullptr, &attributes->lpSecurityDescriptor);
if (ERROR_SUCCESS == result)
return true;
return false;
}
} // namespace
namespace sandbox {
ResultCode CreateAltWindowStation(HWINSTA* winsta) {
// Get the security attributes from the current window station; we will
// use this as the base security attributes for the new window station.
HWINSTA current_winsta = ::GetProcessWindowStation();
if (!current_winsta)
return SBOX_ERROR_CANNOT_GET_WINSTATION;
SECURITY_ATTRIBUTES attributes = {0};
if (!GetSecurityAttributes(current_winsta, &attributes))
return SBOX_ERROR_CANNOT_QUERY_WINSTATION_SECURITY;
// Create the window station using nullptr for the name to ask the os to
// generate it.
*winsta = ::CreateWindowStationW(
nullptr, 0, GENERIC_READ | WINSTA_CREATEDESKTOP, &attributes);
if (!*winsta && ::GetLastError() == ERROR_ACCESS_DENIED) {
*winsta = ::CreateWindowStationW(
nullptr, 0, WINSTA_READATTRIBUTES | WINSTA_CREATEDESKTOP, &attributes);
}
LocalFree(attributes.lpSecurityDescriptor);
if (*winsta)
return SBOX_ALL_OK;
return SBOX_ERROR_CANNOT_CREATE_WINSTATION;
}
ResultCode CreateAltDesktop(HWINSTA winsta, HDESK* desktop) {
std::wstring desktop_name = L"sbox_alternate_desktop_";
if (!winsta) {
desktop_name += L"local_winstation_";
}
// Append the current PID to the desktop name.
wchar_t buffer[16];
_snwprintf_s(buffer, sizeof(buffer) / sizeof(wchar_t), L"0x%X",
::GetCurrentProcessId());
desktop_name += buffer;
HDESK current_desktop = GetThreadDesktop(GetCurrentThreadId());
if (!current_desktop)
return SBOX_ERROR_CANNOT_GET_DESKTOP;
// Get the security attributes from the current desktop, we will use this as
// the base security attributes for the new desktop.
SECURITY_ATTRIBUTES attributes = {0};
if (!GetSecurityAttributes(current_desktop, &attributes))
return SBOX_ERROR_CANNOT_QUERY_DESKTOP_SECURITY;
// Detect when the current desktop has a null DACL since it will require
// special casing below.
bool is_null_dacl = false;
BOOL dacl_present = false;
ACL* acl = nullptr;
BOOL dacl_defaulted = false;
if (::GetSecurityDescriptorDacl(attributes.lpSecurityDescriptor,
&dacl_present, &acl, &dacl_defaulted)) {
is_null_dacl = dacl_present && (acl == nullptr);
}
// Back up the current window station, in case we need to switch it.
HWINSTA current_winsta = ::GetProcessWindowStation();
if (winsta) {
// We need to switch to the alternate window station before creating the
// desktop.
if (!::SetProcessWindowStation(winsta)) {
::LocalFree(attributes.lpSecurityDescriptor);
return SBOX_ERROR_CANNOT_CREATE_DESKTOP;
}
}
// Create the destkop.
*desktop = ::CreateDesktop(desktop_name.c_str(), nullptr, nullptr, 0,
DESKTOP_CREATEWINDOW | DESKTOP_READOBJECTS |
READ_CONTROL | WRITE_DAC | WRITE_OWNER,
&attributes);
::LocalFree(attributes.lpSecurityDescriptor);
if (winsta) {
// Revert to the right window station.
if (!::SetProcessWindowStation(current_winsta)) {
return SBOX_ERROR_FAILED_TO_SWITCH_BACK_WINSTATION;
}
}
if (*desktop) {
if (is_null_dacl) {
// If the desktop had a NULL DACL, it allowed access to everything. When
// we apply a new ACE with |kDesktopDenyMask| below, a NULL DACL would be
// replaced with a new DACL with one ACE that denies access - which means
// there is no ACE to allow anything access to the desktop. In this case,
// replace the NULL DACL with one that has a single ACE that allows access
// to everyone, so the desktop remains accessible when we further modify
// the DACL. Also need WinBuiltinAnyPackageSid for AppContainer processes.
if (base::win::GetVersion() >= base::win::Version::WIN8) {
AddKnownSidToObject(*desktop, SE_WINDOW_OBJECT,
Sid(WinBuiltinAnyPackageSid), GRANT_ACCESS,
GENERIC_ALL);
}
AddKnownSidToObject(*desktop, SE_WINDOW_OBJECT, Sid(WinWorldSid),
GRANT_ACCESS, GENERIC_ALL);
}
// Replace the DACL on the new Desktop with a reduced privilege version.
// We can soft fail on this for now, as it's just an extra mitigation.
static const ACCESS_MASK kDesktopDenyMask =
WRITE_DAC | WRITE_OWNER | DELETE | DESKTOP_CREATEMENU |
DESKTOP_CREATEWINDOW | DESKTOP_HOOKCONTROL | DESKTOP_JOURNALPLAYBACK |
DESKTOP_JOURNALRECORD | DESKTOP_SWITCHDESKTOP;
AddKnownSidToObject(*desktop, SE_WINDOW_OBJECT, Sid(WinRestrictedCodeSid),
DENY_ACCESS, kDesktopDenyMask);
return SBOX_ALL_OK;
}
return SBOX_ERROR_CANNOT_CREATE_DESKTOP;
}
std::wstring GetFullDesktopName(HWINSTA winsta, HDESK desktop) {
if (!desktop) {
NOTREACHED();
return std::wstring();
}
std::wstring name;
if (winsta) {
name = base::win::GetWindowObjectName(winsta);
name += L'\\';
}
name += base::win::GetWindowObjectName(desktop);
return name;
}
} // namespace sandbox
| scheib/chromium | sandbox/win/src/window.cc | C++ | bsd-3-clause | 6,157 |
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/test/web_layer_tree_view_impl_for_testing.h"
#include "base/command_line.h"
#include "base/strings/string_number_conversions.h"
#include "base/synchronization/lock.h"
#include "base/thread_task_runner_handle.h"
#include "cc/animation/animation_host.h"
#include "cc/animation/animation_timeline.h"
#include "cc/base/switches.h"
#include "cc/blink/web_layer_impl.h"
#include "cc/input/input_handler.h"
#include "cc/layers/layer.h"
#include "cc/scheduler/begin_frame_source.h"
#include "cc/trees/layer_tree_host.h"
#include "content/test/test_blink_web_unit_test_support.h"
#include "third_party/WebKit/public/platform/Platform.h"
#include "third_party/WebKit/public/platform/WebLayer.h"
#include "third_party/WebKit/public/platform/WebLayerTreeView.h"
#include "third_party/WebKit/public/platform/WebSize.h"
#include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
using blink::WebColor;
using blink::WebRect;
using blink::WebSize;
namespace content {
WebLayerTreeViewImplForTesting::WebLayerTreeViewImplForTesting() {}
WebLayerTreeViewImplForTesting::~WebLayerTreeViewImplForTesting() {}
void WebLayerTreeViewImplForTesting::Initialize() {
cc::LayerTreeSettings settings;
// For web contents, layer transforms should scale up the contents of layers
// to keep content always crisp when possible.
settings.layer_transforms_should_scale_layer_contents = true;
// Accelerated animations are enabled for unit tests.
settings.accelerated_animation_enabled = true;
// External cc::AnimationHost is enabled for unit tests.
settings.use_compositor_animation_timelines = true;
cc::LayerTreeHost::InitParams params;
params.client = this;
params.settings = &settings;
params.main_task_runner = base::ThreadTaskRunnerHandle::Get();
params.task_graph_runner = &task_graph_runner_;
layer_tree_host_ = cc::LayerTreeHost::CreateSingleThreaded(this, ¶ms);
DCHECK(layer_tree_host_);
}
void WebLayerTreeViewImplForTesting::setRootLayer(
const blink::WebLayer& root) {
layer_tree_host_->SetRootLayer(
static_cast<const cc_blink::WebLayerImpl*>(&root)->layer());
}
void WebLayerTreeViewImplForTesting::clearRootLayer() {
layer_tree_host_->SetRootLayer(scoped_refptr<cc::Layer>());
}
void WebLayerTreeViewImplForTesting::attachCompositorAnimationTimeline(
cc::AnimationTimeline* compositor_timeline) {
DCHECK(layer_tree_host_->animation_host());
layer_tree_host_->animation_host()->AddAnimationTimeline(compositor_timeline);
}
void WebLayerTreeViewImplForTesting::detachCompositorAnimationTimeline(
cc::AnimationTimeline* compositor_timeline) {
DCHECK(layer_tree_host_->animation_host());
layer_tree_host_->animation_host()->RemoveAnimationTimeline(
compositor_timeline);
}
void WebLayerTreeViewImplForTesting::setViewportSize(
const WebSize& unused_deprecated,
const WebSize& device_viewport_size) {
layer_tree_host_->SetViewportSize(device_viewport_size);
}
void WebLayerTreeViewImplForTesting::setViewportSize(
const WebSize& device_viewport_size) {
layer_tree_host_->SetViewportSize(device_viewport_size);
}
void WebLayerTreeViewImplForTesting::setDeviceScaleFactor(
float device_scale_factor) {
layer_tree_host_->SetDeviceScaleFactor(device_scale_factor);
}
void WebLayerTreeViewImplForTesting::setBackgroundColor(WebColor color) {
layer_tree_host_->set_background_color(color);
}
void WebLayerTreeViewImplForTesting::setHasTransparentBackground(
bool transparent) {
layer_tree_host_->set_has_transparent_background(transparent);
}
void WebLayerTreeViewImplForTesting::setVisible(bool visible) {
layer_tree_host_->SetVisible(visible);
}
void WebLayerTreeViewImplForTesting::setPageScaleFactorAndLimits(
float page_scale_factor,
float minimum,
float maximum) {
layer_tree_host_->SetPageScaleFactorAndLimits(
page_scale_factor, minimum, maximum);
}
void WebLayerTreeViewImplForTesting::startPageScaleAnimation(
const blink::WebPoint& scroll,
bool use_anchor,
float new_page_scale,
double duration_sec) {}
void WebLayerTreeViewImplForTesting::setNeedsAnimate() {
layer_tree_host_->SetNeedsAnimate();
}
void WebLayerTreeViewImplForTesting::didStopFlinging() {}
void WebLayerTreeViewImplForTesting::setDeferCommits(bool defer_commits) {
layer_tree_host_->SetDeferCommits(defer_commits);
}
void WebLayerTreeViewImplForTesting::UpdateLayerTreeHost() {
}
void WebLayerTreeViewImplForTesting::ApplyViewportDeltas(
const gfx::Vector2dF& inner_delta,
const gfx::Vector2dF& outer_delta,
const gfx::Vector2dF& elastic_overscroll_delta,
float page_scale,
float top_controls_delta) {
}
void WebLayerTreeViewImplForTesting::RequestNewOutputSurface() {
// Intentionally do not create and set an OutputSurface.
}
void WebLayerTreeViewImplForTesting::DidFailToInitializeOutputSurface() {
NOTREACHED();
}
void WebLayerTreeViewImplForTesting::registerForAnimations(
blink::WebLayer* layer) {
cc::Layer* cc_layer = static_cast<cc_blink::WebLayerImpl*>(layer)->layer();
cc_layer->RegisterForAnimations(layer_tree_host_->animation_registrar());
}
void WebLayerTreeViewImplForTesting::registerViewportLayers(
const blink::WebLayer* overscrollElasticityLayer,
const blink::WebLayer* pageScaleLayer,
const blink::WebLayer* innerViewportScrollLayer,
const blink::WebLayer* outerViewportScrollLayer) {
layer_tree_host_->RegisterViewportLayers(
// The scroll elasticity layer will only exist when using pinch virtual
// viewports.
overscrollElasticityLayer
? static_cast<const cc_blink::WebLayerImpl*>(
overscrollElasticityLayer)->layer()
: NULL,
static_cast<const cc_blink::WebLayerImpl*>(pageScaleLayer)->layer(),
static_cast<const cc_blink::WebLayerImpl*>(innerViewportScrollLayer)
->layer(),
// The outer viewport layer will only exist when using pinch virtual
// viewports.
outerViewportScrollLayer
? static_cast<const cc_blink::WebLayerImpl*>(outerViewportScrollLayer)
->layer()
: NULL);
}
void WebLayerTreeViewImplForTesting::clearViewportLayers() {
layer_tree_host_->RegisterViewportLayers(scoped_refptr<cc::Layer>(),
scoped_refptr<cc::Layer>(),
scoped_refptr<cc::Layer>(),
scoped_refptr<cc::Layer>());
}
void WebLayerTreeViewImplForTesting::registerSelection(
const blink::WebSelection& selection) {
}
void WebLayerTreeViewImplForTesting::clearSelection() {
}
void WebLayerTreeViewImplForTesting::setEventListenerProperties(
blink::WebEventListenerClass eventClass,
blink::WebEventListenerProperties properties) {
// Equality of static_cast is checked in render_widget_compositor.cc.
layer_tree_host_->SetEventListenerProperties(
static_cast<cc::EventListenerClass>(eventClass),
static_cast<cc::EventListenerProperties>(properties));
}
blink::WebEventListenerProperties
WebLayerTreeViewImplForTesting::eventListenerProperties(
blink::WebEventListenerClass event_class) const {
// Equality of static_cast is checked in render_widget_compositor.cc.
return static_cast<blink::WebEventListenerProperties>(
layer_tree_host_->event_listener_properties(
static_cast<cc::EventListenerClass>(event_class)));
}
void WebLayerTreeViewImplForTesting::setHaveScrollEventHandlers(
bool have_event_handlers) {
layer_tree_host_->SetHaveScrollEventHandlers(have_event_handlers);
}
bool WebLayerTreeViewImplForTesting::haveScrollEventHandlers() const {
return layer_tree_host_->have_scroll_event_handlers();
}
} // namespace content
| ds-hwang/chromium-crosswalk | content/test/web_layer_tree_view_impl_for_testing.cc | C++ | bsd-3-clause | 7,916 |
<?php
namespace test\h\l;
class c { } | theosyspe/levent_01 | vendor/ZF2/bin/test/h/l/c.php | PHP | bsd-3-clause | 37 |
<?php
/**
* Abstract property class
*
* Extend this class to create custom complex properties
*
* @package Sabre
* @subpackage DAV
* @copyright Copyright (C) 2007-2011 Rooftop Solutions. All rights reserved.
* @author Evert Pot (http://www.rooftopsolutions.nl/)
* @license http://code.google.com/p/sabredav/wiki/License Modified BSD License
*/
abstract class Sabre_DAV_Property {
abstract function serialize(Sabre_DAV_Server $server, DOMElement $prop);
static function unserialize(DOMElement $prop) {
return null;
}
}
| mgrauer/midas3score | modules/webdav/library/SabreDAV/lib/Sabre/DAV/Property.php | PHP | bsd-3-clause | 557 |
/*
* Copyright (c) 2009-2015, United States Government, as represented by the Secretary of Health and Human Services.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the United States Government nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE UNITED STATES GOVERNMENT BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package gov.hhs.fha.nhinc.docsubmission.adapter.proxy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.lang.reflect.Method;
import org.junit.Test;
import gov.hhs.fha.nhinc.aspect.AdapterDelegationEvent;
import gov.hhs.fha.nhinc.common.nhinccommon.AssertionType;
import gov.hhs.fha.nhinc.docsubmission.aspect.DocSubmissionBaseEventDescriptionBuilder;
import ihe.iti.xds_b._2007.ProvideAndRegisterDocumentSetRequestType;
/**
* @author achidamb
*
*/
public class AdapterDocSubmissionProxyJavaImplTest {
@Test
public void hasAdapterDelegationEvent() throws Exception {
Class<AdapterDocSubmissionProxyJavaImpl> clazz = AdapterDocSubmissionProxyJavaImpl.class;
Method method = clazz.getMethod("provideAndRegisterDocumentSetB",
ProvideAndRegisterDocumentSetRequestType.class, AssertionType.class);
AdapterDelegationEvent annotation = method.getAnnotation(AdapterDelegationEvent.class);
assertNotNull(annotation);
assertEquals(DocSubmissionBaseEventDescriptionBuilder.class, annotation.beforeBuilder());
assertEquals(DocSubmissionBaseEventDescriptionBuilder.class, annotation.afterReturningBuilder());
assertEquals("Document Submission", annotation.serviceType());
assertEquals("", annotation.version());
}
}
| beiyuxinke/CONNECT | Product/Production/Services/DocumentSubmissionCore/src/test/java/gov/hhs/fha/nhinc/docsubmission/adapter/proxy/AdapterDocSubmissionProxyJavaImplTest.java | Java | bsd-3-clause | 3,032 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Inbox2.Framework;
using Inbox2.Framework.Deployment;
namespace Inbox2.Core.Upgrade
{
public class upgrade_0_1_0_2 : UpgradeActionBase
{
public override Version TargetVersion
{
get { return new Version("0.1.0.2"); }
}
protected override void UpgradeCore()
{
ClientState.Current.DataService.ExecuteNonQuery("alter table Documents add column IsRead text");
ClientState.Current.DataService.ExecuteNonQuery("update Documents set IsRead='True' where DocumentState = 'Read'");
ClientState.Current.DataService.ExecuteNonQuery("update Documents set IsRead='False' where DocumentState != 'Read';");
ClientState.Current.DataService.ExecuteNonQuery("alter table Messages add column IsRead text;");
ClientState.Current.DataService.ExecuteNonQuery("update Messages set IsRead='True' where MessageState = 'Read'");
ClientState.Current.DataService.ExecuteNonQuery("update Messages set IsRead='False' where MessageState != 'Read'");
}
}
}
| Klaudit/inbox2_desktop | Code/Client/Inbox2/Core/Upgrade/upgrade_0_1_0_2.cs | C# | bsd-3-clause | 1,084 |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_int_memcpy_09.cpp
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805.label.xml
Template File: sources-sink-09.tmpl.cpp
*/
/*
* @description
* CWE: 122 Heap Based Buffer Overflow
* BadSource: Allocate using new[] and set data pointer to a small buffer
* GoodSource: Allocate using new[] and set data pointer to a large buffer
* Sink: memcpy
* BadSink : Copy int array to data using memcpy
* Flow Variant: 09 Control flow: if(GLOBAL_CONST_TRUE) and if(GLOBAL_CONST_FALSE)
*
* */
#include "std_testcase.h"
namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_int_memcpy_09
{
#ifndef OMITBAD
void bad()
{
int * data;
data = NULL;
if(GLOBAL_CONST_TRUE)
{
/* FLAW: Allocate using new[] and point data to a small buffer that is smaller than the large buffer used in the sinks */
data = new int[50];
}
{
int source[100] = {0}; /* fill with 0's */
/* POTENTIAL FLAW: Possible buffer overflow if data < 100 */
memcpy(data, source, 100*sizeof(int));
printIntLine(data[0]);
delete [] data;
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B1() - use goodsource and badsink by changing the GLOBAL_CONST_TRUE to GLOBAL_CONST_FALSE */
static void goodG2B1()
{
int * data;
data = NULL;
if(GLOBAL_CONST_FALSE)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
}
else
{
/* FIX: Allocate using new[] and point data to a large buffer that is at least as large as the large buffer used in the sink */
data = new int[100];
}
{
int source[100] = {0}; /* fill with 0's */
/* POTENTIAL FLAW: Possible buffer overflow if data < 100 */
memcpy(data, source, 100*sizeof(int));
printIntLine(data[0]);
delete [] data;
}
}
/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */
static void goodG2B2()
{
int * data;
data = NULL;
if(GLOBAL_CONST_TRUE)
{
/* FIX: Allocate using new[] and point data to a large buffer that is at least as large as the large buffer used in the sink */
data = new int[100];
}
{
int source[100] = {0}; /* fill with 0's */
/* POTENTIAL FLAW: Possible buffer overflow if data < 100 */
memcpy(data, source, 100*sizeof(int));
printIntLine(data[0]);
delete [] data;
}
}
void good()
{
goodG2B1();
goodG2B2();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_int_memcpy_09; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| JianpingZeng/xcc | xcc/test/juliet/testcases/CWE122_Heap_Based_Buffer_Overflow/s03/CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_int_memcpy_09.cpp | C++ | bsd-3-clause | 3,578 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#
from os.path import dirname
from os.path import join
from setuptools import find_packages
from setuptools import setup
# requirements
with open('requirements.txt') as f:
required = f.read().splitlines()
with open(join(dirname(__file__), 'pyrcmd3/VERSION'), 'rb') as f:
version = f.read().decode('ascii').strip()
setup(
name="pyrcmd3",
version=version,
description="Python3 Remote Commands toolkit",
long_description=open('README.rst').read(),
author="Marreta",
author_email="coder@marreta.org",
maintainer="Bruno Costa, Kairo Araujo",
maintainer_email="coder@marreta.org",
url="https://github.com/marreta/pyrcmd3/",
keywords="Python3 Remote Command Commands SSH Toolkit",
packages=find_packages(exclude=['*.test', 'tests.*']),
package_data={'': ['license.txt', 'pyrcmd3/VERSION']},
install_requires=required,
include_package_data=True,
license='BSD',
platforms='Posix; MacOS X; Windows',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: Unix',
'Topic :: System :: Shells',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
)
| marreta-sources/pyrcmd3 | setup.py | Python | bsd-3-clause | 1,533 |
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/common/switches.h"
#include <iostream>
namespace shell {
namespace switches {
const char kAotInstructionsBlob[] = "instructions-blob";
const char kAotIsolateSnapshot[] = "isolate-snapshot";
const char kAotRodataBlob[] = "rodata-blob";
const char kAotSnapshotPath[] = "aot-snapshot-path";
const char kAotVmIsolateSnapshot[] = "vm-isolate-snapshot";
const char kCacheDirPath[] = "cache-dir-path";
const char kDartFlags[] = "dart-flags";
const char kDeviceObservatoryPort[] = "observatory-port";
const char kDisableObservatory[] = "disable-observatory";
const char kEndlessTraceBuffer[] = "endless-trace-buffer";
const char kFLX[] = "flx";
const char kHelp[] = "help";
const char kMainDartFile[] = "dart-main";
const char kNonInteractive[] = "non-interactive";
const char kNoRedirectToSyslog[] = "no-redirect-to-syslog";
const char kPackages[] = "packages";
const char kStartPaused[] = "start-paused";
const char kTraceStartup[] = "trace-startup";
void PrintUsage(const std::string& executable_name) {
// clang-format off
std::cerr << "Usage: " << executable_name
<< " --" << kNonInteractive
<< " --" << kStartPaused
<< " --" << kTraceStartup
<< " --" << kFLX << "=FLX"
<< " --" << kPackages << "=PACKAGES"
<< " --" << kDeviceObservatoryPort << "=8181"
<< " [ MAIN_DART ]" << std::endl;
// clang-format on
}
} // namespace switches
} // namespace shell
| mpcomplete/engine | shell/common/switches.cc | C++ | bsd-3-clause | 1,637 |
/*
* Copyright (C) 2015 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "platform/image-decoders/FastSharedBufferReader.h"
namespace blink {
FastSharedBufferReader::FastSharedBufferReader(PassRefPtr<SharedBuffer> data)
: m_data(data)
, m_segment(0)
, m_segmentLength(0)
, m_dataPosition(0)
{
}
const char* FastSharedBufferReader::getConsecutiveData(size_t dataPosition, size_t length, char* buffer)
{
RELEASE_ASSERT(dataPosition + length <= m_data->size());
// Use the cached segment if it can serve the request.
if (dataPosition >= m_dataPosition && dataPosition + length <= m_dataPosition + m_segmentLength)
return m_segment + dataPosition - m_dataPosition;
// Return a pointer into |m_data| if the request doesn't span segments.
m_dataPosition = dataPosition;
m_segmentLength = m_data->getSomeData(m_segment, m_dataPosition);
ASSERT(m_segmentLength);
if (length <= m_segmentLength)
return m_segment;
for (char* tempBuffer = buffer; length;) {
size_t copy = std::min(length, m_segmentLength);
memcpy(tempBuffer, m_segment, copy);
m_dataPosition += copy;
length -= copy;
tempBuffer += copy;
m_segmentLength = m_data->getSomeData(m_segment, m_dataPosition);
ASSERT(m_segmentLength);
}
return buffer;
}
size_t FastSharedBufferReader::getSomeData(const char*& someData, size_t dataPosition)
{
m_segmentLength = m_data->getSomeData(m_segment, dataPosition);
someData = m_segment;
m_dataPosition = dataPosition;
ASSERT(m_segmentLength);
return m_segmentLength;
}
} // namespace blink
| sgraham/nope | third_party/WebKit/Source/platform/image-decoders/FastSharedBufferReader.cpp | C++ | bsd-3-clause | 3,162 |
#########################################################################
# Copyright (C) 2007, 2008, 2009
# Alex Clemesha <alex@clemesha.org> & Dorian Raymer <deldotdr@gmail.com>
#
# This module is part of codenode, and is distributed under the terms
# of the BSD License: http://www.opensource.org/licenses/bsd-license.php
#########################################################################
from django.conf.urls.defaults import *
from codenode.frontend.bookshelf.views import bookshelf, folders
from codenode.frontend.bookshelf.views import load_bookshelf_data, change_notebook_location
from codenode.frontend.bookshelf.views import empty_trash, new_notebook
urlpatterns = patterns('',
url(r'^$', bookshelf, name='bookshelf'),
url(r'^load$', load_bookshelf_data, name='load_bookshelf_data'),
url(r'^folders$', folders, name='folders'),
url(r'^move$', change_notebook_location, name='change_notebook_location'),
url(r'^new$', new_notebook, name='new_notebook'),
url(r'^emptytrash$', empty_trash, name='empty_trash'),
)
| ccordoba12/codenode | codenode/frontend/bookshelf/urls.py | Python | bsd-3-clause | 1,059 |
<?php
/**
* SimpleFw Framework
*
* @copyright Copyright (c) 2013 Kuldeep Kamboj
* @license New BSD License
*/
namespace SimpleFw\Core\Tools;
class Form
{
public static $instance = NULL;
public static function getInstance()
{
if(!isset(self::$instance))
{
self::$instance = new Form();
}
return self::$instance;
}
public function text($name, $value = null, $attributes = null)
{
$text = "<input type='text' name='".$name."' ";
$text = $this->applyIdAndAttributes($text, $name, $attributes);
if(!is_null($value))
{
$text .= "value='".$value."' ";
}
$text .= ' >';
return $text;
}
public function hidden($name, $value = null, $attributes = null)
{
$text = "<input type='hidden' name='".$name."' ";
$text = $this->applyIdAndAttributes($text, $name, $attributes);
if(!is_null($value))
{
$text .= "value='".$value."' ";
}
$text .= ' >';
return $text;
}
public function submit($name, $value = null, $attributes = null)
{
$text = "<input type='submit' name='".$name."' ";
$text = $this->applyIdAndAttributes($text, $name, $attributes);
if(!is_null($value))
{
$text .= "value='".$value."' ";
}
$text .= ' >';
return $text;
}
public function textArea($name, $value = null, $attributes = null)
{
$text = "<textarea name='".$name."' ";
$text = $this->applyIdAndAttributes($text, $name, $attributes);
$text .= $value."</textarea>";
if(!is_null($value))
{
$text .= "".$value."";
}
$text .= "</textarea>";
return $text;
}
public function dropdown($name, $options, $value = null, $attributes = null)
{
$text = "<select name='".$name."' ";
$text = $this->applyIdAndAttributes($text, $name, $attributes);
$text .= ' >';
if(is_array($options))
{
foreach($options as $k => $v)
{
if($value == $v)
{
$text .= "<option selected value='".$k."'>".$v."<option> ";
}
else
{
$text .= "<option value='".$k."'>".$v."<option> ";
}
}
}
if(!is_null($value))
{
$text .= "value='".$value."' ";
}
$text .= ' <select>';
return $text;
}
private function applyIdAndAttributes($text, $name, $attributes)
{
if(!array_key_exists($attributes['id']))
{
$text .= "id='".$name."' ";
}
else
{
$text .= "id='".$attributes['id']."' ";
}
if(is_array($attributes))
{
unset($attributes['id']);
foreach($attributes as $key => $val)
{
$text .= $key."='".$val."' ";
}
}
else if(is_string($attributes))
{
$text .= $attributes;
}
return $text;
}
}
?>
| kuldeep-k/CodeCompare | core/tools/Form.php | PHP | bsd-3-clause | 2,638 |
#ifndef PYTHONIC_RANDOM_RANDINT_HPP
#define PYTHONIC_RANDOM_RANDINT_HPP
#include "pythonic/include/random/randint.hpp"
#include "pythonic/utils/proxy.hpp"
#include "pythonic/random/randrange.hpp"
namespace pythonic
{
namespace random
{
long randint(long a, long b)
{
// TODO: It should be implemented with an uniform_int_distribution
return randrange(a, b + 1);
}
PROXY_IMPL(pythonic::random, randint);
}
}
#endif
| hainm/pythran | pythran/pythonic/random/randint.hpp | C++ | bsd-3-clause | 455 |
/**
* Copyright 2020 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { isNode } from '../environment.js';
/* Use the global version if we're in the browser, else load the node-fetch module. */
export const getFetch = async () => {
return isNode ? await import('node-fetch') : globalThis.fetch;
};
//# sourceMappingURL=fetch.js.map | ChromeDevTools/devtools-frontend | node_modules/puppeteer/lib/esm/puppeteer/common/fetch.js | JavaScript | bsd-3-clause | 889 |
import unittest
from django.db import connections
from wp_frontman.models import Site, Blog
from wp_frontman.wp_helpers import month_archives, year_archives
from wp_frontman.tests.utils import MultiBlogMixin
class HelpersArchivesTestCase(MultiBlogMixin, unittest.TestCase):
def setUp(self):
super(HelpersArchivesTestCase, self).setUp()
self.cursor = connections['test'].cursor()
self.cursor_mu = connections['test_multi'].cursor()
def testMonthlyArchives(self):
self.reset_blog_class()
blog = Blog(1)
self.cursor.execute("""
select distinct date_format(post_date, '%%Y %%m') as monthly_archive
from %s
where post_type='post' and post_status='publish'
order by monthly_archive desc
""" % blog.models.Post._meta.db_table)
archive_dates = [tuple(map(int, r[0].split())) for r in self.cursor.fetchall()]
archives = month_archives(blog)
self.assertEqual(archive_dates, [(a['year'], a['month']) for a in archives])
self.assertEqual(archives[0]['get_absolute_url'], '/%02i/%02i/' % archive_dates[0])
def testYearlyArchives(self):
self.reset_blog_class()
blog = Blog(1)
self.cursor.execute("""
select distinct year(post_date) as y
from %s
where post_type='post' and post_status='publish'
order by y desc
""" % blog.models.Post._meta.db_table)
archive_dates = [r[0] for r in self.cursor.fetchall()]
archives = year_archives(blog)
self.assertEqual(archive_dates, [a['year'] for a in archives])
self.assertEqual(archives[0]['get_absolute_url'], '/%02i/' % archive_dates[0])
| ludoo/wpkit | attic/ngfrontman/wp_frontman/tests/test_helpers_archives.py | Python | bsd-3-clause | 1,742 |
from behave import *
# Unique to Scenario: User cancels attempt to request new account
@when('I cancel the request account form')
def impl(context):
context.browser.find_by_css('.cancel').first.click()
| nlhkabu/connect | bdd/features/steps/request_account.py | Python | bsd-3-clause | 208 |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/manifest/manifest_icon_downloader.h"
#include <string>
#include <vector>
#include "testing/gtest/include/gtest/gtest.h"
class ManifestIconDownloaderTest : public testing::Test {
protected:
ManifestIconDownloaderTest() = default;
~ManifestIconDownloaderTest() override = default;
int FindBitmap(const int ideal_icon_size_in_px,
const int minimum_icon_size_in_px,
const std::vector<SkBitmap>& bitmaps) {
return ManifestIconDownloader::FindClosestBitmapIndex(
ideal_icon_size_in_px, minimum_icon_size_in_px, bitmaps);
}
SkBitmap CreateDummyBitmap(int width, int height) {
SkBitmap bitmap;
bitmap.allocN32Pixels(width, height);
bitmap.setImmutable();
return bitmap;
}
DISALLOW_COPY_AND_ASSIGN(ManifestIconDownloaderTest);
};
TEST_F(ManifestIconDownloaderTest, NoIcons) {
ASSERT_EQ(-1, FindBitmap(0, 0, std::vector<SkBitmap>()));
}
TEST_F(ManifestIconDownloaderTest, ExactIsChosen) {
std::vector<SkBitmap> bitmaps;
bitmaps.push_back(CreateDummyBitmap(10, 10));
ASSERT_EQ(0, FindBitmap(10, 0, bitmaps));
}
TEST_F(ManifestIconDownloaderTest, BiggerIsChosen) {
std::vector<SkBitmap> bitmaps;
bitmaps.push_back(CreateDummyBitmap(20, 20));
ASSERT_EQ(0, FindBitmap(10, 0, bitmaps));
}
TEST_F(ManifestIconDownloaderTest, SmallerBelowMinimumIsIgnored) {
std::vector<SkBitmap> bitmaps;
bitmaps.push_back(CreateDummyBitmap(10, 10));
ASSERT_EQ(-1, FindBitmap(20, 15, bitmaps));
}
TEST_F(ManifestIconDownloaderTest, SmallerAboveMinimumIsChosen) {
std::vector<SkBitmap> bitmaps;
bitmaps.push_back(CreateDummyBitmap(15, 15));
ASSERT_EQ(0, FindBitmap(20, 15, bitmaps));
}
TEST_F(ManifestIconDownloaderTest, ExactIsPreferredOverBigger) {
std::vector<SkBitmap> bitmaps;
bitmaps.push_back(CreateDummyBitmap(20, 20));
bitmaps.push_back(CreateDummyBitmap(10, 10));
ASSERT_EQ(1, FindBitmap(10, 0, bitmaps));
}
TEST_F(ManifestIconDownloaderTest, ExactIsPreferredOverSmaller) {
std::vector<SkBitmap> bitmaps;
bitmaps.push_back(CreateDummyBitmap(20, 20));
bitmaps.push_back(CreateDummyBitmap(10, 10));
ASSERT_EQ(0, FindBitmap(20, 0, bitmaps));
}
TEST_F(ManifestIconDownloaderTest, BiggerIsPreferredOverCloserSmaller) {
std::vector<SkBitmap> bitmaps;
bitmaps.push_back(CreateDummyBitmap(20, 20));
bitmaps.push_back(CreateDummyBitmap(10, 10));
ASSERT_EQ(0, FindBitmap(11, 0, bitmaps));
}
TEST_F(ManifestIconDownloaderTest, ClosestToExactIsChosen) {
std::vector<SkBitmap> bitmaps;
bitmaps.push_back(CreateDummyBitmap(25, 25));
bitmaps.push_back(CreateDummyBitmap(20, 20));
ASSERT_EQ(1, FindBitmap(10, 0, bitmaps));
}
TEST_F(ManifestIconDownloaderTest, MixedReturnsBiggestClosest) {
std::vector<SkBitmap> bitmaps;
bitmaps.push_back(CreateDummyBitmap(10, 10));
bitmaps.push_back(CreateDummyBitmap(8, 8));
bitmaps.push_back(CreateDummyBitmap(6, 6));
ASSERT_EQ(0, FindBitmap(9, 0, bitmaps));
}
TEST_F(ManifestIconDownloaderTest, MixedCanReturnMiddle) {
std::vector<SkBitmap> bitmaps;
bitmaps.push_back(CreateDummyBitmap(10, 10));
bitmaps.push_back(CreateDummyBitmap(8, 8));
bitmaps.push_back(CreateDummyBitmap(6, 6));
ASSERT_EQ(1, FindBitmap(7, 0, bitmaps));
}
TEST_F(ManifestIconDownloaderTest, SquareIsPickedOverNonSquare) {
std::vector<SkBitmap> bitmaps;
bitmaps.push_back(CreateDummyBitmap(5, 5));
bitmaps.push_back(CreateDummyBitmap(10, 15));
ASSERT_EQ(0, FindBitmap(15, 5, bitmaps));
ASSERT_EQ(0, FindBitmap(10, 5, bitmaps));
}
TEST_F(ManifestIconDownloaderTest, MostSquareNonSquareIsPicked) {
std::vector<SkBitmap> bitmaps;
bitmaps.push_back(CreateDummyBitmap(25, 35));
bitmaps.push_back(CreateDummyBitmap(10, 11));
ASSERT_EQ(1, FindBitmap(25, 0, bitmaps));
ASSERT_EQ(1, FindBitmap(35, 0, bitmaps));
}
TEST_F(ManifestIconDownloaderTest, NonSquareBelowMinimumIsNotPicked) {
std::vector<SkBitmap> bitmaps;
bitmaps.push_back(CreateDummyBitmap(10, 15));
bitmaps.push_back(CreateDummyBitmap(15, 10));
ASSERT_EQ(-1, FindBitmap(15, 11, bitmaps));
}
| Workday/OpenFrame | chrome/browser/manifest/manifest_icon_downloader_unittest.cc | C++ | bsd-3-clause | 4,221 |
<?php
/**
* aheadWorks Co.
*
* NOTICE OF LICENSE
*
* This source file is subject to the EULA
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://ecommerce.aheadworks.com/LICENSE-L.txt
*
* @category AW
* @package AW_Blog
* @copyright Copyright (c) 2009-2010 aheadWorks Co. (http://www.aheadworks.com)
* @license http://ecommerce.aheadworks.com/LICENSE-L.txt
*/
class AW_Blog_Block_Post extends AW_Blog_Block_Abstract
{
public function getPost()
{
if (!$this->hasData('post')) {
if ($this->getPostId()) {
$post = Mage::getModel('blog/post')->load($this->getPostId());
} else {
$post = Mage::getSingleton('blog/post');
}
$category = Mage::getSingleton('blog/cat')->load($this->getRequest()->getParam(self::$_catUriParam), "identifier");
if ($category->getIdentifier()) {
$post->setAddress($this->getBlogUrl(null, array(self::$_catUriParam => $category->getIdentifier(), self::$_postUriParam => $post->getIdentifier())));
} else {
$post->setAddress($this->getBlogUrl($post->getIdentifier()));
}
$this->_prepareData($post)->_prepareDates($post);
$this->setData('post', $post);
}
return $this->getData('post');
}
public function getBookmarkHtml($post)
{
if ($this->_helper()->isBookmarksPost()) {
return $this->setTemplate('aw_blog/bookmark.phtml')->setPost($post)->renderView();
}
}
public function getComment()
{
if (!$this->hasData('commentCollection')) {
$collection = Mage::getModel('blog/comment')
->getCollection()
->addPostFilter($this->getPost()->getPostId())
->setOrder('created_time', 'DESC')
->addApproveFilter(2);
$collection->setPageSize((int) Mage::helper('blog')->commentsPerPage());
$this->setData('commentCollection', $collection);
}
return $this->getData('commentCollection');
}
public function getCommentsEnabled()
{
return Mage::getStoreConfig('blog/comments/enabled');
}
public function getLoginRequired()
{
return Mage::getStoreConfig('blog/comments/login');
}
public function getFormAction()
{
return $this->getUrl('*/*/*');
}
public function getFormData()
{
return $this->getRequest();
}
protected function _prepareLayout()
{
$this->_prepareCrumbs()->_prepareHead();
}
protected function _beforeToHtml()
{
Mage::helper('blog/toolbar')->create($this, array(
'orders' => array('created_time' => $this->__('Created At'), 'email' => $this->__('Added By')),
'default_order' => 'created_time',
'dir' => 'desc',
'limits' => self::$_helper->commentsPerPage(),
'method' => 'getComment'
)
);
return $this;
}
protected function _prepareCrumbs()
{
$breadcrumbs = $this->getCrumbs();
if ($breadcrumbs) {
$helper = $this->_helper();
$breadcrumbs->addCrumb('blog', array(
'label' => $helper->getTitle(),
'title' => $this->__('Return to %s', $helper->getTitle()),
'link' => Mage::getUrl($helper->getRoute()))
);
$title = trim($this->getCategory()->getTitle());
if ($title) {
$breadcrumbs->addCrumb('cat', array(
'label' => $title,
'title' => $this->__('Return to %s', $title),
'link' => Mage::getUrl($helper->getRoute(), array('cat' => $this->getCategory()->getIdentifier())))
);
}
$breadcrumbs->addCrumb('blog_page', array(
'label' => htmlspecialchars_decode($this->getPost()->getTitle()))
);
}
return $this;
}
protected function getCategory()
{
if (!$this->hasData('postCategory')) {
$this->setData('postCategory', Mage::getSingleton('blog/cat')->load($this->getRequest()->getParam('cat'), "identifier"));
}
return $this->getData('postCategory');
}
protected function _prepareHead()
{
parent::_prepareMetaData($this->getPost());
return $this;
}
public function setCommentDetails($name, $email, $comment)
{
return $this->setData('commentName', $name)->setData('commentEmail', $email)->setData('commentComment', $comment);
}
public function getCommentText()
{
$blogPostModelFromSession = Mage::getSingleton('customer/session')->getBlogPostModel();
if ($blogPostModelFromSession) {
return $blogPostModelFromSession->getComment();
}
if (!empty($this->_data['commentComment'])) {
return $this->_data['commentComment'];
}
return;
}
public function getCommentEmail()
{
$blogPostModelFromSession = Mage::getSingleton('customer/session')->getBlogPostModel();
if ($blogPostModelFromSession)
return $blogPostModelFromSession->getEmail();
if (!empty($this->_data['commentEmail'])) {
return $this->_data['commentEmail'];
} elseif ($customer = Mage::getSingleton('customer/session')->getCustomer()) {
return $customer->getEmail();
}
return;
}
public function getCommentName()
{
$blogPostModelFromSession = Mage::getSingleton('customer/session')->getBlogPostModel();
$name = null;
if ($blogPostModelFromSession) {
$name = $blogPostModelFromSession->getUser();
}
if (!empty($this->_data['commentName'])) {
$name = $this->_data['commentName'];
} elseif ($customer = Mage::getSingleton('customer/session')->getCustomer()) {
$name = $customer->getName();
}
return trim($name);
}
}
| 5452/durex | includes/src/AW_Blog_Block_Post.php | PHP | bsd-3-clause | 6,215 |
require 'spree/api'
| ambertch/stylestalk-spree | api/lib/spree_api.rb | Ruby | bsd-3-clause | 20 |