code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// La información general de un ensamblado se controla mediante el siguiente
// conjunto de atributos. Cambie estos valores de atributo para modificar la información
// asociada con un ensamblado.
[assembly: AssemblyTitle("MECS.Core.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MECS.Core.Tests")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Si establece ComVisible en false, los tipos de este ensamblado no estarán visibles
// para los componentes COM. Si necesita obtener acceso a un tipo de este ensamblado desde
// COM, establezca el atributo ComVisible en true en este tipo.
[assembly: ComVisible(false)]
// El siguiente GUID sirve como id. de typelib si este proyecto se expone a COM.
[assembly: Guid("3bac78d6-7021-41b0-bca8-6e1bd77c5f7d")]
// La información de versión de un ensamblado consta de los cuatro valores siguientes:
//
// Versión principal
// Versión secundaria
// Número de compilación
// Revisión
//
// Puede especificar todos los valores o usar los valores predeterminados de número de compilación y de revisión
// mediante el carácter '*', como se muestra a continuación:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
Mr-Alicates/MECS
|
MECS/MECS.Core.Tests/Properties/AssemblyInfo.cs
|
C#
|
gpl-3.0
| 1,541
|
#!/bin/bash
function force_copy {
mkdir -p $(dirname $2)
if [ -f $2 ] && [ $1 != $2 ]; then
echo "Removing file"
rm -f $2
fi
cp $1 $2
}
if [ -d `dirname $0`/build/cluster/modules/ext ]; then
force_copy `dirname $0`/lib/ovation.jar `dirname $0`/build/cluster/modules/ext/ovation.jar
fi
force_copy `dirname $0`/lib/ovation.jar `dirname $0`/Browser/release/modules/ext/ovation.jar
force_copy `dirname $0`/lib/ovation.jar `dirname $0`/DBConnectionProvider/release/modules/ext/ovation.jar
force_copy `dirname $0`/lib/ovation.jar `dirname $0`/OvationAPI/release/modules/ext/ovation.jar
force_copy `dirname $0`/lib/test-manager.jar `dirname $0`/TestManager/release/modules/ext/test-manager.jar
force_copy `dirname $0`/lib/interfaces.jar `dirname $0`/GlobalInterfaceLibrary/release/modules/ext/interfaces.jar
|
physion/ovation-ui
|
ovation-ui/redistribute-lib-jars.sh
|
Shell
|
gpl-3.0
| 826
|
/*
* This class is an auto-generated source file for a HAPI
* HL7 v2.x standard structure class.
*
* For more information, visit: http://hl7api.sourceforge.net/
*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (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.mozilla.org/MPL/
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the
* specific language governing rights and limitations under the License.
*
* The Original Code is "[file_name]". Description:
* "[one_line_description]"
*
* The Initial Developer of the Original Code is University Health Network. Copyright (C)
* 2012. All Rights Reserved.
*
* Contributor(s): ______________________________________.
*
* Alternatively, the contents of this file may be used under the terms of the
* GNU General Public License (the "GPL"), in which case the provisions of the GPL are
* applicable instead of those above. If you wish to allow use of your version of this
* file only under the terms of the GPL and not to allow others to use your version
* of this file under the MPL, indicate your decision by deleting the provisions above
* and replace them with the notice and other provisions required by the GPL License.
* If you do not delete the provisions above, a recipient may use your version of
* this file under either the MPL or the GPL.
*
*/
package org.petermac.hl7.model.v251.group;
import org.petermac.hl7.model.v251.segment.*;
import ca.uhn.hl7v2.HL7Exception;
import ca.uhn.hl7v2.parser.ModelClassFactory;
import ca.uhn.hl7v2.model.*;
/**
* <p>Represents a RGV_O15_PATIENT group structure (a Group object).
* A Group is an ordered collection of message segments that can repeat together or be optionally in/excluded together.
* This Group contains the following elements:
* </p>
* <ul>
* <li>1: PID (Patient Identification) <b> </b></li>
* <li>2: NTE (Notes and Comments) <b>optional repeating </b></li>
* <li>3: AL1 (Patient Allergy Information) <b>optional repeating </b></li>
* <li>4: RGV_O15_PATIENT_VISIT (a Group object) <b>optional </b></li>
* </ul>
*/
//@SuppressWarnings("unused")
public class RGV_O15_PATIENT extends AbstractGroup {
/**
* Creates a new RGV_O15_PATIENT group
*/
public RGV_O15_PATIENT(Group parent, ModelClassFactory factory) {
super(parent, factory);
init(factory);
}
private void init(ModelClassFactory factory) {
try {
this.add(PID.class, true, false, false);
this.add(NTE.class, false, true, false);
this.add(AL1.class, false, true, false);
this.add(RGV_O15_PATIENT_VISIT.class, false, false, false);
} catch(HL7Exception e) {
log.error("Unexpected error creating RGV_O15_PATIENT - this is probably a bug in the source code generator.", e);
}
}
/**
* Returns "2.5.1"
*/
public String getVersion() {
return "2.5.1";
}
/**
* Returns
* PID (Patient Identification) - creates it if necessary
*/
public PID getPID() {
PID retVal = getTyped("PID", PID.class);
return retVal;
}
/**
* Returns
* the first repetition of
* NTE (Notes and Comments) - creates it if necessary
*/
public NTE getNTE() {
NTE retVal = getTyped("NTE", NTE.class);
return retVal;
}
/**
* Returns a specific repetition of
* NTE (Notes and Comments) - creates it if necessary
*
* @param rep The repetition index (0-indexed, i.e. the first repetition is at index 0)
* @throws HL7Exception if the repetition requested is more than one
* greater than the number of existing repetitions.
*/
public NTE getNTE(int rep) {
NTE retVal = getTyped("NTE", rep, NTE.class);
return retVal;
}
/**
* Returns the number of existing repetitions of NTE
*/
public int getNTEReps() {
return getReps("NTE");
}
/**
* <p>
* Returns a non-modifiable List containing all current existing repetitions of NTE.
* <p>
* <p>
* Note that unlike {@link #getNTE()}, this method will not create any reps
* if none are already present, so an empty list may be returned.
* </p>
*/
public java.util.List<NTE> getNTEAll() throws HL7Exception {
return getAllAsList("NTE", NTE.class);
}
/**
* Inserts a specific repetition of NTE (Notes and Comments)
* @see AbstractGroup#insertRepetition(Structure, int)
*/
public void insertNTE(NTE structure, int rep) throws HL7Exception {
super.insertRepetition("NTE", structure, rep);
}
/**
* Inserts a specific repetition of NTE (Notes and Comments)
* @see AbstractGroup#insertRepetition(Structure, int)
*/
public NTE insertNTE(int rep) throws HL7Exception {
return (NTE)super.insertRepetition("NTE", rep);
}
/**
* Removes a specific repetition of NTE (Notes and Comments)
* @see AbstractGroup#removeRepetition(String, int)
*/
public NTE removeNTE(int rep) throws HL7Exception {
return (NTE)super.removeRepetition("NTE", rep);
}
/**
* Returns
* the first repetition of
* AL1 (Patient Allergy Information) - creates it if necessary
*/
public AL1 getAL1() {
AL1 retVal = getTyped("AL1", AL1.class);
return retVal;
}
/**
* Returns a specific repetition of
* AL1 (Patient Allergy Information) - creates it if necessary
*
* @param rep The repetition index (0-indexed, i.e. the first repetition is at index 0)
* @throws HL7Exception if the repetition requested is more than one
* greater than the number of existing repetitions.
*/
public AL1 getAL1(int rep) {
AL1 retVal = getTyped("AL1", rep, AL1.class);
return retVal;
}
/**
* Returns the number of existing repetitions of AL1
*/
public int getAL1Reps() {
return getReps("AL1");
}
/**
* <p>
* Returns a non-modifiable List containing all current existing repetitions of AL1.
* <p>
* <p>
* Note that unlike {@link #getAL1()}, this method will not create any reps
* if none are already present, so an empty list may be returned.
* </p>
*/
public java.util.List<AL1> getAL1All() throws HL7Exception {
return getAllAsList("AL1", AL1.class);
}
/**
* Inserts a specific repetition of AL1 (Patient Allergy Information)
* @see AbstractGroup#insertRepetition(Structure, int)
*/
public void insertAL1(AL1 structure, int rep) throws HL7Exception {
super.insertRepetition("AL1", structure, rep);
}
/**
* Inserts a specific repetition of AL1 (Patient Allergy Information)
* @see AbstractGroup#insertRepetition(Structure, int)
*/
public AL1 insertAL1(int rep) throws HL7Exception {
return (AL1)super.insertRepetition("AL1", rep);
}
/**
* Removes a specific repetition of AL1 (Patient Allergy Information)
* @see AbstractGroup#removeRepetition(String, int)
*/
public AL1 removeAL1(int rep) throws HL7Exception {
return (AL1)super.removeRepetition("AL1", rep);
}
/**
* Returns
* PATIENT_VISIT (a Group object) - creates it if necessary
*/
public RGV_O15_PATIENT_VISIT getPATIENT_VISIT() {
RGV_O15_PATIENT_VISIT retVal = getTyped("PATIENT_VISIT", RGV_O15_PATIENT_VISIT.class);
return retVal;
}
}
|
PapenfussLab/PathOS
|
Tools/Hl7Tools/src/main/java/org/petermac/hl7/model/v251/group/RGV_O15_PATIENT.java
|
Java
|
gpl-3.0
| 8,244
|
// FoldWatcher
// ---------------------
// Coded by Dr.K@meleon <drkameleon@hotmail.com>
//
// homepage : http://kameleon-nest.blogspot.com
// http://sourceforge.net/projects/foldwatcher/
// ============================
// Filename : preferences.cpp
// Last Update : 17/05/2008
//
// -----------------------------------------------------------------
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright (C) 2008 by Dr.K@meleon
// ========================================================
#include "Messages.h"
#include "preferences.h"
preferences::preferences(int rel, QWidget * parent, Qt::WFlags f) : QDialog(parent, f)
{
setupUi(this);
reloadTime = rel;
reloadSlider->setValue(rel);
label->setText(QString::number(rel)+" mins");
connect(okButton, SIGNAL(clicked()), this, SLOT(checkValue()));
connect(cancelButton, SIGNAL(clicked()), this, SLOT(hide()));
connect(reloadSlider, SIGNAL(valueChanged(int)), this, SLOT(harmonizeValues()));
}
void preferences::checkValue()
{
reloadTime = reloadSlider->value();
hide();
}
void preferences::harmonizeValues()
{
label->setText(QString::number(reloadSlider->value())+" mins");
}
|
drkameleon/FoldWatcher
|
src/preferences.cpp
|
C++
|
gpl-3.0
| 1,771
|
/*
* Lumeer: Modern Data Definition and Processing Platform
*
* Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import {COLOR_PRIMARY} from '../../../../core/constants';
import {BlocklyUtils, MasterBlockType} from '../blockly-utils';
import {LinkType} from '../../../../core/store/link-types/link.type';
import {LinkDocumentsNoReturnBlocklyComponent} from './link-documents-no-return-blockly-component';
import {isNotNullOrUndefined} from '../../../utils/common.utils';
declare var Blockly: any;
export class LinkDocumentsReturnBlocklyComponent extends LinkDocumentsNoReturnBlocklyComponent {
public constructor(public blocklyUtils: BlocklyUtils, protected linkTypes: LinkType[]) {
super(blocklyUtils, linkTypes);
}
public getVisibility(): MasterBlockType[] {
return [MasterBlockType.Rule, MasterBlockType.Link];
}
public registerBlock(workspace: any) {
const this_ = this;
Blockly.Blocks[BlocklyUtils.LINK_DOCUMENTS_RETURN] = {
init: function () {
this.jsonInit({
type: BlocklyUtils.LINK_DOCUMENTS_RETURN,
message0: '%{BKY_BLOCK_LINK_DOCUMENTS_RETURN}', // link records via %1 %2 %3
args0: [
{
type: 'field_dropdown',
name: 'LINKTYPE',
options: this_.linkTypeOptions,
},
{
type: 'input_value',
name: 'DOCUMENT1',
},
{
type: 'input_value',
name: 'DOCUMENT2',
},
],
output: '',
colour: COLOR_PRIMARY,
tooltip: this_.tooltip,
helpUrl: '',
});
},
};
Blockly.JavaScript[BlocklyUtils.LINK_DOCUMENTS_RETURN] = function (block) {
const dropdown_linktype = block.getFieldValue('LINKTYPE') || null;
const value_document1 =
Blockly.JavaScript.valueToCode(block, 'DOCUMENT1', Blockly.JavaScript.ORDER_ATOMIC) || null;
const value_document2 =
Blockly.JavaScript.valueToCode(block, 'DOCUMENT2', Blockly.JavaScript.ORDER_ATOMIC) || null;
const code =
this_.blocklyUtils.getLumeerVariable() +
'.linkDocuments(' +
value_document1 +
', ' +
value_document2 +
", '" +
dropdown_linktype +
"')";
return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL];
};
}
public getLinkVariablesXml(workspace: any): string {
return '<xml><block type="' + BlocklyUtils.LINK_DOCUMENTS_RETURN + '"></block></xml>';
}
public onWorkspaceChange(workspace, changeEvent) {
super.onWorkspaceChange(workspace, changeEvent);
if (
changeEvent instanceof Blockly.Events.Create ||
changeEvent instanceof Blockly.Events.Change ||
changeEvent instanceof Blockly.Events.Move
) {
const block = workspace.getBlockById(changeEvent.blockId);
if (isNotNullOrUndefined(block) && block.type === BlocklyUtils.LINK_DOCUMENTS_RETURN) {
const linkTypeId = block.getField('LINKTYPE').value_;
block.setOutput(true, linkTypeId + BlocklyUtils.LINK_VAR_SUFFIX);
this.blocklyUtils.checkVariablesType(changeEvent, workspace);
}
}
}
}
|
Lumeer/web-ui
|
src/app/shared/blockly/blockly-editor/blocks/link-documents-return-blockly-component.ts
|
TypeScript
|
gpl-3.0
| 3,865
|
/* -*- c++ -*- */
/*
* Copyright 2011-2013,2015 Free Software Foundation, Inc.
*
* This file is part of GNU Radio
*
* SPDX-License-Identifier: GPL-3.0-or-later
*
*/
#ifndef INCLUDED_QTGUI_TIME_SINK_C_IMPL_H
#define INCLUDED_QTGUI_TIME_SINK_C_IMPL_H
#include <gnuradio/qtgui/time_sink_c.h>
#include <gnuradio/high_res_timer.h>
#include <gnuradio/qtgui/timedisplayform.h>
namespace gr {
namespace qtgui {
class QTGUI_API time_sink_c_impl : public time_sink_c
{
private:
void initialize();
int d_size, d_buffer_size;
double d_samp_rate;
const std::string d_name;
unsigned int d_nconnections;
const pmt::pmt_t d_tag_key;
int d_index, d_start, d_end;
std::vector<volk::vector<gr_complex>> d_cbuffers;
std::vector<volk::vector<double>> d_buffers;
std::vector<std::vector<gr::tag_t>> d_tags;
// Required now for Qt; argc must be greater than 0 and argv
// must have at least one valid character. Must be valid through
// life of the qApplication:
// http://harmattan-dev.nokia.com/docs/library/html/qt4/qapplication.html
char d_zero;
int d_argc = 1;
char* d_argv = &d_zero;
QWidget* d_parent;
TimeDisplayForm* d_main_gui = nullptr;
gr::high_res_timer_type d_update_time;
gr::high_res_timer_type d_last_time;
// Members used for triggering scope
trigger_mode d_trigger_mode;
trigger_slope d_trigger_slope;
float d_trigger_level;
int d_trigger_channel;
int d_trigger_delay;
pmt::pmt_t d_trigger_tag_key;
bool d_triggered;
int d_trigger_count;
void _reset();
void _npoints_resize();
void _adjust_tags(int adj);
void _gui_update_trigger();
void _test_trigger_tags(int nitems);
void _test_trigger_norm(int nitems, gr_vector_const_void_star inputs);
bool _test_trigger_slope(const gr_complex* in) const;
// Handles message input port for displaying PDU samples.
void handle_pdus(pmt::pmt_t msg);
public:
time_sink_c_impl(int size,
double samp_rate,
const std::string& name,
unsigned int nconnections,
QWidget* parent = NULL);
~time_sink_c_impl() override;
bool check_topology(int ninputs, int noutputs) override;
void exec_() override;
QWidget* qwidget() override;
#ifdef ENABLE_PYTHON
PyObject* pyqwidget() override;
#else
void* pyqwidget();
#endif
void set_y_axis(double min, double max) override;
void set_y_label(const std::string& label, const std::string& unit = "") override;
void set_update_time(double t) override;
void set_title(const std::string& title) override;
void set_line_label(unsigned int which, const std::string& label) override;
void set_line_color(unsigned int which, const std::string& color) override;
void set_line_width(unsigned int which, int width) override;
void set_line_style(unsigned int which, int style) override;
void set_line_marker(unsigned int which, int marker) override;
void set_nsamps(const int size) override;
void set_samp_rate(const double samp_rate) override;
void set_line_alpha(unsigned int which, double alpha) override;
void set_trigger_mode(trigger_mode mode,
trigger_slope slope,
float level,
float delay,
int channel,
const std::string& tag_key = "") override;
std::string title() override;
std::string line_label(unsigned int which) override;
std::string line_color(unsigned int which) override;
int line_width(unsigned int which) override;
int line_style(unsigned int which) override;
int line_marker(unsigned int which) override;
double line_alpha(unsigned int which) override;
void set_size(int width, int height) override;
int nsamps() const override;
void enable_menu(bool en) override;
void enable_grid(bool en) override;
void enable_autoscale(bool en) override;
void enable_stem_plot(bool en) override;
void enable_semilogx(bool en) override;
void enable_semilogy(bool en) override;
void enable_control_panel(bool en) override;
void enable_tags(unsigned int which, bool en) override;
void enable_tags(bool en) override;
void enable_axis_labels(bool en) override;
void disable_legend() override;
void reset() override;
int work(int noutput_items,
gr_vector_const_void_star& input_items,
gr_vector_void_star& output_items) override;
};
} /* namespace qtgui */
} /* namespace gr */
#endif /* INCLUDED_QTGUI_TIME_SINK_C_IMPL_H */
|
mrjacobagilbert/gnuradio
|
gr-qtgui/lib/time_sink_c_impl.h
|
C
|
gpl-3.0
| 4,672
|
/*
* Copyright, ViewTouch Inc., 1995, 1996, 1997, 1998
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* report_zone.cc - revision 139 (10/7/98)
* Implementation of report information display zone
*/
#include <cstring>
#include "image_data.hh"
#include "report_zone.hh"
#include "terminal.hh"
#include "check.hh"
#include "drawer.hh"
#include "sales.hh"
#include "printer.hh"
#include "dialog_zone.hh"
#include "employee.hh"
#include "labor.hh"
#include "settings.hh"
#include "system.hh"
#include "archive.hh"
#include "manager.hh"
#include "labels.hh"
#ifdef DMALLOC
#include <dmalloc.h>
#endif
/**** ReportZone Class ****/
// Constructor
ReportZone::ReportZone()
{
min_size_x = 10;
min_size_y = 5;
report_type = REPORT_SERVER;
report = NULL;
temp_report = NULL;
lines_shown = 0;
page = 0;
columns = 1;
print = RP_PRINT_LOCAL;
printer_dest = RP_PRINT_LOCAL;
period_view = 0;
period_fiscal = NULL;
spacing = 1;
check_disp_num = 0;
video_target = PRINTER_DEFAULT;
rzstate = 0;
printing_to_printer = 0;
}
// Destructor
ReportZone::~ReportZone()
{
if (report)
delete report;
if (temp_report)
delete temp_report;
}
// Member Functions
RenderResult ReportZone::Render(Terminal *term, int update_flag)
{
FnTrace("ReportZone::Render()");
Employee *e = term->user;
System *sys = term->system_data;
Settings *s = &(sys->settings);
Report *r = temp_report;
// allow no user signin for kitchen display
if (e == NULL && report_type != REPORT_CHECK)
return RENDER_OKAY;
if (r)
{
update_flag = 0;
if (r->is_complete)
{
if (report)
delete report;
report = r;
temp_report = NULL;
if (printing_to_printer)
{
Print(term, printer_dest);
printing_to_printer = 0;
if (report != NULL)
delete report;
report = NULL;
temp_report = new Report();
sys->RoyaltyReport(term, day_start, day_end, term->archive, temp_report, this);
return RENDER_OKAY;
}
}
}
if (update_flag)
{
if (report)
{
delete report;
report = NULL;
page = 0;
}
if (update_flag == RENDER_NEW)
{ // set relevant variables to default values
// printf("ReportZone::Render() update_flag == RENDER_NEW\n");
day_start.Clear();
day_end.Clear();
ref = SystemTime;
period_view = s->default_report_period;
page = 0;
if (term->server == NULL && s->drawer_mode == DRAWER_SERVER)
term->server = e;
// printf("ReportZone::Render() drawer_mode == DRAWER_SERVER\n");
// period_fiscal = &s->sales_start;
// period_view = SP_DAY;
period_fiscal = NULL;
period_view = s->default_report_period;
if (report_type == REPORT_SALES)
{
// printf("ReportZone::Render() repoort_type == REPORT_SALES\n");
period_view = SP_DAY;
// period_view = s->sales_period;
period_fiscal = &s->sales_start;
term->server = NULL; // sales report defaults to all users
}
else if (report_type == REPORT_BALANCE &&
s->report_start_midnight == 0)
{
// printf("ReportZone::Render() report_type == REPORT_BALANCE\n");
period_view = SP_DAY;
period_fiscal = &s->sales_start;
}
else if (report_type == REPORT_SERVERLABOR)
{
// printf("ReportZone::Render() report_type == REPORT_SERVERLABOR\n");
period_view = s->labor_period;
period_fiscal = &s->labor_start;
}
else if (report_type == REPORT_DEPOSIT &&
s->report_start_midnight == 0)
{
// printf("ReportZone::Render() report_type == REPORT_DEPOSIT\n");
period_view = s->default_report_period;
period_fiscal = &s->sales_start;
}
else if (report_type == REPORT_ROYALTY)
{
// printf("ReportZone::Render() report_type == REPORT_ROYALTY\n");
period_view = SP_MONTH;
period_fiscal = NULL;
}
else if (report_type == REPORT_AUDITING)
{
// printf("ReportZone::Render() report_type == REPORT_AUDITING\n");
period_view = SP_DAY;
period_fiscal = NULL;
}
}
Archive *a = term->archive;
if (a)
{
day_start = a->start_time;
day_end = a->end_time;
}
else
{
if (sys->ArchiveListEnd())
day_start = sys->ArchiveListEnd()->end_time;
else
day_start.Clear();
day_end = SystemTime;
}
// calculate the start and end times
if (period_view != SP_NONE)
s->SetPeriod(ref, day_start, day_end, period_view, period_fiscal);
TimeInfo user_start;
TimeInfo user_end;
user_start = day_start;
user_end = day_end;
WorkEntry *work_entry = sys->labor_db.CurrentWorkEntry(term->server);
if (work_entry)
{
user_start = work_entry->start;
user_end = SystemTime;
}
Drawer *drawer_list = sys->DrawerList();
Check *check_list = sys->CheckList();
if (a)
{
if (a->loaded == 0)
a->LoadPacked(s);
check_list = a->CheckList();
drawer_list = a->DrawerList();
}
Drawer *d = NULL;
if (a == NULL)
{
if (term->server)
d = drawer_list->FindByOwner(term->server, DRAWER_OPEN);
else
d = term->FindDrawer();
}
temp_report = new Report;
switch (report_type)
{
case REPORT_DRAWER:
if (term->server == NULL)
sys->DrawerSummaryReport(term, drawer_list, check_list, temp_report);
else if (d)
d->MakeReport(term, check_list, temp_report);
break;
case REPORT_CLOSEDCHECK:
sys->ClosedCheckReport(term, day_start, day_end, term->server, temp_report);
break;
case REPORT_SERVERLABOR:
sys->labor_db.ServerLaborReport(term, e, day_start, day_end, temp_report);
break;
case REPORT_CHECK:
DisplayCheckReport(term, temp_report);
break;
case REPORT_SERVER:
sys->ServerReport(term, day_start, day_end, term->server, temp_report);
break;
case REPORT_SALES:
sys->SalesMixReport(term, day_start, day_end, term->server, temp_report);
break;
case REPORT_BALANCE:
if (period_view != SP_DAY)
sys->BalanceReport(term, day_start, day_end, temp_report);
else
sys->ShiftBalanceReport(term, ref, temp_report);
break;
case REPORT_DEPOSIT:
if (period_view != SP_NONE)
sys->DepositReport(term, day_start, day_end, NULL, temp_report);
else
sys->DepositReport(term, day_start, day_end, term->archive, temp_report);
break;
case REPORT_COMPEXCEPTION:
sys->ItemExceptionReport(term, day_start, day_end, 1, term->server, temp_report);
break;
case REPORT_VOIDEXCEPTION:
sys->ItemExceptionReport(term, day_start, day_end, 2, term->server, temp_report);
break;
case REPORT_TABLEEXCEPTION:
sys->TableExceptionReport(term, day_start, day_end, term->server, temp_report);
break;
case REPORT_REBUILDEXCEPTION:
sys->RebuildExceptionReport(term, day_start, day_end, term->server, temp_report);
break;
case REPORT_CUSTOMERDETAIL:
sys->CustomerDetailReport(term, e, temp_report);
break;
case REPORT_EXPENSES:
sys->ExpenseReport(term, day_start, day_end, NULL, temp_report, this);
break;
case REPORT_ROYALTY:
sys->RoyaltyReport(term, day_start, day_end, term->archive, temp_report, this);
break;
case REPORT_AUDITING:
sys->AuditingReport(term, day_start, day_end, term->archive, temp_report, this);
break;
case REPORT_CREDITCARD:
sys->CreditCardReport(term, day_start, day_end, term->archive, temp_report, this);
break;
}
//ref = day_start;
if (temp_report && temp_report->is_complete)
{
report = temp_report;
temp_report = NULL;
}
}
LayoutZone::Render(term, update_flag);
int hs = 0;
if (name.size() > 0)
{
hs = 1;
TextC(term, 0, name.Value(), color[0]);
}
if (report)
{
report->Render(term, this, hs, 0, page, print, (Flt) spacing);
page = report->page;
}
else
{
TextC(term, 4, "Working...", color[0]);
}
return RENDER_OKAY;
}
int ReportZone::State(Terminal *term)
{
FnTrace("ReportZone::State()");
return rzstate;
}
RenderResult ReportZone::DisplayCheckReport(Terminal *term, Report *disp_report)
{
FnTrace("ReportZone::DisplayCheckReport()");
Settings *settings = term->GetSettings();
rzstate = 0;
if (check_disp_num)
{
// This is only for the Kitchen Video reports.
Check *disp_check = GetDisplayCheck(term);
if (disp_check != NULL)
{
if (disp_check->check_state & ORDER_MADE)
rzstate = 1;
else if (disp_check->check_state & ORDER_SENT && disp_check->made_time.IsSet())
rzstate = 2;
int display_flags = CHECK_DISPLAY_ALL;
if (video_target != PRINTER_DEFAULT)
display_flags =~ CHECK_DISPLAY_CASH; //Remove cash info
term->curr_font_id = font;
ColumnSpacing(term, 1); // just to set font_width
term->curr_font_width = font_width;
if (settings->kv_print_method == KV_PRINT_UNMATCHED)
disp_check->MakeReport(term, disp_report, display_flags, video_target, this);
else
disp_check->PrintWorkOrder(term, disp_report, video_target, 0, this);
term->curr_font_id = -1;
term->curr_font_width = -1;
}
else
{
disp_report->update_flag = UPDATE_CHECKS;
disp_report->TextC(term->Translate("No Check Selected"));
}
}
else if (term->check)
{
// This is the non-Kitchen Video report when we have a check.
term->check->MakeReport(term, disp_report, CHECK_DISPLAY_ALL, video_target);
}
else
{
disp_report->update_flag = UPDATE_CHECKS;
disp_report->TextC(term->Translate("No Check Selected"));
}
return RENDER_OKAY;
}
/****
* IsKitchenCheck: For Kitchen Video, we only want to display checks that have
* been closed, but have not yet been served.
****/
int ReportZone::IsKitchenCheck(Terminal *term, Check *check)
{
FnTrace("ReportZone::IsKitchenCheck()");
int retval = 1;
// I don't like huge conditionals ("if (a && b || (c || d)...)"),
// so I'm going to break it out into an if-elsif block instead.
if (check == NULL)
retval = 0;
else if (check->Status() == CHECK_VOIDED)
retval = 0;
else if (check->check_state < ORDER_FINAL || check->check_state >= ORDER_SERVED)
retval = 0;
else if (!ShowCheck(term, check))
retval = 0;
return retval;
}
/****
* ShowCheck: Process through the subchecks and orders. If there are no items
* to be displayed on this report_zone's video target, return 0, otherwise
* return 1. This is used to determine whether a check should be sent to the
* kitchen.
****/
int ReportZone::ShowCheck(Terminal *term, Check *check)
{
FnTrace("ReportZone::ShowCheck()");
if (video_target == PRINTER_DEFAULT)
return 1; // always show everything on the default
Settings *settings = term->GetSettings();
int show = 0;
int vtarget;
Order *order;
SubCheck *scheck = check->SubList();
while (!show && (scheck != NULL))
{
order = scheck->OrderList();
while (!show && (order != NULL))
{
vtarget = order->VideoTarget(settings);
if (vtarget == video_target)
show = 1;
order = order->next;
}
scheck = scheck->next;
}
return show;
}
/****
* NextCheck: Gets the next check in the direction determined by sort_order.
****/
Check *ReportZone::NextCheck(Check *check, int sort_order)
{
FnTrace("ReportZone::NextCheck()");
Check *retcheck = NULL;
if (sort_order == CHECK_ORDER_OLDNEW)
retcheck = check->next;
else
retcheck = check->fore;
return retcheck;
}
/****
* GetDisplayCheck: For kitchen video, we want to know which check to display.
* Search through the checks based on sort order. Returns pointer to
* the check object to display, or NULL if no matching checks are found.
****/
Check *ReportZone::GetDisplayCheck(Terminal *term)
{
FnTrace("ReportZone::GetDisplayCheck()");
Check *checklist = NULL;
Check *disp_check = NULL;
int counter = 0;
if (term->sortorder == CHECK_ORDER_NEWOLD)
checklist = term->system_data->CheckListEnd();
else
checklist = term->system_data->CheckList();
if (checklist)
{
while ((counter < check_disp_num) && (checklist != NULL))
{
if (IsKitchenCheck(term, checklist))
{
disp_check = checklist;
counter += 1;
}
checklist = NextCheck(checklist, term->sortorder);
}
// verify we have a check we want
if (!IsKitchenCheck(term, disp_check) ||
(counter < check_disp_num))
disp_check = NULL;
}
if (disp_check)
{
disp_check->checknum = check_disp_num;
if (disp_check->check_state == 0)
{
disp_check->chef_time.Set();
disp_check->check_state = ORDER_SENT;
}
}
return disp_check;
}
/****
* GetCheckByNum: Search through the checks, returning NULL or whichever check's
* checknum value matches the current ReportZone's check_disp_num.
* //FIX BAK-->This feels like a kludge. It seems more sensible to associated the
* check directly with the ReportZone, say as a public member. But I'm worried that
* the check will at some point be deleted out from under us, causing a crash later.
* This method does have the virtue of being totally reliable. BUT: when I
* understand the code better, assuming there's no danger of having the check
* deleted at a bad time, it would be MUCH faster to use the public member method.
****/
Check *ReportZone::GetCheckByNum(Terminal *term)
{
FnTrace("ReportZone::GetCheckByNum()");
Check *checkptr = term->system_data->CheckList();
Check *retcheck = NULL;
// Steve McConnell would probably hate this: stop when we have no more
// checks to look at or when we have a return value
while ((checkptr != NULL) && (retcheck == NULL))
{
if (check_disp_num == checkptr->checknum)
retcheck = checkptr;
checkptr = checkptr->next;
}
return retcheck;
}
/****
* UndoRecentCheck:
****/
int ReportZone::UndoRecentCheck(Terminal *term)
{
FnTrace("ReportZone::UndoRecentCheck()");
int retval = 0;
if (term->same_signal < 1)
{
term->same_signal = 1;
Check *currcheck = term->system_data->CheckListEnd();
Check *lastcheck = NULL;
TimeInfo lasttime = term->system_data->start;
lasttime.AdjustYears(-1);
while (currcheck != NULL)
{
if (currcheck->check_state == ORDER_SERVED &&
currcheck->made_time > lasttime)
{
lastcheck = currcheck;
lasttime = currcheck->made_time;
}
currcheck = currcheck->fore;
}
if (lastcheck != NULL)
{
lastcheck->check_state = ORDER_SENT;
lastcheck->undo = 1;
lastcheck->ClearOrderStatus(NULL, ORDER_SHOWN);
term->Draw(1);
}
}
return retval;
}
/****
* AdjustPeriod: adjust should be either 1 or -1.
****/
int AdjustPeriod(TimeInfo &ref, int period, int adjust)
{
FnTrace("AdjustPeriod()");
// verify adjust has a sane value
adjust = (adjust >= 0) ? 1 : -1;
switch (period)
{
case SP_DAY:
ref += date::days(1 * adjust);
break;
case SP_WEEK:
ref += date::days(7 * adjust);
break;
case SP_2WEEKS:
ref += date::days(14 * adjust);
break;
case SP_4WEEKS:
ref += date::days(28 * adjust);
break;
case SP_MONTH:
ref += date::months(1 * adjust);
break;
case SP_HALF_MONTH:
ref.half_month_jump(adjust, 1, 15);
break;
case SP_HM_11:
ref.half_month_jump(adjust, 11, 26);
break;
case SP_QUARTER:
ref += date::months(3 * adjust);
break;
case SP_YTD:
ref.AdjustYears(1 * adjust);
break;
}
return 0;
}
SignalResult ReportZone::Signal(Terminal *t, const genericChar* message)
{
FnTrace("ReportZone::Signal()");
static const genericChar* commands[] = {
"next", "prior", "print", "localprint", "reportprint",
"day period", "sales period", "labor period", "month period",
"nextperiod", "sortby ", "undo", "ccinit", "cctotals", "cctotals ",
"ccdetails", "ccsettle", "ccsettle2 ", "ccclearsaf", "ccsafdetails",
"ccsafdone", "ccsettledone", "ccinitdone", "cctotalsdone",
"ccdetailsdone", "ccrefund", "ccvoids", "ccrefunds",
"ccexceptions", "ccfinish", "ccfinish2 ", "ccfinish3 ",
"ccprocessed", "ccrefundamount ", "ccvoidttid ",
"zero captured tips", "bump", NULL};
Employee *e = t->user;
System *sys = t->system_data;
Settings *s = &sys->settings;
TenKeyDialog *tkdialog = NULL;
CreditCardDialog *ccdialog = NULL;
GetTextDialog *gtdialog = NULL;
const char* batchnum = NULL;
if (e == NULL)
return SIGNAL_IGNORED;
int idx = CompareListN(commands, message);
switch (idx)
{
case 0: // next
if (report_type == REPORT_CREDITCARD)
{
switch (sys->cc_report_type)
{
case CC_REPORT_BATCH:
sys->cc_settle_results->Next(t);
break;
case CC_REPORT_INIT:
sys->cc_init_results->Next(t);
break;
case CC_REPORT_SAF:
sys->cc_saf_details_results->Next(t);
break;
}
}
else if (t->page && t->page->IsKitchen() && t->page->ZoneList())
{
// highlight next report zone with a check
Zone *zcur = t->active_zone;
Zone *z = zcur;
while (1)
{
if (z == NULL)
z = t->page->ZoneList(); // (re)start at top of list
else
z = z->next;
if (z == zcur)
break;
if (z && z->Type() == ZONE_REPORT &&
((ReportZone *)z)->GetDisplayCheck(t))
{
t->active_zone = z;
Draw(t, 1);
return SIGNAL_END;
}
}
}
else
{
AdjustPeriod(ref, period_view, 1);
if (t->archive)
t->archive = t->archive->next;
else if (t->archive == NULL)
t->archive = sys->ArchiveList();
}
Draw(t, 1);
return SIGNAL_OKAY;
case 1: // prior
if (report_type == REPORT_CREDITCARD)
{
switch (sys->cc_report_type)
{
case CC_REPORT_BATCH:
sys->cc_settle_results->Fore(t);
break;
case CC_REPORT_INIT:
sys->cc_init_results->Fore(t);
break;
case CC_REPORT_SAF:
sys->cc_saf_details_results->Fore(t);
break;
}
}
else if (t->page && t->page->IsKitchen() && t->page->ZoneList())
{
// highlight previous report zone with a check
Zone *zcur = t->active_zone;
Zone *z = zcur;
while (1)
{
if (z == NULL)
z = t->page->ZoneListEnd(); // (re)start at end of list
else
z = z->fore;
if (z == zcur)
break;
if (z && z->Type() == ZONE_REPORT &&
((ReportZone *)z)->GetDisplayCheck(t))
{
t->active_zone = z;
Draw(t, 1);
return SIGNAL_END;
}
}
}
else
{
AdjustPeriod(ref, period_view, -1);
if (t->archive)
t->archive = t->archive->fore;
else if (t->archive == NULL)
t->archive = sys->ArchiveListEnd();
}
Draw(t, 1);
return SIGNAL_OKAY;
case 2: // print
Print(t, print);
return SIGNAL_OKAY;
case 3: // localprint
Print(t, RP_PRINT_LOCAL);
return SIGNAL_OKAY;
case 4: // reportprint
Print(t, RP_PRINT_REPORT);
return SIGNAL_OKAY;
case 5: // day period
printf("report_zone : day_period: \n");
period_view = SP_DAY;
Draw(t, 1);
return SIGNAL_OKAY;
case 6: // sales period
printf("report_zone : sales_period\n");
period_view = s->sales_period;
period_fiscal = &s->sales_start;
Draw(t, 1);
return SIGNAL_OKAY;
case 7: // labor period
period_view = s->labor_period;
period_fiscal = &s->labor_start;
printf("report : labor_period: view = %d; fiscal=%d/%d/%d\n", period_view, period_fiscal->Month(), period_fiscal->Day(), period_fiscal->Year());
Draw(t, 1);
return SIGNAL_OKAY;
case 8: // month period
period_view = SP_MONTH;
Draw(t, 1);
return SIGNAL_OKAY;
case 9: // nextperiod
printf("report_zone : nextperiod\n");
period_view = NextValue(period_view, ReportPeriodValue);
if (period_view == SP_NONE)
{
period_view = SP_DAY;
}
Draw(t, 1);
return SIGNAL_OKAY;
case 10: // sortby
t->system_data->report_sort_method = atoi(&message[6]);
Draw(t, 1);
return SIGNAL_OKAY;
case 11: // undo
if (report_type == REPORT_CHECK)
UndoRecentCheck(t);
return SIGNAL_OKAY;
case 12: // ccinit
if (e->training == 0)
{
sys->cc_report_type = CC_REPORT_INIT;
t->CC_Init();
}
return SIGNAL_OKAY;
case 13: // cctotals
t->cc_totals.Clear();
sys->cc_report_type = CC_REPORT_TOTALS;
t->CC_Totals();
return SIGNAL_OKAY;
case 14: // cctotals with value
if (strcmp(&message[9], "fetch") == 0)
{
tkdialog = new TenKeyDialog("Enter batch number", "cctotals", 0, 0);
tkdialog->target_zone = this;
t->OpenDialog(tkdialog);
}
else
{
t->cc_totals.Clear();
sys->cc_report_type = CC_REPORT_TOTALS;
if (strcmp(&message[9], "0") == 0)
t->CC_Totals();
else
t->CC_Totals(&message[9]);
}
return SIGNAL_OKAY;
case 15: // ccdetails
sys->cc_report_type = CC_REPORT_DETAILS;
t->CC_Details();
return SIGNAL_OKAY;
case 16: // ccsettle
gtdialog = new GetTextDialog("Enter Batch Number (leave empty to settle last batch)",
"ccsettle2");
t->OpenDialog(gtdialog);
return SIGNAL_OKAY;
case 17: // ccsettle2
if (e->training == 0 && e->IsManager(s))
{
sys->non_eod_settle = 1;
if (strlen(&message[10]) > 0)
batchnum = &message[10];
else
batchnum = NULL;
if (t->CC_Settle(batchnum) >= 0)
{
sys->non_eod_settle = 0;
return SIGNAL_IGNORED;
}
}
return SIGNAL_OKAY;
case 18: // ccclearsaf
if (e->training == 0 && e->IsManager(s))
{
if (t->CC_ClearSAF() >= 0)
return SIGNAL_IGNORED;
}
return SIGNAL_OKAY;
case 19: // ccsafdetails
t->CC_SAFDetails();
Draw(t, 1);
return SIGNAL_OKAY;
case 20: // ccsafdone
sys->cc_report_type = CC_REPORT_SAF;
Draw(t, 1);
return SIGNAL_OKAY;
case 21: // ccsettledone
sys->cc_report_type = CC_REPORT_BATCH;
sys->non_eod_settle = 0;
Draw(t, 1);
return SIGNAL_OKAY;
case 22: // ccinitdone
sys->cc_report_type = CC_REPORT_INIT;
Draw(t, 1);
return SIGNAL_OKAY;
case 23: // cctotalsdone
sys->cc_report_type = CC_REPORT_TOTALS;
Draw(t, 1);
return SIGNAL_OKAY;
case 24: // ccdetailsdone
sys->cc_report_type = CC_REPORT_DETAILS;
Draw(t, 1);
return SIGNAL_OKAY;
case 25: // ccrefund
tkdialog = new TenKeyDialog("Enter Amount of Refund", "ccrefundamount", 0, 1);
tkdialog->target_zone = this;
t->OpenDialog(tkdialog);
return SIGNAL_OKAY;
case 26: // ccvoids
sys->cc_report_type = CC_REPORT_VOIDS;
Draw(t, 1);
return SIGNAL_OKAY;
case 27: // ccrefunds
sys->cc_report_type = CC_REPORT_REFUNDS;
Draw(t, 1);
return SIGNAL_OKAY;
case 28: // ccexceptions
sys->cc_report_type = CC_REPORT_EXCEPTS;
Draw(t, 1);
return SIGNAL_OKAY;
case 29: // ccfinish
if (t->GetSettings()->authorize_method == CCAUTH_MAINSTREET)
gtdialog = new GetTextDialog("Enter TTID Number", "ccfinish2");
else
gtdialog = new GetTextDialog("Enter Authorization Code", "ccfinish2");
t->OpenDialog(gtdialog);
return SIGNAL_OKAY;
case 30: // ccfinish2
if (t->credit == NULL)
{
t->credit = new Credit();
if (t->GetSettings()->authorize_method == CCAUTH_MAINSTREET)
t->credit->SetTTID(atol(&message[10]));
else
t->credit->SetAuth(&message[10]);
tkdialog = new TenKeyDialog("Enter the Amount", "ccfinish3", 0, 1);
t->OpenDialog(tkdialog);
}
return SIGNAL_OKAY;
case 31: // ccfinish3
if (t->credit != NULL)
{
t->credit->Amount(atoi(&message[10]));
t->CC_GetFinalApproval();
}
return SIGNAL_OKAY;
case 32: // ccprocessed
if (t->credit != NULL && t->credit->IsRefunded(1) == 0)
{
sys->cc_exception_db->Add(t, t->credit);
t->credit = NULL;
sys->cc_finish = sys->cc_exception_db->CreditListEnd();
sys->cc_report_type = CC_REPORT_FINISH;
Draw(t, 1);
}
return SIGNAL_OKAY;
case 33: // ccrefundamount
// got refund amount for Credit Card Report.
t->credit = NULL;
t->auth_amount = atoi(&message[15]);
t->auth_action = AUTH_REFUND;
t->auth_message = REFUND_MSG;
ccdialog = new CreditCardDialog(t);
t->NextDialog(ccdialog);
return SIGNAL_OKAY;
case 34: // ccvoidttid
if (debug_mode)
{
int ttid = atoi(&message[11]);
t->credit = new Credit();
t->credit->SetTTID((long)ttid);
t->CC_GetVoid();
}
return SIGNAL_OKAY;
case 35: // zero captured tips
sys->ClearCapturedTips(day_start, day_end, t->archive);
Draw(t, 1);
return SIGNAL_OKAY;
case 36: // bump active check
if (check_disp_num && this == t->active_zone)
return ToggleCheckReport(t);
break;
default:
if (strncmp(message, "search ", 7) == 0)
{
e = sys->user_db.NameSearch(&message[7], NULL);
if (e)
{
t->server = e;
Draw(t, 1);
}
return SIGNAL_OKAY;
}
else if (strncmp(message, "nextsearch ", 11) == 0)
{
e = sys->user_db.NameSearch(&message[11], t->server);
if (e)
{
t->server = e;
Draw(t, 1);
}
return SIGNAL_OKAY;
}
return SIGNAL_IGNORED;
}
return SIGNAL_IGNORED;
}
SignalResult ReportZone::Touch(Terminal *term, int tx, int ty)
{
FnTrace("ReportZone::Touch()");
if (report == NULL)
return SIGNAL_IGNORED;
int new_page = page;
LayoutZone::Touch(term, tx, ty);
if (selected_y <= 3.0)
{
--new_page;
}
else if (selected_y >= (size_y - 3.0))
{
++new_page;
}
else if (check_disp_num)
{
return ToggleCheckReport(term);
}
else
{
if (Print(term, print))
return SIGNAL_IGNORED;
return SIGNAL_OKAY;
}
int max_page = report->max_pages;
if (new_page >= max_page)
new_page = 0;
else if (new_page < 0)
new_page = max_page - 1;
if (new_page == page)
return SIGNAL_IGNORED;
page = new_page;
Draw(term, 0);
return SIGNAL_OKAY;
}
SignalResult ReportZone::Mouse(Terminal *term, int action, int mx, int my)
{
FnTrace("ReportZone::Mouse()");
if (!(action & MOUSE_PRESS) || report == NULL)
return SIGNAL_IGNORED;
int new_page = page;
LayoutZone::Touch(term, mx, my);
if (selected_y <= 3.0)
{
if (action & MOUSE_LEFT)
--new_page;
else if (action & MOUSE_RIGHT)
++new_page;
}
else if (selected_y >= (size_y - 3.0))
{
if (action & MOUSE_LEFT)
++new_page;
else if (action & MOUSE_RIGHT)
--new_page;
}
else if (check_disp_num)
{
return ToggleCheckReport(term);
}
else
{
if (Print(term, print))
return SIGNAL_IGNORED;
return SIGNAL_OKAY;
}
int max_page = report->max_pages;
if (new_page >= max_page)
new_page = 0;
else if (new_page < 0)
new_page = max_page - 1;
if (new_page == page)
return SIGNAL_IGNORED;
page = new_page;
Draw(term, 0);
return SIGNAL_OKAY;
}
SignalResult ReportZone::ToggleCheckReport(Terminal *term)
{
FnTrace("ReportZone::ToggleCheckReport()");
//toggle a check done, reusing ORDER_yada states because they have exactly
// what we want.
Check *reportcheck = GetDisplayCheck(term);
if ( reportcheck )
{
if ( reportcheck->check_state < ORDER_MADE )
{
// first toggle cooked
reportcheck->check_state = ORDER_MADE;
reportcheck->made_time.Set(); //FIX BAK-->should be current time
}
else
{
// then toggle served to remove from Kitchen Video
reportcheck->check_state = ORDER_SERVED;
reportcheck->flags |= CF_SHOWN;
reportcheck->SetOrderStatus(NULL, ORDER_SHOWN);
}
update = 1;
reportcheck->Save();
term->Draw(UPDATE_CHECKS | UPDATE_ORDERS | UPDATE_ORDER_SELECT | UPDATE_PAYMENTS);
return SIGNAL_OKAY;
}
else
{
return SIGNAL_IGNORED;
}
}
SignalResult ReportZone::Keyboard(Terminal *t, int my_key, int state)
{
FnTrace("ReportZone::Keyboard()");
if (report == NULL)
return SIGNAL_IGNORED;
// automatically accept check number (in ascii) as keyboard shortcut to bump
if (my_key == check_disp_num + '0')
return ToggleCheckReport(t);
int new_page = page;
switch (my_key)
{
case 16: // page up
--new_page;
break;
case 14: // page down
++new_page;
break;
case 118: // v
if (debug_mode)
{
TenKeyDialog *tk = new TenKeyDialog("Enter TTID", "ccvoidttid", 0);
t->OpenDialog(tk);
return SIGNAL_TERMINATE;
}
break;
default:
return SIGNAL_IGNORED;
}
int max_page = report->max_pages;
if (new_page >= max_page)
new_page = 0;
else if (new_page < 0)
new_page = max_page - 1;
if (new_page == page)
return SIGNAL_IGNORED;
page = new_page;
Draw(t, 0);
return SIGNAL_OKAY;
}
int ReportZone::Update(Terminal *t, int update_message, const genericChar* value)
{
FnTrace("ReportZone::Update()");
if ((update_message & UPDATE_REPORT) && temp_report)
{
Draw(t, 0);
return 0;
}
else if ((update_message & UPDATE_BLINK) && report_type == REPORT_CHECK)
{
Draw(t, 1);
return 0;
}
Report *r = report;
if (r == NULL)
return 0;
if ((update_message & r->update_flag) && r->is_complete)
return Draw(t, 1);
// FIX - obsolete - should be part of r->update_flag
switch (report_type)
{
case REPORT_AUDITING:
case REPORT_BALANCE:
if (update_message & UPDATE_SETTINGS)
return Draw(t, 1);
break;
case REPORT_SALES:
if ((update_message & UPDATE_SETTINGS) && value)
{
int sw = atoi(value);
if (sw == SWITCH_SHOW_FAMILY || sw == SWITCH_SHOW_MODIFIERS)
return Draw(t, 1);
}
break;
}
return 0;
}
int ReportZone::Print(Terminal *t, int print_mode)
{
FnTrace("ReportZone::Print()");
if (print_mode == RP_NO_PRINT)
return 0;
Employee *e = t->user;
if (e == NULL || report == NULL)
return 1;
Printer *p1 = t->FindPrinter(PRINTER_RECEIPT);
Printer *p2 = t->FindPrinter(PRINTER_REPORT);
if (p1 == NULL && p2 == NULL)
return 1;
// If we have RP_ASK and there are two different printers, ask.
// If there's only one printer, then don't bother asking.
if (print_mode == RP_ASK && p1 && p2 && (p1 != p2))
{
DialogZone *d = NewPrintDialog(p1 == p2);
d->target_zone = this;
t->OpenDialog(d);
return 0;
}
else
printer_dest = print_mode;
Printer *p = p1;
if ((print_mode == RP_PRINT_REPORT && p2) || p1 == NULL)
p = p2;
if (p == NULL)
return 1;
if (report_type == REPORT_ROYALTY && printing_to_printer == 0)
{
System *sys = t->system_data;
printing_to_printer = 1;
if (report != NULL)
{
delete report;
report = NULL;
}
if (temp_report != NULL)
{
delete temp_report;
temp_report = NULL;
}
temp_report = new Report;
temp_report->max_width = p->MaxWidth();
temp_report->destination = RP_DEST_PRINTER;
sys->RoyaltyReport(t, day_start, day_end, t->archive, temp_report, this);
return 0;
}
if (t->GetSettings()->print_report_header)
report->CreateHeader(t, p, e);
report->FormalPrint(p);
return 0;
}
/**** ReadZone Class ****/
ReadZone::ReadZone()
{
loaded = 0;
page = 0;
}
RenderResult ReadZone::Render(Terminal *t, int update_flag)
{
FnTrace("ReadZone::Render()");
if (update_flag)
{
loaded = 0;
page = 0;
}
LayoutZone::Render(t, update_flag);
if (loaded == 0 && filename.size() > 0)
{
loaded = 1;
report.Clear();
if (report.Load(filename.Value(), color[0]) != 0)
{
return RENDER_ERROR;
}
}
int hs = 0;
if (name.size() > 0)
{
TextC(t, 0, name.Value(), color[0]);
hs = 1;
}
if(report.Render(t, this, hs, 0, page, 0) == 0)
{
return RENDER_OKAY;
} else
{
return RENDER_ERROR;
}
}
SignalResult ReadZone::Signal(Terminal *t, const char* message)
{
FnTrace("ReadZone::Signal()");
SignalResult retval = SIGNAL_IGNORED;
char newfile[STRLONG];
if (strncmp(message, "findfile ", 9) == 0)
{
if (message[9] != '/')
{
MasterSystem->FullPath("text/", newfile);
strcat(newfile, &message[9]);
filename.Set(newfile);
}
else
{
filename.Set(&message[9]);
}
Draw(t, 1);
}
return retval;
}
SignalResult ReadZone::Touch(Terminal *t, int tx, int ty)
{
FnTrace("ReadZone::Touch()");
int new_page = 0;
LayoutZone::Touch(t, tx, ty);
if (selected_y < 3.0)
new_page = page - 1;
else if (selected_y > (size_y - 3.0))
new_page = page + 1;
else
return SIGNAL_IGNORED;
int max_page = report.max_pages;
if (new_page >= max_page)
new_page = 0;
else if (new_page < 0)
new_page = max_page - 1;
if (new_page != page)
{
page = new_page;
Draw(t, 0);
}
return SIGNAL_OKAY;
}
SignalResult ReadZone::Keyboard(Terminal *t, int my_key, int state)
{
FnTrace("ReadZone::Keyboard()");
int new_page = page;
switch (my_key)
{
case 16: // page up
--new_page;
break;
case 14: // page down
++new_page;
break;
default:
return SIGNAL_IGNORED;
}
int max_page = report.max_pages;
if (new_page >= max_page)
new_page = 0;
else if (new_page < 0)
new_page = max_page - 1;
if (new_page == page)
return SIGNAL_IGNORED;
page = new_page;
Draw(t, 0);
return SIGNAL_OKAY;
}
|
ViewTouch/viewtouch
|
zone/report_zone.cc
|
C++
|
gpl-3.0
| 38,913
|
#include "CNoiseGenerator.h"
#include "CMath.h"
#include <QDebug>
#include <QImage>
#include <QColor>
//-----------------------------------------------------------------------------------------
CNoiseGenerator1D::CNoiseGenerator1D(int iSize, int iStep, int iOctave)
: m_iSize(iSize + 1)
, m_iStep(iStep)
, m_iOctave(iOctave)
{
m_Values.resize((int) ceil(m_iSize * pow(2., iOctave - 1) / iStep));
Math::initRand();
for (int i = 0; i < m_Values.size(); ++i)
{
m_Values[i] = Math::randNorm();
}
}
//-----------------------------------------------------------------------------------------
double CNoiseGenerator1D::fNoise(double x) const
{
int i = (int) (x / m_iStep);
return Math::cosInterpolation(getNoise(i), getNoise(i + 1), fmod(x / m_iStep, 1));
}
//-----------------------------------------------------------------------------------------
double CNoiseGenerator1D::fCoherentNoise(double x, double persistance) const
{
double sum = 0;
double p = 1;
int f = 1;
for(int i = 0 ; i < m_iOctave ; ++i)
{
sum += p * fNoise(x * f);
p *= persistance;
f *= 2;
}
return sum * (1 - persistance) / (1 - p);
}
//-----------------------------------------------------------------------------------------
CNoiseGenerator2D::CNoiseGenerator2D(int iWidth, int iHeight, int iStep, int iOctave)
: m_iWidth(iWidth + 1)
, m_iHeight(iHeight + 1)
, m_iStep(iStep)
, m_iOctave(iOctave)
{
m_iMaxWidth = (int) ceil(m_iWidth * pow(2., iOctave - 1) / iStep);
int iMaxHeight = (int) ceil(m_iHeight * pow(2., iOctave - 1) / iStep);
m_Values.resize(m_iMaxWidth * iMaxHeight);
Math::initRand();
for (int i = 0; i < m_Values.size(); ++i)
{
m_Values[i] = Math::randNorm();
}
}
//-----------------------------------------------------------------------------------------
double CNoiseGenerator2D::fNoise(double x, double y) const
{
int i = (int) (x / m_iStep);
int j = (int) (y / m_iStep);
return Math::cosInterpolation2D(getNoise(i, j), getNoise(i + 1, j), getNoise(i, j + 1), getNoise(i + 1, j + 1), fmod(x / m_iStep, 1), fmod(y / m_iStep, 1));
}
//-----------------------------------------------------------------------------------------
double CNoiseGenerator2D::fCoherentNoise(double x, double y, double persistance) const
{
double sum = 0;
double p = 1;
int f = 1;
for(int i = 0 ; i < m_iOctave ; ++i)
{
sum += p * fNoise(x * f, y * f);
p *= persistance;
f *= 2;
}
return sum * (1 - persistance) / (1 - p);
}
//-----------------------------------------------------------------------------------------
QImage CNoiseGenerator2D::toImage(double dPersistance) const
{
QImage img(m_iWidth - 1, m_iHeight - 1, QImage::Format_RGB32);
for (int i = 0; i < m_iWidth - 1; i++)
{
for (int j = 0; j < m_iHeight - 1; j++)
{
double dValue = fCoherentNoise(i, j, dPersistance);
QColor color(dValue * 255., dValue * 255., dValue * 255.);
img.setPixel(i, j, color.rgb());
}
}
return img;
}
//-----------------------------------------------------------------------------------------
QColor CNoiseGenerator2D::threshold(double dValue, const QList<QColor>& colors, const QList<double>& thresholds) const
{
QColor color;
if (dValue <= thresholds[0])
{
color = colors[0];
}
else
{
bool bInter = false;
for (int i = 1; i < thresholds.size(); ++i)
{
if (dValue < thresholds[i])
{
double f = (dValue - thresholds[i-1]) / (thresholds[i] - thresholds[i-1]);
color.setRedF (colors[i-1].redF() * (1 - f) + colors[i].redF() * f);
color.setGreenF (colors[i-1].greenF() * (1 - f) + colors[i].greenF() * f);
color.setBlueF (colors[i-1].blueF() * (1 - f) + colors[i].blueF() * f);
bInter = true;
break;
}
}
if (!bInter)
{
color = colors[colors.size() - 1];
}
}
return color;
}
//-----------------------------------------------------------------------------------------
QImage CNoiseGenerator2D::toImage(double dPersistance, const QList<QColor>& colors, const QList<double>& thresholds) const
{
QImage img(m_iWidth - 1, m_iHeight - 1, QImage::Format_RGB32);
for (int i = 0; i < m_iWidth - 1; i++)
{
for (int j = 0; j < m_iHeight - 1; j++)
{
double dValue = fCoherentNoise(i, j, dPersistance);
QColor color = threshold(dValue, colors, thresholds);
img.setPixel(i, j, color.rgb());
}
}
return img;
}
|
Jbx2-0b/Humble3D
|
lib_math/CNoiseGenerator.cpp
|
C++
|
gpl-3.0
| 4,783
|
/* Copyright (c) Damian Jakub Smoczyk
*
* Contact: jakub.smoczyk@gmail.com
*
* All rights reserved.
*
* This file is part of reVision Project
*
* reVision Project is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* reVision Project 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 reVision Project. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "QtBranchProperty.hpp"
class QtArrayProperty : public QtBranchProperty
{
Q_OBJECT
public:
explicit QtArrayProperty(const QString& name, QWidget* parent = nullptr);
virtual ~QtArrayProperty();
};
|
creepydragon/r2
|
window/qt/QtPropertyWidget/QtArrayProperty.hpp
|
C++
|
gpl-3.0
| 1,039
|
/*
* Panther is a program to encode your media files from one format to the other.
* Copyright (C) 2012 Sankha Narayan Guria
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package sngforge.panther.modules;
/*
* interface that implies that this will be an encoder's basic class
*/
public interface EncoderEntry {
}
|
sankha93/Panther
|
src/sngforge/panther/modules/EncoderEntry.java
|
Java
|
gpl-3.0
| 968
|
---
title: "सऊदी अरब की तेल कंपनी अरामको पर ड्रोन से हमला"
layout: item
category: ["international"]
date: 2019-09-14T06:05:24.172Z
image: 1568441124171aramco.jpg
---
<p>दुबई: सऊदी अरब की सरकारी मीडिया ने गृह मंत्रालय के हवाले से बताया कि शनिवार को सऊदी अरामको के दो तेल संयंत्रों पर ड्रोन से हमला किया गया। आधिकारिक सऊदी प्रेस एजेंसी ने बताया, ''अरामको के औद्योगिक सुरक्षा दलों ने अब्कैक और खुरैस में अपने संयंत्रों में ड्रोन हमले के कारण लगी आग से निपटना शुरू कर दिया है।" उसने कहा, ''दोनों संयंत्रों में आग पर काबू पा लिया गया है।"</p>
<p>सऊदी अरामको सऊदी अरब की राष्ट्रीय पेट्रोलियम और प्राकृतिक गैस कंपनी है। यह राजस्व के मामले में दुनिया की कच्चे तेल की सबसे बड़ी कंपनी है। इससे पहले सऊदी के एक उपग्रह समाचार चैनल ने देश के पूर्वी हिस्से में स्थित सऊदी अरामको केंद्र में विस्फोट होने और आग लगने की खबर दी थी।</p>
<p>दुबई दुबई स्थित प्रसारणकर्ता अल-अरबिया ने ईस्टर्न प्रांत में दम्माम के समीप बुकयाक में शनिवार तड़के आग लगने की खबर दी। चैनल ने इसके बारे में विस्तार से जानकारी नहीं दी। ऑनलाइन वीडियो में भयंकर आग लगे हुए और पीछे से गोलियां चलने की आवाज आ रही है।</p>
<p>गौरतलब है कि अरामको को आतंकवादी निशाना बनाते रहे हैं। अल-कायदा के आत्मघाती विस्फोटकों ने फरवरी 2006 में इस तेल कंपनी पर हमला करने की कोशिश की थी लेकिन वे नाकाम रहे थे।</p>
|
InstantKhabar/_source
|
_source/news/2019-09-14-aramco.html
|
HTML
|
gpl-3.0
| 3,008
|
/****************************************************************************
**
** Copyright (C) 2016 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Milian Wolff <milian.wolff@kdab.com>
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtWebChannel module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "tst_webchannel.h"
#include <qwebchannel.h>
#include <qwebchannel_p.h>
#include <qmetaobjectpublisher_p.h>
#include <QtTest>
#ifdef WEBCHANNEL_TESTS_CAN_USE_JS_ENGINE
#include <QJSEngine>
#endif
QT_USE_NAMESPACE
#ifdef WEBCHANNEL_TESTS_CAN_USE_JS_ENGINE
class TestJSEngine;
class TestEngineTransport : public QWebChannelAbstractTransport
{
Q_OBJECT
public:
TestEngineTransport(TestJSEngine *);
void sendMessage(const QJsonObject &message) Q_DECL_OVERRIDE;
Q_INVOKABLE void channelSetupReady();
Q_INVOKABLE void send(const QByteArray &message);
private:
TestJSEngine *m_testEngine;
};
class ConsoleLogger : public QObject
{
Q_OBJECT
public:
ConsoleLogger(QObject *parent = 0);
Q_INVOKABLE void log(const QString &text);
Q_INVOKABLE void error(const QString &text);
int errorCount() const { return m_errCount; }
int logCount() const { return m_logCount; }
QString lastError() const { return m_lastError; }
private:
int m_errCount;
int m_logCount;
QString m_lastError;
};
ConsoleLogger::ConsoleLogger(QObject *parent)
: QObject(parent)
, m_errCount(0)
, m_logCount(0)
{
}
void ConsoleLogger::log(const QString &text)
{
m_logCount++;
qDebug("LOG: %s", qPrintable(text));
}
void ConsoleLogger::error(const QString &text)
{
m_errCount++;
m_lastError = text;
qWarning("ERROR: %s", qPrintable(text));
}
// A test JS engine with convenience integration with WebChannel.
class TestJSEngine : public QJSEngine
{
Q_OBJECT
public:
TestJSEngine();
TestEngineTransport *transport() const;
ConsoleLogger *logger() const;
void initWebChannelJS();
signals:
void channelSetupReady(TestEngineTransport *transport);
private:
TestEngineTransport *m_transport;
ConsoleLogger *m_logger;
};
TestEngineTransport::TestEngineTransport(TestJSEngine *engine)
: QWebChannelAbstractTransport(engine)
, m_testEngine(engine)
{
}
void TestEngineTransport::sendMessage(const QJsonObject &message)
{
QByteArray json = QJsonDocument(message).toJson(QJsonDocument::Compact);
QJSValue callback = m_testEngine->evaluate(QStringLiteral("transport.onmessage"));
Q_ASSERT(callback.isCallable());
QJSValue arg = m_testEngine->newObject();
QJSValue data = m_testEngine->evaluate(QString::fromLatin1("JSON.parse('%1');").arg(QString::fromUtf8(json)));
Q_ASSERT(!data.isError());
arg.setProperty(QStringLiteral("data"), data);
QJSValue val = callback.call((QJSValueList() << arg));
Q_ASSERT(!val.isError());
}
void TestEngineTransport::channelSetupReady()
{
emit m_testEngine->channelSetupReady(m_testEngine->transport());
}
void TestEngineTransport::send(const QByteArray &message)
{
QJsonDocument doc(QJsonDocument::fromJson(message));
emit messageReceived(doc.object(), this);
}
TestJSEngine::TestJSEngine()
: m_transport(new TestEngineTransport(this))
, m_logger(new ConsoleLogger(this))
{
globalObject().setProperty("transport", newQObject(m_transport));
globalObject().setProperty("console", newQObject(m_logger));
QString webChannelJSPath(QStringLiteral(":/qtwebchannel/qwebchannel.js"));
QFile webChannelJS(webChannelJSPath);
if (!webChannelJS.open(QFile::ReadOnly))
qFatal("Error opening qwebchannel.js");
QString source(QString::fromUtf8(webChannelJS.readAll()));
evaluate(source, webChannelJSPath);
}
TestEngineTransport *TestJSEngine::transport() const
{
return m_transport;
}
ConsoleLogger *TestJSEngine::logger() const
{
return m_logger;
}
void TestJSEngine::initWebChannelJS()
{
globalObject().setProperty(QStringLiteral("channel"), newObject());
QJSValue channel = evaluate(QStringLiteral("channel = new QWebChannel(transport, function(channel) { transport.channelSetupReady();});"));
Q_ASSERT(!channel.isError());
}
#endif // WEBCHANNEL_TESTS_CAN_USE_JS_ENGINE
TestWebChannel::TestWebChannel(QObject *parent)
: QObject(parent)
, m_dummyTransport(new DummyTransport(this))
, m_lastInt(0)
, m_lastBool(false)
, m_lastDouble(0)
{
}
TestWebChannel::~TestWebChannel()
{
}
int TestWebChannel::readInt() const
{
return m_lastInt;
}
void TestWebChannel::setInt(int i)
{
m_lastInt = i;
emit lastIntChanged();
}
bool TestWebChannel::readBool() const
{
return m_lastBool;
}
void TestWebChannel::setBool(bool b)
{
m_lastBool = b;
emit lastBoolChanged();
}
double TestWebChannel::readDouble() const
{
return m_lastDouble;
}
void TestWebChannel::setDouble(double d)
{
m_lastDouble = d;
emit lastDoubleChanged();
}
QVariant TestWebChannel::readVariant() const
{
return m_lastVariant;
}
void TestWebChannel::setVariant(const QVariant &v)
{
m_lastVariant = v;
emit lastVariantChanged();
}
QJsonValue TestWebChannel::readJsonValue() const
{
return m_lastJsonValue;
}
void TestWebChannel::setJsonValue(const QJsonValue& v)
{
m_lastJsonValue = v;
emit lastJsonValueChanged();
}
QJsonObject TestWebChannel::readJsonObject() const
{
return m_lastJsonObject;
}
void TestWebChannel::setJsonObject(const QJsonObject& v)
{
m_lastJsonObject = v;
emit lastJsonObjectChanged();
}
QJsonArray TestWebChannel::readJsonArray() const
{
return m_lastJsonArray;
}
void TestWebChannel::setJsonArray(const QJsonArray& v)
{
m_lastJsonArray = v;
emit lastJsonArrayChanged();
}
void TestWebChannel::testRegisterObjects()
{
QWebChannel channel;
QObject plain;
QHash<QString, QObject*> objects;
objects[QStringLiteral("plain")] = &plain;
objects[QStringLiteral("channel")] = &channel;
objects[QStringLiteral("publisher")] = channel.d_func()->publisher;
objects[QStringLiteral("test")] = this;
channel.registerObjects(objects);
}
void TestWebChannel::testDeregisterObjects()
{
QWebChannel channel;
TestObject testObject;
testObject.setObjectName("myTestObject");
channel.registerObject(testObject.objectName(), &testObject);
channel.connectTo(m_dummyTransport);
channel.d_func()->publisher->initializeClient(m_dummyTransport);
QJsonObject connectMessage =
QJsonDocument::fromJson(("{\"type\": 7,"
"\"object\": \"myTestObject\","
"\"signal\": " + QString::number(testObject.metaObject()->indexOfSignal("sig1()"))
+ "}").toLatin1()).object();
channel.d_func()->publisher->handleMessage(connectMessage, m_dummyTransport);
emit testObject.sig1();
channel.deregisterObject(&testObject);
emit testObject.sig1();
}
void TestWebChannel::testInfoForObject()
{
TestObject obj;
obj.setObjectName("myTestObject");
QWebChannel channel;
const QJsonObject info = channel.d_func()->publisher->classInfoForObject(&obj, m_dummyTransport);
QCOMPARE(info.keys(), QStringList() << "enums" << "methods" << "properties" << "signals");
{ // enums
QJsonObject fooEnum;
fooEnum["Asdf"] = TestObject::Asdf;
fooEnum["Bar"] = TestObject::Bar;
QJsonObject expected;
expected["Foo"] = fooEnum;
QCOMPARE(info["enums"].toObject(), expected);
}
{ // methods & slots
QJsonArray expected;
{
QJsonArray method;
method.append(QStringLiteral("deleteLater"));
method.append(obj.metaObject()->indexOfMethod("deleteLater()"));
expected.append(method);
}
{
QJsonArray method;
method.append(QStringLiteral("slot1"));
method.append(obj.metaObject()->indexOfMethod("slot1()"));
expected.append(method);
}
{
QJsonArray method;
method.append(QStringLiteral("slot2"));
method.append(obj.metaObject()->indexOfMethod("slot2(QString)"));
expected.append(method);
}
{
QJsonArray method;
method.append(QStringLiteral("setReturnedObject"));
method.append(obj.metaObject()->indexOfMethod("setReturnedObject(TestObject*)"));
expected.append(method);
}
{
QJsonArray method;
method.append(QStringLiteral("setObjectProperty"));
method.append(obj.metaObject()->indexOfMethod("setObjectProperty(QObject*)"));
expected.append(method);
}
{
QJsonArray method;
method.append(QStringLiteral("setProp"));
method.append(obj.metaObject()->indexOfMethod("setProp(QString)"));
expected.append(method);
}
{
QJsonArray method;
method.append(QStringLiteral("fire"));
method.append(obj.metaObject()->indexOfMethod("fire()"));
expected.append(method);
}
{
QJsonArray method;
method.append(QStringLiteral("method1"));
method.append(obj.metaObject()->indexOfMethod("method1()"));
expected.append(method);
}
QCOMPARE(info["methods"].toArray(), expected);
}
{ // signals
QJsonArray expected;
{
QJsonArray signal;
signal.append(QStringLiteral("destroyed"));
signal.append(obj.metaObject()->indexOfMethod("destroyed(QObject*)"));
expected.append(signal);
}
{
QJsonArray signal;
signal.append(QStringLiteral("sig1"));
signal.append(obj.metaObject()->indexOfMethod("sig1()"));
expected.append(signal);
}
{
QJsonArray signal;
signal.append(QStringLiteral("sig2"));
signal.append(obj.metaObject()->indexOfMethod("sig2(QString)"));
expected.append(signal);
}
{
QJsonArray signal;
signal.append(QStringLiteral("replay"));
signal.append(obj.metaObject()->indexOfMethod("replay()"));
expected.append(signal);
}
QCOMPARE(info["signals"].toArray(), expected);
}
{ // properties
QJsonArray expected;
{
QJsonArray property;
property.append(obj.metaObject()->indexOfProperty("objectName"));
property.append(QStringLiteral("objectName"));
{
QJsonArray signal;
signal.append(1);
signal.append(obj.metaObject()->indexOfMethod("objectNameChanged(QString)"));
property.append(signal);
}
property.append(obj.objectName());
expected.append(property);
}
{
QJsonArray property;
property.append(obj.metaObject()->indexOfProperty("foo"));
property.append(QStringLiteral("foo"));
{
QJsonArray signal;
property.append(signal);
}
property.append(obj.foo());
expected.append(property);
}
{
QJsonArray property;
property.append(obj.metaObject()->indexOfProperty("asdf"));
property.append(QStringLiteral("asdf"));
{
QJsonArray signal;
signal.append(1);
signal.append(obj.metaObject()->indexOfMethod("asdfChanged()"));
property.append(signal);
}
property.append(obj.asdf());
expected.append(property);
}
{
QJsonArray property;
property.append(obj.metaObject()->indexOfProperty("bar"));
property.append(QStringLiteral("bar"));
{
QJsonArray signal;
signal.append(QStringLiteral("theBarHasChanged"));
signal.append(obj.metaObject()->indexOfMethod("theBarHasChanged()"));
property.append(signal);
}
property.append(obj.bar());
expected.append(property);
}
{
QJsonArray property;
property.append(obj.metaObject()->indexOfProperty("objectProperty"));
property.append(QStringLiteral("objectProperty"));
{
QJsonArray signal;
signal.append(1);
signal.append(obj.metaObject()->indexOfMethod("objectPropertyChanged()"));
property.append(signal);
}
property.append(QJsonValue::fromVariant(QVariant::fromValue(obj.objectProperty())));
expected.append(property);
}
{
QJsonArray property;
property.append(obj.metaObject()->indexOfProperty("returnedObject"));
property.append(QStringLiteral("returnedObject"));
{
QJsonArray signal;
signal.append(1);
signal.append(obj.metaObject()->indexOfMethod("returnedObjectChanged()"));
property.append(signal);
}
property.append(QJsonValue::fromVariant(QVariant::fromValue(obj.returnedObject())));
expected.append(property);
}
{
QJsonArray property;
property.append(obj.metaObject()->indexOfProperty("prop"));
property.append(QStringLiteral("prop"));
{
QJsonArray signal;
signal.append(1);
signal.append(obj.metaObject()->indexOfMethod("propChanged(QString)"));
property.append(signal);
}
property.append(QJsonValue::fromVariant(QVariant::fromValue(obj.prop())));
expected.append(property);
}
QCOMPARE(info["properties"].toArray(), expected);
}
}
void TestWebChannel::testInvokeMethodConversion()
{
QWebChannel channel;
channel.connectTo(m_dummyTransport);
QJsonArray args;
args.append(QJsonValue(1000));
{
int method = metaObject()->indexOfMethod("setInt(int)");
QVERIFY(method != -1);
channel.d_func()->publisher->invokeMethod(this, method, args);
QCOMPARE(m_lastInt, args.at(0).toInt());
}
{
int method = metaObject()->indexOfMethod("setBool(bool)");
QVERIFY(method != -1);
QJsonArray args;
args.append(QJsonValue(!m_lastBool));
channel.d_func()->publisher->invokeMethod(this, method, args);
QCOMPARE(m_lastBool, args.at(0).toBool());
}
{
int method = metaObject()->indexOfMethod("setDouble(double)");
QVERIFY(method != -1);
channel.d_func()->publisher->invokeMethod(this, method, args);
QCOMPARE(m_lastDouble, args.at(0).toDouble());
}
{
int method = metaObject()->indexOfMethod("setVariant(QVariant)");
QVERIFY(method != -1);
channel.d_func()->publisher->invokeMethod(this, method, args);
QCOMPARE(m_lastVariant, args.at(0).toVariant());
}
{
int method = metaObject()->indexOfMethod("setJsonValue(QJsonValue)");
QVERIFY(method != -1);
channel.d_func()->publisher->invokeMethod(this, method, args);
QCOMPARE(m_lastJsonValue, args.at(0));
}
{
int method = metaObject()->indexOfMethod("setJsonObject(QJsonObject)");
QVERIFY(method != -1);
QJsonObject object;
object["foo"] = QJsonValue(123);
object["bar"] = QJsonValue(4.2);
args[0] = object;
channel.d_func()->publisher->invokeMethod(this, method, args);
QCOMPARE(m_lastJsonObject, object);
}
{
int method = metaObject()->indexOfMethod("setJsonArray(QJsonArray)");
QVERIFY(method != -1);
QJsonArray array;
array << QJsonValue(123);
array << QJsonValue(4.2);
args[0] = array;
channel.d_func()->publisher->invokeMethod(this, method, args);
QCOMPARE(m_lastJsonArray, array);
}
}
void TestWebChannel::testSetPropertyConversion()
{
QWebChannel channel;
channel.connectTo(m_dummyTransport);
{
int property = metaObject()->indexOfProperty("lastInt");
QVERIFY(property != -1);
channel.d_func()->publisher->setProperty(this, property, QJsonValue(42));
QCOMPARE(m_lastInt, 42);
}
{
int property = metaObject()->indexOfProperty("lastBool");
QVERIFY(property != -1);
bool newValue = !m_lastBool;
channel.d_func()->publisher->setProperty(this, property, QJsonValue(newValue));
QCOMPARE(m_lastBool, newValue);
}
{
int property = metaObject()->indexOfProperty("lastDouble");
QVERIFY(property != -1);
channel.d_func()->publisher->setProperty(this, property, QJsonValue(-4.2));
QCOMPARE(m_lastDouble, -4.2);
}
{
int property = metaObject()->indexOfProperty("lastVariant");
QVERIFY(property != -1);
QVariant variant("foo bar asdf");
channel.d_func()->publisher->setProperty(this, property, QJsonValue::fromVariant(variant));
QCOMPARE(m_lastVariant, variant);
}
{
int property = metaObject()->indexOfProperty("lastJsonValue");
QVERIFY(property != -1);
QJsonValue value("asdf asdf");
channel.d_func()->publisher->setProperty(this, property, value);
QCOMPARE(m_lastJsonValue, value);
}
{
int property = metaObject()->indexOfProperty("lastJsonArray");
QVERIFY(property != -1);
QJsonArray array;
array << QJsonValue(-123);
array << QJsonValue(-42);
channel.d_func()->publisher->setProperty(this, property, array);
QCOMPARE(m_lastJsonArray, array);
}
{
int property = metaObject()->indexOfProperty("lastJsonObject");
QVERIFY(property != -1);
QJsonObject object;
object["foo"] = QJsonValue(-123);
object["bar"] = QJsonValue(-4.2);
channel.d_func()->publisher->setProperty(this, property, object);
QCOMPARE(m_lastJsonObject, object);
}
}
void TestWebChannel::testDisconnect()
{
QWebChannel channel;
channel.connectTo(m_dummyTransport);
channel.disconnectFrom(m_dummyTransport);
m_dummyTransport->emitMessageReceived(QJsonObject());
}
void TestWebChannel::testWrapRegisteredObject()
{
QWebChannel channel;
TestObject obj;
obj.setObjectName("myTestObject");
channel.registerObject(obj.objectName(), &obj);
channel.connectTo(m_dummyTransport);
channel.d_func()->publisher->initializeClient(m_dummyTransport);
QJsonObject objectInfo = channel.d_func()->publisher->wrapResult(QVariant::fromValue(&obj), m_dummyTransport).toObject();
QCOMPARE(2, objectInfo.length());
QVERIFY(objectInfo.contains("id"));
QVERIFY(objectInfo.contains("__QObject*__"));
QVERIFY(objectInfo.value("__QObject*__").isBool() && objectInfo.value("__QObject*__").toBool());
QString returnedId = objectInfo.value("id").toString();
QCOMPARE(&obj, channel.d_func()->publisher->registeredObjects.value(obj.objectName()));
QCOMPARE(obj.objectName(), channel.d_func()->publisher->registeredObjectIds.value(&obj));
QCOMPARE(obj.objectName(), returnedId);
}
void TestWebChannel::testRemoveUnusedTransports()
{
QWebChannel channel;
DummyTransport *dummyTransport = new DummyTransport(this);
TestObject obj;
channel.connectTo(dummyTransport);
channel.d_func()->publisher->initializeClient(dummyTransport);
QMetaObjectPublisher *pub = channel.d_func()->publisher;
pub->wrapResult(QVariant::fromValue(&obj), dummyTransport);
QCOMPARE(pub->wrappedObjects.size(), 1);
QCOMPARE(pub->registeredObjectIds.size(), 1);
channel.disconnectFrom(dummyTransport);
delete dummyTransport;
QCOMPARE(pub->wrappedObjects.size(), 0);
QCOMPARE(pub->registeredObjectIds.size(), 0);
}
void TestWebChannel::testPassWrappedObjectBack()
{
QWebChannel channel;
TestObject registeredObj;
TestObject returnedObjMethod;
TestObject returnedObjProperty;
registeredObj.setObjectName("registeredObject");
channel.registerObject(registeredObj.objectName(), ®isteredObj);
channel.connectTo(m_dummyTransport);
channel.d_func()->publisher->initializeClient(m_dummyTransport);
QMetaObjectPublisher *pub = channel.d_func()->publisher;
QJsonObject returnedObjMethodInfo = pub->wrapResult(QVariant::fromValue(&returnedObjMethod), m_dummyTransport).toObject();
QJsonObject returnedObjPropertyInfo = pub->wrapResult(QVariant::fromValue(&returnedObjProperty), m_dummyTransport).toObject();
QJsonArray argsMethod;
QJsonObject argMethod0;
argMethod0["id"] = returnedObjMethodInfo["id"];
argsMethod << argMethod0;
QJsonObject argProperty;
argProperty["id"] = returnedObjPropertyInfo["id"];
pub->invokeMethod(®isteredObj, registeredObj.metaObject()->indexOfSlot("setReturnedObject(TestObject*)"), argsMethod);
QCOMPARE(registeredObj.mReturnedObject, &returnedObjMethod);
pub->setProperty(®isteredObj, registeredObj.metaObject()->indexOfProperty("returnedObject"), argProperty);
QCOMPARE(registeredObj.mReturnedObject, &returnedObjProperty);
}
void TestWebChannel::testInfiniteRecursion()
{
QWebChannel channel;
TestObject obj;
obj.setObjectProperty(&obj);
obj.setObjectName("myTestObject");
channel.connectTo(m_dummyTransport);
channel.d_func()->publisher->initializeClient(m_dummyTransport);
QJsonObject objectInfo = channel.d_func()->publisher->wrapResult(QVariant::fromValue(&obj), m_dummyTransport).toObject();
}
void TestWebChannel::testAsyncObject()
{
QWebChannel channel;
channel.connectTo(m_dummyTransport);
QThread thread;
thread.start();
TestObject obj;
obj.moveToThread(&thread);
QJsonArray args;
args.append(QJsonValue("message"));
int method = obj.metaObject()->indexOfMethod("setProp(QString)");
QVERIFY(method != -1);
{
QSignalSpy spy(&obj, &TestObject::propChanged);
channel.d_func()->publisher->invokeMethod(&obj, method, args);
QVERIFY(spy.wait());
QCOMPARE(spy.at(0).at(0).toString(), args.at(0).toString());
}
channel.registerObject("myObj", &obj);
channel.d_func()->publisher->initializeClient(m_dummyTransport);
QJsonObject connectMessage;
connectMessage["type"] = 7;
connectMessage["object"] = "myObj";
connectMessage["signal"] = obj.metaObject()->indexOfSignal("replay()");
channel.d_func()->publisher->handleMessage(connectMessage, m_dummyTransport);
{
QSignalSpy spy(&obj, &TestObject::replay);
QMetaObject::invokeMethod(&obj, "fire");
QVERIFY(spy.wait());
channel.deregisterObject(&obj);
QMetaObject::invokeMethod(&obj, "fire");
QVERIFY(spy.wait());
}
thread.quit();
thread.wait();
}
static QHash<QString, QObject*> createObjects(QObject *parent)
{
const int num = 100;
QHash<QString, QObject*> objects;
objects.reserve(num);
for (int i = 0; i < num; ++i) {
objects[QStringLiteral("obj%1").arg(i)] = new BenchObject(parent);
}
return objects;
}
void TestWebChannel::benchClassInfo()
{
QWebChannel channel;
channel.connectTo(m_dummyTransport);
QObject parent;
const QHash<QString, QObject*> objects = createObjects(&parent);
QBENCHMARK {
foreach (const QObject *object, objects) {
channel.d_func()->publisher->classInfoForObject(object, m_dummyTransport);
}
}
}
void TestWebChannel::benchInitializeClients()
{
QWebChannel channel;
channel.connectTo(m_dummyTransport);
QObject parent;
channel.registerObjects(createObjects(&parent));
QMetaObjectPublisher *publisher = channel.d_func()->publisher;
QBENCHMARK {
publisher->initializeClient(m_dummyTransport);
publisher->propertyUpdatesInitialized = false;
publisher->signalToPropertyMap.clear();
publisher->signalHandler.clear();
}
}
void TestWebChannel::benchPropertyUpdates()
{
QWebChannel channel;
channel.connectTo(m_dummyTransport);
QObject parent;
const QHash<QString, QObject*> objects = createObjects(&parent);
QVector<BenchObject*> objectList;
objectList.reserve(objects.size());
foreach (QObject *obj, objects) {
objectList << qobject_cast<BenchObject*>(obj);
}
channel.registerObjects(objects);
channel.d_func()->publisher->initializeClient(m_dummyTransport);
QBENCHMARK {
foreach (BenchObject *obj, objectList) {
obj->change();
}
channel.d_func()->publisher->clientIsIdle = true;
channel.d_func()->publisher->sendPendingPropertyUpdates();
}
}
void TestWebChannel::benchRegisterObjects()
{
QWebChannel channel;
channel.connectTo(m_dummyTransport);
QObject parent;
const QHash<QString, QObject*> objects = createObjects(&parent);
QBENCHMARK {
channel.registerObjects(objects);
}
}
void TestWebChannel::benchRemoveTransport()
{
QWebChannel channel;
QList<DummyTransport*> dummyTransports;
for (int i = 500; i > 0; i--)
dummyTransports.append(new DummyTransport(this));
QList<QSharedPointer<TestObject>> objs;
QMetaObjectPublisher *pub = channel.d_func()->publisher;
foreach (DummyTransport *transport, dummyTransports) {
channel.connectTo(transport);
channel.d_func()->publisher->initializeClient(transport);
/* 30 objects per transport */
for (int i = 30; i > 0; i--) {
QSharedPointer<TestObject> obj = QSharedPointer<TestObject>::create();
objs.append(obj);
pub->wrapResult(QVariant::fromValue(obj.data()), transport);
}
}
QBENCHMARK_ONCE {
for (auto transport : dummyTransports)
pub->transportRemoved(transport);
}
qDeleteAll(dummyTransports);
}
#ifdef WEBCHANNEL_TESTS_CAN_USE_JS_ENGINE
class SubclassedTestObject : public TestObject
{
Q_OBJECT
Q_PROPERTY(QString bar READ bar WRITE setBar NOTIFY theBarHasChanged)
public:
void setBar(const QString &newBar);
signals:
void theBarHasChanged();
};
void SubclassedTestObject::setBar(const QString &newBar)
{
if (!newBar.isNull())
emit theBarHasChanged();
}
class TestSubclassedFunctor {
public:
TestSubclassedFunctor(TestJSEngine *engine)
: m_engine(engine)
{
}
void operator()() {
QCOMPARE(m_engine->logger()->errorCount(), 0);
}
private:
TestJSEngine *m_engine;
};
#endif // WEBCHANNEL_TESTS_CAN_USE_JS_ENGINE
void TestWebChannel::qtbug46548_overriddenProperties()
{
#ifndef WEBCHANNEL_TESTS_CAN_USE_JS_ENGINE
QSKIP("A JS engine is required for this test to make sense.");
#else
SubclassedTestObject obj;
obj.setObjectName("subclassedTestObject");
QWebChannel webChannel;
webChannel.registerObject(obj.objectName(), &obj);
TestJSEngine engine;
webChannel.connectTo(engine.transport());
QSignalSpy spy(&engine, &TestJSEngine::channelSetupReady);
connect(&engine, &TestJSEngine::channelSetupReady, TestSubclassedFunctor(&engine));
engine.initWebChannelJS();
if (!spy.count())
spy.wait();
QCOMPARE(spy.count(), 1);
QJSValue subclassedTestObject = engine.evaluate("channel.objects[\"subclassedTestObject\"]");
QVERIFY(subclassedTestObject.isObject());
#endif // WEBCHANNEL_TESTS_CAN_USE_JS_ENGINE
}
QTEST_MAIN(TestWebChannel)
#include "tst_webchannel.moc"
|
geminy/aidear
|
oss/qt/qt-everywhere-opensource-src-5.9.0/qtwebchannel/tests/auto/webchannel/tst_webchannel.cpp
|
C++
|
gpl-3.0
| 28,865
|
import React from 'react'
import PropTypes from 'prop-types'
import Link from '@material-ui/core/Link'
import Dialog from '@material-ui/core/Dialog'
import IconButton from '@material-ui/core/IconButton'
import TableContainer from '@material-ui/core/TableContainer'
import Table from '@material-ui/core/Table'
import TableBody from '@material-ui/core/TableBody'
import TableRow from '@material-ui/core/TableRow'
import TableCell from '@material-ui/core/TableCell'
import Paper from '@material-ui/core/Paper'
import FavoriteBorderIcon from '@material-ui/icons/FavoriteBorder'
import inflection from 'inflection'
import { useTranslate } from 'react-admin'
import config from '../config'
import { DialogTitle } from './DialogTitle'
import { DialogContent } from './DialogContent'
const links = {
homepage: 'navidrome.org',
reddit: 'reddit.com/r/Navidrome',
twitter: 'twitter.com/navidrome',
discord: 'discord.gg/xh7j7yF',
source: 'github.com/navidrome/navidrome',
featureRequests: 'github.com/navidrome/navidrome/issues',
}
const AboutDialog = ({ open, onClose }) => {
const translate = useTranslate()
return (
<Dialog
onClose={onClose}
onBackdropClick={onClose}
aria-labelledby="about-dialog-title"
open={open}
>
<DialogTitle id="about-dialog-title" onClose={onClose}>
Navidrome Music Server
</DialogTitle>
<DialogContent dividers>
<TableContainer component={Paper}>
<Table aria-label={translate('menu.about')} size="small">
<TableBody>
<TableRow>
<TableCell align="right" component="th" scope="row">
{translate('menu.version')}:
</TableCell>
{config.version === 'dev' ? (
<TableCell align="left"> {config.version} </TableCell>
) : (
<TableCell align="left">
<Link
href={`https://github.com/navidrome/navidrome/releases/tag/v${
config.version.split(' ')[0]
}`}
target="_blank"
rel="noopener noreferrer"
>
{config.version.split(' ')[0]}
</Link>
{' ' + config.version.split(' ')[1]}
</TableCell>
)}
</TableRow>
{Object.keys(links).map((key) => {
return (
<TableRow key={key}>
<TableCell align="right" component="th" scope="row">
{translate(`about.links.${key}`, {
_: inflection.humanize(inflection.underscore(key)),
})}
:
</TableCell>
<TableCell align="left">
<Link
href={`https://${links[key]}`}
target="_blank"
rel="noopener noreferrer"
>
{links[key]}
</Link>
</TableCell>
</TableRow>
)
})}
<TableRow>
<TableCell align="right" component="th" scope="row">
<Link
href={'https://github.com/sponsors/deluan'}
target="_blank"
rel="noopener noreferrer"
>
<IconButton size={'small'}>
<FavoriteBorderIcon fontSize={'small'} />
</IconButton>
</Link>
</TableCell>
<TableCell align="left">
<Link
href={'https://ko-fi.com/deluan'}
target="_blank"
rel="noopener noreferrer"
>
ko-fi.com/deluan
</Link>
</TableCell>
</TableRow>
</TableBody>
</Table>
</TableContainer>
</DialogContent>
</Dialog>
)
}
AboutDialog.propTypes = {
open: PropTypes.bool.isRequired,
onClose: PropTypes.func.isRequired,
}
export { AboutDialog }
|
cloudsonic/sonic-server
|
ui/src/dialogs/AboutDialog.js
|
JavaScript
|
gpl-3.0
| 4,279
|
//
// ScrollPlotView.h
// iCash
//
// Created by Vitaly Merenkov on 02.03.13.
//
#import <Cocoa/Cocoa.h>
@class PlotView;
@interface ScrollPlotView : NSScrollView
@property IBOutlet PlotView *plotView;
@end
|
yberdnikov/yaMK
|
yaMK/ScrollPlotView.h
|
C
|
gpl-3.0
| 214
|
//Exercise 7.3
class IterativePowerTen {
public static void main(String[] args) {
double x = 2.0;
int n = 10;
double y = x;
for (int i = 1; i <= n; i++) {
x = x * y;
}
System.out.println(x);
}
}
|
manueleiria/exercises
|
think_java/chapter_7/IterativePowerTen.java
|
Java
|
gpl-3.0
| 253
|
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
type animal struct {
food string
locomotion string
noise string
}
func (a *animal) Eat() {
fmt.Println(a.food)
}
func (a *animal) Move() {
fmt.Println(a.locomotion)
}
func (a *animal) Speak() {
fmt.Println(a.noise)
}
func main() {
reader := bufio.NewReader(os.Stdin)
for {
fmt.Print("> ")
input, _ := reader.ReadString('\n')
s := strings.Split(strings.TrimSpace(input), " ")
a := new(animal)
switch s[0] {
case "cow":
a.food = "grass"
a.locomotion = "walk"
a.noise = "moo"
case "bird":
a.food = "worms"
a.locomotion = "fly"
a.noise = "poop"
case "snake":
a.food = "mice"
a.locomotion = "slither"
a.noise = "hsss"
}
switch s[1] {
case "eat":
a.Eat()
case "speak":
a.Speak()
case "move":
a.Move()
}
}
}
|
syhan/coursera
|
golang-functions-methods/Week3/animal.go
|
GO
|
gpl-3.0
| 851
|
<?php
/*
Plugin Name: Interactions
Description: People you mentioned in your posts in the last week.
When: Wednesdays for Twitter, Saturday otherwise
*/
/**
*
* ThinkUp/webapp/plugins/insightsgenerator/insights/interactions.php
*
* Copyright (c) 2013-2016 Nilaksh Das, Gina Trapani
*
* LICENSE:
*
* This file is part of ThinkUp (http://thinkup.com).
*
* ThinkUp is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any
* later version.
*
* ThinkUp 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 ThinkUp. If not, see
* <http://www.gnu.org/licenses/>.
*
* @license http://www.gnu.org/licenses/gpl.html
* @copyright 2013-2016 Nilaksh Das, Gina Trapani
* @author Nilaksh Das <nilakshdas [at] gmail [dot] com>
*/
class InteractionsInsight extends InsightPluginParent implements InsightPlugin {
public function generateInsight(Instance $instance, User $user, $last_week_of_posts, $number_days) {
parent::generateInsight($instance, $user, $last_week_of_posts, $number_days);
$this->logger->logInfo("Begin generating insight", __METHOD__.','.__LINE__);
if ($instance->network == 'twitter') {
$day_of_week = 3;
} else {
$day_of_week = 6;
}
$should_generate_insight = self::shouldGenerateWeeklyInsight('interactions', $instance, $insight_date='today',
$regenerate_existing_insight=false, $day_of_week=3, count($last_week_of_posts),
$excluded_networks=array('facebook', 'google+', 'foursquare', 'youtube'));
if ($should_generate_insight) {
$user_dao = DAOFactory::getDAO('UserDAO');
$mentions_count = array();
$mentions_info = array();
$mentions_avatars = array();
$insight_data = array();
$insight_text = '';
if ($instance->network == 'twitter') {
$talk_time = 15;
} else {
$talk_time = 38;
}
foreach ($last_week_of_posts as $post) {
if ($post->in_reply_to_user_id && $instance->network_user_id != $post->in_reply_to_user_id) {
$mentioned_user = $user_dao->getDetails($post->in_reply_to_user_id, $instance->network);
if (isset($mentioned_user)) {
$mention_in_post = $instance->network == 'twitter' ? '@' : '';
$mention_in_post .= $mentioned_user->username;
$mentions_info[$mention_in_post] = $mentioned_user;
// Update mention count
if (array_key_exists($mention_in_post, $mentions_count)) {
$mentions_count[$mention_in_post]++;
} else {
$mentions_count[$mention_in_post] = 1;
}
}
}
}
if (count($mentions_count)) {
// Get most mentioned user
arsort($mentions_count);
$most_mentioned_user = each($mentions_count);
// Add mentions to dataset
$users_mentioned = array();
foreach (array_slice($mentions_count, 0, 10) as $mention => $count) {
$mention_info['mention'] = $mention;
$mention_info['count'] = $count;
$mention_info['user'] = $mentions_info[$mention];
$users_mentioned[] = $mention_info;
}
}
if (isset($most_mentioned_user) && ($talk_time * $most_mentioned_user['value']) >= 60) {
$headline = $this->username." replied to ".$most_mentioned_user['key'] ." <strong>"
.$this->terms->getOccurrencesAdverb($most_mentioned_user['value'])."</strong> last week";
$conversation_seconds = $this->terms->getOccurrencesAdverb($most_mentioned_user['value']) * $talk_time;
$milestones = $this->convertSecondsToMilestone($conversation_seconds);
$insight_text = 'Time having good conversation is time well spent.';
// $header_image = $users_mentioned[0][user]->avatar;
$header_image = $users_mentioned[0]["user"]->avatar;
//Instantiate the Insight object
$my_insight = new Insight();
//REQUIRED: Set the insight's required attributes
$my_insight->instance_id = $instance->id;
$my_insight->slug = 'interactions'; //slug to label this insight's content
$my_insight->date = $this->insight_date; //date of the data this insight applies to
$my_insight->headline = $headline;
$my_insight->text = $insight_text;
$my_insight->header_image = $header_image;
$my_insight->emphasis = Insight::EMPHASIS_MED;
$my_insight->filename = basename(__FILE__, ".php");
$my_insight->setPeople($users_mentioned);
$my_insight->setMilestones($milestones);
$this->insight_dao->insertInsight($my_insight);
}
}
$this->logger->logInfo("Done generating insight", __METHOD__.','.__LINE__);
}
/**
* Take some seconds and make a pretty milestone.
* @param int $total_seconds How many seconds to covnert
* @param int $total_drill_down How many units to drill down from days
* @return array
*/
protected function convertSecondsToMilestone($total_seconds, $total_drill_down = 2) {
$secondsInAMinute = 60;
$secondsInAnHour = 60 * $secondsInAMinute;
$secondsInADay = 24 * $secondsInAnHour;
// extract days
$days = floor($total_seconds / $secondsInADay);
// extract hours
$hourSeconds = $total_seconds % $secondsInADay;
$hours = floor($hourSeconds / $secondsInAnHour);
// extract minutes
$minuteSeconds = $hourSeconds % $secondsInAnHour;
$minutes = floor($minuteSeconds / $secondsInAMinute);
// extract the remaining seconds
$remainingSeconds = $minuteSeconds % $secondsInAMinute;
$seconds = ceil($remainingSeconds);
// return the final array
$obj = array(
'd' => (int) $days,
'h' => (int) $hours,
'm' => (int) $minutes,
's' => (int) $seconds,
);
$places = 0;
$text = '';
$milestones = array(
"per_row" => 2,
"label_type" => "text",
"items" => array(),
);
if ($obj["d"] && $places < $total_drill_down) {
$milestones["items"][] = array(
"number" => $obj["d"],
"label" => "days",
);
$places++;
}
if ($obj["h"] && $places < $total_drill_down) {
$milestones["items"][] = array(
"number" => $obj["h"],
"label" => "hours",
);
$places++;
}
if ($obj["m"] && $places < $total_drill_down) {
if ($obj["m"] > 1) {
$milestones["items"][] = array(
"number" => $obj["m"],
"label" => "minutes",
);
} else {
$milestones["items"][] = array(
"number" => $obj["m"],
"label" => "minute",
);
}
$places++;
}
if ($obj["s"] && $places < $total_drill_down) {
$milestones["items"][] = array(
"number" => $obj["s"],
"label" => "seconds",
);
$places++;
}
return $milestones;
}
}
$insights_plugin_registrar = PluginRegistrarInsights::getInstance();
$insights_plugin_registrar->registerInsightPlugin('InteractionsInsight');
|
ThinkUpLLC/ThinkUp
|
webapp/plugins/insightsgenerator/insights/retired/interactions.php
|
PHP
|
gpl-3.0
| 8,364
|
tinymce.PluginManager.add('tabpanel', function(editor, url) {
var walker = tinymce.dom.TreeWalker;
editor.ui.registry.addNestedMenuItem('tabpanel', {
//icon: 'tabpanel',
text: "Tabs",
tooltip: "Tabs",
getSubmenuItems: function () {
return [
{
type: 'menuitem',
//icon: 'tab',
text: "New panel",
tooltip: "New panel",
onAction: function () {
let el = editor.selection.getNode();
let parent = el.parentNode;
let tabpanels = editor.dom.getParents(el,'.tabpanels')[0];
if(tabpanels !== undefined && tabpanels !== null) {
let tabs = editor.dom.select('.nav-tabs',tabpanels)[0],
panels = editor.dom.select('.tab-content',tabpanels)[0],
nb = tabs.children.length;
nb++;
editor.dom.add(tabs,'li',false,'<a role="tab" href="#tab'+nb+'" aria-controls="tab'+nb+'" data-toggle="tab"><img class="img-responsive" src="#" alt="color'+nb+'" width="250" height="250" /><span>Color'+nb+'</span></a>');
editor.dom.add(panels,'section',{id:'tab'+nb,class:'tab-pane',role:'tabpanel'},'<p>color'+nb+'</p>');
}
}
},
{
type: 'menuitem',
//icon: 'tab',
text: "Remove panel",
tooltip: "Remove panel",
onAction: function () {
let el = editor.selection.getNode();
let parent = el.parentNode;
let tabpanels = editor.dom.getParents(el,'.tabpanels')[0];
if(tabpanels !== undefined && tabpanels !== null) {
let tabs = editor.dom.select('.nav-tabs',tabpanels)[0],
panels = editor.dom.select('.tab-content',tabpanels)[0];
tinymce.activeEditor.dom.remove(tinymce.activeEditor.dom.select('li:last-child',tabs));
tinymce.activeEditor.dom.remove(tinymce.activeEditor.dom.select('section:last-child',panels));
}
}
}
];
}
});
});
// Load the required translation files
tinymce.PluginManager.requireLangPack('tabpanel', 'en_EN,fr_FR');
|
magix-cms/magixcms-3
|
admin/template/js/vendor/tiny_mce.5.8.2/plugins/tabpanel/plugin.js
|
JavaScript
|
gpl-3.0
| 2,609
|
# -*- mode: cmake; tab-width: 2; indent-tabs-mode: t; truncate-lines: t; compile-command: "cmake -Wdev" -*-
# vim: set filetype=cmake autoindent tabstop=2 shiftwidth=2 noexpandtab softtabstop=2 nowrap:
# defines that must be present in config.h for our headers
set (opm-upscaling_CONFIG_VAR
HAVE_SUPERLU
)
# dependencies
set (opm-upscaling_DEPS
# compile with C99 support if available
"C99"
# compile with C++0x/11 support if available
"CXX11Features"
# various runtime library enhancements
"Boost 1.44.0
COMPONENTS date_time filesystem system iostreams unit_test_framework REQUIRED"
# matrix library
"BLAS REQUIRED"
"LAPACK REQUIRED"
# solver
"SuperLU"
# DUNE dependency
"dune-common REQUIRED;
dune-istl REQUIRED;
dune-geometry REQUIRED;
dune-grid REQUIRED;
opm-common REQUIRED;
opm-grid REQUIRED;
opm-core REQUIRED;
opm-output REQUIRED"
)
|
babrodtk/opm-cmake
|
cmake/Modules/opm-upscaling-prereqs.cmake
|
CMake
|
gpl-3.0
| 869
|
/*
* Copyright (C) 2015 Arthur Gregorio, AG.Software
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package br.com.webbudget.application.controller.registration;
import br.com.webbudget.application.components.ui.ViewState;
import br.com.webbudget.application.components.ui.table.Page;
import br.com.webbudget.application.components.ui.LazyFormBean;
import br.com.webbudget.domain.entities.registration.*;
import br.com.webbudget.domain.repositories.registration.AddressRepository;
import br.com.webbudget.domain.repositories.registration.ContactRepository;
import br.com.webbudget.domain.services.ContactService;
import lombok.Getter;
import lombok.Setter;
import org.primefaces.model.SortOrder;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
import static br.com.webbudget.application.components.ui.NavigationManager.PageType.*;
/**
* The {@link Contact} maintenance routine controller
*
* @author Arthur Gregorio
*
* @version 1.3.0
* @since 1.2.0, 12/04/2015
*/
@Named
@ViewScoped
public class ContactBean extends LazyFormBean<Contact> {
@Getter
@Setter
private Telephone telephone;
@Inject
private ContactRepository contactRepository;
@Inject
private AddressRepository addressRepository;
@Inject
private ContactService contactService;
/**
* {@inheritDoc}
*
* @param id
* @param viewState
*/
@Override
public void initialize(long id, ViewState viewState) {
this.viewState = viewState;
this.value = this.contactRepository.findById(id).orElseGet(Contact::new);
}
/**
* {@inheritDoc}
*/
@Override
protected void initializeNavigationManager() {
this.navigation.addPage(LIST_PAGE, "listContacts.xhtml");
this.navigation.addPage(ADD_PAGE, "formContact.xhtml");
this.navigation.addPage(UPDATE_PAGE, "formContact.xhtml");
this.navigation.addPage(DETAIL_PAGE, "detailContact.xhtml");
this.navigation.addPage(DELETE_PAGE, "detailContact.xhtml");
}
/**
* {@inheritDoc}
*
* @param first
* @param pageSize
* @param sortField
* @param sortOrder
* @return
*/
@Override
public Page<Contact> load(int first, int pageSize, String sortField, SortOrder sortOrder) {
return this.contactRepository.findAllBy(this.filter.getValue(),
this.filter.getEntityStatusValue(), first, pageSize);
}
/**
* {@inheritDoc}
*/
@Override
public void doSave() {
this.contactService.save(this.value);
this.value = new Contact();
this.addInfo(true, "saved");
}
/**
* {@inheritDoc}
*/
@Override
public void doUpdate() {
this.value = this.contactService.update(this.value);
this.addInfo(true, "updated");
}
/**
* {@inheritDoc}
*
* @return
*/
@Override
public String doDelete() {
this.contactService.delete(this.value);
this.addInfoAndKeep("deleted");
return this.changeToListing();
}
/**
* Find the contact address by his brazilian zip code
*/
public void searchAddress() {
final Address address = this.addressRepository.findByZipcode(
this.value.getZipcode());
this.value.setAddress(address);
this.updateComponent("addressBox");
}
/**
* Show the telephone dialog
*/
public void showTelephoneDialog() {
this.telephone = new Telephone();
this.updateAndOpenDialog("telephoneDialog", "dialogTelephone");
}
/**
* Add a number to the contact
*/
public void addTelephone() {
this.value.addTelephone(this.telephone);
this.updateComponent("telephonesList");
this.closeDialog("dialogTelephone");
}
/**
* Add the number deleted to the list of numbers to delete from DB
*
* @param telephone the number
*/
public void deleteTelephone(Telephone telephone) {
this.value.removeTelephone(telephone);
this.updateComponent("telephonesList");
}
/**
* Method to list the possible types of an {@link Contact}
*
* @return an array with the values of {@link ContactType} enum
*/
public ContactType[] getContactTypes() {
return ContactType.values();
}
/**
* Method to list the possible types of an {@link Telephone}
*
* @return an array with the values of {@link NumberType} enum
*/
public NumberType[] getNumberTypes() {
return NumberType.values();
}
}
|
arthurgregorio/web-budget
|
src/main/java/br/com/webbudget/application/controller/registration/ContactBean.java
|
Java
|
gpl-3.0
| 5,250
|
<div id="commonHeaderDiv" ng-hide="hideCommonHeader">
<!-- Plan Banner -->
<ng-include
replace-include
ng-controller="PlanBannerCtrl"
src="'partials/common-header/plan-banner.html'"
></ng-include>
<!-- END Plan Banner -->
<!-- Common Header Navbar -->
<nav class="navbar navbar-default hidden-print"
ng-class="{'active-banner': isSubcompanySelected() || isTestCompanySelected()}" role="navigation">
<div class="navbar-header">
<a class="navbar-brand visible-md visible-lg"
href="http://www.risevision.com/" target="{{newTabHome ? '_blank' : '_self'}}" ng-if="!inRVAFrame">
<img loading="lazy" src="//s3.amazonaws.com/Rise-Images/UI/logo.svg" class="img-responsive logo-small" width="113" height="42" alt="Rise Vision">
</a>
<a class="navbar-brand hidden-md hidden-lg text-center"
href="" off-canvas-toggle>
<i class="fa fa-bars"></i>
</a>
<!-- If User Authenticated -->
<!-- Nav Links -->
<div class="navbar-left visible-xs visible-sm" ng-if="ENV_NAME">
<ul class="nav navbar-nav">
<li class="env-name-nav-item">
<span class="env-name-label">{{ENV_NAME}}</span>
</li>
</ul>
</div>
<div class="navbar-collapse navbar-left hidden-xs hidden-sm">
<ul class="nav navbar-nav">
<li class="env-name-nav-item visible-md visible-lg" ng-if="ENV_NAME">
<span class="env-name-label">{{ENV_NAME}}</span>
</li>
<li ng-repeat="opt in navOptions">
<a id="{{opt.title + 'Link'}}" ng-if="opt.cid" ng-href="{{opt.link}}" link-cid target="{{opt.target}}" ng-class="{'selected': opt.states && opt.states.indexOf(navSelected) > -1}">{{opt.title}}</a>
<a id="{{opt.title + 'Link'}}" ng-if="!opt.cid" ng-href="{{opt.link}}" target="{{opt.target}}" ng-class="{'selected': opt.states && opt.states.indexOf(navSelected) > -1}">{{opt.title}}</a>
</li>
<li>
<a id="trainingLink" href="https://risevision.com/webinars?utm_source=app&utm_medium=web&utm_campaign=in_app_training_notification" target="_blank">Training</a>
</li>
<li ng-if="!inRVAFrame && !hideHelpMenu">
<a href="http://www.risevision.com/help/" target="_blank">
Help
</a>
</li>
</ul>
</div>
<!-- Action Nav -->
<ul class="nav navbar-nav navbar-right actions-nav pull-right u_remove-right">
<!-- Get Started Button -->
<li class="madero-style hidden-xs">
<button id="onboardingButton" class="btn btn-default btn-navbar u_margin-right"
ui-sref="apps.launcher.onboarding"
ng-if="isApps()" if-onboarding>
Get Started
</button>
</li>
<!-- Zendesk -->
<ng-include
replace-include
ng-controller="ZendeskButtonCtrl"
src="'partials/common-header/zendesk-button.html'"
></ng-include>
<ng-include
replace-include
ng-if="inRVAFrame"
ng-controller="CloseFrameButtonCtrl"
src="'partials/common-header/close-frame-button.html'"
></ng-include>
<!-- Auth -->
<ng-include
replace-include
ng-if="!inRVAFrame"
ng-controller="AuthButtonsCtr"
src="'partials/common-header/auth-buttons.html'"
></ng-include>
<li ng-if="inRVAFrame"
ng-controller="AuthButtonsCtr"></li>
</ul>
<!-- END Action Nav -->
<!-- END Nav Links -->
</div>
<ng-include
replace-include
ng-controller="TestCompanyBannerCtrl"
src="'partials/common-header/test-company-banner.html'"></ng-include>
<ng-include
replace-include
ng-controller="SubcompanyBannerCtrl"
src="'partials/common-header/subcompany-banner.html'"></ng-include>
</nav>
<ng-include
replace-include
ng-controller="GlobalAlertsCtrl"
src="'partials/common-header/global-alerts.html'"></ng-include>
<!-- END Common Header Navbar -->
<!-- Off Canvas Version of the Nav -->
<nav class="off-canvas-nav" off-canvas-nav>
<ul class="nav nav-pills nav-stacked">
<li off-canvas-toggle>
<i class="fa fa-times fa-2x pull-right"></i>
<img loading="lazy" src="//s3.amazonaws.com/rise-common/images/logo-small.png" class="img-responsive logo-small" width="113" height="42" alt="Rise Vision">
</li>
<li>
<a ui-sref="apps.launcher.onboarding" ng-if="isApps()" if-onboarding>Get Started</a>
</li>
<li ng-repeat="opt in navOptions">
<a ng-if="opt.cid" ng-href="{{opt.link}}" link-cid target="{{opt.target}}">{{opt.title}}</a>
<a ng-if="!opt.cid" ng-href="{{opt.link}}" target="{{opt.target}}">{{opt.title}}</a>
</li>
<li>
<a id="trainingLink" href="https://risevision.com/webinars?utm_source=app&utm_medium=web&utm_campaign=in_app_training_notification" target="_blank">Training</a>
</li>
<li ng-if="!hideHelpMenu">
<a target="_blank" href="http://www.risevision.com/help">Help</a>
</li>
</ul>
</nav>
</div>
<div ng-show="cookieEnabled === false" class="bg-warning text-center u_padding-sm">
<small><strong>Cookies Are Disabled.</strong> Rise Vision needs to use cookies to properly function. Please enable Cookies and Third-Party Cookies on your web browser and refresh this page.</small>
</div>
<iframe name="logoutFrame" id="logoutFrame" style='display:none'></iframe>
|
Rise-Vision/rise-vision-app-launcher
|
web/partials/common-header/common-header.html
|
HTML
|
gpl-3.0
| 5,277
|
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
import { Animation } from '../../animations/animation';
import { Transition } from '../../transitions/transition';
var ActionSheetSlideIn = (function (_super) {
__extends(ActionSheetSlideIn, _super);
function ActionSheetSlideIn() {
return _super !== null && _super.apply(this, arguments) || this;
}
ActionSheetSlideIn.prototype.init = function () {
var ele = this.enteringView.pageRef().nativeElement;
var backdrop = new Animation(this.plt, ele.querySelector('ion-backdrop'));
var wrapper = new Animation(this.plt, ele.querySelector('.action-sheet-wrapper'));
backdrop.fromTo('opacity', 0.01, 0.4);
wrapper.fromTo('translateY', '100%', '0%');
this.easing('cubic-bezier(.36,.66,.04,1)').duration(400).add(backdrop).add(wrapper);
};
return ActionSheetSlideIn;
}(Transition));
export { ActionSheetSlideIn };
var ActionSheetSlideOut = (function (_super) {
__extends(ActionSheetSlideOut, _super);
function ActionSheetSlideOut() {
return _super !== null && _super.apply(this, arguments) || this;
}
ActionSheetSlideOut.prototype.init = function () {
var ele = this.leavingView.pageRef().nativeElement;
var backdrop = new Animation(this.plt, ele.querySelector('ion-backdrop'));
var wrapper = new Animation(this.plt, ele.querySelector('.action-sheet-wrapper'));
backdrop.fromTo('opacity', 0.4, 0);
wrapper.fromTo('translateY', '0%', '100%');
this.easing('cubic-bezier(.36,.66,.04,1)').duration(300).add(backdrop).add(wrapper);
};
return ActionSheetSlideOut;
}(Transition));
export { ActionSheetSlideOut };
var ActionSheetMdSlideIn = (function (_super) {
__extends(ActionSheetMdSlideIn, _super);
function ActionSheetMdSlideIn() {
return _super !== null && _super.apply(this, arguments) || this;
}
ActionSheetMdSlideIn.prototype.init = function () {
var ele = this.enteringView.pageRef().nativeElement;
var backdrop = new Animation(this.plt, ele.querySelector('ion-backdrop'));
var wrapper = new Animation(this.plt, ele.querySelector('.action-sheet-wrapper'));
backdrop.fromTo('opacity', 0.01, 0.26);
wrapper.fromTo('translateY', '100%', '0%');
this.easing('cubic-bezier(.36,.66,.04,1)').duration(400).add(backdrop).add(wrapper);
};
return ActionSheetMdSlideIn;
}(Transition));
export { ActionSheetMdSlideIn };
var ActionSheetMdSlideOut = (function (_super) {
__extends(ActionSheetMdSlideOut, _super);
function ActionSheetMdSlideOut() {
return _super !== null && _super.apply(this, arguments) || this;
}
ActionSheetMdSlideOut.prototype.init = function () {
var ele = this.leavingView.pageRef().nativeElement;
var backdrop = new Animation(this.plt, ele.querySelector('ion-backdrop'));
var wrapper = new Animation(this.plt, ele.querySelector('.action-sheet-wrapper'));
backdrop.fromTo('opacity', 0.26, 0);
wrapper.fromTo('translateY', '0%', '100%');
this.easing('cubic-bezier(.36,.66,.04,1)').duration(450).add(backdrop).add(wrapper);
};
return ActionSheetMdSlideOut;
}(Transition));
export { ActionSheetMdSlideOut };
var ActionSheetWpSlideIn = (function (_super) {
__extends(ActionSheetWpSlideIn, _super);
function ActionSheetWpSlideIn() {
return _super !== null && _super.apply(this, arguments) || this;
}
ActionSheetWpSlideIn.prototype.init = function () {
var ele = this.enteringView.pageRef().nativeElement;
var backdrop = new Animation(this.plt, ele.querySelector('ion-backdrop'));
var wrapper = new Animation(this.plt, ele.querySelector('.action-sheet-wrapper'));
backdrop.fromTo('opacity', 0.01, 0.16);
wrapper.fromTo('translateY', '100%', '0%');
this.easing('cubic-bezier(.36,.66,.04,1)').duration(400).add(backdrop).add(wrapper);
};
return ActionSheetWpSlideIn;
}(Transition));
export { ActionSheetWpSlideIn };
var ActionSheetWpSlideOut = (function (_super) {
__extends(ActionSheetWpSlideOut, _super);
function ActionSheetWpSlideOut() {
return _super !== null && _super.apply(this, arguments) || this;
}
ActionSheetWpSlideOut.prototype.init = function () {
var ele = this.leavingView.pageRef().nativeElement;
var backdrop = new Animation(this.plt, ele.querySelector('ion-backdrop'));
var wrapper = new Animation(this.plt, ele.querySelector('.action-sheet-wrapper'));
backdrop.fromTo('opacity', 0.1, 0);
wrapper.fromTo('translateY', '0%', '100%');
this.easing('cubic-bezier(.36,.66,.04,1)').duration(450).add(backdrop).add(wrapper);
};
return ActionSheetWpSlideOut;
}(Transition));
export { ActionSheetWpSlideOut };
//# sourceMappingURL=action-sheet-transitions.js.map
|
ricardo7227/DAW
|
Cliente/Codigo fuente/my-app-apk/node_modules/ionic-angular/components/action-sheet/action-sheet-transitions.js
|
JavaScript
|
gpl-3.0
| 5,337
|
/*
* uSelect iDownload
*
* Copyright © 2011-2013 Alessandro Guido
* Copyright © 2011-2013 Marco Palumbo
*
* This file is part of uSelect iDownload.
*
* uSelect iDownload is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* uSelect iDownload 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 uSelect iDownload. If not, see <http://www.gnu.org/licenses/>.
*/
function req_action_handler(request, sender, sendResponse) {
var urls = request['urls'];
var action = request['action'];
var tabId = request['tabId'];
if (action == 'window') {
/*
* TODO:
* - incognito window
* - selected
*/
chrome.windows.create({'url': urls});
} else {
switch (action) {
case 'download':
urls.forEach(function (url) {
console.log(url);
chrome.downloads.download({
'url': url,
});
});
chrome.tabs.create({
'url': 'chrome://downloads',
'selected': true,
'openerTabId': sender.tab.id,
});
break;
case 'tabs':
urls.forEach(function (url) {
chrome.tabs.create({
'url': url,
'selected': false,
'openerTabId': sender.tab.id,
});
});
break;
}
}
// The chrome.extension.onMessage listener must return true if you want to send a response after the listener returns
return true;
}
function req_inject_handler(request, sender, sendResponse) {
chrome.tabs.executeScript(sender.tab.id, {file: 'js/statemachine.js'}, function () {
chrome.tabs.executeScript(sender.tab.id, {file: 'js/overlay.js'}, function () {
if (sendResponse != null)
sendResponse();
});
});
// The chrome.extension.onMessage listener must return true if you want to send a response after the listener returns
return true;
}
/**
* Demultiplex requests using the '__req__' property of the request object
*/
chrome.extension.onMessage.addListener(function (request, sender, sendResponse) {
switch (request['__req__']) {
case 'inject':
return req_inject_handler(request, sender, sendResponse);
case 'action':
return req_action_handler(request, sender, sendResponse);
default:
console.log('Unknown message');
}
});
chrome.browserAction.onClicked.addListener(function (tab) {
chrome.tabs.sendMessage(tab.id, 'toggle');
});
|
lasagnacode/uselect-idownload
|
js/background.js
|
JavaScript
|
gpl-3.0
| 2,657
|
#include "event_threads.h"
#include "psx.h"
#include <lv2/process.h>
#include <sys/file.h>
#include <ppu-lv2.h>
#include <sys/stat.h>
#include <lv2/sysfs.h>
#include <sysutil/disc.h>
#include <sys/thread.h>
#include <sys/event_queue.h>
static sys_ppu_thread_t thread_id;
static sys_event_queue_t evQ_sd;
static sys_event_port_t portId;
static volatile int event_thread_working = 0;
static sys_event_queue_attr_t evQAttr_sd = { SYS_EVENT_QUEUE_FIFO, SYS_EVENT_QUEUE_PPU, "EvTh"};
static void Event_thread(void *a)
{
sys_event_t event_sd;
void (*func)(void * priv) = NULL;
while(1) {
if(sysEventQueueReceive(evQ_sd, &event_sd, 0) < 0) break;
if(event_sd.data_1 == 0x666) break;
if(event_sd.data_1 == 0x555) {
event_thread_working = 1;
func = (void *) event_sd.data_2;
if(func) func((void *) event_sd.data_3);
event_thread_working = 0;
}
}
sysThreadExit(0);
}
static int init = 0;
void event_threads_init()
{
if(init) return;
init = 1;
#ifdef PSDEBUG
int ret=
#endif
sysEventQueueCreate(&evQ_sd, &evQAttr_sd, 0xAAAA4242, 16);
#ifdef PSDEBUG
ret =
#endif
sysEventPortCreate(&portId, 1, 0xAAAA4242);
#ifdef PSDEBUG
ret =
#endif
sysEventPortConnectLocal(portId, evQ_sd);
sysThreadCreate(&thread_id, Event_thread, NULL, 992, 0x100000/4, THREAD_JOINABLE, "Event_thread");
}
void event_threads_finish()
{
u64 retval;
if(!init) return;
event_thread_send(0x666, 0, 0);
sysThreadJoin(thread_id, &retval);
sysEventPortDestroy(portId);
sysEventQueueDestroy(evQ_sd, 0);
init = 0;
}
int event_thread_send(u64 data0, u64 data1, u64 data2)
{
return sysEventPortSend(portId, data0, data1, data2);
}
void wait_event_thread()
{
while(event_thread_working) usleep(1000);
}
|
stephencapes/simplicity
|
source/event_threads.c
|
C
|
gpl-3.0
| 1,878
|
package com.jpblo19.me.coreapp.activities;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.EditText;
import com.jpblo19.me.coreapp.R;
import com.jpblo19.me.coreapp.json.decoders.DecodeHttpResponse;
import com.jpblo19.me.coreapp.json.encoders.EncodeDemoObject;
import com.jpblo19.me.coreapp.models.DemoObject;
import com.jpblo19.me.coreapp.models.HttpResponseObject;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* CORE 3
* Created by jpblo19 on 5/16/16.
* Updated 8/24/16.
*/
public class EndpointPostActivity extends CoreActivity {
private static String TAG_CLASS = "ENDPOINT POST ACTIVITY";
private Context ctx;
private ProgressDialog progress;
private EditText form_demoobject_title;
private EditText form_demoobject_value;
private EditText form_demoobject_descripcion;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_endpoint_post);
tools.Log_i("Instances Activity", TAG_CLASS);
ctx = this;
progress = new ProgressDialog(this);
form_demoobject_title = (EditText) findViewById(R.id.form_demoobject_title);
form_demoobject_value = (EditText) findViewById(R.id.form_demoobject_value);
form_demoobject_descripcion = (EditText) findViewById(R.id.form_demoobject_descripcion);
}
/////---[DIALOGS]-------------------------------------------------------------------------------
public void ConfirmationCancelSend(){
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_NEUTRAL:
//DO NOTHING
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(getString(R.string.dialog_canceltasksend));
builder.setNeutralButton(getResources().getString(R.string.options_accept), dialogClickListener);
builder.show();
}
/////---[ASYNC METHODS]-------------------------------------------------------------------------
private void ASYNC_POST_DEMO(final DemoObject this_item){
class asycn_method extends AsyncTask<String, String, Void> {
private boolean complete_fetch;
private HttpResponseObject content;
protected void forceCancel(){
tools.Log_e("ASYNC_POST_DEMO [[FORCE CANCEL EVENT]]", TAG_CLASS);
tools.networking.DestroyActualSocket();
this.cancel(true);
ConfirmationCancelSend();
}
@Override
protected void onCancelled(){
tools.Log_i("ASYNC_POST_DEMO [ONCANCEL] - END ASYNC",TAG_CLASS);
}
protected void onPreExecute(){
tools.Log_i("ASYNC_POST_DEMO [PRE] - GET DEMO",TAG_CLASS);
complete_fetch = false;
content = new HttpResponseObject();
progress.setTitle("Enviando");
progress.setMessage("favor esperar...");
progress.setCancelable(true);
progress.setIndeterminate(true);
progress.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
forceCancel();
}
});
progress.show();
tools.Log_i("ASYNC_POST_DEMO [PRE] - GET DEMO (END)", TAG_CLASS);
}
@Override
protected Void doInBackground(String... params) {
tools.Log_i("ASYNC_POST_DEMO [BACKGROUND] - GET DEMO",TAG_CLASS);
try{
String s_url = tools.getServer(PREF_MODE_AUX_SERVER)+"api/post_demoobjects";
JSONObject json = (new EncodeDemoObject()).Encode(this_item);
String fetch_response = tools.networking.POST_HTTP_REQUEST(s_url, json, 20, 35);
tools.Log_i("ASYNC_POST_DEMO [BACKGROUND] - Fetch Response: "+fetch_response,TAG_CLASS);
if(!fetch_response.equals(getString(R.string.FAIL_RESPONSE))){
content = (new DecodeHttpResponse()).Decode(fetch_response);
complete_fetch = true;
}
}catch (Exception e){
tools.Log_e("ASYNC_POST_DEMO [BACKGROUND] - Catch Error. Reason: " + e, TAG_CLASS);
}
tools.Log_i("ASYNC [BACKGROUND] - GET DEMO (END)",TAG_CLASS);
return null;
}
protected void onPostExecute(Void v){
tools.Log_i("ASYNC_POST_DEMO [POST] - GET DEMO",TAG_CLASS);
progress.dismiss();
if(complete_fetch){
tools.MakeToast(content.getInfo());
if(content.isSuccess()){
//DO SOMETHING WITH SUCCESS TRUE
}else{
//DO SOMETHING WITH SUCCESS FALSE
}
}else{
tools.MakeToast(getString(R.string.psvtxt_error_badconnection));
}
tools.Log_i("ASYNC_POST_DEMO [POST] - GET DEMO (END)",TAG_CLASS);
}
}
if(tools.networking.isNetworkAvailable()){
asycn_method am = new asycn_method();
try{
am.execute();
}catch (Exception e){
am.cancel(true);
}
}else{
tools.MakeToast(getString(R.string.psvtxt_error_nointernet_conn));
}
}
/////---[LAUNCHERS]-----------------------------------------------------------------------------
private void LaunchDemo(){
tools.Log_i("LAUNCH DEMO", TAG_CLASS);
DemoObject this_item = new DemoObject();
if(!form_demoobject_title.getText().equals("") && !form_demoobject_value.getText().equals("") && !form_demoobject_descripcion.getText().equals("")) {
try {
this_item.setTitle(form_demoobject_title.getText().toString());
this_item.setValue(Integer.parseInt(form_demoobject_value.getText().toString()));
this_item.setDescription(form_demoobject_descripcion.getText().toString());
ASYNC_POST_DEMO(this_item);
} catch (Exception e) {
tools.Log_e("Some error. Reason: " + e, TAG_CLASS);
tools.MakeToast(getResources().getString(R.string.psvtxt_error_badform));
}
}else{
tools.Log_e("Error: Empty fields", TAG_CLASS);
tools.MakeToast(getResources().getString(R.string.psvtxt_error_emptyform));
}
}
/////---[EVT ACTIONS----------------------------------------------------------------------------
public void evt_async_post(View view){
tools.Log_i("EVT ASYNC DEMO LAUNCH",TAG_CLASS);
LaunchDemo();
}
}
|
carnash-oz/RoRdroid_AndroidApp
|
app/src/main/java/com/jpblo19/me/coreapp/activities/EndpointPostActivity.java
|
Java
|
gpl-3.0
| 7,455
|
<?php
/**
* New const visibility sniff test file
*
* @package PHPCompatibility
*/
namespace PHPCompatibility\Tests\Classes;
use PHPCompatibility\Tests\BaseSniffTest;
/**
* New const visibility sniff test file
*
* @group newConstVisibility
* @group classes
*
* @covers \PHPCompatibility\Sniffs\Classes\NewConstVisibilitySniff
*
* @uses \PHPCompatibility\Tests\BaseSniffTest
* @package PHPCompatibility
* @author Juliette Reinders Folmer <phpcompatibility_nospam@adviesenzo.nl>
*/
class NewConstVisibilityUnitTest extends BaseSniffTest
{
/**
* testConstVisibility
*
* @dataProvider dataConstVisibility
*
* @param int $line The line number.
*
* @return void
*/
public function testConstVisibility($line)
{
$file = $this->sniffFile(__FILE__, '7.0');
$this->assertError($file, $line, 'Visibility indicators for class constants are not supported in PHP 7.0 or earlier.');
}
/**
* Data provider.
*
* @see testConstVisibility()
*
* @return array
*/
public function dataConstVisibility()
{
return array(
array(10),
array(11),
array(12),
array(20),
array(23),
array(24),
array(33),
array(34),
array(35),
);
}
/**
* testNoFalsePositives
*
* @dataProvider dataNoFalsePositives
*
* @param int $line The line number.
*
* @return void
*/
public function testNoFalsePositives($line)
{
$file = $this->sniffFile(__FILE__, '7.0');
$this->assertNoViolation($file, $line);
}
/**
* Data provider.
*
* @see testNoFalsePositives()
*
* @return array
*/
public function dataNoFalsePositives()
{
return array(
array(3),
array(7),
array(17),
array(30),
array(44),
array(48),
);
}
/**
* Verify no notices are thrown at all.
*
* @return void
*/
public function testNoViolationsInFileOnValidVersion()
{
$file = $this->sniffFile(__FILE__, '7.1');
$this->assertNoViolation($file);
}
}
|
universityofglasgow/moodle
|
local/codechecker/PHPCompatibility/Tests/Classes/NewConstVisibilityUnitTest.php
|
PHP
|
gpl-3.0
| 2,283
|
//
// Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010,
// 2011 Free Software Foundation, Inc
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#ifdef HAVE_CONFIG_H
#include "gnashconfig.h"
#endif
#include <vector>
#include <string>
#include <iostream>
#include "rc.h"
#include "gst/gst.h"
#include <gst/interfaces/propertyprobe.h>
namespace {
//get rc file for webcam selection
gnash::RcInitFile& rcfile = gnash::RcInitFile::getDefaultInstance();
}
class data {
public:
data();
gchar* deviceName;
gchar* deviceType;
gint deviceNumber;
gboolean duplicate;
};
data::data() {
deviceName = NULL;
deviceType = NULL;
deviceNumber = -1;
duplicate = false;
};
gint numDuplicates = 0;
size_t findVidDevs(std::vector<data*>& vidVect) {
gint numdevs = 0;
//vid test source
GstElement *element;
element = gst_element_factory_make ("videotestsrc", "vidtestsrc");
if (element == NULL) {
vidVect.push_back(NULL);
numdevs += 1;
} else {
vidVect.push_back(new data);
vidVect[numdevs]->deviceName = g_strdup_printf("videotestsrc");
vidVect[numdevs]->deviceType = g_strdup_printf("videotestsrc");
vidVect[numdevs]->deviceNumber = 0;
numdevs += 1;
}
//video4linux source
GstPropertyProbe *probe;
GValueArray *devarr;
element = NULL;
element = gst_element_factory_make ("v4lsrc", "v4lvidsrc");
probe = GST_PROPERTY_PROBE (element);
devarr = gst_property_probe_probe_and_get_values_name (probe, "device");
for (size_t i = 0; devarr != NULL && i < devarr->n_values; ++i) {
GValue *val;
gchar *dev_name = NULL;
val = g_value_array_get_nth (devarr, i);
g_object_set (element, "device", g_value_get_string (val), NULL);
gst_element_set_state (element, GST_STATE_PLAYING);
g_object_get (element, "device-name", &dev_name, NULL);
gst_element_set_state (element, GST_STATE_NULL);
if (strcmp(dev_name, "null") == 0) {
std::cout << "no v4l video sources found" << std::endl;
}
else {
vidVect.push_back(new data);
vidVect[numdevs]->deviceType = g_strdup_printf("v4lsrc");
vidVect[numdevs]->deviceName = dev_name;
vidVect[numdevs]->deviceNumber = numdevs;
numdevs += 1;
}
}
if (devarr) {
g_value_array_free (devarr);
}
//video4linux2 source
probe = NULL;
element = NULL;
devarr = NULL;
element = gst_element_factory_make ("v4l2src", "v4l2vidsrc");
probe = GST_PROPERTY_PROBE (element);
devarr = gst_property_probe_probe_and_get_values_name (probe, "device");
for (size_t i = 0; devarr != NULL && i < devarr->n_values; ++i) {
GValue *val;
gchar *dev_name = NULL;
val = g_value_array_get_nth (devarr, i);
g_object_set (element, "device", g_value_get_string (val), NULL);
gst_element_set_state (element, GST_STATE_PLAYING);
g_object_get (element, "device-name", &dev_name, NULL);
gst_element_set_state (element, GST_STATE_NULL);
if (strcmp(dev_name, "null") == 0) {
std::cout << "no v4l2 video sources found." << std::endl;
}
else {
vidVect.push_back(new data);
vidVect[numdevs]->deviceType = g_strdup_printf("v4l2src");
vidVect[numdevs]->deviceName = dev_name;
vidVect[numdevs]->deviceNumber = numdevs;
//mark duplicates (we like v4l2 sources more than v4l, so if
//they're both detected, mark the v4l source as a duplicate)
for (size_t g=1; g < (vidVect.size()-1); g++) {
if (strcmp(vidVect[numdevs]->deviceName,
vidVect[g]->deviceName) == 0) {
vidVect[g]->duplicate = true;
numDuplicates += 1;
}
}
numdevs += 1;
}
}
if (devarr) {
g_value_array_free (devarr);
}
return numdevs;
}
int main () {
//initialize gstreamer to probe for devs
gst_init(NULL, NULL);
size_t numdevs = 0;
std::vector<data*> vidVector;
int fromrc = rcfile.getWebcamDevice();
if (fromrc == -1) {
std::cout << std::endl
<< "Use this utility to set your desired default webcam device." << std::endl;
numdevs = findVidDevs(vidVector);
std::cout << std::endl
<< "INFO: these devices were ignored because they are supported by both" << std::endl
<< "video4linux and video4linux2:" << std::endl << std::endl;
for (size_t i = 0; i < numdevs; ++i) {
if (vidVector[i]->duplicate == true) {
std::cout << " " << vidVector[i]->deviceName
<< " (" << vidVector[i]->deviceType << ")" << std::endl;
}
}
std::cout << std::endl
<< "Gnash interacts with v4l2 sources better than v4l sources, thus the" << std::endl
<< "v4l sources will not be printed in the list below." << std::endl
<< std::endl
<< "Found " << (numdevs - numDuplicates)
<< " video devices: " << std::endl << std::endl;
gint counter = 0;
for (size_t i = 0; i < numdevs; ++i)
{
if (i == 0 && (vidVector[i] != 0)) {
std::cout << " " << i
<< ". Video Test Source (videotestsrc)" << std::endl;
counter++;
} else if (i == 0 && (vidVector[i] == 0)) {
std::cout << "no test video device available";
} else {
if (vidVector[i]->duplicate != true) {
std::cout << " " << counter << ". "
<< vidVector[i]->deviceName
<< " (" << vidVector[i]->deviceType << ")" << std::endl;
counter++;
}
}
}
//prompt user for device selection
int dev_select = -1;
std::string fromCin;
do {
dev_select = -1;
std::cout << std::endl
<< "Choose the device you would like to use (0-"
<< (numdevs - numDuplicates - 1) << "): ";
std::cin >> fromCin;
if (fromCin.size() != 1) {
dev_select = -1;
} else if (fromCin[0] == '0') {
dev_select = 0;
} else {
dev_select = atoi(fromCin.c_str());
}
if ((dev_select < 0) || (dev_select > ((int)numdevs - numDuplicates - 1))) {
std::cout << "You must make a valid device selection" << std::endl;
}
} while ((dev_select < 0) || (dev_select > ((int)numdevs - numDuplicates - 1)));
std::cout << std::endl
<< "To select this camera, add this line to your gnashrc file:" << std::endl
<< "set webcamDevice "
<< (vidVector[dev_select + numDuplicates]->deviceNumber) << std::endl;
} else {
numdevs = findVidDevs(vidVector);
if ((size_t)fromrc <= (vidVector.size() - 1)) {
std::cout << std::endl
<< "The gnashrc file reports default webcam is set to:" << std::endl
<< vidVector[fromrc]->deviceName
<< " (" << vidVector[fromrc]->deviceType << ")" << std::endl
<< "To change this setting, delete the 'set webcamDevice' line" << std::endl
<< "from your gnashrc file and re-run this program." << std::endl << std::endl;
} else {
std::cout << std::endl
<< "You have an invalid webcam chosen in your gnashrc file." << std::endl
<< "Try reattaching the device or deleting the value from gnashrc" << std::endl
<< "and running this program again" << std::endl;
}
}
return 0;
}
|
jlopez/gnash
|
utilities/findwebcams.cpp
|
C++
|
gpl-3.0
| 8,729
|
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
| -------------------------------------------------------------------
| AUTO-LOADER
| -------------------------------------------------------------------
| This file specifies which systems should be loaded by default.
|
| In order to keep the framework as light-weight as possible only the
| absolute minimal resources are loaded by default. For example,
| the database is not connected to automatically since no assumption
| is made regarding whether you intend to use it. This file lets
| you globally define which systems you would like loaded with every
| request.
|
| -------------------------------------------------------------------
| Instructions
| -------------------------------------------------------------------
|
| These are the things you can load automatically:
|
| 1. Packages
| 2. Libraries
| 3. Helper files
| 4. Custom config files
| 5. Language files
| 6. Models
|
*/
/*
| -------------------------------------------------------------------
| Auto-load Packges
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['packages'] = array(APPPATH.'third_party', '/usr/local/shared');
|
*/
$autoload['packages'] = array();
/*
| -------------------------------------------------------------------
| Auto-load Libraries
| -------------------------------------------------------------------
| These are the classes located in the system/libraries folder
| or in your application/libraries folder.
|
| Prototype:
|
| $autoload['libraries'] = array('database', 'session', 'xmlrpc');
*/
$autoload['libraries'] = array(
'session');
/*
| -------------------------------------------------------------------
| Auto-load Helper Files
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['helper'] = array('url', 'file');
*/
$autoload['helper'] = array(
'url');
/*
| -------------------------------------------------------------------
| Auto-load Config files
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['config'] = array('config1', 'config2');
|
| NOTE: This item is intended for use ONLY if you have created custom
| config files. Otherwise, leave it blank.
|
*/
$autoload['config'] = array();
/*
| -------------------------------------------------------------------
| Auto-load Language files
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['language'] = array('lang1', 'lang2');
|
| NOTE: Do not include the "_lang" part of your file. For example
| "codeigniter_lang.php" would be referenced as array('codeigniter');
|
*/
$autoload['language'] = array();
/*
| -------------------------------------------------------------------
| Auto-load Models
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['model'] = array('model1', 'model2');
|
*/
$autoload['model'] = array();
/* End of file autoload.php */
/* Location: ./application/config/autoload.php */
|
warmpaper/Umbrella-Revolution-Inventory-Management
|
html/ur_inventory/application/config/autoload.php
|
PHP
|
gpl-3.0
| 3,112
|
/*
* FinTP - Financial Transactions Processing Application
* Copyright (C) 2013 Business Information Systems (Allevo) S.R.L.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* or contact Allevo at : 031281 Bucuresti, 23C Calea Vitan, Romania,
* phone +40212554577, office@allevo.ro <mailto:office@allevo.ro>, www.allevo.ro.
*/
#ifndef EXTENSIONHASH_H
#define EXTENSIONHASH_H
#include <xalanc/Include/PlatformDefinitions.hpp>
#include <xalanc/XPath/Function.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include <xalanc/XalanTransformer/XalanTransformer.hpp>
#include <xalanc/XPath/XObjectFactory.hpp>
#include "../DllMain.h"
XALAN_USING_XALAN(Function)
XALAN_USING_XALAN(XPathExecutionContext)
XALAN_USING_XALAN(XalanDOMString)
XALAN_USING_XALAN(XalanNode)
//XALAN_USING_XALAN(StaticStringToDOMString)
XALAN_USING_XALAN(XObjectPtr)
#ifdef XALAN_1_9
XALAN_USING_XALAN(MemoryManagerType)
#endif
namespace FinTP
{
class ExportedObject FunctionHash : public Function
{
public:
virtual XObjectPtr execute( XPathExecutionContext& executionContext, XalanNode* context, const XObjectArgVectorType& args,const LocatorType* locator ) const;
#ifdef XALAN_1_9
#if defined( XALAN_NO_COVARIANT_RETURN_TYPE )
virtual Function* clone( MemoryManagerType& theManager ) const;
#else
virtual FunctionHash* clone( MemoryManagerType& theManager ) const;
#endif
protected:
const XalanDOMString& getError( XalanDOMString& theResult ) const;
#else
#if defined( XALAN_NO_COVARIANT_RETURN_TYPE )
virtual Function* clone() const;
#else
virtual FunctionHash* clone() const;
#endif
protected:
const XalanDOMString getError() const;
#endif
private:
// The assignment and equality operators are not implemented...
FunctionHash& operator=( const FunctionHash& );
bool operator==( const FunctionHash& ) const;
};
}
#endif // EXTENSIONHASH_H
|
FinTP/fintp_base
|
src/XSLT/ExtensionHash.h
|
C
|
gpl-3.0
| 2,471
|
/*
Stylom: A command line utility for stylometric text analysis
Copyright (C) 2013 Bob Mottram
fuzzgun@gmail.com
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "stylom.h"
int read_text_from_file(char ** text, char * filename)
{
FILE * fp;
char linestr[4096];
char * retval = NULL;
int string_length = 0, i, ctr=0;
fp = fopen(filename,"r");
if (fp != NULL) {
/* determine the length of the text needed */
while (!feof(fp)) {
retval = fgets(linestr,4095,fp);
if (retval != NULL) {
string_length += strlen(linestr);
}
}
fclose(fp);
/* if nothing was read */
if (string_length == 0) {
printf("Warning: nothing loaded\n");
return 0;
}
/* allocate memory for the text */
(*text) = (char*)malloc((string_length+1)*sizeof(char));
if (!(*text)) {
printf("read_text_from_file: Unable to allocate %d bytes\n",
string_length+1);
return 0;
}
/* read the text into the array */
fp = fopen(filename,"r");
if (!fp) {
printf("read_text_from_file: Unable to load %s\n",filename);
free(*text);
return 0;
}
while (!feof(fp)) {
retval = fgets(linestr,4095,fp);
if (retval != NULL) {
for (i = 0; i < strlen(linestr); i++) {
(*text)[ctr++] = linestr[i];
}
}
}
fclose(fp);
/* append string terminator */
(*text)[ctr] = 0;
return 1;
}
return 0;
}
/* frequencies of pairs of letters */
static void letter_pair_frequency(char * text, float histogram[])
{
int i, index, x, y;
float max = 1;
/* clear the histogram */
memset((void*)histogram, '\0',
MAX_LETTERS*MAX_LETTERS*sizeof(float));
/* count letter pairs */
for (i = strlen(text)-4; i >= 0; i--) {
x = (int)text[i];
if ((x >= 0) && (x < MAX_LETTERS)) {
if ((x!=10) && (x!=13)) {
/* first frequency */
y = (int)text[i+1];
if ((y >= 0) && (y < MAX_LETTERS)) {
if ((y!=10) && (y!=13)) {
index = (y*MAX_LETTERS) + x;
histogram[index] += 1.0f;
if (histogram[index] > max) {
max = histogram[index];
}
}
}
/* second frequency */
y = (int)text[i+2];
if ((y >= 0) && (y < MAX_LETTERS)) {
if ((y!=10) && (y!=13)) {
index = (y*MAX_LETTERS) + x;
histogram[index] += 0.5f;
if (histogram[index] > max) {
max = histogram[index];
}
}
}
/* third frequency */
y = (int)text[i+3];
if ((y >= 0) && (y < MAX_LETTERS)) {
if ((y!=10) && (y!=13)) {
index = (y*MAX_LETTERS) + x;
histogram[index] += 0.2f;
if (histogram[index] > max) {
max = histogram[index];
}
}
}
}
}
}
/* normalise */
for (i = 0; i < MAX_LETTERS*MAX_LETTERS; i++) {
if (histogram[i] > 0) {
histogram[i] /= max;
}
}
}
/* creates a histogram based upon the first letters
of successive words */
static void word_pair_frequency(char * text, float histogram[])
{
int i, index, x, y, state=1;
float max = 1;
int length = strlen(text)-1;
char prev_ch = ' ';
char prev_ch2 = ' ';
char prev_ch3 = ' ';
/* clear the histogram */
memset((void*)histogram, '\0', MAX_LETTERS*MAX_LETTERS*sizeof(float));
for (i = 0; i < length; i++) {
if (state == 0) {
/* look for the start of a word */
if (((text[i]>='a') && (text[i]<='z')) ||
((text[i]>='A') && (text[i]<='Z'))) {
/* change state to look for the end of a word */
state = 1;
if ((prev_ch != ' ') &&
(prev_ch2 != ' ') &&
(prev_ch3 != ' ')) {
x = (int)text[i];
if ((x >= 0) && (x < MAX_LETTERS)) {
/* first frequency */
y = (int)prev_ch;
if ((y >= 0) && (y < MAX_LETTERS)) {
index = (y*MAX_LETTERS) + x;
histogram[index] += 1.0f;
if (histogram[index] > max) {
max = histogram[index];
}
}
/* second frequency */
y = (int)prev_ch2;
if ((y >= 0) && (y < MAX_LETTERS)) {
index = (y*MAX_LETTERS) + x;
histogram[index] += 0.5f;
if (histogram[index] > max) {
max = histogram[index];
}
}
/* third frequency */
y = (int)prev_ch3;
if ((y >= 0) && (y < MAX_LETTERS)) {
index = (y*MAX_LETTERS) + x;
histogram[index] += 0.2f;
if (histogram[index] > max) {
max = histogram[index];
}
}
}
}
prev_ch3 = prev_ch2;
prev_ch2 = prev_ch;
prev_ch = text[i];
}
}
if (state == 1) {
/* look for the end of a word */
if (word_terminator(text[i],text[i+1])==1) {
/* change state to look for the start of a word */
state = 0;
}
}
}
/* normalise */
for (i = 0; i < MAX_LETTERS*MAX_LETTERS; i++) {
if (histogram[i] > 0) {
histogram[i] /= max;
}
}
}
/* creates a letter fequency histogram */
static void letter_frequency(char * text, float histogram[])
{
int i, index;
float max = 1;
/* clear the histogram */
memset((void*)histogram, '\0', MAX_LETTERS*sizeof(float));
/* count letters */
for (i = strlen(text)-1; i >= 0; i--) {
index = (int)text[i];
if ((index >= 0) && (index < MAX_LETTERS)) {
if ((index!=10) && (index!=13)) {
histogram[index]++;
}
}
}
/* find the maximum frequency */
for (i = 0; i < MAX_LETTERS; i++) {
if (histogram[i] > max) max = histogram[i];
}
/* normalise */
for (i = 0; i < MAX_LETTERS; i++) {
histogram[i] /= max;
}
}
/* returns an estimate of the number of words within a given region */
static int words_count_region(char * text, int start_pos, int end_pos)
{
int i,words=0;
if (end_pos-start_pos < 2) return 0;
for (i = start_pos; i < end_pos-1; i++) {
if (word_terminator(text[i],text[i+1])!=0) {
words++;
}
}
return words;
}
/* create a histogram of word lengths */
static void word_length_histogram(char * text, float * histogram)
{
int i, prev_pos=0,word_length,max=1;
int length = strlen(text)-1;
if (strlen(text) < 2) return;
/* clear the histogram */
memset((void*)histogram, '\0', MAX_WORD_LENGTH*sizeof(float));
for (i = 0; i < length; i++) {
if (word_terminator(text[i], text[i+1])!=0) {
word_length = (i+1) - prev_pos;
if ((word_length > 0) && (word_length < MAX_WORD_LENGTH)) {
histogram[word_length]++;
if (histogram[word_length] > max) {
max = histogram[word_length];
}
}
prev_pos = i+1;
}
}
/* normalise */
for (i = 0; i < MAX_WORD_LENGTH; i++) {
histogram[i] /= max;
}
}
/* returns a histogram of sentence lengths */
static void sentence_length_histogram(char * text, float histogram[])
{
int i, start_pos=0, end_pos, words, max=1;
int length = strlen(text);
/* clear the histogram */
memset((void*)histogram, '\0',
MAX_WORDS_PER_SENTENCE*sizeof(float));
for (i = 0; i < length; i++) {
if ((text[i]=='.') || (i==length-1)) {
end_pos = i;
words = words_count_region(text, start_pos, end_pos);
if ((words > 0) && (words < MAX_WORDS_PER_SENTENCE)) {
histogram[words] = histogram[words] + 1;
if (histogram[words] > max) {
max = histogram[words];
}
}
start_pos = end_pos+1;
}
}
/* normalise */
for (i = 0; i < MAX_WORDS_PER_SENTENCE; i++) {
histogram[i] /= max;
}
}
/* returns a histogram of paragraph lengths */
static void paragraph_length_histogram(char * text, float histogram[])
{
int i, start_pos=0, end_pos, words, max=1;
int sentences=0, eol_ctr=0;
int length = strlen(text);
/* clear the histogram */
memset((void*)histogram, '\0',
MAX_WORDS_PER_SENTENCE*sizeof(float));
for (i = 0; i < length; i++) {
if (text[i]==13) {
eol_ctr++;
if (eol_ctr > 1) {
if ((sentences > 0) &&
(sentences < MAX_SENTENCES_PER_PARAGRAPH)) {
histogram[sentences] = histogram[sentences] + 1;
if (histogram[sentences] > max) {
max = histogram[sentences];
}
}
eol_ctr = 0;
sentences = 0;
}
}
if ((text[i]=='.') || (i==length-1)) {
end_pos = i;
words = words_count_region(text, start_pos, end_pos);
if ((words > 0) && (words < MAX_WORDS_PER_SENTENCE)) {
sentences++;
eol_ctr = 0;
}
start_pos = end_pos+1;
}
}
/* normalise */
for (i = 0; i < MAX_WORDS_PER_SENTENCE; i++) {
histogram[i] /= max;
}
}
/* finds a sentence of the given length and returns the line number.
Returns -1 if no sentence of the given length is found */
static int find_sentence_of_length(char * text,
int sentence_length,
int * found_start,
int * found_end)
{
int i, start_pos=0, end_pos, line_number = 0;
int length = strlen(text);
for (i = 0; i < length; i++) {
if ((text[i]=='.') || (i==length-1)) {
end_pos = i;
if (words_count_region(text, start_pos, end_pos) ==
sentence_length) {
*found_start = start_pos;
*found_end = end_pos;
return line_number;
}
start_pos = end_pos+1;
}
if (text[i]==13) line_number++;
}
return -1;
}
/* compares sentence histograms and suggests changes to make f1
more similar to f2 */
static int recommend_sentence_change(char * f1_text,
stylom_fingerprint * f1,
stylom_fingerprint * f2,
int * sentence_start,
int * sentence_end,
int * add_words)
{
int i,j,length=0,length2=0,length3=0,line_number=-1;
const int range = 3;
float diff[2],max_diff=0,max;
/* for every number of words */
for (i = 7; i < MAX_WORDS_PER_SENTENCE; i++) {
/* how many more instances are there in f2 than f1 ? */
diff[0] = f2->sentence_length_histogram[i] -
f1->sentence_length_histogram[i];
/* if this the maximum difference ? */
if (diff[0]*diff[0] > max_diff) {
max = 0;
length2 = -1;
/* search within a range of a few words */
for (j = -range+1; j < range; j++) {
if (range == 0) continue;
/* range check */
if ((i+j < 1) ||
(i+j >= MAX_WORDS_PER_SENTENCE)) continue;
/* how many more instances are there in f2 than f1 ? */
diff[1] = f2->sentence_length_histogram[i+j] -
f1->sentence_length_histogram[i+j];
/* if this is the biggest difference */
if (diff[1]*diff[1] > max) {
/* ensure that the differences are
of opposite sign */
if ((diff[0] < 0) && (diff[1] > 0)) {
/* fewer instances in f1 than f2 */
max = diff[1]*diff[1];
length2 = i+j;
}
if ((diff[0] > 0) && (diff[1] < 0)) {
/* more instances in f1 than f2 */
max = diff[1]*diff[1];
length2 = i+j;
}
}
}
if (length2 > -1) {
max_diff = diff[0]*diff[0];
length = i;
length3 = length2;
}
}
}
if (length == 0) return -1;
line_number = find_sentence_of_length(f1_text, length,
sentence_start,
sentence_end);
if (line_number > -1) {
*add_words = length3-length;
}
return line_number;
}
/* returns a fingerprint for the given text */
void get_fingerprint(char * name, char * text,
stylom_fingerprint * fingerprint)
{
/* set the author name */
sprintf(fingerprint->name,"%s",name);
/* calculate letter frequency histogram */
letter_frequency(text, fingerprint->letter_histogram);
/* calculate letter pair histogram */
letter_pair_frequency(text, fingerprint->letter_pair_histogram);
/* calculate word pair histogram */
word_pair_frequency(text, fingerprint->word_pair_histogram);
/* calculate sentence length histogram */
sentence_length_histogram(text,
fingerprint->sentence_length_histogram);
/* calculate paragraph length histogram */
paragraph_length_histogram(text,
fingerprint->paragraph_length_histogram);
/* calculate word length histogram */
word_length_histogram(text, fingerprint->word_length_histogram);
/* create a dictionary */
create_dictionary(text, fingerprint->dictionary);
/* create vocabulary */
create_vocabulary(text, fingerprint->vocabulary,
fingerprint->vocabulary_frequency);
}
/* convert text extracted from xml into an array of floats */
static void string_to_float_array(char * text, float * floatarray)
{
int i, index=0, ctr = 0, length = strlen(text);
char value_str[256];
for (i = 0; i < length; i++) {
if (((text[i] == ' ') ||
(text[i] == 13) ||
(i == length-1)) && (ctr > 0)) {
value_str[ctr] = 0;
floatarray[index++] = atof(value_str);
ctr = 0;
}
else {
if (ctr < 255) {
if (((text[i]>='0') && (text[i]<='9')) ||
(text[i]=='.') || (text[i]==',')) {
value_str[ctr++] = text[i];
}
}
else {
printf("Float array value too big\n");
break;
}
}
}
}
/* reads an XML file and updates a fingerprint */
int read_fingerprint_xml(stylom_fingerprint * fingerprint, FILE * fp)
{
char linestr[256];
int i, j, state = 0, section_ctr=0;
char section[256], text_body[11*MAX_LETTERS*MAX_LETTERS];
char text_vocab[26*MAX_VOCAB_SIZE*MAX_WORD_LENGTH];
int text_body_ctr = 0;
int active = 0, data_type = 0;
int retval = 0;
/* types of data within the xml file */
enum {
DATA_NAME = 1,
DATA_LETTER_HISTOGRAM,
DATA_LETTER_PAIR_HISTOGRAM,
DATA_WORD_PAIR_HISTOGRAM,
DATA_SENTENCE_HISTOGRAM,
DATA_PARAGRAPH_HISTOGRAM,
DATA_WORD_HISTOGRAM,
DATA_DICTIONARY,
DATA_VOCABULARY,
DATA_VOCABULARY_FREQUENCY
};
while (!feof(fp)) {
if (fgets(linestr, 255, fp) != NULL ) {
for (i = 0; i < strlen(linestr); i++) {
switch (state) {
case 0: {
if (linestr[i] == '<') {
state++;
section_ctr=0;
}
break;
}
case 1: {
if (linestr[i] != '>') {
if (section_ctr < 255) {
section[section_ctr++] = linestr[i];
}
else {
printf("Section too long\n");
}
}
else {
section[section_ctr] = 0;
section_ctr = 0;
text_body_ctr = 0;
state = 0;
if ((strcmp(section,"fingerprint")==0) &&
(active == 0)) {
active = 1;
}
if ((strcmp(section,"/fingerprint")==0) &&
(active == 1)) {
active = 0;
retval = 1;
}
if (((strcmp(section,"name")==0) ||
(strcmp(section,"Name")==0)) &&
(active == 1)) {
data_type = DATA_NAME;
state = 2;
}
if (((strcmp(section,"letters")==0) ||
(strcmp(section,"Letters")==0)) &&
(active == 1)) {
data_type = DATA_LETTER_HISTOGRAM;
state = 2;
}
if (((strcmp(section,"letterpairs")==0) ||
(strcmp(section,"LetterPairs")==0)) &&
(active == 1)) {
data_type = DATA_LETTER_PAIR_HISTOGRAM;
state = 2;
}
if (((strcmp(section,"wordpairs")==0) ||
(strcmp(section,"WordPairs")==0)) &&
(active == 1)) {
data_type = DATA_WORD_PAIR_HISTOGRAM;
state = 2;
}
if (((strcmp(section,"sentencelength")==0) ||
(strcmp(section,"SentenceLength")==0)) &&
(active == 1)) {
data_type = DATA_SENTENCE_HISTOGRAM;
state = 2;
}
if (((strcmp(section,"paragraphlength")==0) ||
(strcmp(section,"paragraphLength")==0)) &&
(active == 1)) {
data_type = DATA_PARAGRAPH_HISTOGRAM;
state = 2;
}
if (((strcmp(section,"wordlength")==0) ||
(strcmp(section,"WordLength")==0)) &&
(active == 1)) {
data_type = DATA_WORD_HISTOGRAM;
state = 2;
}
if (((strcmp(section,"dictionary")==0) ||
(strcmp(section,"Dictionary")==0)) &&
(active == 1)) {
data_type = DATA_DICTIONARY;
state = 2;
}
if (((strcmp(section,"vocabulary")==0) ||
(strcmp(section,"vocabulary")==0)) &&
(active == 1)) {
data_type = DATA_VOCABULARY;
state = 2;
}
if (((strcmp(section,"vocabularyfreq")==0) ||
(strcmp(section,"vocabularyfreq")==0)) &&
(active == 1)) {
data_type = DATA_VOCABULARY_FREQUENCY;
state = 2;
}
}
break;
}
case 2: {
if (linestr[i] == '<') {
state = 3;
section_ctr = 0;
text_body[text_body_ctr] = 0;
}
else {
if ((data_type != DATA_VOCABULARY) &&
(data_type != DATA_VOCABULARY_FREQUENCY)) {
if (text_body_ctr <
11*MAX_LETTERS*MAX_LETTERS) {
text_body[text_body_ctr++] = linestr[i];
}
else {
printf("text_body too long\n");
}
}
else {
if (text_body_ctr <
26*MAX_VOCAB_SIZE*MAX_WORD_LENGTH) {
text_vocab[text_body_ctr++] = linestr[i];
}
else {
printf("text_vocab too long\n");
}
}
}
break;
}
case 3: {
if (linestr[i] != '>') {
if (section_ctr < 255) {
section[section_ctr++] = linestr[i];
}
else {
printf("Final section too long\n");
}
}
else {
section[section_ctr] = 0;
switch(data_type) {
case DATA_NAME: {
assert(strlen(text_body)<255);
for (j = 0; j < strlen(text_body); j++) {
fingerprint->name[j] = text_body[j];
}
fingerprint->name[j] = 0;
break;
}
case DATA_LETTER_HISTOGRAM: {
string_to_float_array(text_body,
fingerprint->letter_histogram);
break;
}
case DATA_LETTER_PAIR_HISTOGRAM: {
string_to_float_array(text_body,
fingerprint->letter_pair_histogram);
break;
}
case DATA_WORD_PAIR_HISTOGRAM: {
string_to_float_array(text_body,
fingerprint->word_pair_histogram);
break;
}
case DATA_SENTENCE_HISTOGRAM: {
string_to_float_array(text_body,
fingerprint->sentence_length_histogram);
break;
}
case DATA_PARAGRAPH_HISTOGRAM: {
string_to_float_array(text_body,
fingerprint->paragraph_length_histogram);
break;
}
case DATA_WORD_HISTOGRAM: {
string_to_float_array(text_body,
fingerprint->word_length_histogram);
break;
}
case DATA_DICTIONARY: {
string_to_float_array(text_body,
fingerprint->dictionary);
break;
}
case DATA_VOCABULARY: {
text_vocab[text_body_ctr] = 0;
parse_vocabulary_string(text_vocab,
fingerprint->vocabulary);
break;
}
case DATA_VOCABULARY_FREQUENCY: {
text_vocab[text_body_ctr] = 0;
parse_vocabulary_frequency_string(text_vocab,
fingerprint->vocabulary,
fingerprint->vocabulary_frequency);
break;
}
}
data_type = 0;
state = 0;
}
break;
}
}
}
}
}
return retval;
}
/* save the given fingerprint to an XML file */
void write_fingerprint_xml(stylom_fingerprint * fingerprint, FILE * fp)
{
int i,ctr=0;
const int max_cols = 65;
fprintf(fp,"%s","<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
fprintf(fp,"%s","<fingerprint>\n");
fprintf(fp," <name>%s</name>\n",fingerprint->name);
fprintf(fp,"%s"," <letters>\n ");
for (i = 0; i < MAX_LETTERS; i++) {
if (fingerprint->letter_histogram[i]==0) {
fprintf(fp,"%s ", "0");
ctr+=2;
}
else {
fprintf(fp,"%.8f ",fingerprint->letter_histogram[i]);
ctr+=10;
}
if (ctr > max_cols) {
fprintf(fp,"%s","\n ");
ctr=0;
}
}
fprintf(fp,"%s","\n </letters>\n");
fprintf(fp,"%s"," <letterpairs>\n ");
ctr=0;
for (i = 0; i < MAX_LETTERS*MAX_LETTERS; i++) {
if (fingerprint->letter_pair_histogram[i]==0) {
fprintf(fp,"%s ", "0");
ctr += 2;
}
else {
fprintf(fp,"%.8f ",fingerprint->letter_pair_histogram[i]);
ctr += 10;
}
if (ctr > max_cols) {
fprintf(fp,"%s","\n ");
ctr=0;
}
}
fprintf(fp,"%s","\n </letterpairs>\n");
fprintf(fp,"%s"," <wordpairs>\n ");
ctr=0;
for (i = 0; i < MAX_LETTERS*MAX_LETTERS; i++) {
if (fingerprint->word_pair_histogram[i]==0) {
fprintf(fp,"%s ", "0");
ctr += 2;
}
else {
fprintf(fp,"%.8f ",fingerprint->word_pair_histogram[i]);
ctr += 10;
}
if (ctr > max_cols) {
fprintf(fp,"%s","\n ");
ctr=0;
}
}
fprintf(fp,"%s","\n </wordpairs>\n");
fprintf(fp,"%s"," <sentencelength>\n ");
ctr=0;
for (i = 0; i < MAX_WORDS_PER_SENTENCE; i++) {
if (fingerprint->sentence_length_histogram[i]==0) {
fprintf(fp,"%s ", "0");
ctr += 2;
}
else {
fprintf(fp,"%.8f ",fingerprint->sentence_length_histogram[i]);
ctr += 10;
}
if (ctr > max_cols) {
fprintf(fp,"%s","\n ");
ctr=0;
}
}
fprintf(fp,"%s","\n </sentencelength>\n");
fprintf(fp,"%s"," <paragraphlength>\n ");
ctr=0;
for (i = 0; i < MAX_SENTENCES_PER_PARAGRAPH; i++) {
if (fingerprint->paragraph_length_histogram[i]==0) {
fprintf(fp,"%s ", "0");
ctr += 2;
}
else {
fprintf(fp,"%.8f ",fingerprint->paragraph_length_histogram[i]);
ctr += 10;
}
if (ctr > max_cols) {
fprintf(fp,"%s","\n ");
ctr=0;
}
}
fprintf(fp,"%s","\n </paragraphlength>\n");
fprintf(fp,"%s"," <wordlength>\n ");
ctr=0;
for (i = 0; i < MAX_WORD_LENGTH; i++) {
if (fingerprint->word_length_histogram[i]==0) {
fprintf(fp,"%s ", "0");
ctr += 2;
}
else {
fprintf(fp,"%.8f ",fingerprint->word_length_histogram[i]);
ctr += 10;
}
if (ctr > max_cols) {
fprintf(fp,"%s","\n ");
ctr=0;
}
}
fprintf(fp,"%s","\n </wordlength>\n");
fprintf(fp,"%s"," <dictionary>\n ");
ctr=0;
for (i = 0; i < DICTIONARY_SIZE; i++) {
if (fingerprint->dictionary[i]==0) {
fprintf(fp,"%s ", "0");
ctr += 2;
}
else {
fprintf(fp,"%.8f ",fingerprint->dictionary[i]);
ctr += 10;
}
if (ctr > max_cols) {
fprintf(fp,"%s","\n ");
ctr=0;
}
}
fprintf(fp,"%s","\n </dictionary>\n");
write_vocabulary_xml(fingerprint->vocabulary,
fingerprint->vocabulary_frequency,
fp);
fprintf(fp,"%s","</fingerprint>\n");
}
int fingerprints_identical(stylom_fingerprint * f1,
stylom_fingerprint * f2,
int include_vocabulary)
{
int i,j;
float diff;
const float max_diff = 0.00001f;
if (strcmp(f1->name,f2->name)!=0) {
return -1;
}
for (i = 0; i < MAX_LETTERS; i++) {
diff = fabs(f1->letter_histogram[i] -
f2->letter_histogram[i]);
if (diff > max_diff) {
return -2;
}
}
for (i = 0; i < MAX_LETTERS*MAX_LETTERS; i++) {
diff = fabs(f1->letter_pair_histogram[i] -
f2->letter_pair_histogram[i]);
if (diff > max_diff) {
return -3;
}
diff = fabs(f1->word_pair_histogram[i] -
f2->word_pair_histogram[i]);
if (diff > max_diff) {
return -4;
}
}
for (i = 0; i < MAX_WORDS_PER_SENTENCE; i++) {
diff = fabs(f1->sentence_length_histogram[i] -
f2->sentence_length_histogram[i]);
if (diff > max_diff) {
return -5;
}
}
for (i = 0; i < MAX_SENTENCES_PER_PARAGRAPH; i++) {
diff = fabs(f1->paragraph_length_histogram[i] -
f2->paragraph_length_histogram[i]);
if (diff > max_diff) {
return -6;
}
}
for (i = 0; i < MAX_WORD_LENGTH; i++) {
diff = fabs(f1->word_length_histogram[i] -
f2->word_length_histogram[i]);
if (diff > max_diff) {
return -7;
}
}
for (i = 0; i < DICTIONARY_SIZE; i++) {
diff = fabs(f1->dictionary[i] -
f2->dictionary[i]);
if (diff > max_diff) {
return -8;
}
}
if (include_vocabulary > 0) {
for (i = 0; i < 26; i++) {
for (j = 0; j < MAX_VOCAB_SIZE; j++) {
if (strcmp(&f1->vocabulary[VINDEX(i,j)],
&f2->vocabulary[VINDEX(i,j)])!=0) {
return -9;
}
diff = fabs(f1->vocabulary_frequency[FINDEX(i,j)] -
f2->vocabulary_frequency[FINDEX(i,j)]);
if (diff > max_diff) {
return -10;
}
}
}
}
return 0;
}
/* clears the given fingerprint */
static void fingerprint_clear(stylom_fingerprint * f)
{
f->name[0] = 0;
memset((void*)f->letter_histogram,'\0',
MAX_LETTERS*sizeof(float));
memset((void*)f->letter_pair_histogram,'\0',
MAX_LETTERS*MAX_LETTERS*sizeof(float));
memset((void*)f->word_pair_histogram,'\0',
MAX_LETTERS*MAX_LETTERS*sizeof(float));
memset((void*)f->sentence_length_histogram,'\0',
MAX_WORDS_PER_SENTENCE*sizeof(float));
memset((void*)f->paragraph_length_histogram,'\0',
MAX_SENTENCES_PER_PARAGRAPH*sizeof(float));
memset((void*)f->word_length_histogram,'\0',
MAX_WORD_LENGTH*sizeof(float));
memset((void*)f->dictionary,'\0',
DICTIONARY_SIZE*sizeof(float));
}
/* adds one fingerprint to another */
static void fingerprint_sum(stylom_fingerprint * source,
stylom_fingerprint * dest)
{
int i;
for (i = 0; i < MAX_LETTERS; i++) {
dest->letter_histogram[i] +=
source->letter_histogram[i];
}
for (i = 0; i < MAX_LETTERS*MAX_LETTERS; i++) {
dest->letter_pair_histogram[i] +=
source->letter_pair_histogram[i];
dest->word_pair_histogram[i] +=
source->word_pair_histogram[i];
}
for (i = 0; i < MAX_WORDS_PER_SENTENCE; i++) {
dest->sentence_length_histogram[i] +=
source->sentence_length_histogram[i];
}
for (i = 0; i < MAX_SENTENCES_PER_PARAGRAPH; i++) {
dest->paragraph_length_histogram[i] +=
source->paragraph_length_histogram[i];
}
for (i = 0; i < MAX_WORD_LENGTH; i++) {
dest->word_length_histogram[i] +=
source->word_length_histogram[i];
}
for (i = 0; i < DICTIONARY_SIZE; i++) {
dest->dictionary[i] +=
source->dictionary[i];
}
}
static void fingerprint_subtract(stylom_fingerprint * a,
stylom_fingerprint * b)
{
int i;
for (i = 0; i < MAX_LETTERS; i++) {
a->letter_histogram[i] -=
b->letter_histogram[i];
}
for (i = 0; i < MAX_LETTERS*MAX_LETTERS; i++) {
a->letter_pair_histogram[i] -=
b->letter_pair_histogram[i];
a->word_pair_histogram[i] -=
b->word_pair_histogram[i];
}
for (i = 0; i < MAX_WORDS_PER_SENTENCE; i++) {
a->sentence_length_histogram[i] -=
b->sentence_length_histogram[i];
}
for (i = 0; i < MAX_SENTENCES_PER_PARAGRAPH; i++) {
a->paragraph_length_histogram[i] -=
b->paragraph_length_histogram[i];
}
for (i = 0; i < MAX_WORD_LENGTH; i++) {
a->word_length_histogram[i] -=
b->word_length_histogram[i];
}
for (i = 0; i < DICTIONARY_SIZE; i++) {
a->dictionary[i] -=
b->dictionary[i];
}
}
/* returns a value indicating the similarity between two fingerprints */
float fingerprint_similarity(stylom_fingerprint * a, stylom_fingerprint * b)
{
stylom_fingerprint diff;
float dist[6],v;
int i;
/* calculate the difference between the two */
memcpy((void*)(&diff), (void*)a, sizeof(stylom_fingerprint));
fingerprint_subtract(&diff, b);
/* square the differences */
dist[0] = 0;
for (i = 0; i < MAX_LETTERS; i++) {
dist[0] += diff.letter_histogram[i] * diff.letter_histogram[i];
}
dist[0] /= MAX_LETTERS;
dist[1] = 0;
for (i = 0; i < MAX_LETTERS*MAX_LETTERS; i++) {
dist[1] += diff.letter_pair_histogram[i] * diff.letter_pair_histogram[i];
}
dist[1] /= MAX_LETTERS*MAX_LETTERS;
dist[2] = 0;
for (i = 0; i < MAX_LETTERS*MAX_LETTERS; i++) {
dist[2] += diff.word_pair_histogram[i] * diff.word_pair_histogram[i];
}
dist[2] /= MAX_LETTERS*MAX_LETTERS;
dist[3] = 0;
for (i = 0; i < MAX_WORDS_PER_SENTENCE; i++) {
dist[3] +=
diff.sentence_length_histogram[i] *
diff.sentence_length_histogram[i];
}
dist[3] /= MAX_WORDS_PER_SENTENCE;
dist[4] = 0;
for (i = 0; i < MAX_SENTENCES_PER_PARAGRAPH; i++) {
dist[4] +=
diff.paragraph_length_histogram[i] *
diff.paragraph_length_histogram[i];
}
dist[4] /= MAX_SENTENCES_PER_PARAGRAPH;
dist[5] = 0;
for (i = 0; i < MAX_WORD_LENGTH; i++) {
dist[5] += diff.word_length_histogram[i] *
diff.word_length_histogram[i];
}
dist[5] /= MAX_WORD_LENGTH;
dist[6] = 0;
for (i = 0; i < DICTIONARY_SIZE; i++) {
dist[6] += diff.dictionary[i] *
diff.dictionary[i];
}
dist[6] /= DICTIONARY_SIZE;
v = (float)sqrt((dist[0] + dist[1] + dist[2] +
dist[3] + dist[4] + dist[5] +
dist[6])/7.0f);
return 100 - (v*100);
}
/* Divide the fingerprint values by a given number.
This is used to calculate averages */
static void fingerprint_divide(stylom_fingerprint * f, int divisor)
{
int i;
for (i = 0; i < MAX_LETTERS; i++) {
f->letter_histogram[i] /= divisor;
}
for (i = 0; i < MAX_LETTERS*MAX_LETTERS; i++) {
f->letter_pair_histogram[i] /= divisor;
f->word_pair_histogram[i] /= divisor;
}
for (i = 0; i < MAX_WORDS_PER_SENTENCE; i++) {
f->sentence_length_histogram[i] /= divisor;
}
for (i = 0; i < MAX_SENTENCES_PER_PARAGRAPH; i++) {
f->paragraph_length_histogram[i] /= divisor;
}
for (i = 0; i < MAX_WORD_LENGTH; i++) {
f->word_length_histogram[i] /= divisor;
}
for (i = 0; i < DICTIONARY_SIZE; i++) {
f->dictionary[i] /= divisor;
}
}
/* Returns an average model for fingerprints in the given directory.
This can be used to calculate eigenvectors */
int fingerprint_average(stylom_fingerprint * f,
char * directory)
{
DIR * dp;
stylom_fingerprint fingerprint;
struct dirent *ep;
char filename[256];
FILE * fp;
int instances = 0;
fingerprint_clear(f);
dp = opendir (directory);
if (dp != NULL) {
while ((ep = readdir (dp)) != NULL) {
if ((strcmp(ep->d_name,".")!=0) &&
(strcmp(ep->d_name,"..")!=0)) {
sprintf(filename,"%s/%s",directory,ep->d_name);
fp = fopen(filename,"r");
if (fp) {
if (read_fingerprint_xml(&fingerprint, fp)!=0) {
fingerprint_sum(&fingerprint, f);
instances++;
}
fclose(fp);
}
}
}
(void) closedir (dp);
if (instances>0) {
fingerprint_divide(f, instances);
}
return 1;
}
return 0;
}
static void fingerprint_eigenvector(stylom_fingerprint * f,
stylom_fingerprint * average,
stylom_fingerprint * eigen)
{
/* copy the eigenvector */
memcpy((void*)eigen,(void*)f,sizeof(stylom_fingerprint));
/* subtract the average */
fingerprint_subtract(eigen, average);
}
/* matches the given fingerprint against those in the given directory
and returns the name of the best match */
int fingerprint_match(stylom_fingerprint * f,
char * directory,
char * best_name,
int show_list)
{
stylom_fingerprint fingerprint, fingerprint_av;
stylom_fingerprint fingerprint_eigen, f_eigen;
DIR * dp;
struct dirent *ep;
char filename[256];
FILE * fp;
float max_similarity=0,similarity;
int min_index, max_index, i, j, retval = 0, list_index = 0;
char * list_name[STYLOM_LIST_LENGTH], * temp_name;
float list_similarity[STYLOM_LIST_LENGTH];
float min_similarity, temp_similarity;
/* clear the best name */
best_name[0]=0;
/* get the average of all fingerprints */
fingerprint_average(&fingerprint_av, directory);
/* calculate the eigenvector */
fingerprint_eigenvector(f,&fingerprint_av,&f_eigen);
dp = opendir (directory);
if (dp != NULL) {
/* for every file in the directory */
while ((ep = readdir (dp)) != NULL) {
if ((strcmp(ep->d_name,".")!=0) &&
(strcmp(ep->d_name,"..")!=0)) {
/* the full filename */
sprintf(filename,"%s/%s",directory,ep->d_name);
/* open the file */
fp = fopen(filename,"r");
if (fp) {
/* read the fingerprint */
if (read_fingerprint_xml(&fingerprint, fp)!=0) {
/* calculate eigenvector */
fingerprint_eigenvector(&fingerprint,
&fingerprint_av,
&fingerprint_eigen);
/* similarity of this fingerprint eigenvector to
the eigenvector of the one given */
similarity =
fingerprint_similarity(&f_eigen,
&fingerprint_eigen);
if (show_list!=0) {
min_similarity = 9999;
min_index = 0;
for (i = 0; i < list_index; i++) {
if (list_similarity[i] <
min_similarity) {
min_similarity = list_similarity[i];
min_index = i;
}
}
if ((similarity > min_similarity) ||
(list_index < STYLOM_LIST_LENGTH)) {
if (list_index < STYLOM_LIST_LENGTH) {
list_similarity[list_index] =
similarity;
list_name[list_index] =
(char*)malloc(256*sizeof(char));
if (fingerprint.name[0]!=0) {
sprintf(list_name[list_index],
"%s",
(&fingerprint)->name);
}
else {
sprintf(list_name[list_index],
"%s",ep->d_name);
}
list_index++;
}
else {
list_similarity[min_index] =
similarity;
if (fingerprint.name[0]!=0) {
sprintf(list_name[min_index],
"%s",
(&fingerprint)->name);
}
else {
sprintf(list_name[min_index],
"%s",ep->d_name);
}
}
}
}
/* is this the best? */
if (similarity > max_similarity) {
max_similarity = similarity;
if (fingerprint.name[0]!=0) {
/* if an author name is specified */
sprintf(best_name,"%s",
(&fingerprint)->name);
}
else {
/* if no name was assigned */
sprintf(best_name,"%s",ep->d_name);
}
retval = 1;
}
}
fclose(fp);
}
}
}
(void) closedir (dp);
if (list_index > 0) {
/* sort the list */
for (i = 0; i < list_index-1; i++) {
max_similarity = list_similarity[i];
max_index = i;
for (j = i+1; j < list_index; j++) {
if (list_similarity[j] > max_similarity) {
max_similarity = list_similarity[j];
max_index = j;
}
}
if (max_index != i) {
temp_similarity = list_similarity[i];
list_similarity[i] = list_similarity[max_index];
list_similarity[max_index] = temp_similarity;
temp_name = list_name[i];
list_name[i] = list_name[max_index];
list_name[max_index] = temp_name;
}
}
/* show the list */
for (i = 0; i < list_index; i++) {
printf("%.8f\t%s\n",list_similarity[i],list_name[i]);
free(list_name[i]);
}
}
}
return retval;
}
/* Calculates 2D coordinates for a fingerprint relative to fingerprints within
a given directory */
void fingerprint_coordinates(stylom_fingerprint * f, float * x, float * y)
{
int i;
*x = 0;
for (i = 0; i < MAX_LETTERS; i++) {
(*x) = (*x) + (f->letter_histogram[i]);
}
for (i = 0; i < MAX_LETTERS*MAX_LETTERS; i++) {
(*x) = (*x) + (f->letter_pair_histogram[i]);
(*x) = (*x) + (f->word_pair_histogram[i]);
}
for (i = 0; i < MAX_SENTENCES_PER_PARAGRAPH; i++) {
(*x) = (*x) + (f->paragraph_length_histogram[i]);
}
(*x) = (*x) / (MAX_LETTERS + (MAX_LETTERS*MAX_LETTERS*2) +
MAX_SENTENCES_PER_PARAGRAPH);
*y = 0;
for (i = 0; i < MAX_WORDS_PER_SENTENCE; i++) {
(*y) = (*y) + (f->sentence_length_histogram[i]);
}
for (i = 0; i < MAX_WORD_LENGTH; i++) {
(*y) = (*y) + (f->word_length_histogram[i]);
}
for (i = 0; i < DICTIONARY_SIZE; i++) {
(*y) = (*y) + (f->dictionary[i]);
}
(*y) = (*y) / (MAX_WORDS_PER_SENTENCE +
MAX_WORD_LENGTH + DICTIONARY_SIZE);
}
static void fingerprints_range(char * directory,
float * min_x, float * min_y,
float * max_x, float * max_y)
{
char filename[256];
FILE * fp;
DIR * dp;
struct dirent *ep;
stylom_fingerprint fingerprint, fingerprint_av;
stylom_fingerprint fingerprint_eigen;
float x, y;
*min_x = 9999;
*min_y = 9999;
*max_x = -9999;
*max_y = -9999;
/* get the average of all fingerprints */
fingerprint_average(&fingerprint_av, directory);
dp = opendir (directory);
if (dp != NULL) {
/* for every file in the directory */
while ((ep = readdir (dp)) != NULL) {
if ((strcmp(ep->d_name,".")!=0) &&
(strcmp(ep->d_name,"..")!=0)) {
/* the full filename */
sprintf(filename,"%s/%s",directory,ep->d_name);
/* open the file */
fp = fopen(filename,"r");
if (fp) {
/* read the fingerprint */
if (read_fingerprint_xml(&fingerprint,
fp)!=0) {
/* calculate eigenvector */
fingerprint_eigenvector(&fingerprint,
&fingerprint_av,
&fingerprint_eigen);
/* coordinates of the eigenvector */
fingerprint_coordinates(&fingerprint_eigen,
&x, &y);
if (x < (*min_x)) (*min_x) = x;
if (y < (*min_y)) (*min_y) = y;
if (x > (*max_x)) (*max_x) = x;
if (y > (*max_y)) (*max_y) = y;
}
fclose(fp);
}
}
}
(void) closedir (dp);
}
}
/* plot fingerprints within the given directory as points */
int plot_fingerprints(char * image_filename,
char * title, char * directory,
int width, int height)
{
char * data_filename = "/tmp/temp_data.dat";
char * plot_filename = "/tmp/temp_plotfile.plot";
char commandstr[256],filename[256];
FILE * fp, * fp_data;
int retval=0;
DIR * dp;
struct dirent *ep;
stylom_fingerprint fingerprint, fingerprint_av;
stylom_fingerprint fingerprint_eigen;
float x, y;
float min_x = 9999, min_y = 9999;
float max_x = -9999, max_y = -9999;
fp = fopen(plot_filename,"r");
if (fp) {
fclose(fp);
sprintf((char*)commandstr,"rm %s", plot_filename);
retval = system(commandstr);
}
/* get the minimum and maximum range */
fingerprints_range(directory, &min_x, &min_y,
&max_x, &max_y);
/* get the average of all fingerprints */
fingerprint_average(&fingerprint_av, directory);
fp_data = fopen(data_filename,"w");
if (!fp_data) return 0;
dp = opendir (directory);
if (dp != NULL) {
/* for every file in the directory */
while ((ep = readdir (dp)) != NULL) {
if ((strcmp(ep->d_name,".")!=0) &&
(strcmp(ep->d_name,"..")!=0)) {
/* the full filename */
sprintf(filename,"%s/%s",directory,ep->d_name);
/* open the file */
fp = fopen(filename,"r");
if (fp) {
/* read the fingerprint */
if (read_fingerprint_xml(&fingerprint,
fp)!=0) {
fclose(fp);
/* calculate eigenvector */
fingerprint_eigenvector(&fingerprint,
&fingerprint_av,
&fingerprint_eigen);
/* coordinates of the eigenvector */
fingerprint_coordinates(&fingerprint_eigen,
&x, &y);
x = 5 + ((x - min_x)*90/(max_x - min_x));
y = 5 + ((y - min_y)*90/(max_y - min_y));
if (fingerprint.name[0]!=0) {
fprintf(fp_data,
"%.8f %.8f \"%s\"\n",
x, y, fingerprint.name);
}
else {
fprintf(fp_data,
"%.8f %.8f \"%s\"\n",
x, y, ep->d_name);
}
}
else {
fclose(fp);
}
}
}
}
(void) closedir (dp);
}
fclose(fp_data);
fp = fopen(plot_filename,"w");
if (fp) {
fprintf(fp,"reset\n");
fprintf(fp,"set title \"%s\"\n",title);
fprintf(fp,"set lmargin 9\n");
fprintf(fp,"set rmargin 2\n");
fprintf(fp,"set xlabel \"X\"\n");
fprintf(fp,"set ylabel \"Y\"\n");
fprintf(fp,"set xrange [0:100]\n");
fprintf(fp,"set yrange [0:100]\n");
fprintf(fp,"set key off\n");
fprintf(fp,"set terminal png size %d,%d ",
width,height);
fprintf(fp,"%s","font courier 10\n");
fprintf(fp,"set output \"%s\"\n",image_filename);
fprintf(fp,"plot \"%s\" using 1:2 with points\n",
data_filename);
fclose(fp);
sprintf((char*)commandstr,"gnuplot %s",plot_filename);
retval=system(commandstr);
}
return retval;
}
/* compares the given text to a fingerprint of an existing author */
int fingerprint_compare(char * text,
char * author_fingerprint_filename)
{
FILE * fp;
stylom_fingerprint author_fingerprint;
stylom_fingerprint text_fingerprint;
char more[1024],less[1024],missing[1024];
int no_of_differences, sentence_start=0;
int sentence_end=0, add_words=0,sentence_line_number,i;
fp = fopen(author_fingerprint_filename,"r");
if (!fp) return -1;
/* load the author fingerprint */
if (read_fingerprint_xml(&author_fingerprint, fp)==1) {
fclose(fp);
/* calculate the text fingerprint */
get_fingerprint("Unknown", text, &text_fingerprint);
no_of_differences =
compare_vocabulary((&text_fingerprint)->vocabulary,
(&author_fingerprint)->vocabulary,
(&text_fingerprint)->vocabulary_frequency,
(&author_fingerprint)->vocabulary_frequency,
missing, more, less,
SIMILARITY_THRESHOLD,
CONSOLE_WIDTH-20);
sentence_line_number =
recommend_sentence_change(text,
&text_fingerprint,
&author_fingerprint,
&sentence_start,
&sentence_end,
&add_words);
printf("\nNumber of style differences: %d\n\n",
no_of_differences);
if (strlen(missing)>0) {
printf("Avoid using the following words:\n\n");
printf("%s\n\n", missing);
}
if (strlen(more)>0) {
printf("Use more of the following words:\n\n");
printf("%s\n\n", more);
}
if (strlen(less)>0) {
printf("Use fewer of the following words:\n\n");
printf("%s\n\n", less);
}
if (sentence_line_number > -1) {
if (add_words > 0) {
printf("Add %d words\n",add_words);
}
else {
printf("Remove %d words\n",-add_words);
}
printf("Line number %d\n",sentence_line_number);
for (i = sentence_start; i < sentence_end; i++) {
if ((text[i] != 13) && (text[i] != 10)) {
printf("%c",text[i]);
}
else {
if ((i > 0) && (text[i] != 13)) {
if (text[i-1]!=' ') {
printf(" ");
}
}
}
}
printf("\n");
}
}
else {
fclose(fp);
printf("Cound not open %s\n",author_fingerprint_filename);
}
return 0;
}
/* reports words which exist in the given text but which are missing
from the given fingerprint */
int fingerprint_missing_words(char * text,
char * author_fingerprint_filename)
{
FILE * fp;
stylom_fingerprint author_fingerprint;
stylom_fingerprint text_fingerprint;
char more[1024],less[1024],missing[1024];
fp = fopen(author_fingerprint_filename,"r");
if (!fp) return -1;
/* load the author fingerprint */
if (read_fingerprint_xml(&author_fingerprint, fp)==1) {
fclose(fp);
/* calculate the text fingerprint */
get_fingerprint("Unknown", text, &text_fingerprint);
compare_vocabulary((&text_fingerprint)->vocabulary,
(&author_fingerprint)->vocabulary,
(&text_fingerprint)->vocabulary_frequency,
(&author_fingerprint)->vocabulary_frequency,
missing, more, less,
SIMILARITY_THRESHOLD, 9999);
if (strlen(missing)>0) {
printf("%s\n", missing);
}
}
else {
fclose(fp);
printf("Cound not open %s\n",author_fingerprint_filename);
}
return 0;
}
/* reports words which are more frequent in the given fingerprint
than in the given text */
int fingerprint_more_frequent_words(char * text,
char * author_fingerprint_filename)
{
FILE * fp;
stylom_fingerprint author_fingerprint;
stylom_fingerprint text_fingerprint;
char more[1024],less[1024],missing[1024];
fp = fopen(author_fingerprint_filename,"r");
if (!fp) return -1;
/* load the author fingerprint */
if (read_fingerprint_xml(&author_fingerprint, fp)==1) {
fclose(fp);
/* calculate the text fingerprint */
get_fingerprint("Unknown", text, &text_fingerprint);
compare_vocabulary((&text_fingerprint)->vocabulary,
(&author_fingerprint)->vocabulary,
(&text_fingerprint)->vocabulary_frequency,
(&author_fingerprint)->vocabulary_frequency,
missing, more, less,
SIMILARITY_THRESHOLD, 9999);
if (strlen(more)>0) {
printf("%s\n", more);
}
}
else {
fclose(fp);
printf("Cound not open %s\n",author_fingerprint_filename);
}
return 0;
}
/* reports words which are less frequent in the given fingerprint
than in the given text */
int fingerprint_less_frequent_words(char * text,
char * author_fingerprint_filename)
{
FILE * fp;
stylom_fingerprint author_fingerprint;
stylom_fingerprint text_fingerprint;
char more[1024],less[1024],missing[1024];
fp = fopen(author_fingerprint_filename,"r");
if (!fp) return -1;
/* load the author fingerprint */
if (read_fingerprint_xml(&author_fingerprint, fp)==1) {
fclose(fp);
/* calculate the text fingerprint */
get_fingerprint("Unknown", text, &text_fingerprint);
compare_vocabulary((&text_fingerprint)->vocabulary,
(&author_fingerprint)->vocabulary,
(&text_fingerprint)->vocabulary_frequency,
(&author_fingerprint)->vocabulary_frequency,
missing, more, less,
SIMILARITY_THRESHOLD, 9999);
if (strlen(less)>0) {
printf("%s\n", less);
}
}
else {
fclose(fp);
printf("Cound not open %s\n",author_fingerprint_filename);
}
return 0;
}
/* plot texts within a directory */
int plot_texts(char * image_filename,
char * title, char * directory,
int width, int height)
{
DIR * dp;
struct dirent *ep;
char temp_directory[256],text_filename[256];
char fingerprint_filename[256], commandstr[256];
char * text;
FILE * fp;
stylom_fingerprint fingerprint;
int result;
sprintf(temp_directory,"%s","/tmp/temp_stylom_plot_texts");
/* delete any previous temporary ditrectory */
sprintf(commandstr,"rm -rf %s",temp_directory);
result = system(commandstr);
/* create the temporary directory */
sprintf(commandstr,"mkdir %s",temp_directory);
if (system(commandstr)!=0) {
printf("Unable to create temporary directory %s\n",
temp_directory);
}
dp = opendir(directory);
if (dp != NULL) {
/* for every file in the directory */
while ((ep = readdir (dp)) != NULL) {
if ((strcmp(ep->d_name,".")!=0) &&
(strcmp(ep->d_name,"..")!=0)) {
/* the full filename */
sprintf(text_filename,"%s/%s",directory,ep->d_name);
printf("%s\n",text_filename);
text = 0;
if (read_text_from_file(&text, text_filename)!=0) {
/* calculate the fingerprint */
get_fingerprint(ep->d_name, text, &fingerprint);
/* save the fingerprint in the temporary directory */
sprintf(fingerprint_filename,
"%s/%s", temp_directory, ep->d_name);
fp = fopen(fingerprint_filename,"w");
if (fp) {
write_fingerprint_xml(&fingerprint, fp);
fclose(fp);
}
}
if (text != 0) {
free(text);
}
}
}
(void)closedir(dp);
}
result = plot_fingerprints(image_filename, title, temp_directory,
width, height);
return result;
}
|
bashrc/stylom
|
src/fingerprint.c
|
C
|
gpl-3.0
| 59,994
|
package com.StaticVoidGames.games;
import org.springframework.web.multipart.MultipartFile;
/**
* Class used by the game edit pages. Forms shown to (and submitted by) the user are backed by an instance of this class, so all of the handling can be done in one place.
* @see com.StaticVoidGames.spring.controller.EditGameController
*
*/
public class GameForm {
private String title;
private String description;
private String shortDescription;
private String website;
private MultipartFile jarFile;
private MultipartFile source;
private MultipartFile faviconFile;
private MultipartFile backgroundFile;
private MultipartFile thumbnailFile;
private String mainClass;
private Integer webstartWidth;
private Integer webstartHeight;
private String appletClass;
private Integer appletWidth;
private Integer appletHeight;
private String appletDescription;
private String javaVersion;
private String rating;
private String adText;
private Boolean showAdBorder;
private String adPlacement;
private String language;
private Boolean published;
private Boolean lwjgl;
private Boolean signed;
private String sourcePermissionsText;
private MultipartFile apkFile;
private String androidText;
private Boolean android;
private Boolean showLibGdxHtml;
private String libGdxHtmlMode;
private MultipartFile libGdxHtmlFile;
private String libGdxHtmlText;
private Boolean showProcessingJavaScript;
private String processingJavaScriptMode;
private MultipartFile processingJavaScriptFile;
private String processingJavaScriptText;
private String processingSketchName;
private Boolean showJavaScript;
private String javaScriptIndex;
private MultipartFile javaScriptFile;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getShortDescription() {
return shortDescription;
}
public void setShortDescription(String shortDescription) {
this.shortDescription = shortDescription;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public MultipartFile getJarFile() {
return jarFile;
}
public void setJarFile(MultipartFile jarFile) {
this.jarFile = jarFile;
}
public MultipartFile getSource() {
return source;
}
public void setSource(MultipartFile source) {
this.source = source;
}
public MultipartFile getFaviconFile() {
return faviconFile;
}
public void setFaviconUrl(MultipartFile faviconFile) {
this.faviconFile = faviconFile;
}
public MultipartFile getBackgroundFile() {
return backgroundFile;
}
public void setBackgroundUrl(MultipartFile backgroundFile) {
this.backgroundFile = backgroundFile;
}
public MultipartFile getThumbnailFile() {
return thumbnailFile;
}
public void setThumbnailFile(MultipartFile thumbnailFile) {
this.thumbnailFile = thumbnailFile;
}
public MultipartFile getLibgdxHtmlFile() {
return libGdxHtmlFile;
}
public void setLibGdxHtmlFile(MultipartFile libGdxHtmlFile) {
this.libGdxHtmlFile = libGdxHtmlFile;
}
public String getMainClass() {
return mainClass;
}
public void setMainClass(String mainClass) {
this.mainClass = mainClass;
}
public Integer getWebstartWidth() {
return webstartWidth;
}
public void setWebstartWidth(Integer webstartWidth) {
this.webstartWidth = webstartWidth;
}
public Integer getWebstartHeight() {
return webstartHeight;
}
public void setWebstartHeight(Integer webstartHeight) {
this.webstartHeight = webstartHeight;
}
public String getAppletClass() {
return appletClass;
}
public void setAppletClass(String appletClass) {
this.appletClass = appletClass;
}
public Integer getAppletWidth() {
return appletWidth;
}
public void setAppletWidth(Integer appletWidth) {
this.appletWidth = appletWidth;
}
public Integer getAppletHeight() {
return appletHeight;
}
public void setAppletHeight(Integer appletHeight) {
this.appletHeight = appletHeight;
}
public String getAppletDescription() {
return appletDescription;
}
public void setAppletDescription(String appletDescription) {
this.appletDescription = appletDescription;
}
public String getJavaVersion() {
return javaVersion;
}
public void setJavaVersion(String javaVersion) {
this.javaVersion = javaVersion;
}
public String getRating() {
return rating;
}
public void setRating(String rating) {
this.rating = rating;
}
public String getAdText() {
return adText;
}
public void setAdText(String adText) {
this.adText = adText;
}
public Boolean getShowAdBorder() {
return showAdBorder;
}
public void setShowAdBorder(Boolean showAdBorder) {
this.showAdBorder = showAdBorder;
}
public String getAdPlacement() {
return adPlacement;
}
public void setAdPlacement(String adPlacement) {
this.adPlacement = adPlacement;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
public Boolean getPublished() {
return published;
}
public void setPublished(Boolean published) {
this.published = published;
}
public Boolean getLwjgl() {
return lwjgl;
}
public void setLwjgl(Boolean lwjgl) {
this.lwjgl = lwjgl;
}
public Boolean getSigned() {
return signed;
}
public void setSigned(Boolean signed) {
this.signed = signed;
}
public String getSourcePermissionsText() {
return sourcePermissionsText;
}
public void setSourcePermissionsText(String sourcePermissionsText) {
this.sourcePermissionsText = sourcePermissionsText;
}
public MultipartFile getApkFile() {
return apkFile;
}
public void setApkFile(MultipartFile apkFile) {
this.apkFile = apkFile;
}
public String getAndroidText() {
return androidText;
}
public void setAndroidText(String androidText) {
this.androidText = androidText;
}
public Boolean getAndroid() {
return android;
}
public void setAndroid(Boolean android) {
this.android = android;
}
public Boolean getShowLibGdxHtml() {
return showLibGdxHtml;
}
public void setShowLibGdxHtml(boolean showLibGdxHtml) {
this.showLibGdxHtml = showLibGdxHtml;
}
public String getLibGdxHtmlMode() {
return libGdxHtmlMode;
}
public void setLibGdxHtmlMode(String libGdxHtmlMode) {
this.libGdxHtmlMode = libGdxHtmlMode;
}
public String getLibGdxHtmlText() {
return libGdxHtmlText;
}
public void setLibGdxHtmlText(String libGdxHtmlText) {
this.libGdxHtmlText = libGdxHtmlText;
}
public Boolean getShowProcessingJavaScript() {
return showProcessingJavaScript;
}
public void setShowProcessingJavaScript(Boolean showProcessingJavaScript) {
this.showProcessingJavaScript = showProcessingJavaScript;
}
public String getProcessingJavaScriptMode() {
return processingJavaScriptMode;
}
public void setProcessingJavaScriptMode(String processingJavaScriptMode) {
this.processingJavaScriptMode = processingJavaScriptMode;
}
public MultipartFile getProcessingJavaScriptFile() {
return processingJavaScriptFile;
}
public void setProcessingJavaScriptFile(MultipartFile processingJavaScriptFile) {
this.processingJavaScriptFile = processingJavaScriptFile;
}
public String getProcessingJavaScriptText() {
return processingJavaScriptText;
}
public void setProcessingJavaScriptText(String processingJavaScriptText) {
this.processingJavaScriptText = processingJavaScriptText;
}
public String getProcessingSketchName() {
return processingSketchName;
}
public void setProcessingSketchName(String processingSketchName) {
this.processingSketchName = processingSketchName;
}
public Boolean getShowJavaScript() {
return showJavaScript;
}
public void setShowJavaScript(boolean showJavaScript) {
this.showJavaScript = showJavaScript;
}
public String getJavaScriptIndex() {
return javaScriptIndex;
}
public void setJavaScriptIndex(String javaScriptIndex) {
this.javaScriptIndex = javaScriptIndex;
}
public MultipartFile getJavaScriptFile() {
return javaScriptFile;
}
public void setJavaScriptFile(MultipartFile javaScriptFile) {
this.javaScriptFile = javaScriptFile;
}
}
|
KevinWorkman/StaticVoidGames
|
StaticVoidGames/src/main/java/com/StaticVoidGames/games/GameForm.java
|
Java
|
gpl-3.0
| 8,299
|
#ifndef IF_ELSE_IF_TRUE_H
#define IF_ELSE_IF_TRUE_H
#include "ibp/foundation/boolean.h"
#include "ibp/foundation/integer.h"
ibp::Integer foo( ibp::Integer x,
ibp::Boolean y );
#endif
|
isaac-benson-powell/ibp_software
|
projects/language/test/test_io/for_ag_tests/input/parse_tree_nodes/Node_Else_If_True/expect_parser_pass/if_else_if_true/expected_cpp_translation/if_else_if_true.h
|
C
|
gpl-3.0
| 207
|
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Copyright (C) 2012-2020 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
Class
Foam::displacementMotionSolver
Description
Virtual base class for displacement motion solver
The boundary displacement is set as a boundary condition
on the pointDisplacement pointVectorField.
SourceFiles
displacementMotionSolver.C
\*---------------------------------------------------------------------------*/
#ifndef displacementMotionSolver_H
#define displacementMotionSolver_H
#include "points0MotionSolver.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
/*---------------------------------------------------------------------------*\
Class displacementMotionSolver Declaration
\*---------------------------------------------------------------------------*/
class displacementMotionSolver
:
public points0MotionSolver
{
protected:
// Protected data
//- Point motion field
mutable pointVectorField pointDisplacement_;
public:
//- Runtime type information
TypeName("displacementMotionSolver");
// Constructors
//- Construct from mesh and dictionary
displacementMotionSolver
(
const polyMesh&,
const dictionary&,
const word& type
);
//- Disallow default bitwise copy construction
displacementMotionSolver(const displacementMotionSolver&) = delete;
//- Destructor
virtual ~displacementMotionSolver();
// Member Functions
//- Return reference to the point motion displacement field
pointVectorField& pointDisplacement()
{
return pointDisplacement_;
}
//- Return const reference to the point motion displacement field
const pointVectorField& pointDisplacement() const
{
return pointDisplacement_;
}
// Member Operators
//- Disallow default bitwise assignment
void operator=(const displacementMotionSolver&) = delete;
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
|
OpenFOAM/OpenFOAM-dev
|
src/dynamicMesh/motionSolvers/displacement/displacement/displacementMotionSolver.H
|
C++
|
gpl-3.0
| 3,368
|
// Copyright (C) 2015 xaizek <xaizek@openmailbox.org>
//
// This plugin is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The plugin 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 the plugin. If not, see <http://www.gnu.org/licenses/>.
#include <cstring>
#include <iostream>
#include <string>
#include <vector>
#include <gcc-plugin.h>
#include <input.h>
#include <c-family/c-pragma.h>
#include "IncTree.hpp"
static void includeCallback(void *includeName, void *userData);
static void finishCallback(void *gccData, void *userData);
extern "C"
{
/**
* @brief Confirms GCC that we comply to GPL.
*/
int plugin_is_GPL_compatible = 1;
}
/**
* @brief Name of the plugin.
*/
static const char *const PLUGIN_NAME = "inc-tree";
/**
* @brief Generic information about the plugin.
*/
static plugin_info helpInfo = {
.version = "0.1",
.help = "Prints tree of includes",
};
/**
* @brief Plugin version requirements.
*/
static plugin_gcc_version pluginVer = {
.basever = "4.9",
};
/**
* @brief Object that builds the tree.
*/
static IncTree incTree;
/**
* @brief Plugin entry point.
*
* @param info Argument information.
* @param ver Version info of GCC.
*
* @returns @c 0 on success or error code on failure.
*/
int
plugin_init(struct plugin_name_args *info, struct plugin_gcc_version *ver)
{
// Validate the version information without plugin_default_version_check().
if (std::strncmp(ver->basever, pluginVer.basever,
std::strlen(pluginVer.basever)) < 0) {
// Incorrect version of GCC.
return -1;
}
// Provide plugin information for --help and --version.
register_callback(PLUGIN_NAME, PLUGIN_INFO, nullptr, &helpInfo);
// Setup callback for each #include (and #line) directive.
register_callback(PLUGIN_NAME, PLUGIN_INCLUDE_FILE, &includeCallback,
nullptr);
// Setup callback that will print out results.
register_callback(PLUGIN_NAME, PLUGIN_FINISH, &finishCallback, &helpInfo);
return 0;
}
/**
* @brief Callback which is called for @c #include and @c #line directives.
*
* @param includeName Name of include.
* @param userData User-provided data.
*/
static void
includeCallback(void */*includeName*/, void */*userData*/)
{
cpp_buffer *curr = cpp_get_buffer(parse_in);
// Register root source files as no other files include them, but we want
// to have them in the output even in the absence on any includes.
if (cpp_get_prev(curr) == nullptr) {
incTree.addUnit(cpp_get_path(cpp_get_file(curr)));
return;
}
std::vector<std::string> includeTrail;
do {
includeTrail.push_back(cpp_get_path(cpp_get_file(curr)));
curr = cpp_get_prev(curr);
} while (curr != nullptr);
// Not using std::reverse() as there are poisoned symbols.
incTree.addIncludeTrail({ includeTrail.rbegin(), includeTrail.rend() });
}
/**
* @brief Callback which is called before GCC quits.
*
* @param gccData Unused GCC-provided data.
* @param userData User-provided data.
*/
static void
finishCallback(void */*gccData*/, void */*userData*/)
{
std::cout << incTree;
}
|
xaizek/gcc-plugins
|
inc-tree/inc-tree.cpp
|
C++
|
gpl-3.0
| 3,636
|
<?php defined( 'ABSPATH' ) or die( header( 'HTTP/1.0 403 Forbidden' ) );
// intentionally empty!
|
geminorum/gtheme_03
|
amp/meta-taxonomy.php
|
PHP
|
gpl-3.0
| 98
|
#!/bin/bash
set -e
pegasus_lite_version_major="4"
pegasus_lite_version_minor="7"
pegasus_lite_version_patch="0"
pegasus_lite_enforce_strict_wp_check="true"
pegasus_lite_version_allow_wp_auto_download="true"
. pegasus-lite-common.sh
pegasus_lite_init
# cleanup in case of failures
trap pegasus_lite_signal_int INT
trap pegasus_lite_signal_term TERM
trap pegasus_lite_exit EXIT
echo -e "\n################################ Setting up workdir ################################" 1>&2
# work dir
export pegasus_lite_work_dir=$PWD
pegasus_lite_setup_work_dir
echo -e "\n###################### figuring out the worker package to use ######################" 1>&2
# figure out the worker package to use
pegasus_lite_worker_package
echo -e "\n##################### setting the xbit for executables staged #####################" 1>&2
# set the xbit for any executables staged
/bin/chmod +x example_workflow-taskevent_1-1.0
echo -e "\n############################# executing the user tasks #############################" 1>&2
# execute the tasks
set +e
pegasus-kickstart -n example_workflow::taskevent_1:1.0 -N ID0000007 -R condorpool -L example_workflow -T 2016-11-07T08:05:01+00:00 ./example_workflow-taskevent_1-1.0
job_ec=$?
set -e
|
elainenaomi/sciwonc-dataflow-examples
|
dissertation2017/Experiment 1A/instances/10_1_workflow_full_10files_secondary_w1_3sh_3rs_with_annot_with_proj_3s_range/dags/ubuntu/pegasus/example_workflow/20161107T080502+0000/00/00/taskevent_1_ID0000007.sh
|
Shell
|
gpl-3.0
| 1,237
|
-----------------------------------------
-- Spell: Cure II
-- Restores target's HP.
-- Shamelessly stolen from http://members.shaw.ca/pizza_steve/cure/Cure_Calculator.html
-----------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function OnMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local divisor = 0;
local constant = 0;
local basepower = 0;
local power = 0;
local basecure = 0;
local final = 0;
local minCure = 60;
if(USE_OLD_CURE_FORMULA == true) then
power = getCurePowerOld(caster);
divisor = 1;
constant = 20;
if(power > 170) then
divisor = 35.6666;
constant = 87.62;
elseif(power > 110) then
divisor = 2;
constant = 47.5;
end
else
power = getCurePower(caster);
if(power < 70) then
divisor = 1;
constant = 60;
basepower = 40;
elseif(power < 125) then
divisor = 5.5;
constant = 90;
basepower = 70;
elseif(power < 200) then
divisor = 7.5;
constant = 100;
basepower = 125;
elseif(power < 400) then
divisor = 10;
constant = 110;
basepower = 200;
elseif(power < 700) then
divisor = 20;
constant = 130;
basepower = 400;
else
divisor = 999999;
constant = 145;
basepower = 0;
end
end
if(target:getObjType() == TYPE_PC) then
if(USE_OLD_CURE_FORMULA == true) then
basecure = getBaseCure(power,divisor,constant);
else
basecure = getBaseCure(power,divisor,constant,basepower);
end
final = getCureFinal(caster,spell,basecure,minCure,false);
if(caster:hasStatusEffect(EFFECT_AFFLATUS_SOLACE) and target:hasStatusEffect(EFFECT_STONESKIN) == false) then
local solaceStoneskin = 0;
local equippedBody = caster:getEquipID(SLOT_BODY);
if(equippedBody == 11186) then
solaceStoneskin = math.floor(final * 0.30);
elseif(equippedBody == 11086) then
solaceStoneskin = math.floor(final * 0.35);
else
solaceStoneskin = math.floor(final * 0.25);
end
target:addStatusEffect(EFFECT_STONESKIN,solaceStoneskin,0,25);
end;
final = final + (final * (target:getMod(MOD_CURE_POTENCY_RCVD)/100));
--Applying server mods....
final = final * CURE_POWER;
local diff = (target:getMaxHP() - target:getHP());
if(final > diff) then
final = diff;
end
target:addHP(final);
target:wakeUp();
caster:updateEnmityFromCure(target,final);
else
if(target:isUndead()) then
spell:setMsg(2);
local dmg = calculateMagicDamage(minCure,1,caster,spell,target,HEALING_MAGIC_SKILL,MOD_MND,false)*0.5;
local resist = applyResistance(caster,spell,target,caster:getStat(MOD_MND)-target:getStat(MOD_MND),HEALING_MAGIC_SKILL,1.0);
dmg = dmg*resist;
dmg = addBonuses(caster,spell,target,dmg);
dmg = adjustForTarget(target,dmg,spell:getElement());
dmg = finalMagicAdjustments(caster,target,spell,dmg);
final = dmg;
target:delHP(final);
target:updateEnmityFromDamage(caster,final);
elseif(caster:getObjType() == TYPE_PC) then
spell:setMsg(75);
else
-- e.g. monsters healing themselves.
if(USE_OLD_CURE_FORMULA == true) then
basecure = getBaseCureOld(power,divisor,constant);
else
basecure = getBaseCure(power,divisor,constant,basepower);
end
final = getCureFinal(caster,spell,basecure,minCure,false);
local diff = (target:getMaxHP() - target:getHP());
if(final > diff) then
final = diff;
end
target:addHP(final);
end
end
return final;
end;
|
Gwynthell/FFDB
|
scripts/globals/spells/cure_ii.lua
|
Lua
|
gpl-3.0
| 3,693
|
/*! \file janus_rabbitmqevh.c
* \author Piter Konstantinov <pit.here@gmail.com>
* \copyright GNU General Public License v3
* \brief Janus RabbitMQEventHandler plugin
* \details This is a trivial RabbitMQ event handler plugin for Janus
*
* \ingroup eventhandlers
* \ref eventhandlers
*/
#include "eventhandler.h"
#include <math.h>
#include <amqp.h>
#include <amqp_framing.h>
#include <amqp_tcp_socket.h>
#include <amqp_ssl_socket.h>
#include "../debug.h"
#include "../config.h"
#include "../mutex.h"
#include "../utils.h"
#include "../events.h"
/* Plugin information */
#define JANUS_RABBITMQEVH_VERSION 1
#define JANUS_RABBITMQEVH_VERSION_STRING "0.0.1"
#define JANUS_RABBITMQEVH_DESCRIPTION "This is a trivial RabbitMQ event handler plugin for Janus."
#define JANUS_RABBITMQEVH_NAME "JANUS RabbitMQEventHandler plugin"
#define JANUS_RABBITMQEVH_AUTHOR "Meetecho s.r.l."
#define JANUS_RABBITMQEVH_PACKAGE "janus.eventhandler.rabbitmqevh"
/* Plugin methods */
janus_eventhandler *create(void);
int janus_rabbitmqevh_init(const char *config_path);
void janus_rabbitmqevh_destroy(void);
int janus_rabbitmqevh_get_api_compatibility(void);
int janus_rabbitmqevh_get_version(void);
const char *janus_rabbitmqevh_get_version_string(void);
const char *janus_rabbitmqevh_get_description(void);
const char *janus_rabbitmqevh_get_name(void);
const char *janus_rabbitmqevh_get_author(void);
const char *janus_rabbitmqevh_get_package(void);
void janus_rabbitmqevh_incoming_event(json_t *event);
json_t *janus_rabbitmqevh_handle_request(json_t *request);
/* Event handler setup */
static janus_eventhandler janus_rabbitmqevh =
JANUS_EVENTHANDLER_INIT (
.init = janus_rabbitmqevh_init,
.destroy = janus_rabbitmqevh_destroy,
.get_api_compatibility = janus_rabbitmqevh_get_api_compatibility,
.get_version = janus_rabbitmqevh_get_version,
.get_version_string = janus_rabbitmqevh_get_version_string,
.get_description = janus_rabbitmqevh_get_description,
.get_name = janus_rabbitmqevh_get_name,
.get_author = janus_rabbitmqevh_get_author,
.get_package = janus_rabbitmqevh_get_package,
.incoming_event = janus_rabbitmqevh_incoming_event,
.handle_request = janus_rabbitmqevh_handle_request,
.events_mask = JANUS_EVENT_TYPE_NONE
);
/* Plugin creator */
janus_eventhandler *create(void) {
JANUS_LOG(LOG_VERB, "%s created!\n", JANUS_RABBITMQEVH_NAME);
return &janus_rabbitmqevh;
}
/* Useful stuff */
static volatile gint initialized = 0, stopping = 0;
static GThread *handler_thread;
static void *janus_rabbitmqevh_handler(void *data);
/* Queue of events to handle */
static GAsyncQueue *events = NULL;
static gboolean group_events = TRUE;
static json_t exit_event;
static void janus_rabbitmqevh_event_free(json_t *event) {
if(!event || event == &exit_event)
return;
json_decref(event);
}
/* JSON serialization options */
static size_t json_format = JSON_INDENT(3) | JSON_PRESERVE_ORDER;
/* FIXME: Should it be configurable? */
#define JANUS_RABBITMQ_EXCHANGE_TYPE "fanout"
/* RabbitMQ session */
static amqp_connection_state_t rmq_conn;
static amqp_channel_t rmq_channel = 0;
static amqp_bytes_t rmq_exchange;
static amqp_bytes_t rmq_route_key;
/* Parameter validation (for tweaking via Admin API) */
static struct janus_json_parameter request_parameters[] = {
{"request", JSON_STRING, JANUS_JSON_PARAM_REQUIRED}
};
static struct janus_json_parameter tweak_parameters[] = {
{"events", JSON_STRING, 0},
{"grouping", JANUS_JSON_BOOL, 0}
};
/* Error codes (for the tweaking via Admin API */
#define JANUS_RABBITMQEVH_ERROR_INVALID_REQUEST 411
#define JANUS_RABBITMQEVH_ERROR_MISSING_ELEMENT 412
#define JANUS_RABBITMQEVH_ERROR_INVALID_ELEMENT 413
#define JANUS_RABBITMQEVH_ERROR_UNKNOWN_ERROR 499
/* Plugin implementation */
int janus_rabbitmqevh_init(const char *config_path) {
gboolean success = TRUE;
if(g_atomic_int_get(&stopping)) {
/* Still stopping from before */
return -1;
}
if(config_path == NULL) {
/* Invalid arguments */
return -1;
}
/* Read configuration */
char filename[255];
g_snprintf(filename, 255, "%s/%s.jcfg", config_path, JANUS_RABBITMQEVH_PACKAGE);
JANUS_LOG(LOG_VERB, "Configuration file: %s\n", filename);
janus_config *config = janus_config_parse(filename);
if(config == NULL) {
JANUS_LOG(LOG_WARN, "Couldn't find .jcfg configuration file (%s), trying .cfg\n", JANUS_RABBITMQEVH_PACKAGE);
g_snprintf(filename, 255, "%s/%s.cfg", config_path, JANUS_RABBITMQEVH_PACKAGE);
JANUS_LOG(LOG_VERB, "Configuration file: %s\n", filename);
config = janus_config_parse(filename);
}
if(config != NULL)
janus_config_print(config);
janus_config_category *config_general = janus_config_get_create(config, NULL, janus_config_type_category, "general");
char *rmqhost = NULL;
const char *vhost = NULL, *username = NULL, *password = NULL;
const char *ssl_cacert_file = NULL;
const char *ssl_cert_file = NULL;
const char *ssl_key_file = NULL;
gboolean ssl_enable = FALSE;
gboolean ssl_verify_peer = FALSE;
gboolean ssl_verify_hostname = FALSE;
const char *route_key = NULL, *exchange = NULL;
/* Setup the event handler, if required */
janus_config_item *item = janus_config_get(config, config_general, janus_config_type_item, "enabled");
if(!item || !item->value || !janus_is_true(item->value)) {
JANUS_LOG(LOG_WARN, "RabbitMQ event handler disabled\n");
goto error;
}
item = janus_config_get(config, config_general, janus_config_type_item, "json");
if(item && item->value) {
/* Check how we need to format/serialize the JSON output */
if(!strcasecmp(item->value, "indented")) {
/* Default: indented, we use three spaces for that */
json_format = JSON_INDENT(3) | JSON_PRESERVE_ORDER;
} else if(!strcasecmp(item->value, "plain")) {
/* Not indented and no new lines, but still readable */
json_format = JSON_INDENT(0) | JSON_PRESERVE_ORDER;
} else if(!strcasecmp(item->value, "compact")) {
/* Compact, so no spaces between separators */
json_format = JSON_COMPACT | JSON_PRESERVE_ORDER;
} else {
JANUS_LOG(LOG_WARN, "Unsupported JSON format option '%s', using default (indented)\n", item->value);
json_format = JSON_INDENT(3) | JSON_PRESERVE_ORDER;
}
}
/* Which events should we subscribe to? */
item = janus_config_get(config, config_general, janus_config_type_item, "events");
if(item && item->value)
janus_events_edit_events_mask(item->value, &janus_rabbitmqevh.events_mask);
/* Is grouping of events ok? */
item = janus_config_get(config, config_general, janus_config_type_item, "grouping");
if(item && item->value)
group_events = janus_is_true(item->value);
/* Handle configuration, starting from the server details */
item = janus_config_get(config, config_general, janus_config_type_item, "host");
if(item && item->value)
rmqhost = g_strdup(item->value);
else
rmqhost = g_strdup("localhost");
int rmqport = AMQP_PROTOCOL_PORT;
item = janus_config_get(config, config_general, janus_config_type_item, "port");
if(item && item->value)
rmqport = atoi(item->value);
/* Credentials and Virtual Host */
item = janus_config_get(config, config_general, janus_config_type_item, "vhost");
if(item && item->value)
vhost = g_strdup(item->value);
else
vhost = g_strdup("/");
item = janus_config_get(config, config_general, janus_config_type_item, "username");
if(item && item->value)
username = g_strdup(item->value);
else
username = g_strdup("guest");
item = janus_config_get(config, config_general, janus_config_type_item, "password");
if(item && item->value)
password = g_strdup(item->value);
else
password = g_strdup("guest");
/* SSL config*/
item = janus_config_get(config, config_general, janus_config_type_item, "ssl_enable");
if(!item || !item->value || !janus_is_true(item->value)) {
JANUS_LOG(LOG_INFO, "RabbitMQEventHandler: RabbitMQ SSL support disabled\n");
} else {
ssl_enable = TRUE;
item = janus_config_get(config, config_general, janus_config_type_item, "ssl_cacert");
if(item && item->value)
ssl_cacert_file = g_strdup(item->value);
item = janus_config_get(config, config_general, janus_config_type_item, "ssl_cert");
if(item && item->value)
ssl_cert_file = g_strdup(item->value);
item = janus_config_get(config, config_general, janus_config_type_item, "ssl_key");
if(item && item->value)
ssl_key_file = g_strdup(item->value);
item = janus_config_get(config, config_general, janus_config_type_item, "ssl_verify_peer");
if(item && item->value && janus_is_true(item->value))
ssl_verify_peer = TRUE;
item = janus_config_get(config, config_general, janus_config_type_item, "ssl_verify_hostname");
if(item && item->value && janus_is_true(item->value))
ssl_verify_hostname = TRUE;
}
/* Parse configuration */
item = janus_config_get(config, config_general, janus_config_type_item, "route_key");
if(!item || !item->value) {
JANUS_LOG(LOG_FATAL, "RabbitMQEventHandler: Missing name of outgoing route_key for RabbitMQ...\n");
goto error;
}
route_key = g_strdup(item->value);
item = janus_config_get(config, config_general, janus_config_type_item, "exchange");
if(!item || !item->value) {
JANUS_LOG(LOG_INFO, "RabbitMQEventHandler: Missing name of outgoing exchange for RabbitMQ, using default\n");
} else {
exchange = g_strdup(item->value);
}
if (exchange == NULL) {
JANUS_LOG(LOG_INFO, "RabbitMQ event handler enabled, %s:%d (%s)\n", rmqhost, rmqport, route_key);
} else {
JANUS_LOG(LOG_INFO, "RabbitMQ event handler enabled, %s:%d (%s) exch: (%s)\n", rmqhost, rmqport, route_key, exchange);
}
/* Connect */
rmq_conn = amqp_new_connection();
amqp_socket_t *socket = NULL;
int status = AMQP_STATUS_OK;
JANUS_LOG(LOG_VERB, "RabbitMQEventHandler: Creating RabbitMQ socket...\n");
if (ssl_enable) {
socket = amqp_ssl_socket_new(rmq_conn);
if(socket == NULL) {
JANUS_LOG(LOG_FATAL, "RabbitMQEventHandler: Can't connect to RabbitMQ server: error creating socket...\n");
goto error;
}
if(ssl_verify_peer) {
amqp_ssl_socket_set_verify_peer(socket, 1);
} else {
amqp_ssl_socket_set_verify_peer(socket, 0);
}
if(ssl_verify_hostname) {
amqp_ssl_socket_set_verify_hostname(socket, 1);
} else {
amqp_ssl_socket_set_verify_hostname(socket, 0);
}
if(ssl_cacert_file) {
status = amqp_ssl_socket_set_cacert(socket, ssl_cacert_file);
if(status != AMQP_STATUS_OK) {
JANUS_LOG(LOG_FATAL, "RabbitMQEventHandler: Can't connect to RabbitMQ server: error setting CA certificate... (%s)\n", amqp_error_string2(status));
goto error;
}
}
if(ssl_cert_file && ssl_key_file) {
amqp_ssl_socket_set_key(socket, ssl_cert_file, ssl_key_file);
if(status != AMQP_STATUS_OK) {
JANUS_LOG(LOG_FATAL, "RabbitMQEventHandler: Can't connect to RabbitMQ server: error setting key... (%s)\n", amqp_error_string2(status));
goto error;
}
}
} else {
socket = amqp_tcp_socket_new(rmq_conn);
if(socket == NULL) {
JANUS_LOG(LOG_FATAL, "RabbitMQEventHandler: Can't connect to RabbitMQ server: error creating socket...\n");
goto error;
}
}
JANUS_LOG(LOG_VERB, "RabbitMQEventHandler: Connecting to RabbitMQ server...\n");
status = amqp_socket_open(socket, rmqhost, rmqport);
if(status != AMQP_STATUS_OK) {
JANUS_LOG(LOG_FATAL, "Can't connect to RabbitMQ server: error opening socket... (%s)\n", amqp_error_string2(status));
goto error;
}
JANUS_LOG(LOG_VERB, "RabbitMQEventHandler: Logging in...\n");
amqp_rpc_reply_t result = amqp_login(rmq_conn, vhost, 0, 131072, 0, AMQP_SASL_METHOD_PLAIN, username, password);
if(result.reply_type != AMQP_RESPONSE_NORMAL) {
JANUS_LOG(LOG_FATAL, "RabbitMQEventHandler: Can't connect to RabbitMQ server: error logging in... %s, %s\n", amqp_error_string2(result.library_error), amqp_method_name(result.reply.id));
goto error;
}
rmq_channel = 1;
JANUS_LOG(LOG_VERB, "Opening channel...\n");
amqp_channel_open(rmq_conn, rmq_channel);
result = amqp_get_rpc_reply(rmq_conn);
if(result.reply_type != AMQP_RESPONSE_NORMAL) {
JANUS_LOG(LOG_FATAL, "RabbitMQEventHandler: Can't connect to RabbitMQ server: error opening channel... %s, %s\n", amqp_error_string2(result.library_error), amqp_method_name(result.reply.id));
goto error;
}
rmq_exchange = amqp_empty_bytes;
if(exchange != NULL) {
JANUS_LOG(LOG_VERB, "RabbitMQEventHandler: Declaring exchange...\n");
rmq_exchange = amqp_cstring_bytes(exchange);
amqp_exchange_declare(rmq_conn, rmq_channel, rmq_exchange, amqp_cstring_bytes(JANUS_RABBITMQ_EXCHANGE_TYPE), 0, 0, 0, 0, amqp_empty_table);
result = amqp_get_rpc_reply(rmq_conn);
if(result.reply_type != AMQP_RESPONSE_NORMAL) {
JANUS_LOG(LOG_FATAL, "RabbitMQEventHandler: Can't connect to RabbitMQ server: error diclaring exchange... %s, %s\n", amqp_error_string2(result.library_error), amqp_method_name(result.reply.id));
goto error;
}
}
JANUS_LOG(LOG_VERB, "Declaring outgoing queue... (%s)\n", route_key);
rmq_route_key = amqp_cstring_bytes(route_key);
amqp_queue_declare(rmq_conn, rmq_channel, rmq_route_key, 0, 0, 0, 0, amqp_empty_table);
result = amqp_get_rpc_reply(rmq_conn);
if(result.reply_type != AMQP_RESPONSE_NORMAL) {
JANUS_LOG(LOG_FATAL, "RabbitMQEventHandler: Can't connect to RabbitMQ server: error declaring queue... %s, %s\n", amqp_error_string2(result.library_error), amqp_method_name(result.reply.id));
goto error;
}
/* Initialize the events queue */
events = g_async_queue_new_full((GDestroyNotify) janus_rabbitmqevh_event_free);
g_atomic_int_set(&initialized, 1);
GError *error = NULL;
handler_thread = g_thread_try_new("janus rabbitmqevh handler", janus_rabbitmqevh_handler, NULL, &error);
if(error != NULL) {
g_atomic_int_set(&initialized, 0);
JANUS_LOG(LOG_FATAL, "Got error %d (%s) trying to launch the RabbitMQEventHandler handler thread...\n", error->code, error->message ? error->message : "??");
goto error;
}
/* Done */
JANUS_LOG(LOG_INFO, "Setup of RabbitMQ event handler completed\n");
goto done;
error:
/* If we got here, something went wrong */
success = FALSE;
if(route_key)
g_free((char *)route_key);
if(exchange)
g_free((char *)exchange);
/* Fall through */
done:
if(rmqhost)
g_free((char *)rmqhost);
if(vhost)
g_free((char *)vhost);
if(username)
g_free((char *)username);
if(password)
g_free((char *)password);
if(ssl_cacert_file)
g_free((char *)ssl_cacert_file);
if(ssl_cert_file)
g_free((char *)ssl_cert_file);
if(ssl_key_file)
g_free((char *)ssl_key_file);
if(config)
janus_config_destroy(config);
if(!success) {
return -1;
}
JANUS_LOG(LOG_INFO, "%s initialized!\n", JANUS_RABBITMQEVH_NAME);
return 0;
}
void janus_rabbitmqevh_destroy(void) {
if(!g_atomic_int_get(&initialized))
return;
g_atomic_int_set(&stopping, 1);
g_async_queue_push(events, &exit_event);
if(handler_thread != NULL) {
g_thread_join(handler_thread);
handler_thread = NULL;
}
g_async_queue_unref(events);
events = NULL;
if(rmq_conn && rmq_channel) {
amqp_channel_close(rmq_conn, rmq_channel, AMQP_REPLY_SUCCESS);
amqp_connection_close(rmq_conn, AMQP_REPLY_SUCCESS);
amqp_destroy_connection(rmq_conn);
}
if(rmq_exchange.bytes)
g_free((char *)rmq_exchange.bytes);
if(rmq_route_key.bytes)
g_free((char *)rmq_route_key.bytes);
g_atomic_int_set(&initialized, 0);
g_atomic_int_set(&stopping, 0);
JANUS_LOG(LOG_INFO, "%s destroyed!\n", JANUS_RABBITMQEVH_NAME);
}
int janus_rabbitmqevh_get_api_compatibility(void) {
/* Important! This is what your plugin MUST always return: don't lie here or bad things will happen */
return JANUS_EVENTHANDLER_API_VERSION;
}
int janus_rabbitmqevh_get_version(void) {
return JANUS_RABBITMQEVH_VERSION;
}
const char *janus_rabbitmqevh_get_version_string(void) {
return JANUS_RABBITMQEVH_VERSION_STRING;
}
const char *janus_rabbitmqevh_get_description(void) {
return JANUS_RABBITMQEVH_DESCRIPTION;
}
const char *janus_rabbitmqevh_get_name(void) {
return JANUS_RABBITMQEVH_NAME;
}
const char *janus_rabbitmqevh_get_author(void) {
return JANUS_RABBITMQEVH_AUTHOR;
}
const char *janus_rabbitmqevh_get_package(void) {
return JANUS_RABBITMQEVH_PACKAGE;
}
void janus_rabbitmqevh_incoming_event(json_t *event) {
if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
/* Janus is closing or the plugin is */
return;
}
/* Do NOT handle the event here in this callback! Since Janus notifies you right
* away when something happens, these events are triggered from working threads and
* not some sort of message bus. As such, performing I/O or network operations in
* here could dangerously slow Janus down. Let's just reference and enqueue the event,
* and handle it in our own thread: the event contains a monotonic time indicator of
* when the event actually happened on this machine, so that, if relevant, we can compute
* any delay in the actual event processing ourselves. */
json_incref(event);
g_async_queue_push(events, event);
}
json_t *janus_rabbitmqevh_handle_request(json_t *request) {
if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized)) {
return NULL;
}
/* We can use this requests to apply tweaks to the logic */
int error_code = 0;
char error_cause[512];
JANUS_VALIDATE_JSON_OBJECT(request, request_parameters,
error_code, error_cause, TRUE,
JANUS_RABBITMQEVH_ERROR_MISSING_ELEMENT, JANUS_RABBITMQEVH_ERROR_INVALID_ELEMENT);
if(error_code != 0)
goto plugin_response;
/* Get the request */
const char *request_text = json_string_value(json_object_get(request, "request"));
if(!strcasecmp(request_text, "tweak")) {
/* We only support a request to tweak the current settings */
JANUS_VALIDATE_JSON_OBJECT(request, tweak_parameters,
error_code, error_cause, TRUE,
JANUS_RABBITMQEVH_ERROR_MISSING_ELEMENT, JANUS_RABBITMQEVH_ERROR_INVALID_ELEMENT);
if(error_code != 0)
goto plugin_response;
/* Events */
if(json_object_get(request, "events"))
janus_events_edit_events_mask(json_string_value(json_object_get(request, "events")), &janus_rabbitmqevh.events_mask);
/* Grouping */
if(json_object_get(request, "grouping"))
group_events = json_is_true(json_object_get(request, "grouping"));
} else {
JANUS_LOG(LOG_VERB, "Unknown request '%s'\n", request_text);
error_code = JANUS_RABBITMQEVH_ERROR_INVALID_REQUEST;
g_snprintf(error_cause, 512, "Unknown request '%s'", request_text);
}
plugin_response:
{
json_t *response = json_object();
if(error_code == 0) {
/* Return a success */
json_object_set_new(response, "result", json_integer(200));
} else {
/* Prepare JSON error event */
json_object_set_new(response, "error_code", json_integer(error_code));
json_object_set_new(response, "error", json_string(error_cause));
}
return response;
}
}
/* Thread to handle incoming events */
static void *janus_rabbitmqevh_handler(void *data) {
JANUS_LOG(LOG_VERB, "Joining RabbitMQEventHandler handler thread\n");
json_t *event = NULL, *output = NULL;
char *event_text = NULL;
int count = 0, max = group_events ? 100 : 1;
while(g_atomic_int_get(&initialized) && !g_atomic_int_get(&stopping)) {
event = g_async_queue_pop(events);
if(event == NULL)
continue;
if(event == &exit_event)
break;
count = 0;
output = NULL;
while(TRUE) {
/* Handle event: just for fun, let's see how long it took for us to take care of this */
json_t *created = json_object_get(event, "timestamp");
if(created && json_is_integer(created)) {
gint64 then = json_integer_value(created);
gint64 now = janus_get_monotonic_time();
JANUS_LOG(LOG_DBG, "Handled event after %"SCNu64" us\n", now-then);
}
if(!group_events) {
/* We're done here, we just need a single event */
output = event;
break;
}
/* If we got here, we're grouping */
if(output == NULL)
output = json_array();
json_array_append_new(output, event);
/* Never group more than a maximum number of events, though, or we might stay here forever */
count++;
if(count == max)
break;
event = g_async_queue_try_pop(events);
if(event == NULL || event == &exit_event)
break;
}
if(!g_atomic_int_get(&stopping)) {
/* Since this a simple plugin, it does the same for all events: so just convert to string... */
event_text = json_dumps(output, json_format);
amqp_basic_properties_t props;
props._flags = 0;
props._flags |= AMQP_BASIC_CONTENT_TYPE_FLAG;
props.content_type = amqp_cstring_bytes("application/json");
amqp_bytes_t message = amqp_cstring_bytes(event_text);
int status = amqp_basic_publish(rmq_conn, rmq_channel, rmq_exchange, rmq_route_key, 0, 0, &props, message);
if(status != AMQP_STATUS_OK) {
JANUS_LOG(LOG_ERR, "RabbitMQEventHandler: Error publishing... %d, %s\n", status, amqp_error_string2(status));
}
free(event_text);
event_text = NULL;
}
/* Done, let's unref the event */
json_decref(output);
output = NULL;
}
JANUS_LOG(LOG_VERB, "Leaving RabbitMQEventHandler handler thread\n");
return NULL;
}
|
ploxiln/janus-gateway
|
events/janus_rabbitmqevh.c
|
C
|
gpl-3.0
| 20,977
|
/*
* Starving is a open source bukkit/spigot mmo game.
* Copyright (C) 2014-2015 Matej Kormuth
* This file is a part of Starving. <http://www.starving.eu>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package eu.matejkormuth.rpgdavid.starving;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
public class StarvingLogger extends Logger {
private static final String prefix = "[Starving] ";
public static boolean broadcast = false;
protected StarvingLogger() {
super("Starving", null);
}
@Override
public void log(LogRecord record) {
record.setMessage(prefix + record.getMessage());
if(broadcast) {
Bukkit.broadcastMessage(ChatColor.GRAY + record.getMessage());
}
super.log(record);
}
}
|
dobrakmato/mcRPG
|
src/main/java/eu/matejkormuth/rpgdavid/starving/StarvingLogger.java
|
Java
|
gpl-3.0
| 1,474
|
#
# Copyright 2013 by Antonio Costa (acosta@conviso.com.br)
#
# This file is part of the Drone openvas project.
# Drone Template is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
require 'net/smtp'
class Output
class Debug
@@level = 0
class << self
attr_accessor 'level'
end
attr_accessor :level
def initialize(configuration)
@config = configuration
output_file = configuration['log_file'].to_s
begin
@output = File.exists?(output_file) ? File.open(output_file, 'a') : STDOUT
rescue Exception => e
@output = STDOUT
warning(e.to_s)
info('Using the default output for all system messages')
end
end
def error(msg)
m = "[E #{__get_time}] #{msg}"
@output.puts m
@output.flush
if (@config.has_key?(:smtp) && @config[:smtp].has_key?(:operator) && @config[:smtp][:operator].has_key?(:email))
__send_message(m)
end
end
def warning(msg)
@output.puts "[W #{__get_time}] #{msg}"
@output.flush
end
def info(msg)
@output.puts "[I #{__get_time}] #{msg}"
@output.flush
end
private
def __get_time
now = DateTime.now
"#{now.year}-#{now.month}-#{now.day} #{now.hour}:#{now.min}"
end
def __send_message(content = '')
message = <<MESSAGE_END
From: Bot #{@config[:plugin_name]} <#{@config[:plugin_name].gsub(' ', '').downcase}@conviso.com.br>
To: #{@config[:smtp][:operator][:name]} <#{@config[:smtp][:operator][:email]}>
Subject: Algum problema foi detectado com o bot #{@config[:plugin_name]}
#{content}
MESSAGE_END
Net::SMTP.start('localhost') do |smtp|
smtp.send_message message, "#{@config[:plugin_name].gsub(' ', '').downcase}@conviso.com.br", @config[:smtp][:operator][:email]
end
end
end
end
|
convisoappsec/drone_openvas
|
lib/output/debug.rb
|
Ruby
|
gpl-3.0
| 2,453
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @author Anton V. Karnachuk
*/
/**
* Created on 09.02.2005
*/
package org.apache.harmony.jpda.tests.jdwp.ClassType;
import java.io.UnsupportedEncodingException;
import org.apache.harmony.jpda.tests.framework.jdwp.CommandPacket;
import org.apache.harmony.jpda.tests.framework.jdwp.JDWPCommands;
import org.apache.harmony.jpda.tests.framework.jdwp.JDWPConstants;
import org.apache.harmony.jpda.tests.framework.jdwp.ReplyPacket;
import org.apache.harmony.jpda.tests.share.JPDADebuggeeSynchronizer;
/**
* JDWP unit test for ClassType.SuperClass command.
* Contains three testcases: testSuperClass001, testSuperClass002, testSuperClass003.
*/
public class SuperClassTest extends JDWPClassTypeTestCase {
private ReplyPacket jdwpGetSuperClassReply(long classID, int errorExpected) {
CommandPacket packet = new CommandPacket(
JDWPCommands.ClassTypeCommandSet.CommandSetID,
JDWPCommands.ClassTypeCommandSet.SuperclassCommand);
packet.setNextValueAsClassID(classID);
ReplyPacket reply = debuggeeWrapper.vmMirror.performCommand(packet);
checkReplyPacket(reply, "ClassType.Superclass command", errorExpected);
return reply;
}
private void asserSuperClassReplyIsValid(ReplyPacket reply, String expectedSignature) {
assertTrue(reply.getErrorCode() == JDWPConstants.Error.NONE);
long superClassID = reply.getNextValueAsClassID();
logWriter.println("superClassID=" + superClassID);
if (superClassID == 0) {
// for superclass of Object expectedSignature is null
assertNull
("ClassType::Superclass command returned invalid expectedSignature that must be null",
expectedSignature);
} else {
String signature = getClassSignature(superClassID);
logWriter.println("Signature: "+signature);
assertString("ClassType::Superclass command returned invalid signature,",
expectedSignature, signature);
}
}
/**
* This testcase exercises ClassType.Superclass command.
* <BR>Starts <A HREF="ClassTypeDebuggee.html">ClassTypeDebuggee</A>.
* <BR>Then does the following checks:
* <BR> - superclass for java.lang.String is java.lang.Object;
* <BR> - superclass for array of Objects is java.lang.Object;
* <BR> - superclass for primitive array is java.lang.Object;
* <BR> - superclass for <A HREF="ClassTypeDebuggee.html">ClassTypeDebuggee</A>
* class is <A HREF="../../share/SyncDebuggee.html">SyncDebuggee</A> class.;
*/
public void testSuperClass001() throws UnsupportedEncodingException {
logWriter.println("testSuperClassTest001 started");
synchronizer.receiveMessage(JPDADebuggeeSynchronizer.SGNL_READY);
// check that superclass for java.lang.String is java.lang.Object
{
// test with String[] class
long classID = getClassIDBySignature("Ljava/lang/String;");
ReplyPacket reply = jdwpGetSuperClassReply(classID, JDWPConstants.Error.NONE);
// complare returned signature with superclass signature
asserSuperClassReplyIsValid(reply, "Ljava/lang/Object;");
}
// check that superclass for array is java.lang.Object
{
// test with String[] class
long classID = getClassIDBySignature("[Ljava/lang/String;");
ReplyPacket reply = jdwpGetSuperClassReply(classID, JDWPConstants.Error.NONE);
// complare returned signature with superclass signature
asserSuperClassReplyIsValid(reply, "Ljava/lang/Object;");
}
// check that superclass for primitive array is java.lang.Object
{
// test with int[] class
long classID = getClassIDBySignature("[I");
ReplyPacket reply = jdwpGetSuperClassReply(classID, JDWPConstants.Error.NONE);
// complare returned signature with superclass signature
asserSuperClassReplyIsValid(reply, "Ljava/lang/Object;");
}
// check that superclass for Debuggee is SyncDebuggee
{
long classID = getClassIDBySignature(getDebuggeeSignature());
ReplyPacket reply = jdwpGetSuperClassReply(classID, JDWPConstants.Error.NONE);
// complare returned signature with superclass signature
asserSuperClassReplyIsValid(reply, "Lorg/apache/harmony/jpda/tests/share/SyncDebuggee;");
}
// check that there is no superclass for java.lang.Object
{
// test with java.lang.Object class
long classID = getClassIDBySignature("Ljava/lang/Object;");
ReplyPacket reply = jdwpGetSuperClassReply(classID, JDWPConstants.Error.NONE);
// complare returned signature with superclass signature
// (expects null for this case)
asserSuperClassReplyIsValid(reply, null);
}
synchronizer.sendMessage(JPDADebuggeeSynchronizer.SGNL_CONTINUE);
}
/**
* This testcase exercises ClassType.Superclass command.
* <BR>Starts <A HREF="ClassTypeDebuggee.html">ClassTypeDebuggee</A>.
* <BR>Then does the following checks:
* <BR> - there is no superclass for interface;
* <BR> - INVALID_OBJECT is returned if classID is non-existent;
* <BR> - INVALID_OBJECT is returned if instead of classID FieldID is passed;
*/
public void testSuperClass002() throws UnsupportedEncodingException {
logWriter.println("testSuperClassTest002 started");
synchronizer.receiveMessage(JPDADebuggeeSynchronizer.SGNL_READY);
// check that there is no superclass for interface objects
{
long interfaceID = getClassIDBySignature("Ljava/lang/Cloneable;");
ReplyPacket reply = jdwpGetSuperClassReply(interfaceID, JDWPConstants.Error.NONE);
// compare returned signature with superclass signature
// (null for interfaces)
asserSuperClassReplyIsValid(reply, null);
}
// check that INVALID_OBJECT returns if classID is non-existent
{
jdwpGetSuperClassReply(10000
, JDWPConstants.Error.INVALID_OBJECT);
}
// check that reply error code is INVALID_OBJECT for a FieldID Out Data
{
long classID = getClassIDBySignature(getDebuggeeSignature());
FieldInfo[] fields = jdwpGetFields(classID);
// assert stringID is not null
assertTrue("Invalid fields.length: 0", fields.length > 0);
// test with the first field
jdwpGetSuperClassReply(fields[0].getFieldID()
, JDWPConstants.Error.INVALID_OBJECT);
}
synchronizer.sendMessage(JPDADebuggeeSynchronizer.SGNL_CONTINUE);
}
/**
* This testcase exercises ClassType.Superclass command.
* <BR>Starts <A HREF="ClassTypeDebuggee.html">ClassTypeDebuggee</A>.
* <BR>Then does the following check:
* <BR> - INVALID_CLASS is returned if instead of classID ObjectID is passed;
*/
public void testSuperClass003() throws UnsupportedEncodingException {
logWriter.println("testSuperClassTest003 started");
synchronizer.receiveMessage(JPDADebuggeeSynchronizer.SGNL_READY);
// check that reply error code is INVALID_CLASS for a StringID Out Data
{
long stringID = createString("Some test string");
// assert stringID is not null
assertFalse("Invalid stringID: 0", stringID == 0);
jdwpGetSuperClassReply(stringID, JDWPConstants.Error.INVALID_CLASS);
}
synchronizer.sendMessage(JPDADebuggeeSynchronizer.SGNL_CONTINUE);
}
}
|
s20121035/rk3288_android5.1_repo
|
external/apache-harmony/jdwp/src/test/java/org/apache/harmony/jpda/tests/jdwp/ClassType/SuperClassTest.java
|
Java
|
gpl-3.0
| 8,687
|
// Copyright 2005, 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.
//
// Tests for Google Test itself. This verifies that the basic constructs of
// Google Test work.
#include "gtest/gtest.h"
// Verifies that the command line flag variables can be accessed in
// code once "gtest.h" has been #included.
// Do not move it after other gtest #includes.
TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) {
bool dummy =
GTEST_FLAG_GET(also_run_disabled_tests) ||
GTEST_FLAG_GET(break_on_failure) || GTEST_FLAG_GET(catch_exceptions) ||
GTEST_FLAG_GET(color) != "unknown" || GTEST_FLAG_GET(fail_fast) ||
GTEST_FLAG_GET(filter) != "unknown" || GTEST_FLAG_GET(list_tests) ||
GTEST_FLAG_GET(output) != "unknown" || GTEST_FLAG_GET(brief) ||
GTEST_FLAG_GET(print_time) || GTEST_FLAG_GET(random_seed) ||
GTEST_FLAG_GET(repeat) > 0 ||
GTEST_FLAG_GET(recreate_environments_when_repeating) ||
GTEST_FLAG_GET(show_internal_stack_frames) || GTEST_FLAG_GET(shuffle) ||
GTEST_FLAG_GET(stack_trace_depth) > 0 ||
GTEST_FLAG_GET(stream_result_to) != "unknown" ||
GTEST_FLAG_GET(throw_on_failure);
EXPECT_TRUE(dummy || !dummy); // Suppresses warning that dummy is unused.
}
#include <limits.h> // For INT_MAX.
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <cstdint>
#include <map>
#include <ostream>
#include <string>
#include <type_traits>
#include <unordered_set>
#include <vector>
#include "gtest/gtest-spi.h"
#include "src/gtest-internal-inl.h"
namespace testing {
namespace internal {
#if GTEST_CAN_STREAM_RESULTS_
class StreamingListenerTest : public Test {
public:
class FakeSocketWriter : public StreamingListener::AbstractSocketWriter {
public:
// Sends a string to the socket.
void Send(const std::string& message) override { output_ += message; }
std::string output_;
};
StreamingListenerTest()
: fake_sock_writer_(new FakeSocketWriter),
streamer_(fake_sock_writer_),
test_info_obj_("FooTest", "Bar", nullptr, nullptr,
CodeLocation(__FILE__, __LINE__), nullptr, nullptr) {}
protected:
std::string* output() { return &(fake_sock_writer_->output_); }
FakeSocketWriter* const fake_sock_writer_;
StreamingListener streamer_;
UnitTest unit_test_;
TestInfo test_info_obj_; // The name test_info_ was taken by testing::Test.
};
TEST_F(StreamingListenerTest, OnTestProgramEnd) {
*output() = "";
streamer_.OnTestProgramEnd(unit_test_);
EXPECT_EQ("event=TestProgramEnd&passed=1\n", *output());
}
TEST_F(StreamingListenerTest, OnTestIterationEnd) {
*output() = "";
streamer_.OnTestIterationEnd(unit_test_, 42);
EXPECT_EQ("event=TestIterationEnd&passed=1&elapsed_time=0ms\n", *output());
}
TEST_F(StreamingListenerTest, OnTestCaseStart) {
*output() = "";
streamer_.OnTestCaseStart(TestCase("FooTest", "Bar", nullptr, nullptr));
EXPECT_EQ("event=TestCaseStart&name=FooTest\n", *output());
}
TEST_F(StreamingListenerTest, OnTestCaseEnd) {
*output() = "";
streamer_.OnTestCaseEnd(TestCase("FooTest", "Bar", nullptr, nullptr));
EXPECT_EQ("event=TestCaseEnd&passed=1&elapsed_time=0ms\n", *output());
}
TEST_F(StreamingListenerTest, OnTestStart) {
*output() = "";
streamer_.OnTestStart(test_info_obj_);
EXPECT_EQ("event=TestStart&name=Bar\n", *output());
}
TEST_F(StreamingListenerTest, OnTestEnd) {
*output() = "";
streamer_.OnTestEnd(test_info_obj_);
EXPECT_EQ("event=TestEnd&passed=1&elapsed_time=0ms\n", *output());
}
TEST_F(StreamingListenerTest, OnTestPartResult) {
*output() = "";
streamer_.OnTestPartResult(TestPartResult(
TestPartResult::kFatalFailure, "foo.cc", 42, "failed=\n&%"));
// Meta characters in the failure message should be properly escaped.
EXPECT_EQ(
"event=TestPartResult&file=foo.cc&line=42&message=failed%3D%0A%26%25\n",
*output());
}
#endif // GTEST_CAN_STREAM_RESULTS_
// Provides access to otherwise private parts of the TestEventListeners class
// that are needed to test it.
class TestEventListenersAccessor {
public:
static TestEventListener* GetRepeater(TestEventListeners* listeners) {
return listeners->repeater();
}
static void SetDefaultResultPrinter(TestEventListeners* listeners,
TestEventListener* listener) {
listeners->SetDefaultResultPrinter(listener);
}
static void SetDefaultXmlGenerator(TestEventListeners* listeners,
TestEventListener* listener) {
listeners->SetDefaultXmlGenerator(listener);
}
static bool EventForwardingEnabled(const TestEventListeners& listeners) {
return listeners.EventForwardingEnabled();
}
static void SuppressEventForwarding(TestEventListeners* listeners) {
listeners->SuppressEventForwarding();
}
};
class UnitTestRecordPropertyTestHelper : public Test {
protected:
UnitTestRecordPropertyTestHelper() {}
// Forwards to UnitTest::RecordProperty() to bypass access controls.
void UnitTestRecordProperty(const char* key, const std::string& value) {
unit_test_.RecordProperty(key, value);
}
UnitTest unit_test_;
};
} // namespace internal
} // namespace testing
using testing::AssertionFailure;
using testing::AssertionResult;
using testing::AssertionSuccess;
using testing::DoubleLE;
using testing::EmptyTestEventListener;
using testing::Environment;
using testing::FloatLE;
using testing::IsNotSubstring;
using testing::IsSubstring;
using testing::kMaxStackTraceDepth;
using testing::Message;
using testing::ScopedFakeTestPartResultReporter;
using testing::StaticAssertTypeEq;
using testing::Test;
using testing::TestEventListeners;
using testing::TestInfo;
using testing::TestPartResult;
using testing::TestPartResultArray;
using testing::TestProperty;
using testing::TestResult;
using testing::TestSuite;
using testing::TimeInMillis;
using testing::UnitTest;
using testing::internal::AlwaysFalse;
using testing::internal::AlwaysTrue;
using testing::internal::AppendUserMessage;
using testing::internal::ArrayAwareFind;
using testing::internal::ArrayEq;
using testing::internal::CodePointToUtf8;
using testing::internal::CopyArray;
using testing::internal::CountIf;
using testing::internal::EqFailure;
using testing::internal::FloatingPoint;
using testing::internal::ForEach;
using testing::internal::FormatEpochTimeInMillisAsIso8601;
using testing::internal::FormatTimeInMillisAsSeconds;
using testing::internal::GetCurrentOsStackTraceExceptTop;
using testing::internal::GetElementOr;
using testing::internal::GetNextRandomSeed;
using testing::internal::GetRandomSeedFromFlag;
using testing::internal::GetTestTypeId;
using testing::internal::GetTimeInMillis;
using testing::internal::GetTypeId;
using testing::internal::GetUnitTestImpl;
using testing::internal::GTestFlagSaver;
using testing::internal::HasDebugStringAndShortDebugString;
using testing::internal::Int32FromEnvOrDie;
using testing::internal::IsContainer;
using testing::internal::IsContainerTest;
using testing::internal::IsNotContainer;
using testing::internal::kMaxRandomSeed;
using testing::internal::kTestTypeIdInGoogleTest;
using testing::internal::NativeArray;
using testing::internal::OsStackTraceGetter;
using testing::internal::OsStackTraceGetterInterface;
using testing::internal::ParseFlag;
using testing::internal::RelationToSourceCopy;
using testing::internal::RelationToSourceReference;
using testing::internal::ShouldRunTestOnShard;
using testing::internal::ShouldShard;
using testing::internal::ShouldUseColor;
using testing::internal::Shuffle;
using testing::internal::ShuffleRange;
using testing::internal::SkipPrefix;
using testing::internal::StreamableToString;
using testing::internal::String;
using testing::internal::TestEventListenersAccessor;
using testing::internal::TestResultAccessor;
using testing::internal::UnitTestImpl;
using testing::internal::WideStringToUtf8;
using testing::internal::edit_distance::CalculateOptimalEdits;
using testing::internal::edit_distance::CreateUnifiedDiff;
using testing::internal::edit_distance::EditType;
#if GTEST_HAS_STREAM_REDIRECTION
using testing::internal::CaptureStdout;
using testing::internal::GetCapturedStdout;
#endif
#if GTEST_IS_THREADSAFE
using testing::internal::ThreadWithParam;
#endif
class TestingVector : public std::vector<int> {
};
::std::ostream& operator<<(::std::ostream& os,
const TestingVector& vector) {
os << "{ ";
for (size_t i = 0; i < vector.size(); i++) {
os << vector[i] << " ";
}
os << "}";
return os;
}
// This line tests that we can define tests in an unnamed namespace.
namespace {
TEST(GetRandomSeedFromFlagTest, HandlesZero) {
const int seed = GetRandomSeedFromFlag(0);
EXPECT_LE(1, seed);
EXPECT_LE(seed, static_cast<int>(kMaxRandomSeed));
}
TEST(GetRandomSeedFromFlagTest, PreservesValidSeed) {
EXPECT_EQ(1, GetRandomSeedFromFlag(1));
EXPECT_EQ(2, GetRandomSeedFromFlag(2));
EXPECT_EQ(kMaxRandomSeed - 1, GetRandomSeedFromFlag(kMaxRandomSeed - 1));
EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
GetRandomSeedFromFlag(kMaxRandomSeed));
}
TEST(GetRandomSeedFromFlagTest, NormalizesInvalidSeed) {
const int seed1 = GetRandomSeedFromFlag(-1);
EXPECT_LE(1, seed1);
EXPECT_LE(seed1, static_cast<int>(kMaxRandomSeed));
const int seed2 = GetRandomSeedFromFlag(kMaxRandomSeed + 1);
EXPECT_LE(1, seed2);
EXPECT_LE(seed2, static_cast<int>(kMaxRandomSeed));
}
TEST(GetNextRandomSeedTest, WorksForValidInput) {
EXPECT_EQ(2, GetNextRandomSeed(1));
EXPECT_EQ(3, GetNextRandomSeed(2));
EXPECT_EQ(static_cast<int>(kMaxRandomSeed),
GetNextRandomSeed(kMaxRandomSeed - 1));
EXPECT_EQ(1, GetNextRandomSeed(kMaxRandomSeed));
// We deliberately don't test GetNextRandomSeed() with invalid
// inputs, as that requires death tests, which are expensive. This
// is fine as GetNextRandomSeed() is internal and has a
// straightforward definition.
}
static void ClearCurrentTestPartResults() {
TestResultAccessor::ClearTestPartResults(
GetUnitTestImpl()->current_test_result());
}
// Tests GetTypeId.
TEST(GetTypeIdTest, ReturnsSameValueForSameType) {
EXPECT_EQ(GetTypeId<int>(), GetTypeId<int>());
EXPECT_EQ(GetTypeId<Test>(), GetTypeId<Test>());
}
class SubClassOfTest : public Test {};
class AnotherSubClassOfTest : public Test {};
TEST(GetTypeIdTest, ReturnsDifferentValuesForDifferentTypes) {
EXPECT_NE(GetTypeId<int>(), GetTypeId<const int>());
EXPECT_NE(GetTypeId<int>(), GetTypeId<char>());
EXPECT_NE(GetTypeId<int>(), GetTestTypeId());
EXPECT_NE(GetTypeId<SubClassOfTest>(), GetTestTypeId());
EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTestTypeId());
EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTypeId<SubClassOfTest>());
}
// Verifies that GetTestTypeId() returns the same value, no matter it
// is called from inside Google Test or outside of it.
TEST(GetTestTypeIdTest, ReturnsTheSameValueInsideOrOutsideOfGoogleTest) {
EXPECT_EQ(kTestTypeIdInGoogleTest, GetTestTypeId());
}
// Tests CanonicalizeForStdLibVersioning.
using ::testing::internal::CanonicalizeForStdLibVersioning;
TEST(CanonicalizeForStdLibVersioning, LeavesUnversionedNamesUnchanged) {
EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::bind"));
EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::_"));
EXPECT_EQ("std::__foo", CanonicalizeForStdLibVersioning("std::__foo"));
EXPECT_EQ("gtl::__1::x", CanonicalizeForStdLibVersioning("gtl::__1::x"));
EXPECT_EQ("__1::x", CanonicalizeForStdLibVersioning("__1::x"));
EXPECT_EQ("::__1::x", CanonicalizeForStdLibVersioning("::__1::x"));
}
TEST(CanonicalizeForStdLibVersioning, ElidesDoubleUnderNames) {
EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::__1::bind"));
EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__1::_"));
EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::__g::bind"));
EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__g::_"));
EXPECT_EQ("std::bind",
CanonicalizeForStdLibVersioning("std::__google::bind"));
EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__google::_"));
}
// Tests FormatTimeInMillisAsSeconds().
TEST(FormatTimeInMillisAsSecondsTest, FormatsZero) {
EXPECT_EQ("0", FormatTimeInMillisAsSeconds(0));
}
TEST(FormatTimeInMillisAsSecondsTest, FormatsPositiveNumber) {
EXPECT_EQ("0.003", FormatTimeInMillisAsSeconds(3));
EXPECT_EQ("0.01", FormatTimeInMillisAsSeconds(10));
EXPECT_EQ("0.2", FormatTimeInMillisAsSeconds(200));
EXPECT_EQ("1.2", FormatTimeInMillisAsSeconds(1200));
EXPECT_EQ("3", FormatTimeInMillisAsSeconds(3000));
}
TEST(FormatTimeInMillisAsSecondsTest, FormatsNegativeNumber) {
EXPECT_EQ("-0.003", FormatTimeInMillisAsSeconds(-3));
EXPECT_EQ("-0.01", FormatTimeInMillisAsSeconds(-10));
EXPECT_EQ("-0.2", FormatTimeInMillisAsSeconds(-200));
EXPECT_EQ("-1.2", FormatTimeInMillisAsSeconds(-1200));
EXPECT_EQ("-3", FormatTimeInMillisAsSeconds(-3000));
}
// Tests FormatEpochTimeInMillisAsIso8601(). The correctness of conversion
// for particular dates below was verified in Python using
// datetime.datetime.fromutctimestamp(<timetamp>/1000).
// FormatEpochTimeInMillisAsIso8601 depends on the current timezone, so we
// have to set up a particular timezone to obtain predictable results.
class FormatEpochTimeInMillisAsIso8601Test : public Test {
public:
// On Cygwin, GCC doesn't allow unqualified integer literals to exceed
// 32 bits, even when 64-bit integer types are available. We have to
// force the constants to have a 64-bit type here.
static const TimeInMillis kMillisPerSec = 1000;
private:
void SetUp() override {
saved_tz_ = nullptr;
GTEST_DISABLE_MSC_DEPRECATED_PUSH_(/* getenv, strdup: deprecated */)
if (getenv("TZ"))
saved_tz_ = strdup(getenv("TZ"));
GTEST_DISABLE_MSC_DEPRECATED_POP_()
// Set up the time zone for FormatEpochTimeInMillisAsIso8601 to use. We
// cannot use the local time zone because the function's output depends
// on the time zone.
SetTimeZone("UTC+00");
}
void TearDown() override {
SetTimeZone(saved_tz_);
free(const_cast<char*>(saved_tz_));
saved_tz_ = nullptr;
}
static void SetTimeZone(const char* time_zone) {
// tzset() distinguishes between the TZ variable being present and empty
// and not being present, so we have to consider the case of time_zone
// being NULL.
#if _MSC_VER || GTEST_OS_WINDOWS_MINGW
// ...Unless it's MSVC, whose standard library's _putenv doesn't
// distinguish between an empty and a missing variable.
const std::string env_var =
std::string("TZ=") + (time_zone ? time_zone : "");
_putenv(env_var.c_str());
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996 /* deprecated function */)
tzset();
GTEST_DISABLE_MSC_WARNINGS_POP_()
#else
if (time_zone) {
setenv(("TZ"), time_zone, 1);
} else {
unsetenv("TZ");
}
tzset();
#endif
}
const char* saved_tz_;
};
const TimeInMillis FormatEpochTimeInMillisAsIso8601Test::kMillisPerSec;
TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsTwoDigitSegments) {
EXPECT_EQ("2011-10-31T18:52:42.000",
FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec));
}
TEST_F(FormatEpochTimeInMillisAsIso8601Test, IncludesMillisecondsAfterDot) {
EXPECT_EQ(
"2011-10-31T18:52:42.234",
FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec + 234));
}
TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsLeadingZeroes) {
EXPECT_EQ("2011-09-03T05:07:02.000",
FormatEpochTimeInMillisAsIso8601(1315026422 * kMillisPerSec));
}
TEST_F(FormatEpochTimeInMillisAsIso8601Test, Prints24HourTime) {
EXPECT_EQ("2011-09-28T17:08:22.000",
FormatEpochTimeInMillisAsIso8601(1317229702 * kMillisPerSec));
}
TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsEpochStart) {
EXPECT_EQ("1970-01-01T00:00:00.000", FormatEpochTimeInMillisAsIso8601(0));
}
# ifdef __BORLANDC__
// Silences warnings: "Condition is always true", "Unreachable code"
# pragma option push -w-ccc -w-rch
# endif
// Tests that the LHS of EXPECT_EQ or ASSERT_EQ can be used as a null literal
// when the RHS is a pointer type.
TEST(NullLiteralTest, LHSAllowsNullLiterals) {
EXPECT_EQ(0, static_cast<void*>(nullptr)); // NOLINT
ASSERT_EQ(0, static_cast<void*>(nullptr)); // NOLINT
EXPECT_EQ(NULL, static_cast<void*>(nullptr)); // NOLINT
ASSERT_EQ(NULL, static_cast<void*>(nullptr)); // NOLINT
EXPECT_EQ(nullptr, static_cast<void*>(nullptr));
ASSERT_EQ(nullptr, static_cast<void*>(nullptr));
const int* const p = nullptr;
EXPECT_EQ(0, p); // NOLINT
ASSERT_EQ(0, p); // NOLINT
EXPECT_EQ(NULL, p); // NOLINT
ASSERT_EQ(NULL, p); // NOLINT
EXPECT_EQ(nullptr, p);
ASSERT_EQ(nullptr, p);
}
struct ConvertToAll {
template <typename T>
operator T() const { // NOLINT
return T();
}
};
struct ConvertToPointer {
template <class T>
operator T*() const { // NOLINT
return nullptr;
}
};
struct ConvertToAllButNoPointers {
template <typename T,
typename std::enable_if<!std::is_pointer<T>::value, int>::type = 0>
operator T() const { // NOLINT
return T();
}
};
struct MyType {};
inline bool operator==(MyType const&, MyType const&) { return true; }
TEST(NullLiteralTest, ImplicitConversion) {
EXPECT_EQ(ConvertToPointer{}, static_cast<void*>(nullptr));
#if !defined(__GNUC__) || defined(__clang__)
// Disabled due to GCC bug gcc.gnu.org/PR89580
EXPECT_EQ(ConvertToAll{}, static_cast<void*>(nullptr));
#endif
EXPECT_EQ(ConvertToAll{}, MyType{});
EXPECT_EQ(ConvertToAllButNoPointers{}, MyType{});
}
#ifdef __clang__
#pragma clang diagnostic push
#if __has_warning("-Wzero-as-null-pointer-constant")
#pragma clang diagnostic error "-Wzero-as-null-pointer-constant"
#endif
#endif
TEST(NullLiteralTest, NoConversionNoWarning) {
// Test that gtests detection and handling of null pointer constants
// doesn't trigger a warning when '0' isn't actually used as null.
EXPECT_EQ(0, 0);
ASSERT_EQ(0, 0);
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
# ifdef __BORLANDC__
// Restores warnings after previous "#pragma option push" suppressed them.
# pragma option pop
# endif
//
// Tests CodePointToUtf8().
// Tests that the NUL character L'\0' is encoded correctly.
TEST(CodePointToUtf8Test, CanEncodeNul) {
EXPECT_EQ("", CodePointToUtf8(L'\0'));
}
// Tests that ASCII characters are encoded correctly.
TEST(CodePointToUtf8Test, CanEncodeAscii) {
EXPECT_EQ("a", CodePointToUtf8(L'a'));
EXPECT_EQ("Z", CodePointToUtf8(L'Z'));
EXPECT_EQ("&", CodePointToUtf8(L'&'));
EXPECT_EQ("\x7F", CodePointToUtf8(L'\x7F'));
}
// Tests that Unicode code-points that have 8 to 11 bits are encoded
// as 110xxxxx 10xxxxxx.
TEST(CodePointToUtf8Test, CanEncode8To11Bits) {
// 000 1101 0011 => 110-00011 10-010011
EXPECT_EQ("\xC3\x93", CodePointToUtf8(L'\xD3'));
// 101 0111 0110 => 110-10101 10-110110
// Some compilers (e.g., GCC on MinGW) cannot handle non-ASCII codepoints
// in wide strings and wide chars. In order to accommodate them, we have to
// introduce such character constants as integers.
EXPECT_EQ("\xD5\xB6",
CodePointToUtf8(static_cast<wchar_t>(0x576)));
}
// Tests that Unicode code-points that have 12 to 16 bits are encoded
// as 1110xxxx 10xxxxxx 10xxxxxx.
TEST(CodePointToUtf8Test, CanEncode12To16Bits) {
// 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
EXPECT_EQ("\xE0\xA3\x93",
CodePointToUtf8(static_cast<wchar_t>(0x8D3)));
// 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
EXPECT_EQ("\xEC\x9D\x8D",
CodePointToUtf8(static_cast<wchar_t>(0xC74D)));
}
#if !GTEST_WIDE_STRING_USES_UTF16_
// Tests in this group require a wchar_t to hold > 16 bits, and thus
// are skipped on Windows, and Cygwin, where a wchar_t is
// 16-bit wide. This code may not compile on those systems.
// Tests that Unicode code-points that have 17 to 21 bits are encoded
// as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx.
TEST(CodePointToUtf8Test, CanEncode17To21Bits) {
// 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
EXPECT_EQ("\xF0\x90\xA3\x93", CodePointToUtf8(L'\x108D3'));
// 0 0001 0000 0100 0000 0000 => 11110-000 10-010000 10-010000 10-000000
EXPECT_EQ("\xF0\x90\x90\x80", CodePointToUtf8(L'\x10400'));
// 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
EXPECT_EQ("\xF4\x88\x98\xB4", CodePointToUtf8(L'\x108634'));
}
// Tests that encoding an invalid code-point generates the expected result.
TEST(CodePointToUtf8Test, CanEncodeInvalidCodePoint) {
EXPECT_EQ("(Invalid Unicode 0x1234ABCD)", CodePointToUtf8(L'\x1234ABCD'));
}
#endif // !GTEST_WIDE_STRING_USES_UTF16_
// Tests WideStringToUtf8().
// Tests that the NUL character L'\0' is encoded correctly.
TEST(WideStringToUtf8Test, CanEncodeNul) {
EXPECT_STREQ("", WideStringToUtf8(L"", 0).c_str());
EXPECT_STREQ("", WideStringToUtf8(L"", -1).c_str());
}
// Tests that ASCII strings are encoded correctly.
TEST(WideStringToUtf8Test, CanEncodeAscii) {
EXPECT_STREQ("a", WideStringToUtf8(L"a", 1).c_str());
EXPECT_STREQ("ab", WideStringToUtf8(L"ab", 2).c_str());
EXPECT_STREQ("a", WideStringToUtf8(L"a", -1).c_str());
EXPECT_STREQ("ab", WideStringToUtf8(L"ab", -1).c_str());
}
// Tests that Unicode code-points that have 8 to 11 bits are encoded
// as 110xxxxx 10xxxxxx.
TEST(WideStringToUtf8Test, CanEncode8To11Bits) {
// 000 1101 0011 => 110-00011 10-010011
EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", 1).c_str());
EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", -1).c_str());
// 101 0111 0110 => 110-10101 10-110110
const wchar_t s[] = { 0x576, '\0' };
EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, 1).c_str());
EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, -1).c_str());
}
// Tests that Unicode code-points that have 12 to 16 bits are encoded
// as 1110xxxx 10xxxxxx 10xxxxxx.
TEST(WideStringToUtf8Test, CanEncode12To16Bits) {
// 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011
const wchar_t s1[] = { 0x8D3, '\0' };
EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, 1).c_str());
EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, -1).c_str());
// 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101
const wchar_t s2[] = { 0xC74D, '\0' };
EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, 1).c_str());
EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, -1).c_str());
}
// Tests that the conversion stops when the function encounters \0 character.
TEST(WideStringToUtf8Test, StopsOnNulCharacter) {
EXPECT_STREQ("ABC", WideStringToUtf8(L"ABC\0XYZ", 100).c_str());
}
// Tests that the conversion stops when the function reaches the limit
// specified by the 'length' parameter.
TEST(WideStringToUtf8Test, StopsWhenLengthLimitReached) {
EXPECT_STREQ("ABC", WideStringToUtf8(L"ABCDEF", 3).c_str());
}
#if !GTEST_WIDE_STRING_USES_UTF16_
// Tests that Unicode code-points that have 17 to 21 bits are encoded
// as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx. This code may not compile
// on the systems using UTF-16 encoding.
TEST(WideStringToUtf8Test, CanEncode17To21Bits) {
// 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011
EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", 1).c_str());
EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", -1).c_str());
// 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100
EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", 1).c_str());
EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", -1).c_str());
}
// Tests that encoding an invalid code-point generates the expected result.
TEST(WideStringToUtf8Test, CanEncodeInvalidCodePoint) {
EXPECT_STREQ("(Invalid Unicode 0xABCDFF)",
WideStringToUtf8(L"\xABCDFF", -1).c_str());
}
#else // !GTEST_WIDE_STRING_USES_UTF16_
// Tests that surrogate pairs are encoded correctly on the systems using
// UTF-16 encoding in the wide strings.
TEST(WideStringToUtf8Test, CanEncodeValidUtf16SUrrogatePairs) {
const wchar_t s[] = { 0xD801, 0xDC00, '\0' };
EXPECT_STREQ("\xF0\x90\x90\x80", WideStringToUtf8(s, -1).c_str());
}
// Tests that encoding an invalid UTF-16 surrogate pair
// generates the expected result.
TEST(WideStringToUtf8Test, CanEncodeInvalidUtf16SurrogatePair) {
// Leading surrogate is at the end of the string.
const wchar_t s1[] = { 0xD800, '\0' };
EXPECT_STREQ("\xED\xA0\x80", WideStringToUtf8(s1, -1).c_str());
// Leading surrogate is not followed by the trailing surrogate.
const wchar_t s2[] = { 0xD800, 'M', '\0' };
EXPECT_STREQ("\xED\xA0\x80M", WideStringToUtf8(s2, -1).c_str());
// Trailing surrogate appearas without a leading surrogate.
const wchar_t s3[] = { 0xDC00, 'P', 'Q', 'R', '\0' };
EXPECT_STREQ("\xED\xB0\x80PQR", WideStringToUtf8(s3, -1).c_str());
}
#endif // !GTEST_WIDE_STRING_USES_UTF16_
// Tests that codepoint concatenation works correctly.
#if !GTEST_WIDE_STRING_USES_UTF16_
TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
const wchar_t s[] = { 0x108634, 0xC74D, '\n', 0x576, 0x8D3, 0x108634, '\0'};
EXPECT_STREQ(
"\xF4\x88\x98\xB4"
"\xEC\x9D\x8D"
"\n"
"\xD5\xB6"
"\xE0\xA3\x93"
"\xF4\x88\x98\xB4",
WideStringToUtf8(s, -1).c_str());
}
#else
TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {
const wchar_t s[] = { 0xC74D, '\n', 0x576, 0x8D3, '\0'};
EXPECT_STREQ(
"\xEC\x9D\x8D" "\n" "\xD5\xB6" "\xE0\xA3\x93",
WideStringToUtf8(s, -1).c_str());
}
#endif // !GTEST_WIDE_STRING_USES_UTF16_
// Tests the Random class.
TEST(RandomDeathTest, GeneratesCrashesOnInvalidRange) {
testing::internal::Random random(42);
EXPECT_DEATH_IF_SUPPORTED(
random.Generate(0),
"Cannot generate a number in the range \\[0, 0\\)");
EXPECT_DEATH_IF_SUPPORTED(
random.Generate(testing::internal::Random::kMaxRange + 1),
"Generation of a number in \\[0, 2147483649\\) was requested, "
"but this can only generate numbers in \\[0, 2147483648\\)");
}
TEST(RandomTest, GeneratesNumbersWithinRange) {
constexpr uint32_t kRange = 10000;
testing::internal::Random random(12345);
for (int i = 0; i < 10; i++) {
EXPECT_LT(random.Generate(kRange), kRange) << " for iteration " << i;
}
testing::internal::Random random2(testing::internal::Random::kMaxRange);
for (int i = 0; i < 10; i++) {
EXPECT_LT(random2.Generate(kRange), kRange) << " for iteration " << i;
}
}
TEST(RandomTest, RepeatsWhenReseeded) {
constexpr int kSeed = 123;
constexpr int kArraySize = 10;
constexpr uint32_t kRange = 10000;
uint32_t values[kArraySize];
testing::internal::Random random(kSeed);
for (int i = 0; i < kArraySize; i++) {
values[i] = random.Generate(kRange);
}
random.Reseed(kSeed);
for (int i = 0; i < kArraySize; i++) {
EXPECT_EQ(values[i], random.Generate(kRange)) << " for iteration " << i;
}
}
// Tests STL container utilities.
// Tests CountIf().
static bool IsPositive(int n) { return n > 0; }
TEST(ContainerUtilityTest, CountIf) {
std::vector<int> v;
EXPECT_EQ(0, CountIf(v, IsPositive)); // Works for an empty container.
v.push_back(-1);
v.push_back(0);
EXPECT_EQ(0, CountIf(v, IsPositive)); // Works when no value satisfies.
v.push_back(2);
v.push_back(-10);
v.push_back(10);
EXPECT_EQ(2, CountIf(v, IsPositive));
}
// Tests ForEach().
static int g_sum = 0;
static void Accumulate(int n) { g_sum += n; }
TEST(ContainerUtilityTest, ForEach) {
std::vector<int> v;
g_sum = 0;
ForEach(v, Accumulate);
EXPECT_EQ(0, g_sum); // Works for an empty container;
g_sum = 0;
v.push_back(1);
ForEach(v, Accumulate);
EXPECT_EQ(1, g_sum); // Works for a container with one element.
g_sum = 0;
v.push_back(20);
v.push_back(300);
ForEach(v, Accumulate);
EXPECT_EQ(321, g_sum);
}
// Tests GetElementOr().
TEST(ContainerUtilityTest, GetElementOr) {
std::vector<char> a;
EXPECT_EQ('x', GetElementOr(a, 0, 'x'));
a.push_back('a');
a.push_back('b');
EXPECT_EQ('a', GetElementOr(a, 0, 'x'));
EXPECT_EQ('b', GetElementOr(a, 1, 'x'));
EXPECT_EQ('x', GetElementOr(a, -2, 'x'));
EXPECT_EQ('x', GetElementOr(a, 2, 'x'));
}
TEST(ContainerUtilityDeathTest, ShuffleRange) {
std::vector<int> a;
a.push_back(0);
a.push_back(1);
a.push_back(2);
testing::internal::Random random(1);
EXPECT_DEATH_IF_SUPPORTED(
ShuffleRange(&random, -1, 1, &a),
"Invalid shuffle range start -1: must be in range \\[0, 3\\]");
EXPECT_DEATH_IF_SUPPORTED(
ShuffleRange(&random, 4, 4, &a),
"Invalid shuffle range start 4: must be in range \\[0, 3\\]");
EXPECT_DEATH_IF_SUPPORTED(
ShuffleRange(&random, 3, 2, &a),
"Invalid shuffle range finish 2: must be in range \\[3, 3\\]");
EXPECT_DEATH_IF_SUPPORTED(
ShuffleRange(&random, 3, 4, &a),
"Invalid shuffle range finish 4: must be in range \\[3, 3\\]");
}
class VectorShuffleTest : public Test {
protected:
static const size_t kVectorSize = 20;
VectorShuffleTest() : random_(1) {
for (int i = 0; i < static_cast<int>(kVectorSize); i++) {
vector_.push_back(i);
}
}
static bool VectorIsCorrupt(const TestingVector& vector) {
if (kVectorSize != vector.size()) {
return true;
}
bool found_in_vector[kVectorSize] = { false };
for (size_t i = 0; i < vector.size(); i++) {
const int e = vector[i];
if (e < 0 || e >= static_cast<int>(kVectorSize) || found_in_vector[e]) {
return true;
}
found_in_vector[e] = true;
}
// Vector size is correct, elements' range is correct, no
// duplicate elements. Therefore no corruption has occurred.
return false;
}
static bool VectorIsNotCorrupt(const TestingVector& vector) {
return !VectorIsCorrupt(vector);
}
static bool RangeIsShuffled(const TestingVector& vector, int begin, int end) {
for (int i = begin; i < end; i++) {
if (i != vector[static_cast<size_t>(i)]) {
return true;
}
}
return false;
}
static bool RangeIsUnshuffled(
const TestingVector& vector, int begin, int end) {
return !RangeIsShuffled(vector, begin, end);
}
static bool VectorIsShuffled(const TestingVector& vector) {
return RangeIsShuffled(vector, 0, static_cast<int>(vector.size()));
}
static bool VectorIsUnshuffled(const TestingVector& vector) {
return !VectorIsShuffled(vector);
}
testing::internal::Random random_;
TestingVector vector_;
}; // class VectorShuffleTest
const size_t VectorShuffleTest::kVectorSize;
TEST_F(VectorShuffleTest, HandlesEmptyRange) {
// Tests an empty range at the beginning...
ShuffleRange(&random_, 0, 0, &vector_);
ASSERT_PRED1(VectorIsNotCorrupt, vector_);
ASSERT_PRED1(VectorIsUnshuffled, vector_);
// ...in the middle...
ShuffleRange(&random_, kVectorSize/2, kVectorSize/2, &vector_);
ASSERT_PRED1(VectorIsNotCorrupt, vector_);
ASSERT_PRED1(VectorIsUnshuffled, vector_);
// ...at the end...
ShuffleRange(&random_, kVectorSize - 1, kVectorSize - 1, &vector_);
ASSERT_PRED1(VectorIsNotCorrupt, vector_);
ASSERT_PRED1(VectorIsUnshuffled, vector_);
// ...and past the end.
ShuffleRange(&random_, kVectorSize, kVectorSize, &vector_);
ASSERT_PRED1(VectorIsNotCorrupt, vector_);
ASSERT_PRED1(VectorIsUnshuffled, vector_);
}
TEST_F(VectorShuffleTest, HandlesRangeOfSizeOne) {
// Tests a size one range at the beginning...
ShuffleRange(&random_, 0, 1, &vector_);
ASSERT_PRED1(VectorIsNotCorrupt, vector_);
ASSERT_PRED1(VectorIsUnshuffled, vector_);
// ...in the middle...
ShuffleRange(&random_, kVectorSize/2, kVectorSize/2 + 1, &vector_);
ASSERT_PRED1(VectorIsNotCorrupt, vector_);
ASSERT_PRED1(VectorIsUnshuffled, vector_);
// ...and at the end.
ShuffleRange(&random_, kVectorSize - 1, kVectorSize, &vector_);
ASSERT_PRED1(VectorIsNotCorrupt, vector_);
ASSERT_PRED1(VectorIsUnshuffled, vector_);
}
// Because we use our own random number generator and a fixed seed,
// we can guarantee that the following "random" tests will succeed.
TEST_F(VectorShuffleTest, ShufflesEntireVector) {
Shuffle(&random_, &vector_);
ASSERT_PRED1(VectorIsNotCorrupt, vector_);
EXPECT_FALSE(VectorIsUnshuffled(vector_)) << vector_;
// Tests the first and last elements in particular to ensure that
// there are no off-by-one problems in our shuffle algorithm.
EXPECT_NE(0, vector_[0]);
EXPECT_NE(static_cast<int>(kVectorSize - 1), vector_[kVectorSize - 1]);
}
TEST_F(VectorShuffleTest, ShufflesStartOfVector) {
const int kRangeSize = kVectorSize/2;
ShuffleRange(&random_, 0, kRangeSize, &vector_);
ASSERT_PRED1(VectorIsNotCorrupt, vector_);
EXPECT_PRED3(RangeIsShuffled, vector_, 0, kRangeSize);
EXPECT_PRED3(RangeIsUnshuffled, vector_, kRangeSize,
static_cast<int>(kVectorSize));
}
TEST_F(VectorShuffleTest, ShufflesEndOfVector) {
const int kRangeSize = kVectorSize / 2;
ShuffleRange(&random_, kRangeSize, kVectorSize, &vector_);
ASSERT_PRED1(VectorIsNotCorrupt, vector_);
EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize,
static_cast<int>(kVectorSize));
}
TEST_F(VectorShuffleTest, ShufflesMiddleOfVector) {
const int kRangeSize = static_cast<int>(kVectorSize) / 3;
ShuffleRange(&random_, kRangeSize, 2*kRangeSize, &vector_);
ASSERT_PRED1(VectorIsNotCorrupt, vector_);
EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);
EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, 2*kRangeSize);
EXPECT_PRED3(RangeIsUnshuffled, vector_, 2 * kRangeSize,
static_cast<int>(kVectorSize));
}
TEST_F(VectorShuffleTest, ShufflesRepeatably) {
TestingVector vector2;
for (size_t i = 0; i < kVectorSize; i++) {
vector2.push_back(static_cast<int>(i));
}
random_.Reseed(1234);
Shuffle(&random_, &vector_);
random_.Reseed(1234);
Shuffle(&random_, &vector2);
ASSERT_PRED1(VectorIsNotCorrupt, vector_);
ASSERT_PRED1(VectorIsNotCorrupt, vector2);
for (size_t i = 0; i < kVectorSize; i++) {
EXPECT_EQ(vector_[i], vector2[i]) << " where i is " << i;
}
}
// Tests the size of the AssertHelper class.
TEST(AssertHelperTest, AssertHelperIsSmall) {
// To avoid breaking clients that use lots of assertions in one
// function, we cannot grow the size of AssertHelper.
EXPECT_LE(sizeof(testing::internal::AssertHelper), sizeof(void*));
}
// Tests String::EndsWithCaseInsensitive().
TEST(StringTest, EndsWithCaseInsensitive) {
EXPECT_TRUE(String::EndsWithCaseInsensitive("foobar", "BAR"));
EXPECT_TRUE(String::EndsWithCaseInsensitive("foobaR", "bar"));
EXPECT_TRUE(String::EndsWithCaseInsensitive("foobar", ""));
EXPECT_TRUE(String::EndsWithCaseInsensitive("", ""));
EXPECT_FALSE(String::EndsWithCaseInsensitive("Foobar", "foo"));
EXPECT_FALSE(String::EndsWithCaseInsensitive("foobar", "Foo"));
EXPECT_FALSE(String::EndsWithCaseInsensitive("", "foo"));
}
// C++Builder's preprocessor is buggy; it fails to expand macros that
// appear in macro parameters after wide char literals. Provide an alias
// for NULL as a workaround.
static const wchar_t* const kNull = nullptr;
// Tests String::CaseInsensitiveWideCStringEquals
TEST(StringTest, CaseInsensitiveWideCStringEquals) {
EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(nullptr, nullptr));
EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L""));
EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"", kNull));
EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L"foobar"));
EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"foobar", kNull));
EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"foobar"));
EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"FOOBAR"));
EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"FOOBAR", L"foobar"));
}
#if GTEST_OS_WINDOWS
// Tests String::ShowWideCString().
TEST(StringTest, ShowWideCString) {
EXPECT_STREQ("(null)",
String::ShowWideCString(NULL).c_str());
EXPECT_STREQ("", String::ShowWideCString(L"").c_str());
EXPECT_STREQ("foo", String::ShowWideCString(L"foo").c_str());
}
# if GTEST_OS_WINDOWS_MOBILE
TEST(StringTest, AnsiAndUtf16Null) {
EXPECT_EQ(NULL, String::AnsiToUtf16(NULL));
EXPECT_EQ(NULL, String::Utf16ToAnsi(NULL));
}
TEST(StringTest, AnsiAndUtf16ConvertBasic) {
const char* ansi = String::Utf16ToAnsi(L"str");
EXPECT_STREQ("str", ansi);
delete [] ansi;
const WCHAR* utf16 = String::AnsiToUtf16("str");
EXPECT_EQ(0, wcsncmp(L"str", utf16, 3));
delete [] utf16;
}
TEST(StringTest, AnsiAndUtf16ConvertPathChars) {
const char* ansi = String::Utf16ToAnsi(L".:\\ \"*?");
EXPECT_STREQ(".:\\ \"*?", ansi);
delete [] ansi;
const WCHAR* utf16 = String::AnsiToUtf16(".:\\ \"*?");
EXPECT_EQ(0, wcsncmp(L".:\\ \"*?", utf16, 3));
delete [] utf16;
}
# endif // GTEST_OS_WINDOWS_MOBILE
#endif // GTEST_OS_WINDOWS
// Tests TestProperty construction.
TEST(TestPropertyTest, StringValue) {
TestProperty property("key", "1");
EXPECT_STREQ("key", property.key());
EXPECT_STREQ("1", property.value());
}
// Tests TestProperty replacing a value.
TEST(TestPropertyTest, ReplaceStringValue) {
TestProperty property("key", "1");
EXPECT_STREQ("1", property.value());
property.SetValue("2");
EXPECT_STREQ("2", property.value());
}
// AddFatalFailure() and AddNonfatalFailure() must be stand-alone
// functions (i.e. their definitions cannot be inlined at the call
// sites), or C++Builder won't compile the code.
static void AddFatalFailure() {
FAIL() << "Expected fatal failure.";
}
static void AddNonfatalFailure() {
ADD_FAILURE() << "Expected non-fatal failure.";
}
class ScopedFakeTestPartResultReporterTest : public Test {
public: // Must be public and not protected due to a bug in g++ 3.4.2.
enum FailureMode {
FATAL_FAILURE,
NONFATAL_FAILURE
};
static void AddFailure(FailureMode failure) {
if (failure == FATAL_FAILURE) {
AddFatalFailure();
} else {
AddNonfatalFailure();
}
}
};
// Tests that ScopedFakeTestPartResultReporter intercepts test
// failures.
TEST_F(ScopedFakeTestPartResultReporterTest, InterceptsTestFailures) {
TestPartResultArray results;
{
ScopedFakeTestPartResultReporter reporter(
ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD,
&results);
AddFailure(NONFATAL_FAILURE);
AddFailure(FATAL_FAILURE);
}
EXPECT_EQ(2, results.size());
EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
}
TEST_F(ScopedFakeTestPartResultReporterTest, DeprecatedConstructor) {
TestPartResultArray results;
{
// Tests, that the deprecated constructor still works.
ScopedFakeTestPartResultReporter reporter(&results);
AddFailure(NONFATAL_FAILURE);
}
EXPECT_EQ(1, results.size());
}
#if GTEST_IS_THREADSAFE
class ScopedFakeTestPartResultReporterWithThreadsTest
: public ScopedFakeTestPartResultReporterTest {
protected:
static void AddFailureInOtherThread(FailureMode failure) {
ThreadWithParam<FailureMode> thread(&AddFailure, failure, nullptr);
thread.Join();
}
};
TEST_F(ScopedFakeTestPartResultReporterWithThreadsTest,
InterceptsTestFailuresInAllThreads) {
TestPartResultArray results;
{
ScopedFakeTestPartResultReporter reporter(
ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, &results);
AddFailure(NONFATAL_FAILURE);
AddFailure(FATAL_FAILURE);
AddFailureInOtherThread(NONFATAL_FAILURE);
AddFailureInOtherThread(FATAL_FAILURE);
}
EXPECT_EQ(4, results.size());
EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());
EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());
EXPECT_TRUE(results.GetTestPartResult(2).nonfatally_failed());
EXPECT_TRUE(results.GetTestPartResult(3).fatally_failed());
}
#endif // GTEST_IS_THREADSAFE
// Tests EXPECT_FATAL_FAILURE{,ON_ALL_THREADS}. Makes sure that they
// work even if the failure is generated in a called function rather than
// the current context.
typedef ScopedFakeTestPartResultReporterTest ExpectFatalFailureTest;
TEST_F(ExpectFatalFailureTest, CatchesFatalFaliure) {
EXPECT_FATAL_FAILURE(AddFatalFailure(), "Expected fatal failure.");
}
TEST_F(ExpectFatalFailureTest, AcceptsStdStringObject) {
EXPECT_FATAL_FAILURE(AddFatalFailure(),
::std::string("Expected fatal failure."));
}
TEST_F(ExpectFatalFailureTest, CatchesFatalFailureOnAllThreads) {
// We have another test below to verify that the macro catches fatal
// failures generated on another thread.
EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFatalFailure(),
"Expected fatal failure.");
}
#ifdef __BORLANDC__
// Silences warnings: "Condition is always true"
# pragma option push -w-ccc
#endif
// Tests that EXPECT_FATAL_FAILURE() can be used in a non-void
// function even when the statement in it contains ASSERT_*.
int NonVoidFunction() {
EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
return 0;
}
TEST_F(ExpectFatalFailureTest, CanBeUsedInNonVoidFunction) {
NonVoidFunction();
}
// Tests that EXPECT_FATAL_FAILURE(statement, ...) doesn't abort the
// current function even though 'statement' generates a fatal failure.
void DoesNotAbortHelper(bool* aborted) {
EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), "");
EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), "");
*aborted = false;
}
#ifdef __BORLANDC__
// Restores warnings after previous "#pragma option push" suppressed them.
# pragma option pop
#endif
TEST_F(ExpectFatalFailureTest, DoesNotAbort) {
bool aborted = true;
DoesNotAbortHelper(&aborted);
EXPECT_FALSE(aborted);
}
// Tests that the EXPECT_FATAL_FAILURE{,_ON_ALL_THREADS} accepts a
// statement that contains a macro which expands to code containing an
// unprotected comma.
static int global_var = 0;
#define GTEST_USE_UNPROTECTED_COMMA_ global_var++, global_var++
TEST_F(ExpectFatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
#ifndef __BORLANDC__
// ICE's in C++Builder.
EXPECT_FATAL_FAILURE({
GTEST_USE_UNPROTECTED_COMMA_;
AddFatalFailure();
}, "");
#endif
EXPECT_FATAL_FAILURE_ON_ALL_THREADS({
GTEST_USE_UNPROTECTED_COMMA_;
AddFatalFailure();
}, "");
}
// Tests EXPECT_NONFATAL_FAILURE{,ON_ALL_THREADS}.
typedef ScopedFakeTestPartResultReporterTest ExpectNonfatalFailureTest;
TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailure) {
EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
"Expected non-fatal failure.");
}
TEST_F(ExpectNonfatalFailureTest, AcceptsStdStringObject) {
EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),
::std::string("Expected non-fatal failure."));
}
TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailureOnAllThreads) {
// We have another test below to verify that the macro catches
// non-fatal failures generated on another thread.
EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddNonfatalFailure(),
"Expected non-fatal failure.");
}
// Tests that the EXPECT_NONFATAL_FAILURE{,_ON_ALL_THREADS} accepts a
// statement that contains a macro which expands to code containing an
// unprotected comma.
TEST_F(ExpectNonfatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {
EXPECT_NONFATAL_FAILURE({
GTEST_USE_UNPROTECTED_COMMA_;
AddNonfatalFailure();
}, "");
EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS({
GTEST_USE_UNPROTECTED_COMMA_;
AddNonfatalFailure();
}, "");
}
#if GTEST_IS_THREADSAFE
typedef ScopedFakeTestPartResultReporterWithThreadsTest
ExpectFailureWithThreadsTest;
TEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailureOnAllThreads) {
EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailureInOtherThread(FATAL_FAILURE),
"Expected fatal failure.");
}
TEST_F(ExpectFailureWithThreadsTest, ExpectNonFatalFailureOnAllThreads) {
EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(
AddFailureInOtherThread(NONFATAL_FAILURE), "Expected non-fatal failure.");
}
#endif // GTEST_IS_THREADSAFE
// Tests the TestProperty class.
TEST(TestPropertyTest, ConstructorWorks) {
const TestProperty property("key", "value");
EXPECT_STREQ("key", property.key());
EXPECT_STREQ("value", property.value());
}
TEST(TestPropertyTest, SetValue) {
TestProperty property("key", "value_1");
EXPECT_STREQ("key", property.key());
property.SetValue("value_2");
EXPECT_STREQ("key", property.key());
EXPECT_STREQ("value_2", property.value());
}
// Tests the TestResult class
// The test fixture for testing TestResult.
class TestResultTest : public Test {
protected:
typedef std::vector<TestPartResult> TPRVector;
// We make use of 2 TestPartResult objects,
TestPartResult * pr1, * pr2;
// ... and 3 TestResult objects.
TestResult * r0, * r1, * r2;
void SetUp() override {
// pr1 is for success.
pr1 = new TestPartResult(TestPartResult::kSuccess,
"foo/bar.cc",
10,
"Success!");
// pr2 is for fatal failure.
pr2 = new TestPartResult(TestPartResult::kFatalFailure,
"foo/bar.cc",
-1, // This line number means "unknown"
"Failure!");
// Creates the TestResult objects.
r0 = new TestResult();
r1 = new TestResult();
r2 = new TestResult();
// In order to test TestResult, we need to modify its internal
// state, in particular the TestPartResult vector it holds.
// test_part_results() returns a const reference to this vector.
// We cast it to a non-const object s.t. it can be modified
TPRVector* results1 = const_cast<TPRVector*>(
&TestResultAccessor::test_part_results(*r1));
TPRVector* results2 = const_cast<TPRVector*>(
&TestResultAccessor::test_part_results(*r2));
// r0 is an empty TestResult.
// r1 contains a single SUCCESS TestPartResult.
results1->push_back(*pr1);
// r2 contains a SUCCESS, and a FAILURE.
results2->push_back(*pr1);
results2->push_back(*pr2);
}
void TearDown() override {
delete pr1;
delete pr2;
delete r0;
delete r1;
delete r2;
}
// Helper that compares two TestPartResults.
static void CompareTestPartResult(const TestPartResult& expected,
const TestPartResult& actual) {
EXPECT_EQ(expected.type(), actual.type());
EXPECT_STREQ(expected.file_name(), actual.file_name());
EXPECT_EQ(expected.line_number(), actual.line_number());
EXPECT_STREQ(expected.summary(), actual.summary());
EXPECT_STREQ(expected.message(), actual.message());
EXPECT_EQ(expected.passed(), actual.passed());
EXPECT_EQ(expected.failed(), actual.failed());
EXPECT_EQ(expected.nonfatally_failed(), actual.nonfatally_failed());
EXPECT_EQ(expected.fatally_failed(), actual.fatally_failed());
}
};
// Tests TestResult::total_part_count().
TEST_F(TestResultTest, total_part_count) {
ASSERT_EQ(0, r0->total_part_count());
ASSERT_EQ(1, r1->total_part_count());
ASSERT_EQ(2, r2->total_part_count());
}
// Tests TestResult::Passed().
TEST_F(TestResultTest, Passed) {
ASSERT_TRUE(r0->Passed());
ASSERT_TRUE(r1->Passed());
ASSERT_FALSE(r2->Passed());
}
// Tests TestResult::Failed().
TEST_F(TestResultTest, Failed) {
ASSERT_FALSE(r0->Failed());
ASSERT_FALSE(r1->Failed());
ASSERT_TRUE(r2->Failed());
}
// Tests TestResult::GetTestPartResult().
typedef TestResultTest TestResultDeathTest;
TEST_F(TestResultDeathTest, GetTestPartResult) {
CompareTestPartResult(*pr1, r2->GetTestPartResult(0));
CompareTestPartResult(*pr2, r2->GetTestPartResult(1));
EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(2), "");
EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(-1), "");
}
// Tests TestResult has no properties when none are added.
TEST(TestResultPropertyTest, NoPropertiesFoundWhenNoneAreAdded) {
TestResult test_result;
ASSERT_EQ(0, test_result.test_property_count());
}
// Tests TestResult has the expected property when added.
TEST(TestResultPropertyTest, OnePropertyFoundWhenAdded) {
TestResult test_result;
TestProperty property("key_1", "1");
TestResultAccessor::RecordProperty(&test_result, "testcase", property);
ASSERT_EQ(1, test_result.test_property_count());
const TestProperty& actual_property = test_result.GetTestProperty(0);
EXPECT_STREQ("key_1", actual_property.key());
EXPECT_STREQ("1", actual_property.value());
}
// Tests TestResult has multiple properties when added.
TEST(TestResultPropertyTest, MultiplePropertiesFoundWhenAdded) {
TestResult test_result;
TestProperty property_1("key_1", "1");
TestProperty property_2("key_2", "2");
TestResultAccessor::RecordProperty(&test_result, "testcase", property_1);
TestResultAccessor::RecordProperty(&test_result, "testcase", property_2);
ASSERT_EQ(2, test_result.test_property_count());
const TestProperty& actual_property_1 = test_result.GetTestProperty(0);
EXPECT_STREQ("key_1", actual_property_1.key());
EXPECT_STREQ("1", actual_property_1.value());
const TestProperty& actual_property_2 = test_result.GetTestProperty(1);
EXPECT_STREQ("key_2", actual_property_2.key());
EXPECT_STREQ("2", actual_property_2.value());
}
// Tests TestResult::RecordProperty() overrides values for duplicate keys.
TEST(TestResultPropertyTest, OverridesValuesForDuplicateKeys) {
TestResult test_result;
TestProperty property_1_1("key_1", "1");
TestProperty property_2_1("key_2", "2");
TestProperty property_1_2("key_1", "12");
TestProperty property_2_2("key_2", "22");
TestResultAccessor::RecordProperty(&test_result, "testcase", property_1_1);
TestResultAccessor::RecordProperty(&test_result, "testcase", property_2_1);
TestResultAccessor::RecordProperty(&test_result, "testcase", property_1_2);
TestResultAccessor::RecordProperty(&test_result, "testcase", property_2_2);
ASSERT_EQ(2, test_result.test_property_count());
const TestProperty& actual_property_1 = test_result.GetTestProperty(0);
EXPECT_STREQ("key_1", actual_property_1.key());
EXPECT_STREQ("12", actual_property_1.value());
const TestProperty& actual_property_2 = test_result.GetTestProperty(1);
EXPECT_STREQ("key_2", actual_property_2.key());
EXPECT_STREQ("22", actual_property_2.value());
}
// Tests TestResult::GetTestProperty().
TEST(TestResultPropertyTest, GetTestProperty) {
TestResult test_result;
TestProperty property_1("key_1", "1");
TestProperty property_2("key_2", "2");
TestProperty property_3("key_3", "3");
TestResultAccessor::RecordProperty(&test_result, "testcase", property_1);
TestResultAccessor::RecordProperty(&test_result, "testcase", property_2);
TestResultAccessor::RecordProperty(&test_result, "testcase", property_3);
const TestProperty& fetched_property_1 = test_result.GetTestProperty(0);
const TestProperty& fetched_property_2 = test_result.GetTestProperty(1);
const TestProperty& fetched_property_3 = test_result.GetTestProperty(2);
EXPECT_STREQ("key_1", fetched_property_1.key());
EXPECT_STREQ("1", fetched_property_1.value());
EXPECT_STREQ("key_2", fetched_property_2.key());
EXPECT_STREQ("2", fetched_property_2.value());
EXPECT_STREQ("key_3", fetched_property_3.key());
EXPECT_STREQ("3", fetched_property_3.value());
EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(3), "");
EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(-1), "");
}
// Tests the Test class.
//
// It's difficult to test every public method of this class (we are
// already stretching the limit of Google Test by using it to test itself!).
// Fortunately, we don't have to do that, as we are already testing
// the functionalities of the Test class extensively by using Google Test
// alone.
//
// Therefore, this section only contains one test.
// Tests that GTestFlagSaver works on Windows and Mac.
class GTestFlagSaverTest : public Test {
protected:
// Saves the Google Test flags such that we can restore them later, and
// then sets them to their default values. This will be called
// before the first test in this test case is run.
static void SetUpTestSuite() {
saver_ = new GTestFlagSaver;
GTEST_FLAG_SET(also_run_disabled_tests, false);
GTEST_FLAG_SET(break_on_failure, false);
GTEST_FLAG_SET(catch_exceptions, false);
GTEST_FLAG_SET(death_test_use_fork, false);
GTEST_FLAG_SET(color, "auto");
GTEST_FLAG_SET(fail_fast, false);
GTEST_FLAG_SET(filter, "");
GTEST_FLAG_SET(list_tests, false);
GTEST_FLAG_SET(output, "");
GTEST_FLAG_SET(brief, false);
GTEST_FLAG_SET(print_time, true);
GTEST_FLAG_SET(random_seed, 0);
GTEST_FLAG_SET(repeat, 1);
GTEST_FLAG_SET(recreate_environments_when_repeating, true);
GTEST_FLAG_SET(shuffle, false);
GTEST_FLAG_SET(stack_trace_depth, kMaxStackTraceDepth);
GTEST_FLAG_SET(stream_result_to, "");
GTEST_FLAG_SET(throw_on_failure, false);
}
// Restores the Google Test flags that the tests have modified. This will
// be called after the last test in this test case is run.
static void TearDownTestSuite() {
delete saver_;
saver_ = nullptr;
}
// Verifies that the Google Test flags have their default values, and then
// modifies each of them.
void VerifyAndModifyFlags() {
EXPECT_FALSE(GTEST_FLAG_GET(also_run_disabled_tests));
EXPECT_FALSE(GTEST_FLAG_GET(break_on_failure));
EXPECT_FALSE(GTEST_FLAG_GET(catch_exceptions));
EXPECT_STREQ("auto", GTEST_FLAG_GET(color).c_str());
EXPECT_FALSE(GTEST_FLAG_GET(death_test_use_fork));
EXPECT_FALSE(GTEST_FLAG_GET(fail_fast));
EXPECT_STREQ("", GTEST_FLAG_GET(filter).c_str());
EXPECT_FALSE(GTEST_FLAG_GET(list_tests));
EXPECT_STREQ("", GTEST_FLAG_GET(output).c_str());
EXPECT_FALSE(GTEST_FLAG_GET(brief));
EXPECT_TRUE(GTEST_FLAG_GET(print_time));
EXPECT_EQ(0, GTEST_FLAG_GET(random_seed));
EXPECT_EQ(1, GTEST_FLAG_GET(repeat));
EXPECT_TRUE(GTEST_FLAG_GET(recreate_environments_when_repeating));
EXPECT_FALSE(GTEST_FLAG_GET(shuffle));
EXPECT_EQ(kMaxStackTraceDepth, GTEST_FLAG_GET(stack_trace_depth));
EXPECT_STREQ("", GTEST_FLAG_GET(stream_result_to).c_str());
EXPECT_FALSE(GTEST_FLAG_GET(throw_on_failure));
GTEST_FLAG_SET(also_run_disabled_tests, true);
GTEST_FLAG_SET(break_on_failure, true);
GTEST_FLAG_SET(catch_exceptions, true);
GTEST_FLAG_SET(color, "no");
GTEST_FLAG_SET(death_test_use_fork, true);
GTEST_FLAG_SET(fail_fast, true);
GTEST_FLAG_SET(filter, "abc");
GTEST_FLAG_SET(list_tests, true);
GTEST_FLAG_SET(output, "xml:foo.xml");
GTEST_FLAG_SET(brief, true);
GTEST_FLAG_SET(print_time, false);
GTEST_FLAG_SET(random_seed, 1);
GTEST_FLAG_SET(repeat, 100);
GTEST_FLAG_SET(recreate_environments_when_repeating, false);
GTEST_FLAG_SET(shuffle, true);
GTEST_FLAG_SET(stack_trace_depth, 1);
GTEST_FLAG_SET(stream_result_to, "localhost:1234");
GTEST_FLAG_SET(throw_on_failure, true);
}
private:
// For saving Google Test flags during this test case.
static GTestFlagSaver* saver_;
};
GTestFlagSaver* GTestFlagSaverTest::saver_ = nullptr;
// Google Test doesn't guarantee the order of tests. The following two
// tests are designed to work regardless of their order.
// Modifies the Google Test flags in the test body.
TEST_F(GTestFlagSaverTest, ModifyGTestFlags) {
VerifyAndModifyFlags();
}
// Verifies that the Google Test flags in the body of the previous test were
// restored to their original values.
TEST_F(GTestFlagSaverTest, VerifyGTestFlags) {
VerifyAndModifyFlags();
}
// Sets an environment variable with the given name to the given
// value. If the value argument is "", unsets the environment
// variable. The caller must ensure that both arguments are not NULL.
static void SetEnv(const char* name, const char* value) {
#if GTEST_OS_WINDOWS_MOBILE
// Environment variables are not supported on Windows CE.
return;
#elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9)
// C++Builder's putenv only stores a pointer to its parameter; we have to
// ensure that the string remains valid as long as it might be needed.
// We use an std::map to do so.
static std::map<std::string, std::string*> added_env;
// Because putenv stores a pointer to the string buffer, we can't delete the
// previous string (if present) until after it's replaced.
std::string *prev_env = NULL;
if (added_env.find(name) != added_env.end()) {
prev_env = added_env[name];
}
added_env[name] = new std::string(
(Message() << name << "=" << value).GetString());
// The standard signature of putenv accepts a 'char*' argument. Other
// implementations, like C++Builder's, accept a 'const char*'.
// We cast away the 'const' since that would work for both variants.
putenv(const_cast<char*>(added_env[name]->c_str()));
delete prev_env;
#elif GTEST_OS_WINDOWS // If we are on Windows proper.
_putenv((Message() << name << "=" << value).GetString().c_str());
#else
if (*value == '\0') {
unsetenv(name);
} else {
setenv(name, value, 1);
}
#endif // GTEST_OS_WINDOWS_MOBILE
}
#if !GTEST_OS_WINDOWS_MOBILE
// Environment variables are not supported on Windows CE.
using testing::internal::Int32FromGTestEnv;
// Tests Int32FromGTestEnv().
// Tests that Int32FromGTestEnv() returns the default value when the
// environment variable is not set.
TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenVariableIsNotSet) {
SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "");
EXPECT_EQ(10, Int32FromGTestEnv("temp", 10));
}
# if !defined(GTEST_GET_INT32_FROM_ENV_)
// Tests that Int32FromGTestEnv() returns the default value when the
// environment variable overflows as an Int32.
TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueOverflows) {
printf("(expecting 2 warnings)\n");
SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12345678987654321");
EXPECT_EQ(20, Int32FromGTestEnv("temp", 20));
SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-12345678987654321");
EXPECT_EQ(30, Int32FromGTestEnv("temp", 30));
}
// Tests that Int32FromGTestEnv() returns the default value when the
// environment variable does not represent a valid decimal integer.
TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueIsInvalid) {
printf("(expecting 2 warnings)\n");
SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "A1");
EXPECT_EQ(40, Int32FromGTestEnv("temp", 40));
SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12X");
EXPECT_EQ(50, Int32FromGTestEnv("temp", 50));
}
# endif // !defined(GTEST_GET_INT32_FROM_ENV_)
// Tests that Int32FromGTestEnv() parses and returns the value of the
// environment variable when it represents a valid decimal integer in
// the range of an Int32.
TEST(Int32FromGTestEnvTest, ParsesAndReturnsValidValue) {
SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "123");
EXPECT_EQ(123, Int32FromGTestEnv("temp", 0));
SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-321");
EXPECT_EQ(-321, Int32FromGTestEnv("temp", 0));
}
#endif // !GTEST_OS_WINDOWS_MOBILE
// Tests ParseFlag().
// Tests that ParseInt32Flag() returns false and doesn't change the
// output value when the flag has wrong format
TEST(ParseInt32FlagTest, ReturnsFalseForInvalidFlag) {
int32_t value = 123;
EXPECT_FALSE(ParseFlag("--a=100", "b", &value));
EXPECT_EQ(123, value);
EXPECT_FALSE(ParseFlag("a=100", "a", &value));
EXPECT_EQ(123, value);
}
// Tests that ParseFlag() returns false and doesn't change the
// output value when the flag overflows as an Int32.
TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueOverflows) {
printf("(expecting 2 warnings)\n");
int32_t value = 123;
EXPECT_FALSE(ParseFlag("--abc=12345678987654321", "abc", &value));
EXPECT_EQ(123, value);
EXPECT_FALSE(ParseFlag("--abc=-12345678987654321", "abc", &value));
EXPECT_EQ(123, value);
}
// Tests that ParseInt32Flag() returns false and doesn't change the
// output value when the flag does not represent a valid decimal
// integer.
TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueIsInvalid) {
printf("(expecting 2 warnings)\n");
int32_t value = 123;
EXPECT_FALSE(ParseFlag("--abc=A1", "abc", &value));
EXPECT_EQ(123, value);
EXPECT_FALSE(ParseFlag("--abc=12X", "abc", &value));
EXPECT_EQ(123, value);
}
// Tests that ParseInt32Flag() parses the value of the flag and
// returns true when the flag represents a valid decimal integer in
// the range of an Int32.
TEST(ParseInt32FlagTest, ParsesAndReturnsValidValue) {
int32_t value = 123;
EXPECT_TRUE(ParseFlag("--" GTEST_FLAG_PREFIX_ "abc=456", "abc", &value));
EXPECT_EQ(456, value);
EXPECT_TRUE(ParseFlag("--" GTEST_FLAG_PREFIX_ "abc=-789", "abc", &value));
EXPECT_EQ(-789, value);
}
// Tests that Int32FromEnvOrDie() parses the value of the var or
// returns the correct default.
// Environment variables are not supported on Windows CE.
#if !GTEST_OS_WINDOWS_MOBILE
TEST(Int32FromEnvOrDieTest, ParsesAndReturnsValidValue) {
EXPECT_EQ(333, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "123");
EXPECT_EQ(123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "-123");
EXPECT_EQ(-123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333));
}
#endif // !GTEST_OS_WINDOWS_MOBILE
// Tests that Int32FromEnvOrDie() aborts with an error message
// if the variable is not an int32_t.
TEST(Int32FromEnvOrDieDeathTest, AbortsOnFailure) {
SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "xxx");
EXPECT_DEATH_IF_SUPPORTED(
Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123),
".*");
}
// Tests that Int32FromEnvOrDie() aborts with an error message
// if the variable cannot be represented by an int32_t.
TEST(Int32FromEnvOrDieDeathTest, AbortsOnInt32Overflow) {
SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "1234567891234567891234");
EXPECT_DEATH_IF_SUPPORTED(
Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123),
".*");
}
// Tests that ShouldRunTestOnShard() selects all tests
// where there is 1 shard.
TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereIsOneShard) {
EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 0));
EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 1));
EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 2));
EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 3));
EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 4));
}
class ShouldShardTest : public testing::Test {
protected:
void SetUp() override {
index_var_ = GTEST_FLAG_PREFIX_UPPER_ "INDEX";
total_var_ = GTEST_FLAG_PREFIX_UPPER_ "TOTAL";
}
void TearDown() override {
SetEnv(index_var_, "");
SetEnv(total_var_, "");
}
const char* index_var_;
const char* total_var_;
};
// Tests that sharding is disabled if neither of the environment variables
// are set.
TEST_F(ShouldShardTest, ReturnsFalseWhenNeitherEnvVarIsSet) {
SetEnv(index_var_, "");
SetEnv(total_var_, "");
EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
}
// Tests that sharding is not enabled if total_shards == 1.
TEST_F(ShouldShardTest, ReturnsFalseWhenTotalShardIsOne) {
SetEnv(index_var_, "0");
SetEnv(total_var_, "1");
EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));
EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
}
// Tests that sharding is enabled if total_shards > 1 and
// we are not in a death test subprocess.
// Environment variables are not supported on Windows CE.
#if !GTEST_OS_WINDOWS_MOBILE
TEST_F(ShouldShardTest, WorksWhenShardEnvVarsAreValid) {
SetEnv(index_var_, "4");
SetEnv(total_var_, "22");
EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
SetEnv(index_var_, "8");
SetEnv(total_var_, "9");
EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
SetEnv(index_var_, "0");
SetEnv(total_var_, "9");
EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));
EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));
}
#endif // !GTEST_OS_WINDOWS_MOBILE
// Tests that we exit in error if the sharding values are not valid.
typedef ShouldShardTest ShouldShardDeathTest;
TEST_F(ShouldShardDeathTest, AbortsWhenShardingEnvVarsAreInvalid) {
SetEnv(index_var_, "4");
SetEnv(total_var_, "4");
EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
SetEnv(index_var_, "4");
SetEnv(total_var_, "-2");
EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
SetEnv(index_var_, "5");
SetEnv(total_var_, "");
EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
SetEnv(index_var_, "");
SetEnv(total_var_, "5");
EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*");
}
// Tests that ShouldRunTestOnShard is a partition when 5
// shards are used.
TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereAreFiveShards) {
// Choose an arbitrary number of tests and shards.
const int num_tests = 17;
const int num_shards = 5;
// Check partitioning: each test should be on exactly 1 shard.
for (int test_id = 0; test_id < num_tests; test_id++) {
int prev_selected_shard_index = -1;
for (int shard_index = 0; shard_index < num_shards; shard_index++) {
if (ShouldRunTestOnShard(num_shards, shard_index, test_id)) {
if (prev_selected_shard_index < 0) {
prev_selected_shard_index = shard_index;
} else {
ADD_FAILURE() << "Shard " << prev_selected_shard_index << " and "
<< shard_index << " are both selected to run test " << test_id;
}
}
}
}
// Check balance: This is not required by the sharding protocol, but is a
// desirable property for performance.
for (int shard_index = 0; shard_index < num_shards; shard_index++) {
int num_tests_on_shard = 0;
for (int test_id = 0; test_id < num_tests; test_id++) {
num_tests_on_shard +=
ShouldRunTestOnShard(num_shards, shard_index, test_id);
}
EXPECT_GE(num_tests_on_shard, num_tests / num_shards);
}
}
// For the same reason we are not explicitly testing everything in the
// Test class, there are no separate tests for the following classes
// (except for some trivial cases):
//
// TestSuite, UnitTest, UnitTestResultPrinter.
//
// Similarly, there are no separate tests for the following macros:
//
// TEST, TEST_F, RUN_ALL_TESTS
TEST(UnitTestTest, CanGetOriginalWorkingDir) {
ASSERT_TRUE(UnitTest::GetInstance()->original_working_dir() != nullptr);
EXPECT_STRNE(UnitTest::GetInstance()->original_working_dir(), "");
}
TEST(UnitTestTest, ReturnsPlausibleTimestamp) {
EXPECT_LT(0, UnitTest::GetInstance()->start_timestamp());
EXPECT_LE(UnitTest::GetInstance()->start_timestamp(), GetTimeInMillis());
}
// When a property using a reserved key is supplied to this function, it
// tests that a non-fatal failure is added, a fatal failure is not added,
// and that the property is not recorded.
void ExpectNonFatalFailureRecordingPropertyWithReservedKey(
const TestResult& test_result, const char* key) {
EXPECT_NONFATAL_FAILURE(Test::RecordProperty(key, "1"), "Reserved key");
ASSERT_EQ(0, test_result.test_property_count()) << "Property for key '" << key
<< "' recorded unexpectedly.";
}
void ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
const char* key) {
const TestInfo* test_info = UnitTest::GetInstance()->current_test_info();
ASSERT_TRUE(test_info != nullptr);
ExpectNonFatalFailureRecordingPropertyWithReservedKey(*test_info->result(),
key);
}
void ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
const char* key) {
const testing::TestSuite* test_suite =
UnitTest::GetInstance()->current_test_suite();
ASSERT_TRUE(test_suite != nullptr);
ExpectNonFatalFailureRecordingPropertyWithReservedKey(
test_suite->ad_hoc_test_result(), key);
}
void ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
const char* key) {
ExpectNonFatalFailureRecordingPropertyWithReservedKey(
UnitTest::GetInstance()->ad_hoc_test_result(), key);
}
// Tests that property recording functions in UnitTest outside of tests
// functions correctly. Creating a separate instance of UnitTest ensures it
// is in a state similar to the UnitTest's singleton's between tests.
class UnitTestRecordPropertyTest :
public testing::internal::UnitTestRecordPropertyTestHelper {
public:
static void SetUpTestSuite() {
ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
"disabled");
ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
"errors");
ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
"failures");
ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
"name");
ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
"tests");
ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(
"time");
Test::RecordProperty("test_case_key_1", "1");
const testing::TestSuite* test_suite =
UnitTest::GetInstance()->current_test_suite();
ASSERT_TRUE(test_suite != nullptr);
ASSERT_EQ(1, test_suite->ad_hoc_test_result().test_property_count());
EXPECT_STREQ("test_case_key_1",
test_suite->ad_hoc_test_result().GetTestProperty(0).key());
EXPECT_STREQ("1",
test_suite->ad_hoc_test_result().GetTestProperty(0).value());
}
};
// Tests TestResult has the expected property when added.
TEST_F(UnitTestRecordPropertyTest, OnePropertyFoundWhenAdded) {
UnitTestRecordProperty("key_1", "1");
ASSERT_EQ(1, unit_test_.ad_hoc_test_result().test_property_count());
EXPECT_STREQ("key_1",
unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
EXPECT_STREQ("1",
unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
}
// Tests TestResult has multiple properties when added.
TEST_F(UnitTestRecordPropertyTest, MultiplePropertiesFoundWhenAdded) {
UnitTestRecordProperty("key_1", "1");
UnitTestRecordProperty("key_2", "2");
ASSERT_EQ(2, unit_test_.ad_hoc_test_result().test_property_count());
EXPECT_STREQ("key_1",
unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
EXPECT_STREQ("1", unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
EXPECT_STREQ("key_2",
unit_test_.ad_hoc_test_result().GetTestProperty(1).key());
EXPECT_STREQ("2", unit_test_.ad_hoc_test_result().GetTestProperty(1).value());
}
// Tests TestResult::RecordProperty() overrides values for duplicate keys.
TEST_F(UnitTestRecordPropertyTest, OverridesValuesForDuplicateKeys) {
UnitTestRecordProperty("key_1", "1");
UnitTestRecordProperty("key_2", "2");
UnitTestRecordProperty("key_1", "12");
UnitTestRecordProperty("key_2", "22");
ASSERT_EQ(2, unit_test_.ad_hoc_test_result().test_property_count());
EXPECT_STREQ("key_1",
unit_test_.ad_hoc_test_result().GetTestProperty(0).key());
EXPECT_STREQ("12",
unit_test_.ad_hoc_test_result().GetTestProperty(0).value());
EXPECT_STREQ("key_2",
unit_test_.ad_hoc_test_result().GetTestProperty(1).key());
EXPECT_STREQ("22",
unit_test_.ad_hoc_test_result().GetTestProperty(1).value());
}
TEST_F(UnitTestRecordPropertyTest,
AddFailureInsideTestsWhenUsingTestSuiteReservedKeys) {
ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
"name");
ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
"value_param");
ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
"type_param");
ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
"status");
ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
"time");
ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(
"classname");
}
TEST_F(UnitTestRecordPropertyTest,
AddRecordWithReservedKeysGeneratesCorrectPropertyList) {
EXPECT_NONFATAL_FAILURE(
Test::RecordProperty("name", "1"),
"'classname', 'name', 'status', 'time', 'type_param', 'value_param',"
" 'file', and 'line' are reserved");
}
class UnitTestRecordPropertyTestEnvironment : public Environment {
public:
void TearDown() override {
ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
"tests");
ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
"failures");
ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
"disabled");
ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
"errors");
ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
"name");
ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
"timestamp");
ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
"time");
ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(
"random_seed");
}
};
// This will test property recording outside of any test or test case.
static Environment* record_property_env GTEST_ATTRIBUTE_UNUSED_ =
AddGlobalTestEnvironment(new UnitTestRecordPropertyTestEnvironment);
// This group of tests is for predicate assertions (ASSERT_PRED*, etc)
// of various arities. They do not attempt to be exhaustive. Rather,
// view them as smoke tests that can be easily reviewed and verified.
// A more complete set of tests for predicate assertions can be found
// in gtest_pred_impl_unittest.cc.
// First, some predicates and predicate-formatters needed by the tests.
// Returns true if and only if the argument is an even number.
bool IsEven(int n) {
return (n % 2) == 0;
}
// A functor that returns true if and only if the argument is an even number.
struct IsEvenFunctor {
bool operator()(int n) { return IsEven(n); }
};
// A predicate-formatter function that asserts the argument is an even
// number.
AssertionResult AssertIsEven(const char* expr, int n) {
if (IsEven(n)) {
return AssertionSuccess();
}
Message msg;
msg << expr << " evaluates to " << n << ", which is not even.";
return AssertionFailure(msg);
}
// A predicate function that returns AssertionResult for use in
// EXPECT/ASSERT_TRUE/FALSE.
AssertionResult ResultIsEven(int n) {
if (IsEven(n))
return AssertionSuccess() << n << " is even";
else
return AssertionFailure() << n << " is odd";
}
// A predicate function that returns AssertionResult but gives no
// explanation why it succeeds. Needed for testing that
// EXPECT/ASSERT_FALSE handles such functions correctly.
AssertionResult ResultIsEvenNoExplanation(int n) {
if (IsEven(n))
return AssertionSuccess();
else
return AssertionFailure() << n << " is odd";
}
// A predicate-formatter functor that asserts the argument is an even
// number.
struct AssertIsEvenFunctor {
AssertionResult operator()(const char* expr, int n) {
return AssertIsEven(expr, n);
}
};
// Returns true if and only if the sum of the arguments is an even number.
bool SumIsEven2(int n1, int n2) {
return IsEven(n1 + n2);
}
// A functor that returns true if and only if the sum of the arguments is an
// even number.
struct SumIsEven3Functor {
bool operator()(int n1, int n2, int n3) {
return IsEven(n1 + n2 + n3);
}
};
// A predicate-formatter function that asserts the sum of the
// arguments is an even number.
AssertionResult AssertSumIsEven4(
const char* e1, const char* e2, const char* e3, const char* e4,
int n1, int n2, int n3, int n4) {
const int sum = n1 + n2 + n3 + n4;
if (IsEven(sum)) {
return AssertionSuccess();
}
Message msg;
msg << e1 << " + " << e2 << " + " << e3 << " + " << e4
<< " (" << n1 << " + " << n2 << " + " << n3 << " + " << n4
<< ") evaluates to " << sum << ", which is not even.";
return AssertionFailure(msg);
}
// A predicate-formatter functor that asserts the sum of the arguments
// is an even number.
struct AssertSumIsEven5Functor {
AssertionResult operator()(
const char* e1, const char* e2, const char* e3, const char* e4,
const char* e5, int n1, int n2, int n3, int n4, int n5) {
const int sum = n1 + n2 + n3 + n4 + n5;
if (IsEven(sum)) {
return AssertionSuccess();
}
Message msg;
msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " + " << e5
<< " ("
<< n1 << " + " << n2 << " + " << n3 << " + " << n4 << " + " << n5
<< ") evaluates to " << sum << ", which is not even.";
return AssertionFailure(msg);
}
};
// Tests unary predicate assertions.
// Tests unary predicate assertions that don't use a custom formatter.
TEST(Pred1Test, WithoutFormat) {
// Success cases.
EXPECT_PRED1(IsEvenFunctor(), 2) << "This failure is UNEXPECTED!";
ASSERT_PRED1(IsEven, 4);
// Failure cases.
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_PRED1(IsEven, 5) << "This failure is expected.";
}, "This failure is expected.");
EXPECT_FATAL_FAILURE(ASSERT_PRED1(IsEvenFunctor(), 5),
"evaluates to false");
}
// Tests unary predicate assertions that use a custom formatter.
TEST(Pred1Test, WithFormat) {
// Success cases.
EXPECT_PRED_FORMAT1(AssertIsEven, 2);
ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), 4)
<< "This failure is UNEXPECTED!";
// Failure cases.
const int n = 5;
EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT1(AssertIsEvenFunctor(), n),
"n evaluates to 5, which is not even.");
EXPECT_FATAL_FAILURE({ // NOLINT
ASSERT_PRED_FORMAT1(AssertIsEven, 5) << "This failure is expected.";
}, "This failure is expected.");
}
// Tests that unary predicate assertions evaluates their arguments
// exactly once.
TEST(Pred1Test, SingleEvaluationOnFailure) {
// A success case.
static int n = 0;
EXPECT_PRED1(IsEven, n++);
EXPECT_EQ(1, n) << "The argument is not evaluated exactly once.";
// A failure case.
EXPECT_FATAL_FAILURE({ // NOLINT
ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), n++)
<< "This failure is expected.";
}, "This failure is expected.");
EXPECT_EQ(2, n) << "The argument is not evaluated exactly once.";
}
// Tests predicate assertions whose arity is >= 2.
// Tests predicate assertions that don't use a custom formatter.
TEST(PredTest, WithoutFormat) {
// Success cases.
ASSERT_PRED2(SumIsEven2, 2, 4) << "This failure is UNEXPECTED!";
EXPECT_PRED3(SumIsEven3Functor(), 4, 6, 8);
// Failure cases.
const int n1 = 1;
const int n2 = 2;
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_PRED2(SumIsEven2, n1, n2) << "This failure is expected.";
}, "This failure is expected.");
EXPECT_FATAL_FAILURE({ // NOLINT
ASSERT_PRED3(SumIsEven3Functor(), 1, 2, 4);
}, "evaluates to false");
}
// Tests predicate assertions that use a custom formatter.
TEST(PredTest, WithFormat) {
// Success cases.
ASSERT_PRED_FORMAT4(AssertSumIsEven4, 4, 6, 8, 10) <<
"This failure is UNEXPECTED!";
EXPECT_PRED_FORMAT5(AssertSumIsEven5Functor(), 2, 4, 6, 8, 10);
// Failure cases.
const int n1 = 1;
const int n2 = 2;
const int n3 = 4;
const int n4 = 6;
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_PRED_FORMAT4(AssertSumIsEven4, n1, n2, n3, n4);
}, "evaluates to 13, which is not even.");
EXPECT_FATAL_FAILURE({ // NOLINT
ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), 1, 2, 4, 6, 8)
<< "This failure is expected.";
}, "This failure is expected.");
}
// Tests that predicate assertions evaluates their arguments
// exactly once.
TEST(PredTest, SingleEvaluationOnFailure) {
// A success case.
int n1 = 0;
int n2 = 0;
EXPECT_PRED2(SumIsEven2, n1++, n2++);
EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
// Another success case.
n1 = n2 = 0;
int n3 = 0;
int n4 = 0;
int n5 = 0;
ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(),
n1++, n2++, n3++, n4++, n5++)
<< "This failure is UNEXPECTED!";
EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
EXPECT_EQ(1, n5) << "Argument 5 is not evaluated exactly once.";
// A failure case.
n1 = n2 = n3 = 0;
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_PRED3(SumIsEven3Functor(), ++n1, n2++, n3++)
<< "This failure is expected.";
}, "This failure is expected.");
EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
// Another failure case.
n1 = n2 = n3 = n4 = 0;
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_PRED_FORMAT4(AssertSumIsEven4, ++n1, n2++, n3++, n4++);
}, "evaluates to 1, which is not even.");
EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once.";
EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once.";
EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once.";
EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once.";
}
// Test predicate assertions for sets
TEST(PredTest, ExpectPredEvalFailure) {
std::set<int> set_a = {2, 1, 3, 4, 5};
std::set<int> set_b = {0, 4, 8};
const auto compare_sets = [] (std::set<int>, std::set<int>) { return false; };
EXPECT_NONFATAL_FAILURE(
EXPECT_PRED2(compare_sets, set_a, set_b),
"compare_sets(set_a, set_b) evaluates to false, where\nset_a evaluates "
"to { 1, 2, 3, 4, 5 }\nset_b evaluates to { 0, 4, 8 }");
}
// Some helper functions for testing using overloaded/template
// functions with ASSERT_PREDn and EXPECT_PREDn.
bool IsPositive(double x) {
return x > 0;
}
template <typename T>
bool IsNegative(T x) {
return x < 0;
}
template <typename T1, typename T2>
bool GreaterThan(T1 x1, T2 x2) {
return x1 > x2;
}
// Tests that overloaded functions can be used in *_PRED* as long as
// their types are explicitly specified.
TEST(PredicateAssertionTest, AcceptsOverloadedFunction) {
// C++Builder requires C-style casts rather than static_cast.
EXPECT_PRED1((bool (*)(int))(IsPositive), 5); // NOLINT
ASSERT_PRED1((bool (*)(double))(IsPositive), 6.0); // NOLINT
}
// Tests that template functions can be used in *_PRED* as long as
// their types are explicitly specified.
TEST(PredicateAssertionTest, AcceptsTemplateFunction) {
EXPECT_PRED1(IsNegative<int>, -5);
// Makes sure that we can handle templates with more than one
// parameter.
ASSERT_PRED2((GreaterThan<int, int>), 5, 0);
}
// Some helper functions for testing using overloaded/template
// functions with ASSERT_PRED_FORMATn and EXPECT_PRED_FORMATn.
AssertionResult IsPositiveFormat(const char* /* expr */, int n) {
return n > 0 ? AssertionSuccess() :
AssertionFailure(Message() << "Failure");
}
AssertionResult IsPositiveFormat(const char* /* expr */, double x) {
return x > 0 ? AssertionSuccess() :
AssertionFailure(Message() << "Failure");
}
template <typename T>
AssertionResult IsNegativeFormat(const char* /* expr */, T x) {
return x < 0 ? AssertionSuccess() :
AssertionFailure(Message() << "Failure");
}
template <typename T1, typename T2>
AssertionResult EqualsFormat(const char* /* expr1 */, const char* /* expr2 */,
const T1& x1, const T2& x2) {
return x1 == x2 ? AssertionSuccess() :
AssertionFailure(Message() << "Failure");
}
// Tests that overloaded functions can be used in *_PRED_FORMAT*
// without explicitly specifying their types.
TEST(PredicateFormatAssertionTest, AcceptsOverloadedFunction) {
EXPECT_PRED_FORMAT1(IsPositiveFormat, 5);
ASSERT_PRED_FORMAT1(IsPositiveFormat, 6.0);
}
// Tests that template functions can be used in *_PRED_FORMAT* without
// explicitly specifying their types.
TEST(PredicateFormatAssertionTest, AcceptsTemplateFunction) {
EXPECT_PRED_FORMAT1(IsNegativeFormat, -5);
ASSERT_PRED_FORMAT2(EqualsFormat, 3, 3);
}
// Tests string assertions.
// Tests ASSERT_STREQ with non-NULL arguments.
TEST(StringAssertionTest, ASSERT_STREQ) {
const char * const p1 = "good";
ASSERT_STREQ(p1, p1);
// Let p2 have the same content as p1, but be at a different address.
const char p2[] = "good";
ASSERT_STREQ(p1, p2);
EXPECT_FATAL_FAILURE(ASSERT_STREQ("bad", "good"),
" \"bad\"\n \"good\"");
}
// Tests ASSERT_STREQ with NULL arguments.
TEST(StringAssertionTest, ASSERT_STREQ_Null) {
ASSERT_STREQ(static_cast<const char*>(nullptr), nullptr);
EXPECT_FATAL_FAILURE(ASSERT_STREQ(nullptr, "non-null"), "non-null");
}
// Tests ASSERT_STREQ with NULL arguments.
TEST(StringAssertionTest, ASSERT_STREQ_Null2) {
EXPECT_FATAL_FAILURE(ASSERT_STREQ("non-null", nullptr), "non-null");
}
// Tests ASSERT_STRNE.
TEST(StringAssertionTest, ASSERT_STRNE) {
ASSERT_STRNE("hi", "Hi");
ASSERT_STRNE("Hi", nullptr);
ASSERT_STRNE(nullptr, "Hi");
ASSERT_STRNE("", nullptr);
ASSERT_STRNE(nullptr, "");
ASSERT_STRNE("", "Hi");
ASSERT_STRNE("Hi", "");
EXPECT_FATAL_FAILURE(ASSERT_STRNE("Hi", "Hi"),
"\"Hi\" vs \"Hi\"");
}
// Tests ASSERT_STRCASEEQ.
TEST(StringAssertionTest, ASSERT_STRCASEEQ) {
ASSERT_STRCASEEQ("hi", "Hi");
ASSERT_STRCASEEQ(static_cast<const char*>(nullptr), nullptr);
ASSERT_STRCASEEQ("", "");
EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("Hi", "hi2"),
"Ignoring case");
}
// Tests ASSERT_STRCASENE.
TEST(StringAssertionTest, ASSERT_STRCASENE) {
ASSERT_STRCASENE("hi1", "Hi2");
ASSERT_STRCASENE("Hi", nullptr);
ASSERT_STRCASENE(nullptr, "Hi");
ASSERT_STRCASENE("", nullptr);
ASSERT_STRCASENE(nullptr, "");
ASSERT_STRCASENE("", "Hi");
ASSERT_STRCASENE("Hi", "");
EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("Hi", "hi"),
"(ignoring case)");
}
// Tests *_STREQ on wide strings.
TEST(StringAssertionTest, STREQ_Wide) {
// NULL strings.
ASSERT_STREQ(static_cast<const wchar_t*>(nullptr), nullptr);
// Empty strings.
ASSERT_STREQ(L"", L"");
// Non-null vs NULL.
EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"non-null", nullptr), "non-null");
// Equal strings.
EXPECT_STREQ(L"Hi", L"Hi");
// Unequal strings.
EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc", L"Abc"),
"Abc");
// Strings containing wide characters.
EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc\x8119", L"abc\x8120"),
"abc");
// The streaming variation.
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_STREQ(L"abc\x8119", L"abc\x8121") << "Expected failure";
}, "Expected failure");
}
// Tests *_STRNE on wide strings.
TEST(StringAssertionTest, STRNE_Wide) {
// NULL strings.
EXPECT_NONFATAL_FAILURE(
{ // NOLINT
EXPECT_STRNE(static_cast<const wchar_t*>(nullptr), nullptr);
},
"");
// Empty strings.
EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"", L""),
"L\"\"");
// Non-null vs NULL.
ASSERT_STRNE(L"non-null", nullptr);
// Equal strings.
EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"Hi", L"Hi"),
"L\"Hi\"");
// Unequal strings.
EXPECT_STRNE(L"abc", L"Abc");
// Strings containing wide characters.
EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"abc\x8119", L"abc\x8119"),
"abc");
// The streaming variation.
ASSERT_STRNE(L"abc\x8119", L"abc\x8120") << "This shouldn't happen";
}
// Tests for ::testing::IsSubstring().
// Tests that IsSubstring() returns the correct result when the input
// argument type is const char*.
TEST(IsSubstringTest, ReturnsCorrectResultForCString) {
EXPECT_FALSE(IsSubstring("", "", nullptr, "a"));
EXPECT_FALSE(IsSubstring("", "", "b", nullptr));
EXPECT_FALSE(IsSubstring("", "", "needle", "haystack"));
EXPECT_TRUE(IsSubstring("", "", static_cast<const char*>(nullptr), nullptr));
EXPECT_TRUE(IsSubstring("", "", "needle", "two needles"));
}
// Tests that IsSubstring() returns the correct result when the input
// argument type is const wchar_t*.
TEST(IsSubstringTest, ReturnsCorrectResultForWideCString) {
EXPECT_FALSE(IsSubstring("", "", kNull, L"a"));
EXPECT_FALSE(IsSubstring("", "", L"b", kNull));
EXPECT_FALSE(IsSubstring("", "", L"needle", L"haystack"));
EXPECT_TRUE(
IsSubstring("", "", static_cast<const wchar_t*>(nullptr), nullptr));
EXPECT_TRUE(IsSubstring("", "", L"needle", L"two needles"));
}
// Tests that IsSubstring() generates the correct message when the input
// argument type is const char*.
TEST(IsSubstringTest, GeneratesCorrectMessageForCString) {
EXPECT_STREQ("Value of: needle_expr\n"
" Actual: \"needle\"\n"
"Expected: a substring of haystack_expr\n"
"Which is: \"haystack\"",
IsSubstring("needle_expr", "haystack_expr",
"needle", "haystack").failure_message());
}
// Tests that IsSubstring returns the correct result when the input
// argument type is ::std::string.
TEST(IsSubstringTest, ReturnsCorrectResultsForStdString) {
EXPECT_TRUE(IsSubstring("", "", std::string("hello"), "ahellob"));
EXPECT_FALSE(IsSubstring("", "", "hello", std::string("world")));
}
#if GTEST_HAS_STD_WSTRING
// Tests that IsSubstring returns the correct result when the input
// argument type is ::std::wstring.
TEST(IsSubstringTest, ReturnsCorrectResultForStdWstring) {
EXPECT_TRUE(IsSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
EXPECT_FALSE(IsSubstring("", "", L"needle", ::std::wstring(L"haystack")));
}
// Tests that IsSubstring() generates the correct message when the input
// argument type is ::std::wstring.
TEST(IsSubstringTest, GeneratesCorrectMessageForWstring) {
EXPECT_STREQ("Value of: needle_expr\n"
" Actual: L\"needle\"\n"
"Expected: a substring of haystack_expr\n"
"Which is: L\"haystack\"",
IsSubstring(
"needle_expr", "haystack_expr",
::std::wstring(L"needle"), L"haystack").failure_message());
}
#endif // GTEST_HAS_STD_WSTRING
// Tests for ::testing::IsNotSubstring().
// Tests that IsNotSubstring() returns the correct result when the input
// argument type is const char*.
TEST(IsNotSubstringTest, ReturnsCorrectResultForCString) {
EXPECT_TRUE(IsNotSubstring("", "", "needle", "haystack"));
EXPECT_FALSE(IsNotSubstring("", "", "needle", "two needles"));
}
// Tests that IsNotSubstring() returns the correct result when the input
// argument type is const wchar_t*.
TEST(IsNotSubstringTest, ReturnsCorrectResultForWideCString) {
EXPECT_TRUE(IsNotSubstring("", "", L"needle", L"haystack"));
EXPECT_FALSE(IsNotSubstring("", "", L"needle", L"two needles"));
}
// Tests that IsNotSubstring() generates the correct message when the input
// argument type is const wchar_t*.
TEST(IsNotSubstringTest, GeneratesCorrectMessageForWideCString) {
EXPECT_STREQ("Value of: needle_expr\n"
" Actual: L\"needle\"\n"
"Expected: not a substring of haystack_expr\n"
"Which is: L\"two needles\"",
IsNotSubstring(
"needle_expr", "haystack_expr",
L"needle", L"two needles").failure_message());
}
// Tests that IsNotSubstring returns the correct result when the input
// argument type is ::std::string.
TEST(IsNotSubstringTest, ReturnsCorrectResultsForStdString) {
EXPECT_FALSE(IsNotSubstring("", "", std::string("hello"), "ahellob"));
EXPECT_TRUE(IsNotSubstring("", "", "hello", std::string("world")));
}
// Tests that IsNotSubstring() generates the correct message when the input
// argument type is ::std::string.
TEST(IsNotSubstringTest, GeneratesCorrectMessageForStdString) {
EXPECT_STREQ("Value of: needle_expr\n"
" Actual: \"needle\"\n"
"Expected: not a substring of haystack_expr\n"
"Which is: \"two needles\"",
IsNotSubstring(
"needle_expr", "haystack_expr",
::std::string("needle"), "two needles").failure_message());
}
#if GTEST_HAS_STD_WSTRING
// Tests that IsNotSubstring returns the correct result when the input
// argument type is ::std::wstring.
TEST(IsNotSubstringTest, ReturnsCorrectResultForStdWstring) {
EXPECT_FALSE(
IsNotSubstring("", "", ::std::wstring(L"needle"), L"two needles"));
EXPECT_TRUE(IsNotSubstring("", "", L"needle", ::std::wstring(L"haystack")));
}
#endif // GTEST_HAS_STD_WSTRING
// Tests floating-point assertions.
template <typename RawType>
class FloatingPointTest : public Test {
protected:
// Pre-calculated numbers to be used by the tests.
struct TestValues {
RawType close_to_positive_zero;
RawType close_to_negative_zero;
RawType further_from_negative_zero;
RawType close_to_one;
RawType further_from_one;
RawType infinity;
RawType close_to_infinity;
RawType further_from_infinity;
RawType nan1;
RawType nan2;
};
typedef typename testing::internal::FloatingPoint<RawType> Floating;
typedef typename Floating::Bits Bits;
void SetUp() override {
const uint32_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.
values_.close_to_positive_zero = Floating::ReinterpretBits(
zero_bits + max_ulps/2);
values_.close_to_negative_zero = -Floating::ReinterpretBits(
zero_bits + max_ulps - max_ulps/2);
values_.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.
values_.close_to_one = Floating::ReinterpretBits(one_bits + max_ulps);
values_.further_from_one = Floating::ReinterpretBits(
one_bits + max_ulps + 1);
// +infinity.
values_.infinity = Floating::Infinity();
// The bits that represent +infinity.
const Bits infinity_bits = Floating(values_.infinity).bits();
// Makes some numbers close to infinity.
values_.close_to_infinity = Floating::ReinterpretBits(
infinity_bits - max_ulps);
values_.further_from_infinity = Floating::ReinterpretBits(
infinity_bits - max_ulps - 1);
// Makes some NAN's. Sets the most significant bit of the fraction so that
// our NaN's are quiet; trying to process a signaling NaN would raise an
// exception if our environment enables floating point exceptions.
values_.nan1 = Floating::ReinterpretBits(Floating::kExponentBitMask
| (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 1);
values_.nan2 = Floating::ReinterpretBits(Floating::kExponentBitMask
| (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 200);
}
void TestSize() {
EXPECT_EQ(sizeof(RawType), sizeof(Bits));
}
static TestValues values_;
};
template <typename RawType>
typename FloatingPointTest<RawType>::TestValues
FloatingPointTest<RawType>::values_;
// Instantiates FloatingPointTest for testing *_FLOAT_EQ.
typedef FloatingPointTest<float> FloatTest;
// Tests that the size of Float::Bits matches the size of float.
TEST_F(FloatTest, Size) {
TestSize();
}
// Tests comparing with +0 and -0.
TEST_F(FloatTest, Zeros) {
EXPECT_FLOAT_EQ(0.0, -0.0);
EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(-0.0, 1.0),
"1.0");
EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.5),
"1.5");
}
// Tests comparing numbers close to 0.
//
// This ensures that *_FLOAT_EQ handles the sign correctly and no
// overflow occurs when comparing numbers whose absolute value is very
// small.
TEST_F(FloatTest, AlmostZeros) {
// In C++Builder, names within local classes (such as used by
// EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
// scoping class. Use a static local alias as a workaround.
// We use the assignment syntax since some compilers, like Sun Studio,
// don't allow initializing references using construction syntax
// (parentheses).
static const FloatTest::TestValues& v = this->values_;
EXPECT_FLOAT_EQ(0.0, v.close_to_positive_zero);
EXPECT_FLOAT_EQ(-0.0, v.close_to_negative_zero);
EXPECT_FLOAT_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
EXPECT_FATAL_FAILURE({ // NOLINT
ASSERT_FLOAT_EQ(v.close_to_positive_zero,
v.further_from_negative_zero);
}, "v.further_from_negative_zero");
}
// Tests comparing numbers close to each other.
TEST_F(FloatTest, SmallDiff) {
EXPECT_FLOAT_EQ(1.0, values_.close_to_one);
EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, values_.further_from_one),
"values_.further_from_one");
}
// Tests comparing numbers far apart.
TEST_F(FloatTest, LargeDiff) {
EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(2.5, 3.0),
"3.0");
}
// Tests comparing with infinity.
//
// This ensures that no overflow occurs when comparing numbers whose
// absolute value is very large.
TEST_F(FloatTest, Infinity) {
EXPECT_FLOAT_EQ(values_.infinity, values_.close_to_infinity);
EXPECT_FLOAT_EQ(-values_.infinity, -values_.close_to_infinity);
EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, -values_.infinity),
"-values_.infinity");
// This is interesting as the representations of infinity and nan1
// are only 1 DLP apart.
EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, values_.nan1),
"values_.nan1");
}
// Tests that comparing with NAN always returns false.
TEST_F(FloatTest, NaN) {
// In C++Builder, names within local classes (such as used by
// EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
// scoping class. Use a static local alias as a workaround.
// We use the assignment syntax since some compilers, like Sun Studio,
// don't allow initializing references using construction syntax
// (parentheses).
static const FloatTest::TestValues& v = this->values_;
EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan1),
"v.nan1");
EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan2),
"v.nan2");
EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, v.nan1),
"v.nan1");
EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(v.nan1, v.infinity),
"v.infinity");
}
// Tests that *_FLOAT_EQ are reflexive.
TEST_F(FloatTest, Reflexive) {
EXPECT_FLOAT_EQ(0.0, 0.0);
EXPECT_FLOAT_EQ(1.0, 1.0);
ASSERT_FLOAT_EQ(values_.infinity, values_.infinity);
}
// Tests that *_FLOAT_EQ are commutative.
TEST_F(FloatTest, Commutative) {
// We already tested EXPECT_FLOAT_EQ(1.0, values_.close_to_one).
EXPECT_FLOAT_EQ(values_.close_to_one, 1.0);
// We already tested EXPECT_FLOAT_EQ(1.0, values_.further_from_one).
EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.further_from_one, 1.0),
"1.0");
}
// Tests EXPECT_NEAR.
TEST_F(FloatTest, EXPECT_NEAR) {
EXPECT_NEAR(-1.0f, -1.1f, 0.2f);
EXPECT_NEAR(2.0f, 3.0f, 1.0f);
EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0f, 1.5f, 0.25f), // NOLINT
"The difference between 1.0f and 1.5f is 0.5, "
"which exceeds 0.25f");
}
// Tests ASSERT_NEAR.
TEST_F(FloatTest, ASSERT_NEAR) {
ASSERT_NEAR(-1.0f, -1.1f, 0.2f);
ASSERT_NEAR(2.0f, 3.0f, 1.0f);
EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0f, 1.5f, 0.25f), // NOLINT
"The difference between 1.0f and 1.5f is 0.5, "
"which exceeds 0.25f");
}
// Tests the cases where FloatLE() should succeed.
TEST_F(FloatTest, FloatLESucceeds) {
EXPECT_PRED_FORMAT2(FloatLE, 1.0f, 2.0f); // When val1 < val2,
ASSERT_PRED_FORMAT2(FloatLE, 1.0f, 1.0f); // val1 == val2,
// or when val1 is greater than, but almost equals to, val2.
EXPECT_PRED_FORMAT2(FloatLE, values_.close_to_positive_zero, 0.0f);
}
// Tests the cases where FloatLE() should fail.
TEST_F(FloatTest, FloatLEFails) {
// When val1 is greater than val2 by a large margin,
EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(FloatLE, 2.0f, 1.0f),
"(2.0f) <= (1.0f)");
// or by a small yet non-negligible margin,
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_PRED_FORMAT2(FloatLE, values_.further_from_one, 1.0f);
}, "(values_.further_from_one) <= (1.0f)");
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_PRED_FORMAT2(FloatLE, values_.nan1, values_.infinity);
}, "(values_.nan1) <= (values_.infinity)");
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_PRED_FORMAT2(FloatLE, -values_.infinity, values_.nan1);
}, "(-values_.infinity) <= (values_.nan1)");
EXPECT_FATAL_FAILURE({ // NOLINT
ASSERT_PRED_FORMAT2(FloatLE, values_.nan1, values_.nan1);
}, "(values_.nan1) <= (values_.nan1)");
}
// Instantiates FloatingPointTest for testing *_DOUBLE_EQ.
typedef FloatingPointTest<double> DoubleTest;
// Tests that the size of Double::Bits matches the size of double.
TEST_F(DoubleTest, Size) {
TestSize();
}
// Tests comparing with +0 and -0.
TEST_F(DoubleTest, Zeros) {
EXPECT_DOUBLE_EQ(0.0, -0.0);
EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(-0.0, 1.0),
"1.0");
EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(0.0, 1.0),
"1.0");
}
// Tests comparing numbers close to 0.
//
// This ensures that *_DOUBLE_EQ handles the sign correctly and no
// overflow occurs when comparing numbers whose absolute value is very
// small.
TEST_F(DoubleTest, AlmostZeros) {
// In C++Builder, names within local classes (such as used by
// EXPECT_FATAL_FAILURE) cannot be resolved against static members of the
// scoping class. Use a static local alias as a workaround.
// We use the assignment syntax since some compilers, like Sun Studio,
// don't allow initializing references using construction syntax
// (parentheses).
static const DoubleTest::TestValues& v = this->values_;
EXPECT_DOUBLE_EQ(0.0, v.close_to_positive_zero);
EXPECT_DOUBLE_EQ(-0.0, v.close_to_negative_zero);
EXPECT_DOUBLE_EQ(v.close_to_positive_zero, v.close_to_negative_zero);
EXPECT_FATAL_FAILURE({ // NOLINT
ASSERT_DOUBLE_EQ(v.close_to_positive_zero,
v.further_from_negative_zero);
}, "v.further_from_negative_zero");
}
// Tests comparing numbers close to each other.
TEST_F(DoubleTest, SmallDiff) {
EXPECT_DOUBLE_EQ(1.0, values_.close_to_one);
EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, values_.further_from_one),
"values_.further_from_one");
}
// Tests comparing numbers far apart.
TEST_F(DoubleTest, LargeDiff) {
EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(2.0, 3.0),
"3.0");
}
// Tests comparing with infinity.
//
// This ensures that no overflow occurs when comparing numbers whose
// absolute value is very large.
TEST_F(DoubleTest, Infinity) {
EXPECT_DOUBLE_EQ(values_.infinity, values_.close_to_infinity);
EXPECT_DOUBLE_EQ(-values_.infinity, -values_.close_to_infinity);
EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, -values_.infinity),
"-values_.infinity");
// This is interesting as the representations of infinity_ and nan1_
// are only 1 DLP apart.
EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, values_.nan1),
"values_.nan1");
}
// Tests that comparing with NAN always returns false.
TEST_F(DoubleTest, NaN) {
static const DoubleTest::TestValues& v = this->values_;
// Nokia's STLport crashes if we try to output infinity or NaN.
EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan1),
"v.nan1");
EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan2), "v.nan2");
EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, v.nan1), "v.nan1");
EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(v.nan1, v.infinity),
"v.infinity");
}
// Tests that *_DOUBLE_EQ are reflexive.
TEST_F(DoubleTest, Reflexive) {
EXPECT_DOUBLE_EQ(0.0, 0.0);
EXPECT_DOUBLE_EQ(1.0, 1.0);
ASSERT_DOUBLE_EQ(values_.infinity, values_.infinity);
}
// Tests that *_DOUBLE_EQ are commutative.
TEST_F(DoubleTest, Commutative) {
// We already tested EXPECT_DOUBLE_EQ(1.0, values_.close_to_one).
EXPECT_DOUBLE_EQ(values_.close_to_one, 1.0);
// We already tested EXPECT_DOUBLE_EQ(1.0, values_.further_from_one).
EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.further_from_one, 1.0),
"1.0");
}
// Tests EXPECT_NEAR.
TEST_F(DoubleTest, EXPECT_NEAR) {
EXPECT_NEAR(-1.0, -1.1, 0.2);
EXPECT_NEAR(2.0, 3.0, 1.0);
EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0, 1.5, 0.25), // NOLINT
"The difference between 1.0 and 1.5 is 0.5, "
"which exceeds 0.25");
// At this magnitude adjacent doubles are 512.0 apart, so this triggers a
// slightly different failure reporting path.
EXPECT_NONFATAL_FAILURE(
EXPECT_NEAR(4.2934311416234112e+18, 4.2934311416234107e+18, 1.0),
"The abs_error parameter 1.0 evaluates to 1 which is smaller than the "
"minimum distance between doubles for numbers of this magnitude which is "
"512");
}
// Tests ASSERT_NEAR.
TEST_F(DoubleTest, ASSERT_NEAR) {
ASSERT_NEAR(-1.0, -1.1, 0.2);
ASSERT_NEAR(2.0, 3.0, 1.0);
EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0, 1.5, 0.25), // NOLINT
"The difference between 1.0 and 1.5 is 0.5, "
"which exceeds 0.25");
}
// Tests the cases where DoubleLE() should succeed.
TEST_F(DoubleTest, DoubleLESucceeds) {
EXPECT_PRED_FORMAT2(DoubleLE, 1.0, 2.0); // When val1 < val2,
ASSERT_PRED_FORMAT2(DoubleLE, 1.0, 1.0); // val1 == val2,
// or when val1 is greater than, but almost equals to, val2.
EXPECT_PRED_FORMAT2(DoubleLE, values_.close_to_positive_zero, 0.0);
}
// Tests the cases where DoubleLE() should fail.
TEST_F(DoubleTest, DoubleLEFails) {
// When val1 is greater than val2 by a large margin,
EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(DoubleLE, 2.0, 1.0),
"(2.0) <= (1.0)");
// or by a small yet non-negligible margin,
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_PRED_FORMAT2(DoubleLE, values_.further_from_one, 1.0);
}, "(values_.further_from_one) <= (1.0)");
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.infinity);
}, "(values_.nan1) <= (values_.infinity)");
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_PRED_FORMAT2(DoubleLE, -values_.infinity, values_.nan1);
}, " (-values_.infinity) <= (values_.nan1)");
EXPECT_FATAL_FAILURE({ // NOLINT
ASSERT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.nan1);
}, "(values_.nan1) <= (values_.nan1)");
}
// Verifies that a test or test case whose name starts with DISABLED_ is
// not run.
// A test whose name starts with DISABLED_.
// Should not run.
TEST(DisabledTest, DISABLED_TestShouldNotRun) {
FAIL() << "Unexpected failure: Disabled test should not be run.";
}
// A test whose name does not start with DISABLED_.
// Should run.
TEST(DisabledTest, NotDISABLED_TestShouldRun) {
EXPECT_EQ(1, 1);
}
// A test case whose name starts with DISABLED_.
// Should not run.
TEST(DISABLED_TestSuite, TestShouldNotRun) {
FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
}
// A test case and test whose names start with DISABLED_.
// Should not run.
TEST(DISABLED_TestSuite, DISABLED_TestShouldNotRun) {
FAIL() << "Unexpected failure: Test in disabled test case should not be run.";
}
// Check that when all tests in a test case are disabled, SetUpTestSuite() and
// TearDownTestSuite() are not called.
class DisabledTestsTest : public Test {
protected:
static void SetUpTestSuite() {
FAIL() << "Unexpected failure: All tests disabled in test case. "
"SetUpTestSuite() should not be called.";
}
static void TearDownTestSuite() {
FAIL() << "Unexpected failure: All tests disabled in test case. "
"TearDownTestSuite() should not be called.";
}
};
TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_1) {
FAIL() << "Unexpected failure: Disabled test should not be run.";
}
TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_2) {
FAIL() << "Unexpected failure: Disabled test should not be run.";
}
// Tests that disabled typed tests aren't run.
template <typename T>
class TypedTest : public Test {
};
typedef testing::Types<int, double> NumericTypes;
TYPED_TEST_SUITE(TypedTest, NumericTypes);
TYPED_TEST(TypedTest, DISABLED_ShouldNotRun) {
FAIL() << "Unexpected failure: Disabled typed test should not run.";
}
template <typename T>
class DISABLED_TypedTest : public Test {
};
TYPED_TEST_SUITE(DISABLED_TypedTest, NumericTypes);
TYPED_TEST(DISABLED_TypedTest, ShouldNotRun) {
FAIL() << "Unexpected failure: Disabled typed test should not run.";
}
// Tests that disabled type-parameterized tests aren't run.
template <typename T>
class TypedTestP : public Test {
};
TYPED_TEST_SUITE_P(TypedTestP);
TYPED_TEST_P(TypedTestP, DISABLED_ShouldNotRun) {
FAIL() << "Unexpected failure: "
<< "Disabled type-parameterized test should not run.";
}
REGISTER_TYPED_TEST_SUITE_P(TypedTestP, DISABLED_ShouldNotRun);
INSTANTIATE_TYPED_TEST_SUITE_P(My, TypedTestP, NumericTypes);
template <typename T>
class DISABLED_TypedTestP : public Test {
};
TYPED_TEST_SUITE_P(DISABLED_TypedTestP);
TYPED_TEST_P(DISABLED_TypedTestP, ShouldNotRun) {
FAIL() << "Unexpected failure: "
<< "Disabled type-parameterized test should not run.";
}
REGISTER_TYPED_TEST_SUITE_P(DISABLED_TypedTestP, ShouldNotRun);
INSTANTIATE_TYPED_TEST_SUITE_P(My, DISABLED_TypedTestP, NumericTypes);
// Tests that assertion macros evaluate their arguments exactly once.
class SingleEvaluationTest : public Test {
public: // Must be public and not protected due to a bug in g++ 3.4.2.
// This helper function is needed by the FailedASSERT_STREQ test
// below. It's public to work around C++Builder's bug with scoping local
// classes.
static void CompareAndIncrementCharPtrs() {
ASSERT_STREQ(p1_++, p2_++);
}
// This helper function is needed by the FailedASSERT_NE test below. It's
// public to work around C++Builder's bug with scoping local classes.
static void CompareAndIncrementInts() {
ASSERT_NE(a_++, b_++);
}
protected:
SingleEvaluationTest() {
p1_ = s1_;
p2_ = s2_;
a_ = 0;
b_ = 0;
}
static const char* const s1_;
static const char* const s2_;
static const char* p1_;
static const char* p2_;
static int a_;
static int b_;
};
const char* const SingleEvaluationTest::s1_ = "01234";
const char* const SingleEvaluationTest::s2_ = "abcde";
const char* SingleEvaluationTest::p1_;
const char* SingleEvaluationTest::p2_;
int SingleEvaluationTest::a_;
int SingleEvaluationTest::b_;
// Tests that when ASSERT_STREQ fails, it evaluates its arguments
// exactly once.
TEST_F(SingleEvaluationTest, FailedASSERT_STREQ) {
EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementCharPtrs(),
"p2_++");
EXPECT_EQ(s1_ + 1, p1_);
EXPECT_EQ(s2_ + 1, p2_);
}
// Tests that string assertion arguments are evaluated exactly once.
TEST_F(SingleEvaluationTest, ASSERT_STR) {
// successful EXPECT_STRNE
EXPECT_STRNE(p1_++, p2_++);
EXPECT_EQ(s1_ + 1, p1_);
EXPECT_EQ(s2_ + 1, p2_);
// failed EXPECT_STRCASEEQ
EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ(p1_++, p2_++),
"Ignoring case");
EXPECT_EQ(s1_ + 2, p1_);
EXPECT_EQ(s2_ + 2, p2_);
}
// Tests that when ASSERT_NE fails, it evaluates its arguments exactly
// once.
TEST_F(SingleEvaluationTest, FailedASSERT_NE) {
EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementInts(),
"(a_++) != (b_++)");
EXPECT_EQ(1, a_);
EXPECT_EQ(1, b_);
}
// Tests that assertion arguments are evaluated exactly once.
TEST_F(SingleEvaluationTest, OtherCases) {
// successful EXPECT_TRUE
EXPECT_TRUE(0 == a_++); // NOLINT
EXPECT_EQ(1, a_);
// failed EXPECT_TRUE
EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(-1 == a_++), "-1 == a_++");
EXPECT_EQ(2, a_);
// successful EXPECT_GT
EXPECT_GT(a_++, b_++);
EXPECT_EQ(3, a_);
EXPECT_EQ(1, b_);
// failed EXPECT_LT
EXPECT_NONFATAL_FAILURE(EXPECT_LT(a_++, b_++), "(a_++) < (b_++)");
EXPECT_EQ(4, a_);
EXPECT_EQ(2, b_);
// successful ASSERT_TRUE
ASSERT_TRUE(0 < a_++); // NOLINT
EXPECT_EQ(5, a_);
// successful ASSERT_GT
ASSERT_GT(a_++, b_++);
EXPECT_EQ(6, a_);
EXPECT_EQ(3, b_);
}
#if GTEST_HAS_EXCEPTIONS
#if GTEST_HAS_RTTI
#ifdef _MSC_VER
#define ERROR_DESC "class std::runtime_error"
#else
#define ERROR_DESC "std::runtime_error"
#endif
#else // GTEST_HAS_RTTI
#define ERROR_DESC "an std::exception-derived error"
#endif // GTEST_HAS_RTTI
void ThrowAnInteger() {
throw 1;
}
void ThrowRuntimeError(const char* what) {
throw std::runtime_error(what);
}
// Tests that assertion arguments are evaluated exactly once.
TEST_F(SingleEvaluationTest, ExceptionTests) {
// successful EXPECT_THROW
EXPECT_THROW({ // NOLINT
a_++;
ThrowAnInteger();
}, int);
EXPECT_EQ(1, a_);
// failed EXPECT_THROW, throws different
EXPECT_NONFATAL_FAILURE(EXPECT_THROW({ // NOLINT
a_++;
ThrowAnInteger();
}, bool), "throws a different type");
EXPECT_EQ(2, a_);
// failed EXPECT_THROW, throws runtime error
EXPECT_NONFATAL_FAILURE(EXPECT_THROW({ // NOLINT
a_++;
ThrowRuntimeError("A description");
}, bool), "throws " ERROR_DESC " with description \"A description\"");
EXPECT_EQ(3, a_);
// failed EXPECT_THROW, throws nothing
EXPECT_NONFATAL_FAILURE(EXPECT_THROW(a_++, bool), "throws nothing");
EXPECT_EQ(4, a_);
// successful EXPECT_NO_THROW
EXPECT_NO_THROW(a_++);
EXPECT_EQ(5, a_);
// failed EXPECT_NO_THROW
EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW({ // NOLINT
a_++;
ThrowAnInteger();
}), "it throws");
EXPECT_EQ(6, a_);
// successful EXPECT_ANY_THROW
EXPECT_ANY_THROW({ // NOLINT
a_++;
ThrowAnInteger();
});
EXPECT_EQ(7, a_);
// failed EXPECT_ANY_THROW
EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(a_++), "it doesn't");
EXPECT_EQ(8, a_);
}
#endif // GTEST_HAS_EXCEPTIONS
// Tests {ASSERT|EXPECT}_NO_FATAL_FAILURE.
class NoFatalFailureTest : public Test {
protected:
void Succeeds() {}
void FailsNonFatal() {
ADD_FAILURE() << "some non-fatal failure";
}
void Fails() {
FAIL() << "some fatal failure";
}
void DoAssertNoFatalFailureOnFails() {
ASSERT_NO_FATAL_FAILURE(Fails());
ADD_FAILURE() << "should not reach here.";
}
void DoExpectNoFatalFailureOnFails() {
EXPECT_NO_FATAL_FAILURE(Fails());
ADD_FAILURE() << "other failure";
}
};
TEST_F(NoFatalFailureTest, NoFailure) {
EXPECT_NO_FATAL_FAILURE(Succeeds());
ASSERT_NO_FATAL_FAILURE(Succeeds());
}
TEST_F(NoFatalFailureTest, NonFatalIsNoFailure) {
EXPECT_NONFATAL_FAILURE(
EXPECT_NO_FATAL_FAILURE(FailsNonFatal()),
"some non-fatal failure");
EXPECT_NONFATAL_FAILURE(
ASSERT_NO_FATAL_FAILURE(FailsNonFatal()),
"some non-fatal failure");
}
TEST_F(NoFatalFailureTest, AssertNoFatalFailureOnFatalFailure) {
TestPartResultArray gtest_failures;
{
ScopedFakeTestPartResultReporter gtest_reporter(>est_failures);
DoAssertNoFatalFailureOnFails();
}
ASSERT_EQ(2, gtest_failures.size());
EXPECT_EQ(TestPartResult::kFatalFailure,
gtest_failures.GetTestPartResult(0).type());
EXPECT_EQ(TestPartResult::kFatalFailure,
gtest_failures.GetTestPartResult(1).type());
EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
gtest_failures.GetTestPartResult(0).message());
EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
gtest_failures.GetTestPartResult(1).message());
}
TEST_F(NoFatalFailureTest, ExpectNoFatalFailureOnFatalFailure) {
TestPartResultArray gtest_failures;
{
ScopedFakeTestPartResultReporter gtest_reporter(>est_failures);
DoExpectNoFatalFailureOnFails();
}
ASSERT_EQ(3, gtest_failures.size());
EXPECT_EQ(TestPartResult::kFatalFailure,
gtest_failures.GetTestPartResult(0).type());
EXPECT_EQ(TestPartResult::kNonFatalFailure,
gtest_failures.GetTestPartResult(1).type());
EXPECT_EQ(TestPartResult::kNonFatalFailure,
gtest_failures.GetTestPartResult(2).type());
EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure",
gtest_failures.GetTestPartResult(0).message());
EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does",
gtest_failures.GetTestPartResult(1).message());
EXPECT_PRED_FORMAT2(testing::IsSubstring, "other failure",
gtest_failures.GetTestPartResult(2).message());
}
TEST_F(NoFatalFailureTest, MessageIsStreamable) {
TestPartResultArray gtest_failures;
{
ScopedFakeTestPartResultReporter gtest_reporter(>est_failures);
EXPECT_NO_FATAL_FAILURE(FAIL() << "foo") << "my message";
}
ASSERT_EQ(2, gtest_failures.size());
EXPECT_EQ(TestPartResult::kNonFatalFailure,
gtest_failures.GetTestPartResult(0).type());
EXPECT_EQ(TestPartResult::kNonFatalFailure,
gtest_failures.GetTestPartResult(1).type());
EXPECT_PRED_FORMAT2(testing::IsSubstring, "foo",
gtest_failures.GetTestPartResult(0).message());
EXPECT_PRED_FORMAT2(testing::IsSubstring, "my message",
gtest_failures.GetTestPartResult(1).message());
}
// Tests non-string assertions.
std::string EditsToString(const std::vector<EditType>& edits) {
std::string out;
for (size_t i = 0; i < edits.size(); ++i) {
static const char kEdits[] = " +-/";
out.append(1, kEdits[edits[i]]);
}
return out;
}
std::vector<size_t> CharsToIndices(const std::string& str) {
std::vector<size_t> out;
for (size_t i = 0; i < str.size(); ++i) {
out.push_back(static_cast<size_t>(str[i]));
}
return out;
}
std::vector<std::string> CharsToLines(const std::string& str) {
std::vector<std::string> out;
for (size_t i = 0; i < str.size(); ++i) {
out.push_back(str.substr(i, 1));
}
return out;
}
TEST(EditDistance, TestSuites) {
struct Case {
int line;
const char* left;
const char* right;
const char* expected_edits;
const char* expected_diff;
};
static const Case kCases[] = {
// No change.
{__LINE__, "A", "A", " ", ""},
{__LINE__, "ABCDE", "ABCDE", " ", ""},
// Simple adds.
{__LINE__, "X", "XA", " +", "@@ +1,2 @@\n X\n+A\n"},
{__LINE__, "X", "XABCD", " ++++", "@@ +1,5 @@\n X\n+A\n+B\n+C\n+D\n"},
// Simple removes.
{__LINE__, "XA", "X", " -", "@@ -1,2 @@\n X\n-A\n"},
{__LINE__, "XABCD", "X", " ----", "@@ -1,5 @@\n X\n-A\n-B\n-C\n-D\n"},
// Simple replaces.
{__LINE__, "A", "a", "/", "@@ -1,1 +1,1 @@\n-A\n+a\n"},
{__LINE__, "ABCD", "abcd", "////",
"@@ -1,4 +1,4 @@\n-A\n-B\n-C\n-D\n+a\n+b\n+c\n+d\n"},
// Path finding.
{__LINE__, "ABCDEFGH", "ABXEGH1", " -/ - +",
"@@ -1,8 +1,7 @@\n A\n B\n-C\n-D\n+X\n E\n-F\n G\n H\n+1\n"},
{__LINE__, "AAAABCCCC", "ABABCDCDC", "- / + / ",
"@@ -1,9 +1,9 @@\n-A\n A\n-A\n+B\n A\n B\n C\n+D\n C\n-C\n+D\n C\n"},
{__LINE__, "ABCDE", "BCDCD", "- +/",
"@@ -1,5 +1,5 @@\n-A\n B\n C\n D\n-E\n+C\n+D\n"},
{__LINE__, "ABCDEFGHIJKL", "BCDCDEFGJKLJK", "- ++ -- ++",
"@@ -1,4 +1,5 @@\n-A\n B\n+C\n+D\n C\n D\n"
"@@ -6,7 +7,7 @@\n F\n G\n-H\n-I\n J\n K\n L\n+J\n+K\n"},
{}};
for (const Case* c = kCases; c->left; ++c) {
EXPECT_TRUE(c->expected_edits ==
EditsToString(CalculateOptimalEdits(CharsToIndices(c->left),
CharsToIndices(c->right))))
<< "Left <" << c->left << "> Right <" << c->right << "> Edits <"
<< EditsToString(CalculateOptimalEdits(
CharsToIndices(c->left), CharsToIndices(c->right))) << ">";
EXPECT_TRUE(c->expected_diff == CreateUnifiedDiff(CharsToLines(c->left),
CharsToLines(c->right)))
<< "Left <" << c->left << "> Right <" << c->right << "> Diff <"
<< CreateUnifiedDiff(CharsToLines(c->left), CharsToLines(c->right))
<< ">";
}
}
// Tests EqFailure(), used for implementing *EQ* assertions.
TEST(AssertionTest, EqFailure) {
const std::string foo_val("5"), bar_val("6");
const std::string msg1(
EqFailure("foo", "bar", foo_val, bar_val, false)
.failure_message());
EXPECT_STREQ(
"Expected equality of these values:\n"
" foo\n"
" Which is: 5\n"
" bar\n"
" Which is: 6",
msg1.c_str());
const std::string msg2(
EqFailure("foo", "6", foo_val, bar_val, false)
.failure_message());
EXPECT_STREQ(
"Expected equality of these values:\n"
" foo\n"
" Which is: 5\n"
" 6",
msg2.c_str());
const std::string msg3(
EqFailure("5", "bar", foo_val, bar_val, false)
.failure_message());
EXPECT_STREQ(
"Expected equality of these values:\n"
" 5\n"
" bar\n"
" Which is: 6",
msg3.c_str());
const std::string msg4(
EqFailure("5", "6", foo_val, bar_val, false).failure_message());
EXPECT_STREQ(
"Expected equality of these values:\n"
" 5\n"
" 6",
msg4.c_str());
const std::string msg5(
EqFailure("foo", "bar",
std::string("\"x\""), std::string("\"y\""),
true).failure_message());
EXPECT_STREQ(
"Expected equality of these values:\n"
" foo\n"
" Which is: \"x\"\n"
" bar\n"
" Which is: \"y\"\n"
"Ignoring case",
msg5.c_str());
}
TEST(AssertionTest, EqFailureWithDiff) {
const std::string left(
"1\\n2XXX\\n3\\n5\\n6\\n7\\n8\\n9\\n10\\n11\\n12XXX\\n13\\n14\\n15");
const std::string right(
"1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n11\\n12\\n13\\n14");
const std::string msg1(
EqFailure("left", "right", left, right, false).failure_message());
EXPECT_STREQ(
"Expected equality of these values:\n"
" left\n"
" Which is: "
"1\\n2XXX\\n3\\n5\\n6\\n7\\n8\\n9\\n10\\n11\\n12XXX\\n13\\n14\\n15\n"
" right\n"
" Which is: 1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n11\\n12\\n13\\n14\n"
"With diff:\n@@ -1,5 +1,6 @@\n 1\n-2XXX\n+2\n 3\n+4\n 5\n 6\n"
"@@ -7,8 +8,6 @@\n 8\n 9\n-10\n 11\n-12XXX\n+12\n 13\n 14\n-15\n",
msg1.c_str());
}
// Tests AppendUserMessage(), used for implementing the *EQ* macros.
TEST(AssertionTest, AppendUserMessage) {
const std::string foo("foo");
Message msg;
EXPECT_STREQ("foo",
AppendUserMessage(foo, msg).c_str());
msg << "bar";
EXPECT_STREQ("foo\nbar",
AppendUserMessage(foo, msg).c_str());
}
#ifdef __BORLANDC__
// Silences warnings: "Condition is always true", "Unreachable code"
# pragma option push -w-ccc -w-rch
#endif
// Tests ASSERT_TRUE.
TEST(AssertionTest, ASSERT_TRUE) {
ASSERT_TRUE(2 > 1); // NOLINT
EXPECT_FATAL_FAILURE(ASSERT_TRUE(2 < 1),
"2 < 1");
}
// Tests ASSERT_TRUE(predicate) for predicates returning AssertionResult.
TEST(AssertionTest, AssertTrueWithAssertionResult) {
ASSERT_TRUE(ResultIsEven(2));
#ifndef __BORLANDC__
// ICE's in C++Builder.
EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEven(3)),
"Value of: ResultIsEven(3)\n"
" Actual: false (3 is odd)\n"
"Expected: true");
#endif
ASSERT_TRUE(ResultIsEvenNoExplanation(2));
EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEvenNoExplanation(3)),
"Value of: ResultIsEvenNoExplanation(3)\n"
" Actual: false (3 is odd)\n"
"Expected: true");
}
// Tests ASSERT_FALSE.
TEST(AssertionTest, ASSERT_FALSE) {
ASSERT_FALSE(2 < 1); // NOLINT
EXPECT_FATAL_FAILURE(ASSERT_FALSE(2 > 1),
"Value of: 2 > 1\n"
" Actual: true\n"
"Expected: false");
}
// Tests ASSERT_FALSE(predicate) for predicates returning AssertionResult.
TEST(AssertionTest, AssertFalseWithAssertionResult) {
ASSERT_FALSE(ResultIsEven(3));
#ifndef __BORLANDC__
// ICE's in C++Builder.
EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEven(2)),
"Value of: ResultIsEven(2)\n"
" Actual: true (2 is even)\n"
"Expected: false");
#endif
ASSERT_FALSE(ResultIsEvenNoExplanation(3));
EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEvenNoExplanation(2)),
"Value of: ResultIsEvenNoExplanation(2)\n"
" Actual: true\n"
"Expected: false");
}
#ifdef __BORLANDC__
// Restores warnings after previous "#pragma option push" suppressed them
# pragma option pop
#endif
// Tests using ASSERT_EQ on double values. The purpose is to make
// sure that the specialization we did for integer and anonymous enums
// isn't used for double arguments.
TEST(ExpectTest, ASSERT_EQ_Double) {
// A success.
ASSERT_EQ(5.6, 5.6);
// A failure.
EXPECT_FATAL_FAILURE(ASSERT_EQ(5.1, 5.2),
"5.1");
}
// Tests ASSERT_EQ.
TEST(AssertionTest, ASSERT_EQ) {
ASSERT_EQ(5, 2 + 3);
EXPECT_FATAL_FAILURE(ASSERT_EQ(5, 2*3),
"Expected equality of these values:\n"
" 5\n"
" 2*3\n"
" Which is: 6");
}
// Tests ASSERT_EQ(NULL, pointer).
TEST(AssertionTest, ASSERT_EQ_NULL) {
// A success.
const char* p = nullptr;
ASSERT_EQ(nullptr, p);
// A failure.
static int n = 0;
EXPECT_FATAL_FAILURE(ASSERT_EQ(nullptr, &n), " &n\n Which is:");
}
// Tests ASSERT_EQ(0, non_pointer). Since the literal 0 can be
// treated as a null pointer by the compiler, we need to make sure
// that ASSERT_EQ(0, non_pointer) isn't interpreted by Google Test as
// ASSERT_EQ(static_cast<void*>(NULL), non_pointer).
TEST(ExpectTest, ASSERT_EQ_0) {
int n = 0;
// A success.
ASSERT_EQ(0, n);
// A failure.
EXPECT_FATAL_FAILURE(ASSERT_EQ(0, 5.6),
" 0\n 5.6");
}
// Tests ASSERT_NE.
TEST(AssertionTest, ASSERT_NE) {
ASSERT_NE(6, 7);
EXPECT_FATAL_FAILURE(ASSERT_NE('a', 'a'),
"Expected: ('a') != ('a'), "
"actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
}
// Tests ASSERT_LE.
TEST(AssertionTest, ASSERT_LE) {
ASSERT_LE(2, 3);
ASSERT_LE(2, 2);
EXPECT_FATAL_FAILURE(ASSERT_LE(2, 0),
"Expected: (2) <= (0), actual: 2 vs 0");
}
// Tests ASSERT_LT.
TEST(AssertionTest, ASSERT_LT) {
ASSERT_LT(2, 3);
EXPECT_FATAL_FAILURE(ASSERT_LT(2, 2),
"Expected: (2) < (2), actual: 2 vs 2");
}
// Tests ASSERT_GE.
TEST(AssertionTest, ASSERT_GE) {
ASSERT_GE(2, 1);
ASSERT_GE(2, 2);
EXPECT_FATAL_FAILURE(ASSERT_GE(2, 3),
"Expected: (2) >= (3), actual: 2 vs 3");
}
// Tests ASSERT_GT.
TEST(AssertionTest, ASSERT_GT) {
ASSERT_GT(2, 1);
EXPECT_FATAL_FAILURE(ASSERT_GT(2, 2),
"Expected: (2) > (2), actual: 2 vs 2");
}
#if GTEST_HAS_EXCEPTIONS
void ThrowNothing() {}
// Tests ASSERT_THROW.
TEST(AssertionTest, ASSERT_THROW) {
ASSERT_THROW(ThrowAnInteger(), int);
# ifndef __BORLANDC__
// ICE's in C++Builder 2007 and 2009.
EXPECT_FATAL_FAILURE(
ASSERT_THROW(ThrowAnInteger(), bool),
"Expected: ThrowAnInteger() throws an exception of type bool.\n"
" Actual: it throws a different type.");
EXPECT_FATAL_FAILURE(
ASSERT_THROW(ThrowRuntimeError("A description"), std::logic_error),
"Expected: ThrowRuntimeError(\"A description\") "
"throws an exception of type std::logic_error.\n "
"Actual: it throws " ERROR_DESC " "
"with description \"A description\".");
# endif
EXPECT_FATAL_FAILURE(
ASSERT_THROW(ThrowNothing(), bool),
"Expected: ThrowNothing() throws an exception of type bool.\n"
" Actual: it throws nothing.");
}
// Tests ASSERT_NO_THROW.
TEST(AssertionTest, ASSERT_NO_THROW) {
ASSERT_NO_THROW(ThrowNothing());
EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()),
"Expected: ThrowAnInteger() doesn't throw an exception."
"\n Actual: it throws.");
EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowRuntimeError("A description")),
"Expected: ThrowRuntimeError(\"A description\") "
"doesn't throw an exception.\n "
"Actual: it throws " ERROR_DESC " "
"with description \"A description\".");
}
// Tests ASSERT_ANY_THROW.
TEST(AssertionTest, ASSERT_ANY_THROW) {
ASSERT_ANY_THROW(ThrowAnInteger());
EXPECT_FATAL_FAILURE(
ASSERT_ANY_THROW(ThrowNothing()),
"Expected: ThrowNothing() throws an exception.\n"
" Actual: it doesn't.");
}
#endif // GTEST_HAS_EXCEPTIONS
// Makes sure we deal with the precedence of <<. This test should
// compile.
TEST(AssertionTest, AssertPrecedence) {
ASSERT_EQ(1 < 2, true);
bool false_value = false;
ASSERT_EQ(true && false_value, false);
}
// A subroutine used by the following test.
void TestEq1(int x) {
ASSERT_EQ(1, x);
}
// Tests calling a test subroutine that's not part of a fixture.
TEST(AssertionTest, NonFixtureSubroutine) {
EXPECT_FATAL_FAILURE(TestEq1(2),
" x\n Which is: 2");
}
// An uncopyable class.
class Uncopyable {
public:
explicit Uncopyable(int a_value) : value_(a_value) {}
int value() const { return value_; }
bool operator==(const Uncopyable& rhs) const {
return value() == rhs.value();
}
private:
// This constructor deliberately has no implementation, as we don't
// want this class to be copyable.
Uncopyable(const Uncopyable&); // NOLINT
int value_;
};
::std::ostream& operator<<(::std::ostream& os, const Uncopyable& value) {
return os << value.value();
}
bool IsPositiveUncopyable(const Uncopyable& x) {
return x.value() > 0;
}
// A subroutine used by the following test.
void TestAssertNonPositive() {
Uncopyable y(-1);
ASSERT_PRED1(IsPositiveUncopyable, y);
}
// A subroutine used by the following test.
void TestAssertEqualsUncopyable() {
Uncopyable x(5);
Uncopyable y(-1);
ASSERT_EQ(x, y);
}
// Tests that uncopyable objects can be used in assertions.
TEST(AssertionTest, AssertWorksWithUncopyableObject) {
Uncopyable x(5);
ASSERT_PRED1(IsPositiveUncopyable, x);
ASSERT_EQ(x, x);
EXPECT_FATAL_FAILURE(TestAssertNonPositive(),
"IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
EXPECT_FATAL_FAILURE(TestAssertEqualsUncopyable(),
"Expected equality of these values:\n"
" x\n Which is: 5\n y\n Which is: -1");
}
// Tests that uncopyable objects can be used in expects.
TEST(AssertionTest, ExpectWorksWithUncopyableObject) {
Uncopyable x(5);
EXPECT_PRED1(IsPositiveUncopyable, x);
Uncopyable y(-1);
EXPECT_NONFATAL_FAILURE(EXPECT_PRED1(IsPositiveUncopyable, y),
"IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1");
EXPECT_EQ(x, x);
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y),
"Expected equality of these values:\n"
" x\n Which is: 5\n y\n Which is: -1");
}
enum NamedEnum {
kE1 = 0,
kE2 = 1
};
TEST(AssertionTest, NamedEnum) {
EXPECT_EQ(kE1, kE1);
EXPECT_LT(kE1, kE2);
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 0");
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 1");
}
// Sun Studio and HP aCC2reject this code.
#if !defined(__SUNPRO_CC) && !defined(__HP_aCC)
// Tests using assertions with anonymous enums.
enum {
kCaseA = -1,
# if GTEST_OS_LINUX
// We want to test the case where the size of the anonymous enum is
// larger than sizeof(int), to make sure our implementation of the
// assertions doesn't truncate the enums. However, MSVC
// (incorrectly) doesn't allow an enum value to exceed the range of
// an int, so this has to be conditionally compiled.
//
// On Linux, kCaseB and kCaseA have the same value when truncated to
// int size. We want to test whether this will confuse the
// assertions.
kCaseB = testing::internal::kMaxBiggestInt,
# else
kCaseB = INT_MAX,
# endif // GTEST_OS_LINUX
kCaseC = 42
};
TEST(AssertionTest, AnonymousEnum) {
# if GTEST_OS_LINUX
EXPECT_EQ(static_cast<int>(kCaseA), static_cast<int>(kCaseB));
# endif // GTEST_OS_LINUX
EXPECT_EQ(kCaseA, kCaseA);
EXPECT_NE(kCaseA, kCaseB);
EXPECT_LT(kCaseA, kCaseB);
EXPECT_LE(kCaseA, kCaseB);
EXPECT_GT(kCaseB, kCaseA);
EXPECT_GE(kCaseA, kCaseA);
EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseB),
"(kCaseA) >= (kCaseB)");
EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseC),
"-1 vs 42");
ASSERT_EQ(kCaseA, kCaseA);
ASSERT_NE(kCaseA, kCaseB);
ASSERT_LT(kCaseA, kCaseB);
ASSERT_LE(kCaseA, kCaseB);
ASSERT_GT(kCaseB, kCaseA);
ASSERT_GE(kCaseA, kCaseA);
# ifndef __BORLANDC__
// ICE's in C++Builder.
EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseB),
" kCaseB\n Which is: ");
EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC),
"\n Which is: 42");
# endif
EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC),
"\n Which is: -1");
}
#endif // !GTEST_OS_MAC && !defined(__SUNPRO_CC)
#if GTEST_OS_WINDOWS
static HRESULT UnexpectedHRESULTFailure() {
return E_UNEXPECTED;
}
static HRESULT OkHRESULTSuccess() {
return S_OK;
}
static HRESULT FalseHRESULTSuccess() {
return S_FALSE;
}
// HRESULT assertion tests test both zero and non-zero
// success codes as well as failure message for each.
//
// Windows CE doesn't support message texts.
TEST(HRESULTAssertionTest, EXPECT_HRESULT_SUCCEEDED) {
EXPECT_HRESULT_SUCCEEDED(S_OK);
EXPECT_HRESULT_SUCCEEDED(S_FALSE);
EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
"Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
" Actual: 0x8000FFFF");
}
TEST(HRESULTAssertionTest, ASSERT_HRESULT_SUCCEEDED) {
ASSERT_HRESULT_SUCCEEDED(S_OK);
ASSERT_HRESULT_SUCCEEDED(S_FALSE);
EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),
"Expected: (UnexpectedHRESULTFailure()) succeeds.\n"
" Actual: 0x8000FFFF");
}
TEST(HRESULTAssertionTest, EXPECT_HRESULT_FAILED) {
EXPECT_HRESULT_FAILED(E_UNEXPECTED);
EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(OkHRESULTSuccess()),
"Expected: (OkHRESULTSuccess()) fails.\n"
" Actual: 0x0");
EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(FalseHRESULTSuccess()),
"Expected: (FalseHRESULTSuccess()) fails.\n"
" Actual: 0x1");
}
TEST(HRESULTAssertionTest, ASSERT_HRESULT_FAILED) {
ASSERT_HRESULT_FAILED(E_UNEXPECTED);
# ifndef __BORLANDC__
// ICE's in C++Builder 2007 and 2009.
EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(OkHRESULTSuccess()),
"Expected: (OkHRESULTSuccess()) fails.\n"
" Actual: 0x0");
# endif
EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(FalseHRESULTSuccess()),
"Expected: (FalseHRESULTSuccess()) fails.\n"
" Actual: 0x1");
}
// Tests that streaming to the HRESULT macros works.
TEST(HRESULTAssertionTest, Streaming) {
EXPECT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
ASSERT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure";
EXPECT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
ASSERT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure";
EXPECT_NONFATAL_FAILURE(
EXPECT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
"expected failure");
# ifndef __BORLANDC__
// ICE's in C++Builder 2007 and 2009.
EXPECT_FATAL_FAILURE(
ASSERT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure",
"expected failure");
# endif
EXPECT_NONFATAL_FAILURE(
EXPECT_HRESULT_FAILED(S_OK) << "expected failure",
"expected failure");
EXPECT_FATAL_FAILURE(
ASSERT_HRESULT_FAILED(S_OK) << "expected failure",
"expected failure");
}
#endif // GTEST_OS_WINDOWS
// The following code intentionally tests a suboptimal syntax.
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdangling-else"
#pragma GCC diagnostic ignored "-Wempty-body"
#pragma GCC diagnostic ignored "-Wpragmas"
#endif
// Tests that the assertion macros behave like single statements.
TEST(AssertionSyntaxTest, BasicAssertionsBehavesLikeSingleStatement) {
if (AlwaysFalse())
ASSERT_TRUE(false) << "This should never be executed; "
"It's a compilation test only.";
if (AlwaysTrue())
EXPECT_FALSE(false);
else
; // NOLINT
if (AlwaysFalse())
ASSERT_LT(1, 3);
if (AlwaysFalse())
; // NOLINT
else
EXPECT_GT(3, 2) << "";
}
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif
#if GTEST_HAS_EXCEPTIONS
// Tests that the compiler will not complain about unreachable code in the
// EXPECT_THROW/EXPECT_ANY_THROW/EXPECT_NO_THROW macros.
TEST(ExpectThrowTest, DoesNotGenerateUnreachableCodeWarning) {
int n = 0;
EXPECT_THROW(throw 1, int);
EXPECT_NONFATAL_FAILURE(EXPECT_THROW(n++, int), "");
EXPECT_NONFATAL_FAILURE(EXPECT_THROW(throw 1, const char*), "");
EXPECT_NO_THROW(n++);
EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(throw 1), "");
EXPECT_ANY_THROW(throw 1);
EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(n++), "");
}
TEST(ExpectThrowTest, DoesNotGenerateDuplicateCatchClauseWarning) {
EXPECT_THROW(throw std::exception(), std::exception);
}
// The following code intentionally tests a suboptimal syntax.
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdangling-else"
#pragma GCC diagnostic ignored "-Wempty-body"
#pragma GCC diagnostic ignored "-Wpragmas"
#endif
TEST(AssertionSyntaxTest, ExceptionAssertionsBehavesLikeSingleStatement) {
if (AlwaysFalse())
EXPECT_THROW(ThrowNothing(), bool);
if (AlwaysTrue())
EXPECT_THROW(ThrowAnInteger(), int);
else
; // NOLINT
if (AlwaysFalse())
EXPECT_NO_THROW(ThrowAnInteger());
if (AlwaysTrue())
EXPECT_NO_THROW(ThrowNothing());
else
; // NOLINT
if (AlwaysFalse())
EXPECT_ANY_THROW(ThrowNothing());
if (AlwaysTrue())
EXPECT_ANY_THROW(ThrowAnInteger());
else
; // NOLINT
}
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif
#endif // GTEST_HAS_EXCEPTIONS
// The following code intentionally tests a suboptimal syntax.
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdangling-else"
#pragma GCC diagnostic ignored "-Wempty-body"
#pragma GCC diagnostic ignored "-Wpragmas"
#endif
TEST(AssertionSyntaxTest, NoFatalFailureAssertionsBehavesLikeSingleStatement) {
if (AlwaysFalse())
EXPECT_NO_FATAL_FAILURE(FAIL()) << "This should never be executed. "
<< "It's a compilation test only.";
else
; // NOLINT
if (AlwaysFalse())
ASSERT_NO_FATAL_FAILURE(FAIL()) << "";
else
; // NOLINT
if (AlwaysTrue())
EXPECT_NO_FATAL_FAILURE(SUCCEED());
else
; // NOLINT
if (AlwaysFalse())
; // NOLINT
else
ASSERT_NO_FATAL_FAILURE(SUCCEED());
}
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif
// Tests that the assertion macros work well with switch statements.
TEST(AssertionSyntaxTest, WorksWithSwitch) {
switch (0) {
case 1:
break;
default:
ASSERT_TRUE(true);
}
switch (0)
case 0:
EXPECT_FALSE(false) << "EXPECT_FALSE failed in switch case";
// Binary assertions are implemented using a different code path
// than the Boolean assertions. Hence we test them separately.
switch (0) {
case 1:
default:
ASSERT_EQ(1, 1) << "ASSERT_EQ failed in default switch handler";
}
switch (0)
case 0:
EXPECT_NE(1, 2);
}
#if GTEST_HAS_EXCEPTIONS
void ThrowAString() {
throw "std::string";
}
// Test that the exception assertion macros compile and work with const
// type qualifier.
TEST(AssertionSyntaxTest, WorksWithConst) {
ASSERT_THROW(ThrowAString(), const char*);
EXPECT_THROW(ThrowAString(), const char*);
}
#endif // GTEST_HAS_EXCEPTIONS
} // namespace
namespace testing {
// Tests that Google Test tracks SUCCEED*.
TEST(SuccessfulAssertionTest, SUCCEED) {
SUCCEED();
SUCCEED() << "OK";
EXPECT_EQ(2, GetUnitTestImpl()->current_test_result()->total_part_count());
}
// Tests that Google Test doesn't track successful EXPECT_*.
TEST(SuccessfulAssertionTest, EXPECT) {
EXPECT_TRUE(true);
EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
}
// Tests that Google Test doesn't track successful EXPECT_STR*.
TEST(SuccessfulAssertionTest, EXPECT_STR) {
EXPECT_STREQ("", "");
EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
}
// Tests that Google Test doesn't track successful ASSERT_*.
TEST(SuccessfulAssertionTest, ASSERT) {
ASSERT_TRUE(true);
EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
}
// Tests that Google Test doesn't track successful ASSERT_STR*.
TEST(SuccessfulAssertionTest, ASSERT_STR) {
ASSERT_STREQ("", "");
EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());
}
} // namespace testing
namespace {
// Tests the message streaming variation of assertions.
TEST(AssertionWithMessageTest, EXPECT) {
EXPECT_EQ(1, 1) << "This should succeed.";
EXPECT_NONFATAL_FAILURE(EXPECT_NE(1, 1) << "Expected failure #1.",
"Expected failure #1");
EXPECT_LE(1, 2) << "This should succeed.";
EXPECT_NONFATAL_FAILURE(EXPECT_LT(1, 0) << "Expected failure #2.",
"Expected failure #2.");
EXPECT_GE(1, 0) << "This should succeed.";
EXPECT_NONFATAL_FAILURE(EXPECT_GT(1, 2) << "Expected failure #3.",
"Expected failure #3.");
EXPECT_STREQ("1", "1") << "This should succeed.";
EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("1", "1") << "Expected failure #4.",
"Expected failure #4.");
EXPECT_STRCASEEQ("a", "A") << "This should succeed.";
EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("a", "A") << "Expected failure #5.",
"Expected failure #5.");
EXPECT_FLOAT_EQ(1, 1) << "This should succeed.";
EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1, 1.2) << "Expected failure #6.",
"Expected failure #6.");
EXPECT_NEAR(1, 1.1, 0.2) << "This should succeed.";
}
TEST(AssertionWithMessageTest, ASSERT) {
ASSERT_EQ(1, 1) << "This should succeed.";
ASSERT_NE(1, 2) << "This should succeed.";
ASSERT_LE(1, 2) << "This should succeed.";
ASSERT_LT(1, 2) << "This should succeed.";
ASSERT_GE(1, 0) << "This should succeed.";
EXPECT_FATAL_FAILURE(ASSERT_GT(1, 2) << "Expected failure.",
"Expected failure.");
}
TEST(AssertionWithMessageTest, ASSERT_STR) {
ASSERT_STREQ("1", "1") << "This should succeed.";
ASSERT_STRNE("1", "2") << "This should succeed.";
ASSERT_STRCASEEQ("a", "A") << "This should succeed.";
EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("a", "A") << "Expected failure.",
"Expected failure.");
}
TEST(AssertionWithMessageTest, ASSERT_FLOATING) {
ASSERT_FLOAT_EQ(1, 1) << "This should succeed.";
ASSERT_DOUBLE_EQ(1, 1) << "This should succeed.";
EXPECT_FATAL_FAILURE(ASSERT_NEAR(1, 1.2, 0.1) << "Expect failure.", // NOLINT
"Expect failure.");
}
// Tests using ASSERT_FALSE with a streamed message.
TEST(AssertionWithMessageTest, ASSERT_FALSE) {
ASSERT_FALSE(false) << "This shouldn't fail.";
EXPECT_FATAL_FAILURE({ // NOLINT
ASSERT_FALSE(true) << "Expected failure: " << 2 << " > " << 1
<< " evaluates to " << true;
}, "Expected failure");
}
// Tests using FAIL with a streamed message.
TEST(AssertionWithMessageTest, FAIL) {
EXPECT_FATAL_FAILURE(FAIL() << 0,
"0");
}
// Tests using SUCCEED with a streamed message.
TEST(AssertionWithMessageTest, SUCCEED) {
SUCCEED() << "Success == " << 1;
}
// Tests using ASSERT_TRUE with a streamed message.
TEST(AssertionWithMessageTest, ASSERT_TRUE) {
ASSERT_TRUE(true) << "This should succeed.";
ASSERT_TRUE(true) << true;
EXPECT_FATAL_FAILURE(
{ // NOLINT
ASSERT_TRUE(false) << static_cast<const char*>(nullptr)
<< static_cast<char*>(nullptr);
},
"(null)(null)");
}
#if GTEST_OS_WINDOWS
// Tests using wide strings in assertion messages.
TEST(AssertionWithMessageTest, WideStringMessage) {
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_TRUE(false) << L"This failure is expected.\x8119";
}, "This failure is expected.");
EXPECT_FATAL_FAILURE({ // NOLINT
ASSERT_EQ(1, 2) << "This failure is "
<< L"expected too.\x8120";
}, "This failure is expected too.");
}
#endif // GTEST_OS_WINDOWS
// Tests EXPECT_TRUE.
TEST(ExpectTest, EXPECT_TRUE) {
EXPECT_TRUE(true) << "Intentional success";
EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #1.",
"Intentional failure #1.");
EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #2.",
"Intentional failure #2.");
EXPECT_TRUE(2 > 1); // NOLINT
EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 < 1),
"Value of: 2 < 1\n"
" Actual: false\n"
"Expected: true");
EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 > 3),
"2 > 3");
}
// Tests EXPECT_TRUE(predicate) for predicates returning AssertionResult.
TEST(ExpectTest, ExpectTrueWithAssertionResult) {
EXPECT_TRUE(ResultIsEven(2));
EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEven(3)),
"Value of: ResultIsEven(3)\n"
" Actual: false (3 is odd)\n"
"Expected: true");
EXPECT_TRUE(ResultIsEvenNoExplanation(2));
EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEvenNoExplanation(3)),
"Value of: ResultIsEvenNoExplanation(3)\n"
" Actual: false (3 is odd)\n"
"Expected: true");
}
// Tests EXPECT_FALSE with a streamed message.
TEST(ExpectTest, EXPECT_FALSE) {
EXPECT_FALSE(2 < 1); // NOLINT
EXPECT_FALSE(false) << "Intentional success";
EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #1.",
"Intentional failure #1.");
EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #2.",
"Intentional failure #2.");
EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 > 1),
"Value of: 2 > 1\n"
" Actual: true\n"
"Expected: false");
EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 < 3),
"2 < 3");
}
// Tests EXPECT_FALSE(predicate) for predicates returning AssertionResult.
TEST(ExpectTest, ExpectFalseWithAssertionResult) {
EXPECT_FALSE(ResultIsEven(3));
EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEven(2)),
"Value of: ResultIsEven(2)\n"
" Actual: true (2 is even)\n"
"Expected: false");
EXPECT_FALSE(ResultIsEvenNoExplanation(3));
EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEvenNoExplanation(2)),
"Value of: ResultIsEvenNoExplanation(2)\n"
" Actual: true\n"
"Expected: false");
}
#ifdef __BORLANDC__
// Restores warnings after previous "#pragma option push" suppressed them
# pragma option pop
#endif
// Tests EXPECT_EQ.
TEST(ExpectTest, EXPECT_EQ) {
EXPECT_EQ(5, 2 + 3);
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2*3),
"Expected equality of these values:\n"
" 5\n"
" 2*3\n"
" Which is: 6");
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2 - 3),
"2 - 3");
}
// Tests using EXPECT_EQ on double values. The purpose is to make
// sure that the specialization we did for integer and anonymous enums
// isn't used for double arguments.
TEST(ExpectTest, EXPECT_EQ_Double) {
// A success.
EXPECT_EQ(5.6, 5.6);
// A failure.
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5.1, 5.2),
"5.1");
}
// Tests EXPECT_EQ(NULL, pointer).
TEST(ExpectTest, EXPECT_EQ_NULL) {
// A success.
const char* p = nullptr;
EXPECT_EQ(nullptr, p);
// A failure.
int n = 0;
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(nullptr, &n), " &n\n Which is:");
}
// Tests EXPECT_EQ(0, non_pointer). Since the literal 0 can be
// treated as a null pointer by the compiler, we need to make sure
// that EXPECT_EQ(0, non_pointer) isn't interpreted by Google Test as
// EXPECT_EQ(static_cast<void*>(NULL), non_pointer).
TEST(ExpectTest, EXPECT_EQ_0) {
int n = 0;
// A success.
EXPECT_EQ(0, n);
// A failure.
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(0, 5.6),
" 0\n 5.6");
}
// Tests EXPECT_NE.
TEST(ExpectTest, EXPECT_NE) {
EXPECT_NE(6, 7);
EXPECT_NONFATAL_FAILURE(EXPECT_NE('a', 'a'),
"Expected: ('a') != ('a'), "
"actual: 'a' (97, 0x61) vs 'a' (97, 0x61)");
EXPECT_NONFATAL_FAILURE(EXPECT_NE(2, 2),
"2");
char* const p0 = nullptr;
EXPECT_NONFATAL_FAILURE(EXPECT_NE(p0, p0),
"p0");
// Only way to get the Nokia compiler to compile the cast
// is to have a separate void* variable first. Putting
// the two casts on the same line doesn't work, neither does
// a direct C-style to char*.
void* pv1 = (void*)0x1234; // NOLINT
char* const p1 = reinterpret_cast<char*>(pv1);
EXPECT_NONFATAL_FAILURE(EXPECT_NE(p1, p1),
"p1");
}
// Tests EXPECT_LE.
TEST(ExpectTest, EXPECT_LE) {
EXPECT_LE(2, 3);
EXPECT_LE(2, 2);
EXPECT_NONFATAL_FAILURE(EXPECT_LE(2, 0),
"Expected: (2) <= (0), actual: 2 vs 0");
EXPECT_NONFATAL_FAILURE(EXPECT_LE(1.1, 0.9),
"(1.1) <= (0.9)");
}
// Tests EXPECT_LT.
TEST(ExpectTest, EXPECT_LT) {
EXPECT_LT(2, 3);
EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 2),
"Expected: (2) < (2), actual: 2 vs 2");
EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1),
"(2) < (1)");
}
// Tests EXPECT_GE.
TEST(ExpectTest, EXPECT_GE) {
EXPECT_GE(2, 1);
EXPECT_GE(2, 2);
EXPECT_NONFATAL_FAILURE(EXPECT_GE(2, 3),
"Expected: (2) >= (3), actual: 2 vs 3");
EXPECT_NONFATAL_FAILURE(EXPECT_GE(0.9, 1.1),
"(0.9) >= (1.1)");
}
// Tests EXPECT_GT.
TEST(ExpectTest, EXPECT_GT) {
EXPECT_GT(2, 1);
EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 2),
"Expected: (2) > (2), actual: 2 vs 2");
EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 3),
"(2) > (3)");
}
#if GTEST_HAS_EXCEPTIONS
// Tests EXPECT_THROW.
TEST(ExpectTest, EXPECT_THROW) {
EXPECT_THROW(ThrowAnInteger(), int);
EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool),
"Expected: ThrowAnInteger() throws an exception of "
"type bool.\n Actual: it throws a different type.");
EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowRuntimeError("A description"),
std::logic_error),
"Expected: ThrowRuntimeError(\"A description\") "
"throws an exception of type std::logic_error.\n "
"Actual: it throws " ERROR_DESC " "
"with description \"A description\".");
EXPECT_NONFATAL_FAILURE(
EXPECT_THROW(ThrowNothing(), bool),
"Expected: ThrowNothing() throws an exception of type bool.\n"
" Actual: it throws nothing.");
}
// Tests EXPECT_NO_THROW.
TEST(ExpectTest, EXPECT_NO_THROW) {
EXPECT_NO_THROW(ThrowNothing());
EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()),
"Expected: ThrowAnInteger() doesn't throw an "
"exception.\n Actual: it throws.");
EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowRuntimeError("A description")),
"Expected: ThrowRuntimeError(\"A description\") "
"doesn't throw an exception.\n "
"Actual: it throws " ERROR_DESC " "
"with description \"A description\".");
}
// Tests EXPECT_ANY_THROW.
TEST(ExpectTest, EXPECT_ANY_THROW) {
EXPECT_ANY_THROW(ThrowAnInteger());
EXPECT_NONFATAL_FAILURE(
EXPECT_ANY_THROW(ThrowNothing()),
"Expected: ThrowNothing() throws an exception.\n"
" Actual: it doesn't.");
}
#endif // GTEST_HAS_EXCEPTIONS
// Make sure we deal with the precedence of <<.
TEST(ExpectTest, ExpectPrecedence) {
EXPECT_EQ(1 < 2, true);
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(true, true && false),
" true && false\n Which is: false");
}
// Tests the StreamableToString() function.
// Tests using StreamableToString() on a scalar.
TEST(StreamableToStringTest, Scalar) {
EXPECT_STREQ("5", StreamableToString(5).c_str());
}
// Tests using StreamableToString() on a non-char pointer.
TEST(StreamableToStringTest, Pointer) {
int n = 0;
int* p = &n;
EXPECT_STRNE("(null)", StreamableToString(p).c_str());
}
// Tests using StreamableToString() on a NULL non-char pointer.
TEST(StreamableToStringTest, NullPointer) {
int* p = nullptr;
EXPECT_STREQ("(null)", StreamableToString(p).c_str());
}
// Tests using StreamableToString() on a C string.
TEST(StreamableToStringTest, CString) {
EXPECT_STREQ("Foo", StreamableToString("Foo").c_str());
}
// Tests using StreamableToString() on a NULL C string.
TEST(StreamableToStringTest, NullCString) {
char* p = nullptr;
EXPECT_STREQ("(null)", StreamableToString(p).c_str());
}
// Tests using streamable values as assertion messages.
// Tests using std::string as an assertion message.
TEST(StreamableTest, string) {
static const std::string str(
"This failure message is a std::string, and is expected.");
EXPECT_FATAL_FAILURE(FAIL() << str,
str.c_str());
}
// Tests that we can output strings containing embedded NULs.
// Limited to Linux because we can only do this with std::string's.
TEST(StreamableTest, stringWithEmbeddedNUL) {
static const char char_array_with_nul[] =
"Here's a NUL\0 and some more string";
static const std::string string_with_nul(char_array_with_nul,
sizeof(char_array_with_nul)
- 1); // drops the trailing NUL
EXPECT_FATAL_FAILURE(FAIL() << string_with_nul,
"Here's a NUL\\0 and some more string");
}
// Tests that we can output a NUL char.
TEST(StreamableTest, NULChar) {
EXPECT_FATAL_FAILURE({ // NOLINT
FAIL() << "A NUL" << '\0' << " and some more string";
}, "A NUL\\0 and some more string");
}
// Tests using int as an assertion message.
TEST(StreamableTest, int) {
EXPECT_FATAL_FAILURE(FAIL() << 900913,
"900913");
}
// Tests using NULL char pointer as an assertion message.
//
// In MSVC, streaming a NULL char * causes access violation. Google Test
// implemented a workaround (substituting "(null)" for NULL). This
// tests whether the workaround works.
TEST(StreamableTest, NullCharPtr) {
EXPECT_FATAL_FAILURE(FAIL() << static_cast<const char*>(nullptr), "(null)");
}
// Tests that basic IO manipulators (endl, ends, and flush) can be
// streamed to testing::Message.
TEST(StreamableTest, BasicIoManip) {
EXPECT_FATAL_FAILURE({ // NOLINT
FAIL() << "Line 1." << std::endl
<< "A NUL char " << std::ends << std::flush << " in line 2.";
}, "Line 1.\nA NUL char \\0 in line 2.");
}
// Tests the macros that haven't been covered so far.
void AddFailureHelper(bool* aborted) {
*aborted = true;
ADD_FAILURE() << "Intentional failure.";
*aborted = false;
}
// Tests ADD_FAILURE.
TEST(MacroTest, ADD_FAILURE) {
bool aborted = true;
EXPECT_NONFATAL_FAILURE(AddFailureHelper(&aborted),
"Intentional failure.");
EXPECT_FALSE(aborted);
}
// Tests ADD_FAILURE_AT.
TEST(MacroTest, ADD_FAILURE_AT) {
// Verifies that ADD_FAILURE_AT does generate a nonfatal failure and
// the failure message contains the user-streamed part.
EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42) << "Wrong!", "Wrong!");
// Verifies that the user-streamed part is optional.
EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42), "Failed");
// Unfortunately, we cannot verify that the failure message contains
// the right file path and line number the same way, as
// EXPECT_NONFATAL_FAILURE() doesn't get to see the file path and
// line number. Instead, we do that in googletest-output-test_.cc.
}
// Tests FAIL.
TEST(MacroTest, FAIL) {
EXPECT_FATAL_FAILURE(FAIL(),
"Failed");
EXPECT_FATAL_FAILURE(FAIL() << "Intentional failure.",
"Intentional failure.");
}
// Tests GTEST_FAIL_AT.
TEST(MacroTest, GTEST_FAIL_AT) {
// Verifies that GTEST_FAIL_AT does generate a fatal failure and
// the failure message contains the user-streamed part.
EXPECT_FATAL_FAILURE(GTEST_FAIL_AT("foo.cc", 42) << "Wrong!", "Wrong!");
// Verifies that the user-streamed part is optional.
EXPECT_FATAL_FAILURE(GTEST_FAIL_AT("foo.cc", 42), "Failed");
// See the ADD_FAIL_AT test above to see how we test that the failure message
// contains the right filename and line number -- the same applies here.
}
// Tests SUCCEED
TEST(MacroTest, SUCCEED) {
SUCCEED();
SUCCEED() << "Explicit success.";
}
// Tests for EXPECT_EQ() and ASSERT_EQ().
//
// These tests fail *intentionally*, s.t. the failure messages can be
// generated and tested.
//
// We have different tests for different argument types.
// Tests using bool values in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest, Bool) {
EXPECT_EQ(true, true);
EXPECT_FATAL_FAILURE({
bool false_value = false;
ASSERT_EQ(false_value, true);
}, " false_value\n Which is: false\n true");
}
// Tests using int values in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest, Int) {
ASSERT_EQ(32, 32);
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(32, 33),
" 32\n 33");
}
// Tests using time_t values in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest, Time_T) {
EXPECT_EQ(static_cast<time_t>(0),
static_cast<time_t>(0));
EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<time_t>(0),
static_cast<time_t>(1234)),
"1234");
}
// Tests using char values in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest, Char) {
ASSERT_EQ('z', 'z');
const char ch = 'b';
EXPECT_NONFATAL_FAILURE(EXPECT_EQ('\0', ch),
" ch\n Which is: 'b'");
EXPECT_NONFATAL_FAILURE(EXPECT_EQ('a', ch),
" ch\n Which is: 'b'");
}
// Tests using wchar_t values in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest, WideChar) {
EXPECT_EQ(L'b', L'b');
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'\0', L'x'),
"Expected equality of these values:\n"
" L'\0'\n"
" Which is: L'\0' (0, 0x0)\n"
" L'x'\n"
" Which is: L'x' (120, 0x78)");
static wchar_t wchar;
wchar = L'b';
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'a', wchar),
"wchar");
wchar = 0x8119;
EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<wchar_t>(0x8120), wchar),
" wchar\n Which is: L'");
}
// Tests using ::std::string values in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest, StdString) {
// Compares a const char* to an std::string that has identical
// content.
ASSERT_EQ("Test", ::std::string("Test"));
// Compares two identical std::strings.
static const ::std::string str1("A * in the middle");
static const ::std::string str2(str1);
EXPECT_EQ(str1, str2);
// Compares a const char* to an std::string that has different
// content
EXPECT_NONFATAL_FAILURE(EXPECT_EQ("Test", ::std::string("test")),
"\"test\"");
// Compares an std::string to a char* that has different content.
char* const p1 = const_cast<char*>("foo");
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::std::string("bar"), p1),
"p1");
// Compares two std::strings that have different contents, one of
// which having a NUL character in the middle. This should fail.
static ::std::string str3(str1);
str3.at(2) = '\0';
EXPECT_FATAL_FAILURE(ASSERT_EQ(str1, str3),
" str3\n Which is: \"A \\0 in the middle\"");
}
#if GTEST_HAS_STD_WSTRING
// Tests using ::std::wstring values in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest, StdWideString) {
// Compares two identical std::wstrings.
const ::std::wstring wstr1(L"A * in the middle");
const ::std::wstring wstr2(wstr1);
ASSERT_EQ(wstr1, wstr2);
// Compares an std::wstring to a const wchar_t* that has identical
// content.
const wchar_t kTestX8119[] = { 'T', 'e', 's', 't', 0x8119, '\0' };
EXPECT_EQ(::std::wstring(kTestX8119), kTestX8119);
// Compares an std::wstring to a const wchar_t* that has different
// content.
const wchar_t kTestX8120[] = { 'T', 'e', 's', 't', 0x8120, '\0' };
EXPECT_NONFATAL_FAILURE({ // NOLINT
EXPECT_EQ(::std::wstring(kTestX8119), kTestX8120);
}, "kTestX8120");
// Compares two std::wstrings that have different contents, one of
// which having a NUL character in the middle.
::std::wstring wstr3(wstr1);
wstr3.at(2) = L'\0';
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(wstr1, wstr3),
"wstr3");
// Compares a wchar_t* to an std::wstring that has different
// content.
EXPECT_FATAL_FAILURE({ // NOLINT
ASSERT_EQ(const_cast<wchar_t*>(L"foo"), ::std::wstring(L"bar"));
}, "");
}
#endif // GTEST_HAS_STD_WSTRING
// Tests using char pointers in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest, CharPointer) {
char* const p0 = nullptr;
// Only way to get the Nokia compiler to compile the cast
// is to have a separate void* variable first. Putting
// the two casts on the same line doesn't work, neither does
// a direct C-style to char*.
void* pv1 = (void*)0x1234; // NOLINT
void* pv2 = (void*)0xABC0; // NOLINT
char* const p1 = reinterpret_cast<char*>(pv1);
char* const p2 = reinterpret_cast<char*>(pv2);
ASSERT_EQ(p1, p1);
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
" p2\n Which is:");
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
" p2\n Which is:");
EXPECT_FATAL_FAILURE(ASSERT_EQ(reinterpret_cast<char*>(0x1234),
reinterpret_cast<char*>(0xABC0)),
"ABC0");
}
// Tests using wchar_t pointers in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest, WideCharPointer) {
wchar_t* const p0 = nullptr;
// Only way to get the Nokia compiler to compile the cast
// is to have a separate void* variable first. Putting
// the two casts on the same line doesn't work, neither does
// a direct C-style to char*.
void* pv1 = (void*)0x1234; // NOLINT
void* pv2 = (void*)0xABC0; // NOLINT
wchar_t* const p1 = reinterpret_cast<wchar_t*>(pv1);
wchar_t* const p2 = reinterpret_cast<wchar_t*>(pv2);
EXPECT_EQ(p0, p0);
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2),
" p2\n Which is:");
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2),
" p2\n Which is:");
void* pv3 = (void*)0x1234; // NOLINT
void* pv4 = (void*)0xABC0; // NOLINT
const wchar_t* p3 = reinterpret_cast<const wchar_t*>(pv3);
const wchar_t* p4 = reinterpret_cast<const wchar_t*>(pv4);
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p3, p4),
"p4");
}
// Tests using other types of pointers in {EXPECT|ASSERT}_EQ.
TEST(EqAssertionTest, OtherPointer) {
ASSERT_EQ(static_cast<const int*>(nullptr), static_cast<const int*>(nullptr));
EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<const int*>(nullptr),
reinterpret_cast<const int*>(0x1234)),
"0x1234");
}
// A class that supports binary comparison operators but not streaming.
class UnprintableChar {
public:
explicit UnprintableChar(char ch) : char_(ch) {}
bool operator==(const UnprintableChar& rhs) const {
return char_ == rhs.char_;
}
bool operator!=(const UnprintableChar& rhs) const {
return char_ != rhs.char_;
}
bool operator<(const UnprintableChar& rhs) const {
return char_ < rhs.char_;
}
bool operator<=(const UnprintableChar& rhs) const {
return char_ <= rhs.char_;
}
bool operator>(const UnprintableChar& rhs) const {
return char_ > rhs.char_;
}
bool operator>=(const UnprintableChar& rhs) const {
return char_ >= rhs.char_;
}
private:
char char_;
};
// Tests that ASSERT_EQ() and friends don't require the arguments to
// be printable.
TEST(ComparisonAssertionTest, AcceptsUnprintableArgs) {
const UnprintableChar x('x'), y('y');
ASSERT_EQ(x, x);
EXPECT_NE(x, y);
ASSERT_LT(x, y);
EXPECT_LE(x, y);
ASSERT_GT(y, x);
EXPECT_GE(x, x);
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <78>");
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <79>");
EXPECT_NONFATAL_FAILURE(EXPECT_LT(y, y), "1-byte object <79>");
EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <78>");
EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <79>");
// Code tested by EXPECT_FATAL_FAILURE cannot reference local
// variables, so we have to write UnprintableChar('x') instead of x.
#ifndef __BORLANDC__
// ICE's in C++Builder.
EXPECT_FATAL_FAILURE(ASSERT_NE(UnprintableChar('x'), UnprintableChar('x')),
"1-byte object <78>");
EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')),
"1-byte object <78>");
#endif
EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')),
"1-byte object <79>");
EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')),
"1-byte object <78>");
EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')),
"1-byte object <79>");
}
// Tests the FRIEND_TEST macro.
// This class has a private member we want to test. We will test it
// both in a TEST and in a TEST_F.
class Foo {
public:
Foo() {}
private:
int Bar() const { return 1; }
// Declares the friend tests that can access the private member
// Bar().
FRIEND_TEST(FRIEND_TEST_Test, TEST);
FRIEND_TEST(FRIEND_TEST_Test2, TEST_F);
};
// Tests that the FRIEND_TEST declaration allows a TEST to access a
// class's private members. This should compile.
TEST(FRIEND_TEST_Test, TEST) {
ASSERT_EQ(1, Foo().Bar());
}
// The fixture needed to test using FRIEND_TEST with TEST_F.
class FRIEND_TEST_Test2 : public Test {
protected:
Foo foo;
};
// Tests that the FRIEND_TEST declaration allows a TEST_F to access a
// class's private members. This should compile.
TEST_F(FRIEND_TEST_Test2, TEST_F) {
ASSERT_EQ(1, foo.Bar());
}
// Tests the life cycle of Test objects.
// The test fixture for testing the life cycle of Test objects.
//
// This class counts the number of live test objects that uses this
// fixture.
class TestLifeCycleTest : public Test {
protected:
// Constructor. Increments the number of test objects that uses
// this fixture.
TestLifeCycleTest() { count_++; }
// Destructor. Decrements the number of test objects that uses this
// fixture.
~TestLifeCycleTest() override { count_--; }
// Returns the number of live test objects that uses this fixture.
int count() const { return count_; }
private:
static int count_;
};
int TestLifeCycleTest::count_ = 0;
// Tests the life cycle of test objects.
TEST_F(TestLifeCycleTest, Test1) {
// There should be only one test object in this test case that's
// currently alive.
ASSERT_EQ(1, count());
}
// Tests the life cycle of test objects.
TEST_F(TestLifeCycleTest, Test2) {
// After Test1 is done and Test2 is started, there should still be
// only one live test object, as the object for Test1 should've been
// deleted.
ASSERT_EQ(1, count());
}
} // namespace
// Tests that the copy constructor works when it is NOT optimized away by
// the compiler.
TEST(AssertionResultTest, CopyConstructorWorksWhenNotOptimied) {
// Checks that the copy constructor doesn't try to dereference NULL pointers
// in the source object.
AssertionResult r1 = AssertionSuccess();
AssertionResult r2 = r1;
// The following line is added to prevent the compiler from optimizing
// away the constructor call.
r1 << "abc";
AssertionResult r3 = r1;
EXPECT_EQ(static_cast<bool>(r3), static_cast<bool>(r1));
EXPECT_STREQ("abc", r1.message());
}
// Tests that AssertionSuccess and AssertionFailure construct
// AssertionResult objects as expected.
TEST(AssertionResultTest, ConstructionWorks) {
AssertionResult r1 = AssertionSuccess();
EXPECT_TRUE(r1);
EXPECT_STREQ("", r1.message());
AssertionResult r2 = AssertionSuccess() << "abc";
EXPECT_TRUE(r2);
EXPECT_STREQ("abc", r2.message());
AssertionResult r3 = AssertionFailure();
EXPECT_FALSE(r3);
EXPECT_STREQ("", r3.message());
AssertionResult r4 = AssertionFailure() << "def";
EXPECT_FALSE(r4);
EXPECT_STREQ("def", r4.message());
AssertionResult r5 = AssertionFailure(Message() << "ghi");
EXPECT_FALSE(r5);
EXPECT_STREQ("ghi", r5.message());
}
// Tests that the negation flips the predicate result but keeps the message.
TEST(AssertionResultTest, NegationWorks) {
AssertionResult r1 = AssertionSuccess() << "abc";
EXPECT_FALSE(!r1);
EXPECT_STREQ("abc", (!r1).message());
AssertionResult r2 = AssertionFailure() << "def";
EXPECT_TRUE(!r2);
EXPECT_STREQ("def", (!r2).message());
}
TEST(AssertionResultTest, StreamingWorks) {
AssertionResult r = AssertionSuccess();
r << "abc" << 'd' << 0 << true;
EXPECT_STREQ("abcd0true", r.message());
}
TEST(AssertionResultTest, CanStreamOstreamManipulators) {
AssertionResult r = AssertionSuccess();
r << "Data" << std::endl << std::flush << std::ends << "Will be visible";
EXPECT_STREQ("Data\n\\0Will be visible", r.message());
}
// The next test uses explicit conversion operators
TEST(AssertionResultTest, ConstructibleFromContextuallyConvertibleToBool) {
struct ExplicitlyConvertibleToBool {
explicit operator bool() const { return value; }
bool value;
};
ExplicitlyConvertibleToBool v1 = {false};
ExplicitlyConvertibleToBool v2 = {true};
EXPECT_FALSE(v1);
EXPECT_TRUE(v2);
}
struct ConvertibleToAssertionResult {
operator AssertionResult() const { return AssertionResult(true); }
};
TEST(AssertionResultTest, ConstructibleFromImplicitlyConvertible) {
ConvertibleToAssertionResult obj;
EXPECT_TRUE(obj);
}
// Tests streaming a user type whose definition and operator << are
// both in the global namespace.
class Base {
public:
explicit Base(int an_x) : x_(an_x) {}
int x() const { return x_; }
private:
int x_;
};
std::ostream& operator<<(std::ostream& os,
const Base& val) {
return os << val.x();
}
std::ostream& operator<<(std::ostream& os,
const Base* pointer) {
return os << "(" << pointer->x() << ")";
}
TEST(MessageTest, CanStreamUserTypeInGlobalNameSpace) {
Message msg;
Base a(1);
msg << a << &a; // Uses ::operator<<.
EXPECT_STREQ("1(1)", msg.GetString().c_str());
}
// Tests streaming a user type whose definition and operator<< are
// both in an unnamed namespace.
namespace {
class MyTypeInUnnamedNameSpace : public Base {
public:
explicit MyTypeInUnnamedNameSpace(int an_x): Base(an_x) {}
};
std::ostream& operator<<(std::ostream& os,
const MyTypeInUnnamedNameSpace& val) {
return os << val.x();
}
std::ostream& operator<<(std::ostream& os,
const MyTypeInUnnamedNameSpace* pointer) {
return os << "(" << pointer->x() << ")";
}
} // namespace
TEST(MessageTest, CanStreamUserTypeInUnnamedNameSpace) {
Message msg;
MyTypeInUnnamedNameSpace a(1);
msg << a << &a; // Uses <unnamed_namespace>::operator<<.
EXPECT_STREQ("1(1)", msg.GetString().c_str());
}
// Tests streaming a user type whose definition and operator<< are
// both in a user namespace.
namespace namespace1 {
class MyTypeInNameSpace1 : public Base {
public:
explicit MyTypeInNameSpace1(int an_x): Base(an_x) {}
};
std::ostream& operator<<(std::ostream& os,
const MyTypeInNameSpace1& val) {
return os << val.x();
}
std::ostream& operator<<(std::ostream& os,
const MyTypeInNameSpace1* pointer) {
return os << "(" << pointer->x() << ")";
}
} // namespace namespace1
TEST(MessageTest, CanStreamUserTypeInUserNameSpace) {
Message msg;
namespace1::MyTypeInNameSpace1 a(1);
msg << a << &a; // Uses namespace1::operator<<.
EXPECT_STREQ("1(1)", msg.GetString().c_str());
}
// Tests streaming a user type whose definition is in a user namespace
// but whose operator<< is in the global namespace.
namespace namespace2 {
class MyTypeInNameSpace2 : public ::Base {
public:
explicit MyTypeInNameSpace2(int an_x): Base(an_x) {}
};
} // namespace namespace2
std::ostream& operator<<(std::ostream& os,
const namespace2::MyTypeInNameSpace2& val) {
return os << val.x();
}
std::ostream& operator<<(std::ostream& os,
const namespace2::MyTypeInNameSpace2* pointer) {
return os << "(" << pointer->x() << ")";
}
TEST(MessageTest, CanStreamUserTypeInUserNameSpaceWithStreamOperatorInGlobal) {
Message msg;
namespace2::MyTypeInNameSpace2 a(1);
msg << a << &a; // Uses ::operator<<.
EXPECT_STREQ("1(1)", msg.GetString().c_str());
}
// Tests streaming NULL pointers to testing::Message.
TEST(MessageTest, NullPointers) {
Message msg;
char* const p1 = nullptr;
unsigned char* const p2 = nullptr;
int* p3 = nullptr;
double* p4 = nullptr;
bool* p5 = nullptr;
Message* p6 = nullptr;
msg << p1 << p2 << p3 << p4 << p5 << p6;
ASSERT_STREQ("(null)(null)(null)(null)(null)(null)",
msg.GetString().c_str());
}
// Tests streaming wide strings to testing::Message.
TEST(MessageTest, WideStrings) {
// Streams a NULL of type const wchar_t*.
const wchar_t* const_wstr = nullptr;
EXPECT_STREQ("(null)",
(Message() << const_wstr).GetString().c_str());
// Streams a NULL of type wchar_t*.
wchar_t* wstr = nullptr;
EXPECT_STREQ("(null)",
(Message() << wstr).GetString().c_str());
// Streams a non-NULL of type const wchar_t*.
const_wstr = L"abc\x8119";
EXPECT_STREQ("abc\xe8\x84\x99",
(Message() << const_wstr).GetString().c_str());
// Streams a non-NULL of type wchar_t*.
wstr = const_cast<wchar_t*>(const_wstr);
EXPECT_STREQ("abc\xe8\x84\x99",
(Message() << wstr).GetString().c_str());
}
// This line tests that we can define tests in the testing namespace.
namespace testing {
// Tests the TestInfo class.
class TestInfoTest : public Test {
protected:
static const TestInfo* GetTestInfo(const char* test_name) {
const TestSuite* const test_suite =
GetUnitTestImpl()->GetTestSuite("TestInfoTest", "", nullptr, nullptr);
for (int i = 0; i < test_suite->total_test_count(); ++i) {
const TestInfo* const test_info = test_suite->GetTestInfo(i);
if (strcmp(test_name, test_info->name()) == 0)
return test_info;
}
return nullptr;
}
static const TestResult* GetTestResult(
const TestInfo* test_info) {
return test_info->result();
}
};
// Tests TestInfo::test_case_name() and TestInfo::name().
TEST_F(TestInfoTest, Names) {
const TestInfo* const test_info = GetTestInfo("Names");
ASSERT_STREQ("TestInfoTest", test_info->test_suite_name());
ASSERT_STREQ("Names", test_info->name());
}
// Tests TestInfo::result().
TEST_F(TestInfoTest, result) {
const TestInfo* const test_info = GetTestInfo("result");
// Initially, there is no TestPartResult for this test.
ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
// After the previous assertion, there is still none.
ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());
}
#define VERIFY_CODE_LOCATION \
const int expected_line = __LINE__ - 1; \
const TestInfo* const test_info = GetUnitTestImpl()->current_test_info(); \
ASSERT_TRUE(test_info); \
EXPECT_STREQ(__FILE__, test_info->file()); \
EXPECT_EQ(expected_line, test_info->line())
TEST(CodeLocationForTEST, Verify) {
VERIFY_CODE_LOCATION;
}
class CodeLocationForTESTF : public Test {
};
TEST_F(CodeLocationForTESTF, Verify) {
VERIFY_CODE_LOCATION;
}
class CodeLocationForTESTP : public TestWithParam<int> {
};
TEST_P(CodeLocationForTESTP, Verify) {
VERIFY_CODE_LOCATION;
}
INSTANTIATE_TEST_SUITE_P(, CodeLocationForTESTP, Values(0));
template <typename T>
class CodeLocationForTYPEDTEST : public Test {
};
TYPED_TEST_SUITE(CodeLocationForTYPEDTEST, int);
TYPED_TEST(CodeLocationForTYPEDTEST, Verify) {
VERIFY_CODE_LOCATION;
}
template <typename T>
class CodeLocationForTYPEDTESTP : public Test {
};
TYPED_TEST_SUITE_P(CodeLocationForTYPEDTESTP);
TYPED_TEST_P(CodeLocationForTYPEDTESTP, Verify) {
VERIFY_CODE_LOCATION;
}
REGISTER_TYPED_TEST_SUITE_P(CodeLocationForTYPEDTESTP, Verify);
INSTANTIATE_TYPED_TEST_SUITE_P(My, CodeLocationForTYPEDTESTP, int);
#undef VERIFY_CODE_LOCATION
// Tests setting up and tearing down a test case.
// Legacy API is deprecated but still available
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
class SetUpTestCaseTest : public Test {
protected:
// This will be called once before the first test in this test case
// is run.
static void SetUpTestCase() {
printf("Setting up the test case . . .\n");
// Initializes some shared resource. In this simple example, we
// just create a C string. More complex stuff can be done if
// desired.
shared_resource_ = "123";
// Increments the number of test cases that have been set up.
counter_++;
// SetUpTestCase() should be called only once.
EXPECT_EQ(1, counter_);
}
// This will be called once after the last test in this test case is
// run.
static void TearDownTestCase() {
printf("Tearing down the test case . . .\n");
// Decrements the number of test cases that have been set up.
counter_--;
// TearDownTestCase() should be called only once.
EXPECT_EQ(0, counter_);
// Cleans up the shared resource.
shared_resource_ = nullptr;
}
// This will be called before each test in this test case.
void SetUp() override {
// SetUpTestCase() should be called only once, so counter_ should
// always be 1.
EXPECT_EQ(1, counter_);
}
// Number of test cases that have been set up.
static int counter_;
// Some resource to be shared by all tests in this test case.
static const char* shared_resource_;
};
int SetUpTestCaseTest::counter_ = 0;
const char* SetUpTestCaseTest::shared_resource_ = nullptr;
// A test that uses the shared resource.
TEST_F(SetUpTestCaseTest, Test1) { EXPECT_STRNE(nullptr, shared_resource_); }
// Another test that uses the shared resource.
TEST_F(SetUpTestCaseTest, Test2) {
EXPECT_STREQ("123", shared_resource_);
}
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
// Tests SetupTestSuite/TearDown TestSuite
class SetUpTestSuiteTest : public Test {
protected:
// This will be called once before the first test in this test case
// is run.
static void SetUpTestSuite() {
printf("Setting up the test suite . . .\n");
// Initializes some shared resource. In this simple example, we
// just create a C string. More complex stuff can be done if
// desired.
shared_resource_ = "123";
// Increments the number of test cases that have been set up.
counter_++;
// SetUpTestSuite() should be called only once.
EXPECT_EQ(1, counter_);
}
// This will be called once after the last test in this test case is
// run.
static void TearDownTestSuite() {
printf("Tearing down the test suite . . .\n");
// Decrements the number of test suites that have been set up.
counter_--;
// TearDownTestSuite() should be called only once.
EXPECT_EQ(0, counter_);
// Cleans up the shared resource.
shared_resource_ = nullptr;
}
// This will be called before each test in this test case.
void SetUp() override {
// SetUpTestSuite() should be called only once, so counter_ should
// always be 1.
EXPECT_EQ(1, counter_);
}
// Number of test suites that have been set up.
static int counter_;
// Some resource to be shared by all tests in this test case.
static const char* shared_resource_;
};
int SetUpTestSuiteTest::counter_ = 0;
const char* SetUpTestSuiteTest::shared_resource_ = nullptr;
// A test that uses the shared resource.
TEST_F(SetUpTestSuiteTest, TestSetupTestSuite1) {
EXPECT_STRNE(nullptr, shared_resource_);
}
// Another test that uses the shared resource.
TEST_F(SetUpTestSuiteTest, TestSetupTestSuite2) {
EXPECT_STREQ("123", shared_resource_);
}
// The ParseFlagsTest test case tests ParseGoogleTestFlagsOnly.
// The Flags struct stores a copy of all Google Test flags.
struct Flags {
// Constructs a Flags struct where each flag has its default value.
Flags()
: also_run_disabled_tests(false),
break_on_failure(false),
catch_exceptions(false),
death_test_use_fork(false),
fail_fast(false),
filter(""),
list_tests(false),
output(""),
brief(false),
print_time(true),
random_seed(0),
repeat(1),
recreate_environments_when_repeating(true),
shuffle(false),
stack_trace_depth(kMaxStackTraceDepth),
stream_result_to(""),
throw_on_failure(false) {}
// Factory methods.
// Creates a Flags struct where the gtest_also_run_disabled_tests flag has
// the given value.
static Flags AlsoRunDisabledTests(bool also_run_disabled_tests) {
Flags flags;
flags.also_run_disabled_tests = also_run_disabled_tests;
return flags;
}
// Creates a Flags struct where the gtest_break_on_failure flag has
// the given value.
static Flags BreakOnFailure(bool break_on_failure) {
Flags flags;
flags.break_on_failure = break_on_failure;
return flags;
}
// Creates a Flags struct where the gtest_catch_exceptions flag has
// the given value.
static Flags CatchExceptions(bool catch_exceptions) {
Flags flags;
flags.catch_exceptions = catch_exceptions;
return flags;
}
// Creates a Flags struct where the gtest_death_test_use_fork flag has
// the given value.
static Flags DeathTestUseFork(bool death_test_use_fork) {
Flags flags;
flags.death_test_use_fork = death_test_use_fork;
return flags;
}
// Creates a Flags struct where the gtest_fail_fast flag has
// the given value.
static Flags FailFast(bool fail_fast) {
Flags flags;
flags.fail_fast = fail_fast;
return flags;
}
// Creates a Flags struct where the gtest_filter flag has the given
// value.
static Flags Filter(const char* filter) {
Flags flags;
flags.filter = filter;
return flags;
}
// Creates a Flags struct where the gtest_list_tests flag has the
// given value.
static Flags ListTests(bool list_tests) {
Flags flags;
flags.list_tests = list_tests;
return flags;
}
// Creates a Flags struct where the gtest_output flag has the given
// value.
static Flags Output(const char* output) {
Flags flags;
flags.output = output;
return flags;
}
// Creates a Flags struct where the gtest_brief flag has the given
// value.
static Flags Brief(bool brief) {
Flags flags;
flags.brief = brief;
return flags;
}
// Creates a Flags struct where the gtest_print_time flag has the given
// value.
static Flags PrintTime(bool print_time) {
Flags flags;
flags.print_time = print_time;
return flags;
}
// Creates a Flags struct where the gtest_random_seed flag has the given
// value.
static Flags RandomSeed(int32_t random_seed) {
Flags flags;
flags.random_seed = random_seed;
return flags;
}
// Creates a Flags struct where the gtest_repeat flag has the given
// value.
static Flags Repeat(int32_t repeat) {
Flags flags;
flags.repeat = repeat;
return flags;
}
// Creates a Flags struct where the gtest_recreate_environments_when_repeating
// flag has the given value.
static Flags RecreateEnvironmentsWhenRepeating(
bool recreate_environments_when_repeating) {
Flags flags;
flags.recreate_environments_when_repeating =
recreate_environments_when_repeating;
return flags;
}
// Creates a Flags struct where the gtest_shuffle flag has the given
// value.
static Flags Shuffle(bool shuffle) {
Flags flags;
flags.shuffle = shuffle;
return flags;
}
// Creates a Flags struct where the GTEST_FLAG(stack_trace_depth) flag has
// the given value.
static Flags StackTraceDepth(int32_t stack_trace_depth) {
Flags flags;
flags.stack_trace_depth = stack_trace_depth;
return flags;
}
// Creates a Flags struct where the GTEST_FLAG(stream_result_to) flag has
// the given value.
static Flags StreamResultTo(const char* stream_result_to) {
Flags flags;
flags.stream_result_to = stream_result_to;
return flags;
}
// Creates a Flags struct where the gtest_throw_on_failure flag has
// the given value.
static Flags ThrowOnFailure(bool throw_on_failure) {
Flags flags;
flags.throw_on_failure = throw_on_failure;
return flags;
}
// These fields store the flag values.
bool also_run_disabled_tests;
bool break_on_failure;
bool catch_exceptions;
bool death_test_use_fork;
bool fail_fast;
const char* filter;
bool list_tests;
const char* output;
bool brief;
bool print_time;
int32_t random_seed;
int32_t repeat;
bool recreate_environments_when_repeating;
bool shuffle;
int32_t stack_trace_depth;
const char* stream_result_to;
bool throw_on_failure;
};
// Fixture for testing ParseGoogleTestFlagsOnly().
class ParseFlagsTest : public Test {
protected:
// Clears the flags before each test.
void SetUp() override {
GTEST_FLAG_SET(also_run_disabled_tests, false);
GTEST_FLAG_SET(break_on_failure, false);
GTEST_FLAG_SET(catch_exceptions, false);
GTEST_FLAG_SET(death_test_use_fork, false);
GTEST_FLAG_SET(fail_fast, false);
GTEST_FLAG_SET(filter, "");
GTEST_FLAG_SET(list_tests, false);
GTEST_FLAG_SET(output, "");
GTEST_FLAG_SET(brief, false);
GTEST_FLAG_SET(print_time, true);
GTEST_FLAG_SET(random_seed, 0);
GTEST_FLAG_SET(repeat, 1);
GTEST_FLAG_SET(recreate_environments_when_repeating, true);
GTEST_FLAG_SET(shuffle, false);
GTEST_FLAG_SET(stack_trace_depth, kMaxStackTraceDepth);
GTEST_FLAG_SET(stream_result_to, "");
GTEST_FLAG_SET(throw_on_failure, false);
}
// Asserts that two narrow or wide string arrays are equal.
template <typename CharType>
static void AssertStringArrayEq(int size1, CharType** array1, int size2,
CharType** array2) {
ASSERT_EQ(size1, size2) << " Array sizes different.";
for (int i = 0; i != size1; i++) {
ASSERT_STREQ(array1[i], array2[i]) << " where i == " << i;
}
}
// Verifies that the flag values match the expected values.
static void CheckFlags(const Flags& expected) {
EXPECT_EQ(expected.also_run_disabled_tests,
GTEST_FLAG_GET(also_run_disabled_tests));
EXPECT_EQ(expected.break_on_failure, GTEST_FLAG_GET(break_on_failure));
EXPECT_EQ(expected.catch_exceptions, GTEST_FLAG_GET(catch_exceptions));
EXPECT_EQ(expected.death_test_use_fork,
GTEST_FLAG_GET(death_test_use_fork));
EXPECT_EQ(expected.fail_fast, GTEST_FLAG_GET(fail_fast));
EXPECT_STREQ(expected.filter, GTEST_FLAG_GET(filter).c_str());
EXPECT_EQ(expected.list_tests, GTEST_FLAG_GET(list_tests));
EXPECT_STREQ(expected.output, GTEST_FLAG_GET(output).c_str());
EXPECT_EQ(expected.brief, GTEST_FLAG_GET(brief));
EXPECT_EQ(expected.print_time, GTEST_FLAG_GET(print_time));
EXPECT_EQ(expected.random_seed, GTEST_FLAG_GET(random_seed));
EXPECT_EQ(expected.repeat, GTEST_FLAG_GET(repeat));
EXPECT_EQ(expected.recreate_environments_when_repeating,
GTEST_FLAG_GET(recreate_environments_when_repeating));
EXPECT_EQ(expected.shuffle, GTEST_FLAG_GET(shuffle));
EXPECT_EQ(expected.stack_trace_depth, GTEST_FLAG_GET(stack_trace_depth));
EXPECT_STREQ(expected.stream_result_to,
GTEST_FLAG_GET(stream_result_to).c_str());
EXPECT_EQ(expected.throw_on_failure, GTEST_FLAG_GET(throw_on_failure));
}
// Parses a command line (specified by argc1 and argv1), then
// verifies that the flag values are expected and that the
// recognized flags are removed from the command line.
template <typename CharType>
static void TestParsingFlags(int argc1, const CharType** argv1,
int argc2, const CharType** argv2,
const Flags& expected, bool should_print_help) {
const bool saved_help_flag = ::testing::internal::g_help_flag;
::testing::internal::g_help_flag = false;
# if GTEST_HAS_STREAM_REDIRECTION
CaptureStdout();
# endif
// Parses the command line.
internal::ParseGoogleTestFlagsOnly(&argc1, const_cast<CharType**>(argv1));
# if GTEST_HAS_STREAM_REDIRECTION
const std::string captured_stdout = GetCapturedStdout();
# endif
// Verifies the flag values.
CheckFlags(expected);
// Verifies that the recognized flags are removed from the command
// line.
AssertStringArrayEq(argc1 + 1, argv1, argc2 + 1, argv2);
// ParseGoogleTestFlagsOnly should neither set g_help_flag nor print the
// help message for the flags it recognizes.
EXPECT_EQ(should_print_help, ::testing::internal::g_help_flag);
# if GTEST_HAS_STREAM_REDIRECTION
const char* const expected_help_fragment =
"This program contains tests written using";
if (should_print_help) {
EXPECT_PRED_FORMAT2(IsSubstring, expected_help_fragment, captured_stdout);
} else {
EXPECT_PRED_FORMAT2(IsNotSubstring,
expected_help_fragment, captured_stdout);
}
# endif // GTEST_HAS_STREAM_REDIRECTION
::testing::internal::g_help_flag = saved_help_flag;
}
// This macro wraps TestParsingFlags s.t. the user doesn't need
// to specify the array sizes.
# define GTEST_TEST_PARSING_FLAGS_(argv1, argv2, expected, should_print_help) \
TestParsingFlags(sizeof(argv1)/sizeof(*argv1) - 1, argv1, \
sizeof(argv2)/sizeof(*argv2) - 1, argv2, \
expected, should_print_help)
};
// Tests parsing an empty command line.
TEST_F(ParseFlagsTest, Empty) {
const char* argv[] = {nullptr};
const char* argv2[] = {nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
}
// Tests parsing a command line that has no flag.
TEST_F(ParseFlagsTest, NoFlag) {
const char* argv[] = {"foo.exe", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
}
// Tests parsing --gtest_fail_fast.
TEST_F(ParseFlagsTest, FailFast) {
const char* argv[] = {"foo.exe", "--gtest_fail_fast", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::FailFast(true), false);
}
// Tests parsing a bad --gtest_filter flag.
TEST_F(ParseFlagsTest, FilterBad) {
const char* argv[] = {"foo.exe", "--gtest_filter", nullptr};
const char* argv2[] = {"foo.exe", "--gtest_filter", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), true);
}
// Tests parsing an empty --gtest_filter flag.
TEST_F(ParseFlagsTest, FilterEmpty) {
const char* argv[] = {"foo.exe", "--gtest_filter=", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), false);
}
// Tests parsing a non-empty --gtest_filter flag.
TEST_F(ParseFlagsTest, FilterNonEmpty) {
const char* argv[] = {"foo.exe", "--gtest_filter=abc", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false);
}
// Tests parsing --gtest_break_on_failure.
TEST_F(ParseFlagsTest, BreakOnFailureWithoutValue) {
const char* argv[] = {"foo.exe", "--gtest_break_on_failure", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);
}
// Tests parsing --gtest_break_on_failure=0.
TEST_F(ParseFlagsTest, BreakOnFailureFalse_0) {
const char* argv[] = {"foo.exe", "--gtest_break_on_failure=0", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
}
// Tests parsing --gtest_break_on_failure=f.
TEST_F(ParseFlagsTest, BreakOnFailureFalse_f) {
const char* argv[] = {"foo.exe", "--gtest_break_on_failure=f", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
}
// Tests parsing --gtest_break_on_failure=F.
TEST_F(ParseFlagsTest, BreakOnFailureFalse_F) {
const char* argv[] = {"foo.exe", "--gtest_break_on_failure=F", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);
}
// Tests parsing a --gtest_break_on_failure flag that has a "true"
// definition.
TEST_F(ParseFlagsTest, BreakOnFailureTrue) {
const char* argv[] = {"foo.exe", "--gtest_break_on_failure=1", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);
}
// Tests parsing --gtest_catch_exceptions.
TEST_F(ParseFlagsTest, CatchExceptions) {
const char* argv[] = {"foo.exe", "--gtest_catch_exceptions", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::CatchExceptions(true), false);
}
// Tests parsing --gtest_death_test_use_fork.
TEST_F(ParseFlagsTest, DeathTestUseFork) {
const char* argv[] = {"foo.exe", "--gtest_death_test_use_fork", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::DeathTestUseFork(true), false);
}
// Tests having the same flag twice with different values. The
// expected behavior is that the one coming last takes precedence.
TEST_F(ParseFlagsTest, DuplicatedFlags) {
const char* argv[] = {"foo.exe", "--gtest_filter=a", "--gtest_filter=b",
nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("b"), false);
}
// Tests having an unrecognized flag on the command line.
TEST_F(ParseFlagsTest, UnrecognizedFlag) {
const char* argv[] = {"foo.exe", "--gtest_break_on_failure",
"bar", // Unrecognized by Google Test.
"--gtest_filter=b", nullptr};
const char* argv2[] = {"foo.exe", "bar", nullptr};
Flags flags;
flags.break_on_failure = true;
flags.filter = "b";
GTEST_TEST_PARSING_FLAGS_(argv, argv2, flags, false);
}
// Tests having a --gtest_list_tests flag
TEST_F(ParseFlagsTest, ListTestsFlag) {
const char* argv[] = {"foo.exe", "--gtest_list_tests", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false);
}
// Tests having a --gtest_list_tests flag with a "true" value
TEST_F(ParseFlagsTest, ListTestsTrue) {
const char* argv[] = {"foo.exe", "--gtest_list_tests=1", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false);
}
// Tests having a --gtest_list_tests flag with a "false" value
TEST_F(ParseFlagsTest, ListTestsFalse) {
const char* argv[] = {"foo.exe", "--gtest_list_tests=0", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
}
// Tests parsing --gtest_list_tests=f.
TEST_F(ParseFlagsTest, ListTestsFalse_f) {
const char* argv[] = {"foo.exe", "--gtest_list_tests=f", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
}
// Tests parsing --gtest_list_tests=F.
TEST_F(ParseFlagsTest, ListTestsFalse_F) {
const char* argv[] = {"foo.exe", "--gtest_list_tests=F", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);
}
// Tests parsing --gtest_output (invalid).
TEST_F(ParseFlagsTest, OutputEmpty) {
const char* argv[] = {"foo.exe", "--gtest_output", nullptr};
const char* argv2[] = {"foo.exe", "--gtest_output", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), true);
}
// Tests parsing --gtest_output=xml
TEST_F(ParseFlagsTest, OutputXml) {
const char* argv[] = {"foo.exe", "--gtest_output=xml", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml"), false);
}
// Tests parsing --gtest_output=xml:file
TEST_F(ParseFlagsTest, OutputXmlFile) {
const char* argv[] = {"foo.exe", "--gtest_output=xml:file", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:file"), false);
}
// Tests parsing --gtest_output=xml:directory/path/
TEST_F(ParseFlagsTest, OutputXmlDirectory) {
const char* argv[] = {"foo.exe", "--gtest_output=xml:directory/path/",
nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2,
Flags::Output("xml:directory/path/"), false);
}
// Tests having a --gtest_brief flag
TEST_F(ParseFlagsTest, BriefFlag) {
const char* argv[] = {"foo.exe", "--gtest_brief", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Brief(true), false);
}
// Tests having a --gtest_brief flag with a "true" value
TEST_F(ParseFlagsTest, BriefFlagTrue) {
const char* argv[] = {"foo.exe", "--gtest_brief=1", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Brief(true), false);
}
// Tests having a --gtest_brief flag with a "false" value
TEST_F(ParseFlagsTest, BriefFlagFalse) {
const char* argv[] = {"foo.exe", "--gtest_brief=0", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Brief(false), false);
}
// Tests having a --gtest_print_time flag
TEST_F(ParseFlagsTest, PrintTimeFlag) {
const char* argv[] = {"foo.exe", "--gtest_print_time", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);
}
// Tests having a --gtest_print_time flag with a "true" value
TEST_F(ParseFlagsTest, PrintTimeTrue) {
const char* argv[] = {"foo.exe", "--gtest_print_time=1", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);
}
// Tests having a --gtest_print_time flag with a "false" value
TEST_F(ParseFlagsTest, PrintTimeFalse) {
const char* argv[] = {"foo.exe", "--gtest_print_time=0", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
}
// Tests parsing --gtest_print_time=f.
TEST_F(ParseFlagsTest, PrintTimeFalse_f) {
const char* argv[] = {"foo.exe", "--gtest_print_time=f", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
}
// Tests parsing --gtest_print_time=F.
TEST_F(ParseFlagsTest, PrintTimeFalse_F) {
const char* argv[] = {"foo.exe", "--gtest_print_time=F", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);
}
// Tests parsing --gtest_random_seed=number
TEST_F(ParseFlagsTest, RandomSeed) {
const char* argv[] = {"foo.exe", "--gtest_random_seed=1000", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::RandomSeed(1000), false);
}
// Tests parsing --gtest_repeat=number
TEST_F(ParseFlagsTest, Repeat) {
const char* argv[] = {"foo.exe", "--gtest_repeat=1000", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Repeat(1000), false);
}
// Tests parsing --gtest_recreate_environments_when_repeating
TEST_F(ParseFlagsTest, RecreateEnvironmentsWhenRepeating) {
const char* argv[] = {
"foo.exe",
"--gtest_recreate_environments_when_repeating=0",
nullptr,
};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(
argv, argv2, Flags::RecreateEnvironmentsWhenRepeating(false), false);
}
// Tests having a --gtest_also_run_disabled_tests flag
TEST_F(ParseFlagsTest, AlsoRunDisabledTestsFlag) {
const char* argv[] = {"foo.exe", "--gtest_also_run_disabled_tests", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(true),
false);
}
// Tests having a --gtest_also_run_disabled_tests flag with a "true" value
TEST_F(ParseFlagsTest, AlsoRunDisabledTestsTrue) {
const char* argv[] = {"foo.exe", "--gtest_also_run_disabled_tests=1",
nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(true),
false);
}
// Tests having a --gtest_also_run_disabled_tests flag with a "false" value
TEST_F(ParseFlagsTest, AlsoRunDisabledTestsFalse) {
const char* argv[] = {"foo.exe", "--gtest_also_run_disabled_tests=0",
nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(false),
false);
}
// Tests parsing --gtest_shuffle.
TEST_F(ParseFlagsTest, ShuffleWithoutValue) {
const char* argv[] = {"foo.exe", "--gtest_shuffle", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);
}
// Tests parsing --gtest_shuffle=0.
TEST_F(ParseFlagsTest, ShuffleFalse_0) {
const char* argv[] = {"foo.exe", "--gtest_shuffle=0", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(false), false);
}
// Tests parsing a --gtest_shuffle flag that has a "true" definition.
TEST_F(ParseFlagsTest, ShuffleTrue) {
const char* argv[] = {"foo.exe", "--gtest_shuffle=1", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);
}
// Tests parsing --gtest_stack_trace_depth=number.
TEST_F(ParseFlagsTest, StackTraceDepth) {
const char* argv[] = {"foo.exe", "--gtest_stack_trace_depth=5", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::StackTraceDepth(5), false);
}
TEST_F(ParseFlagsTest, StreamResultTo) {
const char* argv[] = {"foo.exe", "--gtest_stream_result_to=localhost:1234",
nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(
argv, argv2, Flags::StreamResultTo("localhost:1234"), false);
}
// Tests parsing --gtest_throw_on_failure.
TEST_F(ParseFlagsTest, ThrowOnFailureWithoutValue) {
const char* argv[] = {"foo.exe", "--gtest_throw_on_failure", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
}
// Tests parsing --gtest_throw_on_failure=0.
TEST_F(ParseFlagsTest, ThrowOnFailureFalse_0) {
const char* argv[] = {"foo.exe", "--gtest_throw_on_failure=0", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(false), false);
}
// Tests parsing a --gtest_throw_on_failure flag that has a "true"
// definition.
TEST_F(ParseFlagsTest, ThrowOnFailureTrue) {
const char* argv[] = {"foo.exe", "--gtest_throw_on_failure=1", nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);
}
# if GTEST_OS_WINDOWS
// Tests parsing wide strings.
TEST_F(ParseFlagsTest, WideStrings) {
const wchar_t* argv[] = {
L"foo.exe",
L"--gtest_filter=Foo*",
L"--gtest_list_tests=1",
L"--gtest_break_on_failure",
L"--non_gtest_flag",
NULL
};
const wchar_t* argv2[] = {
L"foo.exe",
L"--non_gtest_flag",
NULL
};
Flags expected_flags;
expected_flags.break_on_failure = true;
expected_flags.filter = "Foo*";
expected_flags.list_tests = true;
GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false);
}
# endif // GTEST_OS_WINDOWS
#if GTEST_USE_OWN_FLAGFILE_FLAG_
class FlagfileTest : public ParseFlagsTest {
public:
void SetUp() override {
ParseFlagsTest::SetUp();
testdata_path_.Set(internal::FilePath(
testing::TempDir() + internal::GetCurrentExecutableName().string() +
"_flagfile_test"));
testing::internal::posix::RmDir(testdata_path_.c_str());
EXPECT_TRUE(testdata_path_.CreateFolder());
}
void TearDown() override {
testing::internal::posix::RmDir(testdata_path_.c_str());
ParseFlagsTest::TearDown();
}
internal::FilePath CreateFlagfile(const char* contents) {
internal::FilePath file_path(internal::FilePath::GenerateUniqueFileName(
testdata_path_, internal::FilePath("unique"), "txt"));
FILE* f = testing::internal::posix::FOpen(file_path.c_str(), "w");
fprintf(f, "%s", contents);
fclose(f);
return file_path;
}
private:
internal::FilePath testdata_path_;
};
// Tests an empty flagfile.
TEST_F(FlagfileTest, Empty) {
internal::FilePath flagfile_path(CreateFlagfile(""));
std::string flagfile_flag =
std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
}
// Tests passing a non-empty --gtest_filter flag via --gtest_flagfile.
TEST_F(FlagfileTest, FilterNonEmpty) {
internal::FilePath flagfile_path(CreateFlagfile(
"--" GTEST_FLAG_PREFIX_ "filter=abc"));
std::string flagfile_flag =
std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr};
const char* argv2[] = {"foo.exe", nullptr};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false);
}
// Tests passing several flags via --gtest_flagfile.
TEST_F(FlagfileTest, SeveralFlags) {
internal::FilePath flagfile_path(CreateFlagfile(
"--" GTEST_FLAG_PREFIX_ "filter=abc\n"
"--" GTEST_FLAG_PREFIX_ "break_on_failure\n"
"--" GTEST_FLAG_PREFIX_ "list_tests"));
std::string flagfile_flag =
std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr};
const char* argv2[] = {"foo.exe", nullptr};
Flags expected_flags;
expected_flags.break_on_failure = true;
expected_flags.filter = "abc";
expected_flags.list_tests = true;
GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false);
}
#endif // GTEST_USE_OWN_FLAGFILE_FLAG_
// Tests current_test_info() in UnitTest.
class CurrentTestInfoTest : public Test {
protected:
// Tests that current_test_info() returns NULL before the first test in
// the test case is run.
static void SetUpTestSuite() {
// There should be no tests running at this point.
const TestInfo* test_info =
UnitTest::GetInstance()->current_test_info();
EXPECT_TRUE(test_info == nullptr)
<< "There should be no tests running at this point.";
}
// Tests that current_test_info() returns NULL after the last test in
// the test case has run.
static void TearDownTestSuite() {
const TestInfo* test_info =
UnitTest::GetInstance()->current_test_info();
EXPECT_TRUE(test_info == nullptr)
<< "There should be no tests running at this point.";
}
};
// Tests that current_test_info() returns TestInfo for currently running
// test by checking the expected test name against the actual one.
TEST_F(CurrentTestInfoTest, WorksForFirstTestInATestSuite) {
const TestInfo* test_info =
UnitTest::GetInstance()->current_test_info();
ASSERT_TRUE(nullptr != test_info)
<< "There is a test running so we should have a valid TestInfo.";
EXPECT_STREQ("CurrentTestInfoTest", test_info->test_suite_name())
<< "Expected the name of the currently running test suite.";
EXPECT_STREQ("WorksForFirstTestInATestSuite", test_info->name())
<< "Expected the name of the currently running test.";
}
// Tests that current_test_info() returns TestInfo for currently running
// test by checking the expected test name against the actual one. We
// use this test to see that the TestInfo object actually changed from
// the previous invocation.
TEST_F(CurrentTestInfoTest, WorksForSecondTestInATestSuite) {
const TestInfo* test_info =
UnitTest::GetInstance()->current_test_info();
ASSERT_TRUE(nullptr != test_info)
<< "There is a test running so we should have a valid TestInfo.";
EXPECT_STREQ("CurrentTestInfoTest", test_info->test_suite_name())
<< "Expected the name of the currently running test suite.";
EXPECT_STREQ("WorksForSecondTestInATestSuite", test_info->name())
<< "Expected the name of the currently running test.";
}
} // namespace testing
// These two lines test that we can define tests in a namespace that
// has the name "testing" and is nested in another namespace.
namespace my_namespace {
namespace testing {
// Makes sure that TEST knows to use ::testing::Test instead of
// ::my_namespace::testing::Test.
class Test {};
// Makes sure that an assertion knows to use ::testing::Message instead of
// ::my_namespace::testing::Message.
class Message {};
// Makes sure that an assertion knows to use
// ::testing::AssertionResult instead of
// ::my_namespace::testing::AssertionResult.
class AssertionResult {};
// Tests that an assertion that should succeed works as expected.
TEST(NestedTestingNamespaceTest, Success) {
EXPECT_EQ(1, 1) << "This shouldn't fail.";
}
// Tests that an assertion that should fail works as expected.
TEST(NestedTestingNamespaceTest, Failure) {
EXPECT_FATAL_FAILURE(FAIL() << "This failure is expected.",
"This failure is expected.");
}
} // namespace testing
} // namespace my_namespace
// Tests that one can call superclass SetUp and TearDown methods--
// that is, that they are not private.
// No tests are based on this fixture; the test "passes" if it compiles
// successfully.
class ProtectedFixtureMethodsTest : public Test {
protected:
void SetUp() override { Test::SetUp(); }
void TearDown() override { Test::TearDown(); }
};
// StreamingAssertionsTest tests the streaming versions of a representative
// sample of assertions.
TEST(StreamingAssertionsTest, Unconditional) {
SUCCEED() << "expected success";
EXPECT_NONFATAL_FAILURE(ADD_FAILURE() << "expected failure",
"expected failure");
EXPECT_FATAL_FAILURE(FAIL() << "expected failure",
"expected failure");
}
#ifdef __BORLANDC__
// Silences warnings: "Condition is always true", "Unreachable code"
# pragma option push -w-ccc -w-rch
#endif
TEST(StreamingAssertionsTest, Truth) {
EXPECT_TRUE(true) << "unexpected failure";
ASSERT_TRUE(true) << "unexpected failure";
EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "expected failure",
"expected failure");
EXPECT_FATAL_FAILURE(ASSERT_TRUE(false) << "expected failure",
"expected failure");
}
TEST(StreamingAssertionsTest, Truth2) {
EXPECT_FALSE(false) << "unexpected failure";
ASSERT_FALSE(false) << "unexpected failure";
EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "expected failure",
"expected failure");
EXPECT_FATAL_FAILURE(ASSERT_FALSE(true) << "expected failure",
"expected failure");
}
#ifdef __BORLANDC__
// Restores warnings after previous "#pragma option push" suppressed them
# pragma option pop
#endif
TEST(StreamingAssertionsTest, IntegerEquals) {
EXPECT_EQ(1, 1) << "unexpected failure";
ASSERT_EQ(1, 1) << "unexpected failure";
EXPECT_NONFATAL_FAILURE(EXPECT_EQ(1, 2) << "expected failure",
"expected failure");
EXPECT_FATAL_FAILURE(ASSERT_EQ(1, 2) << "expected failure",
"expected failure");
}
TEST(StreamingAssertionsTest, IntegerLessThan) {
EXPECT_LT(1, 2) << "unexpected failure";
ASSERT_LT(1, 2) << "unexpected failure";
EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1) << "expected failure",
"expected failure");
EXPECT_FATAL_FAILURE(ASSERT_LT(2, 1) << "expected failure",
"expected failure");
}
TEST(StreamingAssertionsTest, StringsEqual) {
EXPECT_STREQ("foo", "foo") << "unexpected failure";
ASSERT_STREQ("foo", "foo") << "unexpected failure";
EXPECT_NONFATAL_FAILURE(EXPECT_STREQ("foo", "bar") << "expected failure",
"expected failure");
EXPECT_FATAL_FAILURE(ASSERT_STREQ("foo", "bar") << "expected failure",
"expected failure");
}
TEST(StreamingAssertionsTest, StringsNotEqual) {
EXPECT_STRNE("foo", "bar") << "unexpected failure";
ASSERT_STRNE("foo", "bar") << "unexpected failure";
EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("foo", "foo") << "expected failure",
"expected failure");
EXPECT_FATAL_FAILURE(ASSERT_STRNE("foo", "foo") << "expected failure",
"expected failure");
}
TEST(StreamingAssertionsTest, StringsEqualIgnoringCase) {
EXPECT_STRCASEEQ("foo", "FOO") << "unexpected failure";
ASSERT_STRCASEEQ("foo", "FOO") << "unexpected failure";
EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ("foo", "bar") << "expected failure",
"expected failure");
EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("foo", "bar") << "expected failure",
"expected failure");
}
TEST(StreamingAssertionsTest, StringNotEqualIgnoringCase) {
EXPECT_STRCASENE("foo", "bar") << "unexpected failure";
ASSERT_STRCASENE("foo", "bar") << "unexpected failure";
EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("foo", "FOO") << "expected failure",
"expected failure");
EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("bar", "BAR") << "expected failure",
"expected failure");
}
TEST(StreamingAssertionsTest, FloatingPointEquals) {
EXPECT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
ASSERT_FLOAT_EQ(1.0, 1.0) << "unexpected failure";
EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(0.0, 1.0) << "expected failure",
"expected failure");
EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.0) << "expected failure",
"expected failure");
}
#if GTEST_HAS_EXCEPTIONS
TEST(StreamingAssertionsTest, Throw) {
EXPECT_THROW(ThrowAnInteger(), int) << "unexpected failure";
ASSERT_THROW(ThrowAnInteger(), int) << "unexpected failure";
EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool) <<
"expected failure", "expected failure");
EXPECT_FATAL_FAILURE(ASSERT_THROW(ThrowAnInteger(), bool) <<
"expected failure", "expected failure");
}
TEST(StreamingAssertionsTest, NoThrow) {
EXPECT_NO_THROW(ThrowNothing()) << "unexpected failure";
ASSERT_NO_THROW(ThrowNothing()) << "unexpected failure";
EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()) <<
"expected failure", "expected failure");
EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()) <<
"expected failure", "expected failure");
}
TEST(StreamingAssertionsTest, AnyThrow) {
EXPECT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
ASSERT_ANY_THROW(ThrowAnInteger()) << "unexpected failure";
EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(ThrowNothing()) <<
"expected failure", "expected failure");
EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()) <<
"expected failure", "expected failure");
}
#endif // GTEST_HAS_EXCEPTIONS
// Tests that Google Test correctly decides whether to use colors in the output.
TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsYes) {
GTEST_FLAG_SET(color, "yes");
SetEnv("TERM", "xterm"); // TERM supports colors.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
SetEnv("TERM", "dumb"); // TERM doesn't support colors.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
}
TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsAliasOfYes) {
SetEnv("TERM", "dumb"); // TERM doesn't support colors.
GTEST_FLAG_SET(color, "True");
EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
GTEST_FLAG_SET(color, "t");
EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
GTEST_FLAG_SET(color, "1");
EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY.
}
TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsNo) {
GTEST_FLAG_SET(color, "no");
SetEnv("TERM", "xterm"); // TERM supports colors.
EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
SetEnv("TERM", "dumb"); // TERM doesn't support colors.
EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
}
TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsInvalid) {
SetEnv("TERM", "xterm"); // TERM supports colors.
GTEST_FLAG_SET(color, "F");
EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
GTEST_FLAG_SET(color, "0");
EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
GTEST_FLAG_SET(color, "unknown");
EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
}
TEST(ColoredOutputTest, UsesColorsWhenStdoutIsTty) {
GTEST_FLAG_SET(color, "auto");
SetEnv("TERM", "xterm"); // TERM supports colors.
EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
}
TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) {
GTEST_FLAG_SET(color, "auto");
#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW
// On Windows, we ignore the TERM variable as it's usually not set.
SetEnv("TERM", "dumb");
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "");
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "xterm");
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
#else
// On non-Windows platforms, we rely on TERM to determine if the
// terminal supports colors.
SetEnv("TERM", "dumb"); // TERM doesn't support colors.
EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "emacs"); // TERM doesn't support colors.
EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "vt100"); // TERM doesn't support colors.
EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "xterm-mono"); // TERM doesn't support colors.
EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "xterm"); // TERM supports colors.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "xterm-color"); // TERM supports colors.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "xterm-256color"); // TERM supports colors.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "screen"); // TERM supports colors.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "screen-256color"); // TERM supports colors.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "tmux"); // TERM supports colors.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "tmux-256color"); // TERM supports colors.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "rxvt-unicode"); // TERM supports colors.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "rxvt-unicode-256color"); // TERM supports colors.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "linux"); // TERM supports colors.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
SetEnv("TERM", "cygwin"); // TERM supports colors.
EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY.
#endif // GTEST_OS_WINDOWS
}
// Verifies that StaticAssertTypeEq works in a namespace scope.
static bool dummy1 GTEST_ATTRIBUTE_UNUSED_ = StaticAssertTypeEq<bool, bool>();
static bool dummy2 GTEST_ATTRIBUTE_UNUSED_ =
StaticAssertTypeEq<const int, const int>();
// Verifies that StaticAssertTypeEq works in a class.
template <typename T>
class StaticAssertTypeEqTestHelper {
public:
StaticAssertTypeEqTestHelper() { StaticAssertTypeEq<bool, T>(); }
};
TEST(StaticAssertTypeEqTest, WorksInClass) {
StaticAssertTypeEqTestHelper<bool>();
}
// Verifies that StaticAssertTypeEq works inside a function.
typedef int IntAlias;
TEST(StaticAssertTypeEqTest, CompilesForEqualTypes) {
StaticAssertTypeEq<int, IntAlias>();
StaticAssertTypeEq<int*, IntAlias*>();
}
TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsNoFailure) {
EXPECT_FALSE(HasNonfatalFailure());
}
static void FailFatally() { FAIL(); }
TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsOnlyFatalFailure) {
FailFatally();
const bool has_nonfatal_failure = HasNonfatalFailure();
ClearCurrentTestPartResults();
EXPECT_FALSE(has_nonfatal_failure);
}
TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
ADD_FAILURE();
const bool has_nonfatal_failure = HasNonfatalFailure();
ClearCurrentTestPartResults();
EXPECT_TRUE(has_nonfatal_failure);
}
TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
FailFatally();
ADD_FAILURE();
const bool has_nonfatal_failure = HasNonfatalFailure();
ClearCurrentTestPartResults();
EXPECT_TRUE(has_nonfatal_failure);
}
// A wrapper for calling HasNonfatalFailure outside of a test body.
static bool HasNonfatalFailureHelper() {
return testing::Test::HasNonfatalFailure();
}
TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody) {
EXPECT_FALSE(HasNonfatalFailureHelper());
}
TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody2) {
ADD_FAILURE();
const bool has_nonfatal_failure = HasNonfatalFailureHelper();
ClearCurrentTestPartResults();
EXPECT_TRUE(has_nonfatal_failure);
}
TEST(HasFailureTest, ReturnsFalseWhenThereIsNoFailure) {
EXPECT_FALSE(HasFailure());
}
TEST(HasFailureTest, ReturnsTrueWhenThereIsFatalFailure) {
FailFatally();
const bool has_failure = HasFailure();
ClearCurrentTestPartResults();
EXPECT_TRUE(has_failure);
}
TEST(HasFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {
ADD_FAILURE();
const bool has_failure = HasFailure();
ClearCurrentTestPartResults();
EXPECT_TRUE(has_failure);
}
TEST(HasFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {
FailFatally();
ADD_FAILURE();
const bool has_failure = HasFailure();
ClearCurrentTestPartResults();
EXPECT_TRUE(has_failure);
}
// A wrapper for calling HasFailure outside of a test body.
static bool HasFailureHelper() { return testing::Test::HasFailure(); }
TEST(HasFailureTest, WorksOutsideOfTestBody) {
EXPECT_FALSE(HasFailureHelper());
}
TEST(HasFailureTest, WorksOutsideOfTestBody2) {
ADD_FAILURE();
const bool has_failure = HasFailureHelper();
ClearCurrentTestPartResults();
EXPECT_TRUE(has_failure);
}
class TestListener : public EmptyTestEventListener {
public:
TestListener() : on_start_counter_(nullptr), is_destroyed_(nullptr) {}
TestListener(int* on_start_counter, bool* is_destroyed)
: on_start_counter_(on_start_counter),
is_destroyed_(is_destroyed) {}
~TestListener() override {
if (is_destroyed_)
*is_destroyed_ = true;
}
protected:
void OnTestProgramStart(const UnitTest& /*unit_test*/) override {
if (on_start_counter_ != nullptr) (*on_start_counter_)++;
}
private:
int* on_start_counter_;
bool* is_destroyed_;
};
// Tests the constructor.
TEST(TestEventListenersTest, ConstructionWorks) {
TestEventListeners listeners;
EXPECT_TRUE(TestEventListenersAccessor::GetRepeater(&listeners) != nullptr);
EXPECT_TRUE(listeners.default_result_printer() == nullptr);
EXPECT_TRUE(listeners.default_xml_generator() == nullptr);
}
// Tests that the TestEventListeners destructor deletes all the listeners it
// owns.
TEST(TestEventListenersTest, DestructionWorks) {
bool default_result_printer_is_destroyed = false;
bool default_xml_printer_is_destroyed = false;
bool extra_listener_is_destroyed = false;
TestListener* default_result_printer =
new TestListener(nullptr, &default_result_printer_is_destroyed);
TestListener* default_xml_printer =
new TestListener(nullptr, &default_xml_printer_is_destroyed);
TestListener* extra_listener =
new TestListener(nullptr, &extra_listener_is_destroyed);
{
TestEventListeners listeners;
TestEventListenersAccessor::SetDefaultResultPrinter(&listeners,
default_result_printer);
TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners,
default_xml_printer);
listeners.Append(extra_listener);
}
EXPECT_TRUE(default_result_printer_is_destroyed);
EXPECT_TRUE(default_xml_printer_is_destroyed);
EXPECT_TRUE(extra_listener_is_destroyed);
}
// Tests that a listener Append'ed to a TestEventListeners list starts
// receiving events.
TEST(TestEventListenersTest, Append) {
int on_start_counter = 0;
bool is_destroyed = false;
TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
{
TestEventListeners listeners;
listeners.Append(listener);
TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
*UnitTest::GetInstance());
EXPECT_EQ(1, on_start_counter);
}
EXPECT_TRUE(is_destroyed);
}
// Tests that listeners receive events in the order they were appended to
// the list, except for *End requests, which must be received in the reverse
// order.
class SequenceTestingListener : public EmptyTestEventListener {
public:
SequenceTestingListener(std::vector<std::string>* vector, const char* id)
: vector_(vector), id_(id) {}
protected:
void OnTestProgramStart(const UnitTest& /*unit_test*/) override {
vector_->push_back(GetEventDescription("OnTestProgramStart"));
}
void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {
vector_->push_back(GetEventDescription("OnTestProgramEnd"));
}
void OnTestIterationStart(const UnitTest& /*unit_test*/,
int /*iteration*/) override {
vector_->push_back(GetEventDescription("OnTestIterationStart"));
}
void OnTestIterationEnd(const UnitTest& /*unit_test*/,
int /*iteration*/) override {
vector_->push_back(GetEventDescription("OnTestIterationEnd"));
}
private:
std::string GetEventDescription(const char* method) {
Message message;
message << id_ << "." << method;
return message.GetString();
}
std::vector<std::string>* vector_;
const char* const id_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(SequenceTestingListener);
};
TEST(EventListenerTest, AppendKeepsOrder) {
std::vector<std::string> vec;
TestEventListeners listeners;
listeners.Append(new SequenceTestingListener(&vec, "1st"));
listeners.Append(new SequenceTestingListener(&vec, "2nd"));
listeners.Append(new SequenceTestingListener(&vec, "3rd"));
TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
*UnitTest::GetInstance());
ASSERT_EQ(3U, vec.size());
EXPECT_STREQ("1st.OnTestProgramStart", vec[0].c_str());
EXPECT_STREQ("2nd.OnTestProgramStart", vec[1].c_str());
EXPECT_STREQ("3rd.OnTestProgramStart", vec[2].c_str());
vec.clear();
TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramEnd(
*UnitTest::GetInstance());
ASSERT_EQ(3U, vec.size());
EXPECT_STREQ("3rd.OnTestProgramEnd", vec[0].c_str());
EXPECT_STREQ("2nd.OnTestProgramEnd", vec[1].c_str());
EXPECT_STREQ("1st.OnTestProgramEnd", vec[2].c_str());
vec.clear();
TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationStart(
*UnitTest::GetInstance(), 0);
ASSERT_EQ(3U, vec.size());
EXPECT_STREQ("1st.OnTestIterationStart", vec[0].c_str());
EXPECT_STREQ("2nd.OnTestIterationStart", vec[1].c_str());
EXPECT_STREQ("3rd.OnTestIterationStart", vec[2].c_str());
vec.clear();
TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationEnd(
*UnitTest::GetInstance(), 0);
ASSERT_EQ(3U, vec.size());
EXPECT_STREQ("3rd.OnTestIterationEnd", vec[0].c_str());
EXPECT_STREQ("2nd.OnTestIterationEnd", vec[1].c_str());
EXPECT_STREQ("1st.OnTestIterationEnd", vec[2].c_str());
}
// Tests that a listener removed from a TestEventListeners list stops receiving
// events and is not deleted when the list is destroyed.
TEST(TestEventListenersTest, Release) {
int on_start_counter = 0;
bool is_destroyed = false;
// Although Append passes the ownership of this object to the list,
// the following calls release it, and we need to delete it before the
// test ends.
TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
{
TestEventListeners listeners;
listeners.Append(listener);
EXPECT_EQ(listener, listeners.Release(listener));
TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
*UnitTest::GetInstance());
EXPECT_TRUE(listeners.Release(listener) == nullptr);
}
EXPECT_EQ(0, on_start_counter);
EXPECT_FALSE(is_destroyed);
delete listener;
}
// Tests that no events are forwarded when event forwarding is disabled.
TEST(EventListenerTest, SuppressEventForwarding) {
int on_start_counter = 0;
TestListener* listener = new TestListener(&on_start_counter, nullptr);
TestEventListeners listeners;
listeners.Append(listener);
ASSERT_TRUE(TestEventListenersAccessor::EventForwardingEnabled(listeners));
TestEventListenersAccessor::SuppressEventForwarding(&listeners);
ASSERT_FALSE(TestEventListenersAccessor::EventForwardingEnabled(listeners));
TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
*UnitTest::GetInstance());
EXPECT_EQ(0, on_start_counter);
}
// Tests that events generated by Google Test are not forwarded in
// death test subprocesses.
TEST(EventListenerDeathTest, EventsNotForwardedInDeathTestSubprecesses) {
EXPECT_DEATH_IF_SUPPORTED({
GTEST_CHECK_(TestEventListenersAccessor::EventForwardingEnabled(
*GetUnitTestImpl()->listeners())) << "expected failure";},
"expected failure");
}
// Tests that a listener installed via SetDefaultResultPrinter() starts
// receiving events and is returned via default_result_printer() and that
// the previous default_result_printer is removed from the list and deleted.
TEST(EventListenerTest, default_result_printer) {
int on_start_counter = 0;
bool is_destroyed = false;
TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
TestEventListeners listeners;
TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);
EXPECT_EQ(listener, listeners.default_result_printer());
TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
*UnitTest::GetInstance());
EXPECT_EQ(1, on_start_counter);
// Replacing default_result_printer with something else should remove it
// from the list and destroy it.
TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, nullptr);
EXPECT_TRUE(listeners.default_result_printer() == nullptr);
EXPECT_TRUE(is_destroyed);
// After broadcasting an event the counter is still the same, indicating
// the listener is not in the list anymore.
TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
*UnitTest::GetInstance());
EXPECT_EQ(1, on_start_counter);
}
// Tests that the default_result_printer listener stops receiving events
// when removed via Release and that is not owned by the list anymore.
TEST(EventListenerTest, RemovingDefaultResultPrinterWorks) {
int on_start_counter = 0;
bool is_destroyed = false;
// Although Append passes the ownership of this object to the list,
// the following calls release it, and we need to delete it before the
// test ends.
TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
{
TestEventListeners listeners;
TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);
EXPECT_EQ(listener, listeners.Release(listener));
EXPECT_TRUE(listeners.default_result_printer() == nullptr);
EXPECT_FALSE(is_destroyed);
// Broadcasting events now should not affect default_result_printer.
TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
*UnitTest::GetInstance());
EXPECT_EQ(0, on_start_counter);
}
// Destroying the list should not affect the listener now, too.
EXPECT_FALSE(is_destroyed);
delete listener;
}
// Tests that a listener installed via SetDefaultXmlGenerator() starts
// receiving events and is returned via default_xml_generator() and that
// the previous default_xml_generator is removed from the list and deleted.
TEST(EventListenerTest, default_xml_generator) {
int on_start_counter = 0;
bool is_destroyed = false;
TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
TestEventListeners listeners;
TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);
EXPECT_EQ(listener, listeners.default_xml_generator());
TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
*UnitTest::GetInstance());
EXPECT_EQ(1, on_start_counter);
// Replacing default_xml_generator with something else should remove it
// from the list and destroy it.
TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, nullptr);
EXPECT_TRUE(listeners.default_xml_generator() == nullptr);
EXPECT_TRUE(is_destroyed);
// After broadcasting an event the counter is still the same, indicating
// the listener is not in the list anymore.
TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
*UnitTest::GetInstance());
EXPECT_EQ(1, on_start_counter);
}
// Tests that the default_xml_generator listener stops receiving events
// when removed via Release and that is not owned by the list anymore.
TEST(EventListenerTest, RemovingDefaultXmlGeneratorWorks) {
int on_start_counter = 0;
bool is_destroyed = false;
// Although Append passes the ownership of this object to the list,
// the following calls release it, and we need to delete it before the
// test ends.
TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);
{
TestEventListeners listeners;
TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);
EXPECT_EQ(listener, listeners.Release(listener));
EXPECT_TRUE(listeners.default_xml_generator() == nullptr);
EXPECT_FALSE(is_destroyed);
// Broadcasting events now should not affect default_xml_generator.
TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart(
*UnitTest::GetInstance());
EXPECT_EQ(0, on_start_counter);
}
// Destroying the list should not affect the listener now, too.
EXPECT_FALSE(is_destroyed);
delete listener;
}
// Sanity tests to ensure that the alternative, verbose spellings of
// some of the macros work. We don't test them thoroughly as that
// would be quite involved. Since their implementations are
// straightforward, and they are rarely used, we'll just rely on the
// users to tell us when they are broken.
GTEST_TEST(AlternativeNameTest, Works) { // GTEST_TEST is the same as TEST.
GTEST_SUCCEED() << "OK"; // GTEST_SUCCEED is the same as SUCCEED.
// GTEST_FAIL is the same as FAIL.
EXPECT_FATAL_FAILURE(GTEST_FAIL() << "An expected failure",
"An expected failure");
// GTEST_ASSERT_XY is the same as ASSERT_XY.
GTEST_ASSERT_EQ(0, 0);
EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(0, 1) << "An expected failure",
"An expected failure");
EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(1, 0) << "An expected failure",
"An expected failure");
GTEST_ASSERT_NE(0, 1);
GTEST_ASSERT_NE(1, 0);
EXPECT_FATAL_FAILURE(GTEST_ASSERT_NE(0, 0) << "An expected failure",
"An expected failure");
GTEST_ASSERT_LE(0, 0);
GTEST_ASSERT_LE(0, 1);
EXPECT_FATAL_FAILURE(GTEST_ASSERT_LE(1, 0) << "An expected failure",
"An expected failure");
GTEST_ASSERT_LT(0, 1);
EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(0, 0) << "An expected failure",
"An expected failure");
EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(1, 0) << "An expected failure",
"An expected failure");
GTEST_ASSERT_GE(0, 0);
GTEST_ASSERT_GE(1, 0);
EXPECT_FATAL_FAILURE(GTEST_ASSERT_GE(0, 1) << "An expected failure",
"An expected failure");
GTEST_ASSERT_GT(1, 0);
EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(0, 1) << "An expected failure",
"An expected failure");
EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(1, 1) << "An expected failure",
"An expected failure");
}
// Tests for internal utilities necessary for implementation of the universal
// printing.
class ConversionHelperBase {};
class ConversionHelperDerived : public ConversionHelperBase {};
struct HasDebugStringMethods {
std::string DebugString() const { return ""; }
std::string ShortDebugString() const { return ""; }
};
struct InheritsDebugStringMethods : public HasDebugStringMethods {};
struct WrongTypeDebugStringMethod {
std::string DebugString() const { return ""; }
int ShortDebugString() const { return 1; }
};
struct NotConstDebugStringMethod {
std::string DebugString() { return ""; }
std::string ShortDebugString() const { return ""; }
};
struct MissingDebugStringMethod {
std::string DebugString() { return ""; }
};
struct IncompleteType;
// Tests that HasDebugStringAndShortDebugString<T>::value is a compile-time
// constant.
TEST(HasDebugStringAndShortDebugStringTest, ValueIsCompileTimeConstant) {
GTEST_COMPILE_ASSERT_(
HasDebugStringAndShortDebugString<HasDebugStringMethods>::value,
const_true);
GTEST_COMPILE_ASSERT_(
HasDebugStringAndShortDebugString<InheritsDebugStringMethods>::value,
const_true);
GTEST_COMPILE_ASSERT_(HasDebugStringAndShortDebugString<
const InheritsDebugStringMethods>::value,
const_true);
GTEST_COMPILE_ASSERT_(
!HasDebugStringAndShortDebugString<WrongTypeDebugStringMethod>::value,
const_false);
GTEST_COMPILE_ASSERT_(
!HasDebugStringAndShortDebugString<NotConstDebugStringMethod>::value,
const_false);
GTEST_COMPILE_ASSERT_(
!HasDebugStringAndShortDebugString<MissingDebugStringMethod>::value,
const_false);
GTEST_COMPILE_ASSERT_(
!HasDebugStringAndShortDebugString<IncompleteType>::value, const_false);
GTEST_COMPILE_ASSERT_(!HasDebugStringAndShortDebugString<int>::value,
const_false);
}
// Tests that HasDebugStringAndShortDebugString<T>::value is true when T has
// needed methods.
TEST(HasDebugStringAndShortDebugStringTest,
ValueIsTrueWhenTypeHasDebugStringAndShortDebugString) {
EXPECT_TRUE(
HasDebugStringAndShortDebugString<InheritsDebugStringMethods>::value);
}
// Tests that HasDebugStringAndShortDebugString<T>::value is false when T
// doesn't have needed methods.
TEST(HasDebugStringAndShortDebugStringTest,
ValueIsFalseWhenTypeIsNotAProtocolMessage) {
EXPECT_FALSE(HasDebugStringAndShortDebugString<int>::value);
EXPECT_FALSE(
HasDebugStringAndShortDebugString<const ConversionHelperBase>::value);
}
// Tests GTEST_REMOVE_REFERENCE_AND_CONST_.
template <typename T1, typename T2>
void TestGTestRemoveReferenceAndConst() {
static_assert(std::is_same<T1, GTEST_REMOVE_REFERENCE_AND_CONST_(T2)>::value,
"GTEST_REMOVE_REFERENCE_AND_CONST_ failed.");
}
TEST(RemoveReferenceToConstTest, Works) {
TestGTestRemoveReferenceAndConst<int, int>();
TestGTestRemoveReferenceAndConst<double, double&>();
TestGTestRemoveReferenceAndConst<char, const char>();
TestGTestRemoveReferenceAndConst<char, const char&>();
TestGTestRemoveReferenceAndConst<const char*, const char*>();
}
// Tests GTEST_REFERENCE_TO_CONST_.
template <typename T1, typename T2>
void TestGTestReferenceToConst() {
static_assert(std::is_same<T1, GTEST_REFERENCE_TO_CONST_(T2)>::value,
"GTEST_REFERENCE_TO_CONST_ failed.");
}
TEST(GTestReferenceToConstTest, Works) {
TestGTestReferenceToConst<const char&, char>();
TestGTestReferenceToConst<const int&, const int>();
TestGTestReferenceToConst<const double&, double>();
TestGTestReferenceToConst<const std::string&, const std::string&>();
}
// Tests IsContainerTest.
class NonContainer {};
TEST(IsContainerTestTest, WorksForNonContainer) {
EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<int>(0)));
EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<char[5]>(0)));
EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<NonContainer>(0)));
}
TEST(IsContainerTestTest, WorksForContainer) {
EXPECT_EQ(sizeof(IsContainer),
sizeof(IsContainerTest<std::vector<bool> >(0)));
EXPECT_EQ(sizeof(IsContainer),
sizeof(IsContainerTest<std::map<int, double> >(0)));
}
struct ConstOnlyContainerWithPointerIterator {
using const_iterator = int*;
const_iterator begin() const;
const_iterator end() const;
};
struct ConstOnlyContainerWithClassIterator {
struct const_iterator {
const int& operator*() const;
const_iterator& operator++(/* pre-increment */);
};
const_iterator begin() const;
const_iterator end() const;
};
TEST(IsContainerTestTest, ConstOnlyContainer) {
EXPECT_EQ(sizeof(IsContainer),
sizeof(IsContainerTest<ConstOnlyContainerWithPointerIterator>(0)));
EXPECT_EQ(sizeof(IsContainer),
sizeof(IsContainerTest<ConstOnlyContainerWithClassIterator>(0)));
}
// Tests IsHashTable.
struct AHashTable {
typedef void hasher;
};
struct NotReallyAHashTable {
typedef void hasher;
typedef void reverse_iterator;
};
TEST(IsHashTable, Basic) {
EXPECT_TRUE(testing::internal::IsHashTable<AHashTable>::value);
EXPECT_FALSE(testing::internal::IsHashTable<NotReallyAHashTable>::value);
EXPECT_FALSE(testing::internal::IsHashTable<std::vector<int>>::value);
EXPECT_TRUE(testing::internal::IsHashTable<std::unordered_set<int>>::value);
}
// Tests ArrayEq().
TEST(ArrayEqTest, WorksForDegeneratedArrays) {
EXPECT_TRUE(ArrayEq(5, 5L));
EXPECT_FALSE(ArrayEq('a', 0));
}
TEST(ArrayEqTest, WorksForOneDimensionalArrays) {
// Note that a and b are distinct but compatible types.
const int a[] = { 0, 1 };
long b[] = { 0, 1 };
EXPECT_TRUE(ArrayEq(a, b));
EXPECT_TRUE(ArrayEq(a, 2, b));
b[0] = 2;
EXPECT_FALSE(ArrayEq(a, b));
EXPECT_FALSE(ArrayEq(a, 1, b));
}
TEST(ArrayEqTest, WorksForTwoDimensionalArrays) {
const char a[][3] = { "hi", "lo" };
const char b[][3] = { "hi", "lo" };
const char c[][3] = { "hi", "li" };
EXPECT_TRUE(ArrayEq(a, b));
EXPECT_TRUE(ArrayEq(a, 2, b));
EXPECT_FALSE(ArrayEq(a, c));
EXPECT_FALSE(ArrayEq(a, 2, c));
}
// Tests ArrayAwareFind().
TEST(ArrayAwareFindTest, WorksForOneDimensionalArray) {
const char a[] = "hello";
EXPECT_EQ(a + 4, ArrayAwareFind(a, a + 5, 'o'));
EXPECT_EQ(a + 5, ArrayAwareFind(a, a + 5, 'x'));
}
TEST(ArrayAwareFindTest, WorksForTwoDimensionalArray) {
int a[][2] = { { 0, 1 }, { 2, 3 }, { 4, 5 } };
const int b[2] = { 2, 3 };
EXPECT_EQ(a + 1, ArrayAwareFind(a, a + 3, b));
const int c[2] = { 6, 7 };
EXPECT_EQ(a + 3, ArrayAwareFind(a, a + 3, c));
}
// Tests CopyArray().
TEST(CopyArrayTest, WorksForDegeneratedArrays) {
int n = 0;
CopyArray('a', &n);
EXPECT_EQ('a', n);
}
TEST(CopyArrayTest, WorksForOneDimensionalArrays) {
const char a[3] = "hi";
int b[3];
#ifndef __BORLANDC__ // C++Builder cannot compile some array size deductions.
CopyArray(a, &b);
EXPECT_TRUE(ArrayEq(a, b));
#endif
int c[3];
CopyArray(a, 3, c);
EXPECT_TRUE(ArrayEq(a, c));
}
TEST(CopyArrayTest, WorksForTwoDimensionalArrays) {
const int a[2][3] = { { 0, 1, 2 }, { 3, 4, 5 } };
int b[2][3];
#ifndef __BORLANDC__ // C++Builder cannot compile some array size deductions.
CopyArray(a, &b);
EXPECT_TRUE(ArrayEq(a, b));
#endif
int c[2][3];
CopyArray(a, 2, c);
EXPECT_TRUE(ArrayEq(a, c));
}
// Tests NativeArray.
TEST(NativeArrayTest, ConstructorFromArrayWorks) {
const int a[3] = { 0, 1, 2 };
NativeArray<int> na(a, 3, RelationToSourceReference());
EXPECT_EQ(3U, na.size());
EXPECT_EQ(a, na.begin());
}
TEST(NativeArrayTest, CreatesAndDeletesCopyOfArrayWhenAskedTo) {
typedef int Array[2];
Array* a = new Array[1];
(*a)[0] = 0;
(*a)[1] = 1;
NativeArray<int> na(*a, 2, RelationToSourceCopy());
EXPECT_NE(*a, na.begin());
delete[] a;
EXPECT_EQ(0, na.begin()[0]);
EXPECT_EQ(1, na.begin()[1]);
// We rely on the heap checker to verify that na deletes the copy of
// array.
}
TEST(NativeArrayTest, TypeMembersAreCorrect) {
StaticAssertTypeEq<char, NativeArray<char>::value_type>();
StaticAssertTypeEq<int[2], NativeArray<int[2]>::value_type>();
StaticAssertTypeEq<const char*, NativeArray<char>::const_iterator>();
StaticAssertTypeEq<const bool(*)[2], NativeArray<bool[2]>::const_iterator>();
}
TEST(NativeArrayTest, MethodsWork) {
const int a[3] = { 0, 1, 2 };
NativeArray<int> na(a, 3, RelationToSourceCopy());
ASSERT_EQ(3U, na.size());
EXPECT_EQ(3, na.end() - na.begin());
NativeArray<int>::const_iterator it = na.begin();
EXPECT_EQ(0, *it);
++it;
EXPECT_EQ(1, *it);
it++;
EXPECT_EQ(2, *it);
++it;
EXPECT_EQ(na.end(), it);
EXPECT_TRUE(na == na);
NativeArray<int> na2(a, 3, RelationToSourceReference());
EXPECT_TRUE(na == na2);
const int b1[3] = { 0, 1, 1 };
const int b2[4] = { 0, 1, 2, 3 };
EXPECT_FALSE(na == NativeArray<int>(b1, 3, RelationToSourceReference()));
EXPECT_FALSE(na == NativeArray<int>(b2, 4, RelationToSourceCopy()));
}
TEST(NativeArrayTest, WorksForTwoDimensionalArray) {
const char a[2][3] = { "hi", "lo" };
NativeArray<char[3]> na(a, 2, RelationToSourceReference());
ASSERT_EQ(2U, na.size());
EXPECT_EQ(a, na.begin());
}
// IndexSequence
TEST(IndexSequence, MakeIndexSequence) {
using testing::internal::IndexSequence;
using testing::internal::MakeIndexSequence;
EXPECT_TRUE(
(std::is_same<IndexSequence<>, MakeIndexSequence<0>::type>::value));
EXPECT_TRUE(
(std::is_same<IndexSequence<0>, MakeIndexSequence<1>::type>::value));
EXPECT_TRUE(
(std::is_same<IndexSequence<0, 1>, MakeIndexSequence<2>::type>::value));
EXPECT_TRUE((
std::is_same<IndexSequence<0, 1, 2>, MakeIndexSequence<3>::type>::value));
EXPECT_TRUE(
(std::is_base_of<IndexSequence<0, 1, 2>, MakeIndexSequence<3>>::value));
}
// ElemFromList
TEST(ElemFromList, Basic) {
using testing::internal::ElemFromList;
EXPECT_TRUE(
(std::is_same<int, ElemFromList<0, int, double, char>::type>::value));
EXPECT_TRUE(
(std::is_same<double, ElemFromList<1, int, double, char>::type>::value));
EXPECT_TRUE(
(std::is_same<char, ElemFromList<2, int, double, char>::type>::value));
EXPECT_TRUE((
std::is_same<char, ElemFromList<7, int, int, int, int, int, int, int,
char, int, int, int, int>::type>::value));
}
// FlatTuple
TEST(FlatTuple, Basic) {
using testing::internal::FlatTuple;
FlatTuple<int, double, const char*> tuple = {};
EXPECT_EQ(0, tuple.Get<0>());
EXPECT_EQ(0.0, tuple.Get<1>());
EXPECT_EQ(nullptr, tuple.Get<2>());
tuple = FlatTuple<int, double, const char*>(
testing::internal::FlatTupleConstructTag{}, 7, 3.2, "Foo");
EXPECT_EQ(7, tuple.Get<0>());
EXPECT_EQ(3.2, tuple.Get<1>());
EXPECT_EQ(std::string("Foo"), tuple.Get<2>());
tuple.Get<1>() = 5.1;
EXPECT_EQ(5.1, tuple.Get<1>());
}
namespace {
std::string AddIntToString(int i, const std::string& s) {
return s + std::to_string(i);
}
} // namespace
TEST(FlatTuple, Apply) {
using testing::internal::FlatTuple;
FlatTuple<int, std::string> tuple{testing::internal::FlatTupleConstructTag{},
5, "Hello"};
// Lambda.
EXPECT_TRUE(tuple.Apply([](int i, const std::string& s) -> bool {
return i == static_cast<int>(s.size());
}));
// Function.
EXPECT_EQ(tuple.Apply(AddIntToString), "Hello5");
// Mutating operations.
tuple.Apply([](int& i, std::string& s) {
++i;
s += s;
});
EXPECT_EQ(tuple.Get<0>(), 6);
EXPECT_EQ(tuple.Get<1>(), "HelloHello");
}
struct ConstructionCounting {
ConstructionCounting() { ++default_ctor_calls; }
~ConstructionCounting() { ++dtor_calls; }
ConstructionCounting(const ConstructionCounting&) { ++copy_ctor_calls; }
ConstructionCounting(ConstructionCounting&&) noexcept { ++move_ctor_calls; }
ConstructionCounting& operator=(const ConstructionCounting&) {
++copy_assignment_calls;
return *this;
}
ConstructionCounting& operator=(ConstructionCounting&&) noexcept {
++move_assignment_calls;
return *this;
}
static void Reset() {
default_ctor_calls = 0;
dtor_calls = 0;
copy_ctor_calls = 0;
move_ctor_calls = 0;
copy_assignment_calls = 0;
move_assignment_calls = 0;
}
static int default_ctor_calls;
static int dtor_calls;
static int copy_ctor_calls;
static int move_ctor_calls;
static int copy_assignment_calls;
static int move_assignment_calls;
};
int ConstructionCounting::default_ctor_calls = 0;
int ConstructionCounting::dtor_calls = 0;
int ConstructionCounting::copy_ctor_calls = 0;
int ConstructionCounting::move_ctor_calls = 0;
int ConstructionCounting::copy_assignment_calls = 0;
int ConstructionCounting::move_assignment_calls = 0;
TEST(FlatTuple, ConstructorCalls) {
using testing::internal::FlatTuple;
// Default construction.
ConstructionCounting::Reset();
{ FlatTuple<ConstructionCounting> tuple; }
EXPECT_EQ(ConstructionCounting::default_ctor_calls, 1);
EXPECT_EQ(ConstructionCounting::dtor_calls, 1);
EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);
EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);
EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);
EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);
// Copy construction.
ConstructionCounting::Reset();
{
ConstructionCounting elem;
FlatTuple<ConstructionCounting> tuple{
testing::internal::FlatTupleConstructTag{}, elem};
}
EXPECT_EQ(ConstructionCounting::default_ctor_calls, 1);
EXPECT_EQ(ConstructionCounting::dtor_calls, 2);
EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 1);
EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);
EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);
EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);
// Move construction.
ConstructionCounting::Reset();
{
FlatTuple<ConstructionCounting> tuple{
testing::internal::FlatTupleConstructTag{}, ConstructionCounting{}};
}
EXPECT_EQ(ConstructionCounting::default_ctor_calls, 1);
EXPECT_EQ(ConstructionCounting::dtor_calls, 2);
EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);
EXPECT_EQ(ConstructionCounting::move_ctor_calls, 1);
EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);
EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);
// Copy assignment.
// TODO(ofats): it should be testing assignment operator of FlatTuple, not its
// elements
ConstructionCounting::Reset();
{
FlatTuple<ConstructionCounting> tuple;
ConstructionCounting elem;
tuple.Get<0>() = elem;
}
EXPECT_EQ(ConstructionCounting::default_ctor_calls, 2);
EXPECT_EQ(ConstructionCounting::dtor_calls, 2);
EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);
EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);
EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 1);
EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);
// Move assignment.
// TODO(ofats): it should be testing assignment operator of FlatTuple, not its
// elements
ConstructionCounting::Reset();
{
FlatTuple<ConstructionCounting> tuple;
tuple.Get<0>() = ConstructionCounting{};
}
EXPECT_EQ(ConstructionCounting::default_ctor_calls, 2);
EXPECT_EQ(ConstructionCounting::dtor_calls, 2);
EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);
EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);
EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);
EXPECT_EQ(ConstructionCounting::move_assignment_calls, 1);
ConstructionCounting::Reset();
}
TEST(FlatTuple, ManyTypes) {
using testing::internal::FlatTuple;
// Instantiate FlatTuple with 257 ints.
// Tests show that we can do it with thousands of elements, but very long
// compile times makes it unusuitable for this test.
#define GTEST_FLAT_TUPLE_INT8 int, int, int, int, int, int, int, int,
#define GTEST_FLAT_TUPLE_INT16 GTEST_FLAT_TUPLE_INT8 GTEST_FLAT_TUPLE_INT8
#define GTEST_FLAT_TUPLE_INT32 GTEST_FLAT_TUPLE_INT16 GTEST_FLAT_TUPLE_INT16
#define GTEST_FLAT_TUPLE_INT64 GTEST_FLAT_TUPLE_INT32 GTEST_FLAT_TUPLE_INT32
#define GTEST_FLAT_TUPLE_INT128 GTEST_FLAT_TUPLE_INT64 GTEST_FLAT_TUPLE_INT64
#define GTEST_FLAT_TUPLE_INT256 GTEST_FLAT_TUPLE_INT128 GTEST_FLAT_TUPLE_INT128
// Let's make sure that we can have a very long list of types without blowing
// up the template instantiation depth.
FlatTuple<GTEST_FLAT_TUPLE_INT256 int> tuple;
tuple.Get<0>() = 7;
tuple.Get<99>() = 17;
tuple.Get<256>() = 1000;
EXPECT_EQ(7, tuple.Get<0>());
EXPECT_EQ(17, tuple.Get<99>());
EXPECT_EQ(1000, tuple.Get<256>());
}
// Tests SkipPrefix().
TEST(SkipPrefixTest, SkipsWhenPrefixMatches) {
const char* const str = "hello";
const char* p = str;
EXPECT_TRUE(SkipPrefix("", &p));
EXPECT_EQ(str, p);
p = str;
EXPECT_TRUE(SkipPrefix("hell", &p));
EXPECT_EQ(str + 4, p);
}
TEST(SkipPrefixTest, DoesNotSkipWhenPrefixDoesNotMatch) {
const char* const str = "world";
const char* p = str;
EXPECT_FALSE(SkipPrefix("W", &p));
EXPECT_EQ(str, p);
p = str;
EXPECT_FALSE(SkipPrefix("world!", &p));
EXPECT_EQ(str, p);
}
// Tests ad_hoc_test_result().
TEST(AdHocTestResultTest, AdHocTestResultForUnitTestDoesNotShowFailure) {
const testing::TestResult& test_result =
testing::UnitTest::GetInstance()->ad_hoc_test_result();
EXPECT_FALSE(test_result.Failed());
}
class DynamicUnitTestFixture : public testing::Test {};
class DynamicTest : public DynamicUnitTestFixture {
void TestBody() override { EXPECT_TRUE(true); }
};
auto* dynamic_test = testing::RegisterTest(
"DynamicUnitTestFixture", "DynamicTest", "TYPE", "VALUE", __FILE__,
__LINE__, []() -> DynamicUnitTestFixture* { return new DynamicTest; });
TEST(RegisterTest, WasRegistered) {
auto* unittest = testing::UnitTest::GetInstance();
for (int i = 0; i < unittest->total_test_suite_count(); ++i) {
auto* tests = unittest->GetTestSuite(i);
if (tests->name() != std::string("DynamicUnitTestFixture")) continue;
for (int j = 0; j < tests->total_test_count(); ++j) {
if (tests->GetTestInfo(j)->name() != std::string("DynamicTest")) continue;
// Found it.
EXPECT_STREQ(tests->GetTestInfo(j)->value_param(), "VALUE");
EXPECT_STREQ(tests->GetTestInfo(j)->type_param(), "TYPE");
return;
}
}
FAIL() << "Didn't find the test!";
}
|
alemariusnexus/electronicsdb
|
src/googletest/googletest/test/gtest_unittest.cc
|
C++
|
gpl-3.0
| 260,178
|
package org.jeecgframework.web.demo.service.impl.test;
import org.jeecgframework.core.util.ContextHolderUtils;
import org.jeecgframework.core.util.FileUtils;
import org.jeecgframework.core.util.ResourceUtil;
import java.util.List;
import java.util.Map;
import org.jeecgframework.web.demo.entity.test.TFinanceEntity;
import org.jeecgframework.web.demo.entity.test.TFinanceFilesEntity;
import org.jeecgframework.web.demo.service.test.TFinanceServiceI;
import org.jeecgframework.web.system.pojo.base.TSAttachment;
import org.jeecgframework.core.common.service.impl.CommonServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service("tFinanceService")
@Transactional
public class TFinanceServiceImpl extends CommonServiceImpl implements TFinanceServiceI {
/**
* 附件删除
*/
public void deleteFile(TFinanceFilesEntity file) {
//[1].删除附件
String sql = "select * from t_s_attachment where id = ?";
Map<String, Object> attachmentMap = commonDao.findOneForJdbc(sql, file.getId());
//附件相对路径
String realpath = (String) attachmentMap.get("realpath");
String fileName = FileUtils.getFilePrefix2(realpath);
//获取部署项目绝对地址
String realPath = ContextHolderUtils.getSession().getServletContext().getRealPath("/");
FileUtils.delete(realPath+realpath);
FileUtils.delete(realPath+fileName+".pdf");
FileUtils.delete(realPath+fileName+".swf");
//[2].删除数据
commonDao.delete(file);
}
/**
* 资金管理删除
*/
public void deleteFinance(TFinanceEntity finance) {
//[1].上传附件删除
String attach_sql = "select * from t_s_attachment where id in (select id from t_finance_files where financeId = ?)";
List<Map<String, Object>> attachmentList = commonDao.findForJdbc(attach_sql, finance.getId());
for(Map<String, Object> map:attachmentList){
//附件相对路径
String realpath = (String) map.get("realpath");
String fileName = FileUtils.getFilePrefix2(realpath);
//获取部署项目绝对地址
String realPath = ContextHolderUtils.getSession().getServletContext().getRealPath("/");
FileUtils.delete(realPath+realpath);
FileUtils.delete(realPath+fileName+".pdf");
FileUtils.delete(realPath+fileName+".swf");
}
//[2].删除资金管理
commonDao.delete(finance);
}
}
|
shamoxiaoniqiu2008/jeecg-framework
|
src/main/java/org/jeecgframework/web/demo/service/impl/test/TFinanceServiceImpl.java
|
Java
|
gpl-3.0
| 2,430
|
<?php
/*
* TreeChecker: Error recognition for genealogical trees
*
* Copyright (C) 2014 Digital Humanities Lab, Faculty of Humanities, Universiteit Utrecht
* Corry Gellatly <corry.gellatly@gmail.com>
* Martijn van der Klis <M.H.vanderKlis@uu.nl>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
abstract class ParseController extends BaseController
{
public function __construct()
{
parent::__construct();
// Prevent access to controller methods without login
$this->beforeFilter('auth');
}
/**
* Parses a Gedcom and creates parse errors when necessary.
* @param integer $gedcom_id
* @return void (if finished)
*/
public function getParse($gedcom_id)
{
// Get the GEDCOM
$gedcom = Gedcom::findOrFail($gedcom_id);
if ($this->allowedAccess($gedcom->user_id))
{
Session::put('progress', 1);
Session::save();
// Delete the related individuals, families and errors
$gedcom->individuals()->delete();
$gedcom->families()->delete();
$gedcom->geocodes()->delete();
$gedcom->errors()->delete();
$gedcom->notes()->delete();
Session::put('progress', 2);
Session::save();
// Retrieve the file folder
$abs_storage_dir = Config::get('app.upload_dir') . $gedcom->path;
chdir($abs_storage_dir);
// Do before actions
$this->doBeforeParse($gedcom_id);
$filecount = 0;
$files = glob("*");
if ($files)
{
$filecount = count($files);
}
// Loop through the chunked files and parse/import them
for ($i = 1; file_exists($i); ++$i)
{
$this->importRecords($i, $gedcom_id);
Session::put('progress', min(floor(($i / $filecount) * 100), 99));
Session::save();
}
// Do after actions
$this->doAfterParse($gedcom_id);
// Set the file as parsed, but not checked for errors
$gedcom->parsed = true;
$gedcom->error_checked = false;
$gedcom->save();
Session::put('progress', 100);
Session::save();
return;
}
else
{
return Response::make('Unauthorized', 401);
}
}
abstract protected function doBeforeParse($gedcom_id);
abstract protected function doAfterParse($gedcom_id);
/**
* Returns the progress of the current parse session.
* @return Response the progress in JSON format
*/
public function getProgress()
{
$progress = Session::has('progress') ? Session::get('progress') : 0;
return Response::json(array($progress));
}
/**
* Imports all records of a file
* @param string $file
* @param integer $gedcom_id
*/
protected function importRecords($file, $gedcom_id)
{
// Retrieve the contents of the file
$gedcom = file_get_contents($file);
// Allow 3 minutes of execution time
set_time_limit(180);
// Query log is save in memory, so we need to disable it for large file parsing
DB::connection()->disableQueryLog();
// Start the transaction
DB::beginTransaction();
// Start the import
$this->doImport($gedcom_id, $gedcom);
// End the transaction
DB::commit();
}
/**
* Starts the file-specific (GEDCOM, JSON) import.
* @param integer $gedcom_id
* @param string $gedcom
*/
abstract protected function doImport($gedcom_id, $gedcom);
/**
* Looks up a GedcomIndividual by key.
* Creates a GedcomError if not found.
* @param integer $gedcom_id
* @param string $gedcom_key
* @return GedcomIndividual
*/
protected function retrieveIndividual($gedcom_id, $gedcom_key)
{
if (!$gedcom_key)
{
return NULL;
}
$ind = GedcomIndividual::GedcomKey($gedcom_id, $gedcom_key)->first();
if (!$ind)
{
$error = new GedcomError();
$error->gedcom_id = $gedcom_id;
$error->stage = 'parsing';
$error->type_broad = 'missing';
$error->type_specific = 'individual missing';
$error->eval_broad = 'error';
$error->eval_specific = '';
$error->message = sprintf('No individual found for %s', $gedcom_key);
$error->save();
}
return $ind;
}
}
|
cgeltly/treechecker
|
app/controllers/ParseController.php
|
PHP
|
gpl-3.0
| 5,263
|
/************************************************************************************************************************
**
** Copyright 2015-2021 Daniel Nikpayuk, Inuit Nunangat, The Inuit Nation
**
** This file is part of nik.
**
** nik is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License
** as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
**
** nik 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 nik. If not, see
** <http://www.gnu.org/licenses/>.
**
************************************************************************************************************************/
struct inductor
{
#include nik_symbolic_typedef(patronum, natural, kernel, builtin, inductor)
template<typename Type, typename Exp>
using pattern_match_typename_stem = typename dependent_memoization<Type>::template pattern_match_<Exp>;
};
|
Daniel-Nikpayuk/nik
|
space-symbolic/patronum-natural-kernel-typename_stem/inductor-semiotic.hpp
|
C++
|
gpl-3.0
| 1,208
|
<?php
$url = $_GET['sayfa'] ? $_GET['sayfa'] : 'anasayfa';
$dosyaYol = "moduller/".$url.".php";
global $tema;
require_once $tema->temaAl();
if(file_exists($dosyaYol))
{
require_once $dosyaYol;
$icerik = new $url;
}
else
{
if($ayarlar->404 == true)
{
require_once('errors/404.htm')
}
else
{
require_once('moduller/anasayfa.php');
$icerik = new Anasayfa;
}
}
$tema->temaAl()."index.php";
?>
|
MMOTutkunlari/metin2-panel
|
index.php
|
PHP
|
gpl-3.0
| 420
|
// Decompiled with JetBrains decompiler
// Type: System.Base64FormattingOptions
// Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// MVID: 255ABCDF-D9D6-4E3D-BAD4-F74D4CE3D7A8
// Assembly location: C:\Windows\Microsoft.NET\Framework\v4.0.30319\mscorlib.dll
namespace System
{
/// <summary>
/// Specifies whether relevant <see cref="Overload:System.Convert.ToBase64CharArray"/> and <see cref="Overload:System.Convert.ToBase64String"/> methods insert line breaks in their output.
/// </summary>
/// <filterpriority>1</filterpriority>
[Flags]
public enum Base64FormattingOptions
{
None = 0,
InsertLineBreaks = 1,
}
}
|
mater06/LEGOChimaOnlineReloaded
|
LoCO Client Files/Decompressed Client/Extracted DLL/mscorlib/System/Base64FormattingOptions.cs
|
C#
|
gpl-3.0
| 681
|
#ifndef _C14_re670_
#define _C14_re670_
#ifdef __cplusplus
extern "C" {
#endif
extern EIF_INTEGER_32 F298_1998(EIF_REFERENCE);
extern void EIF_Minit670(void);
extern char *(*R1751[])();
#ifdef __cplusplus
}
#endif
#endif
|
evilksi/jeux-oriente-objet-2
|
Test/EIFGENs/coinplumber/F_code/C14/re670.h
|
C
|
gpl-3.0
| 226
|
{% extends "base.html"%}
{% block content %}
{% include "fa-decoration.html" with title=title|default:"Turnover by Service Family" icon="fa-calculator" block="main" %}
{% include "servicefamily_report_table.html" %}
{% endblock %}
|
gdebure/cream
|
services/templates/servicefamilies_report.html
|
HTML
|
gpl-3.0
| 232
|
/*
* Bhyve host interface - VM allocation, mapping
* guest memory, populating guest register state etc
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/errno.h>
#include <x86/segments.h>
#include <x86/specialreg.h>
#include <machine/vmm.h>
#include <vmmapi.h>
#include <grub/err.h>
#include <grub/dl.h>
#include <grub/misc.h>
#include <grub/i386/memory.h>
#include <grub/emu/bhyve.h>
#define GB (1024*1024*1024ULL)
#define DESC_UNUSABLE 0x00010000
#define GUEST_NULL_SEL 0
#define GUEST_CODE_SEL 2
#define GUEST_DATA_SEL 3
#define GUEST_TSS_SEL 4
#define GUEST_GDTR_LIMIT (5 * 8 - 1)
static uint16_t bhyve_gdt[] = {
0x0000, 0x0000, 0x0000, 0x0000, /* Null */
0x0000, 0x0000, 0x0000, 0x0000, /* Null #2 */
0xffff, 0x0000, 0x9a00, 0x00cf, /* code */
0xffff, 0x0000, 0x9200, 0x00cf, /* data */
0x0000, 0x0000, 0x8900, 0x0080 /* tss */
};
static struct vmctx *bhyve_ctx;
static int bhyve_cinsert = 1;
static int bhyve_vgainsert = 1;
#define BHYVE_MAXSEGS 5
struct {
grub_uint64_t lomem, himem;
void *lomem_ptr, *himem_ptr;
} bhyve_g2h;
static struct grub_mmap_region bhyve_mm[BHYVE_MAXSEGS];
static struct grub_bhyve_info bhyve_info;
int
grub_emu_bhyve_init(const char *name, grub_uint64_t memsz)
{
int err;
int val;
grub_uint64_t lomemsz;
#ifdef VMMAPI_VERSION
int need_reinit = 0;
#endif
err = vm_create (name);
if (err != 0)
{
if (errno != EEXIST)
{
fprintf (stderr, "Could not create VM %s\n", name);
return GRUB_ERR_ACCESS_DENIED;
}
#ifdef VMMAPI_VERSION
need_reinit = 1;
#endif
}
bhyve_ctx = vm_open (name);
if (bhyve_ctx == NULL)
{
fprintf (stderr, "Could not open VM %s\n", name);
return GRUB_ERR_BUG;
}
#ifdef VMMAPI_VERSION
if (need_reinit)
{
err = vm_reinit (bhyve_ctx);
if (err != 0)
{
fprintf (stderr, "Could not reinit VM %s\n", name);
return GRUB_ERR_BUG;
}
}
#endif
val = 0;
err = vm_get_capability (bhyve_ctx, 0, VM_CAP_UNRESTRICTED_GUEST, &val);
if (err != 0)
{
fprintf (stderr, "VM unrestricted guest capability required\n");
return GRUB_ERR_BAD_DEVICE;
}
err = vm_set_capability (bhyve_ctx, 0, VM_CAP_UNRESTRICTED_GUEST, 1);
if (err != 0)
{
fprintf (stderr, "Could not enable unrestricted guest for VM\n");
return GRUB_ERR_BUG;
}
err = vm_setup_memory (bhyve_ctx, memsz, VM_MMAP_ALL);
if (err) {
fprintf (stderr, "Could not setup memory for VM\n");
return GRUB_ERR_OUT_OF_MEMORY;
}
lomemsz = vm_get_lowmem_limit(bhyve_ctx);
/*
* Extract the virtual address of the mapped guest memory.
*/
if (memsz >= lomemsz) {
bhyve_g2h.lomem = lomemsz;
bhyve_g2h.himem = memsz - lomemsz;
bhyve_g2h.himem_ptr = vm_map_gpa(bhyve_ctx, 4*GB, bhyve_g2h.himem);
} else {
bhyve_g2h.lomem = memsz;
bhyve_g2h.himem = 0;
}
bhyve_g2h.lomem_ptr = vm_map_gpa(bhyve_ctx, 0, bhyve_g2h.lomem);
/*
* bhyve is going to return the following memory segments
*
* 0 - 640K - usable
* 640K- 1MB - vga hole, BIOS, not usable.
* 1MB - lomem - usable
* lomem - 4G - not usable
* 4G - himem - usable [optional if himem != 0]
*/
bhyve_info.nsegs = 2;
bhyve_info.segs = bhyve_mm;
bhyve_mm[0].start = 0x0;
bhyve_mm[0].end = 640*1024 - 1; /* 640K */
bhyve_mm[0].type = GRUB_MEMORY_AVAILABLE;
bhyve_mm[1].start = 1024*1024;
bhyve_mm[1].end = (memsz > lomemsz) ? lomemsz : memsz;
bhyve_mm[1].type = GRUB_MEMORY_AVAILABLE;
if (memsz > lomemsz) {
bhyve_info.nsegs++;
bhyve_mm[2].start = 4*GB;
bhyve_mm[2].end = (memsz - lomemsz) + bhyve_mm[2].start;
bhyve_mm[2].type = GRUB_MEMORY_AVAILABLE;
}
/* The boot-code size is just the GDT that needs to be copied */
bhyve_info.bootsz = sizeof(bhyve_gdt);
return 0;
}
/*
* 32-bit boot state initialization. The Linux sequence appears to
* work fine for Net/OpenBSD kernel entry. Use the GP register state
* passed in, and copy other info to the allocated phys address, bt.
*/
void
grub_emu_bhyve_boot32(grub_uint32_t bt, struct grub_relocator32_state rs)
{
uint64_t cr0, cr4, rflags, desc_base;
uint32_t desc_access, desc_limit;
uint16_t gsel;
/*
* "At entry, the CPU must be in 32-bit protected mode with paging
* disabled;"
*/
cr0 = CR0_PE;
assert(vm_set_register(bhyve_ctx, 0, VM_REG_GUEST_CR0, cr0) == 0);
cr4 = 0;
assert(vm_set_register(bhyve_ctx, 0, VM_REG_GUEST_CR4, cr4) == 0);
/*
* Reserved bit 1 set to 1. "interrupt must be disabled"
*/
rflags = 0x2;
assert(vm_set_register(bhyve_ctx, 0, VM_REG_GUEST_RFLAGS, rflags) == 0);
/*
* "__BOOT_CS(0x10) and __BOOT_DS(0x18); both descriptors must be 4G
* flat segment; __BOOS_CS must have execute/read permission, and
* __BOOT_DS must have read/write permission; CS must be __BOOT_CS"
*/
desc_base = 0;
desc_limit = 0xffffffff;
desc_access = 0x0000C09B;
assert(vm_set_desc(bhyve_ctx, 0, VM_REG_GUEST_CS,
desc_base, desc_limit, desc_access) == 0);
desc_access = 0x0000C093;
assert(vm_set_desc(bhyve_ctx, 0, VM_REG_GUEST_DS,
desc_base, desc_limit, desc_access) == 0);
/*
* ... "and DS, ES, SS must be __BOOT_DS;"
*/
assert(vm_set_desc(bhyve_ctx, 0, VM_REG_GUEST_ES,
desc_base, desc_limit, desc_access) == 0);
assert(vm_set_desc(bhyve_ctx, 0, VM_REG_GUEST_FS,
desc_base, desc_limit, desc_access) == 0);
assert(vm_set_desc(bhyve_ctx, 0, VM_REG_GUEST_GS,
desc_base, desc_limit, desc_access) == 0);
assert(vm_set_desc(bhyve_ctx, 0, VM_REG_GUEST_SS,
desc_base, desc_limit, desc_access) == 0);
/*
* XXX TR is pointing to null selector even though we set the
* TSS segment to be usable with a base address and limit of 0.
* Has to be 8b or vmenter will fail
*/
desc_access = 0x0000008b;
assert(vm_set_desc(bhyve_ctx, 0, VM_REG_GUEST_TR, 0x1000, 0x67,
desc_access) == 0);
assert(vm_set_desc(bhyve_ctx, 0, VM_REG_GUEST_LDTR, 0, 0xffff,
DESC_UNUSABLE | 0x82) == 0);
gsel = GSEL(GUEST_CODE_SEL, SEL_KPL);
assert(vm_set_register(bhyve_ctx, 0, VM_REG_GUEST_CS, gsel) == 0);
gsel = GSEL(GUEST_DATA_SEL, SEL_KPL);
assert(vm_set_register(bhyve_ctx, 0, VM_REG_GUEST_DS, gsel) == 0);
assert(vm_set_register(bhyve_ctx, 0, VM_REG_GUEST_ES, gsel) == 0);
assert(vm_set_register(bhyve_ctx, 0, VM_REG_GUEST_FS, gsel) == 0);
assert(vm_set_register(bhyve_ctx, 0, VM_REG_GUEST_GS, gsel) == 0);
assert(vm_set_register(bhyve_ctx, 0, VM_REG_GUEST_SS, gsel) == 0);
/* XXX TR is pointing to selector 1 */
gsel = GSEL(GUEST_TSS_SEL, SEL_KPL);
assert(vm_set_register(bhyve_ctx, 0, VM_REG_GUEST_TR, gsel) == 0);
/* LDTR is pointing to the null selector */
assert(vm_set_register(bhyve_ctx, 0, VM_REG_GUEST_LDTR, 0) == 0);
/*
* "In 32-bit boot protocol, the kernel is started by jumping to the
* 32-bit kernel entry point, which is the start address of loaded
* 32/64-bit kernel."
*/
assert(vm_set_register(bhyve_ctx, 0, VM_REG_GUEST_RIP, rs.eip) == 0);
/*
* Set up the GDT by copying it into low memory, and then pointing
* the guest's GDT descriptor at it
*/
memcpy(grub_emu_bhyve_virt(bt), bhyve_gdt, sizeof(bhyve_gdt));
desc_base = bt;
desc_limit = GUEST_GDTR_LIMIT;
assert(vm_set_desc(bhyve_ctx, 0, VM_REG_GUEST_GDTR, desc_base,
desc_limit, 0) == 0);;
/*
* Set the stack to be just below the params real-mode area
*/
assert(vm_set_register(bhyve_ctx, 0, VM_REG_GUEST_RSP, rs.esp) == 0);
/*
* "%esi must hold the base address of the struct boot_params"
*/
assert(vm_set_register(bhyve_ctx, 0, VM_REG_GUEST_RSI, rs.esi) == 0);
/*
* "%ebp, %edi and %ebx must be zero."
* Assume that grub set these up correctly - might be different for
* *BSD. While at it, init the remaining passed-in register state.
*/
assert(vm_set_register(bhyve_ctx, 0, VM_REG_GUEST_RBP, rs.ebp) == 0);
assert(vm_set_register(bhyve_ctx, 0, VM_REG_GUEST_RDI, rs.edi) == 0);
assert(vm_set_register(bhyve_ctx, 0, VM_REG_GUEST_RBX, rs.ebx) == 0);
assert(vm_set_register(bhyve_ctx, 0, VM_REG_GUEST_RAX, rs.eax) == 0);
assert(vm_set_register(bhyve_ctx, 0, VM_REG_GUEST_RCX, rs.ecx) == 0);
assert(vm_set_register(bhyve_ctx, 0, VM_REG_GUEST_RDX, rs.edx) == 0);
/*
* XXX debug: turn on tracing
*/
#if 0
assert(vm_set_capability(bhyve_ctx, 0, VM_CAP_MTRAP_EXIT, 1) == 0);
#endif
/*
* Exit cleanly, using the conditional test to avoid the noreturn
* warning.
*/
if (bt)
grub_reboot();
}
/*
* 64-bit boot state initilization. This is really only used for FreeBSD.
* It is assumed that the repeating 1GB page tables have already been
* setup. The bhyve library call does almost everything - remaining
* GP register state is set here
*/
void
grub_emu_bhyve_boot64(struct grub_relocator64_state rs)
{
uint64_t gdt64[3];
uint64_t gdt64_addr;
int error;
/*
* Set up the GDT by copying it to just below the top of low memory
* and point the guest's GDT descriptor at it
*/
gdt64_addr = bhyve_g2h.lomem - 2 * sizeof(gdt64);
vm_setup_freebsd_gdt(gdt64);
memcpy(grub_emu_bhyve_virt(gdt64_addr), gdt64, sizeof(gdt64));
/*
* Use the library API to set up a FreeBSD entry reg state
*/
error = vm_setup_freebsd_registers(bhyve_ctx, 0, rs.rip, rs.cr3,
gdt64_addr, rs.rsp);
assert(error == 0);
/* Set up the remaining regs */
assert(vm_set_register(bhyve_ctx, 0, VM_REG_GUEST_RAX, rs.rax) == 0);
assert(vm_set_register(bhyve_ctx, 0, VM_REG_GUEST_RBX, rs.rbx) == 0);
assert(vm_set_register(bhyve_ctx, 0, VM_REG_GUEST_RCX, rs.rcx) == 0);
assert(vm_set_register(bhyve_ctx, 0, VM_REG_GUEST_RDX, rs.rdx) == 0);
assert(vm_set_register(bhyve_ctx, 0, VM_REG_GUEST_RSI, rs.rsi) == 0);
/*
* Exit cleanly, using the conditional test to avoid the noreturn
* warning.
*/
if (gdt64_addr)
grub_reboot();
}
const struct grub_bhyve_info *
grub_emu_bhyve_info(void)
{
return &bhyve_info;
}
void *
grub_emu_bhyve_virt(grub_uint64_t physaddr)
{
void *virt;
virt = NULL;
if (physaddr < bhyve_g2h.lomem)
virt = (char *)bhyve_g2h.lomem_ptr + physaddr;
else if (physaddr >= 4*GB && physaddr < (4*GB + bhyve_g2h.himem))
virt = (char *)bhyve_g2h.himem_ptr + (physaddr - 4*GB);
return (virt);
}
int
grub_emu_bhyve_parse_memsize(const char *arg, grub_uint64_t *size)
{
/*
* Assume size_t == uint64_t. Safe for amd64, which is the
* only platform grub-bhyve will ever run on.
*/
return (vm_parse_memsize(arg, size));
}
void
grub_emu_bhyve_unset_cinsert(void)
{
bhyve_cinsert = 0;
}
int
grub_emu_bhyve_cinsert(void)
{
return bhyve_cinsert;
}
void
grub_emu_bhyve_unset_vgainsert(void)
{
bhyve_vgainsert = 0;
}
int
grub_emu_bhyve_vgainsert(void)
{
return bhyve_vgainsert;
}
|
kmoore134/grub-bhyve
|
grub-core/kern/emu/bhyve_hostif.c
|
C
|
gpl-3.0
| 10,974
|
#!/bin/sh
Data='BBN'
Indir='Data/BBN'
Intermediate='Intermediate/BBN'
Outdir='Results/BBN'
### Make intermediate and output dirs
mkdir -pv $Intermediate
mkdir -pv $Outdir
### Generate features
echo 'Feature Generation...'
python DataProcessor/feature_generation.py $Data 4
echo ' '
### Train PLE
### - Wiki: -iters 50 -lr 0.25
### - OntoNotes: -iters 50 -lr 0.3
### - BBN: -iters 80 -lr 0.4
echo 'Heterogeneous Partial-Label Embedding...'
Model/ple/hple -data $Data -mode bcd -size 50 -negatives 10 -iters 80 -threads 30 -lr 0.4 -alpha 0.0001
echo ' '
### Clean training labels
### - Wiki: maximum dot -1.0
### - OntoNotes: topdown dot -1
### - BBN: maximum dot -100
echo 'Label Noise Reduction with learned embeddings...'
python Evaluation/emb_prediction.py $Data hple hete_feature maximum dot -100
echo ' '
### Train a type Classifier over the de-noised training data; predict on test data
### - Wiki: 0.003 1
### - OntoNotes: 0.003 20
### - BBN: 0.003 50
echo 'Train classifier and predict...'
python Classifier/Classifier.py perceptron $Data hple hete_feature 0.003 30
echo ' '
### Evalaute prediction results...
echo 'Evaluate on test data...'
python Evaluation/evaluation.py $Data hple hete_feature
|
shanzhenren/PLE
|
run.sh
|
Shell
|
gpl-3.0
| 1,219
|
from yanntricks import *
def KScolorD():
pspict,fig = SinglePicture("KScolorD")
pspict.dilatation(1)
x=var('x')
C=Circle(Point(0,0),1)
N1=C.graph(90,180)
N2=C.graph(270,360)
C.parameters.color="blue"
N1.parameters.color="black"
N2.parameters.color=N1.parameters.color
N1.wave(0.1,0.2)
#N2.wave(0.1,0.2)
N=Point(0,1)
S=Point(0,-1)
pspict.axes.no_graduation()
pspict.DrawGraphs(C,N1,N2,N,S)
pspict.DrawDefaultAxes()
fig.conclude()
fig.write_the_file()
|
LaurentClaessens/mazhe
|
src_yanntricks/yanntricksKScolorD.py
|
Python
|
gpl-3.0
| 526
|
/*
* Copyright (C) 2014 Ultramarin Design AB <dan@ultramarin.se>
*
* This file is part of uxmpp.
*
* uxmpp is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <uxmpp/types.hpp>
#include <uxmpp/Semaphore.hpp>
UXMPP_START_NAMESPACE1(uxmpp)
using namespace std;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
Semaphore::Semaphore (int initial_value)
{
std::lock_guard<std::mutex> lock (value_mutex);
value = initial_value;
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
void Semaphore::post ()
{
lock_guard<mutex> lock (value_mutex);
++value;
cond.notify_all ();
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
void Semaphore::wait ()
{
unique_lock<mutex> lock (value_mutex);
cond.wait (lock, [this]{return value;});
--value;
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
bool Semaphore::try_wait ()
{
unique_lock<mutex> lock (value_mutex);
if (value) {
--value;
return true;
}else{
return false;
}
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
unsigned Semaphore::get_value ()
{
lock_guard<mutex> lock (value_mutex);
return value;
}
UXMPP_END_NAMESPACE1
|
alfmep/uxmpp
|
src/uxmpp/Semaphore.cpp
|
C++
|
gpl-3.0
| 2,339
|
# coding: utf-8
# Copyright: (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
# Copyright: (c) 2018, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import base64
import json
import os
import random
import re
import stat
import tempfile
import time
from abc import ABCMeta, abstractmethod
from ansible import constants as C
from ansible.errors import AnsibleError, AnsibleConnectionFailure, AnsibleActionSkip, AnsibleActionFail
from ansible.executor.module_common import modify_module
from ansible.executor.interpreter_discovery import discover_interpreter, InterpreterDiscoveryRequiredError
from ansible.module_utils.common._collections_compat import Sequence
from ansible.module_utils.json_utils import _filter_non_json_lines
from ansible.module_utils.six import binary_type, string_types, text_type, iteritems, with_metaclass
from ansible.module_utils.six.moves import shlex_quote
from ansible.module_utils._text import to_bytes, to_native, to_text
from ansible.parsing.utils.jsonify import jsonify
from ansible.release import __version__
from ansible.utils.display import Display
from ansible.utils.unsafe_proxy import wrap_var, AnsibleUnsafeText
from ansible.vars.clean import remove_internal_keys
display = Display()
class ActionBase(with_metaclass(ABCMeta, object)):
'''
This class is the base class for all action plugins, and defines
code common to all actions. The base class handles the connection
by putting/getting files and executing commands based on the current
action in use.
'''
# A set of valid arguments
_VALID_ARGS = frozenset([])
def __init__(self, task, connection, play_context, loader, templar, shared_loader_obj):
self._task = task
self._connection = connection
self._play_context = play_context
self._loader = loader
self._templar = templar
self._shared_loader_obj = shared_loader_obj
self._cleanup_remote_tmp = False
self._supports_check_mode = True
self._supports_async = False
# interpreter discovery state
self._discovered_interpreter_key = None
self._discovered_interpreter = False
self._discovery_deprecation_warnings = []
self._discovery_warnings = []
# Backwards compat: self._display isn't really needed, just import the global display and use that.
self._display = display
self._used_interpreter = None
@abstractmethod
def run(self, tmp=None, task_vars=None):
""" Action Plugins should implement this method to perform their
tasks. Everything else in this base class is a helper method for the
action plugin to do that.
:kwarg tmp: Deprecated parameter. This is no longer used. An action plugin that calls
another one and wants to use the same remote tmp for both should set
self._connection._shell.tmpdir rather than this parameter.
:kwarg task_vars: The variables (host vars, group vars, config vars,
etc) associated with this task.
:returns: dictionary of results from the module
Implementors of action modules may find the following variables especially useful:
* Module parameters. These are stored in self._task.args
"""
result = {}
if tmp is not None:
result['warning'] = ['ActionModule.run() no longer honors the tmp parameter. Action'
' plugins should set self._connection._shell.tmpdir to share'
' the tmpdir']
del tmp
if self._task.async_val and not self._supports_async:
raise AnsibleActionFail('async is not supported for this task.')
elif self._play_context.check_mode and not self._supports_check_mode:
raise AnsibleActionSkip('check mode is not supported for this task.')
elif self._task.async_val and self._play_context.check_mode:
raise AnsibleActionFail('check mode and async cannot be used on same task.')
# Error if invalid argument is passed
if self._VALID_ARGS:
task_opts = frozenset(self._task.args.keys())
bad_opts = task_opts.difference(self._VALID_ARGS)
if bad_opts:
raise AnsibleActionFail('Invalid options for %s: %s' % (self._task.action, ','.join(list(bad_opts))))
if self._connection._shell.tmpdir is None and self._early_needs_tmp_path():
self._make_tmp_path()
return result
def cleanup(self, force=False):
"""Method to perform a clean up at the end of an action plugin execution
By default this is designed to clean up the shell tmpdir, and is toggled based on whether
async is in use
Action plugins may override this if they deem necessary, but should still call this method
via super
"""
if force or not self._task.async_val:
self._remove_tmp_path(self._connection._shell.tmpdir)
def get_plugin_option(self, plugin, option, default=None):
"""Helper to get an option from a plugin without having to use
the try/except dance everywhere to set a default
"""
try:
return plugin.get_option(option)
except (AttributeError, KeyError):
return default
def get_become_option(self, option, default=None):
return self.get_plugin_option(self._connection.become, option, default=default)
def get_connection_option(self, option, default=None):
return self.get_plugin_option(self._connection, option, default=default)
def get_shell_option(self, option, default=None):
return self.get_plugin_option(self._connection._shell, option, default=default)
def _remote_file_exists(self, path):
cmd = self._connection._shell.exists(path)
result = self._low_level_execute_command(cmd=cmd, sudoable=True)
if result['rc'] == 0:
return True
return False
def _configure_module(self, module_name, module_args, task_vars=None):
'''
Handles the loading and templating of the module code through the
modify_module() function.
'''
if task_vars is None:
task_vars = dict()
# Search module path(s) for named module.
for mod_type in self._connection.module_implementation_preferences:
# Check to determine if PowerShell modules are supported, and apply
# some fixes (hacks) to module name + args.
if mod_type == '.ps1':
# FIXME: This should be temporary and moved to an exec subsystem plugin where we can define the mapping
# for each subsystem.
win_collection = 'ansible.windows'
# async_status, win_stat, win_file, win_copy, and win_ping are not just like their
# python counterparts but they are compatible enough for our
# internal usage
if module_name in ('stat', 'file', 'copy', 'ping') and self._task.action != module_name:
module_name = '%s.win_%s' % (win_collection, module_name)
elif module_name in ['async_status']:
module_name = '%s.%s' % (win_collection, module_name)
# Remove extra quotes surrounding path parameters before sending to module.
if module_name.split('.')[-1] in ['win_stat', 'win_file', 'win_copy', 'slurp'] and module_args and \
hasattr(self._connection._shell, '_unquote'):
for key in ('src', 'dest', 'path'):
if key in module_args:
module_args[key] = self._connection._shell._unquote(module_args[key])
module_path = self._shared_loader_obj.module_loader.find_plugin(module_name, mod_type, collection_list=self._task.collections)
if module_path:
break
else: # This is a for-else: http://bit.ly/1ElPkyg
raise AnsibleError("The module %s was not found in configured module paths" % (module_name))
# insert shared code and arguments into the module
final_environment = dict()
self._compute_environment_string(final_environment)
become_kwargs = {}
if self._connection.become:
become_kwargs['become'] = True
become_kwargs['become_method'] = self._connection.become.name
become_kwargs['become_user'] = self._connection.become.get_option('become_user',
playcontext=self._play_context)
become_kwargs['become_password'] = self._connection.become.get_option('become_pass',
playcontext=self._play_context)
become_kwargs['become_flags'] = self._connection.become.get_option('become_flags',
playcontext=self._play_context)
# modify_module will exit early if interpreter discovery is required; re-run after if necessary
for dummy in (1, 2):
try:
(module_data, module_style, module_shebang) = modify_module(module_name, module_path, module_args, self._templar,
task_vars=task_vars,
module_compression=self._play_context.module_compression,
async_timeout=self._task.async_val,
environment=final_environment,
**become_kwargs)
break
except InterpreterDiscoveryRequiredError as idre:
self._discovered_interpreter = AnsibleUnsafeText(discover_interpreter(
action=self,
interpreter_name=idre.interpreter_name,
discovery_mode=idre.discovery_mode,
task_vars=task_vars))
# update the local task_vars with the discovered interpreter (which might be None);
# we'll propagate back to the controller in the task result
discovered_key = 'discovered_interpreter_%s' % idre.interpreter_name
# store in local task_vars facts collection for the retry and any other usages in this worker
if task_vars.get('ansible_facts') is None:
task_vars['ansible_facts'] = {}
task_vars['ansible_facts'][discovered_key] = self._discovered_interpreter
# preserve this so _execute_module can propagate back to controller as a fact
self._discovered_interpreter_key = discovered_key
return (module_style, module_shebang, module_data, module_path)
def _compute_environment_string(self, raw_environment_out=None):
'''
Builds the environment string to be used when executing the remote task.
'''
final_environment = dict()
if self._task.environment is not None:
environments = self._task.environment
if not isinstance(environments, list):
environments = [environments]
# The order of environments matters to make sure we merge
# in the parent's values first so those in the block then
# task 'win' in precedence
for environment in environments:
if environment is None or len(environment) == 0:
continue
temp_environment = self._templar.template(environment)
if not isinstance(temp_environment, dict):
raise AnsibleError("environment must be a dictionary, received %s (%s)" % (temp_environment, type(temp_environment)))
# very deliberately using update here instead of combine_vars, as
# these environment settings should not need to merge sub-dicts
final_environment.update(temp_environment)
if len(final_environment) > 0:
final_environment = self._templar.template(final_environment)
if isinstance(raw_environment_out, dict):
raw_environment_out.clear()
raw_environment_out.update(final_environment)
return self._connection._shell.env_prefix(**final_environment)
def _early_needs_tmp_path(self):
'''
Determines if a tmp path should be created before the action is executed.
'''
return getattr(self, 'TRANSFERS_FILES', False)
def _is_pipelining_enabled(self, module_style, wrap_async=False):
'''
Determines if we are required and can do pipelining
'''
# any of these require a true
for condition in [
self._connection.has_pipelining,
self._play_context.pipelining or self._connection.always_pipeline_modules, # pipelining enabled for play or connection requires it (eg winrm)
module_style == "new", # old style modules do not support pipelining
not C.DEFAULT_KEEP_REMOTE_FILES, # user wants remote files
not wrap_async or self._connection.always_pipeline_modules, # async does not normally support pipelining unless it does (eg winrm)
(self._connection.become.name if self._connection.become else '') != 'su', # su does not work with pipelining,
# FIXME: we might need to make become_method exclusion a configurable list
]:
if not condition:
return False
return True
def _get_admin_users(self):
'''
Returns a list of admin users that are configured for the current shell
plugin
'''
return self.get_shell_option('admin_users', ['root'])
def _get_remote_user(self):
''' consistently get the 'remote_user' for the action plugin '''
# TODO: use 'current user running ansible' as fallback when moving away from play_context
# pwd.getpwuid(os.getuid()).pw_name
remote_user = None
try:
remote_user = self._connection.get_option('remote_user')
except KeyError:
# plugin does not have remote_user option, fallback to default and/play_context
remote_user = getattr(self._connection, 'default_user', None) or self._play_context.remote_user
except AttributeError:
# plugin does not use config system, fallback to old play_context
remote_user = self._play_context.remote_user
return remote_user
def _is_become_unprivileged(self):
'''
The user is not the same as the connection user and is not part of the
shell configured admin users
'''
# if we don't use become then we know we aren't switching to a
# different unprivileged user
if not self._connection.become:
return False
# if we use become and the user is not an admin (or same user) then
# we need to return become_unprivileged as True
admin_users = self._get_admin_users()
remote_user = self._get_remote_user()
become_user = self.get_become_option('become_user')
return bool(become_user and become_user not in admin_users + [remote_user])
def _make_tmp_path(self, remote_user=None):
'''
Create and return a temporary path on a remote box.
'''
# Network connection plugins (network_cli, netconf, etc.) execute on the controller, rather than the remote host.
# As such, we want to avoid using remote_user for paths as remote_user may not line up with the local user
# This is a hack and should be solved by more intelligent handling of remote_tmp in 2.7
if getattr(self._connection, '_remote_is_local', False):
tmpdir = C.DEFAULT_LOCAL_TMP
else:
# NOTE: shell plugins should populate this setting anyways, but they dont do remote expansion, which
# we need for 'non posix' systems like cloud-init and solaris
tmpdir = self._remote_expand_user(self.get_shell_option('remote_tmp', default='~/.ansible/tmp'), sudoable=False)
become_unprivileged = self._is_become_unprivileged()
basefile = self._connection._shell._generate_temp_dir_name()
cmd = self._connection._shell.mkdtemp(basefile=basefile, system=become_unprivileged, tmpdir=tmpdir)
result = self._low_level_execute_command(cmd, sudoable=False)
# error handling on this seems a little aggressive?
if result['rc'] != 0:
if result['rc'] == 5:
output = 'Authentication failure.'
elif result['rc'] == 255 and self._connection.transport in ('ssh',):
if self._play_context.verbosity > 3:
output = u'SSH encountered an unknown error. The output was:\n%s%s' % (result['stdout'], result['stderr'])
else:
output = (u'SSH encountered an unknown error during the connection. '
'We recommend you re-run the command using -vvvv, which will enable SSH debugging output to help diagnose the issue')
elif u'No space left on device' in result['stderr']:
output = result['stderr']
else:
output = ('Failed to create temporary directory.'
'In some cases, you may have been able to authenticate and did not have permissions on the target directory. '
'Consider changing the remote tmp path in ansible.cfg to a path rooted in "/tmp", for more error information use -vvv. '
'Failed command was: %s, exited with result %d' % (cmd, result['rc']))
if 'stdout' in result and result['stdout'] != u'':
output = output + u", stdout output: %s" % result['stdout']
if self._play_context.verbosity > 3 and 'stderr' in result and result['stderr'] != u'':
output += u", stderr output: %s" % result['stderr']
raise AnsibleConnectionFailure(output)
else:
self._cleanup_remote_tmp = True
try:
stdout_parts = result['stdout'].strip().split('%s=' % basefile, 1)
rc = self._connection._shell.join_path(stdout_parts[-1], u'').splitlines()[-1]
except IndexError:
# stdout was empty or just space, set to / to trigger error in next if
rc = '/'
# Catch failure conditions, files should never be
# written to locations in /.
if rc == '/':
raise AnsibleError('failed to resolve remote temporary directory from %s: `%s` returned empty string' % (basefile, cmd))
self._connection._shell.tmpdir = rc
return rc
def _should_remove_tmp_path(self, tmp_path):
'''Determine if temporary path should be deleted or kept by user request/config'''
return tmp_path and self._cleanup_remote_tmp and not C.DEFAULT_KEEP_REMOTE_FILES and "-tmp-" in tmp_path
def _remove_tmp_path(self, tmp_path):
'''Remove a temporary path we created. '''
if tmp_path is None and self._connection._shell.tmpdir:
tmp_path = self._connection._shell.tmpdir
if self._should_remove_tmp_path(tmp_path):
cmd = self._connection._shell.remove(tmp_path, recurse=True)
# If we have gotten here we have a working ssh configuration.
# If ssh breaks we could leave tmp directories out on the remote system.
tmp_rm_res = self._low_level_execute_command(cmd, sudoable=False)
if tmp_rm_res.get('rc', 0) != 0:
display.warning('Error deleting remote temporary files (rc: %s, stderr: %s})'
% (tmp_rm_res.get('rc'), tmp_rm_res.get('stderr', 'No error string available.')))
else:
self._connection._shell.tmpdir = None
def _transfer_file(self, local_path, remote_path):
"""
Copy a file from the controller to a remote path
:arg local_path: Path on controller to transfer
:arg remote_path: Path on the remote system to transfer into
.. warning::
* When you use this function you likely want to use use fixup_perms2() on the
remote_path to make sure that the remote file is readable when the user becomes
a non-privileged user.
* If you use fixup_perms2() on the file and copy or move the file into place, you will
need to then remove filesystem acls on the file once it has been copied into place by
the module. See how the copy module implements this for help.
"""
self._connection.put_file(local_path, remote_path)
return remote_path
def _transfer_data(self, remote_path, data):
'''
Copies the module data out to the temporary module path.
'''
if isinstance(data, dict):
data = jsonify(data)
afd, afile = tempfile.mkstemp(dir=C.DEFAULT_LOCAL_TMP)
afo = os.fdopen(afd, 'wb')
try:
data = to_bytes(data, errors='surrogate_or_strict')
afo.write(data)
except Exception as e:
raise AnsibleError("failure writing module data to temporary file for transfer: %s" % to_native(e))
afo.flush()
afo.close()
try:
self._transfer_file(afile, remote_path)
finally:
os.unlink(afile)
return remote_path
def _fixup_perms2(self, remote_paths, remote_user=None, execute=True):
"""
We need the files we upload to be readable (and sometimes executable)
by the user being sudo'd to but we want to limit other people's access
(because the files could contain passwords or other private
information. We achieve this in one of these ways:
* If no sudo is performed or the remote_user is sudo'ing to
themselves, we don't have to change permissions.
* If the remote_user sudo's to a privileged user (for instance, root),
we don't have to change permissions
* If the remote_user sudo's to an unprivileged user then we attempt to
grant the unprivileged user access via file system acls.
* If granting file system acls fails we try to change the owner of the
file with chown which only works in case the remote_user is
privileged or the remote systems allows chown calls by unprivileged
users (e.g. HP-UX)
* If the chown fails we can set the file to be world readable so that
the second unprivileged user can read the file.
Since this could allow other users to get access to private
information we only do this if ansible is configured with
"allow_world_readable_tmpfiles" in the ansible.cfg
"""
if remote_user is None:
remote_user = self._get_remote_user()
if getattr(self._connection._shell, "_IS_WINDOWS", False):
# This won't work on Powershell as-is, so we'll just completely skip until
# we have a need for it, at which point we'll have to do something different.
return remote_paths
if self._is_become_unprivileged():
# Unprivileged user that's different than the ssh user. Let's get
# to work!
# Try to use file system acls to make the files readable for sudo'd
# user
if execute:
chmod_mode = 'rx'
setfacl_mode = 'r-x'
else:
chmod_mode = 'rX'
# NOTE: this form fails silently on freebsd. We currently
# never call _fixup_perms2() with execute=False but if we
# start to we'll have to fix this.
setfacl_mode = 'r-X'
res = self._remote_set_user_facl(remote_paths, self.get_become_option('become_user'), setfacl_mode)
if res['rc'] != 0:
# File system acls failed; let's try to use chown next
# Set executable bit first as on some systems an
# unprivileged user can use chown
if execute:
res = self._remote_chmod(remote_paths, 'u+x')
if res['rc'] != 0:
raise AnsibleError('Failed to set file mode on remote temporary files (rc: {0}, err: {1})'.format(res['rc'], to_native(res['stderr'])))
res = self._remote_chown(remote_paths, self.get_become_option('become_user'))
if res['rc'] != 0 and remote_user in self._get_admin_users():
# chown failed even if remote_user is administrator/root
raise AnsibleError('Failed to change ownership of the temporary files Ansible needs to create despite connecting as a privileged user. '
'Unprivileged become user would be unable to read the file.')
elif res['rc'] != 0:
if C.ALLOW_WORLD_READABLE_TMPFILES:
# chown and fs acls failed -- do things this insecure
# way only if the user opted in in the config file
display.warning('Using world-readable permissions for temporary files Ansible needs to create when becoming an unprivileged user. '
'This may be insecure. For information on securing this, see '
'https://docs.ansible.com/ansible/user_guide/become.html#risks-of-becoming-an-unprivileged-user')
res = self._remote_chmod(remote_paths, 'a+%s' % chmod_mode)
if res['rc'] != 0:
raise AnsibleError('Failed to set file mode on remote files (rc: {0}, err: {1})'.format(res['rc'], to_native(res['stderr'])))
else:
raise AnsibleError('Failed to set permissions on the temporary files Ansible needs to create when becoming an unprivileged user '
'(rc: %s, err: %s}). For information on working around this, see '
'https://docs.ansible.com/ansible/become.html#becoming-an-unprivileged-user'
% (res['rc'], to_native(res['stderr'])))
elif execute:
# Can't depend on the file being transferred with execute permissions.
# Only need user perms because no become was used here
res = self._remote_chmod(remote_paths, 'u+x')
if res['rc'] != 0:
raise AnsibleError('Failed to set execute bit on remote files (rc: {0}, err: {1})'.format(res['rc'], to_native(res['stderr'])))
return remote_paths
def _remote_chmod(self, paths, mode, sudoable=False):
'''
Issue a remote chmod command
'''
cmd = self._connection._shell.chmod(paths, mode)
res = self._low_level_execute_command(cmd, sudoable=sudoable)
return res
def _remote_chown(self, paths, user, sudoable=False):
'''
Issue a remote chown command
'''
cmd = self._connection._shell.chown(paths, user)
res = self._low_level_execute_command(cmd, sudoable=sudoable)
return res
def _remote_set_user_facl(self, paths, user, mode, sudoable=False):
'''
Issue a remote call to setfacl
'''
cmd = self._connection._shell.set_user_facl(paths, user, mode)
res = self._low_level_execute_command(cmd, sudoable=sudoable)
return res
def _execute_remote_stat(self, path, all_vars, follow, tmp=None, checksum=True):
'''
Get information from remote file.
'''
if tmp is not None:
display.warning('_execute_remote_stat no longer honors the tmp parameter. Action'
' plugins should set self._connection._shell.tmpdir to share'
' the tmpdir')
del tmp # No longer used
module_args = dict(
path=path,
follow=follow,
get_checksum=checksum,
checksum_algorithm='sha1',
)
mystat = self._execute_module(module_name='stat', module_args=module_args, task_vars=all_vars,
wrap_async=False)
if mystat.get('failed'):
msg = mystat.get('module_stderr')
if not msg:
msg = mystat.get('module_stdout')
if not msg:
msg = mystat.get('msg')
raise AnsibleError('Failed to get information on remote file (%s): %s' % (path, msg))
if not mystat['stat']['exists']:
# empty might be matched, 1 should never match, also backwards compatible
mystat['stat']['checksum'] = '1'
# happens sometimes when it is a dir and not on bsd
if 'checksum' not in mystat['stat']:
mystat['stat']['checksum'] = ''
elif not isinstance(mystat['stat']['checksum'], string_types):
raise AnsibleError("Invalid checksum returned by stat: expected a string type but got %s" % type(mystat['stat']['checksum']))
return mystat['stat']
def _remote_checksum(self, path, all_vars, follow=False):
'''
Produces a remote checksum given a path,
Returns a number 0-4 for specific errors instead of checksum, also ensures it is different
0 = unknown error
1 = file does not exist, this might not be an error
2 = permissions issue
3 = its a directory, not a file
4 = stat module failed, likely due to not finding python
5 = appropriate json module not found
'''
x = "0" # unknown error has occurred
try:
remote_stat = self._execute_remote_stat(path, all_vars, follow=follow)
if remote_stat['exists'] and remote_stat['isdir']:
x = "3" # its a directory not a file
else:
x = remote_stat['checksum'] # if 1, file is missing
except AnsibleError as e:
errormsg = to_text(e)
if errormsg.endswith(u'Permission denied'):
x = "2" # cannot read file
elif errormsg.endswith(u'MODULE FAILURE'):
x = "4" # python not found or module uncaught exception
elif 'json' in errormsg:
x = "5" # json module needed
finally:
return x # pylint: disable=lost-exception
def _remote_expand_user(self, path, sudoable=True, pathsep=None):
''' takes a remote path and performs tilde/$HOME expansion on the remote host '''
# We only expand ~/path and ~username/path
if not path.startswith('~'):
return path
# Per Jborean, we don't have to worry about Windows as we don't have a notion of user's home
# dir there.
split_path = path.split(os.path.sep, 1)
expand_path = split_path[0]
if expand_path == '~':
# Network connection plugins (network_cli, netconf, etc.) execute on the controller, rather than the remote host.
# As such, we want to avoid using remote_user for paths as remote_user may not line up with the local user
# This is a hack and should be solved by more intelligent handling of remote_tmp in 2.7
become_user = self.get_become_option('become_user')
if getattr(self._connection, '_remote_is_local', False):
pass
elif sudoable and self._connection.become and become_user:
expand_path = '~%s' % become_user
else:
# use remote user instead, if none set default to current user
expand_path = '~%s' % (self._get_remote_user() or '')
# use shell to construct appropriate command and execute
cmd = self._connection._shell.expand_user(expand_path)
data = self._low_level_execute_command(cmd, sudoable=False)
try:
initial_fragment = data['stdout'].strip().splitlines()[-1]
except IndexError:
initial_fragment = None
if not initial_fragment:
# Something went wrong trying to expand the path remotely. Try using pwd, if not, return
# the original string
cmd = self._connection._shell.pwd()
pwd = self._low_level_execute_command(cmd, sudoable=False).get('stdout', '').strip()
if pwd:
expanded = pwd
else:
expanded = path
elif len(split_path) > 1:
expanded = self._connection._shell.join_path(initial_fragment, *split_path[1:])
else:
expanded = initial_fragment
if '..' in os.path.dirname(expanded).split('/'):
raise AnsibleError("'%s' returned an invalid relative home directory path containing '..'" % self._play_context.remote_addr)
return expanded
def _strip_success_message(self, data):
'''
Removes the BECOME-SUCCESS message from the data.
'''
if data.strip().startswith('BECOME-SUCCESS-'):
data = re.sub(r'^((\r)?\n)?BECOME-SUCCESS.*(\r)?\n', '', data)
return data
def _update_module_args(self, module_name, module_args, task_vars):
# set check mode in the module arguments, if required
if self._play_context.check_mode:
if not self._supports_check_mode:
raise AnsibleError("check mode is not supported for this operation")
module_args['_ansible_check_mode'] = True
else:
module_args['_ansible_check_mode'] = False
# set no log in the module arguments, if required
no_target_syslog = C.config.get_config_value('DEFAULT_NO_TARGET_SYSLOG', variables=task_vars)
module_args['_ansible_no_log'] = self._play_context.no_log or no_target_syslog
# set debug in the module arguments, if required
module_args['_ansible_debug'] = C.DEFAULT_DEBUG
# let module know we are in diff mode
module_args['_ansible_diff'] = self._play_context.diff
# let module know our verbosity
module_args['_ansible_verbosity'] = display.verbosity
# give the module information about the ansible version
module_args['_ansible_version'] = __version__
# give the module information about its name
module_args['_ansible_module_name'] = module_name
# set the syslog facility to be used in the module
module_args['_ansible_syslog_facility'] = task_vars.get('ansible_syslog_facility', C.DEFAULT_SYSLOG_FACILITY)
# let module know about filesystems that selinux treats specially
module_args['_ansible_selinux_special_fs'] = C.DEFAULT_SELINUX_SPECIAL_FS
# what to do when parameter values are converted to strings
module_args['_ansible_string_conversion_action'] = C.STRING_CONVERSION_ACTION
# give the module the socket for persistent connections
module_args['_ansible_socket'] = getattr(self._connection, 'socket_path')
if not module_args['_ansible_socket']:
module_args['_ansible_socket'] = task_vars.get('ansible_socket')
# make sure all commands use the designated shell executable
module_args['_ansible_shell_executable'] = self._play_context.executable
# make sure modules are aware if they need to keep the remote files
module_args['_ansible_keep_remote_files'] = C.DEFAULT_KEEP_REMOTE_FILES
# make sure all commands use the designated temporary directory if created
if self._is_become_unprivileged(): # force fallback on remote_tmp as user cannot normally write to dir
module_args['_ansible_tmpdir'] = None
else:
module_args['_ansible_tmpdir'] = self._connection._shell.tmpdir
# make sure the remote_tmp value is sent through in case modules needs to create their own
module_args['_ansible_remote_tmp'] = self.get_shell_option('remote_tmp', default='~/.ansible/tmp')
def _execute_module(self, module_name=None, module_args=None, tmp=None, task_vars=None, persist_files=False, delete_remote_tmp=None, wrap_async=False):
'''
Transfer and run a module along with its arguments.
'''
if tmp is not None:
display.warning('_execute_module no longer honors the tmp parameter. Action plugins'
' should set self._connection._shell.tmpdir to share the tmpdir')
del tmp # No longer used
if delete_remote_tmp is not None:
display.warning('_execute_module no longer honors the delete_remote_tmp parameter.'
' Action plugins should check self._connection._shell.tmpdir to'
' see if a tmpdir existed before they were called to determine'
' if they are responsible for removing it.')
del delete_remote_tmp # No longer used
tmpdir = self._connection._shell.tmpdir
# We set the module_style to new here so the remote_tmp is created
# before the module args are built if remote_tmp is needed (async).
# If the module_style turns out to not be new and we didn't create the
# remote tmp here, it will still be created. This must be done before
# calling self._update_module_args() so the module wrapper has the
# correct remote_tmp value set
if not self._is_pipelining_enabled("new", wrap_async) and tmpdir is None:
self._make_tmp_path()
tmpdir = self._connection._shell.tmpdir
if task_vars is None:
task_vars = dict()
# if a module name was not specified for this execution, use the action from the task
if module_name is None:
module_name = self._task.action
if module_args is None:
module_args = self._task.args
self._update_module_args(module_name, module_args, task_vars)
# FIXME: convert async_wrapper.py to not rely on environment variables
# make sure we get the right async_dir variable, backwards compatibility
# means we need to lookup the env value ANSIBLE_ASYNC_DIR first
remove_async_dir = None
if wrap_async or self._task.async_val:
env_async_dir = [e for e in self._task.environment if
"ANSIBLE_ASYNC_DIR" in e]
if len(env_async_dir) > 0:
msg = "Setting the async dir from the environment keyword " \
"ANSIBLE_ASYNC_DIR is deprecated. Set the async_dir " \
"shell option instead"
self._display.deprecated(msg, "2.12")
else:
# ANSIBLE_ASYNC_DIR is not set on the task, we get the value
# from the shell option and temporarily add to the environment
# list for async_wrapper to pick up
async_dir = self.get_shell_option('async_dir', default="~/.ansible_async")
remove_async_dir = len(self._task.environment)
self._task.environment.append({"ANSIBLE_ASYNC_DIR": async_dir})
# FUTURE: refactor this along with module build process to better encapsulate "smart wrapper" functionality
(module_style, shebang, module_data, module_path) = self._configure_module(module_name=module_name, module_args=module_args, task_vars=task_vars)
display.vvv("Using module file %s" % module_path)
if not shebang and module_style != 'binary':
raise AnsibleError("module (%s) is missing interpreter line" % module_name)
self._used_interpreter = shebang
remote_module_path = None
if not self._is_pipelining_enabled(module_style, wrap_async):
# we might need remote tmp dir
if tmpdir is None:
self._make_tmp_path()
tmpdir = self._connection._shell.tmpdir
remote_module_filename = self._connection._shell.get_remote_filename(module_path)
remote_module_path = self._connection._shell.join_path(tmpdir, 'AnsiballZ_%s' % remote_module_filename)
args_file_path = None
if module_style in ('old', 'non_native_want_json', 'binary'):
# we'll also need a tmp file to hold our module arguments
args_file_path = self._connection._shell.join_path(tmpdir, 'args')
if remote_module_path or module_style != 'new':
display.debug("transferring module to remote %s" % remote_module_path)
if module_style == 'binary':
self._transfer_file(module_path, remote_module_path)
else:
self._transfer_data(remote_module_path, module_data)
if module_style == 'old':
# we need to dump the module args to a k=v string in a file on
# the remote system, which can be read and parsed by the module
args_data = ""
for k, v in iteritems(module_args):
args_data += '%s=%s ' % (k, shlex_quote(text_type(v)))
self._transfer_data(args_file_path, args_data)
elif module_style in ('non_native_want_json', 'binary'):
self._transfer_data(args_file_path, json.dumps(module_args))
display.debug("done transferring module to remote")
environment_string = self._compute_environment_string()
# remove the ANSIBLE_ASYNC_DIR env entry if we added a temporary one for
# the async_wrapper task - this is so the async_status plugin doesn't
# fire a deprecation warning when it runs after this task
if remove_async_dir is not None:
del self._task.environment[remove_async_dir]
remote_files = []
if tmpdir and remote_module_path:
remote_files = [tmpdir, remote_module_path]
if args_file_path:
remote_files.append(args_file_path)
sudoable = True
in_data = None
cmd = ""
if wrap_async and not self._connection.always_pipeline_modules:
# configure, upload, and chmod the async_wrapper module
(async_module_style, shebang, async_module_data, async_module_path) = self._configure_module(module_name='async_wrapper', module_args=dict(),
task_vars=task_vars)
async_module_remote_filename = self._connection._shell.get_remote_filename(async_module_path)
remote_async_module_path = self._connection._shell.join_path(tmpdir, async_module_remote_filename)
self._transfer_data(remote_async_module_path, async_module_data)
remote_files.append(remote_async_module_path)
async_limit = self._task.async_val
async_jid = str(random.randint(0, 999999999999))
# call the interpreter for async_wrapper directly
# this permits use of a script for an interpreter on non-Linux platforms
# TODO: re-implement async_wrapper as a regular module to avoid this special case
interpreter = shebang.replace('#!', '').strip()
async_cmd = [interpreter, remote_async_module_path, async_jid, async_limit, remote_module_path]
if environment_string:
async_cmd.insert(0, environment_string)
if args_file_path:
async_cmd.append(args_file_path)
else:
# maintain a fixed number of positional parameters for async_wrapper
async_cmd.append('_')
if not self._should_remove_tmp_path(tmpdir):
async_cmd.append("-preserve_tmp")
cmd = " ".join(to_text(x) for x in async_cmd)
else:
if self._is_pipelining_enabled(module_style):
in_data = module_data
display.vvv("Pipelining is enabled.")
else:
cmd = remote_module_path
cmd = self._connection._shell.build_module_command(environment_string, shebang, cmd, arg_path=args_file_path).strip()
# Fix permissions of the tmpdir path and tmpdir files. This should be called after all
# files have been transferred.
if remote_files:
# remove none/empty
remote_files = [x for x in remote_files if x]
self._fixup_perms2(remote_files, self._get_remote_user())
# actually execute
res = self._low_level_execute_command(cmd, sudoable=sudoable, in_data=in_data)
# parse the main result
data = self._parse_returned_data(res)
# NOTE: INTERNAL KEYS ONLY ACCESSIBLE HERE
# get internal info before cleaning
if data.pop("_ansible_suppress_tmpdir_delete", False):
self._cleanup_remote_tmp = False
# NOTE: yum returns results .. but that made it 'compatible' with squashing, so we allow mappings, for now
if 'results' in data and (not isinstance(data['results'], Sequence) or isinstance(data['results'], string_types)):
data['ansible_module_results'] = data['results']
del data['results']
display.warning("Found internal 'results' key in module return, renamed to 'ansible_module_results'.")
# remove internal keys
remove_internal_keys(data)
if wrap_async:
# async_wrapper will clean up its tmpdir on its own so we want the controller side to
# forget about it now
self._connection._shell.tmpdir = None
# FIXME: for backwards compat, figure out if still makes sense
data['changed'] = True
# pre-split stdout/stderr into lines if needed
if 'stdout' in data and 'stdout_lines' not in data:
# if the value is 'False', a default won't catch it.
txt = data.get('stdout', None) or u''
data['stdout_lines'] = txt.splitlines()
if 'stderr' in data and 'stderr_lines' not in data:
# if the value is 'False', a default won't catch it.
txt = data.get('stderr', None) or u''
data['stderr_lines'] = txt.splitlines()
# propagate interpreter discovery results back to the controller
if self._discovered_interpreter_key:
if data.get('ansible_facts') is None:
data['ansible_facts'] = {}
data['ansible_facts'][self._discovered_interpreter_key] = self._discovered_interpreter
if self._discovery_warnings:
if data.get('warnings') is None:
data['warnings'] = []
data['warnings'].extend(self._discovery_warnings)
if self._discovery_deprecation_warnings:
if data.get('deprecations') is None:
data['deprecations'] = []
data['deprecations'].extend(self._discovery_deprecation_warnings)
# mark the entire module results untrusted as a template right here, since the current action could
# possibly template one of these values.
data = wrap_var(data)
display.debug("done with _execute_module (%s, %s)" % (module_name, module_args))
return data
def _parse_returned_data(self, res):
try:
filtered_output, warnings = _filter_non_json_lines(res.get('stdout', u''))
for w in warnings:
display.warning(w)
data = json.loads(filtered_output)
data['_ansible_parsed'] = True
except ValueError:
# not valid json, lets try to capture error
data = dict(failed=True, _ansible_parsed=False)
data['module_stdout'] = res.get('stdout', u'')
if 'stderr' in res:
data['module_stderr'] = res['stderr']
if res['stderr'].startswith(u'Traceback'):
data['exception'] = res['stderr']
# in some cases a traceback will arrive on stdout instead of stderr, such as when using ssh with -tt
if 'exception' not in data and data['module_stdout'].startswith(u'Traceback'):
data['exception'] = data['module_stdout']
# The default
data['msg'] = "MODULE FAILURE"
# try to figure out if we are missing interpreter
if self._used_interpreter is not None:
match = re.compile('%s: (?:No such file or directory|not found)' % self._used_interpreter.lstrip('!#'))
if match.search(data['module_stderr']) or match.search(data['module_stdout']):
data['msg'] = "The module failed to execute correctly, you probably need to set the interpreter."
# always append hint
data['msg'] += '\nSee stdout/stderr for the exact error'
if 'rc' in res:
data['rc'] = res['rc']
return data
# FIXME: move to connection base
def _low_level_execute_command(self, cmd, sudoable=True, in_data=None, executable=None, encoding_errors='surrogate_then_replace', chdir=None):
'''
This is the function which executes the low level shell command, which
may be commands to create/remove directories for temporary files, or to
run the module code or python directly when pipelining.
:kwarg encoding_errors: If the value returned by the command isn't
utf-8 then we have to figure out how to transform it to unicode.
If the value is just going to be displayed to the user (or
discarded) then the default of 'replace' is fine. If the data is
used as a key or is going to be written back out to a file
verbatim, then this won't work. May have to use some sort of
replacement strategy (python3 could use surrogateescape)
:kwarg chdir: cd into this directory before executing the command.
'''
display.debug("_low_level_execute_command(): starting")
# if not cmd:
# # this can happen with powershell modules when there is no analog to a Windows command (like chmod)
# display.debug("_low_level_execute_command(): no command, exiting")
# return dict(stdout='', stderr='', rc=254)
if chdir:
display.debug("_low_level_execute_command(): changing cwd to %s for this command" % chdir)
cmd = self._connection._shell.append_command('cd %s' % chdir, cmd)
# https://github.com/ansible/ansible/issues/68054
if executable:
self._connection._shell.executable = executable
ruser = self._get_remote_user()
buser = self.get_become_option('become_user')
if (sudoable and self._connection.become and # if sudoable and have become
self._connection.transport.split('.')[-1] != 'network_cli' and # if not using network_cli
(C.BECOME_ALLOW_SAME_USER or (buser != ruser or not any((ruser, buser))))): # if we allow same user PE or users are different and either is set
display.debug("_low_level_execute_command(): using become for this command")
cmd = self._connection.become.build_become_command(cmd, self._connection._shell)
if self._connection.allow_executable:
if executable is None:
executable = self._play_context.executable
# mitigation for SSH race which can drop stdout (https://github.com/ansible/ansible/issues/13876)
# only applied for the default executable to avoid interfering with the raw action
cmd = self._connection._shell.append_command(cmd, 'sleep 0')
if executable:
cmd = executable + ' -c ' + shlex_quote(cmd)
display.debug("_low_level_execute_command(): executing: %s" % (cmd,))
# Change directory to basedir of task for command execution when connection is local
if self._connection.transport == 'local':
self._connection.cwd = to_bytes(self._loader.get_basedir(), errors='surrogate_or_strict')
rc, stdout, stderr = self._connection.exec_command(cmd, in_data=in_data, sudoable=sudoable)
# stdout and stderr may be either a file-like or a bytes object.
# Convert either one to a text type
if isinstance(stdout, binary_type):
out = to_text(stdout, errors=encoding_errors)
elif not isinstance(stdout, text_type):
out = to_text(b''.join(stdout.readlines()), errors=encoding_errors)
else:
out = stdout
if isinstance(stderr, binary_type):
err = to_text(stderr, errors=encoding_errors)
elif not isinstance(stderr, text_type):
err = to_text(b''.join(stderr.readlines()), errors=encoding_errors)
else:
err = stderr
if rc is None:
rc = 0
# be sure to remove the BECOME-SUCCESS message now
out = self._strip_success_message(out)
display.debug(u"_low_level_execute_command() done: rc=%d, stdout=%s, stderr=%s" % (rc, out, err))
return dict(rc=rc, stdout=out, stdout_lines=out.splitlines(), stderr=err, stderr_lines=err.splitlines())
def _get_diff_data(self, destination, source, task_vars, source_file=True):
# Note: Since we do not diff the source and destination before we transform from bytes into
# text the diff between source and destination may not be accurate. To fix this, we'd need
# to move the diffing from the callback plugins into here.
#
# Example of data which would cause trouble is src_content == b'\xff' and dest_content ==
# b'\xfe'. Neither of those are valid utf-8 so both get turned into the replacement
# character: diff['before'] = u'�' ; diff['after'] = u'�' When the callback plugin later
# diffs before and after it shows an empty diff.
diff = {}
display.debug("Going to peek to see if file has changed permissions")
peek_result = self._execute_module(module_name='file', module_args=dict(path=destination, _diff_peek=True), task_vars=task_vars, persist_files=True)
if peek_result.get('failed', False):
display.warning(u"Failed to get diff between '%s' and '%s': %s" % (os.path.basename(source), destination, to_text(peek_result.get(u'msg', u''))))
return diff
if peek_result.get('rc', 0) == 0:
if peek_result.get('state') in (None, 'absent'):
diff['before'] = u''
elif peek_result.get('appears_binary'):
diff['dst_binary'] = 1
elif peek_result.get('size') and C.MAX_FILE_SIZE_FOR_DIFF > 0 and peek_result['size'] > C.MAX_FILE_SIZE_FOR_DIFF:
diff['dst_larger'] = C.MAX_FILE_SIZE_FOR_DIFF
else:
display.debug(u"Slurping the file %s" % source)
dest_result = self._execute_module(module_name='slurp', module_args=dict(path=destination), task_vars=task_vars, persist_files=True)
if 'content' in dest_result:
dest_contents = dest_result['content']
if dest_result['encoding'] == u'base64':
dest_contents = base64.b64decode(dest_contents)
else:
raise AnsibleError("unknown encoding in content option, failed: %s" % to_native(dest_result))
diff['before_header'] = destination
diff['before'] = to_text(dest_contents)
if source_file:
st = os.stat(source)
if C.MAX_FILE_SIZE_FOR_DIFF > 0 and st[stat.ST_SIZE] > C.MAX_FILE_SIZE_FOR_DIFF:
diff['src_larger'] = C.MAX_FILE_SIZE_FOR_DIFF
else:
display.debug("Reading local copy of the file %s" % source)
try:
with open(source, 'rb') as src:
src_contents = src.read()
except Exception as e:
raise AnsibleError("Unexpected error while reading source (%s) for diff: %s " % (source, to_native(e)))
if b"\x00" in src_contents:
diff['src_binary'] = 1
else:
diff['after_header'] = source
diff['after'] = to_text(src_contents)
else:
display.debug(u"source of file passed in")
diff['after_header'] = u'dynamically generated'
diff['after'] = source
if self._play_context.no_log:
if 'before' in diff:
diff["before"] = u""
if 'after' in diff:
diff["after"] = u" [[ Diff output has been hidden because 'no_log: true' was specified for this result ]]\n"
return diff
def _find_needle(self, dirname, needle):
'''
find a needle in haystack of paths, optionally using 'dirname' as a subdir.
This will build the ordered list of paths to search and pass them to dwim
to get back the first existing file found.
'''
# dwim already deals with playbook basedirs
path_stack = self._task.get_search_path()
# if missing it will return a file not found exception
return self._loader.path_dwim_relative_stack(path_stack, dirname, needle)
|
tonk/ansible
|
lib/ansible/plugins/action/__init__.py
|
Python
|
gpl-3.0
| 58,185
|
/*******************************************************************
Part of the Fritzing project - http://fritzing.org
Copyright (c) 2007-2011 Fachhochschule Potsdam - http://fh-potsdam.de
Fritzing is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Fritzing 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 Fritzing. If not, see <http://www.gnu.org/licenses/>.
********************************************************************
$Revision: 5721 $:
$Author: cohen@irascible.com $:
$Date: 2012-01-03 07:53:58 -0800 (Tue, 03 Jan 2012) $
********************************************************************/
#include "tracewire.h"
#include "../sketch/infographicsview.h"
#include "../connectors/connectoritem.h"
#include "../utils/focusoutcombobox.h"
#include <QComboBox>
const int TraceWire::MinTraceWidthMils = 8;
const int TraceWire::MaxTraceWidthMils = 128;
/////////////////////////////////////////////////////////
TraceWire::TraceWire( ModelPart * modelPart, ViewIdentifierClass::ViewIdentifier viewIdentifier, const ViewGeometry & viewGeometry, long id, QMenu * itemMenu )
: ClipableWire(modelPart, viewIdentifier, viewGeometry, id, itemMenu, true)
{
m_canChainMultiple = true;
m_wireDirection = TraceWire::NoDirection;
}
TraceWire::~TraceWire()
{
}
QComboBox * TraceWire::createWidthComboBox(double m, QWidget * parent)
{
QComboBox * comboBox = new FocusOutComboBox(parent); // new QComboBox(parent);
comboBox->setEditable(true);
QIntValidator * intValidator = new QIntValidator(comboBox);
intValidator->setRange(MinTraceWidthMils, MaxTraceWidthMils);
comboBox->setValidator(intValidator);
int ix = 0;
if (!Wire::widths.contains(m)) {
Wire::widths.append(m);
qSort(Wire::widths.begin(), Wire::widths.end());
}
foreach(long widthValue, Wire::widths) {
QString widthName = Wire::widthTrans.value(widthValue, "");
QVariant val((int) widthValue);
comboBox->addItem(widthName.isEmpty() ? QString::number(widthValue) : widthName, val);
if (qAbs(m - widthValue) < .01) {
comboBox->setCurrentIndex(ix);
}
ix++;
}
return comboBox;
}
bool TraceWire::collectExtraInfo(QWidget * parent, const QString & family, const QString & prop, const QString & value, bool swappingEnabled, QString & returnProp, QString & returnValue, QWidget * & returnWidget)
{
if (prop.compare("width", Qt::CaseInsensitive) == 0) {
returnProp = tr("width");
QComboBox * comboBox = createWidthComboBox(mils(), parent);
comboBox->setEnabled(swappingEnabled);
comboBox->setObjectName("infoViewComboBox");
connect(comboBox, SIGNAL(currentIndexChanged(const QString &)), this, SLOT(widthEntry(const QString &)));
returnWidget = comboBox;
returnValue = comboBox->currentText();
return true;
}
return ClipableWire::collectExtraInfo(parent, family, prop, value, swappingEnabled, returnProp, returnValue, returnWidget);
}
void TraceWire::widthEntry(const QString & text) {
int w = widthEntry(text, sender());
if (w == 0) return;
InfoGraphicsView * infoGraphicsView = InfoGraphicsView::getInfoGraphicsView(this);
if (infoGraphicsView != NULL) {
infoGraphicsView->changeWireWidthMils(QString::number(w));
}
}
int TraceWire::widthEntry(const QString & text, QObject * sender) {
QComboBox * comboBox = qobject_cast<QComboBox *>(sender);
if (comboBox == NULL) return 0;
int w = comboBox->itemData(comboBox->currentIndex()).toInt();
if (w == 0) {
// user typed in a number
w = text.toInt();
}
if (!Wire::widths.contains(w)) {
Wire::widths.append(w);
qSort(Wire::widths.begin(), Wire::widths.end());
}
return w;
}
void TraceWire::setColorFromElement(QDomElement & element) {
switch (m_viewLayerID) {
case ViewLayer::Copper0Trace:
element.setAttribute("color", ViewLayer::Copper0Color);
break;
case ViewLayer::Copper1Trace:
element.setAttribute("color", ViewLayer::Copper1Color);
break;
case ViewLayer::SchematicTrace:
//element.setAttribute("color", "#000000");
default:
break;
}
Wire::setColorFromElement(element);
}
bool TraceWire::canSwitchLayers() {
QList<Wire *> wires;
QList<ConnectorItem *> ends;
collectChained(wires, ends);
if (ends.count() < 2) return false; // should never happen, since traces have to be connected at both ends
foreach (ConnectorItem * end, ends) {
if (end->getCrossLayerConnectorItem() == NULL) return false;
}
return true;
}
void TraceWire::setWireDirection(TraceWire::WireDirection wireDirection) {
m_wireDirection = wireDirection;
}
TraceWire::WireDirection TraceWire::wireDirection() {
return m_wireDirection;
}
TraceWire * TraceWire::getTrace(ConnectorItem * connectorItem)
{
return qobject_cast<TraceWire *>(connectorItem->attachedTo());
}
void TraceWire::setSchematic(bool schematic) {
m_viewGeometry.setSchematicTrace(schematic);
}
|
logxen/Fritzing
|
src/items/tracewire.cpp
|
C++
|
gpl-3.0
| 5,391
|
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-19924913-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
|
rasmusbergpalm/AESpad
|
app/webroot/js/ga.js
|
JavaScript
|
gpl-3.0
| 418
|
#include "simulation/Elements.h"
//#TPT-Directive ElementClass Element_AERO PT_AERO 186
Element_AERO::Element_AERO()
{
Identifier = "DEFAULT_PT_AERO";
Name = "AERO";
Colour = PIXPACK(0x8AA2A1);//0x8AA2A1
MenuVisible = 1;
MenuSection = SC_ALLY;
Enabled = 1;
Advection = 0.0f;
AirDrag = 0.00f * CFDS;
AirLoss = 0.5f;
Loss = 0.00f;
Collision = 0.0f;
Gravity = 0.0f;
Diffusion = 0.00f;
HotAir = -0.0000001f * CFDS;
Falldown = 0;
Flammable = 0;
Explosive = 0;
Meltable = 0;
Hardness = 0.5;
Weight = 100;
Temperature = R_TEMP + 0.0f + 273.15f;
HeatConduct = 0;
Description = "Aerogel. Powerful heat insulator.";
Properties = TYPE_SOLID;
LowPressure = IPL;
LowPressureTransition = NT;
HighPressure = IPH;
HighPressureTransition = NT;
LowTemperature = ITL;
LowTemperatureTransition = NT;
HighTemperature = 1473.15f;
HighTemperatureTransition = ST;
Update = &Element_AERO::update;
Graphics = &Element_AERO::graphics;
}
//#TPT-Directive ElementHeader Element_AERO static int update(UPDATE_FUNC_ARGS)
int Element_AERO::update(UPDATE_FUNC_ARGS)
{
int r, rx, ry, give_temp;
if (parts[i].temp > 1473.15)
{
sim->part_change_type(i, x, y, PT_GEL);
}
for (rx = -1; rx < 2; rx++)
for (ry = -1; ry < 2; ry++)
if (BOUNDS_CHECK && (rx || ry))
{
r = pmap[y + ry][x + rx];
if (!r)
continue;
if (parts[r>>8].type==PT_ARAY || parts[r>>8].type==PT_GPMP || parts[r>>8].type==PT_INSL || (parts[r>>8].type==PT_HSWC && parts[r>>8].life==0)) //Stop conduction to non-conducting elements
continue;
if (parts[i].temp - parts[r>>8].temp != 0)
{
give_temp = ((parts[i].temp - parts[r>>8].temp) / 300);
parts[i].temp = parts[i].temp - give_temp;
parts[r>>8].temp = parts[r>>8].temp + give_temp;
}
}
return 0;
}
//#TPT-Directive ElementHeader Element_AERO static int graphics(GRAPHICS_FUNC_ARGS)
int Element_AERO::graphics(GRAPHICS_FUNC_ARGS)
{
*firea = 20;
*firer = *colr;
*fireg = *colg;
*fireb = *colb;
*pixel_mode |= FIRE_ADD;
return 1;
}
Element_AERO::~Element_AERO() {}
|
RCAProduction/The-Alliance-Toy
|
src/simulation/elements/AERO.cpp
|
C++
|
gpl-3.0
| 2,075
|
package com.czw.toolkit.netty.heartbeat;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import java.nio.charset.Charset;
/**
* Created by zevi on 2017/7/3.
*/
public class Client {
public final static void main(String[] args) {
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(workerGroup).channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new StringEncoder(Charset.forName("UTF-8")));
ch.pipeline().addLast(new LoginInfoHandler());
}
})
.option(ChannelOption.SO_KEEPALIVE, true);
// 启动客户端
ChannelFuture cf = b.connect("localhost", 1000).sync();
// cf.addListener(future -> {
// if (future.isSuccess()) {
// System.out.println("重新连接服务器成功");
// } else {
// System.out.println("重新连接服务器失败");
// //doConnection();
// }
// });
// cf.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
workerGroup.shutdownGracefully();
}
}
}
|
zevichen/base
|
src/main/java/com/czw/toolkit/netty/heartbeat/Client.java
|
Java
|
gpl-3.0
| 1,894
|
/****************************************************************************
* VLC-Qt - Qt and libvlc connector library
* Copyright (C) 2013 Tadej Novak <tadej@tano.si>
*
* This library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library. If not, see <http://www.gnu.org/licenses/>.
*****************************************************************************/
#ifndef VLCQT_QMLVIDEOPLAYER_H_
#define VLCQT_QMLVIDEOPLAYER_H_
#include <QtQuick/QQuickItem>
#include "QmlVideoObject.h"
#include "SharedExportQml.h"
class VlcAudio;
class VlcInstance;
class VlcMedia;
class VlcMediaPlayer;
class VlcVideo;
/*!
\class VlcQmlVideoPlayer QmlVideoPlayer.h vlc-qt/QmlVideoPlayer.h
\brief QML video player
A simple QML video player that can be used standalone and directly inside QML.
*/
class VLCQT_QML_EXPORT VlcQmlVideoPlayer : public VlcQmlVideoObject
{
Q_OBJECT
public:
/*!
\brief Current volume
\see setVolume
\see volumeChanged
*/
Q_PROPERTY(int volume READ volume WRITE setVolume NOTIFY volumeChanged)
/*!
\brief Current aspect ratio
\see setAspectRatio
*/
Q_PROPERTY(int aspectRatio READ aspectRatio WRITE setAspectRatio)
/*!
\brief Current crop ratio
\see setCropRatio
*/
Q_PROPERTY(int cropRatio READ cropRatio WRITE setCropRatio)
/*!
\brief Current deinterlacing mode
\see setDeinterlacing
*/
Q_PROPERTY(int deinterlacing READ deinterlacing WRITE setDeinterlacing)
/*!
\brief Current media URL
\see setUrl
*/
Q_PROPERTY(QUrl url READ url WRITE setUrl)
/*!
\brief Current autoplay setting
\see setAutoplay
*/
Q_PROPERTY(bool autoplay READ autoplay WRITE setAutoplay)
/*!
\brief Current state
\see stateChanged
*/
Q_PROPERTY(int state READ state NOTIFY stateChanged)
/*!
\brief Current seekable status
\see seekableChanged
*/
Q_PROPERTY(bool seekable READ seekable NOTIFY seekableChanged)
/*!
\brief Current media length
\see length
\see lengthChanged
*/
Q_PROPERTY(int length READ length NOTIFY lengthChanged)
/*!
\brief Current media time
\see time
\see timeChanged
*/
Q_PROPERTY(int time READ time WRITE setTime NOTIFY timeChanged)
/*!
\brief Current media position
\see position
\see positionChanged
*/
Q_PROPERTY(float position READ position WRITE setPosition NOTIFY positionChanged)
/*!
\brief VlcQmlVideoPlayer constructor.
\param parent parent item (QQuickItem *)
*/
explicit VlcQmlVideoPlayer(QQuickItem *parent = 0);
/*!
VlcMediaPlayer destructor
*/
~VlcQmlVideoPlayer();
/*!
\brief Register QML plugin as VLCQt.VlcVideoPlayer
Include into QML file as
import VLCQt VERSION_MAJOR.VERSION_MINOR
Object name: VlcVideoPlayer
*/
static void registerPlugin();
/*!
\brief Pause current playback
Invokable from QML.
*/
Q_INVOKABLE void pause();
/*!
\brief Play current playback
Invokable from QML.
*/
Q_INVOKABLE void play();
/*!
\brief Stop current playback
Invokable from QML.
*/
Q_INVOKABLE void stop();
/*!
\brief Get current volume
\return current volume (int)
Used as property in QML.
*/
int volume() const;
/*!
\brief Set volume
\param volume new volume (int)
Used as property in QML.
*/
void setVolume(int volume);
/*!
\brief Get current aspect ratio
\return current aspect ratio (int)
Used as property in QML.
*/
int aspectRatio();
/*!
\brief Set aspect ratio
\param aspectRatio new aspect ratio (int)
Used as property in QML.
*/
void setAspectRatio(int aspectRatio);
/*!
\brief Get current crop ratio
\return current crop ratio (int)
Used as property in QML.
*/
int cropRatio();
/*!
\brief Set crop ratio
\param cropRatio new crop ratio (int)
Used as property in QML.
*/
void setCropRatio(int cropRatio);
/*!
\brief Get current media URL
\return current media URL (QUrl)
Used as property in QML.
*/
QUrl url() const;
/*!
\brief Set media URL
\param url new media URL (QUrl)
Used as property in QML.
*/
void setUrl(const QUrl &url);
/*!
\brief Get current autoplay setting
\return current autoplay setting (bool)
Used as property in QML.
*/
bool autoplay() const;
/*!
\brief Set autoplay setting
\param autoplay new autoplay setting (bool)
Used as property in QML.
*/
void setAutoplay(bool autoplay);
/*!
\brief Get current deinterlacing() mode
\return current deinterlacing mode (int)
Used as property in QML.
*/
int deinterlacing() const;
/*!
\brief Set deinterlacing mode
\param deinterlacing new deinterlacing mode (int)
Used as property in QML.
*/
void setDeinterlacing(int deinterlacing);
/*!
\brief Get current state
\return current state (int)
Used as property in QML.
*/
int state() const;
/*!
\brief Get current seekable status
\return current seekable status (bool)
Used as property in QML.
*/
bool seekable() const;
/*!
\brief Get current media length
\return current media length(int)
Used as property in QML.
*/
int length() const;
/*!
\brief Get current media time
\return current media time(int)
Used as property in QML.
*/
int time() const;
/*!
\brief Set current media time
\param current media time(int)
Used as property in QML.
*/
void setTime(int time);
/*!
\brief Get current media position
\return current media position from 0 to 1(float)
Used as property in QML.
*/
float position() const;
/*!
\brief Set current media position
\param position media position from 0 to 1(float)
Used as property in QML.
*/
void setPosition(float position);
signals:
/*!
\brief Volume changed signal
*/
void volumeChanged();
/*!
\brief State changed signal
*/
void stateChanged();
/*!
\brief Seekable status changed signal
*/
void seekableChanged();
/*!
\brief Length changed signal
*/
void lengthChanged();
/*!
\brief Time changed signal
*/
void timeChanged();
/*!
\brief Position changed signal
*/
void positionChanged();
private slots:
void seekableChangedPrivate(bool);
private:
void openInternal();
VlcInstance *_instance;
VlcMediaPlayer *_player;
VlcMedia *_media;
VlcAudio *_audioManager;
Vlc::Deinterlacing _deinterlacing;
bool _hasMedia;
bool _autoplay;
bool _seekable;
};
#endif // VLCQT_QMLVIDEOPLAYER_H_
|
TripleWhy/vlc-qt
|
src/qml/QmlVideoPlayer.h
|
C
|
gpl-3.0
| 7,854
|
require 'spec_helper'
require 'socket'
require 'oac'
class ServerTest < OAC::Server
end
describe OAC::Server do
before do
@server = OAC::Server.new
end
after do
begin
@server.close
rescue Exception => e
puts e
end
end
describe ".listen" do
context "given port #{RSpec.configuration.test_port}" do
it "listens on #{RSpec.configuration.test_port}" do
@server.listen RSpec.configuration.test_port
expect { TCPSocket.new("127.0.0.1", RSpec.configuration.test_port) }.to_not raise_error
end
end
context "given a random port" do
it "listens on that random port" do
port = rand(2**15) + 1024
@server.listen port
end
end
context "given an in-use port" do
it "throws a OAC::Exceptions::BindError" do
tmp_server = TCPServer.new "127.0.0.1", RSpec.configuration.test_port
expect { @server.listen RSpec.configuration.test_port }.to raise_error OAC::Exceptions::BindError
tmp_server.close rescue nil
end
end
end
describe ".close" do
context "when listening" do
it "closes the server socket" do
server = OAC::Server.new
server.listen rand(2**15) + 1024
expect { server.close }.not_to raise_error Exception
end
end
context "when not listening" do
it "throws a OAC::Exceptions::NoServer error" do
server = OAC::Server.new
expect { server.close }.to raise_error OAC::Exceptions::NoServer
end
end
end
end
|
InsanityRadio/OnAirController
|
spec/server_spec.rb
|
Ruby
|
gpl-3.0
| 1,438
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_18) on Sun Mar 21 10:29:35 CDT 2010 -->
<TITLE>
Uses of Class cern.colt.list.tint.IntListAdapter (Parallel Colt 0.9.4 - API Specification)
</TITLE>
<META NAME="date" CONTENT="2010-03-21">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class cern.colt.list.tint.IntListAdapter (Parallel Colt 0.9.4 - API Specification)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../cern/colt/list/tint/IntListAdapter.html" title="class in cern.colt.list.tint"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
<b>Parallel Colt 0.9.4</b></EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?cern/colt/list/tint/\class-useIntListAdapter.html" target="_top"><B>FRAMES</B></A>
<A HREF="IntListAdapter.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>cern.colt.list.tint.IntListAdapter</B></H2>
</CENTER>
No usage of cern.colt.list.tint.IntListAdapter
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../cern/colt/list/tint/IntListAdapter.html" title="class in cern.colt.list.tint"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
<b>Parallel Colt 0.9.4</b></EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?cern/colt/list/tint/\class-useIntListAdapter.html" target="_top"><B>FRAMES</B></A>
<A HREF="IntListAdapter.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
<font size=-1 >Jump to the <a target=_top href=http://sites.google.com/site/piotrwendykier/software/parallelcolt >Parallel Colt Homepage</a>
</BODY>
</HTML>
|
Shappiro/GEOFRAME
|
PROJECTS/oms3.proj.richards1d/src/JAVA/ParallelColt/doc/cern/colt/list/tint/class-use/IntListAdapter.html
|
HTML
|
gpl-3.0
| 6,304
|
package net.v00d00.xr.events;
/**
* Created by ian on 11/10/14.
*/
public class StopEvent {
}
|
v00d00/xr
|
app/src/main/java/net/v00d00/xr/events/StopEvent.java
|
Java
|
gpl-3.0
| 97
|
/*
* Copyright (C) 2012 Jason Gedge <http://www.gedge.ca>
*
* This file is part of the OpGraph project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package ca.gedge.opgraph.nodes.general;
import java.util.List;
import ca.gedge.opgraph.InputField;
import ca.gedge.opgraph.OpContext;
import ca.gedge.opgraph.OpNode;
import ca.gedge.opgraph.OpNodeInfo;
import ca.gedge.opgraph.OutputField;
/**
* A node that outputs a constant value.
*/
@OpNodeInfo(
name="Range",
description="Outputs a range of integers.",
category="Data Generation"
)
public class RangeNode extends OpNode {
/** Input field for the start of the output range */
public final InputField START_INPUT_FIELD = new InputField("start", "Start value of range", false, true, Number.class);
/** Input field for the end of the output range */
public final InputField END_INPUT_FIELD = new InputField("end", "End value of range", false, true, Number.class);
/** Output field for the range */
public final OutputField RANGE_OUTPUT_FIELD = new OutputField("range", "Range list", true, List.class);
/**
* Default constructor.
*/
public RangeNode() {
putField(START_INPUT_FIELD);
putField(END_INPUT_FIELD);
putField(RANGE_OUTPUT_FIELD);
}
@Override
public void operate(OpContext context) {
final int start = ((Number)context.get(START_INPUT_FIELD)).intValue();
final int end = ((Number)context.get(END_INPUT_FIELD)).intValue();
context.put(RANGE_OUTPUT_FIELD, new IntRangeList(start, end));
}
}
|
thegedge/opgraph
|
common-nodes/src/main/java/ca/gedge/opgraph/nodes/general/RangeNode.java
|
Java
|
gpl-3.0
| 2,101
|
package com.wenhaofan.common.model.base;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.IBean;
/**
* Generated by JFinal, do not modify this file.
*/
@SuppressWarnings("serial")
public abstract class BaseSession<M extends BaseSession<M>> extends Model<M> implements IBean {
public void setId(java.lang.String id) {
set("id", id);
}
public java.lang.String getId() {
return get("id");
}
public void setUserId(java.lang.Integer userId) {
set("userId", userId);
}
public java.lang.Integer getUserId() {
return get("userId");
}
public void setExpireAt(java.lang.Long expireAt) {
set("expireAt", expireAt);
}
public java.lang.Long getExpireAt() {
return get("expireAt");
}
}
|
wenhaofan/blog
|
src/main/java/com/wenhaofan/common/model/base/BaseSession.java
|
Java
|
gpl-3.0
| 777
|
<!DOCTYPE html>
<html>
<head>
<title>wait</title>
<link rel="stylesheet" type="text/css" href="../../../format.css" />
</head>
<body>
<h3>
wait <img src="../DPS.png" alt="[DPS]" align="middle" />
</h3>
<pre>lock condition <b>wait</b> -</pre>
<p>
releases <i>lock</i>, waits for <i>condition</i> to be notified by
some other execution context, and finally reacquires <i>lock</i>. The
<i>lock</i> must originally have been acquired by the current context,
which means that <a href="../w/wait.html">wait</a> can be invoked only
within the execution of a <a href="../m/monitor.html">monitor</a> that
references the same <i>lock</i> (see section <a
href="../../../DPS/1.html">7.1, "Multiple Execution Contexts"</a>).
</p>
<p>
If <i>lock</i> is initially held by some other context or is not held
by any context, an <a href="../i/invalidcontext.html">invalidcontext</a>
error occurs. On the other hand, during the wait for <i>condition</i>,
the <i>lock</i> can be acquired by some other context. After <i>condition</i>
is notified, <b>wait</b> will wait an arbitrary length of time to
reacquire <i>lock</i>.
</p>
<p>
If the current context has previously executed a <a
href="../s/save.html">save</a> not yet matched by a <a
href="../r/restore.html">restore</a>, an <a
href="../i/invalidcontext.html">invalidcontext</a> error occurs
unless both <i>lock</i> and <i>condition</i> are in global VM. The
latter case is permitted under the assumption that the <b>wait</b> is
synchronizing with some context whose local VM is different from that
of the current context.
</p>
<p>
<b>Errors:</b> <a href="../i/invalidcontext.html">invalidcontext</a>,
<a href="../s/stackunderflow.html">stackunderflow</a>, <a
href="../t/typecheck.html">typecheck</a>
</p>
<p>
<b>See Also:</b> <a href="../c/condition.html">condition</a>, <a
href="../l/lock.html">lock</a>, <a href="../m/monitor.html">monitor</a>,
<a href="../n/notify.html">notify</a>
</p>
</body>
</html>
|
thomas-fritsch/psdt
|
de.tfritsch.psdt.help/html/Reference/8/2/w/wait.html
|
HTML
|
gpl-3.0
| 2,016
|
/* ---------------------------------------------------------------------------
* Programa: muestra_vector_con_indices
* Entradas: Una serie de números
* Salidas: Los elementos del vector con sus índices asociados
* --------------------------------------------------------------------------- */
#include <iostream>
using namespace std;
int main ()
{
const int TAM = 1000; // tamaño físico
double v[TAM]; // se reserva un vector de TAM posiciones
int tam; // número de posiciones con las que se trabaja (tamaño lógico)
do {
cout << "Introduce el tamaño del vector: ";
cin >> tam;
} while (tam < 0 || tam > TAM);
for (int i = 0; i < tam; i++) {
cout << "Introduce el elemento en la posición " << i << ": ";
cin >> v[i];
}
for (int i = 0; i < tam; i++)
cout << "Posición (" << i << ") = " << v[i] << '\n';
return 0;
}
|
FundamentosProgramacionUJA/Ejercicios
|
Tema5-Tipos de datos estructurados/muestra_vector_con_indices.cc
|
C++
|
gpl-3.0
| 928
|
#!/usr/bin/python
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
#from matplotlib.backends.backend_pdf import PdfPages
import sys
def stats_file_as_matrix(file_name):
with open(file_name, 'r') as f:
return [ map(float,line.strip().split(' ')) for line in f ]
#pdfTitle = 'results.pdf'
#pp = PdfPages(pdfTitle)
titles = ["Bitrate", "Delay", "Jitter", "Packet loss"]
for f in sys.argv[1:]:
print("Starting work on "+f+", converting stats to matrix!")
mat = stats_file_as_matrix(f)
x = range(len(mat))
#define the figure size and grid layout properties
figsize = (10, 8)
cols = 2
rows = 2
gs = gridspec.GridSpec( rows, cols)
fig = plt.figure(num=1, figsize=figsize)
fig.suptitle(f)
ax = []
for i in range(4):
y = map(lambda r:r[i+1],mat)
row = (i // cols)
col = i % cols
ax.append(fig.add_subplot(gs[row, col]))
ax[-1].set_title(titles[i])
ax[-1].set_xlabel('Time [ms]')
ax[-1].plot(x, y, 'o', ls='-', ms=4)
print("Finished with "+f+", creating JPG!")
#pp.savefig(fig)
plt.savefig(f+'.jpg')
plt.clf()
#pp.close()
|
yossisolomon/ITGController
|
plot_from_stats.py
|
Python
|
gpl-3.0
| 1,136
|
package diet;
import java.util.LinkedList;
import java.util.List;
/**
* Represent a recipe of the diet.
*
* A recipe consists of a a set of ingredients that are given amounts of raw
* materials. The overall nutritional values of a recipe can be computed on the
* basis of the ingredients' values and are expressed per 100g
*
*
*/
public class Recipe implements NutritionalElement {
private String name;
private Food food;
private List<Ingredient> ingredients = new LinkedList<>();
private double totQuantity;
private double calories, proteins, carbs, fat;
private class Ingredient {
private String material;
private double quantity;
Ingredient(String material, double quantity) {
this.material = material;
this.quantity = quantity;
}
public String getMaterial() {
return material;
}
public double getQuantity() {
return quantity;
}
}
/**
* Recipe constructor. The reference {@code food} of type {@link Food} must
* be used to retrieve the information about ingredients.
*
* @param nome
* unique name of the recipe
* @param food
* object containing the information about ingredients
*/
public Recipe(String name, Food food) {
this.name = name;
this.food = food;
food.defineRecipe(name, this);
}
/**
* Adds a given quantity of an ingredient to the recipe. The ingredient is a
* raw material defined with the {@code food} argument of the constructor.
*
* @param material
* the name of the raw material to be used as ingredient
* @param quantity
* the amount in grams of the raw material to be used
*/
public void addIngredient(String material, double quantity) {
NutritionalElement tmpMaterial;
ingredients.add(new Ingredient(material, quantity));
tmpMaterial = food.getRawMaterial(material);
totQuantity += quantity;
calories += quantity / 100.0 * tmpMaterial.getCalories();
proteins += quantity / 100.0 * tmpMaterial.getProteins();
carbs += quantity / 100.0 * tmpMaterial.getCarbs();
fat += quantity / 100.0 * tmpMaterial.getFat();
}
public String getName() {
return name;
}
public double getCalories() {
return 100.0 / totQuantity * calories;
}
public double getProteins() {
return 100.0 / totQuantity * proteins;
}
public double getCarbs() {
return 100.0 / totQuantity * carbs;
}
public double getFat() {
return 100.0 / totQuantity * fat;
}
public boolean per100g() {
// a recipe expressed nutritional values per 100g
return true;
}
}
|
aerdnar/OOP
|
OOP_LAB_Diet/src/diet/Recipe.java
|
Java
|
gpl-3.0
| 2,629
|
/* eslint unused: 0 */
import test from 'ava';
import sortObject from 'deep-sort-object';
import {
templateAccount,
templateDeployment,
templateLambdaIntegration,
templateMethod,
templateModel,
templateResource,
templateResourceHelper,
templateRest,
templateStage,
templateCloudWatchRole,
templateAuthorizer
} from './cf_apig';
const requestTemplatePartial = contentType => {
return `#set($allParams = $input.params())
{
"params" : {
#foreach($type in $allParams.keySet())
#set($params = $allParams.get($type))
"$type" : {
#foreach($paramName in $params.keySet())
#if($type == "header")
"$paramName.toLowerCase()" : "$util.escapeJavaScript($params.get($paramName))"
#else
"$paramName" : "$util.escapeJavaScript($params.get($paramName))"
#end
#if($foreach.hasNext),#end
#end
}
#if($foreach.hasNext),#end
#end
},
"context" : {
"apiId": "$context.apiId",
"authorizer": {
#foreach($property in $context.authorizer.keySet())
"$property": "$context.authorizer.get($property)"
#if($foreach.hasNext),#end
#end
},
"httpMethod": "$context.httpMethod",
"identity": {
#foreach($property in $context.identity.keySet())
"$property": "$context.identity.get($property)"
#if($foreach.hasNext),#end
#end
},
"requestId": "$context.requestId",
"resourceId": "$context.resourceId",
"resourcePath": "$context.resourcePath",
"stage": "$context.stage"
},
"body": $input.json('$'),
"meta": {
"expectedResponseContentType": "${contentType}"
}
}`;
};
test('templateRest', t => {
const expected = {
API: {
Type: 'AWS::ApiGateway::RestApi',
Properties: {
Description: 'REST API for dawson app',
Name: 'AppAPIStage'
}
}
};
const actual = templateRest({ appStage: 'stage' });
t.deepEqual(
sortObject(expected),
sortObject(actual),
'should return a rest api template'
);
});
test('templateResource', t => {
t.deepEqual(
templateResource({ resourceName: 'Users', resourcePath: 'users' }),
{
ResourceUsers: {
Type: 'AWS::ApiGateway::Resource',
Properties: {
RestApiId: { Ref: 'API' },
ParentId: { 'Fn::GetAtt': ['API', 'RootResourceId'] },
PathPart: 'users'
}
}
},
'should return a resource template, which references the root api as parent'
);
t.deepEqual(
templateResource({
resourceName: 'List',
resourcePath: 'list',
parentResourceName: 'Users'
}),
{
ResourceList: {
Type: 'AWS::ApiGateway::Resource',
Properties: {
RestApiId: { Ref: 'API' },
ParentId: { Ref: 'ResourceUsers' },
PathPart: 'list'
}
}
},
'should return a resource template, which references the given parentResourceName as parent'
);
});
test('templateResourceHelper', t => {
const expected = {
resourceName: 'Bar',
templateResourcePartial: {
ResourceBar: {
Properties: {
ParentId: { Ref: 'ResourceFoo' },
PathPart: 'bar',
RestApiId: { Ref: 'API' }
},
Type: 'AWS::ApiGateway::Resource'
},
ResourceFoo: {
Properties: {
ParentId: { 'Fn::GetAtt': ['API', 'RootResourceId'] },
PathPart: 'foo',
RestApiId: { Ref: 'API' }
},
Type: 'AWS::ApiGateway::Resource'
}
}
};
const actual = templateResourceHelper({ resourcePath: 'foo/bar' });
t.deepEqual(sortObject(expected), sortObject(actual));
});
test('templateResourceHelper with non-alphanum path', t => {
const expected = {
resourceName: 'Bar',
templateResourcePartial: {
ResourceBar: {
Properties: {
ParentId: { Ref: 'ResourceBoo' },
PathPart: 'bar',
RestApiId: { Ref: 'API' }
},
Type: 'AWS::ApiGateway::Resource'
},
ResourceBoo: {
Properties: {
ParentId: { 'Fn::GetAtt': ['API', 'RootResourceId'] },
PathPart: 'bo$o',
RestApiId: { Ref: 'API' }
},
Type: 'AWS::ApiGateway::Resource'
}
}
};
const actual = templateResourceHelper({ resourcePath: 'bo$o/bar' });
t.deepEqual(sortObject(expected), sortObject(actual));
});
test('templateResourceHelper with non-alphanum path is ok', t => {
const expected = {
resourceName: 'Bar2',
templateResourcePartial: {
ResourceBar2: {
Properties: {
ParentId: { Ref: 'ResourceBoo' },
PathPart: 'bar2',
RestApiId: { Ref: 'API' }
},
Type: 'AWS::ApiGateway::Resource'
},
ResourceBoo: {
Properties: {
ParentId: { 'Fn::GetAtt': ['API', 'RootResourceId'] },
PathPart: 'bo$o',
RestApiId: { Ref: 'API' }
},
Type: 'AWS::ApiGateway::Resource'
}
}
};
const actual = templateResourceHelper({ resourcePath: 'bo$o/bar2' });
t.deepEqual(sortObject(expected), sortObject(actual));
});
test('templateResourceHelper with non-alphanum path cannot overlap existing path part', t => {
// internal algorithm maps the path /fo^o to an API Gateway Resource
// named 'Foo', which conflicts with the Resource Name mapped for
// 'fo$o' above.
t.throws(() => templateResourceHelper({ resourcePath: 'bo^o/bar' }));
});
test('path parts in braces cannot contain non-alphanum characters', t => {
t.throws(() => templateResourceHelper({ resourcePath: 'bo$o/bar/{foo%}' }));
});
test('templateResourceHelper with named params', t => {
const expected = {
resourceName: 'Bar',
templateResourcePartial: {
ResourceBar: {
Properties: {
ParentId: { Ref: 'ResourceFoo' },
PathPart: '{bar}',
RestApiId: { Ref: 'API' }
},
Type: 'AWS::ApiGateway::Resource'
},
ResourceFoo: {
Properties: {
ParentId: { 'Fn::GetAtt': ['API', 'RootResourceId'] },
PathPart: 'foo',
RestApiId: { Ref: 'API' }
},
Type: 'AWS::ApiGateway::Resource'
}
}
};
const actual = templateResourceHelper({ resourcePath: 'foo/{bar}' });
t.deepEqual(sortObject(expected), sortObject(actual));
});
test('templateResourceHelper with empty path', t => {
const expected = {
resourceName: null, // this will cause Resourcenull to be created
templateResourcePartial: {}
};
const actual = templateResourceHelper({ resourcePath: '' });
t.deepEqual(sortObject(expected), sortObject(actual));
});
test('templateModel', t => {
const expected = {
ModelCustomResponse: {
Type: 'AWS::ApiGateway::Model',
Properties: {
ContentType: 'application/json',
Description: `Model CustomResponse`,
RestApiId: { Ref: 'API' },
Schema: {}
}
}
};
const actual = templateModel({
modelName: 'CustomResponse',
modelSchema: {}
});
t.deepEqual(sortObject(expected), sortObject(actual), 'should return');
});
test('templateLambdaIntegration with custom ContentType', t => {
const expected = {
IntegrationHttpMethod: 'POST',
IntegrationResponses: [
{
ResponseParameters: {},
ResponseTemplates: {
'text/x-beer': `#set($inputRoot = $input.path('$'))
$inputRoot.response`
},
StatusCode: 200
},
{
ResponseParameters: {},
ResponseTemplates: {
'text/x-beer': `#set ($errorMessageObj = $util.parseJson($input.path('$.errorMessage')))
$errorMessageObj.response`
},
SelectionPattern: '.*"httpStatus":500.*',
StatusCode: 500
},
{
ResponseParameters: {},
ResponseTemplates: {
'text/x-beer': `#set ($errorMessageObj = $util.parseJson($input.path('$.errorMessage')))
$errorMessageObj.response`
},
SelectionPattern: '.*"httpStatus":400.*',
StatusCode: 400
},
{
ResponseParameters: {},
ResponseTemplates: {
'text/x-beer': `#set ($errorMessageObj = $util.parseJson($input.path('$.errorMessage')))
$errorMessageObj.response`
},
SelectionPattern: '.*"httpStatus":403.*',
StatusCode: 403
},
{
ResponseParameters: {},
ResponseTemplates: {
'text/x-beer': `#set ($errorMessageObj = $util.parseJson($input.path('$.errorMessage')))
$errorMessageObj.response`
},
SelectionPattern: '.*"httpStatus":404.*',
StatusCode: 404
}
],
PassthroughBehavior: 'NEVER',
RequestTemplates: {
'application/json': requestTemplatePartial('text/x-beer'),
'application/x-www-form-urlencoded': requestTemplatePartial('text/x-beer')
},
Type: 'AWS',
Uri: {
'Fn::Join': [
'',
[
'arn:aws:apigateway:',
{ Ref: 'AWS::Region' },
':lambda:path/2015-03-31/functions/',
{ 'Fn::GetAtt': ['Lambdabarman', 'Arn'] },
'/invocations'
]
]
}
};
const actual = templateLambdaIntegration({
lambdaName: 'barman',
responseContentType: 'text/x-beer',
redirects: false
});
t.deepEqual(sortObject(expected), sortObject(actual), 'should return');
});
test('templateLambdaIntegration with ContentType = application/json', t => {
const expected = {
IntegrationHttpMethod: 'POST',
IntegrationResponses: [
{
ResponseParameters: {},
ResponseTemplates: {
'application/json': `#set($inputRoot = $input.path('$'))
$inputRoot.response`
},
StatusCode: 200
},
{
ResponseParameters: {},
ResponseTemplates: {
'application/json': `$input.path('$.errorMessage')`
},
SelectionPattern: '.*"httpStatus":500.*',
StatusCode: 500
},
{
ResponseParameters: {},
ResponseTemplates: {
'application/json': `$input.path('$.errorMessage')`
},
SelectionPattern: '.*"httpStatus":400.*',
StatusCode: 400
},
{
ResponseParameters: {},
ResponseTemplates: {
'application/json': `$input.path('$.errorMessage')`
},
SelectionPattern: '.*"httpStatus":403.*',
StatusCode: 403
},
{
ResponseParameters: {},
ResponseTemplates: {
'application/json': `$input.path('$.errorMessage')`
},
SelectionPattern: '.*"httpStatus":404.*',
StatusCode: 404
}
],
PassthroughBehavior: 'NEVER',
RequestTemplates: {
'application/json': requestTemplatePartial('application/json'),
'application/x-www-form-urlencoded': requestTemplatePartial(
'application/json'
)
},
Type: 'AWS',
Uri: {
'Fn::Join': [
'',
[
'arn:aws:apigateway:',
{ Ref: 'AWS::Region' },
':lambda:path/2015-03-31/functions/',
{ 'Fn::GetAtt': ['Lambdabarman', 'Arn'] },
'/invocations'
]
]
}
};
const actual = templateLambdaIntegration({
lambdaName: 'barman',
responseContentType: 'application/json',
redirects: false
});
t.deepEqual(sortObject(expected), sortObject(actual), 'should return');
});
test('templateLambdaIntegration with redirect = true', t => {
const expected = {
IntegrationHttpMethod: 'POST',
IntegrationResponses: [
{
ResponseParameters: {
'method.response.header.Location': 'integration.response.body.response.Location'
},
ResponseTemplates: {
'text/plain': `#set($inputRoot = $input.path('$'))
You are being redirected to $inputRoot.response.Location`
},
StatusCode: 307
},
{
ResponseParameters: {
'method.response.header.Location': 'integration.response.body.response.Location'
},
ResponseTemplates: {
'text/plain': `Cannot redirect because of an error`
},
SelectionPattern: '.*"httpStatus":500.*',
StatusCode: 500
},
{
ResponseParameters: {
'method.response.header.Location': 'integration.response.body.response.Location'
},
ResponseTemplates: {
'text/plain': `Cannot redirect because of an error`
},
SelectionPattern: '.*"httpStatus":400.*',
StatusCode: 400
},
{
ResponseParameters: {
'method.response.header.Location': 'integration.response.body.response.Location'
},
ResponseTemplates: {
'text/plain': `Cannot redirect because of an error`
},
SelectionPattern: '.*"httpStatus":403.*',
StatusCode: 403
},
{
ResponseParameters: {
'method.response.header.Location': 'integration.response.body.response.Location'
},
ResponseTemplates: {
'text/plain': `Cannot redirect because of an error`
},
SelectionPattern: '.*"httpStatus":404.*',
StatusCode: 404
}
],
PassthroughBehavior: 'NEVER',
RequestTemplates: {
'application/json': requestTemplatePartial('text/plain'),
'application/x-www-form-urlencoded': requestTemplatePartial('text/plain')
},
Type: 'AWS',
Uri: {
'Fn::Join': [
'',
[
'arn:aws:apigateway:',
{ Ref: 'AWS::Region' },
':lambda:path/2015-03-31/functions/',
{ 'Fn::GetAtt': ['Lambdabarman', 'Arn'] },
'/invocations'
]
]
}
};
const actual = templateLambdaIntegration({
lambdaName: 'barman',
responseContentType: 'application/json',
redirects: true
});
t.deepEqual(sortObject(expected), sortObject(actual), 'should return');
});
test('templateMethod with an authorizer', t => {
const expected = {
APIGAuthorizerDemoBarAuthorizer: {
Properties: {
AuthorizerResultTtlInSeconds: 0,
AuthorizerUri: {
'Fn::Sub': 'arn:aws:apigateway:\x24{AWS::Region}:lambda:path//2015-03-31/functions/\x24{LambdaDemoBarAuthorizer.Arn}/invocations'
},
IdentitySource: 'method.request.header.token',
Name: 'APIGAuthorizerDemoBarAuthorizer',
RestApiId: { Ref: 'API' },
Type: 'TOKEN'
},
Type: 'AWS::ApiGateway::Authorizer'
},
MethodRootGET: {
DependsOn: ['APIGAuthorizerDemoBarAuthorizer'],
Properties: {
AuthorizationType: 'CUSTOM',
AuthorizerId: { Ref: 'APIGAuthorizerDemoBarAuthorizer' },
HttpMethod: 'GET',
Integration: {
IntegrationHttpMethod: 'POST',
IntegrationResponses: [
{
ResponseParameters: {},
ResponseTemplates: {
'text/x-bar': `#set($inputRoot = $input.path('$'))
$inputRoot.response`
},
StatusCode: 200
},
{
ResponseParameters: {},
ResponseTemplates: {
'text/x-bar': `#set ($errorMessageObj = $util.parseJson($input.path('$.errorMessage')))
$errorMessageObj.response`
},
SelectionPattern: '.*"httpStatus":500.*',
StatusCode: 500
},
{
ResponseParameters: {},
ResponseTemplates: {
'text/x-bar': `#set ($errorMessageObj = $util.parseJson($input.path('$.errorMessage')))
$errorMessageObj.response`
},
SelectionPattern: '.*"httpStatus":400.*',
StatusCode: 400
},
{
ResponseParameters: {},
ResponseTemplates: {
'text/x-bar': `#set ($errorMessageObj = $util.parseJson($input.path('$.errorMessage')))
$errorMessageObj.response`
},
SelectionPattern: '.*"httpStatus":403.*',
StatusCode: 403
},
{
ResponseParameters: {},
ResponseTemplates: {
'text/x-bar': `#set ($errorMessageObj = $util.parseJson($input.path('$.errorMessage')))
$errorMessageObj.response`
},
SelectionPattern: '.*"httpStatus":404.*',
StatusCode: 404
}
],
PassthroughBehavior: 'NEVER',
RequestTemplates: {
'application/json': requestTemplatePartial('text/x-bar'),
'application/x-www-form-urlencoded': requestTemplatePartial(
'text/x-bar'
)
},
Type: 'AWS',
Uri: {
'Fn::Join': [
'',
[
'arn:aws:apigateway:',
{ Ref: 'AWS::Region' },
':lambda:path/2015-03-31/functions/',
{ 'Fn::GetAtt': ['LambdafooBarGet', 'Arn'] },
'/invocations'
]
]
}
},
MethodResponses: [
{
ResponseModels: { 'text/x-bar': { Ref: 'ModelHelloWorldModel' } },
StatusCode: 200
},
{
ResponseModels: { 'text/x-bar': { Ref: 'ModelHelloWorldModel' } },
StatusCode: 400
},
{
ResponseModels: { 'text/x-bar': { Ref: 'ModelHelloWorldModel' } },
StatusCode: 403
},
{
ResponseModels: { 'text/x-bar': { Ref: 'ModelHelloWorldModel' } },
StatusCode: 404
},
{
ResponseModels: { 'text/x-bar': { Ref: 'ModelHelloWorldModel' } },
StatusCode: 500
},
{
ResponseModels: { 'text/x-bar': { Ref: 'ModelHelloWorldModel' } },
ResponseParameters: { 'method.response.header.Location': false },
StatusCode: 307
}
],
ResourceId: { 'Fn::GetAtt': ['API', 'RootResourceId'] },
RestApiId: { Ref: 'API' }
},
Type: 'AWS::ApiGateway::Method'
},
ModelHelloWorldModel: {
Properties: {
ContentType: 'application/json',
Description: 'Model HelloWorldModel',
RestApiId: { Ref: 'API' },
Schema: '{}'
},
Type: 'AWS::ApiGateway::Model'
}
};
const actual = templateMethod({
lambdaName: 'fooBarGet',
responseContentType: 'text/x-bar',
authorizerFunctionName: 'demoBarAuthorizer',
redirects: false
});
t.deepEqual(sortObject(expected), sortObject(actual), 'should return');
});
test('templateMethod without an authorizer', t => {
const expected = {
MethodbarpathGET: {
Properties: {
AuthorizationType: 'NONE',
HttpMethod: 'GET',
Integration: {
IntegrationHttpMethod: 'POST',
IntegrationResponses: [
{
ResponseParameters: {},
ResponseTemplates: {
'application/json': `#set($inputRoot = $input.path('$'))
$inputRoot.response`
},
StatusCode: 200
},
{
ResponseParameters: {},
ResponseTemplates: {
'application/json': `$input.path('$.errorMessage')`
},
SelectionPattern: '.*"httpStatus":500.*',
StatusCode: 500
},
{
ResponseParameters: {},
ResponseTemplates: {
'application/json': `$input.path('$.errorMessage')`
},
SelectionPattern: '.*"httpStatus":400.*',
StatusCode: 400
},
{
ResponseParameters: {},
ResponseTemplates: {
'application/json': `$input.path('$.errorMessage')`
},
SelectionPattern: '.*"httpStatus":403.*',
StatusCode: 403
},
{
ResponseParameters: {},
ResponseTemplates: {
'application/json': `$input.path('$.errorMessage')`
},
SelectionPattern: '.*"httpStatus":404.*',
StatusCode: 404
}
],
PassthroughBehavior: 'NEVER',
RequestTemplates: {
'application/json': requestTemplatePartial('application/json'),
'application/x-www-form-urlencoded': requestTemplatePartial(
'application/json'
)
},
Type: 'AWS',
Uri: {
'Fn::Join': [
'',
[
'arn:aws:apigateway:',
{ Ref: 'AWS::Region' },
':lambda:path/2015-03-31/functions/',
{ 'Fn::GetAtt': ['LambdafooBarGet', 'Arn'] },
'/invocations'
]
]
}
},
MethodResponses: [
{
ResponseModels: {
'application/json': { Ref: 'ModelHelloWorldModel' }
},
StatusCode: 200
},
{
ResponseModels: {
'application/json': { Ref: 'ModelHelloWorldModel' }
},
StatusCode: 400
},
{
ResponseModels: {
'application/json': { Ref: 'ModelHelloWorldModel' }
},
StatusCode: 403
},
{
ResponseModels: {
'application/json': { Ref: 'ModelHelloWorldModel' }
},
StatusCode: 404
},
{
ResponseModels: {
'application/json': { Ref: 'ModelHelloWorldModel' }
},
StatusCode: 500
},
{
ResponseModels: {
'application/json': { Ref: 'ModelHelloWorldModel' }
},
ResponseParameters: { 'method.response.header.Location': false },
StatusCode: 307
}
],
ResourceId: { Ref: 'Resourcebarpath' },
RestApiId: { Ref: 'API' }
},
Type: 'AWS::ApiGateway::Method'
},
ModelHelloWorldModel: {
Properties: {
ContentType: 'application/json',
Description: 'Model HelloWorldModel',
RestApiId: { Ref: 'API' },
Schema: '{}'
},
Type: 'AWS::ApiGateway::Model'
}
};
const actual = templateMethod({
lambdaName: 'fooBarGet',
responseContentType: 'application/json',
resourceName: 'barpath',
redirects: false
});
t.deepEqual(sortObject(expected), sortObject(actual), 'should return');
});
test('templateDeployment', t => {
const expected = {
Deployment1234ABC: {
DependsOn: ['MethodUsersGET'],
Type: 'AWS::ApiGateway::Deployment',
Properties: {
RestApiId: { Ref: 'API' },
Description: `Automated deployment by dawson`
}
}
};
const actual = templateDeployment({
deploymentUid: '1234ABC',
dependsOnMethods: [{ resourceName: 'Users', httpMethod: 'GET' }]
});
t.deepEqual(
sortObject(expected),
sortObject(actual),
'should return the deployment template'
);
});
test('templateStage', t => {
const expected = {
StageProd: {
Type: 'AWS::ApiGateway::Stage',
Properties: {
CacheClusterEnabled: false,
DeploymentId: { Ref: 'Deployment1234567' },
Description: 'prod Stage',
RestApiId: { Ref: 'API' },
StageName: 'prod',
MethodSettings: [
{
HttpMethod: '*',
ResourcePath: '/*',
LoggingLevel: 'INFO',
DataTraceEnabled: 'true'
}
]
}
}
};
const actual = templateStage({ stageName: 'prod', deploymentUid: '1234567' });
t.deepEqual(
sortObject(expected),
sortObject(actual),
'should return the stage template'
);
});
test('templateAccount', t => {
const expected = {
APIGatewayAccount: {
Type: 'AWS::ApiGateway::Account',
Properties: {
CloudWatchRoleArn: { 'Fn::Sub': '\x24{RoleAPIGatewayAccount.Arn}' }
}
},
RoleAPIGatewayAccount: {
Properties: {
AssumeRolePolicyDocument: {
Statement: [
{
Action: 'sts:AssumeRole',
Effect: 'Allow',
Principal: { Service: ['apigateway.amazonaws.com'] }
}
],
Version: '2012-10-17'
},
ManagedPolicyArns: [
'arn:aws:iam::aws:policy/service-role/AmazonAPIGatewayPushToCloudWatchLogs'
],
Path: '/'
},
Type: 'AWS::IAM::Role'
}
};
const actual = templateAccount();
t.deepEqual(
sortObject(expected),
sortObject(actual),
'should return the stage template'
);
});
test('templateCloudWatchRole', t => {
const expected = {
RoleAPIGatewayAccount: {
Properties: {
AssumeRolePolicyDocument: {
Statement: [
{
Action: 'sts:AssumeRole',
Effect: 'Allow',
Principal: { Service: ['apigateway.amazonaws.com'] }
}
],
Version: '2012-10-17'
},
ManagedPolicyArns: [
'arn:aws:iam::aws:policy/service-role/AmazonAPIGatewayPushToCloudWatchLogs'
],
Path: '/'
},
Type: 'AWS::IAM::Role'
}
};
const actual = templateCloudWatchRole();
t.deepEqual(
actual,
expected,
'should return an API Gateway role with push access to CloudWatch Logs'
);
});
test('templateAuthorizer', t => {
const expected = {
APIGAuthorizerFooBar: {
Properties: {
AuthorizerResultTtlInSeconds: 0,
AuthorizerUri: {
'Fn::Sub': 'arn:aws:apigateway:\x24{AWS::Region}:lambda:path//2015-03-31/functions/\x24{LambdaFooBar.Arn}/invocations'
},
IdentitySource: 'method.request.header.token',
Name: 'APIGAuthorizerFooBar',
RestApiId: { Ref: 'API' },
Type: 'TOKEN'
},
Type: 'AWS::ApiGateway::Authorizer'
}
};
const actual = templateAuthorizer({ authorizerFunctionName: 'fooBar' });
t.deepEqual(
expected,
actual,
'should return an API Gateway Authorizer template'
);
});
|
dawson-org/dawson-cli
|
src/factories/cf_apig.spec.js
|
JavaScript
|
gpl-3.0
| 26,162
|
#include<bits/stdc++.h>
using namespace std;
const int maxn=233;
typedef long double LD;
const LD eps=1e-15;
LD A[maxn][maxn];
void print(int n){
for(int i=1;i<=n;i++){
for(int j=0;j<=n;j++)
printf("%.3Lf ",A[i][j]);
puts("");
}
puts("");
}
int id[maxn],pos[maxn];
void Gauss(int n){
//print(n);
int now=1;
for(int i=1;i<=n;i++){
int r=now;
for(int j=now;j<=n;j++){
if(fabs(A[r][i])<fabs(A[j][i])){
r=j;
}
}
if(fabs(A[r][i])<eps)
continue;
pos[now]=i;
swap(A[r],A[now]);
// cerr<<i<<endl;
// assert(fabs(A[i][i])>1e-8);
//print(n);
for(int j=now+1;j<=n;j++){
LD t=A[j][i]/A[now][i];
for(int k=0;k<=n;k++){
A[j][k]-=A[now][k]*t;
}
}
now++;
//print(n);
}
for(int i=n;i>=1;i--){
for(int j=pos[i]+1;j<=n;j++)if(fabs(A[i][j])>eps)
A[i][0]-=A[i][j]*A[j][0];
A[i][0]/=A[i][pos[i]];
A[i][pos[i]]/=A[i][pos[i]];
}
//print(n);
}
LD a,b,c,d,r;
int n,m;
int main(){
int T;cin>>T;
while(T--){
cin>>n>>m>>a>>b>>c>>d>>r;
memset(A,0,sizeof A);
for(int i=-m;i<=m;i++){
id[i+m+1]=i+m+1;
int nxt;
LD t=(LD)i/m;
if(i<=0){
nxt=-m-2*i;
A[i +m+1][i +m+1]+=1;
A[i +m+1][nxt +m+1]+= - (b+r*t*t)/r;
A[i +m+1][0]+=a/r;
}else{
nxt=m-2*i;
A[i +m+1][i +m+1]+=1;
A[i +m+1][nxt +m+1]+= - (d+r*t*t)/r;
A[i +m+1][0]+=c/r;
}
}
Gauss(2*m+1);
int ps=0;
for(int i=1;i<=2*m+1;i++)
if(::pos[i]==n+m+1)
ps=i;
assert(ps);
printf("%.20f\n",(double)A[ps][0]);
}
return 0;
}
|
kzoacn/Grimoire
|
Training/11.25/D.cpp
|
C++
|
gpl-3.0
| 1,523
|
#ifdef EXPORT_3DS
#include "LD3dsExporter.h"
#include <LDLoader/LDLMainModel.h>
#include <LDLoader/LDLModelLine.h>
#include <LDLoader/LDLTriangleLine.h>
#include <LDLoader/LDLQuadLine.h>
#include <LDLoader/LDLPalette.h>
#include <lib3ds.h>
#if defined WIN32 && defined(_MSC_VER) && _MSC_VER >= 1400 && defined(_DEBUG)
#define new DEBUG_CLIENTBLOCK
#endif
LD3dsExporter::LD3dsExporter(void):
LDExporter("3dsExporter/")
{
loadSettings();
}
LD3dsExporter::~LD3dsExporter(void)
{
}
void LD3dsExporter::initSettings(void) const
{
addSetting(LDExporterSetting(ls(_UC("3dsSeams")), m_seams,
udKey("Seams").c_str()));
LDExporterSetting *pGroup = &m_settings.back();
addSetting(pGroup, LDExporterSetting(ls(_UC("3dsSeamWidth")), m_seamWidth,
udKey("SeamWidth").c_str()));
}
void LD3dsExporter::dealloc(void)
{
LDExporter::dealloc();
}
ucstring LD3dsExporter::getTypeDescription(void) const
{
return ls(_UC("3dsTypeDescription"));
}
void LD3dsExporter::loadSettings(void)
{
LDExporter::loadSettings();
m_seams = boolForKey("Seams", true);
m_seamWidth = floatForKey("SeamWidth", 0.5);
//m_includeCamera = boolForKey("IncludeCamera", true);
}
int LD3dsExporter::getMaterial(int colorNumber)
{
IntIntMap::iterator it = m_colorNumbers.find(colorNumber);
if (it == m_colorNumbers.end())
{
int material = (int)m_colorNumbers.size();
Lib3dsMaterial *mat = lib3ds_material_new((std::string("ldraw_") +
ltostr(colorNumber)).c_str());
lib3ds_file_insert_material(m_file, mat, -1);
int r, g, b, a;
LDLPalette *pPalette = m_topModel->getMainModel()->getPalette();
pPalette->getRGBA(colorNumber, r, g, b, a);
LDLColorInfo colorInfo = pPalette->getAnyColorInfo(colorNumber);
mat->diffuse[0] = r / 255.0f;
mat->diffuse[1] = g / 255.0f;
mat->diffuse[2] = b / 255.0f;
mat->transparency = 1.0f - a / 255.0f;
mat->two_sided = 1;
if (colorInfo.rubber)
{
mat->specular[0] = mat->specular[1] = mat->specular[2] = 0.05f;
}
mat->shading = LIB3DS_SHADING_PHONG;
m_colorNumbers[colorNumber] = material;
return material;
}
else
{
return it->second;
}
}
void LD3dsExporter::writeTriangle(
VertexVector &vecVertices,
FaceVector &vecFaces,
const TCVector *points,
int i0,
int i1,
int i2,
int colorNumber,
const TCFloat *matrix)
{
int ix[3];
int voffset = (int)vecVertices.size();
int foffset = (int)vecFaces.size();
ix[0] = i0;
ix[1] = i1;
ix[2] = i2;
vecVertices.resize(vecVertices.size() + 3);
vecFaces.resize(vecFaces.size() + 1);
for (int i = 0; i < 3; i++)
{
TCVector vector = points[ix[i]];
vector = vector.transformPoint(matrix);
vecVertices[voffset + i].v[0] = vector[0];
vecVertices[voffset + i].v[1] = vector[1];
vecVertices[voffset + i].v[2] = vector[2];
vecFaces[foffset].index[i] = (unsigned short)(voffset + i);
vecFaces[foffset].material = getMaterial(colorNumber);
}
}
bool LD3dsExporter::shouldFlipWinding(
bool bfc,
bool invert,
LDLShapeLine *pShapeLine)
{
if (bfc)
{
if (invert)
{
return pShapeLine->getBFCWindingCCW();
}
else
{
return !pShapeLine->getBFCWindingCCW();
}
}
else
{
return invert;
}
}
void LD3dsExporter::writeShapeLine(
VertexVector &vecVertices,
FaceVector &vecFaces,
LDLShapeLine *pShapeLine,
const TCFloat *matrix,
int colorNumber,
bool bfc,
bool invert)
{
if (pShapeLine->getColorNumber() != 16)
{
colorNumber = pShapeLine->getColorNumber();
}
if (shouldFlipWinding(bfc, invert, pShapeLine))
{
writeTriangle(vecVertices, vecFaces, pShapeLine->getPoints(), 2, 1, 0,
colorNumber, matrix);
}
else
{
writeTriangle(vecVertices, vecFaces, pShapeLine->getPoints(), 0, 1, 2,
colorNumber, matrix);
}
if (pShapeLine->getNumPoints() > 3)
{
if (shouldFlipWinding(bfc, invert, pShapeLine))
{
writeTriangle(vecVertices, vecFaces, pShapeLine->getPoints(),
3, 2, 0, colorNumber, matrix);
}
else
{
writeTriangle(vecVertices, vecFaces, pShapeLine->getPoints(),
0, 2, 3, colorNumber, matrix);
}
}
}
std::string LD3dsExporter::getMeshName(LDLModel *model, Lib3dsMesh *&pMesh)
{
std::string modelName;
std::string meshName = "LDXM_";
StringIntMap::iterator it;
int index;
if (model != NULL)
{
char *filename = filenameFromPath(model->getFilename());
size_t dotSpot;
modelName = filename;
dotSpot = modelName.rfind('.');
delete filename;
if (dotSpot < modelName.size())
{
modelName = modelName.substr(0, dotSpot);
}
}
else
{
modelName = "no_name";
}
it = m_names.find(modelName);
if (it == m_names.end())
{
index = (int)m_names.size() + 1;
meshName += ltostr(index);
pMesh = NULL;
}
else
{
index = it->second;
meshName += ltostr(index);
pMesh = m_meshes[meshName];
}
//m_names[modelName] = index;
return meshName;
}
void LD3dsExporter::doExport(
LDLModel *pModel,
Lib3dsNode * /*pParentNode*/,
const TCFloat *matrix,
int colorNumber,
bool inPart,
bool bfc,
bool invert)
{
LDLFileLineArray *pFileLines = pModel->getFileLines();
if (pFileLines != NULL)
{
BFCState newBfcState = pModel->getBFCState();
int count = pModel->getActiveLineCount();
std::string meshName;
Lib3dsMesh *pMesh = NULL;
Lib3dsNode *pChildNode = NULL;
// Lib3dsMeshInstanceNode *pInst;
bool linesInvert = invert;
bool isNew = false;
if (TCVector::determinant(matrix) < 0.0f)
{
linesInvert = !linesInvert;
}
bfc = (bfc && newBfcState == BFCOnState) ||
newBfcState == BFCForcedOnState;
meshName.resize(128);
sprintf(&meshName[0], "m_%06d", ++m_meshCount);
// meshName = getMeshName(pModel, pMesh);
if (pMesh == NULL)
{
pMesh = lib3ds_mesh_new(meshName.c_str());
// memcpy(pMesh->matrix, matrix, sizeof(pMesh->matrix));
m_meshes[meshName] = pMesh;
lib3ds_file_insert_mesh(m_file, pMesh, -1);
isNew = true;
}
// pInst = lib3ds_node_new_mesh_instance(pMesh,
// NULL/*(meshName + "n").c_str()*/, NULL, NULL, NULL);
// pChildNode = (Lib3dsNode *)pInst;
// memcpy(pChildNode->matrix, matrix, sizeof(float) * 16);
// lib3ds_file_append_node(m_file, pChildNode, pParentNode);
VertexVector vecVertices;
FaceVector vecFaces;
for (int i = 0; i < count; i++)
{
LDLFileLine *pFileLine = (*pFileLines)[i];
if (!pFileLine->isValid())
{
continue;
}
switch (pFileLine->getLineType())
{
case LDLLineTypeTriangle:
case LDLLineTypeQuad:
writeShapeLine(vecVertices, vecFaces, (LDLShapeLine *)pFileLine,
matrix, colorNumber, bfc, linesInvert);
break;
case LDLLineTypeModel:
{
LDLModelLine *pModelLine = (LDLModelLine *)pFileLine;
LDLModel *pOtherModel = pModelLine->getModel(true);
if (pOtherModel != NULL)
{
TCFloat newMatrix[16];
int otherColorNumber = pModelLine->getColorNumber();
bool otherInPart = inPart;
bool otherInvert = invert;
if (pModelLine->getBFCInvert())
{
otherInvert = !otherInvert;
}
if (otherColorNumber == 16)
{
otherColorNumber = colorNumber;
}
TCVector::multMatrix(matrix, pModelLine->getMatrix(),
newMatrix);
if (!inPart && pOtherModel->isPart() && m_seams)
{
TCVector min, max;
TCFloat seamMatrix[16];
TCFloat tempMatrix[16];
pOtherModel->getBoundingBox(min, max);
TCVector::calcScaleMatrix(m_seamWidth, seamMatrix,
min, max);
TCVector::multMatrix(newMatrix, seamMatrix,
tempMatrix);
memcpy(newMatrix, tempMatrix, sizeof(newMatrix));
otherInPart = true;
}
doExport(pOtherModel, pChildNode, newMatrix,
otherColorNumber, otherInPart, bfc, otherInvert);
}
}
break;
default:
// Get rid of warning
break;
}
}
if (isNew && vecVertices.size() > 0)
{
lib3ds_mesh_resize_vertices(pMesh, (int)vecVertices.size(), 0, 0);
memcpy(pMesh->vertices, &vecVertices[0],
sizeof(vecVertices[0]) * vecVertices.size());
lib3ds_mesh_resize_faces(pMesh, (int)vecFaces.size());
memcpy(pMesh->faces, &vecFaces[0],
sizeof(vecFaces[0]) * vecFaces.size());
}
else
{
--m_meshCount;
}
}
}
int LD3dsExporter::doExport(LDLModel *pTopModel)
{
int retVal = 1;
TCFloat matrix[16];
TCVector::initIdentityMatrix(matrix);
matrix[5] = 0.0;
matrix[6] = -1.0;
matrix[9] = 1.0;
matrix[10] = 0.0;
m_topModel = pTopModel;
m_file = lib3ds_file_new();
m_names.clear();
m_meshes.clear();
m_meshCount = 0;
doExport(pTopModel, NULL, matrix, 7, false, true, false);
//if (m_includeCamera)
//{
// Lib3dsCamera *pCamera = lib3ds_camera_new("Default");
// Lib3dsCameraNode *pCameraNode;
// TCVector cameraLoc(m_camera.getPosition().transformPoint(matrix));
// pCamera->position[0] = cameraLoc[0];
// pCamera->position[1] = cameraLoc[1];
// pCamera->position[2] = cameraLoc[2];
// pCamera->fov = m_fov;
// pCameraNode = lib3ds_node_new_camera(pCamera);
// lib3ds_file_append_node(m_file, (Lib3dsNode *)pCameraNode, NULL);
//}
if (!lib3ds_file_save(m_file, m_filename.c_str()))
{
retVal = 0;
}
lib3ds_file_free(m_file);
return retVal;
}
#endif // EXPORT_3DS
|
wangguojing/pokomodel
|
samples/LDView/LDExporter/LD3dsExporter.cpp
|
C++
|
gpl-3.0
| 9,075
|
#ifndef VARIABLETERM_H
#define VARIABLETERM_H
#include"basicterm.h"
#include"valuebase.h"
#include"value.h"
#include<string>
#include<QString>
#include<map>
using Xeml::Document::BasicTerm;
namespace Xeml {
namespace Document{
class VariableTerm : public BasicTerm
{
private:
std::map<ValueBase*,QString> * valuecollection;
public:
VariableTerm();
VariableTerm(QString _id);
~VariableTerm();
std::map<ValueBase*,QString> * get_valuecollection();
void add_value(ValueBase * _value);
};
}
}
#endif // VARIABLETERM_H
|
cbib/XEML-Lab
|
Src/XemlLab/XemlCore/CoreObjects/variableterm.h
|
C
|
gpl-3.0
| 579
|
#include "insertion.h"
#include "factory.h"
#include <chrono>
#include <thread>
static registrar<insertion> r;
insertion::insertion(int d) :
sorter(d)
{
}
insertion::~insertion()
{
}
void insertion::operator()(wrapper& v) {
for (int i = 1; i < v.size(); i++) {
int j = i;
const unsigned int tmp = v[j];
while (j > 0 && v[j-1] > tmp) {
v[j] = v[j - 1];
j--;
}
v[j] = tmp;
std::this_thread::sleep_for(std::chrono::microseconds(_delay));
}
}
void insertion::reg() {
auto f = factory<sorter>::getInstance();
f->reg("insertion",
[]() -> std::shared_ptr<sorter> { return std::make_shared<insertion>(insertion(10)); } );
}
|
dagon666/sortviz
|
insertion.cpp
|
C++
|
gpl-3.0
| 651
|
package host.serenity.serenity.api.command;
import host.serenity.serenity.Serenity;
import host.serenity.serenity.api.command.parser.CommandBranch;
import host.serenity.serenity.api.command.parser.CommandContext;
import host.serenity.serenity.api.command.parser.argument.CommandArgument;
import host.serenity.serenity.api.command.parser.argument.impl.StringArgument;
import net.minecraft.client.Minecraft;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public abstract class Command {
protected final Minecraft mc = Minecraft.getMinecraft();
private final String commandName;
protected final List<CommandBranch> branches = new ArrayList<>();
public Command(String commandName) {
this.commandName = commandName;
}
protected Command() {
this.commandName = this.getClass().getSimpleName().toLowerCase();
}
public String getCommandName() {
return commandName;
}
@SuppressWarnings("unchecked")
public final void execute(CommandSender sender, String[] args) {
List<CommandBranch> viableBranches = getViableBranches(args, true);
if (viableBranches.size() > 1) {
viableBranches = getViableBranches(args, false);
}
if (viableBranches.size() == 1) {
CommandBranch branch = viableBranches.get(0);
int numberOfArguments = (branch.getIdentifier() != null) ? branch.getArguments().size() + 1 : branch.getArguments().size();
boolean isFinalStringArgument = (args.length > numberOfArguments &&
branch.getArguments().size() >= 1 &&
branch.getArguments().get(branch.getArguments().size() - 1) instanceof StringArgument);
List<String> rawArgsList = new ArrayList<>(Arrays.asList(args));
if (branch.getIdentifier() != null)
rawArgsList.remove(0);
CommandContext context = new CommandContext(sender, rawArgsList.toArray(new String[rawArgsList.size()]));
if (branch.getArguments().size() == 0) {
branch.accept(context);
} else {
for (int i = (branch.getIdentifier() != null ? 1 : 0); i < args.length; i++) {
final String argument = args[i];
if (i == numberOfArguments - 1 && isFinalStringArgument) {
StringBuilder argumentStringBuilder = new StringBuilder();
for (int j = i; j < args.length; j++) {
argumentStringBuilder.append(args[j]).append(" ");
}
argumentStringBuilder.setLength(argumentStringBuilder.length() - 1); // Remove final ' ' character.
StringArgument stringArgument = (StringArgument) branch.getArguments().get(branch.getArguments().size() - 1);
context.getArguments().put(stringArgument, argumentStringBuilder.toString());
break;
}
CommandArgument commandArgument = branch.getArguments().get(i + (branch.getIdentifier() == null ? 0 : -1));
if (commandArgument.getAllowedObjects().length == 0) {
context.getArguments().put(commandArgument, commandArgument.getObjectFromString(argument));
} else {
for (Object allowedObject : commandArgument.getAllowedObjects()) {
if (commandArgument.getStringFromObject(allowedObject).equalsIgnoreCase(argument)) {
context.getArguments().put(commandArgument, allowedObject);
break;
}
}
}
}
branch.accept(context);
}
} else {
out(String.format("Syntax:\n%s", this.getSyntax()));
}
}
private List<CommandBranch> getViableBranches(String[] args, boolean shouldCheckFinalStringArgument) {
List<CommandBranch> viableBranches = new ArrayList<>();
for (CommandBranch branch : branches) {
if (branch.getIdentifier() == null || (args.length > 0 && args[0].equalsIgnoreCase(branch.getIdentifier()))) {
int numberOfArguments = (branch.getIdentifier() != null) ? branch.getArguments().size() + 1 : branch.getArguments().size();
boolean isFinalStringArgument = (args.length > numberOfArguments &&
branch.getArguments().size() >= 1 &&
branch.getArguments().get(branch.getArguments().size() - 1) instanceof StringArgument);
isFinalStringArgument = isFinalStringArgument && shouldCheckFinalStringArgument;
if (args.length == numberOfArguments ||
isFinalStringArgument) {
boolean isViableBranch = true;
for (int i = (branch.getIdentifier() != null ? 1 : 0); i < args.length; i++) {
final String argument = args[i];
if (i >= numberOfArguments - 1 && isFinalStringArgument) {
isViableBranch = true;
break;
} else {
if (branch.getArguments().size() > 0) {
CommandArgument commandArgument = branch.getArguments().get(i + (branch.getIdentifier() == null ? 0 : -1));
if (commandArgument.getAllowedObjects().length == 0) {
if (commandArgument.getObjectFromString(argument) == null) {
isViableBranch = false;
break;
}
} else {
boolean found = false;
for (Object allowedObject : commandArgument.getAllowedObjects()) {
if (allowedObject == null)
continue;
if (commandArgument.getStringFromObject(allowedObject).equalsIgnoreCase(argument)) {
found = true;
break;
}
}
if (!found) {
isViableBranch = false;
break;
}
}
}
}
}
if (isViableBranch)
viableBranches.add(branch);
}
}
}
return viableBranches;
}
public String getSyntax() {
StringBuilder syntax = new StringBuilder();
for (CommandBranch branch : branches) {
syntax.append(".").append(this.getCommandName());
if (branch.getIdentifier() != null)
syntax.append(" ");
syntax.append(getBranchSyntax(branch)).append("\n");
}
return syntax.toString().substring(0, syntax.length() - 1);
}
public static String getBranchSyntax(CommandBranch branch) {
StringBuilder syntax = new StringBuilder();
if (branch.getIdentifier() != null) {
syntax.append(branch.getIdentifier());
}
for (CommandArgument<?> commandArgument : branch.getArguments()) {
syntax.append(" <").append(commandArgument.getIdentifier()).append(":").append(commandArgument.getTypeDescriptor()).append(">");
}
return syntax.toString();
}
protected static void out(String info) {
Serenity.getInstance().addChatMessage(info);
}
protected static void out(String info, Object... formatting) {
out(String.format(info, formatting));
}
}
|
SerenityEnterprises/SerenityCE
|
src/main/java/host/serenity/serenity/api/command/Command.java
|
Java
|
gpl-3.0
| 8,132
|
/********************************************************************************/
/* 888888 888888888 88 888 88888 888 888 88888888 */
/* 8 8 8 8 8 8 8 8 8 8 */
/* 8 8 8 8 8 8 8 8 8 */
/* 8 888888888 8 8 8 8 8 8 8888888 */
/* 8 8888 8 8 8 8 8 8 8 8 */
/* 8 8 8 8 8 8 8 8 8 8 */
/* 888888 888888888 888 88 88888 88888888 88888888 */
/* */
/* A Three-Dimensional General Purpose Semiconductor Simulator. */
/* */
/* */
/* Copyright (C) 2007-2008 */
/* Cogenda Pte Ltd */
/* */
/* Please contact Cogenda Pte Ltd for license information */
/* */
/* Author: Gong Ding gdiso@ustc.edu */
/* */
/********************************************************************************/
// $Id: mesh_generation.h,v 1.9 2008/07/09 05:58:16 gdiso Exp $
#ifndef __mesh_generation_h__
#define __mesh_generation_h__
// C++ Includes -----------------------------------
#include <vector>
// Local Includes -----------------------------------
#include "genius_common.h"
#include "enum_elem_type.h" // needed for ElemType enum
#include "point.h"
#include "parser.h"
#include "skeleton.h"
#include "mesh_generation_base.h"
class MeshGeneratorStruct : public MeshGeneratorBase
{
public:
/**
* Constructor.
*/
MeshGeneratorStruct (MeshBase& mesh)
: MeshGeneratorBase(mesh), dscale(1e2), point_num(0), point_array3d(0),
IX(0), IY(0), IZ(0), h_min(1e30), h_max(0.0)
{}
/**
* destructor.
*/
virtual ~MeshGeneratorStruct() {}
protected:
/**
* scale the dimension of geometry
* the unit of dimension in input file should be um
* default scale is multiply 1e2 to um
*/
Real dscale;
/**
* the total point number
*/
int point_num;
/**
* the 3D point array which makes the background point clouds
*/
SkeletonPoint ***point_array3d;
/**
* the bound box of 3D points array by index
*/
unsigned int IX,IY,IZ;
/**
* the bound box of point clouds by coordinate
*/
double xmin,xmax,ymin,ymax,zmin,zmax;
/**
* the min/max grid size
*/
double h_min, h_max;
/**
* the SkeletonLine in x dim
*/
SkeletonLine skeleton_line_x;
/**
* the SkeletonLine in y dim
*/
SkeletonLine skeleton_line_y;
/**
* the SkeletonLine in z dim
*/
SkeletonLine skeleton_line_z;
/**
* set_x_line: This function check and do X.MESH card
* which init mesh line in x direction.
*/
int set_x_line(const Parser::Card &c);
/**
* set_y_line: This function check and do Y.MESH card
* which init mesh line in y direction.
*/
int set_y_line(const Parser::Card &c);
/**
* set_z_line: This function check and do Z.MESH card
* which init mesh line in z direction.
*/
int set_z_line(const Parser::Card &c);
/**
* @return the index of x direction skeleton line by x coordinate
*/
int find_skeleton_line_x(double x);
/**
* @return the index of y direction skeleton line by y coordinate
*/
int find_skeleton_line_y(double y);
/**
* @return the index of z direction skeleton line by z coordinate
*/
int find_skeleton_line_z(double z);
};
#endif // #define __mesh_generation_h__
|
cogenda/Genius-TCAD-Open
|
include/meshgen/mesh_generation_struct.h
|
C
|
gpl-3.0
| 4,117
|
package mx.edu.uam.practica4.familia;
/**
*
* @author jhernandezn
*/
public class Padre extends Familiar{
}
|
trainingSoapros/Java
|
Carlos/Practica3/src/mx/edu/uam/practica4/familia/Padre.java
|
Java
|
gpl-3.0
| 138
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_17) on Thu Jul 18 19:11:06 EDT 2013 -->
<title>Uses of Class com.ep.ggs.world.mcmodel.Chunk</title>
<meta name="date" content="2013-07-18">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class com.ep.ggs.world.mcmodel.Chunk";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../com/ep/ggs/world/mcmodel/Chunk.html" title="class in com.ep.ggs.world.mcmodel">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?com/ep/ggs/world/mcmodel/class-use/Chunk.html" target="_top">Frames</a></li>
<li><a href="Chunk.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class com.ep.ggs.world.mcmodel.Chunk" class="title">Uses of Class<br>com.ep.ggs.world.mcmodel.Chunk</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../com/ep/ggs/world/mcmodel/Chunk.html" title="class in com.ep.ggs.world.mcmodel">Chunk</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#com.ep.ggs.world.generator.mcmodel">com.ep.ggs.world.generator.mcmodel</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#com.ep.ggs.world.mcmodel">com.ep.ggs.world.mcmodel</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="com.ep.ggs.world.generator.mcmodel">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../com/ep/ggs/world/mcmodel/Chunk.html" title="class in com.ep.ggs.world.mcmodel">Chunk</a> in <a href="../../../../../../com/ep/ggs/world/generator/mcmodel/package-summary.html">com.ep.ggs.world.generator.mcmodel</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../com/ep/ggs/world/generator/mcmodel/package-summary.html">com.ep.ggs.world.generator.mcmodel</a> with parameters of type <a href="../../../../../../com/ep/ggs/world/mcmodel/Chunk.html" title="class in com.ep.ggs.world.mcmodel">Chunk</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">FlatGrassChunk.</span><code><strong><a href="../../../../../../com/ep/ggs/world/generator/mcmodel/FlatGrassChunk.html#generate(com.ep.ggs.world.mcmodel.Chunk)">generate</a></strong>(<a href="../../../../../../com/ep/ggs/world/mcmodel/Chunk.html" title="class in com.ep.ggs.world.mcmodel">Chunk</a> c)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">ChunkGenerator.</span><code><strong><a href="../../../../../../com/ep/ggs/world/generator/mcmodel/ChunkGenerator.html#generate(com.ep.ggs.world.mcmodel.Chunk)">generate</a></strong>(<a href="../../../../../../com/ep/ggs/world/mcmodel/Chunk.html" title="class in com.ep.ggs.world.mcmodel">Chunk</a> c)</code> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.ep.ggs.world.mcmodel">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../com/ep/ggs/world/mcmodel/Chunk.html" title="class in com.ep.ggs.world.mcmodel">Chunk</a> in <a href="../../../../../../com/ep/ggs/world/mcmodel/package-summary.html">com.ep.ggs.world.mcmodel</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../com/ep/ggs/world/mcmodel/package-summary.html">com.ep.ggs.world.mcmodel</a> with parameters of type <a href="../../../../../../com/ep/ggs/world/mcmodel/Chunk.html" title="class in com.ep.ggs.world.mcmodel">Chunk</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><span class="strong">ChunkGeneratorService.</span><code><strong><a href="../../../../../../com/ep/ggs/world/mcmodel/ChunkGeneratorService.html#addChunk(com.ep.ggs.world.mcmodel.Chunk)">addChunk</a></strong>(<a href="../../../../../../com/ep/ggs/world/mcmodel/Chunk.html" title="class in com.ep.ggs.world.mcmodel">Chunk</a> c)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><span class="strong">ChunkGeneratorService.</span><code><strong><a href="../../../../../../com/ep/ggs/world/mcmodel/ChunkGeneratorService.html#addChunk(com.ep.ggs.world.mcmodel.Chunk, com.ep.ggs.world.generator.mcmodel.ChunkGenerator)">addChunk</a></strong>(<a href="../../../../../../com/ep/ggs/world/mcmodel/Chunk.html" title="class in com.ep.ggs.world.mcmodel">Chunk</a> c,
<a href="../../../../../../com/ep/ggs/world/generator/mcmodel/ChunkGenerator.html" title="interface in com.ep.ggs.world.generator.mcmodel">ChunkGenerator</a> gen)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">ChunkColumn.</span><code><strong><a href="../../../../../../com/ep/ggs/world/mcmodel/ChunkColumn.html#addChunk(int, com.ep.ggs.world.mcmodel.Chunk)">addChunk</a></strong>(int y,
<a href="../../../../../../com/ep/ggs/world/mcmodel/Chunk.html" title="class in com.ep.ggs.world.mcmodel">Chunk</a> c)</code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../com/ep/ggs/world/mcmodel/Chunk.html" title="class in com.ep.ggs.world.mcmodel">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?com/ep/ggs/world/mcmodel/class-use/Chunk.html" target="_top">Frames</a></li>
<li><a href="Chunk.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
hypereddie/GGS
|
docs/com/ep/ggs/world/mcmodel/class-use/Chunk.html
|
HTML
|
gpl-3.0
| 9,243
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Skoolify</title>
<meta name="description" content="School management and administration frontend app">
<meta name="author" content="Skoolify">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="plugins/bootstrap/bootstrap.css" rel="stylesheet">
<link href="plugins/jquery-ui/jquery-ui.min.css" rel="stylesheet">
<link href="http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
<link href='http://fonts.googleapis.com/css?family=Righteous' rel='stylesheet' type='text/css'>
<link href="plugins/fancybox/jquery.fancybox.css" rel="stylesheet">
<link href="plugins/fullcalendar/fullcalendar.css" rel="stylesheet">
<link href="plugins/xcharts/xcharts.min.css" rel="stylesheet">
<link href="plugins/select2/select2.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="http://getbootstrap.com/docs-assets/js/html5shiv.js"></script>
<script src="http://getbootstrap.com/docs-assets/js/respond.min.js"></script>
<![endif]-->
</head>
<body>
<script type="text/x-handlebars" data-template-name="application">
<!--Start Header-->
<div id="screensaver">
<canvas id="canvas"></canvas>
<i class="fa fa-lock" id="screen_unlock"></i>
</div>
<!-- Modal box -->
<div id="modalbox">
<div class="devoops-modal">
<div class="devoops-modal-header">
<div class="modal-header-name">
<span>Basic table</span>
</div>
<div class="box-icons">
<a class="close-link">
<i class="fa fa-times"></i>
</a>
</div>
</div>
<div class="devoops-modal-inner">
</div>
<div class="devoops-modal-bottom">
</div>
</div>
</div>
<!-- Primary Navigation -->
{{partial "nav"}}
<!-- End Primary Navigation -->
<!-- Start Container -->
<div id="main" class="container-fluid">
<div class="row">
<!-- Start Sidebar -->
{{partial "Sidebar"}}
<!-- End Sidebar -->
<!-- Start Content -->
<div id="content" class="col-xs-12 col-sm-10">
<div class="preloader">
<img src="img/devoops_getdata.gif" class="devoops-getdata" alt="preloader"/>
</div>
<div id="ajax-content">
{{outlet}}
</div>
</div>
<!-- End Content -->
</div>
</div>
<!-- End Start Container -->
</script>
<!-- Partials -->
<script type="text/x-handlebars" data-template-name="_nav">
<header class="navbar">
<div class="container-fluid expanded-panel">
<div class="row">
<div id="logo" class="col-xs-12 col-sm-2">
<a href="#">Skoolify</a>
</div>
<div id="top-panel" class="col-xs-12 col-sm-10">
<div class="row">
<div class="col-xs-8 col-sm-4">
<a href="#" class="show-sidebar">
<i class="fa fa-bars"></i>
</a>
<div id="search">
{{view App.SearchTextField placeholder="Search" valueBinding="App.studentController.name"}}
<!-- <input type="text" placeholder="search"/> -->
<i class="fa fa-search"></i>
</div>
</div>
<div class="col-xs-4 col-sm-8 top-panel-right">
<ul class="nav navbar-nav pull-right panel-menu">
<li class="hidden-xs">
<a href="index.html" class="modal-link">
<i class="fa fa-bell"></i>
<span class="badge">7</span>
</a>
</li>
<li class="hidden-xs">
<a class="ajax-link" href="#">
<i class="fa fa-calendar"></i>
<span class="badge">7</span>
</a>
</li>
<li class="hidden-xs">
<a href="#" class="ajax-link">
<i class="fa fa-envelope"></i>
<span class="badge">7</span>
</a>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle account" data-toggle="dropdown">
<div class="avatar">
<img src="img/avatar.jpg" class="img-rounded" alt="avatar" />
</div>
<i class="fa fa-angle-down pull-right"></i>
<div class="user-mini pull-right">
<span class="welcome">Welcome,</span>
<span>Jane Devoops</span>
</div>
</a>
<ul class="dropdown-menu">
<li>
<a href="#">
<i class="fa fa-user"></i>
<span class="hidden-sm text">Profile</span>
</a>
</li>
<li>
<a href="ajax/calendar.html" class="ajax-link">
<i class="fa fa-tasks"></i>
<span class="hidden-sm text">Tasks</span>
</a>
</li>
<li>
<a href="#">
<i class="fa fa-cog"></i>
<span class="hidden-sm text">Settings</span>
</a>
</li>
<li>
<a href="#">
<i class="fa fa-power-off"></i>
<span class="hidden-sm text">Logout</span>
</a>
</li>
</ul>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</header>
</script>
<script type="text/x-handlebars" data-template-name="_sidebar">
<div id="sidebar-left" class="col-xs-2 col-sm-2">
<ul class="nav main-menu">
<li>
<a href="#" class="active ajax-link">
<i class="fa fa-dashboard"></i>
<span class="hidden-xs">Dashboard</span>
</a>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle">
<i class="fa fa-bar-chart-o"></i>
<span class="hidden-xs">Charts</span>
</a>
<ul class="dropdown-menu">
<li><a class="ajax-link" href="#">xCharts</a></li>
<li><a class="ajax-link" href="#">Flot Charts</a></li>
<li><a class="ajax-link" href="#">Google Charts</a></li>
<li><a class="ajax-link" href="#">Morris Charts</a></li>
<li><a class="ajax-link" href="#">CoinDesk realtime</a></li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle">
<i class="fa fa-table"></i>
<span class="hidden-xs">Tables</span>
</a>
<ul class="dropdown-menu">
<li><a class="ajax-link" href="#">Simple Tables</a></li>
<li><a class="ajax-link" href="#">Data Tables</a></li>
<li><a class="ajax-link" href="#">Beauty Tables</a></li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle">
<i class="fa fa-pencil-square-o"></i>
<span class="hidden-xs">Forms</span>
</a>
<ul class="dropdown-menu">
<li><a class="ajax-link" href="#">Elements</a></li>
<li><a class="ajax-link" href="#">Layouts</a></li>
<li><a class="ajax-link" href="#">File Uploader</a></li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle">
<i class="fa fa-desktop"></i>
<span class="hidden-xs">UI Elements</span>
</a>
<ul class="dropdown-menu">
<li><a class="ajax-link" href="#">Grid</a></li>
<li><a class="ajax-link" href="#">Buttons</a></li>
<li><a class="ajax-link" href="#">Progress Bars</a></li>
<li><a class="ajax-link" href="#">Jquery UI</a></li>
<li><a class="ajax-link" href="#">Icons</a></li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle">
<i class="fa fa-list"></i>
<span class="hidden-xs">Pages</span>
</a>
<ul class="dropdown-menu">
<li><a href="#">Login</a></li>
<li><a href="#">Register</a></li>
<li><a id="locked-screen" class="submenu" href="#">Locked Screen</a></li>
<li><a class="ajax-link" href="#">Contacts</a></li>
<li><a class="ajax-link" href="#">Feed</a></li>
<li><a class="ajax-link add-full" href="#">Messages</a></li>
<li><a class="ajax-link" href="#">Pricing</a></li>
<li><a class="ajax-link" href="#">Invoice</a></li>
<li><a class="ajax-link" href="#">Search Results</a></li>
<li><a class="ajax-link" href="#">Error 404</a></li>
<li><a href="#">Error 500</a></li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle">
<i class="fa fa-map-marker"></i>
<span class="hidden-xs">Maps</span>
</a>
<ul class="dropdown-menu">
<li><a class="ajax-link" href="#">OpenStreetMap</a></li>
<li><a class="ajax-link" href="#">Fullscreen map</a></li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle">
<i class="fa fa-picture-o"></i>
<span class="hidden-xs">Gallery</span>
</a>
<ul class="dropdown-menu">
<li><a class="ajax-link" href="#">Simple Gallery</a></li>
<li><a class="ajax-link" href="#">Flickr Gallery</a></li>
</ul>
</li>
<li>
<a class="ajax-link" href="#">
<i class="fa fa-font"></i>
<span class="hidden-xs">Typography</span>
</a>
</li>
<li>
<a class="ajax-link" href="#">
<i class="fa fa-calendar"></i>
<span class="hidden-xs">Calendar</span>
</a>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle">
<i class="fa fa-picture-o"></i>
<span class="hidden-xs">Multilevel menu</span>
</a>
<ul class="dropdown-menu">
<li><a href="#">First level menu</a></li>
<li><a href="#">First level menu</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle">
<i class="fa fa-plus-square"></i>
<span class="hidden-xs">Second level menu group</span>
</a>
<ul class="dropdown-menu">
<li><a href="#">Second level menu</a></li>
<li><a href="#">Second level menu</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle">
<i class="fa fa-plus-square"></i>
<span class="hidden-xs">Three level menu group</span>
</a>
<ul class="dropdown-menu">
<li><a href="#">Three level menu</a></li>
<li><a href="#">Three level menu</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle">
<i class="fa fa-plus-square"></i>
<span class="hidden-xs">Four level menu group</span>
</a>
<ul class="dropdown-menu">
<li><a href="#">Four level menu</a></li>
<li><a href="#">Four level menu</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle">
<i class="fa fa-plus-square"></i>
<span class="hidden-xs">Five level menu group</span>
</a>
<ul class="dropdown-menu">
<li><a href="#">Five level menu</a></li>
<li><a href="#">Five level menu</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle">
<i class="fa fa-plus-square"></i>
<span class="hidden-xs">Six level menu group</span>
</a>
<ul class="dropdown-menu">
<li><a href="#">Six level menu</a></li>
<li><a href="#">Six level menu</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><a href="#">Three level menu</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</script>
<script type="text/x-handlebars" data-template-name="_breadcrumb">
<!--Start Breadcrumb-->
<div class="row">
<div id="breadcrumb" class="col-xs-12">
<ol class="breadcrumb">
<li><a href="index.html">Home</a></li>
<li><a href="#">Dashboard</a></li>
</ol>
</div>
</div>
<!--End Breadcrumb-->
</script>
<!-- Views -->
<script type="text/x-handlebars" data-template-name="dashboard">
{{partial "breadcrumb"}}
<!--Start Dashboard 1-->
<div id="dashboard-header" class="row">
<div class="col-xs-10 col-sm-2">
<h3>HELLO, DASHBOARD!</h3>
</div>
<div class="col-xs-2 col-sm-1 col-sm-offset-1">
<div id="social" class="row">
<a href="#"><i class="fa fa-google-plus"></i></a>
<a href="#"><i class="fa fa-facebook"></i></a>
<a href="#"><i class="fa fa-twitter"></i></a>
<a href="#"><i class="fa fa-linkedin"></i></a>
<a href="#"><i class="fa fa-youtube"></i></a>
</div>
</div>
<div class="clearfix visible-xs"></div>
<div class="col-xs-12 col-sm-8 col-md-7 pull-right">
<div class="row">
<div class="col-xs-4">
<div class="sparkline-dashboard" id="sparkline-1"></div>
<div class="sparkline-dashboard-info">
<i class="fa fa-usd"></i>756.45M
<span class="txt-primary">EBITDA</span>
</div>
</div>
<div class="col-xs-4">
<div class="sparkline-dashboard" id="sparkline-2"></div>
<div class="sparkline-dashboard-info">
<i class="fa fa-usd"></i>245.12M
<span class="txt-info">OIBDA</span>
</div>
</div>
<div class="col-xs-4">
<div class="sparkline-dashboard" id="sparkline-3"></div>
<div class="sparkline-dashboard-info">
<i class="fa fa-usd"></i>107.83M
<span>REVENUE</span>
</div>
</div>
</div>
</div>
</div>
<!--End Dashboard 1-->
<!--Start Dashboard 2-->
<div class="row-fluid">
<div id="dashboard_links" class="col-xs-12 col-sm-2 pull-right">
<ul class="nav nav-pills nav-stacked">
<li class="active"><a href="#" class="tab-link" id="overview">Overview</a></li>
<li><a href="#" class="tab-link" id="clients">Clients</a></li>
<li><a href="#" class="tab-link" id="graph">Statistics</a></li>
<li><a href="#" class="tab-link" id="servers">Servers</a></li>
</ul>
</div>
<div id="dashboard_tabs" class="col-xs-12 col-sm-10">
<!--Start Dashboard Tab 1-->
<div id="dashboard-overview" class="row" style="visibility: visible; position: relative;">
<div id="ow-marketplace" class="col-sm-12 col-md-6">
<div id="ow-setting">
<a href="#"><i class="fa fa-folder-open"></i></a>
<a href="#"><i class="fa fa-credit-card"></i></a>
<a href="#"><i class="fa fa-ticket"></i></a>
<a href="#"><i class="fa fa-bookmark-o"></i></a>
<a href="#"><i class="fa fa-globe"></i></a>
</div>
<h4 class="page-header">MARKETPLACE</h4>
<table id="ticker-table" class="table m-table table-bordered table-hover table-heading">
<thead>
<tr>
<th>Ticker</th>
<th>Price</th>
<th>Change</th>
<th>Weekly Chart</th>
</tr>
</thead>
<tbody>
<tr>
<td class="m-ticker"><b>BRDM</b><span>Broadem Inc.</span></td>
<td class="m-price">33.27</td>
<td class="m-change"><i class="fa fa-angle-up"></i> 1.45 (27%)</td>
<td class="td-graph"></td>
</tr>
<tr>
<td class="m-ticker"><b>ASWLL</b><span>Aswell Corp.</span></td>
<td class="m-price">45.13</td>
<td class="m-change"><i class="fa fa-angle-up"></i> 6.32 (12%)</td>
<td class="td-graph"></td>
</tr>
<tr>
<td class="m-ticker"><b>MIXL</b><span>Mixal LTD.</span></td>
<td class="m-price">71.13</td>
<td class="m-change"><i class="fa fa-angle-down"></i> 7.2 (12%)</td>
<td class="td-graph"></td>
</tr>
<tr>
<td class="m-ticker"><b>LMPRD</b><span>L.A. Prod.</span></td>
<td class="m-price">30.24</td>
<td class="m-change"><i class="fa fa-angle-up"></i> 5.3 (18%)</td>
<td class="td-graph"></td>
</tr>
<tr>
<td class="m-ticker"><b>ALK</b><span>Allien K.</span></td>
<td class="m-price">51.1</td>
<td class="m-change"><i class="fa fa-angle-up"></i> 7.5 (3.5%)</td>
<td class="td-graph"></td>
</tr>
<tr>
<td class="m-ticker"><b>LNISW</b><span>Lenstri Sweet</span></td>
<td class="m-price">123.12</td>
<td class="m-change"><i class="fa fa-angle-down"></i> 54.3 (15.3%)</td>
<td class="td-graph"></td>
</tr>
<tr>
<td class="m-ticker"><b>RNLD</b><span>Ron LEED</span></td>
<td class="m-price">64.14</td>
<td class="m-change"><i class="fa fa-angle-up"></i> 12.33 (0.3%)</td>
<td class="td-graph"></td>
</tr>
<tr>
<td class="m-ticker"><b>BCN</b><span>BeetCN Corp.</span></td>
<td class="m-price">64.14</td>
<td class="m-change"><i class="fa fa-angle-up"></i> 12.33 (0.3%)</td>
<td class="td-graph"></td>
</tr>
<tr>
<td class="m-ticker"><b>AWS</b><span>Awesome Inc.</span></td>
<td class="m-price">64.14</td>
<td class="m-change"><i class="fa fa-angle-up"></i> 12.33 (0.3%)</td>
<td class="td-graph"></td>
</tr>
</tbody>
</table>
</div>
<div class="col-xs-12 col-md-6">
<div id="ow-donut" class="row">
<div class="col-xs-4">
<div id="morris_donut_1" style="width:120px;height:120px;"></div>
</div>
<div class="col-xs-4">
<div id="morris_donut_2" style="width:120px;height:120px;"></div>
</div>
<div class="col-xs-4">
<div id="morris_donut_3" style="width:120px;height:120px;"></div>
</div>
</div>
<div id="ow-activity" class="row">
<div class="col-xs-2 col-sm-1 col-md-2">
<div class="v-txt">ACTIVITY</div>
</div>
<div class="col-xs-7 col-sm-5 col-md-6">
<div class="row"><i class="fa fa-code"></i> Release published <span class="label label-default pull-right">01:17:34</span></div>
<div class="row"><i class="fa fa-cloud-upload"></i> Backup created <span class="label label-default pull-right">03:23:34</span></div>
<div class="row"><i class="fa fa-camera"></i> Snapshot created <span class="label label-default pull-right">04:22:11</span></div>
<div class="row"><i class="fa fa fa-money"></i> Invoice pay <span class="label label-default pull-right">05:11:51</span></div>
<div class="row"><i class="fa fa-briefcase"></i> Project edited <span class="label label-default pull-right">04:52:23</span></div>
<div class="row"><i class="fa fa-floppy-o"></i> Project saved <span class="label label-default pull-right">07:11:01</span></div>
<div class="row"><i class="fa fa-bug"></i> Bug fixed <span class="label label-default pull-right">09:10:31</span></div>
</div>
<div id="ow-stat" class="col-xs-3 col-sm-4 col-md-4 pull-right">
<div class="row"><small><b>Ow Stat.:</b></small></div>
<div class="row">%user <sup>20,43</sup></div>
<div class="row">%nice <sup>1,01</sup></div>
<div class="row">%system <sup>27,34</sup></div>
<div class="row">%iowait <sup>2,02</sup></div>
<div class="row">%steal <sup>1,22</sup></div>
<div class="row">%idle <sup>47,98</sup></div>
<div class="row">tps <sup>296546</sup></div>
</div>
</div>
<div id="ow-summary" class="row">
<div class="col-xs-12">
<h4 class="page-header">Σ SUMMARY</h4>
<div class="row">
<div class="col-xs-12">
<div class="row">
<div class="col-xs-6">Total commits<b>1245634</b></div>
<div class="col-xs-6">Release count<b>227</b></div>
</div>
<div class="row">
<div class="col-xs-6">Tests passed<b>5222345</b></div>
<div class="col-xs-6">Tickets solved<b>324322</b></div>
</div>
<div class="row">
<div class="col-xs-6">Active clients<b>52145</b></div>
<div class="col-xs-6">Support team<b>288</b></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!--End Dashboard Tab 1-->
<!--Start Dashboard Tab 2-->
<div id="dashboard-clients" class="row" style="visibility: hidden; position: absolute;">
<div class="row one-list-message">
<div class="col-xs-1"><i class="fa fa-users"></i></div>
<div class="col-xs-2"><b>Country</b></div>
<div class="col-xs-2">Visitors</div>
<div class="col-xs-2">Page hits</div>
<div class="col-xs-2">Revenue</div>
<div class="col-xs-1">Activity</div>
<div class="col-xs-2">Date</div>
</div>
<div class="row one-list-message">
<div class="col-xs-1"><i class="fa fa-user"></i></div>
<div class="col-xs-2"><b>USA</b></div>
<div class="col-xs-2">109455</div>
<div class="col-xs-2">54322344</div>
<div class="col-xs-2"><i class="fa fa-usd"></i> 354563</div>
<div class="col-xs-1"><span class="bar"></span></div>
<div class="col-xs-2 message-date">12/31/13</div>
</div>
<div class="row one-list-message">
<div class="col-xs-1"><i class="fa fa-user"></i></div>
<div class="col-xs-2"><b>U.K.</b></div>
<div class="col-xs-2">86549</div>
<div class="col-xs-2">43242344</div>
<div class="col-xs-2"><i class="fa fa-usd"></i> 265563</div>
<div class="col-xs-1"><span class="bar"></span></div>
<div class="col-xs-2 message-date">12/25/13</div>
</div>
<div class="row one-list-message">
<div class="col-xs-1"><i class="fa fa-user"></i></div>
<div class="col-xs-2"><b>FRANCE</b></div>
<div class="col-xs-2">79399</div>
<div class="col-xs-2">45376844</div>
<div class="col-xs-2"><i class="fa fa-usd"></i> 309456</div>
<div class="col-xs-1"><span class="bar"></span></div>
<div class="col-xs-2 message-date">12/30/13</div>
</div>
<div class="row one-list-message">
<div class="col-xs-1"><i class="fa fa-user"></i></div>
<div class="col-xs-2"><b>GERMANY</b></div>
<div class="col-xs-2">94567</div>
<div class="col-xs-2">35322344</div>
<div class="col-xs-2"><i class="fa fa-usd"></i> 301040</div>
<div class="col-xs-1"><span class="bar"></span></div>
<div class="col-xs-2 message-date">12/26/13</div>
</div>
<div class="row one-list-message">
<div class="col-xs-1"><i class="fa fa-user"></i></div>
<div class="col-xs-2"><b>CANADA</b></div>
<div class="col-xs-2">89525</div>
<div class="col-xs-2">1342344</div>
<div class="col-xs-2"><i class="fa fa-usd"></i> 298764</div>
<div class="col-xs-1"><span class="bar"></span></div>
<div class="col-xs-2 message-date">12/30/13</div>
</div>
<div class="row one-list-message">
<div class="col-xs-1"><i class="fa fa-user"></i></div>
<div class="col-xs-2"><b>CHINA</b></div>
<div class="col-xs-2">120865</div>
<div class="col-xs-2">43522344</div>
<div class="col-xs-2"><i class="fa fa-usd"></i> 776563</div>
<div class="col-xs-1"><span class="bar"></span></div>
<div class="col-xs-2 message-date">12/29/13</div>
</div>
</div>
<!--End Dashboard Tab 2-->
<!--Start Dashboard Tab 3-->
<div id="dashboard-graph" class="row" style="width:100%; visibility: hidden; position: absolute;" >
<div class="col-xs-12">
<h4 class="page-header">OS Platform Statistics</h4>
<div id="stat-graph" style="height: 300px;"></div>
</div>
</div>
<!--End Dashboard Tab 3-->
<!--Start Dashboard Tab 4-->
<div id="dashboard-servers" class="row" style="visibility: hidden; position: absolute;">
<div class="col-xs-12 col-sm-6 col-md-4 ow-server">
<h4 class="page-header text-right"><i class="fa fa-windows"></i>#SRV-APP</h4>
<small>Application server</small>
<div class="ow-settings">
<a href="#"><i class="fa fa-gears"></i></a>
</div>
<div class="row ow-server-bottom">
<div class="col-sm-4">
<div class="knob-slider">
<input id="knob-srv-1" class="knob" data-width="60" data-height="60" data-angleOffset="180" data-fgColor="#6AA6D6" data-skin="tron" data-thickness=".2" value="">CPU Load
</div>
</div>
<div class="col-sm-8">
<div class="row"><i class="fa fa-windows"></i> Windows 2008</div>
<div class="row"><i class="fa fa-user"></i> Active users - 49</div>
<div class="row"><i class="fa fa-bolt"></i> Uptime - 10 days</div>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-4 ow-server">
<h4 class="page-header text-right"><i class="fa fa-windows"></i>#DB-MASTER</h4>
<small>SQL server</small>
<div class="ow-settings">
<a href="#"><i class="fa fa-gears"></i></a>
</div>
<div class="row ow-server-bottom">
<div class="col-sm-4">
<div class="knob-slider">
<input id="knob-srv-2" class="knob" data-width="60" data-height="60" data-angleOffset="180" data-fgColor="#6AA6D6" data-skin="tron" data-thickness=".2" value="">CPU Load
</div>
</div>
<div class="col-sm-8">
<div class="row"><i class="fa fa-windows"></i> Windows 2013</div>
<div class="row"><i class="fa fa-user"></i> Active users - 39</div>
<div class="row"><i class="fa fa-bolt"></i> Uptime - 2 month 1 day</div>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-4 ow-server">
<h4 class="page-header text-right"><i class="fa fa-linux"></i>#DB-WEB</h4>
<small>MySQL server</small>
<div class="ow-settings">
<a href="#"><i class="fa fa-gears"></i></a>
</div>
<div class="row ow-server-bottom">
<div class="col-sm-4">
<div class="knob-slider">
<input id="knob-srv-3" class="knob" data-width="60" data-height="60" data-angleOffset="180" data-fgColor="#6AA6D6" data-skin="tron" data-thickness=".2" value="">CPU Load
</div>
</div>
<div class="col-sm-8">
<div class="row"><i class="fa fa-linux"></i> CentOS 6.5</div>
<div class="row"><i class="fa fa-user"></i> Active users - 298</div>
<div class="row"><i class="fa fa-bolt"></i> Uptime - 9 month 17 day</div>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-4 ow-server">
<h4 class="page-header text-right"><i class="fa fa-linux"></i>#WWW-SRV</h4>
<small>Web-server</small>
<div class="ow-settings">
<a href="#"><i class="fa fa-gears"></i></a>
</div>
<div class="row ow-server-bottom">
<div class="col-sm-4">
<div class="knob-slider">
<input id="knob-srv-4" class="knob" data-width="60" data-height="60" data-angleOffset="180" data-fgColor="#6AA6D6" data-skin="tron" data-thickness=".2" value="">CPU Load
</div>
</div>
<div class="col-sm-8">
<div class="row"><i class="fa fa-linux"></i> Centos 6.5</div>
<div class="row"><i class="fa fa-user"></i> Active users - 1989</div>
<div class="row"><i class="fa fa-bolt"></i> Uptime - 2 years 3 month</div>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-4 ow-server">
<h4 class="page-header text-right"><i class="fa fa-linux"></i>#PHONE-OFFICE</h4>
<small>Asterisk</small>
<div class="ow-settings">
<a href="#"><i class="fa fa-gears"></i></a>
</div>
<div class="row ow-server-bottom">
<div class="col-sm-4">
<div class="knob-slider">
<input id="knob-srv-5" class="knob" data-width="60" data-height="60" data-angleOffset="180" data-fgColor="#6AA6D6" data-skin="tron" data-thickness=".2" value="">CPU Load
</div>
</div>
<div class="col-sm-8">
<div class="row"><i class="fa fa-linux"></i> Debian 6.4</div>
<div class="row"><i class="fa fa-phone"></i> Active calls - 86</div>
<div class="row"><i class="fa fa-bolt"></i> Uptime - 3 month 19 day</div>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-4 ow-server">
<h4 class="page-header text-right"><i class="fa fa-linux"></i>#DEVEL</h4>
<small>DEV server</small>
<div class="ow-settings">
<a href="#"><i class="fa fa-gears"></i></a>
</div>
<div class="row ow-server-bottom">
<div class="col-sm-4">
<div class="knob-slider">
<input id="knob-srv-6" class="knob" data-width="60" data-height="60" data-angleOffset="180" data-fgColor="#6AA6D6" data-skin="tron" data-thickness=".2" value="">CPU Load
</div>
</div>
<div class="col-sm-8">
<div class="row"><i class="fa fa-linux"></i> CentOS 6.5</div>
<div class="row"><i class="fa fa-archive"></i> Repositories - 17</div>
<div class="row"><i class="fa fa-bolt"></i> Uptime - 4 month 21 day</div>
</div>
</div>
</div>
<div class="clearfix"></div>
<div id="ow-server-footer">
<a href="#" class="col-xs-4 col-sm-2 btn-default text-center"><i class="fa fa-sun-o"></i> <b>287</b> <span>Hosts</span></a>
<a href="#" class="col-xs-4 col-sm-2 btn-default text-center"><i class="fa fa-envelope-o"></i> <b>56</b> <span>Messages</span></a>
<a href="#" class="col-xs-4 col-sm-2 btn-default text-center"><i class="fa fa-desktop"></i> <b>85</b> <span>Stations</span></a>
<a href="#" class="col-xs-4 col-sm-2 btn-default text-center"><i class="fa fa-info-circle"></i> <b>33</b> <span>Errors</span></a>
<a href="#" class="col-xs-4 col-sm-2 btn-default text-center"><i class="fa fa-comments-o"></i> <b>1386</b> <span>Comments</span></a>
<a href="#" class="col-xs-4 col-sm-2 btn-default text-center"><i class="fa fa-user"></i> <b>19985</b> <span>Clients</span></a>
</div>
</div>
<!--End Dashboard Tab 4-->
</div>
<div class="clearfix"></div>
</div>
<!--End Dashboard 2 -->
<div style="height: 40px;"></div>
</script>
<!--End Container-->
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<!--<script src="http://code.jquery.com/jquery.js"></script>-->
<script src="js/libs/jquery/dist/jquery.min.js"></script>
<script src="plugins/jquery-ui/jquery-ui.min.js"></script>
<!-- Ember related -->
<script src="js/handlebars-v1.3.0.js"></script>
<script src="js/ember.min.js"></script>
<script src="js/ember-data.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="plugins/bootstrap/bootstrap.min.js"></script>
<script src="plugins/justified-gallery/jquery.justifiedgallery.min.js"></script>
<script src="plugins/tinymce/tinymce.min.js"></script>
<script src="plugins/tinymce/jquery.tinymce.min.js"></script>
<!-- All functions for this theme + document.ready processing -->
<script src="js/app.js"></script>
<script src="js/devoops.js"></script>
</body>
</html>
|
verygreenboi/sawe
|
index.html
|
HTML
|
gpl-3.0
| 30,176
|
/*
===========================================================================
Copyright (c) 2010-2015 Darkstar Dev Teams
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/
This file is part of DarkStar-server source code.
===========================================================================
*/
#ifndef _BATTLEUTILS_H
#define _BATTLEUTILS_H
#include "../../common/cbasetypes.h"
#include "../blue_spell.h"
#include "../status_effect.h"
#include "../merit.h"
#include <list>
#include "../entities/battleentity.h"
class CAbility;
class CItemWeapon;
class CMobSkill;
class CSpell;
class CTrait;
class CWeaponSkill;
struct actionTarget_t;
enum ENSPELL
{
ENSPELL_NONE = 0,
ENSPELL_I_FIRE = 1,
ENSPELL_I_EARTH = 2,
ENSPELL_I_WATER = 3,
ENSPELL_I_WIND = 4,
ENSPELL_I_ICE = 5,
ENSPELL_I_THUNDER = 6,
ENSPELL_I_LIGHT = 7,
ENSPELL_I_DARK = 8,
ENSPELL_II_FIRE = 9,
ENSPELL_II_EARTH = 10,
ENSPELL_II_WATER = 11,
ENSPELL_II_WIND = 12,
ENSPELL_II_ICE = 13,
ENSPELL_II_THUNDER = 14,
ENSPELL_II_LIGHT = 15,
ENSPELL_BLOOD_WEAPON = 16,
ENSPELL_ROLLING_THUNDER = 17,
ENSPELL_AUSPICE = 18,
ENSPELL_DRAIN_SAMBA = 19,
ENSPELL_ASPIR_SAMBA = 20,
ENSPELL_HASTE_SAMBA = 21
};
enum SPIKES
{
SPIKE_NONE = 0,
SPIKE_BLAZE = 1,
SPIKE_ICE = 2,
SPIKE_DREAD = 3,
SPIKE_CURSE = 4,
SPIKE_SHOCK = 5,
SPIKE_REPRISAL = 6,
SPIKE_WIND = 7,
SPIKE_STONE = 8,
SPIKE_DELUGE = 9,
RETALIATION = 63
};
enum ELEMENT
{
ELEMENT_NONE = 0,
ELEMENT_FIRE = 1,
ELEMENT_EARTH = 2,
ELEMENT_WATER = 3,
ELEMENT_WIND = 4,
ELEMENT_ICE = 5,
ELEMENT_THUNDER = 6,
ELEMENT_LIGHT = 7,
ELEMENT_DARK = 8
};
namespace battleutils
{
void LoadSkillTable();
void LoadWeaponSkillsList();
void LoadMobSkillsList();
void LoadSkillChainDamageModifiers();
uint8 CheckMultiHits(CBattleEntity* PEntity, CItemWeapon* PWeapon);
uint8 getHitCount(uint8 hits);
uint8 CheckMobMultiHits(CBattleEntity* PEntity);
int16 GetSnapshotReduction(CCharEntity* m_PChar, int16 delay);
int32 GetRangedAttackBonuses(CBattleEntity* battleEntity);
int32 GetRangedAccuracyBonuses(CBattleEntity* battleEntity);
uint8 GetSkillRank(SKILLTYPE SkillID, JOBTYPE JobID);
uint16 GetMaxSkill(SKILLTYPE SkillID, JOBTYPE JobID, uint8 level);
uint16 GetMaxSkill(uint8 rank, uint8 level);
CWeaponSkill* GetWeaponSkill(uint16 WSkillID);
CMobSkill* GetMobSkill(uint16 SkillID);
CMobSkill* GetTwoHourMobSkill(JOBTYPE job, uint16 familyId);
const std::list<CWeaponSkill*>& GetWeaponSkills(uint8 skill);
const std::vector<uint16>& GetMobSkillList(uint16 ListID);
void FreeWeaponSkillsList();
void FreeMobSkillList();
SUBEFFECT GetSkillChainEffect(CBattleEntity* PDefender, CWeaponSkill* PWeaponSkill);
SUBEFFECT GetSkillChainEffect(CBattleEntity* PDefender, CBlueSpell* PSpell);
SKILLCHAIN_ELEMENT FormSkillchain(const std::list<SKILLCHAIN_ELEMENT>& resonance, const std::list<SKILLCHAIN_ELEMENT>& skill);
uint8 GetSkillchainTier(SKILLCHAIN_ELEMENT skillchain);
uint8 GetSkillchainSubeffect(SKILLCHAIN_ELEMENT skillchain);
int16 GetSkillchainMinimumResistance(SKILLCHAIN_ELEMENT element, CBattleEntity* PDefender, ELEMENT* appliedEle);
bool IsParalyzed(CBattleEntity* PAttacker);
bool IsAbsorbByShadow(CBattleEntity* PDefender);
bool IsIntimidated(CBattleEntity* PAttacker, CBattleEntity* PDefender);
int32 GetFSTR(CBattleEntity* PAttacker, CBattleEntity* PDefender, uint8 SlotID);
uint8 GetHitRateEx(CBattleEntity* PAttacker, CBattleEntity* PDefender, uint8 attackNumber, int8 offsetAccuracy);
uint8 GetHitRate(CBattleEntity* PAttacker, CBattleEntity* PDefender);
uint8 GetHitRate(CBattleEntity* PAttacker, CBattleEntity* PDefender, uint8 attackNumber);
uint8 GetHitRate(CBattleEntity* PAttacker, CBattleEntity* PDefender, uint8 attackNumber, int8 offsetAccuracy);
uint8 GetCritHitRate(CBattleEntity* PAttacker, CBattleEntity* PDefender, bool ignoreSneakTrickAttack);
uint8 GetBlockRate(CBattleEntity* PAttacker, CBattleEntity* PDefender);
uint8 GetParryRate(CBattleEntity* PAttacker, CBattleEntity* PDefender);
uint8 GetGuardRate(CBattleEntity* PAttacker, CBattleEntity* PDefender);
float GetDamageRatio(CBattleEntity* PAttacker, CBattleEntity* PDefender, bool isCritical, uint16 bonusAttPercent);
int32 TakePhysicalDamage(CBattleEntity* PAttacker, CBattleEntity* PDefender, int32 damage, bool isBlocked, uint8 slot, uint16 tpMultiplier, CBattleEntity* taChar, bool giveTPtoVictim, bool giveTPtoAttacker, bool isCounter = false);
int32 TakeWeaponskillDamage(CCharEntity* PChar, CBattleEntity* PDefender, int32 damage, uint8 slot, float tpMultiplier, uint16 bonusTP, float targetTPMultiplier);
int32 TakeSkillchainDamage(CBattleEntity* PAttacker, CBattleEntity* PDefender, int32 lastSkillDamage, CBattleEntity* taChar);
bool TryInterruptSpell(CBattleEntity* PAttacker, CBattleEntity* PDefender, CSpell* PSpell);
float GetRangedPDIF(CBattleEntity* PAttacker, CBattleEntity* PDefender);
void HandleRangedAdditionalEffect(CCharEntity* PAttacker, CBattleEntity* PDefender, apAction_t* Action);
uint16 CalculateSpikeDamage(CBattleEntity* PAttacker, CBattleEntity* PDefender, actionTarget_t* Action, uint16 damageTaken);
bool HandleSpikesDamage(CBattleEntity* PAttacker, CBattleEntity* PDefender, actionTarget_t* Action, int32 damage);
bool HandleSpikesEquip(CBattleEntity* PAttacker, CBattleEntity* PDefender, actionTarget_t* Action, uint8 damage, SUBEFFECT spikesType, uint8 chance);
void HandleSpikesStatusEffect(CBattleEntity* PAttacker, CBattleEntity* PDefender, actionTarget_t* Action);
void HandleEnspell(CBattleEntity* PAttacker, CBattleEntity* PDefender, actionTarget_t* Action, bool isFirstSwing, CItemWeapon* weapon, int32 damage);
uint8 GetRangedHitRate(CBattleEntity* PAttacker, CBattleEntity* PDefender, bool isBarrage);
int32 CalculateEnspellDamage(CBattleEntity* PAttacker, CBattleEntity* PDefender, uint8 Tier, uint8 element);
uint8 GetEnmityModDamage(uint8 level);
uint8 GetEnmityModCure(uint8 level);
bool isValidSelfTargetWeaponskill(int wsid);
int16 CalculateBaseTP(int delay);
void GenerateCureEnmity(CCharEntity* PSource, CBattleEntity* PTarget, uint16 amount);
void GenerateInRangeEnmity(CBattleEntity* PSource, int16 CE, int16 VE);
CItemWeapon* GetEntityWeapon(CBattleEntity* PEntity, SLOTTYPE Slot);
CItemArmor* GetEntityArmor(CBattleEntity* PEntity, SLOTTYPE Slot);
void MakeEntityStandUp(CBattleEntity* PEntity);
CBattleEntity* getAvailableTrickAttackChar(CBattleEntity* taUser, CBattleEntity* PMob);
bool HasNinjaTool(CBattleEntity* PEntity, CSpell* PSpell, bool ConsumeTool);
bool TryCharm(CBattleEntity* PCharmer, CBattleEntity* PVictim, uint32 base);
void tryToCharm(CBattleEntity* PCharmer, CBattleEntity* PVictim);
void applyCharm(CBattleEntity* PCharmer, CBattleEntity* PVictim, duration charmTime = 0s);
void unCharm(CBattleEntity* PEntity);
uint16 doSoulEaterEffect(CCharEntity* m_PChar, uint32 damage);
uint16 getOverWhelmDamageBonus(CCharEntity* m_PChar, CBattleEntity* PDefender, uint16 damage);
uint16 jumpAbility(CBattleEntity* PAttacker, CBattleEntity* PVictim, uint8 tier);
void TransferEnmity(CBattleEntity* PHateReceiver, CBattleEntity* PHateGiver, CMobEntity* PMob, uint8 percentToTransfer);
uint8 getBarrageShotCount(CCharEntity* PChar);
uint8 getStoreTPbonusFromMerit(CBattleEntity* PEntity);
void ClaimMob(CBattleEntity* PDefender, CBattleEntity* PAttacker);
int32 BreathDmgTaken(CBattleEntity* PDefender, int32 damage);
int32 MagicDmgTaken(CBattleEntity* PDefender, int32 damage, ELEMENT element);
int32 PhysicalDmgTaken(CBattleEntity* PDefender, int32 damage);
int32 RangedDmgTaken(CBattleEntity* PDefender, int32 damage);
void HandleIssekiganEnmityBonus(CBattleEntity* PDefender, CBattleEntity* PAttacker);
int32 HandleSevereDamage(CBattleEntity* PDefender, int32 damage);
int32 HandleSevereDamageEffect(CBattleEntity* PDefender, EFFECT effect, int32 damage, bool removeEffect);
void HandleTacticalParry(CBattleEntity* PEntity);
// Handles everything related to breaking Bind
void BindBreakCheck(CBattleEntity* PAttacker, CBattleEntity* PDefender);
// returns damage taken
int32 HandleStoneskin(CBattleEntity* PDefender, int32 damage);
int32 HandleFanDance(CBattleEntity* PDefender, int32 damage);
// stores damage for afflatus misery if active
void HandleAfflatusMiseryDamage(CBattleEntity* PDefender, int32 damage);
// boosts accuracy when afflatus msiery is active
void HandleAfflatusMiseryAccuracyBonus(CBattleEntity* PAttacker);
// handles enmity loss calculations for tranquil heart
float HandleTranquilHeart(CBattleEntity* PEntity);
void assistTarget(CCharEntity* PChar, uint16 TargID);
uint8 GetSpellAoEType(CBattleEntity* PCaster, CSpell* PSpell);
WEATHER GetWeather(CBattleEntity* PEntity, bool ignoreScholar);
bool WeatherMatchesElement(WEATHER weather, uint8 element);
bool DrawIn(CBattleEntity* PEntity, CMobEntity* PMob, float offset);
void DoWildCardToEntity(CCharEntity* PCaster, CCharEntity* PTarget, uint8 roll);
void AddTraits(CBattleEntity* PEntity, TraitList_t* TraitList, uint8 level);
bool HasClaim(CBattleEntity* PEntity, CBattleEntity* PTarget);
uint32 CalculateSpellCastTime(CBattleEntity*, CSpell*);
uint16 CalculateSpellCost(CBattleEntity*, CSpell*);
uint32 CalculateSpellRecastTime(CBattleEntity*, CSpell*);
int16 CalculateWeaponSkillTP(CBattleEntity*, CWeaponSkill*, int16);
bool RemoveAmmo(CCharEntity*, int quantity = 1);
int32 GetMeritValue(CBattleEntity*, MERIT_TYPE);
int32 GetScaledItemModifier(CBattleEntity*, CItemArmor*, MODIFIER);
};
#endif
|
rpetit3/darkstar
|
src/map/utils/battleutils.h
|
C
|
gpl-3.0
| 11,225
|
'use strict';
angular.module('app').controller('FundraiserNavTabsController', function ($scope, $location) {
$scope.active_tab = function(name) {
if (name === 'overview' && (/^\/fundraisers\/[a-z-_0-9]+$/i).test($location.path())) { return "active"; }
if (name === 'updates' && (/^\/fundraisers\/[a-z-_0-9]+\/updates$/i).test($location.path())) { return "active"; }
if (name === 'pledges' && (/^\/fundraisers\/[a-z-_0-9]+\/pledges$/i).test($location.path())) { return "active"; }
if (name === 'rewards' && (/^\/fundraisers\/[a-z-_0-9]+\/rewards$/i).test($location.path())) { return "active"; }
if (name === 'pledge_now' && (/^\/fundraisers\/[a-z-_0-9]+\/pledge$/i).test($location.path())) { return "active"; }
};
});
|
jeffrey-l-turner/frontend
|
app/pages/fundraisers/controllers/nav_tabs.js
|
JavaScript
|
gpl-3.0
| 743
|
<?php
/* Copyright (C) 2002-2003 Rodolphe Quiedeville <rodolphe@quiedeville.org>
* Copyright (C) 2003 Jean-Louis Bergamo <jlb@j1b.org>
* Copyright (C) 2004-2012 Laurent Destailleur <eldy@users.sourceforge.net>
* Copytight (C) 2005-2009 Regis Houssin <regis.houssin@capnetworks.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file htdocs/compta/bank/fiche.php
* \ingroup banque
* \brief Page to create/view a bank account
*/
require('../../main.inc.php');
require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formbank.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
$langs->load("banks");
$langs->load("categories");
$langs->load("companies");
$action=GETPOST("action");
// Security check
if (isset($_GET["id"]) || isset($_GET["ref"]))
{
$id = isset($_GET["id"])?$_GET["id"]:(isset($_GET["ref"])?$_GET["ref"]:'');
}
$fieldid = isset($_GET["ref"])?'ref':'rowid';
if ($user->societe_id) $socid=$user->societe_id;
$result=restrictedArea($user,'banque',$id,'bank_account','','',$fieldid);
/*
* Actions
*/
if ($_POST["action"] == 'add')
{
$error=0;
// Create account
$account = new Account($db,0);
$account->ref = dol_sanitizeFileName(trim($_POST["ref"]));
$account->label = trim($_POST["label"]);
$account->courant = $_POST["type"];
$account->clos = $_POST["clos"];
$account->rappro = (isset($_POST["norappro"]) && $_POST["norappro"])?0:1;
$account->url = $_POST["url"];
$account->account_number = trim($_POST["account_number"]);
$account->solde = $_POST["solde"];
$account->date_solde = dol_mktime(12,0,0,$_POST["remonth"],$_POST["reday"],$_POST["reyear"]);
$account->currency_code = trim($_POST["account_currency_code"]);
$account->state_id = $_POST["account_state_id"];
$account->country_id = $_POST["account_country_id"];
$account->min_allowed = $_POST["account_min_allowed"];
$account->min_desired = $_POST["account_min_desired"];
$account->comment = trim($_POST["account_comment"]);
if ($conf->global->MAIN_BANK_ACCOUNTANCY_CODE_ALWAYS_REQUIRED && empty($account->account_number))
{
setEventMessage($langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("AccountancyCode")), 'error');
$action='create'; // Force chargement page en mode creation
$error++;
}
if (empty($account->ref))
{
setEventMessage($langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("Ref")), 'errors');
$action='create'; // Force chargement page en mode creation
$error++;
}
if (empty($account->label))
{
setEventMessage($langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("LabelBankCashAccount")), 'errors');
$action='create'; // Force chargement page en mode creation
$error++;
}
if (! $error)
{
$id = $account->create($user->id);
if ($id > 0)
{
$_GET["id"]=$id; // Force chargement page en mode visu
}
else {
setEventMessage($account->error,'errors');
$action='create'; // Force chargement page en mode creation
}
}
}
if ($_POST["action"] == 'update' && ! $_POST["cancel"])
{
$error=0;
// Update account
$account = new Account($db, $_POST["id"]);
$account->fetch($_POST["id"]);
$account->ref = dol_string_nospecial(trim($_POST["ref"]));
$account->label = trim($_POST["label"]);
$account->courant = $_POST["type"];
$account->clos = $_POST["clos"];
$account->rappro = (isset($_POST["norappro"]) && $_POST["norappro"])?0:1;
$account->url = trim($_POST["url"]);
$account->bank = trim($_POST["bank"]);
$account->code_banque = trim($_POST["code_banque"]);
$account->code_guichet = trim($_POST["code_guichet"]);
$account->number = trim($_POST["number"]);
$account->cle_rib = trim($_POST["cle_rib"]);
$account->bic = trim($_POST["bic"]);
$account->iban_prefix = trim($_POST["iban_prefix"]);
$account->domiciliation = trim($_POST["domiciliation"]);
$account->proprio = trim($_POST["proprio"]);
$account->owner_address = trim($_POST["owner_address"]);
$account->account_number = trim($_POST["account_number"]);
$account->currency_code = trim($_POST["account_currency_code"]);
$account->state_id = $_POST["account_state_id"];
$account->country_id = $_POST["account_country_id"];
$account->min_allowed = $_POST["account_min_allowed"];
$account->min_desired = $_POST["account_min_desired"];
$account->comment = trim($_POST["account_comment"]);
if ($conf->global->MAIN_BANK_ACCOUNTANCY_CODE_ALWAYS_REQUIRED && empty($account->account_number))
{
setEventMessage($langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("AccountancyCode")), 'error');
$action='edit'; // Force chargement page en mode creation
$error++;
}
if (empty($account->ref))
{
setEventMessage($langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("Ref")), 'errors');
$action='edit'; // Force chargement page en mode creation
$error++;
}
if (empty($account->label))
{
setEventMessage($langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("LabelBankCashAccount")), 'errors');
$action='edit'; // Force chargement page en mode creation
$error++;
}
if (! $error)
{
$result = $account->update($user);
if ($result >= 0)
{
$_GET["id"]=$_POST["id"]; // Force chargement page en mode visu
}
else
{
$message='<div class="error">'.$account->error.'</div>';
$action='edit'; // Force chargement page edition
}
}
}
if ($_POST["action"] == 'confirm_delete' && $_POST["confirm"] == "yes" && $user->rights->banque->configurer)
{
// Delete
$account = new Account($db);
$account->fetch($_GET["id"]);
$account->delete();
header("Location: ".DOL_URL_ROOT."/compta/bank/index.php");
exit;
}
/*
* View
*/
$form = new Form($db);
$formbank = new FormBank($db);
$formcompany = new FormCompany($db);
$countrynotdefined=$langs->trans("ErrorSetACountryFirst").' ('.$langs->trans("SeeAbove").')';
llxHeader();
// Creation
if ($action == 'create')
{
$account=new Account($db);
print_fiche_titre($langs->trans("NewFinancialAccount"));
dol_htmloutput_mesg($message);
if ($conf->use_javascript_ajax)
{
print "\n".'<script type="text/javascript" language="javascript">';
print 'jQuery(document).ready(function () {
jQuery("#selectaccount_country_id").change(function() {
document.formsoc.action.value="create";
document.formsoc.submit();
});
})';
print '</script>'."\n";
}
print '<form action="'.$_SERVER["PHP_SELF"].'" name="formsoc" method="post">';
print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
print '<input type="hidden" name="action" value="add">';
print '<input type="hidden" name="clos" value="0">';
print '<table class="border" width="100%">';
// Ref
print '<tr><td valign="top" class="fieldrequired">'.$langs->trans("Ref").'</td>';
print '<td colspan="3"><input size="8" type="text" class="flat" name="ref" value="'.($_POST["ref"]?$_POST["ref"]:$account->ref).'" maxlength="12"></td></tr>';
// Label
print '<tr><td valign="top" class="fieldrequired">'.$langs->trans("LabelBankCashAccount").'</td>';
print '<td colspan="3"><input size="30" type="text" class="flat" name="label" value="'.$_POST["label"].'"></td></tr>';
// Type
print '<tr><td valign="top" class="fieldrequired">'.$langs->trans("AccountType").'</td>';
print '<td colspan="3">';
print $formbank->select_type_comptes_financiers(isset($_POST["type"])?$_POST["type"]:1,"type");
print '</td></tr>';
// Currency
print '<tr><td valign="top" class="fieldrequired">'.$langs->trans("Currency").'</td>';
print '<td colspan="3">';
$selectedcode=$account->account_currency_code;
if (! $selectedcode) $selectedcode=$conf->currency;
$form->select_currency((isset($_POST["account_currency_code"])?$_POST["account_currency_code"]:$selectedcode), 'account_currency_code');
//print $langs->trans("Currency".$conf->currency);
//print '<input type="hidden" name="account_currency_code" value="'.$conf->currency.'">';
print '</td></tr>';
// Status
print '<tr><td valign="top" class="fieldrequired">'.$langs->trans("Status").'</td>';
print '<td colspan="3">';
print $form->selectarray("clos",array(0=>$account->status[0],1=>$account->status[1]),(isset($_POST["clos"])?$_POST["clos"]:$account->clos));
print '</td></tr>';
// Country
print '<tr><td valign="top" class="fieldrequired">'.$langs->trans("BankAccountCountry").'</td>';
print '<td colspan="3">';
$selectedcode='';
if (isset($_POST["account_country_id"]))
{
$selectedcode=$_POST["account_country_id"]?$_POST["account_country_id"]:$account->country_code;
}
else if (empty($selectedcode)) $selectedcode=$mysoc->country_code;
print $form->select_country($selectedcode,'account_country_id');
if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
print '</td></tr>';
// State
print '<tr><td>'.$langs->trans('State').'</td><td colspan="3">';
if ($selectedcode)
{
$formcompany->select_departement(isset($_POST["account_state_id"])?$_POST["account_state_id"]:'',$selectedcode,'account_state_id');
}
else
{
print $countrynotdefined;
}
print '</td></tr>';
// Accountancy code
if (! empty($conf->global->MAIN_BANK_ACCOUNTANCY_CODE_ALWAYS_REQUIRED))
{
print '<tr><td valign="top" class="fieldrequired">'.$langs->trans("AccountancyCode").'</td>';
print '<td colspan="3"><input type="text" name="account_number" value="'.$account->account_number.'"></td></tr>';
}
else
{
print '<tr><td valign="top">'.$langs->trans("AccountancyCode").'</td>';
print '<td colspan="3"><input type="text" name="account_number" value="'.$account->account_number.'"></td></tr>';
}
// Web
print '<tr><td valign="top">'.$langs->trans("Web").'</td>';
print '<td colspan="3"><input size="50" type="text" class="flat" name="url" value="'.$_POST["url"].'"></td></tr>';
// Comment
print '<tr><td valign="top">'.$langs->trans("Comment").'</td>';
print '<td colspan="3">';
// Editor wysiwyg
require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
$doleditor=new DolEditor('account_comment',$account->comment,'',200,'dolibarr_notes','',false,true,$conf->global->FCKEDITOR_ENABLE_SOCIETE,10,70);
$doleditor->Create();
print '</td></tr>';
// Sold
print '<tr><td colspan="4"><b>'.$langs->trans("InitialBankBalance").'...</b></td></tr>';
print '<tr><td valign="top">'.$langs->trans("InitialBankBalance").'</td>';
print '<td colspan="3"><input size="12" type="text" class="flat" name="solde" value="'.($_POST["solde"]?$_POST["solde"]:price2num($account->solde)).'"></td></tr>';
print '<tr><td valign="top">'.$langs->trans("Date").'</td>';
print '<td colspan="3">';
$form->select_date(time(), 're', 0, 0, 0, 'formsoc');
print '</td></tr>';
print '<tr><td valign="top">'.$langs->trans("BalanceMinimalAllowed").'</td>';
print '<td colspan="3"><input size="12" type="text" class="flat" name="account_min_allowed" value="'.($_POST["account_min_allowed"]?$_POST["account_min_allowed"]:$account->account_min_allowed).'"></td></tr>';
print '<tr><td valign="top">'.$langs->trans("BalanceMinimalDesired").'</td>';
print '<td colspan="3"><input size="12" type="text" class="flat" name="account_min_desired" value="'.($_POST["account_min_desired"]?$_POST["account_min_desired"]:$account->account_min_desired).'"></td></tr>';
print '</table>';
print '<center><br><input value="'.$langs->trans("CreateAccount").'" type="submit" class="button"></center>';
print '</form>';
}
/* ************************************************************************** */
/* */
/* Visu et edition */
/* */
/* ************************************************************************** */
else
{
if (($_GET["id"] || $_GET["ref"]) && $action != 'edit')
{
$account = new Account($db);
if ($_GET["id"])
{
$account->fetch($_GET["id"]);
}
if ($_GET["ref"])
{
$account->fetch(0,$_GET["ref"]);
$_GET["id"]=$account->id;
}
/*
* Affichage onglets
*/
// Onglets
$head=bank_prepare_head($account);
dol_fiche_head($head, 'bankname', $langs->trans("FinancialAccount"),0,'account');
/*
* Confirmation to delete
*/
if ($action == 'delete')
{
print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$account->id,$langs->trans("DeleteAccount"),$langs->trans("ConfirmDeleteAccount"),"confirm_delete");
}
print '<table class="border" width="100%">';
$linkback = '<a href="'.DOL_URL_ROOT.'/compta/bank/index.php">'.$langs->trans("BackToList").'</a>';
// Ref
print '<tr><td valign="top" width="25%">'.$langs->trans("Ref").'</td>';
print '<td colspan="3">';
print $form->showrefnav($account, 'ref', $linkback, 1, 'ref');
print '</td></tr>';
// Label
print '<tr><td valign="top">'.$langs->trans("Label").'</td>';
print '<td colspan="3">'.$account->label.'</td></tr>';
// Type
print '<tr><td valign="top">'.$langs->trans("AccountType").'</td>';
print '<td colspan="3">'.$account->type_lib[$account->type].'</td></tr>';
// Currency
print '<tr><td valign="top">'.$langs->trans("Currency").'</td>';
print '<td colspan="3">';
$selectedcode=$account->account_currency_code;
if (! $selectedcode) $selectedcode=$conf->currency;
print $langs->trans("Currency".$selectedcode);
print '</td></tr>';
// Status
print '<tr><td valign="top">'.$langs->trans("Status").'</td>';
print '<td colspan="3">'.$account->getLibStatut(4).'</td></tr>';
// Country
print '<tr><td>'.$langs->trans("BankAccountCountry").'</td><td>';
if ($account->country_id > 0)
{
$img=picto_from_langcode($account->country_code);
print $img?$img.' ':'';
print getCountry($account->getCountryCode(),0,$db);
}
print '</td></tr>';
// State
print '<tr><td>'.$langs->trans('State').'</td><td>';
if ($account->fk_departement > 0) print getState($account->fk_departement);
print '</td></tr>';
// Conciliate
print '<tr><td valign="top">'.$langs->trans("Conciliable").'</td>';
print '<td colspan="3">';
$conciliate=$account->canBeConciliated();
if ($conciliate == -2) print $langs->trans("No").' ('.$langs->trans("CashAccount").')';
else if ($conciliate == -3) print $langs->trans("No").' ('.$langs->trans("Closed").')';
else print ($account->rappro==1 ? $langs->trans("Yes") : ($langs->trans("No").' ('.$langs->trans("ConciliationDisabled").')'));
print '</td></tr>';
// Accountancy code
print '<tr><td valign="top">'.$langs->trans("AccountancyCode").'</td>';
print '<td colspan="3">'.$account->account_number.'</td></tr>';
print '<tr><td valign="top">'.$langs->trans("BalanceMinimalAllowed").'</td>';
print '<td colspan="3">'.$account->min_allowed.'</td></tr>';
print '<tr><td valign="top">'.$langs->trans("BalanceMinimalDesired").'</td>';
print '<td colspan="3">'.$account->min_desired.'</td></tr>';
print '<tr><td valign="top">'.$langs->trans("Web").'</td><td colspan="3">';
if ($account->url) print '<a href="'.$account->url.'" target="_gobank">';
print $account->url;
if ($account->url) print '</a>';
print "</td></tr>\n";
print '<tr><td valign="top">'.$langs->trans("Comment").'</td>';
print '<td colspan="3">'.$account->comment.'</td></tr>';
print '</table>';
print '</div>';
/*
* Barre d'actions
*/
print '<div class="tabsAction">';
if ($user->rights->banque->configurer)
{
print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=edit&id='.$account->id.'">'.$langs->trans("Modify").'</a>';
}
$canbedeleted=$account->can_be_deleted(); // Renvoi vrai si compte sans mouvements
if ($user->rights->banque->configurer && $canbedeleted)
{
print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?action=delete&id='.$account->id.'">'.$langs->trans("Delete").'</a>';
}
print '</div>';
}
/* ************************************************************************** */
/* */
/* Edition */
/* */
/* ************************************************************************** */
if (GETPOST('id','int') && $action == 'edit' && $user->rights->banque->configurer)
{
$account = new Account($db);
$account->fetch(GETPOST('id','int'));
print_fiche_titre($langs->trans("EditFinancialAccount"));
print "<br>";
if ($message) { print "$message<br>\n"; }
if ($conf->use_javascript_ajax)
{
print "\n".'<script type="text/javascript" language="javascript">';
print 'jQuery(document).ready(function () {
jQuery("#selectaccount_country_id").change(function() {
document.formsoc.action.value="edit";
document.formsoc.submit();
});
})';
print '</script>'."\n";
}
print '<form action="'.$_SERVER["PHP_SELF"].'?id='.$account->id.'" method="post" name="formsoc">';
print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
print '<input type="hidden" name="action" value="update">';
print '<input type="hidden" name="id" value="'.$_REQUEST["id"].'">'."\n\n";
print '<table class="border" width="100%">';
// Ref
print '<tr><td valign="top" class="fieldrequired">'.$langs->trans("Ref").'</td>';
print '<td colspan="3"><input size="8" type="text" class="flat" name="ref" value="'.(isset($_POST["ref"])?$_POST["ref"]:$account->ref).'"></td></tr>';
// Label
print '<tr><td valign="top" class="fieldrequired">'.$langs->trans("Label").'</td>';
print '<td colspan="3"><input size="30" type="text" class="flat" name="label" value="'.(isset($_POST["label"])?$_POST["label"]:$account->label).'"></td></tr>';
// Type
print '<tr><td valign="top" class="fieldrequired">'.$langs->trans("AccountType").'</td>';
print '<td colspan="3">';
print $formbank->select_type_comptes_financiers((isset($_POST["type"])?$_POST["type"]:$account->type),"type");
print '</td></tr>';
// Currency
print '<tr><td valign="top" class="fieldrequired">'.$langs->trans("Currency");
print '<input type="hidden" value="'.$account->currency_code.'">';
print '</td>';
print '<td colspan="3">';
$selectedcode=$account->account_currency_code;
if (! $selectedcode) $selectedcode=$conf->currency;
$form->select_currency((isset($_POST["account_currency_code"])?$_POST["account_currency_code"]:$selectedcode), 'account_currency_code');
//print $langs->trans("Currency".$conf->currency);
//print '<input type="hidden" name="account_currency_code" value="'.$conf->currency.'">';
print '</td></tr>';
// Status
print '<tr><td valign="top" class="fieldrequired">'.$langs->trans("Status").'</td>';
print '<td colspan="3">';
print $form->selectarray("clos",array(0=>$account->status[0],1=>$account->status[1]),(isset($_POST["clos"])?$_POST["clos"]:$account->clos));
print '</td></tr>';
// Country
$account->country_id=$account->country_id?$account->country_id:$mysoc->country_id;
print '<tr><td valign="top" class="fieldrequired">'.$langs->trans("Country").'</td>';
print '<td colspan="3">';
$selectedcode=$account->country_code;
if (isset($_POST["account_country_id"])) $selectedcode=$_POST["account_country_id"];
else if (empty($selectedcode)) $selectedcode=$mysoc->country_code;
print $form->select_country($selectedcode,'account_country_id');
if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
print '</td></tr>';
// State
print '<tr><td>'.$langs->trans('State').'</td><td colspan="3">';
if ($selectedcode)
{
print $formcompany->select_state(isset($_POST["account_state_id"])?$_POST["account_state_id"]:$account->state_id,$selectedcode,'account_state_id');
}
else
{
print $countrynotdefined;
}
print '</td></tr>';
// Conciliable
print '<tr><td valign="top">'.$langs->trans("Conciliable").'</td>';
print '<td colspan="3">';
$conciliate=$account->canBeConciliated();
if ($conciliate == -2) print $langs->trans("No").' ('.$langs->trans("CashAccount").')';
else if ($conciliate == -3) print $langs->trans("No").' ('.$langs->trans("Closed").')';
else print '<input type="checkbox" class="flat" name="norappro"'.($account->rappro?'':' checked="checked"').'"> '.$langs->trans("DisableConciliation");
print '</td></tr>';
// Accountancy code
if (! empty($conf->global->MAIN_BANK_ACCOUNTANCY_CODE_ALWAYS_REQUIRED))
{
print '<tr><td valign="top" class="fieldrequired">'.$langs->trans("AccountancyCode").'</td>';
print '<td colspan="3"><input type="text" name="account_number" value="'.(isset($_POST["account_number"])?$_POST["account_number"]:$account->account_number).'"></td></tr>';
}
else
{
print '<tr><td valign="top">'.$langs->trans("AccountancyCode").'</td>';
print '<td colspan="3"><input type="text" name="account_number" value="'.(isset($_POST["account_number"])?$_POST["account_number"]:$account->account_number).'"></td></tr>';
}
// Balance
print '<tr><td valign="top">'.$langs->trans("BalanceMinimalAllowed").'</td>';
print '<td colspan="3"><input size="12" type="text" class="flat" name="account_min_allowed" value="'.(isset($_POST["account_min_allowed"])?$_POST["account_min_allowed"]:$account->min_allowed).'"></td></tr>';
print '<tr><td valign="top">'.$langs->trans("BalanceMinimalDesired").'</td>';
print '<td colspan="3"><input size="12" type="text" class="flat" name="account_min_desired" value="'.(isset($_POST["account_min_desired"])?$_POST["account_min_desired"]:$account->min_desired).'"></td></tr>';
// Web
print '<tr><td valign="top">'.$langs->trans("Web").'</td>';
print '<td colspan="3"><input size="50" type="text" class="flat" name="url" value="'.(isset($_POST["url"])?$_POST["url"]:$account->url).'">';
print '</td></tr>';
// Comment
print '<tr><td valign="top">'.$langs->trans("Comment").'</td>';
print '<td colspan="3">';
// Editor wysiwyg
require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
$doleditor=new DolEditor('account_comment',(isset($_POST["account_comment"])?$_POST["account_comment"]:$account->comment),'',200,'dolibarr_notes','',false,true,$conf->global->FCKEDITOR_ENABLE_SOCIETE,10,70);
$doleditor->Create();
print '</td></tr>';
print '<tr><td align="center" colspan="4"><input value="'.$langs->trans("Modify").'" type="submit" class="button">';
print ' <input name="cancel" value="'.$langs->trans("Cancel").'" type="submit" class="button">';
print '</td></tr>';
print '</table>';
print '</form>';
}
}
$db->close();
llxFooter();
?>
|
syrus34/dolibarr
|
htdocs/compta/bank/fiche.php
|
PHP
|
gpl-3.0
| 24,955
|
#pragma once
#include "../Game/Enumeration.h"
namespace ToD
{
namespace Events
{
////////////////////////////////////////////////////////////
/// \brief Declares supported render priorities.
///
////////////////////////////////////////////////////////////
class EventType :
public Enumeration<EventType>
{
/// Enumeation values
public:
////////////////////////////////////////////////////////////
/// \brief No event type is specified.
///
////////////////////////////////////////////////////////////
EnumerationDeclaration__(None, 0)
////////////////////////////////////////////////////////////
/// \brief Raised before a game object is deleted.
///
////////////////////////////////////////////////////////////
EnumerationDeclaration__(GameObjectDeleting, 1)
////////////////////////////////////////////////////////////
/// \brief Raised when a SFML event is processed.
///
////////////////////////////////////////////////////////////
EnumerationDeclaration__(SfmlEvent, 2)
////////////////////////////////////////////////////////////
/// \brief Raised when the mouse moved.
///
////////////////////////////////////////////////////////////
EnumerationDeclaration__(MouseMoved, 3)
////////////////////////////////////////////////////////////
/// \brief Raised when the grid cursor was updated.
///
////////////////////////////////////////////////////////////
EnumerationDeclaration__(GridCursorUpdated, 4)
////////////////////////////////////////////////////////////
/// \brief Raised when the grid cursor was clicked.
///
////////////////////////////////////////////////////////////
EnumerationDeclaration__(GridCursorClicked, 5)
////////////////////////////////////////////////////////////
/// \brief Raised when the game loaded a map.
///
////////////////////////////////////////////////////////////
EnumerationDeclaration__(GameMapLoaded, 6)
////////////////////////////////////////////////////////////
/// \brief Raised when the game unloaded a map.
///
////////////////////////////////////////////////////////////
EnumerationDeclaration__(GameMapUnloaded, 7)
////////////////////////////////////////////////////////////
/// \brief Raised when a GUI element is entered.
///
////////////////////////////////////////////////////////////
EnumerationDeclaration__(GuiElementEntering, 8)
////////////////////////////////////////////////////////////
/// \brief Raised when a GUI element is left.
///
////////////////////////////////////////////////////////////
EnumerationDeclaration__(GuiElementLeaving, 9)
////////////////////////////////////////////////////////////
/// \brief Raised when the end turn button was clicked.
///
////////////////////////////////////////////////////////////
EnumerationDeclaration__(GuiEndTurnButtonClicked, 10)
////////////////////////////////////////////////////////////
/// \brief Raised when the end turn button was clicked.
///
////////////////////////////////////////////////////////////
EnumerationDeclaration__(GuiReturnToMainMenuButtonClicked, 11)
////////////////////////////////////////////////////////////
/// \brief Raised when a playable character is activated.
///
////////////////////////////////////////////////////////////
EnumerationDeclaration__(PlayableCharacterActivated, 12)
////////////////////////////////////////////////////////////
/// \brief Raised when a playable character is deactivated.
///
////////////////////////////////////////////////////////////
EnumerationDeclaration__(PlayableCharacterDeactivated, 13)
////////////////////////////////////////////////////////////
/// \brief Raised when the turn system sets the next character active.
///
////////////////////////////////////////////////////////////
EnumerationDeclaration__(TurnSystemNextCharacter, 14)
////////////////////////////////////////////////////////////
/// \brief Raised when the turn system is shutting down.
///
////////////////////////////////////////////////////////////
EnumerationDeclaration__(TurnSystemShuttingDown, 15)
////////////////////////////////////////////////////////////
/// \brief Raised when a character requests the walkable area.
///
////////////////////////////////////////////////////////////
EnumerationDeclaration__(TurnSystemCharacterRequestsWalkableArea, 16)
////////////////////////////////////////////////////////////
/// \brief Raised when the walkable area response is sent.
///
////////////////////////////////////////////////////////////
EnumerationDeclaration__(TurnSystemCharacterResponseWalkableArea, 17)
////////////////////////////////////////////////////////////
/// \brief Raised when a character requests a walkable path.
///
////////////////////////////////////////////////////////////
EnumerationDeclaration__(TurnSystemCharacterRequestsWalkablePath, 18)
////////////////////////////////////////////////////////////
/// \brief Raised when the walkable path response is sent.
///
////////////////////////////////////////////////////////////
EnumerationDeclaration__(TurnSystemCharacterResponseWalkablePath, 19)
////////////////////////////////////////////////////////////
/// \brief Raised when the walkable path was updated due to player movement.
///
////////////////////////////////////////////////////////////
EnumerationDeclaration__(TurnSystemCharacterWalkablePathUpdated, 20)
////////////////////////////////////////////////////////////
/// \brief Raised when a character starts moving.
///
////////////////////////////////////////////////////////////
EnumerationDeclaration__(TurnSystemCharacterStartsMoving, 21)
////////////////////////////////////////////////////////////
/// \brief Raised when a character ends moving.
///
////////////////////////////////////////////////////////////
EnumerationDeclaration__(TurnSystemCharacterEndsMoving, 22)
////////////////////////////////////////////////////////////
/// \brief Raised when a character ends their turn active.
///
////////////////////////////////////////////////////////////
EnumerationDeclaration__(TurnSystemCharacterEndsTurn, 23)
////////////////////////////////////////////////////////////
/// \brief Raised when a grid cell was clicked.
///
////////////////////////////////////////////////////////////
EnumerationDeclaration__(GridCellClicked, 24)
/// Constructors, destructors
private:
////////////////////////////////////////////////////////////
/// \brief The constructor (default constructor).
///
////////////////////////////////////////////////////////////
EventType() IsDefault__;
////////////////////////////////////////////////////////////
/// \brief The destructor.
///
////////////////////////////////////////////////////////////
~EventType() IsDefault__;
/// Properties
public:
////////////////////////////////////////////////////////////
/// \brief Gets the static runtime type.
///
/// \return The static runtime type.
///
////////////////////////////////////////////////////////////
static string RuntimeType();
};
}
}
|
AndreasLang1204/TowerOfDoom
|
src/Engine/Events/EventType.h
|
C
|
gpl-3.0
| 7,370
|
<?php
include("config.php");
if(!isset($login_session))
{
header("location:index.php");
}
$findPriv = "select priv from login where username like '".$username."'";//echo "$findPriv";
$resPriv = mysqli_query($conn,$findPriv);
$rowPriv = mysqli_fetch_assoc($resPriv);
$prev = $rowPriv['priv'];//echo "$prev";
?>
<!DOCTYPE html>
<html>
<head>
<title>Bill</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="js/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<link rel="stylesheet" href="css/jqui.css">
<script src="jq_cal1.js"></script>
<script src="js/jq_cal2.js"></script>
<!-- for datepicker -->
<script type="text/javascript" src="datepicker/bootstrap-datepicker.min.js"></script>
<link rel="stylesheet" type="text/css" href="datepicker/bootstrap-datepicker3.css">
</head>
<style type="text/css">
#header-image {
width: 100%;
}
th{
background-color: 333333;
color: white;
}
html {
min-height: 100%;
position: relative;
}
body {
/* Margin bottom by footer height */
margin-bottom: 60px;
}
#footer {
position: absolute;
bottom: 0;
width: 100%;
min-height: 80px;
height: 60px;
background-color: rgba(0,0,0,0.7);
}
.top-form {
position: absolute;
background-color: #f3f3f3;
height: 400px;
width: 100%;
border: solid;
}
.main-form {
position: absolute;
margin-top: 400px;
align-self: center;
align-content: center;
}
select{
text-transform: uppercase;
}
</style>
<script>
$( function() {
$( ".datepicker" ).datepicker();
} );
</script>
<script type="text/javascript">
var tableToExcel = (function() {
var uri = 'data:application/vnd.ms-excel;base64,'
, template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
, base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
return function(table, name) {
if (!table.nodeType) table = document.getElementById(table)
var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
window.location.href = uri + base64(format(template, ctx))
}
})()
</script>
<nav role="navigation" class="navbar navbar-default navbar-static-top hidden-print" style="width: 100%;position: fixed;box-shadow: 3px 3px 3px;">
<div class="container ">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" data-target="#navbarCollapse" data-toggle="collapse" class="navbar-toggle">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a href="http://www.gechassan.ac.in" class="navbar-brand"><b>GECH</b></a>
</div>
<!-- Collection of nav links and other content for toggling -->
<div id="navbarCollapse" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="attendance.php">Attendance</a></li>
<li><a href="edit.php">Edit</a></li>
<?php if($prev == '1') echo '<li><a href="papers.php">Daily Papers</a></li>'; ?>
<li class="active"><a href="billing.php">Generate Bill</a></li>
<li><a href="history.php">History</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"><b><?php echo "$username "; ?> <span class="glyphicon glyphicon-user"></span><span class="caret"></span></b></span></a>
<ul class="dropdown-menu">
<li><a style="width: 150px;" href="update.php">Update Profile</a></li>
<li role="separator" class="divider"></li>
<li><a style="width: 150px;" href="logout.php">Log out</a></li>
</ul>
</li>
<li><a><b><?php echo "".date("Y-m-d").""; ?></b></a></li>
</ul>
</div>
</div>
<img id="header-image" src="images/header2.png">
</nav>
<body>
<?php
if (isset($_GET['date'])) {
$date = $_GET['date'];
}
else {
$date = date("Y-m", strtotime("first day of this month -1 day"));//echo "$date";
}
$monthDays = "select day(last_day('".$date."-01')) as lastDay";
$resMonthDays = mysqli_query($conn,$monthDays);
$rowMonthDays = mysqli_fetch_assoc($resMonthDays);
$lastDay = $rowMonthDays['lastDay'];
echo '<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<table class="table table-hover table-striped" border="1" style="border-style: solid;" id="testTable" align="center" style="text-transform: uppercase;width:90%;">
<tr><th colspan = "'.($lastDay+3).'">Daywise Report</th></tr>
';
echo "<tr><th>Papers</th>";
for ($i=1; $i <= $lastDay; $i++) {
echo "<th>$i</th>";
}
echo "</tr>";
$listPapers = "select paper from cost";
$resPapers = mysqli_query($conn,$listPapers);
$count = '1';
while ($rowPapers = mysqli_fetch_assoc($resPapers)) {
echo "<tr><th colspan='1' style=''>".$rowPapers['paper']."</th>";
for ($i=1; $i <= $lastDay; $i++) {
if($i<10)
{
$append = '0';
}
else
{
$append = '';
}
$listAttendance = "select delivery from attendance where paper like '".$rowPapers['paper']."' and date like '".$date."-$append$i'";
//echo "$listAttendance";
$resListAttendance = mysqli_query($conn,$listAttendance);
if(mysqli_num_rows($resListAttendance)=='0')
{
echo "<td><img src='images/wrong.png' style='height:20px;'></td>";
}
else {
while ($rowAttendance = mysqli_fetch_assoc($resListAttendance)) {
if ($rowAttendance['delivery'] == 'yes') {
echo "<td><img src='images/right.png' style='height:20px;'></td>";
}
if ($rowAttendance['delivery'] == 'no') {
echo "<td><img src='images/wrong.png' style='height:20px;'></td>";
}
}
}
}
}
?>
<!-- <a target="_blank" href="mpdf/bill_generation/pdfDailyAttendance.php?date=<?php echo "$date"; ?>"><button class="btn-lg btn-primary hidden-print" >Generate PDF Report</button></a>-->
<button class="btn-lg btn-primary hidden-print" onclick="window.print()">Generate PDF Report</button>
<br><br>
</body>
</html>
<script>
//$("#date").datepicker();
$("#date").datepicker( {
format: "yyyy-mm",
startView: "months",
minViewMode: "months",
endDate: "-1m"
});
$("#date").on("keyup", function(e) {
var date, day, month, newYear, value, year;
value = e.target.value;
if (value.search(/(.*)\/(.*)\/(.*)/) !== -1) {
date = e.target.value.split("/");
year = date[2];
month = date[0];
if (year === "") {
year = "0";
}
if (year.length < 4) {
newYear = String(2000 + parseInt(year));
$(this).datepicker("setValue", "" + newYear + "/" + month + "/" + day);
if (year === "0") {
year = "";
}
return $(this).val("" + year + "/" + month + "/" + day);
}
}
});
</script>
<?php
function showMonth($month, $year)
{
$date = mktime(12, 0, 0, $month, 1, $year);
$daysInMonth = date("t", $date);
// calculate the position of the first day in the calendar (sunday = 1st column, etc)
$offset = date("w", $date);
$rows = 1;
echo "<table border=\"0\" style='text-align:center;' >\n";
echo "<tr ><td colspan='7'>" . date("F Y", $date) . "</td></tr>\n";
echo "\t<tr ><th style='width:30px;' >Su</th><th style='width:30px;'>M</th><th style='width:30px;'>Tu</th><th style='width:30px;'>W</th><th style='width:30px;'>Th</th style='width:30px;'><th style='width:30px;'>F</th><th style='width:30px;'>Sa</th></tr>";
echo "\n\t<tr>";
for($i = 1; $i <= $offset; $i++)
{
echo "<td></td>";
}
for($day = 1; $day <= $daysInMonth; $day++)
{
if( ($day + $offset - 1) % 7 == 0 && $day != 1)
{
echo "</tr>\n\t<tr>";
$rows++;
}
echo "<td>" . $day . "</td>";
}
while( ($day + $offset) <= $rows * 7)
{
echo "<td></td>";
$day++;
}
echo "</tr>\n";
echo "</table>\n";
}
?>
|
vinayakowndinya/-newspaper-billing-system-GECH
|
dayWiseReport.php
|
PHP
|
gpl-3.0
| 8,917
|
<?php
/*
WildPHP - a modular and easily extendable IRC bot written in PHP
Copyright (C) 2015 WildPHP
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace WildPHP\Modules;
use WildPHP\BaseModule;
class ChannelManager extends BaseModule
{
/**
* List of channels the bot is currently in.
*/
private $channels = array();
/**
* The Auth module's object.
* @var \WildPHP\Modules\Auth
*/
private $auth;
/**
* Dependencies of this module.
* @var string[]
*/
protected static $dependencies = array('Auth');
/**
* Set up the module.
* @throws \Exception
*/
public function setup()
{
// Register our commands.
$this->evman()->register(array('command_join', 'command_part'), array('hook_once' => true));
$this->evman()->registerListener('command_join', array($this, 'JoinCommand'));
$this->evman()->registerListener('command_part', array($this, 'PartCommand'));
// We also have a listener.
$this->evman()->registerListener('data_receive', array($this, 'initialJoin'));
// Register any custom events.
$this->evman()->register(array('initial_join', 'join_channel'));
// Get the auth module.
$this->auth = $this->bot->getModuleInstance('Auth');
}
/**
* Returns the module dependencies.
* @return array The array containing the module names of the dependencies.
*/
public static function getDependencies()
{
return array('Auth');
}
/**
* The Join command.
* @param array $data The last data received.
*/
public function JoinCommand($data)
{
if (empty($data['command_args']))
return;
if (!$this->auth->authUser($data['prefix']))
return;
// Join all specified channels.
$c = explode(' ', $data['command_args']);
foreach ($c as $chan)
{
$this->bot->log('Joining channel ' . $chan . '...', 'CHANMAN');
$this->channels[] = $chan;
$this->bot->sendData('JOIN ' . $chan);
}
}
/**
* The Part command.
* @param array $data The last data received.
*/
public function PartCommand($data)
{
if (!$this->auth->authUser($data['prefix']))
return;
// Part the current channel.
if (empty($data['command_args']))
$c = array($data['targets'][0]);
// Part all specified channels.
else
$c = explode(' ', $data['command_args']);
foreach ($c as $chan)
{
$this->bot->log('Parting channel ' . $chan . '...', 'CHANMAN');
$this->bot->sendData('PART ' . $chan);
}
}
/**
* This function handles the initial joining of channels.
* @param array $data The last data received.
*/
public function initialJoin($data)
{
// Are we ready?
$status = !empty($data['code']) && $data['code'] == 'RPL_ENDOFMOTD';
if (!$status)
return;
// Do any modules think we are ready?
$this->evman()->trigger('initial_join', array($this->bot->getConfig('channels')));
// And?
if ($status)
{
$channels = $this->bot->getConfig('channels');
foreach ($channels as $chan)
{
$this->joinChannel($chan);
}
$this->evman()->removeListener('onDataReceive', array($this, 'initialJoin'));
}
}
/**
* Join a channel.
* @param string $channel The channel name.
*/
public function joinChannel($channel)
{
if (empty($channel))
return;
$this->bot->sendData('JOIN ' . $channel);
$this->evman()->trigger('join_channel', array($channel));
}
}
|
Yoshi2889/FatalException
|
modules/ChannelManager/ChannelManager.php
|
PHP
|
gpl-3.0
| 3,905
|
/*
* tkButton.h --
*
* Declarations of types and functions used to implement button-like
* widgets.
*
* Copyright (c) 1996-1998 by Sun Microsystems, Inc.
*
* See the file "license.terms" for information on usage and redistribution of
* this file, and for a DISCLAIMER OF ALL WARRANTIES.
*/
#ifndef _TKBUTTON
#define _TKBUTTON
#ifndef _TKINT
#include "tkInt.h"
#endif
/*
* Legal values for the "compound" field of TkButton records.
*/
enum compound {
COMPOUND_BOTTOM, COMPOUND_CENTER, COMPOUND_LEFT, COMPOUND_NONE,
COMPOUND_RIGHT, COMPOUND_TOP
};
/*
* Legal values for the "state" field of TkButton records.
*/
enum state {
STATE_ACTIVE, STATE_DISABLED, STATE_NORMAL
};
/*
* Legal values for the "defaultState" field of TkButton records.
*/
enum defaultState {
DEFAULT_ACTIVE, DEFAULT_DISABLED, DEFAULT_NORMAL
};
/*
* A data structure of the following type is kept for each widget managed by
* this file:
*/
typedef struct {
Tk_Window tkwin; /* Window that embodies the button. NULL means
* that the window has been destroyed. */
Display *display; /* Display containing widget. Needed to free
* up resources after tkwin is gone. */
Tcl_Interp *interp; /* Interpreter associated with button. */
Tcl_Command widgetCmd; /* Token for button's widget command. */
int type; /* Type of widget, such as TYPE_LABEL:
* restricts operations that may be performed
* on widget. See below for legal values. */
Tk_OptionTable optionTable; /* Table that defines configuration options
* available for this widget. */
/*
* Information about what's in the button.
*/
Tcl_Obj *textPtr; /* Value of -text option: specifies text to
* display in button. */
int underline; /* Value of -underline option: specifies index
* of character to underline. < 0 means don't
* underline anything. */
Tcl_Obj *textVarNamePtr; /* Value of -textvariable option: specifies
* name of variable or NULL. If non-NULL,
* button displays the contents of this
* variable. */
Pixmap bitmap; /* Value of -bitmap option. If not None,
* specifies bitmap to display and text and
* textVar are ignored. */
Tcl_Obj *imagePtr; /* Value of -image option: specifies image to
* display in window, or NULL if none. If
* non-NULL, bitmap, text, and textVarName are
* ignored.*/
Tk_Image image; /* Derived from imagePtr by calling
* Tk_GetImage, or NULL if imagePtr is
* NULL. */
Tcl_Obj *selectImagePtr; /* Value of -selectimage option: specifies
* image to display in window when selected,
* or NULL if none. Ignored if imagePtr is
* NULL. */
Tk_Image selectImage; /* Derived from selectImagePtr by calling
* Tk_GetImage, or NULL if selectImagePtr is
* NULL. */
Tcl_Obj *tristateImagePtr; /* Value of -tristateimage option: specifies
* image to display in window when selected,
* or NULL if none. Ignored if imagePtr is
* NULL. */
Tk_Image tristateImage; /* Derived from tristateImagePtr by calling
* Tk_GetImage, or NULL if tristateImagePtr is
* NULL. */
/*
* Information used when displaying widget:
*/
enum state state; /* Value of -state option: specifies state of
* button for display purposes.*/
Tk_3DBorder normalBorder; /* Value of -background option: specifies
* color for background (and border) when
* window isn't active. */
Tk_3DBorder activeBorder; /* Value of -activebackground option: this is
* the color used to draw 3-D border and
* background when widget is active. */
Tcl_Obj *borderWidthPtr; /* Value of -borderWidth option: specifies
* width of border in pixels. */
int borderWidth; /* Integer value corresponding to
* borderWidthPtr. Always >= 0. */
int relief; /* Value of -relief option: specifies 3-d
* effect for border, such as
* TK_RELIEF_RAISED. */
int overRelief; /* Value of -overrelief option: specifies a
* 3-d effect for the border, such as
* TK_RELIEF_RAISED, to be used when the mouse
* is over the button. */
int offRelief; /* Value of -offrelief option: specifies a 3-d
* effect for the border, such as
* TK_RELIEF_RAISED, to be used when a
* checkbutton or radiobutton without
* indicator is off. */
Tcl_Obj *highlightWidthPtr; /* Value of -highlightthickness option:
* specifies width in pixels of highlight to
* draw around widget when it has the focus.
* <= 0 means don't draw a highlight. */
int highlightWidth; /* Integer value corresponding to
* highlightWidthPtr. Always >= 0. */
Tk_3DBorder highlightBorder;/* Value of -highlightbackground option:
* specifies background with which to draw 3-D
* default ring and focus highlight area when
* highlight is off. */
XColor *highlightColorPtr; /* Value of -highlightcolor option: specifies
* color for drawing traversal highlight. */
int inset; /* Total width of all borders, including
* traversal highlight and 3-D border.
* Indicates how much interior stuff must be
* offset from outside edges to leave room for
* borders. */
Tk_Font tkfont; /* Value of -font option: specifies font to
* use for display text. */
XColor *normalFg; /* Value of -font option: specifies foreground
* color in normal mode. */
XColor *activeFg; /* Value of -activeforeground option:
* foreground color in active mode. NULL means
* use -foreground instead. */
XColor *disabledFg; /* Value of -disabledforeground option:
* foreground color when disabled. NULL means
* use normalFg with a 50% stipple instead. */
GC normalTextGC; /* GC for drawing text in normal mode. Also
* used to copy from off-screen pixmap onto
* screen. */
GC activeTextGC; /* GC for drawing text in active mode (NULL
* means use normalTextGC). */
GC disabledGC; /* Used to produce disabled effect for text
* and check/radio marks. */
GC stippleGC; /* Used to produce disabled stipple effect for
* images when disabled. */
Pixmap gray; /* Pixmap for displaying disabled text if
* disabledFg is NULL. */
GC copyGC; /* Used for copying information from an
* off-screen pixmap to the screen. */
Tcl_Obj *widthPtr; /* Value of -width option. */
int width; /* Integer value corresponding to widthPtr. */
Tcl_Obj *heightPtr; /* Value of -height option. */
int height; /* Integer value corresponding to heightPtr. */
Tcl_Obj *wrapLengthPtr; /* Value of -wraplength option: specifies line
* length (in pixels) at which to wrap onto
* next line. <= 0 means don't wrap except at
* newlines. */
int wrapLength; /* Integer value corresponding to
* wrapLengthPtr. */
Tcl_Obj *padXPtr; /* Value of -padx option: specifies how many
* pixels of extra space to leave on left and
* right of text. Ignored for bitmaps and
* images. */
int padX; /* Integer value corresponding to padXPtr. */
Tcl_Obj *padYPtr; /* Value of -padx option: specifies how many
* pixels of extra space to leave above and
* below text. Ignored for bitmaps and
* images. */
int padY; /* Integer value corresponding to padYPtr. */
Tk_Anchor anchor; /* Value of -anchor option: specifies where
* text/bitmap should be displayed inside
* button region. */
Tk_Justify justify; /* Value of -justify option: specifies how to
* align lines of multi-line text. */
int indicatorOn; /* Value of -indicatoron option: 1 means draw
* indicator in checkbuttons and radiobuttons,
* 0 means don't draw it. */
Tk_3DBorder selectBorder; /* Value of -selectcolor option: specifies
* color for drawing indicator background, or
* perhaps widget background, when
* selected. */
int textWidth; /* Width needed to display text as requested,
* in pixels. */
int textHeight; /* Height needed to display text as requested,
* in pixels. */
Tk_TextLayout textLayout; /* Saved text layout information. */
int indicatorSpace; /* Horizontal space (in pixels) allocated for
* display of indicator. */
int indicatorDiameter; /* Diameter of indicator, in pixels. */
enum defaultState defaultState;
/* Value of -default option, such as
* DEFAULT_NORMAL: specifies state of default
* ring for buttons (normal, active, or
* disabled). NULL for other classes. */
/*
* For check and radio buttons, the fields below are used to manage the
* variable indicating the button's state.
*/
Tcl_Obj *selVarNamePtr; /* Value of -variable option: specifies name
* of variable used to control selected state
* of button. */
Tcl_Obj *onValuePtr; /* Value of -offvalue option: specifies value
* to store in variable when this button is
* selected. */
Tcl_Obj *offValuePtr; /* Value of -offvalue option: specifies value
* to store in variable when this button isn't
* selected. Used only by checkbuttons. */
Tcl_Obj *tristateValuePtr; /* Value of -tristatevalue option: specifies
* value to display Tristate or Multivalue
* mode when variable matches this value.
* Used by check- buttons. */
/*
* Miscellaneous information:
*/
Tk_Cursor cursor; /* Value of -cursor option: if not NULL,
* specifies current cursor for window. */
Tcl_Obj *takeFocusPtr; /* Value of -takefocus option; not used in the
* C code, but used by keyboard traversal
* scripts. */
Tcl_Obj *commandPtr; /* Value of -command option: specifies script
* to execute when button is invoked. If
* widget is label or has no command, this is
* NULL. */
int compound; /* Value of -compound option; specifies
* whether the button should show both an
* image and text, and, if so, how. */
int repeatDelay; /* Value of -repeatdelay option; specifies the
* number of ms after which the button will
* start to auto-repeat its command. */
int repeatInterval; /* Value of -repeatinterval option; specifies
* the number of ms between auto-repeat
* invocataions of the button command. */
int flags; /* Various flags; see below for
* definitions. */
} TkButton;
/*
* Possible "type" values for buttons. These are the kinds of widgets
* supported by this file. The ordering of the type numbers is significant:
* greater means more features and is used in the code.
*/
#define TYPE_LABEL 0
#define TYPE_BUTTON 1
#define TYPE_CHECK_BUTTON 2
#define TYPE_RADIO_BUTTON 3
/*
* Flag bits for buttons:
*
* REDRAW_PENDING: Non-zero means a DoWhenIdle handler has
* already been queued to redraw this window.
* SELECTED: Non-zero means this button is selected, so
* special highlight should be drawn.
* GOT_FOCUS: Non-zero means this button currently has the
* input focus.
* BUTTON_DELETED: Non-zero needs that this button has been
* deleted, or is in the process of being deleted
*/
#define REDRAW_PENDING (1 << 0)
#define SELECTED (1 << 1)
#define GOT_FOCUS (1 << 2)
#define BUTTON_DELETED (1 << 3)
#define TRISTATED (1 << 4)
/*
* Declaration of button class functions structure
* and button/label defaults, for use in optionSpecs.
*/
MODULE_SCOPE const Tk_ClassProcs tkpButtonProcs;
MODULE_SCOPE char tkDefButtonHighlightWidth[TCL_INTEGER_SPACE];
MODULE_SCOPE char tkDefButtonPadx[TCL_INTEGER_SPACE];
MODULE_SCOPE char tkDefButtonPady[TCL_INTEGER_SPACE];
MODULE_SCOPE char tkDefButtonBorderWidth[TCL_INTEGER_SPACE];
MODULE_SCOPE char tkDefLabelHighlightWidth[TCL_INTEGER_SPACE];
MODULE_SCOPE char tkDefLabelPadx[TCL_INTEGER_SPACE];
MODULE_SCOPE char tkDefLabelPady[TCL_INTEGER_SPACE];
/*
* Declaration of functions used in the implementation of the button widget.
*/
#ifndef TkpButtonSetDefaults
MODULE_SCOPE void TkpButtonSetDefaults(void);
#endif
MODULE_SCOPE void TkButtonWorldChanged(ClientData instanceData);
MODULE_SCOPE void TkpComputeButtonGeometry(TkButton *butPtr);
MODULE_SCOPE TkButton *TkpCreateButton(Tk_Window tkwin);
#ifndef TkpDestroyButton
MODULE_SCOPE void TkpDestroyButton(TkButton *butPtr);
#endif
#ifndef TkpDisplayButton
MODULE_SCOPE void TkpDisplayButton(ClientData clientData);
#endif
MODULE_SCOPE int TkInvokeButton(TkButton *butPtr);
#endif /* _TKBUTTON */
|
SAOImageDS9/SAOImageDS9
|
tk8.6/generic/tkButton.h
|
C
|
gpl-3.0
| 12,496
|
/**
* \file IMP/isd/HybridMonteCarlo.h
* \brief A hybrid monte carlo implementation
*
* Copyright 2007-2017 IMP Inventors. All rights reserved.
*
*/
#ifndef IMPISD_HYBRID_MONTE_CARLO_H
#define IMPISD_HYBRID_MONTE_CARLO_H
#include <IMP/isd/isd_config.h>
#include <IMP/core/MonteCarlo.h>
#include <IMP/isd/MolecularDynamics.h>
#include <IMP/isd/MolecularDynamicsMover.h>
#include <IMP/macros.h>
IMPISD_BEGIN_NAMESPACE
//! Hybrid Monte Carlo optimizer
// moves all xyz particles having a fixed mass with an MD proposal
class IMPISDEXPORT HybridMonteCarlo : public core::MonteCarlo {
public:
HybridMonteCarlo(Model *m, Float kT = 1.0, unsigned steps = 100,
Float timestep = 1.0, unsigned persistence = 1);
Float get_kinetic_energy() const;
Float get_potential_energy() const;
Float get_total_energy() const;
// set md timestep
void set_timestep(Float ts);
double get_timestep() const;
// set number of md steps per mc step
void set_number_of_md_steps(unsigned nsteps);
unsigned get_number_of_md_steps() const;
// set how many mc steps happen until you redraw the momenta
void set_persistence(unsigned persistence = 1);
unsigned get_persistence() const;
// return pointer to isd::MolecularDynamics instance
// useful if you want to set other stuff that is not exposed here
MolecularDynamics *get_md() const;
// evaluate should return the total energy
double do_evaluate(const ParticleIndexes &) const;
virtual void do_step();
IMP_OBJECT_METHODS(HybridMonteCarlo);
private:
unsigned num_md_steps_, persistence_;
unsigned persistence_counter_;
IMP::PointerMember<MolecularDynamicsMover> mv_;
Pointer<MolecularDynamics> md_;
};
IMPISD_END_NAMESPACE
#endif /* IMPISD_HYBRID_MONTE_CARLO_H */
|
shanot/imp
|
modules/isd/include/HybridMonteCarlo.h
|
C
|
gpl-3.0
| 1,778
|
Milesdatas::Application.routes.draw do
devise_for :users
resources :records
authenticated :user do
root :to => "records#index"
end
namespace :api do
devise_for :users
resources :records
match '/sessions/check_auth_token_validity', :controller => 'sessions', :action => 'check_auth_token_validity', :via => [:get]
end
# The priority is based upon order of creation:
# first created -> highest priority.
# Sample of regular route:
# match 'products/:id' => 'catalog#view'
# Keep in mind you can assign values other than :controller and :action
# Sample of named route:
# match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase
# This route can be invoked with purchase_url(:id => product.id)
# Sample resource route (maps HTTP verbs to controller actions automatically):
# resources :products
# Sample resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Sample resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Sample resource route with more complex sub-resources
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', :on => :collection
# end
# end
# Sample resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
# You can have the root of your site routed with "root"
# just remember to delete public/index.html.
root :to => redirect("/users/sign_in")
# See how all your routes lay out with "rake routes"
# This is a legacy wild controller route that's not recommended for RESTful applications.
# Note: This route will make all actions in every controller accessible via GET requests.
# match ':controller(/:action(/:id))(.:format)'
end
|
naysayer/miles_data_rails_iphone_auth
|
config/routes.rb
|
Ruby
|
gpl-3.0
| 2,112
|
'use strict'
/* globals describe it spyOn expect fail */
const pupilDataService = require('../../../services/data-access/pupil.data.service')
const pupilMock = require('../mocks/pupil')
const pupilAttendanceDataService = require('../../../services/data-access/pupil-attendance.data.service')
const redisCacheService = require('../../../services/data-access/redis-cache.service')
const service = require('../../../services/attendance.service')
describe('attendanceService', () => {
describe('#updatePupilAttendanceBySlug', () => {
it('just calls the data service', async () => {
spyOn(redisCacheService, 'drop')
const slugs = ['slug1', 'slug2', 'slug3']
const code = 'ABSNT'
const userId = 1
const schoolId = 7
spyOn(pupilAttendanceDataService, 'markAsNotAttending')
await service.updatePupilAttendanceBySlug(slugs, code, userId, schoolId)
expect(pupilAttendanceDataService.markAsNotAttending).toHaveBeenCalled()
})
})
describe('#unsetAttendanceCode', () => {
const pupilSlug = 'slug1'
const dfeNumber = 9991999
it('makes a call to get the pupil', async () => {
spyOn(pupilDataService, 'sqlFindOneBySlugAndSchool').and.returnValue({})
spyOn(pupilAttendanceDataService, 'sqlDeleteOneByPupilId').and.returnValue(Promise.resolve())
spyOn(redisCacheService, 'drop')
try {
await service.unsetAttendanceCode(pupilSlug, dfeNumber)
expect(pupilDataService.sqlFindOneBySlugAndSchool).toHaveBeenCalled()
} catch (error) {
fail(error.message)
}
})
it('throws if the pupil is not found', async () => {
spyOn(pupilDataService, 'sqlFindOneBySlugAndSchool')
spyOn(redisCacheService, 'drop')
try {
await service.unsetAttendanceCode(pupilSlug, dfeNumber)
fail('expected to throw')
} catch (error) {
expect(error.message).toBe(`Pupil with id ${pupilSlug} and school ${dfeNumber} not found`)
}
})
it('makes a call to delete the pupilAttendance record if the pupil is found', async () => {
spyOn(pupilDataService, 'sqlFindOneBySlugAndSchool').and.returnValue(Promise.resolve(pupilMock))
spyOn(pupilAttendanceDataService, 'sqlDeleteOneByPupilId').and.returnValue()
spyOn(redisCacheService, 'drop')
await service.unsetAttendanceCode(pupilSlug, dfeNumber)
expect(pupilAttendanceDataService.sqlDeleteOneByPupilId).toHaveBeenCalledWith(pupilMock.id)
})
})
describe('#hasAttendance', () => {
describe('for live env', () => {
it('returns valid if pupil has any attendance', async () => {
spyOn(pupilAttendanceDataService, 'findOneByPupilId').and.returnValue({ id: 'id', code: 'A' })
const result = await service.hasAttendance('id', 'live')
expect(result).toBe(true)
})
it('returns invalid if there is no attendance', async () => {
spyOn(pupilAttendanceDataService, 'findOneByPupilId').and.returnValue(undefined)
const result = await service.hasAttendance('id', 'live')
expect(result).toBe(false)
})
})
describe('for familiarisation env', () => {
it('returns valid if pupil has left school attendance', async () => {
spyOn(pupilAttendanceDataService, 'findOneByPupilId').and.returnValue({ id: 'id', code: 'LEFTT' })
const result = await service.hasAttendance('id', 'familiarisation')
expect(result).toBe(true)
})
it('returns invalid if pupil has other attendance than left school', async () => {
spyOn(pupilAttendanceDataService, 'findOneByPupilId').and.returnValue({ id: 'id', code: 'A' })
const result = await service.hasAttendance('id', 'familiarisation')
expect(result).toBe(false)
})
it('returns invalid if there is no attendance', async () => {
spyOn(pupilAttendanceDataService, 'findOneByPupilId').and.returnValue(undefined)
const result = await service.hasAttendance('id', 'familiarisation')
expect(result).toBe(false)
})
})
})
})
|
DFEAGILEDEVOPS/MTC
|
admin/spec/back-end/service/attendance.service.spec.js
|
JavaScript
|
gpl-3.0
| 4,062
|
// Decompiled with JetBrains decompiler
// Type: System.ComponentModel.Design.CommandID
// Assembly: System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// MVID: 5ABD58FD-DF31-44FD-A492-63F2B47CC9AF
// Assembly location: C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.dll
using System;
using System.Globalization;
using System.Runtime;
using System.Runtime.InteropServices;
using System.Security.Permissions;
namespace System.ComponentModel.Design
{
/// <summary>
/// Represents a unique command identifier that consists of a numeric command ID and a GUID menu group identifier.
/// </summary>
[ComVisible(true)]
[PermissionSet(SecurityAction.InheritanceDemand, Name = "FullTrust")]
[PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")]
[HostProtection(SecurityAction.LinkDemand, SharedState = true)]
public class CommandID
{
private readonly Guid menuGroup;
private readonly int commandID;
/// <summary>
/// Gets the numeric command ID.
/// </summary>
///
/// <returns>
/// The command ID number.
/// </returns>
public virtual int ID
{
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get
{
return this.commandID;
}
}
/// <summary>
/// Gets the GUID of the menu group that the menu command identified by this <see cref="T:System.ComponentModel.Design.CommandID"/> belongs to.
/// </summary>
///
/// <returns>
/// The GUID of the command group for this command.
/// </returns>
public virtual Guid Guid
{
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get
{
return this.menuGroup;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="T:System.ComponentModel.Design.CommandID"/> class using the specified menu group GUID and command ID number.
/// </summary>
/// <param name="menuGroup">The GUID of the group that this menu command belongs to. </param><param name="commandID">The numeric identifier of this menu command. </param>
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public CommandID(Guid menuGroup, int commandID)
{
this.menuGroup = menuGroup;
this.commandID = commandID;
}
/// <summary>
/// Determines whether two <see cref="T:System.ComponentModel.Design.CommandID"/> instances are equal.
/// </summary>
///
/// <returns>
/// true if the specified object is equivalent to this one; otherwise, false.
/// </returns>
/// <param name="obj">The object to compare. </param>
public override bool Equals(object obj)
{
if (!(obj is CommandID))
return false;
CommandID commandId = (CommandID) obj;
if (commandId.menuGroup.Equals(this.menuGroup))
return commandId.commandID == this.commandID;
return false;
}
/// <returns>
/// A hash code for the current <see cref="T:System.Object"/>.
/// </returns>
public override int GetHashCode()
{
return this.menuGroup.GetHashCode() << 2 | this.commandID;
}
/// <summary>
/// Returns a <see cref="T:System.String"/> that represents the current object.
/// </summary>
///
/// <returns>
/// A string that contains the command ID information, both the GUID and integer identifier.
/// </returns>
public override string ToString()
{
return this.menuGroup.ToString() + " : " + this.commandID.ToString((IFormatProvider) CultureInfo.CurrentCulture);
}
}
}
|
mater06/LEGOChimaOnlineReloaded
|
LoCO Client Files/Decompressed Client/Extracted DLL/System/System/ComponentModel/Design/CommandID.cs
|
C#
|
gpl-3.0
| 3,701
|
/*
Copyright (c) 2007-2011 iMatix Corporation
Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
This file is part of 0MQ.
0MQ is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
0MQ is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "platform.hpp"
#if defined ZMQ_FORCE_SELECT
#define ZMQ_SIGNALER_WAIT_BASED_ON_SELECT
#elif defined ZMQ_FORCE_POLL
#define ZMQ_SIGNALER_WAIT_BASED_ON_POLL
#elif defined ZMQ_HAVE_LINUX || defined ZMQ_HAVE_FREEBSD ||\
defined ZMQ_HAVE_OPENBSD || defined ZMQ_HAVE_SOLARIS ||\
defined ZMQ_HAVE_OSX || defined ZMQ_HAVE_QNXNTO ||\
defined ZMQ_HAVE_HPUX || defined ZMQ_HAVE_AIX ||\
defined ZMQ_HAVE_NETBSD
#define ZMQ_SIGNALER_WAIT_BASED_ON_POLL
#elif defined ZMQ_HAVE_WINDOWS || defined ZMQ_HAVE_OPENVMS
#define ZMQ_SIGNALER_WAIT_BASED_ON_SELECT
#endif
// On AIX, poll.h has to be included before zmq.h to get consistent
// definition of pollfd structure (AIX uses 'reqevents' and 'retnevents'
// instead of 'events' and 'revents' and defines macros to map from POSIX-y
// names to AIX-specific names).
#if defined ZMQ_SIGNALER_WAIT_BASED_ON_POLL
#include <poll.h>
#elif defined ZMQ_SIGNALER_WAIT_BASED_ON_SELECT
#if defined ZMQ_HAVE_WINDOWS
#include "windows.hpp"
#elif defined ZMQ_HAVE_HPUX
#include <sys/param.h>
#include <sys/types.h>
#include <sys/time.h>
#elif defined ZMQ_HAVE_OPENVMS
#include <sys/types.h>
#include <sys/time.h>
#else
#include <sys/select.h>
#endif
#endif
#include "signaler.hpp"
#include "likely.hpp"
#include "err.hpp"
#include "fd.hpp"
#include "ip.hpp"
#if defined ZMQ_HAVE_WINDOWS
#include "windows.hpp"
#else
#include <unistd.h>
#include <fcntl.h>
#include <limits.h>
#include <netinet/tcp.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#endif
zmq::signaler_t::signaler_t ()
{
// Create the socketpair for signaling.
int rc = make_fdpair (&r, &w);
errno_assert (rc == 0);
// Set both fds to non-blocking mode.
#if defined ZMQ_HAVE_WINDOWS
unsigned long argp = 1;
rc = ioctlsocket (w, FIONBIO, &argp);
wsa_assert (rc != SOCKET_ERROR);
rc = ioctlsocket (r, FIONBIO, &argp);
wsa_assert (rc != SOCKET_ERROR);
#else
int flags = fcntl (w, F_GETFL, 0);
errno_assert (flags >= 0);
rc = fcntl (w, F_SETFL, flags | O_NONBLOCK);
errno_assert (rc == 0);
flags = fcntl (r, F_GETFL, 0);
errno_assert (flags >= 0);
rc = fcntl (r, F_SETFL, flags | O_NONBLOCK);
errno_assert (rc == 0);
#endif
}
zmq::signaler_t::~signaler_t ()
{
#if defined ZMQ_HAVE_WINDOWS
int rc = closesocket (w);
wsa_assert (rc != SOCKET_ERROR);
rc = closesocket (r);
wsa_assert (rc != SOCKET_ERROR);
#else
close (w);
close (r);
#endif
}
zmq::fd_t zmq::signaler_t::get_fd ()
{
return r;
}
void zmq::signaler_t::send ()
{
#if defined ZMQ_HAVE_WINDOWS
unsigned char dummy = 0;
int nbytes = ::send (w, (char*) &dummy, sizeof (dummy), 0);
wsa_assert (nbytes != SOCKET_ERROR);
zmq_assert (nbytes == sizeof (dummy));
#else
unsigned char dummy = 0;
while (true) {
ssize_t nbytes = ::send (w, &dummy, sizeof (dummy), 0);
if (unlikely (nbytes == -1 && errno == EINTR))
continue;
zmq_assert (nbytes == sizeof (dummy));
break;
}
#endif
}
int zmq::signaler_t::wait (int timeout_)
{
#ifdef ZMQ_SIGNALER_WAIT_BASED_ON_POLL
struct pollfd pfd;
pfd.fd = r;
pfd.events = POLLIN;
int rc = poll (&pfd, 1, timeout_);
if (unlikely (rc < 0)) {
zmq_assert (errno == EINTR);
return -1;
}
else if (unlikely (rc == 0)) {
errno = EAGAIN;
return -1;
}
zmq_assert (rc == 1);
zmq_assert (pfd.revents & POLLIN);
return 0;
#elif defined ZMQ_SIGNALER_WAIT_BASED_ON_SELECT
fd_set fds;
FD_ZERO (&fds);
FD_SET (r, &fds);
struct timeval timeout;
if (timeout_ >= 0) {
timeout.tv_sec = timeout_ / 1000;
timeout.tv_usec = timeout_ % 1000 * 1000;
}
#ifdef ZMQ_HAVE_WINDOWS
int rc = select (0, &fds, NULL, NULL,
timeout_ >= 0 ? &timeout : NULL);
wsa_assert (rc != SOCKET_ERROR);
#else
int rc = select (r + 1, &fds, NULL, NULL,
timeout_ >= 0 ? &timeout : NULL);
if (unlikely (rc < 0)) {
zmq_assert (errno == EINTR);
return -1;
}
#endif
if (unlikely (rc == 0)) {
errno = EAGAIN;
return -1;
}
zmq_assert (rc == 1);
return 0;
#else
#error
#endif
}
void zmq::signaler_t::recv ()
{
// Attempt to read a signal.
unsigned char dummy;
#ifdef ZMQ_HAVE_WINDOWS
int nbytes = ::recv (r, (char*) &dummy, sizeof (dummy), 0);
wsa_assert (nbytes != SOCKET_ERROR);
#else
ssize_t nbytes = ::recv (r, &dummy, sizeof (dummy), 0);
errno_assert (nbytes >= 0);
#endif
zmq_assert (nbytes == sizeof (dummy));
zmq_assert (dummy == 0);
}
int zmq::signaler_t::make_fdpair (fd_t *r_, fd_t *w_)
{
#if defined ZMQ_HAVE_WINDOWS
// Windows has no 'socketpair' function. CreatePipe is no good as pipe
// handles cannot be polled on. Here we create the socketpair by hand.
*w_ = INVALID_SOCKET;
*r_ = INVALID_SOCKET;
// Create listening socket.
SOCKET listener;
listener = socket (AF_INET, SOCK_STREAM, 0);
wsa_assert (listener != INVALID_SOCKET);
// Set SO_REUSEADDR and TCP_NODELAY on listening socket.
BOOL so_reuseaddr = 1;
int rc = setsockopt (listener, SOL_SOCKET, SO_REUSEADDR,
(char *)&so_reuseaddr, sizeof (so_reuseaddr));
wsa_assert (rc != SOCKET_ERROR);
BOOL tcp_nodelay = 1;
rc = setsockopt (listener, IPPROTO_TCP, TCP_NODELAY,
(char *)&tcp_nodelay, sizeof (tcp_nodelay));
wsa_assert (rc != SOCKET_ERROR);
// Bind listening socket to any free local port.
struct sockaddr_in addr;
memset (&addr, 0, sizeof (addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
addr.sin_port = 0;
rc = bind (listener, (const struct sockaddr*) &addr, sizeof (addr));
wsa_assert (rc != SOCKET_ERROR);
// Retrieve local port listener is bound to (into addr).
int addrlen = sizeof (addr);
rc = getsockname (listener, (struct sockaddr*) &addr, &addrlen);
wsa_assert (rc != SOCKET_ERROR);
// Listen for incomming connections.
rc = listen (listener, 1);
wsa_assert (rc != SOCKET_ERROR);
// Create the writer socket.
*w_ = WSASocket (AF_INET, SOCK_STREAM, 0, NULL, 0, 0);
wsa_assert (*w_ != INVALID_SOCKET);
// Set TCP_NODELAY on writer socket.
rc = setsockopt (*w_, IPPROTO_TCP, TCP_NODELAY,
(char *)&tcp_nodelay, sizeof (tcp_nodelay));
wsa_assert (rc != SOCKET_ERROR);
// Connect writer to the listener.
rc = connect (*w_, (sockaddr *) &addr, sizeof (addr));
wsa_assert (rc != SOCKET_ERROR);
// Accept connection from writer.
*r_ = accept (listener, NULL, NULL);
wsa_assert (*r_ != INVALID_SOCKET);
// We don't need the listening socket anymore. Close it.
rc = closesocket (listener);
wsa_assert (rc != SOCKET_ERROR);
return 0;
#elif defined ZMQ_HAVE_OPENVMS
// Whilst OpenVMS supports socketpair - it maps to AF_INET only. Further,
// it does not set the socket options TCP_NODELAY and TCP_NODELACK which
// can lead to performance problems.
//
// The bug will be fixed in V5.6 ECO4 and beyond. In the meantime, we'll
// create the socket pair manually.
sockaddr_in lcladdr;
memset (&lcladdr, 0, sizeof (lcladdr));
lcladdr.sin_family = AF_INET;
lcladdr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
lcladdr.sin_port = 0;
int listener = socket (AF_INET, SOCK_STREAM, 0);
errno_assert (listener != -1);
int on = 1;
int rc = setsockopt (listener, IPPROTO_TCP, TCP_NODELAY, &on, sizeof (on));
errno_assert (rc != -1);
rc = setsockopt (listener, IPPROTO_TCP, TCP_NODELACK, &on, sizeof (on));
errno_assert (rc != -1);
rc = bind(listener, (struct sockaddr*) &lcladdr, sizeof (lcladdr));
errno_assert (rc != -1);
socklen_t lcladdr_len = sizeof (lcladdr);
rc = getsockname (listener, (struct sockaddr*) &lcladdr, &lcladdr_len);
errno_assert (rc != -1);
rc = listen (listener, 1);
errno_assert (rc != -1);
*w_ = socket (AF_INET, SOCK_STREAM, 0);
errno_assert (*w_ != -1);
rc = setsockopt (*w_, IPPROTO_TCP, TCP_NODELAY, &on, sizeof (on));
errno_assert (rc != -1);
rc = setsockopt (*w_, IPPROTO_TCP, TCP_NODELACK, &on, sizeof (on));
errno_assert (rc != -1);
rc = connect (*w_, (struct sockaddr*) &lcladdr, sizeof (lcladdr));
errno_assert (rc != -1);
*r_ = accept (listener, NULL, NULL);
errno_assert (*r_ != -1);
close (listener);
return 0;
#else // All other implementations support socketpair()
int sv [2];
int rc = socketpair (AF_UNIX, SOCK_STREAM, 0, sv);
errno_assert (rc == 0);
*w_ = sv [0];
*r_ = sv [1];
return 0;
#endif
}
#if defined ZMQ_SIGNALER_WAIT_BASED_ON_SELECT
#undef ZMQ_SIGNALER_WAIT_BASED_ON_SELECT
#endif
#if defined ZMQ_SIGNALER_WAIT_BASED_ON_POLL
#undef ZMQ_SIGNALER_WAIT_BASED_ON_POLL
#endif
|
simonrussell/libzmq-gem
|
libzmq/zeromq-2.1.9/src/signaler.cpp
|
C++
|
gpl-3.0
| 9,740
|
<?php
// This file is part of CodeRunner - http://coderunner.org.nz/
//
// CodeRunner is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// CodeRunner 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 CodeRunner. If not, see <http://www.gnu.org/licenses/>.
/**
* Testing the templating mechanism.
* @group qtype_coderunner
*
* @package qtype
* @subpackage coderunner
* @copyright 2014 Richard Lobb, University of Canterbury
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->dirroot . '/question/type/coderunner/tests/test.php');
require_once($CFG->dirroot . '/question/type/coderunner/vendor/autoload.php');
require_once($CFG->dirroot . '/question/type/coderunner/classes/twigmacros.php');
/**
* Unit tests for the coderunner question definition class.
*/
class qtype_coderunner_template_testcase extends qtype_coderunner_testcase {
public function test_template_engine() {
// Check if the template engine is installed and working OK.
$macros = qtype_coderunner_twigmacros::macros();
$twigloader = new \Twig\Loader\ArrayLoader($macros);
$twigoptions = array(
'cache' => false,
'optimizations' => 0,
'autoescape' => false,
'strict_variables' => true,
'debug' => true);
$twig = new \Twig\Environment($twigloader, $twigoptions);
$template = $twig->createTemplate('Hello {{ name }}!');
$renderedstring = $template->render(array('name' => 'Fabien'));
$this->assertEquals('Hello Fabien!', $renderedstring);
}
public function test_question_template() {
// Check that a Python question gets suitably expanded with parameters
// from the question itself. Also tests the JSON handling of sandbox
// params.
$q = $this->make_question('sqr');
$q->sandboxparams = "twiddle-twaddle";
$q->template = <<<EOTEMPLATE
{{ STUDENT_ANSWER }}
{{ TEST.testcode }}
print( '{{QUESTION.sandboxparams}}')
EOTEMPLATE;
$q->iscombinatortemplate = false;
$q->allornothing = false;
$q->testcases = array(
(object) array('testtype' => 0,
'testcode' => 'print(sqr(-3))',
'expected' => "9\ntwiddle-twaddle",
'stdin' => '',
'extra' => '',
'useasexample' => 0,
'display' => 'SHOW',
'mark' => 1.0,
'hiderestiffail' => 0),
);
$code = "def sqr(n): return n * n\n";
$response = array('answer' => $code);
$result = $q->grade_response($response);
list($mark, $grade, $cache) = $result;
$this->assertEquals(question_state::$gradedright, $grade);
}
public function test_grading_template() {
// Test a template that is also custom grader, plus python-escaping
// in Twig templates.
// This grader gives full marks if the input value is negative and
// the output value is correct or zero marks otherwise.
// The testcases are for n = {0, 1, 11, -7, -6} with marks of
// 1, 2, 4, 8, 16 respectively. So the expected mark is 24 / 31
// i.e 0.7742.
$q = $this->make_question('sqrnoprint');
$q->template = <<<EOTEMPLATE
{{ STUDENT_ANSWER }}
got = str({{TEST.testcode}})
expected = """{{TEST.expected|e('py')}}""".strip()
if expected == '36' and expected == got:
print('{"fraction":1.0}')
elif expected == '49' and expected == got:
print('{"fraction":1}')
else:
print('{"fraction":0}')
EOTEMPLATE;
$q->grader = 'TemplateGrader';
$q->iscombinatortemplate = false;
$q->allornothing = false;
$code = "def sqr(n): return n * n\n";
$response = array('answer' => $code);
$result = $q->grade_response($response);
list($mark, $grade, $cache) = $result;
$this->assertTrue(abs($mark - 24.0 / 31.0) < 0.000001);
$q->allornothing = true;
$result = $q->grade_response($response);
list($mark, $grade, $cache) = $result;
$this->assertTrue($mark == 0.0);
}
public function test_template_params() {
// Test that a templateparams field in the question is expanded
// from a JSON string and available to the template engine.
$q = $this->make_question('sqr');
$q->templateparams = '{"age":23, "string":"blah"}';
$q->parameters = json_decode($q->templateparams);
$q->template = <<<EOTEMPLATE
{{ STUDENT_ANSWER }}
{{ TEST.testcode }}
print( {{QUESTION.parameters.age}}, '{{QUESTION.parameters.string}}')
EOTEMPLATE;
$q->allornothing = false;
$q->iscombinatortemplate = false;
$q->testcases = array(
(object) array('type' => 0,
'testcode' => '',
'expected' => "23 blah",
'stdin' => '',
'extra' => '',
'useasexample' => 0,
'display' => 'SHOW',
'mark' => 1.0,
'hiderestiffail' => 0),
);
$q->allornothing = false;
$q->iscombinatortemplate = false;
$code = "";
$response = array('answer' => $code);
$result = $q->grade_response($response);
list($mark, $grade, $cache) = $result;
$this->assertEquals(question_state::$gradedright, $grade);
}
}
|
saylordotorg/Moodle_Saylor
|
question/type/coderunner/tests/template_test.php
|
PHP
|
gpl-3.0
| 6,184
|
/*
Copyright(C) 2020 YLoader.com
This program is free software : you can redistribute it and / or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program.If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifdef PLUGIN_EXPORTS
#define PLUGIN_API __declspec(dllexport)
#else
#define PLUGIN_API __declspec(dllimport)
#endif
#include <set>
#include "exceptions.h"
/**
* \defgroup Plugin Plugin classes and APIs
* '
* For several complete examples of plugins, using persistence in the registry
* or not, see the sample projects
*/
/*@{*/
namespace yloader {
/**
* plugin info: info (id, name, description) + version
*/
class PluginInfo : public Info {
private:
const Version m_version;
public:
/**
* Copy constructor
*
* @param pluginInfo The source PluginInfo
*
* @see Info
* @see Version
*/
PluginInfo(const PluginInfo& pluginInfo)
: m_version(pluginInfo.version()), Info(pluginInfo) {}
/**
* Constructor - takes a reference to a Info object
*
* The version is set by default to the current version of the product
*
* @param info The source info
*
* @see Info
* @see Version
*/
PluginInfo(const Info& info) : m_version(Version::CURRENT), Info(info) {}
/**
* Returns the plugin version
*
* @return The plugin version
* @see Version
*/
const Version& version() const { return m_version; }
};
/**
* Abstract base class for all plugin types and instances.
*
* Implemented as a template class to allow different type of plugins.
* Also, implemented as an abstract class to allow for specific implementations
* of various plugins
*
* A plugin must derive from this class and implement its various virtual
* methods that will define its behavior. The plugin type is determined by the
* type passed as template argument.
*
* The template argument is the type of the plugin. For example, a data source
* plugin is defined as:
*
* \code
* typedef Plugin< DataSource > DataSourcePlugin;
* \endcode
*
* To be useful, a plugin must be able to instantiate at least one
* configuration, which is an object of the type of the plugin. Most plugins
* will be able to create, edit and delete multiple configurations as well as
* persist them.
*
* For example a DataSource plugin will be able to create instances of
* DataSource derived classes and pass them as pinters when requested.
*
* To traverse the list of available configuration, use first/next.
*/
template <class Type>
class Plugin : public PluginInfo {
public:
/**
* Constructor - takes a reference to an Info object
*
* @param info The info for the current plugin
*/
Plugin(const Info& info) : PluginInfo(info) {}
/**
* Returns a pointer to a Info about the first available configuration
*
* @return A smart pointer to an Info object, or 0 if no configurations are
* available
* @exception PluginException
* Thrown in case of an error
* @see Info
*/
virtual InfoPtr first() const = 0;
/**
* Returns a pointer to an Info object for the next available configuration
*
* @return A smart pointer to an Info object, or 0 if no more configurations
* are available
* @exception PluginException
* Thrown in case of an error
* @see Info
*/
virtual InfoPtr next() const = 0;
/**
* Gets an instance of a configuration, usually as a pointer or smart pointer.
*
* @param id The id of the configuration
*
* @return The configuration pointer, or 0 if could not get
* @exception PluginException
* Thrown in case of an error
* @see UniqueId
* @see Info
*/
virtual std::shared_ptr<Type> get(const UniqueId& id, const std::vector<std::wstring>* createStrings = 0) = 0;
/**
* Indicates the configuration capabilities of the plugin
*
* If the plugin is capable of creating new configurations, it will return
* true
*
* @return true if can create new configurations, false otherwise
*/
virtual bool canCreate() const = 0;
/**
* creates a new configuration
*
* For this method to be called, the canCreate method must return true,
* indicating that plug-in creation is supported
*
* Internally, a plugin can call a dialog box to set parameters, persist the
* configuration in the registry or do anything that it needs to, the only
* requirement being that at the end it returns a pointer to a new
* configuration or 0 if it didn't or couldn't create it.
*
* A plug-in configuration can be passed a string that can contain runtime
* information such as a list of symbols for a symbolssource or other values
*
* @param createString
* A configuration defined string passed at creation. The
* default value is an empty string This string can be any value that the
* plug-in configuration will know how to interpret and handle.
*
* @return The pointer to the new configuration, or 0 if no configuration has
* been created
* @exception PluginException
* Thrown in case of an error
* @see UniqueId
*/
virtual std::shared_ptr<Type> create(const std::vector<std::wstring>* createStrings = 0) = 0;
/**
* Determines if a specific configuration can be edited
*
* @param id The id of the configuration that is tested
*
* @return true if the configuration can be edited, false otherwise
* @see UniqueId
*/
virtual bool canEdit(const UniqueId& id) const = 0;
/**
* Edits a configuration
*
* For this method to be called, the canEdit method must return true
*
* Internally, a plugin can call a dialog box to change the configuration's
* parameters, persist them in the registry or do anything that it needs to,
* the only requirement being that at the end it returns a pointer to the
* edited configuration
*
* @param id The id of the configuration to be edited
*
* @return the edited configuration
* @exception PluginException
* Thrown in case of an internal error
* @see UniqueId
*/
virtual std::shared_ptr<Type> edit(const UniqueId& id) = 0;
/**
* Determines if a specific configuration can be removed
*
* @param id The id of the configuration to be removed
*
* @return true if it can be removed, false if not
* @see UniqueId
*/
virtual bool canRemove(const UniqueId& id) const = 0;
/**
* Removes a configuration
*
* For this method to be called, the canRemove method must return true
*
* If the configuration can't be removed, an exception should be thrown
* indicating the reason
*
* @param id The id of the configuration to be removed
*
* @exception PluginException
* Thrown in case of an error, for example of the
* configuration can't be removed
* @see UniqueId
*/
virtual void remove(const UniqueId& id) = 0;
/**
* Indicates whether a plug-in configuration corresponding to a id is UI
* enabled
*
* The default implementation returns false. If the plug-in configuration id
* can create its own UI, this method should be overriden and it should return
* true for that id. In that case, the plug-in configuration will be requested
* to provide more information about its UI - see the PluginConfiguration
* class.
*
* @param id The id of the configuration to be checked for UI
*
* @see UniqueId
* @see PluginConfiguration
*/
virtual bool hasWindow(const UniqueId& id) const { return false; }
};
////////////////////////////////////
// Plugin APIs
//
class PluginTreeException {
public:
std::vector<InfoPtr> m_info;
public:
PluginTreeException() {}
PluginTreeException(const Info& info) { add(info); }
PluginTreeException(const std::vector<InfoPtr>& info) {
m_info.insert(m_info.begin(), info.begin(), info.end());
}
void add(const Info& info) { m_info.push_back(InfoPtr(new Info(info))); }
void add(const InfoPtr infoPtr) { m_info.push_back(infoPtr); }
const std::vector<InfoPtr>& info() const { return m_info; }
bool empty() const { return m_info.empty(); }
const std::wstring message() const {
std::wostringstream o;
o << L"Duplicate ids, the components with these Ids will be ignored: " << std::endl;
for (auto i : m_info) {
o << i->id() << L", name: " << i->name() << std::endl;
}
return o.str();
}
};
class PluginLoadingStatusHandler {
public:
virtual ~PluginLoadingStatusHandler() {}
virtual void event(const std::wstring& event) = 0;
virtual void done() = 0;
};
class NullPluginLoadingStatusHandler : public PluginLoadingStatusHandler {
virtual void event(const std::wstring& event) {}
virtual void done() {}
};
class PluginExplorer {
private:
virtual void process(const std::wstring& path, PluginLoadingStatusHandler* loadingStatusHandler,
std::vector<InfoPtr>& duplicates) = 0;
static void initIgnoreModulesSet(std::set<std::wstring>& ignoreModulesSet);
static bool ignoreModule(const std::wstring& m_fileName);
public:
// searches and loads all plug-ins in several paths
void explore(const std::vector<std::wstring>& paths, const std::wstring& ext,
bool recursive, PluginLoadingStatusHandler* loadingStatusHandler) {
std::vector<InfoPtr> duplicates;
for (auto const& path : paths) {
explore(path, ext, recursive, loadingStatusHandler, duplicates);
}
if (!duplicates.empty()) throw PluginTreeException(duplicates);
}
void explore(const std::wstring& path, const std::wstring& ext, bool recursive,
PluginLoadingStatusHandler* loadingStatusHandler) {
std::vector<std::wstring> paths;
paths.push_back(path);
explore(paths, ext, recursive, loadingStatusHandler);
}
private:
// search and loads all plug-ins in one path
void explore(const std::wstring& p, const std::wstring& ext, bool recursive,
PluginLoadingStatusHandler* loadingStatusHandler, std::vector<InfoPtr>& duplicates);
};
} // namespace yloader
// end Plugin group
/*@}*/
|
adrianmichel/yloader
|
src/include/plugin.h
|
C
|
gpl-3.0
| 10,595
|
/** \file
* \brief useable example of the Modular Multilevel Mixer
*
* \author Gereon Bartel
*
* \par License:
* This file is part of the Open Graph Drawing Framework (OGDF).
*
* \par
* Copyright (C)<br>
* See README.md in the OGDF root directory for details.
*
* \par
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* Version 2 or 3 as published by the Free Software Foundation;
* see the file LICENSE.txt included in the packaging of this file
* for details.
*
* \par
* 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.
*
* \par
* You should have received a copy of the GNU General Public
* License along with this program; if not, see
* http://www.gnu.org/copyleft/gpl.html
*/
#pragma once
#include <ogdf/module/LayoutModule.h>
#include <ogdf/energybased/multilevel_mixer/MultilevelGraph.h>
namespace ogdf {
/** \brief An example Layout using the Modular Mutlievel Mixer
*
* This example is tuned for nice drawings for most types of graphs.
* EdgeCoverMerger and BarycenterPlacer are used as merging and placement
* strategies. The FastMultipoleEmbedder is for force calculation.
*
* For an easy variation of the Modular Multilevel Mixer copy the code in call.
*/
class OGDF_EXPORT MMMExampleNiceLayout : public LayoutModule
{
public:
//! Constructor
MMMExampleNiceLayout();
//! calculates a drawing for the Graph GA
void call(GraphAttributes &GA) override;
//! calculates a drawing for the Graph MLG
void call(MultilevelGraph &MLG);
private:
};
} // namespace ogdf
|
likr/emogdf
|
ogdf/include/ogdf/energybased/multilevel_mixer/MMMExampleNiceLayout.h
|
C
|
gpl-3.0
| 1,789
|
package uni.miskolc.ips.ilona.measurement.model.position;
import static org.junit.Assert.*;
import java.util.UUID;
import org.junit.Test;
public class PositionTest {
@Test
public void testSetParameters() {
UUID uuid= UUID.randomUUID();
Coordinate coord= new Coordinate();
Zone zone = Zone.UNKNOWN_POSITION;
Position pos = new Position();
pos.setCoordinate(coord);
pos.setZone(zone);
pos.setUUID(uuid);
if(pos.getUUID().compareTo(uuid)==0 && pos.getCoordinate().equals(coord) && pos.getZone().equals(zone)){
String positionString = pos.toString();
}
}
@Test
public void testEqualsDifferent(){
Coordinate coord= new Coordinate();
Position pos = new Position(coord);
assertFalse(pos.equals(coord));
}
@Test
public void testEqualsSame(){
Coordinate coord= new Coordinate();
Position pos = new Position(coord,Zone.UNKNOWN_POSITION);
assertTrue(pos.equals(pos));
}
}
|
ZsoltToth/ilona
|
measurement/measurement-model/src/test/java/uni/miskolc/ips/ilona/measurement/model/position/PositionTest.java
|
Java
|
gpl-3.0
| 916
|
<?php
/**
* File for responseware forms
* @author jacob
* @package mod_turningtech
* @copyright 2012 Turning Technologies
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*
*/
global $CFG;
require_once($CFG->dirroot . '/lib/formslib.php');
/**
* provides a form that allows students to enter their responseware username and password
* to get their device ID
* @author jacob
*
*/
/**
* form class that allows students to enter their responseware username and password
* @author jacob
* @copyright 2012 Turning Technologies
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*
*/
class turningtech_responseware_form extends moodleform {
/**
* form Definition
* @return unknown_type
*/
function definition() {
$mform =& $this->_form;
$mform->addElement('header', 'responsewareheader', get_string('responsewareheadertext', 'turningtech'));
$mform->setType('responsewareheader', PARAM_RAW);
$link = "<a href='" . TurningTechTurningHelper::getresponsewareurl('forgotpassword') . "' target='_blank'>" . get_string('forgotpassword', 'turningtech') . "</a>";
$linkcreateaccount = "<a href='" . TurningTechTurningHelper::getresponsewareurl('createaccount') . "' target='_blank'>" . get_string('createaccount', 'turningtech') . "</a>";
//$mform->addElement('static','createaccountlink', '', $link);
$mform->addElement('hidden', 'typeid');
$mform->setType('typeid', PARAM_INT);
$mform->addElement('html', '<div class="tt_rw_form_item">');
$mform->addElement('text', 'username', get_string('responsewareuserid', 'turningtech'));
$mform->setType('username', PARAM_TEXT);
$mform->addElement('html', '</div>');
$mform->addElement('html', '<div class="tt_rw_form_item">');
$mform->addElement('password', 'password', get_string('responsewarepassword', 'turningtech'));
$mform->addElement('html', '</div>');
$mform->addElement('html', '<div class="tt_rw_form_item">');
$mform->addElement('static', 'forgotpasswordlink', '', $link ." ". $linkcreateaccount);
$mform->setType('forgotpasswordlink', PARAM_RAW);
$mform->addElement('html', '</div>');
$mform->addElement('submit', 'submitbutton', get_string('register', 'turningtech'), array('style'=>'margin-top:10px;text-align:center;margin-left:13%;'));
}
/**
* Validate
* @param unknown_type $data
* @param unknown_type $files
* @return unknown_type
*/
function validation($data, $files) {
$errors = parent::validation($data, $files);
if (empty($data['username'])) {
$errors['username'] = get_string('mustprovideid', 'turningtech');
}
if (empty($data['password'])) {
$errors['password'] = get_string('mustprovidepassword', 'turningtech');
}
return $errors;
}
}
?>
|
lsuits/moodle
|
mod/turningtech/lib/forms/turningtech_responseware_form.php
|
PHP
|
gpl-3.0
| 3,063
|
#pragma once
#include <malloc.h>
#include <memory>
namespace walberla {
namespace simd {
/**
* STL-compliant allocator that allocates aligned memory.
* \tparam T Type of the element to allocate.
* \tparam Alignment Alignment of the allocation, e.g. 16.
*/
template <class T, size_t Alignment>
struct aligned_allocator
: public std::allocator<T> // Inherit construct(), destruct() etc.
{
typedef typename std::allocator<T>::size_type size_type;
typedef typename std::allocator<T>::pointer pointer;
typedef typename std::allocator<T>::const_pointer const_pointer;
/// Defines an aligned allocator suitable for allocating elements of type
/// @c U.
template <class U>
struct rebind { typedef aligned_allocator<U,Alignment> other; };
/// Default-constructs an allocator.
aligned_allocator() throw() { }
/// Copy-constructs an allocator.
aligned_allocator(const aligned_allocator& other) throw()
: std::allocator<T>(other) { }
/// Convert-constructs an allocator.
template <class U>
aligned_allocator(const aligned_allocator<U,Alignment>&) throw() { }
/// Destroys an allocator.
~aligned_allocator() throw() { }
/// Allocates @c n elements of type @c T, aligned to a multiple of
/// @c Alignment.
pointer allocate(size_type n)
{
return allocate(n, const_pointer(0));
}
/// Allocates @c n elements of type @c T, aligned to a multiple of
/// @c Alignment.
pointer allocate(size_type n, const_pointer /* hint */)
{
void *p;
#ifndef _WIN32
if (posix_memalign(&p, Alignment, n*sizeof(T)) != 0)
p = NULL;
#else
p = _aligned_malloc(n*sizeof(T), Alignment);
#endif
if (!p)
throw std::bad_alloc();
return static_cast<pointer>(p);
}
/// Frees the memory previously allocated by an aligned allocator.
void deallocate(pointer p, size_type /* n */)
{
#ifndef _WIN32
free(p);
#else
_aligned_free(p);
#endif
}
};
/**
* Checks whether two aligned allocators are equal. Two allocators are equal
* if the memory allocated using one allocator can be deallocated by the other.
* \returns Always @c true.
*/
template <class T1, size_t A1, class T2, size_t A2>
bool operator == (const aligned_allocator<T1,A1> &, const aligned_allocator<T2,A2> &)
{
return true;
}
/**
* Checks whether two aligned allocators are not equal. Two allocators are equal
* if the memory allocated using one allocator can be deallocated by the other.
* \returns Always @c false.
*/
template <class T1, size_t A1, class T2, size_t A2>
bool operator != (const aligned_allocator<T1,A1> &, const aligned_allocator<T2,A2> &)
{
return false;
}
} // namespace simd
} // namespace walberla
|
lssfau/walberla
|
src/simd/AlignedAllocator.h
|
C
|
gpl-3.0
| 3,023
|
#ifndef MATADOR_ADDRESS_RESOLVER_HPP
#define MATADOR_ADDRESS_RESOLVER_HPP
#ifdef _MSC_VER
#ifdef matador_net_EXPORTS
#define OOS_NET_API __declspec(dllexport)
#define EXPIMP_NET_TEMPLATE
#else
#define OOS_NET_API __declspec(dllimport)
#define EXPIMP_NET_TEMPLATE extern
#endif
#pragma warning(disable: 4251)
#else
#define OOS_NET_API
#endif
#include "matador/net/peer.hpp"
#include "matador/net/error.hpp"
#include <vector>
namespace matador {
/// @cond MATADOR_DEV
class tcp;
class udp;
namespace detail {
template < class P >
int determine_socktype();
template <>
OOS_NET_API int determine_socktype<tcp>();
template <>
OOS_NET_API int determine_socktype<udp>();
template < class P >
void initialize_hints(struct addrinfo &hints, int flags) {
memset(&hints,0,sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = determine_socktype<P>();
hints.ai_protocol = 0;
hints.ai_flags = flags;
}
/// @endcond
}
/**
* The address resolver resolves a given host and port
* to a peer object representing the given address
*
* @tparam P Type of protocol
*/
template < class P >
class address_resolver
{
public:
typedef typename P::peer peer; /**< Shortcut to peer type */
/**
* Default constructor
*/
address_resolver() = default;
/**
* Resolves the given host and port to a list
* of valid peers representing the ip addresses
* of the host either in IPv4 or IPv6 format
*
* @param hostname Hostname to resolve
* @param port Port to resolve
* @return A list of peers representing the host and port
*/
std::vector<peer> resolve(const std::string &hostname, const std::string &port);
/**
* Resolves the given host and port to a list
* of valid peers representing the ip addresses
* of the host either in IPv4 or IPv6 format
*
* @param hostname Hostname to resolve
* @param port Port to resolve
* @return A list of peers representing the host and port
*/
std::vector<peer> resolve(const char *hostname, const char *port);
};
/// @cond MATADOR_DEV
template<class P>
std::vector<typename address_resolver<P>::peer> address_resolver<P>::resolve(const std::string &hostname, const std::string &port)
{
return resolve(hostname.c_str(), port.c_str());
}
template < class P >
std::vector<typename address_resolver<P>::peer> address_resolver<P>::resolve(const char *hostname, const char *port)
{
struct addrinfo hints = {};
detail::initialize_hints<P>(hints, AI_PASSIVE);
struct addrinfo* res = nullptr;
struct addrinfo* head = nullptr;
int err = getaddrinfo(hostname, port, &hints, &res);
if (err != 0) {
detail::throw_logic_error_with_gai_errno("error on getaddrinfo: %s", err);
}
head = res;
std::vector<peer> peers;
do {
if (res->ai_family == PF_INET) {
peers.push_back(peer(address(*(struct sockaddr_in*)res->ai_addr)));
} else if (res->ai_family == PF_INET6) {
peers.push_back(peer(address(*(struct sockaddr_in6*)res->ai_addr)));
} // else -> not supported
} while ( (res = res->ai_next) != nullptr);
freeaddrinfo(head);
return peers;
}
/// @endcond
}
#endif //MATADOR_ADDRESS_RESOLVER_HPP
|
zussel/matador
|
include/matador/net/address_resolver.hpp
|
C++
|
gpl-3.0
| 3,144
|
#funcion para separar un numero telefonico por un "-" creando una estructura similar 1-23-456-7891
function separa_numero_telefonico($numero){
$separar = 1;
$cadena = (string)$numero;
$long = strlen($cadena);
for($i=0; $i<$long; $separar++) {
if ($i==0){
$telefono= substr($cadena, $i, $separar);
}
else {
$telefono = $telefono."-".substr($cadena, $i, $separar);
}
$i+= $separar;
}
return $telefono; }
|
edgarslr/scr
|
num_tel.php
|
PHP
|
gpl-3.0
| 417
|
namespace UnityEditor
{
using System;
using System.Collections.Generic;
using UnityEngine;
internal class ExposablePopupMenu
{
private List<ItemData> m_Items;
private float m_ItemSpacing;
private float m_MinWidthOfPopup;
private PopupButtonData m_PopupButtonData;
private Action<ItemData> m_SelectionChangedCallback;
private float m_WidthOfButtons;
private float m_WidthOfPopup;
private void CalcWidths()
{
this.m_WidthOfButtons = 0f;
foreach (ItemData data in this.m_Items)
{
data.m_Width = data.m_Style.CalcSize(data.m_GUIContent).x;
this.m_WidthOfButtons += data.m_Width;
}
this.m_WidthOfButtons += (this.m_Items.Count - 1) * this.m_ItemSpacing;
Vector2 vector = this.m_PopupButtonData.m_Style.CalcSize(this.m_PopupButtonData.m_GUIContent);
vector.x += 3f;
this.m_WidthOfPopup = vector.x;
}
public void Init(List<ItemData> items, float itemSpacing, float minWidthOfPopup, PopupButtonData popupButtonData, Action<ItemData> selectionChangedCallback)
{
this.m_Items = items;
this.m_ItemSpacing = itemSpacing;
this.m_PopupButtonData = popupButtonData;
this.m_SelectionChangedCallback = selectionChangedCallback;
this.m_MinWidthOfPopup = minWidthOfPopup;
this.CalcWidths();
}
public float OnGUI(Rect rect)
{
if ((rect.width >= this.m_WidthOfButtons) && (rect.width > this.m_MinWidthOfPopup))
{
Rect position = rect;
foreach (ItemData data in this.m_Items)
{
position.width = data.m_Width;
EditorGUI.BeginChangeCheck();
EditorGUI.BeginDisabledGroup(!data.m_Enabled);
GUI.Toggle(position, data.m_On, data.m_GUIContent, data.m_Style);
EditorGUI.EndDisabledGroup();
if (EditorGUI.EndChangeCheck())
{
this.SelectionChanged(data);
GUIUtility.ExitGUI();
}
position.x += data.m_Width + this.m_ItemSpacing;
}
return this.m_WidthOfButtons;
}
if (this.m_WidthOfPopup < rect.width)
{
rect.width = this.m_WidthOfPopup;
}
if (EditorGUI.ButtonMouseDown(rect, this.m_PopupButtonData.m_GUIContent, FocusType.Passive, this.m_PopupButtonData.m_Style))
{
PopUpMenu.Show(rect, this.m_Items, this);
}
return this.m_WidthOfPopup;
}
private void SelectionChanged(ItemData item)
{
if (this.m_SelectionChangedCallback != null)
{
this.m_SelectionChangedCallback(item);
}
else
{
Debug.LogError("Callback is null");
}
}
public class ItemData
{
public bool m_Enabled;
public GUIContent m_GUIContent;
public bool m_On;
public GUIStyle m_Style;
public object m_UserData;
public float m_Width;
public ItemData(GUIContent content, GUIStyle style, bool on, bool enabled, object userData)
{
this.m_GUIContent = content;
this.m_Style = style;
this.m_On = on;
this.m_Enabled = enabled;
this.m_UserData = userData;
}
}
public class PopupButtonData
{
public GUIContent m_GUIContent;
public GUIStyle m_Style;
public PopupButtonData(GUIContent content, GUIStyle style)
{
this.m_GUIContent = content;
this.m_Style = style;
}
}
internal class PopUpMenu
{
private static ExposablePopupMenu m_Caller;
private static List<ExposablePopupMenu.ItemData> m_Data;
private static void SelectionCallback(object userData)
{
ExposablePopupMenu.ItemData item = (ExposablePopupMenu.ItemData) userData;
m_Caller.SelectionChanged(item);
m_Caller = null;
m_Data = null;
}
internal static void Show(Rect activatorRect, List<ExposablePopupMenu.ItemData> buttonData, ExposablePopupMenu caller)
{
m_Data = buttonData;
m_Caller = caller;
GenericMenu menu = new GenericMenu();
foreach (ExposablePopupMenu.ItemData data in m_Data)
{
if (data.m_Enabled)
{
menu.AddItem(data.m_GUIContent, data.m_On, new GenericMenu.MenuFunction2(ExposablePopupMenu.PopUpMenu.SelectionCallback), data);
}
else
{
menu.AddDisabledItem(data.m_GUIContent);
}
}
menu.DropDown(activatorRect);
}
}
}
}
|
randomize/VimConfig
|
tags/unity5/UnityEditor/ExposablePopupMenu.cs
|
C#
|
gpl-3.0
| 5,354
|
//----------------------------------------------------------------------------
//
// Copyright (C) 2004-2015 by EMGU Corporation. All rights reserved.
//
// Vector of DMatch
//
// This file is automatically generated, do not modify.
//----------------------------------------------------------------------------
using System;
using System.Drawing;
using System.Diagnostics;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Emgu.CV.Structure;
#if !NETFX_CORE
using System.Runtime.Serialization;
#endif
namespace Emgu.CV.Util
{
/// <summary>
/// Wrapped class of the C++ standard vector of DMatch.
/// </summary>
#if !NETFX_CORE
[Serializable]
[DebuggerTypeProxy(typeof(VectorOfDMatch.DebuggerProxy))]
#endif
public partial class VectorOfDMatch : Emgu.Util.UnmanagedObject, IInputOutputArray
#if !NETFX_CORE
, ISerializable
#endif
{
private bool _needDispose;
static VectorOfDMatch()
{
CvInvoke.CheckLibraryLoaded();
}
#if !NETFX_CORE
/// <summary>
/// Constructor used to deserialize runtime serialized object
/// </summary>
/// <param name="info">The serialization info</param>
/// <param name="context">The streaming context</param>
public VectorOfDMatch(SerializationInfo info, StreamingContext context)
: this()
{
Push((MDMatch[])info.GetValue("DMatchArray", typeof(MDMatch[])));
}
/// <summary>
/// A function used for runtime serialization of the object
/// </summary>
/// <param name="info">Serialization info</param>
/// <param name="context">Streaming context</param>
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("DMatchArray", ToArray());
}
#endif
/// <summary>
/// Create an empty standard vector of DMatch
/// </summary>
public VectorOfDMatch()
: this(VectorOfDMatchCreate(), true)
{
}
internal VectorOfDMatch(IntPtr ptr, bool needDispose)
{
_ptr = ptr;
_needDispose = needDispose;
}
/// <summary>
/// Create an standard vector of DMatch of the specific size
/// </summary>
/// <param name="size">The size of the vector</param>
public VectorOfDMatch(int size)
: this( VectorOfDMatchCreateSize(size), true)
{
}
/// <summary>
/// Create an standard vector of DMatch with the initial values
/// </summary>
/// <param name="values">The initial values</param>
public VectorOfDMatch(MDMatch[] values)
:this()
{
Push(values);
}
/// <summary>
/// Push an array of value into the standard vector
/// </summary>
/// <param name="value">The value to be pushed to the vector</param>
public void Push(MDMatch[] value)
{
if (value.Length > 0)
{
GCHandle handle = GCHandle.Alloc(value, GCHandleType.Pinned);
VectorOfDMatchPushMulti(_ptr, handle.AddrOfPinnedObject(), value.Length);
handle.Free();
}
}
/// <summary>
/// Convert the standard vector to an array of DMatch
/// </summary>
/// <returns>An array of DMatch</returns>
public MDMatch[] ToArray()
{
MDMatch[] res = new MDMatch[Size];
if (res.Length > 0)
{
GCHandle handle = GCHandle.Alloc(res, GCHandleType.Pinned);
VectorOfDMatchCopyData(_ptr, handle.AddrOfPinnedObject());
handle.Free();
}
return res;
}
/// <summary>
/// Get the size of the vector
/// </summary>
public int Size
{
get
{
return VectorOfDMatchGetSize(_ptr);
}
}
/// <summary>
/// Clear the vector
/// </summary>
public void Clear()
{
VectorOfDMatchClear(_ptr);
}
/// <summary>
/// The pointer to the first element on the vector. In case of an empty vector, IntPtr.Zero will be returned.
/// </summary>
public IntPtr StartAddress
{
get
{
return VectorOfDMatchGetStartAddress(_ptr);
}
}
/// <summary>
/// Get the item in the specific index
/// </summary>
/// <param name="index">The index</param>
/// <returns>The item in the specific index</returns>
public MDMatch this[int index]
{
get
{
MDMatch result = new MDMatch();
VectorOfDMatchGetItem(_ptr, index, ref result);
return result;
}
}
/// <summary>
/// Release the standard vector
/// </summary>
protected override void DisposeObject()
{
if (_needDispose && _ptr != IntPtr.Zero)
VectorOfDMatchRelease(ref _ptr);
}
/// <summary>
/// Get the pointer to cv::_InputArray
/// </summary>
public InputArray GetInputArray()
{
return new InputArray( cvInputArrayFromVectorOfDMatch(_ptr) );
}
/// <summary>
/// Get the pointer to cv::_OutputArray
/// </summary>
public OutputArray GetOutputArray()
{
return new OutputArray( cvOutputArrayFromVectorOfDMatch(_ptr) );
}
/// <summary>
/// Get the pointer to cv::_InputOutputArray
/// </summary>
public InputOutputArray GetInputOutputArray()
{
return new InputOutputArray( cvInputOutputArrayFromVectorOfDMatch(_ptr) );
}
internal class DebuggerProxy
{
private VectorOfDMatch _v;
public DebuggerProxy(VectorOfDMatch v)
{
_v = v;
}
public MDMatch[] Values
{
get { return _v.ToArray(); }
}
}
[DllImport(CvInvoke.ExternLibrary, CallingConvention = CvInvoke.CvCallingConvention)]
internal static extern IntPtr VectorOfDMatchCreate();
[DllImport(CvInvoke.ExternLibrary, CallingConvention = CvInvoke.CvCallingConvention)]
internal static extern IntPtr VectorOfDMatchCreateSize(int size);
[DllImport(CvInvoke.ExternLibrary, CallingConvention = CvInvoke.CvCallingConvention)]
internal static extern void VectorOfDMatchRelease(ref IntPtr v);
[DllImport(CvInvoke.ExternLibrary, CallingConvention = CvInvoke.CvCallingConvention)]
internal static extern int VectorOfDMatchGetSize(IntPtr v);
[DllImport(CvInvoke.ExternLibrary, CallingConvention = CvInvoke.CvCallingConvention)]
internal static extern void VectorOfDMatchCopyData(IntPtr v, IntPtr data);
[DllImport(CvInvoke.ExternLibrary, CallingConvention = CvInvoke.CvCallingConvention)]
internal static extern IntPtr VectorOfDMatchGetStartAddress(IntPtr v);
[DllImport(CvInvoke.ExternLibrary, CallingConvention = CvInvoke.CvCallingConvention)]
internal static extern void VectorOfDMatchPushMulti(IntPtr v, IntPtr values, int count);
[DllImport(CvInvoke.ExternLibrary, CallingConvention = CvInvoke.CvCallingConvention)]
internal static extern void VectorOfDMatchClear(IntPtr v);
[DllImport(CvInvoke.ExternLibrary, CallingConvention = CvInvoke.CvCallingConvention)]
internal static extern void VectorOfDMatchGetItem(IntPtr vec, int index, ref MDMatch element);
[DllImport(CvInvoke.ExternLibrary, CallingConvention = CvInvoke.CvCallingConvention)]
internal static extern IntPtr cvInputArrayFromVectorOfDMatch(IntPtr vec);
[DllImport(CvInvoke.ExternLibrary, CallingConvention = CvInvoke.CvCallingConvention)]
internal static extern IntPtr cvOutputArrayFromVectorOfDMatch(IntPtr vec);
[DllImport(CvInvoke.ExternLibrary, CallingConvention = CvInvoke.CvCallingConvention)]
internal static extern IntPtr cvInputOutputArrayFromVectorOfDMatch(IntPtr vec);
}
}
|
whitechoclax/IntelSocketDesocketRB
|
VishnuSocket/Common/EMGU/Emgu.CV/Util/VectorOfDMatch.cs
|
C#
|
gpl-3.0
| 7,964
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.